Search in sources :

Example 1 with ModifiersTree

use of com.sun.source.tree.ModifiersTree in project error-prone by google.

the class SuggestedFixes method addModifiers.

/** Add modifiers to the given class, method, or field declaration. */
@Nullable
public static SuggestedFix addModifiers(Tree tree, VisitorState state, Modifier... modifiers) {
    ModifiersTree originalModifiers = getModifiers(tree);
    if (originalModifiers == null) {
        return null;
    }
    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();
        java.util.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 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 fix.build();
}
Also used : Arrays(java.util.Arrays) SimpleTypeVisitor8(javax.lang.model.util.SimpleTypeVisitor8) Modifier(javax.lang.model.element.Modifier) TreeScanner(com.sun.tools.javac.tree.TreeScanner) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) AssignmentTree(com.sun.source.tree.AssignmentTree) FluentIterable(com.google.common.collect.FluentIterable) Optional(com.google.common.base.Optional) Map(java.util.Map) NewArrayTree(com.sun.source.tree.NewArrayTree) ASTHelpers.getAnnotationWithSimpleName(com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName) Builder(com.google.errorprone.fixes.SuggestedFix.Builder) ParenthesizedTree(com.sun.source.tree.ParenthesizedTree) ArrayType(javax.lang.model.type.ArrayType) TreePath(com.sun.source.util.TreePath) Function(com.google.common.base.Function) ImmutableSet(com.google.common.collect.ImmutableSet) 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) Sets(com.google.common.collect.Sets) JavacTrees(com.sun.tools.javac.api.JavacTrees) List(java.util.List) Tokens(com.sun.tools.javac.parser.Tokens) ASTHelpers.getAnnotation(com.google.errorprone.util.ASTHelpers.getAnnotation) ModifiersTree(com.sun.source.tree.ModifiersTree) Type(com.sun.tools.javac.code.Type) Joiner(com.google.common.base.Joiner) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) CLASS(com.sun.tools.javac.code.TypeTag.CLASS) Deque(java.util.Deque) 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) 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) 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) TreeMaker(com.sun.tools.javac.tree.TreeMaker) JCTree(com.sun.tools.javac.tree.JCTree) ASSIGNMENT(com.sun.source.tree.Tree.Kind.ASSIGNMENT) TypeMirror(javax.lang.model.type.TypeMirror) TreeMap(java.util.TreeMap) ASTHelpers.getModifiers(com.google.errorprone.util.ASTHelpers.getModifiers) PARENTHESIZED(com.sun.source.tree.Tree.Kind.PARENTHESIZED) DocTree(com.sun.source.doctree.DocTree) ArrayDeque(java.util.ArrayDeque) 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) Nullable(javax.annotation.Nullable)

Example 2 with ModifiersTree

use of com.sun.source.tree.ModifiersTree in project error-prone by google.

the class IncompatibleModifiersChecker method matchAnnotation.

@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
    Set<Modifier> incompatibleModifiers = getIncompatibleModifiers(tree, state);
    if (incompatibleModifiers.isEmpty()) {
        return Description.NO_MATCH;
    }
    Tree parent = state.getPath().getParentPath().getLeaf();
    if (!(parent instanceof ModifiersTree)) {
        // e.g. An annotated package name
        return Description.NO_MATCH;
    }
    Set<Modifier> incompatible = Sets.intersection(incompatibleModifiers, ((ModifiersTree) parent).getFlags());
    if (incompatible.isEmpty()) {
        return Description.NO_MATCH;
    }
    String annotationName = ASTHelpers.getAnnotationName(tree);
    String nameString = annotationName != null ? String.format("The annotation '@%s'", annotationName) : "This annotation";
    String customMessage = String.format(MESSAGE_TEMPLATE, nameString, incompatible.toString());
    return buildDescription(tree).setMessage(customMessage).build();
}
Also used : ModifiersTree(com.sun.source.tree.ModifiersTree) AnnotationTree(com.sun.source.tree.AnnotationTree) ModifiersTree(com.sun.source.tree.ModifiersTree) Tree(com.sun.source.tree.Tree) Modifier(javax.lang.model.element.Modifier)

Example 3 with ModifiersTree

use of com.sun.source.tree.ModifiersTree in project error-prone by google.

the class SuggestedFixes method removeModifiers.

/** Remove modifiers from the given class, method, or field declaration. */
@Nullable
public static Fix removeModifiers(Tree tree, VisitorState state, Modifier... modifiers) {
    Set<Modifier> toRemove = ImmutableSet.copyOf(modifiers);
    ModifiersTree originalModifiers = getModifiers(tree);
    if (originalModifiers == null) {
        return null;
    }
    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 null;
    }
    return 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) Nullable(javax.annotation.Nullable)

Example 4 with ModifiersTree

use of com.sun.source.tree.ModifiersTree in project error-prone by google.

the class RequiredModifiersChecker method matchAnnotation.

@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
    RequiredModifiers annotation = ASTHelpers.getAnnotation(tree, RequiredModifiers.class);
    if (annotation == null) {
        return Description.NO_MATCH;
    }
    Set<Modifier> requiredModifiers = ImmutableSet.copyOf(annotation.value());
    if (requiredModifiers.isEmpty()) {
        return Description.NO_MATCH;
    }
    Tree parent = state.getPath().getParentPath().getLeaf();
    if (!(parent instanceof ModifiersTree)) {
        // e.g. An annotated package name
        return Description.NO_MATCH;
    }
    Set<Modifier> missing = Sets.difference(requiredModifiers, ((ModifiersTree) parent).getFlags());
    if (missing.isEmpty()) {
        return Description.NO_MATCH;
    }
    String annotationName = ASTHelpers.getAnnotationName(tree);
    String nameString = annotationName != null ? String.format("The annotation '@%s'", annotationName) : "This annotation";
    String customMessage = String.format(MESSAGE_TEMPLATE, nameString, missing.toString());
    return buildDescription(tree).setMessage(customMessage).build();
}
Also used : ModifiersTree(com.sun.source.tree.ModifiersTree) AnnotationTree(com.sun.source.tree.AnnotationTree) ModifiersTree(com.sun.source.tree.ModifiersTree) Tree(com.sun.source.tree.Tree) Modifier(javax.lang.model.element.Modifier) RequiredModifiers(com.google.errorprone.annotations.RequiredModifiers)

Aggregations

ModifiersTree (com.sun.source.tree.ModifiersTree)4 AnnotationTree (com.sun.source.tree.AnnotationTree)3 Tree (com.sun.source.tree.Tree)3 Modifier (javax.lang.model.element.Modifier)3 Builder (com.google.errorprone.fixes.SuggestedFix.Builder)2 ErrorProneToken (com.google.errorprone.util.ErrorProneToken)2 Function (com.google.common.base.Function)1 Joiner (com.google.common.base.Joiner)1 Optional (com.google.common.base.Optional)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 VisitorState (com.google.errorprone.VisitorState)1 RequiredModifiers (com.google.errorprone.annotations.RequiredModifiers)1