<commit_before>/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.api.internal.tasks.compile;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.GroovySystem;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.codehaus.groovy.control.messages.SimpleMessage;
import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit;
import org.codehaus.groovy.tools.javac.JavaCompiler;
import org.codehaus.groovy.tools.javac.JavaCompilerFactory;
import org.gradle.api.GradleException;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.internal.classloading.GroovySystemLoader;
import org.gradle.api.internal.classloading.GroovySystemLoaderFactory;
import org.gradle.api.tasks.WorkResult;
import org.gradle.internal.classloader.ClassLoaderUtils;
import org.gradle.internal.classloader.DefaultClassLoaderFactory;
import org.gradle.internal.classloader.FilteringClassLoader;
import org.gradle.internal.classpath.DefaultClassPath;
import org.gradle.internal.concurrent.CompositeStoppable;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.util.internal.VersionNumber;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static org.gradle.internal.FileUtils.hasExtension;

public class ApiGroovyCompiler implements org.gradle.language.base.internal.compile.Compiler<GroovyJavaJointCompileSpec>, Serializable {
    private final Compiler<JavaCompileSpec> javaCompiler;
    private final ProjectLayout projectLayout;

    public ApiGroovyCompiler(Compiler<JavaCompileSpec> javaCompiler, ProjectLayout projectLayout) {
        this.javaCompiler = javaCompiler;
        this.projectLayout = projectLayout;
    }

    private static abstract class IncrementalCompilationCustomizer extends CompilationCustomizer {
        static IncrementalCompilationCustomizer fromSpec(GroovyJavaJointCompileSpec spec, ApiCompilerResult result) {
            if (spec.incrementalCompilationEnabled()) {
                return new TrackingClassGenerationCompilationCustomizer(new CompilationSourceDirs(spec), result);
            } else {
                return new NoOpCompilationCustomizer();
            }
        }

        public IncrementalCompilationCustomizer() {
            super(CompilePhase.CLASS_GENERATION);
        }

        abstract void addToConfiguration(CompilerConfiguration configuration);
    }

    private static class NoOpCompilationCustomizer extends IncrementalCompilationCustomizer {

        @Override
        public void addToConfiguration(CompilerConfiguration configuration) {
        }

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws org.codehaus.groovy.control.CompilationFailedException {
            throw new UnsupportedOperationException();
        }
    }

    private static class TrackingClassGenerationCompilationCustomizer extends IncrementalCompilationCustomizer {
        private final CompilationSourceDirs compilationSourceDirs;
        private final ApiCompilerResult result;

        private TrackingClassGenerationCompilationCustomizer(CompilationSourceDirs compilationSourceDirs, ApiCompilerResult result) {
            this.compilationSourceDirs = compilationSourceDirs;
            this.result = result;
        }

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
            inspectClassNode(source, classNode);
        }

        private void inspectClassNode(SourceUnit sourceUnit, ClassNode classNode) {
            String relativePath = compilationSourceDirs.relativize(new File(sourceUnit.getSource().getURI().getPath())).orElseThrow(IllegalStateException::new);
            result.getSourceClassesMapping().computeIfAbsent(relativePath, key -> new HashSet<>()).add(classNode.getName());
            Iterator<InnerClassNode> iterator = classNode.getInnerClasses();
            while (iterator.hasNext()) {
                inspectClassNode(sourceUnit, iterator.next());
            }
        }

        @Override
        public void addToConfiguration(CompilerConfiguration configuration) {
            configuration.addCompilationCustomizers(this);
        }
    }

    private File[] getSortedSourceFiles(GroovyJavaJointCompileSpec spec) {
        // Sort source files to work around https://issues.apache.org/jira/browse/GROOVY-7966
        File[] sortedSourceFiles = Iterables.toArray(spec.getSourceFiles(), File.class);
        Arrays.sort(sortedSourceFiles);
        return sortedSourceFiles;
    }

    @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 TODO */ }
        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;<commit_msg>Fix todo<commit_after>/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.api.internal.tasks.compile;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.GroovySystem;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.InnerClassNode;
import org.codehaus.groovy.classgen.GeneratorContext;
import org.codehaus.groovy.control.CompilationUnit;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;
import org.codehaus.groovy.control.customizers.ImportCustomizer;
import org.codehaus.groovy.control.messages.SimpleMessage;
import org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit;
import org.codehaus.groovy.tools.javac.JavaCompiler;
import org.codehaus.groovy.tools.javac.JavaCompilerFactory;
import org.gradle.api.GradleException;
import org.gradle.api.file.ProjectLayout;
import org.gradle.api.internal.classloading.GroovySystemLoader;
import org.gradle.api.internal.classloading.GroovySystemLoaderFactory;
import org.gradle.api.tasks.WorkResult;
import org.gradle.internal.classloader.ClassLoaderUtils;
import org.gradle.internal.classloader.DefaultClassLoaderFactory;
import org.gradle.internal.classloader.FilteringClassLoader;
import org.gradle.internal.classpath.DefaultClassPath;
import org.gradle.internal.concurrent.CompositeStoppable;
import org.gradle.language.base.internal.compile.Compiler;
import org.gradle.util.internal.VersionNumber;

import java.io.File;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static org.gradle.internal.FileUtils.hasExtension;

public class ApiGroovyCompiler implements org.gradle.language.base.internal.compile.Compiler<GroovyJavaJointCompileSpec>, Serializable {
    private final Compiler<JavaCompileSpec> javaCompiler;
    private final ProjectLayout projectLayout;

    public ApiGroovyCompiler(Compiler<JavaCompileSpec> javaCompiler, ProjectLayout projectLayout) {
        this.javaCompiler = javaCompiler;
        this.projectLayout = projectLayout;
    }

    private static abstract class IncrementalCompilationCustomizer extends CompilationCustomizer {
        static IncrementalCompilationCustomizer fromSpec(GroovyJavaJointCompileSpec spec, ApiCompilerResult result) {
            if (spec.incrementalCompilationEnabled()) {
                return new TrackingClassGenerationCompilationCustomizer(new CompilationSourceDirs(spec), result);
            } else {
                return new NoOpCompilationCustomizer();
            }
        }

        public IncrementalCompilationCustomizer() {
            super(CompilePhase.CLASS_GENERATION);
        }

        abstract void addToConfiguration(CompilerConfiguration configuration);
    }

    private static class NoOpCompilationCustomizer extends IncrementalCompilationCustomizer {

        @Override
        public void addToConfiguration(CompilerConfiguration configuration) {
        }

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws org.codehaus.groovy.control.CompilationFailedException {
            throw new UnsupportedOperationException();
        }
    }

    private static class TrackingClassGenerationCompilationCustomizer extends IncrementalCompilationCustomizer {
        private final CompilationSourceDirs compilationSourceDirs;
        private final ApiCompilerResult result;

        private TrackingClassGenerationCompilationCustomizer(CompilationSourceDirs compilationSourceDirs, ApiCompilerResult result) {
            this.compilationSourceDirs = compilationSourceDirs;
            this.result = result;
        }

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
            inspectClassNode(source, classNode);
        }

        private void inspectClassNode(SourceUnit sourceUnit, ClassNode classNode) {
            String relativePath = compilationSourceDirs.relativize(new File(sourceUnit.getSource().getURI().getPath())).orElseThrow(IllegalStateException::new);
            result.getSourceClassesMapping().computeIfAbsent(relativePath, key -> new HashSet<>()).add(classNode.getName());
            Iterator<InnerClassNode> iterator = classNode.getInnerClasses();
            while (iterator.hasNext()) {
                inspectClassNode(sourceUnit, iterator.next());
            }
        }

        @Override
        public void addToConfiguration(CompilerConfiguration configuration) {
            configuration.addCompilationCustomizers(this);
        }
    }

    private File[] getSortedSourceFiles(GroovyJavaJointCompileSpec spec) {
        // Sort source files to work around https://issues.apache.org/jira/browse/GROOVY-7966
        File[] sortedSourceFiles = Iterables.toArray(spec.getSourceFiles(), File.class);
        Arrays.sort(sortedSourceFiles);
        return sortedSourceFiles;
    }

    @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;
{'fraction_non_alphanumeric': 0.08309737070210922, 'fraction_numerical': 0.0023692574400462295, 'mean_word_length': 4.239479261277626, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 21, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5941515', 'n_tokens_mistral': 4568, 'n_tokens_neox': 4262, 'n_words': 888}