use of javax.tools.DiagnosticCollector in project error-prone by google.
the class CodeTransformerTestHelper method transform.
public JavaFileObject transform(JavaFileObject original) {
JavaCompiler compiler = JavacTool.create();
DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH, UTF_8);
JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(), fileManager, diagnosticsCollector, ImmutableList.<String>of(), null, ImmutableList.of(original));
try {
SourceFile sourceFile = SourceFile.create(original);
Iterable<? extends CompilationUnitTree> trees = task.parse();
task.analyze();
JCCompilationUnit tree = Iterables.getOnlyElement(Iterables.filter(trees, JCCompilationUnit.class));
DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree);
transformer().apply(new TreePath(tree), task.getContext(), diff);
diff.applyDifferences(sourceFile);
return JavaFileObjects.forSourceString(Iterables.getOnlyElement(Iterables.filter(tree.getTypeDecls(), JCClassDecl.class)).sym.getQualifiedName().toString(), sourceFile.getSourceText());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
use of javax.tools.DiagnosticCollector in project error-prone by google.
the class ErrorProneJavacPluginTest method hello.
@Test
public void hello() throws IOException {
FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
Path source = fileSystem.getPath("Test.java");
Files.write(source, ImmutableList.of("import java.util.HashSet;", "import java.util.Set;", "class Test {", " public static void main(String[] args) {", " Set<Short> s = new HashSet<>();", " for (short i = 0; i < 100; i++) {", " s.add(i);", " s.remove(i - 1);", " }", " System.out.println(s.size());", " }", "}"), UTF_8);
JavacFileManager fileManager = new JavacFileManager(new Context(), false, UTF_8);
DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<>();
JavacTask task = JavacTool.create().getTask(null, fileManager, diagnosticCollector, ImmutableList.of("-Xplugin:ErrorProne"), ImmutableList.of(), fileManager.getJavaFileObjects(source));
assertThat(task.call()).isFalse();
Diagnostic<? extends JavaFileObject> diagnostic = diagnosticCollector.getDiagnostics().stream().filter(d -> d.getKind() == Diagnostic.Kind.ERROR).collect(onlyElement());
assertThat(diagnostic.getMessage(ENGLISH)).contains("[CollectionIncompatibleType]");
}
use of javax.tools.DiagnosticCollector in project j2objc by google.
the class JavacParser method createEnvironment.
// Creates a javac environment from a collection of files and/or file objects.
private JavacEnvironment createEnvironment(List<File> files, List<JavaFileObject> fileObjects, boolean processAnnotations) throws IOException {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
JavacFileManager fileManager = getFileManager(compiler, diagnostics);
List<String> javacOptions = getJavacOptions(processAnnotations);
if (fileObjects == null) {
fileObjects = new ArrayList<>();
}
for (JavaFileObject jfo : fileManager.getJavaFileObjectsFromFiles(files)) {
fileObjects.add(jfo);
}
JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fileManager, diagnostics, javacOptions, null, fileObjects);
return new JavacEnvironment(task, fileManager, diagnostics);
}
use of javax.tools.DiagnosticCollector in project symmetric-ds by JumpMind.
the class SimpleClassCompiler method getCompiledClass.
public Object getCompiledClass(String javaCode) throws Exception {
Integer id = javaCode.hashCode();
Object javaObject = objectMap.get(id);
if (javaObject == null) {
String className = getNextClassName();
String origClassName = null;
Pattern pattern = Pattern.compile(REGEX_CLASS);
Matcher matcher = pattern.matcher(javaCode);
if (matcher.find()) {
origClassName = matcher.group(1);
}
javaCode = javaCode.replaceAll(REGEX_CLASS, "public class " + className);
log.info("Compiling class '" + origClassName + "'");
if (log.isDebugEnabled()) {
log.debug("Compiling code: \n" + javaCode);
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new SimpleClassCompilerException("Missing Java compiler: the JDK is required for compiling classes.");
}
JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
DiagnosticCollector<JavaFileObject> diag = new DiagnosticCollector<JavaFileObject>();
List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>();
javaFiles.add(new JavaObjectFromString(className, javaCode));
Boolean success = compiler.getTask(null, fileManager, diag, null, null, javaFiles).call();
if (success) {
log.debug("Compilation has succeeded");
Class<?> clazz = fileManager.getClassLoader(null).loadClass(className);
if (clazz != null) {
javaObject = clazz.newInstance();
objectMap.put(id, javaObject);
} else {
throw new SimpleClassCompilerException("The '" + className + "' class could not be located");
}
} else {
log.error("Compilation of '" + origClassName + "' failed");
for (Diagnostic diagnostic : diag.getDiagnostics()) {
log.error(origClassName + " at line " + diagnostic.getLineNumber() + ", column " + diagnostic.getColumnNumber() + ": " + diagnostic.getMessage(null));
}
throw new SimpleClassCompilerException(diag.getDiagnostics());
}
}
return javaObject;
}
use of javax.tools.DiagnosticCollector in project incubator-systemml by apache.
the class CodegenUtils method compileClassJavac.
////////////////////////////
//JAVAC-specific methods (used for hadoop environments)
private static Class<?> compileClassJavac(String name, String src) throws DMLRuntimeException {
try {
//create working dir on demand
if (_workingDir == null)
createWorkingDir();
//write input file (for debugging / classpath handling)
File ftmp = new File(_workingDir + "/" + name.replace(".", "/") + ".java");
if (!ftmp.getParentFile().exists())
ftmp.getParentFile().mkdirs();
LocalFileUtils.writeTextFile(ftmp, src);
//get system java compiler
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null)
throw new RuntimeException("Unable to obtain system java compiler.");
//prepare file manager
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
//prepare input source code
Iterable<? extends JavaFileObject> sources = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(ftmp));
//prepare class path
URL runDir = CodegenUtils.class.getProtectionDomain().getCodeSource().getLocation();
String classpath = System.getProperty("java.class.path") + File.pathSeparator + runDir.getPath();
List<String> options = Arrays.asList("-classpath", classpath);
//compile source code
CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, sources);
Boolean success = task.call();
//output diagnostics and error handling
for (Diagnostic<? extends JavaFileObject> tmp : diagnostics.getDiagnostics()) if (tmp.getKind() == Kind.ERROR)
System.err.println("ERROR: " + tmp.toString());
if (success == null || !success)
throw new RuntimeException("Failed to compile class " + name);
//dynamically load compiled class
URLClassLoader classLoader = null;
try {
classLoader = new URLClassLoader(new URL[] { new File(_workingDir).toURI().toURL(), runDir }, CodegenUtils.class.getClassLoader());
return classLoader.loadClass(name);
} finally {
IOUtilFunctions.closeSilently(classLoader);
}
} catch (Exception ex) {
throw new DMLRuntimeException(ex);
}
}
Aggregations