javacc,why ' return jjtThis ' - javacc

Why write return jjtThis at the end of the methods?
What effect will it make?
What if I don't write this line?
When should I add this line and when shouldn't I add this line?
Is it return for the judge of other place?
ASTDirectSQLStatement DirectSQLStatement() :
{}
{
DirectlyExecutableStatement() <SEMICOLON>
{
return jjtThis;
}
}
ASTDirectlyExecutableStatement DirectlyExecutableStatement() :
{}
{ (
LOOKAHEAD(<SELECT> | <DELETE> <FROM> | <INSERT> | <UPDATE> | <DECLARE>)
DirectSQLDataStatement()
| LOOKAHEAD(SQLSchemaStatement())
SQLSchemaStatement()
)
{
return jjtThis;
}
}
Thank you :)

Quite simply, jjtThis is a special identifier of SimpleNode class, that refers to the Function/Production it is written inside of. We use/return jjtThis when we generate a parse tree or AST. In your example; DirectSQLStatement production is a node in a tree, this production calls another production DirectlyExecutableStatement which will be DirectSQLStatement's child node in the tree, DirectlyExecutableStatement then calls some other production(s) which will be its children so on so forth.
SimpleNode is the class that makes your tree. Usually jjtThis is returned only from the first production/function of grammar and in main() you have a SimpleNode's object say "root" that catches it. Then by root.Dump(" ") the tree is printed. Hope it helps!

Related

Add element to arrays, that are values to a given key name (json transformation with jq)

I'm a jq newbie, and I try to transform a json (a Swagger spec). I want to add an element to the array value of the "parameter" keys:
{
...
"paths": {
"/great/endpoint1": {
"get": {
"parameters": [] <<--- add a value here
}
}
"/great/endpoint2": {
"post": {
"parameters": [] <<-- and here too here too etc.
....
The following jqplay almost works. It adds values to the right arrays, but it has the nasty side effect of also removing the "x-id" value from the root of the input json. It's probably because of a faulty if-condition. As the paths contain a varying string (the endpoint names), I don't know how to write a wildcard path expression to address those, which is why I have tried using walk instead:
https://jqplay.org/s/az56quLZa3
Since the sample data is incomplete, it's difficult to say exactly what you're looking for but it looks like you should be using parameters in the call to walk:
walk(if type=="object" and has("parameters")
then .parameters += [{"extra": "value"}]
else . end)
If you want to restrict the walk to the top-level paths, you would preface the above with: .paths |=

Iterating along a Dictionary in Swift 3

I am trying to iterate along a Dictionary in order to prune unconfirmed entries. The Swift 3 translation of the following Objective-C code does not work:
[[self sharingDictionary] enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
SharingElement* element=[[self sharingDictionary] objectForKey:key];
if (!element.confirmed){
dispatch_async(dispatch_get_main_queue(), ^{
[element deleteMe];
});
[[self sharingDictionary] performSelector:#selector(removeObjectForKey:) withObject:key
afterDelay:.2];
} else{
element.confirmed=NO;
}];
And so I tried using the following compact enumerated() method in this way:
for (key, element) in self.sharingDictionary.enumerated(){
if (!element.confirmed){
element.deleteMe()
self.perform(#selector(self.removeSharingInArray(key:)), with:key, afterDelay:0.2);
} else{
element.confirmed=false
}
}
Yet the compiler reports the following error while processing the usage of variable 'element':
Value of tuple type '(key: Int, value: SharingElement)' has no member
'confirmed'
Like 'element' took the full tuple father than the part of its competence.
Is the problem in the use of enumerated() or in the processing of the dictionary and how may I fix it?
Use element.value.confirmed. element is a tuple that contains both key and value.
But you probably just want to remove enumerated():
for (key, element) in self.sharingDictionary {
...
}
enumerated() takes the iteration and adds indices starting with zero. That's not very common to use with dictionaries.
This should do the trick,
localDictionary.enumerateKeysAndObjects ({ (key, value, stop) -> Void in
})
I ended up implementing the thing as:
DispatchQueue.global(attributes: .qosBackground).async{
for (key, element) in self.sharingDictionary{
if !element.confirmed{
DispatchQueue.main.async({
element.deleteMe()
self.removeSharingInArray(key:key)
})
} else{
element.confirmed=false
}
}
}
So to hopefully delete the object without changing the Dictionary while it is browsed, what used to crash the app, even if I do not know if it still the case.

if {...} else {...} : Does the line break between "}" and "else" really matters?

I write my if {...} else {...} statement in R in the following way as I find it more readable.
Testifelse = function(number1)
{
if(number1>1 & number1<=5)
{
number1 =1
}
else if ((number1>5 & number1 < 10))
{
number1 =2
}
else
{
number1 =3
}
return(number1)
}
According to ?Control:
... In particular, you should not have a newline between } and else to avoid a syntax error in entering a if ... else construct at the keyboard or via source ...
the function above will cause syntax error, but actually it works! What's going on here?
Thanks for your help.
Original question and answer
If we put in R console:
if (1 > 0) {
cat("1\n");
}
else {
cat("0\n");
}
why does it not work?
R is an interpreted language, so R code is parsed line by line. (Remark by #JohnColeman: This judgement is too broad. Any modern interpreter does some parsing, and an interpreted language like Python has no problem analogous to R's problem here. It is a design decision that the makers of R made, but it wasn't a decision that was forced on them in virtue of the fact that it is interpreted (though doubtless it made the interpreter somewhat easier to write).)
Since
if (1 > 0) {
cat("1\n");
}
makes a complete, legal statement, the parser will treat it as a complete code block. Then, the following
else {
cat("0\n");
}
will run into error, as it is seen as a new code block, while there is no control statement starting with else.
Therefore, we really should do:
if (1 > 0) {
cat("1\n");
} else {
cat("0\n");
}
so that the parser will have no difficulty in identifying them as a whole block.
In compiled language like C, there is no such issue. Because at compilation time, the compiler can "see" all lines of your code.
Final update related to what's going on inside a function
There is really no magic here! The key is the use of {} to manually indicate a code block. We all know that in R,
{statement_1; statement_2; ...; statement_n;}
is treated as a single expression, whose value is statement_n.
Now, let's do:
{
if (1 > 0) {
cat("1\n");
}
else {
cat("0\n");
}
}
It works and prints 1.
Here, the outer {} is a hint to the parser that everything inside is a single expression, so parsing and interpreting should not terminate till reaching the final }. This is exactly what happens in a function, as a function body has {}.

Specman e: How to constrain 'all_different' to list of structs?

I have my_list that defined this way:
struct my_struct {
comparator[2] : list of int(bits:16);
something_else[2] : list of uint(bits:16);
};
...
my_list[10] : list of my_struct;
It is forbidden to comparators at the same index (0 or 1) to be the same in all the list. When I constrain it this way (e.g. for index 0):
keep my_list.all_different(it.comparator[0]);
I get compilation error:
*** Error: GEN_NO_GENERATABLE_NOTIF:
Constraint without any generatable element.
...
keep my_list.all_different(it.comparator[0]);
How can I generate them all different? Appreciate any help
It also works in one go:
keep for each (elem) in my_list {
elem.comparator[0] not in my_list[0..max(0, index-1)].apply(.comparator[0]);
elem.comparator[1] not in my_list[0..max(0, index-1)].apply(.comparator[1]);
};
When you reference my_list.comparator it doesn't do what you think it does. What happens is that it concatenates all comparator lists into one bit 20 element list. Try it out by removing your constraint and printing it:
extend sys {
my_list[10] : list of my_struct;
run() is also {
print my_list.comparator;
};
};
What you can do in this case is construct your own list of comparator[0] elements:
extend sys {
comparators0 : list of int;
keep comparators0.size() == my_list.size();
keep for each (comp) in comparators0 {
comp == my_list.comparator[index * 2];
};
keep comparators0.all_different(it);
// just to make sure that we've sliced the appropriate elements
run() is also {
print my_list[0].comparator[0], comparators0[0];
print my_list[1].comparator[0], comparators0[1];
print my_list[2].comparator[0], comparators0[2];
};
};
You can apply an all_different() constraint on this new list. To make sure it's working, adding the following constraint should cause a contradiction:
extend sys {
// this constraint should cause a contradiction
keep my_list[0].comparator[0] == my_list[1].comparator[0];
};

Newbie on use of recursion in Groovy/traverse tree?

In our current application we have a need to traverse down a tree and capture all operators on a specific device (and child devices). A device could have child devices with also specific operators on it.
As i am new to the use of recursion in Groovy i am wondering if i am doing things right..?
Any pointer to help me learn better ways of doing things?
def listOperators(device) {
// list with all operator id's
def results = []
// closure to traverse down the tree
def getAllOperators = { aDevice->
if(aDevice) {
aDevice.operators.each { it ->
results << it.id
}
}
if (aDevice?.children) {
aDevice.children.each { child ->
results << owner.call(child)
}
}
}
// call the closure with the given device
getAllOperators(device)
// return list with unique results
return results.unique()
}
A couple things to note:
Doing the recursive call through owner is not a good idea. The definition of owner changes if the call is nested within another closure. It's error prone and has no advantages over just using the name. When the closure is a local variable, split its up the declaration and definition of the closure so the name is in scope. E.g.:
def getAllOperators
getAllOperators = { ...
You are appending the operators to a result list outside the recursive closure. But you are also appending the result of each recursive call to the same list. Either append to the list or store the results from each recursive call, but not both.
Here's a simpler alternative:
def listOperators(device) {
def results = []
if (device) {
results += device.operators*.id
device.children?.each { child ->
results += listOperators(child)
}
}
results.unique()
}

Resources