Java Code Examples for org.codehaus.groovy.control.CompilationUnit#addSource()

The following examples show how to use org.codehaus.groovy.control.CompilationUnit#addSource() . 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: TestMethodUtilTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private ModuleNode createGroovyModuleNode() {
    final CompilerConfiguration conf = new CompilerConfiguration();
    conf.setTargetDirectory(compileDir);
    final CompilationUnit cu
            = new CompilationUnit(
                    new GroovyClassLoader(
                            getClass().getClassLoader()
                    )
            );
    cu.configure(conf);
    final SourceUnit sn = cu.addSource("AGroovyClass.groovy", groovyScript.toString());
    try {
        cu.compile();
    } catch (Exception e) {
        //this groovy compile bit didn't work when running tests
        //but did work when debugging them, so odd, but the AST is in
        //place either way, and is all we need for this
        this.log(e.getMessage());
    }
    final ModuleNode mn = sn.getAST();
    return mn;
}
 
Example 2
Source File: AstStringCompiler.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the String source to {@link java.util.List} of {@link ASTNode}.
 *
 * @param script
 *      a Groovy script in String form
 * @param compilePhase
 *      the int based CompilePhase to compile it to.
 * @param statementsOnly
 * @return {@link java.util.List} of {@link ASTNode}
 */
public List<ASTNode> compile(String script, CompilePhase compilePhase, boolean statementsOnly) {
    final String scriptClassName = makeScriptClassName();
    GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptClassName + ".groovy", "/groovy/script");
    CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.getCodeSource(),
            AccessController.doPrivileged((PrivilegedAction<GroovyClassLoader>) GroovyClassLoader::new));
    cu.addSource(codeSource.getName(), script);
    cu.compile(compilePhase.getPhaseNumber());

    // collect all the ASTNodes into the result, possibly ignoring the script body if desired
    List<ASTNode> result = cu.getAST().getModules().stream().reduce(new LinkedList<>(), (acc, node) -> {
        BlockStatement statementBlock = node.getStatementBlock();
        if (null != statementBlock) {
            acc.add(statementBlock);
        }
        acc.addAll(
                node.getClasses().stream()
                    .filter(c -> !(statementsOnly && scriptClassName.equals(c.getName())))
                    .collect(Collectors.toList())
        );

        return acc;
    }, (o1, o2) -> o1);

    return result;
}
 
Example 3
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 4
Source File: ScriptCompilationExecuter.java    From groovy with Apache License 2.0 5 votes vote down vote up
public long execute() throws Exception {
    ClassLoader cl = new URLClassLoader(classpath, ClassLoader.getSystemClassLoader().getParent());
    GroovyClassLoader gcl = new GroovyClassLoader(cl);
    CompilationUnit cu = new CompilationUnit(new CompilerConfiguration(), null, gcl, new GroovyClassLoader(this.getClass().getClassLoader()));
    for (File source : sources) {
        cu.addSource(source);
    }
    long sd = System.nanoTime();
    cu.compile(CompilePhase.CLASS_GENERATION.getPhaseNumber());
    long dur = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - sd);
    return dur;
}
 
Example 5
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 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: ASTTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public ModuleNode getAST(String source, int untilPhase) {
    SourceUnit unit = SourceUnit.create("Test", source);
    CompilationUnit compUnit = new CompilationUnit();
    compUnit.addSource(unit);
    compUnit.compile(untilPhase);
    return unit.getAST();
}
 
Example 8
Source File: ConstraintInputIndexerTest.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
protected void configureModuleNode(final String source) {
    final CompilationUnit compilationUnit = new CompilationUnit();
    final SourceUnit sourceUnit = SourceUnit.create("unitName", source);
    compilationUnit.addSource(sourceUnit);
    compilationUnit.compile();
    when(groovyCompilationUnit.getModuleNode()).thenReturn(sourceUnit.getAST());
}
 
Example 9
Source File: Compiler.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Compiles a single File.
 */
public void compile(File file) throws CompilationFailedException {
    CompilationUnit unit = new CompilationUnit(configuration);
    unit.addSource(file);
    unit.compile();
}
 
Example 10
Source File: Compiler.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Compiles a string of code.
 */
public void compile(String name, String code) throws CompilationFailedException {
    CompilationUnit unit = new CompilationUnit(configuration);
    unit.addSource(new SourceUnit(name, code, configuration, unit.getClassLoader(), unit.getErrorCollector()));
    unit.compile();
}
 
Example 11
Source File: MetaClassImpl.java    From groovy with Apache License 2.0 4 votes vote down vote up
/**
 * Obtains a reference to the original AST for the MetaClass if it is available at runtime
 *
 * @return The original AST or null if it cannot be returned
 */
public ClassNode getClassNode() {
    if (classNode == null && GroovyObject.class.isAssignableFrom(theClass)) {
        // let's try load it from the classpath
        String groovyFile = theClass.getName();
        int idx = groovyFile.indexOf('$');
        if (idx > 0) {
            groovyFile = groovyFile.substring(0, idx);
        }
        groovyFile = groovyFile.replace('.', '/') + ".groovy";

        //System.out.println("Attempting to load: " + groovyFile);
        URL url = theClass.getClassLoader().getResource(groovyFile);
        if (url == null) {
            url = Thread.currentThread().getContextClassLoader().getResource(groovyFile);
        }
        if (url != null) {
            try {

                /*
                 * todo there is no CompileUnit in scope so class name
                 * checking won't work but that mostly affects the bytecode
                 * generation rather than viewing the AST
                 */
                CompilationUnit.ClassgenCallback search = (writer, node) -> {
                    if (node.getName().equals(theClass.getName())) {
                        MetaClassImpl.this.classNode = node;
                    }
                };

                CompilationUnit unit = new CompilationUnit();
                unit.setClassgenCallback(search);
                unit.addSource(url);
                unit.compile(Phases.CLASS_GENERATION);
            } catch (Exception e) {
                throw new GroovyRuntimeException("Exception thrown parsing: " + groovyFile + ". Reason: " + e, e);
            }
        }

    }
    return classNode;
}
 
Example 12
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;
}