org.codehaus.groovy.control.CompilePhase Java Examples

The following examples show how to use org.codehaus.groovy.control.CompilePhase. 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: GroovyScriptEngine.java    From chaosblade-exec-jvm with Apache License 2.0 6 votes vote down vote up
@Override
public Object compile(com.alibaba.chaosblade.exec.plugin.jvm.script.base.Script script, ClassLoader classLoader,
                      Map<String, String> configs) {
    String className = "groovy_script_" + script.getId();
    GroovyCodeSource codeSource = new GroovyCodeSource(script.getContent(), className, UNTRUSTED_CODEBASE);
    codeSource.setCachable(true);
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration()
        .addCompilationCustomizers(
            new ImportCustomizer().addStaticStars("java.lang.Math"))
        .addCompilationCustomizers(new GroovyBigDecimalTransformer(CompilePhase.CONVERSION));
    compilerConfiguration.getOptimizationOptions().put(GROOVY_INDY_SETTING_NAME, true);
    GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader, compilerConfiguration);
    try {
        return groovyClassLoader.parseClass(script.getContent());
    } catch (Exception ex) {
        throw convertToScriptException("Compile script failed:" + className, script.getId(), ex);
    }
}
 
Example #2
Source File: GroovyGradleParser.java    From size-analyzer with Apache License 2.0 6 votes vote down vote up
public static GradleContext.Builder parseGradleBuildFile(
    String content,
    int defaultMinSdkVersion,
    @Nullable AndroidPluginVersion defaultAndroidPluginVersion) {
  // We need to have an abstract syntax tree, which is what the conversion phase produces,
  // Anything more will try to semantically understand the groovy code.
  List<ASTNode> astNodes = new AstBuilder().buildFromString(CompilePhase.CONVERSION, content);
  GroovyGradleParser parser =
      new GroovyGradleParser(content, defaultMinSdkVersion, defaultAndroidPluginVersion);

  for (ASTNode node : astNodes) {
    if (node instanceof ClassNode) {
      // class nodes do not implement the visit method, and will throw a runtime exception.
      continue;
    }
    node.visit(parser);
  }
  return parser.getGradleContextBuilder();
}
 
Example #3
Source File: MarkupTemplateEngine.java    From groovy with Apache License 2.0 6 votes vote down vote up
public MarkupTemplateEngine(final ClassLoader parentLoader, final TemplateConfiguration tplConfig, final TemplateResolver resolver) {
    compilerConfiguration = new CompilerConfiguration();
    templateConfiguration = tplConfig;
    compilerConfiguration.addCompilationCustomizers(new TemplateASTTransformer(tplConfig));
    compilerConfiguration.addCompilationCustomizers(
            new ASTTransformationCustomizer(Collections.singletonMap("extensions", "groovy.text.markup.MarkupTemplateTypeCheckingExtension"), CompileStatic.class));
    if (templateConfiguration.isAutoNewLine()) {
        compilerConfiguration.addCompilationCustomizers(
                new CompilationCustomizer(CompilePhase.CONVERSION) {
                    @Override
                    public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
                        new AutoNewLineTransformer(source).visitClass(classNode);
                    }
                }
        );
    }
    groovyClassLoader = AccessController.doPrivileged((PrivilegedAction<TemplateGroovyClassLoader>) () -> new TemplateGroovyClassLoader(parentLoader, compilerConfiguration));
    if (DEBUG_BYTECODE) {
        compilerConfiguration.setBytecodePostprocessor(BytecodeDumper.STANDARD_ERR);
    }
    templateResolver = resolver == null ? new DefaultTemplateResolver() : resolver;
    templateResolver.configure(groovyClassLoader, templateConfiguration);
}
 
Example #4
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 #5
Source File: InlinedASTCustomizerFactory.java    From groovy with Apache License 2.0 6 votes vote down vote up
public Object postCompleteNode(final FactoryBuilderSupport factory, final Object parent, final Object node) {
    if (node instanceof Map) {
        Map map = (Map) node;
        ProxyGeneratorAdapter adapter = new ProxyGeneratorAdapter(
                map,
                map.containsKey("superClass")?(Class)map.get("superClass"):CompilationCustomizer.class,
                map.containsKey("interfaces")?(Class[])map.get("interfaces"):null,
                this.getClass().getClassLoader(),
                false,
                null
        );
        Object phase = map.get("phase");
        if (!(phase instanceof CompilePhase)) {
            phase = CompilePhase.valueOf(phase.toString());
        }
        return adapter.proxy(map, phase);
    }
    return node;
}
 
Example #6
Source File: DriverCompilationCustomizer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Inject
public DriverCompilationCustomizer(CapabilityRegistry registry) {
   // copied from ImportCustomizer, not sure what the best phase is,
   // but this should be early enough to add imports, etc
   super(CompilePhase.CONVERSION);
   this.capabilityRegistry = registry;
}
 
Example #7
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 #8
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 #9
Source File: ClassNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
private Map<CompilePhase, Map<Class<? extends ASTTransformation>, Set<ASTNode>>> getTransformInstances() {
    if (transformInstances == null) {
        transformInstances = new EnumMap<>(CompilePhase.class);
        for (CompilePhase phase : CompilePhase.values()) {
            transformInstances.put(phase, new LinkedHashMap<>());
        }
    }
    return transformInstances;
}
 
Example #10
Source File: SourceAwareCustomizerFactory.java    From groovy with Apache License 2.0 5 votes vote down vote up
public Object newInstance(final FactoryBuilderSupport builder, final Object name, final Object value, final Map attributes) throws InstantiationException, IllegalAccessException {
    SourceOptions data = new SourceOptions();
    if (value instanceof CompilationCustomizer) {
        data.delegate = (CompilationCustomizer) value;
    } else {
        // GROOVY-9035 supply a "no-op" CompilationCustomizer if none found to make DSL friendly for empty case
        data.delegate = new CompilationCustomizer(CompilePhase.FINALIZATION) {
            @Override
            public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
            }
        };
    }
    return data;
}
 
Example #11
Source File: TestCompilationCustomizer.java    From Nicobar with Apache License 2.0 4 votes vote down vote up
public TestCompilationCustomizer() {
    super(CompilePhase.SEMANTIC_ANALYSIS);
}
 
Example #12
Source File: Groovy2CompilerHelperTest.java    From Nicobar with Apache License 2.0 4 votes vote down vote up
public TestCompilationCustomizer() {
    super(CompilePhase.SEMANTIC_ANALYSIS);
}
 
Example #13
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
public CpsTransformer() {
    super(CompilePhase.CANONICALIZATION);
}
 
Example #14
Source File: ClassNode.java    From groovy with Apache License 2.0 4 votes vote down vote up
public Map<Class <? extends ASTTransformation>, Set<ASTNode>> getTransforms(CompilePhase phase) {
    return getTransformInstances().get(phase);
}
 
Example #15
Source File: ASTTransformationVisitor.java    From groovy with Apache License 2.0 4 votes vote down vote up
private ASTTransformationVisitor(final CompilePhase phase, final ASTTransformationsContext context) {
    this.phase = phase;
    this.context = context;
}
 
Example #16
Source File: SecureASTCustomizer.java    From groovy with Apache License 2.0 4 votes vote down vote up
public SecureASTCustomizer() {
    super(CompilePhase.CANONICALIZATION);
}
 
Example #17
Source File: ImportCustomizer.java    From groovy with Apache License 2.0 4 votes vote down vote up
public ImportCustomizer() {
    super(CompilePhase.CONVERSION);
}
 
Example #18
Source File: CompilationCustomizer.java    From groovy with Apache License 2.0 4 votes vote down vote up
public CompilePhase getPhase() {
    return phase;
}
 
Example #19
Source File: CompilationCustomizer.java    From groovy with Apache License 2.0 4 votes vote down vote up
public CompilationCustomizer(final CompilePhase phase) {
    this.phase = phase;
}
 
Example #20
Source File: MacroGroovyMethods.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static <T> T macro(Object self, CompilePhase compilePhase, boolean asIs, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
    throw new IllegalStateException("MacroGroovyMethods.macro(CompilePhase, boolean, Closure) should never be called at runtime. Are you sure you are using it correctly?");
}
 
Example #21
Source File: MacroGroovyMethods.java    From groovy with Apache License 2.0 4 votes vote down vote up
public static <T> T macro(Object self, CompilePhase compilePhase, @DelegatesTo(MacroValuePlaceholder.class) Closure cl) {
    throw new IllegalStateException("MacroGroovyMethods.macro(CompilePhase, Closure) should never be called at runtime. Are you sure you are using it correctly?");
}
 
Example #22
Source File: TemplateASTTransformer.java    From groovy with Apache License 2.0 4 votes vote down vote up
public TemplateASTTransformer(TemplateConfiguration config) {
    super(CompilePhase.SEMANTIC_ANALYSIS);
    this.config = config;
}
 
Example #23
Source File: GroovyScriptEngine.java    From chaosblade-exec-jvm with Apache License 2.0 4 votes vote down vote up
private GroovyBigDecimalTransformer(CompilePhase phase) {
    super(phase);
}
 
Example #24
Source File: AstStringCompiler.java    From groovy with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the String source to {@link java.util.List} of statement {@link ASTNode}.
 *
 * @param script a Groovy script in String form
 * @return {@link java.util.List} of statement {@link ASTNode}
 * @since 3.0.0
 */
public List<ASTNode> compile(String script) {
    return this.compile(script, CompilePhase.CONVERSION, true);
}