repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/OperatorPrecedence.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.util; import com.sun.source.tree.Tree; /** * The precedence for an operator kind in the {@link com.sun.source.tree} API. * * <p>As documented at: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html */ public enum OperatorPrecedence { POSTFIX(13), UNARY(12), MULTIPLICATIVE(11), ADDITIVE(10), SHIFT(9), RELATIONAL(8), EQUALITY(7), AND(6), XOR(5), OR(4), CONDITIONAL_AND(3), CONDITIONAL_OR(2), TERNARY(1), ASSIGNMENT(0); private final int precedence; OperatorPrecedence(int precedence) { this.precedence = precedence; } public boolean isHigher(OperatorPrecedence other) { return precedence > other.precedence; } public static OperatorPrecedence from(Tree.Kind kind) { switch (kind) { case POSTFIX_DECREMENT: case POSTFIX_INCREMENT: return OperatorPrecedence.POSTFIX; case PREFIX_DECREMENT: case PREFIX_INCREMENT: return OperatorPrecedence.UNARY; case MULTIPLY: case DIVIDE: case REMAINDER: return OperatorPrecedence.MULTIPLICATIVE; case PLUS: case MINUS: return OperatorPrecedence.ADDITIVE; case RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT: case LEFT_SHIFT: return OperatorPrecedence.SHIFT; case LESS_THAN: case LESS_THAN_EQUAL: case GREATER_THAN: case GREATER_THAN_EQUAL: case INSTANCE_OF: return OperatorPrecedence.RELATIONAL; case EQUAL_TO: case NOT_EQUAL_TO: return OperatorPrecedence.EQUALITY; case AND: return OperatorPrecedence.AND; case XOR: return OperatorPrecedence.XOR; case OR: return OperatorPrecedence.OR; case CONDITIONAL_AND: return OperatorPrecedence.CONDITIONAL_AND; case CONDITIONAL_OR: return OperatorPrecedence.CONDITIONAL_OR; case ASSIGNMENT: case MULTIPLY_ASSIGNMENT: case DIVIDE_ASSIGNMENT: case REMAINDER_ASSIGNMENT: case PLUS_ASSIGNMENT: case MINUS_ASSIGNMENT: case LEFT_SHIFT_ASSIGNMENT: case AND_ASSIGNMENT: case XOR_ASSIGNMENT: case OR_ASSIGNMENT: case RIGHT_SHIFT_ASSIGNMENT: case UNSIGNED_RIGHT_SHIFT_ASSIGNMENT: return OperatorPrecedence.ASSIGNMENT; default: throw new IllegalArgumentException("Unexpected operator kind: " + kind); } } }
3,024
27.009259
95
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/util/Signatures.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.util; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.stream.Collectors.joining; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.code.Types.DefaultTypeVisitor; import com.sun.tools.javac.code.Types.SignatureGenerator; import com.sun.tools.javac.util.Name; import java.util.Arrays; /** Signature generation. */ public final class Signatures { /** Returns the binary names of the class. */ public static String classDescriptor(Type type, Types types) { SigGen sig = new SigGen(types); sig.assembleClassSig(types.erasure(type)); return sig.toString(); } /** Returns a JVMS 4.3.3 method descriptor. */ public static String descriptor(Type type, Types types) { SigGen sig = new SigGen(types); sig.assembleSig(types.erasure(type)); return sig.toString(); } private static class SigGen extends SignatureGenerator { private final com.sun.tools.javac.util.ByteBuffer buffer = new com.sun.tools.javac.util.ByteBuffer(); protected SigGen(Types types) { super(types); } @Override protected void append(char ch) { buffer.appendByte(ch); } @Override protected void append(byte[] ba) { buffer.appendBytes(ba); } @Override protected void append(Name name) { buffer.appendName(name); } @Override public String toString() { // We could use buffer.toName(Names), but we want a string anyways and this // avoids plumbing a Context or instances of Names through. // Names always uses UTF-8 internally. return new String(Arrays.copyOf(buffer.elems, buffer.length), UTF_8); } } /** * Pretty-prints a method signature for use in diagnostics. * * <p>Uses simple names for declared types, and omitting formal type parameters and the return * type since they do not affect overload resolution. */ public static String prettyMethodSignature(ClassSymbol origin, MethodSymbol m) { StringBuilder sb = new StringBuilder(); if (m.isConstructor()) { Name name = m.owner.enclClass().getSimpleName(); if (name.isEmpty()) { // use the superclass name of anonymous classes name = m.owner.enclClass().getSuperclass().asElement().getSimpleName(); } sb.append(name); } else { if (!m.owner.equals(origin)) { sb.append(m.owner.getSimpleName()).append('.'); } sb.append(m.getSimpleName()); } sb.append( m.getParameters().stream() .map(v -> v.type.accept(PRETTY_TYPE_VISITOR, null)) .collect(joining(", ", "(", ")"))); return sb.toString(); } /** Pretty-prints a Type for use in diagnostics, using simple names for class types */ public static String prettyType(Type type) { return type.accept(PRETTY_TYPE_VISITOR, null); } private static final Type.Visitor<String, Void> PRETTY_TYPE_VISITOR = new DefaultTypeVisitor<String, Void>() { @Override public String visitWildcardType(Type.WildcardType t, Void unused) { StringBuilder sb = new StringBuilder(); sb.append(t.kind); if (t.kind != BoundKind.UNBOUND) { sb.append(t.type.accept(this, null)); } return sb.toString(); } @Override public String visitClassType(Type.ClassType t, Void s) { StringBuilder sb = new StringBuilder(); sb.append(t.tsym.getSimpleName()); if (t.getTypeArguments().nonEmpty()) { sb.append('<'); sb.append( t.getTypeArguments().stream() .map(a -> a.accept(this, null)) .collect(joining(", "))); sb.append(">"); } return sb.toString(); } @Override public String visitCapturedType(Type.CapturedType t, Void s) { return t.wildcard.accept(this, null); } @Override public String visitArrayType(Type.ArrayType t, Void unused) { return t.elemtype.accept(this, null) + "[]"; } @Override public String visitType(Type t, Void s) { return t.toString(); } }; private Signatures() {} }
5,073
30.7125
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/IndexedPosition.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import static com.google.common.base.Preconditions.checkArgument; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** Describes a position that only has a start and end index. */ public class IndexedPosition implements DiagnosticPosition { final int startPos; final int endPos; public IndexedPosition(int startPos, int endPos) { checkArgument(startPos >= 0, "Start [%s] should not be less than zero", startPos); checkArgument(startPos <= endPos, "Start [%s] should not be after end [%s]", startPos, endPos); this.startPos = startPos; this.endPos = endPos; } @Override public JCTree getTree() { throw new UnsupportedOperationException(); } @Override public int getStartPosition() { return startPos; } @Override public int getPreferredPosition() { throw new UnsupportedOperationException(); } @Override public int getEndPosition(EndPosTable endPosTable) { return endPos; } }
1,694
28.224138
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/package-info.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** Support code for providing automated corrections for defects we find. */ package com.google.errorprone.fixes;
723
37.105263
76
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/AppliedFix.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.sun.tools.javac.tree.EndPosTable; import java.util.Set; import javax.annotation.Nullable; /** * Represents the corrected source which we think was intended, by applying a Fix. This is used to * generate the "Did you mean?" snippet in the error message. * * @author alexeagle@google.com (Alex Eagle) */ public class AppliedFix { private final String snippet; private final boolean isRemoveLine; private AppliedFix(String snippet, boolean isRemoveLine) { this.snippet = snippet; this.isRemoveLine = isRemoveLine; } public CharSequence getNewCodeSnippet() { return snippet; } public boolean isRemoveLine() { return isRemoveLine; } public static class Applier { private final CharSequence source; private final EndPosTable endPositions; public Applier(CharSequence source, EndPosTable endPositions) { this.source = source; this.endPositions = endPositions; } /** * Applies the suggestedFix to the source. Returns null if applying the fix results in no change * to the source, or a change only to imports. */ @Nullable public AppliedFix apply(Fix suggestedFix) { // We apply the replacements in ascending order here. Descending is simpler, since applying a // replacement can't change the index for future replacements, but it leads to quadratic // copying behavior as we constantly shift the tail of the file around in our StringBuilder. ImmutableSet<Replacement> replacements = ascending(suggestedFix.getReplacements(endPositions)); if (replacements.isEmpty()) { return null; } StringBuilder replaced = new StringBuilder(); int positionInOriginal = 0; for (Replacement repl : replacements) { checkArgument( repl.endPosition() <= source.length(), "End [%s] should not exceed source length [%s]", repl.endPosition(), source.length()); // Write the unmodified content leading up to this change replaced.append(source, positionInOriginal, repl.startPosition()); // And the modified content for this change replaced.append(repl.replaceWith()); // Then skip everything from source between start and end positionInOriginal = repl.endPosition(); } // Flush out any remaining content after the final change replaced.append(source, positionInOriginal, source.length()); // Find the changed line containing the first edit String snippet = firstEditedLine(replaced, Iterables.get(replacements, 0)); if (snippet.isEmpty()) { return new AppliedFix("to remove this line", /* isRemoveLine= */ true); } return new AppliedFix(snippet, /* isRemoveLine= */ false); } /** Get the replacements in an appropriate order to apply correctly. */ private static ImmutableSet<Replacement> ascending(Set<Replacement> set) { Replacements replacements = new Replacements(); set.forEach(replacements::add); return replacements.ascending(); } /** * Finds the full text of the first line that's changed. In this case "line" means "bracketed by * \n characters". We don't handle \r\n specially, because the strings that javac provides to * Error Prone have already been transformed from platform line endings to newlines (and even if * it didn't, the dangling \r characters would be handled by a trim() call). */ private static String firstEditedLine(StringBuilder content, Replacement firstEdit) { // We subtract 1 here because we want to find the first newline *before* the edit, not one // at its beginning. int startOfFirstEditedLine = content.lastIndexOf("\n", firstEdit.startPosition() - 1); int endOfFirstEditedLine = content.indexOf("\n", firstEdit.startPosition()); if (startOfFirstEditedLine == -1) { startOfFirstEditedLine = 0; // Change to start of file with no preceding newline } if (endOfFirstEditedLine == -1) { // Change to last line of file endOfFirstEditedLine = content.length(); } String snippet = content.substring(startOfFirstEditedLine, endOfFirstEditedLine); snippet = snippet.trim(); if (snippet.contains("//")) { snippet = snippet.substring(0, snippet.indexOf("//")).trim(); } return snippet; } } public static Applier fromSource(CharSequence source, EndPosTable endPositions) { return new Applier(source, endPositions); } }
5,359
37.561151
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/Replacement.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import static com.google.common.base.Preconditions.checkArgument; import com.google.auto.value.AutoValue; import com.google.common.collect.Range; /** A replaced section of a source file. */ @AutoValue public abstract class Replacement { /** * Creates a {@link Replacement}. Start and end positions are represented as code unit indices in * a Unicode 16-bit string. * * @param startPosition the beginning of the replacement * @param endPosition the end of the replacement, exclusive * @param replaceWith the replacement text */ public static Replacement create(int startPosition, int endPosition, String replaceWith) { checkArgument( startPosition >= 0 && startPosition <= endPosition, "invalid replacement: [%s, %s) (%s)", startPosition, endPosition, replaceWith); return new AutoValue_Replacement(Range.closedOpen(startPosition, endPosition), replaceWith); } /** The beginning of the replacement range. */ public int startPosition() { return range().lowerEndpoint(); } /** The length of the input text to be replaced. */ public int length() { return endPosition() - startPosition(); } /** The end of the replacement range, exclusive. */ public int endPosition() { return range().upperEndpoint(); } /** The {@link Range} to be replaced. */ public abstract Range<Integer> range(); /** The source text to appear in the output. */ public abstract String replaceWith(); /** Creates a new replacement at the same range with different text. */ Replacement withDifferentText(String replaceWith) { return new AutoValue_Replacement(range(), replaceWith); } }
2,329
31.361111
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/AdjustedPosition.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** Describes a tree position with adjustments to the start and end indices. */ public class AdjustedPosition implements DiagnosticPosition { protected final JCTree position; protected final int startPositionAdjustment; protected final int endPositionAdjustment; public AdjustedPosition(JCTree position, int startPosAdjustment, int endPosAdjustment) { this.position = position; this.startPositionAdjustment = startPosAdjustment; this.endPositionAdjustment = endPosAdjustment; } @Override public int getStartPosition() { return position.getStartPosition() + startPositionAdjustment; } @Override public JCTree getTree() { return position; } @Override public int getPreferredPosition() { return position.getPreferredPosition(); } @Override public int getEndPosition(EndPosTable endPositions) { return position.getEndPosition(endPositions) + endPositionAdjustment; } }
1,730
30.472727
90
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/Replacements.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Joiner; import com.google.common.collect.ComparisonChain; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import com.google.common.collect.Range; import com.google.common.collect.RangeMap; import com.google.common.collect.TreeRangeMap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; /** A collection of {@link Replacement}s to be made to a source file. */ public class Replacements { /** * We apply replacements in reverse order of start position, so that replacements that change the * length of the input don't affect the position of earlier replacements. */ private static final Comparator<Range<Integer>> DESCENDING = new Comparator<Range<Integer>>() { @Override public int compare(Range<Integer> o1, Range<Integer> o2) { return ComparisonChain.start() .compare(o1.lowerEndpoint(), o2.lowerEndpoint(), Ordering.natural().reverse()) .compare(o1.upperEndpoint(), o2.upperEndpoint(), Ordering.natural().reverse()) .result(); } }; private final TreeMap<Range<Integer>, Replacement> replacements = new TreeMap<>(DESCENDING); private final RangeMap<Integer, Replacement> overlaps = TreeRangeMap.create(); private final TreeSet<Integer> zeroLengthRanges = new TreeSet<>(); /** A policy for handling overlapping insertions. */ public enum CoalescePolicy { /** Reject overlapping insertions and throw an {@link IllegalArgumentException}. */ REJECT(DuplicateInsertPolicy.DROP) { @Override public String coalesce(String replacement, String existing) { throw new IllegalArgumentException( String.format("%s conflicts with existing replacement %s", replacement, existing)); } }, /** * Accept overlapping insertions, with the new insertion before the existing one. Duplicate * insertions (inserting the same text at the same position) will still be dropped. */ REPLACEMENT_FIRST(DuplicateInsertPolicy.DROP) { @Override public String coalesce(String replacement, String existing) { return replacement + existing; } }, /** * Accept overlapping insertions, with the existing insertion before the new one. Duplicate * insertions (inserting the same text at the same position) will still be dropped. */ EXISTING_FIRST(DuplicateInsertPolicy.DROP) { @Override public String coalesce(String replacement, String existing) { return existing + replacement; } }, /** * Reject overlapping inserts, but treat duplicate inserts (same text at same position) * specially. Instead of dropping duplicates, as the other coalesce policies do, this policy * keeps them. */ KEEP_ONLY_IDENTICAL_INSERTS(DuplicateInsertPolicy.KEEP) { @Override public String coalesce(String replacement, String existing) { return REJECT.coalesce(replacement, existing); } }; private final DuplicateInsertPolicy duplicateInsertPolicy; CoalescePolicy(DuplicateInsertPolicy duplicateInsertPolicy) { this.duplicateInsertPolicy = duplicateInsertPolicy; } /** * Handle two insertions at the same position. * * @param replacement the replacement being added * @param existing the existing insert at this position * @return the coalesced replacement */ public abstract String coalesce(String replacement, String existing); /** * Duplicate inserts are handled specially: usually dropped (e.g. don't add the same import * twice), but can be kept. e.g., a BugChecker that adds {} blocks around some statements may * need to insert a close brace at the same place twice. */ private Replacement handleDuplicateInsertion(Replacement replacement) { return duplicateInsertPolicy.combineDuplicateInserts(replacement); } private enum DuplicateInsertPolicy { KEEP { @Override Replacement combineDuplicateInserts(Replacement insertion) { return insertion.withDifferentText(insertion.replaceWith() + insertion.replaceWith()); } }, DROP { @Override Replacement combineDuplicateInserts(Replacement insertion) { return insertion; } }; abstract Replacement combineDuplicateInserts(Replacement insertion); } } @CanIgnoreReturnValue public Replacements add(Replacement replacement) { return add(replacement, CoalescePolicy.REJECT); } @CanIgnoreReturnValue public Replacements add(Replacement replacement, CoalescePolicy coalescePolicy) { if (replacements.containsKey(replacement.range())) { Replacement existing = replacements.get(replacement.range()); if (replacement.range().isEmpty()) { // The replacement is an insertion, and there's an existing insertion at the same point. // First check whether it's a duplicate insert. if (existing.equals(replacement)) { replacement = coalescePolicy.handleDuplicateInsertion(replacement); } else { // Coalesce overlapping non-duplicate insertions together. replacement = replacement.withDifferentText( coalescePolicy.coalesce(replacement.replaceWith(), existing.replaceWith())); } } else if (existing.equals(replacement)) { // Two copies of a non-insertion edit. Just ignore the new one since it's already done. } else { throw new IllegalArgumentException( String.format("%s conflicts with existing replacement %s", replacement, existing)); } } else { checkOverlaps(replacement); } replacements.put(replacement.range(), replacement); return this; } private void checkOverlaps(Replacement replacement) { Range<Integer> replacementRange = replacement.range(); Collection<Replacement> overlap = overlaps.subRangeMap(replacementRange).asMapOfRanges().values(); checkArgument( overlap.isEmpty(), "%s overlaps with existing replacements: %s", replacement, Joiner.on(", ").join(overlap)); Set<Integer> containedZeroLengthRangeStarts = zeroLengthRanges.subSet( replacementRange.lowerEndpoint(), /* fromInclusive= */ false, replacementRange.upperEndpoint(), /* toInclusive= */ false); checkArgument( containedZeroLengthRangeStarts.isEmpty(), "%s overlaps with existing zero-length replacements: %s", replacement, Joiner.on(", ").join(containedZeroLengthRangeStarts)); overlaps.put(replacementRange, replacement); if (replacementRange.isEmpty()) { zeroLengthRanges.add(replacementRange.lowerEndpoint()); } } /** * Non-overlapping replacements, sorted in descending order by position. Prefer using {@link * #ascending} when applying changes, because applying changes in reverse tends to result in * quadratic-time copying of the underlying string. */ @Deprecated public Set<Replacement> descending() { // TODO(cushon): refactor SuggestedFix#getReplacements and just return a Collection, return new LinkedHashSet<>(replacements.values()); } /** Non-overlapping replacements, sorted in ascending order by position. */ public ImmutableSet<Replacement> ascending() { return ImmutableSet.copyOf(replacements.descendingMap().values()); } public boolean isEmpty() { return replacements.isEmpty(); } }
8,473
37.343891
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFixes.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.common.collect.Iterables.getLast; import static com.google.common.collect.Streams.stream; import static com.google.errorprone.util.ASTHelpers.getAnnotation; import static com.google.errorprone.util.ASTHelpers.getAnnotationWithSimpleName; import static com.google.errorprone.util.ASTHelpers.getModifiers; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getSymbol; import static com.sun.source.tree.Tree.Kind.ASSIGNMENT; import static com.sun.source.tree.Tree.Kind.CONDITIONAL_EXPRESSION; import static com.sun.source.tree.Tree.Kind.NEW_ARRAY; import static com.sun.tools.javac.code.TypeTag.CLASS; import static com.sun.tools.javac.util.Position.NOPOS; import static java.util.stream.Collectors.joining; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Objects; import com.google.common.base.Predicates; import com.google.common.base.Splitter; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.collect.Streams; import com.google.common.io.CharStreams; import com.google.errorprone.VisitorState; import com.google.errorprone.apply.DescriptionBasedDiff; import com.google.errorprone.apply.ImportOrganizer; import com.google.errorprone.apply.SourceFile; import com.google.errorprone.fixes.SuggestedFixes.FixCompiler.Result; import com.google.errorprone.util.ASTHelpers; import com.google.errorprone.util.ErrorProneToken; import com.google.errorprone.util.FindIdentifiers; import com.sun.source.doctree.DocTree; import com.sun.source.doctree.ParamTree; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ModifiersTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TypeParameterTree; import com.sun.source.tree.VariableTree; import com.sun.source.util.DocSourcePositions; import com.sun.source.util.DocTreePath; import com.sun.source.util.DocTreeScanner; import com.sun.source.util.JavacTask; import com.sun.source.util.TreePath; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.api.BasicJavacTask; import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Kinds.KindSelector; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types.DefaultTypeVisitor; import com.sun.tools.javac.main.Arguments; import com.sun.tools.javac.parser.Tokens; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.TokenKind; import com.sun.tools.javac.tree.DCTree; import com.sun.tools.javac.tree.DCTree.DCDocComment; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.JCDiagnostic; import com.sun.tools.javac.util.Options; import com.sun.tools.javac.util.Position; import java.io.IOException; import java.io.UncheckedIOException; import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.net.JarURLConnection; import java.net.URI; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.IntStream; import java.util.stream.StreamSupport; import javax.annotation.Nullable; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.SimpleTypeVisitor8; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import javax.tools.JavaFileObject.Kind; import javax.tools.SimpleJavaFileObject; /** Factories for constructing {@link Fix}es. */ public final class SuggestedFixes { /** Parse a modifier token into a {@link Modifier}. */ @Nullable private static Modifier getTokModifierKind(ErrorProneToken tok) { switch (tok.kind()) { case PUBLIC: return Modifier.PUBLIC; case PROTECTED: return Modifier.PROTECTED; case PRIVATE: return Modifier.PRIVATE; case ABSTRACT: return Modifier.ABSTRACT; case STATIC: return Modifier.STATIC; case FINAL: return Modifier.FINAL; case TRANSIENT: return Modifier.TRANSIENT; case VOLATILE: return Modifier.VOLATILE; case SYNCHRONIZED: return Modifier.SYNCHRONIZED; case NATIVE: return Modifier.NATIVE; case STRICTFP: return Modifier.STRICTFP; case DEFAULT: return Modifier.DEFAULT; default: return null; } } /** 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(); } return addModifiers(tree, originalModifiers, state, new TreeSet<>(Arrays.asList(modifiers))); } /** Adds modifiers to the given declaration and corresponding modifiers tree. */ public static Optional<SuggestedFix> addModifiers( Tree tree, ModifiersTree originalModifiers, VisitorState state, Set<Modifier> modifiers) { Set<Modifier> toAdd = Sets.difference(modifiers, originalModifiers.getFlags()); SuggestedFix.Builder fix = SuggestedFix.builder(); List<Modifier> modifiersToWrite = new ArrayList<>(); if (!originalModifiers.getFlags().isEmpty()) { // 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.getOffsetTokensForNode(originalModifiers); for (ErrorProneToken tok : tokens) { Modifier mod = getTokModifierKind(tok); if (mod != null) { modifierPositions.put(mod, tok.pos()); } } // walk the map of all modifiers, and accumulate a list of new modifiers to insert // beside an existing modifier modifierPositions.forEach( (mod, p) -> { if (p == -1) { modifiersToWrite.add(mod); } else if (!modifiersToWrite.isEmpty()) { fix.replace(p, p, Joiner.on(' ').join(modifiersToWrite) + " "); modifiersToWrite.clear(); } }); } else { modifiersToWrite.addAll(toAdd); } addRemainingModifiers(tree, state, originalModifiers, modifiersToWrite, fix); return Optional.of(fix.build()); } private static void addRemainingModifiers( Tree tree, VisitorState state, ModifiersTree originalModifiers, Collection<Modifier> toAdd, SuggestedFix.Builder fix) { if (toAdd.isEmpty()) { return; } int insertPos; if (tree.getKind() == Tree.Kind.ANNOTATION_TYPE) { // For annotation types, the modifiers tree include the '@' of @interface. And all modifiers // must appear before @interface. int pos = Streams.findLast( state.getOffsetTokensForNode(originalModifiers).stream() .filter(tok -> tok.kind().equals(TokenKind.MONKEYS_AT))) .get() .pos(); insertPos = state.getOffsetTokensForNode(tree).stream() .mapToInt(ErrorProneToken::pos) .filter(thisPos -> thisPos >= pos) .findFirst() .orElse(pos); // shouldn't ever be able to get to the else } else { int pos = state.getEndPosition(originalModifiers) == NOPOS ? getStartPosition(tree) : state.getEndPosition(originalModifiers) + 1; insertPos = state.getOffsetTokensForNode(originalModifiers).stream() .filter(t -> getTokModifierKind(t) != null) .mapToInt(t -> t.endPos() + 1) .max() .orElse(pos); } fix.replace(insertPos, insertPos, Joiner.on(' ').join(toAdd) + " "); } /** Removes modifiers from the given class, method, or field declaration. */ public static Optional<SuggestedFix> removeModifiers( Tree tree, VisitorState state, Modifier... modifiers) { ImmutableSet<Modifier> toRemove = ImmutableSet.copyOf(modifiers); ModifiersTree originalModifiers = getModifiers(tree); if (originalModifiers == null) { return Optional.empty(); } return removeModifiers(originalModifiers, state, toRemove); } /** Removes modifiers to the given declaration and corresponding modifiers tree. */ public static Optional<SuggestedFix> removeModifiers( ModifiersTree originalModifiers, VisitorState state, Set<Modifier> toRemove) { SuggestedFix.Builder fix = SuggestedFix.builder(); List<ErrorProneToken> tokens = state.getOffsetTokensForNode(originalModifiers); boolean empty = true; for (ErrorProneToken tok : tokens) { Modifier mod = getTokModifierKind(tok); if (toRemove.contains(mod)) { empty = false; fix.replace(tok.pos(), tok.endPos() + 1, ""); } } if (empty) { return Optional.empty(); } return Optional.of(fix.build()); } /** * Returns a human-friendly name of the given {@link Symbol} for use in fixes. * * <ul> * <li>If the symbol is already in scope, its simple name is used. * <li>If the symbol is a {@link Symbol.TypeSymbol} and an enclosing type is imported, that * enclosing type is used as a qualifier. * <li>Otherwise the outermost enclosing type is imported and used as a qualifier. * </ul> */ public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, Symbol sym) { if (sym.getKind() == ElementKind.TYPE_PARAMETER) { return sym.getSimpleName().toString(); } if (sym.getKind() == ElementKind.CLASS) { if (ASTHelpers.isLocal(sym)) { if (!sym.isAnonymous()) { return sym.getSimpleName().toString(); } sym = ((ClassSymbol) sym).getSuperclass().tsym; } } if (variableClashInScope(state, sym)) { return qualifyType(state, fix, sym.owner) + "." + sym.getSimpleName(); } Deque<String> names = new ArrayDeque<>(); for (Symbol curr = sym; curr != null; curr = curr.owner) { names.addFirst(curr.getSimpleName().toString()); Symbol found = FindIdentifiers.findIdent(curr.getSimpleName().toString(), state, KindSelector.VAL_TYP); if (found == curr) { break; } if (curr.owner != null && curr.owner.getKind() == ElementKind.PACKAGE) { // If the owner of curr is a package, we can't do anything except import or fully-qualify // the type name. if (found != null) { names.addFirst(curr.owner.getQualifiedName().toString()); } else { fix.addImport(curr.getQualifiedName().toString()); } break; } } return Joiner.on('.').join(names); } private static boolean variableClashInScope(VisitorState state, Symbol sym) { if (!sym.getKind().isField()) { return false; } MethodTree method = state.findEnclosing(MethodTree.class); if (method == null) { return false; } boolean[] result = {false}; new TreeScanner<Void, Void>() { @Override public Void visitVariable(VariableTree tree, Void unused) { if (tree.getName().contentEquals(sym.getSimpleName())) { result[0] = true; } return super.visitVariable(tree, null); } }.scan(method, null); return result[0]; } /** Returns a human-friendly name of the given type for use in fixes. */ public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, TypeMirror type) { return type.accept( new SimpleTypeVisitor8<String, SuggestedFix.Builder>() { @Override protected String defaultAction(TypeMirror e, SuggestedFix.Builder builder) { return e.toString(); } @Override public String visitArray(ArrayType t, SuggestedFix.Builder builder) { return t.getComponentType().accept(this, builder) + "[]"; } @Override public String visitDeclared(DeclaredType t, SuggestedFix.Builder builder) { String baseType = qualifyType(state, builder, ((Type) t).tsym); if (t.getTypeArguments().isEmpty()) { return baseType; } StringBuilder b = new StringBuilder(baseType); b.append('<'); boolean started = false; for (TypeMirror arg : t.getTypeArguments()) { if (started) { b.append(','); } b.append(arg.accept(this, builder)); started = true; } b.append('>'); return b.toString(); } }, fix); } private static final Splitter COMPONENT_SPLITTER = Splitter.on('.'); /** * Returns a human-friendly name of the given {@code typeName} for use in fixes. * * <p>This should be used if the type may not be loaded. * * @param typeName a qualified canonical type name, e.g. {@code java.util.Map.Entry}. */ public static String qualifyType(VisitorState state, SuggestedFix.Builder fix, String typeName) { List<String> components = COMPONENT_SPLITTER.splitToList(typeName); // Check if the simple name is already visible. String simpleName = Iterables.getLast(components); Symbol simpleNameSymbol = FindIdentifiers.findIdent(simpleName, state, KindSelector.VAL_TYP); if (simpleNameSymbol != null && !simpleNameSymbol.getKind().equals(ElementKind.OTHER) && simpleNameSymbol.getQualifiedName().contentEquals(typeName)) { return simpleName; } for (int i = 0; i < components.size(); ++i) { String component = components.get(i); // If it's lowercase, probably a package name. if (!Character.isUpperCase(component.charAt(0))) { continue; } // The qualified name up to (and including) the component we're currently dealing with. String qualifiedName = components.subList(0, i + 1).stream().collect(joining(".")); Symbol found = FindIdentifiers.findIdent(component, state, KindSelector.VAL_TYP); // No clashing name: import it and return. if (found == null) { fix.addImport(qualifiedName); return components.subList(i, components.size()).stream().collect(joining(".")); } // Type already imported or otherwise visible. if (found.getQualifiedName().contentEquals(qualifiedName)) { return components.subList(i, components.size()).stream().collect(joining(".")); } } return typeName; } /** * Provides a name to use for the (fully qualified) method provided in {@code qualifiedName}, * trying to static import it if possible. Adds imports to {@code fix} as appropriate. * * <p>The heuristic is quite conservative: it won't add a static import if an identifier with the * same name is referenced anywhere in the class. Otherwise, we'd have to implement overload * resolution, and ensure that adding a new static import doesn't change the semantics of existing * code. */ public static String qualifyStaticImport( String qualifiedName, SuggestedFix.Builder fix, VisitorState state) { String name = qualifiedName.substring(qualifiedName.lastIndexOf(".") + 1); AtomicBoolean foundConflict = new AtomicBoolean(false); new TreeScanner<Void, Void>() { @Override public Void visitMethod(MethodTree method, Void unused) { process(method, method.getName()); return super.visitMethod(method, null); } @Override public Void visitIdentifier(IdentifierTree ident, Void unused) { process(ident, ident.getName()); return super.visitIdentifier(ident, null); } private void process(Tree tree, Name identifier) { if (!identifier.contentEquals(name)) { return; } Symbol symbol = getSymbol(tree); if (symbol == null) { return; } String identifierQualifiedName = symbol.owner.getQualifiedName() + "." + symbol.getSimpleName(); if (!qualifiedName.equals(identifierQualifiedName)) { foundConflict.set(true); } } }.scan(state.getPath().getCompilationUnit(), null); if (foundConflict.get()) { String className = qualifiedName.substring(0, qualifiedName.lastIndexOf(".")); return qualifyType(state, fix, className) + "." + name; } fix.addStaticImport(qualifiedName); return name; } /** Replaces the leaf doctree in the given path with {@code replacement}. */ public static void replaceDocTree( SuggestedFix.Builder fix, DocTreePath docPath, String replacement) { DocTree leaf = docPath.getLeaf(); checkArgument( leaf instanceof DCTree.DCEndPosTree, "no end position information for %s", leaf.getKind()); DCTree.DCEndPosTree<?> node = (DCTree.DCEndPosTree<?>) leaf; DCTree.DCDocComment comment = (DCTree.DCDocComment) docPath.getDocComment(); fix.replace( node.pos(comment).getStartPosition(), endPosition(node, comment, docPath), replacement); } private static int endPosition( DCTree.DCEndPosTree<?> node, DCTree.DCDocComment comment, DocTreePath docPath) { try { Method method = DCTree.DCEndPosTree.class.getMethod("getEndPos", DCTree.DCDocComment.class); return (int) method.invoke(node, comment); } catch (NoSuchMethodException e) { // continue below } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } JCDiagnostic.DiagnosticPosition pos = node.pos(comment); EndPosTable endPositions = ((JCCompilationUnit) docPath.getTreePath().getCompilationUnit()).endPositions; return pos.getEndPosition(endPositions); } /** * Fully qualifies a javadoc reference, e.g. for replacing <code>{&#64;link List}</code> with * <code>{&#64;link java.util.List}</code>. * * @param fix the fix builder to add to * @param docPath the path to a {@link DCTree.DCReference} element */ public static void qualifyDocReference( SuggestedFix.Builder fix, DocTreePath docPath, VisitorState state) { DocTree leaf = docPath.getLeaf(); checkArgument( leaf.getKind() == DocTree.Kind.REFERENCE, "expected a path to a reference, got %s instead", leaf.getKind()); DCTree.DCReference reference = (DCTree.DCReference) leaf; Symbol sym = (Symbol) JavacTrees.instance(state.context).getElement(docPath); if (sym == null) { return; } String refString = reference.toString(); String qualifiedName; int idx = refString.indexOf('#'); if (idx >= 0) { qualifiedName = sym.owner.getQualifiedName() + refString.substring(idx, refString.length()); } else { qualifiedName = sym.getQualifiedName().toString(); } replaceDocTree(fix, docPath, qualifiedName); } /** * Removes {@code tree} from {@code trees}, assuming that {@code trees} represents a * comma-separated list of expressions containing {@code tree}. * * <p>Can be used to remove a single element from an annotation. Does not remove the enclosing * parentheses if no elements are left. */ public static SuggestedFix removeElement( Tree tree, List<? extends Tree> trees, VisitorState state) { int indexOf = trees.indexOf(tree); checkArgument(indexOf != -1, "trees must contain tree"); if (trees.size() == 1) { return SuggestedFix.delete(tree); } int startPos = getStartPosition(tree); int endPos = state.getEndPosition(tree); if (indexOf == trees.size() - 1) { return SuggestedFix.replace(state.getEndPosition(trees.get(indexOf - 1)), endPos, ""); } return SuggestedFix.replace(startPos, getStartPosition(trees.get(indexOf + 1)), ""); } /** * Instructs {@link #addMembers(ClassTree, VisitorState, AdditionPosition, String, String...)} * whether to add the new member(s) at the beginning of the class, or at the end. */ public enum AdditionPosition { FIRST { @Override int pos(ClassTree tree, VisitorState state) { // We scan backwards from the first member, looking for the class's opening { token. int classStart = getStartPosition(tree); ImmutableList<? extends Tree> members = tree.getMembers().stream() /* Throw away generated members, which may be synthetic, or whose start position may be the same as the class's. We only want to look at members defined in the source, so we can find a source position which is after the opening {.*/ .filter(AdditionPosition::definedInSourceFile) .filter(member -> getStartPosition(member) > classStart) .collect(toImmutableList()); if (members.isEmpty()) { // The approach for inserting first only works if there's a member, but if not then LAST // is just as good. return LAST.pos(tree, state); } JCTree firstMember = (JCTree) members.get(0); int firstMemberStart = firstMember.getStartPosition(); List<ErrorProneToken> methodTokens = state.getOffsetTokens(classStart, firstMemberStart); ListIterator<ErrorProneToken> iter = methodTokens.listIterator(methodTokens.size()); while (iter.hasPrevious()) { ErrorProneToken token = iter.previous(); if (token.kind() == TokenKind.LBRACE) { return token.pos() + 1; } } throw new AssertionError("Found no open brace for class " + tree); } }, LAST { @Override int pos(ClassTree tree, VisitorState state) { return state.getEndPosition(tree) - 1; } }; /** The position at which to make changes */ abstract int pos(ClassTree tree, VisitorState state); /** * An imprecise guess at whether the member is actually defined in a .java file, as opposed to * being generated by javac (e.g. a synthetic member or a generated constructor). */ private static boolean definedInSourceFile(Tree member) { Symbol sym = getSymbol(member); if (sym == null) { return false; } if (member instanceof MethodTree && ASTHelpers.isGeneratedConstructor((MethodTree) member)) { return false; } return (sym.flags() & Flags.SYNTHETIC) == 0; } } /** * Returns a {@link Fix} that adds members defined by {@code firstMember} (and optionally {@code * otherMembers}) to the end of the class referenced by {@code classTree}. This method should only * be called once per {@link ClassTree} as the suggestions will otherwise collide. */ public static SuggestedFix addMembers( ClassTree classTree, VisitorState state, String firstMember, String... otherMembers) { return addMembers(classTree, state, AdditionPosition.LAST, firstMember, otherMembers); } /** * Returns a {@link Fix} that adds members defined by {@code firstMember} (and optionally {@code * otherMembers}) to the class referenced by {@code classTree}. This method should only be called * once per {@link ClassTree} as the suggestions will otherwise collide. */ public static SuggestedFix addMembers( ClassTree classTree, VisitorState state, AdditionPosition where, String firstMember, String... otherMembers) { checkNotNull(classTree); List<String> members = Lists.asList(firstMember, otherMembers); return addMembers(classTree, state, where, members).get(); } /** * Returns a {@link Fix} that adds members defined by {@code members} to the class referenced by * {@code classTree}. This method should only be called once per {@link ClassTree} as the * suggestions will otherwise collide. It will return {@code Optional.empty()} if and only if * {@code members} is empty. */ public static Optional<SuggestedFix> addMembers( ClassTree classTree, VisitorState state, AdditionPosition where, Iterable<String> members) { // Manually desugaring a foreach over members so that we can behave differently if it's empty. Iterator<String> items = members.iterator(); if (!items.hasNext()) { return Optional.empty(); } StringBuilder stringBuilder = new StringBuilder(); do { String item = items.next(); stringBuilder.append("\n\n").append(item); } while (items.hasNext()); stringBuilder.append('\n'); int pos = where.pos(classTree, state); return Optional.of(SuggestedFix.replace(pos, pos, stringBuilder.toString())); } /** * Renames the given {@link VariableTree} and its usages in the current compilation unit to {@code * replacement}. */ public static SuggestedFix renameVariable( VariableTree tree, String replacement, VisitorState state) { String name = tree.getName().toString(); int typeEndPos = state.getEndPosition(tree.getType()); // handle implicit lambda parameter types int searchOffset = typeEndPos == -1 ? 0 : (typeEndPos - getStartPosition(tree)); int pos = getStartPosition(tree) + state.getSourceForNode(tree).indexOf(name, searchOffset); return SuggestedFix.builder() .replace(pos, pos + name.length(), replacement) .merge(renameVariableUsages(tree, replacement, state)) .build(); } /** * Renames usage of the given {@link VariableTree} in the current compilation unit to {@code * replacement}. */ public static SuggestedFix renameVariableUsages( VariableTree tree, String replacement, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder(); Symbol.VarSymbol sym = getSymbol(tree); new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (sym.equals(getSymbol(tree))) { fix.replace(tree, replacement); } return super.visitIdentifier(tree, null); } @Override public Void visitMemberSelect(MemberSelectTree tree, Void unused) { if (sym.equals(getSymbol(tree))) { fix.replace( state.getEndPosition(tree.getExpression()), state.getEndPosition(tree), "." + replacement); } return super.visitMemberSelect(tree, null); } }.scan(state.getPath().getCompilationUnit(), null); return fix.build(); } /** Be warned, only changes method name at the declaration. */ public static SuggestedFix renameMethod(MethodTree tree, String replacement, VisitorState state) { // Search tokens from beginning of method tree to beginning of method body. int basePos = getStartPosition(tree); int endPos = tree.getBody() != null ? getStartPosition(tree.getBody()) : state.getEndPosition(tree); List<ErrorProneToken> methodTokens = state.getOffsetTokens(basePos, endPos); for (ErrorProneToken token : methodTokens) { if (token.kind() == TokenKind.IDENTIFIER && token.name().equals(tree.getName())) { return SuggestedFix.replace(token.pos(), token.endPos(), replacement); } } // Method name not found. throw new AssertionError(); } /** * Renames the given {@link MethodTree} and its usages in the current compilation unit to {@code * replacement}. */ public static SuggestedFix renameMethodWithInvocations( MethodTree tree, String replacement, VisitorState state) { SuggestedFix.Builder fix = SuggestedFix.builder().merge(renameMethod(tree, replacement, state)); MethodSymbol sym = getSymbol(tree); new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { if (sym.equals(getSymbol(tree))) { fix.replace(tree, replacement); } return super.visitIdentifier(tree, null); } @Override public Void visitMemberSelect(MemberSelectTree tree, Void unused) { if (sym.equals(getSymbol(tree))) { fix.replace( state.getEndPosition(tree.getExpression()), state.getEndPosition(tree), "." + replacement); } return super.visitMemberSelect(tree, null); } }.scan(state.getPath().getCompilationUnit(), null); return fix.build(); } /** Replaces the name of the method being invoked in {@code tree} with {@code replacement}. */ public static SuggestedFix renameMethodInvocation( MethodInvocationTree tree, String replacement, VisitorState state) { Tree methodSelect = tree.getMethodSelect(); Name identifier; int startPos; if (methodSelect instanceof MemberSelectTree) { identifier = ((MemberSelectTree) methodSelect).getIdentifier(); startPos = state.getEndPosition(((MemberSelectTree) methodSelect).getExpression()); } else if (methodSelect instanceof IdentifierTree) { identifier = ((IdentifierTree) methodSelect).getName(); startPos = getStartPosition(tree); } else { throw malformedMethodInvocationTree(tree); } int endPos = tree.getArguments().isEmpty() ? state.getEndPosition(tree) : getStartPosition(tree.getArguments().get(0)); List<ErrorProneToken> tokens = state.getOffsetTokens(startPos, endPos); for (ErrorProneToken token : Lists.reverse(tokens)) { if (token.kind() == TokenKind.IDENTIFIER && token.name().equals(identifier)) { return SuggestedFix.replace(token.pos(), token.endPos(), replacement); } } throw malformedMethodInvocationTree(tree); } private static IllegalStateException malformedMethodInvocationTree(MethodInvocationTree tree) { return new IllegalStateException( String.format("Couldn't replace the method name in %s.", tree)); } /** * Renames a type parameter {@code typeParameter} owned by {@code owningTree} to {@code * typeVarReplacement}. Renames occurrences in Javadoc as well. */ public static SuggestedFix renameTypeParameter( TypeParameterTree typeParameter, Tree owningTree, String typeVarReplacement, VisitorState state) { Symbol typeParameterSymbol = getSymbol(typeParameter); // replace only the type parameter name (and not any upper bounds) String name = typeParameter.getName().toString(); int pos = getStartPosition(typeParameter); SuggestedFix.Builder fixBuilder = SuggestedFix.builder().replace(pos, pos + name.length(), typeVarReplacement); new TreeScanner<Void, Void>() { @Override public Void visitIdentifier(IdentifierTree tree, Void unused) { Symbol identSym = getSymbol(tree); if (Objects.equal(identSym, typeParameterSymbol)) { // Lambda parameters can be desugared early, so we need to make sure the source // is there. In the example below, we would try to suggest replacing the node 't' // with T2, since the compiler desugars to g((T t) -> false). The extra condition // prevents us from doing that. // Foo<T> { // <G> void g(Predicate<G> p) {}, // <T> void blah() { // g(t -> false); // } // } if (Objects.equal(state.getSourceForNode(tree), name)) { fixBuilder.replace(tree, typeVarReplacement); } } return super.visitIdentifier(tree, null); } }.scan(owningTree, null); DCDocComment docCommentTree = (DCDocComment) JavacTrees.instance(state.context).getDocCommentTree(state.getPath()); if (docCommentTree != null) { docCommentTree.accept( new DocTreeScanner<Void, Void>() { @Override public Void visitParam(ParamTree paramTree, Void unused) { if (paramTree.isTypeParameter() && paramTree.getName().getName().contentEquals(name)) { DocSourcePositions positions = JavacTrees.instance(state.context).getSourcePositions(); CompilationUnitTree compilationUnitTree = state.getPath().getCompilationUnit(); int startPos = (int) positions.getStartPosition( compilationUnitTree, docCommentTree, paramTree.getName()); int endPos = (int) positions.getEndPosition( compilationUnitTree, docCommentTree, paramTree.getName()); fixBuilder.replace(startPos, endPos, typeVarReplacement); } return super.visitParam(paramTree, null); } }, null); } return fixBuilder.build(); } /** Deletes the given exceptions from a method's throws clause. */ public static Fix deleteExceptions( MethodTree tree, VisitorState state, List<ExpressionTree> toDelete) { List<? extends ExpressionTree> trees = tree.getThrows(); if (toDelete.size() == trees.size()) { return SuggestedFix.replace( getThrowsPosition(tree, state) - 1, state.getEndPosition(getLast(trees)), ""); } String replacement = tree.getThrows().stream() .filter(t -> !toDelete.contains(t)) .map(state::getSourceForNode) .collect(joining(", ")); return SuggestedFix.replace( getStartPosition(tree.getThrows().get(0)), state.getEndPosition(getLast(tree.getThrows())), replacement); } private static int getThrowsPosition(MethodTree tree, VisitorState state) { for (ErrorProneToken token : state.getOffsetTokensForNode(tree)) { if (token.kind() == Tokens.TokenKind.THROWS) { return token.pos(); } } throw new AssertionError(); } /** * Returns a fix that adds a {@code @SuppressWarnings(warningToSuppress)} to the closest * suppressible element to the node pointed at by {@code state.getPath()}. * * @see #addSuppressWarnings(VisitorState, String, String) */ public static SuggestedFix addSuppressWarnings(VisitorState state, String warningToSuppress) { return addSuppressWarnings(state, warningToSuppress, null); } /** * Returns a fix that adds a {@code @SuppressWarnings(warningToSuppress)} to the closest * suppressible element to the node pointed at by {@code state.getPath()}, optionally suffixing * the suppression with a comment suffix (e.g. a reason for the suppression). * * <p>If the closest suppressible element already has a @SuppressWarning annotation, * warningToSuppress will be added to the value in {@code @SuppressWarnings} instead. * * <p>In the event that a suppressible element couldn't be found (e.g.: the state is pointing at a * CompilationUnit, or some other internal inconsistency has occurred), or the enclosing * suppressible element already has a {@code @SuppressWarnings} annotation with {@code * warningToSuppress}, this method will throw an {@link IllegalArgumentException}. */ public static SuggestedFix addSuppressWarnings( VisitorState state, String warningToSuppress, @Nullable String lineComment) { SuggestedFix.Builder fixBuilder = SuggestedFix.builder(); addSuppressWarnings(fixBuilder, state, warningToSuppress, lineComment); if (fixBuilder.isEmpty()) { throw new IllegalArgumentException("Couldn't find a node to attach @SuppressWarnings."); } return fixBuilder.build(); } /** * Modifies {@code fixBuilder} to either create a new {@code @SuppressWarnings} element on the * closest suppressible node, or add {@code warningToSuppress} to that node if there's already a * {@code SuppressWarnings} annotation there. * * @see #addSuppressWarnings(VisitorState, String, String) */ public static void addSuppressWarnings( SuggestedFix.Builder fixBuilder, VisitorState state, String warningToSuppress) { addSuppressWarnings(fixBuilder, state, warningToSuppress, null); } /** * Modifies {@code fixBuilder} to either create a new {@code @SuppressWarnings} element on the * closest suppressible node, or add {@code warningToSuppress} to that node if there's already a * {@code SuppressWarnings} annotation there. * * @param warningToSuppress the warning to be suppressed, without the surrounding annotation. For * example, to produce {@code @SuppressWarnings("Foo")}, pass {@code Foo}. * @param lineComment if non-null, the {@code @SuppressWarnings} will be prefixed by a line * comment containing this text. Do not pass leading {@code //} or include any line breaks. * @see #addSuppressWarnings(VisitorState, String, String) */ public static void addSuppressWarnings( SuggestedFix.Builder fixBuilder, VisitorState state, String warningToSuppress, @Nullable String lineComment) { addSuppressWarnings(fixBuilder, state, warningToSuppress, lineComment, true); } /** * Modifies {@code fixBuilder} to either create a new {@code @SuppressWarnings} element on the * closest suppressible node, or add {@code warningToSuppress} to that node if there's already a * {@code SuppressWarnings} annotation there. * * @param warningToSuppress the warning to be suppressed, without the surrounding annotation. For * example, to produce {@code @SuppressWarnings("Foo")}, pass {@code Foo}. * @param lineComment if non-null, the {@code @SuppressWarnings} will have this comment associated * with it. Do not pass leading {@code //} or include any line breaks. * @param commentOnNewLine if false, and this suppression results in a new annotation, the line * comment will be added on the same line as the {@code @SuppressWarnings} annotation. In * other cases, the line comment will be on its own line. * @see #addSuppressWarnings(VisitorState, String, String) */ public static void addSuppressWarnings( SuggestedFix.Builder fixBuilder, VisitorState state, String warningToSuppress, @Nullable String lineComment, boolean commentOnNewLine) { // Find the nearest tree to add @SuppressWarnings to. Tree suppressibleNode = suppressibleNode(state.getPath()); if (suppressibleNode == null) { return; } SuppressWarnings existingAnnotation = getAnnotation(suppressibleNode, SuppressWarnings.class); String suppression = state.getTreeMaker().Literal(CLASS, warningToSuppress).toString(); // Line comment to add, if it is present. Optional<String> formattedLineComment = Optional.ofNullable(lineComment).map(s -> "// " + s + "\n"); // If we have an existing @SuppressWarnings on the element, extend its value if (existingAnnotation != null) { // Add warning to the existing annotation String[] values = existingAnnotation.value(); if (Arrays.asList(values).contains(warningToSuppress)) { // The nearest suppress warnings already contains this thing, so we can't add another thing return; } AnnotationTree suppressAnnotationTree = getAnnotationWithSimpleName( findAnnotationsTree(suppressibleNode), SuppressWarnings.class.getSimpleName()); if (suppressAnnotationTree == null) { // This is weird, bail out return; } fixBuilder.merge( addValuesToAnnotationArgument( suppressAnnotationTree, "value", ImmutableList.of(suppression), state)); formattedLineComment.ifPresent(lc -> fixBuilder.prefixWith(suppressAnnotationTree, lc)); } else { // Otherwise, add a suppress annotation to the element String replacement = commentOnNewLine ? formattedLineComment.orElse("") + "@SuppressWarnings(" + suppression + ") " : "@SuppressWarnings(" + suppression + ") " + formattedLineComment.orElse(""); fixBuilder.prefixWith(suppressibleNode, replacement); } } /** * Modifies {@code fixBuilder} to either remove a {@code warningToRemove} warning from the closest * {@code SuppressWarning} node or remove the entire {@code SuppressWarning} node if {@code * warningToRemove} is the only warning in that node. */ public static void removeSuppressWarnings( SuggestedFix.Builder fixBuilder, VisitorState state, String warningToRemove) { // Find the nearest tree to remove @SuppressWarnings from. Tree suppressibleNode = suppressibleNode(state.getPath()); if (suppressibleNode == null) { return; } AnnotationTree suppressAnnotationTree = getAnnotationWithSimpleName( findAnnotationsTree(suppressibleNode), SuppressWarnings.class.getSimpleName()); if (suppressAnnotationTree == null) { return; } SuppressWarnings annotation = getAnnotation(suppressibleNode, SuppressWarnings.class); ImmutableSet<String> warningsSuppressed = ImmutableSet.copyOf(annotation.value()); ImmutableSet<String> newWarningSet = warningsSuppressed.stream() .filter(warning -> !warning.equals(warningToRemove)) .map(state::getConstantExpression) .collect(toImmutableSet()); if (newWarningSet.size() == warningsSuppressed.size()) { // no matches found. Nothing to delete. return; } if (newWarningSet.isEmpty()) { // No warning left to suppress. Delete entire annotation. fixBuilder.delete(suppressAnnotationTree); return; } fixBuilder.merge( updateAnnotationArgumentValues(suppressAnnotationTree, state, "value", newWarningSet)); } private static List<? extends AnnotationTree> findAnnotationsTree(Tree tree) { ModifiersTree maybeModifiers = getModifiers(tree); return maybeModifiers == null ? ImmutableList.of() : maybeModifiers.getAnnotations(); } @Nullable private static Tree suppressibleNode(TreePath path) { return StreamSupport.stream(path.spliterator(), false) .filter( tree -> tree instanceof MethodTree // Anonymous classes can't be suppressed || (tree instanceof ClassTree && ((ClassTree) tree).getSimpleName().length() != 0) // Lambda parameters can't be suppressed unless they have Type decls || (tree instanceof VariableTree && getStartPosition(((VariableTree) tree).getType()) != -1)) .findFirst() .orElse(null); } /** * Returns a fix that appends {@code newValues} to the {@code parameterName} argument for {@code * annotation}, regardless of whether there is already an argument. * * <p>N.B.: {@code newValues} are source-code strings, not string literal values. */ public static SuggestedFix.Builder addValuesToAnnotationArgument( AnnotationTree annotation, String parameterName, Collection<String> newValues, VisitorState state) { if (annotation.getArguments().isEmpty()) { String parameterPrefix = parameterName.equals("value") ? "" : (parameterName + " = "); return SuggestedFix.builder() .replace( annotation, annotation .toString() .replaceFirst("\\(\\)", "(" + parameterPrefix + newArgument(newValues) + ")")); } Optional<ExpressionTree> maybeExistingArgument = findArgument(annotation, parameterName); if (!maybeExistingArgument.isPresent()) { return SuggestedFix.builder() .prefixWith( annotation.getArguments().get(0), parameterName + " = " + newArgument(newValues) + ", "); } ExpressionTree existingArgument = maybeExistingArgument.get(); if (!existingArgument.getKind().equals(NEW_ARRAY)) { return SuggestedFix.builder() .replace( existingArgument, newArgument(state.getSourceForNode(existingArgument), newValues)); } NewArrayTree newArray = (NewArrayTree) existingArgument; if (newArray.getInitializers().isEmpty()) { return SuggestedFix.builder().replace(newArray, newArgument(newValues)); } else { return SuggestedFix.builder() .postfixWith(getLast(newArray.getInitializers()), ", " + Joiner.on(", ").join(newValues)); } } /** * @deprecated use {@link #updateAnnotationArgumentValues(AnnotationTree, VisitorState, String, * Collection)} instead */ @Deprecated public static SuggestedFix.Builder updateAnnotationArgumentValues( AnnotationTree annotation, String parameterName, Collection<String> newValues) { return updateAnnotationArgumentValues(annotation, null, parameterName, newValues); } /** * Returns a fix that updates {@code newValues} to the {@code parameterName} argument for {@code * annotation}, regardless of whether there is already an argument. * * <p>N.B.: {@code newValues} are source-code strings, not string literal values. */ public static SuggestedFix.Builder updateAnnotationArgumentValues( AnnotationTree annotation, VisitorState state, String parameterName, Collection<String> newValues) { if (annotation.getArguments().isEmpty()) { String parameterPrefix = parameterName.equals("value") ? "" : (parameterName + " = "); return SuggestedFix.builder() .replace( annotation, '@' // TODO(cushon): remove null check once deprecated overload of // updateAnnotationArgumentValues is removed + (state != null ? state.getSourceForNode(annotation.getAnnotationType()) : annotation.getAnnotationType().toString()) + '(' + parameterPrefix + newArgument(newValues) + ')'); } Optional<ExpressionTree> maybeExistingArgument = findArgument(annotation, parameterName); if (!maybeExistingArgument.isPresent()) { return SuggestedFix.builder() .prefixWith( annotation.getArguments().get(0), parameterName + " = " + newArgument(newValues) + ", "); } ExpressionTree existingArgument = maybeExistingArgument.get(); return SuggestedFix.builder().replace(existingArgument, newArgument(newValues)); } private static String newArgument(String existingParameters, Collection<String> initializers) { return newArgument( ImmutableList.<String>builder().add(existingParameters).addAll(initializers).build()); } private static String newArgument(Collection<String> initializers) { StringBuilder expression = new StringBuilder(); if (initializers.isEmpty()) { return "{}"; } if (initializers.size() > 1) { expression.append('{'); } Joiner.on(", ").appendTo(expression, initializers); if (initializers.size() > 1) { expression.append('}'); } return expression.toString(); } private static Optional<ExpressionTree> findArgument( AnnotationTree annotation, String parameter) { for (ExpressionTree argument : annotation.getArguments()) { if (argument.getKind().equals(ASSIGNMENT)) { AssignmentTree assignment = (AssignmentTree) argument; if (assignment.getVariable().toString().equals(parameter)) { return Optional.of(ASTHelpers.stripParentheses(assignment.getExpression())); } } } return Optional.empty(); } /** * Returns true if the current compilation would succeed with the given fix applied. Note that * calling this method is very expensive as it requires rerunning the entire compile, so it should * be used with restraint. */ public static boolean compilesWithFix(Fix fix, VisitorState state) { return compilesWithFix(fix, state, ImmutableList.of(), false); } /** * Returns true if the current compilation would succeed with the given fix applied, using the * given additional compiler options, optionally limiting the checking of compilation failures to * the compilation unit in which the fix is applied. Note that calling this method is very * expensive as it requires rerunning the entire compile, so it should be used with restraint. */ public static boolean compilesWithFix( Fix fix, VisitorState state, ImmutableList<String> extraOptions, boolean onlyInSameCompilationUnit) { ImmutableList.Builder<String> extraOptionsBuilder = ImmutableList.<String>builder().addAll(extraOptions); int maxErrors = findOptionOrAppend(extraOptionsBuilder, extraOptions, "-Xmaxerrs", 100); int maxWarnings = findOptionOrAppend(extraOptionsBuilder, extraOptions, "-Xmaxwarns", 100); return compilesWithFix( fix, state, extraOptionsBuilder.build(), onlyInSameCompilationUnit, maxErrors, maxWarnings); } private static int findOptionOrAppend( ImmutableList.Builder<String> newOptions, ImmutableList<String> extraOptions, String key, int defaultValue) { int pos = extraOptions.lastIndexOf(key); int value; if (pos >= 0) { // The maximum number of errors was explicitly set. value = Integer.parseInt(extraOptions.get(pos + 1)); } else { // The maximum number of errors was not set - pick a default value. value = defaultValue; newOptions.add(key).add("" + defaultValue); } return value; } private static boolean compilesWithFix( Fix fix, VisitorState state, ImmutableList<String> extraOptions, boolean onlyInSameCompilationUnit, int maxErrors, int maxWarnings) { if (fix.isEmpty() && extraOptions.isEmpty()) { return true; } FixCompiler fixCompiler; try { fixCompiler = FixCompiler.create(fix, state); } catch (IOException e) { return false; } Result compilationResult = fixCompiler.compile(extraOptions); URI modifiedFileUri = FixCompiler.getModifiedFileUri(state); // If we reached the maximum number of diagnostics of a given kind without finding one in the // modified compilation unit, we won't find any more diagnostics, but we can't be sure that // there isn't an diagnostic, as the diagnostic may simply be the (max+1)-th diagnostic, and // thus was dropped. int countErrors = 0; int countWarnings = 0; boolean warningIsError = false; boolean warningInSameCompilationUnit = false; for (Diagnostic<? extends JavaFileObject> diagnostic : compilationResult.diagnostics()) { warningIsError |= diagnostic.getCode().equals("compiler.err.warnings.and.werror"); JavaFileObject diagnosticSource = diagnostic.getSource(); // If the source's origin is unknown, assume that new diagnostics are due to a modification. boolean diagnosticInSameCompilationUnit = diagnosticSource == null || diagnosticSource.toUri().equals(modifiedFileUri); switch (diagnostic.getKind()) { case ERROR: ++countErrors; if (!onlyInSameCompilationUnit || diagnosticInSameCompilationUnit) { return false; } break; case WARNING: ++countWarnings; warningInSameCompilationUnit |= diagnosticInSameCompilationUnit; break; default: continue; } if ((warningIsError && warningInSameCompilationUnit) || (countErrors >= maxErrors) || (countWarnings >= maxWarnings)) { return false; } } return true; } /** * A class to hold the files from the compilation context, with a diff applied to the * currently-processed one; the files can then be recompiled. */ public static final class FixCompiler { private final List<JavaFileObject> fileObjects; private final VisitorState state; private final BasicJavacTask javacTask; private FixCompiler( List<JavaFileObject> fileObjects, VisitorState state, BasicJavacTask javacTask) { this.fileObjects = fileObjects; this.state = state; this.javacTask = javacTask; } public Result compile(ImmutableList<String> extraOptions) { DiagnosticCollector<JavaFileObject> diagnosticListener = new DiagnosticCollector<>(); Context context = createContext(); Arguments arguments = Arguments.instance(javacTask.getContext()); JavacTask newTask = JavacTool.create() .getTask( CharStreams.nullWriter(), state.context.get(JavaFileManager.class), diagnosticListener, extraOptions, arguments.getClassNames(), fileObjects, context); try { newTask.analyze(); } catch (IOException e) { throw new UncheckedIOException(e); } return Result.create(diagnosticListener.getDiagnostics()); } private Context createContext() { Context context = new Context(); Options options = Options.instance(context); Options originalOptions = Options.instance(javacTask.getContext()); for (String key : originalOptions.keySet()) { String value = originalOptions.get(key); if (key.equals("-Xplugin:") && value.startsWith("ErrorProne")) { // When using the -Xplugin Error Prone integration, disable Error Prone for speculative // recompiles to avoid infinite recursion. continue; } if (SOURCE_TARGET_OPTIONS.contains(key) && originalOptions.isSet("--release")) { // javac does not allow -source and -target to be specified explicitly when --release is, // but does add them in response to passing --release. Here we invert that operation. continue; } options.put(key, value); } return context; } public static URI getModifiedFileUri(VisitorState state) { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); JavaFileObject modifiedFile = compilationUnit.getSourceFile(); return modifiedFile.toUri(); } public static FixCompiler create(Fix fix, VisitorState state) throws IOException { BasicJavacTask javacTask = (BasicJavacTask) state.context.get(JavacTask.class); if (javacTask == null) { throw new IllegalArgumentException("No JavacTask in context."); } Arguments arguments = Arguments.instance(javacTask.getContext()); ArrayList<JavaFileObject> fileObjects = new ArrayList<>(arguments.getFileObjects()); applyFix(fix, state, fileObjects); return new FixCompiler(fileObjects, state, javacTask); } private static void applyFix(Fix fix, VisitorState state, ArrayList<JavaFileObject> fileObjects) throws IOException { JCCompilationUnit compilationUnit = (JCCompilationUnit) state.getPath().getCompilationUnit(); JavaFileObject modifiedFile = compilationUnit.getSourceFile(); CharSequence modifiedFileContent = modifiedFile.getCharContent(/* ignoreEncodingErrors= */ false); URI modifiedFileUri = getModifiedFileUri(state); IntStream.range(0, fileObjects.size()) .filter(i -> fileObjects.get(i).toUri().equals(modifiedFileUri)) .findFirst() .ifPresent( i -> { DescriptionBasedDiff diff = DescriptionBasedDiff.create( compilationUnit, ImportOrganizer.STATIC_FIRST_ORGANIZER); diff.handleFix(fix); SourceFile fixSource = new SourceFile(modifiedFile.getName(), modifiedFileContent); diff.applyDifferences(fixSource); fileObjects.set( i, new SimpleJavaFileObject(sourceURI(modifiedFile.toUri()), Kind.SOURCE) { @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return fixSource.getAsSequence(); } }); }); } /** The result of the compilation. */ @AutoValue public abstract static class Result { public abstract List<Diagnostic<? extends JavaFileObject>> diagnostics(); private static Result create(List<Diagnostic<? extends JavaFileObject>> diagnostics) { return new AutoValue_SuggestedFixes_FixCompiler_Result(diagnostics); } } } private static final ImmutableSet<String> SOURCE_TARGET_OPTIONS = ImmutableSet.of("-source", "--source", "-target", "--target"); /** Create a plausible URI to use in {@link #compilesWithFix}. */ @VisibleForTesting static URI sourceURI(URI uri) { if (!uri.getScheme().equals("jar")) { return uri; } try { return URI.create( "file:/" + ((JarURLConnection) uri.toURL().openConnection()).getEntryName()); } catch (IOException e) { throw new UncheckedIOException(e); } } /** * Pretty-prints a Type for use in diagnostic messages, qualifying any enclosed type names using * {@link #qualifyType}}. */ public static String prettyType(Type type, @Nullable VisitorState state) { return prettyType(state, /* existingFix= */ null, type); } /** * Pretty-prints a Type for use in fixes, qualifying any enclosed type names using {@link * #qualifyType}}. */ public static String prettyType( @Nullable VisitorState state, @Nullable SuggestedFix.Builder existingFix, Type type) { SuggestedFix.Builder fix = existingFix == null ? SuggestedFix.builder() : existingFix; return type.accept( new DefaultTypeVisitor<String, Void>() { @Override public String visitWildcardType(Type.WildcardType t, Void unused) { StringBuilder sb = new StringBuilder(); sb.append(t.kind); if (t.kind != BoundKind.UNBOUND) { sb.append(t.type.accept(this, null)); } return sb.toString(); } @Override public String visitClassType(Type.ClassType t, Void unused) { StringBuilder sb = new StringBuilder(); if (state == null) { sb.append(t.tsym.getSimpleName()); } else { sb.append(qualifyType(state, fix, t.tsym)); } if (t.getTypeArguments().nonEmpty()) { sb.append('<'); sb.append( t.getTypeArguments().stream() .map(a -> a.accept(this, null)) .collect(joining(", "))); sb.append(">"); } return sb.toString(); } @Override public String visitCapturedType(Type.CapturedType t, Void unused) { return t.wildcard.accept(this, null); } @Override public String visitArrayType(Type.ArrayType t, Void unused) { return t.elemtype.accept(this, null) + "[]"; } @Override public String visitType(Type t, Void unused) { return t.toString(); } }, null); } /** * Create a fix to add a suppression annotation on the surrounding class. * * <p>No suggested fix is produced if the suppression annotation cannot be used on classes, i.e. * the annotation has a {@code @Target} but does not include {@code @Target(TYPE)}. * * <p>If the suggested annotation is {@code DontSuggestFixes}, return empty. */ public static Optional<SuggestedFix> suggestExemptingAnnotation( String exemptingAnnotation, TreePath where, VisitorState state) { // TODO(bangert): Support annotations that do not have @Target(CLASS). if (exemptingAnnotation.equals("com.google.errorprone.annotations.DontSuggestFixes")) { return Optional.empty(); } SuggestedFix.Builder builder = SuggestedFix.builder(); Type exemptingAnnotationType = state.getTypeFromString(exemptingAnnotation); ImmutableSet<Tree.Kind> supportedExemptingAnnotationLocationKinds; String annotationName; if (exemptingAnnotationType != null) { supportedExemptingAnnotationLocationKinds = supportedTreeTypes(exemptingAnnotationType.asElement()); annotationName = qualifyType(state, builder, exemptingAnnotationType); } else { // If we can't resolve the type, fall back to an approximation. int idx = exemptingAnnotation.lastIndexOf('.'); Verify.verify(idx > 0 && idx + 1 < exemptingAnnotation.length()); supportedExemptingAnnotationLocationKinds = TREE_TYPE_UNKNOWN_ANNOTATION; annotationName = exemptingAnnotation.substring(idx + 1); builder.addImport(exemptingAnnotation); } Optional<Tree> exemptingAnnotationLocation = stream(where) .filter(tree -> supportedExemptingAnnotationLocationKinds.contains(tree.getKind())) .filter(Predicates.not(SuggestedFixes::isAnonymousClassTree)) .findFirst(); return exemptingAnnotationLocation.map( location -> builder.prefixWith(location, "@" + annotationName + " ").build()); } private static boolean isAnonymousClassTree(Tree t) { if (t instanceof ClassTree) { ClassTree classTree = (ClassTree) t; return classTree.getSimpleName().contentEquals(""); } return false; } /** * We assume annotations with an unknown type can be used on these Tree kinds. * * <p>These are reasonable for exempting annotations which annotate a block of code, e.g. they * don't usually make sense on a variable declaration. */ private static final ImmutableSet<Tree.Kind> TREE_TYPE_UNKNOWN_ANNOTATION = ImmutableSet.of( Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE, Tree.Kind.ANNOTATION_TYPE, Tree.Kind.METHOD); /** Returns true iff {@code suggestExemptingAnnotation()} supports this annotation. */ public static boolean suggestedExemptingAnnotationSupported(Element exemptingAnnotation) { return !supportedTreeTypes(exemptingAnnotation).isEmpty(); } private static ImmutableSet<Tree.Kind> supportedTreeTypes(Element exemptingAnnotation) { Target targetAnnotation = exemptingAnnotation.getAnnotation(Target.class); if (targetAnnotation == null) { // in the absence of further information, we assume the annotation is supported on classes and // methods. return TREE_TYPE_UNKNOWN_ANNOTATION; } ImmutableSet.Builder<Tree.Kind> types = ImmutableSet.builder(); for (ElementType t : targetAnnotation.value()) { switch (t) { case TYPE: types.add( Tree.Kind.CLASS, Tree.Kind.ENUM, Tree.Kind.INTERFACE, Tree.Kind.ANNOTATION_TYPE); break; case METHOD: types.add(Tree.Kind.METHOD); break; default: break; } } return types.build(); } /** * Replaces the tree at {@code path} along with any Javadocs/associated single-line comments. * * <p>This is the same as just deleting the tree for non-class members. For class members, we * tokenize and scan backwards to try to work out which prior comments are associated with this * node. */ public static SuggestedFix replaceIncludingComments( TreePath path, String replacement, VisitorState state) { Tree tree = path.getLeaf(); Tree parent = path.getParentPath().getLeaf(); if (!(parent instanceof ClassTree)) { return SuggestedFix.replace(tree, replacement); } Tree previousMember = null; ClassTree classTree = (ClassTree) parent; int startTokenization; for (Tree member : classTree.getMembers()) { if (member instanceof MethodTree && ASTHelpers.isGeneratedConstructor((MethodTree) member)) { continue; } if (member.equals(tree)) { break; } previousMember = member; } if (previousMember != null) { startTokenization = state.getEndPosition(previousMember); } else if (state.getEndPosition(classTree.getModifiers()) == Position.NOPOS) { startTokenization = getStartPosition(classTree); } else { startTokenization = state.getEndPosition(classTree.getModifiers()); } List<ErrorProneToken> tokens = state.getOffsetTokens(startTokenization, state.getEndPosition(tree)); if (previousMember == null) { tokens = getTokensAfterOpeningBrace(tokens); } if (tokens.isEmpty()) { return SuggestedFix.replace(tree, replacement); } if (tokens.get(0).comments().isEmpty()) { return SuggestedFix.replace(tokens.get(0).pos(), state.getEndPosition(tree), replacement); } ImmutableList<Comment> comments = ImmutableList.sortedCopyOf( Comparator.<Comment>comparingInt(c -> c.getSourcePos(0)).reversed(), tokens.get(0).comments()); int startPos = getStartPosition(tree); // This can happen for desugared expressions like `int a, b;`. if (startPos < startTokenization) { return SuggestedFix.emptyFix(); } // Delete backwards for comments which are not separated from our target by a blank line. CharSequence sourceCode = state.getSourceCode(); for (Comment comment : comments) { int endOfCommentPos = comment.getSourcePos(comment.getText().length() - 1); CharSequence stringBetweenComments = sourceCode.subSequence(endOfCommentPos, startPos); if (stringBetweenComments.chars().filter(c -> c == '\n').count() > 1) { break; } startPos = comment.getSourcePos(0); } return SuggestedFix.replace(startPos, state.getEndPosition(tree), replacement); } private static List<ErrorProneToken> getTokensAfterOpeningBrace(List<ErrorProneToken> tokens) { for (int i = 0; i < tokens.size() - 1; ++i) { if (tokens.get(i).kind() == TokenKind.LBRACE) { return tokens.subList(i + 1, tokens.size()); } } return ImmutableList.of(); } /** Casts the given {@code expressionTree} to {@code toType}, adding parentheses if necessary. */ public static String castTree(ExpressionTree expressionTree, String toType, VisitorState state) { boolean needsParentheses = expressionTree instanceof BinaryTree || expressionTree instanceof AssignmentTree || expressionTree instanceof CompoundAssignmentTree || expressionTree instanceof InstanceOfTree || expressionTree.getKind() == CONDITIONAL_EXPRESSION; return "(" + toType + ") " + (needsParentheses ? "(" : "") + state.getSourceForNode(expressionTree) + (needsParentheses ? ")" : ""); } private SuggestedFixes() {} }
69,740
39.359375
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/BranchedSuggestedFixes.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; /** * Helper class for accumulating a branching tree of alternative fixes designed to help build as set * of potential fixes with different options in them. * * <p>Consider building a list of fixes from a set of operations A followed by B or C then D or E. * The resulting list should be ABD, ACD, ABE, ACE. * * <pre>{@code * BranchedSuggestedFixes a = BranchedSuggestedFixes.builder() * .startWith(A) * .then() * .addOption(B) * .addOption(C) * .then() * .addOption(D) * .addOption(E) * .build(); * }</pre> * * This class assumes that in order to build a valid set of fixes you must make some progress at * each branch. So two calls to branch with no merges in between will result in an empty list of * fixes at the end. * * @author andrewrice@google.com (Andrew Rice) */ public class BranchedSuggestedFixes { private final ImmutableList<SuggestedFix> fixes; private BranchedSuggestedFixes(ImmutableList<SuggestedFix> fixes) { this.fixes = fixes; } public ImmutableList<SuggestedFix> getFixes() { return fixes; } public static Builder builder() { return new Builder(); } /** Builder class for BranchedSuggestedFixes */ public static class Builder { private ImmutableList.Builder<SuggestedFix> builder = ImmutableList.builder(); private ImmutableList<SuggestedFix> savedList = ImmutableList.of(); @CanIgnoreReturnValue public Builder startWith(SuggestedFix fix) { savedList = ImmutableList.of(); builder = ImmutableList.<SuggestedFix>builder().add(fix); return this; } @CanIgnoreReturnValue public Builder addOption(SuggestedFix fix) { if (!savedList.isEmpty()) { for (SuggestedFix s : savedList) { builder.add(SuggestedFix.builder().merge(s).merge(fix).build()); } } return this; } @CanIgnoreReturnValue public Builder then() { savedList = builder.build(); builder = ImmutableList.builder(); return this; } public BranchedSuggestedFixes build() { return new BranchedSuggestedFixes(builder.build()); } } }
2,884
28.742268
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/SuggestedFix.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import static com.google.common.base.Preconditions.checkArgument; import com.google.auto.value.AutoValue; import com.google.auto.value.extension.memoized.Memoized; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.annotation.Nullable; /** * @author alexeagle@google.com (Alex Eagle) */ @AutoValue public abstract class SuggestedFix implements Fix { abstract ImmutableList<FixOperation> fixes(); private static SuggestedFix create(SuggestedFix.Builder builder) { return new AutoValue_SuggestedFix( ImmutableList.copyOf(builder.fixes), ImmutableSet.copyOf(builder.importsToAdd), ImmutableSet.copyOf(builder.importsToRemove), builder.shortDescription); } @Override public boolean isEmpty() { return fixes().isEmpty() && getImportsToAdd().isEmpty() && getImportsToRemove().isEmpty(); } @Override public abstract ImmutableSet<String> getImportsToAdd(); @Override public abstract ImmutableSet<String> getImportsToRemove(); @Override public String toString(JCCompilationUnit compilationUnit) { StringBuilder result = new StringBuilder("replace "); for (Replacement replacement : getReplacements(compilationUnit.endPositions)) { result.append( String.format( "position %d:%d with \"%s\" ", replacement.startPosition(), replacement.endPosition(), replacement.replaceWith())); } return result.toString(); } @Override public abstract String getShortDescription(); @Memoized @Override public abstract int hashCode(); @Override public Set<Replacement> getReplacements(EndPosTable endPositions) { if (endPositions == null) { throw new IllegalArgumentException( "Cannot produce correct replacements without endPositions."); } Replacements replacements = new Replacements(); for (FixOperation fix : fixes()) { replacements.add( fix.getReplacement(endPositions), Replacements.CoalescePolicy.EXISTING_FIRST); } return replacements.ascending(); } /** {@link Builder#replace(Tree, String)} */ public static SuggestedFix replace(Tree tree, String replaceWith) { return builder().replace(tree, replaceWith).build(); } /** * Replace the characters from startPos, inclusive, until endPos, exclusive, with the given * string. * * @param startPos The position from which to start replacing, inclusive * @param endPos The position at which to end replacing, exclusive * @param replaceWith The string to replace with */ public static SuggestedFix replace(int startPos, int endPos, String replaceWith) { return builder().replace(startPos, endPos, replaceWith).build(); } /** * Replace a tree node with a string, but adjust the start and end positions as well. For example, * if the tree node begins at index 10 and ends at index 30, this call will replace the characters * at index 15 through 25 with "replacement": * * <pre> * {@code fix.replace(node, "replacement", 5, -5)} * </pre> * * @param node The tree node to replace * @param replaceWith The string to replace with * @param startPosAdjustment The adjustment to add to the start position (negative is OK) * @param endPosAdjustment The adjustment to add to the end position (negative is OK) */ public static SuggestedFix replace( Tree node, String replaceWith, int startPosAdjustment, int endPosAdjustment) { return builder().replace(node, replaceWith, startPosAdjustment, endPosAdjustment).build(); } /** {@link Builder#prefixWith(Tree, String)} */ public static SuggestedFix prefixWith(Tree node, String prefix) { return builder().prefixWith(node, prefix).build(); } /** {@link Builder#postfixWith(Tree, String)} */ public static SuggestedFix postfixWith(Tree node, String postfix) { return builder().postfixWith(node, postfix).build(); } /** {@link Builder#delete(Tree)} */ public static SuggestedFix delete(Tree node) { return builder().delete(node).build(); } /** {@link Builder#swap(Tree, Tree)} */ public static SuggestedFix swap(Tree node1, Tree node2) { return builder().swap(node1, node2).build(); } private static final SuggestedFix EMPTY = builder().build(); /** Creates an empty {@link SuggestedFix}. */ public static SuggestedFix emptyFix() { return EMPTY; } public static Builder builder() { return new Builder(); } /** Builds {@link SuggestedFix}s. */ public static class Builder { private final List<FixOperation> fixes = new ArrayList<>(); private final Set<String> importsToAdd = new LinkedHashSet<>(); private final Set<String> importsToRemove = new LinkedHashSet<>(); private String shortDescription = ""; protected Builder() {} public boolean isEmpty() { return fixes.isEmpty() && importsToAdd.isEmpty() && importsToRemove.isEmpty(); } public SuggestedFix build() { return create(this); } @CanIgnoreReturnValue private Builder with(FixOperation fix) { fixes.add(fix); return this; } /** * Sets a custom short description for this fix. This is useful for differentiating multiple * fixes from the same finding. * * <p>Should be limited to one sentence. */ @CanIgnoreReturnValue public Builder setShortDescription(String shortDescription) { this.shortDescription = shortDescription; return this; } @CanIgnoreReturnValue public Builder replace(Tree node, String replaceWith) { checkNotSyntheticConstructor(node); return with(ReplacementFix.create((DiagnosticPosition) node, replaceWith)); } /** * Replace the characters from startPos, inclusive, until endPos, exclusive, with the given * string. * * @param startPos The position from which to start replacing, inclusive * @param endPos The position at which to end replacing, exclusive * @param replaceWith The string to replace with */ @CanIgnoreReturnValue public Builder replace(int startPos, int endPos, String replaceWith) { DiagnosticPosition pos = new IndexedPosition(startPos, endPos); return with(ReplacementFix.create(pos, replaceWith)); } /** * Replace a tree node with a string, but adjust the start and end positions as well. For * example, if the tree node begins at index 10 and ends at index 30, this call will replace the * characters at index 15 through 25 with "replacement": * * <pre> * {@code fix.replace(node, "replacement", 5, -5)} * </pre> * * @param node The tree node to replace * @param replaceWith The string to replace with * @param startPosAdjustment The adjustment to add to the start position (negative is OK) * @param endPosAdjustment The adjustment to add to the end position (negative is OK) */ @CanIgnoreReturnValue public Builder replace( Tree node, String replaceWith, int startPosAdjustment, int endPosAdjustment) { checkNotSyntheticConstructor(node); return with( ReplacementFix.create( new AdjustedPosition((JCTree) node, startPosAdjustment, endPosAdjustment), replaceWith)); } @CanIgnoreReturnValue public Builder prefixWith(Tree node, String prefix) { checkNotSyntheticConstructor(node); return with(PrefixInsertion.create((DiagnosticPosition) node, prefix)); } @CanIgnoreReturnValue public Builder postfixWith(Tree node, String postfix) { checkNotSyntheticConstructor(node); return with(PostfixInsertion.create((DiagnosticPosition) node, postfix)); } @CanIgnoreReturnValue public Builder delete(Tree node) { checkNotSyntheticConstructor(node); return replace(node, ""); } @CanIgnoreReturnValue public Builder swap(Tree node1, Tree node2) { checkNotSyntheticConstructor(node1); checkNotSyntheticConstructor(node2); // calling Tree.toString() is kind of cheesy, but we don't currently have a better option // TODO(cushon): consider an approach that doesn't rewrite the original tokens fixes.add(ReplacementFix.create((DiagnosticPosition) node1, node2.toString())); fixes.add(ReplacementFix.create((DiagnosticPosition) node2, node1.toString())); return this; } /** * Add an import statement as part of this SuggestedFix. Import string should be of the form * "foo.bar.baz". */ @CanIgnoreReturnValue public Builder addImport(String importString) { importsToAdd.add("import " + importString); return this; } /** * Add a static import statement as part of this SuggestedFix. Import string should be of the * form "foo.bar.baz". */ @CanIgnoreReturnValue public Builder addStaticImport(String importString) { importsToAdd.add("import static " + importString); return this; } /** * Remove an import statement as part of this SuggestedFix. Import string should be of the form * "foo.bar.baz". */ @CanIgnoreReturnValue public Builder removeImport(String importString) { importsToRemove.add("import " + importString); return this; } /** * Remove a static import statement as part of this SuggestedFix. Import string should be of the * form "foo.bar.baz". */ @CanIgnoreReturnValue public Builder removeStaticImport(String importString) { importsToRemove.add("import static " + importString); return this; } /** * Merges all edits from {@code other} into {@code this}. If {@code other} is null, do nothing. */ @CanIgnoreReturnValue public Builder merge(@Nullable Builder other) { if (other == null) { return this; } if (shortDescription.isEmpty()) { shortDescription = other.shortDescription; } fixes.addAll(other.fixes); importsToAdd.addAll(other.importsToAdd); importsToRemove.addAll(other.importsToRemove); return this; } /** * Merges all edits from {@code other} into {@code this}. If {@code other} is null, do nothing. */ @CanIgnoreReturnValue public Builder merge(@Nullable SuggestedFix other) { if (other == null) { return this; } if (shortDescription.isEmpty()) { shortDescription = other.getShortDescription(); } fixes.addAll(other.fixes()); importsToAdd.addAll(other.getImportsToAdd()); importsToRemove.addAll(other.getImportsToRemove()); return this; } /** * Prevent attempts to modify implicit default constructurs, since they are one of the few * synthetic constructs added to the AST early enough to be visible from Error Prone. */ private static void checkNotSyntheticConstructor(Tree tree) { if (tree instanceof MethodTree && ASTHelpers.isGeneratedConstructor((MethodTree) tree)) { throw new IllegalArgumentException("Cannot edit synthetic AST nodes"); } } } /** Models a single fix operation. */ interface FixOperation { /** Calculate the replacement operation once end positions are available. */ Replacement getReplacement(EndPosTable endPositions); } /** Inserts new text at a specific insertion point (e.g. prefix or postfix). */ abstract static class InsertionFix implements FixOperation { protected abstract int getInsertionIndex(EndPosTable endPositions); protected abstract DiagnosticPosition position(); protected abstract String insertion(); @Override public Replacement getReplacement(EndPosTable endPositions) { int insertionIndex = getInsertionIndex(endPositions); return Replacement.create(insertionIndex, insertionIndex, insertion()); } } @AutoValue abstract static class PostfixInsertion extends InsertionFix { public static PostfixInsertion create(DiagnosticPosition position, String insertion) { checkArgument(position.getStartPosition() >= 0, "invalid start position"); return new AutoValue_SuggestedFix_PostfixInsertion(position, insertion); } @Override protected int getInsertionIndex(EndPosTable endPositions) { return position().getEndPosition(endPositions); } } @AutoValue abstract static class PrefixInsertion extends InsertionFix { public static PrefixInsertion create(DiagnosticPosition position, String insertion) { checkArgument(position.getStartPosition() >= 0, "invalid start position"); return new AutoValue_SuggestedFix_PrefixInsertion(position, insertion); } @Override protected int getInsertionIndex(EndPosTable endPositions) { return position().getStartPosition(); } } /** Replaces an entire diagnostic position (from start to end) with the given string. */ @AutoValue abstract static class ReplacementFix implements FixOperation { abstract DiagnosticPosition original(); abstract String replacement(); public static ReplacementFix create(DiagnosticPosition original, String replacement) { checkArgument(original.getStartPosition() >= 0, "invalid start position"); return new AutoValue_SuggestedFix_ReplacementFix(original, replacement); } @Override public Replacement getReplacement(EndPosTable endPositions) { return Replacement.create( original().getStartPosition(), original().getEndPosition(endPositions), replacement()); } } }
14,715
33.383178
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/FixedPosition.java
/* * Copyright 2021 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import com.sun.source.tree.Tree; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; /** A {@link DiagnosticPosition} with a fixed position. */ public final class FixedPosition implements DiagnosticPosition { private final JCTree tree; private final int startPosition; public FixedPosition(Tree tree, int startPosition) { this.tree = (JCTree) tree; this.startPosition = startPosition; } @Override public JCTree getTree() { return tree; } @Override public int getStartPosition() { return startPosition; } @Override public int getPreferredPosition() { return startPosition; } @Override public int getEndPosition(EndPosTable endPosTable) { return startPosition; } }
1,470
26.240741
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/fixes/Fix.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.fixes; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import java.util.Collection; import java.util.Set; /** * Represents a source code transformation, usually used to fix a bug detected by error-prone. * * @author eaftan@google.com (Eddie Aftandilian) */ public interface Fix { String toString(JCCompilationUnit compilationUnit); /** * A short description which can be attached to the Fix to differentiate multiple fixes provided * to the user. * * <p>Empty string generates the default description. */ default String getShortDescription() { return ""; } Set<Replacement> getReplacements(EndPosTable endPositions); Collection<String> getImportsToAdd(); Collection<String> getImportsToRemove(); boolean isEmpty(); }
1,458
27.607843
98
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/DataFlow.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow; import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import com.google.auto.value.AutoValue; import com.google.common.base.Preconditions; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.util.Context; import javax.annotation.Nullable; import javax.annotation.processing.ProcessingEnvironment; import org.checkerframework.errorprone.dataflow.analysis.AbstractValue; import org.checkerframework.errorprone.dataflow.analysis.Analysis; import org.checkerframework.errorprone.dataflow.analysis.ForwardAnalysisImpl; import org.checkerframework.errorprone.dataflow.analysis.ForwardTransferFunction; import org.checkerframework.errorprone.dataflow.analysis.Store; import org.checkerframework.errorprone.dataflow.analysis.TransferFunction; import org.checkerframework.errorprone.dataflow.cfg.ControlFlowGraph; import org.checkerframework.errorprone.dataflow.cfg.UnderlyingAST; import org.checkerframework.errorprone.dataflow.cfg.builder.CFGBuilder; /** * Provides a wrapper around {@link org.checkerframework.errorprone.dataflow.analysis.Analysis}. * * @author konne@google.com (Konstantin Weitz) */ public final class DataFlow { /** A pair of Analysis and ControlFlowGraph. */ public interface Result< A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>> { Analysis<A, S, T> getAnalysis(); ControlFlowGraph getControlFlowGraph(); } /* * We cache both the control flow graph and the analyses that are run on it. * We tuned performance to the following assumptions (which are currently true for error-prone): * * <ul> * <li> all dataflow analyses for a method are finished before another method is analyzed * <li> multiple dataflow analyses for the same method are executed in arbitrary order * </ul> * * TODO(b/158869538): Write a test that checks these assumptions */ private static final LoadingCache<AnalysisParams, Analysis<?, ?, ?>> analysisCache = Caffeine.newBuilder() .build( new CacheLoader<AnalysisParams, Analysis<?, ?, ?>>() { @Override public Analysis<?, ?, ?> load(AnalysisParams key) { ControlFlowGraph cfg = key.cfg(); ForwardTransferFunction<?, ?> transfer = key.transferFunction(); @SuppressWarnings({"unchecked", "rawtypes"}) Analysis<?, ?, ?> analysis = new ForwardAnalysisImpl(transfer); analysis.performAnalysis(cfg); return analysis; } }); private static final LoadingCache<CfgParams, ControlFlowGraph> cfgCache = Caffeine.newBuilder() .maximumSize(1) .build( new CacheLoader<CfgParams, ControlFlowGraph>() { @Override public ControlFlowGraph load(CfgParams key) { TreePath methodPath = key.methodPath(); UnderlyingAST ast; ClassTree classTree = null; MethodTree methodTree = null; for (Tree parent : methodPath) { if (parent instanceof MethodTree) { methodTree = (MethodTree) parent; } if (parent instanceof ClassTree) { classTree = (ClassTree) parent; break; } } if (methodPath.getLeaf() instanceof LambdaExpressionTree) { ast = new UnderlyingAST.CFGLambda( (LambdaExpressionTree) methodPath.getLeaf(), classTree, methodTree); } else if (methodPath.getLeaf() instanceof MethodTree) { methodTree = (MethodTree) methodPath.getLeaf(); ast = new UnderlyingAST.CFGMethod(methodTree, classTree); } else { // must be an initializer per findEnclosingMethodOrLambdaOrInitializer ast = new UnderlyingAST.CFGStatement(methodPath.getLeaf(), classTree); } ProcessingEnvironment env = key.environment(); analysisCache.invalidateAll(); CompilationUnitTree root = methodPath.getCompilationUnit(); // TODO(b/158869538): replace with faster build(bodyPath, env, ast, false, false); return CFGBuilder.build(root, ast, false, false, env); } }); // TODO(b/158869538): remove once we merge jdk8 specific's with core @Nullable private static <T> TreePath findEnclosingMethodOrLambdaOrInitializer(TreePath path) { while (path != null) { if (path.getLeaf() instanceof MethodTree) { return path; } TreePath parent = path.getParentPath(); if (parent != null) { if (parent.getLeaf() instanceof ClassTree) { if (path.getLeaf() instanceof BlockTree) { // this is a class or instance initializer block return path; } if (path.getLeaf() instanceof VariableTree && ((VariableTree) path.getLeaf()).getInitializer() != null) { // this is a field with an inline initializer return path; } } if (parent.getLeaf() instanceof LambdaExpressionTree) { return parent; } } path = parent; } return null; } /** * Run the {@code transfer} dataflow analysis over the method or lambda which is the leaf of the * {@code methodPath}. * * <p>For caching, we make the following assumptions: - if two paths to methods are {@code equal}, * their control flow graph is the same. - if two transfer functions are {@code equal}, and are * run over the same control flow graph, the analysis result is the same. - for all contexts, the * analysis result is the same. */ private static < A extends AbstractValue<A>, S extends Store<S>, T extends ForwardTransferFunction<A, S>> Result<A, S, T> methodDataflow(TreePath methodPath, Context context, T transfer) { ProcessingEnvironment env = JavacProcessingEnvironment.instance(context); ControlFlowGraph cfg = cfgCache.get(CfgParams.create(methodPath, env)); AnalysisParams aparams = AnalysisParams.create(transfer, cfg, env); @SuppressWarnings("unchecked") Analysis<A, S, T> analysis = (Analysis<A, S, T>) analysisCache.get(aparams); return new Result<A, S, T>() { @Override public Analysis<A, S, T> getAnalysis() { return analysis; } @Override public ControlFlowGraph getControlFlowGraph() { return cfg; } }; } /** * Runs the {@code transfer} dataflow analysis to compute the abstract value of the expression * which is the leaf of {@code exprPath}. * * <p>The expression must be part of a method, lambda, or initializer (inline field initializer or * initializer block). Example of an expression outside of such constructs is the identifier in an * import statement. * * <p>Note that for initializers, each inline field initializer or initializer block is treated * separately. I.e., we don't merge all initializers into one virtual block for dataflow. * * @return dataflow result for the given expression or {@code null} if the expression is not part * of a method, lambda or initializer */ @Nullable public static < A extends AbstractValue<A>, S extends Store<S>, T extends ForwardTransferFunction<A, S>> A expressionDataflow(TreePath exprPath, Context context, T transfer) { Tree leaf = exprPath.getLeaf(); Preconditions.checkArgument( leaf instanceof ExpressionTree, "Leaf of exprPath must be of type ExpressionTree, but was %s", leaf.getClass().getName()); ExpressionTree expr = (ExpressionTree) leaf; TreePath enclosingMethodPath = findEnclosingMethodOrLambdaOrInitializer(exprPath); if (enclosingMethodPath == null) { // expression is not part of a method, lambda, or initializer return null; } Tree method = enclosingMethodPath.getLeaf(); if (method instanceof MethodTree && ((MethodTree) method).getBody() == null) { // expressions can occur in abstract methods, for example {@code Map.Entry} in: // // abstract Set<Map.Entry<K, V>> entries(); return null; } return methodDataflow(enclosingMethodPath, context, transfer).getAnalysis().getValue(expr); } @AutoValue abstract static class CfgParams { abstract TreePath methodPath(); // Should not be used for hashCode or equals private ProcessingEnvironment environment; private static CfgParams create(TreePath methodPath, ProcessingEnvironment environment) { CfgParams cp = new AutoValue_DataFlow_CfgParams(methodPath); cp.environment = environment; return cp; } ProcessingEnvironment environment() { return environment; } } @AutoValue abstract static class AnalysisParams { abstract ForwardTransferFunction<?, ?> transferFunction(); abstract ControlFlowGraph cfg(); // Should not be used for hashCode or equals private ProcessingEnvironment environment; private static AnalysisParams create( ForwardTransferFunction<?, ?> transferFunction, ControlFlowGraph cfg, ProcessingEnvironment environment) { AnalysisParams ap = new AutoValue_DataFlow_AnalysisParams(transferFunction, cfg); ap.environment = environment; return ap; } ProcessingEnvironment environment() { return environment; } } private DataFlow() {} }
10,879
38.42029
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/AccessPath.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import javax.annotation.Nullable; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import org.checkerframework.errorprone.dataflow.cfg.node.AssignmentNode; import org.checkerframework.errorprone.dataflow.cfg.node.FieldAccessNode; import org.checkerframework.errorprone.dataflow.cfg.node.LocalVariableNode; import org.checkerframework.errorprone.dataflow.cfg.node.Node; import org.checkerframework.errorprone.dataflow.cfg.node.VariableDeclarationNode; import org.checkerframework.errorprone.javacutil.TreeUtils; /** * A sequence of field names or autovalue accessors, along with a receiver: either a variable or a * reference (explicit or implicit) to {@code this}. Fields and autovalue accessors are stored as * strings, with a "()" appended to accessor names to distinguish them from fields of the same name * * <p>For example: * * <p>{@code x.f.g}, the {@code g} field of the {@code f} field of the local variable {@code x} is * represented by {base = Some x, fields = "g" :: "f" :: nil} * * <p>{@code foo.bar}, the {@code bar} field of the {@code foo} field of the implicit {@code this} * is represented by {base = None, fields = "bar" :: "foo" :: nil} * * <p>{@code x.foo().foo}, the {@code foo} field of the {@code foo()} autovalue accessor of the * local variable {@code x} is represented by {base = Some x, fields = "foo" :: "foo()" :: nil} * * @author bennostein@google.com (Benno Stein) */ @AutoValue public abstract class AccessPath { /** If present, base of access path is contained Element; if absent, base is `this` */ @Nullable public abstract Element base(); public abstract ImmutableList<String> path(); private static AccessPath create(@Nullable Element base, ImmutableList<String> path) { return new AutoValue_AccessPath(base, path); } /** * Check whether {@code tree} is an AutoValue accessor. A tree is an AutoValue accessor iff: * * <ul> * <li>it is a method invocation * <li>of an abstract method * <li>with 0 arguments * <li>defined on a class annotated @AutoValue * </ul> * * <p>Public visibility for use in NullnessPropagationTransfer#returnValueNullness */ public static boolean isAutoValueAccessor(Tree tree) { if (!(tree instanceof MethodInvocationTree)) { return false; } JCMethodInvocation invocationTree = (JCMethodInvocation) tree; // methodSelect is always either a field access (e.g. `obj.foo()`) or identifier (e.g. `foo()`) JCExpression methodSelect = invocationTree.getMethodSelect(); Type rcvrType = (methodSelect instanceof JCFieldAccess) ? ((JCFieldAccess) methodSelect).selected.type : ((JCIdent) methodSelect).sym.owner.type; return invocationTree.getArguments().isEmpty() // 0 arguments && // abstract TreeUtils.elementFromUse(invocationTree).getModifiers().contains(Modifier.ABSTRACT) && // class, not interface rcvrType.tsym.getKind() == ElementKind.CLASS && // annotated @AutoValue MoreAnnotations.getDeclarationAndTypeAttributes(rcvrType.tsym) .map(Object::toString) .anyMatch("@com.google.auto.value.AutoValue"::equals); } /** * Creates an AccessPath from field reads / AutoValue accessor we can track and returns null * otherwise (for example, when the receiver of the field access contains an array access or * non-AutoValue method call. */ @Nullable public static AccessPath fromFieldAccess(FieldAccessNode fieldAccess) { ImmutableList.Builder<String> pathBuilder = ImmutableList.builder(); Tree tree = fieldAccess.getTree(); boolean isFieldAccess; while ((isFieldAccess = TreeUtils.isFieldAccess(tree)) || isAutoValueAccessor(tree)) { if (isFieldAccess) { pathBuilder.add(TreeUtils.getFieldName(tree)); } else { // Must be an AutoValue accessor, since the `while` condition held but the `if` didn't. // Unwrap the method select from the call tree = ((MethodInvocationTree) tree).getMethodSelect(); pathBuilder.add(TreeUtils.getMethodName(tree) + "()"); } if (tree.getKind() == Kind.IDENTIFIER) { // Implicit `this` receiver return AccessPath.create(/* base= */ null, pathBuilder.build()); } tree = ((MemberSelectTree) tree).getExpression(); } // Explicit `this` receiver if (tree.getKind() == Kind.IDENTIFIER && ((IdentifierTree) tree).getName().contentEquals("this")) { return AccessPath.create(/* base= */ null, pathBuilder.build()); } // Local variable receiver if (tree.getKind() == Kind.IDENTIFIER) { return AccessPath.create(TreeUtils.elementFromTree(tree), pathBuilder.build()); } return null; } public static AccessPath fromLocalVariable(LocalVariableNode node) { return AccessPath.create(node.getElement(), ImmutableList.of()); } public static AccessPath fromVariableDecl(VariableDeclarationNode node) { return AccessPath.create(TreeUtils.elementFromDeclaration(node.getTree()), ImmutableList.of()); } /** * Returns an AccessPath representing {@code node} if {@code node} is representable as an access * path and null otherwise */ @Nullable public static AccessPath fromNodeIfTrackable(Node node) { if (node instanceof LocalVariableNode) { return fromLocalVariable((LocalVariableNode) node); } else if (node instanceof VariableDeclarationNode) { return fromVariableDecl((VariableDeclarationNode) node); } else if (node instanceof FieldAccessNode) { return fromFieldAccess((FieldAccessNode) node); } else if (node instanceof AssignmentNode) { return fromNodeIfTrackable(((AssignmentNode) node).getTarget()); } return null; } }
7,110
38.949438
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/ConstantPropagationAnalysis.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow; import com.sun.source.util.TreePath; import com.sun.tools.javac.util.Context; import javax.annotation.Nullable; import org.checkerframework.errorprone.dataflow.constantpropagation.Constant; import org.checkerframework.errorprone.dataflow.constantpropagation.ConstantPropagationTransfer; /** An interface to the constant propagation analysis. */ public final class ConstantPropagationAnalysis { private static final ConstantPropagationTransfer CONSTANT_PROPAGATION = new ConstantPropagationTransfer(); /** * Returns the value of the leaf of {@code exprPath}, if it is determined to be a constant (always * evaluates to the same numeric value), and null otherwise. Note that returning null does not * necessarily mean the expression is *not* a constant. */ @Nullable public static Number numberValue(TreePath exprPath, Context context) { Constant val = DataFlow.expressionDataflow(exprPath, context, CONSTANT_PROPAGATION); if (val == null || !val.isConstant()) { return null; } return val.getValue(); } private ConstantPropagationAnalysis() {} }
1,750
36.255319
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/AccessPathValues.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow; /** * Read-only access to {@link AccessPathStore} for convenience. * * @author bennostein@google.com (Benno Stein) */ public interface AccessPathValues<T> { T valueOfAccessPath(AccessPath path, T defaultValue); }
869
31.222222
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/AccessPathStore.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Sets.intersection; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableMap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.Nullable; import org.checkerframework.errorprone.dataflow.analysis.AbstractValue; import org.checkerframework.errorprone.dataflow.analysis.Store; import org.checkerframework.errorprone.dataflow.cfg.visualize.CFGVisualizer; import org.checkerframework.errorprone.dataflow.expression.JavaExpression; /** * Immutable map from local variables or heap access paths to their {@link AbstractValue} * * <p>To derive a new instance, {@linkplain #toBuilder() create a builder} from an old instance. To * start from scratch, call {@link #empty()}. * * @author bennostein@google.com (Benno Stein) */ @AutoValue public abstract class AccessPathStore<V extends AbstractValue<V>> implements Store<AccessPathStore<V>>, AccessPathValues<V> { public abstract ImmutableMap<AccessPath, V> heap(); private static <V extends AbstractValue<V>> AccessPathStore<V> create( ImmutableMap<AccessPath, V> heap) { return new AutoValue_AccessPathStore<>(heap); } @SuppressWarnings({"unchecked", "rawtypes"}) // fully variant private static final AccessPathStore<?> EMPTY = AccessPathStore.<AbstractValue>create(ImmutableMap.of()); @SuppressWarnings("unchecked") // fully variant public static <V extends AbstractValue<V>> AccessPathStore<V> empty() { return (AccessPathStore<V>) EMPTY; } @Nullable private V getInformation(AccessPath ap) { return heap().get(checkNotNull(ap)); } public Builder<V> toBuilder() { return new Builder<>(this); } @Override public V valueOfAccessPath(AccessPath path, V defaultValue) { V result = getInformation(path); return result != null ? result : defaultValue; } @Override public AccessPathStore<V> copy() { // No need to copy because it's immutable. return this; } @Override public AccessPathStore<V> leastUpperBound(AccessPathStore<V> other) { ImmutableMap.Builder<AccessPath, V> resultHeap = ImmutableMap.builder(); for (AccessPath aPath : intersection(heap().keySet(), other.heap().keySet())) { resultHeap.put(aPath, heap().get(aPath).leastUpperBound(other.heap().get(aPath))); } return AccessPathStore.create(resultHeap.buildOrThrow()); } @Override public AccessPathStore<V> widenedUpperBound(AccessPathStore<V> vAccessPathStore) { // No support for widening yet. return leastUpperBound(vAccessPathStore); } @Override public boolean canAlias(JavaExpression a, JavaExpression b) { return true; } @Override public String visualize(CFGVisualizer<?, AccessPathStore<V>, ?> cfgVisualizer) { throw new UnsupportedOperationException("DOT output not supported"); } /** * Builder for {@link AccessPathStore} instances. To obtain an instance, obtain a {@link * AccessPathStore} (such as {@link AccessPathStore#empty()}), and call {@link * AccessPathStore#toBuilder() toBuilder()} on it. */ public static final class Builder<V extends AbstractValue<V>> { private final Map<AccessPath, V> heap; Builder(AccessPathStore<V> prototype) { this.heap = new LinkedHashMap<>(prototype.heap()); } @CanIgnoreReturnValue public Builder<V> setInformation(AccessPath aPath, V value) { heap.put(checkNotNull(aPath), checkNotNull(value)); return this; } public AccessPathStore<V> build() { return AccessPathStore.create(ImmutableMap.copyOf(heap)); } } }
4,382
32.715385
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessAnalysis.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import com.google.errorprone.dataflow.DataFlow; import com.sun.source.util.TreePath; import com.sun.tools.javac.util.Context; import java.io.Serializable; /** An interface to the nullness analysis. */ public final class NullnessAnalysis implements Serializable { private static final Context.Key<NullnessAnalysis> NULLNESS_ANALYSIS_KEY = new Context.Key<>(); private final NullnessPropagationTransfer nullnessPropagation; /** * Retrieve an instance of {@link NullnessAnalysis} from the {@code context}. If there is no * {@link NullnessAnalysis} currently in the {@code context}, create one, insert it, and return * it. */ public static NullnessAnalysis instance(Context context) { NullnessAnalysis instance = context.get(NULLNESS_ANALYSIS_KEY); if (instance == null) { instance = new NullnessAnalysis(); context.put(NULLNESS_ANALYSIS_KEY, instance); } return instance; } private NullnessAnalysis() { nullnessPropagation = new NullnessPropagationTransfer(); } /** * Returns the {@link Nullness} of the leaf of {@code exprPath}. * * <p>If the leaf required the compiler to generate autoboxing or autounboxing calls, {@code * getNullness} returns the {@code Nullness} <i>after</i> the boxing/unboxing. This implies that, * in those cases, it will always return {@code NONNULL}. */ public Nullness getNullness(TreePath exprPath, Context context) { try { nullnessPropagation.setContext(context).setCompilationUnit(exprPath.getCompilationUnit()); return DataFlow.expressionDataflow(exprPath, context, nullnessPropagation); } finally { nullnessPropagation.setContext(null).setCompilationUnit(null); } } }
2,386
35.723077
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/MethodInfo.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import java.util.List; /** Represents a Java method. Used for custom predicates to match non-null-returning methods. */ public interface MethodInfo { String clazz(); String method(); List<String> annotations(); boolean isStatic(); boolean isPrimitive(); boolean isKnownNonNullReturning(); }
979
27
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/TrustingNullnessAnalysis.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import static com.google.common.base.Preconditions.checkArgument; import com.google.errorprone.dataflow.AccessPathStore; import com.google.errorprone.dataflow.DataFlow; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import java.io.Serializable; import javax.lang.model.element.ElementKind; import org.checkerframework.errorprone.dataflow.analysis.Analysis; import org.checkerframework.errorprone.dataflow.analysis.ForwardAnalysisImpl; import org.checkerframework.errorprone.dataflow.cfg.ControlFlowGraph; import org.checkerframework.errorprone.dataflow.cfg.UnderlyingAST; import org.checkerframework.errorprone.dataflow.cfg.builder.CFGBuilder; /** * An interface to the "trusting" nullness analysis. This variant "trusts" {@code Nullable} * annotations, similar to how a modular nullness checker like the checkerframework's would, meaning * method parameters, fields, and method returns are assumed {@link Nullness#NULLABLE} only if * annotated so. */ public final class TrustingNullnessAnalysis implements Serializable { private static final Context.Key<TrustingNullnessAnalysis> TRUSTING_NULLNESS_KEY = new Context.Key<>(); /** * Retrieve an instance of {@link TrustingNullnessAnalysis} from the {@code context}. If there is * no {@link TrustingNullnessAnalysis} currently in the {@code context}, create one, insert it, * and return it. */ public static TrustingNullnessAnalysis instance(Context context) { TrustingNullnessAnalysis instance = context.get(TRUSTING_NULLNESS_KEY); if (instance == null) { instance = new TrustingNullnessAnalysis(); context.put(TRUSTING_NULLNESS_KEY, instance); } return instance; } private final TrustingNullnessPropagation nullnessPropagation = new TrustingNullnessPropagation(); // Use #instance to instantiate private TrustingNullnessAnalysis() {} /** * Returns the {@link Nullness} of the leaf of {@code exprPath}. * * <p>If the leaf required the compiler to generate autoboxing or autounboxing calls, {@code * getNullness} returns the {@code Nullness} <i>after</i> the boxing/unboxing. This implies that, * in those cases, it will always return {@code NONNULL}. */ public Nullness getNullness(TreePath exprPath, Context context) { try { nullnessPropagation.setContext(context).setCompilationUnit(exprPath.getCompilationUnit()); return DataFlow.expressionDataflow(exprPath, context, nullnessPropagation); } finally { nullnessPropagation.setContext(null).setCompilationUnit(null); } } /** * Returns {@link Nullness} of the initializer of the {@link VariableTree} at the leaf of the * given {@code fieldDeclPath}. Returns {@link Nullness#NULL} should there be no initializer. */ // TODO(kmb): Fold this functionality into Dataflow.expressionDataflow public Nullness getFieldInitializerNullness(TreePath fieldDeclPath, Context context) { Tree decl = fieldDeclPath.getLeaf(); checkArgument( decl instanceof VariableTree && ((JCVariableDecl) decl).sym.getKind() == ElementKind.FIELD, "Leaf of fieldDeclPath must be a field declaration: %s", decl); ExpressionTree initializer = ((VariableTree) decl).getInitializer(); if (initializer == null) { // An uninitialized field is null or 0 to start :) return ((JCVariableDecl) decl).type.isPrimitive() ? Nullness.NONNULL : Nullness.NULL; } TreePath initializerPath = TreePath.getPath(fieldDeclPath, initializer); ClassTree classTree = (ClassTree) fieldDeclPath.getParentPath().getLeaf(); JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(context); UnderlyingAST ast = new UnderlyingAST.CFGStatement(decl, classTree); ControlFlowGraph cfg = CFGBuilder.build( initializerPath, ast, /* assumeAssertionsEnabled */ false, /* assumeAssertionsDisabled */ false, javacEnv); try { nullnessPropagation .setContext(context) .setCompilationUnit(fieldDeclPath.getCompilationUnit()); Analysis<Nullness, AccessPathStore<Nullness>, TrustingNullnessPropagation> analysis = new ForwardAnalysisImpl<>(nullnessPropagation); analysis.performAnalysis(cfg); return analysis.getValue(initializer); } finally { nullnessPropagation.setContext(null).setCompilationUnit(null); } } public static boolean hasNullableAnnotation(Symbol symbol) { return NullnessAnnotations.fromAnnotationsOn(symbol).orElse(null) == Nullness.NULLABLE; } }
5,593
41.378788
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTransfer.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableList.toImmutableList; import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.BOTTOM; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NONNULL; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NULL; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NULLABLE; import static com.sun.tools.javac.code.TypeTag.BOOLEAN; import static javax.lang.model.element.ElementKind.EXCEPTION_PARAMETER; import static org.checkerframework.errorprone.javacutil.TreePathUtil.enclosingOfClass; import static org.checkerframework.errorprone.javacutil.TreeUtils.elementFromDeclaration; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.base.Verify; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSetMultimap; import com.google.common.io.Files; import com.google.common.primitives.UnsignedInteger; import com.google.common.primitives.UnsignedLong; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.dataflow.AccessPath; import com.google.errorprone.dataflow.AccessPathStore; import com.google.errorprone.dataflow.AccessPathValues; import com.google.errorprone.dataflow.nullnesspropagation.inference.InferredNullability; import com.google.errorprone.dataflow.nullnesspropagation.inference.NullnessQualifierInference; import com.google.errorprone.util.MoreAnnotations; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.Tree; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreePath; import com.sun.source.util.Trees; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.ClassSymbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeSymbol; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Symtab; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.Context; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import javax.annotation.Nullable; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeVariable; import org.checkerframework.errorprone.dataflow.analysis.Analysis; import org.checkerframework.errorprone.dataflow.analysis.ForwardAnalysisImpl; import org.checkerframework.errorprone.dataflow.cfg.ControlFlowGraph; import org.checkerframework.errorprone.dataflow.cfg.UnderlyingAST; import org.checkerframework.errorprone.dataflow.cfg.builder.CFGBuilder; import org.checkerframework.errorprone.dataflow.cfg.node.ArrayAccessNode; import org.checkerframework.errorprone.dataflow.cfg.node.ArrayCreationNode; import org.checkerframework.errorprone.dataflow.cfg.node.AssignmentNode; import org.checkerframework.errorprone.dataflow.cfg.node.EqualToNode; import org.checkerframework.errorprone.dataflow.cfg.node.FieldAccessNode; import org.checkerframework.errorprone.dataflow.cfg.node.FunctionalInterfaceNode; import org.checkerframework.errorprone.dataflow.cfg.node.InstanceOfNode; import org.checkerframework.errorprone.dataflow.cfg.node.LocalVariableNode; import org.checkerframework.errorprone.dataflow.cfg.node.MethodInvocationNode; import org.checkerframework.errorprone.dataflow.cfg.node.Node; import org.checkerframework.errorprone.dataflow.cfg.node.NotEqualNode; import org.checkerframework.errorprone.dataflow.cfg.node.SwitchExpressionNode; import org.checkerframework.errorprone.dataflow.cfg.node.TypeCastNode; import org.checkerframework.errorprone.dataflow.cfg.node.VariableDeclarationNode; /** * The {@code TransferFunction} for our nullability analysis. This analysis determines, for all * variables and parameters, whether they are definitely null ({@link Nullness#NULL}), definitely * non-null ({@link Nullness#NONNULL}), possibly null ({@link Nullness#NULLABLE}), or are on an * infeasible path ({@link Nullness#BOTTOM}). This analysis depends only on the code and does not * take nullness annotations into account. * * <p>Each {@code visit*()} implementation provides us with information about nullability that * applies <i>if the expression is successfully evaluated</i> (in other words, it did not throw an * exception). For example, if {@code foo.toString()} is successfully evaluated, we know two things: * * <ol> * <li>The expression itself is non-null (because {@code toString()} is in our list of methods * known to return non-null values) * <li>{@code foo} is non-null (because it has been dereferenced without producing a {@code * NullPointerException}) * </ol> * * <p>These particular two pieces of data also demonstrate the two connected but distinct systems * that we use to track nullness: * * <ol> * <li>We compute the nullability of each expression by applying rules that may reference only the * nullability of <i>subexpressions</i>. We make the result available only to superexpressions * (and to the {@linkplain Analysis#getValue final output of the analysis}). * <li>We {@linkplain Updates update} and {@linkplain AccessPathValues read} the nullability of * <i>variables</i> and <i>access paths</i> in a mapping that persists from node to node. This * is the only exception to the rule that we propagate data from subexpression to * superexpression only. The mapping is read only when visiting a {@link LocalVariableNode} or * {@link FieldAccessNode}. That is enough to give the Node a value that is then available to * superexpressions. * </ol> * * <p>A further complication is that sometimes we know the nullability of an expression only * conditionally based on its result. For example, {@code foo == null} proves that {@code foo} is * null in the true case (such as inside {@code if (foo == null) { ... }}) and non-null in the false * case (such an inside an accompanying {@code else} block). This is handled by methods that accept * multiple {@link Updates} instances, one for the true case and one for the false case. * * @author deminguyen@google.com (Demi Nguyen) */ class NullnessPropagationTransfer extends AbstractNullnessPropagationTransfer implements Serializable { private static final long serialVersionUID = -2413953917354086984L; /** Matches methods that are statically known never to return null. */ private static class ReturnValueIsNonNull implements Predicate<MethodInfo>, Serializable { private static final long serialVersionUID = -6277529478866058532L; private static final ImmutableSet<MemberName> METHODS_WITH_NON_NULLABLE_RETURNS = ImmutableSet.of( // We would love to include all the methods of Files, but readFirstLine can return null. member(Files.class.getName(), "toString"), // Some methods of Class can return null, e.g. getAnnotation, getCanonicalName member(Class.class.getName(), "getName"), member(Class.class.getName(), "getSimpleName"), member(Class.class.getName(), "forName"), member(Charset.class.getName(), "forName")); // TODO(cpovirk): respect nullness annotations (and also check them to ensure correctness!) private static final ImmutableSet<String> CLASSES_WITH_NON_NULLABLE_RETURNS = ImmutableSet.of( com.google.common.base.Optional.class.getName(), Preconditions.class.getName(), Verify.class.getName(), String.class.getName(), BigInteger.class.getName(), BigDecimal.class.getName(), UnsignedInteger.class.getName(), UnsignedLong.class.getName(), Objects.class.getName()); private static final ImmutableSet<String> CLASSES_WITH_NON_NULLABLE_VALUE_OF_METHODS = ImmutableSet.of( // The primitive types. Boolean.class.getName(), Byte.class.getName(), Character.class.getName(), Double.class.getName(), Float.class.getName(), Integer.class.getName(), Long.class.getName(), Short.class.getName(), // Other types. // TODO(cpovirk): recognize the compiler-generated valueOf() methods on Enum subclasses Enum.class.getName(), String.class.getName()); @Override public boolean test(MethodInfo methodInfo) { // Any method explicitly annotated is trusted to behave as advertised. Optional<Nullness> fromAnnotations = NullnessAnnotations.fromAnnotations(methodInfo.annotations()); if (fromAnnotations.isPresent()) { return fromAnnotations.get() == NONNULL; } if (methodInfo.method().equals("valueOf") && CLASSES_WITH_NON_NULLABLE_VALUE_OF_METHODS.contains(methodInfo.clazz())) { return true; } if (methodInfo.isPrimitive()) { return true; } if (methodInfo.isKnownNonNullReturning()) { return true; } if (CLASSES_WITH_NON_NULLABLE_RETURNS.contains(methodInfo.clazz())) { return true; } MemberName searchMemberName = new MemberName(methodInfo.clazz(), methodInfo.method()); if (METHODS_WITH_NON_NULLABLE_RETURNS.contains(searchMemberName)) { return true; } return false; } } private final transient Set<VarSymbol> traversed = new HashSet<>(); protected final Nullness defaultAssumption; private final Predicate<MethodInfo> methodReturnsNonNull; /** * Javac context so we can {@link #fieldInitializerNullnessIfAvailable find and analyze field * initializers}. */ private transient Context context; /** Compilation unit to limit evaluating field initializers to. */ private transient CompilationUnitTree compilationUnit; /** Cached local inference results for nullability annotations on type parameters */ @Nullable private transient InferredNullability inferenceResults; @Override public AccessPathStore<Nullness> initialStore( UnderlyingAST underlyingAST, List<LocalVariableNode> parameters) { if (parameters == null) { // Documentation of this method states, "parameters is only set if the underlying AST is a // method" return AccessPathStore.empty(); } AccessPathStore.Builder<Nullness> result = AccessPathStore.<Nullness>empty().toBuilder(); for (LocalVariableNode param : parameters) { Nullness declared = NullnessAnnotations.fromAnnotationsOn((Symbol) param.getElement()) .orElse(defaultAssumption); result.setInformation(AccessPath.fromLocalVariable(param), declared); } return result.build(); } private Optional<Nullness> getInferredNullness(MethodInvocationNode node) { // Method has a generic result, so ask inference to infer a qualifier for that type parameter if (inferenceResults == null) { // inferenceResults are per-procedure; if it is null that means this is the first query within // the procedure tree containing this node. A "procedure" is either a method, a lambda // expression, an initializer block, or a field initializer. TreePath pathToNode = node.getTreePath(); Tree procedureTree = enclosingOfClass(pathToNode, LambdaExpressionTree.class); // lambda if (procedureTree == null) { procedureTree = enclosingOfClass(pathToNode, MethodTree.class); // method } if (procedureTree == null) { procedureTree = enclosingOfClass(pathToNode, BlockTree.class); // init block } if (procedureTree == null) { procedureTree = enclosingOfClass(pathToNode, VariableTree.class); // field init } inferenceResults = NullnessQualifierInference.getInferredNullability( checkNotNull( procedureTree, "Call `%s` is not contained in an lambda, initializer or method.", node)); } return inferenceResults.getExprNullness(node.getTree()); } /** * Constructs a {@link NullnessPropagationTransfer} instance with the built-in set of non-null * returning methods. */ public NullnessPropagationTransfer() { this(NULLABLE, new ReturnValueIsNonNull()); } /** * Constructs a {@link NullnessPropagationTransfer} instance with additional non-null returning * methods. The additional predicate is or'ed with the predicate for the built-in set of non-null * returning methods. */ public NullnessPropagationTransfer(Predicate<MethodInfo> additionalNonNullReturningMethods) { this(NULLABLE, new ReturnValueIsNonNull().or(additionalNonNullReturningMethods)); } /** * Constructor for use by subclasses. * * @param defaultAssumption used if a field or method can't be resolved as well as as the default * for local variables, field and array reads in the absence of better information * @param methodReturnsNonNull determines whether a method's return value is known to be non-null */ protected NullnessPropagationTransfer( Nullness defaultAssumption, Predicate<MethodInfo> methodReturnsNonNull) { this.defaultAssumption = defaultAssumption; this.methodReturnsNonNull = methodReturnsNonNull; } /** * Stores the given Javac context to find and analyze field initializers. Set before analyzing a * method and reset after. */ @CanIgnoreReturnValue NullnessPropagationTransfer setContext(@Nullable Context context) { // This is a best-effort check (similar to ArrayList iterators, for instance), no guarantee Preconditions.checkArgument( context == null || this.context == null, "Context already set: reset after use and don't use this class concurrently"); this.context = context; // Clear traversed set just-in-case as this marks the beginning or end of analyzing a method this.traversed.clear(); // Null out local inference results when leaving a method this.inferenceResults = null; return this; } /** * Set compilation unit being analyzed, to limit analyzing field initializers to that compilation * unit. Analyzing initializers from other compilation units tends to fail because type * information is sometimes missing on nodes returned from {@link Trees}. */ @CanIgnoreReturnValue NullnessPropagationTransfer setCompilationUnit(@Nullable CompilationUnitTree compilationUnit) { this.compilationUnit = compilationUnit; return this; } // Literals @Override Nullness visitThis() { return NONNULL; } @Override Nullness visitSuper() { return NONNULL; } /** * Note: A short literal appears as an int to the compiler, and the compiler can perform a * narrowing conversion on the literal to cast from int to short. For example, when assigning a * literal to a short variable, the literal does not transfer its own non-null type to the * variable. Instead, the variable receives the non-null type from the return value of the * conversion call. */ @Override Nullness visitValueLiteral() { return NONNULL; } @Override Nullness visitNullLiteral() { return NULL; } @Override Nullness visitBitwiseOperation() { return NONNULL; } @Override Nullness visitNumericalComparison() { return NONNULL; } @Override Nullness visitNumericalOperation() { return NONNULL; } @Override Nullness visitInstanceOf( InstanceOfNode node, SubNodeValues inputs, Updates thenUpdates, Updates elseUpdates) { setNonnullIfTrackable(thenUpdates, node.getOperand()); return NONNULL; // the result of an instanceof is a primitive boolean, so it's non-null } @Override Nullness visitTypeCast(TypeCastNode node, SubNodeValues inputs) { ImmutableList<String> annotations = node.getType().getAnnotationMirrors().stream() .map(Object::toString) .collect(toImmutableList()); return NullnessAnnotations.fromAnnotations(annotations) .orElseGet( () -> hasPrimitiveType(node) ? NONNULL : inputs.valueOfSubNode(node.getOperand())); } /** * The result of string concatenation is always non-null. If an operand is {@code null}, it is * converted to {@code "null"}. For more information, see JLS 15.18.1 "String Concatenation * Operator +", and 5.1.11, "String Conversion". */ @Override Nullness visitStringConcatenate() { // TODO(b/158869538): Mark the inputs as dereferenced. return NONNULL; } @Override Nullness visitStringConversion() { return NONNULL; } @Override Nullness visitNarrowingConversion() { return NONNULL; } @Override Nullness visitWideningConversion() { return NONNULL; } @Override void visitEqualTo( EqualToNode node, SubNodeValues inputs, Updates thenUpdates, Updates elseUpdates) { handleEqualityComparison( /* equalTo= */ true, node.getLeftOperand(), node.getRightOperand(), inputs, thenUpdates, elseUpdates); } @Override void visitNotEqual( NotEqualNode node, SubNodeValues inputs, Updates thenUpdates, Updates elseUpdates) { handleEqualityComparison( /* equalTo= */ false, node.getLeftOperand(), node.getRightOperand(), inputs, thenUpdates, elseUpdates); } @Override Nullness visitAssignment(AssignmentNode node, SubNodeValues inputs, Updates updates) { Nullness value = inputs.valueOfSubNode(node.getExpression()); Node target = node.getTarget(); if (target instanceof LocalVariableNode) { updates.set((LocalVariableNode) target, value); } if (target instanceof ArrayAccessNode) { setNonnullIfTrackable(updates, ((ArrayAccessNode) target).getArray()); } if (target instanceof FieldAccessNode) { FieldAccessNode fieldAccess = (FieldAccessNode) target; if (!fieldAccess.isStatic()) { setNonnullIfTrackable(updates, fieldAccess.getReceiver()); } /* NOTE: This transfer function makes the unsound assumption that the {@code fieldAccess} * memory cell does not alias any element of other tracked access paths. To be sound, we * would have to "forget" all information about any access path that could contain an alias * of {@code fieldAccess} in non-terminal position (by setting it to NULLABLE) and perform a * weak update of {@code value} into any access path that could alias {@code fieldAccess} in * full (by setting its value to the join of its current value and {@code value}). */ updates.set(fieldAccess, value); } /* * We propagate the value of the target to the value of the assignment expressions as a whole. * We do this regardless of whether the target is a local variable. For example: * * String s = object.field = "foo"; // Now |s| is non-null. * * It's not clear to me that this is technically correct, but it works in practice with the * bytecode generated by both javac and ecj. * * http://stackoverflow.com/q/12850676/28465 */ return value; } /** * Variables take their values from their past assignments (as far as they can be determined). * Additionally, variables of primitive type are always refined to non-null. * * <p>(This second case is rarely of interest to us. Either the variable is being used as a * primitive, in which case we probably wouldn't have bothered to run the nullness checker on it, * or it's being used as an Object, in which case the compiler generates a call to {@code valueOf} * (to autobox the value), which triggers {@link #visitMethodInvocation}.) * * <p>Edge case: {@code node} can be a captured local variable accessed from inside a local or * anonymous inner class, or possibly from inside a lambda expression (even though these manifest * as fields in bytecode). As of 7/2016 this analysis doesn't have any knowledge of captured local * variables will essentially assume whatever default is used in {@code values}. */ @Override Nullness visitLocalVariable(LocalVariableNode node, AccessPathValues<Nullness> values) { return hasPrimitiveType(node) || hasNonNullConstantValue(node) ? NONNULL : values.valueOfAccessPath(AccessPath.fromLocalVariable(node), defaultAssumption); } /** * Refines the receiver of a field access to type non-null after a successful field access, and * refines the value of the expression as a whole to non-null if applicable (e.g., if the field * has a primitive type or the {@code store}) has a non-null value for this access path. * * <p>Note: If the field access occurs when the node is an l-value, the analysis won't call this * method. Instead, it will call {@link #visitAssignment}. */ @Override Nullness visitFieldAccess( FieldAccessNode node, Updates updates, AccessPathValues<Nullness> store) { if (!node.isStatic()) { setNonnullIfTrackable(updates, node.getReceiver()); } ClassAndField accessed = tryGetFieldSymbol(node.getTree()); return fieldNullness(accessed, AccessPath.fromFieldAccess(node), store); } /** * Refines the accessed array to non-null after a successful array access. * * <p>Note: If the array access occurs when the node is an l-value, the analysis won't call this * method. Instead, it will call {@link #visitAssignment}. */ @Override Nullness visitArrayAccess(ArrayAccessNode node, SubNodeValues inputs, Updates updates) { setNonnullIfTrackable(updates, node.getArray()); return hasPrimitiveType(node) ? NONNULL : defaultAssumption; } /** * Refines the receiver of a method invocation to type non-null after successful invocation, and * refines the value of the expression as a whole to non-null if applicable (e.g., if the method * returns a primitive type). * * <p>NOTE: This transfer makes the unsound assumption that fields reachable via the actual params * of this method invocation are not mutated by the callee. To be sound with respect to escaping * mutable references in general, we would have to set to top (i.e. NULLABLE) any tracked access * path that could contain an alias of an actual parameter of this invocation. */ @Override Nullness visitMethodInvocation( MethodInvocationNode node, Updates thenUpdates, Updates elseUpdates, Updates bothUpdates) { ClassAndMethod callee = tryGetMethodSymbol(node.getTree(), Types.instance(context)); if (callee != null && !callee.isStatic) { setNonnullIfTrackable(bothUpdates, node.getTarget().getReceiver()); } setUnconditionalArgumentNullness(bothUpdates, node.getArguments(), callee); setConditionalArgumentNullness( thenUpdates, elseUpdates, node.getArguments(), callee, Types.instance(context), Symtab.instance(context)); return returnValueNullness(node, callee); } @Override Nullness visitSwitchExpression(SwitchExpressionNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override Nullness visitObjectCreation() { return NONNULL; } @Override Nullness visitClassDeclaration() { return NONNULL; } @Override Nullness visitArrayCreation(ArrayCreationNode node, SubNodeValues inputs, Updates updates) { return NONNULL; } @Override Nullness visitMemberReference( FunctionalInterfaceNode node, SubNodeValues inputs, Updates updates) { // TODO(kmb,cpovirk): Mark object member reference receivers as non-null return NONNULL; // lambdas and member references are never null :) } @Override void visitVariableDeclaration( VariableDeclarationNode node, SubNodeValues inputs, Updates updates) { /* * We could try to handle primitives here instead of in visitLocalVariable, but it won't be * enough because we don't see method parameters here. */ if (isCatchVariable(node)) { updates.set(node, NONNULL); } } private static boolean isCatchVariable(VariableDeclarationNode node) { return elementFromDeclaration(node.getTree()).getKind() == EXCEPTION_PARAMETER; } /** * Refines the {@code Nullness} of {@code LocalVariableNode}s used in an equality comparison using * the greatest lower bound. * * @param equalTo whether the comparison is == (false for !=) * @param leftNode the left-hand side of the comparison * @param rightNode the right-hand side of the comparison * @param inputs access to nullness values of the left and right nodes * @param thenUpdates the local variables whose nullness values should be updated if the * comparison returns {@code true} * @param elseUpdates the local variables whose nullness values should be updated if the * comparison returns {@code false} */ private static void handleEqualityComparison( boolean equalTo, Node leftNode, Node rightNode, SubNodeValues inputs, Updates thenUpdates, Updates elseUpdates) { Nullness leftVal = inputs.valueOfSubNode(leftNode); Nullness rightVal = inputs.valueOfSubNode(rightNode); Nullness equalBranchValue = leftVal.greatestLowerBound(rightVal); Updates equalBranchUpdates = equalTo ? thenUpdates : elseUpdates; Updates notEqualBranchUpdates = equalTo ? elseUpdates : thenUpdates; AccessPath leftOperand = AccessPath.fromNodeIfTrackable(leftNode); AccessPath rightOperand = AccessPath.fromNodeIfTrackable(rightNode); if (leftOperand != null) { equalBranchUpdates.set(leftOperand, equalBranchValue); notEqualBranchUpdates.set( leftOperand, leftVal.greatestLowerBound(rightVal.deducedValueWhenNotEqual())); } if (rightOperand != null) { equalBranchUpdates.set(rightOperand, equalBranchValue); notEqualBranchUpdates.set( rightOperand, rightVal.greatestLowerBound(leftVal.deducedValueWhenNotEqual())); } } private static boolean hasPrimitiveType(Node node) { return node.getType().getKind().isPrimitive(); } private static boolean hasNonNullConstantValue(LocalVariableNode node) { if (node.getElement() instanceof VariableElement) { VariableElement element = (VariableElement) node.getElement(); return (element.getConstantValue() != null); } return false; } @Nullable private static ClassAndField tryGetFieldSymbol(Tree tree) { Symbol symbol = tryGetSymbol(tree); if (symbol instanceof VarSymbol) { return ClassAndField.make((VarSymbol) symbol); } return null; } @Nullable static ClassAndMethod tryGetMethodSymbol(MethodInvocationTree tree, Types types) { Symbol symbol = tryGetSymbol(tree.getMethodSelect()); if (symbol instanceof MethodSymbol) { return ClassAndMethod.make((MethodSymbol) symbol, types); } return null; } /* * We can't use ASTHelpers here. It's in core, which depends on jdk8, so we can't make jdk8 depend * back on core. */ @Nullable private static Symbol tryGetSymbol(Tree tree) { if (tree instanceof JCIdent) { return ((JCIdent) tree).sym; } if (tree instanceof JCFieldAccess) { return ((JCFieldAccess) tree).sym; } if (tree instanceof JCVariableDecl) { return ((JCVariableDecl) tree).sym; } return null; } Nullness fieldNullness( @Nullable ClassAndField accessed, @Nullable AccessPath path, AccessPathValues<Nullness> store) { if (accessed == null) { return defaultAssumption; } if (accessed.field.equals("class")) { return NONNULL; } if (accessed.isEnumConstant()) { return NONNULL; } if (accessed.isPrimitive()) { // includes <array>.length return NONNULL; } if (accessed.hasNonNullConstantValue()) { return NONNULL; } if (accessed.isStatic() && accessed.isFinal()) { if (CLASSES_WITH_NON_NULL_CONSTANTS.contains(accessed.clazz)) { return NONNULL; } // Try to evaluate initializer. // TODO(kmb): Consider handling final instance fields as well Nullness initializer = fieldInitializerNullnessIfAvailable(accessed); if (initializer != null) { return initializer; } } return standardFieldNullness(accessed, path, store); } /** Determines field nullness based on store and annotations. */ // TODO(kmb): Reverse subtyping between this class and TrustingNullnessPropagation to avoid this Nullness standardFieldNullness( ClassAndField accessed, @Nullable AccessPath path, AccessPathValues<Nullness> store) { // First, check the store for a dataflow-computed nullness value and return it if it exists // Otherwise, check for nullness annotations on the field's symbol (including type annotations) // If there are none, check for nullness annotations on generic type bounds, if any // If there are none, fall back to the defaultAssumption Nullness dataflowResult = (path == null) ? BOTTOM : store.valueOfAccessPath(path, BOTTOM); if (dataflowResult != BOTTOM) { return dataflowResult; } Optional<Nullness> declaredNullness = NullnessAnnotations.fromAnnotationsOn(accessed.symbol); if (declaredNullness.isEmpty()) { Type ftype = accessed.symbol.type; if (ftype instanceof TypeVariable) { declaredNullness = NullnessAnnotations.getUpperBound((TypeVariable) ftype); } else { declaredNullness = NullnessAnnotations.fromDefaultAnnotations(accessed.symbol); } } return declaredNullness.orElse(defaultAssumption); } private Nullness returnValueNullness(MethodInvocationNode node, @Nullable ClassAndMethod callee) { if (callee == null) { return defaultAssumption; } Optional<Nullness> declaredNullness = NullnessAnnotations.fromAnnotations(callee.annotations); if (declaredNullness.isPresent()) { return declaredNullness.get(); } // Auto Value accessors are nonnull unless explicitly annotated @Nullable. if (AccessPath.isAutoValueAccessor(node.getTree())) { return NONNULL; } Nullness assumedNullness = methodReturnsNonNull.test(callee) ? NONNULL : NULLABLE; if (!callee.isGenericResult) { // We only care about inference results for methods that return a type variable. return assumedNullness; } // Method has a generic result, so ask inference to infer a qualifier for that type parameter return getInferredNullness(node).orElse(assumedNullness); } @Nullable private Nullness fieldInitializerNullnessIfAvailable(ClassAndField accessed) { if (!traversed.add(accessed.symbol)) { // Circular dependency between initializers results in null. Note static fields can also be // null if they're observed before initialized, but we're ignoring that case for simplicity. // TODO(kmb): Try to recognize problems with initialization order return NULL; } try { JavacProcessingEnvironment javacEnv = JavacProcessingEnvironment.instance(context); TreePath fieldDeclPath = Trees.instance(javacEnv).getPath(accessed.symbol); // Skip initializers in other compilation units as analysis of such nodes can fail due to // missing types. if (fieldDeclPath == null || fieldDeclPath.getCompilationUnit() != compilationUnit || !(fieldDeclPath.getLeaf() instanceof VariableTree)) { return null; } ExpressionTree initializer = ((VariableTree) fieldDeclPath.getLeaf()).getInitializer(); if (initializer == null) { return null; } ClassTree classTree = (ClassTree) fieldDeclPath.getParentPath().getLeaf(); // Run flow analysis on field initializer. This is inefficient compared to just walking // the initializer expression tree but it avoids duplicating the logic from this transfer // function into a method that operates on Javac Nodes. TreePath initializerPath = TreePath.getPath(fieldDeclPath, initializer); UnderlyingAST ast = new UnderlyingAST.CFGStatement(initializerPath.getLeaf(), classTree); ControlFlowGraph cfg = CFGBuilder.build( initializerPath, ast, /* assumeAssertionsEnabled= */ false, /* assumeAssertionsDisabled= */ false, javacEnv); Analysis<Nullness, AccessPathStore<Nullness>, NullnessPropagationTransfer> analysis = new ForwardAnalysisImpl<>(this); analysis.performAnalysis(cfg); return analysis.getValue(initializerPath.getLeaf()); } finally { traversed.remove(accessed.symbol); } } private static void setNonnullIfTrackable(Updates updates, Node node) { if (node instanceof LocalVariableNode) { updates.set((LocalVariableNode) node, NONNULL); } else if (node instanceof FieldAccessNode) { updates.set((FieldAccessNode) node, NONNULL); } else if (node instanceof VariableDeclarationNode) { updates.set((VariableDeclarationNode) node, NONNULL); } } /** * Records which arguments are guaranteed to be non-null if the method completes without * exception. For example, if {@code checkNotNull(foo, message)} completes successfully, then * {@code foo} is not null. */ private static void setUnconditionalArgumentNullness( Updates bothUpdates, List<Node> arguments, ClassAndMethod callee) { ImmutableSet<Integer> requiredNonNullParameters = REQUIRED_NON_NULL_PARAMETERS.get(callee.name()); for (LocalVariableNode var : variablesAtIndexes(requiredNonNullParameters, arguments)) { bothUpdates.set(var, NONNULL); } } /** * Records which arguments are guaranteed to be non-null only if the method completes by returning * {@code true} or only if the method completes by returning {@code false}. For example, if {@code * Strings.isNullOrEmpty(s)} returns {@code false}, then {@code s} is not null. */ private static void setConditionalArgumentNullness( Updates thenUpdates, Updates elseUpdates, List<Node> arguments, ClassAndMethod callee, Types types, Symtab symtab) { MemberName calleeName = callee.name(); for (LocalVariableNode var : variablesAtIndexes(NULL_IMPLIES_TRUE_PARAMETERS.get(calleeName), arguments)) { elseUpdates.set(var, NONNULL); } for (LocalVariableNode var : variablesAtIndexes(NONNULL_IFF_TRUE_PARAMETERS.get(calleeName), arguments)) { thenUpdates.set(var, NONNULL); elseUpdates.set(var, NULL); } for (LocalVariableNode var : variablesAtIndexes(NULL_IFF_TRUE_PARAMETERS.get(calleeName), arguments)) { thenUpdates.set(var, NULL); elseUpdates.set(var, NONNULL); } if (isEqualsMethod(calleeName, arguments, types, symtab)) { LocalVariableNode var = variablesAtIndexes(ImmutableSet.of(0), arguments).get(0); thenUpdates.set(var, NONNULL); } } private static boolean isEqualsMethod( MemberName calleeName, List<Node> arguments, Types types, Symtab symtab) { // we don't care about class name -- we're matching against Object.equals(Object) // this implies that non-overriding methods are assumed to be null-guaranteeing. // Also see http://errorprone.info/bugpattern/NonOverridingEquals if (!calleeName.member.equals("equals") || arguments.size() != 1) { return false; } if (!(getOnlyElement(arguments).getTree() instanceof JCIdent)) { return false; } Symbol sym = ((JCIdent) getOnlyElement(arguments).getTree()).sym; if (sym == null || sym.type == null) { return false; } return types.isSameType(sym.type, symtab.objectType) && !variablesAtIndexes(ImmutableSet.of(0), arguments).isEmpty(); } private static List<LocalVariableNode> variablesAtIndexes( Set<Integer> indexes, List<Node> arguments) { List<LocalVariableNode> result = new ArrayList<>(); for (Integer i : indexes) { if (i < 0) { i = arguments.size() + i; } // TODO(cpovirk): better handling of varargs if (i >= 0 && i < arguments.size()) { Node argument = arguments.get(i); if (argument instanceof LocalVariableNode) { result.add((LocalVariableNode) argument); } } } return result; } interface Member { boolean isStatic(); } private static MemberName member(Class<?> clazz, String member) { return member(clazz.getName(), member); } private static MemberName member(String clazz, String member) { return new MemberName(clazz, member); } private void writeObject(ObjectOutputStream out) throws IOException { Preconditions.checkState(context == null, "Can't serialize while analyzing a method"); Preconditions.checkState(compilationUnit == null, "Can't serialize while analyzing a method"); out.defaultWriteObject(); } @VisibleForTesting static final class MemberName { final String clazz; final String member; MemberName(String clazz, String member) { this.clazz = clazz; this.member = member; } @Override public boolean equals(Object obj) { if (obj instanceof MemberName) { MemberName other = (MemberName) obj; return clazz.equals(other.clazz) && member.equals(other.member); } return false; } @Override public int hashCode() { return Objects.hash(clazz, member); } } static final class ClassAndMethod implements Member, MethodInfo { final String clazz; final String method; final ImmutableList<String> annotations; final boolean isStatic; final boolean isPrimitive; final boolean isBoolean; final boolean isGenericResult; final boolean isNonNullReturning; private ClassAndMethod( String clazz, String method, ImmutableList<String> annotations, boolean isStatic, boolean isPrimitive, boolean isBoolean, boolean isGenericResult, boolean isNonNullReturning) { this.clazz = clazz; this.method = method; this.annotations = annotations; this.isStatic = isStatic; this.isPrimitive = isPrimitive; this.isBoolean = isBoolean; this.isGenericResult = isGenericResult; this.isNonNullReturning = isNonNullReturning; } static ClassAndMethod make(MethodSymbol methodSymbol, @Nullable Types types) { // TODO(b/71812955): consider just wrapping methodSymbol instead of copying everything out. ImmutableList<String> annotations = MoreAnnotations.getDeclarationAndTypeAttributes(methodSymbol) .map(Object::toString) .collect(toImmutableList()); ClassSymbol clazzSymbol = (ClassSymbol) methodSymbol.owner; return new ClassAndMethod( clazzSymbol.getQualifiedName().toString(), methodSymbol.getSimpleName().toString(), annotations, methodSymbol.isStatic(), methodSymbol.getReturnType().isPrimitive(), methodSymbol.getReturnType().getTag() == BOOLEAN, hasGenericResult(methodSymbol), knownNonNullMethod(methodSymbol, clazzSymbol, types)); } /** * Returns {@code true} for {@link MethodSymbol}s whose result type is a generic type variable. */ private static boolean hasGenericResult(MethodSymbol methodSymbol) { return methodSymbol.getReturnType().tsym instanceof TypeVariableSymbol; } private static boolean knownNonNullMethod( MethodSymbol methodSymbol, ClassSymbol clazzSymbol, @Nullable Types types) { if (types == null) { return false; } // Proto getters are not null if (methodSymbol.name.toString().startsWith("get") && methodSymbol.params().isEmpty() && !methodSymbol.isStatic()) { Type type = clazzSymbol.type; while (type != null) { TypeSymbol typeSymbol = type.asElement(); if (typeSymbol == null) { break; } if (typeSymbol .getQualifiedName() .contentEquals("com.google.protobuf.AbstractMessageLite")) { return true; } type = types.supertype(type); } } return false; } @Override public boolean isStatic() { return isStatic; } MemberName name() { return new MemberName(this.clazz, this.method); } @Override public String clazz() { return clazz; } @Override public String method() { return method; } @Override public ImmutableList<String> annotations() { return annotations; } @Override public boolean isPrimitive() { return isPrimitive; } @Override public boolean isKnownNonNullReturning() { return isNonNullReturning; } } static final class ClassAndField implements Member { final VarSymbol symbol; final String clazz; final String field; private ClassAndField(VarSymbol symbol) { this.symbol = symbol; this.clazz = symbol.owner.getQualifiedName().toString(); this.field = symbol.getSimpleName().toString(); } static ClassAndField make(VarSymbol symbol) { return new ClassAndField(symbol); } @Override public boolean isStatic() { return symbol.isStatic(); } public boolean isFinal() { return (symbol.flags() & Flags.FINAL) == Flags.FINAL; } public boolean isPrimitive() { return symbol.type.isPrimitive(); } public boolean isEnumConstant() { return symbol.isEnum(); } public boolean hasNonNullConstantValue() { return symbol.getConstValue() != null; } } /** Classes where we know that all static final fields are non-null. */ @VisibleForTesting static final ImmutableSet<String> CLASSES_WITH_NON_NULL_CONSTANTS = ImmutableSet.of( BigInteger.class.getName(), BigDecimal.class.getName(), UnsignedInteger.class.getName(), UnsignedLong.class.getName(), StandardCharsets.class.getName()); /** * Maps from the names of null-rejecting methods to the indexes of the arguments that aren't * permitted to be null. Indexes may be negative to indicate a position relative to the end of the * argument list. For example, "-1" means "the final parameter." */ @VisibleForTesting static final ImmutableSetMultimap<MemberName, Integer> REQUIRED_NON_NULL_PARAMETERS = new ImmutableSetMultimap.Builder<MemberName, Integer>() .put(member(Objects.class, "requireNonNull"), 0) .put(member(Preconditions.class, "checkNotNull"), 0) .put(member(Verify.class, "verifyNotNull"), 0) .put(member("junit.framework.Assert", "assertNotNull"), -1) .put(member("org.junit.Assert", "assertNotNull"), -1) .build(); /** * Maps from the names of null-querying methods to the indexes of the arguments that are compared * against null. Indexes may be negative to indicate a position relative to the end of the * argument list. For example, "-1" means "the final parameter." */ @VisibleForTesting static final ImmutableSetMultimap<MemberName, Integer> NULL_IMPLIES_TRUE_PARAMETERS = new ImmutableSetMultimap.Builder<MemberName, Integer>() .put(member(Strings.class, "isNullOrEmpty"), 0) .put(member("android.text.TextUtils", "isEmpty"), 0) .build(); /** * Maps from non-null test methods to indices of arguments that are comapred against null. These * methods must guarantee non-nullness if {@code true} <b>and nullness if {@code false}</b>. */ private static final ImmutableSetMultimap<MemberName, Integer> NONNULL_IFF_TRUE_PARAMETERS = ImmutableSetMultimap.of(member(Objects.class, "nonNull"), 0); /** * Maps from null test methods to indices of arguments that are comapred against null. These * methods must guarantee nullness if {@code true} <b>and non-nullness if {@code false}</b>. */ private static final ImmutableSetMultimap<MemberName, Integer> NULL_IFF_TRUE_PARAMETERS = ImmutableSetMultimap.of(member(Objects.class, "isNull"), 0); }
46,272
37.787091
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessAnnotations.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import static javax.lang.model.element.ElementKind.TYPE_PARAMETER; import com.google.errorprone.util.MoreAnnotations; import com.sun.tools.javac.code.Symbol; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; import java.util.stream.Stream; import javax.annotation.Nullable; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Parameterizable; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.IntersectionType; import javax.lang.model.type.TypeMirror; import javax.lang.model.type.TypeVariable; /** Utilities to extract {@link Nullness} from annotations. */ public class NullnessAnnotations { // TODO(kmb): Correctly handle JSR 305 @Nonnull(NEVER) etc. private static final Predicate<String> ANNOTATION_RELEVANT_TO_NULLNESS = Pattern.compile( ".*\\b(" + "(Recently)?NonNull(Decl|Type)?|NotNull|Nonnull|" + "(Recently)?Nullable(Decl|Type)?|CheckForNull|PolyNull|MonotonicNonNull(Decl)?|" + "ProtoMethodMayReturnNull|ProtoMethodAcceptsNullParameter|" + "ProtoPassThroughNullness" + ")$") .asPredicate(); private static final Predicate<String> NULLABLE_ANNOTATION = Pattern.compile( ".*\\b(" + "(Recently)?Nullable(Decl|Type)?|CheckForNull|PolyNull|MonotonicNonNull(Decl)?|" + "ProtoMethodMayReturnNull|ProtoMethodAcceptsNullParameter|" + "ProtoPassThroughNullness" + ")$") .asPredicate(); private NullnessAnnotations() {} // static methods only public static Optional<Nullness> fromAnnotations(Collection<String> annotations) { return fromAnnotationStream(annotations.stream()); } public static Optional<Nullness> fromAnnotationsOn(@Nullable Symbol sym) { if (sym == null) { return Optional.empty(); } /* * We try to read annotations in two ways: * * 1. from the TypeMirror: This is how we "should" always read *type-use* annotations, but * JDK-8225377 prevents it from working across compilation boundaries. * * 2. from getRawAttributes(): This works around the problem across compilation boundaries, and * it handles declaration annotations (though there are other ways we could handle declaration * annotations). But it has a bug of its own with type-use annotations on inner classes * (b/203207989). To reduce the chance that we hit the inner-class bug, we apply it only if the * first approach fails. */ TypeMirror elementType; switch (sym.getKind()) { case METHOD: elementType = ((ExecutableElement) sym).getReturnType(); break; case FIELD: case PARAMETER: elementType = sym.asType(); break; default: elementType = null; } Optional<Nullness> fromElement = fromAnnotationsOn(elementType); if (fromElement.isPresent()) { return fromElement; } return fromAnnotationStream( MoreAnnotations.getDeclarationAndTypeAttributes(sym).map(Object::toString)); } public static Optional<Nullness> fromAnnotationsOn(@Nullable TypeMirror type) { if (type != null) { return fromAnnotationList(type.getAnnotationMirrors()); } return Optional.empty(); } /** * Walks the syntactically enclosing elements of the given element until it finds a defaulting * annotation. */ // Note this may be a good candidate for caching public static Optional<Nullness> fromDefaultAnnotations(@Nullable Element sym) { while (sym != null) { // Just look through declaration annotations here for simplicitly; default annotations aren't // type annotations. For now we're just using a hard-coded simple name. // TODO(b/121272440): Look for existing default annotations if (sym.getAnnotationMirrors().stream() .map(Object::toString) .anyMatch(it -> it.endsWith(".DefaultNotNull"))) { return Optional.of(Nullness.NONNULL); } sym = sym.getEnclosingElement(); } return Optional.empty(); } /** * Returns any declared or implied bound for the given type variable, meaning this returns any * annotation on the given type variable and otherwise returns {@link #fromDefaultAnnotations} to * find any default in scope of the given type variable. */ public static Optional<Nullness> getUpperBound(TypeVariable typeVar) { // Annotations on bounds at type variable declaration Optional<Nullness> result; if (typeVar.getUpperBound() instanceof IntersectionType) { // For intersection types, use the lower bound of any annotations on the individual bounds result = fromAnnotationStream( ((IntersectionType) typeVar.getUpperBound()) .getBounds().stream() .map(TypeMirror::getAnnotationMirrors) .map(Object::toString)); } else { result = fromAnnotationsOn(typeVar.getUpperBound()); } if (result.isPresent()) { // If upper bound is annotated, return that, ignoring annotations on the type variable itself. // This gets the upper bound for <T extends @Nullable Object> whether T is annotated or not. return result; } // Only if the bound isn't annotated, look for an annotation on the type variable itself and // treat that as the upper bound. This handles "interface I<@NonNull|@Nullable T>" as a bound. if (typeVar.asElement().getKind() == TYPE_PARAMETER) { Element genericElt = ((TypeParameterElement) typeVar.asElement()).getGenericElement(); if (genericElt.getKind().isClass() || genericElt.getKind().isInterface() || genericElt.getKind() == ElementKind.METHOD) { result = ((Parameterizable) genericElt) .getTypeParameters().stream() .filter( typeParam -> typeParam.getSimpleName().equals(typeVar.asElement().getSimpleName())) .findFirst() // Annotations at class/interface/method type variable declaration .flatMap(decl -> fromAnnotationList(decl.getAnnotationMirrors())); } } // If the type variable doesn't have an explicit bound, see if its declaration is in the scope // of a default and use that as the bound. return result.isPresent() ? result : fromDefaultAnnotations(typeVar.asElement()); } private static Optional<Nullness> fromAnnotationList(List<?> annotations) { return fromAnnotationStream(annotations.stream().map(Object::toString)); } private static Optional<Nullness> fromAnnotationStream(Stream<String> annotations) { return annotations .filter(ANNOTATION_RELEVANT_TO_NULLNESS) .map(annot -> NULLABLE_ANNOTATION.test(annot) ? Nullness.NULLABLE : Nullness.NONNULL) .reduce(Nullness::greatestLowerBound); } }
7,885
40.287958
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/AbstractNullnessPropagationTransfer.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.BOTTOM; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NONNULL; import static com.google.errorprone.dataflow.nullnesspropagation.Nullness.NULLABLE; import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTransfer.tryGetMethodSymbol; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.dataflow.AccessPath; import com.google.errorprone.dataflow.AccessPathStore; import com.google.errorprone.dataflow.AccessPathValues; import java.util.HashMap; import java.util.List; import java.util.Map; import org.checkerframework.errorprone.dataflow.analysis.ConditionalTransferResult; import org.checkerframework.errorprone.dataflow.analysis.ForwardTransferFunction; import org.checkerframework.errorprone.dataflow.analysis.RegularTransferResult; import org.checkerframework.errorprone.dataflow.analysis.TransferInput; import org.checkerframework.errorprone.dataflow.analysis.TransferResult; import org.checkerframework.errorprone.dataflow.cfg.UnderlyingAST; import org.checkerframework.errorprone.dataflow.cfg.node.ArrayAccessNode; import org.checkerframework.errorprone.dataflow.cfg.node.ArrayCreationNode; import org.checkerframework.errorprone.dataflow.cfg.node.ArrayTypeNode; import org.checkerframework.errorprone.dataflow.cfg.node.AssertionErrorNode; import org.checkerframework.errorprone.dataflow.cfg.node.AssignmentNode; import org.checkerframework.errorprone.dataflow.cfg.node.BitwiseAndNode; import org.checkerframework.errorprone.dataflow.cfg.node.BitwiseComplementNode; import org.checkerframework.errorprone.dataflow.cfg.node.BitwiseOrNode; import org.checkerframework.errorprone.dataflow.cfg.node.BitwiseXorNode; import org.checkerframework.errorprone.dataflow.cfg.node.BooleanLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.CaseNode; import org.checkerframework.errorprone.dataflow.cfg.node.CharacterLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.ClassDeclarationNode; import org.checkerframework.errorprone.dataflow.cfg.node.ClassNameNode; import org.checkerframework.errorprone.dataflow.cfg.node.ConditionalAndNode; import org.checkerframework.errorprone.dataflow.cfg.node.ConditionalNotNode; import org.checkerframework.errorprone.dataflow.cfg.node.ConditionalOrNode; import org.checkerframework.errorprone.dataflow.cfg.node.DoubleLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.EqualToNode; import org.checkerframework.errorprone.dataflow.cfg.node.ExplicitThisNode; import org.checkerframework.errorprone.dataflow.cfg.node.ExpressionStatementNode; import org.checkerframework.errorprone.dataflow.cfg.node.FieldAccessNode; import org.checkerframework.errorprone.dataflow.cfg.node.FloatLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.FloatingDivisionNode; import org.checkerframework.errorprone.dataflow.cfg.node.FloatingRemainderNode; import org.checkerframework.errorprone.dataflow.cfg.node.FunctionalInterfaceNode; import org.checkerframework.errorprone.dataflow.cfg.node.GreaterThanNode; import org.checkerframework.errorprone.dataflow.cfg.node.GreaterThanOrEqualNode; import org.checkerframework.errorprone.dataflow.cfg.node.ImplicitThisNode; import org.checkerframework.errorprone.dataflow.cfg.node.InstanceOfNode; import org.checkerframework.errorprone.dataflow.cfg.node.IntegerDivisionNode; import org.checkerframework.errorprone.dataflow.cfg.node.IntegerLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.IntegerRemainderNode; import org.checkerframework.errorprone.dataflow.cfg.node.LambdaResultExpressionNode; import org.checkerframework.errorprone.dataflow.cfg.node.LeftShiftNode; import org.checkerframework.errorprone.dataflow.cfg.node.LessThanNode; import org.checkerframework.errorprone.dataflow.cfg.node.LessThanOrEqualNode; import org.checkerframework.errorprone.dataflow.cfg.node.LocalVariableNode; import org.checkerframework.errorprone.dataflow.cfg.node.LongLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.MarkerNode; import org.checkerframework.errorprone.dataflow.cfg.node.MethodAccessNode; import org.checkerframework.errorprone.dataflow.cfg.node.MethodInvocationNode; import org.checkerframework.errorprone.dataflow.cfg.node.NarrowingConversionNode; import org.checkerframework.errorprone.dataflow.cfg.node.Node; import org.checkerframework.errorprone.dataflow.cfg.node.NotEqualNode; import org.checkerframework.errorprone.dataflow.cfg.node.NullChkNode; import org.checkerframework.errorprone.dataflow.cfg.node.NullLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.NumericalAdditionNode; import org.checkerframework.errorprone.dataflow.cfg.node.NumericalMinusNode; import org.checkerframework.errorprone.dataflow.cfg.node.NumericalMultiplicationNode; import org.checkerframework.errorprone.dataflow.cfg.node.NumericalPlusNode; import org.checkerframework.errorprone.dataflow.cfg.node.NumericalSubtractionNode; import org.checkerframework.errorprone.dataflow.cfg.node.ObjectCreationNode; import org.checkerframework.errorprone.dataflow.cfg.node.PackageNameNode; import org.checkerframework.errorprone.dataflow.cfg.node.ParameterizedTypeNode; import org.checkerframework.errorprone.dataflow.cfg.node.PrimitiveTypeNode; import org.checkerframework.errorprone.dataflow.cfg.node.ReturnNode; import org.checkerframework.errorprone.dataflow.cfg.node.ShortLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.SignedRightShiftNode; import org.checkerframework.errorprone.dataflow.cfg.node.StringConcatenateAssignmentNode; import org.checkerframework.errorprone.dataflow.cfg.node.StringConcatenateNode; import org.checkerframework.errorprone.dataflow.cfg.node.StringConversionNode; import org.checkerframework.errorprone.dataflow.cfg.node.StringLiteralNode; import org.checkerframework.errorprone.dataflow.cfg.node.SuperNode; import org.checkerframework.errorprone.dataflow.cfg.node.SwitchExpressionNode; import org.checkerframework.errorprone.dataflow.cfg.node.SynchronizedNode; import org.checkerframework.errorprone.dataflow.cfg.node.TernaryExpressionNode; import org.checkerframework.errorprone.dataflow.cfg.node.ThrowNode; import org.checkerframework.errorprone.dataflow.cfg.node.TypeCastNode; import org.checkerframework.errorprone.dataflow.cfg.node.UnsignedRightShiftNode; import org.checkerframework.errorprone.dataflow.cfg.node.VariableDeclarationNode; import org.checkerframework.errorprone.dataflow.cfg.node.WideningConversionNode; /** * A default implementation of a transfer function for nullability analysis with more convenient * visitor methods. The default implementation consists of labeling almost every kind of node as * {@code NULLABLE}. The convenient visitor methods consist first of "summary" methods, like the * {@code visitValueLiteral} method called for every {@code ValueLiteralNode} (like {@code * AbstractNodeVisitor}), and second of more targeted parameters to the individual {@code visit*} * methods. For example, a {@code visitTypeCast} does not need access to the full {@link * TransferInput}{@code <Nullness, NullnessPropagationStore>}, only to {@linkplain * TransferInput#getValueOfSubNode the subnode values it provides}. To accomplish this, this class * provides a {@code final} implementation of the inherited {@code visitTypeCast} method that * delegates to an overrideable {@code visitTypeCast} method with simpler parameters. * * <p>Despite being "abstract," this class is fairly tightly coupled to its sole current * implementation, {@link NullnessPropagationTransfer}. I expect that changes to that class will * sometimes require corresponding changes to this one. The value of separating the two classes * isn't in decoupling the two so much as in hiding the boilerplate in this class. * * @author cpovirk@google.com (Chris Povirk) */ abstract class AbstractNullnessPropagationTransfer implements ForwardTransferFunction<Nullness, AccessPathStore<Nullness>> { @Override public AccessPathStore<Nullness> initialStore( UnderlyingAST underlyingAST, List<LocalVariableNode> parameters) { return AccessPathStore.empty(); } /** * Provides the previously computed nullness values of descendant nodes. All descendant nodes have * already been assigned a value, if only the default of {@code NULLABLE}. */ interface SubNodeValues { Nullness valueOfSubNode(Node node); } /** * Receives updates to the nullness values of local parameters. The transfer function * implementation calls {@link #set} when it can conclude that a variable must have a given * nullness value upon successful (non-exceptional) execution of the current node's expression. */ interface Updates { // TODO(cpovirk): consider the API setIfLocalVariable(Node, Nullness) void set(LocalVariableNode node, Nullness value); void set(VariableDeclarationNode node, Nullness value); void set(FieldAccessNode node, Nullness value); void set(AccessPath path, Nullness value); } /** "Summary" method called by default for every {@code ValueLiteralNode}. */ Nullness visitValueLiteral() { return NULLABLE; } /** "Summary" method called by default for bitwise operations. */ Nullness visitBitwiseOperation() { return NULLABLE; } /** "Summary" method called by default for numerical comparisons. */ Nullness visitNumericalComparison() { return NULLABLE; } /** "Summary" method called by default for numerical operations. */ Nullness visitNumericalOperation() { return NULLABLE; } /** "Summary" method called by default for every {@code ThisNode}. */ Nullness visitThis() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNullLiteral( NullLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitNullLiteral(); return updateRegularStore(result, input, updates); } Nullness visitNullLiteral() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitTypeCast( TypeCastNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitTypeCast(node, values(input)); return noStoreChanges(result, input); } Nullness visitTypeCast(TypeCastNode node, SubNodeValues inputs) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNumericalAddition( NumericalAdditionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitNumericalAddition(); return noStoreChanges(result, input); } Nullness visitNumericalAddition() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNarrowingConversion( NarrowingConversionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitNarrowingConversion(); return noStoreChanges(result, input); } Nullness visitNarrowingConversion() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitEqualTo( EqualToNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates thenUpdates = new ReadableUpdates(); ReadableUpdates elseUpdates = new ReadableUpdates(); visitEqualTo(node, values(input), thenUpdates, elseUpdates); ResultingStore thenStore = updateStore(input.getThenStore(), thenUpdates); ResultingStore elseStore = updateStore(input.getElseStore(), elseUpdates); return conditionalResult( thenStore.store, elseStore.store, thenStore.storeChanged || elseStore.storeChanged); } void visitEqualTo( EqualToNode node, SubNodeValues inputs, Updates thenUpdates, Updates elseUpdates) {} @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNotEqual( NotEqualNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates thenUpdates = new ReadableUpdates(); ReadableUpdates elseUpdates = new ReadableUpdates(); visitNotEqual(node, values(input), thenUpdates, elseUpdates); ResultingStore thenStore = updateStore(input.getThenStore(), thenUpdates); ResultingStore elseStore = updateStore(input.getElseStore(), elseUpdates); return conditionalResult( thenStore.store, elseStore.store, thenStore.storeChanged || elseStore.storeChanged); } void visitNotEqual( NotEqualNode node, SubNodeValues inputs, Updates thenUpdates, Updates elseUpdates) {} @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitAssignment( AssignmentNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitAssignment(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitAssignment(AssignmentNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitLocalVariable( LocalVariableNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitLocalVariable(node, input.getRegularStore()); return updateRegularStore(result, input, updates); } Nullness visitLocalVariable(LocalVariableNode node, AccessPathValues<Nullness> store) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitFieldAccess( FieldAccessNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitFieldAccess(node, updates, input.getRegularStore()); return updateRegularStore(result, input, updates); } Nullness visitFieldAccess( FieldAccessNode node, Updates updates, AccessPathValues<Nullness> store) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitMethodInvocation( MethodInvocationNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates thenUpdates = new ReadableUpdates(); ReadableUpdates elseUpdates = new ReadableUpdates(); ReadableUpdates bothUpdates = new ReadableUpdates(); Nullness result = visitMethodInvocation(node, thenUpdates, elseUpdates, bothUpdates); /* * Returning a ConditionalTransferResult for a non-boolean node causes weird test failures, even * if I'm careful to give it its correct Nullness instead of hardcoding it to NONNULL as the * current code does. To avoid problems, we return a RegularTransferResult when possible. */ if (tryGetMethodSymbol(node.getTree(), null).isBoolean) { ResultingStore thenStore = updateStore(input.getThenStore(), thenUpdates, bothUpdates); ResultingStore elseStore = updateStore(input.getElseStore(), elseUpdates, bothUpdates); return conditionalResult( thenStore.store, elseStore.store, thenStore.storeChanged || elseStore.storeChanged); } else { return updateRegularStore(result, input, bothUpdates); } } Nullness visitMethodInvocation( MethodInvocationNode node, Updates thenUpdates, Updates elseUpdates, Updates bothUpdates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitConditionalAnd( ConditionalAndNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { return conditionalResult(input.getThenStore(), input.getElseStore(), NO_STORE_CHANGE); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitConditionalOr( ConditionalOrNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { return conditionalResult(input.getThenStore(), input.getElseStore(), NO_STORE_CHANGE); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitConditionalNot( ConditionalNotNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { /* * Weird case: We swap the contents of the THEN and ELSE stores without otherwise modifying * them. Presumably that can still count as a change? */ boolean storeChanged = !input.getThenStore().equals(input.getElseStore()); return conditionalResult( /* thenStore= */ input.getElseStore(), /* elseStore= */ input.getThenStore(), storeChanged); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitObjectCreation( ObjectCreationNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitObjectCreation(); return noStoreChanges(result, input); } Nullness visitObjectCreation() { return NULLABLE; } private static TransferResult<Nullness, AccessPathStore<Nullness>> noStoreChanges( Nullness value, TransferInput<?, AccessPathStore<Nullness>> input) { return new RegularTransferResult<>(value, input.getRegularStore()); } @CheckReturnValue private static TransferResult<Nullness, AccessPathStore<Nullness>> updateRegularStore( Nullness value, TransferInput<?, AccessPathStore<Nullness>> input, ReadableUpdates updates) { ResultingStore newStore = updateStore(input.getRegularStore(), updates); return new RegularTransferResult<>(value, newStore.store, newStore.storeChanged); } private static TransferResult<Nullness, AccessPathStore<Nullness>> conditionalResult( AccessPathStore<Nullness> thenStore, AccessPathStore<Nullness> elseStore, boolean storeChanged) { return new ConditionalTransferResult<>(NONNULL, thenStore, elseStore, storeChanged); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitShortLiteral( ShortLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitShortLiteral(); return noStoreChanges(result, input); } Nullness visitShortLiteral() { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitIntegerLiteral( IntegerLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitIntegerLiteral(); return noStoreChanges(result, input); } Nullness visitIntegerLiteral() { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitLongLiteral( LongLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitLongLiteral(); return noStoreChanges(result, input); } Nullness visitLongLiteral() { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitFloatLiteral( FloatLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitFloatLiteral(); return noStoreChanges(result, input); } Nullness visitFloatLiteral() { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitDoubleLiteral( DoubleLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitDoubleLiteral(); return noStoreChanges(result, input); } Nullness visitDoubleLiteral() { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitBooleanLiteral( BooleanLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitBooleanLiteral(); return noStoreChanges(result, input); } Nullness visitBooleanLiteral() { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitCharacterLiteral( CharacterLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitCharacterLiteral(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitCharacterLiteral(CharacterLiteralNode node, SubNodeValues inputs, Updates updates) { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitStringLiteral( StringLiteralNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitStringLiteral(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitStringLiteral(StringLiteralNode node, SubNodeValues inputs, Updates updates) { return visitValueLiteral(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNumericalMinus( NumericalMinusNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitNumericalMinus(); return noStoreChanges(value, input); } Nullness visitNumericalMinus() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNumericalPlus( NumericalPlusNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitNumericalPlus(); return noStoreChanges(value, input); } Nullness visitNumericalPlus() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitBitwiseComplement( BitwiseComplementNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitBitwiseComplement(); return noStoreChanges(value, input); } Nullness visitBitwiseComplement() { return visitBitwiseOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNullChk( NullChkNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitNullChk(); return noStoreChanges(value, input); } Nullness visitNullChk() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitStringConcatenate( StringConcatenateNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitStringConcatenate(); return noStoreChanges(value, input); } Nullness visitStringConcatenate() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNumericalSubtraction( NumericalSubtractionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitNumericalSubtraction(); return noStoreChanges(value, input); } Nullness visitNumericalSubtraction() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitNumericalMultiplication( NumericalMultiplicationNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitNumericalMultiplication(); return noStoreChanges(value, input); } Nullness visitNumericalMultiplication() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitIntegerDivision( IntegerDivisionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitIntegerDivision(); return noStoreChanges(value, input); } Nullness visitIntegerDivision() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitFloatingDivision( FloatingDivisionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitFloatingDivision(); return noStoreChanges(value, input); } Nullness visitFloatingDivision() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitIntegerRemainder( IntegerRemainderNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitIntegerRemainder(); return noStoreChanges(value, input); } Nullness visitIntegerRemainder() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitFloatingRemainder( FloatingRemainderNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitFloatingRemainder(); return noStoreChanges(value, input); } Nullness visitFloatingRemainder() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitLeftShift( LeftShiftNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitLeftShift(); return noStoreChanges(value, input); } Nullness visitLeftShift() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitSignedRightShift( SignedRightShiftNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitSignedRightShift(); return noStoreChanges(value, input); } Nullness visitSignedRightShift() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitUnsignedRightShift( UnsignedRightShiftNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitUnsignedRightShift(); return noStoreChanges(value, input); } Nullness visitUnsignedRightShift() { return visitNumericalOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitBitwiseAnd( BitwiseAndNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitBitwiseAnd(); return noStoreChanges(value, input); } Nullness visitBitwiseAnd() { return visitBitwiseOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitBitwiseOr( BitwiseOrNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitBitwiseOr(); return noStoreChanges(value, input); } Nullness visitBitwiseOr() { return visitBitwiseOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitBitwiseXor( BitwiseXorNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitBitwiseXor(); return noStoreChanges(value, input); } Nullness visitBitwiseXor() { return visitBitwiseOperation(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitStringConcatenateAssignment( StringConcatenateAssignmentNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitStringConcatenateAssignment(); return noStoreChanges(value, input); } Nullness visitStringConcatenateAssignment() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitLessThan( LessThanNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitLessThan(); return noStoreChanges(value, input); } Nullness visitLessThan() { return visitNumericalComparison(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitLessThanOrEqual( LessThanOrEqualNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitLessThanOrEqual(); return noStoreChanges(value, input); } Nullness visitLessThanOrEqual() { return visitNumericalComparison(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitGreaterThan( GreaterThanNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitGreaterThan(); return noStoreChanges(value, input); } Nullness visitGreaterThan() { return visitNumericalComparison(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitGreaterThanOrEqual( GreaterThanOrEqualNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitGreaterThanOrEqual(); return noStoreChanges(value, input); } Nullness visitGreaterThanOrEqual() { return visitNumericalComparison(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitTernaryExpression( TernaryExpressionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitTernaryExpression(node, values(input)); // TODO(kmb): Return conditional result if node itself is of boolean type, as for method calls return noStoreChanges(result, input); } Nullness visitTernaryExpression(TernaryExpressionNode node, SubNodeValues inputs) { return inputs .valueOfSubNode(node.getThenOperand()) .leastUpperBound(inputs.valueOfSubNode(node.getElseOperand())); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitVariableDeclaration( VariableDeclarationNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); visitVariableDeclaration(node, values(input), updates); /* * We can return whatever we want here because a variable declaration is not an expression and * thus no one can use its value directly. Any updates to the nullness of the variable are * performed in the store so that they are available to future reads. */ Nullness result = BOTTOM; return updateRegularStore(result, input, updates); } void visitVariableDeclaration( VariableDeclarationNode node, SubNodeValues inputs, Updates updates) {} @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitMethodAccess( MethodAccessNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitMethodAccess(); return noStoreChanges(value, input); } Nullness visitMethodAccess() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitArrayAccess( ArrayAccessNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitArrayAccess(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitArrayAccess(ArrayAccessNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitImplicitThis( ImplicitThisNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitImplicitThis(); return noStoreChanges(value, input); } Nullness visitImplicitThis() { return visitThis(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitExplicitThis( ExplicitThisNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitExplicitThis(); return noStoreChanges(value, input); } Nullness visitExplicitThis() { return visitThis(); } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitSuper( SuperNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitSuper(); return noStoreChanges(value, input); } Nullness visitSuper() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitReturn( ReturnNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitReturn(); return noStoreChanges(value, input); } Nullness visitReturn() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitLambdaResultExpression( LambdaResultExpressionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitLambdaResultExpression(); return noStoreChanges(value, input); } Nullness visitLambdaResultExpression() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitStringConversion( StringConversionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitStringConversion(); return noStoreChanges(value, input); } Nullness visitStringConversion() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitWideningConversion( WideningConversionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitWideningConversion(); return noStoreChanges(value, input); } Nullness visitWideningConversion() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitInstanceOf( InstanceOfNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates thenUpdates = new ReadableUpdates(); ReadableUpdates elseUpdates = new ReadableUpdates(); Nullness result = visitInstanceOf(node, values(input), thenUpdates, elseUpdates); ResultingStore thenStore = updateStore(input.getThenStore(), thenUpdates); ResultingStore elseStore = updateStore(input.getElseStore(), elseUpdates); return new ConditionalTransferResult<>( result, thenStore.store, elseStore.store, thenStore.storeChanged || elseStore.storeChanged); } Nullness visitInstanceOf( InstanceOfNode node, SubNodeValues inputs, Updates thenUpdates, Updates elseUpdates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitSwitchExpressionNode( SwitchExpressionNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitSwitchExpression(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitSwitchExpression(SwitchExpressionNode node, SubNodeValues inputs, Updates updates) { // TODO(b/217592536): Implement switch expressions return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitSynchronized( SynchronizedNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitSynchronized(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitSynchronized(SynchronizedNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitAssertionError( AssertionErrorNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitAssertionError(); return noStoreChanges(value, input); } Nullness visitAssertionError() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitThrow( ThrowNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitThrow(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitThrow(ThrowNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitCase( CaseNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitCase(); return noStoreChanges(value, input); } Nullness visitCase() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitMemberReference( FunctionalInterfaceNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitMemberReference(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitMemberReference( FunctionalInterfaceNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitArrayCreation( ArrayCreationNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitArrayCreation(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitArrayCreation(ArrayCreationNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitArrayType( ArrayTypeNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitArrayType(); return noStoreChanges(value, input); } Nullness visitArrayType() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitPrimitiveType( PrimitiveTypeNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitPrimitiveType(); return noStoreChanges(value, input); } Nullness visitPrimitiveType() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitClassName( ClassNameNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitClassName(); return noStoreChanges(value, input); } Nullness visitClassName() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitPackageName( PackageNameNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitPackageName(); return noStoreChanges(value, input); } Nullness visitPackageName() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitParameterizedType( ParameterizedTypeNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness value = visitParameterizedType(); return noStoreChanges(value, input); } Nullness visitParameterizedType() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitMarker( MarkerNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { ReadableUpdates updates = new ReadableUpdates(); Nullness result = visitMarker(node, values(input), updates); return updateRegularStore(result, input, updates); } Nullness visitMarker(MarkerNode node, SubNodeValues inputs, Updates updates) { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitClassDeclaration( ClassDeclarationNode classDeclarationNode, TransferInput<Nullness, AccessPathStore<Nullness>> input) { Nullness result = visitClassDeclaration(); return noStoreChanges(result, input); } Nullness visitClassDeclaration() { return NULLABLE; } @Override public final TransferResult<Nullness, AccessPathStore<Nullness>> visitExpressionStatement( ExpressionStatementNode node, TransferInput<Nullness, AccessPathStore<Nullness>> input) { /* * The fact that something is an expression statement is presumably irrelevant to nullness. So * probably no code looks at this result. And if the statement needs to update the store * somehow, that gets handled by the other visit* methods. I think. * * See * https://github.com/eisop/checker-framework/blob/7c5e731da5665cba0612e8c85287d380fd66e924/dataflow/src/main/java/org/checkerframework/dataflow/cfg/node/ExpressionStatementNode.java#L20 */ return noStoreChanges(NONNULL, input); } private static final class ReadableUpdates implements Updates { final Map<AccessPath, Nullness> values = new HashMap<>(); @Override public void set(LocalVariableNode node, Nullness value) { values.put(AccessPath.fromLocalVariable(node), checkNotNull(value)); } @Override public void set(VariableDeclarationNode node, Nullness value) { values.put(AccessPath.fromVariableDecl(node), checkNotNull(value)); } @Override public void set(FieldAccessNode node, Nullness value) { AccessPath path = AccessPath.fromFieldAccess(node); if (path != null) { values.put(path, checkNotNull(value)); } } @Override public void set(AccessPath path, Nullness value) { values.put(checkNotNull(path), checkNotNull(value)); } } @CheckReturnValue private static ResultingStore updateStore( AccessPathStore<Nullness> oldStore, ReadableUpdates... updates) { AccessPathStore.Builder<Nullness> builder = oldStore.toBuilder(); for (ReadableUpdates update : updates) { for (Map.Entry<AccessPath, Nullness> entry : update.values.entrySet()) { builder.setInformation(entry.getKey(), entry.getValue()); } } AccessPathStore<Nullness> newStore = builder.build(); return new ResultingStore(newStore, !newStore.equals(oldStore)); } private static SubNodeValues values(TransferInput<Nullness, AccessPathStore<Nullness>> input) { return input::getValueOfSubNode; } private static final class ResultingStore { final AccessPathStore<Nullness> store; final boolean storeChanged; ResultingStore(AccessPathStore<Nullness> store, boolean storeChanged) { this.store = store; this.storeChanged = storeChanged; } } private static final boolean NO_STORE_CHANGE = false; }
43,567
38.824497
190
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/Nullness.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import org.checkerframework.errorprone.dataflow.analysis.AbstractValue; /** * Represents one of the possible nullness values in our nullness analysis. * * @author deminguyen@google.com (Demi Nguyen) */ public enum Nullness implements AbstractValue<Nullness> { /** * The lattice for nullness looks like: * * <pre> * Nullable * / \ * Null Non-null * \ / * Bottom * </pre> */ NULLABLE("Nullable"), // TODO(eaftan): Rename to POSSIBLY_NULL? NULL("Null"), NONNULL("Non-null"), BOTTOM("Bottom"); private final String displayName; Nullness(String displayName) { this.displayName = displayName; } // The following leastUpperBound and greatestLowerBound methods were created by handwriting a // truth table and then encoding the values into these functions. A better approach would be to // represent the lattice directly and compute these functions from the lattice. @Override public Nullness leastUpperBound(Nullness other) { if (this == other) { return this; } // Bottom loses. if (this == BOTTOM) { return other; } if (other == BOTTOM) { return this; } // They disagree, and neither is bottom. return NULLABLE; } public Nullness greatestLowerBound(Nullness other) { if (this == other) { return this; } // Nullable loses. if (this == NULLABLE) { return other; } if (other == NULLABLE) { return this; } // They disagree, and neither is nullable. return BOTTOM; } /** * Returns the {@code Nullness} that corresponds to what you can deduce by knowing that some * expression is not equal to another expression with this {@code Nullness}. * * <p>A {@code Nullness} represents a set of possible values for a expression. Suppose you have * two variables {@code var1} and {@code var2}. If {@code var1 != var2}, then {@code var1} must be * an element of the complement of the singleton set containing the value of {@code var2}. If you * union these complement sets over all possible values of {@code var2}, the set that results is * what this method returns, assuming that {@code this} is the {@code Nullness} of {@code var2}. * * <p>Example 1: Suppose {@code nv2 == NULL}. Then {@code var2} can have exactly one value, {@code * null}, and {@code var1} must have a value in the set of all values except {@code null}. That * set is exactly {@code NONNULL}. * * <p>Example 2: Suppose {@code nv2 == NONNULL}. Then {@code var2} can have any value except * {@code null}. Suppose {@code var2} has value {@code "foo"}. Then {@code var1} must have a value * in the set of all values except {@code "foo"}. Now suppose {@code var2} has value {@code "bar"} * . Then {@code var1} must have a value in set of all values except {@code "bar"}. Since we don't * know which value in the set {@code NONNULL var2} has, we union all possible complement sets to * get the set of all values, or {@code NULLABLE}. */ public Nullness deducedValueWhenNotEqual() { switch (this) { case NULLABLE: case NONNULL: return NULLABLE; case NULL: return NONNULL; case BOTTOM: return BOTTOM; default: throw new AssertionError("Inverse of " + this + " not defined"); } } @Override public String toString() { return displayName; } }
4,134
32.08
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/TrustingNullnessPropagation.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation; import com.google.common.base.Predicate; import com.google.errorprone.dataflow.AccessPath; import com.google.errorprone.dataflow.AccessPathValues; import java.util.List; import javax.annotation.Nullable; /** * Transfer function for {@link TrustingNullnessAnalysis}. It "trusts" annotations, meaning: * * <ul> * <li>The parameters of the analyzed method are assumed non-null unless annotated {@code * Nullable}. * <li>Field reads and method calls are assumed to return non-null unless annotated. * </ul> * * <p>This transfer function also uses {@link Nullness#NONNULL} as its default, which means: * * <ul> * <li>all array reads are assumed non-null. In the absence of Java 8 type annotations that * matches what we'll do for the result of {@link List#get} etc. Will need to revisit with * Java 8. * <li>we'll assume non-null for local variables we don't have any information about. Since we * seed {@link #initialStore} based on annotations on method parameters, the only known source * of unknown locals would be "local variables" from outer scopes accessed in anonymous and * local inner classes. * <li>in the case of missing method or field symbols, non-null is assumed as well. * </ul> */ // TODO(b/71812955): Respect type annotations on arrays // TODO(kmb): Use annotations on captured locals from outer scopes class TrustingNullnessPropagation extends NullnessPropagationTransfer { private static final long serialVersionUID = -3128676755493202966L; TrustingNullnessPropagation() { super(Nullness.NONNULL, TrustReturnAnnotation.INSTANCE); } @Override Nullness fieldNullness( @Nullable ClassAndField accessed, @Nullable AccessPath path, AccessPathValues<Nullness> store) { if (accessed == null) { return defaultAssumption; // optimistically assume non-null if we can't resolve } // TODO(kmb): Reverse subtyping between this class and NullnessPropagationTransfer to avoid this return standardFieldNullness(accessed, path, store); } /** Return {@code true} for methods not explicitly annotated Nullable. */ private enum TrustReturnAnnotation implements Predicate<MethodInfo> { INSTANCE; @Override public boolean apply(MethodInfo input) { return NullnessAnnotations.fromAnnotations(input.annotations()).orElse(Nullness.NONNULL) == Nullness.NONNULL; } } }
3,095
37.222222
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/NullnessQualifierInference.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation.inference; import static com.google.common.base.Preconditions.checkArgument; import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.LoadingCache; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Streams; import com.google.common.graph.GraphBuilder; import com.google.common.graph.MutableGraph; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.google.errorprone.dataflow.nullnesspropagation.NullnessAnnotations; import com.sun.source.tree.ArrayAccessTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.Tree; import com.sun.source.tree.Tree.Kind; import com.sun.source.tree.VariableTree; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symbol.MethodSymbol; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; import com.sun.tools.javac.code.Symbol.VarSymbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Type.ArrayType; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCArrayAccess; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; import com.sun.tools.javac.tree.JCTree.JCIdent; import com.sun.tools.javac.tree.JCTree.JCMethodInvocation; import com.sun.tools.javac.tree.TreeInfo; import java.util.ArrayDeque; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.function.Consumer; import javax.annotation.Nullable; import javax.lang.model.type.TypeVariable; /** * Eagerly traverse one {@code MethodTree} at a time and accumulate constraints between nullness * qualifiers. Those constraints are then solved as needed in {@code InferredNullability}. Based on * Java type inference as defined in JLS section 18. * * @author bennostein@google.com (Benno Stein) */ public class NullnessQualifierInference extends TreeScanner<Void, Void> { private static final LoadingCache<Tree, InferredNullability> inferenceCache = Caffeine.newBuilder() .maximumSize(1) .build( new CacheLoader<Tree, InferredNullability>() { @Override public InferredNullability load(Tree methodOrInitializer) { NullnessQualifierInference inferenceEngine = new NullnessQualifierInference(methodOrInitializer); inferenceEngine.scan(methodOrInitializer, null); return new InferredNullability(inferenceEngine.qualifierConstraints); } }); public static InferredNullability getInferredNullability(Tree methodOrInitializerOrLambda) { checkArgument( methodOrInitializerOrLambda instanceof MethodTree || methodOrInitializerOrLambda instanceof LambdaExpressionTree || methodOrInitializerOrLambda instanceof BlockTree || methodOrInitializerOrLambda instanceof VariableTree, "Tree `%s` is not a lambda, initializer, or method.", methodOrInitializerOrLambda); return inferenceCache.get(methodOrInitializerOrLambda); } /** * &lt;= constraints between inference variables: an edge from A to B means A &lt;= B. In other * words, edges point "upwards" in the lattice towards Top == Nullable. */ private final MutableGraph<InferenceVariable> qualifierConstraints; private final Tree currentMethodOrInitializerOrLambda; private NullnessQualifierInference(Tree currentMethodOrInitializerOrLambda) { this.currentMethodOrInitializerOrLambda = currentMethodOrInitializerOrLambda; this.qualifierConstraints = GraphBuilder.directed().build(); // Initialize graph with standard nullness lattice; see ASCII art diagram in // com.google.errorprone.dataflow.nullnesspropagation.Nullness for more details. qualifierConstraints.putEdge(ProperInferenceVar.BOTTOM, ProperInferenceVar.NONNULL); qualifierConstraints.putEdge(ProperInferenceVar.BOTTOM, ProperInferenceVar.NULL); qualifierConstraints.putEdge(ProperInferenceVar.NONNULL, ProperInferenceVar.NULLABLE); qualifierConstraints.putEdge(ProperInferenceVar.NULL, ProperInferenceVar.NULLABLE); } @Override public Void visitIdentifier(IdentifierTree node, Void unused) { Symbol sym = ((JCIdent) node).sym; if (sym instanceof VarSymbol) { Type declaredType = sym.type; generateConstraintsFromAnnotations( ((JCIdent) node).type, sym, declaredType, node, new ArrayDeque<>()); } return super.visitIdentifier(node, unused); } private void generateConstraintsFromAnnotations( Type inferredType, @Nullable Symbol decl, @Nullable Type declaredType, Tree sourceTree, ArrayDeque<Integer> argSelector) { List<Type> inferredTypeArguments = inferredType.getTypeArguments(); List<Type> declaredTypeArguments = declaredType != null ? declaredType.getTypeArguments() : ImmutableList.of(); int numberOfTypeArgs = inferredTypeArguments.size(); for (int i = 0; i < numberOfTypeArgs; i++) { argSelector.push(i); generateConstraintsFromAnnotations( inferredTypeArguments.get(i), decl, i < declaredTypeArguments.size() ? declaredTypeArguments.get(i) : null, sourceTree, argSelector); argSelector.pop(); } Optional<Nullness> fromAnnotations = extractExplicitNullness(declaredType, argSelector.isEmpty() ? decl : null); if (!fromAnnotations.isPresent()) { // Check declared type before inferred type so that type annotations on the declaration take // precedence (just like declaration annotations) over annotations on the inferred type. // For instance, we want a @Nullable T m() to take precedence over annotations on T's inferred // type (e.g., @NotNull String), whether @Nullable is a declaration or type annotation. fromAnnotations = NullnessAnnotations.fromAnnotationsOn(inferredType); } if (!fromAnnotations.isPresent()) { if (declaredType instanceof TypeVariable) { // Check bounds second so explicit annotations take precedence. Even for bounds we still use // equality constraint below since we have to assume the bound as the "worst" case. fromAnnotations = NullnessAnnotations.getUpperBound((TypeVariable) declaredType); } else { // Look for a default annotation in scope of either the symbol we're looking at or, if this // is a type variable, the type variable declaration's scope, which is effectively the type // variable's bound fromAnnotations = NullnessAnnotations.fromDefaultAnnotations(decl); } } // Use equality constraints even for top-level type, since we want to "trust" the annotation fromAnnotations .map(ProperInferenceVar::create) .ifPresent( annot -> { InferenceVariable var = TypeArgInferenceVar.create(ImmutableList.copyOf(argSelector), sourceTree); qualifierConstraints.putEdge(var, annot); qualifierConstraints.putEdge(annot, var); }); } @Override public Void visitAssignment(AssignmentTree node, Void unused) { Type lhsType = node.getVariable() instanceof ArrayAccessTree ? ((JCArrayAccess) node.getVariable()).getExpression().type : TreeInfo.symbol((JCTree) node.getVariable()).type; generateConstraintsForWrite(lhsType, null, node.getExpression(), node); return super.visitAssignment(node, unused); } @Override public Void visitVariable(VariableTree node, Void unused) { if (node.getInitializer() != null) { Symbol symbol = TreeInfo.symbolFor((JCTree) node); generateConstraintsForWrite(symbol.type, symbol, node.getInitializer(), node); } return super.visitVariable(node, unused); } @Override public Void visitReturn(ReturnTree node, Void unused) { if (node.getExpression() != null && currentMethodOrInitializerOrLambda instanceof MethodTree) { MethodSymbol sym = ((MethodSymbol) TreeInfo.symbolFor((JCTree) currentMethodOrInitializerOrLambda)); generateConstraintsForWrite(sym.getReturnType(), sym, node.getExpression(), node); } return super.visitReturn(node, unused); } private static ImmutableList<TypeAndSymbol> expandVarargsToArity( List<VarSymbol> formalArgs, int arity) { ImmutableList.Builder<TypeAndSymbol> result = ImmutableList.builderWithExpectedSize(arity); int numberOfVarArgs = arity - formalArgs.size() + 1; for (Iterator<VarSymbol> argsIterator = formalArgs.iterator(); argsIterator.hasNext(); ) { VarSymbol arg = argsIterator.next(); if (argsIterator.hasNext()) { // Not the variadic argument: just add to result result.add(TypeAndSymbol.create(arg.type, arg)); } else { // Variadic argument: extract the type and add it to result the proper number of times Type varArgType = ((ArrayType) arg.type).elemtype; for (int idx = 0; idx < numberOfVarArgs; idx++) { result.add(TypeAndSymbol.create(varArgType)); } } } return result.build(); } @Override public Void visitMethodInvocation(MethodInvocationTree node, Void unused) { JCMethodInvocation sourceNode = (JCMethodInvocation) node; MethodSymbol callee = (MethodSymbol) TreeInfo.symbol(sourceNode.getMethodSelect()); ImmutableList<TypeAndSymbol> formalParameters = callee.isVarArgs() ? expandVarargsToArity(callee.getParameters(), sourceNode.args.size()) : callee.getParameters().stream() .map(var -> TypeAndSymbol.create(var.type, var)) .collect(ImmutableList.toImmutableList()); // Generate constraints for each argument write. Streams.forEachPair( formalParameters.stream(), sourceNode.getArguments().stream(), (formal, actual) -> { // formal parameter type (no l-val b/c that would wrongly constrain the method return) generateConstraintsForWrite(formal.type(), formal.symbol(), actual, /* lVal= */ null); }); // Generate constraints for method return generateConstraintsFromAnnotations( sourceNode.type, callee, callee.getReturnType(), sourceNode, new ArrayDeque<>()); // If return type is parameterized by a generic type on receiver, collate references to that // generic between the receiver and the result/argument types. if (!callee.isStatic() && node.getMethodSelect() instanceof JCFieldAccess) { JCFieldAccess fieldAccess = ((JCFieldAccess) node.getMethodSelect()); for (TypeVariableSymbol tvs : fieldAccess.selected.type.tsym.getTypeParameters()) { Type rcvrtype = fieldAccess.selected.type.tsym.type; // Note this should be a singleton set, one for each type parameter ImmutableSet<InferenceVariable> rcvrReferences = findUnannotatedTypeVarRefs(tvs, rcvrtype, /* decl= */ null, fieldAccess.selected); Type restype = fieldAccess.sym.type.asMethodType().restype; findUnannotatedTypeVarRefs(tvs, restype, fieldAccess.sym, node) .forEach( resRef -> rcvrReferences.forEach( rcvrRef -> qualifierConstraints.putEdge(resRef, rcvrRef))); Streams.forEachPair( formalParameters.stream(), node.getArguments().stream(), (formal, actual) -> findUnannotatedTypeVarRefs(tvs, formal.type(), formal.symbol(), actual) .forEach( argRef -> rcvrReferences.forEach( rcvrRef -> qualifierConstraints.putEdge(argRef, rcvrRef)))); } } // Get all references to each typeVar in the return type and formal parameters and relate them // in the constraint graph; covariant in the return type, contravariant in the argument types. // Annotated type var references override the type var's inferred qualifier, so ignore them. // // Additionally generate equality constraints between inferred types that are instantiations of // type parameters. For instance, if a method type parameter <T> was instantiated List<String> // for a given call site m(x), and T appears in the return type as Optional<T>, then the // expression's inferred type will be Optional<List<String>> and we generate constraints to // equate T[0] = m(x)[0, 0]. If m's parameter's type is T then the argument type's inferred // type is List<String> and we also generate constraints to equate T[0] = x[0], which will // allow the inference to conclude later that x[0] = m(x)[0, 0], meaning the nullness qualifier // for x's <String> is the same as the one for m(x)'s <String>. for (TypeVariableSymbol typeVar : callee.getTypeParameters()) { TypeVariableInferenceVar typeVarIv = TypeVariableInferenceVar.create(typeVar, node); visitUnannotatedTypeVarRefsAndEquateInferredComponents( typeVarIv, callee.getReturnType(), callee, node, iv -> qualifierConstraints.putEdge(typeVarIv, iv)); Streams.forEachPair( formalParameters.stream(), node.getArguments().stream(), (formal, actual) -> visitUnannotatedTypeVarRefsAndEquateInferredComponents( typeVarIv, formal.type(), formal.symbol(), actual, iv -> qualifierConstraints.putEdge(iv, typeVarIv))); } return super.visitMethodInvocation(node, unused); } private static void visitTypeVarRefs( TypeVariableSymbol typeVar, Type declaredType, ArrayDeque<Integer> partialSelector, @Nullable Type inferredType, TypeComponentConsumer consumer) { List<Type> declaredTypeArguments = declaredType.getTypeArguments(); List<Type> inferredTypeArguments = inferredType != null ? inferredType.getTypeArguments() : ImmutableList.of(); for (int i = 0; i < declaredTypeArguments.size(); i++) { partialSelector.push(i); visitTypeVarRefs( typeVar, declaredTypeArguments.get(i), partialSelector, i < inferredTypeArguments.size() ? inferredTypeArguments.get(i) : null, consumer); partialSelector.pop(); } if (declaredType.tsym.equals(typeVar)) { consumer.accept(declaredType, partialSelector, inferredType); } } @FunctionalInterface private interface TypeComponentConsumer { void accept( Type declaredType, ArrayDeque<Integer> declaredTypeSelector, @Nullable Type inferredType); } private static ImmutableSet<InferenceVariable> findUnannotatedTypeVarRefs( TypeVariableSymbol typeVar, Type declaredType, @Nullable Symbol decl, Tree sourceNode) { ImmutableSet.Builder<InferenceVariable> result = ImmutableSet.builder(); visitTypeVarRefs( typeVar, declaredType, new ArrayDeque<>(), null, (typeVarRef, selector, unused) -> { if (!extractExplicitNullness(typeVarRef, selector.isEmpty() ? decl : null).isPresent()) { result.add(TypeArgInferenceVar.create(ImmutableList.copyOf(selector), sourceNode)); } }); return result.build(); } private void visitUnannotatedTypeVarRefsAndEquateInferredComponents( TypeVariableInferenceVar typeVar, Type type, @Nullable Symbol decl, Tree sourceNode, Consumer<TypeArgInferenceVar> consumer) { visitTypeVarRefs( typeVar.typeVar(), type, new ArrayDeque<>(), ((JCExpression) sourceNode).type, (declaredType, selector, inferredType) -> { if (!extractExplicitNullness(type, selector.isEmpty() ? decl : null).isPresent()) { consumer.accept(TypeArgInferenceVar.create(ImmutableList.copyOf(selector), sourceNode)); } if (inferredType == null) { return; } List<Type> typeArguments = inferredType.getTypeArguments(); int depth = selector.size(); for (int i = 0; i < typeArguments.size(); ++i) { selector.push(i); visitTypeComponents( typeArguments.get(i), selector, sourceNode, typeArg -> { TypeVariableInferenceVar typeVarComponent = typeVar.withSelector( typeArg .typeArgSelector() .subList(depth, typeArg.typeArgSelector().size())); qualifierConstraints.putEdge(typeVarComponent, typeArg); qualifierConstraints.putEdge(typeArg, typeVarComponent); }); selector.pop(); } }); } private static void visitTypeComponents( Type type, ArrayDeque<Integer> partialSelector, Tree sourceNode, Consumer<TypeArgInferenceVar> consumer) { List<Type> typeArguments = type.getTypeArguments(); for (int i = 0; i < typeArguments.size(); ++i) { partialSelector.push(i); visitTypeComponents(typeArguments.get(i), partialSelector, sourceNode, consumer); partialSelector.pop(); } consumer.accept(TypeArgInferenceVar.create(ImmutableList.copyOf(partialSelector), sourceNode)); } private static Optional<Nullness> extractExplicitNullness( @Nullable Type type, @Nullable Symbol symbol) { if (symbol != null) { Optional<Nullness> result = NullnessAnnotations.fromAnnotationsOn(symbol); if (result.isPresent()) { return result; } } return NullnessAnnotations.fromAnnotationsOn(type); } /** * Generate inference variable constraints derived from this write, including proper bounds from * type annotations on the declared type {@code lType} of the r-val as well as relationships * between type parameters of the l-val and r-val (if given). l-val is optional so this method is * usable for method arguments, and note that the l-val is a statement in other cases (return and * variable declarations); the l-val only appears useful when it's an assignment */ private void generateConstraintsForWrite( Type lType, @Nullable Symbol decl, ExpressionTree rVal, @Nullable Tree lVal) { // TODO(kmb): Consider just visiting these expression types if (rVal.getKind() == Kind.NULL_LITERAL) { qualifierConstraints.putEdge( ProperInferenceVar.NULL, TypeArgInferenceVar.create(ImmutableList.of(), rVal)); qualifierConstraints.putEdge( TypeArgInferenceVar.create(ImmutableList.of(), rVal), ProperInferenceVar.NULL); } else if ((rVal instanceof LiteralTree) || (rVal instanceof NewClassTree) || (rVal instanceof NewArrayTree) || ((rVal instanceof IdentifierTree) && ((IdentifierTree) rVal).getName().contentEquals("this"))) { qualifierConstraints.putEdge( ProperInferenceVar.NONNULL, TypeArgInferenceVar.create(ImmutableList.of(), rVal)); qualifierConstraints.putEdge( TypeArgInferenceVar.create(ImmutableList.of(), rVal), ProperInferenceVar.NONNULL); } generateConstraintsForWrite(lType, decl, rVal, lVal, new ArrayDeque<>()); } private void generateConstraintsForWrite( Type lType, @Nullable Symbol decl, ExpressionTree rVal, @Nullable Tree lVal, ArrayDeque<Integer> argSelector) { List<Type> typeArguments = lType.getTypeArguments(); for (int i = 0; i < typeArguments.size(); i++) { argSelector.push(i); generateConstraintsForWrite(typeArguments.get(i), decl, rVal, lVal, argSelector); argSelector.pop(); } ImmutableList<Integer> argSelectorList = ImmutableList.copyOf(argSelector); // If there is an explicit annotation, trust it and constrain the corresponding type arg // inference variable to be equal to that proper inference variable. boolean isBound = false; Optional<Nullness> fromAnnotations = extractExplicitNullness(lType, argSelector.isEmpty() ? decl : null); if (!fromAnnotations.isPresent()) { if (lType instanceof TypeVariable) { fromAnnotations = NullnessAnnotations.getUpperBound((TypeVariable) lType); isBound = true; } else { fromAnnotations = NullnessAnnotations.fromDefaultAnnotations(decl); } } // Top-level target types implicitly only constrain from above: for instance, a method // parameter annotated @Nullable can be called with a non-null argument just fine. Same // goes for bounded type parameters and ? extends @Nullable type parameters, but not for // invariant generic type parameters such as List<@Nullable String> which rVal needs to // satisfy exactly, so we generate equality constraints for those. boolean oneSided = isBound || argSelector.isEmpty(); fromAnnotations .map(ProperInferenceVar::create) .ifPresent( annot -> { InferenceVariable var = TypeArgInferenceVar.create(argSelectorList, rVal); qualifierConstraints.putEdge(var, annot); if (!oneSided) { qualifierConstraints.putEdge(annot, var); } }); if (lVal != null) { // Constrain this type or type argument on the rVal to be <= its lVal counterpart qualifierConstraints.putEdge( TypeArgInferenceVar.create(argSelectorList, rVal), TypeArgInferenceVar.create(argSelectorList, lVal)); } } /** Pair of a {@link Type} and an optional {@link Symbol}. */ @AutoValue abstract static class TypeAndSymbol { static TypeAndSymbol create(Type type) { return create(type, /* symbol= */ null); } static TypeAndSymbol create(Type type, @Nullable VarSymbol symbol) { return new AutoValue_NullnessQualifierInference_TypeAndSymbol(type, symbol); } abstract Type type(); @Nullable abstract VarSymbol symbol(); } }
23,477
42.72067
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/ProperInferenceVar.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation.inference; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; /** * Proper inference variables are thin wrappers around Nullness lattice elements, lifted so that * they can be compared other inference variables. */ enum ProperInferenceVar implements InferenceVariable { BOTTOM { @Override Nullness nullness() { return Nullness.BOTTOM; } }, NONNULL { @Override Nullness nullness() { return Nullness.NONNULL; } }, NULL { @Override Nullness nullness() { return Nullness.NULL; } }, NULLABLE { @Override Nullness nullness() { return Nullness.NULLABLE; } }; abstract Nullness nullness(); static InferenceVariable create(Nullness nullness) { switch (nullness) { case BOTTOM: return ProperInferenceVar.BOTTOM; case NONNULL: return ProperInferenceVar.NONNULL; case NULL: return ProperInferenceVar.NULL; case NULLABLE: return ProperInferenceVar.NULLABLE; } throw new RuntimeException("Unhandled nullness value: " + nullness); } }
1,774
25.492537
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/TypeVariableInferenceVar.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation.inference; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; /** * Type Variable inference variables correspond to type application sites, where type-polymorphic * methods are instantiated with a particular concrete type. */ @AutoValue abstract class TypeVariableInferenceVar implements InferenceVariable { static TypeVariableInferenceVar create( TypeVariableSymbol typeVar, MethodInvocationTree typeAppSite) { return create(typeVar, typeAppSite, ImmutableList.of()); } static TypeVariableInferenceVar create( TypeVariableSymbol typeVar, MethodInvocationTree typeAppSite, ImmutableList<Integer> typeArgSelector) { return new AutoValue_TypeVariableInferenceVar(typeVar, typeAppSite, typeArgSelector); } public final TypeVariableInferenceVar withSelector(ImmutableList<Integer> newSelector) { return create(typeVar(), typeApplicationSite(), newSelector); } abstract TypeVariableSymbol typeVar(); /** AST Node for a method invocation whose type is parameterized by the given type var. */ abstract MethodInvocationTree typeApplicationSite(); /** * An empty list selects the type variable itself, while non-empty lists select type variables * within the actual type the type variable was instantiated with at the application site, using * the format as described for {@link TypeArgInferenceVar}. * * <p>As a simple example, consider a method declared to return its only type variable, {@code T}. * For a given invocation of that method, let's say the type variable is instantiated as {@code * Map&lt;String, Integer&gt;}. Then, an empty selector here selects {@code T} itself, while a * selector [0] selects {@code String} and [1] selects {@code Integer}. */ abstract ImmutableList<Integer> typeArgSelector(); }
2,616
40.539683
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferenceVariable.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation.inference; /** * Inference variable for nullness qualifier inference, including both proper variables (i.e. * constant nullness lattice elements) and variables whose value needs to be inferred. */ interface InferenceVariable {}
900
36.541667
93
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/InferredNullability.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation.inference; import static com.google.common.base.Preconditions.checkState; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.graph.Graph; import com.google.common.graph.ImmutableGraph; import com.google.errorprone.dataflow.nullnesspropagation.Nullness; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Symbol.TypeVariableSymbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.TreeInfo; import java.util.HashMap; import java.util.Map; import java.util.Optional; /** * Results of running {@code NullnessQualifierInference} over a method. The {@code constraintGraph} * represents qualifier constraints as a directed graph, where graph reachability encodes a * less-than-or-equal-to relationship. */ public class InferredNullability { private final ImmutableGraph<InferenceVariable> constraintGraph; private final Map<InferenceVariable, Optional<Nullness>> inferredMemoTable = new HashMap<>(); InferredNullability(Graph<InferenceVariable> constraints) { this.constraintGraph = ImmutableGraph.copyOf(constraints); } /** * Get inferred nullness qualifiers for method-generic type variables at a callsite. When * inference is not possible for a given type variable, that type variable is not included in the * resulting map. */ public ImmutableMap<TypeVariableSymbol, Nullness> getNullnessGenerics( MethodInvocationTree callsite) { ImmutableMap.Builder<TypeVariableSymbol, Nullness> result = ImmutableMap.builder(); for (TypeVariableSymbol tvs : TreeInfo.symbol((JCTree) callsite.getMethodSelect()).getTypeParameters()) { InferenceVariable iv = TypeVariableInferenceVar.create(tvs, callsite); if (constraintGraph.nodes().contains(iv)) { getNullness(iv).ifPresent(nullness -> result.put(tvs, nullness)); } } return result.buildOrThrow(); } /** Get inferred nullness qualifier for an expression, if possible. */ public Optional<Nullness> getExprNullness(ExpressionTree exprTree) { InferenceVariable iv = TypeArgInferenceVar.create(ImmutableList.of(), exprTree); return constraintGraph.nodes().contains(iv) ? getNullness(iv) : Optional.empty(); } private Optional<Nullness> getNullness(InferenceVariable iv) { Optional<Nullness> result; // short-circuit and return if... // ...this inference variable is a `proper` bound, i.e. a concrete nullness lattice element if (iv instanceof ProperInferenceVar) { return Optional.of(((ProperInferenceVar) iv).nullness()); // ...we've already computed and memoized a nullness value for it. } else if ((result = inferredMemoTable.get(iv)) != null) { return result; } else { // In case of cycles in constraint graph, ensures base case to recursion inferredMemoTable.put(iv, Optional.empty()); // Resolution per JLS 18.4: // 1. resolve predecessors to see if there are lower bounds we can use result = constraintGraph.predecessors(iv).stream() .map(this::getNullness) .filter(Optional::isPresent) .map(Optional::get) .reduce(Nullness::leastUpperBound); // use least upper bound (lub) to combine // 2. If not, resolve successors and use them as upper bounds if (!result.isPresent()) { result = constraintGraph.successors(iv).stream() .map(this::getNullness) .filter(Optional::isPresent) .map(Optional::get) .reduce(Nullness::greatestLowerBound); // use greatest lower bound (glb) to combine } checkState(!inferredMemoTable.put(iv, result).isPresent()); return result; } } }
4,508
40.75
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/dataflow/nullnesspropagation/inference/TypeArgInferenceVar.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.dataflow.nullnesspropagation.inference; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.sun.source.tree.Tree; /** * TypeArg inference variables correspond to types (and parameters thereof) of AST nodes. The {@code * typeArgSelector} specifies a type (or parameter thereof) of the {@code astNode} by a series of * indices of type parameter lists corresponding to a path into the tree structure of {@code * astNode}'s type. * * <p>For example, if the type of {@code astNode} is {@code A<B, C<D, E<F, G>>>}, then inference * variables are specified by typeArgSelectors as follows: {@code A} by the empty list {@code []} * since it is the base type; {@code B} by the list {@code [0]} since it is the 0th type parameter * of the base type; {@code F} by the list {@code [1,1,0]} since it is the 0th type parameter of the * 1st type parameter of the 1st type parameter of the base type; and so on. */ @AutoValue abstract class TypeArgInferenceVar implements InferenceVariable { static TypeArgInferenceVar create(ImmutableList<Integer> typeArgSelector, Tree astNode) { return new AutoValue_TypeArgInferenceVar(typeArgSelector, astNode); } /** * An empty list selects the type of the {@code astNode} itself, while non-empty lists select type * variables within, according to the format described in the class-level Javadoc */ abstract ImmutableList<Integer> typeArgSelector(); abstract Tree astNode(); }
2,123
42.346939
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/names/LevenshteinEditDistance.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.names; import com.google.common.base.Ascii; import com.google.common.primitives.Ints; /** * A utility class for finding the Levenshtein edit distance between strings. The edit distance * between two strings is the number of deletions, insertions, and substitutions required to * transform the source to the target. See <a * href="https://en.wikipedia.org/wiki/Levenshtein_distance"> * https://en.wikipedia.org/wiki/Levenshtein_distance</a>. * * @author eaftan@google.com (Eddie Aftandilian) */ public class LevenshteinEditDistance { private LevenshteinEditDistance() { /* disallow instantiation */ } /** * Returns the edit distance between two strings. * * @param source The source string. * @param target The target distance. * @return The edit distance between the source and target string. * @see #getEditDistance(String, String, boolean) */ public static int getEditDistance(String source, String target) { return getEditDistance(source, target, /* caseSensitive= */ true); } /** * Returns the edit distance between two strings. The algorithm used to calculate this distance * has space requirements of len(source)*len(target). * * @param source The source string. * @param target The target string * @param caseSensitive If true, case is used in comparisons and 'a' != 'A'. * @return The edit distance between the source and target strings. * @see #getEditDistance(String, String) */ public static int getEditDistance(String source, String target, boolean caseSensitive) { // Levenshtein distance algorithm int sourceLength = isEmptyOrWhitespace(source) ? 0 : source.length(); int targetLength = isEmptyOrWhitespace(target) ? 0 : target.length(); if (sourceLength == 0) { return targetLength; } if (targetLength == 0) { return sourceLength; } if (!caseSensitive) { source = Ascii.toLowerCase(source); target = Ascii.toLowerCase(target); } int[][] levMatrix = new int[sourceLength + 1][targetLength + 1]; for (int i = 0; i <= sourceLength; i++) { levMatrix[i][0] = i; } for (int i = 0; i <= targetLength; i++) { levMatrix[0][i] = i; } for (int i = 1; i <= sourceLength; i++) { char sourceI = source.charAt(i - 1); for (int j = 1; j <= targetLength; j++) { char targetJ = target.charAt(j - 1); int cost = 0; if (sourceI != targetJ) { cost = 1; } levMatrix[i][j] = Ints.min( cost + levMatrix[i - 1][j - 1], levMatrix[i - 1][j] + 1, levMatrix[i][j - 1] + 1); } } return levMatrix[sourceLength][targetLength]; } /** Calculate the worst case distance between two strings with the given lengths */ public static int getWorstCaseEditDistance(int sourceLength, int targetLength) { return Math.max(sourceLength, targetLength); } /** * Determines if a string is empty or consists only of whitespace * * @param source The string to check * @return True if the string is empty or contains only whitespace, false otherwise */ private static boolean isEmptyOrWhitespace(String source) { return source == null || source.matches("\\s*"); } }
3,904
30.491935
98
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/names/TermEditDistance.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.names; import blogspot.software_and_algorithms.stern_library.optimization.HungarianAlgorithm; import com.google.common.collect.ImmutableList; import java.util.function.BiFunction; import java.util.stream.DoubleStream; /** * A utility class for finding the distance between two identifiers. Each identifier is split into * its constituent terms (based on camel case or underscore naming conventions). Then the edit * distance between each term is computed and the minimum cost assignment is found. */ public class TermEditDistance { private final BiFunction<String, String, Double> editDistanceFn; private final BiFunction<Integer, Integer, Double> maxDistanceFn; /** * Creates a TermEditDistance Object * * @param editDistanceFn function to compute the distance between two terms * @param maxDistanceFn function to compute the worst case distance between two terms */ public TermEditDistance( BiFunction<String, String, Double> editDistanceFn, BiFunction<Integer, Integer, Double> maxDistanceFn) { this.editDistanceFn = editDistanceFn; this.maxDistanceFn = maxDistanceFn; } public TermEditDistance() { this( (s, t) -> (double) LevenshteinEditDistance.getEditDistance(s, t, /* caseSensitive= */ false), (s, t) -> (double) LevenshteinEditDistance.getWorstCaseEditDistance(s, t)); } public double getNormalizedEditDistance(String source, String target) { ImmutableList<String> sourceTerms = NamingConventions.splitToLowercaseTerms(source); ImmutableList<String> targetTerms = NamingConventions.splitToLowercaseTerms(target); // costMatrix[s][t] is the edit distance between source term s and target term t double[][] costMatrix = sourceTerms.stream() .map(s -> targetTerms.stream().mapToDouble(t -> editDistanceFn.apply(s, t)).toArray()) .toArray(double[][]::new); // worstCaseMatrix[s][t] is the worst case distance between source term s and target term t double[][] worstCaseMatrix = sourceTerms.stream() .map(s -> s.length()) .map( s -> targetTerms.stream() .map(t -> t.length()) .mapToDouble(t -> maxDistanceFn.apply(s, t)) .toArray()) .toArray(double[][]::new); double[] sourceTermDeletionCosts = sourceTerms.stream().mapToDouble(s -> maxDistanceFn.apply(s.length(), 0)).toArray(); double[] targetTermAdditionCosts = targetTerms.stream().mapToDouble(s -> maxDistanceFn.apply(0, s.length())).toArray(); // this is an array of assignments of source terms to target terms. If assignments[i] contains // the value j this means that source term i has been assigned to target term j // There will be one entry in cost for each source term: // - If there are more source terms than target terms then some will be unassigned - value -1 // - If there are a fewer source terms than target terms then some target terms will not be // referenced in the array int[] assignments = new HungarianAlgorithm(costMatrix).execute(); double assignmentCost = computeCost(assignments, costMatrix, sourceTermDeletionCosts, targetTermAdditionCosts); double maxCost = computeCost(assignments, worstCaseMatrix, sourceTermDeletionCosts, targetTermAdditionCosts); return assignmentCost / maxCost; } /** * Compute the total cost of this assignment including the costs of unassigned source and target * terms. */ private static double computeCost( int[] assignments, double[][] costMatrix, double[] sourceTermDeletionCosts, double[] targetTermDeletionCosts) { // We need to sum the costs of each assigned pair, each unassigned source term, and each // unassigned target term. // Start with the total cost of _not_ using all the target terms, then when we use one we'll // remove it from this total. double totalCost = DoubleStream.of(targetTermDeletionCosts).sum(); for (int sourceTermIndex = 0; sourceTermIndex < assignments.length; sourceTermIndex++) { int targetTermIndex = assignments[sourceTermIndex]; if (targetTermIndex == -1) { // not using this source term totalCost += sourceTermDeletionCosts[sourceTermIndex]; } else { // add the cost of the assignments totalCost += costMatrix[sourceTermIndex][targetTermIndex]; // we are using this target term and so we should remove the cost of deleting it totalCost -= targetTermDeletionCosts[targetTermIndex]; } } return totalCost; } }
5,336
40.053846
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/names/NamingConventions.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.names; import static com.google.common.collect.ImmutableList.toImmutableList; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import java.util.regex.Pattern; import java.util.stream.Collectors; /** Utility functions for dealing with Java naming conventions */ public final class NamingConventions { private static final Pattern ONLY_UNDERSCORES = Pattern.compile("^_+$"); private static final String UNDERSCORE = "_"; private static final String CASE_TRANSITION = "(?<=[a-z0-9])(?=[A-Z])"; private static final String TRAILING_DIGITS = "(?<![0-9_])(?=[0-9]+$)"; private static final Splitter TERM_SPLITTER = Splitter.onPattern(String.format("%s|%s|%s", UNDERSCORE, CASE_TRANSITION, TRAILING_DIGITS)) .omitEmptyStrings(); /** * Split a Java name into terms based on either Camel Case or Underscores. We also split digits at * the end of the name into a separate term so as to treat PERSON1 and PERSON_1 as the same thing. * * @param identifierName to split * @return a list of the terms in the name, in order and converted to lowercase */ public static ImmutableList<String> splitToLowercaseTerms(String identifierName) { if (ONLY_UNDERSCORES.matcher(identifierName).matches()) { // Degenerate case of names which contain only underscore return ImmutableList.of(identifierName); } return TERM_SPLITTER .splitToStream(identifierName) .map(String::toLowerCase) .collect(toImmutableList()); } public static String convertToLowerUnderscore(String identifierName) { return splitToLowercaseTerms(identifierName).stream().collect(Collectors.joining("_")); } private NamingConventions() {} }
2,379
36.777778
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/names/NeedlemanWunschEditDistance.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.names; import com.google.common.base.Ascii; import com.google.common.primitives.Ints; /** * The Needleman-Wunsch algorithm for finding least-cost string edit distances between pairs of * strings. Like Levenshtein, but this version allows for a sequence of adjacent * deletions/insertions to cost less than the total cost of each individual deletion/insertion, so * that, for example editing {@code Christopher} into {@code Chris} (dropping 6 characters) is not 6 * times as expensive as editing {@code Christopher} into {@code Christophe}. * * <p>See http://en.wikipedia.org/wiki/Needleman-Wunsch_algorithm * * @author alanw@google.com (Alan Wendt) */ public final class NeedlemanWunschEditDistance { private NeedlemanWunschEditDistance() { /* disallow instantiation */ } /** * Returns the edit distance between two strings. Levenshtein charges the same cost for each * insertion or deletion. This algorithm is slightly more general in that it charges a sequence of * adjacent insertions/deletions an up-front cost plus an incremental cost per insert/delete * operation. The idea is that Christopher -&gt; Chris should be less than 6 times as expensive as * Christopher -&gt; Christophe. The algorithm used to calculate this distance takes time and * space proportional to the product of {@code source.length()} and {@code target.length()} to * build the 3 arrays. * * @param source source string. * @param target target string * @param caseSensitive if true, case is used in comparisons and 'a' != 'A'. * @param changeCost cost of changing one character * @param openGapCost cost to open a gap to insert or delete some characters. * @param continueGapCost marginal cost to insert or delete next character. * @return edit distance between the source and target strings. */ public static int getEditDistance( String source, String target, boolean caseSensitive, int changeCost, int openGapCost, int continueGapCost) { if (!caseSensitive) { source = Ascii.toLowerCase(source); target = Ascii.toLowerCase(target); } int sourceLength = source.length(); int targetLength = target.length(); if (sourceLength == 0) { return scriptCost(openGapCost, continueGapCost, targetLength); } if (targetLength == 0) { return scriptCost(openGapCost, continueGapCost, sourceLength); } // mMatrix[i][j] = Cost of aligning source.substring(0,i) with // target.substring(0,j), using an edit script ending with // matched characters. int[][] mMatrix = new int[sourceLength + 1][targetLength + 1]; // Cost of an alignment that ends with a bunch of deletions. // dMatrix[i][j] = best found cost of changing the first i chars // of source into the first j chars of target, ending with one // or more deletes of source characters. int[][] dMatrix = new int[sourceLength + 1][targetLength + 1]; // Cost of an alignment that ends with one or more insertions. int[][] iMatrix = new int[sourceLength + 1][targetLength + 1]; mMatrix[0][0] = dMatrix[0][0] = iMatrix[0][0] = 0; // Any edit script that changes i chars of source into zero // chars of target will only involve deletions. So only the // d&m Matrix entries are relevant, because dMatrix[i][0] gives // the cost of changing an i-length string into a 0-length string, // using an edit script ending in deletions. for (int i = 1; i <= sourceLength; i++) { mMatrix[i][0] = dMatrix[i][0] = scriptCost(openGapCost, continueGapCost, i); // Make the iMatrix entries impossibly expensive, so they'll be // ignored as inputs to min(). Use a big cost but not // max int because that will overflow if anything's added to it. iMatrix[i][0] = Integer.MAX_VALUE / 2; } for (int j = 1; j <= targetLength; j++) { // Only the i&m Matrix entries are relevant here, because they represent // the cost of changing a 0-length string into a j-length string, using // an edit script ending in insertions. mMatrix[0][j] = iMatrix[0][j] = scriptCost(openGapCost, continueGapCost, j); // Make the dMatrix entries impossibly expensive, so they'll be // ignored as inputs to min(). Use a big cost but not // max int because that will overflow if anything's added to it. dMatrix[0][j] = Integer.MAX_VALUE / 2; } for (int i = 1; i <= sourceLength; i++) { char sourceI = source.charAt(i - 1); for (int j = 1; j <= targetLength; j++) { char targetJ = target.charAt(j - 1); int cost = (sourceI == targetJ) ? 0 : changeCost; // Cost of changing i chars of source into j chars of target, // using an edit script ending in matched characters. mMatrix[i][j] = cost + Ints.min(mMatrix[i - 1][j - 1], iMatrix[i - 1][j - 1], dMatrix[i - 1][j - 1]); // Cost of an edit script ending in a deletion. dMatrix[i][j] = Math.min( mMatrix[i - 1][j] + openGapCost + continueGapCost, dMatrix[i - 1][j] + continueGapCost); // Cost of an edit script ending in an insertion. iMatrix[i][j] = Math.min( mMatrix[i][j - 1] + openGapCost + continueGapCost, iMatrix[i][j - 1] + continueGapCost); } } // Return the minimum cost. int costOfEditScriptEndingWithMatch = mMatrix[sourceLength][targetLength]; int costOfEditScriptEndingWithDelete = dMatrix[sourceLength][targetLength]; int costOfEditScriptEndingWithInsert = iMatrix[sourceLength][targetLength]; return Ints.min( costOfEditScriptEndingWithMatch, costOfEditScriptEndingWithDelete, costOfEditScriptEndingWithInsert); } /** Return the worst case edit distance between strings of this length */ public static int getWorstCaseEditDistance( int sourceLength, int targetLength, int changeCost, int openGapCost, int continueGapCost) { int maxLen = Math.max(sourceLength, targetLength); int minLen = Math.min(sourceLength, targetLength); // Compute maximum cost of changing one string into another. If the // lengths differ, you'll need maxLen - minLen insertions or deletions. int totChangeCost = scriptCost(openGapCost, continueGapCost, maxLen - minLen) + minLen * changeCost; // Another possibility is to just delete the entire source and insert the // target, and not do any changes. int blowAwayCost = scriptCost(openGapCost, continueGapCost, sourceLength) + scriptCost(openGapCost, continueGapCost, targetLength); return Math.min(totChangeCost, blowAwayCost); } /** * Returns a normalized edit distance between 0 and 1. This is useful if you are comparing or * aggregating distances of different pairs of strings */ public static double getNormalizedEditDistance( String source, String target, boolean caseSensitive, int changeCost, int openGapCost, int continueGapCost) { if (source.isEmpty() && target.isEmpty()) { return 0.0; } return (double) getEditDistance(source, target, caseSensitive, changeCost, openGapCost, continueGapCost) / (double) getWorstCaseEditDistance( source.length(), target.length(), changeCost, openGapCost, continueGapCost); } /** * Return the cost of a script consisting of a contiguous sequence of insertions or a contiguous * sequence of deletions. */ private static int scriptCost(int openGapCost, int continueGapCost, int scriptLength) { return (scriptLength == 0) ? 0 : openGapCost + scriptLength * continueGapCost; } }
8,431
38.773585
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/predicates/TypePredicate.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.predicates; import com.google.errorprone.VisitorState; import com.sun.tools.javac.code.Type; import java.io.Serializable; /** A predicate for testing {@link Type}s. */ public interface TypePredicate extends Serializable { boolean apply(Type type, VisitorState state); }
913
32.851852
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/predicates/TypePredicates.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.predicates; import static com.google.errorprone.suppliers.Suppliers.fromStrings; import com.google.errorprone.predicates.type.Array; import com.google.errorprone.predicates.type.DescendantOf; import com.google.errorprone.predicates.type.DescendantOfAny; import com.google.errorprone.predicates.type.Exact; import com.google.errorprone.predicates.type.ExactAny; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.suppliers.Suppliers; import com.sun.tools.javac.code.Type; /** A collection of {@link TypePredicate}s. */ public final class TypePredicates { /** Matches nothing (always {@code false}). */ public static TypePredicate nothing() { return (type, state) -> false; } /** Matches everything (always {@code true}). */ public static TypePredicate anything() { return (type, state) -> true; } /** Match arrays. */ public static TypePredicate isArray() { return Array.INSTANCE; } /** Match types that are exactly equal. */ public static TypePredicate isExactType(String type) { return isExactType(Suppliers.typeFromString(type)); } /** Match types that are exactly equal. */ public static TypePredicate isExactType(Supplier<Type> type) { return new Exact(type); } /** Match types that are exactly equal to any of the given types. */ public static TypePredicate isExactTypeAny(Iterable<String> types) { return new ExactAny(fromStrings(types)); } /** Match sub-types of the given type. */ public static TypePredicate isDescendantOf(Supplier<Type> type) { return new DescendantOf(type); } /** Match sub-types of the given type. */ public static TypePredicate isDescendantOf(String type) { return isDescendantOf(Suppliers.typeFromString(type)); } /** Match types that are a sub-type of one of the given types. */ public static TypePredicate isDescendantOfAny(Iterable<String> types) { return new DescendantOfAny(fromStrings(types)); } public static TypePredicate allOf(TypePredicate... predicates) { return (type, state) -> { for (TypePredicate predicate : predicates) { if (!predicate.apply(type, state)) { return false; } } return true; }; } public static TypePredicate anyOf(TypePredicate... predicates) { return (type, state) -> { for (TypePredicate predicate : predicates) { if (predicate.apply(type, state)) { return true; } } return false; }; } public static TypePredicate not(TypePredicate predicate) { return (type, state) -> !predicate.apply(type, state); } private TypePredicates() {} }
3,290
30.04717
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/predicates/type/Array.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.predicates.type; import com.google.errorprone.VisitorState; import com.google.errorprone.predicates.TypePredicate; import com.sun.tools.javac.code.Type; /** Matches arrays. */ public enum Array implements TypePredicate { INSTANCE { @Override public boolean apply(Type type, VisitorState state) { return type != null && state.getTypes().isArray(type); } }; }
1,021
30.9375
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/predicates/type/ExactAny.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.predicates.type; import com.google.errorprone.VisitorState; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.tools.javac.code.Type; /** Matches types that exactly match one of the given types. */ public class ExactAny implements TypePredicate { public final Iterable<Supplier<Type>> types; public ExactAny(Iterable<Supplier<Type>> types) { this.types = types; } @Override public boolean apply(Type type, VisitorState state) { if (type == null) { return false; } for (Supplier<Type> supplier : types) { Type expected = supplier.get(state); if (expected == null) { continue; } if (ASTHelpers.isSameType(expected, type, state)) { return true; } } return false; } }
1,510
28.627451
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/predicates/type/DescendantOfAny.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.predicates.type; import com.google.errorprone.VisitorState; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.tools.javac.code.Type; /** Matches types that are a sub-type of one of the given types. */ public class DescendantOfAny implements TypePredicate { public final Iterable<Supplier<Type>> types; public DescendantOfAny(Iterable<Supplier<Type>> types) { this.types = types; } @Override public boolean apply(Type type, VisitorState state) { if (type == null) { return false; } for (Supplier<Type> supplier : types) { Type expected = supplier.get(state); if (expected == null) { continue; } if (ASTHelpers.isSubtype(type, expected, state)) { return true; } } return false; } }
1,527
28.960784
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/predicates/type/DescendantOf.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.predicates.type; import com.google.errorprone.VisitorState; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.tools.javac.code.Type; /** Matches sub-types of the given type. */ public class DescendantOf implements TypePredicate { public final Supplier<Type> expected; public DescendantOf(Supplier<Type> type) { this.expected = type; } @Override public boolean apply(Type type, VisitorState state) { Type bound = expected.get(state); if (bound == null || type == null) { // TODO(cushon): type suppliers are allowed to return null :( return false; } return ASTHelpers.isSubtype(type, bound, state); } }
1,404
30.931818
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/predicates/type/Exact.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.predicates.type; import com.google.errorprone.VisitorState; import com.google.errorprone.predicates.TypePredicate; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.tools.javac.code.Type; /** Matches types that exactly match the given type. */ public class Exact implements TypePredicate { public final Supplier<Type> supplier; public Exact(Supplier<Type> type) { this.supplier = type; } @Override public boolean apply(Type type, VisitorState state) { Type expected = supplier.get(state); if (expected == null || type == null) { return false; } return ASTHelpers.isSameType(expected, type, state); } }
1,344
30.27907
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/suppliers/package-info.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Supports matchers, but rather than giving Matcher implementations which are predicates on * individual AST nodes, a supplier gives contextual information from the traversal of the AST. */ package com.google.errorprone.suppliers;
847
37.545455
95
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/suppliers/Supplier.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.suppliers; import com.google.errorprone.VisitorState; import java.io.Serializable; /** * Simple supplier pattern, which allows delayed binding to access to runtime elements. * * @author alexeagle@google.com (Alex Eagle) */ public interface Supplier<T> extends Serializable { T get(VisitorState state); }
951
30.733333
87
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/suppliers/Suppliers.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.suppliers; import static java.util.Objects.requireNonNull; import com.google.common.base.Function; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.errorprone.VisitorState; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCFieldAccess; /** * @author alexeagle@google.com (Alex Eagle) */ public final class Suppliers { /** * Supplies the n'th generic type of the given expression. For example, in {@code Map<A,B> c;} for * the expression c and n=1, the result is the type of {@code B}. If there are an insufficient * number of type arguments, this method will return the {@code java.lang.Object} type from symbol * table. * * @param expressionSupplier a supplier of the expression which has a generic type * @param n the position of the generic argument */ public static Supplier<Type> genericTypeOf(Supplier<ExpressionTree> expressionSupplier, int n) { return new Supplier<Type>() { @Override public Type get(VisitorState state) { JCExpression jcExpression = (JCExpression) expressionSupplier.get(state); if (jcExpression.type.getTypeArguments().size() <= n) { return state.getSymtab().objectType; } return jcExpression.type.getTypeArguments().get(n); } }; } /** * Supplies the n'th generic type of the given expression. For example, in {@code Map<A,B> c;} for * the type of c and n=1, the result is the type of {@code B}. If there are an insufficient number * of type arguments, this method will return the {@code java.lang.Object} type from symbol table. * * @param typeSupplier a supplier of the expression which has a generic type * @param n the position of the generic argument */ public static Supplier<Type> genericTypeOfType(Supplier<Type> typeSupplier, int n) { return new Supplier<Type>() { @Override public Type get(VisitorState state) { Type type = typeSupplier.get(state); if (type.getTypeArguments().size() <= n) { return state.getSymtab().objectType; } return type.getTypeArguments().get(n); } }; } /** * Supplies the expression which gives the instance of an object that will receive the method * call. For example, in {@code a.getB().getC()} if the visitor is currently visiting the {@code * getC()} method invocation, then this supplier gives the expression {@code a.getB()}. */ public static Supplier<Type> receiverType() { return new Supplier<Type>() { @Override public Type get(VisitorState state) { MethodInvocationTree methodInvocation = (MethodInvocationTree) state.getPath().getLeaf(); return ASTHelpers.getReceiverType(methodInvocation.getMethodSelect()); } }; } /** * Supplies the expression which gives the instance of an object that will receive the method * call. For example, in {@code a.getB().getC()} if the visitor is currently visiting the {@code * getC()} method invocation, then this supplier gives the expression {@code a.getB()}. */ public static Supplier<ExpressionTree> receiverInstance() { return new Supplier<ExpressionTree>() { @Override public ExpressionTree get(VisitorState state) { MethodInvocationTree method = (MethodInvocationTree) state.getPath().getLeaf(); return ((JCFieldAccess) method.getMethodSelect()).getExpression(); } }; } /** * Given the string representation of a type, supplies the corresponding type. * * @param typeString a string representation of a type, e.g., "java.util.List" */ public static Supplier<Type> typeFromString(String typeString) { requireNonNull(typeString); return VisitorState.memoize(state -> state.getTypeFromString(typeString)); } /** Given the class representation of a type, supplies the corresponding type. */ public static Supplier<Type> typeFromClass(Class<?> inputClass) { return typeFromString(inputClass.getName()); } public static final Supplier<Type> JAVA_LANG_VOID_TYPE = typeFromClass(Void.class); public static final Supplier<Type> VOID_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().voidType; } }; public static final Supplier<Type> JAVA_LANG_BOOLEAN_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getTypeFromString("java.lang.Boolean"); } }; public static final Supplier<Type> JAVA_LANG_INTEGER_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getTypeFromString("java.lang.Integer"); } }; public static final Supplier<Type> JAVA_LANG_LONG_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getTypeFromString("java.lang.Long"); } }; public static final Supplier<Type> STRING_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().stringType; } }; public static final Supplier<Type> BOOLEAN_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().booleanType; } }; public static final Supplier<Type> BYTE_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().byteType; } }; public static final Supplier<Type> SHORT_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().shortType; } }; public static final Supplier<Type> INT_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().intType; } }; public static final Supplier<Type> LONG_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().longType; } }; public static final Supplier<Type> DOUBLE_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().doubleType; } }; public static final Supplier<Type> CHAR_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().charType; } }; public static final Supplier<Type> OBJECT_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().objectType; } }; public static final Supplier<Type> EXCEPTION_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().exceptionType; } }; public static final Supplier<Type> THROWABLE_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().throwableType; } }; public static final Supplier<Type> ANNOTATION_TYPE = new Supplier<Type>() { @Override public Type get(VisitorState state) { return state.getSymtab().annotationType; } }; /** * Supplies what was given. Useful for adapting to methods that require a supplier. * * @param toSupply the item to supply */ public static <T> Supplier<T> identitySupplier(T toSupply) { return new Supplier<T>() { @Override public T get(VisitorState state) { return toSupply; } }; } public static final Supplier<Type> ENCLOSING_CLASS = new Supplier<Type>() { @Override public Type get(VisitorState state) { return ASTHelpers.getType(state.findEnclosing(ClassTree.class)); } }; public static Supplier<Type> arrayOf(Supplier<Type> elementType) { return new Supplier<Type>() { @Override public Type get(VisitorState state) { return new Type.ArrayType(elementType.get(state), state.getSymtab().arraysType.tsym); } }; } public static ImmutableList<Supplier<Type>> fromStrings(Iterable<String> types) { return ImmutableList.copyOf( Iterables.transform( types, new Function<String, Supplier<Type>>() { @Override public Supplier<Type> apply(String input) { return Suppliers.typeFromString(input); } })); } private Suppliers() {} }
9,749
31.392027
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/scanner/ScannerSupplier.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import static com.google.common.collect.ImmutableListMultimap.flatteningToImmutableListMultimap; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.HashBiMap; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.common.collect.Streams; import com.google.errorprone.BugCheckerInfo; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.ErrorProneOptions; import com.google.errorprone.ErrorProneOptions.Severity; import com.google.errorprone.InvalidCommandLineOptionException; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.bugpatterns.BugChecker; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * Supplies {@link Scanner}s and provides access to the backing sets of all {@link BugChecker}s and * enabled {@link BugChecker}s. */ public abstract class ScannerSupplier implements Supplier<Scanner> { /* Static factory methods and helpers */ /** Returns a {@link ScannerSupplier} with a specific list of {@link BugChecker} classes. */ @SafeVarargs public static ScannerSupplier fromBugCheckerClasses( Class<? extends BugChecker>... checkerClasses) { return fromBugCheckerClasses(Arrays.asList(checkerClasses)); } private static ImmutableMap<String, SeverityLevel> defaultSeverities( Iterable<BugCheckerInfo> checkers) { ImmutableMap.Builder<String, SeverityLevel> severities = ImmutableMap.builder(); for (BugCheckerInfo check : checkers) { severities.put(check.canonicalName(), check.defaultSeverity()); } return severities.buildOrThrow(); } /** Returns a {@link ScannerSupplier} with a specific list of {@link BugChecker} classes. */ public static ScannerSupplier fromBugCheckerClasses( Iterable<Class<? extends BugChecker>> checkers) { ImmutableList.Builder<BugCheckerInfo> builder = ImmutableList.builder(); for (Class<? extends BugChecker> checker : checkers) { builder.add(BugCheckerInfo.create(checker)); } return fromBugCheckerInfos(builder.build()); } /** Returns a {@link ScannerSupplier} built from a list of {@link BugCheckerInfo}s. */ public static ScannerSupplier fromBugCheckerInfos(Iterable<BugCheckerInfo> checkers) { ImmutableBiMap<String, BugCheckerInfo> allChecks = Streams.stream(checkers) .collect( ImmutableBiMap.toImmutableBiMap(BugCheckerInfo::canonicalName, checker -> checker)); return new ScannerSupplierImpl( allChecks, defaultSeverities(allChecks.values()), ImmutableSet.of(), ErrorProneFlags.empty()); } /** * Returns a {@link ScannerSupplier} that just returns the {@link Scanner} that was passed in. * Used mostly for testing. Does not implement any method other than {@link * ScannerSupplier#get()}. */ public static ScannerSupplier fromScanner(Scanner scanner) { return new InstanceReturningScannerSupplierImpl(scanner); } /* Instance methods */ /** * Returns a map of check name to {@link BugCheckerInfo} for all {@link BugCheckerInfo}s in this * {@link ScannerSupplier}, including disabled ones. */ public abstract ImmutableBiMap<String, BugCheckerInfo> getAllChecks(); /** * Returns the set of {@link BugCheckerInfo}s that are enabled in this {@link ScannerSupplier}. */ public abstract ImmutableSet<BugCheckerInfo> getEnabledChecks(); public abstract ImmutableMap<String, SeverityLevel> severities(); protected abstract ImmutableSet<String> disabled(); protected Set<String> enabled() { return Sets.difference(getAllChecks().keySet(), disabled()); } public abstract ErrorProneFlags getFlags(); /** * Applies options to this {@link ScannerSupplier}. * * <p>Command-line options to override check severities may do any of the following: * * <ul> * <li>Enable a check that is currently off * <li>Disable a check that is currently on * <li>Change the severity of a check that is on, promoting a warning to an error or demoting an * error to a warning * </ul> * * @param errorProneOptions an {@link ErrorProneOptions} object that encapsulates the overrides * for this compilation * @throws InvalidCommandLineOptionException if the override map attempts to disable a check that * may not be disabled */ @CheckReturnValue public ScannerSupplier applyOverrides(ErrorProneOptions errorProneOptions) { ImmutableMap<String, Severity> severityOverrides = errorProneOptions.getSeverityMap(); if (severityOverrides.isEmpty() && errorProneOptions.getFlags().isEmpty() && !errorProneOptions.isEnableAllChecksAsWarnings() && !errorProneOptions.isDropErrorsToWarnings() && !errorProneOptions.isDisableAllChecks() && !errorProneOptions.isDisableAllWarnings() && !errorProneOptions.isSuggestionsAsWarnings()) { return this; } // Initialize result allChecks map and enabledChecks set with current state of this Supplier. ImmutableBiMap<String, BugCheckerInfo> checks = getAllChecks(); Map<String, SeverityLevel> severities = new LinkedHashMap<>(severities()); Set<String> disabled = new HashSet<>(disabled()); Map<String, String> flagsMap = new HashMap<>(getFlags().getFlagsMap()); if (errorProneOptions.isEnableAllChecksAsWarnings()) { disabled.forEach(c -> severities.put(c, SeverityLevel.WARNING)); disabled.clear(); } if (errorProneOptions.isDropErrorsToWarnings()) { checks.values().stream() .filter(c -> c.defaultSeverity() == SeverityLevel.ERROR && c.disableable()) .forEach(c -> severities.put(c.canonicalName(), SeverityLevel.WARNING)); } if (errorProneOptions.isSuggestionsAsWarnings()) { getAllChecks().values().stream() .filter(c -> c.defaultSeverity() == SeverityLevel.SUGGESTION) .forEach(c -> severities.put(c.canonicalName(), SeverityLevel.WARNING)); } if (errorProneOptions.isDisableAllWarnings()) { checks.values().stream() .filter(c -> c.defaultSeverity() == SeverityLevel.WARNING) .forEach(c -> disabled.add(c.canonicalName())); } if (errorProneOptions.isDisableAllChecks()) { checks.values().stream() .filter(c -> c.disableable()) .forEach(c -> disabled.add(c.canonicalName())); } ImmutableListMultimap<String, BugCheckerInfo> checksByAltName = checks.values().stream() .collect(flatteningToImmutableListMultimap(x -> x, c -> c.allNames().stream())) .inverse(); // Process overrides severityOverrides.forEach( (checkName, newSeverity) -> { if (!checksByAltName.containsKey(checkName)) { if (errorProneOptions.ignoreUnknownChecks()) { return; } throw new InvalidCommandLineOptionException(checkName + " is not a valid checker name"); } for (BugCheckerInfo check : checksByAltName.get(checkName)) { switch (newSeverity) { case OFF: if (!check.disableable()) { throw new InvalidCommandLineOptionException( check.canonicalName() + " may not be disabled"); } severities.remove(check.canonicalName()); disabled.add(check.canonicalName()); break; case DEFAULT: severities.put(check.canonicalName(), check.defaultSeverity()); disabled.remove(check.canonicalName()); break; case WARN: // Demoting an enabled check from an error to a warning is a form of disabling if (!disabled().contains(check.canonicalName()) && !check.disableable() && check.defaultSeverity() == SeverityLevel.ERROR) { throw new InvalidCommandLineOptionException( check.canonicalName() + " is not disableable and may not be demoted to a warning"); } severities.put(check.canonicalName(), SeverityLevel.WARNING); disabled.remove(check.canonicalName()); break; case ERROR: severities.put(check.canonicalName(), SeverityLevel.ERROR); disabled.remove(check.canonicalName()); break; } } }); flagsMap.putAll(errorProneOptions.getFlags().getFlagsMap()); return new ScannerSupplierImpl( checks, ImmutableMap.copyOf(severities), ImmutableSet.copyOf(disabled), ErrorProneFlags.fromMap(flagsMap)); } /** * Composes this {@link ScannerSupplier} with the {@code other} {@link ScannerSupplier}. The set * of checks that are turned on is the intersection of the checks on in {@code this} and {@code * other}. */ @CheckReturnValue public ScannerSupplier plus(ScannerSupplier other) { HashBiMap<String, BugCheckerInfo> combinedAllChecks = HashBiMap.create(this.getAllChecks()); other .getAllChecks() .forEach( (k, v) -> { BugCheckerInfo existing = combinedAllChecks.putIfAbsent(k, v); if (existing != null && !existing.checkerClass().getName().contentEquals(v.checkerClass().getName())) { throw new IllegalArgumentException( String.format( "Cannot combine scanner suppliers with different implementations of" + " '%s': %s, %s", k, v.checkerClass().getName(), existing.checkerClass().getName())); } }); HashMap<String, SeverityLevel> combinedSeverities = new LinkedHashMap<>(this.severities()); other .severities() .forEach( (k, v) -> { SeverityLevel existing = combinedSeverities.putIfAbsent(k, v); if (existing != null && !existing.equals(v)) { throw new IllegalArgumentException( String.format( "Cannot combine scanner suppliers with different severities for" + " '%s': %s, %s", k, v, existing)); } }); ImmutableSet<String> disabled = Sets.difference(combinedAllChecks.keySet(), Sets.union(enabled(), other.enabled())) .immutableCopy(); ErrorProneFlags combinedFlags = this.getFlags().plus(other.getFlags()); return new ScannerSupplierImpl( ImmutableBiMap.copyOf(combinedAllChecks), ImmutableMap.copyOf(combinedSeverities), disabled, combinedFlags); } /** * Filters this {@link ScannerSupplier} based on the provided predicate. Returns a {@link * ScannerSupplier} with only the checks enabled that satisfy the predicate. */ @CheckReturnValue public ScannerSupplier filter(Predicate<? super BugCheckerInfo> predicate) { ImmutableSet<String> disabled = getAllChecks().values().stream() .filter(predicate.negate()) .map(BugCheckerInfo::canonicalName) .collect(ImmutableSet.toImmutableSet()); return new ScannerSupplierImpl(getAllChecks(), severities(), disabled, getFlags()); } }
12,486
39.674267
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneInjector.java
/* * Copyright 2023 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import static com.google.common.collect.Lists.reverse; import static java.util.Arrays.stream; import static java.util.stream.Collectors.joining; import com.google.common.collect.ClassToInstanceMap; import com.google.common.collect.MutableClassToInstanceMap; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Predicate; /** * An injector for ErrorProne. * * <p>This implements a very simplified subset of the functionality that Guice does. Specifically, * it allows injecting only non-generic classes, and treats everything as a singleton within a given * compilation. */ public final class ErrorProneInjector { private final ClassToInstanceMap<Object> instances = MutableClassToInstanceMap.create(); /** Indicates that there was a runtime failure while providing an instance. */ public static final class ProvisionException extends RuntimeException { public ProvisionException(String message) { super(message); } public ProvisionException(String message, Throwable cause) { super(message, cause); } } public static ErrorProneInjector create() { return new ErrorProneInjector(); } @CanIgnoreReturnValue public <T> ErrorProneInjector addBinding(Class<T> clazz, T instance) { instances.putInstance(clazz, instance); return this; } public synchronized <T> T getInstance(Class<T> clazz) { return getInstance(clazz, new ArrayList<>()); } private synchronized <T> T getInstance(Class<T> clazz, List<Class<?>> path) { var instance = instances.getInstance(clazz); if (instance != null) { return instance; } path.add(clazz); Constructor<T> constructor = findConstructor(clazz) .orElseThrow( () -> new ProvisionException( "Failed to find an injectable constructor for " + clazz.getCanonicalName() + " requested by " + printPath(path))); constructor.setAccessible(true); Object[] args = stream(constructor.getParameterTypes()).map(c -> getInstance(c, path)).toArray(); T newInstance; try { newInstance = constructor.newInstance(args); } catch (ReflectiveOperationException e) { throw new ProvisionException("Failed to initialize " + clazz.getCanonicalName(), e); } instances.putInstance(clazz, newInstance); return newInstance; } public static <T> Optional<Constructor<T>> findConstructor(Class<T> clazz) { return findConstructorMatching( clazz, c -> stream(c.getAnnotations()) .anyMatch(a -> a.annotationType().getSimpleName().equals("Inject"))) .or( () -> findConstructorMatching( clazz, c -> c.getParameters().length != 0 && stream(c.getParameters()) .allMatch(p -> p.getType().equals(ErrorProneFlags.class)))) .or(() -> findConstructorMatching(clazz, c -> c.getParameters().length == 0)); } @SuppressWarnings("unchecked") private static <T> Optional<Constructor<T>> findConstructorMatching( Class<T> clazz, Predicate<Constructor<?>> predicate) { return stream(clazz.getDeclaredConstructors()) .filter(predicate) .map(c -> (Constructor<T>) c) .findFirst(); } private static String printPath(List<Class<?>> path) { return reverse(path).stream().map(Class::getSimpleName).collect(joining(" <- ")); } }
4,456
33.820313
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/scanner/ScannerSupplierImpl.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Iterables.getFirst; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.errorprone.BugCheckerInfo; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.ErrorProneFlags; import com.google.errorprone.bugpatterns.BugChecker; import java.io.Serializable; /** * An implementation of a {@link ScannerSupplier}, abstracted as a set of all known {@link * BugChecker}s and a set of enabled {@link BugChecker}s. The set of enabled suppliers must be a * subset of all known suppliers. */ class ScannerSupplierImpl extends ScannerSupplier implements Serializable { private final ImmutableBiMap<String, BugCheckerInfo> checks; private final ImmutableMap<String, SeverityLevel> severities; private final ImmutableSet<String> disabled; private final ErrorProneFlags flags; // Lazily initialized to make serialization easy. private transient ErrorProneInjector injector; ScannerSupplierImpl( ImmutableBiMap<String, BugCheckerInfo> checks, ImmutableMap<String, SeverityLevel> severities, ImmutableSet<String> disabled, ErrorProneFlags flags) { checkArgument( Sets.difference(severities.keySet(), checks.keySet()).isEmpty(), "enabledChecks must be a subset of allChecks"); checkArgument( Sets.difference(disabled, checks.keySet()).isEmpty(), "disabled must be a subset of allChecks"); this.checks = checks; this.severities = severities; this.disabled = disabled; this.flags = flags; } private BugChecker instantiateChecker(BugCheckerInfo checker) { if (injector == null) { injector = ErrorProneInjector.create().addBinding(ErrorProneFlags.class, flags); } return injector.getInstance(checker.checkerClass()); } @Override public ErrorProneScanner get() { return new ErrorProneScanner( getEnabledChecks().stream() .map(this::instantiateChecker) .collect(ImmutableSet.toImmutableSet()), severities); } @Override public ImmutableBiMap<String, BugCheckerInfo> getAllChecks() { return checks; } @Override public ImmutableMap<String, SeverityLevel> severities() { return severities; } @Override protected ImmutableSet<String> disabled() { return disabled; } @Override public ImmutableSet<BugCheckerInfo> getEnabledChecks() { return getAllChecks().values().stream() .filter(input -> !disabled.contains(input.canonicalName())) .collect(ImmutableSet.toImmutableSet()); } @Override public ErrorProneFlags getFlags() { return flags; } /** Returns the name of the first check, or {@code ""}. */ @Override public String toString() { return getFirst(getAllChecks().keySet(), ""); } }
3,646
31.855856
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/scanner/Scanner.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.ErrorProneOptions; import com.google.errorprone.SuppressionInfo; import com.google.errorprone.SuppressionInfo.SuppressedState; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Suppressible; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.Tree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.util.Name; import java.util.Collections; import java.util.Map; import java.util.Set; /** * TODO(eaftan): I'm worried about this performance of this code, specifically the part that handles * SuppressWarnings. We should profile it and see where the hotspots are. * * @author alexeagle@google.com (Alex Eagle) * @author eaftan@google.com (Eddie Aftandilian) */ @CheckReturnValue public class Scanner extends TreePathScanner<Void, VisitorState> { private SuppressionInfo currentSuppressions = SuppressionInfo.EMPTY; /** Scan a tree from a position identified by a TreePath. */ @Override public Void scan(TreePath path, VisitorState state) { SuppressionInfo prevSuppressionInfo = updateSuppressions(path.getLeaf(), state); try { return super.scan(path, state); } finally { // Restore old suppression state. currentSuppressions = prevSuppressionInfo; } } /** Scan a single node. The current path is updated for the duration of the scan. */ @Override public Void scan(Tree tree, VisitorState state) { if (tree == null) { return null; } SuppressionInfo prevSuppressionInfo = updateSuppressions(tree, state); try { return super.scan(tree, state); } finally { // Restore old suppression state. currentSuppressions = prevSuppressionInfo; } } /** * Updates current suppression state with information for the given {@code tree}. Returns the * previous suppression state so that it can be restored when going up the tree. */ private SuppressionInfo updateSuppressions(Tree tree, VisitorState state) { SuppressionInfo prevSuppressionInfo = currentSuppressions; if (tree instanceof CompilationUnitTree) { currentSuppressions = currentSuppressions.forCompilationUnit((CompilationUnitTree) tree, state); } else { Symbol sym = ASTHelpers.getDeclaredSymbol(tree); if (sym != null) { currentSuppressions = currentSuppressions.withExtendedSuppressions( sym, state, getCustomSuppressionAnnotations(state)); } } return prevSuppressionInfo; } /** * Returns if this checker should be suppressed on the current tree path. * * @param suppressible holds information about the suppressibility of a checker * @param errorProneOptions Options object configuring whether or not to suppress non-errors in */ protected SuppressedState isSuppressed( Suppressible suppressible, ErrorProneOptions errorProneOptions, VisitorState state) { boolean suppressedInGeneratedCode = errorProneOptions.disableWarningsInGeneratedCode() && severityMap().get(suppressible.canonicalName()) != SeverityLevel.ERROR; return currentSuppressions.suppressedState(suppressible, suppressedInGeneratedCode, state); } /** * Returns a set of all the custom suppression annotation types used by the {@code BugChecker}s in * this{@code Scanner}. */ protected Set<? extends Name> getCustomSuppressionAnnotations(VisitorState state) { return ImmutableSet.of(); } protected void reportMatch(Description description, VisitorState state) { checkNotNull(description, "Use Description.NO_MATCH to denote an absent finding."); state.reportMatch(description); } /** Handles an exception thrown by an individual check. */ protected void handleError(Suppressible s, Throwable t) {} /** Returns a mapping between the canonical names of checks and their {@link SeverityLevel}. */ public Map<String, SeverityLevel> severityMap() { return Collections.emptyMap(); } }
5,065
35.710145
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScannerTransformer.java
/* * Copyright 2015 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import static java.util.Objects.requireNonNull; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableClassToInstanceMap; import com.google.errorprone.CodeTransformer; import com.google.errorprone.DescriptionListener; import com.google.errorprone.ErrorProneOptions; import com.google.errorprone.VisitorState; import com.sun.source.util.TreePath; import com.sun.tools.javac.util.Context; import java.lang.annotation.Annotation; /** Adapter from an {@link ErrorProneScanner} to a {@link CodeTransformer}. */ @AutoValue public abstract class ErrorProneScannerTransformer implements CodeTransformer { public static ErrorProneScannerTransformer create(Scanner scanner) { return new AutoValue_ErrorProneScannerTransformer(scanner); } abstract Scanner scanner(); @Override public void apply(TreePath tree, Context context, DescriptionListener listener) { scanner().scan(tree, createVisitorState(context, listener).withPath(tree)); } @Override public ImmutableClassToInstanceMap<Annotation> annotations() { return ImmutableClassToInstanceMap.of(); } /** Create a VisitorState object from a compilation unit. */ private VisitorState createVisitorState(Context context, DescriptionListener listener) { ErrorProneOptions options = requireNonNull(context.get(ErrorProneOptions.class)); return VisitorState.createConfiguredForCompilation( context, listener, scanner().severityMap(), options); } }
2,118
35.534483
90
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/scanner/InstanceReturningScannerSupplierImpl.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import com.google.common.collect.ImmutableBiMap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugCheckerInfo; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.ErrorProneFlags; /** * An implementation of a {@link ScannerSupplier} that just returns the {@link Scanner} that was * passed in. Used mostly for testing. Does not implement any method other than {@link * ScannerSupplier#get()}. */ class InstanceReturningScannerSupplierImpl extends ScannerSupplier { private final Scanner scanner; InstanceReturningScannerSupplierImpl(Scanner scanner) { this.scanner = scanner; } @Override public Scanner get() { return scanner; } @Override public ImmutableBiMap<String, BugCheckerInfo> getAllChecks() { // TODO(cushon): migrate users off Scanner-based ScannerSuppliers, and throw UOE here return ImmutableBiMap.of(); } @Override public ImmutableMap<String, SeverityLevel> severities() { throw new UnsupportedOperationException(); } @Override protected ImmutableSet<String> disabled() { throw new UnsupportedOperationException(); } @Override public ErrorProneFlags getFlags() { throw new UnsupportedOperationException(); } @Override public ImmutableSet<BugCheckerInfo> getEnabledChecks() { throw new UnsupportedOperationException(); } }
2,078
29.130435
96
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/scanner/ErrorProneScanner.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.scanner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.errorprone.BugPattern; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.ErrorProneError; import com.google.errorprone.ErrorProneOptions; import com.google.errorprone.SuppressionInfo.SuppressedState; import com.google.errorprone.VisitorState; import com.google.errorprone.bugpatterns.BugChecker; import com.google.errorprone.bugpatterns.BugChecker.AnnotatedTypeTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ArrayAccessTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ArrayTypeTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.AssertTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.AssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.BinaryTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.BlockTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.BreakTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.CaseTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.CatchTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.CompilationUnitTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.CompoundAssignmentTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ConditionalExpressionTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ContinueTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.DoWhileLoopTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.EmptyStatementTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.EnhancedForLoopTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ExpressionStatementTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ForLoopTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.IdentifierTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.IfTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ImportTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.InstanceOfTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.IntersectionTypeTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.LabeledStatementTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.LambdaExpressionTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.LiteralTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberReferenceTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MemberSelectTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ModifiersTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewArrayTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ParameterizedTypeTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ParenthesizedTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.PrimitiveTypeTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ReturnTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.SwitchTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.SynchronizedTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.ThrowTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.TryTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.TypeCastTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.TypeParameterTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.UnaryTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.UnionTypeTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.WhileLoopTreeMatcher; import com.google.errorprone.bugpatterns.BugChecker.WildcardTreeMatcher; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Suppressible; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ArrayAccessTree; import com.sun.source.tree.ArrayTypeTree; import com.sun.source.tree.AssertTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.BreakTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ContinueTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.EmptyStatementTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ForLoopTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.ImportTree; import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.IntersectionTypeTree; import com.sun.source.tree.LabeledStatementTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ModifiersTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.PrimitiveTypeTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.SwitchTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.ThrowTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.TypeParameterTree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.UnionTypeTree; import com.sun.source.tree.VariableTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.tree.WildcardTree; import com.sun.source.util.TreePath; import com.sun.tools.javac.code.Symbol.CompletionFailure; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.Name; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; /** * Scans the parsed AST, looking for violations of any of the enabled checks. * * @author Alex Eagle (alexeagle@google.com) */ public class ErrorProneScanner extends Scanner { private final com.google.errorprone.suppliers.Supplier<? extends Set<? extends Name>> customSuppressionAnnotations; private final Map<String, SeverityLevel> severities; private final ImmutableSet<BugChecker> bugCheckers; /** * Create an error-prone scanner for the given checkers. * * @param checkers The checkers that this scanner should use. */ public ErrorProneScanner(BugChecker... checkers) { this(Arrays.asList(checkers)); } /** * Create an error-prone scanner for a non-hardcoded set of checkers. * * @param checkers The checkers that this scanner should use. */ public ErrorProneScanner(Iterable<BugChecker> checkers) { this(checkers, defaultSeverities(checkers)); } /** * Create an error-prone scanner for a non-hardcoded set of checkers. * * @param checkers The checkers that this scanner should use. * @param severities The default check severities. */ public ErrorProneScanner(Iterable<BugChecker> checkers, Map<String, SeverityLevel> severities) { this.bugCheckers = ImmutableSet.copyOf(checkers); this.severities = severities; ImmutableSet.Builder<Class<? extends Annotation>> annotationClassesBuilder = ImmutableSet.builder(); for (BugChecker checker : this.bugCheckers) { registerNodeTypes(checker, annotationClassesBuilder); } ImmutableSet<Class<? extends Annotation>> annotationClasses = annotationClassesBuilder.build(); this.customSuppressionAnnotations = VisitorState.memoize( state -> { ImmutableSet.Builder<Name> builder = ImmutableSet.builder(); for (Class<? extends Annotation> annotation : annotationClasses) { builder.add(state.getName(annotation.getName())); } return builder.build(); }); } private static ImmutableMap<String, BugPattern.SeverityLevel> defaultSeverities( Iterable<BugChecker> checkers) { ImmutableMap.Builder<String, BugPattern.SeverityLevel> builder = ImmutableMap.builder(); for (BugChecker check : checkers) { builder.put(check.canonicalName(), check.defaultSeverity()); } return builder.buildOrThrow(); } @Override protected Set<? extends Name> getCustomSuppressionAnnotations(VisitorState state) { return customSuppressionAnnotations.get(state); } private final List<AnnotationTreeMatcher> annotationMatchers = new ArrayList<>(); private final List<AnnotatedTypeTreeMatcher> annotatedTypeMatchers = new ArrayList<>(); private final List<ArrayAccessTreeMatcher> arrayAccessMatchers = new ArrayList<>(); private final List<ArrayTypeTreeMatcher> arrayTypeMatchers = new ArrayList<>(); private final List<AssertTreeMatcher> assertMatchers = new ArrayList<>(); private final List<AssignmentTreeMatcher> assignmentMatchers = new ArrayList<>(); private final List<BinaryTreeMatcher> binaryMatchers = new ArrayList<>(); private final List<BlockTreeMatcher> blockMatchers = new ArrayList<>(); private final List<BreakTreeMatcher> breakMatchers = new ArrayList<>(); private final List<CaseTreeMatcher> caseMatchers = new ArrayList<>(); private final List<CatchTreeMatcher> catchMatchers = new ArrayList<>(); private final List<ClassTreeMatcher> classMatchers = new ArrayList<>(); private final List<CompilationUnitTreeMatcher> compilationUnitMatchers = new ArrayList<>(); private final List<CompoundAssignmentTreeMatcher> compoundAssignmentMatchers = new ArrayList<>(); private final List<ConditionalExpressionTreeMatcher> conditionalExpressionMatchers = new ArrayList<>(); private final List<ContinueTreeMatcher> continueMatchers = new ArrayList<>(); private final List<DoWhileLoopTreeMatcher> doWhileLoopMatchers = new ArrayList<>(); private final List<EmptyStatementTreeMatcher> emptyStatementMatchers = new ArrayList<>(); private final List<EnhancedForLoopTreeMatcher> enhancedForLoopMatchers = new ArrayList<>(); private final List<ExpressionStatementTreeMatcher> expressionStatementMatchers = new ArrayList<>(); private final List<ForLoopTreeMatcher> forLoopMatchers = new ArrayList<>(); private final List<IdentifierTreeMatcher> identifierMatchers = new ArrayList<>(); private final List<IfTreeMatcher> ifMatchers = new ArrayList<>(); private final List<ImportTreeMatcher> importMatchers = new ArrayList<>(); private final List<InstanceOfTreeMatcher> instanceOfMatchers = new ArrayList<>(); private final List<IntersectionTypeTreeMatcher> intersectionTypeMatchers = new ArrayList<>(); private final List<LabeledStatementTreeMatcher> labeledStatementMatchers = new ArrayList<>(); private final List<LambdaExpressionTreeMatcher> lambdaExpressionMatchers = new ArrayList<>(); private final List<LiteralTreeMatcher> literalMatchers = new ArrayList<>(); private final List<MemberReferenceTreeMatcher> memberReferenceMatchers = new ArrayList<>(); private final List<MemberSelectTreeMatcher> memberSelectMatchers = new ArrayList<>(); private final List<MethodTreeMatcher> methodMatchers = new ArrayList<>(); private final List<MethodInvocationTreeMatcher> methodInvocationMatchers = new ArrayList<>(); private final List<ModifiersTreeMatcher> modifiersMatchers = new ArrayList<>(); private final List<NewArrayTreeMatcher> newArrayMatchers = new ArrayList<>(); private final List<NewClassTreeMatcher> newClassMatchers = new ArrayList<>(); private final List<ParameterizedTypeTreeMatcher> parameterizedTypeMatchers = new ArrayList<>(); private final List<ParenthesizedTreeMatcher> parenthesizedMatchers = new ArrayList<>(); private final List<PrimitiveTypeTreeMatcher> primitiveTypeMatchers = new ArrayList<>(); private final List<ReturnTreeMatcher> returnMatchers = new ArrayList<>(); private final List<SwitchTreeMatcher> switchMatchers = new ArrayList<>(); private final List<SynchronizedTreeMatcher> synchronizedMatchers = new ArrayList<>(); private final List<ThrowTreeMatcher> throwMatchers = new ArrayList<>(); private final List<TryTreeMatcher> tryMatchers = new ArrayList<>(); private final List<TypeCastTreeMatcher> typeCastMatchers = new ArrayList<>(); private final List<TypeParameterTreeMatcher> typeParameterMatchers = new ArrayList<>(); private final List<UnaryTreeMatcher> unaryMatchers = new ArrayList<>(); private final List<UnionTypeTreeMatcher> unionTypeMatchers = new ArrayList<>(); private final List<VariableTreeMatcher> variableMatchers = new ArrayList<>(); private final List<WhileLoopTreeMatcher> whileLoopMatchers = new ArrayList<>(); private final List<WildcardTreeMatcher> wildcardMatchers = new ArrayList<>(); private void registerNodeTypes( BugChecker checker, ImmutableSet.Builder<Class<? extends Annotation>> customSuppressionAnnotationClasses) { customSuppressionAnnotationClasses.addAll(checker.customSuppressionAnnotations()); if (checker instanceof AnnotationTreeMatcher) { annotationMatchers.add((AnnotationTreeMatcher) checker); } if (checker instanceof AnnotatedTypeTreeMatcher) { annotatedTypeMatchers.add((AnnotatedTypeTreeMatcher) checker); } if (checker instanceof ArrayAccessTreeMatcher) { arrayAccessMatchers.add((ArrayAccessTreeMatcher) checker); } if (checker instanceof ArrayTypeTreeMatcher) { arrayTypeMatchers.add((ArrayTypeTreeMatcher) checker); } if (checker instanceof AssertTreeMatcher) { assertMatchers.add((AssertTreeMatcher) checker); } if (checker instanceof AssignmentTreeMatcher) { assignmentMatchers.add((AssignmentTreeMatcher) checker); } if (checker instanceof BinaryTreeMatcher) { binaryMatchers.add((BinaryTreeMatcher) checker); } if (checker instanceof BlockTreeMatcher) { blockMatchers.add((BlockTreeMatcher) checker); } if (checker instanceof BreakTreeMatcher) { breakMatchers.add((BreakTreeMatcher) checker); } if (checker instanceof CaseTreeMatcher) { caseMatchers.add((CaseTreeMatcher) checker); } if (checker instanceof CatchTreeMatcher) { catchMatchers.add((CatchTreeMatcher) checker); } if (checker instanceof ClassTreeMatcher) { classMatchers.add((ClassTreeMatcher) checker); } if (checker instanceof CompilationUnitTreeMatcher) { compilationUnitMatchers.add((CompilationUnitTreeMatcher) checker); } if (checker instanceof CompoundAssignmentTreeMatcher) { compoundAssignmentMatchers.add((CompoundAssignmentTreeMatcher) checker); } if (checker instanceof ConditionalExpressionTreeMatcher) { conditionalExpressionMatchers.add((ConditionalExpressionTreeMatcher) checker); } if (checker instanceof ContinueTreeMatcher) { continueMatchers.add((ContinueTreeMatcher) checker); } if (checker instanceof DoWhileLoopTreeMatcher) { doWhileLoopMatchers.add((DoWhileLoopTreeMatcher) checker); } if (checker instanceof EmptyStatementTreeMatcher) { emptyStatementMatchers.add((EmptyStatementTreeMatcher) checker); } if (checker instanceof EnhancedForLoopTreeMatcher) { enhancedForLoopMatchers.add((EnhancedForLoopTreeMatcher) checker); } if (checker instanceof ExpressionStatementTreeMatcher) { expressionStatementMatchers.add((ExpressionStatementTreeMatcher) checker); } if (checker instanceof ForLoopTreeMatcher) { forLoopMatchers.add((ForLoopTreeMatcher) checker); } if (checker instanceof IdentifierTreeMatcher) { identifierMatchers.add((IdentifierTreeMatcher) checker); } if (checker instanceof IfTreeMatcher) { ifMatchers.add((IfTreeMatcher) checker); } if (checker instanceof ImportTreeMatcher) { importMatchers.add((ImportTreeMatcher) checker); } if (checker instanceof InstanceOfTreeMatcher) { instanceOfMatchers.add((InstanceOfTreeMatcher) checker); } if (checker instanceof IntersectionTypeTreeMatcher) { intersectionTypeMatchers.add((IntersectionTypeTreeMatcher) checker); } if (checker instanceof LabeledStatementTreeMatcher) { labeledStatementMatchers.add((LabeledStatementTreeMatcher) checker); } if (checker instanceof LambdaExpressionTreeMatcher) { lambdaExpressionMatchers.add((LambdaExpressionTreeMatcher) checker); } if (checker instanceof LiteralTreeMatcher) { literalMatchers.add((LiteralTreeMatcher) checker); } if (checker instanceof MemberReferenceTreeMatcher) { memberReferenceMatchers.add((MemberReferenceTreeMatcher) checker); } if (checker instanceof MemberSelectTreeMatcher) { memberSelectMatchers.add((MemberSelectTreeMatcher) checker); } if (checker instanceof MethodTreeMatcher) { methodMatchers.add((MethodTreeMatcher) checker); } if (checker instanceof MethodInvocationTreeMatcher) { methodInvocationMatchers.add((MethodInvocationTreeMatcher) checker); } if (checker instanceof ModifiersTreeMatcher) { modifiersMatchers.add((ModifiersTreeMatcher) checker); } if (checker instanceof NewArrayTreeMatcher) { newArrayMatchers.add((NewArrayTreeMatcher) checker); } if (checker instanceof NewClassTreeMatcher) { newClassMatchers.add((NewClassTreeMatcher) checker); } if (checker instanceof ParameterizedTypeTreeMatcher) { parameterizedTypeMatchers.add((ParameterizedTypeTreeMatcher) checker); } if (checker instanceof ParenthesizedTreeMatcher) { parenthesizedMatchers.add((ParenthesizedTreeMatcher) checker); } if (checker instanceof PrimitiveTypeTreeMatcher) { primitiveTypeMatchers.add((PrimitiveTypeTreeMatcher) checker); } if (checker instanceof ReturnTreeMatcher) { returnMatchers.add((ReturnTreeMatcher) checker); } if (checker instanceof SwitchTreeMatcher) { switchMatchers.add((SwitchTreeMatcher) checker); } if (checker instanceof SynchronizedTreeMatcher) { synchronizedMatchers.add((SynchronizedTreeMatcher) checker); } if (checker instanceof ThrowTreeMatcher) { throwMatchers.add((ThrowTreeMatcher) checker); } if (checker instanceof TryTreeMatcher) { tryMatchers.add((TryTreeMatcher) checker); } if (checker instanceof TypeCastTreeMatcher) { typeCastMatchers.add((TypeCastTreeMatcher) checker); } if (checker instanceof TypeParameterTreeMatcher) { typeParameterMatchers.add((TypeParameterTreeMatcher) checker); } if (checker instanceof UnaryTreeMatcher) { unaryMatchers.add((UnaryTreeMatcher) checker); } if (checker instanceof UnionTypeTreeMatcher) { unionTypeMatchers.add((UnionTypeTreeMatcher) checker); } if (checker instanceof VariableTreeMatcher) { variableMatchers.add((VariableTreeMatcher) checker); } if (checker instanceof WhileLoopTreeMatcher) { whileLoopMatchers.add((WhileLoopTreeMatcher) checker); } if (checker instanceof WildcardTreeMatcher) { wildcardMatchers.add((WildcardTreeMatcher) checker); } } @FunctionalInterface private interface TreeProcessor<M extends Suppressible, T extends Tree> { Description process(M matcher, T tree, VisitorState state); } private <M extends Suppressible, T extends Tree> VisitorState processMatchers( Iterable<M> matchers, T tree, TreeProcessor<M, T> processingFunction, VisitorState oldState) { ErrorProneOptions errorProneOptions = oldState.errorProneOptions(); // A VisitorState with our new path, but without mentioning the suppression of any matcher. VisitorState newState = oldState.withPath(getCurrentPath()); for (M matcher : matchers) { SuppressedState suppressed = isSuppressed(matcher, errorProneOptions, newState); // If the ErrorProneOptions say to visit suppressed code, we still visit it if (suppressed == SuppressedState.UNSUPPRESSED || errorProneOptions.isIgnoreSuppressionAnnotations()) { try (AutoCloseable unused = oldState.timingSpan(matcher)) { // We create a new VisitorState with the suppression info specific to this matcher. VisitorState stateWithSuppressionInformation = newState.withSuppression(suppressed); reportMatch( processingFunction.process(matcher, tree, stateWithSuppressionInformation), stateWithSuppressionInformation); } catch (Exception | AssertionError t) { handleError(matcher, t); } } } return newState; } @Override public Void visitAnnotation(AnnotationTree tree, VisitorState visitorState) { VisitorState state = processMatchers( annotationMatchers, tree, AnnotationTreeMatcher::matchAnnotation, visitorState); return super.visitAnnotation(tree, state); } @Override public Void visitAnnotatedType(AnnotatedTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( annotatedTypeMatchers, tree, AnnotatedTypeTreeMatcher::matchAnnotatedType, visitorState); return super.visitAnnotatedType(tree, state); } @Override public Void visitArrayAccess(ArrayAccessTree tree, VisitorState visitorState) { VisitorState state = processMatchers( arrayAccessMatchers, tree, ArrayAccessTreeMatcher::matchArrayAccess, visitorState); return super.visitArrayAccess(tree, state); } @Override public Void visitArrayType(ArrayTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( arrayTypeMatchers, tree, ArrayTypeTreeMatcher::matchArrayType, visitorState); return super.visitArrayType(tree, state); } @Override public Void visitAssert(AssertTree tree, VisitorState visitorState) { VisitorState state = processMatchers(assertMatchers, tree, AssertTreeMatcher::matchAssert, visitorState); return super.visitAssert(tree, state); } @Override public Void visitAssignment(AssignmentTree tree, VisitorState visitorState) { VisitorState state = processMatchers( assignmentMatchers, tree, AssignmentTreeMatcher::matchAssignment, visitorState); return super.visitAssignment(tree, state); } @Override public Void visitBinary(BinaryTree tree, VisitorState visitorState) { VisitorState state = processMatchers(binaryMatchers, tree, BinaryTreeMatcher::matchBinary, visitorState); return super.visitBinary(tree, state); } @Override public Void visitBlock(BlockTree tree, VisitorState visitorState) { VisitorState state = processMatchers(blockMatchers, tree, BlockTreeMatcher::matchBlock, visitorState); return super.visitBlock(tree, state); } @Override public Void visitBreak(BreakTree tree, VisitorState visitorState) { VisitorState state = processMatchers(breakMatchers, tree, BreakTreeMatcher::matchBreak, visitorState); return super.visitBreak(tree, state); } @Override public Void visitCase(CaseTree tree, VisitorState visitorState) { VisitorState state = processMatchers(caseMatchers, tree, CaseTreeMatcher::matchCase, visitorState); return super.visitCase(tree, state); } @Override public Void visitCatch(CatchTree tree, VisitorState visitorState) { VisitorState state = processMatchers(catchMatchers, tree, CatchTreeMatcher::matchCatch, visitorState); return super.visitCatch(tree, state); } @Override public Void visitClass(ClassTree tree, VisitorState visitorState) { VisitorState state = processMatchers(classMatchers, tree, ClassTreeMatcher::matchClass, visitorState); return super.visitClass(tree, state); } @Override public Void visitCompilationUnit(CompilationUnitTree tree, VisitorState visitorState) { VisitorState state = processMatchers( compilationUnitMatchers, tree, CompilationUnitTreeMatcher::matchCompilationUnit, visitorState); return super.visitCompilationUnit(tree, state); } @Override public Void visitCompoundAssignment(CompoundAssignmentTree tree, VisitorState visitorState) { VisitorState state = processMatchers( compoundAssignmentMatchers, tree, CompoundAssignmentTreeMatcher::matchCompoundAssignment, visitorState); return super.visitCompoundAssignment(tree, state); } @Override public Void visitConditionalExpression( ConditionalExpressionTree tree, VisitorState visitorState) { VisitorState state = processMatchers( conditionalExpressionMatchers, tree, ConditionalExpressionTreeMatcher::matchConditionalExpression, visitorState); return super.visitConditionalExpression(tree, state); } @Override public Void visitContinue(ContinueTree tree, VisitorState visitorState) { VisitorState state = processMatchers(continueMatchers, tree, ContinueTreeMatcher::matchContinue, visitorState); return super.visitContinue(tree, state); } @Override public Void visitDoWhileLoop(DoWhileLoopTree tree, VisitorState visitorState) { VisitorState state = processMatchers( doWhileLoopMatchers, tree, DoWhileLoopTreeMatcher::matchDoWhileLoop, visitorState); return super.visitDoWhileLoop(tree, state); } @Override public Void visitEmptyStatement(EmptyStatementTree tree, VisitorState visitorState) { VisitorState state = processMatchers( emptyStatementMatchers, tree, EmptyStatementTreeMatcher::matchEmptyStatement, visitorState); return super.visitEmptyStatement(tree, state); } @Override public Void visitEnhancedForLoop(EnhancedForLoopTree tree, VisitorState visitorState) { VisitorState state = processMatchers( enhancedForLoopMatchers, tree, EnhancedForLoopTreeMatcher::matchEnhancedForLoop, visitorState); return super.visitEnhancedForLoop(tree, state); } // Intentionally skip visitErroneous -- we don't analyze malformed expressions. @Override public Void visitExpressionStatement(ExpressionStatementTree tree, VisitorState visitorState) { VisitorState state = processMatchers( expressionStatementMatchers, tree, ExpressionStatementTreeMatcher::matchExpressionStatement, visitorState); return super.visitExpressionStatement(tree, state); } @Override public Void visitForLoop(ForLoopTree tree, VisitorState visitorState) { VisitorState state = processMatchers(forLoopMatchers, tree, ForLoopTreeMatcher::matchForLoop, visitorState); return super.visitForLoop(tree, state); } @Override public Void visitIdentifier(IdentifierTree tree, VisitorState visitorState) { VisitorState state = processMatchers( identifierMatchers, tree, IdentifierTreeMatcher::matchIdentifier, visitorState); return super.visitIdentifier(tree, state); } @Override public Void visitIf(IfTree tree, VisitorState visitorState) { VisitorState state = processMatchers(ifMatchers, tree, IfTreeMatcher::matchIf, visitorState); return super.visitIf(tree, state); } @Override public Void visitImport(ImportTree tree, VisitorState visitorState) { VisitorState state = processMatchers(importMatchers, tree, ImportTreeMatcher::matchImport, visitorState); return super.visitImport(tree, state); } @Override public Void visitInstanceOf(InstanceOfTree tree, VisitorState visitorState) { VisitorState state = processMatchers( instanceOfMatchers, tree, InstanceOfTreeMatcher::matchInstanceOf, visitorState); return super.visitInstanceOf(tree, state); } @Override public Void visitIntersectionType(IntersectionTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( intersectionTypeMatchers, tree, IntersectionTypeTreeMatcher::matchIntersectionType, visitorState); return super.visitIntersectionType(tree, state); } @Override public Void visitLabeledStatement(LabeledStatementTree tree, VisitorState visitorState) { VisitorState state = processMatchers( labeledStatementMatchers, tree, LabeledStatementTreeMatcher::matchLabeledStatement, visitorState); return super.visitLabeledStatement(tree, state); } @Override public Void visitLambdaExpression(LambdaExpressionTree tree, VisitorState visitorState) { VisitorState state = processMatchers( lambdaExpressionMatchers, tree, LambdaExpressionTreeMatcher::matchLambdaExpression, visitorState); return super.visitLambdaExpression(tree, state); } @Override public Void visitLiteral(LiteralTree tree, VisitorState visitorState) { VisitorState state = processMatchers(literalMatchers, tree, LiteralTreeMatcher::matchLiteral, visitorState); return super.visitLiteral(tree, state); } @Override public Void visitMemberReference(MemberReferenceTree tree, VisitorState visitorState) { VisitorState state = processMatchers( memberReferenceMatchers, tree, MemberReferenceTreeMatcher::matchMemberReference, visitorState); return super.visitMemberReference(tree, state); } @Override public Void visitMemberSelect(MemberSelectTree tree, VisitorState visitorState) { VisitorState state = processMatchers( memberSelectMatchers, tree, MemberSelectTreeMatcher::matchMemberSelect, visitorState); return super.visitMemberSelect(tree, state); } @Override public Void visitMethod(MethodTree tree, VisitorState visitorState) { // Ignore synthetic constructors: if (ASTHelpers.isGeneratedConstructor(tree)) { return null; } VisitorState state = processMatchers(methodMatchers, tree, MethodTreeMatcher::matchMethod, visitorState); return super.visitMethod(tree, state); } @Override public Void visitMethodInvocation(MethodInvocationTree tree, VisitorState visitorState) { VisitorState state = processMatchers( methodInvocationMatchers, tree, MethodInvocationTreeMatcher::matchMethodInvocation, visitorState); return super.visitMethodInvocation(tree, state); } @Override public Void visitModifiers(ModifiersTree tree, VisitorState visitorState) { VisitorState state = processMatchers( modifiersMatchers, tree, ModifiersTreeMatcher::matchModifiers, visitorState); return super.visitModifiers(tree, state); } @Override public Void visitNewArray(NewArrayTree tree, VisitorState visitorState) { VisitorState state = processMatchers(newArrayMatchers, tree, NewArrayTreeMatcher::matchNewArray, visitorState); return super.visitNewArray(tree, state); } @Override public Void visitNewClass(NewClassTree tree, VisitorState visitorState) { VisitorState state = processMatchers(newClassMatchers, tree, NewClassTreeMatcher::matchNewClass, visitorState); return super.visitNewClass(tree, state); } // Intentionally skip visitOther. It seems to be used only for let expressions, which are // generated by javac to implement autoboxing. We are only interested in source-level constructs. @Override public Void visitParameterizedType(ParameterizedTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( parameterizedTypeMatchers, tree, ParameterizedTypeTreeMatcher::matchParameterizedType, visitorState); return super.visitParameterizedType(tree, state); } @Override public Void visitParenthesized(ParenthesizedTree tree, VisitorState visitorState) { VisitorState state = processMatchers( parenthesizedMatchers, tree, ParenthesizedTreeMatcher::matchParenthesized, visitorState); return super.visitParenthesized(tree, state); } @Override public Void visitPrimitiveType(PrimitiveTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( primitiveTypeMatchers, tree, PrimitiveTypeTreeMatcher::matchPrimitiveType, visitorState); return super.visitPrimitiveType(tree, state); } @Override public Void visitReturn(ReturnTree tree, VisitorState visitorState) { VisitorState state = processMatchers(returnMatchers, tree, ReturnTreeMatcher::matchReturn, visitorState); return super.visitReturn(tree, state); } @Override public Void visitSwitch(SwitchTree tree, VisitorState visitorState) { VisitorState state = processMatchers(switchMatchers, tree, SwitchTreeMatcher::matchSwitch, visitorState); return super.visitSwitch(tree, state); } @Override public Void visitSynchronized(SynchronizedTree tree, VisitorState visitorState) { VisitorState state = processMatchers( synchronizedMatchers, tree, SynchronizedTreeMatcher::matchSynchronized, visitorState); return super.visitSynchronized(tree, state); } @Override public Void visitThrow(ThrowTree tree, VisitorState visitorState) { VisitorState state = processMatchers(throwMatchers, tree, ThrowTreeMatcher::matchThrow, visitorState); return super.visitThrow(tree, state); } @Override public Void visitTry(TryTree tree, VisitorState visitorState) { VisitorState state = processMatchers(tryMatchers, tree, TryTreeMatcher::matchTry, visitorState); return super.visitTry(tree, state); } @Override public Void visitTypeCast(TypeCastTree tree, VisitorState visitorState) { VisitorState state = processMatchers(typeCastMatchers, tree, TypeCastTreeMatcher::matchTypeCast, visitorState); return super.visitTypeCast(tree, state); } @Override public Void visitTypeParameter(TypeParameterTree tree, VisitorState visitorState) { VisitorState state = processMatchers( typeParameterMatchers, tree, TypeParameterTreeMatcher::matchTypeParameter, visitorState); return super.visitTypeParameter(tree, state); } @Override public Void visitUnary(UnaryTree tree, VisitorState visitorState) { VisitorState state = processMatchers(unaryMatchers, tree, UnaryTreeMatcher::matchUnary, visitorState); return super.visitUnary(tree, state); } @Override public Void visitUnionType(UnionTypeTree tree, VisitorState visitorState) { VisitorState state = processMatchers( unionTypeMatchers, tree, UnionTypeTreeMatcher::matchUnionType, visitorState); return super.visitUnionType(tree, state); } @Override public Void visitVariable(VariableTree tree, VisitorState visitorState) { VisitorState state = processMatchers(variableMatchers, tree, VariableTreeMatcher::matchVariable, visitorState); return super.visitVariable(tree, state); } @Override public Void visitWhileLoop(WhileLoopTree tree, VisitorState visitorState) { VisitorState state = processMatchers( whileLoopMatchers, tree, WhileLoopTreeMatcher::matchWhileLoop, visitorState); return super.visitWhileLoop(tree, state); } @Override public Void visitWildcard(WildcardTree tree, VisitorState visitorState) { VisitorState state = processMatchers(wildcardMatchers, tree, WildcardTreeMatcher::matchWildcard, visitorState); return super.visitWildcard(tree, state); } /** * Handles an exception thrown by an individual BugPattern. By default, wraps the exception in an * {@link ErrorProneError} and rethrows. May be overridden by subclasses, for example to log the * error and continue. */ @Override protected void handleError(Suppressible s, Throwable t) { if (t instanceof ErrorProneError) { throw (ErrorProneError) t; } if (t instanceof CompletionFailure) { throw (CompletionFailure) t; } TreePath path = getCurrentPath(); throw new ErrorProneError( s.canonicalName(), t, (DiagnosticPosition) path.getLeaf(), path.getCompilationUnit().getSourceFile()); } @Override public Map<String, SeverityLevel> severityMap() { return severities; } public ImmutableSet<BugChecker> getBugCheckers() { return this.bugCheckers; } }
38,520
40.287245
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/bugpatterns/BugChecker.java
/* * Copyright 2013 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.bugpatterns; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static com.google.errorprone.util.ASTHelpers.getModifiers; import static com.google.errorprone.util.ASTHelpers.getStartPosition; import static com.google.errorprone.util.ASTHelpers.getSymbol; import com.google.common.collect.ImmutableRangeSet; import com.google.common.collect.Iterables; import com.google.common.collect.Range; import com.google.errorprone.BugCheckerInfo; import com.google.errorprone.BugPattern.SeverityLevel; import com.google.errorprone.ErrorProneOptions; import com.google.errorprone.SuppressionInfo; import com.google.errorprone.VisitorState; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.fixes.Fix; import com.google.errorprone.matchers.Description; import com.google.errorprone.matchers.Suppressible; import com.google.errorprone.suppliers.Supplier; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.AnnotatedTypeTree; import com.sun.source.tree.AnnotationTree; import com.sun.source.tree.ArrayAccessTree; import com.sun.source.tree.ArrayTypeTree; import com.sun.source.tree.AssertTree; import com.sun.source.tree.AssignmentTree; import com.sun.source.tree.BinaryTree; import com.sun.source.tree.BlockTree; import com.sun.source.tree.BreakTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.CatchTree; import com.sun.source.tree.ClassTree; import com.sun.source.tree.CompilationUnitTree; import com.sun.source.tree.CompoundAssignmentTree; import com.sun.source.tree.ConditionalExpressionTree; import com.sun.source.tree.ContinueTree; import com.sun.source.tree.DoWhileLoopTree; import com.sun.source.tree.EmptyStatementTree; import com.sun.source.tree.EnhancedForLoopTree; import com.sun.source.tree.ExpressionStatementTree; import com.sun.source.tree.ForLoopTree; import com.sun.source.tree.IdentifierTree; import com.sun.source.tree.IfTree; import com.sun.source.tree.ImportTree; import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.IntersectionTypeTree; import com.sun.source.tree.LabeledStatementTree; import com.sun.source.tree.LambdaExpressionTree; import com.sun.source.tree.LiteralTree; import com.sun.source.tree.MemberReferenceTree; import com.sun.source.tree.MemberSelectTree; import com.sun.source.tree.MethodInvocationTree; import com.sun.source.tree.MethodTree; import com.sun.source.tree.ModifiersTree; import com.sun.source.tree.NewArrayTree; import com.sun.source.tree.NewClassTree; import com.sun.source.tree.ParameterizedTypeTree; import com.sun.source.tree.ParenthesizedTree; import com.sun.source.tree.PrimitiveTypeTree; import com.sun.source.tree.ReturnTree; import com.sun.source.tree.SwitchTree; import com.sun.source.tree.SynchronizedTree; import com.sun.source.tree.ThrowTree; import com.sun.source.tree.Tree; import com.sun.source.tree.TryTree; import com.sun.source.tree.TypeCastTree; import com.sun.source.tree.TypeParameterTree; import com.sun.source.tree.UnaryTree; import com.sun.source.tree.UnionTypeTree; import com.sun.source.tree.VariableTree; import com.sun.source.tree.WhileLoopTree; import com.sun.source.tree.WildcardTree; import com.sun.source.util.TreePath; import com.sun.source.util.TreePathScanner; import com.sun.source.util.TreeScanner; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition; import com.sun.tools.javac.util.Name; import java.io.Serializable; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collections; import java.util.Objects; import java.util.Set; import java.util.function.BiPredicate; /** * A base class for implementing bug checkers. The {@code BugChecker} supplies a Scanner * implementation for this checker, making it easy to use a single checker. Subclasses should also * implement one or more of the {@code *Matcher} interfaces in this class to declare which tree node * types to match against. * * @author Colin Decker * @author Eddie Aftandilian (eaftan@google.com) */ public abstract class BugChecker implements Suppressible, Serializable { private final BugCheckerInfo info; private final BiPredicate<Set<? extends Name>, VisitorState> checkSuppression; public BugChecker() { info = BugCheckerInfo.create(getClass()); checkSuppression = suppressionPredicate(info.customSuppressionAnnotations()); } private static BiPredicate<Set<? extends Name>, VisitorState> suppressionPredicate( Set<Class<? extends Annotation>> suppressionClasses) { switch (suppressionClasses.size()) { case 0: return (annos, state) -> false; case 1: { Supplier<Name> self = VisitorState.memoize( state -> state.getName(Iterables.getOnlyElement(suppressionClasses).getName())); return (annos, state) -> annos.contains(self.get(state)); } default: { Supplier<Set<? extends Name>> self = VisitorState.memoize( state -> suppressionClasses.stream() .map(Class::getName) .map(state::getName) .collect(toImmutableSet())); return (annos, state) -> !Collections.disjoint(self.get(state), annos); } } } /** Helper to create a Description for the common case where there is a fix. */ @CheckReturnValue public Description describeMatch(Tree node, Fix fix) { return buildDescription(node).addFix(fix).build(); } /** Helper to create a Description for the common case where there is a fix. */ @CheckReturnValue public Description describeMatch(JCTree node, Fix fix) { return describeMatch((Tree) node, fix); } /** Helper to create a Description for the common case where there is a fix. */ @CheckReturnValue public Description describeMatch(DiagnosticPosition position, Fix fix) { return buildDescription(position).addFix(fix).build(); } /** Helper to create a Description for the common case where there is no fix. */ @CheckReturnValue public Description describeMatch(Tree node) { return buildDescription(node).build(); } /** Helper to create a Description for the common case where there is no fix. */ @CheckReturnValue public Description describeMatch(JCTree node) { return buildDescription(node).build(); } /** Helper to create a Description for the common case where there is no fix. */ @CheckReturnValue public Description describeMatch(DiagnosticPosition position) { return buildDescription(position).build(); } /** * Returns a Description builder, which allows you to customize the diagnostic with a custom * message or multiple fixes. */ @CheckReturnValue public Description.Builder buildDescription(Tree node) { return Description.builder(node, canonicalName(), linkUrl(), message()); } /** * Returns a Description builder, which allows you to customize the diagnostic with a custom * message or multiple fixes. */ @CheckReturnValue public Description.Builder buildDescription(DiagnosticPosition position) { return Description.builder(position, canonicalName(), linkUrl(), message()); } /** * Returns a Description builder, which allows you to customize the diagnostic with a custom * message or multiple fixes. */ // This overload exists purely to disambiguate for JCTree. @CheckReturnValue public Description.Builder buildDescription(JCTree tree) { return Description.builder(tree, canonicalName(), linkUrl(), message()); } @Override public String canonicalName() { return info.canonicalName(); } @Override public Set<String> allNames() { return info.allNames(); } public String message() { return info.message(); } public SeverityLevel defaultSeverity() { return info.defaultSeverity(); } public String linkUrl() { return info.linkUrl(); } @Override public boolean supportsSuppressWarnings() { return info.supportsSuppressWarnings(); } public boolean disableable() { return info.disableable(); } @Override public Set<Class<? extends Annotation>> customSuppressionAnnotations() { return info.customSuppressionAnnotations(); } @Override public boolean suppressedByAnyOf(Set<Name> annotations, VisitorState s) { return checkSuppression.test(annotations, s); } /** * @deprecated use {@link #isSuppressed(Tree, VisitorState)} instead */ @Deprecated public boolean isSuppressed(Tree tree) { return isSuppressed(ASTHelpers.getAnnotation(tree, SuppressWarnings.class)); } /** * @deprecated use {@link #isSuppressed(Symbol, VisitorState)} instead */ @Deprecated public boolean isSuppressed(Symbol symbol) { return isSuppressed(ASTHelpers.getAnnotation(symbol, SuppressWarnings.class)); } private boolean isSuppressed(SuppressWarnings suppression) { return suppression != null && !Collections.disjoint(Arrays.asList(suppression.value()), allNames()); } /** * Returns true if the given tree is annotated with a {@code @SuppressWarnings} that disables this * bug checker. */ public boolean isSuppressed(Tree tree, VisitorState state) { Symbol sym = getSymbol(tree); return sym != null && isSuppressed(sym, state); } /** * Returns true if the given symbol is annotated with a {@code @SuppressWarnings} or other * annotation that disables this bug checker. */ public boolean isSuppressed(Symbol sym, VisitorState state) { ErrorProneOptions errorProneOptions = state.errorProneOptions(); boolean suppressedInGeneratedCode = errorProneOptions.disableWarningsInGeneratedCode() && state.severityMap().get(canonicalName()) != SeverityLevel.ERROR; SuppressionInfo.SuppressedState suppressedState = SuppressionInfo.EMPTY .withExtendedSuppressions(sym, state, customSuppressionAnnotationNames.get(state)) .suppressedState(BugChecker.this, suppressedInGeneratedCode, state); return suppressedState == SuppressionInfo.SuppressedState.SUPPRESSED; } private final Supplier<? extends Set<? extends Name>> customSuppressionAnnotationNames = VisitorState.memoize( state -> customSuppressionAnnotations().stream() .map(a -> state.getName(a.getName())) .collect(toImmutableSet())); /** Computes a RangeSet of code regions which are suppressed by this bug checker. */ public ImmutableRangeSet<Integer> suppressedRegions(VisitorState state) { ImmutableRangeSet.Builder<Integer> suppressedRegions = ImmutableRangeSet.builder(); new TreeScanner<Void, Void>() { @Override public Void scan(Tree tree, Void unused) { if (getModifiers(tree) != null && isSuppressed(tree, state)) { suppressedRegions.add(Range.closed(getStartPosition(tree), state.getEndPosition(tree))); } else { super.scan(tree, null); } return null; } }.scan(state.getPath().getCompilationUnit(), null); return suppressedRegions.build(); } public interface AnnotationTreeMatcher extends Suppressible { Description matchAnnotation(AnnotationTree tree, VisitorState state); } public interface AnnotatedTypeTreeMatcher extends Suppressible { Description matchAnnotatedType(AnnotatedTypeTree tree, VisitorState state); } public interface ArrayAccessTreeMatcher extends Suppressible { Description matchArrayAccess(ArrayAccessTree tree, VisitorState state); } public interface ArrayTypeTreeMatcher extends Suppressible { Description matchArrayType(ArrayTypeTree tree, VisitorState state); } public interface AssertTreeMatcher extends Suppressible { Description matchAssert(AssertTree tree, VisitorState state); } public interface AssignmentTreeMatcher extends Suppressible { Description matchAssignment(AssignmentTree tree, VisitorState state); } public interface BinaryTreeMatcher extends Suppressible { Description matchBinary(BinaryTree tree, VisitorState state); } public interface BlockTreeMatcher extends Suppressible { Description matchBlock(BlockTree tree, VisitorState state); } public interface BreakTreeMatcher extends Suppressible { Description matchBreak(BreakTree tree, VisitorState state); } public interface CaseTreeMatcher extends Suppressible { Description matchCase(CaseTree tree, VisitorState state); } public interface CatchTreeMatcher extends Suppressible { Description matchCatch(CatchTree tree, VisitorState state); } public interface ClassTreeMatcher extends Suppressible { Description matchClass(ClassTree tree, VisitorState state); } public interface CompilationUnitTreeMatcher extends Suppressible { Description matchCompilationUnit(CompilationUnitTree tree, VisitorState state); } public interface CompoundAssignmentTreeMatcher extends Suppressible { Description matchCompoundAssignment(CompoundAssignmentTree tree, VisitorState state); } public interface ConditionalExpressionTreeMatcher extends Suppressible { Description matchConditionalExpression(ConditionalExpressionTree tree, VisitorState state); } public interface ContinueTreeMatcher extends Suppressible { Description matchContinue(ContinueTree tree, VisitorState state); } public interface DoWhileLoopTreeMatcher extends Suppressible { Description matchDoWhileLoop(DoWhileLoopTree tree, VisitorState state); } public interface EmptyStatementTreeMatcher extends Suppressible { Description matchEmptyStatement(EmptyStatementTree tree, VisitorState state); } public interface EnhancedForLoopTreeMatcher extends Suppressible { Description matchEnhancedForLoop(EnhancedForLoopTree tree, VisitorState state); } // Intentionally skip ErroneousTreeMatcher -- we don't analyze malformed expressions. public interface ExpressionStatementTreeMatcher extends Suppressible { Description matchExpressionStatement(ExpressionStatementTree tree, VisitorState state); } public interface ForLoopTreeMatcher extends Suppressible { Description matchForLoop(ForLoopTree tree, VisitorState state); } public interface IdentifierTreeMatcher extends Suppressible { Description matchIdentifier(IdentifierTree tree, VisitorState state); } public interface IfTreeMatcher extends Suppressible { Description matchIf(IfTree tree, VisitorState state); } public interface ImportTreeMatcher extends Suppressible { Description matchImport(ImportTree tree, VisitorState state); } public interface InstanceOfTreeMatcher extends Suppressible { Description matchInstanceOf(InstanceOfTree tree, VisitorState state); } public interface IntersectionTypeTreeMatcher extends Suppressible { Description matchIntersectionType(IntersectionTypeTree tree, VisitorState state); } public interface LabeledStatementTreeMatcher extends Suppressible { Description matchLabeledStatement(LabeledStatementTree tree, VisitorState state); } public interface LambdaExpressionTreeMatcher extends Suppressible { Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state); } public interface LiteralTreeMatcher extends Suppressible { Description matchLiteral(LiteralTree tree, VisitorState state); } public interface MemberReferenceTreeMatcher extends Suppressible { Description matchMemberReference(MemberReferenceTree tree, VisitorState state); } public interface MemberSelectTreeMatcher extends Suppressible { Description matchMemberSelect(MemberSelectTree tree, VisitorState state); } public interface MethodTreeMatcher extends Suppressible { Description matchMethod(MethodTree tree, VisitorState state); } public interface MethodInvocationTreeMatcher extends Suppressible { Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state); } public interface ModifiersTreeMatcher extends Suppressible { Description matchModifiers(ModifiersTree tree, VisitorState state); } public interface NewArrayTreeMatcher extends Suppressible { Description matchNewArray(NewArrayTree tree, VisitorState state); } public interface NewClassTreeMatcher extends Suppressible { Description matchNewClass(NewClassTree tree, VisitorState state); } // Intentionally skip OtherTreeMatcher. It seems to be used only for let expressions, which are // generated by javac to implement autoboxing. We are only interested in source-level constructs. public interface ParameterizedTypeTreeMatcher extends Suppressible { Description matchParameterizedType(ParameterizedTypeTree tree, VisitorState state); } public interface ParenthesizedTreeMatcher extends Suppressible { Description matchParenthesized(ParenthesizedTree tree, VisitorState state); } public interface PrimitiveTypeTreeMatcher extends Suppressible { Description matchPrimitiveType(PrimitiveTypeTree tree, VisitorState state); } public interface ReturnTreeMatcher extends Suppressible { Description matchReturn(ReturnTree tree, VisitorState state); } public interface SwitchTreeMatcher extends Suppressible { Description matchSwitch(SwitchTree tree, VisitorState state); } public interface SynchronizedTreeMatcher extends Suppressible { Description matchSynchronized(SynchronizedTree tree, VisitorState state); } public interface ThrowTreeMatcher extends Suppressible { Description matchThrow(ThrowTree tree, VisitorState state); } public interface TryTreeMatcher extends Suppressible { Description matchTry(TryTree tree, VisitorState state); } public interface TypeCastTreeMatcher extends Suppressible { Description matchTypeCast(TypeCastTree tree, VisitorState state); } public interface TypeParameterTreeMatcher extends Suppressible { Description matchTypeParameter(TypeParameterTree tree, VisitorState state); } public interface UnaryTreeMatcher extends Suppressible { Description matchUnary(UnaryTree tree, VisitorState state); } public interface UnionTypeTreeMatcher extends Suppressible { Description matchUnionType(UnionTypeTree tree, VisitorState state); } public interface VariableTreeMatcher extends Suppressible { Description matchVariable(VariableTree tree, VisitorState state); } public interface WhileLoopTreeMatcher extends Suppressible { Description matchWhileLoop(WhileLoopTree tree, VisitorState state); } public interface WildcardTreeMatcher extends Suppressible { Description matchWildcard(WildcardTree tree, VisitorState state); } @Override public boolean equals(Object obj) { if (!(obj instanceof BugChecker)) { return false; } BugChecker that = (BugChecker) obj; return this.canonicalName().equals(that.canonicalName()) && this.defaultSeverity().equals(that.defaultSeverity()) && this.supportsSuppressWarnings() == that.supportsSuppressWarnings() && this.customSuppressionAnnotations().equals(that.customSuppressionAnnotations()); } @Override public int hashCode() { return Objects.hash( canonicalName(), defaultSeverity(), supportsSuppressWarnings(), customSuppressionAnnotations()); } /** * A {@link TreePathScanner} which skips trees which are suppressed for this check. * * @param <R> the type returned by each scanner method * @param <P> the type of the parameter passed to each scanner method */ protected class SuppressibleTreePathScanner<R, P> extends TreePathScanner<R, P> { protected final VisitorState state; public SuppressibleTreePathScanner(VisitorState state) { this.state = state; } @Override public R scan(Tree tree, P param) { return suppressed(tree) ? null : super.scan(tree, param); } @Override public R scan(TreePath treePath, P param) { return suppressed(treePath.getLeaf()) ? null : super.scan(treePath, param); } private boolean suppressed(Tree tree) { boolean isSuppressible = tree instanceof ClassTree || tree instanceof MethodTree || tree instanceof VariableTree; return isSuppressible && isSuppressed(tree, state); } } }
21,072
35.022222
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/FileSource.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import java.io.IOException; /** * @author sjnickerson@google.com (Simon Nickerson) */ public interface FileSource { SourceFile readFile(String path) throws IOException; }
822
28.392857
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/IdeaImportOrganizer.java
/* * Copyright 2018 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; /** * Organizes imports based on the default format provided by IntelliJ IDEA. * * <p>This groups the imports into three groups, each delimited by a newline: * * <ol> * <li>Non-static, non-{@code java.*}, non-{@code javax.*} imports. * <li>{@code javax.*} and {@code java.*} imports, with {@code javax.*} imports ordered first. * <li>Static imports. * </ol> */ public class IdeaImportOrganizer implements ImportOrganizer { private static final String JAVA_PREFIX = "java."; private static final String JAVAX_PREFIX = "javax."; @Override public OrganizedImports organizeImports(List<Import> imports) { Map<PackageType, ImmutableSortedSet<Import>> partitioned = imports.stream() .collect( Collectors.groupingBy( IdeaImportOrganizer::getPackageType, TreeMap::new, toImmutableSortedSet(IdeaImportOrganizer::compareImport))); return new OrganizedImports() .addGroups( partitioned, ImmutableList.of(PackageType.NON_STATIC, PackageType.JAVAX_JAVA, PackageType.STATIC)); } private static int compareImport(Import a, Import b) { if (a.isStatic() || b.isStatic()) { return a.getType().compareTo(b.getType()); } else if (a.getType().startsWith(JAVA_PREFIX) && b.getType().startsWith(JAVAX_PREFIX)) { return 1; } else if (a.getType().startsWith(JAVAX_PREFIX) && b.getType().startsWith(JAVA_PREFIX)) { return -1; } else { return a.getType().compareTo(b.getType()); } } private static PackageType getPackageType(Import anImport) { if (anImport.isStatic()) { return PackageType.STATIC; } else if (anImport.getType().startsWith(JAVA_PREFIX)) { return PackageType.JAVAX_JAVA; } else if (anImport.getType().startsWith(JAVAX_PREFIX)) { return PackageType.JAVAX_JAVA; } else { return PackageType.NON_STATIC; } } private enum PackageType { JAVAX_JAVA, NON_STATIC, STATIC } }
2,973
31.681319
98
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/DiscardingFileDestination.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import java.util.logging.Logger; /** File destination which simply throws away the generated file. */ public class DiscardingFileDestination implements FileDestination { private static final Logger log = Logger.getLogger(DiscardingFileDestination.class.toString()); @Override public void writeFile(SourceFile file) { log.info(String.format("Altered file %s thrown away", file.getPath())); } @Override public void flush() {} }
1,091
31.117647
97
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/DiffNotApplicableException.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; /** Exception thrown if a {@link Diff} could not be applied by a {@link DiffApplier} */ public class DiffNotApplicableException extends RuntimeException { public DiffNotApplicableException(String msg) { super(msg); } public DiffNotApplicableException(String msg, Throwable cause) { super(msg, cause); } public DiffNotApplicableException(Throwable cause) { super(cause); } }
1,045
30.69697
87
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/BasicImportOrganizer.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * Sorts imports according to a supplied {@link StaticOrder} and separates static and non-static * with a blank line. */ class BasicImportOrganizer implements ImportOrganizer { private final StaticOrder order; BasicImportOrganizer(StaticOrder order) { this.order = order; } @Override public OrganizedImports organizeImports(List<Import> imports) { // Group into static and non-static. Each group is a set sorted by type. Map<Boolean, ImmutableSortedSet<Import>> partionedByStatic = imports.stream() .collect( Collectors.partitioningBy( Import::isStatic, toImmutableSortedSet(Comparator.comparing(Import::getType)))); return new OrganizedImports() // Add groups, in the appropriate order. .addGroups(partionedByStatic, order.groupOrder()); } }
1,744
31.924528
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/PatchFileDestination.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import static java.nio.charset.StandardCharsets.UTF_8; import com.github.difflib.DiffUtils; import com.github.difflib.UnifiedDiffUtils; import com.github.difflib.algorithm.DiffException; import com.github.difflib.patch.Patch; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import java.io.IOException; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.TreeMap; /** * A {@link FileDestination} that writes a unix-patch file to {@code rootPath} containing the * suggested changes. */ public final class PatchFileDestination implements FileDestination { // TODO(glorioso): This won't work for Windows, although getting unix patch on Windows is // a bit funky. private static final Splitter LINE_SPLITTER = Splitter.on('\n'); private final Path baseDir; private final Path rootPath; // Path -> Unified Diff, sorted by path private final Map<URI, String> diffByFile = new TreeMap<>(); public PatchFileDestination(Path baseDir, Path rootPath) { this.baseDir = baseDir; this.rootPath = rootPath; } @Override public void writeFile(SourceFile update) throws IOException { Path sourceFilePath = rootPath.resolve(update.getPath()); String oldSource = new String(Files.readAllBytes(sourceFilePath), UTF_8); String newSource = update.getSourceText(); if (!oldSource.equals(newSource)) { List<String> originalLines = LINE_SPLITTER.splitToList(oldSource); Patch<String> diff = null; try { diff = DiffUtils.diff(originalLines, LINE_SPLITTER.splitToList(newSource)); } catch (DiffException e) { throw new AssertionError("DiffUtils.diff should not fail", e); } String relativePath = baseDir.relativize(sourceFilePath).toString(); List<String> unifiedDiff = UnifiedDiffUtils.generateUnifiedDiff(relativePath, relativePath, originalLines, diff, 2); String diffString = Joiner.on("\n").join(unifiedDiff) + "\n"; diffByFile.put(sourceFilePath.toUri(), diffString); } } public String patchFile(URI uri) { return diffByFile.remove(uri); } @Override public void flush() throws IOException {} }
2,890
33.416667
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/FileDestination.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import java.io.IOException; /** * @author sjnickerson@google.com (Simon Nickerson) */ public interface FileDestination { void writeFile(SourceFile file) throws IOException; void flush() throws IOException; }
862
27.766667
75
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/ImportOrganizer.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.List; import java.util.Map; /** Organizes import statements when patching files. */ public interface ImportOrganizer { /** * Organize the imports supplied, e.g. insert blank lines between various groups. * * @param imports the imports to organize, the order is undefined. * @return the list of organized imports. */ OrganizedImports organizeImports(List<Import> imports); /** * An {@link ImportOrganizer} that sorts import statements according to the Google Java Style * Guide, i.e. static first, static and non-static separated by blank line. */ ImportOrganizer STATIC_FIRST_ORGANIZER = new BasicImportOrganizer(StaticOrder.STATIC_FIRST); /** * An {@link ImportOrganizer} that sorts import statements so that non-static imports come first, * and static and non-static separated by blank line. */ ImportOrganizer STATIC_LAST_ORGANIZER = new BasicImportOrganizer(StaticOrder.STATIC_LAST); /** * An {@link ImportOrganizer} that sorts import statements according to Android Code Style, with * static imports first. * * <p>The imports are partitioned into groups in two steps, each step sub-partitions all groups * from the previous step. The steps are: * * <ol> * <li>Split into static and non-static, the static imports come before the non static imports. * <li>The groups are then partitioned based on a prefix of the type, the groups are ordered by * prefix as follows: * <ol> * <li>{@code android.} * <li>{@code com.android.} * <li>A group for each root package, in alphabetical order. * <li>{@code java.} * <li>{@code javax.} * </ol> * </ol> */ ImportOrganizer ANDROID_STATIC_FIRST_ORGANIZER = new AndroidImportOrganizer(StaticOrder.STATIC_FIRST); /** * An {@link ImportOrganizer} that sorts import statements according to Android Code Style, with * static imports last. * * <p>The imports are partitioned into groups in two steps, each step sub-partitions all groups * from the previous step. The steps are: * * <ol> * <li>Split into static and non-static, the static imports come after the non static imports. * <li>The groups are then partitioned based on a prefix of the type, the groups are ordered by * prefix as follows: * <ol> * <li>{@code android.} * <li>{@code com.android.} * <li>A group for each root package, in alphabetical order. * <li>{@code java.} * <li>{@code javax.} * </ol> * </ol> */ ImportOrganizer ANDROID_STATIC_LAST_ORGANIZER = new AndroidImportOrganizer(StaticOrder.STATIC_LAST); /** * An {@link ImportOrganizer} that organizes imports based on the default format provided by * IntelliJ IDEA. * * <p>This groups the imports into three groups, each delimited by a newline: * * <ol> * <li>Non-static, non-{@code java.*}, non-{@code javax.*} imports. * <li>{@code javax.*} and {@code java.*} imports, with {@code javax.*} imports ordered first. * <li>Static imports. * </ol> */ ImportOrganizer IDEA_ORGANIZER = new IdeaImportOrganizer(); /** Represents an import. */ @AutoValue abstract class Import { /** True if the import is static, false otherwise. */ public abstract boolean isStatic(); /** Return the type to import. */ public abstract String getType(); /** * Create an {@link Import} * * @param importString in the format {@code import( static)? <type>}. * @return the newly created {@link Import} */ static Import importOf(String importString) { boolean isStatic = (importString.startsWith("import static ")); String type = isStatic ? importString.substring("import static ".length()) : importString.substring("import ".length()); return new AutoValue_ImportOrganizer_Import(isStatic, type); } @Override public final String toString() { return String.format("import%s %s", isStatic() ? " static" : "", getType()); } } /** * Provides support for building a list of imports from groups and formatting it as a block of * imports. */ class OrganizedImports { private final StringBuilder importBlock = new StringBuilder(); private int importCount; /** * Add a group of already sorted imports. * * <p>If there are any other imports in the list then this will add a newline separator before * this group is added. * * @param imports the imports in the group. */ private void addGroup(Collection<Import> imports) { if (imports.isEmpty()) { return; } if (importBlock.length() != 0) { importBlock.append('\n'); } importCount += imports.size(); imports.forEach(i -> importBlock.append(i).append(";\n")); } /** * Get the organized imports as a block of imports, with blank links between the separate * groups. */ public String asImportBlock() { return importBlock.toString(); } /** * Add groups of already sorted imports. * * <p>If there are any other imports in the list then this will add a newline separator before * any groups are added. It will also add a newline separate between each group. * * @param groups the imports in the group. * @param keys the keys to add, in order, if a key is not in the groups then it is ignored. * @return this for chaining. */ @CanIgnoreReturnValue public <K> OrganizedImports addGroups( Map<K, ? extends Collection<Import>> groups, Iterable<K> keys) { for (K key : keys) { Collection<Import> imports = groups.get(key); if (imports != null) { addGroup(imports); } } return this; } /** The number of imports added, excludes blank lines. */ int getImportCount() { return importCount; } } }
6,836
32.35122
99
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/ImportStatements.java
/* * Copyright 2012 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import com.google.common.base.CharMatcher; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.JCTree.JCImport; import java.util.Collection; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * Represents a list of import statements. Supports adding and removing import statements and pretty * printing the result as source code. Sorts and organizes the imports using the given {@code * importOrganizer}. * * @author eaftan@google.com (Eddie Aftandilian) */ public class ImportStatements { private final ImportOrganizer importOrganizer; private int startPos = Integer.MAX_VALUE; private int endPos = -1; private final Set<String> importStrings; private final boolean hasExistingImports; /** A copy of the original imports, used to check for any actual changes to the imports. */ private final ImmutableSet<String> originalImports; public static ImportStatements create(JCCompilationUnit compilationUnit) { return create(compilationUnit, ImportOrganizer.STATIC_FIRST_ORGANIZER); } public static ImportStatements create( JCCompilationUnit compilationUnit, ImportOrganizer importOrganizer) { return new ImportStatements( (JCExpression) compilationUnit.getPackageName(), compilationUnit.getImports(), compilationUnit.endPositions, importOrganizer); } ImportStatements( JCExpression packageTree, List<JCImport> importTrees, EndPosTable endPositions, ImportOrganizer importOrganizer) { // find start, end positions for current list of imports (for replacement) if (importTrees.isEmpty()) { // start/end positions are just after the package expression hasExistingImports = false; startPos = packageTree != null ? packageTree.getEndPosition(endPositions) + 2 // +2 for semicolon and newline : 0; endPos = startPos; } else { // process list of imports and find start/end positions hasExistingImports = true; for (JCImport importTree : importTrees) { int currStartPos = importTree.getStartPosition(); int currEndPos = importTree.getEndPosition(endPositions); startPos = Math.min(startPos, currStartPos); endPos = Math.max(endPos, currEndPos); } } // validate start/end positions Preconditions.checkState(startPos <= endPos); this.importOrganizer = importOrganizer; // convert list of JCImports to set of unique strings importStrings = new LinkedHashSet<>(); importStrings.addAll( Lists.transform( importTrees, new Function<JCImport, String>() { @Override public String apply(JCImport input) { String importExpr = input.toString(); return CharMatcher.whitespace() .or(CharMatcher.is(';')) .trimTrailingFrom(importExpr); } })); originalImports = ImmutableSet.copyOf(importStrings); } /** Return the start position of the import statements. */ public int getStartPos() { return startPos; } /** Return the end position of the import statements. */ public int getEndPos() { return endPos; } /** * Add an import to the list of imports. If the import is already in the list, does nothing. The * import should be of the form "import foo.bar". * * @param importToAdd a string representation of the import to add * @return true if the import was added */ public boolean add(String importToAdd) { return importStrings.add(importToAdd); } /** * Add all imports in a collection to this list of imports. Does not add any imports that are * already in the list. * * @param importsToAdd a collection of imports to add * @return true if any imports were added to the list */ public boolean addAll(Collection<String> importsToAdd) { return importStrings.addAll(importsToAdd); } /** * Remove an import from the list of imports. If the import is not in the list, does nothing. The * import should be of the form "import foo.bar". * * @param importToRemove a string representation of the import to remove * @return true if the import was removed */ public boolean remove(String importToRemove) { return importStrings.remove(importToRemove); } /** * Removes all imports in a collection to this list of imports. Does not remove any imports that * are not in the list. * * @param importsToRemove a collection of imports to remove * @return true if any imports were removed from the list */ public boolean removeAll(Collection<String> importsToRemove) { return importStrings.removeAll(importsToRemove); } public boolean importsHaveChanged() { return !importStrings.equals(originalImports); } /** Returns a string representation of the imports as Java code in correct order. */ @Override public String toString() { if (importStrings.isEmpty()) { return ""; } StringBuilder result = new StringBuilder(); if (!hasExistingImports) { // insert a newline after the package expression, then add imports result.append('\n'); } List<ImportOrganizer.Import> imports = importStrings.stream().map(ImportOrganizer.Import::importOf).collect(Collectors.toList()); // Organize the imports. ImportOrganizer.OrganizedImports organizedImports = importOrganizer.organizeImports(imports); // Make sure that every import was organized. int expectedImportCount = imports.size(); int importCount = organizedImports.getImportCount(); if (importCount != expectedImportCount) { throw new IllegalStateException( String.format( "Expected %d import(s) in the organized imports but it contained %d", expectedImportCount, importCount)); } // output organized imports result.append(organizedImports.asImportBlock()); String replacementString = result.toString(); if (!hasExistingImports) { return replacementString; } else { return CharMatcher.whitespace().trimTrailingFrom(replacementString); // trim last newline } } }
7,227
32.775701
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/Diff.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; /** * All the differences to be applied to a source file to be applied in a refactoring. * * @author sjnickerson@google.com (Simon Nickerson) */ public interface Diff { /** Gets the name of the file this difference applies to */ String getRelevantFileName(); /** * Applies this difference to the supplied {@code sourceFile}. * * @throws DiffNotApplicableException if the diff could not be applied to the source file */ void applyDifferences(SourceFile sourceFile); }
1,137
31.514286
91
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/DiffSupplier.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import java.io.IOException; import javax.annotation.Nullable; /** * Supplier of file differences. * * <p>This can be a data source (e.g. an already computed diff file) or it can produce diffs on the * fly by reading files from a {@link FileSource} and processing each one by one. * * @author sjnickerson@google.com (Simon Nickerson) */ public interface DiffSupplier { /** * Gets the list of differences * * @param fileSource the source of source files * @param fileNames an optional list of filenames to restrict to. If null, there is no restriction * on file names. This will make more sense for some diff suppliers than others.) * @return the diffs * @throws IOException if there is an I/O problem while generating the diffs */ Iterable<Diff> getDiffs(FileSource fileSource, @Nullable String[] fileNames) throws IOException; }
1,515
34.255814
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/SourceFile.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.io.CharSource; import com.google.errorprone.fixes.Replacement; import com.google.errorprone.fixes.Replacements; import java.io.IOException; import java.io.LineNumberReader; import java.io.StringReader; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.List; import javax.tools.JavaFileObject; /** * Representation of a mutable Java source file. * * <p>This class is not thread-safe. * * @author sjnickerson@google.com (Simon Nickerson) * @author alexeagle@google.com (Alex Eagle) */ public class SourceFile { private final String path; private final StringBuilder sourceBuilder; public static SourceFile create(JavaFileObject fileObject) throws IOException { return new SourceFile(fileObject.toUri().getPath(), fileObject.getCharContent(false)); } public SourceFile(String path, CharSequence source) { this.path = path; sourceBuilder = new StringBuilder(source); } /** Returns the path for this source file */ public String getPath() { return path; } /** Returns a copy of code as a list of lines. */ public List<String> getLines() { try { return CharSource.wrap(sourceBuilder).readLines(); } catch (IOException e) { throw new AssertionError("IOException not possible, as the string is in-memory", e); } } /** Returns a copy of the code as a string. */ public String getSourceText() { return sourceBuilder.toString(); } public CharSequence getAsSequence() { return CharBuffer.wrap(sourceBuilder).asReadOnlyBuffer(); } /** Clears the current source test for this SourceFile and resets it to the passed-in value. */ public void setSourceText(CharSequence source) { sourceBuilder.setLength(0); // clear StringBuilder sourceBuilder.append(source); } /** * Returns a fragment of the source code as a string. * * <p>This method uses the same conventions as {@link String#substring(int, int)} for its start * and end parameters. */ public String getFragmentByChars(int startPosition, int endPosition) { return sourceBuilder.substring(startPosition, endPosition); } /** * Returns a fragment of the source code between the two stated line numbers. The parameters * represent <b>inclusive</b> line numbers. * * <p>The returned fragment will end in a newline. */ public String getFragmentByLines(int startLine, int endLine) { Preconditions.checkArgument(startLine <= endLine); return Joiner.on("\n").join(getLines(startLine, endLine)) + "\n"; } private List<String> getLines(int startLine, int endLine) { LineNumberReader reader = new LineNumberReader(new StringReader(sourceBuilder.toString())); List<String> lines = new ArrayList<>(endLine - startLine + 1); String line; try { while ((line = reader.readLine()) != null) { if (reader.getLineNumber() >= startLine) { lines.add(line); } if (reader.getLineNumber() >= endLine) { break; } } return lines; } catch (IOException e) { throw new AssertionError("Wrapped StringReader should not produce I/O exceptions", e); } } /** Replace the source code with the new lines of code. */ public void replaceLines(List<String> lines) { sourceBuilder.replace(0, sourceBuilder.length(), Joiner.on("\n").join(lines) + "\n"); } /** Replace the source code between the start and end lines with some new lines of code. */ public void replaceLines(int startLine, int endLine, List<String> replacementLines) { Preconditions.checkArgument(startLine <= endLine); List<String> originalLines = getLines(); List<String> newLines = new ArrayList<>(); for (int i = 0; i < originalLines.size(); i++) { int lineNum = i + 1; if (lineNum == startLine) { newLines.addAll(replacementLines); } else if (lineNum > startLine && lineNum <= endLine) { // Skip } else { newLines.add(originalLines.get(i)); } } replaceLines(newLines); } /** * Replace the source code between the start and end character positions with a new string. * * <p>This method uses the same conventions as {@link String#substring(int, int)} for its start * and end parameters. */ public void replaceChars(int startPosition, int endPosition, String replacement) { try { sourceBuilder.replace(startPosition, endPosition, replacement); } catch (StringIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException( String.format( "Replacement cannot be made. Source file %s has length %d, requested start " + "position %d, requested end position %d, replacement %s", path, sourceBuilder.length(), startPosition, endPosition, replacement)); } } void makeReplacements(Replacements changes) { ImmutableSet<Replacement> replacements = changes.ascending(); switch (replacements.size()) { case 0: return; case 1: { Replacement onlyReplacement = Iterables.getOnlyElement(replacements); replaceChars( onlyReplacement.startPosition(), onlyReplacement.endPosition(), onlyReplacement.replaceWith()); return; } default: break; } // Since we have many replacements to make all at once, it's better to start off with a clean // slate, rather than make multiple separate replacements which each require shifting around // the tail of our sourceBuilder. If we do them all at once, we can work forward from the // beginning of the tile, so that each new replacement does not affect any previous // replacements. StringBuilder newContent = new StringBuilder(); int positionInOriginal = 0; for (Replacement repl : replacements) { checkArgument( repl.endPosition() <= sourceBuilder.length(), "End [%s] should not exceed source length [%s]", repl.endPosition(), sourceBuilder.length()); // Write the unmodified content leading up to this change newContent.append(sourceBuilder, positionInOriginal, repl.startPosition()); // And the modified content for this change newContent.append(repl.replaceWith()); // Then skip everything from source between start and end positionInOriginal = repl.endPosition(); } // Flush out any remaining content after the final change newContent.append(sourceBuilder, positionInOriginal, sourceBuilder.length()); // Overwrite the contents of our old buffer. Note we mutate the existing StringBuilder rather // than replacing it, because other clients may have a view of the content via getAsSequence, // and we want that view to reflect the new content. setSourceText(newContent); } }
7,755
35.074419
97
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/FsFileDestination.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; /** A {@link FileDestination} that writes content to a destination on the local filesystem. */ public final class FsFileDestination implements FileDestination { private final Path rootPath; public FsFileDestination(Path rootPath) { this.rootPath = rootPath; } @Override public void writeFile(SourceFile update) throws IOException { Path targetPath = rootPath.resolve(update.getPath()); Files.write(targetPath, update.getSourceText().getBytes(StandardCharsets.UTF_8)); } @Override public void flush() throws IOException {} }
1,329
30.666667
94
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/FsFileSource.java
/* * Copyright 2016 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; /** A FileSource that reads source files from the local filesystem. */ public final class FsFileSource implements FileSource { private final Path rootPath; public FsFileSource(Path rootPath) { this.rootPath = rootPath; } @Override public SourceFile readFile(String path) throws IOException { return new SourceFile( path, new String(Files.readAllBytes(rootPath.resolve(path)), StandardCharsets.UTF_8)); } }
1,210
30.051282
94
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/StaticOrder.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import com.google.common.collect.ImmutableList; /** The different ways to order static imports. */ enum StaticOrder { /** * Sorts import statements so that all static imports come before all non-static imports and * otherwise sorted alphabetically. */ STATIC_FIRST(ImmutableList.of(Boolean.TRUE, Boolean.FALSE)), /** * Sorts import statements so that all static imports come after all non-static imports and * otherwise sorted alphabetically. */ STATIC_LAST(ImmutableList.of(Boolean.FALSE, Boolean.TRUE)); private final ImmutableList<Boolean> groupOrder; StaticOrder(ImmutableList<Boolean> groupOrder) { this.groupOrder = groupOrder; } public ImmutableList<Boolean> groupOrder() { return groupOrder; } }
1,399
30.818182
94
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/DescriptionBasedDiff.java
/* * Copyright 2014 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import static com.google.common.base.Preconditions.checkNotNull; import com.google.errorprone.DescriptionListener; import com.google.errorprone.fixes.Fix; import com.google.errorprone.fixes.Replacement; import com.google.errorprone.fixes.Replacements; import com.google.errorprone.matchers.Description; import com.sun.tools.javac.tree.EndPosTable; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; import java.net.URI; import java.nio.file.Paths; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; /** * Implementation of a {@link Diff} that performs the modifications that are passed to its {@link * #onDescribed} method, with no formatting. * * <p>If imports are changed, they are resorted as per Google Java style. * * @author lowasser@google.com (Louis Wasserman) */ public final class DescriptionBasedDiff implements DescriptionListener, Diff { private final String sourcePath; private final boolean ignoreOverlappingFixes; private final JCCompilationUnit compilationUnit; private final Set<String> importsToAdd; private final Set<String> importsToRemove; private final EndPosTable endPositions; private final Replacements replacements = new Replacements(); private final ImportOrganizer importOrganizer; public static DescriptionBasedDiff create( JCCompilationUnit compilationUnit, ImportOrganizer importOrganizer) { return new DescriptionBasedDiff(compilationUnit, false, importOrganizer); } public static DescriptionBasedDiff createIgnoringOverlaps( JCCompilationUnit compilationUnit, ImportOrganizer importOrganizer) { return new DescriptionBasedDiff(compilationUnit, true, importOrganizer); } private DescriptionBasedDiff( JCCompilationUnit compilationUnit, boolean ignoreOverlappingFixes, ImportOrganizer importOrganizer) { this.compilationUnit = checkNotNull(compilationUnit); URI sourceFileUri = compilationUnit.getSourceFile().toUri(); this.sourcePath = (sourceFileUri.isAbsolute() && Objects.equals(sourceFileUri.getScheme(), "file")) ? Paths.get(sourceFileUri).toAbsolutePath().toString() : sourceFileUri.getPath(); this.ignoreOverlappingFixes = ignoreOverlappingFixes; this.importsToAdd = new LinkedHashSet<>(); this.importsToRemove = new LinkedHashSet<>(); this.endPositions = compilationUnit.endPositions; this.importOrganizer = importOrganizer; } @Override public String getRelevantFileName() { return sourcePath; } public boolean isEmpty() { return importsToAdd.isEmpty() && importsToRemove.isEmpty() && replacements.isEmpty(); } @Override public void onDescribed(Description description) { // Use only first (most likely) suggested fix if (description.fixes.size() > 0) { handleFix(description.fixes.get(0)); } } public void handleFix(Fix fix) { importsToAdd.addAll(fix.getImportsToAdd()); importsToRemove.addAll(fix.getImportsToRemove()); for (Replacement replacement : fix.getReplacements(endPositions)) { try { replacements.add(replacement, Replacements.CoalescePolicy.EXISTING_FIRST); } catch (IllegalArgumentException iae) { if (!ignoreOverlappingFixes) { throw iae; } } } } @Override public void applyDifferences(SourceFile sourceFile) throws DiffNotApplicableException { if (!importsToAdd.isEmpty() || !importsToRemove.isEmpty()) { ImportStatements importStatements = ImportStatements.create(compilationUnit, importOrganizer); importStatements.addAll(importsToAdd); importStatements.removeAll(importsToRemove); if (importStatements.importsHaveChanged()) { replacements.add( Replacement.create( importStatements.getStartPos(), importStatements.getEndPos(), importStatements.toString()), Replacements.CoalescePolicy.REPLACEMENT_FIRST); } } sourceFile.makeReplacements(replacements); } }
4,686
35.333333
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/AndroidImportOrganizer.java
/* * Copyright 2017 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.errorprone.apply; import static com.google.common.collect.ImmutableSortedSet.toImmutableSortedSet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; /** * Organizes imports based on Android Code Style * * <p>As the style rules do not specify where static imports are placed this supports first or last. * * <p>The imports are partitioned into groups in two steps, each step sub-partitions all groups from * the previous step. The steps are: * * <ol> * <li>Split into static and non-static, the static imports come before or after the non static * imports depending on the {@link StaticOrder} specified. * <li>The groups are then partitioned based on a prefix of the type, the groups are ordered by * prefix as follows: * <ol> * <li>{@code android.} * <li>{@code com.android.} * <li>A group for each root package, in alphabetical order. * <li>{@code java.} * <li>{@code javax.} * </ol> * </ol> * * <p>Each group is separate from the previous/next groups with a blank line. */ class AndroidImportOrganizer implements ImportOrganizer { private static final String ANDROID = "android"; private static final String COM_ANDROID = "com.android"; private static final String JAVA = "java"; private static final String JAVAX = "javax"; private static final ImmutableSet<String> SPECIAL_ROOTS = ImmutableSet.of(ANDROID, COM_ANDROID, JAVA, JAVAX); private final StaticOrder order; AndroidImportOrganizer(StaticOrder order) { this.order = order; } @Override public OrganizedImports organizeImports(List<Import> imports) { OrganizedImports organized = new OrganizedImports(); // Group into static and non-static. Map<Boolean, List<Import>> partionedByStatic = imports.stream().collect(Collectors.partitioningBy(Import::isStatic)); for (Boolean key : order.groupOrder()) { organizePartition(organized, partionedByStatic.get(key)); } return organized; } private static void organizePartition(OrganizedImports organized, List<Import> imports) { Map<String, ImmutableSortedSet<Import>> groupedByRoot = imports.stream() .collect( Collectors.groupingBy( // Group by root package. AndroidImportOrganizer::rootPackage, // Ensure that the results are sorted. TreeMap::new, // Each group is a set sorted by type. toImmutableSortedSet(Comparator.comparing(Import::getType)))); // Get the third party roots by removing the roots that are handled specially and sorting. ImmutableSortedSet<String> thirdParty = groupedByRoot.keySet().stream() .filter(r -> !SPECIAL_ROOTS.contains(r)) .collect(toImmutableSortedSet(Ordering.natural())); // Construct a list of the possible roots in the correct order. ImmutableList<String> roots = ImmutableList.<String>builder() .add(ANDROID) .add(COM_ANDROID) .addAll(thirdParty) .add(JAVA) .add(JAVAX) .build(); organized.addGroups(groupedByRoot, roots); } private static String rootPackage(Import anImport) { String type = anImport.getType(); if (type.startsWith("com.android.")) { return "com.android"; } int index = type.indexOf('.'); if (index == -1) { // Treat the default package as if it has an empty root. return ""; } else { return type.substring(0, index); } } }
4,520
32.242647
100
java
error-prone
error-prone-master/check_api/src/main/java/com/google/errorprone/apply/DiffApplier.java
/* * Copyright 2011 The Error Prone Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.errorprone.apply; import com.google.common.base.Preconditions; import com.google.common.base.Stopwatch; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import com.google.common.util.concurrent.AbstractService; import java.io.IOException; import java.util.Set; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ConcurrentSkipListSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /** * Applier of diffs to Java source code * * @author alexeagle@google.com (Alex Eagle) * @author sjnickerson@google.com (Simon Nickerson) */ public class DiffApplier extends AbstractService { private static final Logger logger = Logger.getLogger(DiffApplier.class.getName()); private final ExecutorService workerService; private final Set<String> refactoredPaths; private final Set<String> diffsFailedPaths; private final FileSource source; private final FileDestination destination; private final AtomicInteger completedFiles; private final Stopwatch stopwatch; // the number of diffs in flight, plus 1 if the service is in the RUNNING state private final AtomicInteger runState = new AtomicInteger(); public DiffApplier(int diffParallelism, FileSource source, FileDestination destination) { Preconditions.checkNotNull(source); Preconditions.checkNotNull(destination); this.diffsFailedPaths = new ConcurrentSkipListSet<>(); this.refactoredPaths = Sets.newConcurrentHashSet(); this.source = source; this.destination = destination; this.completedFiles = new AtomicInteger(0); this.stopwatch = Stopwatch.createUnstarted(); // configure a bounded queue and a rejectedexecutionpolicy. // In this case CallerRuns may be appropriate. this.workerService = new ThreadPoolExecutor( 0, diffParallelism, 5, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(50), new ThreadPoolExecutor.CallerRunsPolicy()); } @Override protected void doStart() { stopwatch.start(); runState.incrementAndGet(); notifyStarted(); } @Override protected void doStop() { decrementTasks(); // matches the increment in doStart(); } private final void decrementTasks() { if (runState.decrementAndGet() == 0) { workerService.shutdown(); try { destination.flush(); notifyStopped(); } catch (Exception e) { notifyFailed(e); } logger.log( Level.INFO, String.format("Completed %d files in %s", completedFiles.get(), stopwatch)); if (!diffsFailedPaths.isEmpty()) { logger.log( Level.SEVERE, String.format( "Diffs failed to apply to %d files: %s", diffsFailedPaths.size(), Iterables.limit(diffsFailedPaths, 30))); } } } private final class Task implements Runnable { private final Diff diff; Task(Diff diff) { this.diff = diff; } @Override public void run() { try { SourceFile file = source.readFile(diff.getRelevantFileName()); diff.applyDifferences(file); destination.writeFile(file); int completed = completedFiles.incrementAndGet(); if (completed % 100 == 0) { logger.log(Level.INFO, String.format("Completed %d files in %s", completed, stopwatch)); } } catch (IOException | DiffNotApplicableException e) { logger.log(Level.WARNING, "Failed to apply diff to file " + diff.getRelevantFileName(), e); diffsFailedPaths.add(diff.getRelevantFileName()); } finally { decrementTasks(); } } } @Nullable public Future<?> put(Diff diff) { if (refactoredPaths.add(diff.getRelevantFileName())) { runState.incrementAndGet(); return workerService.submit(new Task(diff)); } return null; } }
4,781
32.208333
100
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/ReaderIteratorTest.java
package org.infinispan.cli; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.StringReader; import java.util.Map; import org.infinispan.cli.util.JsonReaderIterator; import org.junit.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ReaderIteratorTest { @Test public void testUnstructuredJSONIterator() throws IOException { String json = "[\"person2.proto\",\"person.proto\"]"; StringReader r = new StringReader(json); JsonReaderIterator iterator = new JsonReaderIterator(r); assertTrue(iterator.hasNext()); assertEquals("person2.proto", iterator.next().values().iterator().next()); assertTrue(iterator.hasNext()); assertEquals("person.proto", iterator.next().values().iterator().next()); } @Test public void testStructuredJSONIterator() throws IOException { String json = "[{\"key\":\n" + "{\n" + " \"_type\": \"string\",\n" + " \"_value\": \"k1\"\n" + "}\n" + ",\"value\":\n" + "{\n" + " \"_type\": \"string\",\n" + " \"_value\": \"v1\"\n" + "}\n" + ",\"timeToLiveSeconds\": 12000, \"maxIdleTimeSeconds\": 12000, \"created\": 1655871119343, \"lastUsed\": 1655871119343, \"expireTime\": 1655883119343}," + "{\"key\":\n" + "{\n" + " \"_type\": \"string\",\n" + " \"_value\": \"k2\"\n" + "}\n" + ",\"value\":\n" + "{\n" + " \"_type\": \"string\",\n" + " \"_value\": \"v2\"\n" + "}\n" + ",\"timeToLiveSeconds\": 12000, \"maxIdleTimeSeconds\": 12000, \"created\": 1655871119343, \"lastUsed\": 1655871119343, \"expireTime\": 1655883119343}," + "]"; StringReader r = new StringReader(json); JsonReaderIterator iterator = new JsonReaderIterator(r); assertTrue(iterator.hasNext()); Map<String, String> row = iterator.next(); assertEquals("k1", row.get("key")); assertEquals("v1", row.get("value")); assertEquals("12000", row.get("timeToLiveSeconds")); assertEquals("12000", row.get("maxIdleTimeSeconds")); assertEquals("1655871119343", row.get("created")); assertEquals("1655871119343", row.get("lastUsed")); assertEquals("1655883119343", row.get("expireTime")); assertTrue(iterator.hasNext()); row = iterator.next(); assertEquals("k2", row.get("key")); assertEquals("v2", row.get("value")); assertEquals("12000", row.get("timeToLiveSeconds")); assertEquals("12000", row.get("maxIdleTimeSeconds")); assertEquals("1655871119343", row.get("created")); assertEquals("1655871119343", row.get("lastUsed")); assertEquals("1655883119343", row.get("expireTime")); } }
2,957
36.923077
166
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/AeshTestShell.java
package org.infinispan.cli; import java.util.concurrent.TimeUnit; import org.aesh.command.shell.Shell; import org.aesh.readline.Prompt; import org.aesh.readline.terminal.Key; import org.aesh.readline.util.Parser; import org.aesh.terminal.tty.Size; import org.aesh.terminal.utils.Config; import org.infinispan.commons.test.Eventually; import org.junit.ComparisonFailure; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 15.0 **/ public class AeshTestShell implements Shell { private final StringBuilder bufferBuilder = new StringBuilder(); @Override public void write(String msg, boolean paging) { bufferBuilder.append(msg); } @Override public void writeln(String msg, boolean paging) { bufferBuilder.append(msg).append(Config.getLineSeparator()); } @Override public void write(int[] out) { bufferBuilder.append(Parser.fromCodePoints(out)); } @Override public void write(char out) { bufferBuilder.append(out); } @Override public String readLine() { return null; } @Override public String readLine(Prompt prompt) { return null; } @Override public Key read() throws InterruptedException { return null; } @Override public Key read(Prompt prompt) throws InterruptedException { return null; } @Override public boolean enableAlternateBuffer() { return false; } @Override public boolean enableMainBuffer() { return false; } @Override public Size size() { return null; } @Override public void clear() { bufferBuilder.setLength(0); } public String getBuffer() { return bufferBuilder.toString(); } public void assertEquals(String expected) { Eventually.eventually( () -> new ComparisonFailure("Expected output was not equal to expected string after timeout", expected, bufferBuilder.toString()), () -> expected.contentEquals(bufferBuilder), 10_000, 50, TimeUnit.MILLISECONDS); } public void assertContains(String expected) { Eventually.eventually( () -> new ComparisonFailure("Expected output did not contain expected string after timeout", expected, bufferBuilder.toString()), () -> bufferBuilder.toString().contains(expected), 10_000, 50, TimeUnit.MILLISECONDS); } }
2,368
23.173469
142
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/CliPipeTest.java
package org.infinispan.cli; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.Properties; import java.util.concurrent.TimeUnit; import org.infinispan.cli.commands.CLI; import org.infinispan.cli.impl.StreamShell; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.test.Eventually; import org.infinispan.commons.util.Util; import org.junit.ComparisonFailure; import org.junit.Test; /** * @since 14.0 **/ public class CliPipeTest { @Test public void testCliBatchPipe() throws IOException, InterruptedException { File workingDir = new File(CommonsTestingUtil.tmpDirectory(CliPipeTest.class)); Util.recursiveFileRemove(workingDir); workingDir.mkdirs(); Properties properties = new Properties(System.getProperties()); properties.put("cli.dir", workingDir.getAbsolutePath()); PipedOutputStream pipe = new PipedOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamShell shell = new StreamShell(new PipedInputStream(pipe), new PrintStream(out)); Thread thread = new Thread(() -> CLI.main(shell, new String[]{"-f", "-"}, properties)); thread.start(); PrintWriter pw = new PrintWriter(pipe, true); pw.println("echo Piped"); Eventually.eventually( () -> new ComparisonFailure("Expected output was not equal to expected string after timeout", "Piped", out.toString(StandardCharsets.UTF_8)), () -> out.toString(StandardCharsets.UTF_8).startsWith("Piped"), 10_000, 50, TimeUnit.MILLISECONDS); pw.close(); thread.join(); } }
1,817
36.875
153
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/user/UserToolTest.java
package org.infinispan.cli.user; import static org.infinispan.commons.test.CommonsTestingUtil.tmpDirectory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.util.Arrays; import java.util.Collections; import java.util.Properties; import org.infinispan.commons.util.Util; import org.junit.Before; import org.junit.Test; import org.wildfly.common.iteration.CodePointIterator; import org.wildfly.security.credential.PasswordCredential; import org.wildfly.security.evidence.PasswordGuessEvidence; import org.wildfly.security.password.PasswordFactory; import org.wildfly.security.password.WildFlyElytronPasswordProvider; import org.wildfly.security.password.spec.BasicPasswordSpecEncoding; import org.wildfly.security.password.spec.PasswordSpec; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class UserToolTest { private static String tmpDirectory; private static File serverDirectory; private static File confDirectory; @Before public void createTestDirectory() { tmpDirectory = tmpDirectory(UserToolTest.class); Util.recursiveFileRemove(tmpDirectory); serverDirectory = new File(tmpDirectory, UserTool.DEFAULT_SERVER_ROOT); confDirectory = new File(serverDirectory, "conf"); confDirectory.mkdirs(); } private static Properties loadProperties(String filename) throws IOException { Properties users = new Properties(); try (FileReader r = new FileReader(new File(confDirectory, filename))) { users.load(r); return users; } } @Test public void testUserToolClearText() throws IOException { UserTool userTool = new UserTool(serverDirectory.getAbsolutePath()); userTool.createUser("user", "password", UserTool.DEFAULT_REALM_NAME, UserTool.Encryption.CLEAR, Collections.singletonList("admin"), null); Properties users = loadProperties("users.properties"); assertEquals(1, users.size()); assertEquals("password", users.getProperty("user")); Properties groups = loadProperties("groups.properties"); assertEquals(1, groups.size()); assertEquals("admin", groups.getProperty("user")); } @Test public void testUserToolEncrypted() throws Exception { UserTool userTool = new UserTool(serverDirectory.getAbsolutePath()); userTool.createUser("user", "password", UserTool.DEFAULT_REALM_NAME, UserTool.Encryption.ENCRYPTED, Collections.singletonList("admin"), null); Properties users = loadProperties("users.properties"); assertEquals(1, users.size()); assertPassword("password", users.getProperty("user")); Properties groups = loadProperties("groups.properties"); assertEquals(1, groups.size()); assertEquals("admin", groups.getProperty("user")); } @Test public void userManipulation() throws Exception { UserTool userTool = new UserTool(serverDirectory.getAbsolutePath()); userTool.createUser("user", "password", UserTool.DEFAULT_REALM_NAME, UserTool.Encryption.ENCRYPTED, Arrays.asList("admin", "other"), null); userTool.reload(); assertEquals("{ username: \"user\", realm: \"default\", groups = [admin, other] }", userTool.describeUser("user")); assertEquals(Collections.singletonList("user"), userTool.listUsers()); assertEquals(Arrays.asList("admin", "other"), userTool.listGroups()); userTool.modifyUser("user", null, null, UserTool.Encryption.DEFAULT, Arrays.asList("admin", "other", "else"), null); assertEquals("{ username: \"user\", realm: \"default\", groups = [admin, other, else] }", userTool.describeUser("user")); assertEquals(Arrays.asList("admin", "else", "other"), userTool.listGroups()); userTool.removeUser("user"); assertTrue(userTool.listUsers().isEmpty()); assertTrue(userTool.listGroups().isEmpty()); } @Test public void reEncrypt() throws Exception { UserTool userTool = new UserTool(serverDirectory.getAbsolutePath()); userTool.createUser("user1", "password1", UserTool.DEFAULT_REALM_NAME, UserTool.Encryption.CLEAR, Arrays.asList("admin", "other"), null); userTool.createUser("user2", "password2", UserTool.DEFAULT_REALM_NAME, UserTool.Encryption.CLEAR, Arrays.asList("yetanother", "something"), null); Properties users = loadProperties("users.properties"); assertEquals(2, users.size()); assertEquals("password1", users.getProperty("user1")); assertEquals("password2", users.getProperty("user2")); userTool.reload(); userTool.encryptAll(null); userTool.reload(); users = loadProperties("users.properties"); assertEquals(2, users.size()); assertPassword("password1", users.getProperty("user1")); assertPassword("password2", users.getProperty("user2")); } private void assertPassword(String clear, String encrypted) throws NoSuchAlgorithmException, InvalidKeySpecException { PasswordGuessEvidence evidence = new PasswordGuessEvidence(clear.toCharArray()); String[] split = encrypted.split(";"); for (int i = 0; i < split.length; i++) { int colon = split[i].indexOf(':'); String algorithm = split[i].substring(0, colon); String encoded = split[i].substring(colon + 1); byte[] passwordBytes = CodePointIterator.ofChars(encoded.toCharArray()).base64Decode().drain(); PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm, WildFlyElytronPasswordProvider.getInstance()); PasswordSpec passwordSpec = BasicPasswordSpecEncoding.decode(passwordBytes); PasswordCredential credential = new PasswordCredential(passwordFactory.generatePassword(passwordSpec)); assertTrue("Passwords don't match", credential.verify(UserTool.PROVIDERS, evidence)); } } }
6,020
46.785714
152
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/commands/kubernetes/KubeTest.java
package org.infinispan.cli.commands.kubernetes; import static org.junit.Assert.assertEquals; import java.util.Collections; import java.util.Map; import org.junit.Test; import io.fabric8.kubernetes.api.model.Secret; /** * @since 15.0 **/ public class KubeTest { @Test public void testKubeSecrets() { Secret secret = new Secret(); secret.setData(Collections.singletonMap("identities.yaml", "Y3JlZGVudGlhbHM6Ci0gdXNlcm5hbWU6IGFkbWluCiAgcGFzc3dvcmQ6IHBhc3N3b3JkCgo=")); Map<String, String> map = Kube.decodeOpaqueSecrets(secret); assertEquals(1, map.size()); Map.Entry<String, String> next = map.entrySet().iterator().next(); assertEquals("admin", next.getKey()); assertEquals("password", next.getValue()); } }
766
26.392857
142
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/connection/rest/RestConnectorTest.java
package org.infinispan.cli.connection.rest; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.infinispan.cli.util.ZeroSecurityTrustManager; import org.infinispan.client.rest.configuration.RestClientConfiguration; import org.infinispan.client.rest.configuration.RestClientConfigurationBuilder; import org.junit.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class RestConnectorTest { @Test public void testUrlWithCredentials() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("http://user:password@localhost:11222", null); RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(11222, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertTrue(configuration.security().authentication().enabled()); assertEquals("user", configuration.security().authentication().username()); assertArrayEquals("password".toCharArray(), configuration.security().authentication().password()); } @Test public void testUrlWithoutCredentials() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("http://localhost:11222", null); RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(11222, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertFalse(configuration.security().authentication().enabled()); } @Test public void testUrlWithoutPort() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("http://localhost", null); RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(80, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertFalse(configuration.security().authentication().enabled()); } @Test public void testUrlWithSSL() throws NoSuchAlgorithmException { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("https://localhost", null); RestClientConfigurationBuilder builder = connection.getBuilder(); builder.security().ssl().sslContext(SSLContext.getDefault()).trustManagers(new TrustManager[]{new ZeroSecurityTrustManager()}); RestClientConfiguration configuration = builder.build(); assertEquals(443, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); assertFalse(configuration.security().authentication().enabled()); assertTrue(configuration.security().ssl().enabled()); } @Test public void testEmptyUrl() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("", null); RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(11222, configuration.servers().get(0).port()); assertEquals("localhost", configuration.servers().get(0).host()); } @Test public void testPlainHostPort() { RestConnector connector = new RestConnector(); RestConnection connection = (RestConnection) connector.getConnection("my.host.com:12345", null); RestClientConfigurationBuilder builder = connection.getBuilder(); RestClientConfiguration configuration = builder.build(); assertEquals(12345, configuration.servers().get(0).port()); assertEquals("my.host.com", configuration.servers().get(0).host()); } }
4,292
45.16129
133
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/printers/TablePrettyPrinterTest.java
package org.infinispan.cli.printers; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import org.infinispan.cli.AeshTestShell; import org.infinispan.cli.util.JsonReaderIterable; import org.junit.Test; /** * @since 15.0 **/ public class TablePrettyPrinterTest { public static final int WIDTH = 120; public static final int COLUMNS = 7; @Test public void testTableWrapping() throws IOException { CacheEntryRowPrinter rowPrinter = new CacheEntryRowPrinter(WIDTH, COLUMNS); AeshTestShell shell = new AeshTestShell(); TablePrettyPrinter t = new TablePrettyPrinter(shell, rowPrinter); try (InputStream is = TablePrettyPrinter.class.getResourceAsStream("/printers/entries.json")) { Iterator<Map<String, String>> it = new JsonReaderIterable(is).iterator(); t.printItem(it.next()); checkRow(rowPrinter, shell.getBuffer(), 17); shell.clear(); t.printItem(it.next()); checkRow(rowPrinter, shell.getBuffer(), 15); } } private static void checkRow(CacheEntryRowPrinter rowPrinter, String row, int numLines) { String[] lines = row.split("\n"); // Ensure we have the right number of lines assertEquals(numLines, lines.length); for (String line : lines) { // Ensure the lines fit the width assertEquals(WIDTH, line.length()); int pos = -1; char separator = line.startsWith("---") ? '+' : '|'; // Ensure the column separators are in the right place for (int i = 0; i < COLUMNS - 1; i++) { pos += rowPrinter.columnWidth(i) + 1; assertEquals(line + ":" + pos, separator, line.charAt(pos)); } } } }
1,813
31.392857
101
java
null
infinispan-main/cli/src/test/java/org/infinispan/cli/patching/PatchToolTest.java
package org.infinispan.cli.patching; import static org.infinispan.cli.util.Utils.sha256; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.net.URI; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.Properties; import org.infinispan.commons.test.CommonsTestingUtil; import org.infinispan.commons.test.Exceptions; import org.infinispan.commons.util.Util; import org.junit.Test; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ public class PatchToolTest { @Test public void testPatchToolCreate() throws IOException { Path tmp = Paths.get(CommonsTestingUtil.tmpDirectory(PatchToolTest.class)); Util.recursiveFileRemove(tmp.toFile()); Files.createDirectories(tmp); Util.recursiveDirectoryCopy(new File("target/test-classes/patch").toPath(), tmp); // Create the infinispan-commons jars that identify a server's version Path v1 = tmp.resolve("v1"); createFakeInfinispanCommons(v1, "Infinispan", "1.0.0.Final"); Path v2 = tmp.resolve("v2"); createFakeInfinispanCommons(v2, "Infinispan", "1.0.1.Final"); Path v3 = tmp.resolve("v3"); createFakeInfinispanCommons(v3, "Infinispan", "1.1.0.Final"); ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream err = new ByteArrayOutputStream(); PatchTool patchTool = new PatchTool(new PrintStream(out), new PrintStream(err)); // List the installed patches on v1 patchTool.listPatches(v1, false); assertContains(out, "No patches installed"); assertEmpty(err); out.reset(); // Create a patch zip that can patch v1 and v2 to v3 Path patch = Paths.get("target/patch.zip"); patch.toFile().delete(); patchTool.createPatch("", patch, v3, v1, v2); assertContains(out, "Adding "); assertEmpty(err); out.reset(); // Attempting to create the patch file again should fail Exceptions.expectException(FileAlreadyExistsException.class, () -> patchTool.createPatch("", patch, v3, v1, v2)); // Ensure the zip file does not contain the .patches directory IGNOREME.txt files try (FileSystem zipfs = FileSystems.newFileSystem(URI.create("jar:" + patch.toUri().toString()), Collections.emptyMap())) { Path root = zipfs.getRootDirectories().iterator().next(); Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { assertNotEquals("/.patches", dir.toString()); return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { assertNotEquals("IGNOREME.txt", file.getFileName().toString()); return FileVisitResult.CONTINUE; } }); } // Describe the patches installed in the zip patchTool.describePatch(patch, false); assertContains(out, "Infinispan patch target=1.1.0.Final source=1.0.1.Final"); assertContains(out, "Infinispan patch target=1.1.0.Final source=1.0.0.Final"); assertEmpty(err); out.reset(); // Install the patch on v1 patchTool.installPatch(patch, v1, false); assertContains(out, "Infinispan patch target=1.1.0.Final source=1.0.0.Final"); assertEmpty(err); out.reset(); // List the patches installed on v1 patchTool.listPatches(v1, false); assertContains(out, "Infinispan patch target=1.1.0.Final source=1.0.0.Final"); assertEmpty(err); out.reset(); // Install the patch on v2 patchTool.installPatch(patch, v2, false); assertContains(out, "Infinispan patch target=1.1.0.Final source=1.0.1.Final"); assertEmpty(err); out.reset(); // List the patches installed on v2 patchTool.listPatches(v2, false); assertContains(out, "Infinispan patch target=1.1.0.Final source=1.0.1.Final"); assertEmpty(err); out.reset(); // Rollback v1 patchTool.rollbackPatch(v1, false); assertContains(out, "Rolled back patch Infinispan patch target=1.1.0.Final source=1.0.0.Final"); assertEmpty(err); out.reset(); // List the patches installed on v1 patchTool.listPatches(v1, false); assertContains(out, "No patches installed"); assertEmpty(err); out.reset(); // Alter a configuration file on v1 Path v1config = v1.resolve("server").resolve("conf").resolve("infinispan.xml"); try(BufferedWriter w = new BufferedWriter(new FileWriter(v1config.toFile(), true))) { w.newLine(); w.write("<!-- Some modification -->"); } String v1sha256 = sha256(v1config); // Install the patch on v1 patchTool.installPatch(patch, v1, false); assertContains(out, "Infinispan patch target=1.1.0.Final source=1.0.0.Final"); assertEmpty(err); out.reset(); // Ensure that the file has not been replaced assertEquals("Expecting SHA-256 of " + v1config +" to stay the same", v1sha256, sha256(v1config)); // And that there is a new file next to it assertTrue(v1.resolve("server").resolve("conf").resolve("infinispan.xml-1.1.0.Final").toFile().exists()); } private void assertContains(ByteArrayOutputStream out, String contains) { String s = out.toString(); assertTrue(s.contains(contains)); } private void assertEmpty(ByteArrayOutputStream out) { assertEquals("", out.toString()); } private void createFakeInfinispanCommons(Path base, String brandName, String version) throws IOException { Path jar = base.resolve("lib").resolve("infinispan-commons-" + version + ".jar"); Files.createDirectories(jar.getParent()); URI jarUri = URI.create("jar:" + jar.toUri().toString()); try (FileSystem zipfs = FileSystems.newFileSystem(jarUri, Collections.singletonMap("create", "true"))) { Path propsPath = zipfs.getPath("META-INF", "infinispan-version.properties"); Files.createDirectories(propsPath.getParent()); OutputStream os = Files.newOutputStream(propsPath, StandardOpenOption.CREATE); Properties properties = new Properties(); properties.put("infinispan.version", version); properties.put("infinispan.brand.name", brandName); properties.store(os, null); os.close(); } } }
7,174
38.20765
130
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/Context.java
package org.infinispan.cli; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.registry.CommandRegistry; import org.aesh.command.shell.Shell; import org.aesh.readline.AeshContext; import org.aesh.readline.ReadlineConsole; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.SSLContextSettings; import org.infinispan.cli.resources.Resource; import org.infinispan.commons.dataconversion.MediaType; /** * Context. * * @author Tristan Tarrant * @since 5.2 */ public interface Context extends AeshContext { Path getConfigPath(); boolean isConnected(); void setProperty(String key, String value); String getProperty(String key); String getProperty(Property property); Properties getProperties(); void resetProperties(); void saveProperties(); void setSslContext(SSLContextSettings sslContext); /** * Connects to a server * * @param shell * @param connectionString * @return */ Connection connect(Shell shell, String connectionString); /** * Connect to a server using the supplied username and password * * @param shell * @param connectionString * @param username * @param password * @return */ Connection connect(Shell shell, String connectionString, String username, String password); void setRegistry(CommandRegistry<? extends CommandInvocation> registry); /** * Returns the current {@link Connection} * * @return */ Connection getConnection(); /** * Disconnects from the server */ void disconnect(); void setConsole(ReadlineConsole console); CommandRegistry<? extends CommandInvocation> getRegistry(); MediaType getEncoding(); void setEncoding(MediaType encoding); void refreshPrompt(); CommandResult changeResource(Class<? extends Resource> fromResource, String resourceType, String name) throws CommandException; enum Property { TRUSTALL, TRUSTSTORE, TRUSTSTORE_PASSWORD, KEYSTORE, KEYSTORE_PASSWORD, PROVIDER, AUTOCONNECT_URL, AUTOEXEC; public static final List<String> NAMES; static { Property[] values = values(); final List<String> names = new ArrayList<>(values.length); for (Property element : values) { names.add(element.propertyName()); } NAMES = names; } public String propertyName() { return name().toLowerCase().replace('_', '-'); } } }
2,723
22.282051
130
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/logging/Messages.java
package org.infinispan.cli.logging; import java.io.IOException; import java.net.ConnectException; import java.nio.file.AccessDeniedException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.NoSuchElementException; import org.aesh.command.CommandException; import org.aesh.command.parser.RequiredOptionException; import org.infinispan.cli.patching.PatchInfo; import org.infinispan.cli.patching.PatchOperation; import org.infinispan.cli.resources.Resource; import org.infinispan.cli.user.UserTool; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; /** * @since 10.0 */ @MessageBundle(projectCode = "ISPN") public interface Messages { Messages MSG = org.jboss.logging.Messages.getBundle(Messages.class); Logger CLI = Logger.getLogger("CLI"); @Message(value = "Username: ") String username(); @Message(value = "Password: ") String password(); @Message("Not Found: %s") IOException notFound(String s); @Message("The supplied credentials are invalid %s") AccessDeniedException unauthorized(String s); @Message("Error: %s") IOException error(String s); @Message("The user is not allowed to access the server resource: %s") AccessDeniedException forbidden(String s); @Message("Error while configuring SSL") String keyStoreError(@Cause Exception e); @Message("No such resource '%s'") IllegalArgumentException noSuchResource(String name); @Message("Command invoked from the wrong context") IllegalStateException illegalContext(); @Message("Illegal arguments for command") IllegalArgumentException illegalCommandArguments(); @Message("The options '%s' and '%s' are mutually exclusive") IllegalArgumentException mutuallyExclusiveOptions(String arg1, String arg2); @Message("One of the '%s' and '%s' options are required") RequiredOptionException requiresOneOf(String arg1, String arg2); @Message("Could not connect to server: %s") ConnectException connectionFailed(String message); @Message("Invalid resource '%s'") IllegalArgumentException invalidResource(String name); @Message("No patches installed") String patchNoPatchesInstalled(); @Message("%s") String patchInfo(PatchInfo patchInfo); @Message("The supplied patch cannot be applied to %s %s") IllegalStateException patchCannotApply(String brandName, String version); @Message("File %s SHA mismatch. Expected = %s, Actual = %s") String patchShaMismatch(Path path, String digest, String sha256); @Message("The following errors were encountered while validating the installation:%n%s") IllegalStateException patchValidationErrors(String errors); @Message("No installed patches to roll back") IllegalStateException patchNoPatchesInstalledToRollback(); @Message("Cannot find the infinispan-commons jar under %s") IllegalStateException patchCannotFindCommons(Path lib); @Message("Cannot create patch %s with patches for %s") IllegalStateException patchIncompatibleProduct(String localBrand, String patchBrand); @Message("Could not write patches file") IllegalStateException patchCannotWritePatchesFile(@Cause IOException e); @Message("Rolled back patch %s") String patchRollback(PatchInfo patchInfo); @Message("[Dry run] ") String patchDryRun(); @Message("Backing up '%s' to '%s'") String patchBackup(Path from, Path to); @Message("Error while creating patch") RuntimeException patchCreateError(@Cause IOException e); @Message("Adding file '%s'") String patchCreateAdd(Path target); @Message("Rolling back file '%s'") String patchRollbackFile(Path file); @Message("Could not read %s") IllegalStateException patchCannotRead(Path patchesFile, @Cause IOException e); @Message("File '%s' already exists") FileAlreadyExistsException patchFileAlreadyExists(Path patch); @Message("At least three arguments are required: the patch file, the target server path and one or more source server paths") IllegalArgumentException patchCreateArgumentsRequired(); @Message("You must specify the path to a patch archive") IllegalArgumentException patchArchiveArgumentRequired(); @Message("Cannot create a patch from identical source and target server versions: %s") IllegalArgumentException patchServerAndTargetMustBeDifferent(String version); @Message("The patch archive appears to have a corrupt entry for: %s") String patchCorruptArchive(PatchOperation operation); @Message("Downloaded file '%s'") String downloadedFile(String filename); @Message(value = "Specify a username: ") String userToolUsername(); @Message(value = "Set a password for the user: ") String userToolPassword(); @Message(value = "Confirm the password for the user: ") String userToolPasswordConfirm(); @Message(value = "User `%s` already exists") IllegalStateException userToolUserExists(String username); @Message("Error accessing file '%s'") RuntimeException userToolIOError(Path path, @Cause IOException e); @Message("Unkown password encryption algorithm: '%s'") IllegalArgumentException userToolUnknownAlgorithm(String algorithm); @Message(value = "User `%s` does not exist") IllegalArgumentException userToolNoSuchUser(String username); @Message(value = "{ username: \"%s\", realm: \"%s\", groups = %s }") String userDescribe(String username, String realm, String[] userGroups); @Message(value = "Invalid Unicode sequence '%s'") IOException invalidUnicodeSequence(String sequence, @Cause NoSuchElementException e); @Message(value = "Attempt to use %s passwords, but only %s passwords are allowed") IllegalArgumentException userToolIncompatibleEncrypyion(UserTool.Encryption encryption1, UserTool.Encryption encryption2); @Message(value = "Attempted to use a different realm '%s' than the already existing one '%s'") IllegalArgumentException userToolWrongRealm(String realm1, String realm2); @Message(value = "Unable to load CLI configuration from `%s`. Using defaults.") String configLoadFailed(String path); @Message(value = "Unable to store CLI configuration to '%s'.") String configStoreFailed(String path); @Message(value = "Wrong argument count: %d.") IllegalArgumentException wrongArgumentCount(int size); @Message("Cannot find service '%s' in namespace '%s'") IllegalArgumentException noSuchService(String serviceName, String namespace); @Message("Cannot find or access generated secrets for service '%s'") IllegalStateException noGeneratedSecret(String serviceName); @Message("A namespace was not specified and a default has not been set") IllegalStateException noDefaultNamespace(); @Message(value = "Enter the password for the credential keystore: ") String credentialToolPassword(); @Message(value = "Confirm the password for the credential store: ") String credentialToolPasswordConfirm(); @Message(value = "Set a credential for the alias: ") String credentialToolCredential(); @Message(value = "Confirm the credential: ") String credentialToolCredentialConfirm(); @Message(value = "Filter rule '%s' is not in the format [ACCEPT|REJECT]/{CIDR}") IllegalArgumentException illegalFilterRule(String rule); @Message(value = "Error executing file: %s, line %d: '%s'") CommandException batchError(String file, int lineNumber, String line, @Cause Throwable t); @Message("Option '%s' requires option '%s'") RequiredOptionException requiresAllOf(String option1, String option2); @Message("The cache name is required") IllegalArgumentException missingCacheName(); @Message("Could not determine catalog source") IllegalStateException noCatalog(); @Message("Target namespaces must be specified when not installing globally") IllegalArgumentException noTargetNamespaces(); @Message("Could not find a default operator namespace") IllegalStateException noDefaultOperatorNamespace(); @Message("Kubernetes client is unavailable in this mode") IllegalStateException noKubernetes(); @Message("Could not find an operator subscription in namespace '%s'") IllegalStateException noOperatorSubscription(String namespace); @Message("Expose type '%s' requires a port") IllegalArgumentException exposeTypeRequiresPort(String exposeType); @Message("Encryption type '%s' requires a secret name") IllegalArgumentException encryptionTypeRequiresSecret(String encryptionType); @Message("No running pods available in service %s") IllegalStateException noRunningPodsInService(String name); @Message("A username must be specified") IllegalArgumentException usernameRequired(); @Message("Checksum for '%s' does not match. Supplied: %s Actual: %s") SecurityException checksumFailed(String path, String checksum, String computed); @Message("Checksum for '%s' verified") String checksumVerified(String path); @Message("Artifact '%s' not found") IllegalArgumentException artifactNotFound(String path); @Message("Retry download '%d/%d'") String retryDownload(int retry, int retries); @Message("The resource does not support the '%s' list format") IllegalArgumentException unsupportedListFormat(Resource.ListFormat format); @Message("Cannot reset an individual statistic") IllegalArgumentException cannotResetIndividualStat(); @Message("File '%s' does not exist") NoSuchFileException nonExistentFile(org.aesh.io.Resource file); @Message("The store migrator requires configuration properties to be set") IllegalArgumentException missingStoreMigratorProperties(); }
9,803
36.136364
128
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/JsonReaderIterable.java
package org.infinispan.cli.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.Iterator; import java.util.Map; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class JsonReaderIterable implements Iterable<Map<String, String>> { private final JsonReaderIterator iterator; public JsonReaderIterable(InputStream is) throws IOException { this(new InputStreamReader(is)); } public JsonReaderIterable(Reader r) throws IOException { this.iterator = new JsonReaderIterator(r); } @Override public Iterator<Map<String, String>> iterator() { return iterator; } }
724
22.387097
74
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/TransformingIterator.java
package org.infinispan.cli.util; import java.util.Iterator; import java.util.function.Function; /** * @since 14.0 **/ public class TransformingIterator<S, T> implements Iterator<T> { private final Iterator<S> iterator; private final Function<S, T> transformer; public TransformingIterator(Iterator<S> iterator, Function<S, T> transformer) { this.iterator = iterator; this.transformer = transformer; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { return transformer.apply(iterator.next()); } }
603
20.571429
82
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/Utils.java
package org.infinispan.cli.util; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.security.MessageDigest; import org.infinispan.commons.util.Util; public class Utils { public static final int BUFFER_SIZE = 8192; public static String sha256(Path path) { return digest(path, "SHA-256"); } public static String digest(Path path, String algorithm) { try (ByteChannel channel = Files.newByteChannel(path, StandardOpenOption.READ)) { MessageDigest digest = MessageDigest.getInstance(algorithm); if (channel instanceof FileChannel) { FileChannel fileChannel = (FileChannel) channel; MappedByteBuffer byteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size()); digest.update(byteBuffer); } else { ByteBuffer bb = ByteBuffer.allocate(BUFFER_SIZE); while (channel.read(bb) != -1) { bb.flip(); digest.update(bb); bb.flip(); } } return Util.toHexString(digest.digest()); } catch (NoSuchFileException e) { return null; } catch (Exception e) { throw new RuntimeException(e); } } }
1,460
31.466667
112
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/ReaderIterator.java
package org.infinispan.cli.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReaderIterator implements Iterator<String>, AutoCloseable { private final BufferedReader reader; private String line; private boolean eof = false; private final Pattern regex; private Matcher matcher; public ReaderIterator(InputStream inputStream, Pattern regex) { Objects.requireNonNull(inputStream); this.reader = new BufferedReader(new InputStreamReader(inputStream)); this.regex = regex; } @Override public boolean hasNext() { if (eof) { return false; } else if (line != null) { return true; } else { try { while (true) { if (regex == null) { // Normal mode String l = reader.readLine(); if (l == null) { close(); return false; } else { line = l; return true; } } else { // Matching mode if (matcher == null) { String l = reader.readLine(); if (l == null) { close(); return false; } matcher = regex.matcher(l); } if (matcher.find()) { line = matcher.group(1); return true; } else { // Force a new line read matcher = null; } } } } catch (IOException e) { close(); throw new IllegalStateException(e); } } } @Override public String next() { if (!hasNext()) { throw new NoSuchElementException(); } String currentLine = line; line = null; return currentLine; } @Override public void close() { try { reader.close(); } catch (IOException e) { // Ignore errors on close } eof = true; line = null; } @Override public void remove() { throw new UnsupportedOperationException(); } }
2,537
24.897959
75
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/TransformingIterable.java
package org.infinispan.cli.util; import java.util.Iterator; import java.util.Map; import java.util.function.Function; /** * @since 14.0 **/ public class TransformingIterable<S, T> implements Iterable<T> { public static Function<Map<String, String>, String> SINGLETON_MAP_VALUE = m -> m.values().iterator().next(); private final Iterable<S> iterable; private final Function<S, T> transformer; public TransformingIterable(Iterable<S> iterable, Function<S, T> transformer) { this.iterable = iterable; this.transformer = transformer; } @Override public Iterator<T> iterator() { return new TransformingIterator<>(iterable.iterator(), transformer); } }
697
24.851852
111
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/JsonReaderIterator.java
package org.infinispan.cli.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; public class JsonReaderIterator implements Iterator<Map<String, String>>, AutoCloseable { private final JsonParser parser; private Map<String, String> row; private boolean eof = false; public JsonReaderIterator(Reader reader) throws IllegalArgumentException, IOException { Objects.requireNonNull(reader); JsonFactory jsonFactory = new JsonFactory(); this.parser = jsonFactory.createParser((reader instanceof BufferedReader) ? reader : new BufferedReader(reader)); } @Override public boolean hasNext() { if (eof) { return false; } else if (row != null) { return true; } else { try { while (true) { JsonToken token = parser.nextToken(); if (token == null) { close(); return false; } else if (token == JsonToken.START_OBJECT) { // List of objects int depth = 0; row = new LinkedHashMap<>(); String key = ""; while (true) { token = parser.nextToken(); if (token == JsonToken.END_OBJECT) { if (depth == 0) { return true; } else { depth--; } } else if (token == JsonToken.START_OBJECT) { depth++; } else if (token == JsonToken.FIELD_NAME) { String name = parser.currentName(); token = parser.nextToken(); if (token == JsonToken.START_OBJECT) { key = name; depth++; } else { String value = parser.getText(); switch (name) { case "_value": row.put(key, value); break; case "_type": break; default: key = name; if (value != null) { row.put(key, value); } } } } } } else if (token == JsonToken.VALUE_STRING) { // List of bare values row = Map.of("", parser.getValueAsString()); return true; } } } catch (IOException e) { close(); throw new IllegalStateException(e); } } } @Override public Map<String, String> next() { if (!hasNext()) { throw new NoSuchElementException(); } Map<String, String> currentRow = row; row = null; return currentRow; } @Override public void close() { try { parser.close(); } catch (IOException e) { // Ignore errors on close } eof = true; row = null; } @Override public void remove() { throw new UnsupportedOperationException(); } }
3,709
30.982759
119
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/SystemUtils.java
package org.infinispan.cli.util; import java.nio.file.Path; import java.nio.file.Paths; /** * SystemUtils. * * @author Tristan Tarrant * @since 5.2 */ public class SystemUtils { /** * Returns an appropriate system-dependent folder for storing application-specific data. The logic in this method * uses the os.name to decide which is best. Currently it uses: ~/.config/${appName} on Unix/Linux (as per * Freedesktop.org) %APPDATA%/Sun/Java/${appName} on Windows ~/Library/Java/${appName} on Mac OS X * * @param appName * @return */ public static String getAppConfigFolder(String appName) { Path configRoot = null; String osName = System.getProperty("os.name"); if ("Mac OS X".equals(osName)) { configRoot = Paths.get(System.getProperty("user.home"), "Library", "Java"); } else if (osName.startsWith("Windows")) { // If on Windows, use the APPDATA environment try { String appData = System.getenv("APPDATA"); if (appData != null) { configRoot = Paths.get(appData).resolve("Sun").resolve("Java"); } } catch (SecurityException e) { // We may be wrapped by a SecurityManager, ignore the exception } } if (configRoot == null) { // Use the user.home configRoot = Paths.get(System.getProperty("user.home"), ".config"); } return configRoot.resolve(appName).toString(); } }
1,483
31.977778
116
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/ZeroSecurityHostnameVerifier.java
package org.infinispan.cli.util; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLSession; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ZeroSecurityHostnameVerifier implements HostnameVerifier { @Override public boolean verify(String hostname, SSLSession session) { return true; } }
364
21.8125
71
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/ZeroSecurityTrustManager.java
package org.infinispan.cli.util; import java.net.Socket; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLEngine; import javax.net.ssl.X509ExtendedTrustManager; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class ZeroSecurityTrustManager extends X509ExtendedTrustManager { @Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }
1,314
25.836735
123
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/util/aesh/graal/NativeMetadataProvider.java
package org.infinispan.cli.util.aesh.graal; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.aesh.command.Command; import org.aesh.command.container.CommandContainer; import org.aesh.command.container.CommandContainerBuilder; import org.aesh.command.impl.container.AeshCommandContainerBuilder; import org.aesh.command.impl.internal.ProcessedCommand; import org.aesh.command.impl.internal.ProcessedOption; import org.aesh.command.impl.parser.CommandLineParser; import org.aesh.command.invocation.CommandInvocation; import org.infinispan.commons.graalvm.ReflectiveClass; public class NativeMetadataProvider implements org.infinispan.commons.graalvm.NativeMetadataProvider { final List<ReflectiveClass> classes = new ArrayList<>(); public NativeMetadataProvider() { loadCommand(org.infinispan.cli.commands.Batch.class); loadCommand(org.infinispan.cli.commands.CLI.class); loadCommand(org.infinispan.cli.commands.kubernetes.Kube.class); classes.addAll(List.of( ReflectiveClass.of(org.infinispan.cli.impl.ExitCodeResultHandler.class), ReflectiveClass.of(org.infinispan.cli.logging.Messages_$bundle.class), ReflectiveClass.of(org.infinispan.commons.logging.Log_$logger.class), ReflectiveClass.of(org.aesh.command.impl.parser.AeshOptionParser.class), ReflectiveClass.of(org.apache.logging.log4j.core.impl.Log4jContextFactory.class), ReflectiveClass.of(org.apache.logging.log4j.core.util.ExecutorServices.class), ReflectiveClass.of(org.apache.logging.log4j.message.ParameterizedMessageFactory.class), ReflectiveClass.of(org.apache.logging.log4j.message.DefaultFlowMessageFactory.class), ReflectiveClass.of(org.wildfly.security.password.impl.PasswordFactorySpiImpl.class) )); } @Override public Stream<ReflectiveClass> reflectiveClasses() { return classes.stream(); } @SuppressWarnings("unchecked") private void loadCommand(Class<?> cmd) { Class<Command<CommandInvocation<?>>> clazz = (Class<Command<CommandInvocation<?>>>) cmd; CommandContainerBuilder<CommandInvocation<?>> builder = new AeshCommandContainerBuilder<>(); try (CommandContainer<CommandInvocation<?>> container = builder.create(clazz)) { addCommandClasses(container.getParser()); } catch (Exception e) { throw new RuntimeException(e); } } private void addCommandClasses(CommandLineParser<CommandInvocation<?>> parser) { addCommandClasses(parser.getProcessedCommand()); if (parser.isGroupCommand()) { for (CommandLineParser<CommandInvocation<?>> child : parser.getAllChildParsers()) addCommandClasses(child); } } private void addCommandClasses(ProcessedCommand<Command<CommandInvocation<?>>, CommandInvocation<?>> command) { Class<?> clazz = command.getCommand().getClass(); if (command.getActivator() != null) classes.add(ReflectiveClass.of(command.getActivator().getClass())); List<ProcessedOption> allArgumentsAndOptions = new ArrayList<>(command.getOptions()); if (command.getArguments() != null) allArgumentsAndOptions.add(command.getArguments()); if (command.getArgument() != null) allArgumentsAndOptions.add(command.getArgument()); Field[] fields = new Field[allArgumentsAndOptions.size()]; for (int i = 0; i < fields.length; i++) { ProcessedOption option = allArgumentsAndOptions.get(i); try { fields[i] = getField(clazz, option.getFieldName()); } catch (NoSuchFieldException e) { throw new RuntimeException(String.format("Unable to process command '%s'", clazz.getName()), e); } if (option.completer() != null) classes.add(ReflectiveClass.of(option.completer().getClass(), false, true)); if (option.activator() != null) classes.add(ReflectiveClass.of(option.activator().getClass(), false, true)); if (option.converter() != null) classes.add(ReflectiveClass.of(option.converter().getClass(), false, true)); } classes.add( new ReflectiveClass(clazz, clazz.getDeclaredConstructors(), fields, clazz.getDeclaredMethods()) ); } Field getField(Class<?> clazz, String field) throws NoSuchFieldException { try { return clazz.getDeclaredField(field); } catch (NoSuchFieldException e) { if (clazz.getSuperclass().equals(Object.class)) throw e; return getField(clazz.getSuperclass(), field); } } }
4,699
42.119266
114
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/user/UserTool.java
package org.infinispan.cli.user; import static org.infinispan.cli.logging.Messages.MSG; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidKeySpecException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import java.util.Properties; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Supplier; import java.util.stream.Collectors; import org.infinispan.cli.logging.Messages; import org.wildfly.common.iteration.ByteIterator; import org.wildfly.common.iteration.CodePointIterator; import org.wildfly.security.password.Password; import org.wildfly.security.password.PasswordFactory; import org.wildfly.security.password.WildFlyElytronPasswordProvider; import org.wildfly.security.password.interfaces.DigestPassword; import org.wildfly.security.password.interfaces.ScramDigestPassword; import org.wildfly.security.password.spec.BasicPasswordSpecEncoding; import org.wildfly.security.password.spec.DigestPasswordAlgorithmSpec; import org.wildfly.security.password.spec.EncryptablePasswordSpec; import org.wildfly.security.password.spec.IteratedSaltedPasswordAlgorithmSpec; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ public class UserTool { public static final Supplier<Provider[]> PROVIDERS = () -> new Provider[]{WildFlyElytronPasswordProvider.getInstance()}; public static final String DEFAULT_USERS_PROPERTIES_FILE = "users.properties"; public static final String DEFAULT_GROUPS_PROPERTIES_FILE = "groups.properties"; public static final String DEFAULT_REALM_NAME = "default"; public static final String DEFAULT_SERVER_ROOT = "server"; private static final String COMMENT_PREFIX1 = "#"; private static final String COMMENT_PREFIX2 = "!"; private static final String REALM_COMMENT_PREFIX = "$REALM_NAME="; private static final String COMMENT_SUFFIX = "$"; private static final String ALGORITHM_COMMENT_PREFIX = "$ALGORITHM="; public static final List<String> DEFAULT_ALGORITHMS = Collections.unmodifiableList(Arrays.asList( ScramDigestPassword.ALGORITHM_SCRAM_SHA_1, ScramDigestPassword.ALGORITHM_SCRAM_SHA_256, ScramDigestPassword.ALGORITHM_SCRAM_SHA_384, ScramDigestPassword.ALGORITHM_SCRAM_SHA_512, DigestPassword.ALGORITHM_DIGEST_MD5, DigestPassword.ALGORITHM_DIGEST_SHA, DigestPassword.ALGORITHM_DIGEST_SHA_256, DigestPassword.ALGORITHM_DIGEST_SHA_384, DigestPassword.ALGORITHM_DIGEST_SHA_512 )); private final Path serverRoot; private final Path usersFile; private final Path groupsFile; private Properties users = new Properties(); private Properties groups = new Properties(); private String realm = null; private Encryption encryption = Encryption.DEFAULT; public UserTool(String serverRoot) { this(serverRoot, DEFAULT_USERS_PROPERTIES_FILE, DEFAULT_GROUPS_PROPERTIES_FILE); } public UserTool(String serverRoot, String usersFile, String groupsFile) { this(serverRoot != null ? Paths.get(serverRoot) : null, usersFile != null ? Paths.get(usersFile) : null, groupsFile != null ? Paths.get(groupsFile) : null); } public UserTool(Path serverRoot, Path usersFile, Path groupsFile) { if (serverRoot != null && serverRoot.isAbsolute()) { this.serverRoot = serverRoot; } else { String serverHome = System.getProperty("infinispan.server.home.path"); Path serverHomePath = serverHome == null ? Paths.get("") : Paths.get(serverHome); if (serverRoot == null) { this.serverRoot = serverHomePath.resolve("server"); } else { this.serverRoot = serverHomePath.resolve(serverRoot); } } if (usersFile == null) { this.usersFile = this.serverRoot.resolve("conf").resolve(DEFAULT_USERS_PROPERTIES_FILE); } else if (usersFile.isAbsolute()) { this.usersFile = usersFile; } else { this.usersFile = this.serverRoot.resolve("conf").resolve(usersFile); } if (groupsFile == null) { this.groupsFile = this.serverRoot.resolve("conf").resolve(DEFAULT_GROUPS_PROPERTIES_FILE); } else if (groupsFile.isAbsolute()) { this.groupsFile = groupsFile; } else { this.groupsFile = this.serverRoot.resolve("conf").resolve(groupsFile); } load(); } public void reload() { this.realm = null; this.encryption = Encryption.DEFAULT; load(); } private void load() { if (Files.exists(usersFile)) { try (BufferedReader reader = Files.newBufferedReader(usersFile, StandardCharsets.UTF_8)) { String currentLine; while ((currentLine = reader.readLine()) != null) { final String trimmed = currentLine.trim(); if (trimmed.startsWith(COMMENT_PREFIX1) && trimmed.contains(REALM_COMMENT_PREFIX)) { // this is the line that contains the realm name. int start = trimmed.indexOf(REALM_COMMENT_PREFIX) + REALM_COMMENT_PREFIX.length(); int end = trimmed.indexOf(COMMENT_SUFFIX, start); if (end > -1) { realm = trimmed.substring(start, end); } } else if (trimmed.startsWith(COMMENT_PREFIX1) && trimmed.contains(ALGORITHM_COMMENT_PREFIX)) { // this is the line that contains the algorithm name. int start = trimmed.indexOf(ALGORITHM_COMMENT_PREFIX) + ALGORITHM_COMMENT_PREFIX.length(); int end = trimmed.indexOf(COMMENT_SUFFIX, start); if (end > -1) { encryption = Encryption.valueOf(trimmed.substring(start, end).toUpperCase()); } } else { if (!(trimmed.startsWith(COMMENT_PREFIX1) || trimmed.startsWith(COMMENT_PREFIX2))) { String username = null; StringBuilder builder = new StringBuilder(); CodePointIterator it = CodePointIterator.ofString(trimmed); while (it.hasNext()) { int cp = it.next(); if (cp == '\\' && it.hasNext()) { // escape //might be regular escape of regex like characters \\t \\! or unicode \\uxxxx int marker = it.next(); if (marker != 'u') { builder.appendCodePoint(marker); } else { StringBuilder hex = new StringBuilder(); try { hex.appendCodePoint(it.next()); hex.appendCodePoint(it.next()); hex.appendCodePoint(it.next()); hex.appendCodePoint(it.next()); builder.appendCodePoint((char) Integer.parseInt(hex.toString(), 16)); } catch (NoSuchElementException nsee) { throw Messages.MSG.invalidUnicodeSequence(hex.toString(), nsee); } } } else if (username == null && (cp == '=' || cp == ':')) { // username-password delimiter username = builder.toString().trim(); builder = new StringBuilder(); } else { builder.appendCodePoint(cp); } } if (username != null) { // end of line and delimiter was read users.setProperty(username, builder.toString()); } } } } } catch (IOException e) { throw MSG.userToolIOError(usersFile, e); } } if (Files.exists(groupsFile)) { try (Reader reader = Files.newBufferedReader(groupsFile)) { groups.load(reader); } catch (IOException e) { throw MSG.userToolIOError(groupsFile, e); } } } private void store() { store(this.realm, this.encryption); } private void store(String realm, Encryption encryption) { encryption = checkEncryption(encryption); if (realm == null) { realm = this.realm; } try (Writer writer = Files.newBufferedWriter(usersFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { users.store(writer, REALM_COMMENT_PREFIX + realm + COMMENT_SUFFIX + "\n" + ALGORITHM_COMMENT_PREFIX + (encryption == Encryption.CLEAR ? "clear" : "encrypted") + COMMENT_SUFFIX); } catch (IOException e) { throw MSG.userToolIOError(usersFile, e); } try (Writer writer = Files.newBufferedWriter(groupsFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { groups.store(writer, null); } catch (IOException e) { throw MSG.userToolIOError(groupsFile, e); } } private Encryption checkEncryption(Encryption encryption) { if (encryption == Encryption.DEFAULT) { // Not forcing anything, use what the current user.properties file specifies or the default return this.encryption; } else { if (this.encryption == Encryption.DEFAULT) { // We can override the default return encryption; } else if (this.encryption == encryption) { // Compatible return encryption; } else { throw MSG.userToolIncompatibleEncrypyion(encryption, this.encryption); } } } public String checkRealm(String realm) { if (realm == null) { return this.realm == null ? DEFAULT_REALM_NAME : this.realm; } else { if (this.realm == null || this.realm.equals(realm)) { return realm; } else { throw MSG.userToolWrongRealm(realm, this.realm); } } } public void createUser(String username, String password, String realm, Encryption encryption, List<String> userGroups, List<String> algorithms) { if (users.containsKey(username)) { throw MSG.userToolUserExists(username); } realm = checkRealm(realm); users.put(username, Encryption.CLEAR.equals(encryption) ? password : encryptPassword(username, realm, password, algorithms)); groups.put(username, userGroups != null ? String.join(",", userGroups) : ""); store(realm, encryption); } public String describeUser(String username) { if (users.containsKey(username)) { String[] userGroups = groups.containsKey(username) ? groups.getProperty(username).trim().split("\\s*,\\s*") : new String[]{}; return MSG.userDescribe(username, realm, userGroups); } else { throw MSG.userToolNoSuchUser(username); } } public void removeUser(String username) { users.remove(username); groups.remove(username); store(); } public void modifyUser(String username, String password, String realm, Encryption encryption, List<String> userGroups, List<String> algorithms) { if (!users.containsKey(username)) { throw MSG.userToolNoSuchUser(username); } else { realm = checkRealm(realm); if (password != null) { // change password users.put(username, Encryption.CLEAR.equals(encryption) ? password : encryptPassword(username, realm, password, algorithms)); } if (userGroups != null) { // change groups groups.put(username, String.join(",", userGroups)); } store(realm, encryption); } } public void encryptAll(List<String> algorithms) { if (this.encryption == Encryption.CLEAR) { users.replaceAll((u, p) -> encryptPassword((String) u, realm, (String) p, algorithms)); this.encryption = Encryption.ENCRYPTED; store(realm, Encryption.ENCRYPTED); } } private String encryptPassword(String username, String realm, String password, List<String> algorithms) { try { if (algorithms == null) { algorithms = DEFAULT_ALGORITHMS; } StringBuilder sb = new StringBuilder(); for (String algorithm : algorithms) { PasswordFactory passwordFactory = PasswordFactory.getInstance(algorithm, WildFlyElytronPasswordProvider.getInstance()); AlgorithmParameterSpec spec; sb.append(algorithm); sb.append(":"); switch (algorithm) { case ScramDigestPassword.ALGORITHM_SCRAM_SHA_1: case ScramDigestPassword.ALGORITHM_SCRAM_SHA_256: case ScramDigestPassword.ALGORITHM_SCRAM_SHA_384: case ScramDigestPassword.ALGORITHM_SCRAM_SHA_512: spec = new IteratedSaltedPasswordAlgorithmSpec(ScramDigestPassword.DEFAULT_ITERATION_COUNT, salt(ScramDigestPassword.DEFAULT_SALT_SIZE)); break; case DigestPassword.ALGORITHM_DIGEST_MD5: case DigestPassword.ALGORITHM_DIGEST_SHA: case DigestPassword.ALGORITHM_DIGEST_SHA_256: case DigestPassword.ALGORITHM_DIGEST_SHA_384: case DigestPassword.ALGORITHM_DIGEST_SHA_512: spec = new DigestPasswordAlgorithmSpec(username, realm); break; default: throw MSG.userToolUnknownAlgorithm(algorithm); } Password encrypted = passwordFactory.generatePassword(new EncryptablePasswordSpec(password.toCharArray(), spec)); byte[] encoded = BasicPasswordSpecEncoding.encode(encrypted, PROVIDERS); sb.append(ByteIterator.ofBytes(encoded).base64Encode().drainToString()); sb.append(";"); } return sb.toString(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } } private static byte[] salt(int size) { byte[] salt = new byte[size]; ThreadLocalRandom.current().nextBytes(salt); return salt; } public List<String> listUsers() { List<String> userList = new ArrayList<>(users.stringPropertyNames()); Collections.sort(userList); return userList; } public List<String> listGroups() { return groups.values().stream() .map(o -> (String) o) .map(s -> s.split("\\s*,\\s*")) .flatMap(a -> Arrays.stream(a)) .filter(g -> !g.isEmpty()) .sorted() .distinct() .collect(Collectors.toList()); } public enum Encryption { DEFAULT, ENCRYPTED, CLEAR; public static Encryption valueOf(boolean plainText) { return plainText ? CLEAR : DEFAULT; } } }
15,454
41.226776
186
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Echo.java
package org.infinispan.cli.commands; import java.util.List; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.option.Arguments; import org.aesh.command.option.Option; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "echo", description = "Echoes messages to the output. Useful for adding information to batch runs.") public class Echo extends CliCommand { @Arguments private List<String> arguments; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { if (arguments != null && arguments.size() > 0) { for (int i = 0; i < arguments.size(); i++) { if (i > 0) invocation.print(" "); invocation.print(arguments.get(i)); } invocation.println(""); } return CommandResult.SUCCESS; } }
1,253
26.866667
126
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Benchmark.java
package org.infinispan.cli.commands; import java.net.URI; import java.util.concurrent.TimeUnit; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.benchmark.BenchmarkOutputFormat; import org.infinispan.cli.benchmark.HotRodBenchmark; import org.infinispan.cli.benchmark.HttpBenchmark; import org.infinispan.cli.benchmark.RespBenchmark; import org.infinispan.cli.completers.BenchmarkModeCompleter; import org.infinispan.cli.completers.BenchmarkVerbosityModeCompleter; import org.infinispan.cli.completers.CacheCompleter; import org.infinispan.cli.completers.TimeUnitCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.runner.Runner; import org.openjdk.jmh.runner.RunnerException; import org.openjdk.jmh.runner.options.OptionsBuilder; import org.openjdk.jmh.runner.options.TimeValue; import org.openjdk.jmh.runner.options.VerboseMode; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 12.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "benchmark", description = "Benchmarks server performance") public class Benchmark extends CliCommand { @Argument(description = "Specifies the URI of the server to benchmark. Supported protocols are http, https, hotrod, hotrods, redis, rediss. If you do not set a protocol, the benchmark uses the URI of the current connection.") String uri; @Option(shortName = 't', defaultValue = "10", description = "Specifies the number of threads to create. Defaults to 10.") int threads; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Option(completer = BenchmarkModeCompleter.class, defaultValue = "Throughput", description = "Specifies the benchmark mode. Possible values are Throughput, AverageTime, SampleTime, SingleShotTime, and All. Defaults to Throughput.") String mode; @Option(completer = BenchmarkVerbosityModeCompleter.class, defaultValue = "NORMAL", description = "Specifies the verbosity level of the output. Possible values, from least to most verbose, are SILENT, NORMAL, and EXTRA. Defaults to NORMAL.") String verbosity; @Option(shortName = 'c', defaultValue = "5", description = "Specifies how many measurement iterations to perform. Defaults to 5.") int count; @Option(defaultValue = "10s", description = "Sets the amount of time, in seconds, that each iteration takes. Defaults to 10.") String time; @Option(defaultValue = "5", name = "warmup-count", description = "Specifies how many warmup iterations to perform. Defaults to 5.") int warmupCount; @Option(defaultValue = "1s", name = "warmup-time", description = "Sets the amount of time, in seconds, that each warmup iteration takes. Defaults to 1.") String warmupTime; @Option(completer = TimeUnitCompleter.class, defaultValue = "MICROSECONDS", name = "time-unit", description = "Specifies the time unit for results in the benchmark report. Possible values are NANOSECONDS, MICROSECONDS, MILLISECONDS, and SECONDS. The default is MICROSECONDS.") String timeUnit; @Option(completer = CacheCompleter.class, defaultValue = "benchmark", description = "Names the cache against which the benchmark is performed. Defaults to 'benchmark'.") String cache; @Option(defaultValue = "16", name="key-size", description = "Sets the size, in bytes, of the key. Defaults to 16 bytes.") int keySize; @Option(defaultValue = "1000", name="value-size", description = "Sets the size, in bytes, of the value. Defaults to 1000 bytes.") int valueSize; @Option(defaultValue = "1000", name="keyset-size", description = "Defines the size, in bytes, of the test key set. Defaults to 1000.") int keySetSize; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { OptionsBuilder opt = new OptionsBuilder(); if (this.uri == null) { if (invocation.getContext().isConnected()) { this.uri = invocation.getContext().getConnection().getURI(); } else { throw new IllegalArgumentException("You must specify a URI"); } } URI uri = URI.create(this.uri); switch (uri.getScheme()) { case "hotrod": case "hotrods": opt.include(HotRodBenchmark.class.getSimpleName()); break; case "http": case "https": opt.include(HttpBenchmark.class.getSimpleName()); break; case "redis": case "rediss": opt.include(RespBenchmark.class.getSimpleName()); break; default: throw new IllegalArgumentException("Unknown scheme " + uri.getScheme()); } opt .forks(0) .threads(threads) .param("uri", this.uri) .param("cacheName", this.cache) .param("keySize", Integer.toString(this.keySize)) .param("valueSize", Integer.toString(this.valueSize)) .param("keySetSize", Integer.toString(this.keySetSize)) .mode(Mode.valueOf(mode)) .verbosity(VerboseMode.valueOf(verbosity)) .measurementIterations(count) .measurementTime(TimeValue.fromString(time)) .warmupIterations(warmupCount) .warmupTime(TimeValue.fromString(warmupTime)) .timeUnit(TimeUnit.valueOf(timeUnit)); try { new Runner(opt.build(), new BenchmarkOutputFormat(invocation.getShell(), VerboseMode.valueOf(verbosity))).run(); return CommandResult.SUCCESS; } catch (RunnerException e) { throw new CommandException(e); } } }
6,001
44.12782
279
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/CLI.java
package org.infinispan.cli.commands; import java.io.FileInputStream; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.Provider; import java.security.UnrecoverableKeyException; import java.util.Map; import java.util.Properties; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import org.aesh.command.AeshCommandRuntimeBuilder; import org.aesh.command.Command; import org.aesh.command.CommandResult; import org.aesh.command.CommandRuntime; import org.aesh.command.GroupCommandDefinition; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.impl.registry.AeshCommandRegistryBuilder; import org.aesh.command.invocation.CommandInvocation; import org.aesh.command.option.Option; import org.aesh.command.option.OptionGroup; import org.aesh.command.registry.CommandRegistry; import org.aesh.command.registry.CommandRegistryException; import org.aesh.command.settings.SettingsBuilder; import org.aesh.command.shell.Shell; import org.aesh.io.Resource; import org.aesh.readline.ReadlineConsole; import org.infinispan.cli.Context; import org.infinispan.cli.activators.ContextAwareCommandActivatorProvider; import org.infinispan.cli.commands.kubernetes.Kube; import org.infinispan.cli.commands.rest.Add; import org.infinispan.cli.commands.rest.Alter; import org.infinispan.cli.commands.rest.Availability; import org.infinispan.cli.commands.rest.Backup; import org.infinispan.cli.commands.rest.Cas; import org.infinispan.cli.commands.rest.ClearCache; import org.infinispan.cli.commands.rest.Create; import org.infinispan.cli.commands.rest.Drop; import org.infinispan.cli.commands.rest.Get; import org.infinispan.cli.commands.rest.Index; import org.infinispan.cli.commands.rest.Logging; import org.infinispan.cli.commands.rest.Migrate; import org.infinispan.cli.commands.rest.Put; import org.infinispan.cli.commands.rest.Query; import org.infinispan.cli.commands.rest.Rebalance; import org.infinispan.cli.commands.rest.Remove; import org.infinispan.cli.commands.rest.Reset; import org.infinispan.cli.commands.rest.Schema; import org.infinispan.cli.commands.rest.Server; import org.infinispan.cli.commands.rest.Shutdown; import org.infinispan.cli.commands.rest.Site; import org.infinispan.cli.commands.rest.Task; import org.infinispan.cli.commands.rest.Topology; import org.infinispan.cli.completers.ContextAwareCompleterInvocationProvider; import org.infinispan.cli.connection.RegexHostnameVerifier; import org.infinispan.cli.impl.AeshDelegatingShell; import org.infinispan.cli.impl.CliAliasManager; import org.infinispan.cli.impl.CliCommandNotFoundHandler; import org.infinispan.cli.impl.CliRuntimeRunner; import org.infinispan.cli.impl.CliShell; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.impl.ContextAwareCommandInvocationProvider; import org.infinispan.cli.impl.ContextAwareQuitHandler; import org.infinispan.cli.impl.ContextImpl; import org.infinispan.cli.impl.ExitCodeResultHandler; import org.infinispan.cli.impl.KubernetesContext; import org.infinispan.cli.impl.SSLContextSettings; import org.infinispan.cli.impl.StreamShell; import org.infinispan.cli.logging.Messages; import org.infinispan.cli.util.ZeroSecurityHostnameVerifier; import org.infinispan.cli.util.ZeroSecurityTrustManager; import org.infinispan.commons.jdkspecific.ProcessInfo; import org.infinispan.commons.util.ServiceFinder; import org.infinispan.commons.util.SslContextFactory; import org.infinispan.commons.util.Util; import org.wildfly.security.credential.store.WildFlyElytronCredentialStoreProvider; import org.wildfly.security.keystore.KeyStoreUtil; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 11.0 **/ @GroupCommandDefinition( name = "cli", description = "", groupCommands = { Add.class, Alter.class, Availability.class, Backup.class, Benchmark.class, Cache.class, Cas.class, Cd.class, Clear.class, ClearCache.class, Config.class, Connect.class, Container.class, Counter.class, Create.class, Credentials.class, Describe.class, Disconnect.class, Drop.class, Echo.class, Encoding.class, Get.class, Index.class, Install.class, Logging.class, Ls.class, Migrate.class, Patch.class, Put.class, Query.class, Rebalance.class, Remove.class, Reset.class, Run.class, Schema.class, Server.class, Shutdown.class, Site.class, Task.class, Topology.class, User.class, Version.class }, resultHandler = ExitCodeResultHandler.class) public class CLI extends CliCommand { private Context context; @Option(completer = FileOptionCompleter.class, shortName = 't', name = "truststore", description = "A truststore to use when connecting to SSL/TLS-enabled servers") Resource truststore; @Option(shortName = 's', name = "truststore-password", description = "The password for the truststore") String truststorePassword; @Option(completer = FileOptionCompleter.class, shortName = 'k', name = "keystore", description = "A keystore containing a client certificate to authenticate with the server") Resource keystore; @Option(shortName = 'w', name = "keystore-password", description = "The password for the keystore") String keystorePassword; @Option(name = "provider", description = "The security provider used to create the SSL/TLS context") String provider; @Option(shortName = 'v', hasValue = false, description = "Shows version information") boolean version; @Option(hasValue = false, description = "Whether to trust all server certificates", name = "trustall") boolean trustAll; @Option(completer = FileOptionCompleter.class, shortName = 'f', description = "File for batch mode") String file; @Option(shortName = 'c', description = "A connection URL. Use '-' to connect to http://localhost:11222") String connect; @Option(shortName = 'P', description = "Sets system properties from the specified file.") String properties; @OptionGroup(shortName = 'D', description = "Sets a system property") Map<String, String> propertyMap; @Option(name = "hostname-verifier", description = "A regular expression used to match hostnames when connecting to SSL/TLS-enabled servers") String hostnameVerifier; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { if (help) { invocation.println(invocation.getHelpInfo()); return CommandResult.SUCCESS; } if (version) { invocation.printf("%s CLI %s\n", org.infinispan.commons.util.Version.getBrandName(), org.infinispan.commons.util.Version.getBrandVersion()); invocation.printf("Copyright (C) Red Hat Inc. and/or its affiliates and other contributors\n"); invocation.printf("License Apache License, v. 2.0. http://www.apache.org/licenses/LICENSE-2.0\n"); return CommandResult.SUCCESS; } context = invocation.getContext(); if (propertyMap != null) { propertyMap.forEach(context.getProperties()::putIfAbsent); } if (properties != null) { try (Reader r = Files.newBufferedReader(Paths.get(properties))) { Properties loaded = new Properties(); loaded.load(r); loaded.forEach(context.getProperties()::putIfAbsent); } catch (IOException e) { throw new IllegalArgumentException(e); } } try { configureSslContext(context, truststore, truststorePassword, keystore, keystorePassword, provider, hostnameVerifier, trustAll); } catch (Exception e) { invocation.getShell().writeln(Messages.MSG.keyStoreError(e)); return CommandResult.FAILURE; } String connectionString = connect != null ? connect : context.getProperty(Context.Property.AUTOCONNECT_URL); if (connectionString != null) { context.connect(null, connectionString); } if (file != null) { return batch(file, invocation.getShell()); } else { if (context.getProperty(Context.Property.AUTOEXEC) != null) { batch(context.getProperty(Context.Property.AUTOEXEC), invocation.getShell()); } return interactive(invocation.getShell()); } } public static void configureSslContext(Context context, Resource truststore, String truststorePassword, Resource keystore, String keystorePassword, String providerName, String hostnameVerifier, boolean trustAll) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, IOException { Provider[] providers = SslContextFactory.discoverSecurityProviders(CLI.class.getClassLoader()); providerName = providerName != null ? providerName : context.getProperty(Context.Property.PROVIDER); String sslKeyStore = keystore != null ? keystore.getAbsolutePath() : context.getProperty(Context.Property.KEYSTORE); KeyManager[] keyManagers = null; if (sslKeyStore != null) { String sslKeyStorePassword = keystorePassword != null ? keystorePassword : context.getProperty(Context.Property.KEYSTORE_PASSWORD); try (FileInputStream f = new FileInputStream(sslKeyStore)) { KeyStore ks = KeyStoreUtil.loadKeyStore(() -> providers, providerName, f, sslKeyStore, sslKeyStorePassword != null ? sslKeyStorePassword.toCharArray() : null); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(ks, sslKeyStorePassword != null ? sslKeyStorePassword.toCharArray() : null); keyManagers = keyManagerFactory.getKeyManagers(); } } String sslTrustStore = truststore != null ? truststore.getAbsolutePath() : context.getProperty(Context.Property.TRUSTSTORE); if (sslTrustStore != null) { TrustManagerFactory trustManagerFactory; String sslTrustStorePassword = truststorePassword != null ? truststorePassword : context.getProperty(Context.Property.TRUSTSTORE_PASSWORD); try (FileInputStream f = new FileInputStream(sslTrustStore)) { KeyStore ts = KeyStoreUtil.loadKeyStore(() -> providers, providerName, f, sslTrustStore, sslTrustStorePassword != null ? sslTrustStorePassword.toCharArray() : null); trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(ts); } HostnameVerifier verifier = hostnameVerifier != null ? new RegexHostnameVerifier(hostnameVerifier) : null; SSLContextSettings sslContext = SSLContextSettings.getInstance("TLS", keyManagers, trustManagerFactory.getTrustManagers(), null, verifier); context.setSslContext(sslContext); } else if (trustAll || Boolean.parseBoolean(context.getProperty(Context.Property.TRUSTALL))) { SSLContextSettings sslContext = SSLContextSettings.getInstance("TLS", keyManagers, new TrustManager[]{new ZeroSecurityTrustManager()}, null, new ZeroSecurityHostnameVerifier()); context.setSslContext(sslContext); } } private CommandResult batch(String inputFile, Shell shell) { CommandRegistry commandRegistry = initializeCommands(Batch.class); AeshCommandRuntimeBuilder runtimeBuilder = AeshCommandRuntimeBuilder.builder(); runtimeBuilder .commandActivatorProvider(new ContextAwareCommandActivatorProvider(context)) .commandInvocationProvider(new ContextAwareCommandInvocationProvider(context)) .commandNotFoundHandler(new CliCommandNotFoundHandler()) .completerInvocationProvider(new ContextAwareCompleterInvocationProvider(context)) .aeshContext(context) .commandRegistry(commandRegistry); runtimeBuilder.shell(shell); CliRuntimeRunner cliRunner = new CliRuntimeRunner("batch", runtimeBuilder.build()); int exitCode = cliRunner .args(new String[]{"run", inputFile}) .execute(); context.disconnect(); return CommandResult.valueOf(exitCode); } private CommandResult interactive(Shell shell) { // We now start an interactive CLI CommandRegistry commandRegistry = initializeCommands(); context.setRegistry(commandRegistry); CliAliasManager aliasManager; try { aliasManager = new CliAliasManager(context.getConfigPath().resolve("aliases").toFile(), true, commandRegistry); } catch (IOException e) { throw new RuntimeException(e); } SettingsBuilder settings = SettingsBuilder.builder(); settings .enableAlias(true) .aliasManager(aliasManager) .historyFile(context.getConfigPath().resolve("history").toFile()) .outputStream(System.out) .outputStreamError(System.err) .inputStream(System.in) .commandActivatorProvider(new ContextAwareCommandActivatorProvider(context)) .commandInvocationProvider(new ContextAwareCommandInvocationProvider(context)) .commandNotFoundHandler(new CliCommandNotFoundHandler()) .completerInvocationProvider(new ContextAwareCompleterInvocationProvider(context)) .commandRegistry(commandRegistry) .aeshContext(context) .quitHandler(new ContextAwareQuitHandler(context)); if (shell instanceof AeshDelegatingShell) { settings.connection(((AeshDelegatingShell) shell).getConnection()); } ReadlineConsole console = new ReadlineConsole(settings.build()); context.setConsole(console); try { console.start(); return CommandResult.SUCCESS; } catch (IOException e) { throw new RuntimeException(e); } } private CommandRegistry initializeCommands(Class<? extends Command>... commands) { try { AeshCommandRegistryBuilder<CommandInvocation> registryBuilder = AeshCommandRegistryBuilder.builder(); for (Class<? extends Command> command : commands) { registryBuilder.command(command); } for (Command command : ServiceFinder.load(Command.class, this.getClass().getClassLoader())) { registryBuilder.command(command); } return registryBuilder.create(); } catch (CommandRegistryException e) { throw new RuntimeException(e); } } private static AeshCommandRuntimeBuilder initialCommandRuntimeBuilder(Shell shell, Properties properties, boolean kube) throws CommandRegistryException { AeshCommandRegistryBuilder registryBuilder = AeshCommandRegistryBuilder.builder(); Context context; if (kube) { context = new KubernetesContext(properties); registryBuilder.command(Kube.class); } else { context = new ContextImpl(properties); registryBuilder.command(CLI.class); } AeshCommandRuntimeBuilder runtimeBuilder = AeshCommandRuntimeBuilder.builder(); runtimeBuilder .commandActivatorProvider(new ContextAwareCommandActivatorProvider(context)) .commandInvocationProvider(new ContextAwareCommandInvocationProvider(context)) .commandNotFoundHandler(new CliCommandNotFoundHandler()) .completerInvocationProvider(new ContextAwareCompleterInvocationProvider(context)) .shell(shell) .aeshContext(context) .commandRegistry(registryBuilder.create()); return runtimeBuilder; } private static boolean isKubernetesMode() { return ProcessInfo.getInstance().getName().contains("kubectl") || Boolean.getBoolean("infinispan.cli.kubernetes"); } public static int main(Shell shell, String[] args, Properties properties, boolean kube) { CommandRuntime<?> runtime = null; try { SecurityActions.addSecurityProvider(WildFlyElytronCredentialStoreProvider.getInstance()); runtime = initialCommandRuntimeBuilder(shell, properties, kube).build(); return new CliRuntimeRunner(kube ? "kube" : "cli", runtime).args(args).execute(); } catch (Exception e) { throw new RuntimeException(e); } finally { if (runtime != null) { Util.close((AutoCloseable) runtime.getAeshContext()); } } } public static int main(Shell shell, String[] args, Properties properties) { return main(shell, args, properties, isKubernetesMode()); } public static void main(String[] args) throws IOException { Shell shell = null; for (int i = 0; i < args.length - 1; i++) { if (args[i].equals("-f") && args[i + 1].equals("-")) { shell = new StreamShell(); } } if (shell == null) { shell = new CliShell(); } System.exit(main(shell, args, System.getProperties())); } public static Path getServerHome(Resource server) { if (server != null) { return Paths.get(server.getAbsolutePath()); } else { String serverHome = System.getProperty("infinispan.server.home.path"); if (serverHome != null) { return Paths.get(serverHome); } else { // Fall back to the cwd return Paths.get(System.getProperty("user.dir")); } } } }
18,222
42.080378
307
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Ls.java
package org.infinispan.cli.commands; import java.io.IOException; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CdContextCompleter; import org.infinispan.cli.completers.ListFormatCompleter; import org.infinispan.cli.completers.PrettyPrintCompleter; import org.infinispan.cli.connection.Connection; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.printers.PrettyPrinter; import org.infinispan.cli.resources.Resource; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "ls", description = "Lists resources in a path", activator = ConnectionActivator.class) public class Ls extends CliCommand { @Argument(description = "The path of the subsystem/item", completer = CdContextCompleter.class) String path; @Option(shortName = 'f', description = "Use a listing format (supported only by some resources)", defaultValue = "NAMES", completer = ListFormatCompleter.class) String format; @Option(shortName = 'p', name = "pretty-print", description = "Pretty-print the output", defaultValue = "TABLE", completer = PrettyPrintCompleter.class) String prettyPrint; @Option(shortName = 'l', hasValue = false, description = "Shortcut for -f FULL.") boolean l; @Option(name = "max-items", shortName = 'm', description = "Limit the number of results (supported only by some resources). Defaults to no limit", defaultValue = "-1") int maxItems; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { try { Connection connection = invocation.getContext().getConnection(); connection.refreshServerInfo(); Resource resource = connection.getActiveResource().getResource(path); resource.printChildren(l ? Resource.ListFormat.FULL : Resource.ListFormat.valueOf(format), maxItems, PrettyPrinter.PrettyPrintMode.valueOf(prettyPrint), invocation.getShell()); return CommandResult.SUCCESS; } catch (IOException e) { throw new CommandException(e); } } }
2,610
37.970149
185
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Connect.java
package org.infinispan.cli.commands; import java.io.IOException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandResult; import org.aesh.command.impl.completer.FileOptionCompleter; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.aesh.io.Resource; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.infinispan.cli.logging.Messages; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "connect", description = "Connects to a remote server") public class Connect extends CliCommand { @Argument(description = "The connection string 'http://<host>:<port>") String connectionString; @Option(shortName = 'u') String username; @Option(shortName = 'p') String password; @Option(completer = FileOptionCompleter.class, shortName = 't', name = "truststore", description = "A truststore to use when connecting to SSL/TLS-enabled servers") Resource truststore; @Option(shortName = 's', name = "truststore-password", description = "The password for the truststore") String truststorePassword; @Option(completer = FileOptionCompleter.class, shortName = 'k', name = "keystore", description = "A keystore containing a client certificate to authenticate with the server") Resource keystore; @Option(shortName = 'w', name = "keystore-password", description = "The password for the keystore") String keystorePassword; @Option(name = "provider", description = "The security provider used to create the SSL/TLS context") String provider; @Option(hasValue = false, description = "Whether to trust all server certificates", name = "trustall") boolean trustAll; @Option(name = "hostname-verifier", description = "A regular expression used to match hostnames when connecting to SSL/TLS-enabled servers") String hostnameVerifier; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) { try { CLI.configureSslContext(invocation.getContext(), truststore, truststorePassword, keystore, keystorePassword, provider, hostnameVerifier, trustAll); } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException | IOException e) { invocation.getShell().writeln(Messages.MSG.keyStoreError(e)); throw new RuntimeException(e); } if (username != null) { invocation.getContext().connect(invocation.getShell(), connectionString, username, password); } else { invocation.getContext().connect(invocation.getShell(), connectionString); } return invocation.getContext().isConnected() ? CommandResult.SUCCESS : CommandResult.FAILURE; } }
3,151
38.4
177
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/Cd.java
package org.infinispan.cli.commands; import org.aesh.command.Command; import org.aesh.command.CommandDefinition; import org.aesh.command.CommandException; import org.aesh.command.CommandResult; import org.aesh.command.option.Argument; import org.aesh.command.option.Option; import org.infinispan.cli.activators.ConnectionActivator; import org.infinispan.cli.completers.CdContextCompleter; import org.infinispan.cli.impl.ContextAwareCommandInvocation; import org.kohsuke.MetaInfServices; /** * @author Tristan Tarrant &lt;tristan@infinispan.org&gt; * @since 10.0 **/ @MetaInfServices(Command.class) @CommandDefinition(name = "cd", description = "Selects a subsystem or item", activator = ConnectionActivator.class) public class Cd extends CliCommand { @Argument(description = "The name of the subsystem/item", completer = CdContextCompleter.class, required = true) String path; @Option(shortName = 'h', hasValue = false, overrideRequired = true) protected boolean help; @Override public boolean isHelp() { return help; } @Override public CommandResult exec(ContextAwareCommandInvocation invocation) throws CommandException { return invocation.getContext().changeResource(null, null, path); } }
1,244
31.763158
115
java
null
infinispan-main/cli/src/main/java/org/infinispan/cli/commands/SecurityActions.java
package org.infinispan.cli.commands; import java.security.Provider; /** * SecurityActions for the org.infinispan.cli.commands package. * <p> * Do not move. Do not change class and method visibility to avoid being called from other * {@link java.security.CodeSource}s, thus granting privilege escalation to external code. * * @author Tristan Tarrant <tristan@infinispan.org> * @since 12.0 */ final class SecurityActions { static void addSecurityProvider(Provider provider) { if (java.security.Security.getProvider(provider.getName()) == null) { java.security.Security.insertProviderAt(provider, 1); } } }
642
28.227273
90
java