Search in sources :

Example 1 with ErrorProneToken

use of com.google.errorprone.util.ErrorProneToken in project error-prone by google.

the class MixedArrayDimensions method checkArrayDimensions.

private Description checkArrayDimensions(Tree tree, Tree type, VisitorState state) {
    if (!(type instanceof ArrayTypeTree)) {
        return NO_MATCH;
    }
    CharSequence source = state.getSourceCode();
    for (; type instanceof ArrayTypeTree; type = ((ArrayTypeTree) type).getType()) {
        Tree elemType = ((ArrayTypeTree) type).getType();
        int start = state.getEndPosition(elemType);
        int end = state.getEndPosition(type);
        if (start >= end) {
            continue;
        }
        String dim = source.subSequence(start, end).toString();
        if (dim.isEmpty()) {
            continue;
        }
        ImmutableList<ErrorProneToken> tokens = ErrorProneTokens.getTokens(dim.trim(), state.context);
        if (tokens.size() > 2 && tokens.get(0).kind() == TokenKind.IDENTIFIER) {
            int nonWhitespace = CharMatcher.isNot(' ').indexIn(dim);
            int idx = dim.indexOf("[]", nonWhitespace);
            if (idx > nonWhitespace) {
                String replacement = dim.substring(idx, dim.length()) + dim.substring(0, idx);
                return describeMatch(tree, SuggestedFix.replace(start, end, replacement));
            }
        }
    }
    return NO_MATCH;
}
Also used : ErrorProneToken(com.google.errorprone.util.ErrorProneToken) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) Tree(com.sun.source.tree.Tree) ArrayTypeTree(com.sun.source.tree.ArrayTypeTree)

Example 2 with ErrorProneToken

use of com.google.errorprone.util.ErrorProneToken in project error-prone by google.

the class BooleanParameter method matchMethodInvocation.

@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
    List<? extends ExpressionTree> arguments = tree.getArguments();
    if (arguments.size() < 2) {
        // single-argument methods are often self-documentating
        return NO_MATCH;
    }
    if (arguments.stream().noneMatch(BooleanParameter::isBooleanLiteral)) {
        return NO_MATCH;
    }
    MethodSymbol sym = ASTHelpers.getSymbol(tree);
    if (NamedParameterComment.containsSyntheticParameterName(sym)) {
        return NO_MATCH;
    }
    int start = ((JCTree) tree).getStartPosition();
    int end = state.getEndPosition(getLast(tree.getArguments()));
    String source = state.getSourceCode().subSequence(start, end).toString();
    Deque<ErrorProneToken> tokens = new ArrayDeque<>(ErrorProneTokens.getTokens(source, state.context));
    forEachPair(sym.getParameters().stream(), arguments.stream(), (p, c) -> checkParameter(p, c, start, tokens, state));
    return NO_MATCH;
}
Also used : MethodSymbol(com.sun.tools.javac.code.Symbol.MethodSymbol) ErrorProneToken(com.google.errorprone.util.ErrorProneToken) JCTree(com.sun.tools.javac.tree.JCTree) ArrayDeque(java.util.ArrayDeque)

Example 3 with ErrorProneToken

use of com.google.errorprone.util.ErrorProneToken in project error-prone by google.

the class SuggestedFixes method addModifiers.

/**
 * Adds modifiers to the given class, method, or field declaration.
 */
public static Optional<SuggestedFix> addModifiers(Tree tree, VisitorState state, Modifier... modifiers) {
    ModifiersTree originalModifiers = getModifiers(tree);
    if (originalModifiers == null) {
        return Optional.empty();
    }
    Set<Modifier> toAdd = Sets.difference(new TreeSet<>(Arrays.asList(modifiers)), originalModifiers.getFlags());
    if (originalModifiers.getFlags().isEmpty()) {
        int pos = state.getEndPosition(originalModifiers) != Position.NOPOS ? state.getEndPosition(originalModifiers) + 1 : ((JCTree) tree).getStartPosition();
        int base = ((JCTree) tree).getStartPosition();
        Optional<Integer> insert = state.getTokensForNode(tree).stream().map(token -> token.pos() + base).filter(thisPos -> thisPos >= pos).findFirst();
        // shouldn't ever be able to get to the else
        int insertPos = insert.orElse(pos);
        return Optional.of(SuggestedFix.replace(insertPos, insertPos, Joiner.on(' ').join(toAdd) + " "));
    }
    // a map from modifiers to modifier position (or -1 if the modifier is being added)
    // modifiers are sorted in Google Java Style order
    Map<Modifier, Integer> modifierPositions = new TreeMap<>();
    for (Modifier mod : toAdd) {
        modifierPositions.put(mod, -1);
    }
    List<ErrorProneToken> tokens = state.getTokensForNode(originalModifiers);
    int base = ((JCTree) originalModifiers).getStartPosition();
    for (ErrorProneToken tok : tokens) {
        Modifier mod = getTokModifierKind(tok);
        if (mod != null) {
            modifierPositions.put(mod, base + tok.pos());
        }
    }
    SuggestedFix.Builder fix = SuggestedFix.builder();
    // walk the map of all modifiers, and accumulate a list of new modifiers to insert
    // beside an existing modifier
    List<Modifier> modifiersToWrite = new ArrayList<>();
    for (Modifier mod : modifierPositions.keySet()) {
        int p = modifierPositions.get(mod);
        if (p == -1) {
            modifiersToWrite.add(mod);
        } else if (!modifiersToWrite.isEmpty()) {
            fix.replace(p, p, Joiner.on(' ').join(modifiersToWrite) + " ");
            modifiersToWrite.clear();
        }
    }
    if (!modifiersToWrite.isEmpty()) {
        fix.postfixWith(originalModifiers, " " + Joiner.on(' ').join(modifiersToWrite));
    }
    return Optional.of(fix.build());
}
Also used : BoundKind(com.sun.tools.javac.code.BoundKind) Arrays(java.util.Arrays) SimpleTypeVisitor8(javax.lang.model.util.SimpleTypeVisitor8) Modifier(javax.lang.model.element.Modifier) JavaFileManager(javax.tools.JavaFileManager) TreeScanner(com.sun.tools.javac.tree.TreeScanner) JavacTaskImpl(com.sun.tools.javac.api.JavacTaskImpl) ImportOrganizer(com.google.errorprone.apply.ImportOrganizer) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) AssignmentTree(com.sun.source.tree.AssignmentTree) FluentIterable(com.google.common.collect.FluentIterable) CharStreams(com.google.common.io.CharStreams) Diagnostic(javax.tools.Diagnostic) Map(java.util.Map) NewArrayTree(com.sun.source.tree.NewArrayTree) ASTHelpers.getAnnotationWithSimpleName(com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName) DiagnosticCollector(javax.tools.DiagnosticCollector) Builder(com.google.errorprone.fixes.SuggestedFix.Builder) ArrayType(javax.lang.model.type.ArrayType) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) TreePath(com.sun.source.util.TreePath) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) JavacTask(com.sun.source.util.JavacTask) Collection(java.util.Collection) Position(com.sun.tools.javac.util.Position) ASTHelpers.getSymbol(com.google.errorprone.util.ASTHelpers.getSymbol) Symbol(com.sun.tools.javac.code.Symbol) Set(java.util.Set) Iterables.getLast(com.google.common.collect.Iterables.getLast) DocTreePath(com.sun.source.util.DocTreePath) Collectors.joining(java.util.stream.Collectors.joining) Sets(com.google.common.collect.Sets) JCCompilationUnit(com.sun.tools.javac.tree.JCTree.JCCompilationUnit) JavaFileObject(javax.tools.JavaFileObject) ErrorProneTokens(com.google.errorprone.util.ErrorProneTokens) JavacTrees(com.sun.tools.javac.api.JavacTrees) List(java.util.List) Arguments(com.sun.tools.javac.main.Arguments) Tokens(com.sun.tools.javac.parser.Tokens) ASTHelpers.getAnnotation(com.google.errorprone.util.ASTHelpers.getAnnotation) ModifiersTree(com.sun.source.tree.ModifiersTree) Optional(java.util.Optional) Context(com.sun.tools.javac.util.Context) Type(com.sun.tools.javac.code.Type) Joiner(com.google.common.base.Joiner) TokenKind(com.sun.tools.javac.parser.Tokens.TokenKind) Kind(javax.tools.JavaFileObject.Kind) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) DefaultTypeVisitor(com.sun.tools.javac.code.Types.DefaultTypeVisitor) VariableTree(com.sun.source.tree.VariableTree) CLASS(com.sun.tools.javac.code.TypeTag.CLASS) Deque(java.util.Deque) DescriptionBasedDiff(com.google.errorprone.apply.DescriptionBasedDiff) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) VisitorState(com.google.errorprone.VisitorState) Lists(com.google.common.collect.Lists) ImmutableList(com.google.common.collect.ImmutableList) JavacTool(com.sun.tools.javac.api.JavacTool) DeclaredType(javax.lang.model.type.DeclaredType) Predicates(com.google.common.base.Predicates) NEW_ARRAY(com.sun.source.tree.Tree.Kind.NEW_ARRAY) StreamSupport(java.util.stream.StreamSupport) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) Nullable(javax.annotation.Nullable) FindIdentifiers(com.google.errorprone.util.FindIdentifiers) ErrorProneToken(com.google.errorprone.util.ErrorProneToken) ElementKind(javax.lang.model.element.ElementKind) ExpressionTree(com.sun.source.tree.ExpressionTree) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) DCTree(com.sun.tools.javac.tree.DCTree) IOException(java.io.IOException) JCTree(com.sun.tools.javac.tree.JCTree) KindSelector(com.sun.tools.javac.code.Kinds.KindSelector) ASSIGNMENT(com.sun.source.tree.Tree.Kind.ASSIGNMENT) SourceFile(com.google.errorprone.apply.SourceFile) TypeMirror(javax.lang.model.type.TypeMirror) TreeMap(java.util.TreeMap) ASTHelpers.getModifiers(com.google.errorprone.util.ASTHelpers.getModifiers) DocTree(com.sun.source.doctree.DocTree) ArrayDeque(java.util.ArrayDeque) ASTHelpers(com.google.errorprone.util.ASTHelpers) Options(com.sun.tools.javac.util.Options) ModifiersTree(com.sun.source.tree.ModifiersTree) ArrayList(java.util.ArrayList) JCTree(com.sun.tools.javac.tree.JCTree) TreeMap(java.util.TreeMap) ErrorProneToken(com.google.errorprone.util.ErrorProneToken) Builder(com.google.errorprone.fixes.SuggestedFix.Builder) Modifier(javax.lang.model.element.Modifier)

Example 4 with ErrorProneToken

use of com.google.errorprone.util.ErrorProneToken in project error-prone by google.

the class SuggestedFixes method renameMethod.

/**
 * Be warned, only changes method name at the declaration.
 */
public static SuggestedFix renameMethod(MethodTree tree, final String replacement, VisitorState state) {
    // Search tokens from beginning of method tree to beginning of method body.
    int basePos = ((JCTree) tree).getStartPosition();
    int endPos = tree.getBody() != null ? ((JCTree) tree.getBody()).getStartPosition() : state.getEndPosition(tree);
    List<ErrorProneToken> methodTokens = ErrorProneTokens.getTokens(state.getSourceCode().subSequence(basePos, endPos).toString(), state.context);
    for (ErrorProneToken token : methodTokens) {
        if (token.kind() == TokenKind.IDENTIFIER && token.name().equals(tree.getName())) {
            int nameStartPosition = basePos + token.pos();
            int nameEndPosition = basePos + token.endPos();
            return SuggestedFix.builder().replace(nameStartPosition, nameEndPosition, replacement).build();
        }
    }
    // Method name not found.
    throw new AssertionError();
}
Also used : ErrorProneToken(com.google.errorprone.util.ErrorProneToken) JCTree(com.sun.tools.javac.tree.JCTree)

Example 5 with ErrorProneToken

use of com.google.errorprone.util.ErrorProneToken in project error-prone by google.

the class SuggestedFixes method removeModifiers.

/**
 * Remove modifiers from the given class, method, or field declaration.
 */
public static Optional<SuggestedFix> removeModifiers(Tree tree, VisitorState state, Modifier... modifiers) {
    Set<Modifier> toRemove = ImmutableSet.copyOf(modifiers);
    ModifiersTree originalModifiers = getModifiers(tree);
    if (originalModifiers == null) {
        return Optional.empty();
    }
    SuggestedFix.Builder fix = SuggestedFix.builder();
    List<ErrorProneToken> tokens = state.getTokensForNode(originalModifiers);
    int basePos = ((JCTree) originalModifiers).getStartPosition();
    boolean empty = true;
    for (ErrorProneToken tok : tokens) {
        Modifier mod = getTokModifierKind(tok);
        if (toRemove.contains(mod)) {
            empty = false;
            fix.replace(basePos + tok.pos(), basePos + tok.endPos() + 1, "");
            break;
        }
    }
    if (empty) {
        return Optional.empty();
    }
    return Optional.of(fix.build());
}
Also used : ModifiersTree(com.sun.source.tree.ModifiersTree) ErrorProneToken(com.google.errorprone.util.ErrorProneToken) JCTree(com.sun.tools.javac.tree.JCTree) Builder(com.google.errorprone.fixes.SuggestedFix.Builder) Modifier(javax.lang.model.element.Modifier)

Aggregations

ErrorProneToken (com.google.errorprone.util.ErrorProneToken)6 JCTree (com.sun.tools.javac.tree.JCTree)5 ArrayDeque (java.util.ArrayDeque)3 Builder (com.google.errorprone.fixes.SuggestedFix.Builder)2 MethodTree (com.sun.source.tree.MethodTree)2 ModifiersTree (com.sun.source.tree.ModifiersTree)2 Tree (com.sun.source.tree.Tree)2 VariableTree (com.sun.source.tree.VariableTree)2 Function (com.google.common.base.Function)1 Joiner (com.google.common.base.Joiner)1 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)1 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 Predicates (com.google.common.base.Predicates)1 FluentIterable (com.google.common.collect.FluentIterable)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Iterables.getLast (com.google.common.collect.Iterables.getLast)1 Lists (com.google.common.collect.Lists)1 Sets (com.google.common.collect.Sets)1 CharStreams (com.google.common.io.CharStreams)1