idx
int64 0
165k
| question
stringlengths 73
4.15k
| target
stringlengths 5
918
| len_question
int64 21
890
| len_target
int64 3
255
|
|---|---|---|---|---|
153,400
|
private List < String > makeAbsoluteCwdCandidates ( String fileName ) { List < String > candidates = new ArrayList <> ( ) ; boolean hasProtocol = ( URLClassPath . getURLProtocol ( fileName ) != null ) ; if ( hasProtocol ) { candidates . add ( fileName ) ; return candidates ; } if ( new File ( fileName ) . isAbsolute ( ) ) { candidates . add ( fileName ) ; return candidates ; } for ( File currentWorkingDirectory : currentWorkingDirectoryList ) { File relativeToCurrent = new File ( currentWorkingDirectory , fileName ) ; if ( relativeToCurrent . exists ( ) ) { candidates . add ( relativeToCurrent . toString ( ) ) ; } } if ( candidates . isEmpty ( ) ) { candidates . add ( fileName ) ; } return candidates ; }
|
Make the given filename absolute relative to the current working directory candidates .
| 180
| 13
|
153,401
|
private < T > boolean addToListInternal ( Collection < T > list , T value ) { if ( ! list . contains ( value ) ) { list . add ( value ) ; isModified = true ; return true ; } else { return false ; } }
|
Add a value to given list making the Project modified if the value is not already present in the list .
| 55
| 21
|
153,402
|
private boolean doRedundantLoadElimination ( ) { if ( ! REDUNDANT_LOAD_ELIMINATION ) { return false ; } XField xfield = loadedFieldSet . getField ( handle ) ; if ( xfield == null ) { return false ; } // TODO: support two-slot fields return ! ( xfield . getSignature ( ) . equals ( "D" ) || xfield . getSignature ( ) . equals ( "J" ) ) ; }
|
Determine whether redundant load elimination should be performed for the heap location referenced by the current instruction .
| 106
| 20
|
153,403
|
private boolean doForwardSubstitution ( ) { if ( ! REDUNDANT_LOAD_ELIMINATION ) { return false ; } XField xfield = loadedFieldSet . getField ( handle ) ; if ( xfield == null ) { return false ; } if ( xfield . getSignature ( ) . equals ( "D" ) || xfield . getSignature ( ) . equals ( "J" ) ) { return false ; } // Don't do forward substitution for fields that // are never read. return loadedFieldSet . isLoaded ( xfield ) ; }
|
Determine whether forward substitution should be performed for the heap location referenced by the current instruction .
| 124
| 19
|
153,404
|
@ Override public void modelNormalInstruction ( Instruction ins , int numWordsConsumed , int numWordsProduced ) { int flags = 0 ; if ( ins instanceof InvokeInstruction ) { flags = ValueNumber . RETURN_VALUE ; } else if ( ins instanceof ArrayInstruction ) { flags = ValueNumber . ARRAY_VALUE ; } else if ( ins instanceof ConstantPushInstruction ) { flags = ValueNumber . CONSTANT_VALUE ; } // Get the input operands to this instruction. ValueNumber [ ] inputValueList = popInputValues ( numWordsConsumed ) ; // See if we have the output operands in the cache. // If not, push default (fresh) values for the output, // and add them to the cache. ValueNumber [ ] outputValueList = getOutputValues ( inputValueList , numWordsProduced , flags ) ; if ( VERIFY_INTEGRITY ) { checkConsumedAndProducedValues ( ins , inputValueList , outputValueList ) ; } // Push output operands on stack. pushOutputValues ( outputValueList ) ; }
|
This is the default instruction modeling method .
| 236
| 8
|
153,405
|
private ValueNumber [ ] popInputValues ( int numWordsConsumed ) { ValueNumberFrame frame = getFrame ( ) ; ValueNumber [ ] inputValueList = allocateValueNumberArray ( numWordsConsumed ) ; // Pop off the input operands. try { frame . getTopStackWords ( inputValueList ) ; while ( numWordsConsumed -- > 0 ) { frame . popValue ( ) ; } } catch ( DataflowAnalysisException e ) { throw new InvalidBytecodeException ( "Error getting input operands" , e ) ; } return inputValueList ; }
|
Pop the input values for the given instruction from the current frame .
| 121
| 13
|
153,406
|
private void pushOutputValues ( ValueNumber [ ] outputValueList ) { ValueNumberFrame frame = getFrame ( ) ; for ( ValueNumber aOutputValueList : outputValueList ) { frame . pushValue ( aOutputValueList ) ; } }
|
Push given output values onto the current frame .
| 52
| 9
|
153,407
|
private void loadInstanceField ( XField instanceField , Instruction obj ) { if ( RLE_DEBUG ) { System . out . println ( "[loadInstanceField for field " + instanceField + " in instruction " + handle ) ; } ValueNumberFrame frame = getFrame ( ) ; try { ValueNumber reference = frame . popValue ( ) ; AvailableLoad availableLoad = new AvailableLoad ( reference , instanceField ) ; if ( RLE_DEBUG ) { System . out . println ( "[getfield of " + availableLoad + "]" ) ; } ValueNumber [ ] loadedValue = frame . getAvailableLoad ( availableLoad ) ; if ( loadedValue == null ) { // Get (or create) the cached result for this instruction ValueNumber [ ] inputValueList = new ValueNumber [ ] { reference } ; loadedValue = getOutputValues ( inputValueList , getNumWordsProduced ( obj ) ) ; // Make the load available frame . addAvailableLoad ( availableLoad , loadedValue ) ; if ( RLE_DEBUG ) { System . out . println ( "[Making load available " + availableLoad + " <- " + vlts ( loadedValue ) + "]" ) ; } } else { // Found an available load! if ( RLE_DEBUG ) { System . out . println ( "[Found available load " + availableLoad + " <- " + vlts ( loadedValue ) + "]" ) ; } } pushOutputValues ( loadedValue ) ; if ( VERIFY_INTEGRITY ) { checkConsumedAndProducedValues ( obj , new ValueNumber [ ] { reference } , loadedValue ) ; } } catch ( DataflowAnalysisException e ) { throw new InvalidBytecodeException ( "Error loading from instance field" , e ) ; } }
|
Load an instance field .
| 372
| 5
|
153,408
|
private void loadStaticField ( XField staticField , Instruction obj ) { if ( RLE_DEBUG ) { System . out . println ( "[loadStaticField for field " + staticField + " in instruction " + handle ) ; } ValueNumberFrame frame = getFrame ( ) ; AvailableLoad availableLoad = new AvailableLoad ( staticField ) ; ValueNumber [ ] loadedValue = frame . getAvailableLoad ( availableLoad ) ; if ( loadedValue == null ) { // Make the load available int numWordsProduced = getNumWordsProduced ( obj ) ; loadedValue = getOutputValues ( EMPTY_INPUT_VALUE_LIST , numWordsProduced ) ; frame . addAvailableLoad ( availableLoad , loadedValue ) ; if ( RLE_DEBUG ) { System . out . println ( "[making load of " + staticField + " available]" ) ; } } else { if ( RLE_DEBUG ) { System . out . println ( "[found available load of " + staticField + "]" ) ; } } if ( VERIFY_INTEGRITY ) { checkConsumedAndProducedValues ( obj , EMPTY_INPUT_VALUE_LIST , loadedValue ) ; } pushOutputValues ( loadedValue ) ; }
|
Load a static field .
| 261
| 5
|
153,409
|
private void storeInstanceField ( XField instanceField , Instruction obj , boolean pushStoredValue ) { if ( RLE_DEBUG ) { System . out . println ( "[storeInstanceField for field " + instanceField + " in instruction " + handle ) ; } ValueNumberFrame frame = getFrame ( ) ; int numWordsConsumed = getNumWordsConsumed ( obj ) ; /* * System.out.println("Instruction is " + handle); * System.out.println("numWordsConsumed="+numWordsConsumed); */ ValueNumber [ ] inputValueList = popInputValues ( numWordsConsumed ) ; ValueNumber reference = inputValueList [ 0 ] ; ValueNumber [ ] storedValue = allocateValueNumberArray ( inputValueList . length - 1 ) ; System . arraycopy ( inputValueList , 1 , storedValue , 0 , inputValueList . length - 1 ) ; if ( pushStoredValue ) { pushOutputValues ( storedValue ) ; } // Kill all previous loads of the same field, // in case there is aliasing we don't know about frame . killLoadsOfField ( instanceField ) ; // Forward substitution frame . addAvailableLoad ( new AvailableLoad ( reference , instanceField ) , storedValue ) ; if ( RLE_DEBUG ) { System . out . println ( "[making store of " + instanceField + " available]" ) ; } if ( VERIFY_INTEGRITY ) { /* * System.out.println("pushStoredValue="+pushStoredValue); */ checkConsumedAndProducedValues ( obj , inputValueList , pushStoredValue ? storedValue : EMPTY_INPUT_VALUE_LIST ) ; } }
|
Store an instance field .
| 359
| 5
|
153,410
|
private void storeStaticField ( XField staticField , Instruction obj , boolean pushStoredValue ) { if ( RLE_DEBUG ) { System . out . println ( "[storeStaticField for field " + staticField + " in instruction " + handle ) ; } ValueNumberFrame frame = getFrame ( ) ; AvailableLoad availableLoad = new AvailableLoad ( staticField ) ; int numWordsConsumed = getNumWordsConsumed ( obj ) ; ValueNumber [ ] inputValueList = popInputValues ( numWordsConsumed ) ; if ( pushStoredValue ) { pushOutputValues ( inputValueList ) ; } // Kill loads of this field frame . killLoadsOfField ( staticField ) ; // Make load available frame . addAvailableLoad ( availableLoad , inputValueList ) ; if ( RLE_DEBUG ) { System . out . println ( "[making store of " + staticField + " available]" ) ; } if ( VERIFY_INTEGRITY ) { checkConsumedAndProducedValues ( obj , inputValueList , pushStoredValue ? inputValueList : EMPTY_INPUT_VALUE_LIST ) ; } }
|
Store a static field .
| 242
| 5
|
153,411
|
@ SuppressFBWarnings ( "ES_COMPARING_STRINGS_WITH_EQ" ) public String getDottedClassConstantOperand ( ) { if ( dottedClassConstantOperand != null ) { assert dottedClassConstantOperand != NOT_AVAILABLE ; return dottedClassConstantOperand ; } if ( classConstantOperand == NOT_AVAILABLE ) { throw new IllegalStateException ( "getDottedClassConstantOperand called but value not available" ) ; } dottedClassConstantOperand = ClassName . toDottedClassName ( classConstantOperand ) ; return dottedClassConstantOperand ; }
|
If the current opcode has a class operand get the associated class constant dot - formatted
| 146
| 18
|
153,412
|
@ Deprecated @ SuppressFBWarnings ( "ES_COMPARING_STRINGS_WITH_EQ" ) public String getRefConstantOperand ( ) { if ( refConstantOperand == NOT_AVAILABLE ) { throw new IllegalStateException ( "getRefConstantOperand called but value not available" ) ; } if ( refConstantOperand == null ) { String dottedClassConstantOperand = getDottedClassConstantOperand ( ) ; StringBuilder ref = new StringBuilder ( dottedClassConstantOperand . length ( ) + nameConstantOperand . length ( ) + sigConstantOperand . length ( ) + 5 ) ; ref . append ( dottedClassConstantOperand ) . append ( "." ) . append ( nameConstantOperand ) . append ( " : " ) . append ( replaceSlashesWithDots ( sigConstantOperand ) ) ; refConstantOperand = ref . toString ( ) ; } return refConstantOperand ; }
|
If the current opcode has a reference constant operand get its string representation
| 222
| 15
|
153,413
|
public int getPrevOpcode ( int offset ) { if ( offset < 0 ) { throw new IllegalArgumentException ( "offset (" + offset + ") must be nonnegative" ) ; } if ( offset >= prevOpcode . length || offset > sizePrevOpcodeBuffer ) { return Const . NOP ; } int pos = currentPosInPrevOpcodeBuffer - offset ; if ( pos < 0 ) { pos += prevOpcode . length ; } return prevOpcode [ pos ] ; }
|
return previous opcode ;
| 105
| 5
|
153,414
|
public void append ( DetectorFactory factory ) { if ( ! memberSet . contains ( factory ) ) { throw new IllegalArgumentException ( "Detector " + factory . getFullName ( ) + " appended to pass it doesn't belong to" ) ; } this . orderedFactoryList . addLast ( factory ) ; }
|
Append the given DetectorFactory to the end of the ordered detector list . The factory must be a member of the pass .
| 69
| 26
|
153,415
|
public Set < DetectorFactory > getUnpositionedMembers ( ) { HashSet < DetectorFactory > result = new HashSet <> ( memberSet ) ; result . removeAll ( orderedFactoryList ) ; return result ; }
|
Get Set of pass members which haven t been assigned a position in the pass .
| 48
| 16
|
153,416
|
protected void mergeInto ( FrameType other , FrameType result ) throws DataflowAnalysisException { // Handle if result Frame or the other Frame is the special "TOP" value. if ( result . isTop ( ) ) { // Result is the identity element, so copy the other Frame result . copyFrom ( other ) ; return ; } else if ( other . isTop ( ) ) { // Other Frame is the identity element, so result stays the same return ; } // Handle if result Frame or the other Frame is the special "BOTTOM" // value. if ( result . isBottom ( ) ) { // Result is the bottom element, so it stays that way return ; } else if ( other . isBottom ( ) ) { // Other Frame is the bottom element, so result becomes the bottom // element too result . setBottom ( ) ; return ; } // If the number of slots in the Frames differs, // then the result is the special "BOTTOM" value. if ( result . getNumSlots ( ) != other . getNumSlots ( ) ) { result . setBottom ( ) ; return ; } // Usual case: ordinary Frames consisting of the same number of values. // Merge each value in the two slot lists element-wise. for ( int i = 0 ; i < result . getNumSlots ( ) ; ++ i ) { mergeValues ( other , result , i ) ; } }
|
Merge one frame into another .
| 297
| 7
|
153,417
|
public LockSet getFactAtLocation ( Location location ) throws DataflowAnalysisException { if ( lockDataflow != null ) { return lockDataflow . getFactAtLocation ( location ) ; } else { LockSet lockSet = cache . get ( location ) ; if ( lockSet == null ) { lockSet = new LockSet ( ) ; lockSet . setDefaultLockCount ( 0 ) ; if ( method . isSynchronized ( ) && ! method . isStatic ( ) ) { // LockSet contains just the "this" reference ValueNumber instance = vnaDataflow . getAnalysis ( ) . getThisValue ( ) ; lockSet . setLockCount ( instance . getNumber ( ) , 1 ) ; } else { // LockSet is completely empty - nothing to do } cache . put ( location , lockSet ) ; } return lockSet ; } }
|
Get LockSet at given Location .
| 180
| 7
|
153,418
|
public Object getMethodAnalysis ( Class < ? > analysisClass , MethodDescriptor methodDescriptor ) { Map < MethodDescriptor , Object > objectMap = getObjectMap ( analysisClass ) ; return objectMap . get ( methodDescriptor ) ; }
|
Retrieve a method analysis object .
| 56
| 7
|
153,419
|
public void purgeMethodAnalyses ( MethodDescriptor methodDescriptor ) { Set < Map . Entry < Class < ? > , Map < MethodDescriptor , Object > > > entrySet = methodAnalysisObjectMap . entrySet ( ) ; for ( Iterator < Map . Entry < Class < ? > , Map < MethodDescriptor , Object > > > i = entrySet . iterator ( ) ; i . hasNext ( ) ; ) { Map . Entry < Class < ? > , Map < MethodDescriptor , Object > > entry = i . next ( ) ; Class < ? > cls = entry . getKey ( ) ; // FIXME: hack if ( ! DataflowAnalysis . class . isAssignableFrom ( cls ) && ! Dataflow . class . isAssignableFrom ( cls ) ) { // There is really no need to purge analysis results // that aren't CFG-based. // Currently, only dataflow analyses need // to be purged. continue ; } entry . getValue ( ) . remove ( methodDescriptor ) ; } }
|
Purge all CFG - based method analyses for given method .
| 230
| 13
|
153,420
|
public Method getMethod ( MethodGen methodGen ) { Method [ ] methodList = jclass . getMethods ( ) ; for ( Method method : methodList ) { if ( method . getName ( ) . equals ( methodGen . getName ( ) ) && method . getSignature ( ) . equals ( methodGen . getSignature ( ) ) && method . getAccessFlags ( ) == methodGen . getAccessFlags ( ) ) { return method ; } } return null ; }
|
Look up the Method represented by given MethodGen .
| 101
| 10
|
153,421
|
@ CheckForNull static public BitSet getBytecodeSet ( JavaClass clazz , Method method ) { XMethod xmethod = XFactory . createXMethod ( clazz , method ) ; if ( cachedBitsets ( ) . containsKey ( xmethod ) ) { return cachedBitsets ( ) . get ( xmethod ) ; } Code code = method . getCode ( ) ; if ( code == null ) { return null ; } byte [ ] instructionList = code . getCode ( ) ; // Create callback UnpackedBytecodeCallback callback = new UnpackedBytecodeCallback ( instructionList . length ) ; // Scan the method. BytecodeScanner scanner = new BytecodeScanner ( ) ; scanner . scan ( instructionList , callback ) ; UnpackedCode unpackedCode = callback . getUnpackedCode ( ) ; BitSet result = null ; if ( unpackedCode != null ) { result = unpackedCode . getBytecodeSet ( ) ; } cachedBitsets ( ) . put ( xmethod , result ) ; return result ; }
|
Get a BitSet representing the bytecodes that are used in the given method . This is useful for prescreening a method for the existence of particular instructions . Because this step doesn t require building a MethodGen it is very fast and memory - efficient . It may allow a Detector to avoid some very expensive analysis which is a Big Win for the user .
| 222
| 72
|
153,422
|
public ExceptionSet duplicate ( ) { ExceptionSet dup = factory . createExceptionSet ( ) ; dup . exceptionSet . clear ( ) ; dup . exceptionSet . or ( this . exceptionSet ) ; dup . explicitSet . clear ( ) ; dup . explicitSet . or ( this . explicitSet ) ; dup . size = this . size ; dup . universalHandler = this . universalHandler ; dup . commonSupertype = this . commonSupertype ; return dup ; }
|
Return an exact copy of this object .
| 97
| 8
|
153,423
|
public boolean isSingleton ( String exceptionName ) { if ( size != 1 ) { return false ; } ObjectType e = iterator ( ) . next ( ) ; return e . toString ( ) . equals ( exceptionName ) ; }
|
Checks to see if the exception set is a singleton set containing just the named exception
| 49
| 18
|
153,424
|
public void add ( ObjectType type , boolean explicit ) { int index = factory . getIndexOfType ( type ) ; if ( ! exceptionSet . get ( index ) ) { ++ size ; } exceptionSet . set ( index ) ; if ( explicit ) { explicitSet . set ( index ) ; } commonSupertype = null ; }
|
Add an exception .
| 70
| 4
|
153,425
|
public void addAll ( ExceptionSet other ) { exceptionSet . or ( other . exceptionSet ) ; explicitSet . or ( other . explicitSet ) ; size = countBits ( exceptionSet ) ; commonSupertype = null ; }
|
Add all exceptions in the given set .
| 49
| 8
|
153,426
|
public void clear ( ) { exceptionSet . clear ( ) ; explicitSet . clear ( ) ; universalHandler = false ; commonSupertype = null ; size = 0 ; }
|
Remove all exceptions from the set .
| 36
| 7
|
153,427
|
public boolean containsCheckedExceptions ( ) throws ClassNotFoundException { for ( ThrownExceptionIterator i = iterator ( ) ; i . hasNext ( ) ; ) { ObjectType type = i . next ( ) ; if ( ! Hierarchy . isUncheckedException ( type ) ) { return true ; } } return false ; }
|
Return whether or not the set contains any checked exceptions .
| 70
| 11
|
153,428
|
public boolean containsExplicitExceptions ( ) { for ( ThrownExceptionIterator i = iterator ( ) ; i . hasNext ( ) ; ) { i . next ( ) ; if ( i . isExplicit ( ) ) { return true ; } } return false ; }
|
Return whether or not the set contains any explicit exceptions .
| 57
| 11
|
153,429
|
public void fileReused ( File f ) { if ( ! recentFiles . contains ( f ) ) { throw new IllegalStateException ( "Selected a recent project that doesn't exist?" ) ; } else { recentFiles . remove ( f ) ; recentFiles . add ( f ) ; } }
|
This should be the method called to add a reused file for the recent menu .
| 62
| 16
|
153,430
|
public void fileNotFound ( File f ) { if ( ! recentFiles . contains ( f ) ) { throw new IllegalStateException ( "Well no wonder it wasn't found, its not in the list." ) ; } else { recentFiles . remove ( f ) ; } }
|
Call to remove a file from the list .
| 58
| 9
|
153,431
|
@ Override public int compareTo ( Edge other ) { int cmp = super . compareTo ( other ) ; if ( cmp != 0 ) { return cmp ; } return type - other . type ; }
|
Compare with other edge .
| 45
| 5
|
153,432
|
public String formatAsString ( boolean reverse ) { BasicBlock source = getSource ( ) ; BasicBlock target = getTarget ( ) ; StringBuilder buf = new StringBuilder ( ) ; buf . append ( reverse ? "REVERSE_EDGE(" : "EDGE(" ) ; buf . append ( getLabel ( ) ) ; buf . append ( ") type " ) ; buf . append ( edgeTypeToString ( type ) ) ; buf . append ( " from block " ) ; buf . append ( reverse ? target . getLabel ( ) : source . getLabel ( ) ) ; buf . append ( " to block " ) ; buf . append ( reverse ? source . getLabel ( ) : target . getLabel ( ) ) ; InstructionHandle sourceInstruction = source . getLastInstruction ( ) ; InstructionHandle targetInstruction = target . getFirstInstruction ( ) ; String exInfo = " -> " ; if ( targetInstruction == null && target . isExceptionThrower ( ) ) { targetInstruction = target . getExceptionThrower ( ) ; exInfo = " => " ; } if ( sourceInstruction != null && targetInstruction != null ) { buf . append ( " [bytecode " ) ; buf . append ( sourceInstruction . getPosition ( ) ) ; buf . append ( exInfo ) ; buf . append ( targetInstruction . getPosition ( ) ) ; buf . append ( ' ' ) ; } else if ( source . isExceptionThrower ( ) ) { if ( type == FALL_THROUGH_EDGE ) { buf . append ( " [successful check]" ) ; } else { buf . append ( " [failed check for " ) ; buf . append ( source . getExceptionThrower ( ) . getPosition ( ) ) ; if ( targetInstruction != null ) { buf . append ( " to " ) ; buf . append ( targetInstruction . getPosition ( ) ) ; } buf . append ( ' ' ) ; } } return buf . toString ( ) ; }
|
Return a string representation of the edge .
| 427
| 8
|
153,433
|
public static @ Type int stringToEdgeType ( String s ) { s = s . toUpperCase ( Locale . ENGLISH ) ; if ( "FALL_THROUGH" . equals ( s ) ) { return FALL_THROUGH_EDGE ; } else if ( "IFCMP" . equals ( s ) ) { return IFCMP_EDGE ; } else if ( "SWITCH" . equals ( s ) ) { return SWITCH_EDGE ; } else if ( "SWITCH_DEFAULT" . equals ( s ) ) { return SWITCH_DEFAULT_EDGE ; } else if ( "JSR" . equals ( s ) ) { return JSR_EDGE ; } else if ( "RET" . equals ( s ) ) { return RET_EDGE ; } else if ( "GOTO" . equals ( s ) ) { return GOTO_EDGE ; } else if ( "RETURN" . equals ( s ) ) { return RETURN_EDGE ; } else if ( "UNHANDLED_EXCEPTION" . equals ( s ) ) { return UNHANDLED_EXCEPTION_EDGE ; } else if ( "HANDLED_EXCEPTION" . equals ( s ) ) { return HANDLED_EXCEPTION_EDGE ; } else if ( "START" . equals ( s ) ) { return START_EDGE ; } else if ( "BACKEDGE_TARGET_EDGE" . equals ( s ) ) { return BACKEDGE_TARGET_EDGE ; } else if ( "BACKEDGE_SOURCE_EDGE" . equals ( s ) ) { return BACKEDGE_SOURCE_EDGE ; } else if ( "EXIT_EDGE" . equals ( s ) ) { return EXIT_EDGE ; } else { throw new IllegalArgumentException ( "Unknown edge type: " + s ) ; } }
|
Get numeric edge type from string representation .
| 417
| 8
|
153,434
|
public boolean isSameOrNewerThan ( JavaVersion other ) { return this . major > other . major || ( this . major == other . major && this . minor >= other . minor ) ; }
|
Return whether the Java version represented by this object is at least as recent as the one given .
| 43
| 19
|
153,435
|
public @ CheckForNull TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation ( ) { boolean firstPartialResult = true ; TypeQualifierAnnotation effective = null ; for ( PartialResult partialResult : partialResultList ) { if ( firstPartialResult ) { effective = partialResult . getTypeQualifierAnnotation ( ) ; firstPartialResult = false ; } else { effective = combine ( effective , partialResult . getTypeQualifierAnnotation ( ) ) ; } } return effective ; }
|
Get the effective TypeQualifierAnnotation .
| 106
| 9
|
153,436
|
protected void clearCaches ( ) { DescriptorFactory . clearInstance ( ) ; ObjectTypeFactory . clearInstance ( ) ; TypeQualifierApplications . clearInstance ( ) ; TypeQualifierAnnotation . clearInstance ( ) ; TypeQualifierValue . clearInstance ( ) ; // Make sure the codebases on the classpath are closed AnalysisContext . removeCurrentAnalysisContext ( ) ; Global . removeAnalysisCacheForCurrentThread ( ) ; IO . close ( classPath ) ; }
|
Protected to allow Eclipse plugin remember some cache data for later reuse
| 101
| 13
|
153,437
|
public static void registerBuiltInAnalysisEngines ( IAnalysisCache analysisCache ) { new edu . umd . cs . findbugs . classfile . engine . EngineRegistrar ( ) . registerAnalysisEngines ( analysisCache ) ; new edu . umd . cs . findbugs . classfile . engine . asm . EngineRegistrar ( ) . registerAnalysisEngines ( analysisCache ) ; new edu . umd . cs . findbugs . classfile . engine . bcel . EngineRegistrar ( ) . registerAnalysisEngines ( analysisCache ) ; }
|
Register the built - in analysis engines with given IAnalysisCache .
| 123
| 13
|
153,438
|
public static void registerPluginAnalysisEngines ( DetectorFactoryCollection detectorFactoryCollection , IAnalysisCache analysisCache ) throws IOException { for ( Iterator < Plugin > i = detectorFactoryCollection . pluginIterator ( ) ; i . hasNext ( ) ; ) { Plugin plugin = i . next ( ) ; Class < ? extends IAnalysisEngineRegistrar > engineRegistrarClass = plugin . getEngineRegistrarClass ( ) ; if ( engineRegistrarClass != null ) { try { IAnalysisEngineRegistrar engineRegistrar = engineRegistrarClass . newInstance ( ) ; engineRegistrar . registerAnalysisEngines ( analysisCache ) ; } catch ( InstantiationException e ) { IOException ioe = new IOException ( "Could not create analysis engine registrar for plugin " + plugin . getPluginId ( ) ) ; ioe . initCause ( e ) ; throw ioe ; } catch ( IllegalAccessException e ) { IOException ioe = new IOException ( "Could not create analysis engine registrar for plugin " + plugin . getPluginId ( ) ) ; ioe . initCause ( e ) ; throw ioe ; } } } }
|
Register all of the analysis engines defined in the plugins contained in a DetectorFactoryCollection with an IAnalysisCache .
| 248
| 23
|
153,439
|
private void buildClassPath ( ) throws InterruptedException , IOException , CheckedAnalysisException { IClassPathBuilder builder = classFactory . createClassPathBuilder ( bugReporter ) ; { HashSet < String > seen = new HashSet <> ( ) ; for ( String path : project . getFileArray ( ) ) { if ( seen . add ( path ) ) { builder . addCodeBase ( classFactory . createFilesystemCodeBaseLocator ( path ) , true ) ; } } for ( String path : project . getAuxClasspathEntryList ( ) ) { if ( seen . add ( path ) ) { builder . addCodeBase ( classFactory . createFilesystemCodeBaseLocator ( path ) , false ) ; } } } builder . scanNestedArchives ( analysisOptions . scanNestedArchives ) ; builder . build ( classPath , progressReporter ) ; appClassList = builder . getAppClassList ( ) ; if ( PROGRESS ) { System . out . println ( appClassList . size ( ) + " classes scanned" ) ; } // If any of the application codebases contain source code, // add them to the source path. // Also, use the last modified time of application codebases // to set the project timestamp. List < String > pathNames = new ArrayList <> ( ) ; for ( Iterator < ? extends ICodeBase > i = classPath . appCodeBaseIterator ( ) ; i . hasNext ( ) ; ) { ICodeBase appCodeBase = i . next ( ) ; if ( appCodeBase . containsSourceFiles ( ) ) { String pathName = appCodeBase . getPathName ( ) ; if ( pathName != null ) { pathNames . add ( pathName ) ; } } project . addTimestamp ( appCodeBase . getLastModifiedTime ( ) ) ; } project . addSourceDirs ( pathNames ) ; }
|
Build the classpath from project codebases and system codebases .
| 408
| 15
|
153,440
|
private void configureAnalysisFeatures ( ) { for ( AnalysisFeatureSetting setting : analysisOptions . analysisFeatureSettingList ) { setting . configure ( AnalysisContext . currentAnalysisContext ( ) ) ; } AnalysisContext . currentAnalysisContext ( ) . setBoolProperty ( AnalysisFeatures . MERGE_SIMILAR_WARNINGS , analysisOptions . mergeSimilarWarnings ) ; }
|
Configure analysis feature settings .
| 77
| 6
|
153,441
|
private void createExecutionPlan ( ) throws OrderingConstraintException { executionPlan = new ExecutionPlan ( ) ; // Use user preferences to decide which detectors are enabled. DetectorFactoryChooser detectorFactoryChooser = new DetectorFactoryChooser ( ) { HashSet < DetectorFactory > forcedEnabled = new HashSet <> ( ) ; @ Override public boolean choose ( DetectorFactory factory ) { boolean result = FindBugs . isDetectorEnabled ( FindBugs2 . this , factory , rankThreshold ) || forcedEnabled . contains ( factory ) ; if ( ExecutionPlan . DEBUG ) { System . out . printf ( " %6s %s %n" , result , factory . getShortName ( ) ) ; } return result ; } @ Override public void enable ( DetectorFactory factory ) { forcedEnabled . add ( factory ) ; factory . setEnabledButNonReporting ( true ) ; } } ; executionPlan . setDetectorFactoryChooser ( detectorFactoryChooser ) ; if ( ExecutionPlan . DEBUG ) { System . out . println ( "rank threshold is " + rankThreshold ) ; } // Add plugins for ( Iterator < Plugin > i = detectorFactoryCollection . pluginIterator ( ) ; i . hasNext ( ) ; ) { Plugin plugin = i . next ( ) ; if ( DEBUG ) { System . out . println ( "Adding plugin " + plugin . getPluginId ( ) + " to execution plan" ) ; } executionPlan . addPlugin ( plugin ) ; } // Build the execution plan executionPlan . build ( ) ; // Stash the ExecutionPlan in the AnalysisCache. Global . getAnalysisCache ( ) . eagerlyPutDatabase ( ExecutionPlan . class , executionPlan ) ; if ( PROGRESS ) { System . out . println ( executionPlan . getNumPasses ( ) + " passes in execution plan" ) ; } }
|
Create an execution plan .
| 395
| 5
|
153,442
|
private void logRecoverableException ( ClassDescriptor classDescriptor , Detector2 detector , Throwable e ) { bugReporter . logError ( "Exception analyzing " + classDescriptor . toDottedClassName ( ) + " using detector " + detector . getDetectorClassName ( ) , e ) ; }
|
Report an exception that occurred while analyzing a class with a detector .
| 71
| 13
|
153,443
|
public static < E > Set < E > newSetFromMap ( Map < E , Boolean > m ) { return new SetFromMap <> ( m ) ; }
|
Duplication 1 . 6 functionality of Collections . newSetFromMap
| 35
| 14
|
153,444
|
protected VertexType getNextSearchTreeRoot ( ) { // FIXME: slow linear search, should improve for ( Iterator < VertexType > i = graph . vertexIterator ( ) ; i . hasNext ( ) ; ) { VertexType vertex = i . next ( ) ; if ( visitMe ( vertex ) ) { return vertex ; } } return null ; }
|
Choose the next search tree root . By default this method just scans for a WHITE vertex . Subclasses may override this method in order to choose which vertices are used as search tree roots .
| 78
| 38
|
153,445
|
private void classifyUnknownEdges ( ) { Iterator < EdgeType > edgeIter = graph . edgeIterator ( ) ; while ( edgeIter . hasNext ( ) ) { EdgeType edge = edgeIter . next ( ) ; int dfsEdgeType = getDFSEdgeType ( edge ) ; if ( dfsEdgeType == UNKNOWN_EDGE ) { int srcDiscoveryTime = getDiscoveryTime ( getSource ( edge ) ) ; int destDiscoveryTime = getDiscoveryTime ( getTarget ( edge ) ) ; if ( srcDiscoveryTime < destDiscoveryTime ) { // If the source was visited earlier than the // target, it's a forward edge. dfsEdgeType = FORWARD_EDGE ; } else { // If the source was visited later than the // target, it's a cross edge. dfsEdgeType = CROSS_EDGE ; } setDFSEdgeType ( edge , dfsEdgeType ) ; } } }
|
Classify CROSS and FORWARD edges
| 206
| 8
|
153,446
|
protected void consumeStack ( Instruction ins ) { ConstantPoolGen cpg = getCPG ( ) ; TypeFrame frame = getFrame ( ) ; int numWordsConsumed = ins . consumeStack ( cpg ) ; if ( numWordsConsumed == Const . UNPREDICTABLE ) { throw new InvalidBytecodeException ( "Unpredictable stack consumption for " + ins ) ; } if ( numWordsConsumed > frame . getStackDepth ( ) ) { throw new InvalidBytecodeException ( "Stack underflow for " + ins + ", " + numWordsConsumed + " needed, " + frame . getStackDepth ( ) + " avail, frame is " + frame ) ; } try { while ( numWordsConsumed -- > 0 ) { frame . popValue ( ) ; } } catch ( DataflowAnalysisException e ) { throw new InvalidBytecodeException ( "Stack underflow for " + ins + ": " + e . getMessage ( ) ) ; } }
|
Consume stack . This is a convenience method for instructions where the types of popped operands can be ignored .
| 207
| 22
|
153,447
|
protected void pushReturnType ( InvokeInstruction ins ) { ConstantPoolGen cpg = getCPG ( ) ; Type type = ins . getType ( cpg ) ; if ( type . getType ( ) != Const . T_VOID ) { pushValue ( type ) ; } }
|
Helper for pushing the return type of an invoke instruction .
| 62
| 11
|
153,448
|
@ Override public void modelNormalInstruction ( Instruction ins , int numWordsConsumed , int numWordsProduced ) { if ( VERIFY_INTEGRITY ) { if ( numWordsProduced > 0 ) { throw new InvalidBytecodeException ( "missing visitor method for " + ins ) ; } } super . modelNormalInstruction ( ins , numWordsConsumed , numWordsProduced ) ; }
|
This is overridden only to ensure that we don t rely on the base class to handle instructions that produce stack operands .
| 88
| 25
|
153,449
|
private Iterator < Edge > logicalPredecessorEdgeIterator ( BasicBlock block ) { return isForwards ? cfg . incomingEdgeIterator ( block ) : cfg . outgoingEdgeIterator ( block ) ; }
|
Return an Iterator over edges that connect given block to its logical predecessors . For forward analyses this is the incoming edges . For backward analyses this is the outgoing edges .
| 44
| 33
|
153,450
|
private int stackEntryThatMustBeNonnegative ( int seen ) { switch ( seen ) { case Const . INVOKEINTERFACE : if ( "java/util/List" . equals ( getClassConstantOperand ( ) ) ) { return getStackEntryOfListCallThatMustBeNonnegative ( ) ; } break ; case Const . INVOKEVIRTUAL : if ( "java/util/LinkedList" . equals ( getClassConstantOperand ( ) ) || "java/util/ArrayList" . equals ( getClassConstantOperand ( ) ) ) { return getStackEntryOfListCallThatMustBeNonnegative ( ) ; } break ; case Const . IALOAD : case Const . AALOAD : case Const . SALOAD : case Const . CALOAD : case Const . BALOAD : case Const . LALOAD : case Const . DALOAD : case Const . FALOAD : return 0 ; case Const . IASTORE : case Const . AASTORE : case Const . SASTORE : case Const . CASTORE : case Const . BASTORE : case Const . LASTORE : case Const . DASTORE : case Const . FASTORE : return 1 ; } return - 1 ; }
|
Return index of stack entry that must be nonnegative .
| 263
| 11
|
153,451
|
private void flush ( ) { if ( pendingAbsoluteValueBug != null ) { absoluteValueAccumulator . accumulateBug ( pendingAbsoluteValueBug , pendingAbsoluteValueBugSourceLine ) ; pendingAbsoluteValueBug = null ; pendingAbsoluteValueBugSourceLine = null ; } accumulator . reportAccumulatedBugs ( ) ; if ( sawLoadOfMinValue ) { absoluteValueAccumulator . clearBugs ( ) ; } else { absoluteValueAccumulator . reportAccumulatedBugs ( ) ; } if ( gcInvocationBugReport != null && ! sawCurrentTimeMillis ) { // Make sure the GC invocation is not in an exception handler // for OutOfMemoryError. boolean outOfMemoryHandler = false ; for ( CodeException handler : exceptionTable ) { if ( gcInvocationPC < handler . getHandlerPC ( ) || gcInvocationPC > handler . getHandlerPC ( ) + OOM_CATCH_LEN ) { continue ; } int catchTypeIndex = handler . getCatchType ( ) ; if ( catchTypeIndex > 0 ) { ConstantPool cp = getThisClass ( ) . getConstantPool ( ) ; Constant constant = cp . getConstant ( catchTypeIndex ) ; if ( constant instanceof ConstantClass ) { String exClassName = ( String ) ( ( ConstantClass ) constant ) . getConstantValue ( cp ) ; if ( "java/lang/OutOfMemoryError" . equals ( exClassName ) ) { outOfMemoryHandler = true ; break ; } } } } if ( ! outOfMemoryHandler ) { bugReporter . reportBug ( gcInvocationBugReport ) ; } } sawCurrentTimeMillis = false ; gcInvocationBugReport = null ; exceptionTable = null ; }
|
Flush out cached state at the end of a method .
| 381
| 12
|
153,452
|
public boolean isNullCheck ( ) { // Null check blocks must be exception throwers, // and are always empty. (The only kind of non-empty // exception throwing block is one terminated by an ATHROW). if ( ! isExceptionThrower ( ) || getFirstInstruction ( ) != null ) { return false ; } short opcode = exceptionThrower . getInstruction ( ) . getOpcode ( ) ; return nullCheckInstructionSet . get ( opcode ) ; }
|
Return whether or not this block is a null check .
| 104
| 11
|
153,453
|
public @ CheckForNull InstructionHandle getSuccessorOf ( InstructionHandle handle ) { if ( VERIFY_INTEGRITY && ! containsInstruction ( handle ) ) { throw new IllegalStateException ( ) ; } return handle == lastInstruction ? null : handle . getNext ( ) ; }
|
Get the successor of given instruction within the basic block .
| 63
| 11
|
153,454
|
public InstructionHandle getPredecessorOf ( InstructionHandle handle ) { if ( VERIFY_INTEGRITY && ! containsInstruction ( handle ) ) { throw new IllegalStateException ( ) ; } return handle == firstInstruction ? null : handle . getPrev ( ) ; }
|
Get the predecessor of given instruction within the basic block .
| 60
| 11
|
153,455
|
public void addInstruction ( InstructionHandle handle ) { if ( firstInstruction == null ) { firstInstruction = lastInstruction = handle ; } else { if ( VERIFY_INTEGRITY && handle != lastInstruction . getNext ( ) ) { throw new IllegalStateException ( "Adding non-consecutive instruction" ) ; } lastInstruction = handle ; } }
|
Add an InstructionHandle to the basic block .
| 82
| 9
|
153,456
|
public boolean containsInstruction ( InstructionHandle handle ) { Iterator < InstructionHandle > i = instructionIterator ( ) ; while ( i . hasNext ( ) ) { if ( i . next ( ) == handle ) { return true ; } } return false ; }
|
Return whether or not the basic block contains the given instruction .
| 54
| 12
|
153,457
|
public boolean containsInstructionWithOffset ( int offset ) { Iterator < InstructionHandle > i = instructionIterator ( ) ; while ( i . hasNext ( ) ) { if ( i . next ( ) . getPosition ( ) == offset ) { return true ; } } return false ; }
|
Return whether or not the basic block contains the instruction with the given bytecode offset .
| 60
| 17
|
153,458
|
public static void writeFile ( IFile file , final FileOutput output , IProgressMonitor monitor ) throws CoreException { try { ByteArrayOutputStream bos = new ByteArrayOutputStream ( ) ; output . writeFile ( bos ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( bos . toByteArray ( ) ) ; if ( ! file . exists ( ) ) { mkdirs ( file , monitor ) ; file . create ( bis , true , monitor ) ; } else { file . setContents ( bis , true , false , monitor ) ; } } catch ( IOException e ) { IStatus status = FindbugsPlugin . createErrorStatus ( "Exception while " + output . getTaskDescription ( ) , e ) ; throw new CoreException ( status ) ; } }
|
Write the contents of a file in the Eclipse workspace .
| 163
| 11
|
153,459
|
public static void writeFile ( final File file , final FileOutput output , final IProgressMonitor monitor ) throws CoreException { try ( FileOutputStream fout = new FileOutputStream ( file ) ; BufferedOutputStream bout = new BufferedOutputStream ( fout ) ) { if ( monitor != null ) { monitor . subTask ( "writing data to " + file . getName ( ) ) ; } output . writeFile ( bout ) ; bout . flush ( ) ; } catch ( IOException e ) { IStatus status = FindbugsPlugin . createErrorStatus ( "Exception while " + output . getTaskDescription ( ) , e ) ; throw new CoreException ( status ) ; } }
|
Write the contents of a java . io . File
| 145
| 10
|
153,460
|
public static void createMarkers ( final IJavaProject javaProject , final SortedBugCollection theCollection , final ISchedulingRule rule , IProgressMonitor monitor ) { if ( monitor . isCanceled ( ) ) { return ; } final List < MarkerParameter > bugParameters = createBugParameters ( javaProject , theCollection , monitor ) ; if ( monitor . isCanceled ( ) ) { return ; } WorkspaceJob wsJob = new WorkspaceJob ( "Creating SpotBugs markers" ) { @ Override public IStatus runInWorkspace ( IProgressMonitor monitor1 ) throws CoreException { IProject project = javaProject . getProject ( ) ; try { new MarkerReporter ( bugParameters , theCollection , project ) . run ( monitor1 ) ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Core exception on add marker" ) ; return e . getStatus ( ) ; } return monitor1 . isCanceled ( ) ? Status . CANCEL_STATUS : Status . OK_STATUS ; } } ; wsJob . setRule ( rule ) ; wsJob . setSystem ( true ) ; wsJob . setUser ( false ) ; wsJob . schedule ( ) ; }
|
Create an Eclipse marker for given BugInstance .
| 274
| 9
|
153,461
|
public static List < MarkerParameter > createBugParameters ( IJavaProject project , BugCollection theCollection , IProgressMonitor monitor ) { List < MarkerParameter > bugParameters = new ArrayList <> ( ) ; if ( project == null ) { FindbugsPlugin . getDefault ( ) . logException ( new NullPointerException ( "project is null" ) , "project is null" ) ; return bugParameters ; } Iterator < BugInstance > iterator = theCollection . iterator ( ) ; while ( iterator . hasNext ( ) && ! monitor . isCanceled ( ) ) { BugInstance bug = iterator . next ( ) ; DetectorFactory detectorFactory = bug . getDetectorFactory ( ) ; if ( detectorFactory != null && ! detectorFactory . getPlugin ( ) . isGloballyEnabled ( ) ) { continue ; } MarkerParameter mp = createMarkerParameter ( project , bug ) ; if ( mp != null ) { bugParameters . add ( mp ) ; } } return bugParameters ; }
|
As a side - effect this method updates missing line information for some bugs stored in the given bug collection
| 214
| 20
|
153,462
|
public static void removeMarkers ( IResource res ) throws CoreException { // remove any markers added by our builder // This triggers resource update on IResourceChangeListener's // (BugTreeView) res . deleteMarkers ( FindBugsMarker . NAME , true , IResource . DEPTH_INFINITE ) ; if ( res instanceof IProject ) { IProject project = ( IProject ) res ; FindbugsPlugin . clearBugCollection ( project ) ; } }
|
Remove all FindBugs problem markers for given resource . If the given resource is project will also clear bug collection .
| 100
| 23
|
153,463
|
public static void redisplayMarkers ( final IJavaProject javaProject ) { final IProject project = javaProject . getProject ( ) ; FindBugsJob job = new FindBugsJob ( "Refreshing SpotBugs markers" , project ) { @ Override protected void runWithProgress ( IProgressMonitor monitor ) throws CoreException { // TODO in case we removed some of previously available // detectors, we should // throw away bugs reported by them // Get the saved bug collection for the project SortedBugCollection bugs = FindbugsPlugin . getBugCollection ( project , monitor ) ; // Remove old markers project . deleteMarkers ( FindBugsMarker . NAME , true , IResource . DEPTH_INFINITE ) ; // Display warnings createMarkers ( javaProject , bugs , project , monitor ) ; } } ; job . setRule ( project ) ; job . scheduleInteractive ( ) ; }
|
Attempt to redisplay FindBugs problem markers for given project .
| 193
| 14
|
153,464
|
public static @ CheckForNull BugInstance findBugInstanceForMarker ( IMarker marker ) { BugCollectionAndInstance bci = findBugCollectionAndInstanceForMarker ( marker ) ; if ( bci == null ) { return null ; } return bci . bugInstance ; }
|
Find the BugInstance associated with given FindBugs marker .
| 60
| 12
|
153,465
|
public static @ CheckForNull BugCollectionAndInstance findBugCollectionAndInstanceForMarker ( IMarker marker ) { IResource resource = marker . getResource ( ) ; IProject project = resource . getProject ( ) ; if ( project == null ) { // Also shouldn't happen. FindbugsPlugin . getDefault ( ) . logError ( "No project for warning marker" ) ; return null ; } if ( ! isFindBugsMarker ( marker ) ) { // log disabled because otherwise each selection in problems view // generates // 6 new errors (we need refactor all bug views to get rid of this). // FindbugsPlugin.getDefault().logError("Selected marker is not a FindBugs marker"); // FindbugsPlugin.getDefault().logError(marker.getType()); // FindbugsPlugin.getDefault().logError(FindBugsMarker.NAME); return null ; } // We have a FindBugs marker. Get the corresponding BugInstance. String bugId = marker . getAttribute ( FindBugsMarker . UNIQUE_ID , null ) ; if ( bugId == null ) { FindbugsPlugin . getDefault ( ) . logError ( "Marker does not contain unique id for warning" ) ; return null ; } try { BugCollection bugCollection = FindbugsPlugin . getBugCollection ( project , null ) ; if ( bugCollection == null ) { FindbugsPlugin . getDefault ( ) . logError ( "Could not get BugCollection for SpotBugs marker" ) ; return null ; } String bugType = ( String ) marker . getAttribute ( FindBugsMarker . BUG_TYPE ) ; Integer primaryLineNumber = ( Integer ) marker . getAttribute ( FindBugsMarker . PRIMARY_LINE ) ; // compatibility if ( primaryLineNumber == null ) { primaryLineNumber = Integer . valueOf ( getEditorLine ( marker ) ) ; } if ( bugType == null ) { FindbugsPlugin . getDefault ( ) . logError ( "Could not get find attributes for marker " + marker + ": (" + bugId + ", " + primaryLineNumber + ")" ) ; return null ; } BugInstance bug = bugCollection . findBug ( bugId , bugType , primaryLineNumber . intValue ( ) ) ; if ( bug == null ) { FindbugsPlugin . getDefault ( ) . logError ( "Could not get find bug for marker on " + resource + ": (" + bugId + ", " + primaryLineNumber + ")" ) ; return null ; } return new BugCollectionAndInstance ( bugCollection , bug ) ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Could not get BugInstance for SpotBugs marker" ) ; return null ; } }
|
Find the BugCollectionAndInstance associated with given FindBugs marker .
| 592
| 14
|
153,466
|
public static Set < IMarker > getMarkerFromSelection ( ISelection selection ) { Set < IMarker > markers = new HashSet <> ( ) ; if ( ! ( selection instanceof IStructuredSelection ) ) { return markers ; } IStructuredSelection sSelection = ( IStructuredSelection ) selection ; for ( Iterator < ? > iter = sSelection . iterator ( ) ; iter . hasNext ( ) ; ) { Object next = iter . next ( ) ; markers . addAll ( getMarkers ( next ) ) ; } return markers ; }
|
Fish an IMarker out of given selection .
| 126
| 10
|
153,467
|
public static IMarker getMarkerFromEditor ( ITextSelection selection , IEditorPart editor ) { IResource resource = ( IResource ) editor . getEditorInput ( ) . getAdapter ( IFile . class ) ; IMarker [ ] allMarkers ; if ( resource != null ) { allMarkers = getMarkers ( resource , IResource . DEPTH_ZERO ) ; } else { IClassFile classFile = ( IClassFile ) editor . getEditorInput ( ) . getAdapter ( IClassFile . class ) ; if ( classFile == null ) { return null ; } Set < IMarker > markers = getMarkers ( classFile . getType ( ) ) ; allMarkers = markers . toArray ( new IMarker [ markers . size ( ) ] ) ; } // if editor contains only one FB marker, do some cheating and always // return it. if ( allMarkers . length == 1 ) { return allMarkers [ 0 ] ; } // +1 because it counts real lines, but editor shows lines + 1 int startLine = selection . getStartLine ( ) + 1 ; for ( IMarker marker : allMarkers ) { int line = getEditorLine ( marker ) ; if ( startLine == line ) { return marker ; } } return null ; }
|
Tries to retrieve right bug marker for given selection . If there are many markers for given editor and text selection doesn t match any of them return null . If there is only one marker for given editor returns this marker in any case .
| 279
| 47
|
153,468
|
@ Nonnull public static IMarker [ ] getMarkers ( IResource fileOrFolder , int depth ) { if ( fileOrFolder . getType ( ) == IResource . PROJECT ) { if ( ! fileOrFolder . isAccessible ( ) ) { // user just closed the project decorator is working on, avoid exception here return EMPTY ; } } try { return fileOrFolder . findMarkers ( FindBugsMarker . NAME , true , depth ) ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Cannot collect SpotBugs warnings from: " + fileOrFolder ) ; } return EMPTY ; }
|
Retrieves all the FB markers from given resource and all its descendants
| 146
| 14
|
153,469
|
private void syncMenu ( ) { if ( bugInstance != null ) { BugProperty severityProperty = bugInstance . lookupProperty ( BugProperty . SEVERITY ) ; if ( severityProperty != null ) { try { int severity = severityProperty . getValueAsInt ( ) ; if ( severity > 0 && severity <= severityItemList . length ) { selectSeverity ( severity ) ; return ; } } catch ( NumberFormatException e ) { // Ignore: we'll allow the user to select a valid severity } } // We didn't get a valid severity from the BugInstance. // So, leave the menu items enabled but cleared, so // the user can select a severity. resetMenuItems ( true ) ; } else { // No BugInstance - disable all menu items. resetMenuItems ( false ) ; } }
|
Synchronize the menu with the current BugInstance .
| 169
| 11
|
153,470
|
private void selectSeverity ( int severity ) { // Severity is 1-based, but the menu item list is 0-based int index = severity - 1 ; for ( int i = 0 ; i < severityItemList . length ; ++ i ) { MenuItem menuItem = severityItemList [ i ] ; menuItem . setEnabled ( true ) ; menuItem . setSelection ( i == index ) ; } }
|
Set the menu to given severity level .
| 89
| 8
|
153,471
|
private void resetMenuItems ( boolean enable ) { for ( int i = 0 ; i < severityItemList . length ; ++ i ) { MenuItem menuItem = severityItemList [ i ] ; menuItem . setEnabled ( enable ) ; menuItem . setSelection ( false ) ; } }
|
Reset menu items so they are unchecked .
| 62
| 9
|
153,472
|
public ValueNumber [ ] lookupOutputValues ( Entry entry ) { if ( DEBUG ) { System . out . println ( "VN cache lookup: " + entry ) ; } ValueNumber [ ] result = entryToOutputMap . get ( entry ) ; if ( DEBUG ) { System . out . println ( " result ==> " + Arrays . toString ( result ) ) ; } return result ; }
|
Look up cached output values for given entry .
| 84
| 9
|
153,473
|
public Binding lookup ( String varName ) { if ( varName . equals ( binding . getVarName ( ) ) ) { return binding ; } return parent != null ? parent . lookup ( varName ) : null ; }
|
Look for a Binding for given variable .
| 46
| 8
|
153,474
|
private IsNullValueFrame replaceValues ( IsNullValueFrame origFrame , IsNullValueFrame frame , ValueNumber replaceMe , ValueNumberFrame prevVnaFrame , ValueNumberFrame targetVnaFrame , IsNullValue replacementValue ) { if ( ! targetVnaFrame . isValid ( ) ) { throw new IllegalArgumentException ( "Invalid frame in " + methodGen . getClassName ( ) + "." + methodGen . getName ( ) + " : " + methodGen . getSignature ( ) ) ; } // If required, make a copy of the frame frame = modifyFrame ( origFrame , frame ) ; assert frame . getNumSlots ( ) == targetVnaFrame . getNumSlots ( ) : " frame has " + frame . getNumSlots ( ) + ", target has " + targetVnaFrame . getNumSlots ( ) + " in " + classAndMethod ; // The VNA frame may have more slots than the IsNullValueFrame // if it was produced by an IF comparison (whose operand or operands // are subsequently popped off the stack). final int targetNumSlots = targetVnaFrame . getNumSlots ( ) ; final int prefixNumSlots = Math . min ( frame . getNumSlots ( ) , prevVnaFrame . getNumSlots ( ) ) ; if ( trackValueNumbers ) { AvailableLoad loadForV = prevVnaFrame . getLoad ( replaceMe ) ; if ( DEBUG && loadForV != null ) { System . out . println ( "For " + replaceMe + " availableLoad is " + loadForV ) ; ValueNumber [ ] matchingValueNumbers = targetVnaFrame . getAvailableLoad ( loadForV ) ; if ( matchingValueNumbers != null ) { for ( ValueNumber v2 : matchingValueNumbers ) { System . out . println ( " matches " + v2 ) ; } } } if ( loadForV != null ) { ValueNumber [ ] matchingValueNumbers = targetVnaFrame . getAvailableLoad ( loadForV ) ; if ( matchingValueNumbers != null ) { for ( ValueNumber v2 : matchingValueNumbers ) { if ( ! replaceMe . equals ( v2 ) ) { frame . setKnownValue ( v2 , replacementValue ) ; if ( DEBUG ) { System . out . println ( "For " + loadForV + " switch from " + replaceMe + " to " + v2 ) ; } } } } } frame . setKnownValue ( replaceMe , replacementValue ) ; } // Here's the deal: // - "replaceMe" is the value number from the previous frame (at the if // branch) // which indicates a value that we have updated is-null information // about // - in the target value number frame (at entry to the target block), // we find the value number in the stack slot corresponding to the // "replaceMe" // value; this is the "corresponding" value // - all instances of the "corresponding" value in the target frame have // their is-null information updated to "replacementValue" // This should thoroughly make use of the updated information. for ( int i = 0 ; i < prefixNumSlots ; ++ i ) { if ( prevVnaFrame . getValue ( i ) . equals ( replaceMe ) ) { ValueNumber corresponding = targetVnaFrame . getValue ( i ) ; for ( int j = 0 ; j < targetNumSlots ; ++ j ) { if ( targetVnaFrame . getValue ( j ) . equals ( corresponding ) ) { frame . setValue ( j , replacementValue ) ; } } } } return frame ; }
|
Update is - null information at a branch target based on information gained at a null comparison branch .
| 774
| 19
|
153,475
|
protected void obtainFindBugsMarkers ( ) { // Delete old markers markers . clear ( ) ; if ( editor == null || ruler == null ) { return ; } // Obtain all markers in the editor IResource resource = ( IResource ) editor . getEditorInput ( ) . getAdapter ( IFile . class ) ; if ( resource == null ) { return ; } IMarker [ ] allMarkers = MarkerUtil . getMarkers ( resource , IResource . DEPTH_ZERO ) ; if ( allMarkers . length == 0 ) { return ; } // Discover relevant markers, i.e. FindBugsMarkers AbstractMarkerAnnotationModel model = getModel ( ) ; IDocument document = getDocument ( ) ; for ( int i = 0 ; i < allMarkers . length ; i ++ ) { if ( includesRulerLine ( model . getMarkerPosition ( allMarkers [ i ] ) , document ) ) { if ( MarkerUtil . isFindBugsMarker ( allMarkers [ i ] ) ) { markers . add ( allMarkers [ i ] ) ; } } } }
|
Fills markers field with all of the FindBugs markers associated with the current line in the text editor s ruler marign .
| 243
| 26
|
153,476
|
protected boolean includesRulerLine ( Position position , IDocument document ) { if ( position != null && ruler != null ) { try { int markerLine = document . getLineOfOffset ( position . getOffset ( ) ) ; int line = ruler . getLineOfLastMouseButtonActivity ( ) ; if ( line == markerLine ) { return true ; } } catch ( BadLocationException x ) { FindbugsPlugin . getDefault ( ) . logException ( x , "Error getting marker line" ) ; } } return false ; }
|
Checks a Position in a document to see whether the line of last mouse activity falls within this region .
| 111
| 21
|
153,477
|
@ CheckForNull protected AbstractMarkerAnnotationModel getModel ( ) { if ( editor == null ) { return null ; } IDocumentProvider provider = editor . getDocumentProvider ( ) ; IAnnotationModel model = provider . getAnnotationModel ( editor . getEditorInput ( ) ) ; if ( model instanceof AbstractMarkerAnnotationModel ) { return ( AbstractMarkerAnnotationModel ) model ; } return null ; }
|
Retrieves the AbstractMarkerAnnontationsModel from the editor .
| 91
| 15
|
153,478
|
protected IDocument getDocument ( ) { Assert . isNotNull ( editor ) ; IDocumentProvider provider = editor . getDocumentProvider ( ) ; return provider . getDocument ( editor . getEditorInput ( ) ) ; }
|
Retrieves the document from the editor .
| 47
| 9
|
153,479
|
public void setProjectChanged ( boolean b ) { if ( curProject == null ) { return ; } if ( projectChanged == b ) { return ; } projectChanged = b ; mainFrameMenu . setSaveMenu ( this ) ; getRootPane ( ) . putClientProperty ( WINDOW_MODIFIED , b ) ; }
|
Called when something in the project is changed and the change needs to be saved . This method should be called instead of using projectChanged = b .
| 70
| 30
|
153,480
|
void callOnClose ( ) { if ( projectChanged && ! SystemProperties . getBoolean ( "findbugs.skipSaveChangesWarning" ) ) { Object [ ] options = { L10N . getLocalString ( "dlg.save_btn" , "Save" ) , L10N . getLocalString ( "dlg.dontsave_btn" , "Don't Save" ) , L10N . getLocalString ( "dlg.cancel_btn" , "Cancel" ) , } ; int value = JOptionPane . showOptionDialog ( this , getActionWithoutSavingMsg ( "closing" ) , L10N . getLocalString ( "msg.confirm_save_txt" , "Do you want to save?" ) , JOptionPane . YES_NO_CANCEL_OPTION , JOptionPane . QUESTION_MESSAGE , null , options , options [ 0 ] ) ; if ( value == 2 || value == JOptionPane . CLOSED_OPTION ) { return ; } else if ( value == 0 ) { if ( saveFile == null ) { if ( ! mainFrameLoadSaveHelper . saveAs ( ) ) { return ; } } else { mainFrameLoadSaveHelper . save ( ) ; } } } GUISaveState guiSaveState = GUISaveState . getInstance ( ) ; guiLayout . saveState ( ) ; guiSaveState . setFrameBounds ( getBounds ( ) ) ; guiSaveState . setExtendedWindowState ( getExtendedState ( ) ) ; guiSaveState . save ( ) ; System . exit ( 0 ) ; }
|
This method is called when the application is closing . This is either by the exit menuItem or by clicking on the window s system menu .
| 356
| 28
|
153,481
|
public boolean openAnalysis ( File f , SaveType saveType ) { if ( ! f . exists ( ) || ! f . canRead ( ) ) { throw new IllegalArgumentException ( "Can't read " + f . getPath ( ) ) ; } mainFrameLoadSaveHelper . prepareForFileLoad ( f , saveType ) ; mainFrameLoadSaveHelper . loadAnalysis ( f ) ; return true ; }
|
Opens the analysis . Also clears the source and summary panes . Makes comments enabled false . Sets the saveType and adds the file to the recent menu .
| 87
| 32
|
153,482
|
public void updateTitle ( ) { Project project = getProject ( ) ; String name = project . getProjectName ( ) ; if ( ( name == null || "" . equals ( name . trim ( ) ) ) && saveFile != null ) { name = saveFile . getAbsolutePath ( ) ; } if ( name == null ) { name = "" ; //Project.UNNAMED_PROJECT; } String oldTitle = this . getTitle ( ) ; String newTitle = TITLE_START_TXT + ( "" . equals ( name . trim ( ) ) ? "" : " - " + name ) ; if ( oldTitle . equals ( newTitle ) ) { return ; } this . setTitle ( newTitle ) ; }
|
Changes the title based on curProject and saveFile .
| 157
| 11
|
153,483
|
public void loadProject ( String arg ) throws IOException { Project newProject = Project . readProject ( arg ) ; newProject . setConfiguration ( project . getConfiguration ( ) ) ; project = newProject ; projectLoadedFromFile = true ; }
|
Load given project file .
| 52
| 5
|
153,484
|
public void execute ( ) { Iterator < ? > elementIter = XMLUtil . selectNodes ( document , "/BugCollection/BugInstance" ) . iterator ( ) ; Iterator < BugInstance > bugInstanceIter = bugCollection . iterator ( ) ; Set < String > bugTypeSet = new HashSet <> ( ) ; Set < String > bugCategorySet = new HashSet <> ( ) ; Set < String > bugCodeSet = new HashSet <> ( ) ; // Add short and long descriptions to BugInstance elements. // We rely on the Document and the BugCollection storing // the bug instances in the same order. while ( elementIter . hasNext ( ) && bugInstanceIter . hasNext ( ) ) { Element element = ( Element ) elementIter . next ( ) ; BugInstance bugInstance = bugInstanceIter . next ( ) ; String bugType = bugInstance . getType ( ) ; bugTypeSet . add ( bugType ) ; BugPattern bugPattern = bugInstance . getBugPattern ( ) ; bugCategorySet . add ( bugPattern . getCategory ( ) ) ; bugCodeSet . add ( bugPattern . getAbbrev ( ) ) ; element . addElement ( "ShortMessage" ) . addText ( bugPattern . getShortDescription ( ) ) ; element . addElement ( "LongMessage" ) . addText ( bugInstance . getMessage ( ) ) ; // Add pre-formatted display strings in "Message" // elements for all bug annotations. Iterator < ? > annElementIter = element . elements ( ) . iterator ( ) ; Iterator < BugAnnotation > annIter = bugInstance . annotationIterator ( ) ; while ( annElementIter . hasNext ( ) && annIter . hasNext ( ) ) { Element annElement = ( Element ) annElementIter . next ( ) ; BugAnnotation ann = annIter . next ( ) ; annElement . addElement ( "Message" ) . addText ( ann . toString ( ) ) ; } } // Add BugPattern elements for each referenced bug types. addBugCategories ( bugCategorySet ) ; addBugPatterns ( bugTypeSet ) ; addBugCodes ( bugCodeSet ) ; }
|
Add messages to the dom4j tree .
| 463
| 9
|
153,485
|
private void addBugCategories ( Set < String > bugCategorySet ) { Element root = document . getRootElement ( ) ; for ( String category : bugCategorySet ) { Element element = root . addElement ( "BugCategory" ) ; element . addAttribute ( "category" , category ) ; Element description = element . addElement ( "Description" ) ; description . setText ( I18N . instance ( ) . getBugCategoryDescription ( category ) ) ; BugCategory bc = DetectorFactoryCollection . instance ( ) . getBugCategory ( category ) ; if ( bc != null ) { // shouldn't be null String s = bc . getAbbrev ( ) ; if ( s != null ) { Element abbrev = element . addElement ( "Abbreviation" ) ; abbrev . setText ( s ) ; } s = bc . getDetailText ( ) ; if ( s != null ) { Element details = element . addElement ( "Details" ) ; details . setText ( s ) ; } } } }
|
Add BugCategory elements .
| 218
| 5
|
153,486
|
private void addBugCodes ( Set < String > bugCodeSet ) { Element root = document . getRootElement ( ) ; for ( String bugCode : bugCodeSet ) { Element element = root . addElement ( "BugCode" ) ; element . addAttribute ( "abbrev" , bugCode ) ; Element description = element . addElement ( "Description" ) ; description . setText ( I18N . instance ( ) . getBugTypeDescription ( bugCode ) ) ; } }
|
Add BugCode elements .
| 105
| 5
|
153,487
|
public static Constant merge ( Constant a , Constant b ) { if ( ! a . isConstant ( ) || ! b . isConstant ( ) ) { return NOT_CONSTANT ; } if ( a . value . getClass ( ) != b . value . getClass ( ) || ! a . value . equals ( b . value ) ) { return NOT_CONSTANT ; } return a ; }
|
Merge two Constnts .
| 86
| 7
|
153,488
|
private void createBugCategoriesGroup ( Composite parent , final IProject project ) { Group checkBoxGroup = new Group ( parent , SWT . SHADOW_ETCHED_OUT ) ; checkBoxGroup . setText ( getMessage ( "property.categoriesGroup" ) ) ; checkBoxGroup . setLayout ( new GridLayout ( 1 , true ) ) ; checkBoxGroup . setLayoutData ( new GridData ( SWT . BEGINNING , SWT . TOP , true , true ) ) ; List < String > bugCategoryList = new LinkedList <> ( DetectorFactoryCollection . instance ( ) . getBugCategories ( ) ) ; chkEnableBugCategoryList = new LinkedList <> ( ) ; ProjectFilterSettings origFilterSettings = propertyPage . getOriginalUserPreferences ( ) . getFilterSettings ( ) ; for ( String category : bugCategoryList ) { Button checkBox = new Button ( checkBoxGroup , SWT . CHECK ) ; checkBox . setText ( I18N . instance ( ) . getBugCategoryDescription ( category ) ) ; checkBox . setSelection ( origFilterSettings . containsCategory ( category ) ) ; GridData layoutData = new GridData ( ) ; layoutData . horizontalIndent = 10 ; checkBox . setLayoutData ( layoutData ) ; // Every time a checkbox is clicked, rebuild the detector factory // table // to show only relevant entries checkBox . addListener ( SWT . Selection , new Listener ( ) { @ Override public void handleEvent ( Event e ) { syncSelectedCategories ( ) ; } } ) ; checkBox . setData ( category ) ; chkEnableBugCategoryList . add ( checkBox ) ; } }
|
Build list of bug categories to be enabled or disabled . Populates chkEnableBugCategoryList and bugCategoryList fields .
| 366
| 25
|
153,489
|
protected void syncSelectedCategories ( ) { ProjectFilterSettings filterSettings = getCurrentProps ( ) . getFilterSettings ( ) ; for ( Button checkBox : chkEnableBugCategoryList ) { String category = ( String ) checkBox . getData ( ) ; if ( checkBox . getSelection ( ) ) { filterSettings . addCategory ( category ) ; } else { filterSettings . removeCategory ( category ) ; } } propertyPage . getVisibleDetectors ( ) . clear ( ) ; }
|
Synchronize selected bug category checkboxes with the current user preferences .
| 108
| 14
|
153,490
|
@ SlashedClassName @ SuppressFBWarnings ( "TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_ALWAYS_SINK" ) public static String toSlashedClassName ( @ SlashedClassName ( when = When . UNKNOWN ) String className ) { if ( className . indexOf ( ' ' ) >= 0 ) { return className . replace ( ' ' , ' ' ) ; } return className ; }
|
Convert class name to slashed format . If the class name is already in slashed format it is returned unmodified .
| 100
| 23
|
153,491
|
@ DottedClassName @ SuppressFBWarnings ( "TQ_EXPLICIT_UNKNOWN_SOURCE_VALUE_REACHES_NEVER_SINK" ) public static String toDottedClassName ( @ SlashedClassName ( when = When . UNKNOWN ) String className ) { if ( className . indexOf ( ' ' ) >= 0 ) { return className . replace ( ' ' , ' ' ) ; } return className ; }
|
Convert class name to dotted format . If the class name is already in dotted format it is returned unmodified .
| 100
| 23
|
153,492
|
public static boolean isAnonymous ( String className ) { int i = className . lastIndexOf ( ' ' ) ; if ( i >= 0 && ++ i < className . length ( ) ) { while ( i < className . length ( ) ) { if ( ! Character . isDigit ( className . charAt ( i ) ) ) { return false ; } i ++ ; } return true ; } return false ; }
|
Does a class name appear to designate an anonymous class? Only the name is analyzed . No classes are loaded or looked up .
| 90
| 25
|
153,493
|
public static @ SlashedClassName String extractClassName ( String originalName ) { String name = originalName ; if ( name . charAt ( 0 ) != ' ' && name . charAt ( name . length ( ) - 1 ) != ' ' ) { return name ; } while ( name . charAt ( 0 ) == ' ' ) { name = name . substring ( 1 ) ; } if ( name . charAt ( 0 ) == ' ' && name . charAt ( name . length ( ) - 1 ) == ' ' ) { name = name . substring ( 1 , name . length ( ) - 1 ) ; } if ( name . charAt ( 0 ) == ' ' ) { throw new IllegalArgumentException ( "Bad class name: " + originalName ) ; } return name ; }
|
Extract a slashed classname from a JVM classname or signature .
| 170
| 15
|
153,494
|
public static @ CheckForNull TypeQualifierAnnotation combineReturnTypeAnnotations ( TypeQualifierAnnotation a , TypeQualifierAnnotation b ) { return combineAnnotations ( a , b , combineReturnValueMatrix ) ; }
|
Combine return type annotations .
| 48
| 6
|
153,495
|
public final @ DottedClassName String getPackageName ( ) { int lastDot = className . lastIndexOf ( ' ' ) ; if ( lastDot < 0 ) { return "" ; } else { return className . substring ( 0 , lastDot ) ; } }
|
Get the package name .
| 61
| 5
|
153,496
|
protected static String removePackageName ( String typeName ) { int index = typeName . lastIndexOf ( ' ' ) ; if ( index >= 0 ) { typeName = typeName . substring ( index + 1 ) ; } return typeName ; }
|
Shorten a type name by removing the package name
| 53
| 10
|
153,497
|
public void downgradeOnControlSplit ( ) { final int numSlots = getNumSlots ( ) ; for ( int i = 0 ; i < numSlots ; ++ i ) { IsNullValue value = getValue ( i ) ; value = value . downgradeOnControlSplit ( ) ; setValue ( i , value ) ; } if ( knownValueMap != null ) { for ( Map . Entry < ValueNumber , IsNullValue > entry : knownValueMap . entrySet ( ) ) { entry . setValue ( entry . getValue ( ) . downgradeOnControlSplit ( ) ) ; } } }
|
Downgrade all NSP values in frame . Should be called when a non - exception control split occurs .
| 127
| 21
|
153,498
|
public static void printCode ( Method [ ] methods ) { for ( Method m : methods ) { System . out . println ( m ) ; Code code = m . getCode ( ) ; if ( code != null ) { System . out . println ( code ) ; } } }
|
Dump the disassembled code of all methods in the class .
| 58
| 13
|
153,499
|
protected boolean isReferenceType ( byte type ) { return type == Const . T_OBJECT || type == Const . T_ARRAY || type == T_NULL || type == T_EXCEPTION ; }
|
Determine if the given typecode refers to a reference type . This implementation just checks that the type code is T_OBJECT T_ARRAY T_NULL or T_EXCEPTION . Subclasses should override this if they have defined new object types with different type codes .
| 44
| 58
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.