How to handle Optional Grammar Blocks with a ANTLR-Visitor? - antlr4

It is possible that this question has been asked before but i cannot find it. So if you guys find something similar, please let me know.
According to the following Rule:
fix_body : ident binders (annotation)? (':' term)? ':=' fix_body_term;
I have an optional annotation and an optional Term. The corresponding visitorRule looks like this :
public FixBody visitFix_body(coqParser.Fix_bodyContext ctx)
My Question is how do i find out, if there was a term or not?
There is a method for reaching the term by using ctx.term(), but when there is no term given, does this method return null? Or is there a completly different way to approach this? As i am working with a large grammer it will take me a while to test this, otherwise I would have done that.

There is no trap there ...
If the term is optional, you just have to test it before calling the accept(visitor) method
In your case
if(ctx.term() != null) ctx.term().accept(new TermVisitor())
Example:
Optional in a grammar
Testing before accepting the visitor

Related

Groovy Pattern for matching a value in map

Hy guys, i'm working on a IDEA plugin and custom references. I have many references working, but i'm stuck with a difficult one.
I'd like to detect patterns in groovy such as this one :
result = run service: 'createAgreementItem', with: createAgreementItemInMap
In the above line, i'd like to get the createAgreementItem element to match.
run is defined in a groovy base script
package org.apache.ofbiz.service.engine
abstract class GroovyBaseScript extends Script {
//...
Map run(Map args) throws ExecutionServiceException {
return runService((String)args.get('service'), (Map)args.get('with', new HashMap()))
}
//...
The problem is, what i'm trying to get isn't technically a parameter, it's a value from a map with the key equals to service.
So this won't work :
GroovyPatterns.groovyLiteralExpression()
.methodCallParameter(0,
GroovyPatterns.psiMethod().withName("run")
.definedInClass("org.apache.ofbiz.service.engine.GroovyBaseScript"))
Do you have any ideas or any help ? Thanks in advance !
EDIT :
Actually, i'm looking for a doc or an example for any use of the org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyPatterns
library.
I don't get it, maybe i'm not familiar enough with groovy though i used it a bit.
Any help welcome on this.
The problem is, what i'm trying to get isn't technically a parameter,
it's a value from a map with the key equals to "service"
If all you want to do is retrieve the service value from the Map then instead of args.get('with', new HashMap()) you could do args.with.service. If you wanted null safety, you could do args?.with?.service.

How to define and call a function in Jenkinsfile?

I've seen a bunch of questions related to this subject, but none of them offers anything that would be an acceptable solution (please, no loading external Groovy scripts, no calling to sh step etc.)
The operation I need to perform is a oneliner, but pipeline limitations made it impossible to write anything useful in that unter-language...
So, here's minimal example:
#NonCPS
def encodeProperties(Map properties) {
properties.collect { k, v -> "$k=$v" }.join('|')
}
node('dockerized') {
stage('Whatever') {
properties = [foo: 123, bar: "foo"]
echo encodeProperties(properties)
}
}
Depending on whether I add or remove #NonCPS annotation, or type declaration of the argument, the error changes, but it never gives any reason for what happened. It's basically random noise, that contradicts the reality of the situation (at times it would claim that some irrelevant object doesn't have a method encodeProperties, other times it would say that it cannot find a method encodeProperties with a signature that nobody was trying to call it with (like two arguments instead of one) and so on.
From reading the documentation, which is of disastrous quality, I sort of understood that maybe functions in general aren't serializable, and that is why you need to explain this explicitly to the Groovy interpreter... I'm sorry, this makes no sense, but this is roughly what documentation says.
Obviously, trying to use collect inside stage creates a load of new errors... Which are, at least understandable in that the author confesses that their version of Groovy doesn't implement most of the Groovy standard...
It's just a typo. You defined encodeProperties but called encodeProprties.

How to match a possible null parameter in Mockito

I'm trying to verify that the class I'm testing calls the correct dependency class's method. So I'm trying to match the method parameters, but I don't really care about the actual values in this test, because I don't want to make my test brittle.
However, I'm running into trouble setting it up because Mockito has decided that the behaviour I'm expecting is a bug: https://github.com/mockito/mockito/issues/134
So what't the correct way to define an ArgumentMatcher for a parameter that might be null?
With issue #134 "fixed", this code fails because the matchers only match in the first case. How can I define a matcher to work in all 4 cases?
MyClass c = mock(MyClass.class);
c.foo("hello", "world");
c.foo("hello", null);
c.foo(null, "world");
c.foo(null, null);
verify(c, times(4)).foo(anyString(), anyString());
From the javadocs of any()
Since Mockito 2.1.0, only allow non-null String. As this
is a nullable reference, the suggested API to match
null wrapper would be isNull(). We felt this
change would make tests harness much safer that it was with Mockito
1.x.
So, the way to match nullable string arguments is explicit declaration:
nullable(String.class)
I got this to work by switching to any(String.class)
I find this a bit misleading, because the API seems to suggest that anyString() is just an alias for any(String.class) at least up till the 2.0 update. To be fair, the documentation does specify that anyString() only matches non-null strings. It just seems counter-intuitive to me.
How about:
verify(c, times(4)).foo(anyObject(), anyObject());
Does that work for you?
Matchers.anyObject() allows for nulls.
Reference in Mockito docs:

xtext inferrer: multiple entities

I am very new to Xtext/Xtend, therefore apologies in advance if the answer is obvious.
I would like to allow the end-users of my DSL to define a 'filter', that when applied and 'returns' true it means that they want to 'filter out' the given entity of data from consideration.
I want to allow them 2 ways of defining the filter
A) by introspecting the attributes of a given data object and apply basic rules like
if (obj.field1<CURRENT_DATE && obj.field2=="EXPIRED)
{ return true;} else {return false;}
B) by executing a controlled snippet using 'eval' of my host language
In other words, the user would be expected to type into a string/code block a valid
code snippet of the hosting language
I had decided that the easiest way for me support case A) would be to leverage the XBase rules (including expressions/etc)
Therefore I defined filters (mostly copying the ideas from Lorenzo's book)
Filter:
(FilterDSL | FilterCode);
FilterDSL:
'filterDSL' (type=JvmTypeReference)? name=ID
'(' (params+=FullJvmFormalParameter (',' params+=FullJvmFormalParameter)*)? ')'
body=XBlockExpression ;
FilterCode:
'filterCode' (type=JvmTypeReference)? name=ID
'(' (params+=FullJvmFormalParameter (',' params+=FullJvmFormalParameter)*)? ')'
'{'
body=STRING
'}';
Now when trying to implement the Java mapping for my DSL, via the inferrer stub in Xtend -- I am running into multiple problems.
All of them likely indicate that I am missing some fundamental understanding
Problem 1) fl.body is not defined. fl Is of type Filter, not FilterDSL or FilterCode
And I do not understand how to check what type a given instance is of, so that I can access the content of a 'body' feature.
Problem 2) I do not understand where 'body' attribute in the inferrer method is defined and why. Is this part of ECore? (I could not find it)
Problem 3) what's the proper way to allow a user to specify a code block? String seems to be not the right thing as it does not allow multiline
Problem 4) How do I correctly convert a code block into something that is accepted by the 'body' such that it ends up in the generated code.
Problem 5) How do I setup multiple inferrers (as I have more than one thing for which I need the code generated (mostly) by xBase code generator)
Appreciate in advance any suggestions, or pointer to code examples solving similar problems.
As a side observation, Inferrer and its interplay with XBase has sofar been the most confusing and difficult thing to understand.
in general: have a look at the xtend docs at xtend-lang.org
You can do a if (x instanceof Type) or a switch statement with Type guards (see domain model example)
i dont get that question. both your FilterDSL and FilterCode EClasses should have a field+getter/setter named body, FilterCode of type String, FilterDSL of type XBlockExpression. The JvmTypesBuilder add extension methods to JvmOperation called setBody(String) and setBody(XExpression), syntax sugar lets you call body = .... instead of setBody(...)
(btw you can do crtl+click to find out where a thing is defined)
strings are actually multiline
is answered by (2)
you dont need multiple inferrers, you can infer multiple stuff e.g. by calling toClass or toField multiple times for the same input

ANTLR 4 : How to know the existence of subpart in rule

I have this code :
varDeclaration
: type ID ('=' expression)? ';'
;
So, not always ('=' expression) exist. But, sometimes, I want to process this part, but don't know it exist or not in this context. I'm using ANTLR 4 (and often using Listener), how can I know this.
Thanks :)
In your listener (exitVarDeclaration) or visitor (visitVarDeclaration) check whether ctx.expression() == null. If null, then ('=' expression) didn't exist. If non-null, then it did exist.

Resources