Search in sources :

Example 1 with JavacCompilerTool

use of org.jetbrains.jps.builders.impl.java.JavacCompilerTool in project intellij-community by JetBrains.

the class CompilerManagerImpl method compileJavaCode.

@Override
public Collection<ClassObject> compileJavaCode(List<String> options, Collection<File> platformCp, Collection<File> classpath, Collection<File> modulePath, Collection<File> sourcePath, Collection<File> files, File outputDir) throws IOException, CompilationException {
    final Pair<Sdk, JavaSdkVersion> runtime = BuildManager.getJavacRuntimeSdk(myProject);
    final Sdk sdk = runtime.getFirst();
    final SdkTypeId type = sdk.getSdkType();
    String javaHome = null;
    if (type instanceof JavaSdkType) {
        javaHome = sdk.getHomePath();
        if (!isJdkOrJre(javaHome)) {
            // this can be a java-dependent SDK, implementing JavaSdkType
            // hack, because there is no direct way to obtain the java sdk, this sdk depends on
            final String binPath = ((JavaSdkType) type).getBinPath(sdk);
            javaHome = binPath != null ? new File(binPath).getParent() : null;
            if (!isJdkOrJre(javaHome)) {
                javaHome = null;
            }
        }
    }
    if (javaHome == null) {
        throw new IOException("Was not able to determine JDK for project " + myProject.getName());
    }
    final OutputCollector outputCollector = new OutputCollector();
    DiagnosticCollector diagnostic = new DiagnosticCollector();
    final Set<File> sourceRoots = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY);
    if (!sourcePath.isEmpty()) {
        for (File file : sourcePath) {
            sourceRoots.add(file);
        }
    } else {
        for (File file : files) {
            final File parentFile = file.getParentFile();
            if (parentFile != null) {
                sourceRoots.add(parentFile);
            }
        }
    }
    final Map<File, Set<File>> outs = Collections.singletonMap(outputDir, sourceRoots);
    final ExternalJavacManager javacManager = getJavacManager();
    boolean compiledOk = javacManager != null && javacManager.forkJavac(javaHome, -1, Collections.emptyList(), options, platformCp, classpath, modulePath, sourcePath, files, outs, diagnostic, outputCollector, new JavacCompilerTool(), CanceledStatus.NULL);
    if (!compiledOk) {
        final List<CompilationException.Message> messages = new SmartList<>();
        for (Diagnostic<? extends JavaFileObject> d : diagnostic.getDiagnostics()) {
            final JavaFileObject source = d.getSource();
            final URI uri = source != null ? source.toUri() : null;
            messages.add(new CompilationException.Message(kindToCategory(d.getKind()), d.getMessage(Locale.US), uri != null ? uri.toURL().toString() : null, (int) d.getLineNumber(), (int) d.getColumnNumber()));
        }
        throw new CompilationException("Compilation failed", messages);
    }
    final List<ClassObject> result = new ArrayList<>();
    for (OutputFileObject fileObject : outputCollector.getCompiledClasses()) {
        final BinaryContent content = fileObject.getContent();
        result.add(new CompiledClass(fileObject.getName(), fileObject.getClassName(), content != null ? content.toByteArray() : null));
    }
    return result;
}
Also used : JavacCompilerTool(org.jetbrains.jps.builders.impl.java.JavacCompilerTool) THashSet(gnu.trove.THashSet) BinaryContent(org.jetbrains.jps.incremental.BinaryContent) URI(java.net.URI) JavaFileObject(javax.tools.JavaFileObject) OutputFileObject(org.jetbrains.jps.javac.OutputFileObject) IOException(java.io.IOException) THashSet(gnu.trove.THashSet) ExternalJavacManager(org.jetbrains.jps.javac.ExternalJavacManager) SmartList(com.intellij.util.SmartList) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File)

Example 2 with JavacCompilerTool

use of org.jetbrains.jps.builders.impl.java.JavacCompilerTool in project intellij-community by JetBrains.

the class JavacMain method compile.

public static boolean compile(Collection<String> options, final Collection<File> sources, Collection<File> classpath, Collection<File> platformClasspath, Collection<File> modulePath, Collection<File> sourcePath, Map<File, Set<File>> outputDirToRoots, final DiagnosticOutputConsumer diagnosticConsumer, final OutputFileConsumer outputSink, CanceledStatus canceledStatus, @NotNull JavaCompilingTool compilingTool) {
    JavaCompiler compiler;
    try {
        compiler = compilingTool.createCompiler();
    } catch (CannotCreateJavaCompilerException e) {
        diagnosticConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, e.getMessage()));
        return false;
    }
    for (File outputDir : outputDirToRoots.keySet()) {
        outputDir.mkdirs();
    }
    final boolean usingJavac = compilingTool instanceof JavacCompilerTool;
    final JavacFileManager fileManager = new JavacFileManager(new ContextImpl(compiler, diagnosticConsumer, outputSink, canceledStatus, canUseOptimizedFileManager(compilingTool)), JavaSourceTransformer.getTransformers());
    if (!platformClasspath.isEmpty()) {
        // for javac6 this will prevent lazy initialization of Paths.bootClassPathRtJar 
        // and thus usage of symbol file for resolution, when this file is not expected to be used
        fileManager.handleOption("-bootclasspath", Collections.singleton("").iterator());
    }
    // this will clear cached stuff
    fileManager.handleOption("-extdirs", Collections.singleton("").iterator());
    // this will clear cached stuff
    fileManager.handleOption("-endorseddirs", Collections.singleton("").iterator());
    final Collection<String> _options = prepareOptions(options, compilingTool);
    try {
        // Note that due to lazy initialization in various components inside javac, handleOption() should be called before setLocation() and others
        for (Iterator<String> iterator = _options.iterator(); iterator.hasNext(); ) {
            fileManager.handleOption(iterator.next(), iterator);
        }
        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 (!usingJavac && !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 {
                // this will clear cached stuff
                fileManager.handleOption("-bootclasspath", Collections.singleton("").iterator());
                fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, buildPlatformClasspath(platformClasspath, _options));
            } catch (IOException e) {
                fileManager.getContext().reportMessage(Diagnostic.Kind.ERROR, e.getMessage());
                return false;
            }
        }
        if (!modulePath.isEmpty()) {
            final JavaFileManager.Location modulePathLocation = StandardLocation.locationFor("MODULE_PATH");
            if (modulePathLocation != null) {
                // if this option is supported
                try {
                    fileManager.setLocation(modulePathLocation, modulePath);
                } 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 (usingJavac) {
                    diagnosticConsumer.outputLineAvailable(line);
                } else {
                // todo: filter too verbose eclipse output?
                }
            }
        };
        final JavaCompiler.CompilationTask task = compiler.getTask(out, wrapWithCallDispatcher(fileManager), diagnosticConsumer, _options, null, fileManager.getJavaFileObjectsFromFiles(sources));
        for (JavaCompilerToolExtension extension : JavaCompilerToolExtension.getExtensions()) {
            try {
                extension.beforeCompileTaskExecution(compilingTool, task, _options, diagnosticConsumer);
            } catch (Throwable e) {
                fileManager.getContext().reportMessage(Diagnostic.Kind.MANDATORY_WARNING, extension.getClass() + " : " + e.getMessage());
                e.printStackTrace(System.err);
            }
        }
        //}
        return task.call();
    } catch (IllegalArgumentException e) {
        diagnosticConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, e.getMessage()));
    } catch (CompilationCanceledException ignored) {
        handleCancelException(diagnosticConsumer);
    } catch (RuntimeException e) {
        final Throwable cause = e.getCause();
        if (cause instanceof CompilationCanceledException) {
            handleCancelException(diagnosticConsumer);
        } else {
            throw e;
        }
    } finally {
        fileManager.close();
        if (usingJavac) {
            cleanupJavacNameTable();
        }
    }
    return false;
}
Also used : JavacCompilerTool(org.jetbrains.jps.builders.impl.java.JavacCompilerTool) IOException(java.io.IOException) LineOutputWriter(org.jetbrains.jps.incremental.LineOutputWriter) CannotCreateJavaCompilerException(org.jetbrains.jps.builders.java.CannotCreateJavaCompilerException) File(java.io.File)

Aggregations

File (java.io.File)2 IOException (java.io.IOException)2 JavacCompilerTool (org.jetbrains.jps.builders.impl.java.JavacCompilerTool)2 VirtualFile (com.intellij.openapi.vfs.VirtualFile)1 SmartList (com.intellij.util.SmartList)1 THashSet (gnu.trove.THashSet)1 URI (java.net.URI)1 JavaFileObject (javax.tools.JavaFileObject)1 CannotCreateJavaCompilerException (org.jetbrains.jps.builders.java.CannotCreateJavaCompilerException)1 BinaryContent (org.jetbrains.jps.incremental.BinaryContent)1 LineOutputWriter (org.jetbrains.jps.incremental.LineOutputWriter)1 ExternalJavacManager (org.jetbrains.jps.javac.ExternalJavacManager)1 OutputFileObject (org.jetbrains.jps.javac.OutputFileObject)1