Pass multiple types as parameter in filter function of Iterable object in Xtend - xtext

I am using the DSL generator interface of Xtext in order to generate some models based on my Xtext DSL. This is working fine, but right now I am facing a bit of a problem in writing the generator. I am using the generator to filter out Rules declared in my Xtext DSL. I do this by selecting certain Rules and then convert them in an Iterable object, which I can then use to filter on certain types (see the toIterable.filter() parts in my code below). The code below contains one for loop which itself again contains 3 nested for loops. These nested loops all filter on one specific kind of Method Statement (types that I declared in my DSL). I would like to combine these 3 for loops in one for loop by passing the 3 types as parameters in the filter() method. In this case there would be one nested for loop where the condition would ideally look something like:
for (eachMethodStatement : ifStatement.expression.eAllContents.toIterable.filter(StatementSort1, StatementSort2, StatementSort3)
The problem is that the filter() method only takes one argument (one type), so right now I have to write three dispatch methods called getDemand which all basically do the same. It works right now, but this forces me to write a lot of boilerplate code for each type that I want to filter.
Is there a way to filter multiple types (in one for loop) without creating a lot of boilerplate code?
for (ifStatement : ifElseStatement.eAllContents.toIterable.filter(IfStatements)){
for (persistenceFunction : ifStatement.expression.eAllContents.toIterable.filter(SingleLibraryPersistenceMethodStatement)) {
expressionDemand += getDemand(persistenceFunction,resourceTable)
}
for (interfaceFunction : ifStatement.expression.eAllContents.toIterable.filter(SingleLibraryInterFaceMethodStatement)) {
expressionDemand += getDemand(interfaceFunction,resourceTable)
}
for (businessFunction : ifStatement.expression.eAllContents.toIterable.filter(SingleLibraryBusinessMethodStatement)) {
expressionDemand += getDemand(businessFunction,resourceTable)
}
for (persistenceFunction : ifStatement.expression.eAllContents.toIterable.filter(RelationalOperator)) {
expressionDemand += getDemand(persistenceFunction,resourceTable)
}
}

<T> T filter(Class<T>) cannot do multiple types because then the return type could not be T but - in the extreme case Object which must be cast later.
But: If your four types (SingleLibraryPersistenceMethodStatement, SingleLibraryInterFaceMethodStatement, SingleLibraryBusinessMethodStatement, RelationalOperator) share a specific interface or supertype you can used that with the existing filter() method:
for (ifStatement : ifElseStatement.eAllContents.toIterable.filter(IfStatements)){
for (statement : ifStatement.expression.eAllContents.toIterable.filter(Statement)) {
expressionDemand += getDemand(statement,resourceTable)
}
}
def Demand getDemand(Statement statement, ResourceTable resourceTable){
...
}
Another solution is to avoid filter in this case and use switch with type guards like this:
for (ifStatement : ifElseStatement.eAllContents.toIterable.filter(IfStatements)){
for (it : ifStatement.expression.eAllContents) {
switch(it){
SingleLibraryPersistenceMethodStatement,
SingleLibraryPersistenceMethodStatement,
SingleLibraryBusinessMethodStatement:
expressionDemand += getDemand(it,resourceTable)
}
}
}

Related

Dart Generic Function with Subtype function call

I am not sure if this is even possible but here's my setup:
I have basically 2 Maps holding a special identifier to get some objects.
these identifier is like a versioning number, i may have data in version 8 that belongs to meta version 5. But at the same time, Meta versions up to 10 may exist and not every meta version holds information about every data, so here's where the _filter kicks in.
The filter is able to find to any given value the correct object. So far so good.
My question belongs to the following: (last codeline)
how am i able to say "if you have no matching candidate, generate me a default value"
For this purpose, i tried to force a named constructor with a super class for "Data" and "Meta" called "BasicInformation".
But even if i implement this, how do i call something like T.namedConstructor(); ?
class Repo{
Map<int, Data> mapData;
Map<int, Meta> mapMeta;
Data getData(int value)
{
return _filter<Data>(mapData, value);
}
Meta getMeta(int value)
{
return _filter<Data>(mapMeta, value);
}
T _filter<T extends BasicInformation>(Map<int, T>, int value)
{
//fancy filtering technique
//....
//speudo code
if (found) return map[found]; //speudo code
else return T.generateDefault();
}
}
I've found the following stackoverflow entry: Calling method on generic type Dart
which says, this is not possible without adding a function call.

RxJava2 order of sequence called with compleatable andThen operator

I am trying to migrate from RxJava1 to RxJava2. I am replacing all code parts where I previously had Observable<Void> to Compleatable. However I ran into one problem with order of stream calls. When I previously was dealing with Observables and using maps and flatMaps the code worked 'as expected'. However the andthen() operator seems to work a little bit differently. Here is a sample code to simplify the problem itself.
public Single<String> getString() {
Log.d("Starting flow..")
return getCompletable().andThen(getSingle());
}
public Completable getCompletable() {
Log.d("calling getCompletable");
return Completable.create(e -> {
Log.d("doing actuall completable work");
e.onComplete();
}
);
}
public Single<String> getSingle() {
Log.d("calling getSingle");
if(conditionBasedOnActualCompletableWork) {
return getSingleA();
}else{
return getSingleB();
}
}
What I see in the logs in the end is :
1-> Log.d("Starting flow..")
2-> Log.d("calling getCompletable");
3-> Log.d("calling getSingle");
4-> Log.d("doing actuall completable work");
And as you can probably figure out I would expect line 4 to be called before line 3 (afterwards the name of andthen() operator suggest that the code would be called 'after' Completable finishes it's job). Previously I was creating the Observable<Void> using the Async.toAsync() operator and the method which is now called getSingle was in flatMap stream - it worked like I expected it to, so Log 4 would appear before 3. Now I tried changing the way the Compleatable is created - like using fromAction or fromCallable but it behaves the same. I also couldn't find any other operator to replace andthen(). To underline - the method must be a Completable since it doesn't have any thing meaning full to return - it changes the app preferences and other settings (and is used like that globally mostly working 'as expected') and those changes are needed later in the stream. I also tried to wrap getSingle() method to somehow create a Single and move the if statement inside the create block but I don't know how to use getSingleA/B() methods inside there. And I need to use them as they have their complexity of their own and it doesn't make sense to duplicate the code. Any one have any idea how to modify this in RxJava2 so it behaves the same? There are multiple places where I rely on a Compleatable job to finish before moving forward with the stream (like refreshing session token, updating db, preferences etc. - no problem in RxJava1 using flatMap).
You can use defer:
getCompletable().andThen(Single.defer(() -> getSingle()))
That way, you don't execute the contents of getSingle() immediately but only when the Completablecompletes and andThen switches to the Single.

ANTLR Parse tree modification

I'm using ANTLR4 to create a parse tree for my grammar, what I want to do is modify certain nodes in the tree. This will include removing certain nodes and inserting new ones. The purpose behind this is optimization for the language I am writing. I have yet to find a solution to this problem. What would be the best way to go about this?
While there is currently no real support or tools for tree rewriting, it is very possible to do. It's not even that painful.
The ParseTreeListener or your MyBaseListener can be used with a ParseTreeWalker to walk your parse tree.
From here, you can remove nodes with ParserRuleContext.removeLastChild(), however when doing this, you have to watch out for ParseTreeWalker.walk:
public void walk(ParseTreeListener listener, ParseTree t) {
if ( t instanceof ErrorNode) {
listener.visitErrorNode((ErrorNode)t);
return;
}
else if ( t instanceof TerminalNode) {
listener.visitTerminal((TerminalNode)t);
return;
}
RuleNode r = (RuleNode)t;
enterRule(listener, r);
int n = r.getChildCount();
for (int i = 0; i<n; i++) {
walk(listener, r.getChild(i));
}
exitRule(listener, r);
}
You must replace removed nodes with something if the walker has visited parents of those nodes, I usually pick empty ParseRuleContext objects (this is because of the cached value of n in the method above). This prevents the ParseTreeWalker from throwing a NPE.
When adding nodes, make sure to set the mutable parent on the ParseRuleContext to the new parent. Also, because of the cached n in the method above, a good strategy is to detect where the changes need to be before you hit where you want your changes to go in the walk, so the ParseTreeWalker will walk over them in the same pass (other wise you might need multiple passes...)
Your pseudo code should look like this:
public void enterRewriteTarget(#NotNull MyParser.RewriteTargetContext ctx){
if(shouldRewrite(ctx)){
ArrayList<ParseTree> nodesReplaced = replaceNodes(ctx);
addChildTo(ctx, createNewParentFor(nodesReplaced));
}
}
I've used this method to write a transpiler that compiled a synchronous internal language into asynchronous javascript. It was pretty painful.
Another approach would be to write a ParseTreeVisitor that converts the tree back to a string. (This can be trivial in some cases, because you are only calling TerminalNode.getText() and concatenate in aggregateResult(..).)
You then add the modifications to this visitor so that the resulting string representation contains the modifications you try to achieve.
Then parse the string and you get a parse tree with the desired modifications.
This is certainly hackish in some ways, since you parse the string twice. On the other hand the solution does not rely on antlr implementation details.
I needed something similar for simple transformations. I ended up using a ParseTreeWalker and a custom ...BaseListener where I overwrote the enter... methods. Inside this method the ParserRuleContext.children is available and can be manipulated.
class MyListener extends ...BaseListener {
#Override
public void enter...(...Context ctx) {
super.enter...(ctx);
ctx.children.add(...);
}
}
new ParseTreeWalker().walk(new MyListener(), parseTree);

Exiting from the middle of a drools rule

In java method we can return from the middle skipping the rest of the method code being executed. e.g.
public String doSomething(){
step 1
step 2
if(some condition){
return "Exited from the middle";
}
step 4
return "Whole code is executed"
}
Is there a way to do such things in a drools rule?
It's quite simple:
return;
Since there's no place of invocation for a single rule you can control, or write code doing that, a return with an expression is not vailable. You can collect values you'd like to return in a global variable, List<String> or, perhaps, Map<String,List<String>> with rule names acting as keys.
Clarification
A rule's right hand side results in a static method with void as result type. A return statement just acts naturally.

Implementing Indexer in F#

I am trying to convert this C# code to F#:
double[,] matrix;
public Matrix(int rows, int cols)
{
this.matrix = new double[rows, cols];
}
public double this[int row, int col]
{
get
{
return this.matrix[row, col];
}
set
{
this.matrix[row, col] = value;
}
}
Basically my biggest problem is creating the indexer in F#. I couldn't find anything that I could apply in this situation anywhere on the web. I included a couple of other parts of the class in case incorporating the indexer into a Matrix type isn't obvious. So a good answer would include how to make a complete type out of the three pieces here, plus anything else that may be needed. Also, I am aware of the matrix type in the F# powerpack, however I am trying to learn F# by converting C# projects I understand into F#.
Thanks in advance,
Bob
F# calls them "indexed properties"; here is the MSDN page. In F# they work slightly differently - each indexed property has a name.
However, there is a default one called "Item". So an implementation of your example would look like this:
member this.Item
with get(x,y) = matrix.[(x,y)]
and set(x,y) value = matrix.[(x,y)] <- value
Then this is accessed via instance.[0,0]. If you have named it something other than "Item", you would access it with instance.Something[0,0].

Resources