idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
32,100
public static final < T extends Tree > Matcher < T > inSynchronized ( ) { return new Matcher < T > ( ) { public boolean matches ( T tree , VisitorState state ) { SynchronizedTree synchronizedTree = ASTHelpers . findEnclosingNode ( state . getPath ( ) , SynchronizedTree . class ) ; if ( synchronizedTree != null ) { return true ; } MethodTree methodTree = ASTHelpers . findEnclosingNode ( state . getPath ( ) , MethodTree . class ) ; return methodTree != null && methodTree . getModifiers ( ) . getFlags ( ) . contains ( Modifier . SYNCHRONIZED ) ; } } ; }
Matches if this Tree is enclosed by either a synchronized block or a synchronized method .
32,101
public static Matcher < ExpressionTree > sameVariable ( final ExpressionTree expr ) { return new Matcher < ExpressionTree > ( ) { public boolean matches ( ExpressionTree tree , VisitorState state ) { return ASTHelpers . sameVariable ( tree , expr ) ; } } ; }
Matches if this ExpressionTree refers to the same variable as the one passed into the matcher .
32,102
public static Matcher < EnhancedForLoopTree > enhancedForLoop ( final Matcher < VariableTree > variableMatcher , final Matcher < ExpressionTree > expressionMatcher , final Matcher < StatementTree > statementMatcher ) { return new Matcher < EnhancedForLoopTree > ( ) { public boolean matches ( EnhancedForLoopTree t , VisitorState state ) { return variableMatcher . matches ( t . getVariable ( ) , state ) && expressionMatcher . matches ( t . getExpression ( ) , state ) && statementMatcher . matches ( t . getStatement ( ) , state ) ; } } ; }
Matches an enhanced for loop if all the given matchers match .
32,103
public static < T extends Tree > Matcher < T > inLoop ( ) { return new Matcher < T > ( ) { public boolean matches ( Tree tree , VisitorState state ) { TreePath path = state . getPath ( ) . getParentPath ( ) ; Tree node = path . getLeaf ( ) ; while ( path != null ) { switch ( node . getKind ( ) ) { case METHOD : case CLASS : return false ; case WHILE_LOOP : case FOR_LOOP : case ENHANCED_FOR_LOOP : case DO_WHILE_LOOP : return true ; default : path = path . getParentPath ( ) ; node = path . getLeaf ( ) ; break ; } } return false ; } } ; }
Matches if the given tree is inside a loop .
32,104
public static Matcher < AssignmentTree > assignment ( final Matcher < ExpressionTree > variableMatcher , final Matcher < ? super ExpressionTree > expressionMatcher ) { return new Matcher < AssignmentTree > ( ) { public boolean matches ( AssignmentTree t , VisitorState state ) { return variableMatcher . matches ( t . getVariable ( ) , state ) && expressionMatcher . matches ( t . getExpression ( ) , state ) ; } } ; }
Matches an assignment operator AST node if both of the given matchers match .
32,105
public static Matcher < TypeCastTree > typeCast ( final Matcher < Tree > typeMatcher , final Matcher < ExpressionTree > expressionMatcher ) { return new Matcher < TypeCastTree > ( ) { public boolean matches ( TypeCastTree t , VisitorState state ) { return typeMatcher . matches ( t . getType ( ) , state ) && expressionMatcher . matches ( t . getExpression ( ) , state ) ; } } ; }
Matches a type cast AST node if both of the given matchers match .
32,106
public static Matcher < AssertTree > assertionWithCondition ( final Matcher < ExpressionTree > conditionMatcher ) { return new Matcher < AssertTree > ( ) { public boolean matches ( AssertTree tree , VisitorState state ) { return conditionMatcher . matches ( tree . getCondition ( ) , state ) ; } } ; }
Matches an assertion AST node if the given matcher matches its condition .
32,107
public static < T extends Tree , V extends Tree > Matcher < T > contains ( Class < V > clazz , Matcher < V > treeMatcher ) { final Matcher < Tree > contains = new Contains ( toType ( clazz , treeMatcher ) ) ; return contains :: matches ; }
Applies the given matcher recursively to all descendants of an AST node and matches if any matching descendant node is found .
32,108
public static Matcher < MethodTree > methodHasArity ( final int arity ) { return new Matcher < MethodTree > ( ) { public boolean matches ( MethodTree methodTree , VisitorState state ) { return methodTree . getParameters ( ) . size ( ) == arity ; } } ; }
Matches if the method accepts the given number of arguments .
32,109
public static Matcher < ClassTree > isDirectImplementationOf ( String clazz ) { Matcher < Tree > isProvidedType = isSameType ( clazz ) ; return new IsDirectImplementationOf ( isProvidedType ) ; }
Matches any node that is directly an implementation but not extension of the given Class .
32,110
public static < T extends Tree > Matcher < T > packageMatches ( Pattern pattern ) { return ( tree , state ) -> pattern . matcher ( getPackageFullName ( state ) ) . matches ( ) ; }
Matches an AST node whose compilation unit s package name matches the given pattern .
32,111
public static < T extends Tree > Matcher < T > packageStartsWith ( String prefix ) { return ( tree , state ) -> getPackageFullName ( state ) . startsWith ( prefix ) ; }
Matches an AST node whose compilation unit starts with this prefix .
32,112
private JCBlock inlineFinallyBlock ( Inliner inliner ) throws CouldNotResolveImportException { if ( getFinallyBlock ( ) != null ) { JCBlock block = getFinallyBlock ( ) . inline ( inliner ) ; if ( ! block . getStatements ( ) . isEmpty ( ) ) { return block ; } } return null ; }
Skips the finally block if the result would be empty .
32,113
private static boolean isGeneratedFactoryType ( ClassSymbol symbol , VisitorState state ) { return GENERATED_BASE_TYPES . stream ( ) . anyMatch ( baseType -> isGeneratedBaseType ( symbol , state , baseType ) ) ; }
instead of checking for subtypes of generated code
32,114
Violation areFieldsImmutable ( Optional < ClassTree > tree , ImmutableSet < String > immutableTyParams , ClassType classType , ViolationReporter reporter ) { ClassSymbol classSym = ( ClassSymbol ) classType . tsym ; if ( classSym . members ( ) == null ) { return Violation . absent ( ) ; } Filter < Symbol > instanceFieldFilter = new Filter < Symbol > ( ) { public boolean accepts ( Symbol symbol ) { return symbol . getKind ( ) == ElementKind . FIELD && ! symbol . isStatic ( ) ; } } ; Map < Symbol , Tree > declarations = new HashMap < > ( ) ; if ( tree . isPresent ( ) ) { for ( Tree member : tree . get ( ) . getMembers ( ) ) { Symbol sym = ASTHelpers . getSymbol ( member ) ; if ( sym != null ) { declarations . put ( sym , member ) ; } } } List < Symbol > members = ImmutableList . copyOf ( classSym . members ( ) . getSymbols ( instanceFieldFilter ) ) . reverse ( ) ; for ( Symbol member : members ) { Optional < Tree > memberTree = Optional . ofNullable ( declarations . get ( member ) ) ; Violation info = isFieldImmutable ( memberTree , immutableTyParams , classSym , classType , ( VarSymbol ) member , reporter ) ; if ( info . isPresent ( ) ) { return info ; } } return Violation . absent ( ) ; }
Check a single class fields for immutability .
32,115
private Violation isFieldImmutable ( Optional < Tree > tree , ImmutableSet < String > immutableTyParams , ClassSymbol classSym , ClassType classType , VarSymbol var , ViolationReporter reporter ) { if ( bugChecker . isSuppressed ( var ) ) { return Violation . absent ( ) ; } if ( ! var . getModifiers ( ) . contains ( Modifier . FINAL ) && ! ASTHelpers . hasAnnotation ( var , LazyInit . class , state ) ) { Violation info = Violation . of ( String . format ( "'%s' has non-final field '%s'" , threadSafety . getPrettyName ( classSym ) , var . getSimpleName ( ) ) ) ; if ( tree . isPresent ( ) ) { state . reportMatch ( reporter . report ( tree . get ( ) , info , SuggestedFixes . addModifiers ( tree . get ( ) , state , Modifier . FINAL ) ) ) ; return Violation . absent ( ) ; } return info ; } Type varType = state . getTypes ( ) . memberType ( classType , var ) ; Violation info = threadSafety . isThreadSafeType ( true , immutableTyParams , varType ) ; if ( info . isPresent ( ) ) { info = info . plus ( String . format ( "'%s' has field '%s' of type '%s'" , threadSafety . getPrettyName ( classSym ) , var . getSimpleName ( ) , varType ) ) ; if ( tree . isPresent ( ) ) { state . reportMatch ( reporter . report ( tree . get ( ) , info , Optional . empty ( ) ) ) ; return Violation . absent ( ) ; } return info ; } return Violation . absent ( ) ; }
Check a single field for immutability .
32,116
public static Result compile ( DiagnosticListener < JavaFileObject > listener , String [ ] args ) { return ErrorProneCompiler . builder ( ) . listenToDiagnostics ( listener ) . build ( ) . run ( args ) ; }
Compiles in - process .
32,117
public static Result compile ( String [ ] args , PrintWriter out ) { return ErrorProneCompiler . builder ( ) . redirectOutputTo ( out ) . build ( ) . run ( args ) ; }
Programmatic interface to the error - prone Java compiler .
32,118
private static boolean functionalInterfaceReturnsExactlyVoid ( Type interfaceType , VisitorState state ) { return state . getTypes ( ) . findDescriptorType ( interfaceType ) . getReturnType ( ) . getKind ( ) == TypeKind . VOID ; }
Checks that the return value of a functional interface is void . Note we do not use ASTHelpers . isVoidType here return values of Void are actually type - checked . Only void - returning functions silently ignore return values of any type .
32,119
private Description matchInvocation ( ExpressionTree tree , MethodSymbol symbol , List < ? extends ExpressionTree > args , VisitorState state ) { if ( ! ASTHelpers . hasAnnotation ( symbol , FormatMethod . class , state ) ) { return Description . NO_MATCH ; } Type stringType = state . getSymtab ( ) . stringType ; List < VarSymbol > params = symbol . getParameters ( ) ; int firstStringIndex = - 1 ; int formatString = - 1 ; for ( int i = 0 ; i < params . size ( ) ; i ++ ) { VarSymbol param = params . get ( i ) ; if ( ASTHelpers . hasAnnotation ( param , FormatString . class , state ) ) { formatString = i ; break ; } if ( firstStringIndex < 0 && ASTHelpers . isSameType ( params . get ( i ) . type , stringType , state ) ) { firstStringIndex = i ; } } if ( formatString < 0 ) { formatString = firstStringIndex ; } FormatStringValidation . ValidationResult result = StrictFormatStringValidation . validate ( args . get ( formatString ) , args . subList ( formatString + 1 , args . size ( ) ) , state ) ; if ( result != null ) { return buildDescription ( tree ) . setMessage ( result . message ( ) ) . build ( ) ; } else { return Description . NO_MATCH ; } }
Matches a method or constructor invocation . The input symbol should match the invoked method or contructor and the args should be the parameters in the invocation .
32,120
private static ImmutableSet < Symbol > lookup ( Symbol . TypeSymbol typeSym , Symbol . TypeSymbol start , Name identifier , Types types , Symbol . PackageSymbol pkg ) { if ( typeSym == null ) { return ImmutableSet . of ( ) ; } ImmutableSet . Builder < Symbol > members = ImmutableSet . builder ( ) ; members . addAll ( lookup ( types . supertype ( typeSym . type ) . tsym , start , identifier , types , pkg ) ) ; for ( Type i : types . interfaces ( typeSym . type ) ) { members . addAll ( lookup ( i . tsym , start , identifier , types , pkg ) ) ; } OUTER : for ( Symbol member : typeSym . members ( ) . getSymbolsByName ( identifier ) ) { if ( ! member . isStatic ( ) ) { continue ; } switch ( ( int ) ( member . flags ( ) & Flags . AccessFlags ) ) { case Flags . PRIVATE : continue OUTER ; case 0 : case Flags . PROTECTED : if ( member . packge ( ) != pkg ) { continue OUTER ; } break ; case Flags . PUBLIC : default : break ; } if ( member . isMemberOf ( start , types ) ) { members . add ( member ) ; } } return members . build ( ) ; }
to filter on method signature .
32,121
void invalidateAllAlternatives ( Parameter formal ) { for ( int actualIndex = 0 ; actualIndex < costMatrix [ formal . index ( ) ] . length ; actualIndex ++ ) { if ( actualIndex != formal . index ( ) ) { costMatrix [ formal . index ( ) ] [ actualIndex ] = Double . POSITIVE_INFINITY ; } } }
Set the cost of all the alternatives for this formal parameter to be Inf .
32,122
void updatePair ( ParameterPair p , double cost ) { costMatrix [ p . formal ( ) . index ( ) ] [ p . actual ( ) . index ( ) ] = cost ; }
Update the cost of the given pairing .
32,123
public static VisitorState createForUtilityPurposes ( Context context ) { return new VisitorState ( context , VisitorState :: nullListener , ImmutableMap . of ( ) , ErrorProneOptions . empty ( ) , StatisticsCollector . createNoOpCollector ( ) , null , null , SuppressedState . UNSUPPRESSED ) ; }
Return a VisitorState that has no Error Prone configuration and can t report results .
32,124
public static VisitorState createConfiguredForCompilation ( Context context , DescriptionListener listener , Map < String , SeverityLevel > severityMap , ErrorProneOptions errorProneOptions ) { return new VisitorState ( context , listener , severityMap , errorProneOptions , StatisticsCollector . createCollector ( ) , null , null , SuppressedState . UNSUPPRESSED ) ; }
Return a VisitorState configured for a new compilation including Error Prone configuration .
32,125
private static String inferBinaryName ( String classname ) { StringBuilder sb = new StringBuilder ( ) ; boolean first = true ; char sep = '.' ; for ( String bit : Splitter . on ( '.' ) . split ( classname ) ) { if ( ! first ) { sb . append ( sep ) ; } sb . append ( bit ) ; if ( Character . isUpperCase ( bit . charAt ( 0 ) ) ) { sep = '$' ; } first = false ; } return sb . toString ( ) ; }
so it may not end up being a performance win . )
32,126
public Type getType ( Type baseType , boolean isArray , List < Type > typeParams ) { boolean isGeneric = typeParams != null && ! typeParams . isEmpty ( ) ; if ( ! isArray && ! isGeneric ) { return baseType ; } else if ( isArray && ! isGeneric ) { ClassSymbol arraySymbol = getSymtab ( ) . arrayClass ; return new ArrayType ( baseType , arraySymbol ) ; } else if ( ! isArray && isGeneric ) { com . sun . tools . javac . util . List < Type > typeParamsCopy = com . sun . tools . javac . util . List . from ( typeParams ) ; return new ClassType ( Type . noType , typeParamsCopy , baseType . tsym ) ; } else { throw new IllegalArgumentException ( "Unsupported arguments to getType" ) ; } }
Build an instance of a Type .
32,127
@ SuppressWarnings ( "unchecked" ) public final < T extends Tree > T findEnclosing ( Class < ? extends T > ... classes ) { TreePath pathToEnclosing = findPathToEnclosing ( classes ) ; return ( pathToEnclosing == null ) ? null : ( T ) pathToEnclosing . getLeaf ( ) ; }
Find the first enclosing tree node of one of the given types .
32,128
public CharSequence getSourceCode ( ) { try { return getPath ( ) . getCompilationUnit ( ) . getSourceFile ( ) . getCharContent ( false ) ; } catch ( IOException e ) { return null ; } }
Gets the current source file .
32,129
public String getSourceForNode ( Tree tree ) { JCTree node = ( JCTree ) tree ; int start = node . getStartPosition ( ) ; int end = getEndPosition ( node ) ; if ( end < 0 ) { return null ; } return getSourceCode ( ) . subSequence ( start , end ) . toString ( ) ; }
Gets the original source code that represents the given node .
32,130
public int getEndPosition ( Tree node ) { JCCompilationUnit compilationUnit = ( JCCompilationUnit ) getPath ( ) . getCompilationUnit ( ) ; if ( compilationUnit . endPositions == null ) { return - 1 ; } return ( ( JCTree ) node ) . getEndPosition ( compilationUnit . endPositions ) ; }
Returns the end position of the node or - 1 if it is not available .
32,131
private static void validateTypeStr ( String typeStr ) { if ( typeStr . contains ( "[" ) || typeStr . contains ( "]" ) ) { throw new IllegalArgumentException ( String . format ( "Cannot convert array types (%s), please build them using getType()" , typeStr ) ) ; } if ( typeStr . contains ( "<" ) || typeStr . contains ( ">" ) ) { throw new IllegalArgumentException ( String . format ( "Cannot convert generic types (%s), please build them using getType()" , typeStr ) ) ; } }
Validates a type string ensuring it is not generic and not an array type .
32,132
public static boolean canCompleteNormally ( CaseTree caseTree ) { List < ? extends StatementTree > statements = caseTree . getStatements ( ) ; if ( statements . isEmpty ( ) ) { return true ; } return canCompleteNormally ( getLast ( statements ) ) ; }
Returns true if the given case tree can complete normally as defined by JLS 14 . 21 .
32,133
public static void setupMessageBundle ( Context context ) { ResourceBundle bundle = ResourceBundle . getBundle ( "com.google.errorprone.errors" ) ; JavacMessages . instance ( context ) . add ( l -> bundle ) ; }
Registers our message bundle .
32,134
static MatchedComment match ( Commented < ExpressionTree > actual , String formal ) { Optional < Comment > lastBlockComment = Streams . findLast ( actual . beforeComments ( ) . stream ( ) . filter ( c -> c . getStyle ( ) == CommentStyle . BLOCK ) ) ; if ( lastBlockComment . isPresent ( ) ) { Matcher m = PARAMETER_COMMENT_PATTERN . matcher ( Comments . getTextFromComment ( lastBlockComment . get ( ) ) ) ; if ( m . matches ( ) ) { return MatchedComment . create ( lastBlockComment . get ( ) , m . group ( 1 ) . equals ( formal ) ? MatchType . EXACT_MATCH : MatchType . BAD_MATCH ) ; } } Optional < Comment > approximateMatchComment = Stream . concat ( actual . beforeComments ( ) . stream ( ) , actual . afterComments ( ) . stream ( ) ) . filter ( comment -> isApproximateMatchingComment ( comment , formal ) ) . findFirst ( ) ; if ( approximateMatchComment . isPresent ( ) ) { String text = CharMatcher . anyOf ( "=:" ) . trimTrailingFrom ( Comments . getTextFromComment ( approximateMatchComment . get ( ) ) . trim ( ) ) ; return MatchedComment . create ( approximateMatchComment . get ( ) , text . equals ( formal ) ? MatchType . EXACT_MATCH : MatchType . APPROXIMATE_MATCH ) ; } return MatchedComment . notAnnotated ( ) ; }
Determine the kind of match we have between the comments on this argument and the formal parameter name .
32,135
public static boolean containsSyntheticParameterName ( MethodSymbol sym ) { return sym . getParameters ( ) . stream ( ) . anyMatch ( p -> SYNTHETIC_PARAMETER_NAME . matcher ( p . getSimpleName ( ) ) . matches ( ) ) ; }
Returns true if the method has synthetic parameter names indicating the real names are not available .
32,136
private Description checkAnnotations ( Tree tree , int treePos , List < ? extends AnnotationTree > annotations , Comment danglingJavadoc , int firstModifierPos , int lastModifierPos , VisitorState state ) { SuggestedFix . Builder builder = SuggestedFix . builder ( ) ; List < AnnotationTree > moveBefore = new ArrayList < > ( ) ; List < AnnotationTree > moveAfter = new ArrayList < > ( ) ; boolean annotationProblem = false ; for ( AnnotationTree annotation : annotations ) { int annotationPos = ( ( JCTree ) annotation ) . getStartPosition ( ) ; if ( annotationPos <= firstModifierPos ) { continue ; } AnnotationType annotationType = ASTHelpers . getAnnotationType ( annotation , getSymbol ( tree ) , state ) ; if ( annotationPos >= lastModifierPos ) { if ( tree instanceof ClassTree || annotationType == AnnotationType . DECLARATION ) { annotationProblem = true ; moveBefore . add ( annotation ) ; } } else { annotationProblem = true ; if ( tree instanceof ClassTree || annotationType == AnnotationType . DECLARATION || annotationType == null ) { moveBefore . add ( annotation ) ; } else { moveAfter . add ( annotation ) ; } } } if ( annotationProblem ) { for ( AnnotationTree annotation : moveBefore ) { builder . delete ( annotation ) ; } for ( AnnotationTree annotation : moveAfter ) { builder . delete ( annotation ) ; } String javadoc = danglingJavadoc == null ? "" : removeJavadoc ( state , treePos , danglingJavadoc , builder ) ; builder . replace ( firstModifierPos , firstModifierPos , String . format ( "%s%s " , javadoc , joinSource ( state , moveBefore ) ) ) . replace ( lastModifierPos , lastModifierPos , String . format ( "%s " , joinSource ( state , moveAfter ) ) ) ; ImmutableList < String > names = annotations . stream ( ) . map ( ASTHelpers :: getSymbol ) . filter ( Objects :: nonNull ) . map ( Symbol :: getSimpleName ) . map ( a -> "@" + a ) . collect ( toImmutableList ( ) ) ; String flattened = names . stream ( ) . collect ( joining ( ", " ) ) ; String isAre = names . size ( ) > 1 ? "are not type annotations" : "is not a type annotation" ; String message = String . format ( "%s %s, so should appear before any modifiers and after Javadocs." , flattened , isAre ) ; return buildDescription ( tree ) . setMessage ( message ) . addFix ( builder . build ( ) ) . build ( ) ; } return NO_MATCH ; }
Checks that annotations are on the right side of the modifiers .
32,137
public static ExpressionTree getArgument ( AnnotationTree annotationTree , String name ) { for ( ExpressionTree argumentTree : annotationTree . getArguments ( ) ) { if ( argumentTree . getKind ( ) != Tree . Kind . ASSIGNMENT ) { continue ; } AssignmentTree assignmentTree = ( AssignmentTree ) argumentTree ; if ( ! assignmentTree . getVariable ( ) . toString ( ) . equals ( name ) ) { continue ; } ExpressionTree expressionTree = assignmentTree . getExpression ( ) ; return expressionTree ; } return null ; }
Gets the value for an argument or null if the argument does not exist .
32,138
public boolean isAcceptableChange ( Changes changes , Tree node , MethodSymbol symbol , VisitorState state ) { return findReverseWordsMatchInParentNodes ( state ) == null ; }
Return true if this call is not enclosed in a method call about reversing things
32,139
private static boolean ignore ( MethodTree method , VisitorState state ) { return firstNonNull ( new TreeScanner < Boolean , Void > ( ) { public Boolean visitBlock ( BlockTree tree , Void unused ) { switch ( tree . getStatements ( ) . size ( ) ) { case 0 : return true ; case 1 : return scan ( getOnlyElement ( tree . getStatements ( ) ) , null ) ; default : return false ; } } public Boolean visitReturn ( ReturnTree tree , Void unused ) { return scan ( tree . getExpression ( ) , null ) ; } public Boolean visitExpressionStatement ( ExpressionStatementTree tree , Void unused ) { return scan ( tree . getExpression ( ) , null ) ; } public Boolean visitTypeCast ( TypeCastTree tree , Void unused ) { return scan ( tree . getExpression ( ) , null ) ; } public Boolean visitMethodInvocation ( MethodInvocationTree node , Void aVoid ) { ExpressionTree receiver = ASTHelpers . getReceiver ( node ) ; return receiver instanceof IdentifierTree && ( ( IdentifierTree ) receiver ) . getName ( ) . contentEquals ( "super" ) && overrides ( ASTHelpers . getSymbol ( method ) , ASTHelpers . getSymbol ( node ) ) ; } private boolean overrides ( MethodSymbol sym , MethodSymbol other ) { return ! sym . isStatic ( ) && ! other . isStatic ( ) && ( ( ( sym . flags ( ) | other . flags ( ) ) & Flags . SYNTHETIC ) == 0 ) && sym . name . contentEquals ( other . name ) && sym . overrides ( other , sym . owner . enclClass ( ) , state . getTypes ( ) , false ) ; } } . scan ( method . getBody ( ) , null ) , false ) ; }
Don t flag methods that are empty or trivially delegate to a super - implementation .
32,140
private Fix buildFix ( Tree tree , List < ? extends Tree > arguments , VisitorState state ) { JCTree node = ( JCTree ) tree ; int startAbsolute = node . getStartPosition ( ) ; int lower = ( ( JCTree ) arguments . get ( 0 ) ) . getStartPosition ( ) - startAbsolute ; int upper = state . getEndPosition ( arguments . get ( arguments . size ( ) - 1 ) ) - startAbsolute ; CharSequence source = state . getSourceForNode ( node ) ; while ( lower >= 0 && source . charAt ( lower ) != '<' ) { lower -- ; } while ( upper < source . length ( ) && source . charAt ( upper ) != '>' ) { upper ++ ; } verify ( source . charAt ( lower ) == '<' && source . charAt ( upper ) == '>' ) ; Fix fix = SuggestedFix . replace ( startAbsolute + lower , startAbsolute + upper + 1 , "" ) ; return fix ; }
Constructor a fix that deletes the set of type arguments .
32,141
private String valueArgumentFromCompatibleWithAnnotation ( AnnotationTree tree ) { ExpressionTree argumentValue = Iterables . getOnlyElement ( tree . getArguments ( ) ) ; if ( argumentValue . getKind ( ) != Kind . ASSIGNMENT ) { return null ; } return ASTHelpers . constValue ( ( ( AssignmentTree ) argumentValue ) . getExpression ( ) , String . class ) ; }
is required .
32,142
public static < T > Choice < T > fromOptional ( Optional < T > optional ) { return optional . isPresent ( ) ? of ( optional . get ( ) ) : Choice . < T > none ( ) ; }
Returns a choice of the optional value if it is present or the empty choice if it is absent .
32,143
public static < T > Choice < T > any ( final Collection < Choice < T > > choices ) { return from ( choices ) . thenChoose ( Functions . < Choice < T > > identity ( ) ) ; }
Returns a choice between any of the options from any of the specified choices .
32,144
public < R > Choice < R > transform ( final Function < ? super T , R > function ) { checkNotNull ( function ) ; final Choice < T > thisChoice = this ; return new Choice < R > ( ) { protected Iterator < R > iterator ( ) { return Iterators . transform ( thisChoice . iterator ( ) , function ) ; } } ; }
Maps the choices with the specified function .
32,145
public static ImmutableList < ErrorProneToken > getTokens ( String source , Context context ) { return new ErrorProneTokens ( source , context ) . getTokens ( ) ; }
Returns the tokens for the given source text including comments .
32,146
private static Matcher < AnnotationTree > hasAnyParameter ( String ... parameters ) { return anyOf ( transform ( asList ( parameters ) , new Function < String , Matcher < AnnotationTree > > ( ) { public Matcher < AnnotationTree > apply ( String parameter ) { return hasArgumentWithValue ( parameter , Matchers . < ExpressionTree > anything ( ) ) ; } } ) ) ; }
Matches an annotation that has an argument for at least one of the given parameters .
32,147
static SuggestedFix . Builder makeConcreteClassAbstract ( ClassTree classTree , VisitorState state ) { Set < Modifier > flags = EnumSet . noneOf ( Modifier . class ) ; flags . addAll ( classTree . getModifiers ( ) . getFlags ( ) ) ; boolean wasFinal = flags . remove ( FINAL ) ; boolean wasAbstract = ! flags . add ( ABSTRACT ) ; if ( classTree . getKind ( ) . equals ( INTERFACE ) || ( ! wasFinal && wasAbstract ) ) { return SuggestedFix . builder ( ) ; } ImmutableList . Builder < Object > modifiers = ImmutableList . builder ( ) ; for ( AnnotationTree annotation : classTree . getModifiers ( ) . getAnnotations ( ) ) { modifiers . add ( state . getSourceForNode ( annotation ) ) ; } modifiers . addAll ( flags ) ; SuggestedFix . Builder makeAbstract = SuggestedFix . builder ( ) ; if ( ( ( JCModifiers ) classTree . getModifiers ( ) ) . pos == - 1 ) { makeAbstract . prefixWith ( classTree , Joiner . on ( ' ' ) . join ( modifiers . build ( ) ) ) ; } else { makeAbstract . replace ( classTree . getModifiers ( ) , Joiner . on ( ' ' ) . join ( modifiers . build ( ) ) ) ; } if ( wasFinal && HAS_GENERATED_CONSTRUCTOR . matches ( classTree , state ) ) { makeAbstract . merge ( addPrivateConstructor ( classTree ) ) ; } return makeAbstract ; }
Returns a fix that changes a concrete class to an abstract class .
32,148
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 class method or field declaration .
32,149
public static Optional < SuggestedFix > removeModifiers ( Tree tree , VisitorState state , Modifier ... modifiers ) { Set < Modifier > toRemove = ImmutableSet . copyOf ( modifiers ) ; ModifiersTree originalModifiers = getModifiers ( tree ) ; if ( originalModifiers == null ) { return Optional . empty ( ) ; } return removeModifiers ( originalModifiers , state , toRemove ) ; }
Remove modifiers from the given class method or field declaration .
32,150
public static String qualifyType ( VisitorState state , SuggestedFix . Builder fix , TypeMirror type ) { return type . accept ( new SimpleTypeVisitor8 < String , SuggestedFix . Builder > ( ) { protected String defaultAction ( TypeMirror e , Builder builder ) { return e . toString ( ) ; } public String visitArray ( ArrayType t , Builder builder ) { return t . getComponentType ( ) . accept ( this , builder ) + "[]" ; } public String visitDeclared ( DeclaredType t , 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 ) ; }
Returns a human - friendly name of the given type for use in fixes .
32,151
public static SuggestedFix renameMethod ( MethodTree tree , final String replacement , VisitorState state ) { int basePos = ( ( JCTree ) tree ) . getStartPosition ( ) ; int endPos = tree . getBody ( ) != null ? ( ( JCTree ) tree . getBody ( ) ) . getStartPosition ( ) : state . getEndPosition ( tree ) ; List < ErrorProneToken > methodTokens = ErrorProneTokens . getTokens ( state . getSourceCode ( ) . subSequence ( basePos , endPos ) . toString ( ) , state . context ) ; for ( ErrorProneToken token : methodTokens ) { if ( token . kind ( ) == TokenKind . IDENTIFIER && token . name ( ) . equals ( tree . getName ( ) ) ) { int nameStartPosition = basePos + token . pos ( ) ; int nameEndPosition = basePos + token . endPos ( ) ; return SuggestedFix . builder ( ) . replace ( nameStartPosition , nameEndPosition , replacement ) . build ( ) ; } } throw new AssertionError ( ) ; }
Be warned only changes method name at the declaration .
32,152
public static Fix deleteExceptions ( MethodTree tree , final 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 = FluentIterable . from ( tree . getThrows ( ) ) . filter ( Predicates . not ( Predicates . in ( toDelete ) ) ) . transform ( new Function < ExpressionTree , String > ( ) { public String apply ( ExpressionTree input ) { return state . getSourceForNode ( input ) ; } } ) . join ( Joiner . on ( ", " ) ) ; return SuggestedFix . replace ( ( ( JCTree ) tree . getThrows ( ) . get ( 0 ) ) . getStartPosition ( ) , state . getEndPosition ( getLast ( tree . getThrows ( ) ) ) , replacement ) ; }
Deletes the given exceptions from a method s throws clause .
32,153
public static boolean compilesWithFix ( Fix fix , VisitorState state ) { if ( fix . isEmpty ( ) ) { return true ; } JCCompilationUnit compilationUnit = ( JCCompilationUnit ) state . getPath ( ) . getCompilationUnit ( ) ; JavaFileObject modifiedFile = compilationUnit . getSourceFile ( ) ; BasicJavacTask javacTask = ( BasicJavacTask ) state . context . get ( JavacTask . class ) ; if ( javacTask == null ) { throw new IllegalArgumentException ( "No JavacTask in context." ) ; } Arguments arguments = Arguments . instance ( javacTask . getContext ( ) ) ; List < JavaFileObject > fileObjects = new ArrayList < > ( arguments . getFileObjects ( ) ) ; for ( int i = 0 ; i < fileObjects . size ( ) ; i ++ ) { final JavaFileObject oldFile = fileObjects . get ( i ) ; if ( modifiedFile . toUri ( ) . equals ( oldFile . toUri ( ) ) ) { DescriptionBasedDiff diff = DescriptionBasedDiff . create ( compilationUnit , ImportOrganizer . STATIC_FIRST_ORGANIZER ) ; diff . handleFix ( fix ) ; SourceFile fixSource ; try { fixSource = new SourceFile ( modifiedFile . getName ( ) , modifiedFile . getCharContent ( false ) ) ; } catch ( IOException e ) { return false ; } diff . applyDifferences ( fixSource ) ; fileObjects . set ( i , new SimpleJavaFileObject ( sourceURI ( modifiedFile . toUri ( ) ) , Kind . SOURCE ) { public CharSequence getCharContent ( boolean ignoreEncodingErrors ) throws IOException { return fixSource . getAsSequence ( ) ; } } ) ; break ; } } DiagnosticCollector < JavaFileObject > diagnosticListener = new DiagnosticCollector < > ( ) ; 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" ) ) { continue ; } options . put ( key , value ) ; } JavacTask newTask = JavacTool . create ( ) . getTask ( CharStreams . nullWriter ( ) , state . context . get ( JavaFileManager . class ) , diagnosticListener , ImmutableList . of ( ) , arguments . getClassNames ( ) , fileObjects , context ) ; try { newTask . analyze ( ) ; } catch ( IOException e ) { throw new UncheckedIOException ( e ) ; } return countErrors ( diagnosticListener ) == 0 ; }
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 .
32,154
public static Optional < SuggestedFix > suggestWhitelistAnnotation ( String whitelistAnnotation , TreePath where , VisitorState state ) { if ( whitelistAnnotation . equals ( "com.google.errorprone.annotations.DontSuggestFixes" ) ) { return Optional . empty ( ) ; } SuggestedFix . Builder builder = SuggestedFix . builder ( ) ; Type whitelistAnnotationType = state . getTypeFromString ( whitelistAnnotation ) ; ImmutableSet < Tree . Kind > supportedWhitelistLocationKinds ; String annotationName ; if ( whitelistAnnotationType != null ) { supportedWhitelistLocationKinds = supportedTreeTypes ( whitelistAnnotationType . asElement ( ) ) ; annotationName = qualifyType ( state , builder , whitelistAnnotationType ) ; } else { int idx = whitelistAnnotation . lastIndexOf ( '.' ) ; Verify . verify ( idx > 0 && idx + 1 < whitelistAnnotation . length ( ) ) ; supportedWhitelistLocationKinds = TREE_TYPE_UNKNOWN_ANNOTATION ; annotationName = whitelistAnnotation . substring ( idx + 1 ) ; builder . addImport ( whitelistAnnotation ) ; } Optional < Tree > whitelistLocation = StreamSupport . stream ( where . spliterator ( ) , false ) . filter ( tree -> supportedWhitelistLocationKinds . contains ( tree . getKind ( ) ) ) . filter ( Predicates . not ( SuggestedFixes :: isAnonymousClassTree ) ) . findFirst ( ) ; return whitelistLocation . map ( location -> builder . prefixWith ( location , "@" + annotationName + " " ) . build ( ) ) ; }
Create a fix to add a suppression annotation on the surrounding class .
32,155
public SuppressedState suppressedState ( Suppressible suppressible , boolean suppressedInGeneratedCode ) { if ( inGeneratedCode && suppressedInGeneratedCode ) { return SuppressedState . SUPPRESSED ; } if ( suppressible . supportsSuppressWarnings ( ) && ! Collections . disjoint ( suppressible . allNames ( ) , suppressWarningsStrings ) ) { return SuppressedState . SUPPRESSED ; } if ( ! Collections . disjoint ( suppressible . customSuppressionAnnotations ( ) , customSuppressions ) ) { return SuppressedState . SUPPRESSED ; } return SuppressedState . UNSUPPRESSED ; }
Returns true if this checker should be considered suppressed given the signals present in this object .
32,156
public static TypePredicate isExactTypeAny ( Iterable < String > types ) { return new ExactAny ( Iterables . transform ( types , GET_TYPE ) ) ; }
Match types that are exactly equal to any of the given types .
32,157
public static TypePredicate isDescendantOfAny ( Iterable < String > types ) { return new DescendantOfAny ( Iterables . transform ( types , GET_TYPE ) ) ; }
Match types that are a sub - type of one of the given types .
32,158
private static ExpressionTree stripNullCheck ( ExpressionTree expression , VisitorState state ) { if ( expression != null && expression . getKind ( ) == METHOD_INVOCATION ) { MethodInvocationTree methodInvocation = ( MethodInvocationTree ) expression ; if ( NON_NULL_MATCHER . matches ( methodInvocation , state ) ) { return methodInvocation . getArguments ( ) . get ( 0 ) ; } } return expression ; }
If the given expression is a call to a method checking the nullity of its first parameter and otherwise returns that parameter .
32,159
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" ) ; } }
Returns a copy of code as a list of lines .
32,160
public void replaceLines ( List < String > lines ) { sourceBuilder . replace ( 0 , sourceBuilder . length ( ) , Joiner . on ( "\n" ) . join ( lines ) + "\n" ) ; }
Replace the source code with the new lines of code .
32,161
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 ) { } else { newLines . add ( originalLines . get ( i ) ) ; } } replaceLines ( newLines ) ; }
Replace the source code between the start and end lines with some new lines of code .
32,162
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 ) ) ; } }
Replace the source code between the start and end character positions with a new string .
32,163
boolean isAssignableTo ( Parameter target , VisitorState state ) { if ( state . getTypes ( ) . isSameType ( type ( ) , Type . noType ) || state . getTypes ( ) . isSameType ( target . type ( ) , Type . noType ) ) { return false ; } try { return state . getTypes ( ) . isAssignable ( type ( ) , target . type ( ) ) ; } catch ( CompletionFailure e ) { Check . instance ( state . context ) . completionError ( ( DiagnosticPosition ) state . getPath ( ) . getLeaf ( ) , e ) ; return false ; } }
Return true if this parameter is assignable to the target parameter . This will consider subclassing autoboxing and null .
32,164
static String getArgumentName ( ExpressionTree expressionTree ) { switch ( expressionTree . getKind ( ) ) { case MEMBER_SELECT : return ( ( MemberSelectTree ) expressionTree ) . getIdentifier ( ) . toString ( ) ; case NULL_LITERAL : return NAME_NULL ; case IDENTIFIER : IdentifierTree idTree = ( IdentifierTree ) expressionTree ; if ( idTree . getName ( ) . contentEquals ( "this" ) ) { Symbol sym = ASTHelpers . getSymbol ( idTree ) ; return sym != null ? getClassName ( ASTHelpers . enclosingClass ( sym ) ) : NAME_NOT_PRESENT ; } else { return idTree . getName ( ) . toString ( ) ; } case METHOD_INVOCATION : MethodInvocationTree methodInvocationTree = ( MethodInvocationTree ) expressionTree ; MethodSymbol methodSym = ASTHelpers . getSymbol ( methodInvocationTree ) ; if ( methodSym != null ) { String name = methodSym . getSimpleName ( ) . toString ( ) ; List < String > terms = NamingConventions . splitToLowercaseTerms ( name ) ; String firstTerm = Iterables . getFirst ( terms , null ) ; if ( METHODNAME_PREFIXES_TO_REMOVE . contains ( firstTerm ) ) { if ( terms . size ( ) == 1 ) { ExpressionTree receiver = ASTHelpers . getReceiver ( methodInvocationTree ) ; if ( receiver == null ) { return getClassName ( ASTHelpers . enclosingClass ( methodSym ) ) ; } return getArgumentName ( receiver ) ; } else { return name . substring ( firstTerm . length ( ) ) ; } } else { return name ; } } else { return NAME_NOT_PRESENT ; } case NEW_CLASS : MethodSymbol constructorSym = ASTHelpers . getSymbol ( ( NewClassTree ) expressionTree ) ; return constructorSym != null && constructorSym . owner != null ? getClassName ( ( ClassSymbol ) constructorSym . owner ) : NAME_NOT_PRESENT ; default : return NAME_NOT_PRESENT ; } }
Extract the name from an argument .
32,165
private void buildFix ( Description . Builder builder , MethodInvocationTree tree , VisitorState state ) { MethodInvocationTree mockitoCall = tree ; List < ? extends ExpressionTree > args = mockitoCall . getArguments ( ) ; Tree mock = mockitoCall . getArguments ( ) . get ( 0 ) ; boolean isVerify = ASTHelpers . getSymbol ( tree ) . getSimpleName ( ) . contentEquals ( "verify" ) ; if ( isVerify && mock . getKind ( ) == Kind . METHOD_INVOCATION ) { MethodInvocationTree invocation = ( MethodInvocationTree ) mock ; String verify = state . getSourceForNode ( mockitoCall . getMethodSelect ( ) ) ; String receiver = state . getSourceForNode ( ASTHelpers . getReceiver ( invocation ) ) ; String mode = args . size ( ) > 1 ? ", " + state . getSourceForNode ( args . get ( 1 ) ) : "" ; String call = state . getSourceForNode ( invocation ) . substring ( receiver . length ( ) ) ; builder . addFix ( SuggestedFix . replace ( tree , String . format ( "%s(%s%s)%s" , verify , receiver , mode , call ) ) ) ; } if ( isVerify && args . size ( ) > 1 && NEVER_METHOD . matches ( args . get ( 1 ) , state ) ) { builder . addFix ( SuggestedFix . builder ( ) . addStaticImport ( "org.mockito.Mockito.verifyZeroInteractions" ) . replace ( tree , String . format ( "verifyZeroInteractions(%s)" , mock ) ) . build ( ) ) ; } Tree parent = state . getPath ( ) . getParentPath ( ) . getLeaf ( ) ; if ( parent . getKind ( ) == Kind . EXPRESSION_STATEMENT ) { builder . addFix ( SuggestedFix . delete ( parent ) ) ; } else { builder . addFix ( SuggestedFix . delete ( tree ) ) ; } }
Create fixes for invalid assertions .
32,166
public Description matchMethod ( MethodTree methodTree , VisitorState state ) { SuggestedFix . Builder fix = null ; if ( isInjectedConstructor ( methodTree , state ) ) { for ( AnnotationTree annotationTree : methodTree . getModifiers ( ) . getAnnotations ( ) ) { if ( OPTIONAL_INJECTION_MATCHER . matches ( annotationTree , state ) ) { if ( fix == null ) { fix = SuggestedFix . builder ( ) ; } fix = fix . replace ( annotationTree , "@Inject" ) ; } else if ( BINDING_ANNOTATION_MATCHER . matches ( annotationTree , state ) ) { if ( fix == null ) { fix = SuggestedFix . builder ( ) ; } fix = fix . delete ( annotationTree ) ; } } } if ( fix == null ) { return Description . NO_MATCH ; } else { return describeMatch ( methodTree , fix . build ( ) ) ; } }
Matches injected constructors annotated with
32,167
private static List < TypeVariableSymbol > typeVariablesEnclosing ( Symbol sym ) { List < TypeVariableSymbol > typeVarScopes = new ArrayList < > ( ) ; outer : while ( ! sym . isStatic ( ) ) { sym = sym . owner ; switch ( sym . getKind ( ) ) { case PACKAGE : break outer ; case METHOD : case CLASS : typeVarScopes . addAll ( sym . getTypeParameters ( ) ) ; break ; default : } } return typeVarScopes ; }
Get list of type params of every enclosing class
32,168
protected List < Type > actualTypes ( Inliner inliner ) { ArrayList < Type > result = new ArrayList < > ( ) ; ImmutableList < String > argNames = expressionArgumentTypes ( ) . keySet ( ) . asList ( ) ; for ( int i = 0 ; i < expressionArgumentTypes ( ) . size ( ) ; i ++ ) { String argName = argNames . get ( i ) ; Optional < JCExpression > singleBinding = inliner . getOptionalBinding ( new UFreeIdent . Key ( argName ) ) ; if ( singleBinding . isPresent ( ) ) { result . add ( singleBinding . get ( ) . type ) ; } else { Optional < java . util . List < JCExpression > > exprs = inliner . getOptionalBinding ( new URepeated . Key ( argName ) ) ; if ( exprs . isPresent ( ) && ! exprs . get ( ) . isEmpty ( ) ) { Type [ ] exprTys = new Type [ exprs . get ( ) . size ( ) ] ; for ( int j = 0 ; j < exprs . get ( ) . size ( ) ; j ++ ) { exprTys [ j ] = exprs . get ( ) . get ( j ) . type ; } result . add ( inliner . types ( ) . lub ( List . from ( exprTys ) ) ) ; } } } for ( PlaceholderExpressionKey key : Ordering . natural ( ) . immutableSortedCopy ( Iterables . filter ( inliner . bindings . keySet ( ) , PlaceholderExpressionKey . class ) ) ) { result . add ( inliner . getBinding ( key ) . type ) ; } return List . from ( result ) ; }
Returns a list of the actual types to be matched . This consists of the types of the expressions bound to the
32,169
private Type infer ( Warner warner , Inliner inliner , List < Type > freeTypeVariables , List < Type > expectedArgTypes , Type returnType , List < Type > actualArgTypes ) throws InferException { Symtab symtab = inliner . symtab ( ) ; Type methodType = new MethodType ( expectedArgTypes , returnType , List . < Type > nil ( ) , symtab . methodClass ) ; if ( ! freeTypeVariables . isEmpty ( ) ) { methodType = new ForAll ( freeTypeVariables , methodType ) ; } Enter enter = inliner . enter ( ) ; MethodSymbol methodSymbol = new MethodSymbol ( 0 , inliner . asName ( "__m__" ) , methodType , symtab . unknownSymbol ) ; Type site = symtab . methodClass . type ; Env < AttrContext > env = enter . getTopLevelEnv ( TreeMaker . instance ( inliner . getContext ( ) ) . TopLevel ( List . < JCTree > nil ( ) ) ) ; try { Field field = AttrContext . class . getDeclaredField ( "pendingResolutionPhase" ) ; field . setAccessible ( true ) ; field . set ( env . info , newMethodResolutionPhase ( autoboxing ( ) ) ) ; } catch ( ReflectiveOperationException e ) { throw new LinkageError ( e . getMessage ( ) , e ) ; } Object resultInfo ; try { Class < ? > resultInfoClass = Class . forName ( "com.sun.tools.javac.comp.Attr$ResultInfo" ) ; Constructor < ? > resultInfoCtor = resultInfoClass . getDeclaredConstructor ( Attr . class , KindSelector . class , Type . class ) ; resultInfoCtor . setAccessible ( true ) ; resultInfo = resultInfoCtor . newInstance ( Attr . instance ( inliner . getContext ( ) ) , KindSelector . PCK , Type . noType ) ; } catch ( ReflectiveOperationException e ) { throw new LinkageError ( e . getMessage ( ) , e ) ; } Log . DeferredDiagnosticHandler handler = new Log . DeferredDiagnosticHandler ( Log . instance ( inliner . getContext ( ) ) ) ; try { MethodType result = callCheckMethod ( warner , inliner , resultInfo , actualArgTypes , methodSymbol , site , env ) ; if ( ! handler . getDiagnostics ( ) . isEmpty ( ) ) { throw new InferException ( handler . getDiagnostics ( ) ) ; } return result ; } finally { Log . instance ( inliner . getContext ( ) ) . popDiagnosticHandler ( handler ) ; } }
Returns the inferred method type of the template based on the given actual argument types .
32,170
private boolean populateTypesToEnforce ( MethodSymbol declaredMethod , Type calledMethodType , Type calledReceiverType , List < RequiredType > argumentTypeRequirements , VisitorState state ) { boolean foundAnyTypeToEnforce = false ; List < VarSymbol > params = declaredMethod . params ( ) ; for ( int i = 0 ; i < params . size ( ) ; i ++ ) { VarSymbol varSymbol = params . get ( i ) ; CompatibleWith anno = ASTHelpers . getAnnotation ( varSymbol , CompatibleWith . class ) ; if ( anno != null ) { foundAnyTypeToEnforce = true ; RequiredType requiredType = resolveRequiredTypeForThisCall ( state , calledMethodType , calledReceiverType , declaredMethod , anno . value ( ) ) ; if ( declaredMethod . isVarArgs ( ) && i == params . size ( ) - 1 ) { if ( i >= argumentTypeRequirements . size ( ) ) { break ; } else { for ( int j = i ; j < argumentTypeRequirements . size ( ) ; j ++ ) { argumentTypeRequirements . set ( j , requiredType ) ; } } } else { argumentTypeRequirements . set ( i , requiredType ) ; } } } return foundAnyTypeToEnforce ; }
caller should explore super - methods .
32,171
public static String classDescriptor ( Type type , Types types ) { SigGen sig = new SigGen ( types ) ; sig . assembleClassSig ( types . erasure ( type ) ) ; return sig . toString ( ) ; }
Returns the binary names of the class .
32,172
public static String descriptor ( Type type , Types types ) { SigGen sig = new SigGen ( types ) ; sig . assembleSig ( types . erasure ( type ) ) ; return sig . toString ( ) ; }
Returns a JVMS 4 . 3 . 3 method descriptor .
32,173
public static String prettyMethodSignature ( ClassSymbol origin , MethodSymbol m ) { StringBuilder sb = new StringBuilder ( ) ; if ( m . isConstructor ( ) ) { Name name = m . owner . enclClass ( ) . getSimpleName ( ) ; if ( name . isEmpty ( ) ) { 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 method signature for use in diagnostics .
32,174
private static char [ ] asUnicodeHexEscape ( char c ) { char [ ] r = new char [ 6 ] ; r [ 0 ] = '\\' ; r [ 1 ] = 'u' ; r [ 5 ] = HEX_DIGITS [ c & 0xF ] ; c >>>= 4 ; r [ 4 ] = HEX_DIGITS [ c & 0xF ] ; c >>>= 4 ; r [ 3 ] = HEX_DIGITS [ c & 0xF ] ; c >>>= 4 ; r [ 2 ] = HEX_DIGITS [ c & 0xF ] ; return r ; }
Helper for common case of escaping a single char .
32,175
private static String identifyBadCast ( Type lhs , Type rhs , Types types ) { if ( ! lhs . isPrimitive ( ) ) { return null ; } if ( types . isConvertible ( rhs , lhs ) ) { return null ; } return String . format ( "Compound assignments from %s to %s hide lossy casts" , prettyType ( rhs ) , prettyType ( lhs ) ) ; }
Classifies bad casts .
32,176
private static Optional < Fix > rewriteCompoundAssignment ( CompoundAssignmentTree tree , VisitorState state ) { CharSequence var = state . getSourceForNode ( tree . getVariable ( ) ) ; CharSequence expr = state . getSourceForNode ( tree . getExpression ( ) ) ; if ( var == null || expr == null ) { return Optional . absent ( ) ; } switch ( tree . getKind ( ) ) { case RIGHT_SHIFT_ASSIGNMENT : return Optional . absent ( ) ; default : break ; } Kind regularAssignmentKind = regularAssignmentFromCompound ( tree . getKind ( ) ) ; String op = assignmentToString ( regularAssignmentKind ) ; OperatorPrecedence rhsPrecedence = tree . getExpression ( ) instanceof JCBinary ? OperatorPrecedence . from ( tree . getExpression ( ) . getKind ( ) ) : tree . getExpression ( ) instanceof ConditionalExpressionTree ? OperatorPrecedence . TERNARY : null ; if ( rhsPrecedence != null ) { if ( ! rhsPrecedence . isHigher ( OperatorPrecedence . from ( regularAssignmentKind ) ) ) { expr = String . format ( "(%s)" , expr ) ; } } String castType = getType ( tree . getVariable ( ) ) . toString ( ) ; String replacement = String . format ( "%s = (%s) (%s %s %s)" , var , castType , var , op , expr ) ; return Optional . of ( SuggestedFix . replace ( tree , replacement ) ) ; }
Desugars a compound assignment making the cast explicit .
32,177
public static Supplier < Type > typeFromString ( final String typeString ) { requireNonNull ( typeString ) ; return new Supplier < Type > ( ) { public Type get ( VisitorState state ) { return state . getTypeFromString ( typeString ) ; } } ; }
Given the string representation of a type supplies the corresponding type .
32,178
public static < T > Supplier < T > identitySupplier ( final T toSupply ) { return new Supplier < T > ( ) { public T get ( VisitorState state ) { return toSupply ; } } ; }
Supplies what was given . Useful for adapting to methods that require a supplier .
32,179
public boolean isAcceptableChange ( Changes changes , Tree node , MethodSymbol symbol , VisitorState state ) { return findArgumentsForOtherInstances ( symbol , node , state ) . stream ( ) . allMatch ( arguments -> ! anyArgumentsMatch ( changes . changedPairs ( ) , arguments ) ) ; }
Returns true if there are no other calls to this method which already have an actual parameter in the position we are moving this one too .
32,180
private static boolean anyArgumentsMatch ( List < ParameterPair > changedPairs , List < Parameter > arguments ) { return changedPairs . stream ( ) . anyMatch ( change -> Objects . equals ( change . actual ( ) . text ( ) , arguments . get ( change . formal ( ) . index ( ) ) . text ( ) ) ) ; }
Return true if the replacement name is equal to the argument name for any replacement position .
32,181
private String methodReferenceDescriptor ( Types types , MethodSymbol sym ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( sym . getSimpleName ( ) ) . append ( '(' ) ; if ( ! sym . isStatic ( ) ) { sb . append ( Signatures . descriptor ( sym . owner . type , types ) ) ; } sym . params ( ) . stream ( ) . map ( p -> Signatures . descriptor ( p . type , types ) ) . forEachOrdered ( sb :: append ) ; sb . append ( ")" ) ; return sb . toString ( ) ; }
Returns a string descriptor of a method s reference type .
32,182
private static boolean localVariableMatches ( VariableTree tree , VisitorState state ) { ExpressionTree expression = tree . getInitializer ( ) ; if ( expression == null ) { Tree leaf = state . getPath ( ) . getParentPath ( ) . getLeaf ( ) ; if ( ! ( leaf instanceof EnhancedForLoopTree ) ) { return true ; } EnhancedForLoopTree node = ( EnhancedForLoopTree ) leaf ; Type expressionType = ASTHelpers . getType ( node . getExpression ( ) ) ; if ( expressionType == null ) { return false ; } Type elemtype = state . getTypes ( ) . elemtype ( expressionType ) ; return elemtype != null && elemtype . isPrimitive ( ) ; } Type initializerType = ASTHelpers . getType ( expression ) ; if ( initializerType == null ) { return false ; } if ( initializerType . isPrimitive ( ) ) { return true ; } return VALUE_OF_MATCHER . matches ( expression , state ) ; }
Check to see if the local variable should be considered for replacement i . e .
32,183
ToStringKind isToString ( Tree parent , ExpressionTree tree , VisitorState state ) { if ( isStringConcat ( parent , state ) ) { return ToStringKind . IMPLICIT ; } if ( parent instanceof ExpressionTree ) { ExpressionTree parentExpression = ( ExpressionTree ) parent ; if ( PRINT_STRING . matches ( parentExpression , state ) ) { return ToStringKind . IMPLICIT ; } if ( VALUE_OF . matches ( parentExpression , state ) ) { return ToStringKind . EXPLICIT ; } } return ToStringKind . NONE ; }
Classifies expressions that are converted to strings by their enclosing expression .
32,184
private static boolean newFluentChain ( ExpressionTree tree , VisitorState state ) { while ( tree instanceof MethodInvocationTree && FLUENT_CHAIN . matches ( tree , state ) ) { tree = getReceiver ( tree ) ; } return tree != null && FLUENT_CONSTRUCTOR . matches ( tree , state ) ; }
Whether this is a chain of method invocations terminating in a new proto or collection builder .
32,185
public static boolean isAnnotation ( VisitorState state , Type type ) { return isAssignableTo ( type , Suppliers . ANNOTATION_TYPE , state ) ; }
Returns true if the type is an annotation .
32,186
public String getMessageWithoutCheckName ( ) { return linkUrl != null ? String . format ( "%s\n%s" , rawMessage , linkTextForDiagnostic ( linkUrl ) ) : String . format ( "%s" , rawMessage ) ; }
Returns the message not including the check name but including the link .
32,187
public Description applySeverityOverride ( SeverityLevel severity ) { return new Description ( position , checkName , rawMessage , linkUrl , fixes , severity ) ; }
Internal - only . Has no effect if applied to a Description within a BugChecker .
32,188
public boolean isAcceptableChange ( Changes changes , Tree node , MethodSymbol symbol , VisitorState state ) { int numberOfChanges = changes . changedPairs ( ) . size ( ) ; return changes . totalOriginalCost ( ) - changes . totalAssignmentCost ( ) >= threshold * numberOfChanges ; }
Return true if the change is sufficiently different .
32,189
private static ImmutableList < ImportTree > getWildcardImports ( List < ? extends ImportTree > imports ) { ImmutableList . Builder < ImportTree > result = ImmutableList . builder ( ) ; for ( ImportTree tree : imports ) { Tree ident = tree . getQualifiedIdentifier ( ) ; if ( ! ( ident instanceof MemberSelectTree ) ) { continue ; } MemberSelectTree select = ( MemberSelectTree ) ident ; if ( select . getIdentifier ( ) . contentEquals ( "*" ) ) { result . add ( tree ) ; } } return result . build ( ) ; }
Collect all on demand imports .
32,190
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 . build ( ) ; }
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 .
32,191
public Optional < Nullness > getExprNullness ( ExpressionTree exprTree ) { InferenceVariable iv = TypeArgInferenceVar . create ( ImmutableList . of ( ) , exprTree ) ; return constraintGraph . nodes ( ) . contains ( iv ) ? getNullness ( iv ) : Optional . empty ( ) ; }
Get inferred nullness qualifier for an expression if possible .
32,192
@ SuppressWarnings ( "unchecked" ) public static < T > T fromXml ( Class < T > clazz , String xml ) { T object = ( T ) CLASS_2_XSTREAM_INSTANCE . get ( clazz ) . fromXML ( xml ) ; return object ; }
xml - > pojo
32,193
public static < T > String toXml ( Class < T > clazz , T object ) { return CLASS_2_XSTREAM_INSTANCE . get ( clazz ) . toXML ( object ) ; }
pojo - > xml
32,194
public void processExpires ( ) { long timeNow = System . currentTimeMillis ( ) ; InternalSession sessions [ ] = findSessions ( ) ; int expireHere = 0 ; if ( log . isDebugEnabled ( ) ) log . debug ( "Start expire sessions {} at {} sessioncount {}" , getName ( ) , timeNow , sessions . length ) ; for ( int i = 0 ; i < sessions . length ; i ++ ) { if ( sessions [ i ] != null && ! sessions [ i ] . isValid ( ) ) { expireHere ++ ; } } long timeEnd = System . currentTimeMillis ( ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "End expire sessions {} processingTime {} expired sessions: {}" , getName ( ) , timeEnd - timeNow , expireHere ) ; processingTime += ( timeEnd - timeNow ) ; }
Invalidate all sessions that have expired .
32,195
public String getString ( final String key , final Object ... args ) { String value = getString ( key ) ; if ( value == null ) { value = key ; } MessageFormat mf = new MessageFormat ( value ) ; mf . setLocale ( locale ) ; return mf . format ( args , new StringBuffer ( ) , null ) . toString ( ) ; }
Get a string from the underlying resource bundle and format it with the given set of arguments .
32,196
public int lookupIndex ( long entry ) { int ret = map . get ( entry ) ; if ( ret <= 0 && ! growthStopped ) { numEntries ++ ; ret = numEntries ; map . put ( entry , ret ) ; } return ret - 1 ; }
Return - 1 if entry isn t present .
32,197
public void init ( Path configFile ) { String abspath = configFile . toAbsolutePath ( ) . toString ( ) ; System . out . println ( "initialize user dictionary:" + abspath ) ; synchronized ( WordDictionary . class ) { if ( loadedPath . contains ( abspath ) ) return ; DirectoryStream < Path > stream ; try { stream = Files . newDirectoryStream ( configFile , String . format ( Locale . getDefault ( ) , "*%s" , USER_DICT_SUFFIX ) ) ; for ( Path path : stream ) { System . err . println ( String . format ( Locale . getDefault ( ) , "loading dict %s" , path . toString ( ) ) ) ; singleton . loadUserDict ( path ) ; } loadedPath . add ( abspath ) ; } catch ( IOException e ) { System . err . println ( String . format ( Locale . getDefault ( ) , "%s: load user dict failure!" , configFile . toString ( ) ) ) ; } } }
for ES to initialize the user dictionary .
32,198
public void wrap ( ImmutableRoaringBitmap r ) { this . roaringBitmap = r ; this . hs = 0 ; this . pos = ( short ) ( this . roaringBitmap . highLowContainer . size ( ) - 1 ) ; this . nextContainer ( ) ; }
Prepares a bitmap for iteration
32,199
protected void appendCopy ( RoaringArray sa , int index ) { extendArray ( 1 ) ; this . keys [ this . size ] = sa . keys [ index ] ; this . values [ this . size ] = sa . values [ index ] . clone ( ) ; this . size ++ ; }
Append copy of the one value from another array