Build AST Model Using Spoon when input project files are located in memory and not saved as files in disk

483 views Asked by At

I am working with Spoon Inria to parse and analyze Java applications. Currently, I am using the below code to create input project model. This code works when project files are saved in the disk.

Launcher spoonAPI = new Launcher();
spoonAPI.addInputResource(projectDirectory);  //The path to the project root directory
spoonAPI.buildModel();
CtModel ctModel = spoonAPI.getModel();

However, currently I have contents of Java files (classes) in the memory and I do not want to write them in the disk as it takes ages. I was wondering if there is a way using Spoon that I can pass file contents to the parser. For example, a code as below.

//Key is name of class and value is its content
Map<String, String> JavafileContents= new HashMap<String, String>();

for (String filePath : JavafileContents.keySet()) {
  spoonAPI.parse(JavafileContents.get(filePath ));
}
CtModel ctModel = spoonAPI.getModel(); //The extracted model should contains all parsed files.

Like a similar solution provided in JDT.

ASTParser parser = ASTParser.newParser(AST.JLS14);
parser.setSource(javaFileContents.get(filePath).toCharArray());
CompilationUnit compilationUnit = (CompilationUnit)parser.createAST(null);
1

There are 1 answers

4
Yu Wang On

I'm also looking for the functionality, I found the following code may meet your requirement.

    import spoon.support.compiler.VirtualFile;
    ...
    public static CtClass<?> parseClass(String code) {
       Launcher launcher = new Launcher();
       launcher.addInputResource(new VirtualFile(code));
       launcher.getEnvironment().setNoClasspath(true);
       launcher.getEnvironment().setAutoImports(true);
    ...

The source is https://github.com/INRIA/spoon/blob/spoon-core-8.2.0/src/main/java/spoon/Launcher.java#L856.

Alternatively, one can use APIs like createCodeSnippetStatement

Factory factory = new Launcher().createFactory();
CtStatement tmpStmt = factory.Code().createCodeSnippetStatement(code);

The way of choosing an API depends on the type of your code snippet (e.g., expression or statement).