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
Related
I took an example from the RavenDB documentation, and adapted it to fit the types I am working with in my code. The type I am using is known (it can be resolved), and the query targets a predefined index. The query uses the spatial option, if that has any part to play in this.
In Eclipse, no matter what type I use for T in this: CloseableIterator<StreamResult<T>> - the error message is always "The type StreamResult is not generic; it cannot be parameterised with arguments <whatever>".
As I'm still quite new to RavenDB, this may well be something obvious that I'm missing.
The type I am working with is a POJO, and consists exclusively of Strings, int and floats.
If you require more info on the index or the type, please let me know.
Thanks !
Pay close attention to your imports ! In my case, it was a simple case of adding the wrong import - because I clicked too fast without verifying that it was the correct library (Eclipse suggested something and I just accepted). It should have been the second option:
net.ravendb.abstractions.data.StreamResult
and NOT
javax.xml.transform.stream.StreamResult
which was first in the list of suggested fixes.
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.
In JAVA(and in every programming language ever invented), we can not use numbers as variables.
So, I was wondering how the 'Java language' developers achieved this. As I see, the only way to achieve this is that somewhere it is declared that a variable name can not be solely numbers.
Can we see the code where it is done so? Or, are the numbers like 1,2,3.. declared as 'static final' somewhere in the basic functionality of java programming language?
I know I risk myself sound stupid by asking this question. But, please let me know your thoughts about this.
This is enforced by the compiler.
As part of lexical analysis and parsing of the source code, if an something that should be an identifier is composed of digits only, it will get rejected and the compiler will issue a warning.
You will need the compiler source code in order to see how this is done. You can get it one compiler from the OpenJDK project, here (thanks to the answer from Brian Agnew).
Note that the compiler source code is available as part of the OpenJDK project, and can be downloaded via this page.
To add to #Oded's great answer, here's the C's grammar (which is not that different from Java, in the relevant respects). Variable names need to be an identifier, while an integer has to be an integer_constant. Note how an identifier cannot start with a digit, while an integer_constant has to.
I need to change the signature of a method used all over the codebase.
Specifically, the method void log(String) will take two additional arguments (Class c, String methodName), which need to be provided by the caller, depending on the method where it is called. I can't simply pass null or similar.
To give an idea of the scope, Eclipse found 7000 references to that method, so if I change it the whole project will go down. It will take weeks for me to fix it manually.
As far as I can tell Eclipse's refactoring plugin of Eclipse is not up to the task, but I really want to automate it.
So, how can I get the job done?
Great, I can copy a previous answer of mine and I just need to edit a tiny little bit:
I think what you need to do is use a source code parser like javaparser to do this.
For every java source file, parse it to a CompilationUnit, create a Visitor, probably using ModifierVisitor as base class, and override (at least) visit(MethodCallExpr, arg). Then write the changed CompilationUnit to a new File and do a diff afterwards.
I would advise against changing the original source file, but creating a shadow file tree may me a good idea (e.g. old file: src/main/java/com/mycompany/MyClass.java, new file src/main/refactored/com/mycompany/MyClass.java, that way you can diff the entire directories).
Eclipse is able to do that using Refactor -> Change Method signature and provide default values for the new parameters.
For the class parameter the defaultValue should be this.getClass() but you are right in your comment I don't know how to do for the method name parameter.
IntelliJ IDEA shouldn't have any trouble with this.
I'm not a Java expert, but something like this could work. It's not a perfect solution (it may even be a very bad solution), but it could get you started:
Change the method signature with IntelliJ's refactoring tools, and specify default values for the 2 new parameters:
c: self.getClass()
methodName: Thread.currentThread().getStackTrace()[1].getMethodName()
or better yet, simply specify null as the default values.
I think that there are several steps to dealing with this, as it is not just a technical issue but a 'situation':
Decline to do it in short order due to the risk.
Point out the issues caused by not using standard frameworks but reinventing the wheel (as Paul says).
Insist on using Log4j or equivalent if making the change.
Use Eclipse refactoring in sensible chunks to make the changes and deal with the varying defaults.
I have used Eclipse refactoring on quite large changes for fixing old smelly code - nowadays it is fairly robust.
Maybe I'm being naive, but why can't you just overload the method name?
void thing(paramA) {
thing(paramA, THE_DEFAULT_B, THE_DEFAULT_C)
}
void thing(paramA, paramB, paramC) {
// new method
}
Do you really need to change the calling code and the method signature? What I'm getting at is it looks like the added parameters are meant to give you the calling class and method to add to your log data. If the only requirement is just adding the calling class/method to the log data then Thread.currentThread().getStackTrace() should work. Once you have the StackTraceElement[] you can get the class name and method name for the caller.
If the lines you need replaced fall into a small number of categories, then what you need is Perl:
find -name '*.java' | xargs perl -pi -e 's/log\(([^,)]*?)\)/log(\1, "foo", "bar")/g'
I'm guessing that it wouldn't be too hard to hack together a script which would put the classname (derived from the filename) in as the second argument. Getting the method name in as the third argument is left as an exercise to the reader.
Try refactor using intellij. It has a feature called SSR (Structural Search and Replace). You can refer classes, method names, etc for a context. (seanizer's answer is more promising, I upvoted it)
I agree with Seanizer's answer that you want a tool that can parse Java. That's necessary but not sufficient; what you really want is a tool that can carry out a reliable mass-change.
To do this, you want a tool that can parse Java, can pattern match against the parsed code, install the replacement call, and spit out the answer without destroying the rest of the source code.
Our DMS Software Reengineering Toolkit can do all of this for a variety of languages, including Java. It parses complete java systems of source, builds abstract syntax trees (for the entire set of code).
DMS can apply pattern-directed, source-to-source transformations to achieve the desired change.
To achieve the OP's effect, he would apply the following program transformation:
rule replace_legacy_log(s:STRING): expression -> expression
" log(\s) " -> " log( \s, \class\(\), \method\(\) ) "
What this rule says is, find a call to log which has a single string argument, and replace it with a call to log with two more arguments determined by auxiliary functions class and method.
These functions determine the containing method name and containing class name for the AST node root where the rule finds a match.
The rule is written in "source form", but actually matches against the AST and replaces found ASTs with the modified AST.
To get back the modified source, you ask DMS to simply prettyprint (to make a nice layout) or fidelity print (if you want the layout of the old code preserved). DMS preserves comments, number radixes, etc.\
If the exisitng application has more than one defintion of the "log" function, you'll need to add a qualifier:
... if IsDesiredLog().
where IsDesiredLog uses DMS's symbol table and inheritance information to determine if the specific log refers to the definition of interest.
Il fact your problem is not to use a click'n'play engine that will allow you to replace all occurences of
log("some weird message");
by
log(this.getClass(), new Exception().getStackTrace()[1].getMethodName());
As it has few chances to work on various cases (like static methods, as an example).
I would tend to suggest you to take a look at spoon. This tool allows source code parsing and transformation, allowing you to achieve your operation in a -obviously code based- slow, but controlled operation.
However, you could alos consider transforming your actual method with one exploring stack trace to get information or, even better, internally use log4j and a log formatter that displays the correct information.
I would search and replace log( with log(#class, #methodname,
Then write a little script in any language (even java) to find the class name and the method names and to replace the #class and #method tokens...
Good luck
If the class and method name are required for "where did this log come from?" type data, then another option is to print out a stack trace in your log method. E.g.
public void log(String text)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw, true);
new Throwable.printStackTrace(pw);
pw.flush();
sw.flush();
String stackTraceAsLog = sw.toString();
//do something with text and stackTraceAsLog
}