idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
153,100
public void addOption ( String option , String argumentDesc , String description ) { optionList . add ( option ) ; optionDescriptionMap . put ( option , description ) ; requiresArgumentSet . add ( option ) ; argumentDescriptionMap . put ( option , argumentDesc ) ; int width = option . length ( ) + 3 + argumentDesc . length ( ) ; if ( width > maxWidth ) { maxWidth = width ; } }
Add an option requiring an argument .
90
7
153,101
public void printUsage ( OutputStream os ) { int count = 0 ; PrintStream out = UTF8 . printStream ( os ) ; for ( String option : optionList ) { if ( optionGroups . containsKey ( count ) ) { out . println ( " " + optionGroups . get ( count ) ) ; } count ++ ; if ( unlistedOptions . contains ( option ) ) { continue ; } out . print ( " " ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( option ) ; if ( optionExtraPartSynopsisMap . get ( option ) != null ) { String optionExtraPartSynopsis = optionExtraPartSynopsisMap . get ( option ) ; buf . append ( "[:" ) ; buf . append ( optionExtraPartSynopsis ) ; buf . append ( "]" ) ; } if ( requiresArgumentSet . contains ( option ) ) { buf . append ( " <" ) ; buf . append ( argumentDescriptionMap . get ( option ) ) ; buf . append ( ">" ) ; } printField ( out , buf . toString ( ) , maxWidth + 1 ) ; out . println ( optionDescriptionMap . get ( option ) ) ; } out . flush ( ) ; }
Print command line usage information to given stream .
256
9
153,102
public void setLockCount ( int valueNumber , int lockCount ) { int index = findIndex ( valueNumber ) ; if ( index < 0 ) { addEntry ( index , valueNumber , lockCount ) ; } else { array [ index + 1 ] = lockCount ; } }
Set the lock count for a lock object .
59
9
153,103
public int getNumLockedObjects ( ) { int result = 0 ; for ( int i = 0 ; i + 1 < array . length ; i += 2 ) { if ( array [ i ] == INVALID ) { break ; } if ( array [ i + 1 ] > 0 ) { ++ result ; } } return result ; }
Get the number of distinct lock values with positive lock counts .
72
12
153,104
public void copyFrom ( LockSet other ) { if ( other . array . length != array . length ) { array = new int [ other . array . length ] ; } System . arraycopy ( other . array , 0 , array , 0 , array . length ) ; this . defaultLockCount = other . defaultLockCount ; }
Make this LockSet the same as the given one .
69
11
153,105
public void meetWith ( LockSet other ) { for ( int i = 0 ; i + 1 < array . length ; i += 2 ) { int valueNumber = array [ i ] ; if ( valueNumber < 0 ) { break ; } int mine = array [ i + 1 ] ; int his = other . getLockCount ( valueNumber ) ; array [ i + 1 ] = mergeValues ( mine , his ) ; } for ( int i = 0 ; i + 1 < other . array . length ; i += 2 ) { int valueNumber = other . array [ i ] ; if ( valueNumber < 0 ) { break ; } int mine = getLockCount ( valueNumber ) ; int his = other . array [ i + 1 ] ; setLockCount ( valueNumber , mergeValues ( mine , his ) ) ; } setDefaultLockCount ( 0 ) ; }
Meet this LockSet with another LockSet storing the result in this object .
182
15
153,106
public boolean containsReturnValue ( ValueNumberFactory factory ) { for ( int i = 0 ; i + 1 < array . length ; i += 2 ) { int valueNumber = array [ i ] ; if ( valueNumber < 0 ) { break ; } int lockCount = array [ i + 1 ] ; if ( lockCount > 0 && factory . forNumber ( valueNumber ) . hasFlag ( ValueNumber . RETURN_VALUE ) ) { return true ; } } return false ; }
Determine whether or not this lock set contains any locked values which are method return values .
101
19
153,107
public boolean isEmpty ( ) { for ( int i = 0 ; i + 1 < array . length ; i += 2 ) { int valueNumber = array [ i ] ; if ( valueNumber < 0 ) { return true ; } int myLockCount = array [ i + 1 ] ; if ( myLockCount > 0 ) { return false ; } } return true ; }
Return whether or not this lock set is empty meaning that no locks have a positive lock count .
78
19
153,108
public SimplePathEnumerator enumerate ( ) { Iterator < Edge > entryOut = cfg . outgoingEdgeIterator ( cfg . getEntry ( ) ) ; if ( ! entryOut . hasNext ( ) ) { throw new IllegalStateException ( ) ; } Edge entryEdge = entryOut . next ( ) ; LinkedList < Edge > init = new LinkedList <> ( ) ; init . add ( entryEdge ) ; work ( init ) ; if ( DEBUG && work == maxWork ) { System . out . println ( "**** Reached max work! ****" ) ; } return this ; }
Enumerate the simple paths .
128
7
153,109
@ Override public void visitClassContext ( ClassContext classContext ) { int majorVersion = classContext . getJavaClass ( ) . getMajor ( ) ; if ( majorVersion >= Const . MAJOR_1_5 && hasInterestingMethod ( classContext . getJavaClass ( ) . getConstantPool ( ) , methods ) ) { super . visitClassContext ( classContext ) ; } }
The detector is only meaningful for Java5 class libraries .
85
11
153,110
public static Collection < AnnotationValue > resolveTypeQualifiers ( AnnotationValue value ) { LinkedList < AnnotationValue > result = new LinkedList <> ( ) ; resolveTypeQualifierNicknames ( value , result , new LinkedList < ClassDescriptor > ( ) ) ; return result ; }
Resolve an AnnotationValue into a list of AnnotationValues representing type qualifier annotations .
67
18
153,111
public void mergeVertices ( Set < VertexType > vertexSet , GraphType g , VertexCombinator < VertexType > combinator , GraphToolkit < GraphType , EdgeType , VertexType > toolkit ) { // Special case: if the vertex set contains a single vertex // or is empty, there is nothing to do if ( vertexSet . size ( ) <= 1 ) { return ; } // Get all vertices to which we have outgoing edges // or from which we have incoming edges, since they'll need // to be fixed TreeSet < EdgeType > edgeSet = new TreeSet <> ( ) ; for ( Iterator < EdgeType > i = g . edgeIterator ( ) ; i . hasNext ( ) ; ) { EdgeType e = i . next ( ) ; if ( vertexSet . contains ( e . getSource ( ) ) || vertexSet . contains ( e . getTarget ( ) ) ) { edgeSet . add ( e ) ; } } // Combine all of the vertices into a single composite vertex VertexType compositeVertex = combinator . combineVertices ( vertexSet ) ; // For each original edge into or out of the vertex set, // create an equivalent edge referencing the composite // vertex for ( EdgeType e : edgeSet ) { VertexType source = vertexSet . contains ( e . getSource ( ) ) ? compositeVertex : e . getSource ( ) ; VertexType target = vertexSet . contains ( e . getTarget ( ) ) ? compositeVertex : e . getTarget ( ) ; // if (source != compositeVertex && target != compositeVertex) // System.out.println("BIG OOPS!"); // Don't create a self edge for the composite vertex // unless one of the vertices in the vertex set // had a self edge if ( source == compositeVertex && target == compositeVertex && e . getSource ( ) != e . getTarget ( ) ) { continue ; } // Don't create duplicate edges. if ( g . lookupEdge ( source , target ) != null ) { continue ; } EdgeType compositeEdge = g . createEdge ( source , target ) ; // FIXME: we really should have an EdgeCombinator here toolkit . copyEdge ( e , compositeEdge ) ; } // Remove all of the vertices in the vertex set; this will // automatically remove the edges into and out of those // vertices for ( VertexType aVertexSet : vertexSet ) { g . removeVertex ( aVertexSet ) ; } }
Merge the specified set of vertices into a single vertex .
535
13
153,112
@ Override @ Nonnull public String getLabel ( ) { ASTVisitor labelFixingVisitor = getCustomLabelVisitor ( ) ; if ( labelFixingVisitor instanceof CustomLabelVisitor ) { if ( customizedLabel == null ) { String labelReplacement = findLabelReplacement ( labelFixingVisitor ) ; customizedLabel = label . replace ( BugResolution . PLACEHOLDER_STRING , labelReplacement ) ; } return customizedLabel ; } return label ; }
Returns the short label that briefly describes the change that will be made .
105
14
153,113
private void runInternal ( IMarker marker ) throws CoreException { Assert . isNotNull ( marker ) ; PendingRewrite pending = resolveWithoutWriting ( marker ) ; if ( pending == null ) { return ; } try { IRegion region = completeRewrite ( pending ) ; if ( region == null ) { return ; } IEditorPart part = EditorUtility . isOpenInEditor ( pending . originalUnit ) ; if ( part instanceof ITextEditor ) { ( ( ITextEditor ) part ) . selectAndReveal ( region . getOffset ( ) , region . getLength ( ) ) ; } } finally { pending . originalUnit . discardWorkingCopy ( ) ; } }
This method is used by the test - framework to catch the thrown exceptions and report it to the user .
147
21
153,114
@ CheckForNull protected ICompilationUnit getCompilationUnit ( IMarker marker ) { IResource res = marker . getResource ( ) ; if ( res instanceof IFile && res . isAccessible ( ) ) { IJavaElement element = JavaCore . create ( ( IFile ) res ) ; if ( element instanceof ICompilationUnit ) { return ( ICompilationUnit ) element ; } } return null ; }
Get the compilation unit for the marker .
91
8
153,115
protected void reportException ( Exception e ) { Assert . isNotNull ( e ) ; FindbugsPlugin . getDefault ( ) . logException ( e , e . getLocalizedMessage ( ) ) ; MessageDialog . openError ( FindbugsPlugin . getShell ( ) , "BugResolution failed." , e . getLocalizedMessage ( ) ) ; }
Reports an exception to the user . This method could be overwritten by a subclass to handle some exceptions individual .
76
22
153,116
public int getSizeOfSurroundingTryBlock ( String vmNameOfExceptionClass , int pc ) { if ( code == null ) { throw new IllegalStateException ( "Not visiting Code" ) ; } return Util . getSizeOfSurroundingTryBlock ( constantPool , code , vmNameOfExceptionClass , pc ) ; }
Get lines of code in try block that surround pc
71
10
153,117
public String getFullyQualifiedMethodName ( ) { if ( ! visitingMethod ) { throw new IllegalStateException ( "getFullyQualifiedMethodName called while not visiting method" ) ; } if ( fullyQualifiedMethodName == null ) { getMethodName ( ) ; getDottedMethodSig ( ) ; StringBuilder ref = new StringBuilder ( 5 + dottedClassName . length ( ) + methodName . length ( ) + dottedMethodSig . length ( ) ) ; ref . append ( dottedClassName ) . append ( "." ) . append ( methodName ) . append ( " : " ) . append ( dottedMethodSig ) ; fullyQualifiedMethodName = ref . toString ( ) ; } return fullyQualifiedMethodName ; }
If currently visiting a method get the method s fully qualified name
161
12
153,118
public String getMethodName ( ) { if ( ! visitingMethod ) { throw new IllegalStateException ( "getMethodName called while not visiting method" ) ; } if ( methodName == null ) { methodName = getStringFromIndex ( method . getNameIndex ( ) ) ; } return methodName ; }
If currently visiting a method get the method s name
65
10
153,119
public static boolean hasInterestingMethod ( ConstantPool cp , Collection < MethodDescriptor > methods ) { for ( Constant c : cp . getConstantPool ( ) ) { if ( c instanceof ConstantMethodref || c instanceof ConstantInterfaceMethodref ) { ConstantCP desc = ( ConstantCP ) c ; ConstantNameAndType nameAndType = ( ConstantNameAndType ) cp . getConstant ( desc . getNameAndTypeIndex ( ) ) ; String className = cp . getConstantString ( desc . getClassIndex ( ) , Const . CONSTANT_Class ) ; String name = ( ( ConstantUtf8 ) cp . getConstant ( nameAndType . getNameIndex ( ) ) ) . getBytes ( ) ; String signature = ( ( ConstantUtf8 ) cp . getConstant ( nameAndType . getSignatureIndex ( ) ) ) . getBytes ( ) ; // We don't know whether method is static thus cannot use equals int hash = FieldOrMethodDescriptor . getNameSigHashCode ( name , signature ) ; for ( MethodDescriptor method : methods ) { if ( method . getNameSigHashCode ( ) == hash && ( method . getSlashedClassName ( ) . isEmpty ( ) || method . getSlashedClassName ( ) . equals ( className ) ) && method . getName ( ) . equals ( name ) && method . getSignature ( ) . equals ( signature ) ) { return true ; } } } } return false ; }
Returns true if given constant pool probably has a reference to any of supplied methods Useful to exclude from analysis uninteresting classes
322
23
153,120
public String getMethodSig ( ) { if ( ! visitingMethod ) { throw new IllegalStateException ( "getMethodSig called while not visiting method" ) ; } if ( methodSig == null ) { methodSig = getStringFromIndex ( method . getSignatureIndex ( ) ) ; } return methodSig ; }
If currently visiting a method get the method s slash - formatted signature
71
13
153,121
public String getDottedMethodSig ( ) { if ( ! visitingMethod ) { throw new IllegalStateException ( "getDottedMethodSig called while not visiting method" ) ; } if ( dottedMethodSig == null ) { dottedMethodSig = getMethodSig ( ) . replace ( ' ' , ' ' ) ; } return dottedMethodSig ; }
If currently visiting a method get the method s dotted method signature
79
12
153,122
public String getFieldName ( ) { if ( ! visitingField ) { throw new IllegalStateException ( "getFieldName called while not visiting field" ) ; } if ( fieldName == null ) { fieldName = getStringFromIndex ( field . getNameIndex ( ) ) ; } return fieldName ; }
If currently visiting a field get the field s name
65
10
153,123
public String getFieldSig ( ) { if ( ! visitingField ) { throw new IllegalStateException ( "getFieldSig called while not visiting field" ) ; } if ( fieldSig == null ) { fieldSig = getStringFromIndex ( field . getSignatureIndex ( ) ) ; } return fieldSig ; }
If currently visiting a field get the field s slash - formatted signature
71
13
153,124
public String getFullyQualifiedFieldName ( ) { if ( ! visitingField ) { throw new IllegalStateException ( "getFullyQualifiedFieldName called while not visiting field" ) ; } if ( fullyQualifiedFieldName == null ) { fullyQualifiedFieldName = getDottedClassName ( ) + "." + getFieldName ( ) + " : " + getFieldSig ( ) ; } return fullyQualifiedFieldName ; }
If currently visiting a field get the field s fully qualified name
96
12
153,125
@ Deprecated public String getDottedFieldSig ( ) { if ( ! visitingField ) { throw new IllegalStateException ( "getDottedFieldSig called while not visiting field" ) ; } if ( dottedFieldSig == null ) { dottedFieldSig = fieldSig . replace ( ' ' , ' ' ) ; } return dottedFieldSig ; }
If currently visiting a field get the field s dot - formatted signature
79
13
153,126
public ClassNotFoundException toClassNotFoundException ( ) { ClassDescriptor classDescriptor = DescriptorFactory . createClassDescriptorFromResourceName ( resourceName ) ; return new ClassNotFoundException ( "ResourceNotFoundException while looking for class " + classDescriptor . toDottedClassName ( ) + ": " + getMessage ( ) ) ; }
Convert this exception to a ClassNotFoundException . This method should only be called if the ResourceNotFoundException occurs while looking for a class . The message format is parseable by ClassNotFoundExceptionParser .
82
43
153,127
private ICodeBaseEntry search ( List < ? extends ICodeBase > codeBaseList , String resourceName ) { for ( ICodeBase codeBase : codeBaseList ) { ICodeBaseEntry resource = codeBase . lookupResource ( resourceName ) ; if ( resource != null ) { return resource ; } // Ignore, continue trying other codebases } return null ; }
Search list of codebases for named resource .
78
10
153,128
public void copyFrom ( StateSet other ) { this . isTop = other . isTop ; this . isBottom = other . isBottom ; this . onExceptionPath = other . onExceptionPath ; this . stateMap . clear ( ) ; for ( State state : other . stateMap . values ( ) ) { State dup = state . duplicate ( ) ; this . stateMap . put ( dup . getObligationSet ( ) , dup ) ; } }
Make this StateSet an exact copy of the given StateSet .
97
13
153,129
public void addObligation ( final Obligation obligation , int basicBlockId ) throws ObligationAcquiredOrReleasedInLoopException { Map < ObligationSet , State > updatedStateMap = new HashMap <> ( ) ; if ( stateMap . isEmpty ( ) ) { State s = new State ( factory ) ; s . getObligationSet ( ) . add ( obligation ) ; updatedStateMap . put ( s . getObligationSet ( ) , s ) ; } else { for ( State state : stateMap . values ( ) ) { checkCircularity ( state , obligation , basicBlockId ) ; state . getObligationSet ( ) . add ( obligation ) ; updatedStateMap . put ( state . getObligationSet ( ) , state ) ; } } replaceMap ( updatedStateMap ) ; }
Add an obligation to every State in the StateSet .
180
11
153,130
public void deleteObligation ( final Obligation obligation , int basicBlockId ) throws ObligationAcquiredOrReleasedInLoopException { Map < ObligationSet , State > updatedStateMap = new HashMap <> ( ) ; for ( Iterator < State > i = stateIterator ( ) ; i . hasNext ( ) ; ) { State state = i . next ( ) ; checkCircularity ( state , obligation , basicBlockId ) ; ObligationSet obligationSet = state . getObligationSet ( ) ; obligationSet . remove ( obligation ) ; if ( ! obligationSet . isEmpty ( ) ) { updatedStateMap . put ( obligationSet , state ) ; } } replaceMap ( updatedStateMap ) ; }
Remove an Obligation from every State in the StateSet .
157
13
153,131
private void checkCircularity ( State state , Obligation obligation , int basicBlockId ) throws ObligationAcquiredOrReleasedInLoopException { if ( state . getPath ( ) . hasComponent ( basicBlockId ) ) { throw new ObligationAcquiredOrReleasedInLoopException ( obligation ) ; } }
Bail out of the analysis is an obligation is acquired or released in a loop .
69
17
153,132
public List < State > getPrefixStates ( Path path ) { List < State > result = new LinkedList <> ( ) ; for ( State state : stateMap . values ( ) ) { if ( state . getPath ( ) . isPrefixOf ( path ) ) { result . add ( state ) ; } } return result ; }
Get all States that have Paths which are prefixes of the given Path .
73
16
153,133
private static boolean acquireAnalysisPermitUnlessCancelled ( IProgressMonitor monitor ) throws InterruptedException { do { if ( analysisSem . tryAcquire ( 1 , TimeUnit . SECONDS ) ) { return true ; } } while ( ! monitor . isCanceled ( ) ) ; return false ; }
Acquires an analysis permit unless first cancelled .
66
10
153,134
public void setTimestamp ( String timestamp ) throws ParseException { this . analysisTimestamp = new SimpleDateFormat ( TIMESTAMP_FORMAT , Locale . ENGLISH ) . parse ( timestamp ) ; }
Set the timestamp for this analysis run .
46
8
153,135
public void addBug ( BugInstance bug ) { SourceLineAnnotation source = bug . getPrimarySourceLineAnnotation ( ) ; PackageStats stat = getPackageStats ( source . getPackageName ( ) ) ; stat . addError ( bug ) ; ++ totalErrors [ 0 ] ; int priority = bug . getPriority ( ) ; if ( priority >= 1 ) { ++ totalErrors [ Math . min ( priority , totalErrors . length - 1 ) ] ; } }
Called when a bug is reported .
101
8
153,136
public void clearBugCounts ( ) { for ( int i = 0 ; i < totalErrors . length ; i ++ ) { totalErrors [ i ] = 0 ; } for ( PackageStats stats : packageStatsMap . values ( ) ) { stats . clearBugCounts ( ) ; } }
Clear bug counts
64
3
153,137
public void transformSummaryToHTML ( Writer htmlWriter ) throws IOException , TransformerException { ByteArrayOutputStream summaryOut = new ByteArrayOutputStream ( 8096 ) ; reportSummary ( summaryOut ) ; StreamSource in = new StreamSource ( new ByteArrayInputStream ( summaryOut . toByteArray ( ) ) ) ; StreamResult out = new StreamResult ( htmlWriter ) ; InputStream xslInputStream = this . getClass ( ) . getClassLoader ( ) . getResourceAsStream ( "summary.xsl" ) ; if ( xslInputStream == null ) { throw new IOException ( "Could not load summary stylesheet" ) ; } StreamSource xsl = new StreamSource ( xslInputStream ) ; TransformerFactory tf = TransformerFactory . newInstance ( ) ; Transformer transformer = tf . newTransformer ( xsl ) ; transformer . transform ( in , out ) ; Reader rdr = in . getReader ( ) ; if ( rdr != null ) { rdr . close ( ) ; } htmlWriter . close ( ) ; InputStream is = xsl . getInputStream ( ) ; if ( is != null ) { is . close ( ) ; } }
Transform summary information to HTML .
254
6
153,138
JPopupMenu createBugPopupMenu ( ) { JPopupMenu popupMenu = new JPopupMenu ( ) ; JMenuItem filterMenuItem = MainFrameHelper . newJMenuItem ( "menu.filterBugsLikeThis" , "Filter bugs like this" ) ; filterMenuItem . addActionListener ( evt -> { new NewFilterFromBug ( new FilterFromBugPicker ( currentSelectedBugLeaf . getBug ( ) , Arrays . asList ( mainFrame . getAvailableSortables ( ) ) ) , new ApplyNewFilter ( mainFrame . getProject ( ) . getSuppressionFilter ( ) , PreferencesFrame . getInstance ( ) , new FilterActivityNotifier ( ) ) ) ; mainFrame . setProjectChanged ( true ) ; mainFrame . getTree ( ) . setSelectionRow ( 0 ) ; // Selects the top of the Jtree so the CommentsArea syncs up. } ) ; popupMenu . add ( filterMenuItem ) ; return popupMenu ; }
Creates popup menu for bugs on tree .
215
9
153,139
JPopupMenu createBranchPopUpMenu ( ) { JPopupMenu popupMenu = new JPopupMenu ( ) ; JMenuItem filterMenuItem = MainFrameHelper . newJMenuItem ( "menu.filterTheseBugs" , "Filter these bugs" ) ; filterMenuItem . addActionListener ( evt -> { // TODO This code does a smarter version of filtering that is // only possible for branches, and does so correctly // However, it is still somewhat of a hack, because if we ever // add more tree listeners than simply the bugtreemodel, // They will not be called by this code. Using FilterActivity to // notify all listeners will however destroy any // benefit of using the smarter deletion method. try { int startCount ; TreePath path = MainFrame . getInstance ( ) . getTree ( ) . getSelectionPath ( ) ; TreePath deletePath = path ; startCount = ( ( BugAspects ) ( path . getLastPathComponent ( ) ) ) . getCount ( ) ; int count = ( ( BugAspects ) ( path . getParentPath ( ) . getLastPathComponent ( ) ) ) . getCount ( ) ; while ( count == startCount ) { deletePath = deletePath . getParentPath ( ) ; if ( deletePath . getParentPath ( ) == null ) // We are at the // top of the // tree, don't // let this be // removed, // rebuild tree // from root. { Matcher m1 = mainFrame . getCurrentSelectedBugAspects ( ) . getMatcher ( ) ; Filter suppressionFilter1 = MainFrame . getInstance ( ) . getProject ( ) . getSuppressionFilter ( ) ; suppressionFilter1 . addChild ( m1 ) ; PreferencesFrame . getInstance ( ) . updateFilterPanel ( ) ; FilterActivity . notifyListeners ( FilterListener . Action . FILTERING , null ) ; return ; } count = ( ( BugAspects ) ( deletePath . getParentPath ( ) . getLastPathComponent ( ) ) ) . getCount ( ) ; } /* * deletePath should now be a path to the highest ancestor * branch with the same number of elements as the branch to * be deleted in other words, the branch that we actually * have to remove in order to correctly remove the selected * branch. */ BugTreeModel model = MainFrame . getInstance ( ) . getBugTreeModel ( ) ; TreeModelEvent event = new TreeModelEvent ( mainFrame , deletePath . getParentPath ( ) , new int [ ] { model . getIndexOfChild ( deletePath . getParentPath ( ) . getLastPathComponent ( ) , deletePath . getLastPathComponent ( ) ) } , new Object [ ] { deletePath . getLastPathComponent ( ) } ) ; Matcher m2 = mainFrame . getCurrentSelectedBugAspects ( ) . getMatcher ( ) ; Filter suppressionFilter2 = MainFrame . getInstance ( ) . getProject ( ) . getSuppressionFilter ( ) ; suppressionFilter2 . addChild ( m2 ) ; PreferencesFrame . getInstance ( ) . updateFilterPanel ( ) ; model . sendEvent ( event , BugTreeModel . TreeModification . REMOVE ) ; // FilterActivity.notifyListeners(FilterListener.Action.FILTERING, // null); mainFrame . setProjectChanged ( true ) ; MainFrame . getInstance ( ) . getTree ( ) . setSelectionRow ( 0 ) ; // Selects // the // top // of // the // Jtree // so // the // CommentsArea // syncs // up. } catch ( RuntimeException e ) { MainFrame . getInstance ( ) . showMessageDialog ( "Unable to create filter: " + e . getMessage ( ) ) ; } } ) ; popupMenu . add ( filterMenuItem ) ; return popupMenu ; }
Creates the branch pop up menu that ask if the user wants to hide all the bugs in that branch .
821
22
153,140
public void accumulateBug ( BugInstance bug , SourceLineAnnotation sourceLine ) { if ( sourceLine == null ) { throw new NullPointerException ( "Missing source line" ) ; } int priority = bug . getPriority ( ) ; if ( ! performAccumulation ) { bug . addSourceLine ( sourceLine ) ; } else { bug . setPriority ( Priorities . NORMAL_PRIORITY ) ; } lastBug = bug ; lastSourceLine = sourceLine ; Data d = map . get ( bug ) ; if ( d == null ) { String hash = bug . getInstanceHash ( ) ; BugInstance conflictingBug = hashes . get ( hash ) ; if ( conflictingBug != null ) { if ( conflictingBug . getPriority ( ) <= priority ) { return ; } map . remove ( conflictingBug ) ; } d = new Data ( priority , sourceLine ) ; map . put ( bug , d ) ; hashes . put ( hash , bug ) ; } else if ( d . priority > priority ) { if ( d . priority >= Priorities . LOW_PRIORITY ) { reportBug ( bug , d ) ; d . allSource . clear ( ) ; } d . priority = priority ; d . primarySource = sourceLine ; } else if ( priority >= Priorities . LOW_PRIORITY && priority > d . priority ) { bug . setPriority ( priority ) ; reporter . reportBug ( bug ) ; return ; } d . allSource . add ( sourceLine ) ; }
Accumulate a warning at given source location .
319
10
153,141
public void accumulateBug ( BugInstance bug , BytecodeScanningDetector visitor ) { SourceLineAnnotation source = SourceLineAnnotation . fromVisitedInstruction ( visitor ) ; accumulateBug ( bug , source ) ; }
Accumulate a warning at source location currently being visited by given BytecodeScanningDetector .
47
20
153,142
public void reportAccumulatedBugs ( ) { for ( Map . Entry < BugInstance , Data > e : map . entrySet ( ) ) { BugInstance bug = e . getKey ( ) ; Data d = e . getValue ( ) ; reportBug ( bug , d ) ; } clearBugs ( ) ; }
Report accumulated warnings to the BugReporter . Clears all accumulated warnings as a side - effect .
69
20
153,143
public void rebuild ( ) { if ( TRACE ) { System . out . println ( "rebuilding bug tree model" ) ; } NewFilterFromBug . closeAll ( ) ; // If this thread is not interrupting a previous thread, set the paths // to be opened when the new tree is complete // If the thread is interrupting another thread, don't do this, because // you don't have the tree with the correct paths selected // As of now, it should be impossible to interrupt a rebuilding thread, // in another version this may change, so this if statement check is // left in, even though it should always be true. if ( rebuildingThread == null ) { setOldSelectedBugs ( ) ; } Debug . println ( "Please Wait called right before starting rebuild thread" ) ; mainFrame . acquireDisplayWait ( ) ; rebuildingThread = edu . umd . cs . findbugs . util . Util . runInDameonThread ( new Runnable ( ) { BugTreeModel newModel ; @ Override public void run ( ) { try { newModel = new BugTreeModel ( BugTreeModel . this ) ; newModel . listeners = listeners ; newModel . resetData ( ) ; newModel . bugSet . sortList ( ) ; } finally { rebuildingThread = null ; SwingUtilities . invokeLater ( ( ) -> { if ( newModel != null ) { JTree newTree = new JTree ( newModel ) ; newModel . tree = newTree ; mainFrame . mainFrameTree . newTree ( newTree , newModel ) ; mainFrame . releaseDisplayWait ( ) ; } getOffListenerList ( ) ; } ) ; } } } , "Rebuilding thread" ) ; }
Swaps in a new BugTreeModel and a new JTree
363
13
153,144
public static Collection < TypeQualifierValue < ? > > getComplementaryExclusiveTypeQualifierValue ( TypeQualifierValue < ? > tqv ) { assert tqv . isExclusiveQualifier ( ) ; LinkedList < TypeQualifierValue < ? > > result = new LinkedList <> ( ) ; for ( TypeQualifierValue < ? > t : instance . get ( ) . allKnownTypeQualifiers ) { // // Any TypeQualifierValue with the same // annotation class but a different value is a complementary // type qualifier. // if ( t . typeQualifier . equals ( tqv . typeQualifier ) && ! Objects . equals ( t . value , tqv . value ) ) { result . add ( t ) ; } } return result ; }
Get the complementary TypeQualifierValues for given exclusive type qualifier .
165
13
153,145
private int getIntValue ( int stackDepth , int defaultValue ) { if ( stack . getStackDepth ( ) < stackDepth ) { return defaultValue ; } OpcodeStack . Item it = stack . getStackItem ( stackDepth ) ; Object value = it . getConstant ( ) ; if ( ! ( value instanceof Integer ) ) { return defaultValue ; } return ( ( Number ) value ) . intValue ( ) ; }
return an int on the stack or defaultValue if can t determine
92
13
153,146
public static synchronized SortedMap < String , String > getContributedDetectors ( ) { if ( contributedDetectors != null ) { return new TreeMap <> ( contributedDetectors ) ; } TreeMap < String , String > set = new TreeMap <> ( ) ; IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; for ( IConfigurationElement configElt : registry . getConfigurationElementsFor ( EXTENSION_POINT_ID ) ) { addContribution ( set , configElt ) ; } contributedDetectors = set ; return new TreeMap <> ( contributedDetectors ) ; }
key is the plugin id value is the plugin library path
134
11
153,147
@ CheckForNull private static String resolvePluginClassesDir ( String bundleName , File sourceDir ) { if ( sourceDir . listFiles ( ) == null ) { FindbugsPlugin . getDefault ( ) . logException ( new IllegalStateException ( "No files in the bundle!" ) , "Failed to create temporary detector package for bundle " + sourceDir ) ; return null ; } String outputDir = getBuildDirectory ( bundleName , sourceDir ) ; if ( outputDir . length ( ) == 0 ) { FindbugsPlugin . getDefault ( ) . logException ( new IllegalStateException ( "No output directory in build.properties" ) , "No output directory in build.properties " + sourceDir ) ; return null ; } File classDir = new File ( sourceDir , outputDir ) ; if ( classDir . listFiles ( ) == null ) { FindbugsPlugin . getDefault ( ) . logException ( new IllegalStateException ( "No files in the bundle output dir!" ) , "Failed to create temporary detector package for bundle " + sourceDir ) ; return null ; } File etcDir = new File ( sourceDir , "etc" ) ; if ( etcDir . listFiles ( ) == null ) { FindbugsPlugin . getDefault ( ) . logException ( new IllegalStateException ( "No files in the bundle etc dir!" ) , "Failed to create temporary detector package for bundle " + sourceDir ) ; return null ; } return classDir . getAbsolutePath ( ) ; }
Used for Eclipse instances running inside debugger . During development Eclipse plugins are just directories . The code below tries to locate plugin s bin directory . It doesn t work if the plugin build . properties are not existing or contain invalid content
317
44
153,148
public static LocalVariableAnnotation getParameterLocalVariableAnnotation ( Method method , int local ) { LocalVariableAnnotation lva = getLocalVariableAnnotation ( method , local , 0 , 0 ) ; if ( lva . isNamed ( ) ) { lva . setDescription ( LocalVariableAnnotation . PARAMETER_NAMED_ROLE ) ; } else { lva . setDescription ( LocalVariableAnnotation . PARAMETER_ROLE ) ; } return lva ; }
Get a local variable annotation describing a parameter .
107
9
153,149
@ Override public char next ( ) { ++ docPos ; if ( docPos < segmentEnd || segmentEnd >= doc . getLength ( ) ) { return text . next ( ) ; } try { doc . getText ( segmentEnd , doc . getLength ( ) - segmentEnd , text ) ; } catch ( BadLocationException e ) { throw new RuntimeException ( e ) ; } segmentEnd += text . count ; return text . current ( ) ; }
Increments the iterator s index by one and returns the character at the new index .
96
17
153,150
public static String rewriteMethodSignature ( ClassNameRewriter classNameRewriter , String methodSignature ) { if ( classNameRewriter != IdentityClassNameRewriter . instance ( ) ) { SignatureParser parser = new SignatureParser ( methodSignature ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( ' ' ) ; for ( Iterator < String > i = parser . parameterSignatureIterator ( ) ; i . hasNext ( ) ; ) { buf . append ( rewriteSignature ( classNameRewriter , i . next ( ) ) ) ; } buf . append ( ' ' ) ; buf . append ( rewriteSignature ( classNameRewriter , parser . getReturnTypeSignature ( ) ) ) ; methodSignature = buf . toString ( ) ; } return methodSignature ; }
Rewrite a method signature .
172
6
153,151
public static String rewriteSignature ( ClassNameRewriter classNameRewriter , String signature ) { if ( classNameRewriter != IdentityClassNameRewriter . instance ( ) && signature . startsWith ( "L" ) ) { String className = signature . substring ( 1 , signature . length ( ) - 1 ) . replace ( ' ' , ' ' ) ; className = classNameRewriter . rewriteClassName ( className ) ; signature = "L" + className . replace ( ' ' , ' ' ) + ";" ; } return signature ; }
Rewrite a signature .
119
5
153,152
public static MethodAnnotation convertMethodAnnotation ( ClassNameRewriter classNameRewriter , MethodAnnotation annotation ) { if ( classNameRewriter != IdentityClassNameRewriter . instance ( ) ) { annotation = new MethodAnnotation ( classNameRewriter . rewriteClassName ( annotation . getClassName ( ) ) , annotation . getMethodName ( ) , rewriteMethodSignature ( classNameRewriter , annotation . getMethodSignature ( ) ) , annotation . isStatic ( ) ) ; } return annotation ; }
Rewrite a MethodAnnotation to update the class name and any class names mentioned in the method signature .
109
21
153,153
public static FieldAnnotation convertFieldAnnotation ( ClassNameRewriter classNameRewriter , FieldAnnotation annotation ) { if ( classNameRewriter != IdentityClassNameRewriter . instance ( ) ) { annotation = new FieldAnnotation ( classNameRewriter . rewriteClassName ( annotation . getClassName ( ) ) , annotation . getFieldName ( ) , rewriteSignature ( classNameRewriter , annotation . getFieldSignature ( ) ) , annotation . isStatic ( ) ) ; } return annotation ; }
Rewrite a FieldAnnotation to update the class name and field signature if needed .
108
17
153,154
private InterproceduralCallGraphVertex findVertex ( XMethod xmethod ) { InterproceduralCallGraphVertex vertex ; vertex = callGraph . lookupVertex ( xmethod . getMethodDescriptor ( ) ) ; if ( vertex == null ) { vertex = new InterproceduralCallGraphVertex ( ) ; vertex . setXmethod ( xmethod ) ; callGraph . addVertex ( vertex ) ; } return vertex ; }
Find the InterproceduralCallGraphVertex for given XMethod .
96
15
153,155
public boolean hasComponent ( int blockId ) { for ( int i = 0 ; i < length ; i ++ ) { if ( blockIdList [ i ] == blockId ) { return true ; } } return false ; }
Determine whether or not the id of the given BasicBlock appears anywhere in the path .
47
19
153,156
public void copyFrom ( Path other ) { grow ( other . length - 1 ) ; System . arraycopy ( other . blockIdList , 0 , this . blockIdList , 0 , other . length ) ; this . length = other . length ; this . cachedHashCode = other . cachedHashCode ; }
Make this Path identical to the given one .
65
9
153,157
public void acceptVisitor ( CFG cfg , PathVisitor visitor ) { if ( getLength ( ) > 0 ) { BasicBlock startBlock = cfg . lookupBlockByLabel ( getBlockIdAt ( 0 ) ) ; acceptVisitorStartingFromLocation ( cfg , visitor , startBlock , startBlock . getFirstInstruction ( ) ) ; } }
Accept a PathVisitor .
77
6
153,158
public void acceptVisitorStartingFromLocation ( CFG cfg , PathVisitor visitor , BasicBlock startBlock , InstructionHandle startHandle ) { // Find the start block in the path int index ; for ( index = 0 ; index < getLength ( ) ; index ++ ) { if ( getBlockIdAt ( index ) == startBlock . getLabel ( ) ) { break ; } } assert index < getLength ( ) ; Iterator < InstructionHandle > i = startBlock . instructionIterator ( ) ; // Position iterator at start instruction handle if ( startHandle != startBlock . getFirstInstruction ( ) ) { while ( i . hasNext ( ) ) { InstructionHandle handle = i . next ( ) ; if ( handle . getNext ( ) == startHandle ) { break ; } } } BasicBlock basicBlock = startBlock ; while ( true ) { // visit block visitor . visitBasicBlock ( basicBlock ) ; // visit instructions in block while ( i . hasNext ( ) ) { visitor . visitInstructionHandle ( i . next ( ) ) ; } // end of path? index ++ ; if ( index >= getLength ( ) ) { break ; } // visit edge BasicBlock next = cfg . lookupBlockByLabel ( getBlockIdAt ( index ) ) ; Edge edge = cfg . lookupEdge ( basicBlock , next ) ; assert edge != null ; visitor . visitEdge ( edge ) ; // continue to next block basicBlock = next ; i = basicBlock . instructionIterator ( ) ; } }
Accept a PathVisitor starting from a given BasicBlock and InstructionHandle .
317
15
153,159
public boolean isPrefixOf ( Path path ) { if ( this . getLength ( ) > path . getLength ( ) ) { return false ; } for ( int i = 0 ; i < getLength ( ) ; i ++ ) { if ( this . getBlockIdAt ( i ) != path . getBlockIdAt ( i ) ) { return false ; } } return true ; }
Determine whether or not given Path is a prefix of this one .
82
15
153,160
private void produce ( IsNullValue value ) { IsNullValueFrame frame = getFrame ( ) ; frame . pushValue ( value ) ; newValueOnTOS ( ) ; }
to produce different values in each of the control successors .
38
11
153,161
private void handleInvoke ( InvokeInstruction obj ) { if ( obj instanceof INVOKEDYNAMIC ) { // should not happen return ; } Type returnType = obj . getReturnType ( getCPG ( ) ) ; Location location = getLocation ( ) ; if ( trackValueNumbers ) { try { ValueNumberFrame vnaFrame = vnaDataflow . getFactAtLocation ( location ) ; Set < ValueNumber > nonnullParameters = UnconditionalValueDerefAnalysis . checkAllNonNullParams ( location , vnaFrame , cpg , null , null , typeDataflow ) ; if ( ! nonnullParameters . isEmpty ( ) ) { IsNullValue kaboom = IsNullValue . noKaboomNonNullValue ( location ) ; IsNullValueFrame frame = getFrame ( ) ; for ( ValueNumber vn : nonnullParameters ) { IsNullValue knownValue = frame . getKnownValue ( vn ) ; if ( knownValue != null && ! knownValue . isDefinitelyNotNull ( ) ) { if ( knownValue . isDefinitelyNull ( ) ) { frame . setTop ( ) ; return ; } frame . setKnownValue ( vn , kaboom ) ; } for ( int i = 0 ; i < vnaFrame . getNumSlots ( ) ; i ++ ) { IsNullValue value = frame . getValue ( i ) ; if ( vnaFrame . getValue ( i ) . equals ( vn ) && ! value . isDefinitelyNotNull ( ) ) { frame . setValue ( i , kaboom ) ; if ( value . isDefinitelyNull ( ) ) { frame . setTop ( ) ; return ; } } } } } } catch ( DataflowAnalysisException e ) { AnalysisContext . logError ( "Error looking up nonnull parameters for invoked method" , e ) ; } } // Determine if we are going to model the return value of this call. boolean modelCallReturnValue = MODEL_NONNULL_RETURN && returnType instanceof ReferenceType ; if ( ! modelCallReturnValue ) { // Normal case: Assume returned values are non-reporting non-null. handleNormalInstruction ( obj ) ; } else { // Special case: some special value is pushed on the stack for the // return value IsNullValue result = null ; TypeFrame typeFrame ; try { typeFrame = typeDataflow . getFactAtLocation ( location ) ; Set < XMethod > targetSet = Hierarchy2 . resolveMethodCallTargets ( obj , typeFrame , cpg ) ; if ( targetSet . isEmpty ( ) ) { XMethod calledMethod = XFactory . createXMethod ( obj , getCPG ( ) ) ; result = getReturnValueNullness ( calledMethod ) ; } else { for ( XMethod calledMethod : targetSet ) { IsNullValue pushValue = getReturnValueNullness ( calledMethod ) ; if ( result == null ) { result = pushValue ; } else { result = IsNullValue . merge ( result , pushValue ) ; } } } } catch ( DataflowAnalysisException e ) { result = IsNullValue . nonReportingNotNullValue ( ) ; } catch ( ClassNotFoundException e ) { result = IsNullValue . nonReportingNotNullValue ( ) ; } modelInstruction ( obj , getNumWordsConsumed ( obj ) , getNumWordsProduced ( obj ) , result ) ; newValueOnTOS ( ) ; } }
Handle method invocations . Generally we want to get rid of null information following a call to a likely exception thrower or assertion .
741
26
153,162
private boolean checkForKnownValue ( Instruction obj ) { if ( trackValueNumbers ) { try { // See if the value number loaded here is a known value ValueNumberFrame vnaFrameAfter = vnaDataflow . getFactAfterLocation ( getLocation ( ) ) ; if ( vnaFrameAfter . isValid ( ) ) { ValueNumber tosVN = vnaFrameAfter . getTopValue ( ) ; IsNullValue knownValue = getFrame ( ) . getKnownValue ( tosVN ) ; if ( knownValue != null ) { // System.out.println("Produce known value!"); // The value produced by this instruction is known. // Push the known value. modelNormalInstruction ( obj , getNumWordsConsumed ( obj ) , 0 ) ; produce ( knownValue ) ; return true ; } } } catch ( DataflowAnalysisException e ) { // Ignore... } } return false ; }
Check given Instruction to see if it produces a known value . If so model the instruction and return true . Otherwise do nothing and return false . Should only be used for instructions that produce a single value on the top of the stack .
194
46
153,163
public static String trimComma ( String s ) { if ( s . endsWith ( "," ) ) { s = s . substring ( 0 , s . length ( ) - 1 ) ; } return s ; }
Trim trailing comma from given string .
46
8
153,164
public static boolean initializeUnescapePattern ( ) { if ( paternIsInitialized == true ) { return true ; } synchronized ( unescapeInitLockObject ) { if ( paternIsInitialized == true ) { return true ; } try { unescapePattern = Pattern . compile ( unicodeUnescapeMatchExpression ) ; } catch ( PatternSyntaxException pse ) { /* * the pattern is compiled from a final string, so this * exception should never be thrown */ System . err . println ( "Imposible error: " + "static final regular expression pattern " + "failed to compile. Exception: " + pse . toString ( ) ) ; return false ; } paternIsInitialized = true ; } return true ; }
Initialize regular expressions used in unescaping . This method will be invoked automatically the first time a string is unescaped .
153
26
153,165
public String getReturnTypeSignature ( ) { int endOfParams = signature . lastIndexOf ( ' ' ) ; if ( endOfParams < 0 ) { throw new IllegalArgumentException ( "Bad method signature: " + signature ) ; } return signature . substring ( endOfParams + 1 ) ; }
Get the method return type signature .
69
7
153,166
public int getNumParameters ( ) { int count = 0 ; for ( Iterator < String > i = parameterSignatureIterator ( ) ; i . hasNext ( ) ; ) { i . next ( ) ; ++ count ; } return count ; }
Get the number of parameters in the signature .
52
9
153,167
public static boolean compareSignatures ( String plainSignature , String genericSignature ) { GenericSignatureParser plainParser = new GenericSignatureParser ( plainSignature ) ; GenericSignatureParser genericParser = new GenericSignatureParser ( genericSignature ) ; return plainParser . getNumParameters ( ) == genericParser . getNumParameters ( ) ; }
Compare a plain method signature to the a generic method Signature and return true if they match
74
17
153,168
public static String findCodeBaseInClassPath ( Pattern codeBaseNamePattern , String classPath ) { if ( classPath == null ) { return null ; } StringTokenizer tok = new StringTokenizer ( classPath , File . pathSeparator ) ; while ( tok . hasMoreTokens ( ) ) { String t = tok . nextToken ( ) ; File f = new File ( t ) ; Matcher m = codeBaseNamePattern . matcher ( f . getName ( ) ) ; if ( m . matches ( ) ) { return t ; } } return null ; }
Try to find a codebase matching the given pattern in the given class path string .
125
17
153,169
public static void skipFully ( InputStream in , long bytes ) throws IOException { if ( bytes < 0 ) { throw new IllegalArgumentException ( "Can't skip " + bytes + " bytes" ) ; } long remaining = bytes ; while ( remaining > 0 ) { long skipped = in . skip ( remaining ) ; if ( skipped <= 0 ) { throw new EOFException ( "Reached EOF while trying to skip a total of " + bytes ) ; } remaining -= skipped ; } }
Provide a skip fully method . Either skips the requested number of bytes or throws an IOException ;
105
21
153,170
public static Type fromExceptionSet ( ExceptionSet exceptionSet ) throws ClassNotFoundException { Type commonSupertype = exceptionSet . getCommonSupertype ( ) ; if ( commonSupertype . getType ( ) != Const . T_OBJECT ) { return commonSupertype ; } ObjectType exceptionSupertype = ( ObjectType ) commonSupertype ; String className = exceptionSupertype . getClassName ( ) ; if ( "java.lang.Throwable" . equals ( className ) ) { return exceptionSupertype ; } return new ExceptionObjectType ( className , exceptionSet ) ; }
Initialize object from an exception set .
124
8
153,171
public String parseNext ( ) { StringBuilder result = new StringBuilder ( ) ; if ( signature . startsWith ( "[" ) ) { int dimensions = 0 ; do { ++ dimensions ; signature = signature . substring ( 1 ) ; } while ( signature . charAt ( 0 ) == ' ' ) ; result . append ( parseNext ( ) ) ; while ( dimensions -- > 0 ) { result . append ( "[]" ) ; } } else if ( signature . startsWith ( "L" ) ) { int semi = signature . indexOf ( ' ' ) ; if ( semi < 0 ) { throw new IllegalStateException ( "missing semicolon in signature " + signature ) ; } result . append ( signature . substring ( 1 , semi ) . replace ( ' ' , ' ' ) ) ; signature = signature . substring ( semi + 1 ) ; } else { switch ( signature . charAt ( 0 ) ) { case ' ' : result . append ( "byte" ) ; break ; case ' ' : result . append ( "char" ) ; break ; case ' ' : result . append ( "double" ) ; break ; case ' ' : result . append ( "float" ) ; break ; case ' ' : result . append ( "int" ) ; break ; case ' ' : result . append ( "long" ) ; break ; case ' ' : result . append ( "short" ) ; break ; case ' ' : result . append ( "boolean" ) ; break ; case ' ' : result . append ( "void" ) ; break ; default : throw new IllegalArgumentException ( "bad signature " + signature ) ; } skip ( ) ; } return result . toString ( ) ; }
Parse a single type out of the signature starting at the beginning of the remaining part of the signature . For example if the first character of the remaining part is I then this method will return int and the I will be consumed . Arrays reference types and basic types are all handled .
362
57
153,172
static public void reportMissingClass ( ClassNotFoundException e ) { requireNonNull ( e , "argument is null" ) ; String missing = AbstractBugReporter . getMissingClassName ( e ) ; if ( skipReportingMissingClass ( missing ) ) { return ; } if ( ! analyzingApplicationClass ( ) ) { return ; } RepositoryLookupFailureCallback lookupFailureCallback = getCurrentLookupFailureCallback ( ) ; if ( lookupFailureCallback != null ) { lookupFailureCallback . reportMissingClass ( e ) ; } }
file a ClassNotFoundException with the lookupFailureCallback
111
11
153,173
public final void loadInterproceduralDatabases ( ) { loadPropertyDatabase ( getFieldStoreTypeDatabase ( ) , FieldStoreTypeDatabase . DEFAULT_FILENAME , "field store type database" ) ; loadPropertyDatabase ( getUnconditionalDerefParamDatabase ( ) , UNCONDITIONAL_DEREF_DB_FILENAME , "unconditional param deref database" ) ; loadPropertyDatabase ( getReturnValueNullnessPropertyDatabase ( ) , NONNULL_RETURN_DB_FILENAME , "nonnull return db database" ) ; }
If possible load interprocedural property databases .
124
10
153,174
public final void setDatabaseInputDir ( String databaseInputDir ) { if ( DEBUG ) { System . out . println ( "Setting database input directory: " + databaseInputDir ) ; } this . databaseInputDir = databaseInputDir ; }
Set the interprocedural database input directory .
50
10
153,175
public final void setDatabaseOutputDir ( String databaseOutputDir ) { if ( DEBUG ) { System . out . println ( "Setting database output directory: " + databaseOutputDir ) ; } this . databaseOutputDir = databaseOutputDir ; }
Set the interprocedural database output directory .
50
10
153,176
public < DatabaseType extends PropertyDatabase < KeyType , Property > , KeyType extends FieldOrMethodDescriptor , Property > void storePropertyDatabase ( DatabaseType database , String fileName , String description ) { try { File dbFile = new File ( getDatabaseOutputDir ( ) , fileName ) ; if ( DEBUG ) { System . out . println ( "Writing " + description + " to " + dbFile . getPath ( ) + "..." ) ; } database . writeToFile ( dbFile . getPath ( ) ) ; } catch ( IOException e ) { getLookupFailureCallback ( ) . logError ( "Error writing " + description , e ) ; } }
Write an interprocedural property database .
143
9
153,177
public static void setCurrentAnalysisContext ( AnalysisContext analysisContext ) { currentAnalysisContext . set ( analysisContext ) ; if ( Global . getAnalysisCache ( ) != null ) { currentXFactory . set ( new XFactory ( ) ) ; } }
Set the current analysis context for this thread .
52
9
153,178
public ClassContext getClassContext ( JavaClass javaClass ) { // This is a bit silly since we're doing an unnecessary // ClassDescriptor->JavaClass lookup. // However, we can be assured that it will succeed. ClassDescriptor classDescriptor = DescriptorFactory . instance ( ) . getClassDescriptor ( ClassName . toSlashedClassName ( javaClass . getClassName ( ) ) ) ; try { return Global . getAnalysisCache ( ) . getClassAnalysis ( ClassContext . class , classDescriptor ) ; } catch ( CheckedAnalysisException e ) { IllegalStateException ise = new IllegalStateException ( "Could not get ClassContext for JavaClass" ) ; ise . initCause ( e ) ; throw ise ; } }
Get the ClassContext for a class .
165
8
153,179
public void copyFrom ( BlockType other ) { this . isValid = other . isValid ; this . isTop = other . isTop ; if ( isValid ) { this . depth = other . depth ; this . clear ( ) ; this . or ( other ) ; } }
Make this object an exact duplicate of given object .
59
10
153,180
public boolean sameAs ( BlockType other ) { if ( ! this . isValid ) { return ! other . isValid && ( this . isTop == other . isTop ) ; } else { if ( ! other . isValid ) { return false ; } else { // Both facts are valid if ( this . depth != other . depth ) { return false ; } // Compare bits for ( int i = 0 ; i < this . depth ; ++ i ) { if ( this . get ( i ) != other . get ( i ) ) { return false ; } } return true ; } } }
Return whether or not this object is identical to the one given .
124
13
153,181
public void mergeWith ( BlockType other ) { if ( this . isTop ( ) || other . isBottom ( ) ) { copyFrom ( other ) ; } else if ( isValid ( ) ) { // To merge, we take the common prefix int pfxLen = Math . min ( this . depth , other . depth ) ; int commonLen ; for ( commonLen = 0 ; commonLen < pfxLen ; ++ commonLen ) { if ( this . get ( commonLen ) != other . get ( commonLen ) ) { break ; } } this . depth = commonLen ; } }
Merge other dataflow value into this value .
125
10
153,182
public static synchronized Map < String , List < QuickFixContribution > > getContributedQuickFixes ( ) { if ( contributedQuickFixes != null ) { return contributedQuickFixes ; } HashMap < String , List < QuickFixContribution > > set = new HashMap <> ( ) ; IExtensionRegistry registry = Platform . getExtensionRegistry ( ) ; for ( IConfigurationElement configElt : registry . getConfigurationElementsFor ( EXTENSION_POINT_ID ) ) { addContribution ( set , configElt ) ; } Set < Entry < String , List < QuickFixContribution > > > entrySet = set . entrySet ( ) ; for ( Entry < String , List < QuickFixContribution > > entry : entrySet ) { entry . setValue ( Collections . unmodifiableList ( entry . getValue ( ) ) ) ; } contributedQuickFixes = Collections . unmodifiableMap ( set ) ; return contributedQuickFixes ; }
key is the pattern id the value is the corresponding contribution
210
11
153,183
public static void getDirectApplications ( Set < TypeQualifierAnnotation > result , XMethod o , int parameter ) { Collection < AnnotationValue > values = getDirectAnnotation ( o , parameter ) ; for ( AnnotationValue v : values ) { constructTypeQualifierAnnotation ( result , v ) ; } }
Populate a Set of TypeQualifierAnnotations representing directly - applied type qualifier annotations on given method parameter .
67
22
153,184
public static void getDirectApplications ( Set < TypeQualifierAnnotation > result , AnnotatedObject o , ElementType e ) { if ( ! o . getElementType ( ) . equals ( e ) ) { return ; } Collection < AnnotationValue > values = getDirectAnnotation ( o ) ; for ( AnnotationValue v : values ) { constructTypeQualifierAnnotation ( result , v ) ; } }
Populate a Set of TypeQualifierAnnotations representing directly - applied type qualifier annotations on given AnnotatedObject .
88
24
153,185
public static TypeQualifierAnnotation constructTypeQualifierAnnotation ( AnnotationValue v ) { assert v != null ; EnumValue whenValue = ( EnumValue ) v . getValue ( "when" ) ; When when = whenValue == null ? When . ALWAYS : When . valueOf ( whenValue . value ) ; ClassDescriptor annotationClass = v . getAnnotationClass ( ) ; TypeQualifierValue < ? > tqv = TypeQualifierValue . getValue ( annotationClass , v . getValue ( "value" ) ) ; TypeQualifierAnnotation tqa = TypeQualifierAnnotation . getValue ( tqv , when ) ; return tqa ; }
Resolve a raw AnnotationValue into a TypeQualifierAnnotation .
145
15
153,186
public static void constructTypeQualifierAnnotation ( Set < TypeQualifierAnnotation > set , AnnotationValue v ) { assert set != null ; TypeQualifierAnnotation tqa = constructTypeQualifierAnnotation ( v ) ; set . add ( tqa ) ; }
Resolve a raw AnnotationValue into a TypeQualifierAnnotation storing result in given Set .
58
20
153,187
private static @ CheckForNull TypeQualifierAnnotation findMatchingTypeQualifierAnnotation ( Collection < TypeQualifierAnnotation > typeQualifierAnnotations , TypeQualifierValue < ? > typeQualifierValue ) { for ( TypeQualifierAnnotation typeQualifierAnnotation : typeQualifierAnnotations ) { if ( typeQualifierAnnotation . typeQualifier . equals ( typeQualifierValue ) ) { return typeQualifierAnnotation ; } } return null ; }
Look up a TypeQualifierAnnotation matching given TypeQualifierValue .
101
15
153,188
private static @ CheckForNull TypeQualifierAnnotation getDefaultAnnotation ( AnnotatedObject o , TypeQualifierValue < ? > typeQualifierValue , ElementType elementType ) { // // Try to find a default annotation using the standard JSR-305 // default annotation mechanism. // TypeQualifierAnnotation result ; Collection < AnnotationValue > values = TypeQualifierResolver . resolveTypeQualifierDefaults ( o . getAnnotations ( ) , elementType ) ; TypeQualifierAnnotation tqa = extractAnnotation ( values , typeQualifierValue ) ; if ( tqa != null ) { // System.out.println("Found default annotation of " + tqa + // " for element " + elementType + " in " + o); return tqa ; } // // Try one of the FindBugs-specific default annotation mechanisms. // if ( ( result = checkFindBugsDefaultAnnotation ( FindBugsDefaultAnnotations . DEFAULT_ANNOTATION , o , typeQualifierValue ) ) != null ) { return result ; } switch ( elementType ) { case FIELD : result = checkFindBugsDefaultAnnotation ( FindBugsDefaultAnnotations . DEFAULT_ANNOTATION_FOR_FIELDS , o , typeQualifierValue ) ; break ; case METHOD : result = checkFindBugsDefaultAnnotation ( FindBugsDefaultAnnotations . DEFAULT_ANNOTATION_FOR_METHODS , o , typeQualifierValue ) ; break ; case PARAMETER : result = checkFindBugsDefaultAnnotation ( FindBugsDefaultAnnotations . DEFAULT_ANNOTATION_FOR_PARAMETERS , o , typeQualifierValue ) ; break ; default : // ignore break ; } // Try out default JDT (Eclipse) annotations if ( result == null ) { AnnotationValue annotationValue = o . getAnnotation ( TypeQualifierResolver . eclipseNonNullByDefault ) ; if ( annotationValue != null ) { Collection < AnnotationValue > resolvedTypeQualifiers = TypeQualifierResolver . resolveTypeQualifiers ( annotationValue ) ; tqa = extractAnnotation ( resolvedTypeQualifiers , typeQualifierValue ) ; if ( tqa != null ) { return tqa ; } } } return result ; }
Look for a default type qualifier annotation .
485
8
153,189
private static TypeQualifierAnnotation getDirectTypeQualifierAnnotation ( AnnotatedObject o , TypeQualifierValue < ? > typeQualifierValue ) { TypeQualifierAnnotation result ; Set < TypeQualifierAnnotation > applications = new HashSet <> ( ) ; getDirectApplications ( applications , o , o . getElementType ( ) ) ; result = findMatchingTypeQualifierAnnotation ( applications , typeQualifierValue ) ; return result ; }
Get a directly - applied TypeQualifierAnnotation on given AnnotatedObject .
99
17
153,190
public static TypeQualifierAnnotation getInheritedTypeQualifierAnnotation ( XMethod o , TypeQualifierValue < ? > typeQualifierValue ) { assert ! o . isStatic ( ) ; ReturnTypeAnnotationAccumulator accumulator = new ReturnTypeAnnotationAccumulator ( typeQualifierValue , o ) ; try { AnalysisContext . currentAnalysisContext ( ) . getSubtypes2 ( ) . traverseSupertypesDepthFirst ( o . getClassDescriptor ( ) , accumulator ) ; TypeQualifierAnnotation result = accumulator . getResult ( ) . getEffectiveTypeQualifierAnnotation ( ) ; if ( result == null && accumulator . overrides ( ) ) { return TypeQualifierAnnotation . OVERRIDES_BUT_NO_ANNOTATION ; } return result ; } catch ( ClassNotFoundException e ) { AnalysisContext . currentAnalysisContext ( ) . getLookupFailureCallback ( ) . reportMissingClass ( e ) ; return null ; } }
Get the effective inherited TypeQualifierAnnotation on given instance method .
211
14
153,191
public static @ CheckForNull @ CheckReturnValue TypeQualifierAnnotation getDirectTypeQualifierAnnotation ( XMethod xmethod , int parameter , TypeQualifierValue < ? > typeQualifierValue ) { XMethod bridge = xmethod . bridgeTo ( ) ; if ( bridge != null ) { xmethod = bridge ; } Set < TypeQualifierAnnotation > applications = new HashSet <> ( ) ; getDirectApplications ( applications , xmethod , parameter ) ; if ( DEBUG_METHOD != null && DEBUG_METHOD . equals ( xmethod . getName ( ) ) ) { System . out . println ( " Direct applications are: " + applications ) ; } return findMatchingTypeQualifierAnnotation ( applications , typeQualifierValue ) ; }
Get the TypeQualifierAnnotation directly applied to given method parameter .
159
14
153,192
public static @ CheckForNull TypeQualifierAnnotation getInheritedTypeQualifierAnnotation ( XMethod xmethod , int parameter , TypeQualifierValue < ? > typeQualifierValue ) { assert ! xmethod . isStatic ( ) ; ParameterAnnotationAccumulator accumulator = new ParameterAnnotationAccumulator ( typeQualifierValue , xmethod , parameter ) ; try { AnalysisContext . currentAnalysisContext ( ) . getSubtypes2 ( ) . traverseSupertypesDepthFirst ( xmethod . getClassDescriptor ( ) , accumulator ) ; TypeQualifierAnnotation result = accumulator . getResult ( ) . getEffectiveTypeQualifierAnnotation ( ) ; if ( result == null && accumulator . overrides ( ) ) { return TypeQualifierAnnotation . OVERRIDES_BUT_NO_ANNOTATION ; } return result ; } catch ( ClassNotFoundException e ) { AnalysisContext . currentAnalysisContext ( ) . getLookupFailureCallback ( ) . reportMissingClass ( e ) ; return null ; } }
Get the effective inherited TypeQualifierAnnotation on the given instance method parameter .
224
16
153,193
private void setSorterCheckBoxes ( ) { SorterTableColumnModel sorter = MainFrame . getInstance ( ) . getSorter ( ) ; for ( SortableCheckBox c : checkBoxSortList ) { c . setSelected ( sorter . isShown ( c . sortable ) ) ; } }
Sets the checkboxes in the sorter panel to what is shown in the MainFrame . This assumes that sorterTableColumnModel will return the list of which box is checked in the same order as the order that sorter panel has .
69
49
153,194
public static MethodAnnotation fromVisitedMethod ( PreorderVisitor visitor ) { String className = visitor . getDottedClassName ( ) ; MethodAnnotation result = new MethodAnnotation ( className , visitor . getMethodName ( ) , visitor . getMethodSig ( ) , visitor . getMethod ( ) . isStatic ( ) ) ; // Try to find the source lines for the method SourceLineAnnotation srcLines = SourceLineAnnotation . fromVisitedMethod ( visitor ) ; result . setSourceLines ( srcLines ) ; return result ; }
Factory method to create a MethodAnnotation from the method the given visitor is currently visiting .
121
18
153,195
public static MethodAnnotation fromCalledMethod ( DismantleBytecode visitor ) { String className = visitor . getDottedClassConstantOperand ( ) ; String methodName = visitor . getNameConstantOperand ( ) ; String methodSig = visitor . getSigConstantOperand ( ) ; if ( visitor instanceof OpcodeStackDetector && visitor . getOpcode ( ) != Const . INVOKESTATIC ) { int params = PreorderVisitor . getNumberArguments ( methodSig ) ; OpcodeStackDetector oVisitor = ( OpcodeStackDetector ) visitor ; if ( ! oVisitor . getStack ( ) . isTop ( ) && oVisitor . getStack ( ) . getStackDepth ( ) > params ) { OpcodeStack . Item item = oVisitor . getStack ( ) . getStackItem ( params ) ; String cName = ClassName . fromFieldSignature ( item . getSignature ( ) ) ; if ( cName != null ) { className = cName ; } } } return fromCalledMethod ( className , methodName , methodSig , visitor . getOpcode ( ) == Const . INVOKESTATIC ) ; }
Factory method to create a MethodAnnotation from a method called by the instruction the given visitor is currently visiting .
260
22
153,196
public static MethodAnnotation fromCalledMethod ( String className , String methodName , String methodSig , boolean isStatic ) { MethodAnnotation methodAnnotation = fromForeignMethod ( className , methodName , methodSig , isStatic ) ; methodAnnotation . setDescription ( METHOD_CALLED ) ; return methodAnnotation ; }
Create a MethodAnnotation from a method that is not directly accessible . We will use the repository to try to find its class in order to populate the information as fully as possible .
74
36
153,197
public static MethodAnnotation fromXMethod ( XMethod xmethod ) { return fromForeignMethod ( xmethod . getClassName ( ) , xmethod . getName ( ) , xmethod . getSignature ( ) , xmethod . isStatic ( ) ) ; }
Create a MethodAnnotation from an XMethod .
56
10
153,198
public static MethodAnnotation fromMethodDescriptor ( MethodDescriptor methodDescriptor ) { return fromForeignMethod ( methodDescriptor . getSlashedClassName ( ) , methodDescriptor . getName ( ) , methodDescriptor . getSignature ( ) , methodDescriptor . isStatic ( ) ) ; }
Create a MethodAnnotation from a MethodDescriptor .
72
12
153,199
public void execute ( ) throws CheckedAnalysisException , IOException , InterruptedException { File dir = new File ( rootSourceDirectory ) ; if ( ! dir . isDirectory ( ) ) { throw new IOException ( "Path " + rootSourceDirectory + " is not a directory" ) ; } // Find all directories underneath the root source directory progress . startRecursiveDirectorySearch ( ) ; RecursiveFileSearch rfs = new RecursiveFileSearch ( rootSourceDirectory , pathname -> pathname . isDirectory ( ) ) ; rfs . search ( ) ; progress . doneRecursiveDirectorySearch ( ) ; List < String > candidateSourceDirList = rfs . getDirectoriesScanned ( ) ; // Build the classpath IClassFactory factory = ClassFactory . instance ( ) ; IClassPathBuilder builder = factory . createClassPathBuilder ( errorLogger ) ; try ( IClassPath classPath = buildClassPath ( builder , factory ) ) { // From the application classes, find the full list of // fully-qualified source file names. List < String > fullyQualifiedSourceFileNameList = findFullyQualifiedSourceFileNames ( builder , classPath ) ; // Attempt to find source directories for all source files, // and add them to the discoveredSourceDirectoryList if ( DEBUG ) { System . out . println ( "looking for " + fullyQualifiedSourceFileNameList . size ( ) + " files" ) ; } findSourceDirectoriesForAllSourceFiles ( fullyQualifiedSourceFileNameList , candidateSourceDirList ) ; } }
Execute the search for source directories .
322
8