Search in sources :

Example 1 with GeneratorContext

use of org.codehaus.groovy.classgen.GeneratorContext in project intellij-community by JetBrains.

the class GroovyCompilerWrapper method getStubOutputItems.

@NotNull
static List<OutputItem> getStubOutputItems(CompilationUnit compilationUnit, final File stubDirectory) {
    final List<OutputItem> compiledFiles = new ArrayList<OutputItem>();
    compilationUnit.applyToPrimaryClassNodes(new CompilationUnit.PrimaryClassNodeOperation() {

        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
            final String topLevel = classNode.getName();
            String fileName = source.getName();
            if (fileName.startsWith("file:")) {
                try {
                    fileName = new URL(fileName).getFile();
                } catch (MalformedURLException ignored) {
                }
            }
            OutputItem item = new OutputItem(stubDirectory, topLevel.replace('.', '/') + ".java", fileName);
            if (new File(item.getOutputPath()).exists()) {
                compiledFiles.add(item);
            }
        }
    });
    return compiledFiles;
}
Also used : ClassNode(org.codehaus.groovy.ast.ClassNode) MalformedURLException(java.net.MalformedURLException) GeneratorContext(org.codehaus.groovy.classgen.GeneratorContext) URL(java.net.URL) File(java.io.File) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with GeneratorContext

use of org.codehaus.groovy.classgen.GeneratorContext in project intellij-community by JetBrains.

the class DependentGroovycRunner method createStubGenerator.

private static CompilationUnit createStubGenerator(final CompilerConfiguration config, final GroovyClassLoader classLoader, final GroovyClassLoader transformLoader, final Queue mailbox, final GroovyCompilerWrapper wrapper) {
    final JavaAwareCompilationUnit unit = new JavaAwareCompilationUnit(config, classLoader) {

        private boolean annoRemovedAdded;

        @Override
        public GroovyClassLoader getTransformLoader() {
            return transformLoader;
        }

        @Override
        public void addPhaseOperation(PrimaryClassNodeOperation op, int phase) {
            if (!annoRemovedAdded && mailbox == null && phase == Phases.CONVERSION && op.getClass().getName().startsWith("org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit$")) {
                annoRemovedAdded = true;
                super.addPhaseOperation(new PrimaryClassNodeOperation() {

                    @Override
                    public void call(final SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
                        final ClassCodeVisitorSupport annoRemover = new ClassCodeVisitorSupport() {

                            @Override
                            protected SourceUnit getSourceUnit() {
                                return source;
                            }

                            public void visitClass(ClassNode node) {
                                if (node.isEnum()) {
                                    node.setModifiers(node.getModifiers() & ~Opcodes.ACC_FINAL);
                                }
                                super.visitClass(node);
                            }

                            @Override
                            public void visitField(FieldNode fieldNode) {
                                Expression valueExpr = fieldNode.getInitialValueExpression();
                                if (valueExpr instanceof ConstantExpression && ClassHelper.STRING_TYPE.equals(valueExpr.getType())) {
                                    fieldNode.setInitialValueExpression(new MethodCallExpression(valueExpr, "toString", new ListExpression()));
                                }
                                super.visitField(fieldNode);
                            }

                            @Override
                            public void visitAnnotations(AnnotatedNode node) {
                                List<AnnotationNode> annotations = node.getAnnotations();
                                if (!annotations.isEmpty()) {
                                    annotations.clear();
                                }
                                super.visitAnnotations(node);
                            }
                        };
                        try {
                            annoRemover.visitClass(classNode);
                        } catch (LinkageError ignored) {
                        }
                    }
                }, phase);
            }
            super.addPhaseOperation(op, phase);
        }

        public void gotoPhase(int phase) throws CompilationFailedException {
            if (phase < Phases.SEMANTIC_ANALYSIS) {
                System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovy stub generator: " + getPhaseDescription());
            } else if (phase <= Phases.ALL) {
                System.out.println(GroovyRtConstants.PRESENTABLE_MESSAGE + "Groovyc: " + getPhaseDescription());
            }
            super.gotoPhase(phase);
        }
    };
    unit.setCompilerFactory(new JavaCompilerFactory() {

        public JavaCompiler createCompiler(final CompilerConfiguration config) {
            return new JavaCompiler() {

                public void compile(List<String> files, CompilationUnit cu) {
                    if (mailbox != null) {
                        reportCompiledItems(GroovyCompilerWrapper.getStubOutputItems(unit, (File) config.getJointCompilationOptions().get(STUB_DIR)));
                        System.out.flush();
                        System.err.flush();
                        pauseAndWaitForJavac(mailbox);
                        wrapper.onContinuation();
                    }
                }
            };
        }
    });
    unit.addSources(new String[] { "SomeClass.java" });
    return unit;
}
Also used : JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) JavaCompiler(org.codehaus.groovy.tools.javac.JavaCompiler) JavaAwareCompilationUnit(org.codehaus.groovy.tools.javac.JavaAwareCompilationUnit) GeneratorContext(org.codehaus.groovy.classgen.GeneratorContext) JavaCompilerFactory(org.codehaus.groovy.tools.javac.JavaCompilerFactory) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) ListExpression(org.codehaus.groovy.ast.expr.ListExpression) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) MethodCallExpression(org.codehaus.groovy.ast.expr.MethodCallExpression) Expression(org.codehaus.groovy.ast.expr.Expression)

Example 3 with GeneratorContext

use of org.codehaus.groovy.classgen.GeneratorContext in project ratpack by ratpack.

the class ScriptEngine method createClassLoader.

private GroovyClassLoader createClassLoader(final Path scriptPath) {
    final CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
    if (!scriptBaseClass.equals(Script.class)) {
        compilerConfiguration.setScriptBaseClass(scriptBaseClass.getName());
    }
    compilerConfiguration.addCompilationCustomizers(new CompilationCustomizer(CompilePhase.CONVERSION) {

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
            if (staticCompile) {
                classNode.addAnnotation(new AnnotationNode(new ClassNode(CompileStatic.class)));
            }
            classNode.addAnnotation(new AnnotationNode(new ClassNode(InheritConstructors.class)));
            if (scriptPath != null) {
                AnnotationNode scriptPathAnnotation = new AnnotationNode(new ClassNode(ScriptPath.class));
                scriptPathAnnotation.addMember("value", new ConstantExpression(scriptPath.toUri().toString()));
                classNode.addAnnotation(scriptPathAnnotation);
            }
        }
    });
    return new GroovyClassLoader(parentLoader, compilerConfiguration) {

        @Override
        protected CompilationUnit createCompilationUnit(CompilerConfiguration config, CodeSource source) {
            return new CompilationUnit(config, source, this) {

                {
                    verifier = new Verifier() {

                        @Override
                        public void visitClass(ClassNode node) {
                            if (node.implementsInterface(ClassHelper.GENERATED_CLOSURE_Type)) {
                                AnnotationNode lineNumberAnnotation = new AnnotationNode(LINE_NUMBER_CLASS_NODE);
                                lineNumberAnnotation.addMember("value", new ConstantExpression(node.getLineNumber(), true));
                                node.addAnnotation(lineNumberAnnotation);
                            }
                            super.visitClass(node);
                        }
                    };
                }
            };
        }
    };
}
Also used : Script(groovy.lang.Script) ClassNode(org.codehaus.groovy.ast.ClassNode) InheritConstructors(groovy.transform.InheritConstructors) ConstantExpression(org.codehaus.groovy.ast.expr.ConstantExpression) CompileStatic(groovy.transform.CompileStatic) GeneratorContext(org.codehaus.groovy.classgen.GeneratorContext) CodeSource(java.security.CodeSource) Verifier(org.codehaus.groovy.classgen.Verifier) GroovyClassLoader(groovy.lang.GroovyClassLoader) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) CompilationCustomizer(org.codehaus.groovy.control.customizers.CompilationCustomizer)

Example 4 with GeneratorContext

use of org.codehaus.groovy.classgen.GeneratorContext in project ratpack by ratpack.

the class GroovySnippetExecuter method execute.

@Override
public void execute(TestCodeSnippet snippet) throws Exception {
    CompilerConfiguration config = new CompilerConfiguration();
    config.addCompilationCustomizers(new CompilationCustomizer(CompilePhase.CONVERSION) {

        @Override
        public void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {
            if (compileStatic) {
                classNode.addAnnotation(new AnnotationNode(new ClassNode(CompileStatic.class)));
            }
        }
    });
    ClassLoader classLoader = new URLClassLoader(new URL[] {}, getClass().getClassLoader());
    GroovyShell groovyShell = new GroovyShell(classLoader, new Binding(), config);
    List<String> importsAndSnippet = extractImports(snippet.getSnippet());
    String imports = importsAndSnippet.get(0);
    String snippetMinusImports = fixture.transform(importsAndSnippet.get(1));
    String fullSnippet = imports + fixture.pre() + snippetMinusImports + fixture.post();
    Script script;
    try {
        script = groovyShell.parse(fullSnippet, snippet.getClassName());
    } catch (MultipleCompilationErrorsException e) {
        Message error = e.getErrorCollector().getError(0);
        if (error instanceof SyntaxErrorMessage) {
            // noinspection ThrowableResultOfMethodCallIgnored
            System.out.println(snippet.getSnippet());
            throw new CompileException(e, ((SyntaxErrorMessage) error).getCause().getLine());
        } else {
            throw e;
        }
    }
    ClassLoader previousContextClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(groovyShell.getClassLoader());
        fixture.around(script::run);
    } finally {
        Thread.currentThread().setContextClassLoader(previousContextClassLoader);
    }
}
Also used : Binding(groovy.lang.Binding) ClassNode(org.codehaus.groovy.ast.ClassNode) Script(groovy.lang.Script) Message(org.codehaus.groovy.control.messages.Message) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) CompileStatic(groovy.transform.CompileStatic) GeneratorContext(org.codehaus.groovy.classgen.GeneratorContext) GroovyShell(groovy.lang.GroovyShell) AnnotationNode(org.codehaus.groovy.ast.AnnotationNode) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) CompilationCustomizer(org.codehaus.groovy.control.customizers.CompilationCustomizer)

Example 5 with GeneratorContext

use of org.codehaus.groovy.classgen.GeneratorContext in project groovy-core by groovy.

the class TraitASTTransformation method registerASTTranformations.

private void registerASTTranformations(final ClassNode helper) {
    ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, compilationUnit.getTransformLoader());
    collector.visitClass(helper);
    // Perform an additional phase which has to be done *after* type checking
    compilationUnit.addPhaseOperation(new CompilationUnit.PrimaryClassNodeOperation() {

        @Override
        public void call(final SourceUnit source, final GeneratorContext context, final ClassNode classNode) throws CompilationFailedException {
            if (classNode == helper) {
                PostTypeCheckingExpressionReplacer replacer = new PostTypeCheckingExpressionReplacer(source);
                replacer.visitClass(helper);
            }
        }
    }, CompilePhase.INSTRUCTION_SELECTION.getPhaseNumber());
}
Also used : CompilationUnit(org.codehaus.groovy.control.CompilationUnit) InnerClassNode(org.codehaus.groovy.ast.InnerClassNode) ClassNode(org.codehaus.groovy.ast.ClassNode) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SourceUnit(org.codehaus.groovy.control.SourceUnit) GeneratorContext(org.codehaus.groovy.classgen.GeneratorContext) ASTTransformationCollectorCodeVisitor(org.codehaus.groovy.transform.ASTTransformationCollectorCodeVisitor)

Aggregations

GeneratorContext (org.codehaus.groovy.classgen.GeneratorContext)11 ClassNode (org.codehaus.groovy.ast.ClassNode)10 SourceUnit (org.codehaus.groovy.control.SourceUnit)6 InnerClassNode (org.codehaus.groovy.ast.InnerClassNode)4 CompilationUnit (org.codehaus.groovy.control.CompilationUnit)4 GroovyClassVisitor (org.codehaus.groovy.ast.GroovyClassVisitor)3 CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)3 Script (groovy.lang.Script)2 CompileStatic (groovy.transform.CompileStatic)2 File (java.io.File)2 AnnotationNode (org.codehaus.groovy.ast.AnnotationNode)2 ConstantExpression (org.codehaus.groovy.ast.expr.ConstantExpression)2 Expression (org.codehaus.groovy.ast.expr.Expression)2 CompilationCustomizer (org.codehaus.groovy.control.customizers.CompilationCustomizer)2 ASTTransformationCollectorCodeVisitor (org.codehaus.groovy.transform.ASTTransformationCollectorCodeVisitor)2 Binding (groovy.lang.Binding)1 GroovyClassLoader (groovy.lang.GroovyClassLoader)1 GroovyShell (groovy.lang.GroovyShell)1 InheritConstructors (groovy.transform.InheritConstructors)1 FileOutputStream (java.io.FileOutputStream)1