views:

191

answers:

2

Using Eclipse jdt facilities, you can traverse the AST of java code snippets as follows:

ASTParser ASTparser = ASTParser.newParser(AST.JLS3);
ASTparser.setSource("package x;class X{}".toCharArray());
ASTparser.createAST(null).accept(...);

But when trying to perform code complete & code selection it seems that I have to do it in a plug-in application since I have to write codes like

IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(somePath));
ICodeAssist i  = JavaCore.createCompilationUnitFrom(f);
i.codeComplete/codeSelect(...)

Is there anyway that I can finally get a stand-alone java application which incorporates the jdt code complete/select facilities?

thx a lot! shi kui

A: 

I don't think so, unless you provide your own implementation of ICodeAssist.

As the Performing code assist on Java code mentions, Elements that allow this manipulation should implement ICodeAssist.

There are two kinds of manipulation:

  • Code completion - compute the completion of a Java token.
  • Code selection - answer the Java element indicated by the selected text of a given offset and length.

In the Java model there are two elements that implement this interface: IClassFile and ICompilationUnit.
Code completion and code selection only answer results for a class file if it has attached source.

You could try opening a File outside of any workspace (like this FAQ), but the result wouldn't implement ICodeAssist.

So the IFile most of the time comes from a workspace location.

VonC
I see. Thanks for your information
shi kui
A: 

I have noticed it that using org.eclipse.jdt.internal.codeassist.complete.CompletionParser I can parse a code snippet as well.

CompletionParser parser =new CompletionParser(new ProblemReporter(
        DefaultErrorHandlingPolicies.proceedWithAllProblems(),
        new CompilerOptions(null),
        new DefaultProblemFactory(Locale.getDefault())),
        false);
org.eclipse.jdt.internal.compiler.batch.CompilationUnit sourceUnit =
new org.eclipse.jdt.internal.compiler.batch.CompilationUnit(
    "class T{f(){new T().=1;}  \nint j;}".toCharArray(), "testName", null);
CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);
CompilationUnitDeclaration unit = parser.dietParse(sourceUnit, compilationResult, 25);

But I have 2 questions: 1. How to retrive the assist information? 2. How can I specify class path or source path for the compiler to look up type/method/field information?

shi kui