Search in sources :

Example 1 with Context

use of com.sun.tools.javac.util.Context in project checkstyle by checkstyle.

the class TokenTypesDocletTest method testNotConstants.

@Test
public void testNotConstants() throws Exception {
    // Token types must be public int constants, which means that they must have
    // modifiers public, static, final and type int, because they are referenced statically in
    // a lot of different places, must not be changed and an int value is used to encrypt
    // a token type.
    final ListBuffer<String[]> options = new ListBuffer<>();
    options.add(new String[] { "-doclet", "TokenTypesDoclet" });
    options.add(new String[] { "-destfile", "target/tokentypes.properties" });
    final ListBuffer<String> names = new ListBuffer<>();
    names.add(getPath("InputTokenTypesDocletNotConstants.java"));
    final Context context = new Context();
    new TestMessager(context);
    final JavadocTool javadocTool = JavadocTool.make0(context);
    final RootDoc rootDoc = getRootDoc(javadocTool, options, names);
    assertTrue(TokenTypesDoclet.start(rootDoc));
}
Also used : Context(com.sun.tools.javac.util.Context) ListBuffer(com.sun.tools.javac.util.ListBuffer) RootDoc(com.sun.javadoc.RootDoc) JavadocTool(com.sun.tools.javadoc.JavadocTool) Test(org.junit.Test)

Example 2 with Context

use of com.sun.tools.javac.util.Context in project checkstyle by checkstyle.

the class TokenTypesDocletTest method testCorrect.

@Test
public void testCorrect() throws Exception {
    final ListBuffer<String[]> options = new ListBuffer<>();
    options.add(new String[] { "-destfile", "target/tokentypes.properties" });
    final ListBuffer<String> names = new ListBuffer<>();
    names.add(getPath("InputTokenTypesDocletCorrect.java"));
    final Context context = new Context();
    new TestMessager(context);
    final JavadocTool javadocTool = JavadocTool.make0(context);
    final RootDoc rootDoc = getRootDoc(javadocTool, options, names);
    assertTrue(TokenTypesDoclet.start(rootDoc));
}
Also used : Context(com.sun.tools.javac.util.Context) ListBuffer(com.sun.tools.javac.util.ListBuffer) RootDoc(com.sun.javadoc.RootDoc) JavadocTool(com.sun.tools.javadoc.JavadocTool) Test(org.junit.Test)

Example 3 with Context

use of com.sun.tools.javac.util.Context in project lombok by rzwitserloot.

the class HandleCleanup method handle.

@Override
public void handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.CLEANUP_FLAG_USAGE, "@Cleanup");
    if (inNetbeansEditor(annotationNode))
        return;
    deleteAnnotationIfNeccessary(annotationNode, Cleanup.class);
    String cleanupName = annotation.getInstance().value();
    if (cleanupName.length() == 0) {
        annotationNode.addError("cleanupName cannot be the empty string.");
        return;
    }
    if (annotationNode.up().getKind() != Kind.LOCAL) {
        annotationNode.addError("@Cleanup is legal only on local variable declarations.");
        return;
    }
    JCVariableDecl decl = (JCVariableDecl) annotationNode.up().get();
    if (decl.init == null) {
        annotationNode.addError("@Cleanup variable declarations need to be initialized.");
        return;
    }
    JavacNode ancestor = annotationNode.up().directUp();
    JCTree blockNode = ancestor.get();
    final List<JCStatement> statements;
    if (blockNode instanceof JCBlock) {
        statements = ((JCBlock) blockNode).stats;
    } else if (blockNode instanceof JCCase) {
        statements = ((JCCase) blockNode).stats;
    } else if (blockNode instanceof JCMethodDecl) {
        statements = ((JCMethodDecl) blockNode).body.stats;
    } else {
        annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block.");
        return;
    }
    boolean seenDeclaration = false;
    ListBuffer<JCStatement> newStatements = new ListBuffer<JCStatement>();
    ListBuffer<JCStatement> tryBlock = new ListBuffer<JCStatement>();
    for (JCStatement statement : statements) {
        if (!seenDeclaration) {
            if (statement == decl)
                seenDeclaration = true;
            newStatements.append(statement);
        } else {
            tryBlock.append(statement);
        }
    }
    if (!seenDeclaration) {
        annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent.");
        return;
    }
    doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name);
    JavacTreeMaker maker = annotationNode.getTreeMaker();
    JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName));
    List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec(maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil())));
    JCExpression preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name));
    JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null));
    JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null);
    Context context = annotationNode.getContext();
    JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast, context);
    newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast, context), List.<JCCatch>nil(), finalizer), ast, context));
    if (blockNode instanceof JCBlock) {
        ((JCBlock) blockNode).stats = newStatements.toList();
    } else if (blockNode instanceof JCCase) {
        ((JCCase) blockNode).stats = newStatements.toList();
    } else if (blockNode instanceof JCMethodDecl) {
        ((JCMethodDecl) blockNode).body.stats = newStatements.toList();
    } else
        throw new AssertionError("Should not get here");
    ancestor.rebuild();
}
Also used : Context(com.sun.tools.javac.util.Context) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JCMethodDecl(com.sun.tools.javac.tree.JCTree.JCMethodDecl) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCFieldAccess(com.sun.tools.javac.tree.JCTree.JCFieldAccess) ListBuffer(com.sun.tools.javac.util.ListBuffer) JCTree(com.sun.tools.javac.tree.JCTree) JCBinary(com.sun.tools.javac.tree.JCTree.JCBinary) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JavacNode(lombok.javac.JavacNode) JCIf(com.sun.tools.javac.tree.JCTree.JCIf) JCCase(com.sun.tools.javac.tree.JCTree.JCCase)

Example 4 with Context

use of com.sun.tools.javac.util.Context in project lombok by rzwitserloot.

the class LombokProcessor method placePostCompileAndDontMakeForceRoundDummiesHook.

private void placePostCompileAndDontMakeForceRoundDummiesHook() {
    stopJavacProcessingEnvironmentFromClosingOurClassloader();
    forceMultipleRoundsInNetBeansEditor();
    Context context = processingEnv.getContext();
    disablePartialReparseInNetBeansEditor(context);
    try {
        Method keyMethod = Context.class.getDeclaredMethod("key", Class.class);
        keyMethod.setAccessible(true);
        Object key = keyMethod.invoke(context, JavaFileManager.class);
        Field htField = Context.class.getDeclaredField("ht");
        htField.setAccessible(true);
        @SuppressWarnings("unchecked") Map<Object, Object> ht = (Map<Object, Object>) htField.get(context);
        final JavaFileManager originalFiler = (JavaFileManager) ht.get(key);
        if (!(originalFiler instanceof InterceptingJavaFileManager)) {
            final Messager messager = processingEnv.getMessager();
            DiagnosticsReceiver receiver = new MessagerDiagnosticsReceiver(messager);
            JavaFileManager newFiler = new InterceptingJavaFileManager(originalFiler, receiver);
            ht.put(key, newFiler);
            Field filerFileManagerField = JavacFiler.class.getDeclaredField("fileManager");
            filerFileManagerField.setAccessible(true);
            filerFileManagerField.set(processingEnv.getFiler(), newFiler);
        }
    } catch (Exception e) {
        throw Lombok.sneakyThrow(e);
    }
}
Also used : Context(com.sun.tools.javac.util.Context) Messager(javax.annotation.processing.Messager) JavaFileManager(javax.tools.JavaFileManager) Method(java.lang.reflect.Method) IOException(java.io.IOException) Field(java.lang.reflect.Field) DiagnosticsReceiver(lombok.core.DiagnosticsReceiver) JavaFileObject(javax.tools.JavaFileObject) Map(java.util.Map) IdentityHashMap(java.util.IdentityHashMap)

Example 5 with Context

use of com.sun.tools.javac.util.Context in project lombok by rzwitserloot.

the class HandleSneakyThrows method buildTryCatchBlock.

public JCStatement buildTryCatchBlock(JavacNode node, List<JCStatement> contents, String exception, JCTree source) {
    JavacTreeMaker maker = node.getTreeMaker();
    Context context = node.getContext();
    JCBlock tryBlock = setGeneratedBy(maker.Block(0, contents), source, context);
    JCExpression varType = chainDots(node, exception.split("\\."));
    JCVariableDecl catchParam = maker.VarDef(maker.Modifiers(Flags.FINAL | Flags.PARAMETER), node.toName("$ex"), varType, null);
    JCExpression lombokLombokSneakyThrowNameRef = chainDots(node, "lombok", "Lombok", "sneakyThrow");
    JCBlock catchBody = maker.Block(0, List.<JCStatement>of(maker.Throw(maker.Apply(List.<JCExpression>nil(), lombokLombokSneakyThrowNameRef, List.<JCExpression>of(maker.Ident(node.toName("$ex")))))));
    JCTry tryStatement = maker.Try(tryBlock, List.of(recursiveSetGeneratedBy(maker.Catch(catchParam, catchBody), source, context)), null);
    if (JavacHandlerUtil.inNetbeansEditor(node)) {
        //set span (start and end position) of the try statement and the main block
        //this allows NetBeans to dive into the statement correctly:
        JCCompilationUnit top = (JCCompilationUnit) node.top().get();
        int startPos = contents.head.pos;
        int endPos = Javac.getEndPosition(contents.last().pos(), top);
        tryBlock.pos = startPos;
        tryStatement.pos = startPos;
        Javac.storeEnd(tryBlock, endPos, top);
        Javac.storeEnd(tryStatement, endPos, top);
    }
    return setGeneratedBy(tryStatement, source, context);
}
Also used : Context(com.sun.tools.javac.util.Context) JCTry(com.sun.tools.javac.tree.JCTree.JCTry) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JCBlock(com.sun.tools.javac.tree.JCTree.JCBlock) JavacTreeMaker(lombok.javac.JavacTreeMaker) JCExpression(com.sun.tools.javac.tree.JCTree.JCExpression) JCVariableDecl(com.sun.tools.javac.tree.JCTree.JCVariableDecl)

Aggregations

Context (com.sun.tools.javac.util.Context)65 JavacFileManager (com.sun.tools.javac.file.JavacFileManager)19 Test (org.junit.Test)9 Options (com.sun.tools.javac.util.Options)8 IOException (java.io.IOException)8 PrintWriter (java.io.PrintWriter)8 JavaFileObject (javax.tools.JavaFileObject)7 ListBuffer (com.sun.tools.javac.util.ListBuffer)6 JavacTask (com.sun.source.util.JavacTask)5 JavacProcessingEnvironment (com.sun.tools.javac.processing.JavacProcessingEnvironment)5 JCCompilationUnit (com.sun.tools.javac.tree.JCTree.JCCompilationUnit)5 JavaFileManager (javax.tools.JavaFileManager)5 OutputStreamWriter (java.io.OutputStreamWriter)4 Path (java.nio.file.Path)4 DiagnosticListener (javax.tools.DiagnosticListener)4 ImmutableList (com.google.common.collect.ImmutableList)3 JavacTaskImpl (com.sun.tools.javac.api.JavacTaskImpl)3 JCExpression (com.sun.tools.javac.tree.JCTree.JCExpression)3 JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)3 StringWriter (java.io.StringWriter)3