code stringlengths 73 34.1k | label stringclasses 1 value |
|---|---|
private static Set<Method> findLockedMethods(ClassContext classContext, SelfCalls selfCalls, Set<CallSite> obviouslyLockedSites)
{
JavaClass javaClass = classContext.getJavaClass();
Method[] methodList = javaClass.getMethods();
CallGraph callGraph = selfCalls.getCallGraph();
// Initially, assume all methods are locked
Set<Method> lockedMethodSet = new HashSet<>();
// Assume all public methods are unlocked
for (Method method : methodList) {
if (method.isSynchronized()) {
lockedMethodSet.add(method);
}
}
// Explore the self-call graph to find nonpublic methods
// that can be called from an unlocked context.
boolean change;
do {
change = false;
for (Iterator<CallGraphEdge> i = callGraph.edgeIterator(); i.hasNext();) {
CallGraphEdge edge = i.next();
CallSite callSite = edge.getCallSite();
if (obviouslyLockedSites.contains(callSite) || lockedMethodSet.contains(callSite.getMethod())) {
// Calling method is locked, so the called method
// is also locked.
CallGraphNode target = edge.getTarget();
if (lockedMethodSet.add(target.getMethod())) {
change = true;
}
}
}
} while (change);
if (DEBUG) {
System.out.println("Apparently locked methods:");
for (Method method : lockedMethodSet) {
System.out.println("\t" + method.getName());
}
}
// We assume that any methods left in the locked set
// are called only from a locked context.
return lockedMethodSet;
} | java |
private static Set<CallSite> findObviouslyLockedCallSites(ClassContext classContext, SelfCalls selfCalls)
throws CFGBuilderException, DataflowAnalysisException {
ConstantPoolGen cpg = classContext.getConstantPoolGen();
// Find all obviously locked call sites
Set<CallSite> obviouslyLockedSites = new HashSet<>();
for (Iterator<CallSite> i = selfCalls.callSiteIterator(); i.hasNext();) {
CallSite callSite = i.next();
Method method = callSite.getMethod();
Location location = callSite.getLocation();
InstructionHandle handle = location.getHandle();
// Only instance method calls qualify as candidates for
// "obviously locked"
Instruction ins = handle.getInstruction();
if (ins.getOpcode() == Const.INVOKESTATIC) {
continue;
}
// Get lock set for site
LockChecker lockChecker = classContext.getLockChecker(method);
LockSet lockSet = lockChecker.getFactAtLocation(location);
// Get value number frame for site
ValueNumberDataflow vnaDataflow = classContext.getValueNumberDataflow(method);
ValueNumberFrame frame = vnaDataflow.getFactAtLocation(location);
// NOTE: if the CFG on which the value number analysis was performed
// was pruned, there may be unreachable instructions. Therefore,
// we can't assume the frame is valid.
if (!frame.isValid()) {
continue;
}
// Find the ValueNumber of the receiver object
int numConsumed = ins.consumeStack(cpg);
MethodGen methodGen = classContext.getMethodGen(method);
assert methodGen != null;
if (numConsumed == Const.UNPREDICTABLE) {
throw new DataflowAnalysisException("Unpredictable stack consumption", methodGen, handle);
}
// if (DEBUG) System.out.println("Getting receiver for frame: " +
// frame);
ValueNumber instance = frame.getStackValue(numConsumed - 1);
// Is the instance locked?
int lockCount = lockSet.getLockCount(instance.getNumber());
if (lockCount > 0) {
// This is a locked call site
obviouslyLockedSites.add(callSite);
}
}
return obviouslyLockedSites;
} | java |
private static boolean implementsMap(ClassDescriptor d) {
while (d != null) {
try {
// Do not report this warning for EnumMap: EnumMap.keySet()/get() iteration is as fast as entrySet() iteration
if ("java.util.EnumMap".equals(d.getDottedClassName())) {
return false;
}
// True if variable is itself declared as a Map
if ("java.util.Map".equals(d.getDottedClassName())) {
return true;
}
XClass classNameAndInfo = Global.getAnalysisCache().getClassAnalysis(XClass.class, d);
ClassDescriptor is[] = classNameAndInfo.getInterfaceDescriptorList();
d = classNameAndInfo.getSuperclassDescriptor();
for (ClassDescriptor i : is) {
if ("java.util.Map".equals(i.getDottedClassName())) {
return true;
}
}
} catch (CheckedAnalysisException e) {
d = null;
}
}
return false;
} | java |
private void restoreDefaultSettings() {
if (getProject() != null) {
// By default, don't run FindBugs automatically
chkEnableFindBugs.setSelection(false);
chkRunAtFullBuild.setEnabled(false);
FindBugsPreferenceInitializer.restoreDefaults(projectStore);
} else {
FindBugsPreferenceInitializer.restoreDefaults(workspaceStore);
}
currentUserPreferences = FindBugsPreferenceInitializer.createDefaultUserPreferences();
refreshUI(currentUserPreferences);
} | java |
@Override
public boolean performOk() {
reportConfigurationTab.performOk();
boolean analysisSettingsChanged = false;
boolean reporterSettingsChanged = false;
boolean needRedisplayMarkers = false;
if (workspaceSettingsTab != null) {
workspaceSettingsTab.performOK();
}
boolean pluginsChanged = false;
// Have user preferences for project changed?
// If so, write them to the user preferences file & re-run builder
if (!currentUserPreferences.equals(origUserPreferences)) {
pluginsChanged = !currentUserPreferences.getCustomPlugins().equals(origUserPreferences.getCustomPlugins());
// save only if we in the workspace page OR in the project page with
// enabled
// project settings
if (getProject() == null || enableProjectCheck.getSelection()) {
try {
FindbugsPlugin.saveUserPreferences(getProject(), currentUserPreferences);
} catch (CoreException e) {
FindbugsPlugin.getDefault().logException(e, "Could not store SpotBugs preferences for project");
}
}
if(pluginsChanged) {
FindbugsPlugin.applyCustomDetectors(true);
}
}
analysisSettingsChanged = pluginsChanged || areAnalysisPrefsChanged(currentUserPreferences, origUserPreferences);
reporterSettingsChanged = !currentUserPreferences.getFilterSettings().equals(origUserPreferences.getFilterSettings());
boolean markerSeveritiesChanged = reportConfigurationTab.isMarkerSeveritiesChanged();
needRedisplayMarkers = pluginsChanged || markerSeveritiesChanged || reporterSettingsChanged;
boolean builderEnabled = false;
if (getProject() != null) {
builderEnabled = chkEnableFindBugs.getSelection();
// Update whether or not FindBugs is run automatically.
if (!natureEnabled && builderEnabled) {
addNature();
} else if (natureEnabled && !builderEnabled) {
removeNature();
}
// update the flag to match the incremental/not property
builderEnabled &= chkRunAtFullBuild.getSelection();
boolean newSelection = enableProjectCheck.getSelection();
if (projectPropsInitiallyEnabled != newSelection) {
analysisSettingsChanged = true;
FindbugsPlugin.setProjectSettingsEnabled(project, projectStore, newSelection);
}
}
if (analysisSettingsChanged) {
// trigger a Findbugs rebuild here
if (builderEnabled) {
runFindbugsBuilder();
needRedisplayMarkers = false;
} else {
if (!getPreferenceStore().getBoolean(FindBugsConstants.DONT_REMIND_ABOUT_FULL_BUILD)) {
remindAboutFullBuild();
}
}
}
if (needRedisplayMarkers) {
redisplayMarkers();
}
return true;
} | java |
public Token next() throws IOException {
skipWhitespace();
int c = reader.read();
if (c < 0) {
return new Token(Token.EOF);
} else if (c == '\n') {
return new Token(Token.EOL);
} else if (c == '\'' || c == '"') {
return munchString(c);
} else if (c == '/') {
return maybeComment();
} else if (single.get(c)) {
return new Token(Token.SINGLE, String.valueOf((char) c));
} else {
reader.unread(c);
return parseWord();
}
} | java |
private void reportResultsToConsole() {
if (!isStreamReportingEnabled()) {
return;
}
printToStream("Finished, found: " + bugCount + " bugs");
ConfigurableXmlOutputStream xmlStream = new ConfigurableXmlOutputStream(stream, true);
ProjectStats stats = bugCollection.getProjectStats();
printToStream("\nFootprint: " + new Footprint(stats.getBaseFootprint()).toString());
Profiler profiler = stats.getProfiler();
PrintStream printStream;
try {
printStream = new PrintStream(stream, false, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// can never happen with UTF-8
return;
}
printToStream("\nTotal time:");
profiler.report(new Profiler.TotalTimeComparator(profiler), new Profiler.FilterByTime(10000000), printStream);
printToStream("\nTotal calls:");
int numClasses = stats.getNumClasses();
if(numClasses > 0) {
profiler.report(new Profiler.TotalCallsComparator(profiler), new Profiler.FilterByCalls(numClasses),
printStream);
printToStream("\nTime per call:");
profiler.report(new Profiler.TimePerCallComparator(profiler),
new Profiler.FilterByTimePerCall(10000000 / numClasses), printStream);
}
try {
xmlStream.finish();
} catch (IOException e) {
FindbugsPlugin.getDefault().logException(e, "Print to console failed");
}
} | java |
public ByteCodePattern addWild(int numWild) {
Wild wild = isLastWild();
if (wild != null) {
wild.setMinAndMax(0, numWild);
} else {
addElement(new Wild(numWild));
}
return this;
} | java |
public Edge lookupEdgeById(int id) {
Iterator<Edge> i = edgeIterator();
while (i.hasNext()) {
Edge edge = i.next();
if (edge.getId() == id) {
return edge;
}
}
return null;
} | java |
public BasicBlock lookupBlockByLabel(int blockLabel) {
for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) {
BasicBlock basicBlock = i.next();
if (basicBlock.getLabel() == blockLabel) {
return basicBlock;
}
}
return null;
} | java |
public Collection<Location> orderedLocations() {
TreeSet<Location> tree = new TreeSet<>();
for (Iterator<Location> locs = locationIterator(); locs.hasNext();) {
Location loc = locs.next();
tree.add(loc);
}
return tree;
} | java |
public Collection<BasicBlock> getBlocks(BitSet labelSet) {
LinkedList<BasicBlock> result = new LinkedList<>();
for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) {
BasicBlock block = i.next();
if (labelSet.get(block.getLabel())) {
result.add(block);
}
}
return result;
} | java |
public Collection<BasicBlock> getBlocksContainingInstructionWithOffset(int offset) {
LinkedList<BasicBlock> result = new LinkedList<>();
for (Iterator<BasicBlock> i = blockIterator(); i.hasNext();) {
BasicBlock block = i.next();
if (block.containsInstructionWithOffset(offset)) {
result.add(block);
}
}
return result;
} | java |
public Collection<Location> getLocationsContainingInstructionWithOffset(int offset) {
LinkedList<Location> result = new LinkedList<>();
for (Iterator<Location> i = locationIterator(); i.hasNext();) {
Location location = i.next();
if (location.getHandle().getPosition() == offset) {
result.add(location);
}
}
return result;
} | java |
public int getNumNonExceptionSucessors(BasicBlock block) {
int numNonExceptionSuccessors = block.getNumNonExceptionSuccessors();
if (numNonExceptionSuccessors < 0) {
numNonExceptionSuccessors = 0;
for (Iterator<Edge> i = outgoingEdgeIterator(block); i.hasNext();) {
Edge edge = i.next();
if (!edge.isExceptionEdge()) {
numNonExceptionSuccessors++;
}
}
block.setNumNonExceptionSuccessors(numNonExceptionSuccessors);
}
return numNonExceptionSuccessors;
} | java |
public Location getLocationAtEntry() {
InstructionHandle handle = getEntry().getFirstInstruction();
assert handle != null;
return new Location(handle, getEntry());
} | java |
public void addPlugin(Plugin plugin) throws OrderingConstraintException {
if (DEBUG) {
System.out.println("Adding plugin " + plugin.getPluginId() + " to execution plan");
}
pluginList.add(plugin);
// Add ordering constraints
copyTo(plugin.interPassConstraintIterator(), interPassConstraintList);
copyTo(plugin.intraPassConstraintIterator(), intraPassConstraintList);
// Add detector factories
for (DetectorFactory factory : plugin.getDetectorFactories()) {
if (DEBUG) {
System.out.println(" Detector factory " + factory.getShortName());
}
if (factoryMap.put(factory.getFullName(), factory) != null) {
throw new OrderingConstraintException("Detector " + factory.getFullName() + " is defined by more than one plugin");
}
}
} | java |
private void assignToPass(DetectorFactory factory, AnalysisPass pass) {
pass.addToPass(factory);
assignedToPassSet.add(factory);
} | java |
public void execute(InstructionScannerGenerator generator) {
// Pump the instructions in the path through the generator and all
// generated scanners
while (edgeIter.hasNext()) {
Edge edge = edgeIter.next();
BasicBlock source = edge.getSource();
if (DEBUG) {
System.out.println("ISD: scanning instructions in block " + source.getLabel());
}
// Traverse all instructions in the source block
Iterator<InstructionHandle> i = source.instructionIterator();
int count = 0;
while (i.hasNext()) {
InstructionHandle handle = i.next();
// Check if the generator wants to create a new scanner
if (generator.start(handle)) {
scannerList.add(generator.createScanner());
}
// Pump the instruction into all scanners
for (InstructionScanner scanner : scannerList) {
scanner.scanInstruction(handle);
}
++count;
}
if (DEBUG) {
System.out.println("ISD: scanned " + count + " instructions");
}
// Now that we've finished the source block, pump the edge
// into all scanners
for (InstructionScanner scanner : scannerList) {
scanner.traverseEdge(edge);
}
}
} | java |
@SuppressWarnings("rawtypes")
@Override
protected IProject[] build(int kind, Map args, IProgressMonitor monitor) throws CoreException {
monitor.subTask("Running SpotBugs...");
switch (kind) {
case IncrementalProjectBuilder.FULL_BUILD: {
FindBugs2Eclipse.cleanClassClache(getProject());
if (FindbugsPlugin.getUserPreferences(getProject()).isRunAtFullBuild()) {
if (DEBUG) {
System.out.println("FULL BUILD");
}
doBuild(args, monitor, kind);
} else {
// TODO probably worth to cleanup?
// MarkerUtil.removeMarkers(getProject());
}
break;
}
case IncrementalProjectBuilder.INCREMENTAL_BUILD: {
if (DEBUG) {
System.out.println("INCREMENTAL BUILD");
}
doBuild(args, monitor, kind);
break;
}
case IncrementalProjectBuilder.AUTO_BUILD: {
if (DEBUG) {
System.out.println("AUTO BUILD");
}
doBuild(args, monitor, kind);
break;
}
default: {
FindbugsPlugin.getDefault()
.logWarning("UKNOWN BUILD kind" + kind);
doBuild(args, monitor, kind);
break;
}
}
return null;
} | java |
protected void work(final IResource resource, final List<WorkItem> resources, IProgressMonitor monitor) {
IPreferenceStore store = FindbugsPlugin.getPluginPreferences(getProject());
boolean runAsJob = store.getBoolean(FindBugsConstants.KEY_RUN_ANALYSIS_AS_EXTRA_JOB);
FindBugsJob fbJob = new StartedFromBuilderJob("Finding bugs in " + resource.getName() + "...", resource, resources);
if(runAsJob) {
// run asynchronously, so there might be more similar jobs waiting to run
if (DEBUG) {
FindbugsPlugin.log("cancelSimilarJobs");
}
FindBugsJob.cancelSimilarJobs(fbJob);
if (DEBUG) {
FindbugsPlugin.log("scheduleAsSystem");
}
fbJob.scheduleAsSystem();
if (DEBUG) {
FindbugsPlugin.log("done scheduleAsSystem");
}
} else {
// run synchronously (in same thread)
if (DEBUG) {
FindbugsPlugin.log("running fbJob");
}
fbJob.run(monitor);
if (DEBUG) {
FindbugsPlugin.log("done fbJob");
}
}
} | java |
public static @DottedClassName
String getMissingClassName(ClassNotFoundException ex) {
// If the exception has a ResourceNotFoundException as the cause,
// then we have an easy answer.
Throwable cause = ex.getCause();
if (cause instanceof ResourceNotFoundException) {
String resourceName = ((ResourceNotFoundException) cause).getResourceName();
if (resourceName != null) {
ClassDescriptor classDesc = DescriptorFactory.createClassDescriptorFromResourceName(resourceName);
return classDesc.toDottedClassName();
}
}
if (ex.getMessage() == null) {
return null;
}
// Try the regular expression patterns to parse the class name
// from the exception message.
for (Pattern pattern : patternList) {
Matcher matcher = pattern.matcher(ex.getMessage());
if (matcher.matches()) {
String className = matcher.group(1);
ClassName.assertIsDotted(className);
return className;
}
}
return null;
} | java |
public void addFieldLine(String className, String fieldName, SourceLineRange range) {
fieldLineMap.put(new FieldDescriptor(className, fieldName), range);
} | java |
public void addMethodLine(String className, String methodName, String methodSignature, SourceLineRange range) {
methodLineMap.put(new MethodDescriptor(className, methodName, methodSignature), range);
} | java |
public @CheckForNull
SourceLineRange getFieldLine(String className, String fieldName) {
return fieldLineMap.get(new FieldDescriptor(className, fieldName));
} | java |
public @CheckForNull
SourceLineRange getMethodLine(String className, String methodName, String methodSignature) {
return methodLineMap.get(new MethodDescriptor(className, methodName, methodSignature));
} | java |
private static String parseVersionNumber(String line) {
StringTokenizer tokenizer = new StringTokenizer(line, " \t");
if (!expect(tokenizer, "sourceInfo") || !expect(tokenizer, "version") || !tokenizer.hasMoreTokens()) {
return null;
}
return tokenizer.nextToken();
} | java |
private static boolean expect(StringTokenizer tokenizer, String token) {
if (!tokenizer.hasMoreTokens()) {
return false;
}
String s = tokenizer.nextToken();
if (DEBUG) {
System.out.println("token=" + s);
}
return s.equals(token);
} | java |
private int compareClassesAllowingNull(ClassAnnotation lhs, ClassAnnotation rhs) {
if (lhs == null || rhs == null) {
return compareNullElements(lhs, rhs);
}
String lhsClassName = classNameRewriter.rewriteClassName(lhs.getClassName());
String rhsClassName = classNameRewriter.rewriteClassName(rhs.getClassName());
if (DEBUG) {
System.err.println("Comparing " + lhsClassName + " and " + rhsClassName);
}
int cmp = lhsClassName.compareTo(rhsClassName);
if (DEBUG) {
System.err.println("\t==> " + cmp);
}
return cmp;
} | java |
static int countFilteredBugs() {
int result = 0;
for (BugLeafNode bug : getMainBugSet().mainList) {
if (suppress(bug)) {
result++;
}
}
return result;
} | java |
public BugSet query(BugAspects a) {
BugSet result = this;
for (SortableValue sp : a) {
result = result.query(sp);
}
return result;
} | java |
private static Location pcToLocation(ClassContext classContext, Method method, int pc) throws CFGBuilderException {
CFG cfg = classContext.getCFG(method);
for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
Location location = i.next();
if (location.getHandle().getPosition() == pc) {
return location;
}
}
return null;
} | java |
private static void addReceiverObjectType(WarningPropertySet<WarningProperty> propertySet, ClassContext classContext,
Method method, Location location) {
try {
Instruction ins = location.getHandle().getInstruction();
if (!receiverObjectInstructionSet.get(ins.getOpcode())) {
return;
}
TypeDataflow typeDataflow = classContext.getTypeDataflow(method);
TypeFrame frame = typeDataflow.getFactAtLocation(location);
if (frame.isValid()) {
Type type = frame.getInstance(ins, classContext.getConstantPoolGen());
if (type instanceof ReferenceType) {
propertySet.setProperty(GeneralWarningProperty.RECEIVER_OBJECT_TYPE, type.toString());
}
}
} catch (DataflowAnalysisException e) {
// Ignore
} catch (CFGBuilderException e) {
// Ignore
}
} | java |
private Set<String> buildClassSet(BugCollection bugCollection) {
Set<String> classSet = new HashSet<>();
for (Iterator<BugInstance> i = bugCollection.iterator(); i.hasNext();) {
BugInstance warning = i.next();
for (Iterator<BugAnnotation> j = warning.annotationIterator(); j.hasNext();) {
BugAnnotation annotation = j.next();
if (!(annotation instanceof ClassAnnotation)) {
continue;
}
classSet.add(((ClassAnnotation) annotation).getClassName());
}
}
return classSet;
} | java |
private void suppressWarningsIfOneLiveStoreOnLine(BugAccumulator accumulator, BitSet liveStoreSourceLineSet) {
if (!SUPPRESS_IF_AT_LEAST_ONE_LIVE_STORE_ON_LINE) {
return;
}
// Eliminate any accumulated warnings for instructions
// that (due to inlining) *can* be live stores.
entryLoop: for (Iterator<? extends BugInstance> i = accumulator.uniqueBugs().iterator(); i.hasNext();) {
for (SourceLineAnnotation annotation : accumulator.locations(i.next())) {
if (liveStoreSourceLineSet.get(annotation.getStartLine())) {
// This instruction can be a live store; don't report
// it as a warning.
i.remove();
continue entryLoop;
}
}
}
} | java |
private void countLocalStoresLoadsAndIncrements(int[] localStoreCount, int[] localLoadCount, int[] localIncrementCount,
CFG cfg) {
for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
Location location = i.next();
if (location.getBasicBlock().isExceptionHandler()) {
continue;
}
boolean isStore = isStore(location);
boolean isLoad = isLoad(location);
if (!isStore && !isLoad) {
continue;
}
IndexedInstruction ins = (IndexedInstruction) location.getHandle().getInstruction();
int local = ins.getIndex();
if (ins instanceof IINC) {
localStoreCount[local]++;
localLoadCount[local]++;
localIncrementCount[local]++;
} else if (isStore) {
localStoreCount[local]++;
} else {
localLoadCount[local]++;
}
}
} | java |
private boolean isStore(Location location) {
Instruction ins = location.getHandle().getInstruction();
return (ins instanceof StoreInstruction) || (ins instanceof IINC);
} | java |
private boolean isLoad(Location location) {
Instruction ins = location.getHandle().getInstruction();
return (ins instanceof LoadInstruction) || (ins instanceof IINC);
} | java |
public AnnotationVisitor getAnnotationVisitor() {
return new AnnotationVisitor(FindBugsASM.ASM_VERSION) {
@Override
public void visit(String name, Object value) {
name = canonicalString(name);
valueMap.put(name, value);
}
/*
* (non-Javadoc)
*
* @see
* org.objectweb.asm.AnnotationVisitor#visitAnnotation(java.lang
* .String, java.lang.String)
*/
@Override
public AnnotationVisitor visitAnnotation(String name, String desc) {
name = canonicalString(name);
AnnotationValue newValue = new AnnotationValue(desc);
valueMap.put(name, newValue);
typeMap.put(name, desc);
return newValue.getAnnotationVisitor();
}
/*
* (non-Javadoc)
*
* @see
* org.objectweb.asm.AnnotationVisitor#visitArray(java.lang.String)
*/
@Override
public AnnotationVisitor visitArray(String name) {
name = canonicalString(name);
return new AnnotationArrayVisitor(name);
}
/*
* (non-Javadoc)
*
* @see org.objectweb.asm.AnnotationVisitor#visitEnd()
*/
@Override
public void visitEnd() {
}
/*
* (non-Javadoc)
*
* @see
* org.objectweb.asm.AnnotationVisitor#visitEnum(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public void visitEnum(String name, String desc, String value) {
name = canonicalString(name);
valueMap.put(name, new EnumValue(desc, value));
typeMap.put(name, desc);
}
};
} | java |
private Constant readConstant() throws InvalidClassFileFormatException, IOException {
int tag = in.readUnsignedByte();
if (tag < 0 || tag >= CONSTANT_FORMAT_MAP.length) {
throw new InvalidClassFileFormatException(expectedClassDescriptor, codeBaseEntry);
}
String format = CONSTANT_FORMAT_MAP[tag];
if (format == null) {
throw new InvalidClassFileFormatException(expectedClassDescriptor, codeBaseEntry);
}
Object[] data = new Object[format.length()];
for (int i = 0; i < format.length(); i++) {
char spec = format.charAt(i);
switch (spec) {
case '8':
data[i] = in.readUTF();
break;
case 'I':
data[i] = in.readInt();
break;
case 'F':
data[i] = Float.valueOf(in.readFloat());
break;
case 'L':
data[i] = in.readLong();
break;
case 'D':
data[i] = Double.valueOf(in.readDouble());
break;
case 'i':
data[i] = in.readUnsignedShort();
break;
case 'b':
data[i] = in.readUnsignedByte();
break;
default:
throw new IllegalStateException();
}
}
return new Constant(tag, data);
} | java |
private String getUtf8String(int refIndex) throws InvalidClassFileFormatException {
checkConstantPoolIndex(refIndex);
Constant refConstant = constantPool[refIndex];
checkConstantTag(refConstant, IClassConstants.CONSTANT_Utf8);
return (String) refConstant.data[0];
} | java |
private void checkConstantPoolIndex(int index) throws InvalidClassFileFormatException {
if (index < 0 || index >= constantPool.length || constantPool[index] == null) {
throw new InvalidClassFileFormatException(expectedClassDescriptor, codeBaseEntry);
}
} | java |
private void checkConstantTag(Constant constant, int expectedTag) throws InvalidClassFileFormatException {
if (constant.tag != expectedTag) {
throw new InvalidClassFileFormatException(expectedClassDescriptor, codeBaseEntry);
}
} | java |
private String getSignatureFromNameAndType(int index) throws InvalidClassFileFormatException {
checkConstantPoolIndex(index);
Constant constant = constantPool[index];
checkConstantTag(constant, IClassConstants.CONSTANT_NameAndType);
return getUtf8String((Integer) constant.data[1]);
} | java |
private void checkUnconditionalDerefDatabase(Location location, ValueNumberFrame vnaFrame, UnconditionalValueDerefSet fact)
throws DataflowAnalysisException {
ConstantPoolGen constantPool = methodGen.getConstantPool();
for (ValueNumber vn : checkUnconditionalDerefDatabase(location, vnaFrame, constantPool,
invDataflow.getFactAtLocation(location), typeDataflow)) {
fact.addDeref(vn, location);
}
} | java |
private void checkInstance(Location location, ValueNumberFrame vnaFrame, UnconditionalValueDerefSet fact)
throws DataflowAnalysisException {
// See if this instruction has a null check.
// If it does, the fall through predecessor will be
// identify itself as the null check.
if (!location.isFirstInstructionInBasicBlock()) {
return;
}
if (invDataflow == null) {
return;
}
BasicBlock fallThroughPredecessor = cfg.getPredecessorWithEdgeType(location.getBasicBlock(), EdgeTypes.FALL_THROUGH_EDGE);
if (fallThroughPredecessor == null || !fallThroughPredecessor.isNullCheck()) {
return;
}
// Get the null-checked value
ValueNumber vn = vnaFrame.getInstance(location.getHandle().getInstruction(), methodGen.getConstantPool());
// Ignore dereferences of this
if (!methodGen.isStatic()) {
ValueNumber v = vnaFrame.getValue(0);
if (v.equals(vn)) {
return;
}
}
if (vn.hasFlag(ValueNumber.CONSTANT_CLASS_OBJECT)) {
return;
}
IsNullValueFrame startFact = null;
startFact = invDataflow.getStartFact(fallThroughPredecessor);
if (!startFact.isValid()) {
return;
}
int slot = startFact.getInstanceSlot(location.getHandle().getInstruction(), methodGen.getConstantPool());
if (!reportDereference(startFact, slot)) {
return;
}
if (DEBUG) {
System.out.println("FOUND GUARANTEED DEREFERENCE");
System.out.println("Load: " + vnaFrame.getLoad(vn));
System.out.println("Pred: " + fallThroughPredecessor);
System.out.println("startFact: " + startFact);
System.out.println("Location: " + location);
System.out.println("Value number frame: " + vnaFrame);
System.out.println("Dereferenced valueNumber: " + vn);
System.out.println("invDataflow: " + startFact);
System.out.println("IGNORE_DEREF_OF_NCP: " + IGNORE_DEREF_OF_NCP);
}
// Mark the value number as being dereferenced at this location
fact.addDeref(vn, location);
} | java |
private UnconditionalValueDerefSet duplicateFact(UnconditionalValueDerefSet fact) {
UnconditionalValueDerefSet copyOfFact = createFact();
copy(fact, copyOfFact);
fact = copyOfFact;
return fact;
} | java |
private @CheckForNull
ValueNumber findValueKnownNonnullOnBranch(UnconditionalValueDerefSet fact, Edge edge) {
IsNullValueFrame invFrame = invDataflow.getResultFact(edge.getSource());
if (!invFrame.isValid()) {
return null;
}
IsNullConditionDecision decision = invFrame.getDecision();
if (decision == null) {
return null;
}
IsNullValue inv = decision.getDecision(edge.getType());
if (inv == null || !inv.isDefinitelyNotNull()) {
return null;
}
ValueNumber value = decision.getValue();
if (DEBUG) {
System.out.println("Value number " + value + " is known nonnull on " + edge);
}
return value;
} | java |
private boolean isExceptionEdge(Edge edge) {
boolean isExceptionEdge = edge.isExceptionEdge();
if (isExceptionEdge) {
if (DEBUG) {
System.out.println("NOT Ignoring " + edge);
}
return true; // false
}
if (edge.getType() != EdgeTypes.FALL_THROUGH_EDGE) {
return false;
}
InstructionHandle h = edge.getSource().getLastInstruction();
return h != null
&& h.getInstruction() instanceof IFNONNULL
&& isNullCheck(h, methodGen.getConstantPool());
} | java |
public static boolean isSubtype(ReferenceType t, ReferenceType possibleSupertype) throws ClassNotFoundException {
return Global.getAnalysisCache().getDatabase(Subtypes2.class).isSubtype(t, possibleSupertype);
} | java |
public static boolean isMonitorWait(String methodName, String methodSig) {
return "wait".equals(methodName) && ("()V".equals(methodSig) || "(J)V".equals(methodSig) || "(JI)V".equals(methodSig));
} | java |
public static boolean isMonitorNotify(String methodName, String methodSig) {
return ("notify".equals(methodName) || "notifyAll".equals(methodName)) && "()V".equals(methodSig);
} | java |
public static boolean isMonitorNotify(Instruction ins, ConstantPoolGen cpg) {
if (!(ins instanceof InvokeInstruction)) {
return false;
}
if (ins.getOpcode() == Const.INVOKESTATIC) {
return false;
}
InvokeInstruction inv = (InvokeInstruction) ins;
String methodName = inv.getMethodName(cpg);
String methodSig = inv.getSignature(cpg);
return isMonitorNotify(methodName, methodSig);
} | java |
public static JavaClassAndMethod visitSuperClassMethods(JavaClassAndMethod method, JavaClassAndMethodChooser chooser)
throws ClassNotFoundException {
return findMethod(method.getJavaClass().getSuperClasses(), method.getMethod().getName(), method.getMethod()
.getSignature(), chooser);
} | java |
public static JavaClassAndMethod visitSuperInterfaceMethods(JavaClassAndMethod method, JavaClassAndMethodChooser chooser)
throws ClassNotFoundException {
return findMethod(method.getJavaClass().getAllInterfaces(), method.getMethod().getName(), method.getMethod()
.getSignature(), chooser);
} | java |
public static Set<JavaClassAndMethod> resolveMethodCallTargets(ReferenceType receiverType,
InvokeInstruction invokeInstruction, ConstantPoolGen cpg) throws ClassNotFoundException {
return resolveMethodCallTargets(receiverType, invokeInstruction, cpg, false);
} | java |
@Deprecated
public static boolean isConcrete(XMethod xmethod) {
int accessFlags = xmethod.getAccessFlags();
return (accessFlags & Const.ACC_ABSTRACT) == 0 && (accessFlags & Const.ACC_NATIVE) == 0;
} | java |
public static Field findField(String className, String fieldName) throws ClassNotFoundException {
JavaClass jclass = Repository.lookupClass(className);
while (jclass != null) {
Field[] fieldList = jclass.getFields();
for (Field field : fieldList) {
if (field.getName().equals(fieldName)) {
return field;
}
}
jclass = jclass.getSuperClass();
}
return null;
} | java |
public static boolean isInnerClassAccess(INVOKESTATIC inv, ConstantPoolGen cpg) {
String methodName = inv.getName(cpg);
return methodName.startsWith("access$");
} | java |
public static InnerClassAccess getInnerClassAccess(INVOKESTATIC inv, ConstantPoolGen cpg) throws ClassNotFoundException {
String className = inv.getClassName(cpg);
String methodName = inv.getName(cpg);
String methodSig = inv.getSignature(cpg);
InnerClassAccess access = AnalysisContext.currentAnalysisContext().getInnerClassAccessMap()
.getInnerClassAccess(className, methodName);
return (access != null && access.getMethodSignature().equals(methodSig)) ? access : null;
} | java |
@SuppressWarnings("unchecked")
@Override
public synchronized Enumeration<Object> keys() {
// sort elements based on detector (prop key) names
Set<?> set = keySet();
return (Enumeration<Object>) sortKeys((Set<String>) set);
} | java |
public void loadXml(String fileName) throws CoreException {
if (fileName == null) {
return;
}
st = new StopTimer();
// clear markers
clearMarkers(null);
final Project findBugsProject = new Project();
final Reporter bugReporter = new Reporter(javaProject, findBugsProject, monitor);
bugReporter.setPriorityThreshold(userPrefs.getUserDetectorThreshold());
reportFromXml(fileName, findBugsProject, bugReporter);
// Merge new results into existing results.
updateBugCollection(findBugsProject, bugReporter, false);
monitor.done();
} | java |
private void clearMarkers(List<WorkItem> files) throws CoreException {
if (files == null) {
project.deleteMarkers(FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE);
return;
}
for (WorkItem item : files) {
if (item != null) {
item.clearMarkers();
}
}
} | java |
private void collectClassFiles(List<WorkItem> resources, Map<IPath, IPath> outLocations, Project fbProject) {
for (WorkItem workItem : resources) {
workItem.addFilesToProject(fbProject, outLocations);
}
} | java |
private void runFindBugs(final FindBugs2 findBugs) {
if (DEBUG) {
FindbugsPlugin.log("Running findbugs in thread " + Thread.currentThread().getName());
}
System.setProperty("findbugs.progress", "true");
try {
// Perform the analysis! (note: This is not thread-safe)
findBugs.execute();
} catch (InterruptedException e) {
if (DEBUG) {
FindbugsPlugin.getDefault().logException(e, "Worker interrupted");
}
Thread.currentThread().interrupt();
} catch (IOException e) {
FindbugsPlugin.getDefault().logException(e, "Error performing SpotBugs analysis");
} finally {
findBugs.dispose();
}
} | java |
private void updateBugCollection(Project findBugsProject, Reporter bugReporter, boolean incremental) {
SortedBugCollection newBugCollection = bugReporter.getBugCollection();
try {
st.newPoint("getBugCollection");
SortedBugCollection oldBugCollection = FindbugsPlugin.getBugCollection(project, monitor);
st.newPoint("mergeBugCollections");
SortedBugCollection resultCollection = mergeBugCollections(oldBugCollection, newBugCollection, incremental);
resultCollection.getProject().setGuiCallback(new EclipseGuiCallback(project));
resultCollection.setTimestamp(System.currentTimeMillis());
// will store bugs in the default FB file + Eclipse project session
// props
st.newPoint("storeBugCollection");
FindbugsPlugin.storeBugCollection(project, resultCollection, monitor);
} catch (IOException e) {
FindbugsPlugin.getDefault().logException(e, "Error performing SpotBugs results update");
} catch (CoreException e) {
FindbugsPlugin.getDefault().logException(e, "Error performing SpotBugs results update");
}
// will store bugs as markers in Eclipse workspace
st.newPoint("createMarkers");
MarkerUtil.createMarkers(javaProject, newBugCollection, resource, monitor);
} | java |
public static IPath getFilterPath(String filePath, IProject project) {
IPath path = new Path(filePath);
if (path.isAbsolute()) {
return path;
}
if (project != null) {
// try first project relative location
IPath newPath = project.getLocation().append(path);
if (newPath.toFile().exists()) {
return newPath;
}
}
// try to resolve relative to workspace (if we use workspace properties
// for project)
IPath wspLocation = ResourcesPlugin.getWorkspace().getRoot().getLocation();
IPath newPath = wspLocation.append(path);
if (newPath.toFile().exists()) {
return newPath;
}
// something which we have no idea what it can be (or missing/wrong file
// path)
return path;
} | java |
public static IPath toFilterPath(String filePath, IProject project) {
IPath path = new Path(filePath);
IPath commonPath;
if (project != null) {
commonPath = project.getLocation();
IPath relativePath = getRelativePath(path, commonPath);
if (!relativePath.equals(path)) {
return relativePath;
}
}
commonPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
return getRelativePath(path, commonPath);
} | java |
public static ProjectFilterSettings fromEncodedString(String s) {
ProjectFilterSettings result = new ProjectFilterSettings();
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String minPriority;
if (bar >= 0) {
minPriority = s.substring(0, bar);
s = s.substring(bar + 1);
} else {
minPriority = s;
s = "";
}
if (priorityNameToValueMap.get(minPriority) == null) {
minPriority = DEFAULT_PRIORITY;
}
result.setMinPriority(minPriority);
}
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String categories;
if (bar >= 0) {
categories = s.substring(0, bar);
s = s.substring(bar + 1);
} else {
categories = s;
s = "";
}
StringTokenizer t = new StringTokenizer(categories, LISTITEM_DELIMITER);
while (t.hasMoreTokens()) {
String category = t.nextToken();
// 'result' probably already contains 'category', since
// it contains all known bug category keys by default.
// But add it to the set anyway in case it is an unknown key.
result.addCategory(category);
}
}
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String displayFalseWarnings;
if (bar >= 0) {
displayFalseWarnings = s.substring(0, bar);
s = s.substring(bar + 1);
} else {
displayFalseWarnings = s;
s = "";
}
result.setDisplayFalseWarnings(Boolean.valueOf(displayFalseWarnings).booleanValue());
}
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String minRankStr;
if (bar >= 0) {
minRankStr = s.substring(0, bar);
// s = s.substring(bar + 1);
} else {
minRankStr = s;
// s = "";
}
result.setMinRank(Integer.parseInt(minRankStr));
}
// if (s.length() > 0) {
// // Can add other fields here...
// assert true;
// }
return result;
} | java |
public static void hiddenFromEncodedString(ProjectFilterSettings result, String s) {
if (s.length() > 0) {
int bar = s.indexOf(FIELD_DELIMITER);
String categories;
if (bar >= 0) {
categories = s.substring(0, bar);
} else {
categories = s;
}
StringTokenizer t = new StringTokenizer(categories, LISTITEM_DELIMITER);
while (t.hasMoreTokens()) {
String category = t.nextToken();
result.removeCategory(category);
}
}
} | java |
public boolean displayWarning(BugInstance bugInstance) {
int priority = bugInstance.getPriority();
if (priority > getMinPriorityAsInt()) {
return false;
}
int rank = bugInstance.getBugRank();
if (rank > getMinRank()) {
return false;
}
BugPattern bugPattern = bugInstance.getBugPattern();
// HACK: it is conceivable that the detector plugin which generated
// this warning is not available any more, in which case we can't
// find out the category. Let the warning be visible in this case.
if (!containsCategory(bugPattern.getCategory())) {
return false;
}
if (!displayFalseWarnings) {
boolean isFalseWarning = !Boolean.valueOf(bugInstance.getProperty(BugProperty.IS_BUG, "true")).booleanValue();
if (isFalseWarning) {
return false;
}
}
return true;
} | java |
public void setMinPriority(String minPriority) {
this.minPriority = minPriority;
Integer value = priorityNameToValueMap.get(minPriority);
if (value == null) {
value = priorityNameToValueMap.get(DEFAULT_PRIORITY);
if (value == null) {
throw new IllegalStateException();
}
}
this.minPriorityAsInt = value.intValue();
} | java |
public String hiddenToEncodedString() {
StringBuilder buf = new StringBuilder();
// Encode hidden bug categories
for (Iterator<String> i = hiddenBugCategorySet.iterator(); i.hasNext();) {
buf.append(i.next());
if (i.hasNext()) {
buf.append(LISTITEM_DELIMITER);
}
}
buf.append(FIELD_DELIMITER);
return buf.toString();
} | java |
public String toEncodedString() {
// Priority threshold
StringBuilder buf = new StringBuilder();
buf.append(getMinPriority());
// Encode enabled bug categories. Note that these aren't really used for
// much.
// They only come in to play when parsed by a version of FindBugs older
// than 1.1.
buf.append(FIELD_DELIMITER);
for (Iterator<String> i = activeBugCategorySet.iterator(); i.hasNext();) {
buf.append(i.next());
if (i.hasNext()) {
buf.append(LISTITEM_DELIMITER);
}
}
// Whether to display false warnings
buf.append(FIELD_DELIMITER);
buf.append(displayFalseWarnings ? "true" : "false");
buf.append(FIELD_DELIMITER);
buf.append(getMinRank());
return buf.toString();
} | java |
public static String getIntPriorityAsString(int prio) {
String minPriority;
switch (prio) {
case Priorities.EXP_PRIORITY:
minPriority = ProjectFilterSettings.EXPERIMENTAL_PRIORITY;
break;
case Priorities.LOW_PRIORITY:
minPriority = ProjectFilterSettings.LOW_PRIORITY;
break;
case Priorities.NORMAL_PRIORITY:
minPriority = ProjectFilterSettings.MEDIUM_PRIORITY;
break;
case Priorities.HIGH_PRIORITY:
minPriority = ProjectFilterSettings.HIGH_PRIORITY;
break;
default:
minPriority = ProjectFilterSettings.DEFAULT_PRIORITY;
break;
}
return minPriority;
} | java |
public GraphType transpose(GraphType orig, GraphToolkit<GraphType, EdgeType, VertexType> toolkit) {
GraphType trans = toolkit.createGraph();
// For each vertex in original graph, create an equivalent
// vertex in the transposed graph,
// ensuring that vertex labels in the transposed graph
// match vertex labels in the original graph
for (Iterator<VertexType> i = orig.vertexIterator(); i.hasNext();) {
VertexType v = i.next();
// Make a duplicate of original vertex
// (Ensuring that transposed graph has same labeling as original)
VertexType dupVertex = toolkit.duplicateVertex(v);
dupVertex.setLabel(v.getLabel());
trans.addVertex(v);
// Keep track of correspondence between equivalent vertices
m_origToTransposeMap.put(v, dupVertex);
m_transposeToOrigMap.put(dupVertex, v);
}
trans.setNumVertexLabels(orig.getNumVertexLabels());
// For each edge in the original graph, create a reversed edge
// in the transposed graph
for (Iterator<EdgeType> i = orig.edgeIterator(); i.hasNext();) {
EdgeType e = i.next();
VertexType transSource = m_origToTransposeMap.get(e.getTarget());
VertexType transTarget = m_origToTransposeMap.get(e.getSource());
EdgeType dupEdge = trans.createEdge(transSource, transTarget);
dupEdge.setLabel(e.getLabel());
// Copy auxiliary information for edge
toolkit.copyEdge(e, dupEdge);
}
trans.setNumEdgeLabels(orig.getNumEdgeLabels());
return trans;
} | java |
public void mapInputToOutput(ValueNumber input, ValueNumber output) {
BitSet inputSet = getInputSet(output);
inputSet.set(input.getNumber());
if (DEBUG) {
System.out.println(input.getNumber() + "->" + output.getNumber());
System.out.println("Input set for " + output.getNumber() + " is now " + inputSet);
}
} | java |
public BitSet getInputSet(ValueNumber output) {
BitSet outputSet = outputToInputMap.get(output);
if (outputSet == null) {
if (DEBUG) {
System.out.println("Create new input set for " + output.getNumber());
}
outputSet = new BitSet();
outputToInputMap.put(output, outputSet);
}
return outputSet;
} | java |
private static boolean mightInheritFromException(ClassDescriptor d) {
while (d != null) {
try {
if ("java.lang.Exception".equals(d.getDottedClassName())) {
return true;
}
XClass classNameAndInfo = Global.getAnalysisCache().getClassAnalysis(XClass.class, d);
d = classNameAndInfo.getSuperclassDescriptor();
} catch (CheckedAnalysisException e) {
return true; // don't know
}
}
return false;
} | java |
public void launch() throws Exception {
// Sanity-check the loaded BCEL classes
if (!CheckBcel.check()) {
System.exit(1);
}
int launchProperty = getLaunchProperty();
if (GraphicsEnvironment.isHeadless() || launchProperty == TEXTUI) {
FindBugs2.main(args);
} else if (launchProperty == SHOW_HELP) {
ShowHelp.main(args);
} else if (launchProperty == SHOW_VERSION) {
Version.main(new String[] { "-release" });
} else {
Class<?> launchClass = Class.forName("edu.umd.cs.findbugs.gui2.Driver");
Method mainMethod = launchClass.getMethod("main", args.getClass());
mainMethod.invoke(null, (Object) args);
}
} | java |
private int getLaunchProperty() {
// See if the first command line argument specifies the UI.
if (args.length > 0) {
String firstArg = args[0];
if (firstArg.startsWith("-")) {
String uiName = firstArg.substring(1);
if (uiNameToCodeMap.containsKey(uiName)) {
// Strip the first argument from the command line arguments.
String[] modifiedArgs = new String[args.length - 1];
System.arraycopy(args, 1, modifiedArgs, 0, args.length - 1);
args = modifiedArgs;
return uiNameToCodeMap.get(uiName);
}
}
}
// Check findbugs.launchUI property.
// "gui2" is the default if not otherwise specified.
String s = System.getProperty("findbugs.launchUI");
if (s == null) {
for (String a : args) {
if ("-output".equals(a) || "-xml".equals(a) || a.endsWith(".class") || a.endsWith(".jar")) {
return TEXTUI;
}
}
s = "gui2";
}
// See if the property value is one of the human-readable
// UI names.
if (uiNameToCodeMap.containsKey(s)) {
return uiNameToCodeMap.get(s);
}
// Fall back: try to parse it as an integer.
try {
return Integer.parseInt(s);
} catch (NumberFormatException nfe) {
return GUI2;
}
} | java |
@Override
public void configure() throws CoreException {
if (DEBUG) {
System.out.println("Adding findbugs to the project build spec.");
}
// register FindBugs builder
addToBuildSpec(FindbugsPlugin.BUILDER_ID);
} | java |
@Override
public void deconfigure() throws CoreException {
if (DEBUG) {
System.out.println("Removing findbugs from the project build spec.");
}
// de-register FindBugs builder
removeFromBuildSpec(FindbugsPlugin.BUILDER_ID);
} | java |
protected void removeFromBuildSpec(String builderID) throws CoreException {
MarkerUtil.removeMarkers(getProject());
IProjectDescription description = getProject().getDescription();
ICommand[] commands = description.getBuildSpec();
for (int i = 0; i < commands.length; ++i) {
if (commands[i].getBuilderName().equals(builderID)) {
ICommand[] newCommands = new ICommand[commands.length - 1];
System.arraycopy(commands, 0, newCommands, 0, i);
System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1);
description.setBuildSpec(newCommands);
getProject().setDescription(description, null);
return;
}
}
} | java |
protected void addToBuildSpec(String builderID) throws CoreException {
IProjectDescription description = getProject().getDescription();
ICommand findBugsCommand = getFindBugsCommand(description);
if (findBugsCommand == null) {
// Add a Java command to the build spec
ICommand newCommand = description.newCommand();
newCommand.setBuilderName(builderID);
setFindBugsCommand(description, newCommand);
}
} | java |
private ICommand getFindBugsCommand(IProjectDescription description) {
ICommand[] commands = description.getBuildSpec();
for (int i = 0; i < commands.length; ++i) {
if (FindbugsPlugin.BUILDER_ID.equals(commands[i].getBuilderName())) {
return commands[i];
}
}
return null;
} | java |
public void addSwitch(String option, String description) {
optionList.add(option);
optionDescriptionMap.put(option, description);
if (option.length() > maxWidth) {
maxWidth = option.length();
}
} | java |
public void addSwitchWithOptionalExtraPart(String option, String optionExtraPartSynopsis, String description) {
optionList.add(option);
optionExtraPartSynopsisMap.put(option, optionExtraPartSynopsis);
optionDescriptionMap.put(option, description);
// Option will display as -foo[:extraPartSynopsis]
int length = option.length() + optionExtraPartSynopsis.length() + 3;
if (length > maxWidth) {
maxWidth = length;
}
} | java |
public void addOption(String option, String argumentDesc, String description) {
optionList.add(option);
optionDescriptionMap.put(option, description);
requiresArgumentSet.add(option);
argumentDescriptionMap.put(option, argumentDesc);
int width = option.length() + 3 + argumentDesc.length();
if (width > maxWidth) {
maxWidth = width;
}
} | java |
public void printUsage(OutputStream os) {
int count = 0;
PrintStream out = UTF8.printStream(os);
for (String option : optionList) {
if (optionGroups.containsKey(count)) {
out.println(" " + optionGroups.get(count));
}
count++;
if (unlistedOptions.contains(option)) {
continue;
}
out.print(" ");
StringBuilder buf = new StringBuilder();
buf.append(option);
if (optionExtraPartSynopsisMap.get(option) != null) {
String optionExtraPartSynopsis = optionExtraPartSynopsisMap.get(option);
buf.append("[:");
buf.append(optionExtraPartSynopsis);
buf.append("]");
}
if (requiresArgumentSet.contains(option)) {
buf.append(" <");
buf.append(argumentDescriptionMap.get(option));
buf.append(">");
}
printField(out, buf.toString(), maxWidth + 1);
out.println(optionDescriptionMap.get(option));
}
out.flush();
} | java |
public void setLockCount(int valueNumber, int lockCount) {
int index = findIndex(valueNumber);
if (index < 0) {
addEntry(index, valueNumber, lockCount);
} else {
array[index + 1] = lockCount;
}
} | java |
public int getNumLockedObjects() {
int result = 0;
for (int i = 0; i + 1 < array.length; i += 2) {
if (array[i] == INVALID) {
break;
}
if (array[i + 1] > 0) {
++result;
}
}
return result;
} | java |
public void copyFrom(LockSet other) {
if (other.array.length != array.length) {
array = new int[other.array.length];
}
System.arraycopy(other.array, 0, array, 0, array.length);
this.defaultLockCount = other.defaultLockCount;
} | java |
public void meetWith(LockSet other) {
for (int i = 0; i + 1 < array.length; i += 2) {
int valueNumber = array[i];
if (valueNumber < 0) {
break;
}
int mine = array[i + 1];
int his = other.getLockCount(valueNumber);
array[i + 1] = mergeValues(mine, his);
}
for (int i = 0; i + 1 < other.array.length; i += 2) {
int valueNumber = other.array[i];
if (valueNumber < 0) {
break;
}
int mine = getLockCount(valueNumber);
int his = other.array[i + 1];
setLockCount(valueNumber, mergeValues(mine, his));
}
setDefaultLockCount(0);
} | java |
public boolean containsReturnValue(ValueNumberFactory factory) {
for (int i = 0; i + 1 < array.length; i += 2) {
int valueNumber = array[i];
if (valueNumber < 0) {
break;
}
int lockCount = array[i + 1];
if (lockCount > 0 && factory.forNumber(valueNumber).hasFlag(ValueNumber.RETURN_VALUE)) {
return true;
}
}
return false;
} | java |
public boolean isEmpty() {
for (int i = 0; i + 1 < array.length; i += 2) {
int valueNumber = array[i];
if (valueNumber < 0) {
return true;
}
int myLockCount = array[i + 1];
if (myLockCount > 0) {
return false;
}
}
return true;
} | java |
public SimplePathEnumerator enumerate() {
Iterator<Edge> entryOut = cfg.outgoingEdgeIterator(cfg.getEntry());
if (!entryOut.hasNext()) {
throw new IllegalStateException();
}
Edge entryEdge = entryOut.next();
LinkedList<Edge> init = new LinkedList<>();
init.add(entryEdge);
work(init);
if (DEBUG && work == maxWork) {
System.out.println("**** Reached max work! ****");
}
return this;
} | java |
@Override
public void visitClassContext(ClassContext classContext) {
int majorVersion = classContext.getJavaClass().getMajor();
if (majorVersion >= Const.MAJOR_1_5 && hasInterestingMethod(classContext.getJavaClass().getConstantPool(), methods)) {
super.visitClassContext(classContext);
}
} | java |
public static Collection<AnnotationValue> resolveTypeQualifiers(AnnotationValue value) {
LinkedList<AnnotationValue> result = new LinkedList<>();
resolveTypeQualifierNicknames(value, result, new LinkedList<ClassDescriptor>());
return result;
} | java |
public void mergeVertices(Set<VertexType> vertexSet, GraphType g, VertexCombinator<VertexType> combinator,
GraphToolkit<GraphType, EdgeType, VertexType> toolkit) {
// Special case: if the vertex set contains a single vertex
// or is empty, there is nothing to do
if (vertexSet.size() <= 1) {
return;
}
// Get all vertices to which we have outgoing edges
// or from which we have incoming edges, since they'll need
// to be fixed
TreeSet<EdgeType> edgeSet = new TreeSet<>();
for (Iterator<EdgeType> i = g.edgeIterator(); i.hasNext();) {
EdgeType e = i.next();
if (vertexSet.contains(e.getSource()) || vertexSet.contains(e.getTarget())) {
edgeSet.add(e);
}
}
// Combine all of the vertices into a single composite vertex
VertexType compositeVertex = combinator.combineVertices(vertexSet);
// For each original edge into or out of the vertex set,
// create an equivalent edge referencing the composite
// vertex
for (EdgeType e : edgeSet) {
VertexType source = vertexSet.contains(e.getSource()) ? compositeVertex : e.getSource();
VertexType target = vertexSet.contains(e.getTarget()) ? compositeVertex : e.getTarget();
// if (source != compositeVertex && target != compositeVertex)
// System.out.println("BIG OOPS!");
// Don't create a self edge for the composite vertex
// unless one of the vertices in the vertex set
// had a self edge
if (source == compositeVertex && target == compositeVertex && e.getSource() != e.getTarget()) {
continue;
}
// Don't create duplicate edges.
if (g.lookupEdge(source, target) != null) {
continue;
}
EdgeType compositeEdge = g.createEdge(source, target);
// FIXME: we really should have an EdgeCombinator here
toolkit.copyEdge(e, compositeEdge);
}
// Remove all of the vertices in the vertex set; this will
// automatically remove the edges into and out of those
// vertices
for (VertexType aVertexSet : vertexSet) {
g.removeVertex(aVertexSet);
}
} | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.