Как я могу использовать абстрактное синтаксическое дерево java Eclipse в проекте вне Eclipse? (т.е. не плагин eclipse)

Как я могу использовать абстрактное синтаксическое дерево java Eclipse в проекте вне Eclipse? (т.е. не плагин eclipse)

Все примеры Eclipse AST, которые я видел, относятся к подключаемым модулям Eclipse. Есть ли способ (т.е. пример) проекта, использующего eclipse AST для проекта без затмения.


person hawkeye    schedule 08.06.2009    source источник


Ответы (2)


Ниже приведен код, который я использовал для этого с файлом Java 1.5. Я очень новичок в этом и провел сегодняшний день, просматривая и пытаясь заставить код ниже работать.

public void processJavaFile(File file) {
    String source = FileUtils.readFileToString(file);
    Document document = new Document(source);
    ASTParser parser = ASTParser.newParser(AST.JLS3);
    parser.setSource(document.get().toCharArray());
    CompilationUnit unit = (CompilationUnit)parser.createAST(null);
    unit.recordModifications();

    // to get the imports from the file
    List<ImportDeclaration> imports = unit.imports();
    for (ImportDeclaration i : imports) {
        System.out.println(i.getName().getFullyQualifiedName());
    }

    // to create a new import
    AST ast = unit.getAST();
    ImportDeclaration id = ast.newImportDeclaration();
    String classToImport = "path.to.some.class";
    id.setName(ast.newName(classToImport.split("\\.")));
    unit.imports().add(id); // add import declaration at end

    // to save the changed file
    TextEdit edits = unit.rewrite(document, null);
    edits.apply(document);
    FileUtils.writeStringToFile(file, document.get());

    // to iterate through methods
    List<AbstractTypeDeclaration> types = unit.types();
    for (AbstractTypeDeclaration type : types) {
        if (type.getNodeType() == ASTNode.TYPE_DECLARATION) {
            // Class def found
            List<BodyDeclaration> bodies = type.bodyDeclarations();
            for (BodyDeclaration body : bodies) {
                if (body.getNodeType() == ASTNode.METHOD_DECLARATION) {
                    MethodDeclaration method = (MethodDeclaration)body;
                    System.out.println("name: " + method.getName().getFullyQualifiedName());
                }
            }
        }
    }
}

Для этого требуются следующие библиотеки:

commons-io-1.4.jar
org.eclipse.jdt.core_xxxx.jar
org.eclipse.core.resources_xxxx.jar
org.eclipse.core.jobs_xxxx.jar
org.eclipse.core.runtime_xxxx.jar
org.eclipse.core.contenttype_xxxx.jar
org.eclipse.equinox.common_xxxx.jar
org.eclipse.equinox.preferences_xxxx.jar
org.eclipse.osgi_xxxx.jar
org.eclipse.text_xxxx.jar
person kfox    schedule 13.01.2011
comment
вы круты - я продублировал это и поместил на github здесь: github.com/juliangamble/ASTTest - person hawkeye; 15.01.2011
comment
как я могу получить необходимые банки, кроме commons-io? - person Oeufcoque Penteano; 10.08.2012
comment
Найден в папке плагинов eclipse, как предложено в stackoverflow.com/questions/93728/ - person Oeufcoque Penteano; 10.08.2012

Согласно этой старой статье, вы должны иметь возможность вызывать AST анализатор независимо от контекста вашего приложения (плагин eclipse или нет).

ASTParser parser = ASTParser.newParser(AST.JLS2);
parser.setSource("".toCharArray());
CompilationUnit unit = (CompilationUnit) parser.createAST(null); 
unit.recordModifications();
AST ast = unit.getAST(); 

alt text
(источник: ibm.com)


Из этой записи об ошибке:

ASTParser версии 3.0 можно использовать в другой автономной программе для создания AST Eclipse без фактического запуска Eclipse. Как говорится в документации:

  char[] source = ...;
  ASTParser parser = ASTParser.newParser(AST.JLS2);  // handles JLS2 (J2SE 1.4)
  parser.setSource(source);
  CompilationUnit result = (CompilationUnit) parser.createAST(null);

Следовательно, эта ветка пытается проанализировать очень короткий исходный код Java:

import org.eclipse.jdt.core.dom.*;
import org.eclipse.jface.text.Document;
import org.eclipse.text.edits.TextEdit;

public class Test{

public static void main(String[] args){
 Test t= new Test();
 t.runtest();
}

 void runtest(){
  Document doc = new Document("import java.util.List;\nclass X {}\n");
  ASTParser parser = ASTParser.newParser(AST.JLS3);
  parser.setResolveBindings(true);
  parser.setSource(doc.get().toCharArray());
  CompilationUnit cu = (CompilationUnit) parser.createAST(null);
  cu.recordModifications();
  AST ast = cu.getAST();
  ImportDeclaration id = ast.newImportDeclaration();
  id.setName(ast.newName(new String[] {"java", "util", "Set"}));
  cu.imports().add(id); // add import declaration at end
  TextEdit edits = cu.rewrite(doc, null);
 }

}
person VonC    schedule 08.06.2009