idx int64 0 41.2k | question stringlengths 83 4.15k | target stringlengths 5 715 |
|---|---|---|
29,900 | public int getLineOffset ( int line ) { try { loadFileData ( ) ; } catch ( IOException e ) { System . err . println ( "SourceFile.getLineOffset: " + e . getMessage ( ) ) ; return - 1 ; } if ( line < 0 || line >= numLines ) { return - 1 ; } return lineNumberMap [ line ] ; } | Get the byte offset in the data for a source line . Note that lines are considered to be zero - index so the first line in the file is numbered zero . |
29,901 | public void findStronglyConnectedComponents ( GraphType g , GraphToolkit < GraphType , EdgeType , VertexType > toolkit ) { DepthFirstSearch < GraphType , EdgeType , VertexType > initialDFS = new DepthFirstSearch < > ( g ) ; if ( m_vertexChooser != null ) { initialDFS . setVertexChooser ( m_vertexChooser ) ; } initialDFS . search ( ) ; Transpose < GraphType , EdgeType , VertexType > t = new Transpose < > ( ) ; GraphType transpose = t . transpose ( g , toolkit ) ; VisitationTimeComparator < VertexType > comparator = new VisitationTimeComparator < > ( initialDFS . getFinishTimeList ( ) , VisitationTimeComparator . DESCENDING ) ; Set < VertexType > descendingByFinishTimeSet = new TreeSet < > ( comparator ) ; Iterator < VertexType > i = transpose . vertexIterator ( ) ; while ( i . hasNext ( ) ) { descendingByFinishTimeSet . add ( i . next ( ) ) ; } SearchTreeBuilder < VertexType > searchTreeBuilder = new SearchTreeBuilder < > ( ) ; final Iterator < VertexType > vertexIter = descendingByFinishTimeSet . iterator ( ) ; DepthFirstSearch < GraphType , EdgeType , VertexType > transposeDFS = new DepthFirstSearch < GraphType , EdgeType , VertexType > ( transpose ) { protected VertexType getNextSearchTreeRoot ( ) { while ( vertexIter . hasNext ( ) ) { VertexType vertex = vertexIter . next ( ) ; if ( visitMe ( vertex ) ) { return vertex ; } } return null ; } } ; if ( m_vertexChooser != null ) { transposeDFS . setVertexChooser ( m_vertexChooser ) ; } transposeDFS . setSearchTreeCallback ( searchTreeBuilder ) ; transposeDFS . search ( ) ; Iterator < SearchTree < VertexType > > j = searchTreeBuilder . searchTreeIterator ( ) ; while ( j . hasNext ( ) ) { m_stronglyConnectedSearchTreeList . add ( copySearchTree ( j . next ( ) , t ) ) ; } } | Find the strongly connected components in given graph . |
29,902 | public Collection < String > split ( ) { String s = ident ; Set < String > result = new HashSet < > ( ) ; while ( s . length ( ) > 0 ) { StringBuilder buf = new StringBuilder ( ) ; char first = s . charAt ( 0 ) ; buf . append ( first ) ; int i = 1 ; if ( s . length ( ) > 1 ) { boolean camelWord ; if ( Character . isLowerCase ( first ) ) { camelWord = true ; } else { char next = s . charAt ( i ++ ) ; buf . append ( next ) ; camelWord = Character . isLowerCase ( next ) ; } while ( i < s . length ( ) ) { char c = s . charAt ( i ) ; if ( Character . isUpperCase ( c ) ) { if ( camelWord ) { break ; } } else if ( ! camelWord ) { break ; } buf . append ( c ) ; ++ i ; } if ( ! camelWord && i < s . length ( ) ) { buf . deleteCharAt ( buf . length ( ) - 1 ) ; -- i ; } } result . add ( buf . toString ( ) . toLowerCase ( Locale . US ) ) ; s = s . substring ( i ) ; } return result ; } | Split the identifier into words . |
29,903 | private static void collectAllAnonymous ( List < IType > list , IParent parent , boolean allowNested ) throws JavaModelException { IJavaElement [ ] children = parent . getChildren ( ) ; for ( int i = 0 ; i < children . length ; i ++ ) { IJavaElement childElem = children [ i ] ; if ( isAnonymousType ( childElem ) ) { list . add ( ( IType ) childElem ) ; } if ( childElem instanceof IParent ) { if ( allowNested || ! ( childElem instanceof IType ) ) { collectAllAnonymous ( list , ( IParent ) childElem , allowNested ) ; } } } } | Traverses down the children tree of this parent and collect all child anon . classes |
29,904 | private static void sortAnonymous ( List < IType > anonymous , IType anonType ) { SourceOffsetComparator sourceComparator = new SourceOffsetComparator ( ) ; final AnonymClassComparator classComparator = new AnonymClassComparator ( anonType , sourceComparator ) ; Collections . sort ( anonymous , classComparator ) ; } | Sort given anonymous classes in order like java compiler would generate output classes in context of given anonymous type |
29,905 | public static void addFindBugsNature ( IProject project , IProgressMonitor monitor ) throws CoreException { if ( hasFindBugsNature ( project ) ) { return ; } IProjectDescription description = project . getDescription ( ) ; String [ ] prevNatures = description . getNatureIds ( ) ; for ( int i = 0 ; i < prevNatures . length ; i ++ ) { if ( FindbugsPlugin . NATURE_ID . equals ( prevNatures [ i ] ) ) { return ; } } String [ ] newNatures = new String [ prevNatures . length + 1 ] ; System . arraycopy ( prevNatures , 0 , newNatures , 0 , prevNatures . length ) ; newNatures [ prevNatures . length ] = FindbugsPlugin . NATURE_ID ; if ( DEBUG ) { for ( int i = 0 ; i < newNatures . length ; i ++ ) { System . out . println ( newNatures [ i ] ) ; } } description . setNatureIds ( newNatures ) ; project . setDescription ( description , monitor ) ; } | Adds a FindBugs nature to a project . |
29,906 | public static boolean hasFindBugsNature ( IProject project ) { try { return ProjectUtilities . isJavaProject ( project ) && project . hasNature ( FindbugsPlugin . NATURE_ID ) ; } catch ( CoreException e ) { FindbugsPlugin . getDefault ( ) . logException ( e , "Error while testing SpotBugs nature for project " + project ) ; } return false ; } | Using the natures name check whether the current project has FindBugs nature . |
29,907 | public static void removeFindBugsNature ( IProject project , IProgressMonitor monitor ) throws CoreException { if ( ! hasFindBugsNature ( project ) ) { return ; } IProjectDescription description = project . getDescription ( ) ; String [ ] prevNatures = description . getNatureIds ( ) ; ArrayList < String > newNaturesList = new ArrayList < > ( ) ; for ( int i = 0 ; i < prevNatures . length ; i ++ ) { if ( ! FindbugsPlugin . NATURE_ID . equals ( prevNatures [ i ] ) ) { newNaturesList . add ( prevNatures [ i ] ) ; } } String [ ] newNatures = newNaturesList . toArray ( new String [ newNaturesList . size ( ) ] ) ; description . setNatureIds ( newNatures ) ; project . setDescription ( description , monitor ) ; } | Removes the FindBugs nature from a project . |
29,908 | public void execute ( ) throws CFGBuilderException { JavaClass jclass = classContext . getJavaClass ( ) ; Method [ ] methods = jclass . getMethods ( ) ; LOG . debug ( "Class has {} methods" , methods . length ) ; for ( Method method : methods ) { callGraph . addNode ( method ) ; } LOG . debug ( "Added {} nodes to graph" , callGraph . getNumVertices ( ) ) ; for ( Method method : methods ) { MethodGen mg = classContext . getMethodGen ( method ) ; if ( mg == null ) { continue ; } scan ( callGraph . getNodeForMethod ( method ) ) ; } LOG . debug ( "Found {} self calls" , callGraph . getNumEdges ( ) ) ; } | Find the self calls . |
29,909 | public Iterator < CallSite > callSiteIterator ( ) { return new Iterator < CallSite > ( ) { private final Iterator < CallGraphEdge > iter = callGraph . edgeIterator ( ) ; public boolean hasNext ( ) { return iter . hasNext ( ) ; } public CallSite next ( ) { return iter . next ( ) . getCallSite ( ) ; } public void remove ( ) { iter . remove ( ) ; } } ; } | Get an Iterator over all self call sites . |
29,910 | private void scan ( CallGraphNode node ) throws CFGBuilderException { Method method = node . getMethod ( ) ; CFG cfg = classContext . getCFG ( method ) ; if ( method . isSynchronized ( ) ) { hasSynchronization = true ; } Iterator < BasicBlock > i = cfg . blockIterator ( ) ; while ( i . hasNext ( ) ) { BasicBlock block = i . next ( ) ; Iterator < InstructionHandle > j = block . instructionIterator ( ) ; while ( j . hasNext ( ) ) { InstructionHandle handle = j . next ( ) ; Instruction ins = handle . getInstruction ( ) ; if ( ins instanceof InvokeInstruction ) { InvokeInstruction inv = ( InvokeInstruction ) ins ; Method called = isSelfCall ( inv ) ; if ( called != null ) { CallSite callSite = new CallSite ( method , block , handle ) ; callGraph . createEdge ( node , callGraph . getNodeForMethod ( called ) , callSite ) ; calledMethodSet . add ( called ) ; } } else if ( ins instanceof MONITORENTER || ins instanceof MONITOREXIT ) { hasSynchronization = true ; } } } } | Scan a method for self call sites . |
29,911 | private Method isSelfCall ( InvokeInstruction inv ) { ConstantPoolGen cpg = classContext . getConstantPoolGen ( ) ; JavaClass jclass = classContext . getJavaClass ( ) ; String calledClassName = inv . getClassName ( cpg ) ; if ( ! calledClassName . equals ( jclass . getClassName ( ) ) ) { return null ; } String calledMethodName = inv . getMethodName ( cpg ) ; String calledMethodSignature = inv . getSignature ( cpg ) ; boolean isStaticCall = ( inv instanceof INVOKESTATIC ) ; Method [ ] methods = jclass . getMethods ( ) ; for ( Method method : methods ) { String methodName = method . getName ( ) ; String signature = method . getSignature ( ) ; boolean isStatic = method . isStatic ( ) ; if ( methodName . equals ( calledMethodName ) && signature . equals ( calledMethodSignature ) && isStatic == isStaticCall ) { return wantCallsFor ( method ) ? method : null ; } } LOG . debug ( "No method found for {}.{} : {}" , calledClassName , calledMethodName , calledMethodSignature ) ; return null ; } | Is the given instruction a self - call? |
29,912 | public boolean isEnabledForCurrentJRE ( ) { if ( "" . equals ( requireJRE ) ) { return true ; } try { JavaVersion requiredVersion = new JavaVersion ( requireJRE ) ; JavaVersion runtimeVersion = JavaVersion . getRuntimeVersion ( ) ; if ( DEBUG_JAVA_VERSION ) { System . out . println ( "Checking JRE version for " + getShortName ( ) + " (requires " + requiredVersion + ", running on " + runtimeVersion + ")" ) ; } boolean enabledForCurrentJRE = runtimeVersion . isSameOrNewerThan ( requiredVersion ) ; if ( DEBUG_JAVA_VERSION ) { System . out . println ( "\t==> " + enabledForCurrentJRE ) ; } return enabledForCurrentJRE ; } catch ( JavaVersionException e ) { if ( DEBUG_JAVA_VERSION ) { System . out . println ( "Couldn't check Java version: " + e . toString ( ) ) ; e . printStackTrace ( System . out ) ; } return false ; } } | Check to see if we are running on a recent - enough JRE for this detector to be enabled . |
29,913 | public Set < BugPattern > getReportedBugPatterns ( ) { Set < BugPattern > result = new TreeSet < > ( ) ; StringTokenizer tok = new StringTokenizer ( reports , "," ) ; while ( tok . hasMoreTokens ( ) ) { String type = tok . nextToken ( ) ; BugPattern bugPattern = DetectorFactoryCollection . instance ( ) . lookupBugPattern ( type ) ; if ( bugPattern != null ) { result . add ( bugPattern ) ; } } return result ; } | Get set of all BugPatterns this detector reports . An empty set means that we don t know what kind of bug patterns might be reported . |
29,914 | public String getShortName ( ) { int endOfPkg = className . lastIndexOf ( '.' ) ; if ( endOfPkg >= 0 ) { return className . substring ( endOfPkg + 1 ) ; } return className ; } | Get the short name of the Detector . This is the name of the detector class without the package qualification . |
29,915 | public LoadStoreCount getLoadStoreCount ( XField field ) { LoadStoreCount loadStoreCount = loadStoreCountMap . get ( field ) ; if ( loadStoreCount == null ) { loadStoreCount = new LoadStoreCount ( ) ; loadStoreCountMap . put ( field , loadStoreCount ) ; } return loadStoreCount ; } | Get the number of times given field is loaded and stored within the method . |
29,916 | public void addLoad ( InstructionHandle handle , XField field ) { getLoadStoreCount ( field ) . loadCount ++ ; handleToFieldMap . put ( handle , field ) ; loadHandleSet . set ( handle . getPosition ( ) ) ; } | Add a load of given field at given instruction . |
29,917 | public void addStore ( InstructionHandle handle , XField field ) { getLoadStoreCount ( field ) . storeCount ++ ; handleToFieldMap . put ( handle , field ) ; } | Add a store of given field at given instruction . |
29,918 | public static SourceLineAnnotation forFirstLineOfMethod ( MethodDescriptor methodDescriptor ) { SourceLineAnnotation result = null ; try { Method m = Global . getAnalysisCache ( ) . getMethodAnalysis ( Method . class , methodDescriptor ) ; XClass xclass = Global . getAnalysisCache ( ) . getClassAnalysis ( XClass . class , methodDescriptor . getClassDescriptor ( ) ) ; LineNumberTable lnt = m . getLineNumberTable ( ) ; String sourceFile = xclass . getSource ( ) ; if ( sourceFile != null && lnt != null ) { int firstLine = Integer . MAX_VALUE ; int bytecode = 0 ; LineNumber [ ] entries = lnt . getLineNumberTable ( ) ; for ( LineNumber entry : entries ) { if ( entry . getLineNumber ( ) < firstLine ) { firstLine = entry . getLineNumber ( ) ; bytecode = entry . getStartPC ( ) ; } } if ( firstLine < Integer . MAX_VALUE ) { result = new SourceLineAnnotation ( methodDescriptor . getClassDescriptor ( ) . toDottedClassName ( ) , sourceFile , firstLine , firstLine , bytecode , bytecode ) ; } } } catch ( CheckedAnalysisException e ) { } if ( result == null ) { result = createUnknown ( methodDescriptor . getClassDescriptor ( ) . toDottedClassName ( ) ) ; } return result ; } | Make a best - effort attempt to create a SourceLineAnnotation for the first line of a method . |
29,919 | public static SourceLineAnnotation fromVisitedInstruction ( ClassContext classContext , Method method , Location loc ) { return fromVisitedInstruction ( classContext , method , loc . getHandle ( ) ) ; } | Create from Method and Location in a visited class . |
29,920 | public static SourceLineAnnotation fromVisitedInstruction ( ClassContext classContext , Method method , InstructionHandle handle ) { return fromVisitedInstruction ( classContext , method , handle . getPosition ( ) ) ; } | Create from Method and InstructionHandle in a visited class . |
29,921 | public static SourceLineAnnotation fromVisitedInstruction ( MethodDescriptor methodDescriptor , Location location ) { return fromVisitedInstruction ( methodDescriptor , location . getHandle ( ) . getPosition ( ) ) ; } | Create from MethodDescriptor and Location of visited instruction . |
29,922 | public static SourceLineAnnotation fromVisitedInstructionRange ( ClassContext classContext , MethodGen methodGen , String sourceFile , InstructionHandle start , InstructionHandle end ) { LineNumberTable lineNumberTable = methodGen . getLineNumberTable ( methodGen . getConstantPool ( ) ) ; String className = methodGen . getClassName ( ) ; if ( lineNumberTable == null ) { return createUnknown ( className , sourceFile , start . getPosition ( ) , end . getPosition ( ) ) ; } int startLine = lineNumberTable . getSourceLine ( start . getPosition ( ) ) ; int endLine = lineNumberTable . getSourceLine ( end . getPosition ( ) ) ; return new SourceLineAnnotation ( className , sourceFile , startLine , endLine , start . getPosition ( ) , end . getPosition ( ) ) ; } | Factory method for creating a source line annotation describing the source line numbers for a range of instruction in a method . |
29,923 | public boolean isAssertionInstruction ( Instruction ins , ConstantPoolGen cpg ) { if ( ins instanceof InvokeInstruction ) { return isAssertionCall ( ( InvokeInstruction ) ins ) ; } if ( ins instanceof GETSTATIC ) { GETSTATIC getStatic = ( GETSTATIC ) ins ; String className = getStatic . getClassName ( cpg ) ; String fieldName = getStatic . getFieldName ( cpg ) ; if ( "java.util.logging.Level" . equals ( className ) && "SEVERE" . equals ( fieldName ) ) { return true ; } return "org.apache.log4j.Level" . equals ( className ) && ( "ERROR" . equals ( fieldName ) || "FATAL" . equals ( fieldName ) ) ; } return false ; } | Does the given instruction refer to a likely assertion method? |
29,924 | private static short unsignedValueOf ( byte value ) { short result ; if ( ( value & 0x80 ) != 0 ) { result = ( short ) ( value & 0x7F ) ; result |= 0x80 ; } else { result = value ; } return result ; } | Convert the unsigned value of a byte into a short . |
29,925 | private static int extractInt ( byte [ ] arr , int offset ) { return ( ( arr [ offset ] & 0xFF ) << 24 ) | ( ( arr [ offset + 1 ] & 0xFF ) << 16 ) | ( ( arr [ offset + 2 ] & 0xFF ) << 8 ) | ( arr [ offset + 3 ] & 0xFF ) ; } | Extract an int from bytes at the given offset in the array . |
29,926 | public void makeSameAs ( UnconditionalValueDerefSet source ) { valueNumbersUnconditionallyDereferenced . clear ( ) ; valueNumbersUnconditionallyDereferenced . or ( source . valueNumbersUnconditionallyDereferenced ) ; lastUpdateTimestamp = source . lastUpdateTimestamp ; derefLocationSetMap . clear ( ) ; if ( source . derefLocationSetMap . size ( ) > 0 ) { for ( Map . Entry < ValueNumber , Set < Location > > sourceEntry : source . derefLocationSetMap . entrySet ( ) ) { Set < Location > derefLocationSet = Util . makeSmallHashSet ( sourceEntry . getValue ( ) ) ; derefLocationSetMap . put ( sourceEntry . getKey ( ) , derefLocationSet ) ; } } } | Make this dataflow fact the same as the given one . |
29,927 | public boolean isSameAs ( UnconditionalValueDerefSet otherFact ) { return valueNumbersUnconditionallyDereferenced . equals ( otherFact . valueNumbersUnconditionallyDereferenced ) && derefLocationSetMap . equals ( otherFact . derefLocationSetMap ) ; } | Return whether or not this dataflow fact is identical to the one given . |
29,928 | public void addDeref ( ValueNumber vn , Location location ) { if ( UnconditionalValueDerefAnalysis . DEBUG ) { System . out . println ( "Adding dereference of " + vn + " to # " + System . identityHashCode ( this ) + " @ " + location ) ; } valueNumbersUnconditionallyDereferenced . set ( vn . getNumber ( ) ) ; Set < Location > derefLocationSet = getDerefLocationSet ( vn ) ; derefLocationSet . add ( location ) ; } | Mark a value as being dereferenced at given Location . |
29,929 | public void setDerefSet ( ValueNumber vn , Set < Location > derefSet ) { if ( UnconditionalValueDerefAnalysis . DEBUG ) { System . out . println ( "Adding dereference of " + vn + " for # " + System . identityHashCode ( this ) + " to " + derefSet ) ; } valueNumbersUnconditionallyDereferenced . set ( vn . getNumber ( ) ) ; Set < Location > derefLocationSet = getDerefLocationSet ( vn ) ; derefLocationSet . clear ( ) ; derefLocationSet . addAll ( derefSet ) ; } | Set a value as being unconditionally dereferenced at the given set of locations . |
29,930 | public void clearDerefSet ( ValueNumber value ) { if ( UnconditionalValueDerefAnalysis . DEBUG ) { System . out . println ( "Clearing dereference of " + value + " for # " + System . identityHashCode ( this ) ) ; } valueNumbersUnconditionallyDereferenced . clear ( value . getNumber ( ) ) ; derefLocationSetMap . remove ( value ) ; } | Clear the set of dereferences for given ValueNumber |
29,931 | public Set < Location > getDerefLocationSet ( ValueNumber vn ) { Set < Location > derefLocationSet = derefLocationSetMap . get ( vn ) ; if ( derefLocationSet == null ) { derefLocationSet = new HashSet < > ( ) ; derefLocationSetMap . put ( vn , derefLocationSet ) ; } return derefLocationSet ; } | Get the set of dereference Locations for given value number . |
29,932 | private void work ( final IProject project , final String fileName ) { FindBugsJob runFindBugs = new FindBugsJob ( "Loading XML data from " + fileName + "..." , project ) { protected void runWithProgress ( IProgressMonitor monitor ) throws CoreException { FindBugsWorker worker = new FindBugsWorker ( project , monitor ) ; worker . loadXml ( fileName ) ; } } ; runFindBugs . setRule ( project ) ; runFindBugs . scheduleInteractive ( ) ; } | Run a FindBugs import on the given project displaying a progress monitor . |
29,933 | private void handleWillCloseWhenClosed ( XMethod xmethod , Obligation deletedObligation ) { if ( deletedObligation == null ) { if ( DEBUG_ANNOTATIONS ) { System . out . println ( "Method " + xmethod . toString ( ) + " is marked @WillCloseWhenClosed, " + "but its parameter is not an obligation" ) ; } return ; } Obligation createdObligation = null ; if ( "<init>" . equals ( xmethod . getName ( ) ) ) { createdObligation = database . getFactory ( ) . getObligationByType ( xmethod . getClassDescriptor ( ) ) ; } else { Type returnType = Type . getReturnType ( xmethod . getSignature ( ) ) ; if ( returnType instanceof ObjectType ) { try { createdObligation = database . getFactory ( ) . getObligationByType ( ( ObjectType ) returnType ) ; } catch ( ClassNotFoundException e ) { reporter . reportMissingClass ( e ) ; return ; } } } if ( createdObligation == null ) { if ( DEBUG_ANNOTATIONS ) { System . out . println ( "Method " + xmethod . toString ( ) + " is marked @WillCloseWhenClosed, " + "but its return type is not an obligation" ) ; } return ; } database . addEntry ( new MatchMethodEntry ( xmethod , ObligationPolicyDatabaseActionType . DEL , ObligationPolicyDatabaseEntryType . STRONG , deletedObligation ) ) ; database . addEntry ( new MatchMethodEntry ( xmethod , ObligationPolicyDatabaseActionType . ADD , ObligationPolicyDatabaseEntryType . STRONG , createdObligation ) ) ; } | Handle a method with a WillCloseWhenClosed parameter annotation . |
29,934 | public IsNullValue toExceptionValue ( ) { if ( getBaseKind ( ) == NO_KABOOM_NN ) { return new IsNullValue ( kind | EXCEPTION , locationOfKaBoom ) ; } return instanceByFlagsList [ ( getFlags ( ) | EXCEPTION ) >> FLAG_SHIFT ] [ getBaseKind ( ) ] ; } | Convert to an exception path value . |
29,935 | public static IsNullValue merge ( IsNullValue a , IsNullValue b ) { if ( a == b ) { return a ; } if ( a . equals ( b ) ) { return a ; } int aKind = a . kind & 0xff ; int bKind = b . kind & 0xff ; int aFlags = a . getFlags ( ) ; int bFlags = b . getFlags ( ) ; int combinedFlags = aFlags & bFlags ; if ( ! ( a . isNullOnSomePath ( ) || a . isDefinitelyNull ( ) ) && b . isException ( ) ) { combinedFlags |= EXCEPTION ; } else if ( ! ( b . isNullOnSomePath ( ) || b . isDefinitelyNull ( ) ) && a . isException ( ) ) { combinedFlags |= EXCEPTION ; } if ( aKind < bKind ) { int tmp = aKind ; aKind = bKind ; bKind = tmp ; } assert aKind >= bKind ; int result = mergeMatrix [ aKind ] [ bKind ] ; IsNullValue resultValue = ( result == NO_KABOOM_NN ) ? noKaboomNonNullValue ( a . locationOfKaBoom ) : instanceByFlagsList [ combinedFlags >> FLAG_SHIFT ] [ result ] ; return resultValue ; } | Merge two values . |
29,936 | public boolean isNullOnSomePath ( ) { int baseKind = getBaseKind ( ) ; if ( NCP_EXTRA_BRANCH ) { return baseKind == NSP || baseKind == NCP2 ; } else { return baseKind == NSP ; } } | Is this value null on some path? |
29,937 | static public boolean isContainer ( ReferenceType target ) throws ClassNotFoundException { Subtypes2 subtypes2 = AnalysisContext . currentAnalysisContext ( ) . getSubtypes2 ( ) ; return subtypes2 . isSubtype ( target , COLLECTION_TYPE ) || subtypes2 . isSubtype ( target , MAP_TYPE ) ; } | A collection a map or some other container |
29,938 | public void addApplicationClass ( XClass appXClass ) { for ( XMethod m : appXClass . getXMethods ( ) ) { if ( m . isStub ( ) ) { return ; } } ClassVertex vertex = addClassAndGetClassVertex ( appXClass ) ; vertex . markAsApplicationClass ( ) ; } | Add an application class and its transitive supertypes to the inheritance graph . |
29,939 | private ClassVertex addClassAndGetClassVertex ( XClass xclass ) { if ( xclass == null ) { throw new IllegalStateException ( ) ; } LinkedList < XClass > workList = new LinkedList < > ( ) ; workList . add ( xclass ) ; while ( ! workList . isEmpty ( ) ) { XClass work = workList . removeFirst ( ) ; ClassVertex vertex = classDescriptorToVertexMap . get ( work . getClassDescriptor ( ) ) ; if ( vertex != null && vertex . isFinished ( ) ) { continue ; } if ( vertex == null ) { vertex = ClassVertex . createResolvedClassVertex ( work . getClassDescriptor ( ) , work ) ; addVertexToGraph ( work . getClassDescriptor ( ) , vertex ) ; } addSupertypeEdges ( vertex , workList ) ; vertex . setFinished ( true ) ; } return classDescriptorToVertexMap . get ( xclass . getClassDescriptor ( ) ) ; } | Add an XClass and all of its supertypes to the InheritanceGraph . |
29,940 | public boolean isSubtype ( ReferenceType type , ReferenceType possibleSupertype ) throws ClassNotFoundException { if ( type . equals ( possibleSupertype ) ) { return true ; } if ( possibleSupertype . equals ( Type . OBJECT ) ) { return true ; } if ( type . equals ( Type . OBJECT ) ) { return false ; } boolean typeIsObjectType = ( type instanceof ObjectType ) ; boolean possibleSupertypeIsObjectType = ( possibleSupertype instanceof ObjectType ) ; if ( typeIsObjectType && possibleSupertypeIsObjectType ) { return isSubtype ( ( ObjectType ) type , ( ObjectType ) possibleSupertype ) ; } boolean typeIsArrayType = ( type instanceof ArrayType ) ; boolean possibleSupertypeIsArrayType = ( possibleSupertype instanceof ArrayType ) ; if ( typeIsArrayType ) { if ( possibleSupertype . equals ( SERIALIZABLE ) || possibleSupertype . equals ( CLONEABLE ) ) { return true ; } if ( ! possibleSupertypeIsArrayType ) { return false ; } ArrayType typeAsArrayType = ( ArrayType ) type ; ArrayType possibleSupertypeAsArrayType = ( ArrayType ) possibleSupertype ; if ( typeAsArrayType . getDimensions ( ) < possibleSupertypeAsArrayType . getDimensions ( ) ) { return false ; } Type possibleSupertypeBasicType = possibleSupertypeAsArrayType . getBasicType ( ) ; if ( ! ( possibleSupertypeBasicType instanceof ObjectType ) ) { return false ; } Type typeBasicType = typeAsArrayType . getBasicType ( ) ; if ( typeAsArrayType . getDimensions ( ) > possibleSupertypeAsArrayType . getDimensions ( ) ) { return isSubtype ( new ArrayType ( typeBasicType , typeAsArrayType . getDimensions ( ) - possibleSupertypeAsArrayType . getDimensions ( ) ) , ( ObjectType ) possibleSupertypeBasicType ) ; } if ( ! ( typeBasicType instanceof ObjectType ) ) { return false ; } return isSubtype ( ( ObjectType ) typeBasicType , ( ObjectType ) possibleSupertypeBasicType ) ; } return false ; } | Determine whether or not a given ReferenceType is a subtype of another . Throws ClassNotFoundException if the question cannot be answered definitively due to a missing class . |
29,941 | public boolean isSubtype ( ObjectType type , ObjectType possibleSupertype ) throws ClassNotFoundException { if ( DEBUG_QUERIES ) { System . out . println ( "isSubtype: check " + type + " subtype of " + possibleSupertype ) ; } if ( type . equals ( possibleSupertype ) ) { if ( DEBUG_QUERIES ) { System . out . println ( " ==> yes, types are same" ) ; } return true ; } ClassDescriptor typeClassDescriptor = DescriptorFactory . getClassDescriptor ( type ) ; ClassDescriptor possibleSuperclassClassDescriptor = DescriptorFactory . getClassDescriptor ( possibleSupertype ) ; return isSubtype ( typeClassDescriptor , possibleSuperclassClassDescriptor ) ; } | Determine whether or not a given ObjectType is a subtype of another . Throws ClassNotFoundException if the question cannot be answered definitively due to a missing class . |
29,942 | private ReferenceType computeFirstCommonSuperclassOfSameDimensionArrays ( ArrayType aArrType , ArrayType bArrType ) throws ClassNotFoundException { assert aArrType . getDimensions ( ) == bArrType . getDimensions ( ) ; Type aBaseType = aArrType . getBasicType ( ) ; Type bBaseType = bArrType . getBasicType ( ) ; boolean aBaseIsObjectType = ( aBaseType instanceof ObjectType ) ; boolean bBaseIsObjectType = ( bBaseType instanceof ObjectType ) ; if ( ! aBaseIsObjectType || ! bBaseIsObjectType ) { assert ( aBaseType instanceof BasicType ) || ( bBaseType instanceof BasicType ) ; if ( aArrType . getDimensions ( ) > 1 ) { return new ArrayType ( Type . OBJECT , aArrType . getDimensions ( ) - 1 ) ; } else { assert aArrType . getDimensions ( ) == 1 ; return Type . OBJECT ; } } else { assert ( aBaseType instanceof ObjectType ) ; assert ( bBaseType instanceof ObjectType ) ; ObjectType firstCommonBaseType = getFirstCommonSuperclass ( ( ObjectType ) aBaseType , ( ObjectType ) bBaseType ) ; return new ArrayType ( firstCommonBaseType , aArrType . getDimensions ( ) ) ; } } | Get first common supertype of arrays with the same number of dimensions . |
29,943 | private ReferenceType computeFirstCommonSuperclassOfDifferentDimensionArrays ( ArrayType aArrType , ArrayType bArrType ) { assert aArrType . getDimensions ( ) != bArrType . getDimensions ( ) ; boolean aBaseTypeIsPrimitive = ( aArrType . getBasicType ( ) instanceof BasicType ) ; boolean bBaseTypeIsPrimitive = ( bArrType . getBasicType ( ) instanceof BasicType ) ; if ( aBaseTypeIsPrimitive || bBaseTypeIsPrimitive ) { int minDimensions , maxDimensions ; if ( aArrType . getDimensions ( ) < bArrType . getDimensions ( ) ) { minDimensions = aArrType . getDimensions ( ) ; maxDimensions = bArrType . getDimensions ( ) ; } else { minDimensions = bArrType . getDimensions ( ) ; maxDimensions = aArrType . getDimensions ( ) ; } if ( minDimensions == 1 ) { return Type . OBJECT ; } else { return new ArrayType ( Type . OBJECT , maxDimensions - minDimensions ) ; } } else { return new ArrayType ( Type . OBJECT , Math . min ( aArrType . getDimensions ( ) , bArrType . getDimensions ( ) ) ) ; } } | Get the first common superclass of arrays with different numbers of dimensions . |
29,944 | public boolean hasSubtypes ( ClassDescriptor classDescriptor ) throws ClassNotFoundException { Set < ClassDescriptor > subtypes = getDirectSubtypes ( classDescriptor ) ; if ( DEBUG ) { System . out . println ( "Direct subtypes of " + classDescriptor + " are " + subtypes ) ; } return ! subtypes . isEmpty ( ) ; } | Determine whether or not the given class has any known subtypes . |
29,945 | public Set < ClassDescriptor > getDirectSubtypes ( ClassDescriptor classDescriptor ) throws ClassNotFoundException { ClassVertex startVertex = resolveClassVertex ( classDescriptor ) ; Set < ClassDescriptor > result = new HashSet < > ( ) ; Iterator < InheritanceEdge > i = graph . incomingEdgeIterator ( startVertex ) ; while ( i . hasNext ( ) ) { InheritanceEdge edge = i . next ( ) ; result . add ( edge . getSource ( ) . getClassDescriptor ( ) ) ; } return result ; } | Get known subtypes of given class . |
29,946 | public Set < ClassDescriptor > getTransitiveCommonSubtypes ( ClassDescriptor classDescriptor1 , ClassDescriptor classDescriptor2 ) throws ClassNotFoundException { Set < ClassDescriptor > subtypes1 = getSubtypes ( classDescriptor1 ) ; Set < ClassDescriptor > result = new HashSet < > ( subtypes1 ) ; Set < ClassDescriptor > subtypes2 = getSubtypes ( classDescriptor2 ) ; result . retainAll ( subtypes2 ) ; return result ; } | Get the set of common subtypes of the two given classes . |
29,947 | public void traverseSupertypes ( ClassDescriptor start , InheritanceGraphVisitor visitor ) throws ClassNotFoundException { LinkedList < SupertypeTraversalPath > workList = new LinkedList < > ( ) ; ClassVertex startVertex = resolveClassVertex ( start ) ; workList . addLast ( new SupertypeTraversalPath ( startVertex ) ) ; while ( ! workList . isEmpty ( ) ) { SupertypeTraversalPath cur = workList . removeFirst ( ) ; ClassVertex vertex = cur . getNext ( ) ; assert ! cur . hasBeenSeen ( vertex . getClassDescriptor ( ) ) ; cur . markSeen ( vertex . getClassDescriptor ( ) ) ; if ( ! visitor . visitClass ( vertex . getClassDescriptor ( ) , vertex . getXClass ( ) ) ) { continue ; } if ( ! vertex . isResolved ( ) ) { continue ; } ClassDescriptor superclassDescriptor = vertex . getXClass ( ) . getSuperclassDescriptor ( ) ; if ( superclassDescriptor != null && traverseEdge ( vertex , superclassDescriptor , false , visitor ) ) { addToWorkList ( workList , cur , superclassDescriptor ) ; } for ( ClassDescriptor ifaceDesc : vertex . getXClass ( ) . getInterfaceDescriptorList ( ) ) { if ( traverseEdge ( vertex , ifaceDesc , true , visitor ) ) { addToWorkList ( workList , cur , ifaceDesc ) ; } } } } | Starting at the class or interface named by the given ClassDescriptor traverse the inheritance graph exploring all paths from the class or interface to java . lang . Object . |
29,948 | public void traverseSupertypesDepthFirst ( ClassDescriptor start , SupertypeTraversalVisitor visitor ) throws ClassNotFoundException { this . traverseSupertypesDepthFirstHelper ( start , visitor , new HashSet < ClassDescriptor > ( ) ) ; } | Starting at the class or interface named by the given ClassDescriptor traverse the inheritance graph depth first visiting each class only once . This is much faster than traversing all paths in certain circumstances . |
29,949 | private Set < ClassDescriptor > computeKnownSubtypes ( ClassDescriptor classDescriptor ) throws ClassNotFoundException { LinkedList < ClassVertex > workList = new LinkedList < > ( ) ; ClassVertex startVertex = resolveClassVertex ( classDescriptor ) ; workList . addLast ( startVertex ) ; Set < ClassDescriptor > result = new HashSet < > ( ) ; while ( ! workList . isEmpty ( ) ) { ClassVertex current = workList . removeFirst ( ) ; if ( result . contains ( current . getClassDescriptor ( ) ) ) { continue ; } result . add ( current . getClassDescriptor ( ) ) ; Iterator < InheritanceEdge > i = graph . incomingEdgeIterator ( current ) ; while ( i . hasNext ( ) ) { InheritanceEdge edge = i . next ( ) ; workList . addLast ( edge . getSource ( ) ) ; } } return new HashSet < > ( result ) ; } | Compute set of known subtypes of class named by given ClassDescriptor . |
29,950 | public SupertypeQueryResults getSupertypeQueryResults ( ClassDescriptor classDescriptor ) { SupertypeQueryResults supertypeQueryResults = supertypeSetMap . get ( classDescriptor ) ; if ( supertypeQueryResults == null ) { supertypeQueryResults = computeSupertypes ( classDescriptor ) ; supertypeSetMap . put ( classDescriptor , supertypeQueryResults ) ; } return supertypeQueryResults ; } | Look up or compute the SupertypeQueryResults for class named by given ClassDescriptor . |
29,951 | private SupertypeQueryResults computeSupertypes ( ClassDescriptor classDescriptor ) { if ( DEBUG_QUERIES ) { System . out . println ( "Computing supertypes for " + classDescriptor . toDottedClassName ( ) ) ; } ClassVertex typeVertex = optionallyResolveClassVertex ( classDescriptor ) ; SupertypeQueryResults supertypeSet = new SupertypeQueryResults ( ) ; LinkedList < ClassVertex > workList = new LinkedList < > ( ) ; workList . addLast ( typeVertex ) ; while ( ! workList . isEmpty ( ) ) { ClassVertex vertex = workList . removeFirst ( ) ; supertypeSet . addSupertype ( vertex . getClassDescriptor ( ) ) ; if ( vertex . isResolved ( ) ) { if ( DEBUG_QUERIES ) { System . out . println ( " Adding supertype " + vertex . getClassDescriptor ( ) . toDottedClassName ( ) ) ; } } else { if ( DEBUG_QUERIES ) { System . out . println ( " Encountered unresolved class " + vertex . getClassDescriptor ( ) . toDottedClassName ( ) + " in supertype query" ) ; } supertypeSet . setEncounteredMissingClasses ( true ) ; } Iterator < InheritanceEdge > i = graph . outgoingEdgeIterator ( vertex ) ; while ( i . hasNext ( ) ) { InheritanceEdge edge = i . next ( ) ; workList . addLast ( edge . getTarget ( ) ) ; } } return supertypeSet ; } | Compute supertypes for class named by given ClassDescriptor . |
29,952 | private ClassVertex resolveClassVertex ( ClassDescriptor classDescriptor ) throws ClassNotFoundException { ClassVertex typeVertex = optionallyResolveClassVertex ( classDescriptor ) ; if ( ! typeVertex . isResolved ( ) ) { ClassDescriptor . throwClassNotFoundException ( classDescriptor ) ; } assert typeVertex . isResolved ( ) ; return typeVertex ; } | Resolve a class named by given ClassDescriptor and return its resolved ClassVertex . |
29,953 | private void addSupertypeEdges ( ClassVertex vertex , LinkedList < XClass > workList ) { XClass xclass = vertex . getXClass ( ) ; ClassDescriptor superclassDescriptor = xclass . getSuperclassDescriptor ( ) ; if ( superclassDescriptor != null ) { addInheritanceEdge ( vertex , superclassDescriptor , false , workList ) ; } for ( ClassDescriptor ifaceDesc : xclass . getInterfaceDescriptorList ( ) ) { addInheritanceEdge ( vertex , ifaceDesc , true , workList ) ; } } | Add supertype edges to the InheritanceGraph for given ClassVertex . If any direct supertypes have not been processed add them to the worklist . |
29,954 | private ClassVertex addClassVertexForMissingClass ( ClassDescriptor missingClassDescriptor , boolean isInterfaceEdge ) { ClassVertex missingClassVertex = ClassVertex . createMissingClassVertex ( missingClassDescriptor , isInterfaceEdge ) ; missingClassVertex . setFinished ( true ) ; addVertexToGraph ( missingClassDescriptor , missingClassVertex ) ; AnalysisContext . currentAnalysisContext ( ) ; AnalysisContext . reportMissingClass ( missingClassDescriptor ) ; return missingClassVertex ; } | Add a ClassVertex representing a missing class . |
29,955 | public boolean prescreen ( ClassContext classContext , Method method ) { BitSet bytecodeSet = classContext . getBytecodeSet ( method ) ; return bytecodeSet != null && ( bytecodeSet . get ( Const . INVOKEINTERFACE ) || bytecodeSet . get ( Const . INVOKEVIRTUAL ) || bytecodeSet . get ( Const . INVOKESPECIAL ) || bytecodeSet . get ( Const . INVOKESTATIC ) || bytecodeSet . get ( Const . INVOKENONVIRTUAL ) ) ; } | Use this to screen out methods that do not contain invocations . |
29,956 | private boolean isSynthetic ( Method m ) { if ( ( m . getAccessFlags ( ) & Const . ACC_SYNTHETIC ) != 0 ) { return true ; } Attribute [ ] attrs = m . getAttributes ( ) ; for ( Attribute attr : attrs ) { if ( attr instanceof Synthetic ) { return true ; } } return false ; } | Methods marked with the Synthetic attribute do not appear in the source code |
29,957 | private boolean compareTypesOld ( Type parmType , Type argType ) { if ( GenericUtilities . getString ( parmType ) . equals ( GenericUtilities . getString ( argType ) ) ) { return true ; } if ( parmType instanceof GenericObjectType ) { GenericObjectType o = ( GenericObjectType ) parmType ; if ( o . getTypeCategory ( ) == GenericUtilities . TypeCategory . WILDCARD_EXTENDS ) { return compareTypesOld ( o . getExtension ( ) , argType ) ; } } if ( parmType instanceof GenericObjectType && ! ( ( GenericObjectType ) parmType ) . hasParameters ( ) ) { return true ; } if ( argType instanceof GenericObjectType && ! ( ( GenericObjectType ) argType ) . hasParameters ( ) ) { return true ; } if ( parmType instanceof GenericObjectType && argType instanceof GenericObjectType ) { return true ; } else { if ( ! ( parmType instanceof ReferenceType && argType instanceof ReferenceType ) ) { return true ; } if ( ! ( parmType instanceof ObjectType && argType instanceof ObjectType ) ) { return true ; } try { return Repository . instanceOf ( ( ( ObjectType ) argType ) . getClassName ( ) , ( ( ObjectType ) parmType ) . getClassName ( ) ) ; } catch ( ClassNotFoundException e ) { } } return true ; } | old version of compare types |
29,958 | public void checkMessages ( XMLFile messagesDoc ) throws DocumentException { for ( Iterator < Node > i = messagesDoc . xpathIterator ( "/MessageCollection/Detector" ) ; i . hasNext ( ) ; ) { Node node = i . next ( ) ; messagesDoc . checkAttribute ( node , "class" ) ; messagesDoc . checkElement ( node , "Details" ) ; } for ( Iterator < Node > i = messagesDoc . xpathIterator ( "/MessageCollection/BugPattern" ) ; i . hasNext ( ) ; ) { Node node = i . next ( ) ; messagesDoc . checkAttribute ( node , "type" ) ; messagesDoc . checkElement ( node , "ShortDescription" ) ; messagesDoc . checkElement ( node , "LongDescription" ) ; messagesDoc . checkElement ( node , "Details" ) ; } for ( Iterator < Node > i = messagesDoc . xpathIterator ( "/MessageCollection/BugCode" ) ; i . hasNext ( ) ; ) { Node node = i . next ( ) ; messagesDoc . checkAttribute ( node , "abbrev" ) ; messagesDoc . checkNonEmptyText ( node ) ; } Set < String > describedDetectorsSet = messagesDoc . collectAttributes ( "/MessageCollection/Detector" , "class" ) ; checkDescribed ( "Bug detectors not described by Detector elements" , messagesDoc , declaredDetectorsSet , describedDetectorsSet ) ; Set < String > describedAbbrevsSet = messagesDoc . collectAttributes ( "/MessageCollection/BugCode" , "abbrev" ) ; checkDescribed ( "Abbreviations not described by BugCode elements" , messagesDoc , declaredAbbrevsSet , describedAbbrevsSet ) ; } | Check given messages file for validity . |
29,959 | public static boolean check ( ) { Class < ? > objectType ; Class < ? > type ; Class < ? > constants ; Class < ? > emptyVis ; Class < ? > repository ; try { objectType = Class . forName ( ORG_APACHE_BCEL_GENERIC_OBJECT_TYPE ) ; type = Class . forName ( ORG_APACHE_BCEL_GENERIC_TYPE ) ; constants = Class . forName ( ORG_APACHE_BCEL_CONSTANTS ) ; emptyVis = Class . forName ( ORG_APACHE_BCEL_CLASSFILE_EMPTY_VISITOR ) ; repository = Class . forName ( ORG_APACHE_BCEL_REPOSITORY ) ; } catch ( ClassNotFoundException e ) { LOG . error ( "One or more required BCEL classes were missing." + " Ensure that bcel.jar is placed at the same directory with spotbugs.jar" ) ; return false ; } if ( isFinal ( objectType ) ) { error ( ORG_APACHE_BCEL_GENERIC_OBJECT_TYPE ) ; return false ; } if ( isFinal ( type ) ) { error ( ORG_APACHE_BCEL_GENERIC_TYPE ) ; return false ; } if ( isFinal ( constants ) ) { error ( ORG_APACHE_BCEL_CONSTANTS ) ; return false ; } if ( isFinal ( emptyVis ) ) { error ( ORG_APACHE_BCEL_CLASSFILE_EMPTY_VISITOR ) ; return false ; } if ( isFinal ( repository ) ) { error ( ORG_APACHE_BCEL_REPOSITORY ) ; return false ; } return true ; } | Check that the BCEL classes present seem to be the right ones . Specifically we check whether the ones extended in FindBugs code are non - final . |
29,960 | public ValueNumber forNumber ( int number ) { if ( number >= getNumValuesAllocated ( ) ) { throw new IllegalArgumentException ( "Value " + number + " has not been allocated" ) ; } return allocatedValueList . get ( number ) ; } | Return a previously allocated value . |
29,961 | public String format ( BugAnnotation [ ] args , ClassAnnotation primaryClass , boolean abridgedMessages ) { String pat = pattern ; StringBuilder result = new StringBuilder ( ) ; while ( pat . length ( ) > 0 ) { int subst = pat . indexOf ( '{' ) ; if ( subst < 0 ) { result . append ( pat ) ; break ; } result . append ( pat . substring ( 0 , subst ) ) ; pat = pat . substring ( subst + 1 ) ; int end = pat . indexOf ( '}' ) ; if ( end < 0 ) { throw new IllegalStateException ( "unmatched { in " + pat ) ; } String substPat = pat . substring ( 0 , end ) ; int dot = substPat . indexOf ( '.' ) ; String key = "" ; if ( dot >= 0 ) { key = substPat . substring ( dot + 1 ) ; substPat = substPat . substring ( 0 , dot ) ; } else if ( abridgedMessages && primaryClass != null ) { key = "givenClass" ; } int fieldNum ; try { fieldNum = Integer . parseInt ( substPat ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "Bad integer value " + substPat + " in " + pattern ) ; } if ( fieldNum < 0 ) { result . append ( "?<?" + fieldNum + "/" + args . length + "???" ) ; } else if ( fieldNum >= args . length ) { result . append ( "?>?" + fieldNum + "/" + args . length + "???" ) ; } else { BugAnnotation field = args [ fieldNum ] ; String formatted = "" ; try { formatted = field . format ( key , primaryClass ) ; } catch ( IllegalArgumentException iae ) { if ( SystemProperties . ASSERTIONS_ENABLED ) { throw new IllegalArgumentException ( "Problem processing " + pattern + " format " + substPat + " for " + field . getClass ( ) . getSimpleName ( ) , iae ) ; } formatted = "\u00BF" + fieldNum + ".(key=" + key + ")?" ; } result . append ( formatted ) ; } pat = pat . substring ( end + 1 ) ; } return result . toString ( ) ; } | Format the message using the given array of BugAnnotations as arguments to bind to the placeholders in the pattern string . |
29,962 | public static FieldAnnotation fromVisitedField ( PreorderVisitor visitor ) { return new FieldAnnotation ( visitor . getDottedClassName ( ) , visitor . getFieldName ( ) , visitor . getFieldSig ( ) , visitor . getFieldIsStatic ( ) ) ; } | Factory method . Class name field name and field signatures are taken from the given visitor which is visiting the field . |
29,963 | public static FieldAnnotation fromFieldDescriptor ( FieldDescriptor fieldDescriptor ) { return new FieldAnnotation ( fieldDescriptor . getClassDescriptor ( ) . getDottedClassName ( ) , fieldDescriptor . getName ( ) , fieldDescriptor . getSignature ( ) , fieldDescriptor . isStatic ( ) ) ; } | Factory method . Construct from a FieldDescriptor . |
29,964 | public static FieldAnnotation isRead ( Instruction ins , ConstantPoolGen cpg ) { if ( ins instanceof GETFIELD || ins instanceof GETSTATIC ) { FieldInstruction fins = ( FieldInstruction ) ins ; String className = fins . getClassName ( cpg ) ; return new FieldAnnotation ( className , fins . getName ( cpg ) , fins . getSignature ( cpg ) , fins instanceof GETSTATIC ) ; } else { return null ; } } | Is the given instruction a read of a field? |
29,965 | public static FieldAnnotation isWrite ( Instruction ins , ConstantPoolGen cpg ) { if ( ins instanceof PUTFIELD || ins instanceof PUTSTATIC ) { FieldInstruction fins = ( FieldInstruction ) ins ; String className = fins . getClassName ( cpg ) ; return new FieldAnnotation ( className , fins . getName ( cpg ) , fins . getSignature ( cpg ) , fins instanceof PUTSTATIC ) ; } else { return null ; } } | Is the instruction a write of a field? |
29,966 | public static boolean isClassFile ( IJavaElement elt ) { if ( elt == null ) { return false ; } return elt instanceof IClassFile || elt instanceof ICompilationUnit ; } | Checks whether the given java element is a Java class file . |
29,967 | public static void copyToClipboard ( String content ) { if ( content == null ) { return ; } Clipboard cb = null ; try { cb = new Clipboard ( Display . getDefault ( ) ) ; cb . setContents ( new String [ ] { content } , new TextTransfer [ ] { TextTransfer . getInstance ( ) } ) ; } finally { if ( cb != null ) { cb . dispose ( ) ; } } } | Copies given string to the system clipboard |
29,968 | public static void sortIMarkers ( IMarker [ ] markers ) { Arrays . sort ( markers , new Comparator < IMarker > ( ) { public int compare ( IMarker arg0 , IMarker arg1 ) { IResource resource0 = arg0 . getResource ( ) ; IResource resource1 = arg1 . getResource ( ) ; if ( resource0 != null && resource1 != null ) { return resource0 . getName ( ) . compareTo ( resource1 . getName ( ) ) ; } if ( resource0 != null && resource1 == null ) { return 1 ; } if ( resource0 == null && resource1 != null ) { return - 1 ; } return 0 ; } } ) ; } | Sorts an array of IMarkers based on their underlying resource name |
29,969 | public IsNullValue getDecision ( int edgeType ) { switch ( edgeType ) { case EdgeTypes . IFCMP_EDGE : return ifcmpDecision ; case EdgeTypes . FALL_THROUGH_EDGE : return fallThroughDecision ; default : throw new IllegalArgumentException ( "Bad edge type: " + edgeType ) ; } } | Get the decision reached about the value on outgoing edge of given type . |
29,970 | private BitSet findPreviouslyDeadBlocks ( ) throws DataflowAnalysisException , CFGBuilderException { BitSet deadBlocks = new BitSet ( ) ; ValueNumberDataflow vnaDataflow = classContext . getValueNumberDataflow ( method ) ; for ( Iterator < BasicBlock > i = vnaDataflow . getCFG ( ) . blockIterator ( ) ; i . hasNext ( ) ; ) { BasicBlock block = i . next ( ) ; ValueNumberFrame vnaFrame = vnaDataflow . getStartFact ( block ) ; if ( vnaFrame . isTop ( ) ) { deadBlocks . set ( block . getLabel ( ) ) ; } } return deadBlocks ; } | Find set of blocks which were known to be dead before doing the null pointer analysis . |
29,971 | public void addStreamEscape ( Stream source , Location target ) { StreamEscape streamEscape = new StreamEscape ( source , target ) ; streamEscapeSet . add ( streamEscape ) ; if ( FindOpenStream . DEBUG ) { System . out . println ( "Adding potential stream escape " + streamEscape ) ; } } | Indicate that a stream escapes at the given target Location . |
29,972 | public void addStreamOpenLocation ( Location streamOpenLocation , Stream stream ) { if ( FindOpenStream . DEBUG ) { System . out . println ( "Stream open location at " + streamOpenLocation ) ; } streamOpenLocationMap . put ( streamOpenLocation , stream ) ; if ( stream . isUninteresting ( ) ) { uninterestingStreamEscapeSet . add ( stream ) ; } } | Indicate that a stream is constructed at this Location . |
29,973 | private NullnessAnnotation getMethodNullnessAnnotation ( ) { if ( method . getSignature ( ) . indexOf ( ")L" ) >= 0 || method . getSignature ( ) . indexOf ( ")[" ) >= 0 ) { if ( DEBUG_NULLRETURN ) { System . out . println ( "Checking return annotation for " + SignatureConverter . convertMethodSignature ( classContext . getJavaClass ( ) , method ) ) ; } XMethod m = XFactory . createXMethod ( classContext . getJavaClass ( ) , method ) ; return AnalysisContext . currentAnalysisContext ( ) . getNullnessAnnotationDatabase ( ) . getResolvedAnnotation ( m , false ) ; } return NullnessAnnotation . UNKNOWN_NULLNESS ; } | See if the currently - visited method declares a |
29,974 | private void checkNonNullParam ( Location location , ConstantPoolGen cpg , TypeDataflow typeDataflow , InvokeInstruction invokeInstruction , BitSet nullArgSet , BitSet definitelyNullArgSet ) { if ( inExplicitCatchNullBlock ( location ) ) { return ; } boolean caught = inIndirectCatchNullBlock ( location ) ; if ( caught && skipIfInsideCatchNull ( ) ) { return ; } if ( invokeInstruction instanceof INVOKEDYNAMIC ) { return ; } XMethod m = XFactory . createXMethod ( invokeInstruction , cpg ) ; INullnessAnnotationDatabase db = AnalysisContext . currentAnalysisContext ( ) . getNullnessAnnotationDatabase ( ) ; SignatureParser sigParser = new SignatureParser ( invokeInstruction . getSignature ( cpg ) ) ; for ( int i = nullArgSet . nextSetBit ( 0 ) ; i >= 0 ; i = nullArgSet . nextSetBit ( i + 1 ) ) { if ( db . parameterMustBeNonNull ( m , i ) ) { boolean definitelyNull = definitelyNullArgSet . get ( i ) ; if ( DEBUG_NULLARG ) { System . out . println ( "Checking " + m ) ; System . out . println ( "QQQ2: " + i + " -- " + i + " is null" ) ; System . out . println ( "QQQ nullArgSet: " + nullArgSet ) ; System . out . println ( "QQQ dnullArgSet: " + definitelyNullArgSet ) ; } BugAnnotation variableAnnotation = null ; try { ValueNumberFrame vnaFrame = classContext . getValueNumberDataflow ( method ) . getFactAtLocation ( location ) ; ValueNumber valueNumber = vnaFrame . getArgument ( invokeInstruction , cpg , i , sigParser ) ; variableAnnotation = ValueNumberSourceInfo . findAnnotationFromValueNumber ( method , location , valueNumber , vnaFrame , "VALUE_OF" ) ; } catch ( DataflowAnalysisException e ) { AnalysisContext . logError ( "error" , e ) ; } catch ( CFGBuilderException e ) { AnalysisContext . logError ( "error" , e ) ; } int priority = definitelyNull ? HIGH_PRIORITY : NORMAL_PRIORITY ; if ( caught ) { priority ++ ; } if ( m . isPrivate ( ) && priority == HIGH_PRIORITY ) { priority = NORMAL_PRIORITY ; } String description = definitelyNull ? "INT_NULL_ARG" : "INT_MAYBE_NULL_ARG" ; WarningPropertySet < WarningProperty > propertySet = new WarningPropertySet < > ( ) ; Set < Location > derefLocationSet = Collections . singleton ( location ) ; addPropertiesForDereferenceLocations ( propertySet , derefLocationSet , false ) ; boolean duplicated = isDuplicated ( propertySet , location . getHandle ( ) . getPosition ( ) , false ) ; if ( duplicated ) { return ; } BugInstance warning = new BugInstance ( this , "NP_NONNULL_PARAM_VIOLATION" , priority ) . addClassAndMethod ( classContext . getJavaClass ( ) , method ) . addMethod ( m ) . describe ( MethodAnnotation . METHOD_CALLED ) . addParameterAnnotation ( i , description ) . addOptionalAnnotation ( variableAnnotation ) . addSourceLine ( classContext , method , location ) ; propertySet . decorateBugInstance ( warning ) ; bugReporter . reportBug ( warning ) ; } } } | We have a method invocation in which a possibly or definitely null parameter is passed . Check it against the library of nonnull annotations . |
29,975 | private boolean isGoto ( Instruction instruction ) { return instruction . getOpcode ( ) == Const . GOTO || instruction . getOpcode ( ) == Const . GOTO_W ; } | Determine whether or not given instruction is a goto . |
29,976 | public void dispose ( ) { classAnalysisMap . clear ( ) ; classAnalysisEngineMap . clear ( ) ; analysisLocals . clear ( ) ; databaseFactoryMap . clear ( ) ; databaseMap . clear ( ) ; methodAnalysisEngineMap . clear ( ) ; } | Cleans up all cached data |
29,977 | public < E > void reuseClassAnalysis ( Class < E > analysisClass , Map < ClassDescriptor , Object > map ) { Map < ClassDescriptor , Object > myMap = classAnalysisMap . get ( analysisClass ) ; if ( myMap != null ) { myMap . putAll ( map ) ; } else { myMap = createMap ( classAnalysisEngineMap , analysisClass ) ; myMap . putAll ( map ) ; classAnalysisMap . put ( analysisClass , myMap ) ; } } | Adds the data for given analysis type from given map to the cache |
29,978 | @ SuppressWarnings ( "unchecked" ) private < E > E analyzeMethod ( ClassContext classContext , Class < E > analysisClass , MethodDescriptor methodDescriptor ) throws CheckedAnalysisException { IMethodAnalysisEngine < E > engine = ( IMethodAnalysisEngine < E > ) methodAnalysisEngineMap . get ( analysisClass ) ; if ( engine == null ) { throw new IllegalArgumentException ( "No analysis engine registered to produce " + analysisClass . getName ( ) ) ; } Profiler profiler = getProfiler ( ) ; profiler . start ( engine . getClass ( ) ) ; try { return engine . analyze ( this , methodDescriptor ) ; } finally { profiler . end ( engine . getClass ( ) ) ; } } | Analyze a method . |
29,979 | private static < DescriptorType > Map < DescriptorType , Object > findOrCreateDescriptorMap ( final Map < Class < ? > , Map < DescriptorType , Object > > analysisClassToDescriptorMapMap , final Map < Class < ? > , ? extends IAnalysisEngine < DescriptorType , ? > > engineMap , final Class < ? > analysisClass ) { Map < DescriptorType , Object > descriptorMap = analysisClassToDescriptorMapMap . get ( analysisClass ) ; if ( descriptorMap == null ) { descriptorMap = createMap ( engineMap , analysisClass ) ; analysisClassToDescriptorMapMap . put ( analysisClass , descriptorMap ) ; } return descriptorMap ; } | Find or create a descriptor to analysis object map . |
29,980 | public void writeElementList ( String tagName , Collection < String > listValues ) { for ( String listValue : listValues ) { openTag ( tagName ) ; writeText ( listValue ) ; closeTag ( tagName ) ; } } | Add a list of Strings to document as elements with given tag name to the tree . |
29,981 | public boolean isObligationType ( ClassDescriptor classDescriptor ) { try { return getObligationByType ( BCELUtil . getObjectTypeInstance ( classDescriptor . toDottedClassName ( ) ) ) != null ; } catch ( ClassNotFoundException e ) { Global . getAnalysisCache ( ) . getErrorLogger ( ) . reportMissingClass ( e ) ; return false ; } } | Determine whether class named by given ClassDescriptor is an Obligation type . |
29,982 | public Obligation [ ] getParameterObligationTypes ( XMethod xmethod ) { Type [ ] paramTypes = Type . getArgumentTypes ( xmethod . getSignature ( ) ) ; Obligation [ ] result = new Obligation [ paramTypes . length ] ; for ( int i = 0 ; i < paramTypes . length ; i ++ ) { if ( ! ( paramTypes [ i ] instanceof ObjectType ) ) { continue ; } try { result [ i ] = getObligationByType ( ( ObjectType ) paramTypes [ i ] ) ; } catch ( ClassNotFoundException e ) { Global . getAnalysisCache ( ) . getErrorLogger ( ) . reportMissingClass ( e ) ; } } return result ; } | Get array of Obligation types corresponding to the parameters of the given method . |
29,983 | public Fact getFactAfterLocation ( Location location ) throws DataflowAnalysisException { BasicBlock basicBlock = location . getBasicBlock ( ) ; InstructionHandle handle = location . getHandle ( ) ; if ( handle == ( isForwards ( ) ? basicBlock . getLastInstruction ( ) : basicBlock . getFirstInstruction ( ) ) ) { return getResultFact ( basicBlock ) ; } else { return getFactAtLocation ( new Location ( isForwards ( ) ? handle . getNext ( ) : handle . getPrev ( ) , basicBlock ) ) ; } } | Get the dataflow fact representing the point just after given Location . Note after is meant in the logical sense so for backward analyses after means before the location in the control flow sense . |
29,984 | public void visit ( JavaClass someObj ) { currentClass = someObj . getClassName ( ) ; currentMethod = null ; currentCFG = null ; currentLockDataFlow = null ; sawDateClass = false ; } | Remembers the class name and resets temporary fields . |
29,985 | private void addAuxClassPathEntries ( String argument ) { StringTokenizer tok = new StringTokenizer ( argument , File . pathSeparator ) ; while ( tok . hasMoreTokens ( ) ) { project . addAuxClasspathEntry ( tok . nextToken ( ) ) ; } } | Parse the argument as auxclasspath entries and add them |
29,986 | private void choose ( String argument , String desc , Chooser chooser ) { StringTokenizer tok = new StringTokenizer ( argument , "," ) ; while ( tok . hasMoreTokens ( ) ) { String what = tok . nextToken ( ) . trim ( ) ; if ( ! what . startsWith ( "+" ) && ! what . startsWith ( "-" ) ) { throw new IllegalArgumentException ( desc + " must start with " + "\"+\" or \"-\" (saw " + what + ")" ) ; } boolean enabled = what . startsWith ( "+" ) ; chooser . choose ( enabled , what . substring ( 1 ) ) ; } } | Common handling code for - chooseVisitors and - choosePlugins options . |
29,987 | public void handleXArgs ( ) throws IOException { if ( getXargs ( ) ) { try ( BufferedReader in = UTF8 . bufferedReader ( System . in ) ) { while ( true ) { String s = in . readLine ( ) ; if ( s == null ) { break ; } project . addFile ( s ) ; } } } } | Handle - xargs command line option by reading jar file names from standard input and adding them to the project . |
29,988 | private void handleAuxClassPathFromFile ( String filePath ) throws IOException { try ( BufferedReader in = new BufferedReader ( UTF8 . fileReader ( filePath ) ) ) { while ( true ) { String s = in . readLine ( ) ; if ( s == null ) { break ; } project . addAuxClasspathEntry ( s ) ; } } } | Handle - readAuxFromFile command line option by reading classpath entries from a file and adding them to the project . |
29,989 | private void handleAnalyzeFromFile ( String filePath ) throws IOException { try ( BufferedReader in = new BufferedReader ( UTF8 . fileReader ( filePath ) ) ) { while ( true ) { String s = in . readLine ( ) ; if ( s == null ) { break ; } project . addFile ( s ) ; } } } | Handle - analyzeFromFile command line option by reading jar file names from a file and adding them to the project . |
29,990 | public Project duplicate ( ) { Project dup = new Project ( ) ; dup . currentWorkingDirectoryList . addAll ( this . currentWorkingDirectoryList ) ; dup . projectName = this . projectName ; dup . analysisTargets . addAll ( this . analysisTargets ) ; dup . srcDirList . addAll ( this . srcDirList ) ; dup . auxClasspathEntryList . addAll ( this . auxClasspathEntryList ) ; dup . timestampForAnalyzedClasses = timestampForAnalyzedClasses ; dup . guiCallback = guiCallback ; return dup ; } | Return an exact copy of this Project . |
29,991 | public void add ( Project project2 ) { analysisTargets = appendWithoutDuplicates ( analysisTargets , project2 . analysisTargets ) ; srcDirList = appendWithoutDuplicates ( srcDirList , project2 . srcDirList ) ; auxClasspathEntryList = appendWithoutDuplicates ( auxClasspathEntryList , project2 . auxClasspathEntryList ) ; } | add information from project2 to this project |
29,992 | public boolean addSourceDirs ( Collection < String > sourceDirs ) { boolean isNew = false ; if ( sourceDirs == null || sourceDirs . isEmpty ( ) ) { return isNew ; } for ( String dirName : sourceDirs ) { for ( String dir : makeAbsoluteCwdCandidates ( dirName ) ) { isNew = addToListInternal ( srcDirList , dir ) || isNew ; } } IO . close ( sourceFinder ) ; sourceFinder = new SourceFinder ( this ) ; return isNew ; } | Add source directories to the project . |
29,993 | public boolean addWorkingDir ( String dirName ) { if ( dirName == null ) { throw new NullPointerException ( ) ; } return addToListInternal ( currentWorkingDirectoryList , new File ( dirName ) ) ; } | Add a working directory to the project . |
29,994 | public void removeSourceDir ( int num ) { srcDirList . remove ( num ) ; IO . close ( sourceFinder ) ; sourceFinder = new SourceFinder ( this ) ; isModified = true ; } | Remove source directory at given index . |
29,995 | public void write ( String outputFile , boolean useRelativePaths , String relativeBase ) throws IOException { PrintWriter writer = UTF8 . printWriter ( outputFile ) ; try { writer . println ( JAR_FILES_KEY ) ; for ( String jarFile : analysisTargets ) { if ( useRelativePaths ) { jarFile = convertToRelative ( jarFile , relativeBase ) ; } writer . println ( jarFile ) ; } writer . println ( SRC_DIRS_KEY ) ; for ( String srcDir : srcDirList ) { if ( useRelativePaths ) { srcDir = convertToRelative ( srcDir , relativeBase ) ; } writer . println ( srcDir ) ; } writer . println ( AUX_CLASSPATH_ENTRIES_KEY ) ; for ( String auxClasspathEntry : auxClasspathEntryList ) { if ( useRelativePaths ) { auxClasspathEntry = convertToRelative ( auxClasspathEntry , relativeBase ) ; } writer . println ( auxClasspathEntry ) ; } if ( useRelativePaths ) { writer . println ( OPTIONS_KEY ) ; writer . println ( RELATIVE_PATHS + "=true" ) ; } } finally { writer . close ( ) ; } isModified = false ; } | Save the project to an output file . |
29,996 | public static Project readProject ( String argument ) throws IOException { String projectFileName = argument ; File projectFile = new File ( projectFileName ) ; if ( projectFileName . endsWith ( ".xml" ) || projectFileName . endsWith ( ".fbp" ) ) { try { return Project . readXML ( projectFile ) ; } catch ( SAXException e ) { IOException ioe = new IOException ( "Couldn't read saved FindBugs project" ) ; ioe . initCause ( e ) ; throw ioe ; } } throw new IllegalArgumentException ( "Can't read project from " + argument ) ; } | Read Project from named file . |
29,997 | private String convertToRelative ( String srcFile , String base ) { String slash = SystemProperties . getProperty ( "file.separator" ) ; if ( FILE_IGNORE_CASE ) { srcFile = srcFile . toLowerCase ( ) ; base = base . toLowerCase ( ) ; } if ( base . equals ( srcFile ) ) { return "." ; } if ( ! base . endsWith ( slash ) ) { base = base + slash ; } if ( base . length ( ) <= srcFile . length ( ) ) { String root = srcFile . substring ( 0 , base . length ( ) ) ; if ( root . equals ( base ) ) { return "." + SystemProperties . getProperty ( "file.separator" ) + srcFile . substring ( base . length ( ) ) ; } } int slashPos = srcFile . indexOf ( slash ) ; int branchPoint ; if ( slashPos >= 0 ) { String subPath = srcFile . substring ( 0 , slashPos ) ; if ( ( subPath . length ( ) == 0 ) || base . startsWith ( subPath ) ) { branchPoint = slashPos + 1 ; slashPos = srcFile . indexOf ( slash , branchPoint ) ; while ( slashPos >= 0 ) { subPath = srcFile . substring ( 0 , slashPos ) ; if ( base . startsWith ( subPath ) ) { branchPoint = slashPos + 1 ; } else { break ; } slashPos = srcFile . indexOf ( slash , branchPoint ) ; } int slashCount = 0 ; slashPos = base . indexOf ( slash , branchPoint ) ; while ( slashPos >= 0 ) { slashCount ++ ; slashPos = base . indexOf ( slash , slashPos + 1 ) ; } StringBuilder path = new StringBuilder ( ) ; String upDir = ".." + slash ; for ( int i = 0 ; i < slashCount ; i ++ ) { path . append ( upDir ) ; } path . append ( srcFile . substring ( branchPoint ) ) ; return path . toString ( ) ; } } return srcFile ; } | Converts a full path to a relative path if possible |
29,998 | private String makeAbsoluteCWD ( String fileName ) { List < String > candidates = makeAbsoluteCwdCandidates ( fileName ) ; return candidates . get ( 0 ) ; } | Make the given filename absolute relative to the current working directory . |
29,999 | 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 . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.