repo
stringlengths 1
191
⌀ | file
stringlengths 23
351
| code
stringlengths 0
5.32M
| file_length
int64 0
5.32M
| avg_line_length
float64 0
2.9k
| max_line_length
int64 0
288k
| extension_type
stringclasses 1
value |
|---|---|---|---|---|---|---|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/CRTFlags.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* CRTFlags.java
*
* Created on 7. Juni 2005, 11:28
*/
package com.ibm.wala.shrike.sourcepos;
import java.util.ArrayList;
import java.util.List;
/**
* This class represents the flags which a entry in the CharacterRangeTable can have. The flags are
* bitwise ORed.
*
* @see CRTData
* @see CRTable
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public final class CRTFlags {
/** Stores the value of the {@code CRT_SOURCE_INFO} flag. */
static final short CRT_SOURCE_INFO = 0x0200;
/** Stores the names of the flags. */
private static final String[] flagNames = {
"CRT_STATEMENT", // 0x0001
"CRT_BLOCK", // 0x0002
"CRT_ASSIGNMENT", // 0x0004
"CRT_FLOW_CONTROLLER", // 0x0008
"CRT_FLOW_TARGET", // 0x0010
"CRT_INVOKE", // 0x0020
"CRT_CREATE", // 0x0040
"CRT_BRANCH_TRUE", // 0x0080
"CRT_BRANCH_FALSE", // 0x0100
"CRT_SOURCE_INFO"
}; // 0x0200
private static final String WARN_INVALID_FLAG = "Error at CRT entry %1$s: invalid flag %2$s";
/** Stores the flags. */
private final short flags;
/**
* Creates a new instance of CRTFlags.
*
* @param flags the flags
* @throws InvalidCRTDataException An InvalidCRTDataException is thrown if the flags are not
* valid.
*/
CRTFlags(short flags) throws InvalidCRTDataException {
this.flags = flags;
if (!isFlagValid())
throw new InvalidCRTDataException(WARN_INVALID_FLAG, Integer.toHexString(flags));
}
/**
* Returns the flag names of this instance.
*
* @return An array of Strings containing the flag names.
*/
public String[] getFlagNames() {
List<String> names = new ArrayList<>();
int index = 0;
short tFlags = flags;
while (tFlags > 0) {
if (tFlags % 2 == 1) {
if (index < flagNames.length) names.add(flagNames[index]);
else {
// assert false
// because exception was thrown in the constructor.
names.add("UNKNOWN (" + Integer.toHexString(2 << index) + ')');
}
}
tFlags >>= 1;
++index;
}
return names.toArray(new String[0]);
}
/**
* Tests whether the flags are valid.
*
* @return whether the flags are valid.
*/
private boolean isFlagValid() {
return 0 < flags && flags < 2 << flagNames.length - 1;
}
}
| 2,718
| 25.656863
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/CRTable.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* CRTable.java
*
* Created on 10. Mai 2005, 09:05
*/
package com.ibm.wala.shrike.sourcepos;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.ArrayDeque;
/**
* This class represents the CharacterRangeTable attribute.
*
* @see CRTData
* @see CRTFlags
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public final class CRTable extends PositionsAttribute {
/** Stores the attribute name of this attribute */
public static final String ATTRIBUTE_NAME = "CharacterRangeTable";
private static final String WARN_CRT_ENTRIES_CONTRADICTORY =
"CRT entries %1$s and %2$s are contradictory.";
private static final String ERR_NO_CRT_ENTRY = "No CRT entry found for program counter %1$s.";
/** Stores the CharacterRangeTable data */
private CRTData[] crt;
/**
* Creates a new instance of CRTable.
*
* @param data the byte array containing the attribute
* @throws IOException An IOException is thrown if the attribute can't be read.
*/
public CRTable(byte[] data) throws IOException {
super(data);
if (Debug.PRINT_CHARACTER_RANGE_TABLE) {
Debug.info(this.toString());
}
}
@Override
protected void readData(DataInputStream in) throws IOException {
assert in != null;
short crt_length = in.readShort();
crt = new CRTData[crt_length];
for (int i = 0; i < crt_length; i++) {
short pc_start_index = in.readShort();
short pc_end_index = in.readShort();
int source_start_position = in.readInt();
int source_end_position = in.readInt();
short flags = in.readShort();
try {
crt[i] =
new CRTData(
pc_start_index, pc_end_index, source_start_position, source_end_position, flags);
} catch (InvalidCRTDataException e) {
ArrayDeque<Object> l = e.getData();
if (l == null) l = new ArrayDeque<>();
l.addFirst(i);
Debug.warn(e.getMessage(), l.toArray());
}
}
}
/**
* Returns the source positions for the given index in the code array of the code attribute.
*
* @param pc the index in the code array of the code attribute
* @return the most precise source position range
*/
public Range getSourceInfo(int pc) {
CRTData sourceInfo = null;
int sourceInfoIndex = 0;
for (int i = 0; i < crt.length; i++) {
if ((crt[i] != null) && crt[i].isInRange(pc)) {
if ((sourceInfo != null) && !sourceInfo.matches(crt[i]))
Debug.warn(WARN_CRT_ENTRIES_CONTRADICTORY, new Object[] {sourceInfoIndex, i});
if ((sourceInfo == null) || crt[i].isMorePrecise(sourceInfo)) {
sourceInfo = crt[i];
sourceInfoIndex = i;
}
}
}
if (sourceInfo == null) {
Debug.error(ERR_NO_CRT_ENTRY, pc);
try {
short short_pc = (short) (pc & 0xFFFF);
sourceInfo = new CRTData(short_pc, short_pc, 0, 0, CRTFlags.CRT_SOURCE_INFO);
} catch (InvalidCRTDataException e) {
assert false;
}
}
return sourceInfo.getSourceInfo();
}
@Override
public String toString() {
if (crt == null) {
return "<undefined>";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < crt.length; i++) {
sb.append(i).append(" -> ");
sb.append(crt[i] == null ? "<null>" : crt[i]);
sb.append('\n');
}
return sb.toString();
}
}
| 3,805
| 28.276923
| 97
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/Debug.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.shrike.sourcepos;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
/** @author Juergen Graf <juergen.graf@gmail.com> */
public final class Debug {
public static final boolean PRINT_CHARACTER_RANGE_TABLE = false;
private Debug() {}
public enum LogLevel {
DEBUG(0),
INFO(1),
WARN(2),
ERROR(3);
private final Integer priority;
LogLevel(int priority) {
this.priority = priority;
}
public boolean isHigherPriority(LogLevel l) {
return priority > l.priority;
}
}
private static PrintStream OUT_STREAM = System.out;
private static final Map<LogLevel, LogStream> logStreams = new EnumMap<>(LogLevel.class);
private static final Set<LogLevel> allowed = EnumSet.noneOf(LogLevel.class);
static {
allowed.addAll(Arrays.asList(LogLevel.values()));
}
public static void setLogFile(String file) throws FileNotFoundException {
if (file != null && file.equals("console")) {
OUT_STREAM = System.out;
} else if (file != null) {
OUT_STREAM = new PrintStream(file);
} else {
OUT_STREAM = null;
}
}
/** Set to log all events with the given or higher priority */
public static void setMinLogLevel(LogLevel level) {
for (LogLevel l : LogLevel.values()) {
if (l == level || l.isHigherPriority(level)) {
allow(l);
} else {
ignore(l);
}
}
}
public static void noLogging() {
for (LogLevel l : LogLevel.values()) {
ignore(l);
}
}
public static void fullLogging() {
for (LogLevel l : LogLevel.values()) {
allow(l);
}
}
public static void error(String str, Object... obj) {
log(LogLevel.ERROR, str + '\n', obj);
}
public static void warn(String str, Object... obj) {
log(LogLevel.WARN, str + '\n', obj);
}
public static void info(String str, Object... obj) {
log(LogLevel.INFO, str + '\n', obj);
}
public static void debug(String str, Object... obj) {
log(LogLevel.DEBUG, str + '\n', obj);
}
public static void error(String str) {
log(LogLevel.ERROR, str + '\n');
}
public static void warn(String str) {
log(LogLevel.WARN, str + '\n');
}
public static void logTime() {
Date date = new Date();
log(LogLevel.INFO, "Current time: " + date + '\n');
}
public static void info(String str) {
log(LogLevel.INFO, str + '\n');
}
public static void appendInfo(String str) {
if (OUT_STREAM != null && allowed.contains(LogLevel.INFO)) {
OUT_STREAM.print(str);
}
}
public static void debug(String str) {
log(LogLevel.DEBUG, str + '\n');
}
public static void error(Throwable t) {
log(LogLevel.ERROR, t);
}
public static void warn(Throwable t) {
log(LogLevel.WARN, t);
}
public static void info(Throwable t) {
log(LogLevel.INFO, t);
}
public static void debug(Throwable t) {
log(LogLevel.DEBUG, t);
}
public static void allow(LogLevel level) {
allowed.add(level);
}
public static void ignore(LogLevel level) {
allowed.remove(level);
}
private static void log(LogLevel level, Throwable exc) {
StringWriter sw = new StringWriter();
exc.printStackTrace(new PrintWriter(sw));
log(level, sw.toString());
}
private static void log(LogLevel level, String str) {
if (OUT_STREAM != null && allowed.contains(level)) {
OUT_STREAM.print("[" + level + "] " + str);
}
}
private static void log(LogLevel level, String str, Object... obj) {
if (OUT_STREAM != null && allowed.contains(level)) {
OUT_STREAM.format("[" + level + "] " + str, obj);
}
}
private static final class LogStream extends PrintStream {
private final LogLevel level;
LogStream(OutputStream out, LogLevel level) {
super(out);
this.level = level;
}
@Override
public void print(String str) {
Debug.log(level, str);
}
@Override
public void println(String str) {
Debug.log(level, str + '\n');
}
}
public static PrintStream getStream(LogLevel level) {
LogStream logStream = logStreams.get(level);
if (OUT_STREAM != null && logStream == null) {
logStream = new LogStream(OUT_STREAM, level);
@SuppressWarnings({"resource", "unused"})
LogStream put = logStreams.put(level, logStream);
}
return logStream;
}
}
| 4,987
| 22.866029
| 91
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/InvalidCRTDataException.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* InvalidCRTDataException.java
*
* Created on 7. Juni 2005, 11:37
*/
package com.ibm.wala.shrike.sourcepos;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.List;
/**
* An exception for invalid data in the CharacterRangeTable.
*
* @see CRTable
* @see CRTData
* @see CRTFlags
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
class InvalidCRTDataException extends Exception {
private static final long serialVersionUID = 1088484553652342438L;
/** Stores additional information */
private List<Object> data;
/** Creates a new instance of {@code InvalidCRTDataException} without detail message. */
InvalidCRTDataException() {}
/**
* Constructs an instance of {@code InvalidCRTDataException} with the specified detail message.
*
* @param msg the detail message.
*/
InvalidCRTDataException(String msg) {
super(msg);
}
/**
* Constructs an instance of {@code InvalidCRTDataException} with the specified detail message and
* additional information.
*
* @param msg the detail message.
* @param data additional information.
*/
InvalidCRTDataException(String msg, Object... data) {
super(msg);
this.data = Arrays.asList(data);
}
/**
* Returns additional information.
*
* @return additional information
*/
ArrayDeque<Object> getData() {
return new ArrayDeque<>(data);
}
}
| 1,801
| 23.684932
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/InvalidPositionException.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* InvalidPositionException.java
*
* Created on 21. Juni 2005, 13:26
*/
package com.ibm.wala.shrike.sourcepos;
/**
* An exception for invalid positions.
*
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
class InvalidPositionException extends Exception {
private static final long serialVersionUID = 7949660405524028349L;
/** possible causes for this exception */
enum Cause {
LINE_NUMBER_ZERO,
COLUMN_NUMBER_ZERO,
LINE_NUMBER_OUT_OF_RANGE,
COLUMN_NUMBER_OUT_OF_RANGE
}
/** the cause for this exception */
private final Cause cause;
/**
* Constructs an instance of {@code InvalidRangeException} with the specified cause.
*
* @param c the cause
*/
InvalidPositionException(Cause c) {
cause = c;
}
/**
* Returns the cause for this exception.
*
* @return the cause for this exception
*/
Cause getThisCause() {
return cause;
}
}
| 1,325
| 21.474576
| 86
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/InvalidRangeException.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* InvalidRangeException.java
*
* Created on 21. Juni 2005, 13:36
*/
package com.ibm.wala.shrike.sourcepos;
/**
* An exception for invalid ranges.
*
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
class InvalidRangeException extends Exception {
private static final long serialVersionUID = 3534258510796557967L;
/** possible causes for this exception */
enum Cause {
END_BEFORE_START,
START_UNDEFINED,
END_UNDEFINED
}
/** the cause for this exception */
private final Cause cause;
/**
* Constructs an instance of {@code InvalidRangeException} with the specified cause.
*
* @param c the cause
*/
InvalidRangeException(Cause c) {
cause = c;
}
/**
* Returns the cause for this exception.
*
* @return the cause for this exception
*/
Cause getThisCause() {
return cause;
}
}
| 1,267
| 20.862069
| 86
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/InvalidSourceInfoException.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* InvalidSourceInfoException.java
*
* Created on 22. Juni 2005, 22:19
*/
package com.ibm.wala.shrike.sourcepos;
/**
* An {@code InvalidSourceInfoException} is thrown if {@code SourceInfo} could not be initialized.
* Reasons are an invalid bytecode and a missing CharacterRangeTable.
*
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public class InvalidSourceInfoException extends Exception {
private static final long serialVersionUID = -5895195422989965097L;
/** Creates a new instance of {@code InvalidSourceInfoException} without detail message. */
public InvalidSourceInfoException() {}
/**
* Constructs an instance of {@code InvalidSourceInfoException} with the specified detail message.
*
* @param msg the detail message.
*/
public InvalidSourceInfoException(String msg) {
super(msg);
}
}
| 1,253
| 28.162791
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/MethodPositions.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* MethodPositions.java
*
* Created on 23. Mai 2005, 14:49
*/
package com.ibm.wala.shrike.sourcepos;
import com.ibm.wala.shrike.sourcepos.InvalidRangeException.Cause;
import java.io.DataInputStream;
import java.io.IOException;
/**
* This class represents the MethodPositions attribute.
*
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public final class MethodPositions extends PositionsAttribute {
/** Stores the attribute name of this attribute */
public static final String ATTRIBUTE_NAME = "joana.sourceinfo.MethodPositions";
private static final String ERR_COLUMN_ZERO =
"Error in MethodPositions attribute: Invalid column number in %1$s.";
private static final String ERR_LINE_ZERO =
"Error in MethodPositions attribute: Invalid line number in %1$s.";
private static final String ERR_RANGE_UNDEFINED =
"Error in MethodPositions attribute: %1$s and %2$s are undefined.";
private static final String ERR_SET_RANGE_UNDEFINED =
"Error in MethodPositions attribute: Invalid positions, so %1$s and %2$s are set undefined.";
private static final String ERR_POSITION_UNDEFINED =
"Error in MethodPositions attribute: %1$s is undefined.";
private static final String ERR_END_BEFORE_START =
"Error in MethodPositions attribute: %2$s (%4$s) is before %1$s (%3$s).";
private static final String ERR_UNKNOWN_REASON =
"Error in MethodPositions attribute: unknown reason %1$s.";
private static final String WARN_INVALID_BLOCK_END =
"Warning in MethodPositions attribute: Invalid method block end position.";
private static final String WARN_PARAMETER_NOT_IN_DECLARATION =
"Warning in MethodPositions attribute: Parameter not in the declaration range.";
/** positions of the method declaration */
private Range declaration;
/** positions of the method parameters */
private Range parameter;
/** positions of the method block */
private Range block_end;
/**
* Creates a new instance of MethodPositions
*
* @param data the byte array containing the attribute
* @throws IOException if the attribute can't be read.
*/
public MethodPositions(byte[] data) throws IOException {
super(data);
if (Debug.PRINT_CHARACTER_RANGE_TABLE) {
Debug.info("MethodPositions found: ");
Debug.info(toString());
}
}
@Override
protected void readData(DataInputStream in) throws IOException {
declaration = readRange(in, "declaration_start", "declaration_end", false);
parameter = readRange(in, "parameter_start", "parameter_end", true);
block_end = readRange(in, "block_end_start", "block_end_end", false);
if (!parameter.isUndefined()
&& (!declaration.getStartPosition().isBefore(parameter.getStartPosition())
|| !parameter.getEndPosition().isBefore(declaration.getEndPosition())))
Debug.warn(WARN_PARAMETER_NOT_IN_DECLARATION);
if (!declaration.getEndPosition().isBefore(block_end.getStartPosition()))
Debug.warn(WARN_INVALID_BLOCK_END);
}
/**
* Reads a range from the input stream.
*
* @param in the input stream
* @param startVarName the variable name for the start position
* @param endVarName the variable name for the end position
* @param undefinedAllowed {@code true} if the range may be undefined.
* @return the range
* @throws IOException if the input stream cannot be read
*/
private static Range readRange(
DataInputStream in, String startVarName, String endVarName, boolean undefinedAllowed)
throws IOException {
boolean valid = true;
Range range = null;
Position start = null;
Position end = null;
try {
start = readPosition(in, startVarName);
} catch (InvalidPositionException e) {
valid = false;
}
try {
end = readPosition(in, endVarName);
} catch (InvalidPositionException e) {
valid = false;
}
if (valid) {
try {
range = new Range(start, end);
} catch (InvalidRangeException e) {
final Cause thisCause = e.getThisCause();
switch (thisCause) {
case END_BEFORE_START:
Debug.warn(ERR_END_BEFORE_START, startVarName, endVarName, start, end);
break;
case START_UNDEFINED:
Debug.warn(ERR_POSITION_UNDEFINED, startVarName);
break;
case END_UNDEFINED:
Debug.warn(ERR_POSITION_UNDEFINED, endVarName);
break;
default:
Debug.warn(ERR_UNKNOWN_REASON, thisCause);
}
}
}
if (range == null) {
range = new Range();
Debug.warn(ERR_SET_RANGE_UNDEFINED, startVarName, endVarName);
}
if (range.isUndefined() && !undefinedAllowed) {
Debug.warn(ERR_RANGE_UNDEFINED, startVarName, endVarName);
}
return range;
}
/**
* Reads a position from the input stream.
*
* @param in the input stream
* @param varName the variable name for this position
* @throws IOException if the input stream cannot be read
* @throws InvalidPositionException if the read position is invalid
*/
private static Position readPosition(DataInputStream in, String varName)
throws IOException, InvalidPositionException {
Position pos = null;
try {
pos = new Position(in.readInt());
} catch (InvalidPositionException e) {
switch (e.getThisCause()) {
case LINE_NUMBER_ZERO:
Debug.warn(ERR_LINE_ZERO, varName);
throw e;
case COLUMN_NUMBER_ZERO:
Debug.warn(ERR_COLUMN_ZERO, varName);
throw e;
default:
assert false;
}
}
return pos;
}
/**
* Returns the source position range of the method declaration.
*
* @return the source position range of the method declaration
*/
public Range getHeaderInfo() {
return declaration;
}
/**
* Returns the source position range of the method parameter declaration.
*
* @return the source position range of the method parameter declaration
*/
public Range getMethodInfo() {
return parameter;
}
/**
* Returns the source position range of the end of the method block.
*
* @return the source position range of the end of the method block
*/
public Range getFooterInfo() {
return block_end;
}
@Override
public String toString() {
return "header: " + declaration + " params: " + parameter + " footer:" + block_end;
}
}
| 6,857
| 31.046729
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/Position.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* Position.java
*
* Created on 20. Juni 2005, 10:32
*/
package com.ibm.wala.shrike.sourcepos;
/**
* Represents a source file position. Source file positions are integers in the format: {@code
* line-number << LINESHIFT + column-number}
*
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public final class Position {
/** Represents the undefined position. */
private static final int NOPOS = 0;
/** bits to shift to get the line number */
private static final int LINE_SHIFT = 10;
/** the bit mask of the column number */
private static final int COLUMN_MASK = 1023;
/** Stores the position as unsigned integer. */
private final int position;
/** Creates the undefined position. */
Position() {
position = NOPOS;
}
/**
* Creates a new instance of Position.
*
* @param position the position as unsigned integer
* @throws InvalidPositionException if the position is not undefined and the line or the column
* number is 0
*/
Position(int position) throws InvalidPositionException {
this.position = position;
if (!isUndefined() && getLine() == 0)
throw new InvalidPositionException(InvalidPositionException.Cause.LINE_NUMBER_ZERO);
if (!isUndefined() && getColumn() == 0)
throw new InvalidPositionException(InvalidPositionException.Cause.COLUMN_NUMBER_ZERO);
}
/**
* Creates a new instance of Position.
*
* @param line the line number
* @param column the column number
* @throws InvalidPositionException if the line or the column number is out of range or if the
* position is not undefined and the line or the column number is 0. The maximum line number
* is 4194303. The maximum column number is 1023.
*/
Position(int line, int column) throws InvalidPositionException {
if (line < 0 || line >= 4194304) // 4194304 = 2^32 >>> LINE_SHIFT
throw new InvalidPositionException(InvalidPositionException.Cause.LINE_NUMBER_OUT_OF_RANGE);
if (column < 0 || column > COLUMN_MASK)
throw new InvalidPositionException(InvalidPositionException.Cause.COLUMN_NUMBER_OUT_OF_RANGE);
if (line == 0 && column != 0)
throw new InvalidPositionException(InvalidPositionException.Cause.LINE_NUMBER_ZERO);
if (line != 0 && column == 0)
throw new InvalidPositionException(InvalidPositionException.Cause.COLUMN_NUMBER_ZERO);
position = (line << LINE_SHIFT) + column;
}
/**
* Returns the line number.
*
* @return the line number
*/
public int getLine() {
return position >>> LINE_SHIFT;
}
/**
* Returns the column number.
*
* @return the column number
*/
public int getColumn() {
return position & COLUMN_MASK;
}
/**
* Tests whether this position is undefined.
*
* @return true if this position is undefined
*/
public boolean isUndefined() {
return position == NOPOS;
}
/**
* Tests whether this position is before the given position. If one of the positions is undefined
* or {@code p} is null then false is returned.
*
* @param p the position to test with
* @return true if this position is greater
*/
boolean isBefore(Position p) {
return (p != null) && !isUndefined() && !p.isUndefined() && toLong() < p.toLong();
}
/**
* Converts this position to a signed long variable.
*
* @return this position as signed long
*/
private long toLong() {
return position & 0xFFFFFFFFL;
}
/**
* Returns this position as an unsigned integer.
*
* @return this position as unsigned integer
*/
int toUnsignedInt() {
return position;
}
@Override
public String toString() {
return getLine() + ":" + getColumn();
}
}
| 4,108
| 28.141844
| 100
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/PositionsAttribute.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* PositionsAttribute.java
*
* Created on 23. Mai 2005, 19:31
*/
package com.ibm.wala.shrike.sourcepos;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
/**
* This is the super class of all position attributes.
*
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
abstract class PositionsAttribute {
/**
* Creates a new instance of PositionsAttribute.
*
* @param data the byte array containing the attribute
* @throws IOException An IOException is thrown if the attribute can't be read or {@code data} is
* null.
*/
PositionsAttribute(byte[] data) throws IOException {
if (data == null) throw new IOException();
DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
readData(in);
}
/**
* Reads the attribute data from the input stream.
*
* @param in the input stream
* @throws IOException if the input stream cannot be read.
*/
protected abstract void readData(DataInputStream in) throws IOException;
}
| 1,454
| 26.45283
| 99
|
java
|
WALA
|
WALA-master/shrike/src/main/java/com/ibm/wala/shrike/sourcepos/Range.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
/*
* Range.java
*
* Created on 21. Juni 2005, 12:20
*/
package com.ibm.wala.shrike.sourcepos;
/**
* This class represents a range in the source file.
*
* @author Siegfried Weber
* @author Juergen Graf <juergen.graf@gmail.com>
*/
public class Range {
/** stores the start position */
private final Position start;
/** stores the end position */
private final Position end;
/** Creates an empty range. */
Range() {
start = new Position();
end = new Position();
}
/**
* Creates a new instance of Range with the given start and end position.
*
* @param start the start position
* @param end the end position
* @throws InvalidRangeException if end is before start or if the range is not undefined and start
* or end is undefined.
*/
Range(Position start, Position end) throws InvalidRangeException {
if (start == null) throw new InvalidRangeException(InvalidRangeException.Cause.START_UNDEFINED);
if (end == null) throw new InvalidRangeException(InvalidRangeException.Cause.END_UNDEFINED);
if (end.isBefore(start))
throw new InvalidRangeException(InvalidRangeException.Cause.END_BEFORE_START);
else if (start.isUndefined() && !end.isUndefined())
throw new InvalidRangeException(InvalidRangeException.Cause.START_UNDEFINED);
else if (!start.isUndefined() && end.isUndefined())
throw new InvalidRangeException(InvalidRangeException.Cause.END_UNDEFINED);
this.start = start;
this.end = end;
}
/**
* Returns whether this range is undefined.
*
* @return whether this range is undefined
*/
boolean isUndefined() {
return start.isUndefined();
}
/**
* Tests whether this range is within the given range. Returns false if a range is undefined or
* {@code r} is null.
*
* @param r the range to test with
* @return {@code true} if this range is within the given range
*/
boolean isWithin(Range r) {
return (r != null) && !start.isBefore(r.start) && !r.end.isBefore(end);
}
/**
* Returns this range as an array of integers.
*
* @return an array with the following entries: start line number, start column number, end line
* number, end column number
*/
int[] toArray() {
return new int[] {start.getLine(), start.getColumn(), end.getLine(), end.getColumn()};
}
/**
* Returns the start position.
*
* @return the start position
*/
public Position getStartPosition() {
return start;
}
/**
* Returns the end position.
*
* @return the end position
*/
public Position getEndPosition() {
return end;
}
@Override
public String toString() {
return (start.isUndefined()
? "<undefined>"
: "(" + getStartPosition() + ") - (" + getEndPosition() + ')');
}
}
| 3,176
| 26.626087
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/AbstractMeetOperator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.AbstractOperator;
import com.ibm.wala.fixpoint.IVariable;
/** Abstract superclass for meet operators */
public abstract class AbstractMeetOperator<T extends IVariable<T>> extends AbstractOperator<T> {
/**
* subclasses can override if needed
*
* @return true iff this meet is a noop when applied to one argument
*/
public boolean isUnaryNoOp() {
return true;
}
}
| 828
| 28.607143
| 96
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BasicFramework.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.util.graph.Graph;
/** a basic implementation of the dataflow framework */
public class BasicFramework<T, V extends IVariable<V>> implements IKilldallFramework<T, V> {
private final Graph<T> flowGraph;
private final ITransferFunctionProvider<T, V> transferFunctionProvider;
public BasicFramework(
Graph<T> flowGraph, ITransferFunctionProvider<T, V> transferFunctionProvider) {
this.flowGraph = flowGraph;
this.transferFunctionProvider = transferFunctionProvider;
}
@Override
public Graph<T> getFlowGraph() {
return flowGraph;
}
@Override
public ITransferFunctionProvider<T, V> getTransferFunctionProvider() {
return transferFunctionProvider;
}
}
| 1,165
| 29.684211
| 92
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorFilter.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.BitVectorIntSet;
import com.ibm.wala.util.intset.IntSet;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** Operator OUT = IN - filterSet */
public class BitVectorFilter extends UnaryOperator<BitVectorVariable> {
private final BitVectorIntSet mask;
public BitVectorFilter(BitVector mask) {
if (mask == null) {
throw new IllegalArgumentException("null mask");
}
this.mask = new BitVectorIntSet(mask);
}
@Override
@NullUnmarked
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException {
if (rhs == null) {
throw new IllegalArgumentException("rhs == null");
}
BitVectorVariable U = new BitVectorVariable();
U.copyState(lhs);
IntSet r = rhs.getValue();
if (r == null) {
return NOT_CHANGED;
}
BitVectorIntSet rr = new BitVectorIntSet();
rr.addAll(r);
rr.removeAll(mask);
System.err.println("adding " + rr + " to " + lhs);
U.addAll(rr.getBitVector());
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
/** @see java.lang.Object#toString() */
@Override
public String toString() {
return "U - " + mask;
}
@Override
public int hashCode() {
return 29 * mask.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof BitVectorFilter) {
BitVectorFilter other = (BitVectorFilter) o;
return mask.equals(other.mask);
} else {
return false;
}
}
}
| 2,161
| 24.435294
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorFramework.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.intset.OrdinalSetMapping;
/** a basic implementation of the dataflow framework */
public class BitVectorFramework<T, L> extends BasicFramework<T, BitVectorVariable> {
private final OrdinalSetMapping<L> latticeValues;
public BitVectorFramework(
Graph<T> flowGraph,
ITransferFunctionProvider<T, BitVectorVariable> transferFunctionProvider,
OrdinalSetMapping<L> latticeValues) {
super(flowGraph, transferFunctionProvider);
this.latticeValues = latticeValues;
}
public OrdinalSetMapping<L> getLatticeValues() {
return latticeValues;
}
}
| 1,101
| 31.411765
| 84
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorIdentity.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import org.jspecify.annotations.Nullable;
/** Operator OUT = IN */
public class BitVectorIdentity extends UnaryOperator<BitVectorVariable> {
private static final BitVectorIdentity SINGLETON = new BitVectorIdentity();
public static BitVectorIdentity instance() {
return SINGLETON;
}
private BitVectorIdentity() {}
@Override
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs cannot be null");
}
if (lhs.sameValue(rhs)) {
return NOT_CHANGED;
} else {
lhs.copyState(rhs);
return CHANGED;
}
}
@Override
public String toString() {
return "Id ";
}
@Override
public int hashCode() {
return 9902;
}
@Override
public boolean equals(Object o) {
return (o instanceof BitVectorIdentity);
}
@Override
public boolean isIdentity() {
return true;
}
}
| 1,477
| 22.460317
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorIntersection.java
|
/*
* Copyright (c) 2002 - 2014 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.util.intset.IntSet;
/** Operator U(n) = U(n) n U(j) */
public final class BitVectorIntersection extends AbstractMeetOperator<BitVectorVariable> {
private static final BitVectorIntersection INSTANCE = new BitVectorIntersection();
public static BitVectorIntersection instance() {
return INSTANCE;
}
private BitVectorIntersection() {}
@Override
public byte evaluate(final BitVectorVariable lhs, final BitVectorVariable[] rhs) {
// as null is the initial value, we treat null as the neutral element to intersection
// which is a set of all possible elements.
IntSet intersect = lhs.getValue();
if (intersect == null) {
for (BitVectorVariable r : rhs) {
intersect = r.getValue();
if (intersect != null) {
break;
}
}
if (intersect == null) {
// still null - so all rhs is null -> no change
return NOT_CHANGED;
}
} else if (intersect.isEmpty()) {
return NOT_CHANGED_AND_FIXED;
}
for (final BitVectorVariable bv : rhs) {
final IntSet vlhs = bv.getValue();
if (vlhs != null) {
intersect = intersect.intersection(vlhs);
}
}
if (lhs.getValue() != null && intersect.sameValue(lhs.getValue())) {
return NOT_CHANGED;
} else {
final BitVectorVariable bvv = new BitVectorVariable();
intersect.foreach(bvv::set);
lhs.copyState(bvv);
return CHANGED;
}
}
@Override
public int hashCode() {
return 9903;
}
@Override
public boolean equals(final Object o) {
return o instanceof BitVectorIntersection;
}
@Override
public String toString() {
return "INTERSECTION";
}
}
| 2,166
| 25.426829
| 90
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorKillAll.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** Just kills everything */
public class BitVectorKillAll extends UnaryOperator<BitVectorVariable> {
private static final BitVectorKillAll SINGLETON = new BitVectorKillAll();
public static BitVectorKillAll instance() {
return SINGLETON;
}
private BitVectorKillAll() {}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.UnaryOperator#evaluate(com.ibm.wala.fixpoint.IVariable, com.ibm.wala.fixpoint.IVariable)
*/
@Override
@NullUnmarked
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs) {
BitVectorVariable empty = new BitVectorVariable();
if (!lhs.sameValue(empty)) {
lhs.copyState(empty);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
return this == o;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#hashCode()
*/
@Override
public int hashCode() {
return 12423958;
}
/* (non-Javadoc)
* @see com.ibm.wala.fixedpoint.impl.AbstractOperator#toString()
*/
@Override
public String toString() {
return "KillAll";
}
}
| 1,821
| 25.794118
| 127
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorKillGen.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.BitVectorIntSet;
import org.jspecify.annotations.Nullable;
/** Operator OUT = (IN - kill) U gen */
public class BitVectorKillGen extends UnaryOperator<BitVectorVariable> {
private final BitVectorIntSet kill;
private final BitVectorIntSet gen;
public BitVectorKillGen(BitVector kill, BitVector gen) {
if (kill == null) {
throw new IllegalArgumentException("null kill");
}
if (gen == null) {
throw new IllegalArgumentException("null gen");
}
this.kill = new BitVectorIntSet(kill);
this.gen = new BitVectorIntSet(gen);
}
@Override
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException {
if (rhs == null) {
throw new IllegalArgumentException("rhs == null");
}
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
BitVectorVariable U = new BitVectorVariable();
BitVectorIntSet bv = new BitVectorIntSet();
if (rhs.getValue() != null) {
bv.addAll(rhs.getValue());
}
bv.removeAll(kill);
bv.addAll(gen);
U.addAll(bv.getBitVector());
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
@Override
public String toString() {
return "GenKill";
}
@Override
public int hashCode() {
return 9901 * kill.hashCode() + 1213 * gen.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof BitVectorKillGen) {
BitVectorKillGen other = (BitVectorKillGen) o;
return kill.sameValue(other.kill) && gen.sameValue(other.gen);
} else {
return false;
}
}
}
| 2,250
| 26.45122
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorMinusVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.BitVectorIntSet;
import org.jspecify.annotations.Nullable;
/** Operator OUT = IN / v */
public class BitVectorMinusVector extends UnaryOperator<BitVectorVariable> {
private final BitVectorIntSet v;
public BitVectorMinusVector(BitVector v) {
this.v = new BitVectorIntSet(v);
}
@Override
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException, IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
if (rhs == null) {
throw new IllegalArgumentException("rhs == null");
}
BitVectorVariable U = new BitVectorVariable();
BitVectorIntSet bv = new BitVectorIntSet();
bv.addAll(rhs.getValue());
bv.removeAll(v);
U.addAll(bv.getBitVector());
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
@Override
public String toString() {
return "U " + v;
}
@Override
public int hashCode() {
return 9901 * v.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof BitVectorMinusVector) {
BitVectorMinusVector other = (BitVectorMinusVector) o;
return v.sameValue(other.v);
} else {
return false;
}
}
}
| 1,885
| 25.56338
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorOr.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.util.intset.BitVector;
import org.jspecify.annotations.Nullable;
/** Operator OUT = IN U v */
public class BitVectorOr extends UnaryOperator<BitVectorVariable> {
private final BitVector v;
public BitVectorOr(BitVector v) {
if (v == null) {
throw new IllegalArgumentException("null v");
}
this.v = v;
}
@Override
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
if (rhs == null) {
throw new IllegalArgumentException("rhs == null");
}
BitVectorVariable U = new BitVectorVariable();
U.copyState(lhs);
U.addAll(rhs);
U.addAll(v);
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
@Override
public String toString() {
return "U " + v;
}
@Override
public int hashCode() {
return 9901 * v.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof BitVectorOr) {
BitVectorOr other = (BitVectorOr) o;
return v.equals(other.v);
} else {
return false;
}
}
}
| 1,738
| 23.492958
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorSolver.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
/** A {@link DataflowSolver} specialized for {@link BitVectorVariable}s */
public class BitVectorSolver<T> extends DataflowSolver<T, BitVectorVariable> {
public BitVectorSolver(IKilldallFramework<T, BitVectorVariable> problem) {
super(problem);
}
@Override
protected BitVectorVariable makeNodeVariable(T n, boolean IN) {
return new BitVectorVariable();
}
@Override
protected BitVectorVariable makeEdgeVariable(T src, T dst) {
return new BitVectorVariable();
}
@Override
protected BitVectorVariable[] makeStmtRHS(int size) {
return new BitVectorVariable[size];
}
}
| 1,068
| 27.891892
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorUnion.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
/** Operator U(n) = U(n) U U(j) */
public class BitVectorUnion extends AbstractMeetOperator<BitVectorVariable> {
private static final BitVectorUnion SINGLETON = new BitVectorUnion();
public static BitVectorUnion instance() {
return SINGLETON;
}
private BitVectorUnion() {}
/** @see java.lang.Object#toString() */
@Override
public String toString() {
return "UNION";
}
@Override
public int hashCode() {
return 9901;
}
@Override
public boolean equals(Object o) {
return (o instanceof BitVectorUnion);
}
/**
* @see com.ibm.wala.fixpoint.AbstractOperator#evaluate(com.ibm.wala.fixpoint.IVariable,
* com.ibm.wala.fixpoint.IVariable[])
*/
@Override
public byte evaluate(BitVectorVariable lhs, BitVectorVariable[] rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("null lhs");
}
if (rhs == null) {
throw new IllegalArgumentException("rhs == null");
}
BitVectorVariable U = new BitVectorVariable();
U.copyState(lhs);
for (BitVectorVariable R : rhs) {
U.addAll(R);
}
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
}
| 1,715
| 24.235294
| 90
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorUnionConstant.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import org.jspecify.annotations.Nullable;
/** Operator OUT = IN U c */
public class BitVectorUnionConstant extends UnaryOperator<BitVectorVariable> {
private final int c;
public BitVectorUnionConstant(int c) {
if (c < 0) {
throw new IllegalArgumentException("Invalid c: " + c);
}
this.c = c;
}
@Override
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
BitVectorVariable U = new BitVectorVariable();
U.copyState(lhs);
U.addAll(rhs);
U.set(c);
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
@Override
public String toString() {
return "U " + c;
}
@Override
public int hashCode() {
return 9901 * c;
}
@Override
public boolean equals(Object o) {
if (o instanceof BitVectorUnionConstant) {
BitVectorUnionConstant other = (BitVectorUnionConstant) o;
return c == other.c;
} else {
return false;
}
}
}
| 1,639
| 23.117647
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BitVectorUnionVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.util.intset.BitVector;
import org.jspecify.annotations.Nullable;
/** Operator lhs = lhs U rhs U v */
public class BitVectorUnionVector extends UnaryOperator<BitVectorVariable> {
private final BitVector v;
public BitVectorUnionVector(BitVector v) {
if (v == null) {
throw new IllegalArgumentException("null v");
}
this.v = v;
}
@Override
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
BitVectorVariable U = new BitVectorVariable();
U.copyState(lhs);
U.addAll(rhs);
U.addAll(v);
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
@Override
public String toString() {
return "U " + v;
}
@Override
public int hashCode() {
return 9901 * v.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof BitVectorUnionVector) {
BitVectorUnionVector other = (BitVectorUnionVector) o;
return v.sameBits(other.v);
} else {
return false;
}
}
}
| 1,707
| 23.753623
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BooleanIdentity.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BooleanVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import org.jspecify.annotations.Nullable;
/** Operator OUT = IN */
public class BooleanIdentity extends UnaryOperator<BooleanVariable> {
private static final BooleanIdentity SINGLETON = new BooleanIdentity();
public static BooleanIdentity instance() {
return SINGLETON;
}
private BooleanIdentity() {}
@Override
public byte evaluate(@Nullable BooleanVariable lhs, BooleanVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
if (lhs.sameValue(rhs)) {
return NOT_CHANGED;
} else {
lhs.copyState(rhs);
return CHANGED;
}
}
@Override
public String toString() {
return "Id ";
}
@Override
public int hashCode() {
return 9802;
}
@Override
public boolean equals(Object o) {
return (o instanceof BooleanIdentity);
}
@Override
public boolean isIdentity() {
return true;
}
}
| 1,450
| 22.031746
| 74
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BooleanSolver.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BooleanVariable;
/** A {@link DataflowSolver} specialized for {@link BooleanVariable}s */
public class BooleanSolver<T> extends DataflowSolver<T, BooleanVariable> {
public BooleanSolver(IKilldallFramework<T, BooleanVariable> problem) {
super(problem);
}
@Override
protected BooleanVariable makeNodeVariable(T n, boolean IN) {
return new BooleanVariable();
}
@Override
protected BooleanVariable makeEdgeVariable(T src, T dst) {
return new BooleanVariable();
}
@Override
protected BooleanVariable[] makeStmtRHS(int size) {
return new BooleanVariable[size];
}
}
| 1,044
| 27.243243
| 74
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/BooleanUnion.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BooleanVariable;
/** Operator U(n) = U(n) U U(j) */
public class BooleanUnion extends AbstractMeetOperator<BooleanVariable> {
private static final BooleanUnion SINGLETON = new BooleanUnion();
public static BooleanUnion instance() {
return SINGLETON;
}
private BooleanUnion() {}
/** @see java.lang.Object#toString() */
@Override
public String toString() {
return "UNION";
}
@Override
public int hashCode() {
return 9901;
}
@Override
public boolean equals(Object o) {
return (o instanceof BooleanUnion);
}
@Override
public byte evaluate(BooleanVariable lhs, BooleanVariable[] rhs) throws NullPointerException {
if (rhs == null) {
throw new IllegalArgumentException("null rhs");
}
BooleanVariable U = new BooleanVariable();
U.copyState(lhs);
for (BooleanVariable R : rhs) {
if (R != null) {
U.or(R);
}
}
if (!lhs.sameValue(U)) {
lhs.copyState(U);
return CHANGED;
} else {
return NOT_CHANGED;
}
}
}
| 1,475
| 22.806452
| 96
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/DataflowSolver.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixedpoint.impl.DefaultFixedPointSolver;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.util.collections.HashMapFactory;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.collections.ObjectArrayMapping;
import com.ibm.wala.util.collections.Pair;
import com.ibm.wala.util.graph.Graph;
import com.ibm.wala.util.intset.IntegerUnionFind;
import java.util.Map;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** Iterative solver for a Killdall dataflow framework */
public abstract class DataflowSolver<T, V extends IVariable<V>> extends DefaultFixedPointSolver<V> {
/** the dataflow problem to solve */
private final IKilldallFramework<T, V> problem;
/** The "IN" variable for each node. */
private final Map<Object, V> node2In = HashMapFactory.make();
/** The "OUT" variable for each node, when node transfer requested. */
private final Map<Object, V> node2Out = HashMapFactory.make();
/** The variable for each edge, when edge transfers requested (indexed by Pair(src, dst)) */
private final Map<Object, V> edge2Var = HashMapFactory.make();
/** */
public DataflowSolver(IKilldallFramework<T, V> problem) {
// tune the implementation for common case of 2 uses for each
// dataflow def
super(2);
this.problem = problem;
}
/**
* @param n a node
* @return a fresh variable to represent the lattice value at the IN or OUT of n
*/
protected abstract V makeNodeVariable(T n, boolean IN);
protected abstract V makeEdgeVariable(T src, T dst);
@Override
protected void initializeVariables() {
Graph<T> G = problem.getFlowGraph();
ITransferFunctionProvider<T, V> functions = problem.getTransferFunctionProvider();
// create a variable for each node.
for (T N : G) {
assert N != null;
V v = makeNodeVariable(N, true);
node2In.put(N, v);
if (functions.hasNodeTransferFunctions()) {
v = makeNodeVariable(N, false);
node2Out.put(N, v);
}
if (functions.hasEdgeTransferFunctions()) {
for (T S : Iterator2Iterable.make(G.getSuccNodes(N))) {
v = makeEdgeVariable(N, S);
edge2Var.put(Pair.make(N, S), v);
}
}
}
}
@Override
protected void initializeWorkList() {
buildEquations(true, false);
}
@NullUnmarked
public V getOut(Object node) {
assert node != null;
V v = node2Out.get(node);
assert v != null : "no out set for " + node;
return v;
}
@NullUnmarked
public V getIn(Object node) {
return node2In.get(node);
}
@Nullable
public V getEdge(Object key) {
return edge2Var.get(key);
}
@Nullable
public V getEdge(Object src, Object dst) {
assert src != null;
assert dst != null;
V v = getEdge(Pair.make(src, dst));
assert v != null;
return v;
}
private class UnionFind {
final IntegerUnionFind uf;
final ObjectArrayMapping<Object> map;
boolean didSomething = false;
private final Object[] allKeys;
private int mapIt(int i, Object[] allVars, Map<Object, V> varMap) {
for (Object key : varMap.keySet()) {
allKeys[i] = key;
allVars[i++] = varMap.get(key);
}
return i;
}
UnionFind() {
allKeys = new Object[node2In.size() + node2Out.size() + edge2Var.size()];
Object allVars[] = new Object[node2In.size() + node2Out.size() + edge2Var.size()];
int i = mapIt(0, allVars, node2In);
i = mapIt(i, allVars, node2Out);
mapIt(i, allVars, edge2Var);
uf = new IntegerUnionFind(allVars.length);
map = new ObjectArrayMapping<>(allVars);
}
/**
* record that variable (n1, in1) is the same as variable (n2,in2), where (x,true) = IN(X) and
* (x,false) = OUT(X)
*/
public void union(@Nullable Object n1, @Nullable Object n2) {
assert n1 != null;
assert n2 != null;
int x = map.getMappedIndex(n1);
int y = map.getMappedIndex(n2);
uf.union(x, y);
didSomething = true;
}
public int size() {
return map.getSize();
}
public int find(int i) {
return uf.find(i);
}
public boolean isIn(int i) {
return i < node2In.size();
}
public boolean isOut(int i) {
return !isIn(i) && i < (node2In.size() + node2Out.size());
}
public Object getKey(int i) {
return allKeys[i];
}
}
protected void buildEquations(boolean toWorkList, boolean eager) {
ITransferFunctionProvider<T, V> functions = problem.getTransferFunctionProvider();
Graph<T> G = problem.getFlowGraph();
AbstractMeetOperator<V> meet = functions.getMeetOperator();
UnionFind uf = new UnionFind();
if (meet.isUnaryNoOp()) {
shortCircuitUnaryMeets(G, functions, uf);
}
shortCircuitIdentities(G, functions, uf);
fixShortCircuits(uf);
// add meet operations
int meetThreshold = (meet.isUnaryNoOp() ? 2 : 1);
for (T node : G) {
int nPred = G.getPredNodeCount(node);
if (nPred >= meetThreshold) {
// todo: optimize further using unary operators when possible?
V[] rhs = makeStmtRHS(nPred);
int i = 0;
for (Object o : Iterator2Iterable.make(G.getPredNodes(node))) {
rhs[i++] = functions.hasEdgeTransferFunctions() ? getEdge(o, node) : getOut(o);
}
newStatement(getIn(node), meet, rhs, toWorkList, eager);
}
}
// add node transfer operations, if requested
if (functions.hasNodeTransferFunctions()) {
for (T node : G) {
UnaryOperator<V> f = functions.getNodeTransferFunction(node);
if (!f.isIdentity()) {
newStatement(getOut(node), f, getIn(node), toWorkList, eager);
}
}
}
// add edge transfer operations, if requested
if (functions.hasEdgeTransferFunctions()) {
for (T node : G) {
for (T succ : Iterator2Iterable.make(G.getSuccNodes(node))) {
UnaryOperator<V> f = functions.getEdgeTransferFunction(node, succ);
if (!f.isIdentity()) {
newStatement(
getEdge(node, succ),
f,
functions.hasNodeTransferFunctions() ? getOut(node) : getIn(node),
toWorkList,
eager);
}
}
}
}
}
/** Swap variables to account for identity transfer functions. */
private void shortCircuitIdentities(
Graph<T> G, ITransferFunctionProvider<T, V> functions, UnionFind uf) {
if (functions.hasNodeTransferFunctions()) {
for (T node : G) {
UnaryOperator<V> f = functions.getNodeTransferFunction(node);
if (f.isIdentity()) {
uf.union(getIn(node), getOut(node));
}
}
}
if (functions.hasEdgeTransferFunctions()) {
for (T node : G) {
for (T succ : Iterator2Iterable.make(G.getSuccNodes(node))) {
UnaryOperator<V> f = functions.getEdgeTransferFunction(node, succ);
if (f.isIdentity()) {
uf.union(
getEdge(node, succ),
functions.hasNodeTransferFunctions() ? getOut(node) : getIn(node));
}
}
}
}
}
/** change the variables to account for short circuit optimizations */
private void fixShortCircuits(UnionFind uf) {
if (uf.didSomething) {
for (int i = 0; i < uf.size(); i++) {
int rep = uf.find(i);
if (i != rep) {
Object x = uf.getKey(i);
Object y = uf.getKey(rep);
if (uf.isIn(i)) {
if (uf.isIn(rep)) {
node2In.put(x, getIn(y));
} else if (uf.isOut(rep)) {
node2In.put(x, getOut(y));
} else {
node2In.put(x, getEdge(y));
}
} else if (uf.isOut(i)) {
if (uf.isIn(rep)) {
node2Out.put(x, getIn(y));
} else if (uf.isOut(rep)) {
node2Out.put(x, getOut(y));
} else {
node2Out.put(x, getEdge(y));
}
} else {
if (uf.isIn(rep)) {
edge2Var.put(x, getIn(y));
} else if (uf.isOut(rep)) {
edge2Var.put(x, getOut(y));
} else {
edge2Var.put(x, getEdge(y));
}
}
}
}
}
}
private void shortCircuitUnaryMeets(
Graph<T> G, ITransferFunctionProvider<T, V> functions, UnionFind uf) {
for (T node : G) {
assert node != null;
int nPred = G.getPredNodeCount(node);
if (nPred == 1) {
// short circuit by setting IN = OUT_p
Object p = G.getPredNodes(node).next();
// if (p == null) {
// p = G.getPredNodes(node).next();
// }
assert p != null;
uf.union(getIn(node), functions.hasEdgeTransferFunctions() ? getEdge(p, node) : getOut(p));
}
}
}
public IKilldallFramework<T, V> getProblem() {
return problem;
}
}
| 9,443
| 28.886076
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/IKilldallFramework.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.util.graph.Graph;
/**
* A dataflow framework in the style of Kildall, POPL 73 This represents a dataflow problem induced
* over a graph.
*
* @param <T> type of nodes in the graph
*/
public interface IKilldallFramework<T, V extends IVariable<V>> {
/** @return the flow graph which induces this dataflow problem */
Graph<T> getFlowGraph();
/** @return an object which provides the flow function for each node in the graph */
ITransferFunctionProvider<T, V> getTransferFunctionProvider();
}
| 977
| 31.6
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/ITransferFunctionProvider.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
/**
* The {@link DataflowSolver} builds system over graphs, with dataflow transfer functions on the
* nodes, the edges or both. In any case, it takes an {@link ITransferFunctionProvider} to tell it
* what functions to use.
*
* @param <T> type of node in the graph
* @param <V> type of abstract states computed
*/
public interface ITransferFunctionProvider<T, V extends IVariable<V>> {
/** @return the transfer function from IN_node -> OUT_node */
UnaryOperator<V> getNodeTransferFunction(T node);
/** @return true if this provider provides node transfer functions */
boolean hasNodeTransferFunctions();
/** @return the transfer function from OUT_src -> EDGE_<src,dst> */
UnaryOperator<V> getEdgeTransferFunction(T src, T dst);
/** @return true if this provider provides edge transfer functions */
boolean hasEdgeTransferFunctions();
/**
* TODO: perhaps this should go with a Lattice object instead. TODO: provide an API to allow
* composition of the meet operator with the flow operator for a given block, as an optimization?
*/
AbstractMeetOperator<V> getMeetOperator();
}
| 1,625
| 35.954545
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/dataflow/graph/UnaryBitVectorUnion.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.dataflow.graph;
import com.ibm.wala.fixpoint.BitVectorVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import org.jspecify.annotations.Nullable;
/** Operator U(n) = U(n) U U(j) */
public class UnaryBitVectorUnion extends UnaryOperator<BitVectorVariable> {
private static final UnaryBitVectorUnion SINGLETON = new UnaryBitVectorUnion();
public static UnaryBitVectorUnion instance() {
return SINGLETON;
}
private UnaryBitVectorUnion() {}
@Override
public byte evaluate(@Nullable BitVectorVariable lhs, BitVectorVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
BitVectorVariable U = new BitVectorVariable();
U.copyState(lhs);
U.addAll(rhs);
if (lhs.sameValue(U)) {
return NOT_CHANGED;
} else {
lhs.copyState(U);
return CHANGED;
}
}
@Override
public String toString() {
return "UNION";
}
@Override
public int hashCode() {
return 9901;
}
@Override
public boolean equals(Object o) {
return (o instanceof UnaryBitVectorUnion);
}
}
| 1,516
| 23.868852
| 81
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/AbstractFixedPointSolver.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.AbstractOperator;
import com.ibm.wala.fixpoint.AbstractStatement;
import com.ibm.wala.fixpoint.FixedPointConstants;
import com.ibm.wala.fixpoint.IFixedPointSolver;
import com.ibm.wala.fixpoint.IFixedPointStatement;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.fixpoint.UnaryOperator;
import com.ibm.wala.fixpoint.UnaryStatement;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
import com.ibm.wala.util.collections.Iterator2Iterable;
import com.ibm.wala.util.debug.VerboseAction;
import com.ibm.wala.util.graph.INodeWithNumber;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* Represents a set of {@link IFixedPointStatement}s to be solved by a {@link IFixedPointSolver}
*
* <p>Implementation Note:
*
* <p>The set of steps and variables is internally represented as a graph. Each step and each
* variable is a node in the graph. If a step produces a variable that is used by another step, the
* graph has a directed edge from the producer to the consumer. Fixed-point iteration proceeds in a
* topological order according to these edges.
*/
@SuppressWarnings("rawtypes")
public abstract class AbstractFixedPointSolver<T extends IVariable<T>>
implements IFixedPointSolver<T>, FixedPointConstants, VerboseAction {
static final boolean DEBUG = false;
public static final boolean verbose =
"true".equals(System.getProperty("com.ibm.wala.fixedpoint.impl.verbose"));
public static final int DEFAULT_VERBOSE_INTERVAL = 100000;
static final boolean MORE_VERBOSE = true;
public static final int DEFAULT_PERIODIC_MAINTENANCE_INTERVAL = 100000;
/**
* A tuning parameter; how may new IStatementDefinitionss must be added before doing a new
* topological sort? TODO: Tune this empirically.
*/
private int minSizeForTopSort = 0;
/**
* A tuning parameter; by what percentage must the number of equations grow before we perform a
* topological sort?
*/
private double topologicalGrowthFactor = 0.1;
/**
* A tuning parameter: how many evaluations are allowed to take place between topological
* re-orderings. The idea is that many evaluations may be a sign of a bad ordering, even when few
* new equations are being added.
*
* <p>A number less than zero mean infinite.
*/
private int maxEvalBetweenTopo = 500000;
private int evaluationsAtLastOrdering = 0;
/** How many equations have been added since the last topological sort? */
int topologicalCounter = 0;
/** The next order number to assign to a new equation */
int nextOrderNumber = 1;
/** During verbose evaluation, holds the number of dataflow equations evaluated */
private int nEvaluated = 0;
/** During verbose evaluation, holds the number of dataflow equations created */
private int nCreated = 0;
/** worklist for the iterative solver */
protected Worklist workList = new Worklist();
/** A boolean which is initially true, but set to false after the first call to solve(); */
private boolean firstSolve = true;
protected abstract T[] makeStmtRHS(int size);
/** Some setup which occurs only before the first solve */
public void initForFirstSolve() {
orderStatements();
initializeVariables();
initializeWorkList();
firstSolve = false;
}
/** @return true iff work list is empty */
public boolean emptyWorkList() {
return workList.isEmpty();
}
/**
* Solve the set of dataflow graph.
*
* <p>PRECONDITION: graph is set up
*
* @return true iff the evaluation of some equation caused a change in the value of some variable.
*/
@Override
@SuppressWarnings("unchecked")
public boolean solve(IProgressMonitor monitor) throws CancelException {
boolean globalChange = false;
if (firstSolve) {
initForFirstSolve();
}
while (!workList.isEmpty()) {
MonitorUtil.throwExceptionIfCanceled(monitor);
orderStatements();
// duplicate insertion detection
AbstractStatement s = workList.takeStatement();
if (DEBUG) {
System.err.println(("Before evaluation " + s));
}
byte code = s.evaluate();
nEvaluated++;
if (verbose) {
if (nEvaluated % getVerboseInterval() == 0) {
performVerboseAction();
}
if (nEvaluated % getPeriodicMaintainInterval() == 0) {
periodicMaintenance();
}
}
if (DEBUG) {
System.err.println(("After evaluation " + s + ' ' + isChanged(code)));
}
if (isChanged(code)) {
globalChange = true;
updateWorkList(s);
}
if (isFixed(code)) {
removeStatement(s);
}
}
return globalChange;
}
@Override
public void performVerboseAction() {
System.err.println("Evaluated " + nEvaluated);
System.err.println("Created " + nCreated);
System.err.println("Worklist " + workList.size());
if (MORE_VERBOSE) {
if (!workList.isEmpty()) {
AbstractStatement<?, ?> s = workList.takeStatement();
System.err.println("Peek " + lineBreak(s.toString(), 132));
if (s instanceof VerboseAction) {
((VerboseAction) s).performVerboseAction();
}
workList.insertStatement(s);
}
}
}
public static String lineBreak(String string, int wrap) {
if (string == null) {
throw new IllegalArgumentException("string is null");
}
if (string.length() > wrap) {
StringBuilder result = new StringBuilder();
int start = 0;
while (start < string.length()) {
int end = Math.min(start + wrap, string.length());
result.append(string, start, end);
result.append("\n ");
start = end;
}
return result.toString();
} else {
return string;
}
}
public void removeStatement(AbstractStatement<T, ?> s) {
getFixedPointSystem().removeStatement(s);
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("Fixed Point System:\n");
for (INodeWithNumber nwn : Iterator2Iterable.make(getStatements())) {
result.append(nwn).append('\n');
}
return result.toString();
}
public Iterator<? extends INodeWithNumber> getStatements() {
return getFixedPointSystem().getStatements();
}
/**
* Add a step to the work list.
*
* @param s the step to add
*/
public void addToWorkList(AbstractStatement s) {
workList.insertStatement(s);
}
/** Add all to the work list. */
public void addAllStatementsToWorkList() {
for (INodeWithNumber nwn : Iterator2Iterable.make(getStatements())) {
AbstractStatement eq = (AbstractStatement) nwn;
addToWorkList(eq);
}
}
/**
* Call this method when the contents of a variable changes. This routine adds all graph using
* this variable to the set of new graph.
*
* @param v the variable that has changed
*/
public void changedVariable(T v) {
for (INodeWithNumber nwn :
Iterator2Iterable.make(getFixedPointSystem().getStatementsThatUse(v))) {
AbstractStatement s = (AbstractStatement) nwn;
addToWorkList(s);
}
}
/**
* Add a step with zero operands on the right-hand side.
*
* <p>TODO: this is a little odd, in that this equation will never fire unless explicitly added to
* a work list. I think in most cases we shouldn't be creating this nullary form.
*
* @param lhs the variable set by this equation
* @param operator the step operator
* @throws IllegalArgumentException if lhs is null
*/
public boolean newStatement(
final T lhs,
final NullaryOperator<T> operator,
final boolean toWorkList,
final boolean eager) {
if (lhs == null) {
throw new IllegalArgumentException("lhs is null");
}
// add to the list of graph
lhs.setOrderNumber(nextOrderNumber++);
final NullaryStatement<T> s = new BasicNullaryStatement<>(lhs, operator);
if (getFixedPointSystem().containsStatement(s)) {
return false;
}
nCreated++;
getFixedPointSystem().addStatement(s);
incorporateNewStatement(toWorkList, eager, s);
topologicalCounter++;
return true;
}
@SuppressWarnings("unchecked")
private void incorporateNewStatement(boolean toWorkList, boolean eager, AbstractStatement s) {
if (eager) {
byte code = s.evaluate();
if (verbose) {
nEvaluated++;
if (nEvaluated % getVerboseInterval() == 0) {
performVerboseAction();
}
if (nEvaluated % getPeriodicMaintainInterval() == 0) {
periodicMaintenance();
}
}
if (isChanged(code)) {
updateWorkList(s);
}
if (isFixed(code)) {
removeStatement(s);
}
} else if (toWorkList) {
addToWorkList(s);
}
}
/**
* Add a step with one operand on the right-hand side.
*
* @param lhs the lattice variable set by this equation
* @param operator the step's operator
* @param rhs first operand on the rhs
* @return true iff the system changes
* @throws IllegalArgumentException if operator is null
*/
public boolean newStatement(
@Nullable T lhs, UnaryOperator<T> operator, T rhs, boolean toWorkList, boolean eager) {
if (operator == null) {
throw new IllegalArgumentException("operator is null");
}
// add to the list of graph
UnaryStatement<T> s = operator.makeEquation(lhs, rhs);
if (getFixedPointSystem().containsStatement(s)) {
return false;
}
if (lhs != null) {
lhs.setOrderNumber(nextOrderNumber++);
}
nCreated++;
getFixedPointSystem().addStatement(s);
incorporateNewStatement(toWorkList, eager, s);
topologicalCounter++;
return true;
}
protected class Statement extends GeneralStatement<T> {
public Statement(T lhs, AbstractOperator<T> operator, T op1, T op2, T op3) {
super(lhs, operator, op1, op2, op3);
}
public Statement(T lhs, AbstractOperator<T> operator, T op1, T op2) {
super(lhs, operator, op1, op2);
}
public Statement(T lhs, AbstractOperator<T> operator, T[] rhs) {
super(lhs, operator, rhs);
}
public Statement(T lhs, AbstractOperator<T> operator) {
super(lhs, operator);
}
@Override
protected T[] makeRHS(int size) {
return makeStmtRHS(size);
}
}
/**
* Add an equation with two operands on the right-hand side.
*
* @param lhs the lattice variable set by this equation
* @param operator the equation operator
* @param op1 first operand on the rhs
* @param op2 second operand on the rhs
*/
public boolean newStatement(
T lhs, AbstractOperator<T> operator, T op1, T op2, boolean toWorkList, boolean eager) {
// add to the list of graph
GeneralStatement<T> s = new Statement(lhs, operator, op1, op2);
if (getFixedPointSystem().containsStatement(s)) {
return false;
}
if (lhs != null) {
lhs.setOrderNumber(nextOrderNumber++);
}
nCreated++;
getFixedPointSystem().addStatement(s);
incorporateNewStatement(toWorkList, eager, s);
topologicalCounter++;
return true;
}
/**
* Add a step with three operands on the right-hand side.
*
* @param lhs the lattice variable set by this equation
* @param operator the equation operator
* @param op1 first operand on the rhs
* @param op2 second operand on the rhs
* @param op3 third operand on the rhs
* @throws IllegalArgumentException if lhs is null
*/
public boolean newStatement(
T lhs, AbstractOperator<T> operator, T op1, T op2, T op3, boolean toWorkList, boolean eager) {
if (lhs == null) {
throw new IllegalArgumentException("lhs is null");
}
// add to the list of graph
lhs.setOrderNumber(nextOrderNumber++);
GeneralStatement<T> s = new Statement(lhs, operator, op1, op2, op3);
if (getFixedPointSystem().containsStatement(s)) {
nextOrderNumber--;
return false;
}
nCreated++;
getFixedPointSystem().addStatement(s);
incorporateNewStatement(toWorkList, eager, s);
topologicalCounter++;
return true;
}
/**
* Add a step to the system with an arbitrary number of operands on the right-hand side.
*
* @param lhs lattice variable set by this equation
* @param operator the operator
* @param rhs the operands on the rhs
*/
public boolean newStatement(
T lhs, AbstractOperator<T> operator, T[] rhs, boolean toWorkList, boolean eager) {
// add to the list of graph
if (lhs != null) lhs.setOrderNumber(nextOrderNumber++);
GeneralStatement<T> s = new Statement(lhs, operator, rhs);
if (getFixedPointSystem().containsStatement(s)) {
nextOrderNumber--;
return false;
}
nCreated++;
getFixedPointSystem().addStatement(s);
incorporateNewStatement(toWorkList, eager, s);
topologicalCounter++;
return true;
}
/** Initialize all lattice vars in the system. */
protected abstract void initializeVariables();
/** Initialize the work list for iteration.j */
protected abstract void initializeWorkList();
/**
* Update the worklist, assuming that a particular equation has been re-evaluated
*
* @param s the equation that has been re-evaluated.
*/
private void updateWorkList(AbstractStatement<T, ?> s) {
// find each equation which uses this lattice cell, and
// add it to the work list
T v = s.getLHS();
if (v == null) {
return;
}
changedVariable(v);
}
/** Number the graph in topological order. */
private void orderStatementsInternal() {
if (verbose) {
if (nEvaluated > 0) {
System.err.println("Reorder " + nEvaluated + ' ' + nCreated);
}
}
reorder();
if (verbose) {
if (nEvaluated > 0) {
System.err.println("Reorder finished " + nEvaluated + ' ' + nCreated);
}
}
topologicalCounter = 0;
evaluationsAtLastOrdering = nEvaluated;
}
/** */
public void orderStatements() {
if (nextOrderNumber > minSizeForTopSort) {
if (((double) topologicalCounter / (double) nextOrderNumber) > topologicalGrowthFactor) {
orderStatementsInternal();
return;
}
}
if ((nEvaluated - evaluationsAtLastOrdering) > maxEvalBetweenTopo) {
orderStatementsInternal();
return;
}
}
/** Re-order the step definitions. */
private void reorder() {
// drain the worklist
List<AbstractStatement> temp = new ArrayList<>();
while (!workList.isEmpty()) {
AbstractStatement eq = workList.takeStatement();
temp.add(eq);
}
workList = new Worklist();
// compute new ordering
getFixedPointSystem().reorder();
// re-populate worklist
for (AbstractStatement s : temp) {
workList.insertStatement(s);
}
}
public static boolean isChanged(byte code) {
return (code & CHANGED_MASK) != 0;
}
public static boolean isSideEffect(byte code) {
return (code & SIDE_EFFECT_MASK) != 0;
}
public static boolean isFixed(byte code) {
return (code & FIXED_MASK) != 0;
}
public int getMinSizeForTopSort() {
return minSizeForTopSort;
}
public void setMinEquationsForTopSort(int i) {
minSizeForTopSort = i;
}
public int getMaxEvalBetweenTopo() {
return maxEvalBetweenTopo;
}
public double getTopologicalGrowthFactor() {
return topologicalGrowthFactor;
}
public void setMaxEvalBetweenTopo(int i) {
maxEvalBetweenTopo = i;
}
public void setTopologicalGrowthFactor(double d) {
topologicalGrowthFactor = d;
}
public int getNumberOfEvaluations() {
return nEvaluated;
}
public void incNumberOfEvaluations() {
nEvaluated++;
}
/** a method that will be called every N evaluations. subclasses should override as desired. */
protected void periodicMaintenance() {}
/** subclasses should override as desired. */
protected int getVerboseInterval() {
return DEFAULT_VERBOSE_INTERVAL;
}
/** subclasses should override as desired. */
protected int getPeriodicMaintainInterval() {
return DEFAULT_PERIODIC_MAINTENANCE_INTERVAL;
}
}
| 16,686
| 28.534513
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/BasicNullaryStatement.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.IVariable;
/** An implementation of NullaryStep that carries its operator explicitly */
public class BasicNullaryStatement<T extends IVariable<T>> extends NullaryStatement<T> {
/** The operator in the equation */
private final NullaryOperator<T> operator;
public BasicNullaryStatement(T lhs, NullaryOperator<T> operator) {
super(lhs);
this.operator = operator;
}
/** @return Returns the operator. */
@Override
public NullaryOperator<T> getOperator() {
return operator;
}
/**
* Return a string representation of this object
*
* @return a string representation of this object
*/
@Override
public String toString() {
String result;
if (lhs == null) {
result = "null lhs";
} else {
result = lhs.toString();
}
result = getOperator() + " " + result;
return result;
}
}
| 1,295
| 25.44898
| 88
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/DefaultFixedPointSolver.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.IFixedPointSystem;
import com.ibm.wala.fixpoint.IVariable;
/** Default implementation of a fixed point solver. */
public abstract class DefaultFixedPointSolver<T extends IVariable<T>>
extends AbstractFixedPointSolver<T> {
private final DefaultFixedPointSystem<T> graph;
/**
* @param expectedOut number of expected out edges in the "usual" case for constraints .. used to
* tune graph representation
*/
public DefaultFixedPointSolver(int expectedOut) {
super();
graph = new DefaultFixedPointSystem<>(expectedOut);
}
public DefaultFixedPointSolver() {
super();
graph = new DefaultFixedPointSystem<>();
}
@Override
public IFixedPointSystem<T> getFixedPointSystem() {
return graph;
}
}
| 1,185
| 27.926829
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/DefaultFixedPointSystem.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.AbstractStatement;
import com.ibm.wala.fixpoint.IFixedPointStatement;
import com.ibm.wala.fixpoint.IFixedPointSystem;
import com.ibm.wala.fixpoint.IVariable;
import com.ibm.wala.fixpoint.UnaryStatement;
import com.ibm.wala.util.collections.EmptyIterator;
import com.ibm.wala.util.collections.FilterIterator;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.graph.GraphIntegrity;
import com.ibm.wala.util.graph.INodeWithNumber;
import com.ibm.wala.util.graph.NumberedGraph;
import com.ibm.wala.util.graph.impl.SparseNumberedGraph;
import com.ibm.wala.util.graph.traverse.Topological;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
/** Default implementation of a dataflow graph */
public class DefaultFixedPointSystem<T extends IVariable<T>> implements IFixedPointSystem<T> {
static final boolean DEBUG = false;
/** A graph which defines the underlying system of statements and variables */
private final NumberedGraph<INodeWithNumber> graph;
/**
* We maintain a hash set of equations in order to check for equality with equals() ... the
* NumberedGraph does not support this. TODO: use a custom NumberedNodeManager to save space
*/
private final Set<IFixedPointStatement<?>> equations = HashSetFactory.make();
/**
* We maintain a hash set of variables in order to check for equality with equals() ... the
* NumberedGraph does not support this. TODO: use a custom NumberedNodeManager to save space
*/
private final Set<IVariable<?>> variables = HashSetFactory.make();
/**
* @param expectedOut number of expected out edges in the "usual" case for constraints .. used to
* tune graph representation
*/
public DefaultFixedPointSystem(int expectedOut) {
super();
graph = new SparseNumberedGraph<>(expectedOut);
}
/** default constructor ... tuned for one use for each def in dataflow graph. */
public DefaultFixedPointSystem() {
this(1);
}
@Override
public boolean equals(Object obj) {
return graph.equals(obj);
}
@Override
public int hashCode() {
return graph.hashCode();
}
@Override
public String toString() {
return graph.toString();
}
@Override
public void removeStatement(IFixedPointStatement<T> s) {
graph.removeNodeAndEdges(s);
}
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public Iterator<AbstractStatement> getStatements() {
return new FilterIterator(graph.iterator(), AbstractStatement.class::isInstance);
}
@Override
@SuppressWarnings("rawtypes")
public void addStatement(IFixedPointStatement statement)
throws IllegalArgumentException, UnimplementedError {
if (statement == null) {
throw new IllegalArgumentException("statement == null");
}
if (statement instanceof UnaryStatement) {
addStatement((UnaryStatement) statement);
} else if (statement instanceof NullaryStatement) {
addStatement((NullaryStatement) statement);
} else if (statement instanceof GeneralStatement) {
addStatement((GeneralStatement) statement);
} else {
Assertions.UNREACHABLE("unexpected: " + statement.getClass());
}
}
public void addStatement(GeneralStatement<?> s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
IVariable<?>[] rhs = s.getRHS();
IVariable<?> lhs = s.getLHS();
equations.add(s);
graph.addNode(s);
if (lhs != null) {
variables.add(lhs);
graph.addNode(lhs);
graph.addEdge(s, lhs);
}
for (IVariable<?> v : rhs) {
IVariable<?> variable = v;
if (variable != null) {
variables.add(variable);
graph.addNode(variable);
graph.addEdge(variable, s);
}
}
if (DEBUG) {
checkGraph();
}
}
public void addStatement(UnaryStatement<?> s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
IVariable<?> lhs = s.getLHS();
IVariable<?> rhs = s.getRightHandSide();
equations.add(s);
graph.addNode(s);
if (lhs != null) {
variables.add(lhs);
graph.addNode(lhs);
graph.addEdge(s, lhs);
}
variables.add(rhs);
graph.addNode(rhs);
graph.addEdge(rhs, s);
if (DEBUG) {
checkGraph();
}
}
public void addStatement(NullaryStatement<?> s) {
if (s == null) {
throw new IllegalArgumentException("s is null");
}
IVariable<?> lhs = s.getLHS();
equations.add(s);
graph.addNode(s);
if (lhs != null) {
variables.add(lhs);
graph.addNode(lhs);
graph.addEdge(s, lhs);
}
if (DEBUG) {
checkGraph();
}
}
public void addVariable(T v) {
variables.add(v);
graph.addNode(v);
if (DEBUG) {
checkGraph();
}
}
public AbstractStatement<?, ?> getStep(int number) {
return (AbstractStatement<?, ?>) graph.getNode(number);
}
@Override
public void reorder() {
if (DEBUG) {
checkGraph();
}
Iterator<INodeWithNumber> order = Topological.makeTopologicalIter(graph).iterator();
int number = 0;
while (order.hasNext()) {
Object elt = order.next();
if (elt instanceof IVariable) {
@SuppressWarnings("unchecked")
T v = (T) elt;
v.setOrderNumber(number++);
}
}
}
/** check that this graph is well-formed */
private void checkGraph() {
try {
GraphIntegrity.check(graph);
} catch (Throwable e) {
e.printStackTrace();
Assertions.UNREACHABLE();
}
}
@Override
public Iterator<? extends INodeWithNumber> getStatementsThatUse(T v) {
return (graph.containsNode(v) ? graph.getSuccNodes(v) : EmptyIterator.instance());
}
@Override
public Iterator<? extends INodeWithNumber> getStatementsThatDef(T v) {
return (graph.containsNode(v) ? graph.getPredNodes(v) : EmptyIterator.instance());
}
@SuppressWarnings("unchecked")
public T getVariable(int n) {
return (T) graph.getNode(n);
}
@Override
public int getNumberOfStatementsThatUse(T v) {
return (graph.containsNode(v) ? graph.getSuccNodeCount(v) : 0);
}
@Override
public int getNumberOfStatementsThatDef(T v) {
return (graph.containsNode(v) ? graph.getPredNodeCount(v) : 0);
}
@Override
public Iterator<? extends INodeWithNumber> getVariables() {
return new FilterIterator<>(graph.iterator(), Objects::nonNull);
}
public int getNumberOfNodes() {
return graph.getNumberOfNodes();
}
public Iterator<? extends INodeWithNumber> getPredNodes(INodeWithNumber n) {
return graph.getPredNodes(n);
}
public int getPredNodeCount(INodeWithNumber n) {
return graph.getPredNodeCount(n);
}
@Override
public boolean containsStatement(IFixedPointStatement<T> s) {
return equations.contains(s);
}
@Override
public boolean containsVariable(T v) {
return variables.contains(v);
}
}
| 7,440
| 26.457565
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/GeneralStatement.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.AbstractOperator;
import com.ibm.wala.fixpoint.AbstractStatement;
import com.ibm.wala.fixpoint.IVariable;
import org.jspecify.annotations.NullUnmarked;
/** Represents a single step in an iterative solver */
public abstract class GeneralStatement<T extends IVariable<T>>
extends AbstractStatement<T, AbstractOperator<T>> {
protected final T lhs;
protected final T[] rhs;
private final int hashCode;
private final AbstractOperator<T> operator;
/**
* Evaluate this equation, setting a new value for the left-hand side.
*
* @return true if the lhs value changed. false otherwise
*/
@Override
public byte evaluate() {
return operator.evaluate(lhs, rhs);
}
/**
* Return the left-hand side of this equation.
*
* @return the lattice cell this equation computes
*/
@Override
public T getLHS() {
return lhs;
}
/**
* Does this equation contain an appearance of a given cell?
*
* <p>Note: this uses reference equality, assuming that the variables are canonical! This is
* fragile. TODO: Address it perhaps, but be careful not to sacrifice efficiency.
*
* @param cell the cell in question
* @return true or false
*/
@Override
public boolean hasVariable(T cell) {
if (lhs == cell) {
return true;
}
for (T rh : rhs) {
if (rh == cell) return true;
}
return false;
}
/**
* Constructor for case of zero operands on the right-hand side.
*
* @param lhs the lattice cell set by this equation
* @param operator the equation operator
*/
@NullUnmarked
public GeneralStatement(T lhs, AbstractOperator<T> operator) {
super();
if (operator == null) {
throw new IllegalArgumentException("null operator");
}
this.operator = operator;
this.lhs = lhs;
this.rhs = null;
this.hashCode = makeHashCode();
}
/**
* Constructor for case of two operands on the right-hand side.
*
* @param lhs the lattice cell set by this equation
* @param operator the equation operator
* @param op1 the first operand on the rhs
* @param op2 the second operand on the rhs
*/
public GeneralStatement(T lhs, AbstractOperator<T> operator, T op1, T op2) {
super();
if (operator == null) {
throw new IllegalArgumentException("null operator");
}
this.operator = operator;
this.lhs = lhs;
rhs = makeRHS(2);
rhs[0] = op1;
rhs[1] = op2;
this.hashCode = makeHashCode();
}
/**
* Constructor for case of three operands on the right-hand side.
*
* @param lhs the lattice cell set by this equation
* @param operator the equation operator
* @param op1 the first operand on the rhs
* @param op2 the second operand on the rhs
* @param op3 the third operand on the rhs
*/
public GeneralStatement(T lhs, AbstractOperator<T> operator, T op1, T op2, T op3) {
super();
if (operator == null) {
throw new IllegalArgumentException("null operator");
}
this.operator = operator;
rhs = makeRHS(3);
this.lhs = lhs;
rhs[0] = op1;
rhs[1] = op2;
rhs[2] = op3;
this.hashCode = makeHashCode();
}
/**
* Constructor for case of more than three operands on the right-hand side.
*
* @param lhs the lattice cell set by this equation
* @param operator the equation operator
* @param rhs the operands of the right-hand side in order
* @throws IllegalArgumentException if rhs is null
*/
public GeneralStatement(T lhs, AbstractOperator<T> operator, T[] rhs) {
super();
if (operator == null) {
throw new IllegalArgumentException("null operator");
}
if (rhs == null) {
throw new IllegalArgumentException("rhs is null");
}
this.operator = operator;
this.lhs = lhs;
this.rhs = rhs.clone();
this.hashCode = makeHashCode();
}
/** TODO: use a better hash code? */
private static final int[] primes = {331, 337, 347, 1277};
private int makeHashCode() {
int result = operator.hashCode();
if (lhs != null) result += lhs.hashCode() * primes[0];
for (int i = 0; i < Math.min(rhs.length, 2); i++) {
if (rhs[i] != null) {
result += primes[i + 1] * rhs[i].hashCode();
}
}
return result;
}
protected abstract T[] makeRHS(int size);
@Override
public int hashCode() {
return hashCode;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (getClass().equals(o.getClass())) {
GeneralStatement<?> other = (GeneralStatement<?>) o;
if (hashCode == other.hashCode) {
if (lhs == null || other.lhs == null) {
if (other.lhs != lhs) {
return false;
}
} else if (!lhs.equals(other.lhs)) {
return false;
}
if (operator.equals(other.operator) && rhs.length == other.rhs.length) {
for (int i = 0; i < rhs.length; i++) {
if (rhs[i] == null || other.rhs[i] == null) {
if (other.rhs[i] != rhs[i]) {
return false;
}
} else if (!rhs[i].equals(other.rhs[i])) {
return false;
}
}
return true;
}
}
}
return false;
}
@Override
public AbstractOperator<T> getOperator() {
return operator;
}
@Override
public T[] getRHS() {
return rhs;
}
}
| 5,826
| 25.852535
| 94
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/NullaryOperator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.AbstractOperator;
import com.ibm.wala.fixpoint.IVariable;
/** An operator of the form lhs = op */
public abstract class NullaryOperator<T extends IVariable<T>> extends AbstractOperator<T> {
@Override
public byte evaluate(T lhs, T[] rhs) throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
/**
* Evaluate this equation, setting a new value for the left-hand side.
*
* @return true if the lhs value changes. false otherwise.
*/
public abstract byte evaluate(T lhs);
}
| 970
| 30.322581
| 91
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/NullaryStatement.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.AbstractStatement;
import com.ibm.wala.fixpoint.IVariable;
/** Represents a single step, restricted to a nullary operator. */
public abstract class NullaryStatement<T extends IVariable<T>>
extends AbstractStatement<T, NullaryOperator<T>> {
/** The operands */
protected final T lhs;
/**
* Evaluate this equation, setting a new value for the left-hand side.
*
* @return true if the lhs value changed. false otherwise
*/
@Override
public byte evaluate() {
NullaryOperator<T> op = getOperator();
return op.evaluate(lhs);
}
/**
* Return the left-hand side of this equation.
*
* @return the lattice cell this equation computes
*/
@Override
public T getLHS() {
return lhs;
}
/**
* Does this equation contain an appearance of a given cell?
*
* @param cell the cell in question
* @return true or false
*/
@Override
public boolean hasVariable(T cell) {
return lhs == cell;
}
/**
* Constructor for case of one operand on the right-hand side.
*
* @param lhs the lattice cell set by this equation
*/
protected NullaryStatement(T lhs) {
super();
this.lhs = lhs;
}
@Override
public boolean equals(Object o) {
if (o instanceof NullaryStatement) {
NullaryStatement<?> other = (NullaryStatement<?>) o;
if (!getOperator().equals(other.getOperator())) {
return false;
}
if (lhs == null) {
if (other.lhs != null) {
return false;
}
} else {
if (other.lhs == null) {
return false;
}
if (!lhs.equals(other.lhs)) {
return false;
}
}
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
int result = getOperator().hashCode() * 1381;
if (lhs != null) {
result += 1399 * lhs.hashCode();
}
return result;
}
@Override
public T[] getRHS() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
| 2,472
| 22.552381
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixedpoint/impl/Worklist.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixedpoint.impl;
import com.ibm.wala.fixpoint.AbstractStatement;
import com.ibm.wala.util.collections.HashSetFactory;
import com.ibm.wala.util.collections.Heap;
import java.util.HashSet;
import java.util.NoSuchElementException;
/** Worklist for fixed-point solver implementation */
@SuppressWarnings("rawtypes")
public class Worklist extends Heap<AbstractStatement> {
private final HashSet<AbstractStatement> contents = HashSetFactory.make();
public Worklist() {
super(100);
}
@Override
protected final boolean compareElements(AbstractStatement eq1, AbstractStatement eq2) {
return (eq1.getOrderNumber() < eq2.getOrderNumber());
}
public AbstractStatement takeStatement() throws NoSuchElementException {
AbstractStatement result = super.take();
contents.remove(result);
return result;
}
public void insertStatement(AbstractStatement eq) {
if (contents.add(eq)) {
super.insert(eq);
}
}
}
| 1,344
| 28.23913
| 89
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/AbstractOperator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
/**
* operator for a step in an iterative solver
*
* <p>This is an abstract class and not an interface in order to force subclasses to re-implement
* equals(), hashCode(), and toString()
*/
public abstract class AbstractOperator<T extends IVariable<T>> implements FixedPointConstants {
/**
* Evaluate this equation, setting a new value for the left-hand side.
*
* @return a code that indicates: 1) has the lhs value changed? 2) has this equation reached a
* fixed-point, in that we never have to evaluate the equation again, even if rhs operands
* change?
*/
public abstract byte evaluate(T lhs, T[] rhs);
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object o);
@Override
public abstract String toString();
}
| 1,205
| 29.923077
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/AbstractStatement.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.graph.impl.NodeWithNumber;
/** Represents a single step in an iterative solver */
public abstract class AbstractStatement<T extends IVariable<T>, O extends AbstractOperator<T>>
extends NodeWithNumber implements IFixedPointStatement<T> {
public abstract O getOperator();
/** Subclasses must implement this, to prevent non-determinism. */
@Override
public abstract int hashCode();
@Override
public abstract boolean equals(Object o);
@Override
public String toString() {
StringBuilder result = new StringBuilder();
if (getLHS() == null) {
result.append("null ");
} else {
result.append(getLHS().toString());
result.append(' ');
}
result.append(getOperator().toString());
result.append(' ');
for (int i = 0; i < getRHS().length; i++) {
if (getRHS()[i] == null) {
result.append("null");
} else {
result.append(getRHS()[i].toString());
}
result.append(' ');
}
return result.toString();
}
public final int getOrderNumber() {
T lhs = getLHS();
return (lhs == null) ? 0 : lhs.getOrderNumber();
}
}
| 1,555
| 27.290909
| 94
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/AbstractVariable.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.graph.impl.NodeWithNumber;
/** Represents a single variable in a fixed-point system. */
public abstract class AbstractVariable<T extends AbstractVariable<T>> extends NodeWithNumber
implements IVariable<T> {
private static int nextHashCode = 0;
private int orderNumber;
private final int hashCode;
protected AbstractVariable() {
this.hashCode = nextHash();
}
@Override
public boolean equals(Object obj) {
// we assume the solver manages these canonically
return this == obj;
}
/**
* I know this is theoretically bad. However,
*
* <ul>
* <li>we need this to be extremely fast .. it's in the inner loop of lots of stuff.
* <li>these objects will probably only be hashed with each other {@code AbstractVariable}s, in
* which case incrementing hash codes is OK.
* <li>we want determinism, so we don't want to rely on System.identityHashCode
* </ul>
*/
public static synchronized int nextHash() {
return nextHashCode++;
}
@Override
public final int hashCode() {
return hashCode;
}
@Override
public int getOrderNumber() {
return orderNumber;
}
@Override
public void setOrderNumber(int orderNumber) {
this.orderNumber = orderNumber;
}
}
| 1,682
| 25.296875
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/BasicUnaryStatement.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import org.jspecify.annotations.Nullable;
/** An implementation of UnaryStatement that carries its operator explicitly */
public class BasicUnaryStatement<T extends IVariable<T>> extends UnaryStatement<T> {
private final UnaryOperator<T> operator;
BasicUnaryStatement(@Nullable T lhs, UnaryOperator<T> operator, T rhs) {
super(lhs, rhs);
this.operator = operator;
}
@Override
public UnaryOperator<T> getOperator() {
return operator;
}
}
| 872
| 28.1
| 84
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/BitVectorVariable.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.intset.BitVector;
import com.ibm.wala.util.intset.BitVectorIntSet;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.MutableSharedBitVectorIntSet;
import org.jspecify.annotations.Nullable;
/** A bit vector variable for dataflow analysis. */
public class BitVectorVariable extends AbstractVariable<BitVectorVariable> {
@Nullable private MutableSharedBitVectorIntSet V;
public BitVectorVariable() {}
/** @see com.ibm.wala.fixpoint.IVariable#copyState(com.ibm.wala.fixpoint.IVariable) */
@Override
public void copyState(@Nullable BitVectorVariable other) {
if (other == null) {
throw new IllegalArgumentException("null other");
}
if (V == null) {
if (other.V != null) {
V = new MutableSharedBitVectorIntSet(other.V);
}
return;
}
if (other.V != null) {
V.copySet(other.V);
} else {
V = null;
}
}
/** Add all the bits in B to this bit vector */
public void addAll(BitVector B) {
if (B == null) {
throw new IllegalArgumentException("null B");
}
if (V == null) {
V = new MutableSharedBitVectorIntSet(new BitVectorIntSet(B));
return;
} else {
V.addAll(new BitVectorIntSet(B));
}
}
/** Add all the bits from other to this bit vector */
public void addAll(BitVectorVariable other) {
if (other == null) {
throw new IllegalArgumentException("null other");
}
if (V == null) {
copyState(other);
} else {
if (other.V != null) {
V.addAll(other.V);
}
}
}
/** Does this variable have the same value as another? */
public boolean sameValue(BitVectorVariable other) {
if (other == null) {
throw new IllegalArgumentException("null other");
}
if (V == null) {
return (other.V == null);
} else {
if (other.V == null) {
return false;
} else {
return V.sameValue(other.V);
}
}
}
@Override
public String toString() {
if (V == null) {
return "[Empty]";
}
return V.toString();
}
/**
* Set a particular bit
*
* @param b the bit to set
*/
public void set(int b) {
if (b < 0) {
throw new IllegalArgumentException("illegal b: " + b);
}
if (V == null) {
V = new MutableSharedBitVectorIntSet();
}
V.add(b);
}
/**
* Is a particular bit set?
*
* @param b the bit to check
*/
public boolean get(int b) {
if (V == null) {
return false;
} else {
return V.contains(b);
}
}
/** @return the value of this variable as a bit vector ... null if the bit vector is empty. */
@Nullable
public IntSet getValue() {
return V;
}
public void clear(int i) {
if (V != null) {
V.remove(i);
}
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
public int populationCount() {
if (V == null) {
return 0;
} else {
return V.size();
}
}
}
| 3,412
| 21.90604
| 96
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/BooleanVariable.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
/** A boolean variable for dataflow analysis. */
public class BooleanVariable extends AbstractVariable<BooleanVariable> {
private boolean B;
public BooleanVariable() {}
/** @param b initial value for this variable */
public BooleanVariable(boolean b) {
this.B = b;
}
@Override
public void copyState(BooleanVariable other) {
if (other == null) {
throw new IllegalArgumentException("other null");
}
B = other.B;
}
public boolean sameValue(BooleanVariable other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
return B == other.B;
}
@Override
public String toString() {
return (B ? "[TRUE]" : "[FALSE]");
}
/** @return the value of this variable */
public boolean getValue() {
return B;
}
/** @throws IllegalArgumentException if other is null */
public void or(BooleanVariable other) {
if (other == null) {
throw new IllegalArgumentException("other is null");
}
B = B || other.B;
}
public void set(boolean b) {
B = b;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
| 1,557
| 22.253731
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/FixedPointConstants.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
/** Constants used in the fixed-point solver framework */
public interface FixedPointConstants {
/**
* A return value which indicates that a lhs has changed, and the statement might need to be
* evaluated again.
*/
byte CHANGED = 1;
/**
* A return value which indicates that lhs has not changed, and the statement might need to be
* evaluated again.
*/
byte NOT_CHANGED = 0;
/**
* A return value which indicates that lhs has changed, and the statement need not be evaluated
* again.
*/
byte CHANGED_AND_FIXED = 3;
/**
* A return value which indicates that lhs has not changed, and the statement need not be
* evaluated again.
*/
byte NOT_CHANGED_AND_FIXED = 2;
/** The bit-mask which defines the "CHANGED" flag */
int CHANGED_MASK = 0x1;
/** The bit-mask which defines the "FIXED" flag */
int FIXED_MASK = 0x2;
/** The bit-mask which defines the "SIDE EFFECT" flag */
int SIDE_EFFECT_MASK = 0x4;
}
| 1,371
| 30.181818
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/IFixedPointSolver.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.CancelException;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
/** Solves a set of constraints */
public interface IFixedPointSolver<T extends IVariable<T>> {
/** @return the set of statements solved by this {@code IFixedPointSolver} */
IFixedPointSystem<T> getFixedPointSystem();
/**
* Solve the problem.
*
* <p>PRECONDITION: graph is set up
*
* @return true iff the evaluation of some constraint caused a change in the value of some
* variable.
*/
boolean solve(IProgressMonitor monitor) throws CancelException;
}
| 993
| 30.0625
| 92
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/IFixedPointStatement.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.graph.INodeWithNumber;
import org.jspecify.annotations.Nullable;
/**
* The general form of a statement definition in an iterative solver is: x >= term, where term
* can be any complex expression whose free variables are among the IVariables of the constraint
* system this {@link IFixedPointStatement}is part of (x represents the left-hand side of the
* constraint). The interpretation of term (the right-hand side of the constraint) must be monotone.
*
* <p>The list of free variables in term is obtained by invoking {@link #getRHS()}, and the left
* hand side variable is obtained by calling {@link #getLHS()}. Intuitively, a statement definition
* corresponds to an "equation" in dataflow parlance, or a "constraint" in constraint solvers.
*/
public interface IFixedPointStatement<T extends IVariable<T>> extends INodeWithNumber {
/** @return the left-hand side of this statement. */
@Nullable
T getLHS();
/** returns the list of free variables appearing in the right-hand side of the statement */
T[] getRHS();
/**
* Evaluate this statement, setting a new value for the left-hand side. The return value is one of
* the following:
*
* <ul>
* <li>{@link FixedPointConstants#CHANGED},
* <li>{@link FixedPointConstants#CHANGED_AND_FIXED},
* <li>{@link FixedPointConstants#NOT_CHANGED}, or
* <li>{@link FixedPointConstants#NOT_CHANGED_AND_FIXED}.
* </ul>
*/
byte evaluate();
/**
* Does this statement definition contain an appearance of a given variable?
*
* @param v the variable in question
*/
boolean hasVariable(T v);
}
| 2,039
| 36.777778
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/IFixedPointSystem.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.graph.INodeWithNumber;
import java.util.Iterator;
/** Represents a set of {@link IFixedPointStatement}s to be solved by a {@link IFixedPointSolver} */
public interface IFixedPointSystem<T extends IVariable<T>> {
/** removes a given statement */
void removeStatement(IFixedPointStatement<T> statement);
/** Add a statement to the system */
void addStatement(IFixedPointStatement<T> statement);
/**
* Return an Iterator of the {@link IFixedPointStatement}s in this system
*
* @return {@link Iterator}<Constraint>
*/
Iterator<? extends INodeWithNumber> getStatements();
/**
* Return an Iterator of the variables in this graph
*
* @return {@link Iterator}<{@link IVariable}>
*/
Iterator<? extends INodeWithNumber> getVariables();
/** @return true iff this system already contains an equation that is equal() to s */
boolean containsStatement(IFixedPointStatement<T> s);
/** @return true iff this system already contains a variable that is equal() to v. */
boolean containsVariable(T v);
/** @return {@link Iterator}<statement>, the statements that use the variable */
Iterator<? extends INodeWithNumber> getStatementsThatUse(T v);
/** @return {@link Iterator}<statement>, the statements that def the variable */
Iterator<? extends INodeWithNumber> getStatementsThatDef(T v);
int getNumberOfStatementsThatUse(T v);
int getNumberOfStatementsThatDef(T v);
/** reorder the statements in this system */
void reorder();
}
| 1,944
| 32.534483
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/IVariable.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.graph.INodeWithNumber;
/** Represents a single variable in a fixed-point iterative system. */
public interface IVariable<T extends IVariable<T>> extends INodeWithNumber {
/**
* Variables must allow the solver implementation to get/set an order number, which the solver
* uses to control evaluation order.
*
* <p>It might be cleaner to hold this on the side, but we cannot tolerate any extra space. TODO:
* consider moving this functionality to a subinterface?
*
* @return a number used to order equation evaluation
*/
int getOrderNumber();
/**
* Variables must allow the solver implementation to get/set an order number, which the solver
* uses to control evaluation order.
*
* <p>It might be cleaner to hold this on the side, but we cannot tolerate any extra space. TODO:
* consider moving this functionality to a subinterface?
*/
void setOrderNumber(int i);
/** Set this variable to have the same state as another one */
void copyState(T v);
}
| 1,436
| 34.04878
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/IntSetVariable.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.intset.IntSet;
import com.ibm.wala.util.intset.IntSetUtil;
import com.ibm.wala.util.intset.MutableIntSet;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* A variable for dataflow analysis, representing a set of integers.
*
* <p>TODO: optimize the representation more; e.g. BitVectors with non-zero lower bound.
*/
@SuppressWarnings("rawtypes")
public abstract class IntSetVariable<T extends IntSetVariable<T>> extends AbstractVariable<T> {
@Nullable MutableIntSet V;
@Override
public void copyState(T other) {
if (V == null) {
if (other.V != null) {
V = IntSetUtil.getDefaultIntSetFactory().makeCopy(other.V);
}
return;
} else {
if (other.V != null) {
V.copySet(other.V);
}
}
}
/**
* Add all integers from the set B
*
* @return true iff the value of this changes
*/
public boolean addAll(IntSet B) {
if (V == null) {
V = IntSetUtil.getDefaultIntSetFactory().makeCopy(B);
return (B.size() > 0);
} else {
boolean result = V.addAll(B);
return result;
}
}
/**
* Add all integers from the other int set variable.
*
* @return true iff the contents of this variable changes.
*/
public boolean addAll(T other) {
if (V == null) {
copyState(other);
return (V != null);
} else {
if (other.V != null) {
boolean result = addAll(other.V);
return result;
} else {
return false;
}
}
}
public boolean sameValue(IntSetVariable other) {
if (V == null) {
return (other.V == null);
} else {
if (other.V == null) {
return false;
} else {
return V.sameValue(other.V);
}
}
}
@Override
public String toString() {
if (V == null) {
return "[Empty]";
}
return V.toString();
}
/**
* Set a particular bit
*
* @param b the bit to set
*/
public boolean add(int b) {
if (V == null) {
V = IntSetUtil.getDefaultIntSetFactory().make();
}
return V.add(b);
}
/**
* Is a particular bit set?
*
* @param b the bit to check
*/
public boolean contains(int b) {
if (V == null) {
return false;
} else {
return V.contains(b);
}
}
/** @return the value of this variable as a MutableSparseIntSet ... null if the set is empty. */
@NullUnmarked
public MutableIntSet getValue() {
return V;
}
public void remove(int i) {
if (V != null) {
V.remove(i);
}
}
public int size() {
return (V == null) ? 0 : V.size();
}
public boolean containsAny(IntSet instances) {
if (V == null) {
return false;
}
return V.containsAny(instances);
}
public boolean addAllInIntersection(T other, IntSet filter) {
if (V == null) {
copyState(other);
if (V != null) {
V.intersectWith(filter);
if (V.isEmpty()) {
V = null;
}
}
return (V != null);
} else {
if (other.V != null) {
boolean result = addAllInIntersection(other.V, filter);
return result;
} else {
return false;
}
}
}
public boolean addAllInIntersection(IntSet other, IntSet filter) {
if (V == null) {
V = IntSetUtil.getDefaultIntSetFactory().makeCopy(other);
V.intersectWith(filter);
if (V.isEmpty()) {
V = null;
}
return (V != null);
} else {
boolean result = V.addAllInIntersection(other, filter);
return result;
}
}
public void removeAll() {
V = null;
}
}
| 4,050
| 21.136612
| 98
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/TrueOperator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import org.jspecify.annotations.Nullable;
/** Operator U(n) = true */
public final class TrueOperator extends UnaryOperator<BooleanVariable> {
private static final TrueOperator SINGLETON = new TrueOperator();
public static TrueOperator instance() {
return TrueOperator.SINGLETON;
}
private TrueOperator() {}
@Override
public byte evaluate(@Nullable BooleanVariable lhs, BooleanVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
if (lhs.getValue()) {
return NOT_CHANGED;
} else {
lhs.set(true);
return CHANGED;
}
}
@Override
public String toString() {
return "TRUE";
}
@Override
public int hashCode() {
return 9889;
}
@Override
public boolean equals(Object o) {
return (o instanceof TrueOperator);
}
}
| 1,283
| 22.345455
| 74
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/UnaryOperator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import org.jspecify.annotations.Nullable;
/** An operator of the form lhs = op (rhs) */
public abstract class UnaryOperator<T extends IVariable<T>> extends AbstractOperator<T> {
/**
* Evaluate this equation, setting a new value for the left-hand side.
*
* @return true if the lhs value changes. false otherwise.
*/
public abstract byte evaluate(@Nullable T lhs, T rhs);
/** Create an equation which uses this operator Override in subclasses for efficiency. */
public UnaryStatement<T> makeEquation(@Nullable T lhs, T rhs) {
return new BasicUnaryStatement<>(lhs, this, rhs);
}
public boolean isIdentity() {
return false;
}
@Override
public byte evaluate(T lhs, T[] rhs) throws UnimplementedError {
// this should never be called. Use the other, more efficient form.
Assertions.UNREACHABLE();
return 0;
}
}
| 1,363
| 30.72093
| 91
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/UnaryOr.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import org.jspecify.annotations.Nullable;
/** Operator U(n) = U(n) | U(j) */
public final class UnaryOr extends UnaryOperator<BooleanVariable> {
private static final UnaryOr SINGLETON = new UnaryOr();
public static UnaryOr instance() {
return UnaryOr.SINGLETON;
}
private UnaryOr() {}
@Override
public byte evaluate(@Nullable BooleanVariable lhs, BooleanVariable rhs)
throws IllegalArgumentException {
if (lhs == null) {
throw new IllegalArgumentException("lhs == null");
}
boolean old = lhs.getValue();
lhs.or(rhs);
return (lhs.getValue() != old) ? FixedPointConstants.CHANGED : FixedPointConstants.NOT_CHANGED;
}
@Override
public String toString() {
return "OR";
}
@Override
public int hashCode() {
return 9887;
}
@Override
public boolean equals(Object o) {
return (o instanceof UnaryOr);
}
}
| 1,291
| 23.377358
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/fixpoint/UnaryStatement.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.fixpoint;
import org.jspecify.annotations.Nullable;
/** Represents a single step, restricted to a unary operator. */
public abstract class UnaryStatement<T extends IVariable<T>>
extends AbstractStatement<T, UnaryOperator<T>> {
/** The operands */
@Nullable protected final T lhs;
protected final T rhs;
/**
* Evaluate this equation, setting a new value for the left-hand side.
*
* @return true if the lhs value changed. false otherwise
*/
@Override
public byte evaluate() {
UnaryOperator<T> op = getOperator();
return op.evaluate(lhs, rhs);
}
/**
* Return the left-hand side of this equation.
*
* @return the lattice cell this equation computes
*/
@Nullable
@Override
public T getLHS() {
return lhs;
}
/** @return the right-hand side of this equation. */
public T getRightHandSide() {
return rhs;
}
/** Return the operands in this equation. */
public IVariable<T>[] getOperands() {
@SuppressWarnings("unchecked")
IVariable<T>[] result = new IVariable[2];
result[0] = lhs;
result[1] = rhs;
return result;
}
/**
* Does this equation contain an appearance of a given cell?
*
* @param cell the cell in question
* @return true or false
*/
@Override
public boolean hasVariable(T cell) {
if (lhs == cell) return true;
if (rhs == cell) return true;
return false;
}
/**
* Return a string representation of this object
*
* @return a string representation of this object
*/
@Override
public String toString() {
String result;
if (lhs == null) {
result = "null lhs";
} else {
result = lhs.toString();
}
result = result + ' ' + getOperator() + ' ' + rhs;
return result;
}
/**
* Constructor for case of one operand on the right-hand side.
*
* @param lhs the lattice cell set by this equation
* @param rhs the first operand on the rhs
*/
protected UnaryStatement(@Nullable T lhs, T rhs) {
super();
this.lhs = lhs;
this.rhs = rhs;
}
@Override
public boolean equals(Object o) {
if (o instanceof UnaryStatement) {
UnaryStatement<?> other = (UnaryStatement<?>) o;
if (!getOperator().equals(other.getOperator())) {
return false;
}
if (lhs == null) {
if (other.lhs != null) {
return false;
}
} else {
if (other.lhs == null) {
return false;
}
if (!lhs.equals(other.lhs)) {
return false;
}
}
if (rhs == null) {
if (other.rhs != null) {
return false;
}
} else {
if (other.rhs == null) {
return false;
}
if (!rhs.equals(other.rhs)) {
return false;
}
}
return true;
} else {
return false;
}
}
@Override
public int hashCode() {
int result = getOperator().hashCode() * 1381;
if (lhs != null) {
result += 1399 * lhs.hashCode();
}
if (rhs != null) {
result += 1409 * rhs.hashCode();
}
return result;
}
@Override
public T[] getRHS() throws UnsupportedOperationException {
// This should never be called ...use the more efficient getRightHandSide instead
throw new UnsupportedOperationException();
}
}
| 3,709
| 22.481013
| 85
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/qual/Initializer.java
|
/*
* Copyright (c) 2002 - 2022 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.qual;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A method annotated with @Initializer is expected to always be invoked before the object is used.
*/
@Retention(RetentionPolicy.CLASS)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface Initializer {}
| 833
| 32.36
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/CancelException.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util;
/**
* An exception for when work is canceled in eclipse. This version forces every API that uses it to
* declare it. Use {@code CancelRuntimeException} to avoid the need to declare a cancel exception.
*/
public class CancelException extends Exception {
private static final long serialVersionUID = 3728159810629412928L;
protected CancelException(String msg) {
super(msg);
}
public CancelException(Exception cause) {
super(cause);
}
public static CancelException make(String msg) {
return new CancelException(msg);
}
}
| 947
| 27.727273
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/MonitorUtil.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util;
/** Simple utilities for Eclipse progress monitors */
public class MonitorUtil {
/** Use this interface to decouple core utilities from the Eclipse layer */
public interface IProgressMonitor {
/** Constant indicating an unknown amount of work. */
int UNKNOWN = -1;
void beginTask(String task, int totalWork);
/* BEGIN Custom change: subtasks and canceling */
void subTask(String subTask);
void cancel();
/* END Custom change: subtasks and canceling */
boolean isCanceled();
void done();
void worked(int units);
String getCancelMessage();
}
public static void beginTask(IProgressMonitor monitor, String task, int totalWork)
throws CancelException {
if (monitor != null) {
monitor.beginTask(task, totalWork);
if (monitor.isCanceled()) {
throw CancelException.make("cancelled in " + task);
}
}
}
public static void done(IProgressMonitor monitor) throws CancelException {
if (monitor != null) {
monitor.done();
if (monitor.isCanceled()) {
throw CancelException.make("cancelled in " + monitor);
}
}
}
public static void worked(IProgressMonitor monitor, int units) throws CancelException {
if (monitor != null) {
monitor.worked(units);
if (monitor.isCanceled()) {
throw CancelException.make("cancelled in " + monitor);
}
}
}
public static void throwExceptionIfCanceled(IProgressMonitor progressMonitor)
throws CancelException {
if (progressMonitor != null) {
if (progressMonitor.isCanceled()) {
throw CancelException.make(progressMonitor.getCancelMessage());
}
}
}
/* BEGIN Custom change: more on subtasks */
public static void subTask(IProgressMonitor progressMonitor, String subTask)
throws CancelException {
if (progressMonitor != null) {
progressMonitor.subTask(subTask);
if (progressMonitor.isCanceled()) {
throw CancelException.make("cancelled in " + subTask);
}
}
}
public static boolean isCanceled(IProgressMonitor progressMonitor) {
if (progressMonitor == null) {
return false;
} else {
return progressMonitor.isCanceled();
}
}
public static void cancel(IProgressMonitor progress) {
if (progress != null) {
progress.cancel();
}
}
/* END Custom change: more on subtasks */
// public static IProgressMonitor subProgress(ProgressMaster progress, int i) {
// if (progress == null) {
// return null;
// } else {
// return new SubProgressMonitor(progress, i);
// }
// }
}
| 3,018
| 26.697248
| 89
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/NullProgressMonitor.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util;
import com.ibm.wala.util.MonitorUtil.IProgressMonitor;
/** Dummy {@link IProgressMonitor} */
public class NullProgressMonitor implements IProgressMonitor {
@Override
public void beginTask(String task, int totalWork) {
// do nothing
}
@Override
public boolean isCanceled() {
// do nothing
return false;
}
@Override
public void done() {
// do nothing
}
@Override
public void worked(int units) {
// do nothing
}
/* BEGIN Custom change: subtasks and canceling */
@Override
public void subTask(String subTask) {
// do nothing
}
@Override
public void cancel() {
// do nothing
}
/* END Custom change: subtasks and canceling */
@Override
public String getCancelMessage() {
assert false;
return "never cqncels";
}
}
| 1,193
| 19.947368
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/PlatformUtil.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/** Platform-specific utility functions. */
public class PlatformUtil {
/** are we running on Mac OS X? */
public static boolean onMacOSX() {
String osname = System.getProperty("os.name");
return osname.toLowerCase().contains("mac");
// return System.getProperty("mrj.version") != null;
}
/** are we running on Linux? */
public static boolean onLinux() {
String osname = System.getProperty("os.name");
return osname.equalsIgnoreCase("linux");
}
/** are we running on Windows? */
public static boolean onWindows() {
String osname = System.getProperty("os.name");
return osname.toLowerCase().contains("windows");
}
/** are we running on <a href="http://www.ikvm.net">IKVM</a>? */
public static boolean onIKVM() {
return "IKVM.NET".equals(System.getProperty("java.runtime.name"));
}
/**
* Gets the standard JDK modules shipped with the running JDK
*
* @param justBase if {@code true}, only include the file corresponding to the {@code java.base}
* module
* @return array of {@code .jmod} module files
* @throws IllegalStateException if modules cannot be found
*/
public static String[] getJDKModules(boolean justBase) {
List<String> jmods;
if (justBase) {
Path basePath = Paths.get(System.getProperty("java.home"), "jmods", "java.base.jmod");
if (!Files.exists(basePath)) {
throw new IllegalStateException("could not find java.base.jmod");
}
jmods = List.of(basePath.toString());
} else {
try (Stream<Path> stream = Files.list(Paths.get(System.getProperty("java.home"), "jmods"))) {
jmods =
stream
.map(Path::toString)
.filter(p -> p.endsWith(".jmod"))
.collect(Collectors.toList());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
return jmods.toArray(new String[0]);
}
/**
* Returns the filesystem path for a JDK module from the running JVM
*
* @param moduleName name of the module, e.g., {@code "java.sql"}
* @return path to the module
*/
public static Path getPathForJDKModule(String moduleName) {
return Paths.get(System.getProperty("java.home"), "jmods", moduleName + ".jmod");
}
/** @return the major version of the Java runtime we are running on. */
public static int getJavaRuntimeVersion() {
String version = System.getProperty("java.version");
if (version.startsWith("1.")) {
version = version.substring(2, 3);
} else {
int dot = version.indexOf(".");
if (dot != -1) {
version = version.substring(0, dot);
}
}
return Integer.parseInt(version);
}
}
| 3,295
| 31.633663
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/WalaException.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util;
/** An exception to raise for some WALA failure */
public class WalaException extends Exception {
private static final long serialVersionUID = 3959226859263419122L;
/** @param s a message describing the failure */
public WalaException(String s, Throwable cause) {
super(s, cause);
}
/** @param string a message describing the failure */
public WalaException(String string) {
super(string);
}
}
| 820
| 30.576923
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/WalaRuntimeException.java
|
/*
* Copyright (c) 2008 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util;
/** Runtime exception for some WALA failure. */
public class WalaRuntimeException extends RuntimeException {
private static final long serialVersionUID = -272544923431659418L;
/** @param s a message describing the failure */
public WalaRuntimeException(String s, Throwable cause) {
super(s, cause);
}
/** @param string a message describing the failure */
public WalaRuntimeException(String string) {
super(string);
}
}
| 838
| 31.269231
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/AbstractMultiMap.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.collections;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.jspecify.annotations.Nullable;
abstract class AbstractMultiMap<K, V> implements Serializable, MultiMap<K, V> {
/** */
private static final long serialVersionUID = 4064901973301954076L;
protected final Map<K, Set<V>> map = HashMapFactory.make();
protected final boolean create;
protected AbstractMultiMap(boolean create) {
this.create = create;
}
protected abstract Set<V> createSet();
protected Set<V> emptySet() {
return Collections.<V>emptySet();
}
@Override
public Set<V> get(@Nullable K key) {
Set<V> ret = map.get(key);
if (ret == null) {
if (create) {
ret = createSet();
map.put(key, ret);
} else {
ret = emptySet();
}
}
return ret;
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#put(K, V)
*/
@Override
public boolean put(K key, @Nullable V val) {
Set<V> vals = map.get(key);
if (vals == null) {
vals = createSet();
map.put(key, vals);
}
return vals.add(val);
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#remove(K, V)
*/
@Override
public boolean remove(K key, V val) {
Set<V> elems = map.get(key);
if (elems == null) return false;
boolean ret = elems.remove(val);
if (elems.isEmpty()) {
map.remove(key);
}
return ret;
}
@Override
public Set<V> removeAll(K key) {
return map.remove(key);
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#keys()
*/
@Override
public Set<K> keySet() {
return map.keySet();
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#containsKey(java.lang.Object)
*/
@Override
public boolean containsKey(K key) {
return map.containsKey(key);
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#size()
*/
@Override
public int size() {
int ret = 0;
for (K key : keySet()) {
ret += get(key).size();
}
return ret;
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#toString()
*/
@Override
public String toString() {
return map.toString();
}
/*
* (non-Javadoc)
*
* @see AAA.util.MultiMap#putAll(K, java.util.Set)
*/
@Override
public boolean putAll(K key, Collection<? extends V> vals) {
Set<V> edges = map.get(key);
if (edges == null) {
edges = createSet();
map.put(key, edges);
}
return edges.addAll(vals);
}
@Override
public void clear() {
map.clear();
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
}
| 4,632
| 24.043243
| 79
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ArrayIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
/** an Iterator of array elements */
public class ArrayIterator<T> implements Iterator<T> {
/** The index of the next array element to return */
protected int _cnt;
/** The index of the last array element to return */
protected final int last;
/** The array source for the iterator */
protected final T[] _elts;
/** @param elts the array which should be iterated over */
public ArrayIterator(T[] elts) {
this(elts, 0);
}
/**
* @param elts the array which should be iterated over
* @param start the first array index to return
*/
public ArrayIterator(T[] elts, int start) {
if (elts == null) {
throw new IllegalArgumentException("null elts");
}
if (start < 0 || start > elts.length) {
throw new IllegalArgumentException(
"invalid start: " + start + ", arrray length " + elts.length);
}
_elts = elts;
_cnt = start;
last = _elts.length - 1;
}
/**
* @param elts the array which should be iterated over
* @param start the first array index to return
*/
public ArrayIterator(T[] elts, int start, int last) {
if (elts == null) {
throw new IllegalArgumentException("null elts");
}
if (start < 0) {
throw new IllegalArgumentException("illegal start: " + start);
}
if (last < 0) {
throw new IllegalArgumentException("illegal last: " + last);
}
_elts = elts;
_cnt = start;
this.last = last;
}
@Override
public boolean hasNext() {
return _cnt <= last;
}
@Override
public T next() throws NoSuchElementException {
if (_cnt >= _elts.length) {
throw new NoSuchElementException();
}
return _elts[_cnt++];
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
| 2,300
| 25.448276
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ArrayNonNullIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.NoSuchElementException;
/**
* Iterator that only returns non-null elements of the array
*
* <p>hasNext() return true when there is a non-null element, false otherwise
*
* <p>next() returns the current element and advances the counter up to the next non-null element or
* beyond the limit of the array
*/
public class ArrayNonNullIterator<T> extends ArrayIterator<T> {
public ArrayNonNullIterator(T[] elts) {
super(elts, 0);
}
public ArrayNonNullIterator(T[] elts, int start) {
super(elts, start);
}
@Override
public boolean hasNext() {
return _cnt < _elts.length && _elts[_cnt] != null;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T result = _elts[_cnt];
do {
_cnt++;
} while (_cnt < _elts.length && _elts[_cnt] == null);
return result;
}
}
| 1,296
| 24.431373
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ArraySet.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.collections;
import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A set implementation backed by an array. This implementation is space-efficient for small sets,
* but several operations like {@link #contains(Object)} are linear time.
*/
public class ArraySet<T> extends AbstractSet<T> implements Serializable {
/** */
private static final long serialVersionUID = -5842124218051589966L;
private static final ArraySet<?> EMPTY =
new ArraySet<>(0, true) {
/** */
private static final long serialVersionUID = -3094823386613798012L;
@Override
/*
* @throws UnsupportedOperationException unconditionally
*/
public boolean add(Object obj_) {
throw new UnsupportedOperationException();
}
};
@SuppressWarnings("all")
public static final <T> ArraySet<T> empty() {
return (ArraySet<T>) EMPTY;
}
private T[] _elems;
private int _curIndex = 0;
private final boolean checkDupes;
@SuppressWarnings("all")
public ArraySet(int n, boolean checkDupes) {
if (n < 0) {
throw new IllegalArgumentException("invalid n: " + n);
}
_elems = (T[]) new Object[n];
this.checkDupes = checkDupes;
}
public ArraySet() {
this(1, true);
}
@SuppressWarnings("all")
public ArraySet(ArraySet<T> other) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("other == null");
}
int size = other._curIndex;
this._elems = (T[]) new Object[size];
this.checkDupes = other.checkDupes;
this._curIndex = size;
System.arraycopy(other._elems, 0, _elems, 0, size);
}
private ArraySet(Collection<T> other) {
this(other.size(), true);
addAll(other);
}
/** @throws UnsupportedOperationException if this {@link ArraySet} is immutable (optional) */
@Override
@SuppressWarnings("all")
public boolean add(T o) {
if (o == null) {
throw new IllegalArgumentException("null o");
}
if (checkDupes && this.contains(o)) {
return false;
}
if (_curIndex == _elems.length) {
// lengthen array
_elems = Arrays.copyOf(_elems, _elems.length * 2);
}
_elems[_curIndex] = o;
_curIndex++;
return true;
}
public boolean addAll(ArraySet<T> other) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("other == null");
}
boolean ret = false;
for (int i = 0; i < other.size(); i++) {
boolean added = add(other.get(i));
ret = ret || added;
}
return ret;
}
@Override
public boolean contains(Object obj_) {
for (int i = 0; i < _curIndex; i++) {
if (_elems[i].equals(obj_)) return true;
}
return false;
}
public boolean intersects(ArraySet<T> other) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("other == null");
}
for (int i = 0; i < other.size(); i++) {
if (contains(other.get(i))) return true;
}
return false;
}
public void forall(ObjectVisitor<T> visitor) {
if (visitor == null) {
throw new IllegalArgumentException("null visitor");
}
for (int i = 0; i < _curIndex; i++) {
visitor.visit(_elems[i]);
}
}
@Override
public int size() {
return _curIndex;
}
/**
* @throws IndexOutOfBoundsException if the index is out of range (index < 0 || index >=
* size()).
*/
public T get(int i) {
return _elems[i];
}
@Override
public boolean remove(Object obj_) {
int ind;
for (ind = 0; ind < _curIndex && !_elems[ind].equals(obj_); ind++) {}
// check if object was never there
if (ind == _curIndex) return false;
return remove(ind);
}
/** @return {@code true} (SJF: So why return a value?) */
public boolean remove(int ind) {
try {
// hope i got this right...
System.arraycopy(_elems, ind + 1, _elems, ind, _curIndex - (ind + 1));
_curIndex--;
return true;
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid ind: " + ind, e);
}
}
@Override
public void clear() {
_curIndex = 0;
}
/** @see java.util.Set#iterator() */
@Override
public Iterator<T> iterator() {
return new ArraySetIterator();
}
public class ArraySetIterator implements Iterator<T> {
int ind = 0;
final int setSize = size();
public ArraySetIterator() {}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return ind < setSize;
}
@Override
public T next() {
if (ind >= setSize) {
throw new NoSuchElementException();
}
return get(ind++);
}
}
public static <T> ArraySet<T> make() {
return new ArraySet<>();
}
public static <T> ArraySet<T> make(Collection<T> other) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("other == null");
}
return new ArraySet<>(other);
}
}
| 7,170
| 27.456349
| 98
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ArraySetMultiMap.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.collections;
import java.util.Collection;
import java.util.Set;
import org.jspecify.annotations.Nullable;
/** */
public class ArraySetMultiMap<K, V> extends AbstractMultiMap<K, V> {
/** */
private static final long serialVersionUID = -3475591699051060160L;
public static final ArraySetMultiMap<?, ?> EMPTY =
new ArraySetMultiMap<>() {
/** */
private static final long serialVersionUID = 1839857029830528896L;
@Override
public boolean put(Object key, @Nullable Object val) {
throw new RuntimeException();
}
@Override
public boolean putAll(Object key, Collection<? extends Object> vals) {
throw new RuntimeException();
}
};
public ArraySetMultiMap() {
super(false);
}
public ArraySetMultiMap(boolean create) {
super(create);
}
@Override
protected Set<V> createSet() {
return new ArraySet<>();
}
@Override
protected Set<V> emptySet() {
return ArraySet.<V>empty();
}
@Override
public ArraySet<V> get(@Nullable K key) {
return (ArraySet<V>) super.get(key);
}
public static <K, V> ArraySetMultiMap<K, V> make() {
return new ArraySetMultiMap<>();
}
}
| 3,157
| 32.595745
| 78
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/BimodalMap.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* This implementation of {@link Map} chooses between one of two implementations, depending on the
* size of the map.
*/
public class BimodalMap<K, V> implements Map<K, V> {
// what's the cutoff between small and big maps?
// this may be a time-space tradeoff; the caller must determine if
// it's willing to put up with slower random access in exchange for
// smaller footprint.
private final int cutOff;
/** The implementation we delegate to */
@Nullable private Map<K, V> backingStore;
/**
* @param cutoff the map size at which to switch from the small map implementation to the large
* map implementation
*/
public BimodalMap(int cutoff) {
this.cutOff = cutoff;
}
@Override
public int size() {
return (backingStore == null) ? 0 : backingStore.size();
}
@Override
public boolean isEmpty() {
return (backingStore == null) ? true : backingStore.isEmpty();
}
@Override
public boolean containsKey(Object key) {
return (backingStore == null) ? false : backingStore.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return (backingStore == null) ? false : backingStore.containsValue(value);
}
@Nullable
@Override
public V get(Object key) {
return (backingStore == null) ? null : backingStore.get(key);
}
@Nullable
@Override
public V put(K key, V value) {
if (backingStore == null) {
backingStore = new SmallMap<>();
backingStore.put(key, value);
return null;
} else {
if (backingStore instanceof SmallMap) {
V result = backingStore.put(key, value);
if (backingStore.size() > cutOff) {
transferBackingStore();
}
return result;
} else {
return backingStore.put(key, value);
}
}
}
/** Switch backing implementation from a SmallMap to a HashMap */
@NullUnmarked
private void transferBackingStore() {
assert backingStore instanceof SmallMap;
SmallMap<K, V> S = (SmallMap<K, V>) backingStore;
backingStore = HashMapFactory.make(2 * S.size());
backingStore.putAll(S);
}
/** @throws UnsupportedOperationException if the backingStore doesn't support remove */
@Nullable
@Override
public V remove(Object key) {
return (backingStore == null) ? null : backingStore.remove(key);
}
@Override
@SuppressWarnings("unchecked")
public void putAll(Map<? extends K, ? extends V> t) throws UnsupportedOperationException {
if (t == null) {
throw new IllegalArgumentException("null t");
}
if (backingStore == null) {
int size = t.size();
if (size > cutOff) {
backingStore = HashMapFactory.make();
} else {
backingStore = new SmallMap<>();
}
backingStore.putAll(t);
return;
} else {
if (backingStore instanceof SmallMap) {
if (t.size() > cutOff) {
Map<K, V> old = backingStore;
backingStore = (Map<K, V>) HashMapFactory.make(t);
backingStore.putAll(old);
} else {
backingStore.putAll(t);
if (backingStore.size() > cutOff) {
transferBackingStore();
}
return;
}
} else {
backingStore.putAll(t);
}
}
}
@Override
public void clear() {
backingStore = null;
}
@Override
@SuppressWarnings("unchecked")
public Set<K> keySet() {
return (Set<K>) ((backingStore == null) ? Collections.emptySet() : backingStore.keySet());
}
@Override
@SuppressWarnings("unchecked")
public Collection<V> values() {
return (Collection<V>)
((backingStore == null) ? Collections.emptySet() : backingStore.values());
}
/** @throws UnimplementedError if the backingStore implementation does */
@Override
@SuppressWarnings("unchecked")
public Set<Map.Entry<K, V>> entrySet() {
return (Set<Entry<K, V>>)
((backingStore == null) ? Collections.emptySet() : backingStore.entrySet());
}
}
| 4,641
| 26.963855
| 98
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/CollectionFilter.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Collection;
import java.util.function.Predicate;
/** A filter defined by set membership */
public class CollectionFilter<T> implements Predicate<T> {
private final Collection<? extends T> S;
public CollectionFilter(Collection<? extends T> S) {
if (S == null) {
throw new IllegalArgumentException("null S");
}
this.S = S;
}
/** @see com.ibm.wala.util.collections.FilterIterator */
@Override
public boolean test(T o) {
return S.contains(o);
}
}
| 916
| 25.2
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ComposedIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/** A 2-level iterator. has not been tested yet! */
public abstract class ComposedIterator<O, I> implements Iterator<I> {
private final Iterator<O> outer;
@Nullable private Iterator<? extends I> inner;
public ComposedIterator(Iterator<O> outer) {
this.outer = outer;
advanceOuter();
}
private void advanceOuter() {
while (outer.hasNext()) {
inner = makeInner(outer.next());
if (inner.hasNext()) {
break;
}
}
if (inner != null && !inner.hasNext()) {
inner = null;
}
}
public abstract Iterator<? extends I> makeInner(O outer);
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
@Override
public boolean hasNext() {
return (inner != null);
}
@NullUnmarked
@Override
public I next() {
I result = inner.next();
if (!inner.hasNext()) {
advanceOuter();
}
return result;
}
}
| 1,489
| 23.032258
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/CompoundIntIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import com.ibm.wala.util.debug.Assertions;
import com.ibm.wala.util.debug.UnimplementedError;
import com.ibm.wala.util.intset.IntIterator;
/** An Iterator which provides a concatenation of two IntIterators. */
public class CompoundIntIterator implements IntIterator {
final IntIterator A;
final IntIterator B;
/**
* @param A the first iterator in the concatenated result
* @param B the second iterator in the concatenated result
*/
public CompoundIntIterator(IntIterator A, IntIterator B) {
this.A = A;
this.B = B;
if (A == null) {
throw new IllegalArgumentException("null A");
}
if (B == null) {
throw new IllegalArgumentException("null B");
}
}
@Override
public boolean hasNext() {
return A.hasNext() || B.hasNext();
}
@Override
public int next() {
if (A.hasNext()) {
return A.next();
} else {
return B.next();
}
}
@Override
public int hashCode() throws UnimplementedError {
Assertions.UNREACHABLE("define a custom hash code to avoid non-determinism");
return 0;
}
}
| 1,500
| 24.440678
| 81
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/CompoundIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
/** An iterator which provides a logical concatenation of the lists from two other iterators */
public class CompoundIterator<T> implements Iterator<T> {
final Iterator<? extends T> A;
final Iterator<? extends T> B;
public CompoundIterator(Iterator<? extends T> A, Iterator<? extends T> B) {
if (A == null) {
throw new IllegalArgumentException("null A");
}
this.A = A;
this.B = B;
}
@Override
public boolean hasNext() {
return A.hasNext() || B.hasNext();
}
@Override
public T next() throws NoSuchElementException {
if (A.hasNext()) {
return A.next();
} else {
return B.next();
}
}
@Override
public void remove() {}
}
| 1,180
| 24.12766
| 95
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/EmptyIntIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import com.ibm.wala.util.intset.IntIterator;
import java.util.NoSuchElementException;
/**
* A singleton instance of an empty iterator; this is better than Collections.EMPTY_SET.iterator(),
* which allocates an iterator object;
*/
public final class EmptyIntIterator implements IntIterator {
private static final EmptyIntIterator EMPTY = new EmptyIntIterator();
public static EmptyIntIterator instance() {
return EMPTY;
}
/** prevent instantiation */
private EmptyIntIterator() {}
@Override
public boolean hasNext() {
return false;
}
@Override
public int next() throws NoSuchElementException {
throw new NoSuchElementException();
}
}
| 1,091
| 25.634146
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/EmptyIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A singleton instance of an empty iterator; this is better than Collections.EMPTY_SET.iterator(),
* which allocates an iterator object;
*/
public final class EmptyIterator<T> implements Iterator<T> {
@SuppressWarnings("rawtypes")
private static final EmptyIterator EMPTY = new EmptyIterator();
public static <T> EmptyIterator<T> instance() {
return EMPTY;
}
/** prevent instantiation */
private EmptyIterator() {}
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
throw new NoSuchElementException();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
| 1,194
| 24.425532
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Factory.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
public interface Factory<T> {
T make();
}
| 452
| 27.3125
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/FifoQueue.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
/**
* FIFO work queue management of Objects that prevents an object from being added to the queue if it
* is already enqueued and has not yet been popped.
*/
public class FifoQueue<T> {
/** The work queue. Items are references to Object instances. */
final ArrayDeque<T> qItems = new ArrayDeque<>();
/**
* Set representing items currently enqueue. This is used to keep an item from having more than
* one entry in the queue.
*/
final Set<T> inQueue = HashSetFactory.make();
/** Creates a FIFO queue with no elements enqueued. */
public FifoQueue() {}
/**
* Creates a new FIFO queue containing the argument to this constructor.
*
* @param element is the element to add to the queue.
*/
public FifoQueue(T element) {
push(element);
}
/**
* Creates a new FIFO queue containing the elements of the specified Collection. The order the
* elements are inserted into the queue is unspecified.
*
* @param collection is the Collection of Object instances to be enqueue.
* @throws IllegalArgumentException if collection is null
*/
public FifoQueue(Collection<T> collection) {
if (collection == null) {
throw new IllegalArgumentException("collection is null");
}
push(collection.iterator());
}
/**
* Return the current number of enqueued Objects, the number of Objects that were pushed into the
* queue and have not been popped.
*
* @return the current queue size.
* @see #isEmpty
*/
public int size() {
return qItems.size();
}
/**
* Returns whether or not this queue is empty (no enqueued elements).
*
* @return {@code true} when there are no enqueued objects. {@code false} if there are objects
* remaining in the queue.
* @see #size
*/
public boolean isEmpty() {
return qItems.isEmpty();
}
/**
* Indicate whether the specified element is currently in the queue.
*
* @param element determine whether this object is in the queue.
* @return {@code true} if {@code element} is in the queue. Otherwise {@code false} if not
* currently in the queue.
*/
public boolean contains(T element) {
return inQueue.contains(element);
}
/**
* Insert an Object at the tail end of the queue if it is not already in the queue. If the Object
* is already in the queue, the queue remains unmodified.
*
* <p>This method determines whether an element is already in the queue using the element's {@code
* equals()} method. If the element's class does not implement {@code equals()}, the default
* implementation assumes they are equal only if it is the same object.
*
* @param element is the Object to be added to the queue if not already present in the queue.
*/
public void push(T element) {
// if element is not in inQueue, then add() returns true.
if (inQueue.add(element)) {
qItems.add(element);
}
}
/**
* Insert all of the elements in the specified Iterator at the tail end of the queue if not
* already present in the queue. Any element in the Iterator already in the queue is ignored.
*
* <p>This method determines whether an element is already in the queue using the element's {@code
* equals()} method. If the element's class does not implement {@code equals()}, the default
* implementation assumes they are equal if it is the same object.
*
* @param elements an Iterator of Objects to be added to the queue if not already queued.
* @throws IllegalArgumentException if elements == null
*/
public void push(Iterator<? extends T> elements) throws IllegalArgumentException {
if (elements == null) {
throw new IllegalArgumentException("elements == null");
}
while (elements.hasNext()) {
T element = elements.next();
// if element is not in inQueue, then add() returns true.
if (inQueue.add(element)) {
qItems.add(element);
}
}
}
/**
* Remove the next Object from the queue and return it to the caller. Throws {@code
* IllegalStateException} if the queue is empty when this method is called.
*
* @return the next Object in the queue.
*/
public T pop() throws IllegalStateException {
// While there are work queue elements, remove the next element &
// indicate that it is no longer in the work queue.
// Throw a IllegalStateException when there is a queue underflow.
if (isEmpty()) throw new IllegalStateException("Unexpected empty queue during pop");
// get & remove the top of the queue.
T element = qItems.removeLast();
// remove element from the elements that are 'inQueue'
inQueue.remove(element);
return element;
}
/**
* Returns the next Object in the queue, but leaves it in the queue. Throws {@code
* IllegalStateException} if the queue is empty when this method is called.
*
* @return the next Object in the queue.
*/
public T peek() throws IllegalStateException {
// While there are work queue elements, return the next element.
// Throw a IllegalStateException if there is a queue underflow.
if (isEmpty()) throw new IllegalStateException("Unexpected empty queue during peek");
// get & remove the top of the queue.
return qItems.getLast();
}
}
| 5,785
| 33.440476
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/FifoQueueNoDuplicates.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
/**
* FIFO work queue management of Objects that prevents an Object from being added to the queue if it
* was ever previously enqueued.
*/
public class FifoQueueNoDuplicates<T> extends FifoQueue<T> {
/**
* Set representing items ever pushed into the work queue. This keeps an item from ever be pushed
* again into the work queue.
*/
private final Set<T> wasInQueue = HashSetFactory.make();
/**
* Return an Iterator over the set of all the nodes that were pushed into the queue.
*
* @return an Iterator over the set of pushed nodes.
*/
public Iterator<T> getPushedNodes() {
return wasInQueue.iterator();
}
/**
* Insert an Object at the tail end of the queue if it was never pushed into the queue.
*
* <p>This method determines whether an element was ever in the queue using the element's {@code
* equals()} method. If the element's class does not implement {@code equals()}, the default
* implementation assumes they are equal if it is the same object.
*
* @param element is the Object to be added to the queue if not ever previously queued.
*/
@Override
public void push(T element) {
if (wasInQueue.add(element)) {
inQueue.add(element);
qItems.add(element);
}
}
/**
* Insert all of the elements in the specified Iterator at the tail end of the queue if never
* previously pushed into the queue.
*
* <p>This method determines whether an element was ever pushed into the queue using the element's
* {@code equals()} method. If the element's class does not implement {@code equals()}, the
* default implementation assumes that two elements are equal if they are the same object.
*
* @param elements an Iterator of Objects to be added to the queue if never already queued.
* @throws IllegalArgumentException if elements == null
*/
@Override
public void push(Iterator<? extends T> elements) throws IllegalArgumentException {
if (elements == null) {
throw new IllegalArgumentException("elements == null");
}
while (elements.hasNext()) {
T element = elements.next();
if (wasInQueue.add(element)) {
inQueue.add(element);
qItems.add(element);
}
}
}
/**
* Indicate whether the specified element was ever in the queue.
*
* @param element determine whether this object is in the queue.
* @return {@code true} if {@code element} is in the queue. Otherwise {@code false}.
*/
public boolean everContained(T element) {
return wasInQueue.contains(element);
}
/** Return the set of objects that have been queued. */
public Set<T> queuedSet() {
return Collections.unmodifiableSet(wasInQueue);
}
}
| 3,197
| 33.021277
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/FilterIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Predicate;
import org.jspecify.annotations.Nullable;
/** A {@code FilterIterator} filters an {@code Iterator} to generate a new one. */
public class FilterIterator<T> implements java.util.Iterator<T> {
final Iterator<? extends T> i;
final Predicate<? super T> f;
@Nullable private T next = null;
private boolean done = false;
/**
* @param i the original iterator
* @param f a filter which defines which elements belong to the generated iterator
*/
public FilterIterator(Iterator<? extends T> i, Predicate<? super T> f) {
if (i == null) {
throw new IllegalArgumentException("null i");
}
if (f == null) {
throw new IllegalArgumentException("null f");
}
this.i = i;
this.f = f;
advance();
}
/** update the internal state to prepare for the next access to this iterator */
private void advance() {
while (i.hasNext()) {
T o = i.next();
if (f.test(o)) {
next = o;
return;
}
}
done = true;
}
@Nullable
@Override
public T next() throws NoSuchElementException {
if (done) {
throw new java.util.NoSuchElementException();
}
T o = next;
advance();
return o;
}
@Override
public boolean hasNext() {
return !done;
}
@Override
public void remove() throws UnsupportedOperationException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public String toString() {
return "filter " + f + " of " + i;
}
}
| 2,001
| 23.414634
| 84
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Filtersection.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.function.Predicate;
/** intersection of two filters */
public class Filtersection<T> implements Predicate<T> {
private final Predicate<T> a;
private final Predicate<T> b;
public Filtersection(Predicate<T> a, Predicate<T> b) {
this.a = a;
this.b = b;
if (a == null) {
throw new IllegalArgumentException("null a");
}
if (b == null) {
throw new IllegalArgumentException("null b");
}
}
@Override
public boolean test(T o) {
return a.test(o) && b.test(o);
}
}
| 944
| 24.540541
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/HashMapFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A debugging aid. When HashSetFactory.DEBUG is set, this class creates ParanoidHashMaps.
* Otherwise, it returns {@link LinkedHashMap}
*/
public class HashMapFactory {
/** @return A ParanoidHashMap if DEBUG = true, a LinkedHashMap otherwise */
public static <K, V> HashMap<K, V> make(int size) {
if (HashSetFactory.DEBUG) {
return new ParanoidHashMap<>(size);
} else {
return new LinkedHashMap<>(size);
}
}
/** @return A ParanoidHashMap if DEBUG = true, a LinkedHashMap otherwise */
public static <K, V> HashMap<K, V> make() {
if (HashSetFactory.DEBUG) {
return new ParanoidHashMap<>();
} else {
return new LinkedHashMap<>();
}
}
/** @return A ParanoidHashMap if DEBUG = true, a LinkedHashMap otherwise */
public static <K, V> HashMap<K, V> make(Map<K, V> t) {
if (t == null) {
throw new IllegalArgumentException("null t");
}
if (HashSetFactory.DEBUG) {
return new ParanoidHashMap<>(t);
} else {
return new LinkedHashMap<>(t);
}
}
}
| 1,544
| 28.150943
| 90
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/HashSetFactory.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
/**
* A debugging aid. When HashSetFactory.DEBUG is set, this class creates ParanoidHashSets.
* Otherwise, it returns {@link LinkedHashSet}s
*/
public class HashSetFactory {
/** If true, this factory returns Paranoid versions of collections */
public static final boolean DEBUG = false;
/** @return A {@link ParanoidHashSet} if DEBUG = true, a java.util.HashSet otherwise */
public static <T> HashSet<T> make(int size) {
if (DEBUG) {
return new ParanoidHashSet<>(size);
} else {
return new LinkedHashSet<>(size);
}
}
/** @return A ParanoidHashSet if DEBUG = true, a java.util.HashSet otherwise */
public static <T> HashSet<T> make() {
if (DEBUG) {
return new ParanoidHashSet<>();
} else {
return new LinkedHashSet<>();
}
}
/** @return A ParanoidHashSet if DEBUG = true, a java.util.HashSet otherwise */
public static <T> HashSet<T> make(Collection<T> s) {
if (s == null) {
throw new IllegalArgumentException("null s");
}
if (DEBUG) {
return new ParanoidHashSet<>(s);
} else {
return new LinkedHashSet<>(s);
}
}
}
| 1,631
| 28.142857
| 90
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/HashSetMultiMap.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.collections;
import java.util.Set;
public class HashSetMultiMap<K, V> extends AbstractMultiMap<K, V> {
/** */
private static final long serialVersionUID = 1699856257459175263L;
public HashSetMultiMap() {
super(false);
}
public HashSetMultiMap(boolean create) {
super(create);
}
@Override
protected Set<V> createSet() {
return HashSetFactory.make();
}
public static <K, V> HashSetMultiMap<K, V> make() {
return new HashSetMultiMap<>();
}
}
| 2,428
| 36.953125
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Heap.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Arrays;
import java.util.NoSuchElementException;
/** Simple Heap data structure. */
public abstract class Heap<T> {
/** @return true iff elt1 is considered < elt2 */
protected abstract boolean compareElements(T elt1, T elt2);
private int numberOfElements;
private T[] backingStore;
/** @return number of elements in this heap */
public int size() {
return numberOfElements;
}
@SuppressWarnings("unchecked")
public Heap(int initialCapacity) {
numberOfElements = 0;
backingStore = (T[]) new Object[initialCapacity];
}
/** @return true iff this heap is non-empty */
public final boolean isEmpty() {
return numberOfElements == 0;
}
public void insert(T elt) {
ensureCapacity(numberOfElements + 1);
bubbleUp(elt, numberOfElements);
numberOfElements++;
}
/** @return the first object in the priority queue */
public T take() throws NoSuchElementException {
if (numberOfElements == 0) {
throw new NoSuchElementException();
}
T result = backingStore[0];
removeElement(0);
return result;
}
private static int heapParent(int index) {
return (index - 1) / 2;
}
private static int heapLeftChild(int index) {
return index * 2 + 1;
}
private static int heapRightChild(int index) {
return index * 2 + 2;
}
private final void ensureCapacity(int min) {
if (backingStore.length < min) {
backingStore = Arrays.copyOf(backingStore, 2 * min);
}
}
/**
* SJF: I know this is horribly uglified ... I've attempted to make things as easy as possible on
* the JIT, since this is performance critical.
*/
private final void removeElement(int index) {
int ne = numberOfElements;
T[] bs = backingStore;
while (true) {
int leftIndex = heapLeftChild(index);
if (leftIndex < ne) {
int rightIndex = heapRightChild(index);
if (rightIndex < ne) {
T leftObject = bs[leftIndex];
T rightObject = bs[rightIndex];
if (compareElements(leftObject, rightObject)) {
bs[index] = leftObject;
index = leftIndex;
} else {
bs[index] = rightObject;
index = rightIndex;
}
} else {
bs[index] = bs[leftIndex];
index = leftIndex;
}
// manual tail recursion elimination here
} else {
numberOfElements--;
ne = numberOfElements;
if (index != ne) {
bubbleUp(bs[ne], index);
}
return;
}
}
}
/**
* SJF: I know this is uglified ... I've attempted to make things as easy as possible on the JIT,
* since this is performance critical.
*/
private final void bubbleUp(T elt, int index) {
T[] bs = backingStore;
while (true) {
if (index == 0) {
bs[index] = elt;
return;
}
int hpIndex = heapParent(index);
T parent = bs[hpIndex];
if (compareElements(parent, elt)) {
bs[index] = elt;
return;
} else {
bs[index] = parent;
// manual tail recursion elimination
index = hpIndex;
}
}
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
s.append('[');
for (int i = 0; i < size(); i++) {
if (backingStore[i] != null) {
if (i > 0) s.append(',');
s.append(backingStore[i].toString());
}
}
s.append(']');
return s.toString();
}
}
| 3,905
| 24.86755
| 99
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/IVector.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import org.jspecify.annotations.Nullable;
/**
* simple interface for a vector.
*
* <p>TODO: get rid of this and use java.util.collection.RandomAccess
*/
public interface IVector<T> extends Iterable<T> {
/** @see com.ibm.wala.util.intset.IntVector#get(int) */
T get(int x);
/**
* TODO: this can be optimized
*
* @see com.ibm.wala.util.intset.IntVector#set(int, int)
*/
void set(int x, @Nullable T value);
/** @see com.ibm.wala.util.debug.VerboseAction#performVerboseAction() */
void performVerboseAction();
/** @return max i s.t get(i) != null */
int getMaxIndex();
}
| 1,018
| 26.540541
| 74
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/ImmutableStack.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.collections;
import java.util.Arrays;
import java.util.EmptyStackException;
import java.util.Iterator;
/**
* An immutable stack of objects. The {@link #push(Object)} and {@link #pop()} operations create new
* stacks.
*/
public class ImmutableStack<T> implements Iterable<T> {
private static final ImmutableStack<Object> EMPTY = new ImmutableStack<>(new Object[0]);
private static final int MAX_SIZE = Integer.MAX_VALUE;
public static int getMaxSize() {
return MAX_SIZE;
}
@SuppressWarnings("unchecked")
public static final <T> ImmutableStack<T> emptyStack() {
return (ImmutableStack<T>) EMPTY;
}
private final T[] entries;
private final int cachedHashCode;
protected ImmutableStack(T[] entries) {
this.entries = entries;
this.cachedHashCode = Arrays.hashCode(entries);
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o != null && o instanceof ImmutableStack) {
ImmutableStack other = (ImmutableStack) o;
return Arrays.equals(entries, other.entries);
}
return false;
}
@Override
public int hashCode() {
return cachedHashCode;
// return Util.hashArray(this.entries);
}
@SuppressWarnings("unused")
public ImmutableStack<T> push(T entry) {
if (entry == null) {
throw new IllegalArgumentException("null entry");
}
if (MAX_SIZE == 0) {
return emptyStack();
}
int size = entries.length + 1;
T[] tmpEntries = null;
if (size <= MAX_SIZE) {
tmpEntries = makeInternalArray(size);
System.arraycopy(entries, 0, tmpEntries, 0, entries.length);
tmpEntries[size - 1] = entry;
} else {
tmpEntries = makeInternalArray(MAX_SIZE);
System.arraycopy(entries, 1, tmpEntries, 0, entries.length - 1);
tmpEntries[MAX_SIZE - 1] = entry;
}
return makeStack(tmpEntries);
}
@SuppressWarnings("unchecked")
protected T[] makeInternalArray(int size) {
return (T[]) new Object[size];
}
protected ImmutableStack<T> makeStack(T[] tmpEntries) {
return new ImmutableStack<>(tmpEntries);
}
/**
* @return the element on the top of the stack
* @throws EmptyStackException if stack is empty
*/
public T peek() {
if (entries.length == 0) {
throw new EmptyStackException();
}
return entries[entries.length - 1];
}
/** @throws EmptyStackException if stack is empty */
public ImmutableStack<T> pop() {
if (entries.length == 0) {
throw new EmptyStackException();
}
int size = entries.length - 1;
T[] tmpEntries = makeInternalArray(size);
System.arraycopy(entries, 0, tmpEntries, 0, size);
return makeStack(tmpEntries);
}
public boolean isEmpty() {
return entries.length == 0;
}
public int size() {
return entries.length;
}
public T get(int i) {
try {
return entries[i];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IllegalArgumentException("invalid i: " + i, e);
}
}
@Override
public String toString() {
String objArrayToString = Arrays.toString(entries);
assert entries.length <= MAX_SIZE : objArrayToString;
return objArrayToString;
}
public boolean contains(T entry) {
if (entry == null) {
return false;
}
for (T entrie : entries) {
if (entrie != null && entrie.equals(entry)) return true;
}
return false;
}
/**
* @return {@code true} iff {@code other.size() = k}, {@code k <= this.size()}, and the top k
* elements of this equal other
* @throws IllegalArgumentException if other == null
*/
public boolean topMatches(ImmutableStack<T> other) throws IllegalArgumentException {
if (other == null) {
throw new IllegalArgumentException("other == null");
}
if (other.size() > size()) {
return false;
}
for (int i = other.size() - 1, j = this.size() - 1; i >= 0; i--, j--) {
if (!other.get(i).equals(get(j))) return false;
}
return true;
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> reverse() {
T[] tmpEntries = (T[]) new Object[entries.length];
for (int i = entries.length - 1, j = 0; i >= 0; i--, j++) {
tmpEntries[j] = entries[i];
}
return new ImmutableStack<>(tmpEntries);
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> popAll(ImmutableStack<T> other) {
if (!topMatches(other)) {
throw new IllegalArgumentException("top does not match");
}
int size = entries.length - other.entries.length;
T[] tmpEntries = (T[]) new Object[size];
System.arraycopy(entries, 0, tmpEntries, 0, size);
return new ImmutableStack<>(tmpEntries);
}
@SuppressWarnings("unchecked")
public ImmutableStack<T> pushAll(ImmutableStack<T> other) {
if (other == null) {
throw new IllegalArgumentException("null other");
}
int size = entries.length + other.entries.length;
T[] tmpEntries = null;
if (size <= MAX_SIZE) {
tmpEntries = (T[]) new Object[size];
System.arraycopy(entries, 0, tmpEntries, 0, entries.length);
System.arraycopy(other.entries, 0, tmpEntries, entries.length, other.entries.length);
} else {
tmpEntries = (T[]) new Object[MAX_SIZE];
// other has size at most MAX_SIZE
// must keep all in other
// top MAX_SIZE - other.size from this
int numFromThis = MAX_SIZE - other.entries.length;
System.arraycopy(entries, entries.length - numFromThis, tmpEntries, 0, numFromThis);
System.arraycopy(other.entries, 0, tmpEntries, numFromThis, other.entries.length);
}
return new ImmutableStack<>(tmpEntries);
}
@Override
public Iterator<T> iterator() {
if (entries.length == 0) {
return EmptyIterator.instance();
}
return new ArrayIterator<>(entries);
}
/** return a new stack with the top replaced with t */
public ImmutableStack<T> replaceTop(T t) {
if (isEmpty()) {
throw new EmptyStackException();
}
int size = entries.length;
T[] tmpEntries = makeInternalArray(size);
System.arraycopy(entries, 0, tmpEntries, 0, entries.length - 1);
tmpEntries[size - 1] = t;
return makeStack(tmpEntries);
}
}
| 8,161
| 30.758755
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/IndiscriminateFilter.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.function.Predicate;
/** A filter that accepts everything. */
public class IndiscriminateFilter<T> implements Predicate<T> {
public static <T> IndiscriminateFilter<T> singleton() {
return new IndiscriminateFilter<>();
}
/** @see FilterIterator */
@Override
public boolean test(Object o) {
return true;
}
}
| 761
| 25.275862
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/IntMapIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import com.ibm.wala.util.intset.IntIterator;
import java.util.Iterator;
import java.util.function.IntFunction;
/** An {@code IntMapIterator} maps an {@code Iterator} contents to produce a new Iterator */
public class IntMapIterator<T> implements Iterator<T> {
final IntIterator i;
final IntFunction<T> f;
public IntMapIterator(IntIterator i, IntFunction<T> f) {
if (i == null) {
throw new IllegalArgumentException("null i");
}
if (f == null) {
throw new IllegalArgumentException("null f");
}
this.i = i;
this.f = f;
}
@Override
public T next() {
return f.apply(i.next());
}
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public String toString() {
return "map: " + f + " of " + i;
}
}
| 1,338
| 23.796296
| 92
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/IntStack.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Arrays;
/** A stack of integer primitives. This should be more efficient than a java.util.Stack */
public class IntStack {
/** Comment for {@code top} */
private int top = -1;
/** Comment for {@code state} */
private int state[] = new int[0];
public void push(int i) {
if (state.length <= (top + 1)) {
state = Arrays.copyOf(state, state.length * 2 + 1);
}
state[++top] = i;
}
/** @return the int at the top of the stack */
public int peek() {
return state[top];
}
/**
* pop the stack
*
* @return the int at the top of the stack
*/
public int pop() {
return state[top--];
}
/** @return true iff the stack is empty */
public boolean isEmpty() {
return top == -1;
}
/** @return the number of elements in the stack. */
public int size() {
return top + 1;
}
/** @return the ith int from the bottom of the stack */
public int get(int i) {
if (i < 0 || i > top) {
throw new IndexOutOfBoundsException();
}
return state[i];
}
}
| 1,466
| 22.285714
| 90
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Iterator2Collection.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Converts an {@link Iterator} to a {@link Collection}. Note that if you just want to use Java 5's
* for-each loop with an {@link Iterator}, use {@link Iterator2Iterable}.
*
* @see Iterator2Iterable
*/
public abstract class Iterator2Collection<T> implements Collection<T> {
protected abstract Collection<T> getDelegate();
/** Returns a {@link Set} containing all elements in i. Note that duplicates will be removed. */
public static <T> Iterator2Set<T> toSet(Iterator<? extends T> i) throws IllegalArgumentException {
if (i == null) {
throw new IllegalArgumentException("i == null");
}
return new Iterator2Set<>(i, new LinkedHashSet<>(5));
}
/** Returns a {@link List} containing all elements in i, preserving duplicates. */
public static <T> Iterator2List<T> toList(Iterator<? extends T> i)
throws IllegalArgumentException {
if (i == null) {
throw new IllegalArgumentException("i == null");
}
return new Iterator2List<>(i, new ArrayList<>(5));
}
@Override
public String toString() {
return getDelegate().toString();
}
@Override
public int size() {
return getDelegate().size();
}
@Override
public void clear() {
getDelegate().clear();
}
@Override
public boolean isEmpty() {
return getDelegate().isEmpty();
}
@Override
public Object[] toArray() {
return getDelegate().toArray();
}
@Override
public boolean add(T arg0) {
return getDelegate().add(arg0);
}
@Override
public boolean contains(Object arg0) {
return getDelegate().contains(arg0);
}
@Override
public boolean remove(Object arg0) {
return getDelegate().remove(arg0);
}
@Override
public boolean addAll(Collection<? extends T> arg0) {
return getDelegate().addAll(arg0);
}
@Override
public boolean containsAll(Collection<?> arg0) {
return getDelegate().containsAll(arg0);
}
@Override
public boolean removeAll(Collection<?> arg0) {
return getDelegate().removeAll(arg0);
}
@Override
public boolean retainAll(Collection<?> arg0) {
return getDelegate().retainAll(arg0);
}
@Override
public Iterator<T> iterator() {
return getDelegate().iterator();
}
@Override
public <U> U[] toArray(U[] a) {
return getDelegate().toArray(a);
}
@Override
public boolean equals(Object o) {
return getDelegate().equals(o);
}
@Override
public int hashCode() {
return getDelegate().hashCode();
}
}
| 3,044
| 23.166667
| 100
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Iterator2Iterable.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import org.jspecify.annotations.Nullable;
/** Converts an {@link Iterator} to an {@link Iterable}. */
public class Iterator2Iterable<T> implements Iterable<T> {
@Nullable private final Iterator<T> iter;
public static <T> Iterator2Iterable<T> make(@Nullable Iterator<T> iter) {
return new Iterator2Iterable<>(iter);
}
public Iterator2Iterable(@Nullable Iterator<T> iter) {
this.iter = iter;
}
@Nullable
@Override
public Iterator<T> iterator() {
return iter;
}
}
| 931
| 25.628571
| 75
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Iterator2List.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Iterator2List<T> extends Iterator2Collection<T> implements Serializable, List<T> {
private static final long serialVersionUID = -4364941553982190713L;
private final List<T> delegate;
public Iterator2List(Iterator<? extends T> i, List<T> delegate) {
this.delegate = delegate;
while (i.hasNext()) {
delegate.add(i.next());
}
}
@Override
public void add(int index, T element) {
delegate.add(index, element);
}
@Override
public boolean addAll(int index, Collection<? extends T> c) {
return delegate.addAll(index, c);
}
@Override
public T get(int index) {
return delegate.get(index);
}
@Override
public int indexOf(Object o) {
return delegate.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return delegate.lastIndexOf(o);
}
@Override
public ListIterator<T> listIterator() {
return delegate.listIterator();
}
@Override
public ListIterator<T> listIterator(int index) {
return delegate.listIterator(index);
}
@Override
public T remove(int index) {
return delegate.remove(index);
}
@Override
public T set(int index, T element) {
return delegate.set(index, element);
}
@Override
public List<T> subList(int fromIndex, int toIndex) {
return delegate.subList(fromIndex, toIndex);
}
@Override
protected Collection<T> getDelegate() {
return delegate;
}
}
| 1,963
| 21.574713
| 95
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/Iterator2Set.java
|
/*
* Copyright (c) 2007 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.io.Serializable;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
public class Iterator2Set<T> extends Iterator2Collection<T> implements Serializable, Set<T> {
private static final long serialVersionUID = 3771468677527694694L;
private final Set<T> delegate;
protected Iterator2Set(Iterator<? extends T> i, Set<T> delegate) {
this.delegate = delegate;
while (i.hasNext()) {
delegate.add(i.next());
}
}
@Override
protected Collection<T> getDelegate() {
return delegate;
}
}
| 962
| 25.75
| 93
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/IteratorPlusOne.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import org.jspecify.annotations.Nullable;
/** A utility to efficiently compose an iterator and a singleton */
public class IteratorPlusOne<T> implements Iterator<T> {
public static <T> IteratorPlusOne<T> make(Iterator<? extends T> it, T xtra) {
if (it == null) {
throw new IllegalArgumentException("null it");
}
return new IteratorPlusOne<>(it, xtra);
}
private final Iterator<? extends T> it;
// the following field will be nulled out after visiting xtra.
@Nullable private T xtra;
private IteratorPlusOne(Iterator<? extends T> it, T xtra) {
this.it = it;
this.xtra = xtra;
}
@Override
public boolean hasNext() {
return it.hasNext() || (xtra != null);
}
@Nullable
@Override
public T next() {
if (it.hasNext()) {
return it.next();
} else {
T result = xtra;
xtra = null;
return result;
}
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
}
| 1,459
| 24.614035
| 79
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/IteratorPlusTwo.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import com.ibm.wala.util.debug.UnimplementedError;
import java.util.Iterator;
import org.jspecify.annotations.Nullable;
public class IteratorPlusTwo<T> implements Iterator<T> {
private final Iterator<T> it;
// the following fields will be nulled out after visiting xtra.
@Nullable private T xtra1;
@Nullable private T xtra2;
public IteratorPlusTwo(Iterator<T> it, T xtra1, T xtra2) {
if (it == null) {
throw new IllegalArgumentException("it null");
}
this.it = it;
this.xtra1 = xtra1;
this.xtra2 = xtra2;
}
@Override
public boolean hasNext() {
return it.hasNext() || (xtra1 != null) || (xtra2 != null);
}
@Nullable
@Override
public T next() {
if (it.hasNext()) {
return it.next();
} else if (xtra1 != null) {
T result = xtra1;
xtra1 = null;
return result;
} else {
T result = xtra2;
xtra2 = null;
return result;
}
}
@Override
public void remove() throws UnimplementedError {
throw new UnimplementedError();
}
}
| 1,456
| 23.694915
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/IteratorUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
/** utilities dealing with Iterators */
public class IteratorUtil {
/** @return true iff the Iterator returns some elements which equals() the object o */
public static <T> boolean contains(Iterator<? extends T> it, T o) {
if (it == null) {
throw new IllegalArgumentException("null it");
}
while (it.hasNext()) {
if (o.equals(it.next())) {
return true;
}
}
return false;
}
public static final <T> int count(Iterator<T> it) throws IllegalArgumentException {
if (it == null) {
throw new IllegalArgumentException("it == null");
}
int count = 0;
while (it.hasNext()) {
it.next();
count++;
}
return count;
}
public static <T, S extends T> Iterator<S> filter(Iterator<T> iterator, final Class<S> cls) {
return new MapIterator<>(new FilterIterator<>(iterator, cls::isInstance), cls::cast);
}
}
| 1,339
| 27.510638
| 95
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/MapIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.util.function.Function;
/** An {@code MapIterator} maps an {@code Iterator} contents to produce a new Iterator */
public class MapIterator<X, Y> implements Iterator<Y> {
final Iterator<? extends X> i;
final Function<X, Y> f;
public MapIterator(Iterator<? extends X> i, Function<X, Y> f) {
if (i == null) {
throw new IllegalArgumentException("null i");
}
this.i = i;
this.f = f;
}
@Override
public Y next() {
return f.apply(i.next());
}
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new java.lang.UnsupportedOperationException();
}
@Override
public String toString() {
return "map: " + f + " of " + i;
}
public static <X, Y> Iterator<Y> map(Function<X, Y> f, Iterator<X> i) {
return new MapIterator<>(i, f);
}
public static <X, Y> Set<Y> map(Function<X, Y> f, Collection<X> i) {
return Iterator2Collection.toSet(new MapIterator<>(i.iterator(), f));
}
}
| 1,541
| 24.7
| 89
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/MapUtil.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import com.ibm.wala.util.intset.MutableIntSet;
import com.ibm.wala.util.intset.MutableSparseIntSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
/** utilities for managing {@link Map}s */
public class MapUtil {
/**
* @param M a mapping from Object -> Set
* @return the Set corresponding to key in M; create one if needed
* @throws IllegalArgumentException if M is null
* @throws ClassCastException if the key is of an inappropriate type for this map (optional)
* @throws NullPointerException if the specified key is null and this map does not permit null
* keys (optional)
*/
public static <K, T> Set<T> findOrCreateSet(Map<K, Set<T>> M, K key) {
if (M == null) {
throw new IllegalArgumentException("M is null");
}
Set<T> result = M.get(key);
if (result == null) {
result = HashSetFactory.make(2);
M.put(key, result);
}
return result;
}
/**
* @throws ClassCastException if the key is of an inappropriate type for this map (optional)
* @throws NullPointerException if the specified key is null and this map does not permit null
* keys (optional)
*/
public static <K> MutableIntSet findOrCreateMutableIntSet(Map<K, MutableIntSet> M, K key) {
if (M == null) {
throw new IllegalArgumentException("M is null");
}
MutableIntSet mis = M.get(key);
if (mis == null) {
mis = MutableSparseIntSet.makeEmpty();
M.put(key, mis);
}
return mis;
}
/**
* @return the Collection corresponding to key in M; create one if needed
* @throws ClassCastException if the key is of an inappropriate type for this map (optional)
* @throws NullPointerException if the specified key is null and this map does not permit null
* keys (optional)
*/
public static <K, T> Collection<T> findOrCreateCollection(Map<K, Collection<T>> M, K key) {
if (M == null) {
throw new IllegalArgumentException("M is null");
}
Collection<T> result = M.get(key);
if (result == null) {
result = HashSetFactory.make(2);
M.put(key, result);
}
return result;
}
/**
* @return the Set corresponding to key in M; create one if needed
* @throws IllegalArgumentException if M is null
* @throws ClassCastException if the key is of an inappropriate type for this map (optional)
* @throws NullPointerException if the specified key is null and this map does not permit null
* keys (optional)
*/
public static <K, T> List<T> findOrCreateList(Map<K, List<T>> M, K key) {
if (M == null) {
throw new IllegalArgumentException("M is null");
}
if (!M.containsKey(key)) {
M.put(key, new ArrayList<>());
}
return M.get(key);
}
/**
* @param M a mapping from Object -> Map
* @return the Map corresponding to key in M; create one if needed
* @throws IllegalArgumentException if M is null
* @throws ClassCastException if the key is of an inappropriate type for this map (optional)
* @throws NullPointerException if the specified key is null and this map does not permit null
* keys (optional)
*/
public static <K, K2, V> Map<K2, V> findOrCreateMap(Map<K, Map<K2, V>> M, K key) {
if (M == null) {
throw new IllegalArgumentException("M is null");
}
Map<K2, V> result = M.get(key);
if (result == null) {
result = HashMapFactory.make(2);
M.put(key, result);
}
return result;
}
/**
* @throws ClassCastException if the key is of an inappropriate type for this map (optional)
* @throws NullPointerException if the specified key is null and this map does not permit null
* keys (optional)
*/
public static <K, V> V findOrCreateValue(Map<K, V> M, K key, Factory<V> factory) {
if (M == null) {
throw new IllegalArgumentException("M is null");
}
V result = M.get(key);
if (result == null) {
result = factory.make();
M.put(key, result);
}
return result;
}
/**
* @param M a mapping from Object -> WeakHashMap
* @return the WeakHashMap corresponding to key in M; create one if needed
* @throws IllegalArgumentException if M is null
* @throws ClassCastException if the key is of an inappropriate type for this map (optional)
* @throws NullPointerException if the specified key is null and this map does not permit null
* keys (optional)
*/
public static <K, V> WeakHashMap<K, V> findOrCreateWeakHashMap(
Map<Object, WeakHashMap<K, V>> M, Object key) {
if (M == null) {
throw new IllegalArgumentException("M is null");
}
WeakHashMap<K, V> result = M.computeIfAbsent(key, k -> new WeakHashMap<>(2));
return result;
}
/**
* @param m a map from key -> {@link Set}<value>
* @return inverted map, value -> {@link Set}<key>
* @throws IllegalArgumentException if m is null
*/
public static <K, V> Map<V, Set<K>> inverseMap(Map<K, Set<V>> m) {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
Map<V, Set<K>> result = HashMapFactory.make(m.size());
for (Map.Entry<K, Set<V>> E : m.entrySet()) {
K key = E.getKey();
Set<V> values = E.getValue();
for (V v : values) {
Set<K> s = findOrCreateSet(result, v);
s.add(key);
}
}
return result;
}
/**
* invert an input map that is one-to-one (i.e., it does not map two different keys to the same
* value)
*
* @throws IllegalArgumentException if m is null
* @throws IllegalArgumentException if m is not one-to-one
*/
public static <K, V> Map<V, K> invertOneToOneMap(Map<K, V> m) {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
Map<V, K> result = HashMapFactory.make(m.size());
for (Map.Entry<K, V> entry : m.entrySet()) {
K key = entry.getKey();
V val = entry.getValue();
if (result.containsKey(val)) {
throw new IllegalArgumentException("input map not one-to-one");
}
result.put(val, key);
}
return result;
}
public static <K, V> Map<Set<K>, V> groupKeysByValue(Map<K, V> m) {
if (m == null) {
throw new IllegalArgumentException("m is null");
}
Map<Set<K>, V> result = HashMapFactory.make();
Map<V, Set<K>> valueToKeys = HashMapFactory.make();
for (Map.Entry<K, V> E : m.entrySet()) {
K key = E.getKey();
V value = E.getValue();
findOrCreateSet(valueToKeys, value).add(key);
}
for (Map.Entry<V, Set<K>> E : valueToKeys.entrySet()) {
V value = E.getKey();
Set<K> keys = E.getValue();
result.put(keys, value);
}
return result;
}
}
| 7,190
| 32.760563
| 97
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/MultiMap.java
|
/*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html.
*
* This file is a derivative of code released by the University of
* California under the terms listed below.
*
* Refinement Analysis Tools is Copyright (c) 2007 The Regents of the
* University of California (Regents). Provided that this notice and
* the following two paragraphs are included in any distribution of
* Refinement Analysis Tools or its derivative work, Regents agrees
* not to assert any of Regents' copyright rights in Refinement
* Analysis Tools against recipient for recipient's reproduction,
* preparation of derivative works, public display, public
* performance, distribution or sublicensing of Refinement Analysis
* Tools and derivative works, in source code and object code form.
* This agreement not to assert does not confer, by implication,
* estoppel, or otherwise any license or rights in any intellectual
* property of Regents, including, but not limited to, any patents
* of Regents or Regents' employees.
*
* IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
* INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE
* AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY
* WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING
* DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
* IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
package com.ibm.wala.util.collections;
import java.util.Collection;
import java.util.Set;
public interface MultiMap<K, V> {
Set<V> get(K key);
boolean put(K key, V val);
boolean remove(K key, V val);
Set<K> keySet();
boolean containsKey(K key);
int size();
@Override
String toString();
boolean putAll(K key, Collection<? extends V> vals);
Set<V> removeAll(K key);
void clear();
boolean isEmpty();
}
| 2,354
| 33.632353
| 72
|
java
|
WALA
|
WALA-master/util/src/main/java/com/ibm/wala/util/collections/NonNullSingletonIterator.java
|
/*
* Copyright (c) 2002 - 2006 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*/
package com.ibm.wala.util.collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.jspecify.annotations.Nullable;
/**
* A singleton iterator for an object which is guaranteed to be not-null. Exploiting this invariant
* allows this class to be slightly more efficient than Collections.iterator()
*/
public class NonNullSingletonIterator<T> implements Iterator<T> {
@Nullable private T it;
/** @param o the single object in this collection, must be non-null */
public NonNullSingletonIterator(@Nullable T o) {
if (o == null) {
throw new IllegalArgumentException("o is null");
}
this.it = o;
}
@Override
public boolean hasNext() {
return it != null;
}
@Override
public T next() {
if (it == null) {
throw new NoSuchElementException();
} else {
T result = it;
it = null;
return result;
}
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException();
}
public static <T> NonNullSingletonIterator<T> make(T item) {
return new NonNullSingletonIterator<>(item);
}
}
| 1,527
| 25.344828
| 99
|
java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.