Java Code Examples for com.sun.tools.javac.util.Log#DiscardDiagnosticHandler

The following examples show how to use com.sun.tools.javac.util.Log#DiscardDiagnosticHandler . 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: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void analyzeLambda(Env<AttrContext> env, JCLambda that, TreeMaker make, boolean speculative) {
    Log.DiagnosticHandler diagHandler = null;
    //we need to disable diagnostics temporarily; the problem is that if
    //a lambda expression contains e.g. an unreachable statement, an error
    //message will be reported and will cause compilation to skip the flow analyis
    //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
    //related errors, which will allow for more errors to be detected
    if (!speculative) {
        diagHandler = new Log.DiscardDiagnosticHandler(log);
    }
    try {
        new LambdaAliveAnalyzer().analyzeTree(env, that, make);
    } finally {
        if (!speculative) {
            log.popDiagnosticHandler(diagHandler);
        }
    }
}
 
Example 2
Source File: Flow.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public List<Type> analyzeLambdaThrownTypes(final Env<AttrContext> env,
        JCLambda that, TreeMaker make) {
    //we need to disable diagnostics temporarily; the problem is that if
    //a lambda expression contains e.g. an unreachable statement, an error
    //message will be reported and will cause compilation to skip the flow analyis
    //step - if we suppress diagnostics, we won't stop at Attr for flow-analysis
    //related errors, which will allow for more errors to be detected
    Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
    try {
        new LambdaAssignAnalyzer(env).analyzeTree(env, that);
        LambdaFlowAnalyzer flowAnalyzer = new LambdaFlowAnalyzer();
        flowAnalyzer.analyzeTree(env, that, make);
        return flowAnalyzer.inferredThrownTypes;
    } finally {
        log.popDiagnosticHandler(diagHandler);
    }
}
 
Example 3
Source File: Check.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Check an annotation value.
 *
 * @param a The annotation tree to check
 * @return true if this annotation tree is valid, otherwise false
 */
public boolean validateAnnotationDeferErrors(JCAnnotation a) {
    boolean res = false;
    final Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
    try {
        res = validateAnnotation(a);
    } finally {
        log.popDiagnosticHandler(diagHandler);
    }
    return res;
}
 
Example 4
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeMirror attributeTree(JavacTaskImpl jti, Tree tree, Scope scope, final List<Diagnostic<? extends JavaFileObject>> errors) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            @Override
            public void report(JCDiagnostic diag) {
                errors.add(diag);
            }            
        };
        NBResolve resolve = NBResolve.instance(jti.getContext());
        resolve.disableAccessibilityChecks();
//        Enter enter = Enter.instance(jti.getContext());
//        enter.shadowTypeEnvs(true);
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
            Attr attr = Attr.instance(jti.getContext());
            Env<AttrContext> env = getEnv(scope);
            if (tree instanceof JCExpression)
                return attr.attribExpr((JCTree) tree,env, Type.noType);
            if (env.tree != null && env.tree.getKind() == Kind.VARIABLE && !VARIABLE_CAN_OWN_VARIABLES) {
                env = env.next;
            }
            return attr.attribStat((JCTree) tree,env);
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
            resolve.restoreAccessbilityChecks();
//            enter.shadowTypeEnvs(false);
        }
    }
 
Example 5
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static Scope attributeTreeTo(JavacTaskImpl jti, Tree tree, Scope scope, Tree to, final List<Diagnostic<? extends JavaFileObject>> errors) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            @Override
            public void report(JCDiagnostic diag) {
                errors.add(diag);
            }            
        };
        NBResolve resolve = NBResolve.instance(jti.getContext());
        resolve.disableAccessibilityChecks();
//        Enter enter = Enter.instance(jti.getContext());
//        enter.shadowTypeEnvs(true);
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
            NBAttr attr = (NBAttr) NBAttr.instance(jti.getContext());
            Env<AttrContext> env = getEnv(scope);
            Env<AttrContext> result = attr.attributeAndCapture((JCTree) tree, env, (JCTree) to);
            try {
                Constructor<JavacScope> c = JavacScope.class.getDeclaredConstructor(Env.class);
                c.setAccessible(true);
                return c.newInstance(result);
            } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                throw new IllegalStateException(ex);
            }
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
            resolve.restoreAccessbilityChecks();
//            enter.shadowTypeEnvs(false);
        }
    }
 
Example 6
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static JCStatement parseStatement(Context context, CharSequence stmt, SourcePositions[] pos, final List<Diagnostic<? extends JavaFileObject>> errors) {
    if (stmt == null || (pos != null && pos.length != 1))
        throw new IllegalArgumentException();
    JavaCompiler compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(new DummyJFO());
    Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
        @Override
        public void report(JCDiagnostic diag) {
            errors.add(diag);
        }            
    };
    try {
        CharBuffer buf = CharBuffer.wrap((stmt+"\u0000").toCharArray(), 0, stmt.length());
        ParserFactory factory = ParserFactory.instance(context);
        ScannerFactory scannerFactory = ScannerFactory.instance(context);
        Names names = Names.instance(context);
        Parser parser = newParser(context, (NBParserFactory) factory, scannerFactory.newScanner(buf, false), false, false, CancelService.instance(context), names);
        if (parser instanceof JavacParser) {
            if (pos != null)
                pos[0] = new ParserSourcePositions((JavacParser)parser);
            return parser.parseStatement();
        }
        return null;
    } finally {
        compiler.log.useSource(prev);
        compiler.log.popDiagnosticHandler(discardHandler);
    }
}
 
Example 7
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static JCExpression parseExpression(Context context, CharSequence expr, boolean onlyFullInput, SourcePositions[] pos, final List<Diagnostic<? extends JavaFileObject>> errors) {
    if (expr == null || (pos != null && pos.length != 1))
        throw new IllegalArgumentException();
    JavaCompiler compiler = JavaCompiler.instance(context);
    JavaFileObject prev = compiler.log.useSource(new DummyJFO());
    Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
        @Override
        public void report(JCDiagnostic diag) {
            errors.add(diag);
        }            
    };
    try {
        CharBuffer buf = CharBuffer.wrap((expr+"\u0000").toCharArray(), 0, expr.length());
        ParserFactory factory = ParserFactory.instance(context);
        ScannerFactory scannerFactory = ScannerFactory.instance(context);
        Names names = Names.instance(context);
        Scanner scanner = scannerFactory.newScanner(buf, false);
        Parser parser = newParser(context, (NBParserFactory) factory, scanner, false, false, CancelService.instance(context), names);
        if (parser instanceof JavacParser) {
            if (pos != null)
                pos[0] = new ParserSourcePositions((JavacParser)parser);
            JCExpression result = parser.parseExpression();

            if (!onlyFullInput || scanner.token().kind == TokenKind.EOF) {
                return result;
            }
        }
        return null;
    } finally {
        compiler.log.useSource(prev);
        compiler.log.popDiagnosticHandler(discardHandler);
    }
}
 
Example 8
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeMirror attributeTree(JavacTaskImpl jti, Tree tree, Scope scope, final List<Diagnostic<? extends JavaFileObject>> errors) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            @Override
            public void report(JCDiagnostic diag) {
                errors.add(diag);
            }            
        };
        NBResolve resolve = NBResolve.instance(jti.getContext());
        resolve.disableAccessibilityChecks();
//        Enter enter = Enter.instance(jti.getContext());
//        enter.shadowTypeEnvs(true);
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
            Attr attr = Attr.instance(jti.getContext());
            Env<AttrContext> env = ((JavacScope) scope).getEnv();
            if (tree instanceof JCExpression)
                return attr.attribExpr((JCTree) tree,env, Type.noType);
            return attr.attribStat((JCTree) tree,env);
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
            resolve.restoreAccessbilityChecks();
//            enter.shadowTypeEnvs(false);
        }
    }
 
Example 9
Source File: Utilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeMirror attributeTree(JavacTaskImpl jti, Tree tree, Scope scope, 
            final List<Diagnostic<? extends JavaFileObject>> errors, @NullAllowed final Diagnostic.Kind filter) {
        Log log = Log.instance(jti.getContext());
        JavaFileObject prev = log.useSource(new DummyJFO());
        Enter enter = Enter.instance(jti.getContext());
        
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(log) {
            private Diagnostic.Kind f = filter == null ? Diagnostic.Kind.ERROR : filter;
            @Override
            public void report(JCDiagnostic diag) {
                if (diag.getKind().compareTo(f) >= 0) {
                    errors.add(diag);
                }
            }            
        };
//        ArgumentAttr argumentAttr = ArgumentAttr.instance(jti.getContext());
//        ArgumentAttr.LocalCacheContext cacheContext = argumentAttr.withLocalCacheContext();
        try {
//            enter.shadowTypeEnvs(true);
            Attr attr = Attr.instance(jti.getContext());
            Env<AttrContext> env = ((JavacScope) scope).getEnv();
            if (tree instanceof JCTree.JCExpression) {
                return attr.attribExpr((JCTree) tree,env, Type.noType);
            }
            return attr.attribStat((JCTree) tree,env);
        } finally {
//            cacheContext.leave();
            log.useSource(prev);
            log.popDiagnosticHandler(discardHandler);
//            enter.shadowTypeEnvs(false);
        }
    }
 
Example 10
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static <T extends Tree> T doParse(JavacTaskImpl task, String text, SourcePositions[] sourcePositions, int offset, Function<Parser, T> actualParse) {
    if (text == null || (sourcePositions != null && sourcePositions.length != 1))
        throw new IllegalArgumentException();
    //use a working init order:
    com.sun.tools.javac.main.JavaCompiler.instance(task.getContext());
    com.sun.tools.javac.tree.TreeMaker jcMaker = com.sun.tools.javac.tree.TreeMaker.instance(task.getContext());
    int oldPos = jcMaker.pos;
    
    try {
        //from org/netbeans/modules/java/hints/spiimpl/Utilities.java:
        Context context = task.getContext();
        JavaCompiler compiler = JavaCompiler.instance(context);
        JavaFileObject prev = compiler.log.useSource(new DummyJFO());
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log) {
            @Override
            public void report(JCDiagnostic diag) {
                //ignore:
            }            
        };
        try {
            CharBuffer buf = CharBuffer.wrap((text+"\u0000").toCharArray(), 0, text.length());
            ParserFactory factory = ParserFactory.instance(context);
            Parser parser = factory.newParser(buf, false, true, false, false);
            if (parser instanceof JavacParser) {
                if (sourcePositions != null)
                    sourcePositions[0] = new ParserSourcePositions((JavacParser)parser, offset);
                return actualParse.apply(parser);
            }
            return null;
        } finally {
            compiler.log.useSource(prev);
            compiler.log.popDiagnosticHandler(discardHandler);
        }
    } finally {
        jcMaker.pos = oldPos;
    }
}
 
Example 11
Source File: Utilities.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static Scope constructScope(CompilationInfo info, Map<String, TypeMirror> constraints, Iterable<? extends String> auxiliaryImports) {
        ScopeDescription desc = new ScopeDescription(constraints, auxiliaryImports);
        Scope result = (Scope) info.getCachedValue(desc);

        if (result != null) return result;
        
        StringBuilder clazz = new StringBuilder();

        clazz.append("package $$;");

        for (String i : auxiliaryImports) {
            clazz.append(i);
        }

        long count = inc++;

        String classname = "$$scopeclass$constraints$" + count;

        clazz.append("public class " + classname + "{");

        for (Entry<String, TypeMirror> e : constraints.entrySet()) {
            if (e.getValue() != null) {
                clazz.append("private ");
                clazz.append(e.getValue().toString()); //XXX
                clazz.append(" ");
                clazz.append(e.getKey());
                clazz.append(";\n");
            }
        }

        clazz.append("private void test() {\n");
        clazz.append("}\n");
        clazz.append("}\n");

        JavacTaskImpl jti = JavaSourceAccessor.getINSTANCE().getJavacTask(info);
        Context context = jti.getContext();
        JavaCompiler compiler = JavaCompiler.instance(context);
        Modules modules = Modules.instance(context);
        Log log = Log.instance(context);
        NBResolve resolve = NBResolve.instance(context);
        Annotate annotate = Annotate.instance(context);
        Names names = Names.instance(context);
        Symtab syms = Symtab.instance(context);
        Log.DiagnosticHandler discardHandler = new Log.DiscardDiagnosticHandler(compiler.log);

        JavaFileObject jfo = FileObjects.memoryFileObject("$", "$", new File("/tmp/$$scopeclass$constraints$" + count + ".java").toURI(), System.currentTimeMillis(), clazz.toString());

        try {
            resolve.disableAccessibilityChecks();
            if (compiler.isEnterDone()) {
                annotate.blockAnnotations();
//                try {
//                    Field f = compiler.getClass().getDeclaredField("enterDone");
//                    f.setAccessible(true);
//                    f.set(compiler, false);
//                } catch (Throwable t) {
//                    Logger.getLogger(Utilities.class.getName()).log(Level.FINE, null, t);
//                }
                //was:
//                compiler.resetEnterDone();
            }
            
            JCCompilationUnit cut = compiler.parse(jfo);
            ClassSymbol enteredClass = syms.enterClass(modules.getDefaultModule(), names.fromString("$$." + classname));
            modules.enter(com.sun.tools.javac.util.List.of(cut), enteredClass);
            compiler.enterTrees(com.sun.tools.javac.util.List.of(cut));

            Todo todo = compiler.todo;
            ListBuffer<Env<AttrContext>> defer = new ListBuffer<Env<AttrContext>>();
            
            while (todo.peek() != null) {
                Env<AttrContext> env = todo.remove();

                if (env.toplevel == cut)
                    compiler.attribute(env);
                else
                    defer = defer.append(env);
            }

            todo.addAll(defer);

            Scope res = new ScannerImpl().scan(cut, info);

            info.putCachedValue(desc, res, CacheClearPolicy.ON_SIGNATURE_CHANGE);

            return res;
        } finally {
            resolve.restoreAccessbilityChecks();
            log.popDiagnosticHandler(discardHandler);
        }
    }