Search in sources :

Example 11 with Context

use of com.sun.tools.javac.util.Context in project error-prone by google.

the class ErrorProneJavacPlugin method init.

@Override
public void init(JavacTask javacTask, String... args) {
    Context context = ((BasicJavacTask) javacTask).getContext();
    BaseErrorProneJavaCompiler.setupMessageBundle(context);
    javacTask.addTaskListener(ErrorProneAnalyzer.createByScanningForPlugins(BuiltInCheckerSuppliers.defaultChecks(), ErrorProneOptions.processArgs(args), context));
}
Also used : Context(com.sun.tools.javac.util.Context) BasicJavacTask(com.sun.tools.javac.api.BasicJavacTask)

Example 12 with Context

use of com.sun.tools.javac.util.Context in project error-prone by google.

the class ErrorProneAnalyzer method finished.

@Override
public void finished(TaskEvent taskEvent) {
    if (taskEvent.getKind() != Kind.ANALYZE) {
        return;
    }
    if (JavaCompiler.instance(context).errorCount() > 0) {
        return;
    }
    TreePath path = JavacTrees.instance(context).getPath(taskEvent.getTypeElement());
    if (path == null) {
        path = new TreePath(taskEvent.getCompilationUnit());
    }
    // Assert that the event is unique and scan the current tree.
    verify(seen.add(path.getLeaf()), "Duplicate FLOW event for: %s", taskEvent.getTypeElement());
    Context subContext = new SubContext(context);
    subContext.put(ErrorProneOptions.class, errorProneOptions);
    Log log = Log.instance(context);
    JCCompilationUnit compilation = (JCCompilationUnit) path.getCompilationUnit();
    DescriptionListener descriptionListener = descriptionListenerFactory.getDescriptionListener(log, compilation);
    try {
        if (path.getLeaf().getKind() == Tree.Kind.COMPILATION_UNIT) {
            // We only get TaskEvents for compilation units if they contain no package declarations
            // (e.g. package-info.java files).  In this case it's safe to analyze the
            // CompilationUnitTree immediately.
            transformer.get().apply(path, subContext, descriptionListener);
        } else if (finishedCompilation(path.getCompilationUnit())) {
            // Otherwise this TaskEvent is for a ClassTree, and we can scan the whole
            // CompilationUnitTree once we've seen all the enclosed classes.
            transformer.get().apply(new TreePath(compilation), subContext, descriptionListener);
        }
    } catch (ErrorProneError e) {
        e.logFatalError(log);
        // terminate with Result.ABNORMAL
        throw e;
    } catch (CompletionFailure e) {
        // A CompletionFailure can be triggered when error-prone tries to complete a symbol
        // that isn't on the compilation classpath. This can occur when a check performs an
        // instanceof test on a symbol, which requires inspecting the transitive closure of the
        // symbol's supertypes. If javac didn't need to check the symbol's assignability
        // then a normal compilation would have succeeded, and no diagnostics will have been
        // reported yet, but we don't want to crash javac.
        log.error("proc.cant.access", e.sym, e.getDetailValue(), Throwables.getStackTraceAsString(e));
    }
}
Also used : Context(com.sun.tools.javac.util.Context) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) TreePath(com.sun.source.util.TreePath) Log(com.sun.tools.javac.util.Log) CompletionFailure(com.sun.tools.javac.code.Symbol.CompletionFailure)

Example 13 with Context

use of com.sun.tools.javac.util.Context in project error-prone by google.

the class BugCheckerRefactoringTestHelper method runTestOnPair.

private void runTestOnPair(JavaFileObject input, JavaFileObject output, TestMode testMode) throws IOException {
    Context context = new Context();
    JCCompilationUnit tree = doCompile(input, sources.keySet(), context);
    JavaFileObject transformed = applyDiff(input, context, tree);
    testMode.verifyMatch(transformed, output);
    if (!allowBreakingChanges) {
        doCompile(output, sources.values(), new Context());
    }
}
Also used : Context(com.sun.tools.javac.util.Context) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JavaFileObject(javax.tools.JavaFileObject)

Example 14 with Context

use of com.sun.tools.javac.util.Context in project error-prone by google.

the class BlockTemplate method replace.

@Override
public Fix replace(BlockTemplateMatch match) {
    checkNotNull(match);
    SuggestedFix.Builder fix = SuggestedFix.builder();
    Inliner inliner = match.createInliner();
    Context context = inliner.getContext();
    if (annotations().containsKey(UseImportPolicy.class)) {
        ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value());
    } else {
        ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL);
    }
    ImmutableList<JCStatement> targetStatements = match.getStatements();
    try {
        ImmutableList.Builder<JCStatement> inlinedStatementsBuilder = ImmutableList.builder();
        for (UStatement statement : templateStatements()) {
            inlinedStatementsBuilder.addAll(statement.inlineStatements(inliner));
        }
        ImmutableList<JCStatement> inlinedStatements = inlinedStatementsBuilder.build();
        int nInlined = inlinedStatements.size();
        int nTargets = targetStatements.size();
        if (nInlined <= nTargets) {
            for (int i = 0; i < nInlined; i++) {
                fix.replace(targetStatements.get(i), printStatement(context, inlinedStatements.get(i)));
            }
            for (int i = nInlined; i < nTargets; i++) {
                fix.delete(targetStatements.get(i));
            }
        } else {
            for (int i = 0; i < nTargets - 1; i++) {
                fix.replace(targetStatements.get(i), printStatement(context, inlinedStatements.get(i)));
            }
            int last = nTargets - 1;
            ImmutableList<JCStatement> remainingInlined = inlinedStatements.subList(last, nInlined);
            fix.replace(targetStatements.get(last), CharMatcher.whitespace().trimTrailingFrom(printStatements(context, remainingInlined)));
        }
    } catch (CouldNotResolveImportException e) {
        logger.log(SEVERE, "Failure to resolve import in replacement", e);
    }
    return addImports(inliner, fix);
}
Also used : Context(com.sun.tools.javac.util.Context) SuggestedFix(com.google.errorprone.fixes.SuggestedFix) ImmutableList(com.google.common.collect.ImmutableList) JCStatement(com.sun.tools.javac.tree.JCTree.JCStatement)

Example 15 with Context

use of com.sun.tools.javac.util.Context in project error-prone by google.

the class UTemplater method createTemplate.

/**
   * Returns a template based on a method. One-line methods starting with a {@code return} statement
   * are guessed to be expression templates, and all other methods are guessed to be block
   * templates.
   */
public static Template<?> createTemplate(Context context, MethodTree decl) {
    MethodSymbol declSym = ASTHelpers.getSymbol(decl);
    ImmutableClassToInstanceMap<Annotation> annotations = UTemplater.annotationMap(declSym);
    ImmutableMap<String, VarSymbol> freeExpressionVars = freeExpressionVariables(decl);
    Context subContext = new SubContext(context);
    final UTemplater templater = new UTemplater(freeExpressionVars, subContext);
    ImmutableMap<String, UType> expressionVarTypes = ImmutableMap.copyOf(Maps.transformValues(freeExpressionVars, new Function<VarSymbol, UType>() {

        @Override
        public UType apply(VarSymbol sym) {
            return templater.template(sym.type);
        }
    }));
    UType genericType = templater.template(declSym.type);
    List<UTypeVar> typeParameters;
    UMethodType methodType;
    if (genericType instanceof UForAll) {
        UForAll forAllType = (UForAll) genericType;
        typeParameters = forAllType.getTypeVars();
        methodType = (UMethodType) forAllType.getQuantifiedType();
    } else if (genericType instanceof UMethodType) {
        typeParameters = ImmutableList.of();
        methodType = (UMethodType) genericType;
    } else {
        throw new IllegalArgumentException("Expected genericType to be either a ForAll or a UMethodType, but was " + genericType);
    }
    List<? extends StatementTree> bodyStatements = decl.getBody().getStatements();
    if (bodyStatements.size() == 1 && Iterables.getOnlyElement(bodyStatements).getKind() == Kind.RETURN && context.get(REQUIRE_BLOCK_KEY) == null) {
        ExpressionTree expression = ((ReturnTree) Iterables.getOnlyElement(bodyStatements)).getExpression();
        return ExpressionTemplate.create(annotations, typeParameters, expressionVarTypes, templater.template(expression), methodType.getReturnType());
    } else {
        List<UStatement> templateStatements = new ArrayList<>();
        for (StatementTree statement : bodyStatements) {
            templateStatements.add(templater.template(statement));
        }
        return BlockTemplate.create(annotations, typeParameters, expressionVarTypes, templateStatements);
    }
}
Also used : Context(com.sun.tools.javac.util.Context) SubContext(com.google.errorprone.SubContext) ArrayList(java.util.ArrayList) VarSymbol(com.sun.tools.javac.code.Symbol.VarSymbol) ReturnTree(com.sun.source.tree.ReturnTree) Annotation(java.lang.annotation.Annotation) ExpressionStatementTree(com.sun.source.tree.ExpressionStatementTree) LabeledStatementTree(com.sun.source.tree.LabeledStatementTree) StatementTree(com.sun.source.tree.StatementTree) EmptyStatementTree(com.sun.source.tree.EmptyStatementTree) Function(com.google.common.base.Function) MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) SubContext(com.google.errorprone.SubContext) LambdaExpressionTree(com.sun.source.tree.LambdaExpressionTree) ConditionalExpressionTree(com.sun.source.tree.ConditionalExpressionTree) ExpressionTree(com.sun.source.tree.ExpressionTree)

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