org.codehaus.groovy.classgen.GeneratorContext Java Examples

The following examples show how to use org.codehaus.groovy.classgen.GeneratorContext. 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: 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 #2
Source File: ImportCustomizer.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) {
    ModuleNode ast = source.getAST();

    // GROOVY-8399: apply import customizations only once per module
    if (!classNode.getName().equals(ast.getMainClassName())) return;

    for (Import anImport : imports) {
        switch (anImport.type) {
            case regular:
                ast.addImport(anImport.alias, anImport.classNode);
                break;
            case staticImport:
                ast.addStaticImport(anImport.classNode, anImport.field, anImport.alias);
                break;
            case staticStar:
                ast.addStaticStarImport(anImport.alias, anImport.classNode);
                break;
            case star:
                ast.addStarImport(anImport.star);
                break;
        }
    }
}
 
Example #3
Source File: StaticTypesWriterController.java    From groovy with Apache License 2.0 6 votes vote down vote up
@Override
public void init(final AsmClassGenerator asmClassGenerator, final GeneratorContext gcon, final ClassVisitor cv, final ClassNode cn) {
    super.init(asmClassGenerator, gcon, cv, cn);
    this.callSiteWriter = new StaticTypesCallSiteWriter(this);
    this.statementWriter = new StaticTypesStatementWriter(this);
    this.typeChooser = new StaticTypesTypeChooser();
    this.invocationWriter = new StaticInvocationWriter(this);
    this.closureWriter = new StaticTypesClosureWriter(this);
    this.lambdaWriter = new StaticTypesLambdaWriter(this);
    this.methodReferenceExpressionWriter = new StaticTypesMethodReferenceExpressionWriter(this);
    this.unaryExpressionHelper = new StaticTypesUnaryExpressionHelper(this);

    CompilerConfiguration config = cn.getCompileUnit().getConfig();
    this.binaryExprHelper = config.isIndyEnabled()
            ? new IndyStaticTypesMultiTypeDispatcher(this)
            : new StaticTypesBinaryExpressionMultiTypeDispatcher(this);
}
 
Example #4
Source File: TemplateASTTransformer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
    if (classNode.isScriptBody()) {
        classNode.setSuperClass(ClassHelper.make(config.getBaseTemplateClass()));
        createConstructor(classNode);
        transformRunMethod(classNode, source);
        VariableScopeVisitor visitor = new VariableScopeVisitor(source);
        visitor.visitClass(classNode);
    }
}
 
Example #5
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 #6
Source File: SourceAwareCustomizer.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
    String fileName = source.getName();
    ReaderSource reader = source.getSource();
    if (reader instanceof FileReaderSource) {
        FileReaderSource file = (FileReaderSource) reader;
        fileName = file.getFile().getName();
    }
    if (acceptSource(source) && acceptClass(classNode) && accept(fileName)) {
        delegate.call(source, context, classNode);
    }
}
 
Example #7
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 #8
Source File: ModuleNode.java    From groovy with Apache License 2.0 5 votes vote down vote up
public ClassNode getScriptClassDummy() {
    if (scriptDummy != null) {
        setScriptBaseClassFromConfig(scriptDummy);
        return scriptDummy;
    }

    String name = getPackageName();
    if (name == null) {
        name = "";
    }
    // now let's use the file name to determine the class name
    if (getDescription() == null) {
        throw new RuntimeException("Cannot generate main(String[]) class for statements when we have no file description");
    }
    name += GeneratorContext.encodeAsValidClassName(extractClassFromFileDescription());

    ClassNode classNode;
    if (isPackageInfo()) {
        classNode = new ClassNode(name, ACC_ABSTRACT | ACC_INTERFACE, ClassHelper.OBJECT_TYPE);
    } else {
        classNode = new ClassNode(name, ACC_PUBLIC, ClassHelper.SCRIPT_TYPE);
        setScriptBaseClassFromConfig(classNode);
        classNode.setScript(true);
        classNode.setScriptBody(true);
    }

    scriptDummy = classNode;
    return classNode;
}
 
Example #9
Source File: GroovyClassLoader.java    From groovy with Apache License 2.0 5 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
    if ((classNode.getModifiers() & Opcodes.ACC_INTERFACE) > 0) {
        // does not apply on interfaces
        return;
    }
    if (!(classNode instanceof InnerClassNode)) {
        addTimeStamp(classNode);
    }
}
 
Example #10
Source File: DelegatingController.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void init(final AsmClassGenerator asmClassGenerator, final GeneratorContext gcon, final ClassVisitor cv, final ClassNode cn) {
    delegationController.init(asmClassGenerator, gcon, cv, cn);
}
 
Example #11
Source File: TestCompilationCustomizer.java    From Nicobar with Apache License 2.0 4 votes vote down vote up
@Override
public void call(SourceUnit source, GeneratorContext context,
        ClassNode classNode) throws CompilationFailedException {
    // no op customizer
}
 
Example #12
Source File: Groovy2CompilerHelperTest.java    From Nicobar with Apache License 2.0 4 votes vote down vote up
@Override
public void call(SourceUnit source, GeneratorContext context,
        ClassNode classNode) throws CompilationFailedException {
    this.executed = true;
}
 
Example #13
Source File: SandboxCpsTransformer.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
@Override
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
    stv = st.createVisitor(source, classNode);
    super.call(source, context, classNode);
}
 
Example #14
Source File: CpsTransformer.java    From groovy-cps with Apache License 2.0 4 votes vote down vote up
@Override
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
    if (classNode.isInterface()) {
        return; // not touching interfaces
    }
    this.sourceUnit = source;
    this.classNode = classNode;

    // Removes all initial expressions for methods and constructors and generates overloads for all variants.
    new InitialExpressionExpander().expandInitialExpressions(classNode);

    try {

        for (FieldNode field : new ArrayList<>(classNode.getFields())) {
            visitNontransformedField(field);
        }
        for (MethodNode method : new ArrayList<>(classNode.getMethods())) {
            visitMethod(method);
        }
        processConstructors(classNode);
        for (Statement statement : new ArrayList<>(classNode.getObjectInitializerStatements())) {
            visitNontransformedStatement(statement);
        }

        classNode.addInterface(SERIALIZABLE_TYPE);

        // groovy puts timestamp of compilation into a class file, causing serialVersionUID to change.
        // this tends to be undesirable for CPS involving persistence.
        // set the timestamp to some bogus value will prevent Verifier from adding a field that encodes
        // timestamp in the field name
        // see http://stackoverflow.com/questions/15310136/neverhappen-variable-in-compiled-classes
        if (classNode.getField(Verifier.__TIMESTAMP) == null) {
            classNode.addField(Verifier.__TIMESTAMP, Modifier.STATIC | Modifier.PRIVATE, ClassHelper.long_TYPE,
                    new ConstantExpression(0L));
        }

        classNode.addAnnotation(new AnnotationNode(WORKFLOW_TRANSFORMED_TYPE));

    } finally {
        this.sourceUnit = null;
        this.classNode = null;
        this.parent = null;
    }
}
 
Example #15
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 #16
Source File: CallSiteGenerator.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static boolean containsOnlyValidChars(String name) {
    // TODO: this might not do enough or too much
    // But it is a good start without spreading logic everywhere
    String encoded = GeneratorContext.encodeAsValidClassName(name);
    return encoded.equals(name);
}
 
Example #17
Source File: WriterController.java    From groovy with Apache License 2.0 4 votes vote down vote up
public GeneratorContext getContext() {
    return context;
}
 
Example #18
Source File: WriterController.java    From groovy with Apache License 2.0 4 votes vote down vote up
public void init(final AsmClassGenerator asmClassGenerator, final GeneratorContext gcon, final ClassVisitor cv, final ClassNode cn) {
    CompilerConfiguration config = cn.getCompileUnit().getConfig();
    Map<String,Boolean> optOptions = config.getOptimizationOptions();
    boolean invokedynamic = false;
    if (optOptions.isEmpty()) {
        // IGNORE
    } else if (Boolean.FALSE.equals(optOptions.get("all"))) {
        this.optimizeForInt = false;
        // set other optimizations options to false here
    } else {
        if (config.isIndyEnabled()) invokedynamic = true;
        if (Boolean.FALSE.equals(optOptions.get("int"))) this.optimizeForInt = false;
        if (invokedynamic) this.optimizeForInt = false;
        // set other optimizations options to false here
    }
    this.classNode = cn;
    this.outermostClass = null;
    this.internalClassName = BytecodeHelper.getClassInternalName(cn);

    this.bytecodeVersion = chooseBytecodeVersion(invokedynamic, config.isPreviewFeatures(), config.getTargetBytecode());

    if (invokedynamic) {
        this.invocationWriter = new InvokeDynamicWriter(this);
        this.callSiteWriter = new IndyCallSiteWriter(this);
        this.binaryExpHelper = new IndyBinHelper(this);
    } else {
        this.callSiteWriter = new CallSiteWriter(this);
        this.invocationWriter = new InvocationWriter(this);
        this.binaryExpHelper = new BinaryExpressionHelper(this);
    }

    this.unaryExpressionHelper = new UnaryExpressionHelper(this);
    if (this.optimizeForInt) {
        this.fastPathBinaryExpHelper = new BinaryExpressionMultiTypeDispatcher(this);
        // TODO: replace with a real fast path unary expression helper when available
        this.fastPathUnaryExpressionHelper = new UnaryExpressionHelper(this);
    } else {
        this.fastPathBinaryExpHelper = this.binaryExpHelper;
        this.fastPathUnaryExpressionHelper = new UnaryExpressionHelper(this);
    }

    this.operandStack = new OperandStack(this);
    this.assertionWriter = new AssertionWriter(this);
    this.closureWriter = new ClosureWriter(this);
    this.lambdaWriter = new LambdaWriter(this);
    this.methodPointerExpressionWriter = new MethodPointerExpressionWriter(this);
    this.methodReferenceExpressionWriter = new MethodReferenceExpressionWriter(this);
    this.internalBaseClassName = BytecodeHelper.getClassInternalName(cn.getSuperClass());
    this.acg = asmClassGenerator;
    this.context = gcon;
    this.compileStack = new CompileStack(this);
    this.cv = createClassVisitor(cv);
    if (this.optimizeForInt) {
        this.statementWriter = new OptimizingStatementWriter(this);
    } else {
        this.statementWriter = new StatementWriter(this);
    }
    this.typeChooser = new StatementMetaTypeChooser();
}
 
Example #19
Source File: DelegatingController.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public GeneratorContext getContext() {
    return delegationController.getContext();
}
 
Example #20
Source File: GroovyScriptEngine.java    From chaosblade-exec-jvm with Apache License 2.0 4 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws
    CompilationFailedException {
    new BigDecimalExpressionTransformer(source).visitClass(classNode);
}
 
Example #21
Source File: DelegatingCustomizer.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
    delegate.call(source, context, classNode);
}
 
Example #22
Source File: CompilationUnit.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
    new OptimizerVisitor(CompilationUnit.this).visitClass(classNode, source); // GROOVY-4272: repositioned from static import visitor

    //
    // Run the Verifier on the outer class
    //
    GroovyClassVisitor visitor = new Verifier();
    try {
        visitor.visitClass(classNode);
    } catch (RuntimeParserException rpe) {
        getErrorCollector().addError(new SyntaxException(rpe.getMessage(), rpe.getNode()), source);
    }

    visitor = new LabelVerifier(source);
    visitor.visitClass(classNode);

    visitor = new InstanceOfVerifier() {
        @Override
        protected SourceUnit getSourceUnit() {
            return source;
        }
    };
    visitor.visitClass(classNode);

    visitor = new ClassCompletionVerifier(source);
    visitor.visitClass(classNode);

    visitor = new ExtendedVerifier(source);
    visitor.visitClass(classNode);

    // because the class may be generated even if a error was found
    // and that class may have an invalid format we fail here if needed
    getErrorCollector().failIfErrors();

    //
    // Prep the generator machinery
    //
    ClassVisitor classVisitor = createClassVisitor();

    String sourceName = (source == null ? classNode.getModule().getDescription() : source.getName());
    // only show the file name and its extension like javac does in its stacktraces rather than the full path
    // also takes care of both \ and / depending on the host compiling environment
    if (sourceName != null) {
        sourceName = sourceName.substring(Math.max(sourceName.lastIndexOf('\\'), sourceName.lastIndexOf('/')) + 1);
    }

    //
    // Run the generation and create the class (if required)
    //
    visitor = new AsmClassGenerator(source, context, classVisitor, sourceName);
    visitor.visitClass(classNode);

    byte[] bytes = ((ClassWriter) classVisitor).toByteArray();
    getClasses().add(new GroovyClass(classNode.getName(), bytes));

    //
    // Handle any callback that's been set
    //
    Optional.ofNullable(getClassgenCallback())
        .ifPresent(callback -> callback.call(classVisitor, classNode));

    //
    // Recurse for inner classes
    //
    LinkedList<ClassNode> innerClasses = ((AsmClassGenerator) visitor).getInnerClasses();
    while (!innerClasses.isEmpty()) {
        classgen.call(source, context, innerClasses.removeFirst());
    }
}
 
Example #23
Source File: JSR223SecurityTest.java    From groovy with Apache License 2.0 4 votes vote down vote up
@Override
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) {
    for (Object statement : source.getAST().getStatementBlock().getStatements()) {
        ((ExpressionStatement) statement).visit(new CustomCodeVisitorSupport());
    }
}
 
Example #24
Source File: DriverCompilationCustomizer.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@Override
public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
   LOGGER.trace("Customize [phase: {} {}, classNode: {}]", source.getPhase(), source.getPhaseDescription(), classNode);
   if(classNode.getField("_HASH") == null) {
      String hash = hash(source);
      if(hash != null) {
         classNode.addField(
               "_HASH", 
               Modifier.PUBLIC | Modifier.FINAL, 
               new ClassNode(String.class), 
               new ConstantExpression(hash)
         );
      }
   }
   
   ClassNode groovyCapabilityDefinition = new ClassNode(GroovyCapabilityDefinition.class);
   for(CapabilityDefinition definition: capabilityRegistry.listCapabilityDefinitions()) {
      if(classNode.getProperty(definition.getCapabilityName()) != null) {
         continue;
      }
      
      if(!isDeviceCapability(definition)) {
         continue;
      }
      
      String fieldName = definition.getNamespace();
      FieldNode field = classNode.addField(
            fieldName,
            Modifier.PRIVATE | Modifier.FINAL, 
            groovyCapabilityDefinition,
            new StaticMethodCallExpression(
                  new ClassNode(GroovyCapabilityDefinitionFactory.class),
                  "create",
                  new TupleExpression(
                        new ConstantExpression(definition.getCapabilityName()),
                        VariableExpression.THIS_EXPRESSION
                  )
            )
      );
      
      
      classNode.addProperty(
            definition.getCapabilityName(),
            Modifier.PUBLIC | Modifier.FINAL,
            groovyCapabilityDefinition,
            new FieldExpression(field),
            new ReturnStatement(new FieldExpression(field)),
            null
       );
   }
}
 
Example #25
Source File: CompilationUnit.java    From groovy with Apache License 2.0 votes vote down vote up
void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException;