Groovy Syntax Checking in Java - java

I'm implementing a Web-based Groovy code editor and need to check the code for syntax errors. The Java implementation below works OK but the resulting message contains some undesired elements (in bold). I'm looking for a way to list warnings and errors individually.
I'm using this maven dependency: groovy-all 2.1.1
try {
new GroovyShell().parse(groovyCode);
} catch(CompilationFailedException cfe) {
System.out.println(cfe.getMessage());
}
Output:
startup failed:
Script1.groovy: 1: unexpected token: n # line 1, column 19.
def factorial(n) n == 1 ? 1 : n * factorial(n - 1) }
^
1 error

Would not make much sense to parse the error message. Try to look into
CompilationFailedException.getUnit()
ProcessingUnit.getErrorCollector()
ErrorCollector.getWarnings() & getErrors()
EDIT
Ok, looks like unit is null on the CompilationFailedException. Try catching MultipleCompilationErrorsException instead:
try {
new GroovyShell().parse(groovyCode);
} catch(MultipleCompilationErrorsException cfe) {
ErrorCollector errorCollector = cfe.getErrorCollector();
System.out.println("Errors: "+errorCollector.getErrorCount());
}
Btw, take a look at the ErrorCollector sources, you might find write method useful to output the info about compilation errors.

Related

Antlr4: Confusing error message (concatenates correct and incorrect lines) for Java grammar

I am trying to build my own parser based on the existing Java grammar.
Even if I use the Java7 grammar from the source repo, generate the parser and use the TestRig from antlr-4.9.3-complete.jar given the code:
1 public class Test {
2 public static void main() {
3 test
4 int b = 1;
5 }
6 }
I get the following error:
line 4:8 no viable alternative at input 'test\n int'
So for some reason it concatenates the incorrect "test" line with correct "int" line.
Also it says "line 4:8" pointing at the "int" line when it should be pointing to "test" (line 3).
(In a regular Java editor I would see a correct error highlighting for the "test" word which would sound like):
"Syntax error, insert "VariableDeclarators" to complete LocalVariableDeclaration"
What do I do to arrive at a similar error with ANTLR so it only picks on the wrong "test" line?
Most likely it's just my misunderstanding how antlr interprets the errors, then how would I get the listener to at least report correctly the starting line?
You can't compare a sophisticated editor/IDE with a parser (generated by ANTLR). A text editor/IDE knows more about the input source and can look up if test is a valid type, and give a meaningful error message if the type cannot be found.
ANTLR's parser rule "sees" test int b as an Identifier, an INT and another Identifier token and cannot match any parser rule for these tokens, resulting in the error starting at the identifier test.
For example, if class test {} was in the classpath, then input without int would be valid:
public class Test {
public static void main() {
test
/*int*/ a = 1;
}
}
It wouldn't compile of course, but the syntax would be correct:

getting syntax error from nifi ExecuteScript processor inspite of correct python code

I am getting below error inspite of correct python code don't know how to resolve this error. Any help is much appreciated
org.apache.nifi.processor.exception.ProcessException: javax.script.ScriptException: SyntaxError: no viable alternative at input '*' in <script> at line number 35 at column number 26
python code
def get_match_list(regEx, line):
match = re.search(regEx, line)
print(match)
if match:
match_list = [*match.groups()] # this is the line exception is pointed
return match_list
else:
return []
It looks like jython use python 2.7 and as Unpacking Generalizations is a feature that introduced in python 3.5 you can not use this syntax in jython, so an alternative way to convert a tuple to a list is that use list ( match.groups) it works fine in older versions of python and current version of jython (2.7.2)

How to allow catchError in Jenkins?

So I fixed one of my organisation's needs by adding a catchError statement in one of their groovy files but in turn this creates a build error with a generic Jenkins test library BasePipelineTest:
[main] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - PipelineTest.testCall_AllFieldsAvailable:71 ? MissingMethod No signature
[main] ERROR org.apache.maven.plugin.surefire.SurefirePlugin - PipelineTest.testCall_FieldsNotAvailable:130 ? MissingMethod No signature
As part of the Jenkins standard BasePipelineTest class the solution for this is typically:
helper.registerAllowedMethod("cleanWs", []) {}
For a method like cleanWs(), or something similar depending on the method and its inputs. However this is for methods with input values, but catchError doesn't have input values, rather it's done like:
catchError {
...
}
So helper.registerAllowedMethod("catchError", []) {} does not work. Does anyone know how to make it work for something like catchError?
I have also attempted:
helper.registerAllowedMethod("catchError", [com.lesfurets.jenkins.unit.catchError]) {}
This creates a MissingProperty error
Turns out the curly brackets themselves register as a class in groovy. I fixed it with:
helper.registerAllowedMethod("catchError", [Closure.class]) {}

Eigen - Levenberg Marquardt algorithm: invalid template arguments on definition of permutation

I'm trying to use the Eigen implementation of Levenberg Marquardt algorithm on a Android application. In order to use Eigen, I'm using Android NDK and jni. I've already tested Eigen with simple calculations (like matrix creation and vector sums) and it works perfectly. However, when I tried to use the Levenberg Marquardt algorithm I got some errors on the LevenbergMarquardt.h file from Eigen's library.
First, here is my code. I based on this code:
Eigen::MatrixXd matrix(count, 3);
for (int i = 0; i < count; i++) {
Eigen::VectorXd t(3);
t << x[i], y[i], accuracy[i];
matrix.row(i) = t;
}
distance_functor functor(matrix, count);
Eigen::NumericalDiff<distance_functor> numDiff(functor);
Eigen::LevenbergMarquardt<Eigen::NumericalDiff<distance_functor>,double> lm(numDiff);
lm.parameters.maxfev = 2000;
lm.parameters.xtol = 1.49012e-08;
lm.parameters.ftol = 1.49012e-08;
lm.parameters.gtol = 0;
lm.parameters.epsfcn = 0;
Eigen::LevenbergMarquardtSpace::Status ret = lm.minimize(poseResult);
And those are the error that I got. The first two errors are in Eigen's library, and the last one is on the LevenbergMarquardt object creation. I've also included the respective line of code of the error, following the message:
Invalid template
arguments LevenbergMarquardt.h /jnimath/jni/unsupported/Eigen/src/LevenbergMarquardt line
121 Semantic Error
typedef PermutationMatrix<Dynamic,Dynamic> PermutationType;
Invalid template
arguments LevenbergMarquardt.h /jnimath/jni/unsupported/Eigen/src/NonLinearOptimization line
103 Semantic Error
PermutationMatrix<Dynamic,Dynamic> permutation;
Invalid template arguments test.cpp /jnimath/jni line 47 Semantic
Error
Eigen::LevenbergMarquardt,double> lm(numDiff);
The first two errors are really strange because there are some other typedefs using Dynamic and they are not throwing errors.
Also, I noticed that I got some symbol errors on the compilation, which are:
Symbol
'YOU_MIXED_DIFFERENT_NUMERIC_TYPES__YOU_NEED_TO_USE_THE_CAST_METHOD_OF_MATRIXBASE_TO_CAST_NUMERIC_TYPES_EXPLICITLY'
could not be resolved Matrix.h /jnimath/jni/Eigen/src/Core line
277 Semantic Error
Symbol 'YOU_TRIED_CALLING_A_VECTOR_METHOD_ON_A_MATRIX' could not be
resolved Matrix.h /jnimath/jni/Eigen/src/Core line 224 Semantic Error
So, I have two questions:
Why am I getting errors on those lines?
Does anyone know how to fix that problem?
Thank you

Gradle - Java Project - Generic For Loop

I have a very simple generic for loop that is causing problems when I attempt to build the project using gradle:
for(TaskAttribute taskAttribute:task.getAttributes())
{
...
}
Task.java
protected final Set<TaskAttribute> attributes = new HashSet<TaskAttribute>();
public Set<TaskAttribute> getAttributes(){return(attributes);}
The error I am getting is that the for loop is getting Object, but requries TaskAttribute. I have my sourceCompatibility set to 1.6. Am I missing something else?
In groovy you can do for loops one of two ways.
task forLoopTest {
// print numbers 8 to 19 inclusive
for (x in 8..19) {
println 'this is run '+x
}
// print numbers 0 to 4
println 'now some groovy'
for(int i = 0;i<5;i++) {
println i
}
}
Run on CLI:
$ gradle forLoopTest
This should out put.
this is run 8
this is run 9
this is run 10
this is run 11
this is run 12
this is run 13
this is run 14
this is run 15
this is run 16
this is run 17
this is run 18
this is run 19
0
1
2
3
4
The basic set up for the enhanced for loop is :
for(<Object_Type> <Object_Name> : <Collection_Name>)
I am not sure what task.getAttributes() returns or what task is, but if you have a Collection( a Set) called attributes you should just change your loop to this:
for(TaskAttribute taskAttribute : attributes)
{
...
}
Note: Since this is a private Set you may be trying to use this from another class, so getAttributes() might be returning a reference to the Set object. In which case my answer may not be useful.
Your code looks fine. Make sure you clean the project and rerun.
What is likely happening is that the type of task is a raw type, of a class that is generic (i.e. it can be parameterized but you didn't parameterize it). If this is the case, I know that logically it shouldn't make a difference on the result of the getAttributes() method; but using raw types "turns off" generics and so it says getAttributes() returns just Set, without its parameter, which causes things you get out of it to be Object.

Categories

Resources