c2nes / javalang

Pure Python Java parser and tools
MIT License
737 stars 161 forks source link

Array argument #52

Open dfagneray opened 6 years ago

dfagneray commented 6 years ago

I'm currently using the Java parser Javalang because I need to iterate through an AST from a java source code, but I need to do it from a python file.

It appears to be quite useful but I have a problem when parsing arguments in a method signature. For exemple in a classic

public void main(String[] args){}

The String[] args is being parsed as a FormalParameter, who's a subclass of Declaration, itself a subclass of Node. In this particular exemple, the type field of FormalParamter will be ReferenceType, that got 4 fields: name,declarations,arguments,sub_type. The name field return only String, and the sub_type returns None. There is no indication of "args" being an array. How can i get that back ?

c2nes commented 6 years ago

This is indicated by the dimensions field of ReferenceType (inherited from Type). Here's an example,

import javalang

ast = javalang.parse.parse_member_signature('public static void main(String args) {}')
print ast.parameters[0].type.dimensions # []

ast = javalang.parse.parse_member_signature('public static void main(String[] args) {}')
print ast.parameters[0].type.dimensions # [None]

ast = javalang.parse.parse_member_signature('public static void main(String[][] args) {}')
print ast.parameters[0].type.dimensions # [None, None]
dfagneray commented 6 years ago

Oh, thanks a lot, I didn't understand what dimensions was !