Getting list of implicitly implemented interfaces for class node - typescript-compiler-api

I work on TypeScript to C# converter.
I wonder if compiler API for TypeScript let me get the list of all the implicitly implemented interfaces for a given ts.ClassDeclaration node.
interface ISomeInterface {
a: number;
}
class ClassThatImplicitlyImplementsISomeInterface {
a: number = 10;
}
Is it somehow possible?

Related

Pass along a Python type to C++ that inherits C++

I have a C++ class RuleSet with a bunch of std::shared_ptr to some rules for a game, most notably to the victory condition, a std::shared_ptr<VictoryRule>. VictoryRule is a abstract C++ type, with one function winners to return the winners of a game. (team_t is a enum, but for simplicity consider it an alias to int.)
class VictoryRule {
public:
//! #brief Check if game is won by a team.
//! #return the teamno of the team that won or team_t::no_team if nobody won.
virtual std::vector<team_t> winners(const Game &game) = 0;
//! #brief Default virtual destructor.
virtual ~VictoryRule() = default;
};
I exposed this class to python with pybind11 to be able to subclass it in python, with a trampoline class.
class PyVictoryRule : public VictoryRule {
public:
std::vector<team_t> winners(const Game &game) override {
PYBIND11_OVERRIDE_PURE(std::vector<team_t>, VictoryRule, winners, game);
}
};
And it's registered with:
pybind11::class_<VictoryRule, PyVictoryRule, std::shared_ptr<VictoryRule>>(
m, "VictoryRule")
.def(pybind11::init())
.def("winners", &VictoryRule::winners, arg("game"));
And I'v reimplemented the Rule in python
class CustomVictoryRule(VictoryRule):
def __init__(self):
VictoryRule.__init__(self)
def winners(self, game):
return [1]
I can instantiate the class in python and call the winners method without any issue.
cvr = CustomVictoryRule()
cvr.winners() # Returns [1]
But I don't want to use the rule directly, I want to store it in the C++ Ruleset.
class RuleSet {
public:
std::shared_ptr<VictoryRule> get_victory_rule();
void register_victory_rule(std::shared_ptr<VictoryRule> victory_rule);
private:
std::unordered_map<CasePawn::Type, std::shared_ptr<Rule>> per_pawn_type_rule_;
std::shared_ptr<VictoryRule> victory_rule_;
};
All methods of RuleSet are registered to pybind11 as-is.
pybind11::class_<RuleSet, std::shared_ptr<RuleSet>>(m, "RuleSet")
.def(pybind11::init())
.def("get_victory_rule", &RuleSet::get_victory_rule)
.def("register_victory_rule", &RuleSet::register_victory_rule,
arg("victory_rule"));
But when I pass along a CustomVictoryRule to RuleSet.register_victory_rule, it loses its dynamic type, and Receive an error for trying to call pure virtual function VictoryRule::winners...
ruleset = RuleSet()
ruleset.register_victory_rule(CustomVictoryRule())
ruleset.get_victory_rule().winners() #fails with RuntimeError: `Tried to call pure virtual function "VictoryRule::winners"`
What should I do so that ruleset.get_victory_rule() return a victory rule with the correct type CustomVictoryRule, so that CustomVictoryRule.winners() is called in that last line of code ?
I found the issue. Instead of doing:
ruleset.register_victory_rule(CustomVictoryRule())
I do:
cvr = CustomVictoryRule()
ruleset.register_victory_rule(cvr)
Then it worked ! So somehow python keeps alive the instance when it's stored into a local variable that's kept alive as long as the ruleset.
Thus, I need to tell pybind11 to keep temporary python objects passed as arguments. Luckily, there's a pybind11::keep_alive decorator to functions to do exactly that. So, binding RuleSet from c++ to python with the following fixes the issue !
pybind11::class_<RuleSet, std::shared_ptr<RuleSet>>(m, "RuleSet")
.def(pybind11::init())
.def("victory_rule", &RuleSet::get_victory_rule)
.def("register_victory_rule", &RuleSet::register_victory_rule,
arg("victory_rule"), keep_alive<1, 2>());

Should I have API models and UI models in an Angular app

I am working on an App where I am using .Net Core as my API, SQL Server as database, and Angular for the UI. I am following a course that does not provide much explanation on why he does what he does so I decided to post a couple of questions here after Googling did not help. In the angular app, the instructor uses an api-model (interface) to fetch the data from the API in a service using an http method, and then in the component .ts file he sets the observable response to a ui-model to use in the template.
Is it a standard or good practice to use api and ui models instead of just one in the front-end? - I am using DTOs and DAOs in the API and have an understanding of the why but not clear there is a benefit to doing this in the Front-end.
Is there an advantage to using an interface instead of a class when creating models? So far this is the first example I've seen of someone using an interface in Angular when creating a model.
UI and API models are identical. He basically puts the API fetched data into an API model and dumps it into a UI model to use in the template
When you say models I'm assuming you just mean defining a schema for your data (type, interface, or class). The main purpose of them is to make sure you as a developer do not make mistakes. If you have defined a data type and you try to access a property that doesn't exist, the typescript compiler will catch this. Another example is if you try to do some math with the id parameter, the compiler will tell you that's a string, not a number.
Yes, you should define your schemas on both sides, or you'll be making dumb mistakes like that all over the place. Plus this way you get intellisense and code completion.
As for the difference between interfaces and classes, there are three ways to define a data type in typescript:
Types
This is simply an object type where each property type is defined. Types do not support inheritance, and they do not have constructors.
type Fruit = {
name: string;
color: string;
weight: number;
similarFruits: Fruit[];
decompose: () => RottenFruit;
};
Interfaces
Interfaces are essentially the same as types but they can extend eachother, and classes can implement them.
interface Fruit {
name: string;
color: string;
}
interface Banana extends Fruit {
eat: () => string;
}
class BigYellowBanana implements Banana {
name: string;
color: string;
eat: () => string;
constructor() {
this.name = 'Big Yellow Banana';
this.color = 'Yellow';
this.eat = () => 'mmmm banana';
}
}
Classes
Classes are a whole other can of worms because they have all the functionality of an object oriented language. Most notably, a constructor that can be called with the new keyword.
class BigBanana extends SmallBanana implements Banana {
name: string;
color: string;
private eatMessage = 'mmmm banana';
constructor(color: string) {
this.color = color;
this.name = `Big ${color} Banana`;
}
eat() {
return this.eatMessage;
}
}
const greenBanana = new BigBanana('Green');
I apologize for my dumb examples.

How to register a class by convention that implements two interfaces?

Let's say I have a class that implements IFoo and IBar. I want to register the class by convention in Unity so that I can inject it via either IFoo or IBar. Is there a way to do this?
Let's start from the unity without using the convention. In that case, you want to register the implementation and bind it to multiple interface you would probably do something like this:
container.Register(typeof(BarFoo), lifetime);
container.Register(typeof(IBar), typeof(BarFoo));
container.Register(typeof(IFoo), typeof(BarFoo));
The points using convention is to archive something like this. The example is really simplified and tries to point out what should be done. The assumption is that type is BarFoo but generally the type is each type which is defined within assembly so some additional logic should be applied to detect multi interface implementations.
container.RegisterTypes(
AllClasses.FromAssemblies(Assembly.Load("AssemblyName")),
type => new[] { typeof(BarFoo), typeof(IFoo), typeof(IBar) },
WithName.Default,
WithLifetime.Hierarchical);
The point is to register the implementation itself next to the interface, then the interface will be mapped to the implementation. If you don't register implementation then each interface will be bound to the separate instance of the implementation. IMO this doesn't make sense with TransiendLifetime...however, you have the possibility to tweak the lifetime per type as well.
n.b. Just as a showcase how it could be implemented
container.RegisterTypes(
AllClasses.FromAssemblies(Assembly.Load("AssemblyName")),
type =>
{
var types = WithMappings.FromAllInterfaces(type).ToList();
if(!type.IsAbstract && type.GetInterfaces().Count() > 1) //more than one interface
{
types.Add(type);
}
return types;
},
WithName.Default,
WithLifetime.Hierarchical);

Kotlin reflection on object instance

I've been trying some stuff from kotlin.reflection during my project, and got stuck on something what occurs to me as hard to understand, I have declared object as follows:
object WebsiteMapping
{
const val ADMIN = "/admin"
}
once I call:
Arrays
.stream(WebsiteMapping::class.java.declaredFields)
.forEach { field -> println(field.type) }
what I get is:
class java.lang.String
class mapping.WebsiteMapping
When I looked a little bit into what is behind declaredFields invocation I grasped why it works as it is, but is there any convenient way of taking only declared consts within that object without getting also root of the whole structure?
The field with the type class mapping.WebsiteMapping is, basically, not the root of the structure but a special field generated in the object type that holds the reference to the singleton object.
In Kotlin, this field is named INSTANCE by convention. You can therefore filter the fields that you get from the class as follows:
WebsiteMapping::class.java.declaredFields
.filter { it.name != "INSTANCE" }
.forEach { println(it.type) }
Another solution is to switch from java.reflect.* to the Kotlin reflection API kotlin.reflect (needs a dependency on the kotlin-reflect module), which automatically filters the property:
WebsiteMapping::class.memberProperties
.forEach { println(it.returnType) }

Swift discover protocol methods

I'm developing a HTML5 showcase application and I need to discover all the methods in my Swift protocols. All the protocols extends from a base protocol.
The application is a HTML5 showcase for testing this methods. The app calls the method and gives the response.
I found some information about one specific protocol but i need to discover all the protocols in my app and then all the information (name, arguments name arguments type and return values) about this methods.
#objc protocol Protocol {
func method1()
func method2() -> Bool
func method3(param1:Int) -> Bool
func method4(param1:Int, param2:Int, param3:Int) -> Bool
}
var numMethods:UInt32 = 0
var methods:UnsafeMutablePointer<objc_method_description> = protocol_copyMethodDescriptionList(Protocol.self, true, true, &numMethods)
for var iuint:CUnsignedInt = 0; iuint < numMethods; iuint++ {
var i:Int = Int(iuint)
var method:objc_method_description = methods[i]
println("Method #\(i): \(method.name)")
}
I'm using Objective-C Runtime Reference
Any ideas how to do this in swift?
You are going to want to get:
the method implementation (method_getImplementation) https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/c/func/method_getImplementation
and the method selector (method_getName) https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/index.html#//apple_ref/c/func/method_getName
Then in objective-c (using a bridged file, of course), cast the method implementation (i.e. IMP) as a function pointer. Then call the function pointer in objective-c with the
target
selector
and any parameters you may have
id (*func)(id, SEL, id) = (void *)imp;
return func(target, selector, param);`
Take a look at how in this blog post he calls the init method and that should help as well.
http://ijoshsmith.com/2014/06/05/instantiating-classes-by-name-in-swift/
There is no real reflection in swift.
For more reading, please read:
Does Swift support reflection?
How do I print the type or class of a variable in Swift?
http://waffletower.blogspot.sg/2014/06/swift-doesnt-have-much-objective-c.html
https://github.com/mikeash/MAObjCRuntime

Resources