Search in sources :

Example 21 with WorkResult

use of org.gradle.api.tasks.WorkResult in project gradle by gradle.

the class ZincScalaCompiler method execute.

public WorkResult execute(final ScalaJavaJointCompileSpec spec) {
    LOGGER.info("Compiling with Zinc Scala compiler.");
    Timer timer = Time.startTimer();
    IncrementalCompilerImpl incremental = new IncrementalCompilerImpl();
    Compilers compilers = incremental.compilers(scalaInstance, ClasspathOptionsUtil.boot(), Option.apply(Jvm.current().getJavaHome()), scalaCompiler);
    List<String> scalacOptions = new ZincScalaCompilerArgumentsGenerator().generate(spec);
    List<String> javacOptions = new JavaCompilerArgumentsBuilder(spec).includeClasspath(false).noEmptySourcePath().build();
    File[] classpath = Iterables.toArray(spec.getCompileClasspath(), File.class);
    CompileOptions compileOptions = CompileOptions.create().withSources(Iterables.toArray(spec.getSourceFiles(), File.class)).withClasspath(classpath).withScalacOptions(scalacOptions.toArray(new String[0])).withClassesDirectory(spec.getDestinationDir()).withJavacOptions(javacOptions.toArray(new String[0]));
    File analysisFile = spec.getAnalysisFile();
    Optional<AnalysisStore> analysisStore;
    Optional<ClassFileManagerType> classFileManagerType;
    if (spec.getScalaCompileOptions().isForce()) {
        analysisStore = Optional.empty();
        classFileManagerType = IncOptions.defaultClassFileManagerType();
    } else {
        analysisStore = Optional.of(analysisStoreProvider.get(analysisFile));
        classFileManagerType = Optional.of(TransactionalManagerType.of(spec.getClassfileBackupDir(), new SbtLoggerAdapter()));
    }
    PreviousResult previousResult = analysisStore.flatMap(store -> store.get().map(a -> PreviousResult.of(Optional.of(a.getAnalysis()), Optional.of(a.getMiniSetup())))).orElse(PreviousResult.of(Optional.empty(), Optional.empty()));
    IncOptions incOptions = IncOptions.of().withExternalHooks(new LookupOnlyExternalHooks(new ExternalBinariesLookup())).withRecompileOnMacroDef(Optional.of(false)).withClassfileManagerType(classFileManagerType).withTransitiveStep(5);
    Setup setup = incremental.setup(new EntryLookup(spec), false, analysisFile, CompilerCache.fresh(), incOptions, // MappedPosition is used to make sure toString returns proper error messages
    new LoggedReporter(100, new SbtLoggerAdapter(), MappedPosition::new), Option.empty(), getExtra());
    Inputs inputs = incremental.inputs(compileOptions, compilers, setup, previousResult);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(inputs.toString());
    }
    if (spec.getScalaCompileOptions().isForce()) {
        // TODO This should use Deleter
        GFileUtils.deleteDirectory(spec.getDestinationDir());
        GFileUtils.deleteQuietly(spec.getAnalysisFile());
    }
    LOGGER.info("Prepared Zinc Scala inputs: {}", timer.getElapsed());
    try {
        CompileResult compile = incremental.compile(inputs, new SbtLoggerAdapter());
        if (analysisStore.isPresent()) {
            AnalysisContents contentNext = AnalysisContents.create(compile.analysis(), compile.setup());
            analysisStore.get().set(contentNext);
        }
    } catch (xsbti.CompileFailed e) {
        throw new CompilationFailedException(e);
    }
    LOGGER.info("Completed Scala compilation: {}", timer.getElapsed());
    return WorkResults.didWork(true);
}
Also used : Compiler(org.gradle.language.base.internal.compile.Compiler) FileHash(xsbti.compile.FileHash) WorkResult(org.gradle.api.tasks.WorkResult) IncOptions(xsbti.compile.IncOptions) Inputs(xsbti.compile.Inputs) TransactionalManagerType(xsbti.compile.TransactionalManagerType) Map(java.util.Map) ScalaCompiler(xsbti.compile.ScalaCompiler) PreviousResult(xsbti.compile.PreviousResult) JavaCompilerArgumentsBuilder(org.gradle.api.internal.tasks.compile.JavaCompilerArgumentsBuilder) Some(scala.Some) Jvm(org.gradle.internal.jvm.Jvm) ClassFileManager(xsbti.compile.ClassFileManager) ExternalLookup(sbt.internal.inc.ExternalLookup) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) DefinesClass(xsbti.compile.DefinesClass) AnalysisContents(xsbti.compile.AnalysisContents) WorkResults(org.gradle.api.tasks.WorkResults) List(java.util.List) CompilerCache(xsbti.compile.CompilerCache) IncrementalCompilerImpl(sbt.internal.inc.IncrementalCompilerImpl) JavaConverters(scala.collection.JavaConverters) Optional(java.util.Optional) ExternalHooks(xsbti.compile.ExternalHooks) Timer(org.gradle.internal.time.Timer) CompileAnalysis(xsbti.compile.CompileAnalysis) Set(scala.collection.immutable.Set) Iterables(com.google.common.collect.Iterables) LoggedReporter(sbt.internal.inc.LoggedReporter) Stamper(sbt.internal.inc.Stamper) CompileOptions(xsbti.compile.CompileOptions) MapBackedCache(org.gradle.cache.internal.MapBackedCache) Setup(xsbti.compile.Setup) HashMap(java.util.HashMap) CompileResult(xsbti.compile.CompileResult) Logger(org.gradle.api.logging.Logger) ClassFileManagerType(xsbti.compile.ClassFileManagerType) PerClasspathEntryLookup(xsbti.compile.PerClasspathEntryLookup) Inject(javax.inject.Inject) Changes(xsbti.compile.Changes) T2(xsbti.T2) GFileUtils(org.gradle.util.internal.GFileUtils) Compilers(xsbti.compile.Compilers) ScalaInstance(sbt.internal.inc.ScalaInstance) Option(scala.Option) AnalysisStore(xsbti.compile.AnalysisStore) File(java.io.File) Analysis(sbt.internal.inc.Analysis) CompilationFailedException(org.gradle.api.internal.tasks.compile.CompilationFailedException) Locate(sbt.internal.inc.Locate) ClasspathOptionsUtil(xsbti.compile.ClasspathOptionsUtil) Logging(org.gradle.api.logging.Logging) Time(org.gradle.internal.time.Time) Stamp(xsbti.compile.analysis.Stamp) JavaCompilerArgumentsBuilder(org.gradle.api.internal.tasks.compile.JavaCompilerArgumentsBuilder) CompilationFailedException(org.gradle.api.internal.tasks.compile.CompilationFailedException) IncrementalCompilerImpl(sbt.internal.inc.IncrementalCompilerImpl) AnalysisContents(xsbti.compile.AnalysisContents) Setup(xsbti.compile.Setup) Inputs(xsbti.compile.Inputs) ClassFileManagerType(xsbti.compile.ClassFileManagerType) PerClasspathEntryLookup(xsbti.compile.PerClasspathEntryLookup) LoggedReporter(sbt.internal.inc.LoggedReporter) PreviousResult(xsbti.compile.PreviousResult) CompileOptions(xsbti.compile.CompileOptions) IncOptions(xsbti.compile.IncOptions) Timer(org.gradle.internal.time.Timer) AnalysisStore(xsbti.compile.AnalysisStore) CompileResult(xsbti.compile.CompileResult) File(java.io.File) Compilers(xsbti.compile.Compilers)

Example 22 with WorkResult

use of org.gradle.api.tasks.WorkResult in project gradle by gradle.

the class IncrementalResultStoringCompiler method execute.

@Override
public WorkResult execute(T spec) {
    WorkResult result = delegate.execute(spec);
    if (result instanceof RecompilationNotNecessary) {
        return result;
    }
    storeResult(spec, result);
    return result;
}
Also used : WorkResult(org.gradle.api.tasks.WorkResult)

Example 23 with WorkResult

use of org.gradle.api.tasks.WorkResult in project gradle by gradle.

the class IncrementalNativeCompiler method execute.

@Override
public WorkResult execute(final T spec) {
    WorkResult workResult;
    if (spec.isIncrementalCompile()) {
        workResult = doIncrementalCompile(incrementalCompilation, spec);
    } else {
        workResult = doCleanIncrementalCompile(spec);
    }
    compileStateCache.set(incrementalCompilation.getFinalState());
    return workResult;
}
Also used : WorkResult(org.gradle.api.tasks.WorkResult)

Example 24 with WorkResult

use of org.gradle.api.tasks.WorkResult in project gradle by gradle.

the class GroovyCompile method compile.

@TaskAction
protected void compile(InputChanges inputChanges) {
    checkGroovyClasspathIsNonEmpty();
    warnIfCompileAvoidanceEnabled();
    GroovyJavaJointCompileSpec spec = createSpec();
    WorkResult result = getCompiler(spec, inputChanges).execute(spec);
    setDidWork(result.getDidWork());
}
Also used : GroovyJavaJointCompileSpec(org.gradle.api.internal.tasks.compile.GroovyJavaJointCompileSpec) DefaultGroovyJavaJointCompileSpec(org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpec) WorkResult(org.gradle.api.tasks.WorkResult) TaskAction(org.gradle.api.tasks.TaskAction)

Example 25 with WorkResult

use of org.gradle.api.tasks.WorkResult in project gradle by gradle.

the class ApiGroovyCompiler method execute.

@Override
public WorkResult execute(final GroovyJavaJointCompileSpec spec) {
    ApiCompilerResult result = new ApiCompilerResult();
    result.getAnnotationProcessingResult().setFullRebuildCause("Incremental annotation processing is not supported by Groovy.");
    GroovySystemLoaderFactory groovySystemLoaderFactory = new GroovySystemLoaderFactory();
    ClassLoader compilerClassLoader = this.getClass().getClassLoader();
    GroovySystemLoader compilerGroovyLoader = groovySystemLoaderFactory.forClassLoader(compilerClassLoader);
    CompilerConfiguration configuration = new CompilerConfiguration();
    configuration.setVerbose(spec.getGroovyCompileOptions().isVerbose());
    configuration.setSourceEncoding(spec.getGroovyCompileOptions().getEncoding());
    configuration.setTargetBytecode(spec.getTargetCompatibility());
    configuration.setTargetDirectory(spec.getDestinationDir());
    canonicalizeValues(spec.getGroovyCompileOptions().getOptimizationOptions());
    VersionNumber version = parseGroovyVersion();
    if (version.compareTo(VersionNumber.parse("2.5")) >= 0) {
        configuration.setParameters(spec.getGroovyCompileOptions().isParameters());
    } else if (spec.getGroovyCompileOptions().isParameters()) {
        throw new GradleException("Using Groovy compiler flag '--parameters' requires Groovy 2.5+ but found Groovy " + version);
    }
    IncrementalCompilationCustomizer customizer = IncrementalCompilationCustomizer.fromSpec(spec, result);
    customizer.addToConfiguration(configuration);
    if (spec.getGroovyCompileOptions().getConfigurationScript() != null) {
        applyConfigurationScript(spec.getGroovyCompileOptions().getConfigurationScript(), configuration);
    }
    try {
        configuration.setOptimizationOptions(spec.getGroovyCompileOptions().getOptimizationOptions());
    } catch (NoSuchMethodError ignored) {
    /* method was only introduced in Groovy 1.8 */
    }
    try {
        configuration.setDisabledGlobalASTTransformations(spec.getGroovyCompileOptions().getDisabledGlobalASTTransformations());
    } catch (NoSuchMethodError ignored) {
    /* method was only introduced in Groovy 2.0.0 */
    }
    Map<String, Object> jointCompilationOptions = new HashMap<String, Object>();
    final File stubDir = spec.getGroovyCompileOptions().getStubDir();
    stubDir.mkdirs();
    jointCompilationOptions.put("stubDir", stubDir);
    jointCompilationOptions.put("keepStubs", spec.getGroovyCompileOptions().isKeepStubs());
    configuration.setJointCompilationOptions(jointCompilationOptions);
    ClassLoader classPathLoader;
    if (version.compareTo(VersionNumber.parse("2.0")) < 0) {
        // using a transforming classloader is only required for older buggy Groovy versions
        classPathLoader = new GroovyCompileTransformingClassLoader(getExtClassLoader(), DefaultClassPath.of(spec.getCompileClasspath()));
    } else {
        classPathLoader = new DefaultClassLoaderFactory().createIsolatedClassLoader("api-groovy-compile-loader", DefaultClassPath.of(spec.getCompileClasspath()));
    }
    GroovyClassLoader compileClasspathClassLoader = new GroovyClassLoader(classPathLoader, null);
    GroovySystemLoader compileClasspathLoader = groovySystemLoaderFactory.forClassLoader(classPathLoader);
    FilteringClassLoader.Spec groovyCompilerClassLoaderSpec = new FilteringClassLoader.Spec();
    groovyCompilerClassLoaderSpec.allowPackage("org.codehaus.groovy");
    groovyCompilerClassLoaderSpec.allowPackage("groovy");
    groovyCompilerClassLoaderSpec.allowPackage("groovyjarjarasm");
    // Disallow classes from Groovy Jar that reference external classes. Such classes must be loaded from astTransformClassLoader,
    // or a NoClassDefFoundError will occur. Essentially this is drawing a line between the Groovy compiler and the Groovy
    // library, albeit only for selected classes that run a high risk of being statically referenced from a transform.
    groovyCompilerClassLoaderSpec.disallowClass("groovy.util.GroovyTestCase");
    groovyCompilerClassLoaderSpec.disallowClass("org.codehaus.groovy.transform.NotYetImplementedASTTransformation");
    groovyCompilerClassLoaderSpec.disallowPackage("groovy.servlet");
    FilteringClassLoader groovyCompilerClassLoader = new FilteringClassLoader(GroovyClassLoader.class.getClassLoader(), groovyCompilerClassLoaderSpec);
    // AST transforms need their own class loader that shares compiler classes with the compiler itself
    final GroovyClassLoader astTransformClassLoader = new GroovyClassLoader(groovyCompilerClassLoader, null);
    // where the transform class is loaded from)
    for (File file : spec.getCompileClasspath()) {
        astTransformClassLoader.addClasspath(file.getPath());
    }
    JavaAwareCompilationUnit unit = new JavaAwareCompilationUnit(configuration, compileClasspathClassLoader) {

        @Override
        public GroovyClassLoader getTransformLoader() {
            return astTransformClassLoader;
        }
    };
    final boolean shouldProcessAnnotations = shouldProcessAnnotations(spec);
    if (shouldProcessAnnotations) {
        // If an annotation processor is detected, we need to force Java stub generation, so the we can process annotations on Groovy classes
        // We are forcing stub generation by tricking the groovy compiler into thinking there are java files to compile.
        // All java files are just passed to the compile method of the JavaCompiler and aren't processed internally by the Groovy Compiler.
        // Since we're maintaining our own list of Java files independent of what's passed by the Groovy compiler, adding a non-existent java file
        // to the sources won't cause any issues.
        unit.addSources(new File[] { new File("ForceStubGeneration.java") });
    }
    unit.addSources(getSortedSourceFiles(spec));
    unit.setCompilerFactory(new JavaCompilerFactory() {

        @Override
        public JavaCompiler createCompiler(final CompilerConfiguration config) {
            return new JavaCompiler() {

                @Override
                public void compile(List<String> files, CompilationUnit cu) {
                    if (shouldProcessAnnotations) {
                        // In order for the Groovy stubs to have annotation processors invoked against them, they must be compiled as source.
                        // Classes compiled as a result of being on the -sourcepath do not have the annotation processor run against them
                        spec.setSourceFiles(Iterables.concat(spec.getSourceFiles(), projectLayout.files(stubDir).getAsFileTree()));
                    } else {
                        // When annotation processing isn't required, it's better to add the Groovy stubs as part of the source path.
                        // This allows compilations to complete faster, because only the Groovy stubs that are needed by the java source are compiled.
                        ImmutableList.Builder<File> sourcepathBuilder = ImmutableList.builder();
                        sourcepathBuilder.add(stubDir);
                        if (spec.getCompileOptions().getSourcepath() != null) {
                            sourcepathBuilder.addAll(spec.getCompileOptions().getSourcepath());
                        }
                        spec.getCompileOptions().setSourcepath(sourcepathBuilder.build());
                    }
                    spec.setSourceFiles(Iterables.filter(spec.getSourceFiles(), new Predicate<File>() {

                        @Override
                        public boolean apply(File file) {
                            return hasExtension(file, ".java");
                        }
                    }));
                    try {
                        WorkResult javaCompilerResult = javaCompiler.execute(spec);
                        if (javaCompilerResult instanceof ApiCompilerResult) {
                            result.getSourceClassesMapping().putAll(((ApiCompilerResult) javaCompilerResult).getSourceClassesMapping());
                        }
                    } catch (CompilationFailedException e) {
                        cu.getErrorCollector().addFatalError(new SimpleMessage(e.getMessage(), cu));
                    }
                }
            };
        }
    });
    try {
        unit.compile();
        return result;
    } catch (org.codehaus.groovy.control.CompilationFailedException e) {
        System.err.println(e.getMessage());
        // Explicit flush, System.err is an auto-flushing PrintWriter unless it is replaced.
        System.err.flush();
        throw new CompilationFailedException();
    } finally {
        // Remove compile and AST types from the Groovy loader
        compilerGroovyLoader.discardTypesFrom(classPathLoader);
        compilerGroovyLoader.discardTypesFrom(astTransformClassLoader);
        // Discard the compile loader
        compileClasspathLoader.shutdown();
        CompositeStoppable.stoppable(classPathLoader, astTransformClassLoader).stop();
    }
}
Also used : HashMap(java.util.HashMap) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) FilteringClassLoader(org.gradle.internal.classloader.FilteringClassLoader) GroovyClassLoader(groovy.lang.GroovyClassLoader) GroovySystemLoader(org.gradle.api.internal.classloading.GroovySystemLoader) GroovySystemLoaderFactory(org.gradle.api.internal.classloading.GroovySystemLoaderFactory) DefaultClassLoaderFactory(org.gradle.internal.classloader.DefaultClassLoaderFactory) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) CompilationUnit(org.codehaus.groovy.control.CompilationUnit) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) JavaCompiler(org.codehaus.groovy.tools.javac.JavaCompiler) JavaCompilerFactory(org.codehaus.groovy.tools.javac.JavaCompilerFactory) VersionNumber(org.gradle.util.internal.VersionNumber) GradleException(org.gradle.api.GradleException) FilteringClassLoader(org.gradle.internal.classloader.FilteringClassLoader) WorkResult(org.gradle.api.tasks.WorkResult) File(java.io.File)

Aggregations

WorkResult (org.gradle.api.tasks.WorkResult)25 TaskAction (org.gradle.api.tasks.TaskAction)11 BuildOperationLogger (org.gradle.internal.operations.logging.BuildOperationLogger)9 File (java.io.File)8 BuildOperationLoggerFactory (org.gradle.internal.operations.logging.BuildOperationLoggerFactory)4 NativePlatformInternal (org.gradle.nativeplatform.platform.internal.NativePlatformInternal)4 NativeToolChainInternal (org.gradle.nativeplatform.toolchain.internal.NativeToolChainInternal)3 HashMap (java.util.HashMap)2 DefaultGroovyJavaJointCompileSpec (org.gradle.api.internal.tasks.compile.DefaultGroovyJavaJointCompileSpec)2 OutputFile (org.gradle.api.tasks.OutputFile)2 WorkResults (org.gradle.api.tasks.WorkResults)2 PatternFilterable (org.gradle.api.tasks.util.PatternFilterable)2 PatternSet (org.gradle.api.tasks.util.PatternSet)2 Timer (org.gradle.internal.time.Timer)2 DefaultWindowsResourceCompileSpec (org.gradle.language.rc.internal.DefaultWindowsResourceCompileSpec)2 NativeCompileSpec (org.gradle.nativeplatform.toolchain.internal.NativeCompileSpec)2 PlatformToolProvider (org.gradle.nativeplatform.toolchain.internal.PlatformToolProvider)2 Iterables (com.google.common.collect.Iterables)1 GroovyClassLoader (groovy.lang.GroovyClassLoader)1 IOException (java.io.IOException)1