For a programming project, I am tasked with taking a set of ANTLR grammar rules for Java and extending them such that they also contain AST rules for the Eclipse JDT API DOM.
For example:
param
: type ID
;
Would become:
param returns [SingleVariableDeclaration result = ast.newSingleVariableDeclaration()]
: paramType=type { result.setType($paramType.result); }
ID { result.setName(ast.newSimpleName($ID.text)); }
;
The first part of the project was creating the grammer rules themselves, and that wasn't too bad, but this part is really throwing me for a loop. Are there any useful resources, examples, or pointers someone could give me as far as adding the AST rules are concerned?
One of the tips I was given was to use the AST viewer in Eclipse to help pinpoint which parts of the API to look at in the Eclipse documentation, but I'm not sure how this helps.
Some of the rules I need to implement yet are array access, for loops, and so on.
Thanks!
Related
I'm going to use ANTLR 4.5.3 for translating one notation to another. I have already designed grammar description using plugin in IntelliJ IDEA.
In my grammar one rule has several alternatives.
When I'm looking at the results in "Parse Tree" each node consists of "rule name" : "row number".
How to receive this information using API? If I understand it clearly, row number could be retrieved from getAltNumber(), but this field is empty.
http://www.antlr.org/api/Java/org/antlr/v4/runtime/RuleContext.html#getAltNumber()
In the docs is said that default implementation does not compute nor store this alt num.
How to get this information?
I had exactly the same problem. The documentation should be a little more precise, but indeed it gives a clue. Also looking directly at the plugin may lead to the solution:
https://github.com/antlr/intellij-plugin-v4/blob/master/src/java/org/antlr/intellij/plugin/preview/AltLabelTextProvider.java
You may simply add a context super class implementing setAltNumber and getAltNumber as in example:
https://github.com/antlr/antlr4/blob/master/tool/src/org/antlr/v4/tool/GrammarInterpreterRuleContext.java
Then provide the class as a generator parameter, e.g.:
antlr4 -o output/path -listener -visitor -DcontextSuperClass=GrammarInterpreterRuleContext -Dlanguage=Java -lib lib/path grammar.g4
In certain problem I need to parse a Java source code fragment that is potentially incomplete. For example, the code can refer to variables that are not defined in such fragment.
In that case, I would still like to parse such incomplete Java code, transform it to a convenient inspectable representation, and being able to generate source code from such abstract representation.
What is the right tool for this ? In this post I found suggestions to use Antlr, JavaCC or the Eclipse JDT.
However, I did not find any reference regarding dealing with incomplete Java source code fragments, hence this question (and in addition the linked question is more than two years old, so I am wondering if something new is on the map).
As an example, the code could be something like the following expression:
"myMethod(aVarName)"
In that case, I would like to be able to somehow detect that the variable aVarName is referenced in the code.
Uhm... This question does not have anything even vaguely like a simple answer. Any of the above parser technologies will allow you to do what you wish to do, if you write the correct grammar and manipulate the parser to do fallback parsing unknown token passover sort of things.
The least amount of work to get you where you're going is either to use ANTLR which has resumable parsing and comes with a reasonably complete java 7 grammar, or see what you can pull out of the eclipse JDT ( which is used for doing the error and intention notations and syntax highlighting in the eclipse IDE. )
Note that none of this stuff is easy -- you're writing klocs, not just importing a class and telling it to go.
At a certain point of incorrect/incompleteness all of these strategies will fail just because no computer ( or even person for that matter ) is able to discern what you mean unless you at least vaguely say it correctly.
Eclipse contains just that: a compiler that can cope with incomplete java code (basically, that was one reason for these guys to implement an own java-compiler. (See here for better explanation)
There are several tutorials that explain the ASTParser, here is one.
If you just want basic parsing - an undecorated AST - you can use existing Java parsers. But from your question I understand you're interested in deeper inspection of the partial code. First, be aware the problem you are trying to solve is far from simple, especially because partial code introduces a lot of ambiguities.
But there is an existing solution - I needed to solve a similar problem, and found that a nice fellow called Barthélémy Dagenais has worked on it, producing a paper and a pair of open-source tools - one based on Soot and the other (which is generally preferable) on Eclipse. I have used both and they work, though they have their own limitations - don't expect miracles.
Here's a direct link to a quick tutorial on how to start with the Eclipse-based tool.
I needed to solve a similar problem in my recent work. I have tried many tools, including Eclipse JDT ASTParser, python javalang and PPA. I'd like to share my experience. To sum up, they all can parse code fragment to some extent, but all failed to parse occasionally when the code fragment is too ambiguous.
Eclipse JDT ASTParser
Eclipse JDT ASTParser is the most powerful and widely-used tool. This is a code snippet to parse the method invocation node.
ASTParser parser = ASTParser.newParser(AST.JLS8);
parser.setResolveBindings(true);
parser.setKind(ASTParser.K_STATEMENTS);
parser.setBindingsRecovery(true);
Map options = JavaCore.getOptions();
parser.setCompilerOptions(options);
parser.setUnitName("test");
String src = "System.out.println(\"test\");";
String[] sources = { };
String[] classpath = {"C:/Users/chenzhi/AppData/Local/Programs/Java/jdk1.8.0_131"};
parser.setEnvironment(classpath, sources, new String[] { }, true);
parser.setSource(src.toCharArray());
final Block block = (Block) parser.createAST(null);
block.accept(new ASTVisitor() {
public boolean visit(MethodInvocation node) {
System.out.println(node);
return false;
}
});
You should pay attention to parser.setKind(ASTParser.K_STATEMENTS), this is setting the kind of constructs to be parsed from the source. ASTParser defines four kind (K_COMPILATION_UNIT, K_CLASS_BODY_DECLARATIONS, K_EXPRESSION, K_STATEMENTS), you can see this javadoc to understand the difference between them.
javalang
javalang is a simple python library. This is a code snippet to parse the method invocation node.
src = 'System.out.println("test");'
tokens = javalang.tokenizer.tokenize(code2)
parser = javalang.parser.Parser(tokens)
try:
ast = parser.parse_expression()
if type(ast) is javalang.tree.MethodInvocation:
print(ast)
except javalang.parser.JavaSyntaxError as err:
print("wrong syntax", err)
Pay attention to ast = parser.parse_expression(), just like the parser.setKind() function in Eclipse JDT ASTParser, you should set the proper parsing function or you will get the 'javalang.parser.JavaSyntaxError' exception. You can read the source code to figure out which function you should use.
PPA
Partial Program Analysis for Java (PPA) is a static analysis framework that transforms the source code of an incomplete Java program into a typed Abstract Syntax Tree. As #Oak said, this tool came from academy.
PPA comes as a set of Eclipse plug-ins which means it need to run with Eclipse. It has provided a headless way to run without displaying the Eclipse GUI or requiring any user input, but it is too heavy.
String src = "System.out.println(\"test\");";
ASTNode node = PPAUtil.getSnippet(src, new PPAOptions(), false);
// Walk through the compilation unit.
node.accept(new ASTVisitor() {
public boolean visit(MethodInvocation node) {
System.out.println(node);
return false;
}
});
I have 2 problems:
In my ANTLR parser, I have this rewrite rule:
msg: msg_content (COMMA msg_content)* -> ^(MSG_CTS msg_content+);
In my tree grammar, how can I make use of the collected msg_content tokens? $msg_content.text is returning a null exception.
More generally, can you please provide some guide to me, as to how I can use my generated AST tree? I basically want to walk over the nodes and create Java classes for the different things for e.g.
I have this simple tree that gets printed:
(MSG (AGENTS A B) (MSG_CTS x y))
I'd like to have some Java class "Message" with fields for "Agents" containing A, B and some Content field that will hold X, Y.
I've gone through the ANTLR definitive guide, but haven't sen references on how to use the combined tokens, or even, how to navigate down the tree like I want. It's as if every ANTLR tutorial out there is about expression evaluators!
I've seen: "Interfacing AST with Java" and "Expression evaluator" from the ANTLR online manual, but I don't quite get how to apply those to my problem. If you can provide a simple example, it'd be very helpful!
Please help... Thank you!
$msg_content.text is returning a null exception
That is impossible to comment on without seeing all the involved rules and code. Can you edit your question and include a self-contained example I, or someone else, can run that reproduces the error/exception?
(MSG (AGENTS A B) (MSG_CTS x y))
I'd like to have some Java class "Message" with fields for "Agents" containing A, B and some Content field that will hold X, Y.
Have a look at this list of tutorials: https://stackoverflow.com/questions/278480/antlr-tutorials, not all are about expression evaluators. My tutorial demonstrates how to use custom Node classes in the tree walker.
Also see this Q&A that also shows how to use custom node-classes in the tree walker.
how to count all Operators and Operands in java class file? Does anyone have an idea?
Doing this kind of thing using regexes is unreliable. The syntax of Java is sufficiently complex that there are bound to be tricky corner cases that will cause your regexes to miscount.
Similarly using a bytecode analyser is liable to give you incorrect results because there isn't necessarily a one-to-one correspondence between source code operators / operands and bytecode instructions. The Java compiler may reorganize and rewrite the code in non-obvious ways.
The best way to do this sort of thing is to find a decent Java AST library, use that to parse your source code, and then traverse the AST to extract the information you need. (In this case, you need to count the operator and operand nodes.)
Forget regex (you'll never get that right without getting false positives like operators in comments etc), you're going to have to run a visitor over your code that counts operators. Now you can either use a source code parser or a byte code parser to do that.
For source code parsing I'd suggest the javaparser project. There, you'd create a custom Visitor extending VoidVisitorAdapter and overriding several relevant methods like this:
public void visit(AssignExpr n, A arg) {
// track the operator here
super.visit(n, arg); // resume visitor
}
On the byte code side, you'd probably use ASM and extend ClassAdapter to create your visitor. Both versions should work equally well. Or maybe not, as Stephen C writes (the compiler may have added or removed some operations).
You could try to analyze the bytecode of your class using a library like bcel.
Or use the sourceforge project lachesis (I haven't tried it):
Lachesis Analysis is a Software Complexity Measurement program for Object-Oriented source code. Analysis for Java source code and Java byte-code only is currently available.
Suppose I want to add minor syntactic sugars to Java. Just little things like adding regex pattern literals, or perhaps base-2 literals, or multiline strings, etc. Nothing major grammatically (at least for now).
How would one go about doing this?
Do I need to extend the bytecode compiler? (Is that possible?)
Can I write Eclipse plugins to do simple source code transforms before feeding it to the standard Java compiler?
I would take a look at Project Lombok and try to reuse the attempt they take. They use Java 5 annotations to hook in a Java agent which can manipulate the abstract syntax tree before the code is compiled. They are currently working on creating an API to allow custom transformers to be written which can be used with javac, or the major IDEs such as Eclipse and NetBeans. As well as annotations which trigger code to be generated, they are also planning on adding syntax changes (possibly mixin or pre-Java 7 closure syntax).
(I may have some of the details slightly off, but I think I'm pretty close).
Lombok is open source so studying their code and trying to build on that would probably be a good start.
Failing that, you could attempt to change the javac compiler. Though from what I've heard that's likely to be a hair-pulling exercise in frustration for anyone who is not a compiler and Java expert.
You can hack javac with JSR 269 (pluggable annotation processing) notably. You can hook into the visitor that traverse the statements in the source code and transform it.
Here is for instance the core of a transformation to add support for roman number in java (read of course the complete post for more details). It seems relatively easy.
public class Transform extends TreeTranslator {
#Override
public void visitIdent(JCIdent tree) {
String name = tree.getName().toString();
if (isRoman(name)) {
result = make.Literal(numberize(name));
result.pos = tree.pos;
} else {
super.visitIdent(tree);
}
}
}
Here are additional resources:
Hacker's guide to the java compiler
Javac hacker resources
I don't know if project Lombok (cited in the other answer) uses the same technique, but I guess yes.
Charles Nutter, the tech lead of JRuby, extended Javac with literal regular expressions. He had to change about 3 lines of case, as far I recall.
See http://twitter.com/headius/status/1319031705
And here is an awesome tutorial on how to add a new operator to javac, http://www.ahristov.com/tutorial/java-compiler.html
For more links like that, see my list of Links for javac hackers .
Charles Nutter, the tech lead of JRuby, extended Javac with literal regular expressions. He had to change about 3 lines of case, as far I recall.
See http://twitter.com/headius/status/1319031705