public static Map<Lang, Result> convertFromFiles( ClassLoader loader, List<Lang> lang, String file, String fqn, String method) throws Exception { DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); StandardJavaFileManager manager = javac.getStandardFileManager(diagnostics, locale, charset); Iterable<? extends JavaFileObject> fileObjects = manager.getJavaFileObjects(file); StringWriter out = new StringWriter(); JavaCompiler.CompilationTask task = javac.getTask( out, manager, diagnostics, Collections.<String>emptyList(), Collections.<String>emptyList(), fileObjects); task.setLocale(locale); ConvertingProcessor processor = new ConvertingProcessor(lang, fqn, method); task.setProcessors(Collections.<Processor>singletonList(processor)); if (task.call()) { return processor.getResults(); } else { StringWriter message = new StringWriter(); PrintWriter writer = new PrintWriter(message); writer.append("Compilation of ").append(file).println(" failed:"); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { writer.append(diagnostic.getMessage(locale)); } writer.println("console:"); writer.append(out.getBuffer()); throw new Exception(message.toString()); } }
@NotNull public static CompilerConfiguration compilerConfigurationForTests( @NotNull ConfigurationKind configurationKind, @NotNull TestJdkKind jdkKind, @NotNull File... extraClasspath) { return compilerConfigurationForTests( configurationKind, jdkKind, Arrays.asList(extraClasspath), Collections.<File>emptyList()); }
private static List<String> parseDependencies(@Nullable String dependencies) { if (dependencies == null) return Collections.emptyList(); Matcher matcher = Pattern.compile("\\w+").matcher(dependencies); List<String> result = new ArrayList<String>(); while (matcher.find()) { result.add(matcher.group()); } return result; }
private static ArrayReference createURLArray(EvaluationContext context) throws EvaluateException, InvocationException, InvalidTypeException, ClassNotLoadedException, IncompatibleThreadStateException { DebugProcess process = context.getDebugProcess(); ArrayType arrayType = (ArrayType) process.findClass(context, "java.net.URL[]", context.getClassLoader()); ArrayReference arrayRef = arrayType.newInstance(1); keep(arrayRef, context); ClassType classType = (ClassType) process.findClass(context, "java.net.URL", context.getClassLoader()); VirtualMachineProxyImpl proxy = (VirtualMachineProxyImpl) process.getVirtualMachineProxy(); StringReference url = proxy.mirrorOf("file:a"); keep(url, context); ObjectReference reference = process.newInstance( context, classType, classType.concreteMethodByName("<init>", "(Ljava/lang/String;)V"), Collections.singletonList(url)); keep(reference, context); arrayRef.setValues(Collections.singletonList(reference)); return arrayRef; }
public static TestRun compileAndCheck( Iterable<? extends JavaFileObject> files, String processor, String[] options) { List<String> opts = new LinkedList<String>(); if (processor != null) { opts.add("-processor"); opts.add(processor); } opts.add("-source"); opts.add("1.8"); for (String option : options) opts.add(option); TestInput input = new TestInput(files, Collections.<String>emptySet(), opts.toArray(new String[opts.size()])); return input.run(); }
public static String getLastCommentedLines(@NotNull Document document) { List<CharSequence> resultLines = new ArrayList<CharSequence>(); for (int i = document.getLineCount() - 1; i >= 0; i--) { int lineStart = document.getLineStartOffset(i); int lineEnd = document.getLineEndOffset(i); if (document.getCharsSequence().subSequence(lineStart, lineEnd).toString().trim().isEmpty()) { continue; } if ("//" .equals(document.getCharsSequence().subSequence(lineStart, lineStart + 2).toString())) { resultLines.add(document.getCharsSequence().subSequence(lineStart + 2, lineEnd)); } else { break; } } Collections.reverse(resultLines); StringBuilder result = new StringBuilder(); for (CharSequence line : resultLines) { result.append(line).append("\n"); } result.delete(result.length() - 1, result.length()); return result.toString(); }
public static boolean compile( Collection<String> options, final Collection<File> sources, Collection<File> classpath, Collection<File> platformClasspath, Collection<File> sourcePath, Map<File, Set<File>> outputDirToRoots, final DiagnosticOutputConsumer outConsumer, final OutputFileConsumer outputSink, CanceledStatus canceledStatus, boolean useEclipseCompiler) { JavaCompiler compiler = null; if (useEclipseCompiler) { for (JavaCompiler javaCompiler : ServiceLoader.load(JavaCompiler.class)) { compiler = javaCompiler; break; } if (compiler == null) { outConsumer.report( new PlainMessageDiagnostic( Diagnostic.Kind.ERROR, "Eclipse Batch Compiler was not found in classpath")); return false; } } final boolean nowUsingJavac; if (compiler == null) { compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { outConsumer.report( new PlainMessageDiagnostic( Diagnostic.Kind.ERROR, "System Java Compiler was not found in classpath")); return false; } nowUsingJavac = true; } else { nowUsingJavac = false; } for (File outputDir : outputDirToRoots.keySet()) { outputDir.mkdirs(); } final List<JavaSourceTransformer> transformers = getSourceTransformers(); final JavacFileManager fileManager = new JavacFileManager( new ContextImpl(compiler, outConsumer, outputSink, canceledStatus, nowUsingJavac), transformers); fileManager.handleOption( "-bootclasspath", Collections.singleton("").iterator()); // this will clear cached stuff fileManager.handleOption( "-extdirs", Collections.singleton("").iterator()); // this will clear cached stuff try { fileManager.setOutputDirectories(outputDirToRoots); } catch (IOException e) { fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage()); return false; } if (!classpath.isEmpty()) { try { fileManager.setLocation(StandardLocation.CLASS_PATH, classpath); if (!nowUsingJavac && !isOptionSet(options, "-processorpath")) { // for non-javac file manager ensure annotation processor path defaults to classpath fileManager.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH, classpath); } } catch (IOException e) { fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage()); return false; } } if (!platformClasspath.isEmpty()) { try { fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, platformClasspath); } catch (IOException e) { fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage()); return false; } } try { // ensure the source path is set; // otherwise, if not set, javac attempts to search both classes and sources in classpath; // so if some classpath jars contain sources, it will attempt to compile them fileManager.setLocation(StandardLocation.SOURCE_PATH, sourcePath); } catch (IOException e) { fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage()); return false; } //noinspection IOResourceOpenedButNotSafelyClosed final LineOutputWriter out = new LineOutputWriter() { protected void lineAvailable(String line) { if (nowUsingJavac) { outConsumer.outputLineAvailable(line); } else { // todo: filter too verbose eclipse output? } } }; try { final Collection<String> _options = prepareOptions(options, nowUsingJavac); // to be on the safe side, we'll have to apply all options _before_ calling any of manager's // methods // i.e. getJavaFileObjectsFromFiles() // This way the manager will be properly initialized. Namely, the encoding will be set // correctly for (Iterator<String> iterator = _options.iterator(); iterator.hasNext(); ) { fileManager.handleOption(iterator.next(), iterator); } final JavaCompiler.CompilationTask task = compiler.getTask( out, fileManager, outConsumer, _options, null, fileManager.getJavaFileObjectsFromFiles(sources)); // if (!IS_VM_6_VERSION) { //todo! // // Do not add the processor for JDK 1.6 because of the bugs in javac // // The processor's presence may lead to NPE and resolve bugs in compiler // final JavacASTAnalyser analyzer = new JavacASTAnalyser(outConsumer, // !annotationProcessingEnabled); // task.setProcessors(Collections.singleton(analyzer)); // } return task.call(); } catch (IllegalArgumentException e) { outConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, e.getMessage())); } catch (CompilationCanceledException ignored) { outConsumer.report( new PlainMessageDiagnostic(Diagnostic.Kind.OTHER, "Compilation was canceled")); } finally { fileManager.close(); if (nowUsingJavac) { cleanupJavacNameTable(); } } return false; }
@Override public Set<String> getSupportedAnnotationTypes() { return Collections.singleton(CodeTranslate.class.getName()); }
@NotNull @Override public <K, V> Collection<K> getKeys(WritableSlice<K, V> slice) { assert slice.isCollective(); return Collections.emptySet(); }