0

Suppose I have the following code

class A{
  public void f(int i, int j){
    // line
  }
}

what I want to do is to

  1. parse the code using JDT parser;
  2. take an input string, e.g. i + j, from somewhere, parse the string using JDT parser and get an AST of type Expression; and
  3. resolve the type of that Expression AST and get it's type int.

1 and 2 seem easy enough. But I couldn't figure out how 3 can be done in JDT. Has anyone any idea?

Thanks.

MYP
  • 195
  • 2
  • 10
  • I meant to parse the string in the scope of method `f`, so that both `i` and `j` are defined. – MYP May 20 '16 at 13:20

1 Answers1

0

You will have to work with bindings (link is deprecated but information still valid).

Note: how binding resolving is activated - an answer I gave.


With bindings available you can I do the following:

Expression expr = ...;
ITypeBinding binding = expr.resolveTypeBinding();
// binding is e.g. 'int' for 'i + j';

Note: to have valid Java code you must insert a statement and not an expression. So an naive approach could be:

  1. add expression as statement e.g. Object $expr = i + j;

  2. save type-binding binding = expr.resolveTypeBinding() // e.g. ITypeBinding 'int';

  3. replace Object $expr placeholder with type according to binding - going from binding back to ASTNode (most likely PrimitiveType) must be done manually.

If you need a simple code sample, just ask.

Community
  • 1
  • 1
Cwt
  • 8,206
  • 3
  • 32
  • 27
  • Thank you for the suggestion, it should work. The challenge in my questions is that the expressions whose types i want to resolve are built at runtime. It's possible to construct a new java file with all the new expressions inserted to the method and then parse the file and resolve the types, but it seems rather cumbersome to me. I'm wondering if there is a way to specify a parsing context (e.g. including the local variables, arguments, surrounding classes) and parse just expressions or statements within that context. – MYP Jun 08 '16 at 01:07