javalang icon indicating copy to clipboard operation
javalang copied to clipboard

how to parse java code snippet to AST?

Open wanyao1992 opened this issue 7 years ago • 2 comments

Dear authors,

Thanks for sharing your code. This package is easy to use, while I still encounter some problems. I want to parse some java code snippet, for example some java functions. Could you tell me how can parse the java snippet to AST?

here is my code:

import javalang tokens = javalang.tokenizer.tokenize('public String toString ( ) { return this . getClass ( ) . getName ( ) ; } /** * @return An arbitrary string. */ public String anotherString ( ) { return "An arbitrary string." ; }') parser = javalang.parser.Parser(tokens) tree = parser.xxx() // I don't know parse_xx should be here.

I always get the 'javalang.parser.JavaSyntaxError' exception.

Any help from you will be highly appreciated.

wanyao1992 avatar Aug 14 '17 13:08 wanyao1992

I had a similar problem generating AST from a source code java snippet. What I concluded is that you cannot produce a full CompilationUnit from a snippet that won't compile itself.

In that case, the best option you have is to split your snippet in code lines and use javalang.parse.parse_expression(line) separately on each line.

Okay now this won't give you the whole structure information that the AST would give you but still you can get a bunch of information about the code you are parsing.

ConflictGK avatar Aug 21 '17 11:08 ConflictGK

There isn't a single method which will work for all snippets, but if you know what kind of snippet you have (e.g. a method declaration, expression, etc.) there is usually an appropriate parser method. For this example I would recommend parse_member_declaration().

c2nes avatar Aug 21 '17 13:08 c2nes