Skip to content

Commit

Permalink
fix: bug when getting CU from a parsed snippet (#2086)
Browse files Browse the repository at this point in the history
  • Loading branch information
surli authored and monperrus committed Jun 19, 2018
1 parent 271be11 commit 259de5c
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import spoon.reflect.declaration.CtModule;
import spoon.reflect.declaration.CtPackage;
import spoon.reflect.declaration.CtType;
import spoon.support.compiler.VirtualFile;
import spoon.support.compiler.jdt.JDTSnippetCompiler;

import java.io.File;
Expand Down Expand Up @@ -147,7 +148,11 @@ public CompilationUnit getOrCreate(String filePath) {
return cu;
}
cu = factory.Core().createCompilationUnit();
cu.setFile(new File(filePath));

if (!filePath.equals(VirtualFile.VIRTUAL_FILE_NAME)) {
cu.setFile(new File(filePath));
}

cachedCompilationUnits.put(filePath, cu);
}
return cu;
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/spoon/support/compiler/VirtualFile.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,11 @@
import java.io.InputStream;

public class VirtualFile implements SpoonFile {
public static final String VIRTUAL_FILE_NAME = "virtual_file";

String content;

String name = "virtual_file";
String name = VIRTUAL_FILE_NAME;

public VirtualFile(String content) {
this.content = content;
Expand Down
11 changes: 11 additions & 0 deletions src/test/java/spoon/test/api/APITest.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

Expand Down Expand Up @@ -566,5 +567,15 @@ public void testOutputWithNoOutputProduceNoFolder() {
assertFalse("Output dir should not exist: "+outputDir.getAbsolutePath(), outputDir.exists());
}

@Test
public void testGetOneLinerMainClassFromCU() {
// contract: when using Spoon with a snippet, we can still use properly CompilationUnit methods
CtClass<?> l = Launcher.parseClass("class A { void m() { System.out.println(\"yeah\");} }");
CompilationUnit compilationUnit = l.getPosition().getCompilationUnit();

assertNotNull(compilationUnit);
CtType<?> mainType = compilationUnit.getMainType();
assertSame(l, mainType);
}

}

0 comments on commit 259de5c

Please sign in to comment.