org.codehaus.groovy.control.Phases Java Examples

The following examples show how to use org.codehaus.groovy.control.Phases. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DependencyTest.java    From groovy with Apache License 2.0 6 votes vote down vote up
public void testTransitiveDep(){
    cu.addSource("testTransitiveDep.gtest", new StringBufferInputStream(
            "class A1 {}\n" +
            "class A2 extends A1{}\n" +
            "class A3 extends A2{}\n"
    ));
    cu.compile(Phases.CLASS_GENERATION);
    cache.makeTransitiveHull();

    Set<String> dep = cache.get("A1");
    assertEquals(dep.size(),1);

    dep = cache.get("A2");
    assertEquals(dep.size(),2);
    assertTrue(dep.contains("A1"));

    dep = cache.get("A3");
    assertEquals(dep.size(),3);
    assertTrue(dep.contains("A1"));
    assertTrue(dep.contains("A2"));
}
 
Example #2
Source File: JavaAwareCompilationUnit.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void gotoPhase(final int phase) throws CompilationFailedException {
    super.gotoPhase(phase);
    // compile Java and clean up
    if (phase == Phases.SEMANTIC_ANALYSIS && !javaSources.isEmpty()) {
        for (ModuleNode module : getAST().getModules()) {
            module.setImportsResolved(false);
        }
        try {
            addJavaCompilationUnits(stubGenerator.getJavaStubCompilationUnitSet()); // add java stubs
            JavaCompiler compiler = compilerFactory.createCompiler(configuration);
            compiler.compile(javaSources, this);
        } finally {
            if (!keepStubs) stubGenerator.clean();
            javaSources.clear();
        }
    }
}
 
Example #3
Source File: StaticTypeCheckingSupport.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * A helper method that can be used to evaluate expressions as found in annotation
 * parameters. For example, it will evaluate a constant, be it referenced directly as
 * an integer or as a reference to a field.
 * <p>
 * If this method throws an exception, then the expression cannot be evaluated on its own.
 *
 * @param expr   the expression to be evaluated
 * @param config the compiler configuration
 * @return the result of the expression
 */
public static Object evaluateExpression(final Expression expr, final CompilerConfiguration config) {
    String className = "Expression$" + UUID.randomUUID().toString().replace('-', '$');
    ClassNode node = new ClassNode(className, Opcodes.ACC_PUBLIC, OBJECT_TYPE);
    ReturnStatement code = new ReturnStatement(expr);
    addGeneratedMethod(node, "eval", Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, OBJECT_TYPE, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, code);
    CompilerConfiguration copyConf = new CompilerConfiguration(config);
    CompilationUnit cu = new CompilationUnit(copyConf);
    cu.addClassNode(node);
    cu.compile(Phases.CLASS_GENERATION);
    List<GroovyClass> classes = cu.getClasses();
    Class<?> aClass = cu.getClassLoader().defineClass(className, classes.get(0).getBytes());
    try {
        return aClass.getMethod("eval").invoke(null);
    } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        throw new GroovyBugError(e);
    }
}
 
Example #4
Source File: DependencyTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    cache = new StringSetMap();
    cu = new CompilationUnit();
    cu.addPhaseOperation((final SourceUnit source, final GeneratorContext context, final ClassNode classNode) -> {
        DependencyTracker dt = new DependencyTracker(source, cache);
        dt.visitClass(classNode);
    }, Phases.CLASS_GENERATION);
}
 
Example #5
Source File: DependencyTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testDep(){
    cu.addSource("testDep.gtest", new StringBufferInputStream(
            "class C1 {}\n" +
            "class C2 {}\n" +
            "class C3 {}\n" +
            "class A1 {C1 x}\n" +
            "class A2 extends C2{}\n" +
            "class A3 {C1 foo(C2 x){new C3()}}\n"
    ));
    cu.compile(Phases.CLASS_GENERATION);
    assertEquals(cache.get("C1").size(),1);
    assertEquals(cache.get("C2").size(),1);
    assertEquals(cache.get("C3").size(),1);

    Set<String> dep = cache.get("A1");
    assertEquals(dep.size(),2);
    assertTrue(dep.contains("C1"));

    dep = cache.get("A2");
    assertEquals(dep.size(),2);
    assertTrue(dep.contains("C2"));

    dep = cache.get("A3");
    assertEquals(dep.size(),4);
    assertTrue(dep.contains("C1"));
    assertTrue(dep.contains("C2"));
    assertTrue(dep.contains("C3"));
}
 
Example #6
Source File: GroovyClassLoader.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Class doParseClass(GroovyCodeSource codeSource) {
    validate(codeSource);
    Class answer;  // Was neither already loaded nor compiling, so compile and add to cache.
    CompilationUnit unit = createCompilationUnit(config, codeSource.getCodeSource());
    if (recompile!=null && recompile || recompile==null && config.getRecompileGroovySource()) {
        unit.addFirstPhaseOperation(TimestampAdder.INSTANCE, CompilePhase.CLASS_GENERATION.getPhaseNumber());
    }
    SourceUnit su = null;
    File file = codeSource.getFile();
    if (file != null) {
        su = unit.addSource(file);
    } else {
        URL url = codeSource.getURL();
        if (url != null) {
            su = unit.addSource(url);
        } else {
            su = unit.addSource(codeSource.getName(), codeSource.getScriptText());
        }
    }

    ClassCollector collector = createCollector(unit, su);
    unit.setClassgenCallback(collector);
    int goalPhase = Phases.CLASS_GENERATION;
    if (config != null && config.getTargetDirectory() != null) goalPhase = Phases.OUTPUT;
    unit.compile(goalPhase);

    answer = collector.generatedClass;
    String mainClass = su.getAST().getMainClassName();
    for (Object o : collector.getLoadedClasses()) {
        Class clazz = (Class) o;
        String clazzName = clazz.getName();
        definePackageInternal(clazzName);
        setClassCacheEntry(clazz);
        if (clazzName.equals(mainClass)) answer = clazz;
    }
    return answer;
}
 
Example #7
Source File: ProxyGeneratorAdapter.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Class adjustSuperClass(Class superClass, final Class[] interfaces) {
    boolean isSuperClassAnInterface = superClass.isInterface();
    if (!isSuperClassAnInterface) {
        return superClass;
    }
    Class result = Object.class;
    Set<ClassNode> traits = new LinkedHashSet<ClassNode>();
    // check if it's a trait
    collectTraits(superClass, traits);
    if (interfaces != null) {
        for (Class anInterface : interfaces) {
            collectTraits(anInterface, traits);
        }
    }
    if (!traits.isEmpty()) {
        String name = superClass.getName() + "$TraitAdapter";
        ClassNode cn = new ClassNode(name, ACC_PUBLIC | ACC_ABSTRACT, ClassHelper.OBJECT_TYPE, traits.toArray(ClassNode.EMPTY_ARRAY), null);
        CompilationUnit cu = new CompilationUnit(loader);
        CompilerConfiguration config = new CompilerConfiguration();
        SourceUnit su = new SourceUnit(name + "wrapper", "", config, loader, new ErrorCollector(config));
        cu.addSource(su);
        cu.compile(Phases.CONVERSION);
        su.getAST().addClass(cn);
        cu.compile(Phases.CLASS_GENERATION);
        @SuppressWarnings("unchecked")
        List<GroovyClass> classes = (List<GroovyClass>) cu.getClasses();
        for (GroovyClass groovyClass : classes) {
            if (groovyClass.getName().equals(name)) {
                return loader.defineClass(name, groovyClass.getBytes());
            }
        }
    }
    return result;
}
 
Example #8
Source File: GroovyDocParser.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Map<String, GroovyClassDoc> parseGroovy(String packagePath, String file, String src) throws RuntimeException {
    CompilerConfiguration config = new CompilerConfiguration();
    config.getOptimizationOptions().put(CompilerConfiguration.GROOVYDOC, true);
    CompilationUnit compUnit = new CompilationUnit(config);
    SourceUnit unit = new SourceUnit(file, src, config, null, new ErrorCollector(config));
    compUnit.addSource(unit);
    compUnit.compile(Phases.CONVERSION);
    ModuleNode root = unit.getAST();
    GroovydocVisitor visitor = new GroovydocVisitor(unit, packagePath, links);
    visitor.visitClass(root.getClasses().get(0));
    return visitor.getGroovyClassDocs();
}
 
Example #9
Source File: ASTTest.java    From groovy with Apache License 2.0 4 votes vote down vote up
public ModuleNode getAST(String source) {
    return getAST(source, Phases.SEMANTIC_ANALYSIS);
}
 
Example #10
Source File: GroovyScriptEngine.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
protected CompilationUnit createCompilationUnit(CompilerConfiguration configuration, CodeSource source) {
    CompilationUnit cu = super.createCompilationUnit(configuration, source);
    LocalData local = getLocalData().get();
    local.cu = cu;
    final StringSetMap cache = local.dependencyCache;
    final Map<String, String> precompiledEntries = local.precompiledEntries;

    // "." is used to transfer compilation dependencies, which will be
    // recollected later during compilation
    for (String depSourcePath : cache.get(".")) {
        try {
            cache.get(depSourcePath);
            cu.addSource(getResourceConnection(depSourcePath).getURL());
        } catch (ResourceException e) {
            /* ignore */
        }
    }

    // remove all old entries including the "." entry
    cache.clear();

    cu.addPhaseOperation((final SourceUnit sourceUnit, final GeneratorContext context, final ClassNode classNode) -> {
       // GROOVY-4013: If it is an inner class, tracking its dependencies doesn't really
       // serve any purpose and also interferes with the caching done to track dependencies
       if (classNode.getOuterClass() != null) return;
       DependencyTracker dt = new DependencyTracker(sourceUnit, cache, precompiledEntries);
       dt.visitClass(classNode);
    }, Phases.CLASS_GENERATION);

    cu.setClassNodeResolver(new ClassNodeResolver() {
        @Override
        public LookupResult findClassNode(String origName, CompilationUnit compilationUnit) {
            CompilerConfiguration cc = compilationUnit.getConfiguration();
            String name = origName.replace('.', '/');
            for (String ext : cc.getScriptExtensions()) {
                try {
                    String finalName = name + "." + ext;
                    URLConnection conn = rc.getResourceConnection(finalName);
                    URL url = conn.getURL();
                    String path = url.toExternalForm();
                    ScriptCacheEntry entry = scriptCache.get(path);
                    Class clazz = null;
                    if (entry != null) clazz = entry.scriptClass;
                    if (GroovyScriptEngine.this.isSourceNewer(entry)) {
                        try {
                            SourceUnit su = compilationUnit.addSource(url);
                            return new LookupResult(su, null);
                        } finally {
                            forceClose(conn);
                        }
                    } else {
                        precompiledEntries.put(origName, path);
                    }
                    if (clazz != null) {
                        ClassNode cn = ClassHelper.make(clazz);
                        return new LookupResult(null, cn);
                    }
                } catch (ResourceException re) {
                    // skip
                }
            }
            return super.findClassNode(origName, compilationUnit);
        }
    });

    return cu;
}
 
Example #11
Source File: ScriptSourceDescriptionTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CONVERSION;
}
 
Example #12
Source File: ModelBlockTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #13
Source File: TaskDefinitionScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #14
Source File: StatementExtractingScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CONVERSION;
}
 
Example #15
Source File: StatementExtractingScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #16
Source File: FixMainScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CONVERSION;
}
 
Example #17
Source File: StatementLabelsScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #18
Source File: TaskDefinitionScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #19
Source File: StatementExtractingScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CONVERSION;
}
 
Example #20
Source File: StatementExtractingScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #21
Source File: FixMainScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CONVERSION;
}
 
Example #22
Source File: StatementLabelsScriptTransformer.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #23
Source File: ExtendedGroovyClassLoader.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
public Class parseClass(InputStream in, String fileName, SourceFile[] files) throws CompilationFailedException {
    return doParseClass(in, fileName, files, Phases.CLASS_GENERATION, null, false);
}
 
Example #24
Source File: ExtendedGroovyClassLoader.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
public Class[] parseClasses(SourceFile[] files) {
    return doParseClasses(files, Phases.CLASS_GENERATION, null);
}
 
Example #25
Source File: FixMainScriptTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CONVERSION;
}
 
Example #26
Source File: ModelBlockTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #27
Source File: TaskDefinitionScriptTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #28
Source File: StatementExtractingScriptTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CONVERSION;
}
 
Example #29
Source File: StatementExtractingScriptTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
protected int getPhase() {
    return Phases.CANONICALIZATION;
}
 
Example #30
Source File: FixMainScriptTransformer.java    From pushfish-android with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
protected int getPhase() {
    return Phases.CONVERSION;
}