code
stringlengths 23
201k
| docstring
stringlengths 17
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
72
| path
stringlengths 11
317
| url
stringlengths 57
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
static @Nullable String describeActualValue(String className, String methodName, int lineNumber) {
InferenceClassVisitor visitor;
try {
// TODO(cpovirk): Verify that methodName is correct for constructors and static initializers.
visitor = new InferenceClassVisitor(methodName);
} catch (IllegalArgumentException theVersionOfAsmIsOlderThanWeRequire) {
// TODO(cpovirk): Consider what minimum version the class and method visitors really need.
// TODO(cpovirk): Log a warning?
return null;
}
ClassLoader loader =
firstNonNull(
currentThread().getContextClassLoader(), ActualValueInference.class.getClassLoader());
/*
* We're assuming that classes were loaded in a simple way. In principle, we could do better
* with java.lang.instrument.
*/
InputStream stream = null;
try {
stream = loader.getResourceAsStream(className.replace('.', '/') + ".class");
// TODO(cpovirk): Disable inference if the bytecode version is newer than we've tested on?
new ClassReader(stream).accept(visitor, /* parsingOptions= */ 0);
ImmutableSet<StackEntry> actualsAtLine = visitor.actualValueAtLine.build().get(lineNumber);
/*
* It's very unlikely that more than one assertion would happen on the same line _but with
* different root actual values_.
*
* That is, it's common to have:
* assertThat(list).containsExactly(...).inOrder();
*
* But it's not common to have, all on one line:
* assertThat(list).isEmpty(); assertThat(list2).containsExactly(...);
*
* In principle, we could try to distinguish further by looking at what assertion method
* failed (which our caller could pass us by looking higher on the stack). But it's hard to
* imagine that it would be worthwhile.
*/
return actualsAtLine.size() == 1 ? getOnlyElement(actualsAtLine).description() : null;
} catch (IOException e) {
/*
* Likely "Class not found," perhaps from generated bytecode (or from StackTraceCleaner's
* pseudo-frames, which ideally ActualValueInference would tell it not to create).
*/
// TODO(cpovirk): Log a warning?
return null;
} catch (SecurityException e) {
// Inside Google, some tests run under a security manager that forbids filesystem access.
// TODO(cpovirk): Log a warning?
return null;
} finally {
closeQuietly(stream);
}
}
|
<b>Call {@link Platform#inferDescription} rather than calling this directly.</b>
|
describeActualValue
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
boolean isSubject() {
return false;
}
|
An entry on the stack (or the local-variable table) with a {@linkplain InferredType type} and
sometimes a description of {@linkplain DescribedEntry how the value was produced} or, as a
special case, whether {@linkplain SubjectEntry the value is a Truth subject}.
|
isSubject
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
StackEntry actualValue() {
throw new ClassCastException(getClass().getName());
}
|
An entry on the stack (or the local-variable table) with a {@linkplain InferredType type} and
sometimes a description of {@linkplain DescribedEntry how the value was produced} or, as a
special case, whether {@linkplain SubjectEntry the value is a Truth subject}.
|
actualValue
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Nullable String description() {
return null;
}
|
An entry on the stack (or the local-variable table) with a {@linkplain InferredType type} and
sometimes a description of {@linkplain DescribedEntry how the value was produced} or, as a
special case, whether {@linkplain SubjectEntry the value is a Truth subject}.
|
description
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public final String toString() {
return "unknown";
}
|
An entry that we know nothing about except for its type.
|
toString
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static StackEntry opaque(InferredType type) {
return new AutoValue_ActualValueInference_OpaqueEntry(type);
}
|
An entry that we know nothing about except for its type.
|
opaque
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public final String toString() {
return description();
}
|
An entry that contains a description of how it was created. Currently, the only case in which
we provide a description is when the value comes from a method call whose name looks
"interesting."
|
toString
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static StackEntry described(InferredType type, String description) {
return new AutoValue_ActualValueInference_DescribedEntry(type, description);
}
|
An entry that contains a description of how it was created. Currently, the only case in which
we provide a description is when the value comes from a method call whose name looks
"interesting."
|
described
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
final boolean isSubject() {
return true;
}
|
An entry for a {@link Subject} (or a similar object derived with a {@code Subject}, like {@link
Ordered}).
<p>The entry contains the "root actual value" of the assertion. In an assertion like {@code
assertThat(e).hasMessageThat().contains("foo")}, the root actual value is the {@code Throwable}
{@code e}, even though the {@code contains} assertion operates on a string message.
|
isSubject
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public final String toString() {
return String.format("subjectFor(%s)", actualValue());
}
|
An entry for a {@link Subject} (or a similar object derived with a {@code Subject}, like {@link
Ordered}).
<p>The entry contains the "root actual value" of the assertion. In an assertion like {@code
assertThat(e).hasMessageThat().contains("foo")}, the root actual value is the {@code Throwable}
{@code e}, even though the {@code contains} assertion operates on a string message.
|
toString
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static StackEntry subjectFor(InferredType type, StackEntry actual) {
return new AutoValue_ActualValueInference_SubjectEntry(type, actual);
}
|
An entry for a {@link Subject} (or a similar object derived with a {@code Subject}, like {@link
Ordered}).
<p>The entry contains the "root actual value" of the assertion. In an assertion like {@code
assertThat(e).hasMessageThat().contains("foo")}, the root actual value is the {@code Throwable}
{@code e}, even though the {@code contains} assertion operates on a string message.
|
subjectFor
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitCode() {
checkState(!used, "Cannot reuse this method visitor.");
used = true;
super.visitCode();
}
|
The output of this process: a mapping from line number to the root actual values with
assertions on that line. This builder is potentially shared across multiple method visitors
for the same class visitor.
|
visitCode
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitEnd() {
if (seenJump) {
/*
* If there are multiple paths through a method, we'd have to examine them all and make sure
* that the values still match up. We could try someday, but it's hard.
*/
super.visitEnd();
return;
}
ImmutableSetMultimap<Label, Integer> lineNumbersAtLabel = this.lineNumbersAtLabel.build();
for (Entry<ImmutableList<Label>, StackEntry> e : actualValueAtLocation.build().entries()) {
for (int lineNumber : lineNumbers(e.getKey(), lineNumbersAtLabel)) {
actualValueAtLine.put(lineNumber, e.getValue());
}
}
super.visitEnd();
}
|
The output of this process: a mapping from line number to the root actual values with
assertions on that line. This builder is potentially shared across multiple method visitors
for the same class visitor.
|
visitEnd
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static ImmutableSet<Integer> lineNumbers(
ImmutableList<Label> labels, ImmutableSetMultimap<Label, Integer> lineNumbersAtLabel) {
for (Label label : labels.reverse()) {
if (lineNumbersAtLabel.containsKey(label)) {
return lineNumbersAtLabel.get(label);
}
}
return ImmutableSet.of();
}
|
The output of this process: a mapping from line number to the root actual values with
assertions on that line. This builder is potentially shared across multiple method visitors
for the same class visitor.
|
lineNumbers
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitLineNumber(int line, Label start) {
lineNumbersAtLabel.put(start, line);
super.visitLineNumber(line, start);
}
|
The output of this process: a mapping from line number to the root actual values with
assertions on that line. This builder is potentially shared across multiple method visitors
for the same class visitor.
|
visitLineNumber
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitLabel(Label label) {
labelsSeen.add(label);
super.visitLabel(label);
}
|
The output of this process: a mapping from line number to the root actual values with
assertions on that line. This builder is potentially shared across multiple method visitors
for the same class visitor.
|
visitLabel
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private StackEntry getOperandFromTop(int offsetFromTop) {
int index = operandStack.size() - 1 - offsetFromTop;
checkState(
index >= 0,
"Invalid offset %s in the list of size %s. The current method is %s",
offsetFromTop,
operandStack.size(),
methodSignature);
return operandStack.get(index);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
getOperandFromTop
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.NOP:
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
case Opcodes.RETURN:
break;
case Opcodes.ACONST_NULL:
push(InferredType.NULL);
break;
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
push(InferredType.INT);
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
push(InferredType.LONG);
push(InferredType.TOP);
break;
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
push(InferredType.FLOAT);
break;
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
push(InferredType.DOUBLE);
push(InferredType.TOP);
break;
case Opcodes.IALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
pop(2);
push(InferredType.INT);
break;
case Opcodes.LALOAD:
case Opcodes.D2L:
pop(2);
push(InferredType.LONG);
push(InferredType.TOP);
break;
case Opcodes.DALOAD:
case Opcodes.L2D:
pop(2);
push(InferredType.DOUBLE);
push(InferredType.TOP);
break;
case Opcodes.AALOAD:
InferredType arrayType = pop(2).type();
InferredType elementType = arrayType.getElementTypeIfArrayOrThrow();
push(elementType);
break;
case Opcodes.IASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
case Opcodes.FASTORE:
case Opcodes.AASTORE:
pop(3);
break;
case Opcodes.LASTORE:
case Opcodes.DASTORE:
pop(4);
break;
case Opcodes.POP:
case Opcodes.IRETURN:
case Opcodes.FRETURN:
case Opcodes.ARETURN:
case Opcodes.ATHROW:
case Opcodes.MONITORENTER:
case Opcodes.MONITOREXIT:
pop();
break;
case Opcodes.POP2:
case Opcodes.LRETURN:
case Opcodes.DRETURN:
pop(2);
break;
case Opcodes.DUP:
push(top());
break;
case Opcodes.DUP_X1:
{
StackEntry top = pop();
StackEntry next = pop();
push(top);
push(next);
push(top);
break;
}
case Opcodes.DUP_X2:
{
StackEntry top = pop();
StackEntry next = pop();
StackEntry bottom = pop();
push(top);
push(bottom);
push(next);
push(top);
break;
}
case Opcodes.DUP2:
{
StackEntry top = pop();
StackEntry next = pop();
push(next);
push(top);
push(next);
push(top);
break;
}
case Opcodes.DUP2_X1:
{
StackEntry top = pop();
StackEntry next = pop();
StackEntry bottom = pop();
push(next);
push(top);
push(bottom);
push(next);
push(top);
break;
}
case Opcodes.DUP2_X2:
{
StackEntry t1 = pop();
StackEntry t2 = pop();
StackEntry t3 = pop();
StackEntry t4 = pop();
push(t2);
push(t1);
push(t4);
push(t3);
push(t2);
push(t1);
break;
}
case Opcodes.SWAP:
{
StackEntry top = pop();
StackEntry next = pop();
push(top);
push(next);
break;
}
case Opcodes.IADD:
case Opcodes.ISUB:
case Opcodes.IMUL:
case Opcodes.IDIV:
case Opcodes.IREM:
case Opcodes.ISHL:
case Opcodes.ISHR:
case Opcodes.IUSHR:
case Opcodes.IAND:
case Opcodes.IOR:
case Opcodes.IXOR:
case Opcodes.L2I:
case Opcodes.D2I:
case Opcodes.FCMPL:
case Opcodes.FCMPG:
pop(2);
push(InferredType.INT);
break;
case Opcodes.LADD:
case Opcodes.LSUB:
case Opcodes.LMUL:
case Opcodes.LDIV:
case Opcodes.LREM:
case Opcodes.LAND:
case Opcodes.LOR:
case Opcodes.LXOR:
pop(4);
push(InferredType.LONG);
push(InferredType.TOP);
break;
case Opcodes.LSHL:
case Opcodes.LSHR:
case Opcodes.LUSHR:
pop(3);
push(InferredType.LONG);
push(InferredType.TOP);
break;
case Opcodes.I2L:
case Opcodes.F2L:
pop();
push(InferredType.LONG);
push(InferredType.TOP);
break;
case Opcodes.I2F:
pop();
push(InferredType.FLOAT);
break;
case Opcodes.LCMP:
case Opcodes.DCMPG:
case Opcodes.DCMPL:
pop(4);
push(InferredType.INT);
break;
case Opcodes.I2D:
case Opcodes.F2D:
pop();
push(InferredType.DOUBLE);
push(InferredType.TOP);
break;
case Opcodes.F2I:
case Opcodes.ARRAYLENGTH:
pop();
push(InferredType.INT);
break;
case Opcodes.FALOAD:
case Opcodes.FADD:
case Opcodes.FSUB:
case Opcodes.FMUL:
case Opcodes.FDIV:
case Opcodes.FREM:
case Opcodes.L2F:
case Opcodes.D2F:
pop(2);
push(InferredType.FLOAT);
break;
case Opcodes.DADD:
case Opcodes.DSUB:
case Opcodes.DMUL:
case Opcodes.DDIV:
case Opcodes.DREM:
pop(4);
push(InferredType.DOUBLE);
push(InferredType.TOP);
break;
default:
throw new RuntimeException("Unhandled opcode " + opcode);
}
super.visitInsn(opcode);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitIntInsn(int opcode, int operand) {
switch (opcode) {
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
push(InferredType.INT);
break;
case Opcodes.NEWARRAY:
pop();
switch (operand) {
case Opcodes.T_BOOLEAN:
pushDescriptor("[Z");
break;
case Opcodes.T_CHAR:
pushDescriptor("[C");
break;
case Opcodes.T_FLOAT:
pushDescriptor("[F");
break;
case Opcodes.T_DOUBLE:
pushDescriptor("[D");
break;
case Opcodes.T_BYTE:
pushDescriptor("[B");
break;
case Opcodes.T_SHORT:
pushDescriptor("[S");
break;
case Opcodes.T_INT:
pushDescriptor("[I");
break;
case Opcodes.T_LONG:
pushDescriptor("[J");
break;
default:
throw new RuntimeException("Unhandled operand value: " + operand);
}
break;
default:
throw new RuntimeException("Unhandled opcode " + opcode);
}
super.visitIntInsn(opcode, operand);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitIntInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitVarInsn(int opcode, int var) {
switch (opcode) {
case Opcodes.ILOAD:
push(InferredType.INT);
break;
case Opcodes.LLOAD:
push(InferredType.LONG);
push(InferredType.TOP);
break;
case Opcodes.FLOAD:
push(InferredType.FLOAT);
break;
case Opcodes.DLOAD:
push(InferredType.DOUBLE);
push(InferredType.TOP);
break;
case Opcodes.ALOAD:
push(getLocalVariable(var));
break;
case Opcodes.ISTORE:
case Opcodes.FSTORE:
case Opcodes.ASTORE:
{
StackEntry entry = pop();
setLocalVariable(var, entry);
break;
}
case Opcodes.LSTORE:
case Opcodes.DSTORE:
{
StackEntry entry = pop(2);
setLocalVariable(var, entry);
setLocalVariable(var + 1, opaque(InferredType.TOP));
break;
}
case Opcodes.RET:
throw new RuntimeException("The instruction RET is not supported");
default:
throw new RuntimeException("Unhandled opcode " + opcode);
}
super.visitVarInsn(opcode, var);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitVarInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitTypeInsn(int opcode, String type) {
String descriptor = convertToDescriptor(type);
switch (opcode) {
case Opcodes.NEW:
// This should be UNINITIALIZED(label). Okay for type inference.
pushDescriptor(descriptor);
break;
case Opcodes.ANEWARRAY:
pop();
pushDescriptor('[' + descriptor);
break;
case Opcodes.CHECKCAST:
pop();
pushDescriptor(descriptor);
break;
case Opcodes.INSTANCEOF:
pop();
push(InferredType.INT);
break;
default:
throw new RuntimeException("Unhandled opcode " + opcode);
}
super.visitTypeInsn(opcode, type);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitTypeInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
switch (opcode) {
case Opcodes.GETSTATIC:
pushDescriptor(desc);
break;
case Opcodes.PUTSTATIC:
popDescriptor(desc);
break;
case Opcodes.GETFIELD:
pop();
pushDescriptor(desc);
break;
case Opcodes.PUTFIELD:
popDescriptor(desc);
pop();
break;
default:
throw new RuntimeException(
"Unhandled opcode "
+ opcode
+ ", owner="
+ owner
+ ", name="
+ name
+ ", desc"
+ desc);
}
super.visitFieldInsn(opcode, owner, name, desc);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitFieldInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
if (opcode == Opcodes.INVOKESPECIAL && name.equals("<init>")) {
int argumentSize = (Type.getArgumentsAndReturnSizes(desc) >> 2);
InferredType receiverType = getOperandFromTop(argumentSize - 1).type();
if (receiverType.isUninitialized()) {
InferredType realType = InferredType.create('L' + owner + ';');
replaceUninitializedTypeInStack(receiverType, realType);
}
}
switch (opcode) {
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESTATIC:
case Opcodes.INVOKEINTERFACE:
Invocation.Builder invocation = Invocation.builder(name);
if (isThatOrAssertThat(owner, name)) {
invocation.setActualValue(getOperandFromTop(0));
} else if (isBoxing(owner, name, desc)) {
invocation.setBoxingInput(
// double and long are represented by a TOP with the "real" value under it.
getOperandFromTop(0).type() == InferredType.TOP
? getOperandFromTop(1)
: getOperandFromTop(0));
}
popDescriptor(desc);
if (opcode != Opcodes.INVOKESTATIC) {
invocation.setReceiver(pop());
}
pushDescriptorAndMaybeProcessMethodCall(desc, invocation.build());
break;
default:
throw new RuntimeException(
String.format(
"Unhandled opcode %s, owner=%s, name=%s, desc=%s, itf=%s",
opcode, owner, name, desc, itf));
}
super.visitMethodInsn(opcode, owner, name, desc, itf);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitMethodInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitInvokeDynamicInsn(String name, String desc, Handle bsm, Object... bsmArgs) {
popDescriptor(desc);
pushDescriptor(desc);
super.visitInvokeDynamicInsn(name, desc, bsm, bsmArgs);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitInvokeDynamicInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitJumpInsn(int opcode, Label label) {
seenJump = true;
switch (opcode) {
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
pop();
break;
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
pop(2);
break;
case Opcodes.GOTO:
break;
case Opcodes.JSR:
throw new RuntimeException("The JSR instruction is not supported.");
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
pop(1);
break;
default:
throw new RuntimeException("Unhandled opcode " + opcode);
}
super.visitJumpInsn(opcode, label);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitJumpInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitLdcInsn(Object cst) {
if (cst instanceof Integer) {
push(InferredType.INT);
} else if (cst instanceof Float) {
push(InferredType.FLOAT);
} else if (cst instanceof Long) {
push(InferredType.LONG);
push(InferredType.TOP);
} else if (cst instanceof Double) {
push(InferredType.DOUBLE);
push(InferredType.TOP);
} else if (cst instanceof String) {
pushDescriptor("Ljava/lang/String;");
} else if (cst instanceof Type) {
pushDescriptor(((Type) cst).getDescriptor());
} else if (cst instanceof Handle) {
pushDescriptor("Ljava/lang/invoke/MethodHandle;");
} else {
throw new RuntimeException("Cannot handle constant " + cst + " for LDC instruction");
}
super.visitLdcInsn(cst);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitLdcInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitIincInsn(int var, int increment) {
setLocalVariable(var, opaque(InferredType.INT));
super.visitIincInsn(var, increment);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitIincInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitTableSwitchInsn(int min, int max, Label dflt, Label... labels) {
seenJump = true;
pop();
super.visitTableSwitchInsn(min, max, dflt, labels);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitTableSwitchInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitLookupSwitchInsn(Label dflt, int[] keys, Label[] labels) {
seenJump = true;
pop();
super.visitLookupSwitchInsn(dflt, keys, labels);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitLookupSwitchInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitTryCatchBlock(Label start, Label end, Label handler, String type) {
/*
* Inference already fails for at least some try-catch blocks, apparently because of the extra
* frames they create. Still, let's disable inference explicitly.
*/
seenJump = true;
super.visitTryCatchBlock(start, end, handler, type);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitTryCatchBlock
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitMultiANewArrayInsn(String desc, int dims) {
pop(dims);
pushDescriptor(desc);
super.visitMultiANewArrayInsn(desc, dims);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitMultiANewArrayInsn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) {
switch (type) {
case Opcodes.F_NEW:
// Expanded form.
previousFrame =
FrameInfo.create(
convertTypesInStackMapFrame(nLocal, local),
convertTypesInStackMapFrame(nStack, stack));
break;
case Opcodes.F_SAME:
// This frame type indicates that the frame has exactly the same local variables as the
// previous frame and that the operand stack is empty.
previousFrame = FrameInfo.create(previousFrame.locals(), ImmutableList.<StackEntry>of());
break;
case Opcodes.F_SAME1:
// This frame type indicates that the frame has exactly the same local variables as the
// previous frame and that the operand stack has one entry.
previousFrame =
FrameInfo.create(previousFrame.locals(), convertTypesInStackMapFrame(nStack, stack));
break;
case Opcodes.F_APPEND:
// This frame type indicates that the frame has the same locals as the previous frame
// except that k additional locals are defined, and that the operand stack is empty.
previousFrame =
FrameInfo.create(
appendArrayToList(previousFrame.locals(), nLocal, local),
ImmutableList.<StackEntry>of());
break;
case Opcodes.F_CHOP:
// This frame type indicates that the frame has the same local variables as the previous
// frame except that the last k local variables are absent, and that the operand stack is
// empty.
previousFrame =
FrameInfo.create(
removeBackFromList(previousFrame.locals(), nLocal),
ImmutableList.<StackEntry>of());
break;
case Opcodes.F_FULL:
previousFrame =
FrameInfo.create(
convertTypesInStackMapFrame(nLocal, local),
convertTypesInStackMapFrame(nStack, stack));
break;
default:
// continue below
}
// Update types for operand stack and local variables.
operandStack.clear();
operandStack.addAll(previousFrame.stack());
localVariableSlots.clear();
localVariableSlots.addAll(previousFrame.locals());
super.visitFrame(type, nLocal, local, nStack, stack);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
visitFrame
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static String convertToDescriptor(String type) {
return (type.length() > 1 && type.charAt(0) != '[') ? 'L' + type + ';' : type;
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
convertToDescriptor
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private void replaceUninitializedTypeInStack(InferredType oldType, InferredType newType) {
checkArgument(oldType.isUninitialized(), "The old type is NOT uninitialized. %s", oldType);
for (int i = 0, size = operandStack.size(); i < size; ++i) {
InferredType type = operandStack.get(i).type();
if (type.equals(oldType)) {
operandStack.set(i, opaque(newType));
}
}
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
replaceUninitializedTypeInStack
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private void pushDescriptor(String desc) {
pushDescriptorAndMaybeProcessMethodCall(desc, /* invocation= */ null);
}
|
Returns the entry for the operand at the specified offset. 0 means the top of the stack.
|
pushDescriptor
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private void pushDescriptorAndMaybeProcessMethodCall(
String desc, @Nullable Invocation invocation) {
if (invocation != null && invocation.isOnSubjectInstance()) {
actualValueAtLocation.put(
labelsSeen.build(), checkNotNull(invocation.receiver()).actualValue());
}
boolean hasParams = invocation != null && (Type.getArgumentsAndReturnSizes(desc) >> 2) > 1;
int index = desc.charAt(0) == '(' ? desc.indexOf(')') + 1 : 0;
switch (desc.charAt(index)) {
case 'V':
return;
case 'Z':
case 'C':
case 'B':
case 'S':
case 'I':
pushMaybeDescribed(InferredType.INT, invocation, hasParams);
break;
case 'F':
pushMaybeDescribed(InferredType.FLOAT, invocation, hasParams);
break;
case 'D':
pushMaybeDescribed(InferredType.DOUBLE, invocation, hasParams);
push(InferredType.TOP);
break;
case 'J':
pushMaybeDescribed(InferredType.LONG, invocation, hasParams);
push(InferredType.TOP);
break;
case 'L':
case '[':
pushMaybeDescribed(InferredType.create(desc.substring(index)), invocation, hasParams);
break;
default:
throw new RuntimeException("Unhandled type: " + desc);
}
}
|
Pushes entries onto the stack for the given arguments, and, if the descriptor is for a method
call, records the assertion made by that call (if any).
<p>If the descriptor is for a call, this method not only records the assertion made by it (if
any) but also examines its parameters to generate more detailed stack entries.
@param desc the descriptor of the type to be added to the stack (or the descriptor of the
method whose return value is to be added to the stack)
@param invocation the method invocation being visited, or {@code null} if a non-method
descriptor is being visited
|
pushDescriptorAndMaybeProcessMethodCall
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private void pushMaybeDescribed(
InferredType type, @Nullable Invocation invocation, boolean hasParams) {
push(invocation == null ? opaque(type) : invocation.deriveEntry(type, hasParams));
}
|
Pushes entries onto the stack for the given arguments, and, if the descriptor is for a method
call, records the assertion made by that call (if any).
<p>If the descriptor is for a call, this method not only records the assertion made by it (if
any) but also examines its parameters to generate more detailed stack entries.
@param desc the descriptor of the type to be added to the stack (or the descriptor of the
method whose return value is to be added to the stack)
@param invocation the method invocation being visited, or {@code null} if a non-method
descriptor is being visited
|
pushMaybeDescribed
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@CanIgnoreReturnValue
private StackEntry pop() {
return pop(1);
}
|
Pushes entries onto the stack for the given arguments, and, if the descriptor is for a method
call, records the assertion made by that call (if any).
<p>If the descriptor is for a call, this method not only records the assertion made by it (if
any) but also examines its parameters to generate more detailed stack entries.
@param desc the descriptor of the type to be added to the stack (or the descriptor of the
method whose return value is to be added to the stack)
@param invocation the method invocation being visited, or {@code null} if a non-method
descriptor is being visited
|
pop
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@CanIgnoreReturnValue
private StackEntry pop(int count) {
checkArgument(
count >= 1, "The count should be at least one: %s (In %s)", count, methodSignature);
checkState(
operandStack.size() >= count,
"There are no enough elements in the stack. count=%s, stack=%s (In %s)",
count,
operandStack,
methodSignature);
int expectedLastIndex = operandStack.size() - count - 1;
StackEntry lastPopped;
do {
lastPopped = operandStack.remove(operandStack.size() - 1);
} while (operandStack.size() - 1 > expectedLastIndex);
return lastPopped;
}
|
Pop elements from the end of the operand stack, and return the last popped element.
|
pop
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private void popDescriptor(String desc) {
char c = desc.charAt(0);
switch (c) {
case '(':
int argumentSize = (Type.getArgumentsAndReturnSizes(desc) >> 2) - 1;
if (argumentSize > 0) {
pop(argumentSize);
}
break;
case 'J':
case 'D':
pop(2);
break;
default:
pop(1);
break;
}
}
|
Pop elements from the end of the operand stack, and return the last popped element.
|
popDescriptor
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private StackEntry getLocalVariable(int index) {
checkState(
index < localVariableSlots.size(),
"Cannot find type for var %s in method %s",
index,
methodSignature);
return localVariableSlots.get(index);
}
|
Pop elements from the end of the operand stack, and return the last popped element.
|
getLocalVariable
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private void setLocalVariable(int index, StackEntry entry) {
while (localVariableSlots.size() <= index) {
localVariableSlots.add(opaque(InferredType.TOP));
}
localVariableSlots.set(index, entry);
}
|
Pop elements from the end of the operand stack, and return the last popped element.
|
setLocalVariable
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private StackEntry top() {
return Iterables.getLast(operandStack);
}
|
Pop elements from the end of the operand stack, and return the last popped element.
|
top
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static ArrayList<StackEntry> createInitialLocalVariableSlots(
int access, String ownerClass, String methodName, String methodDescriptor) {
ArrayList<StackEntry> entries = new ArrayList<>();
if (!isStatic(access)) {
// Instance method, and this is the receiver
entries.add(opaque(InferredType.create(convertToDescriptor(ownerClass))));
}
Type[] argumentTypes = Type.getArgumentTypes(methodDescriptor);
for (Type argumentType : argumentTypes) {
switch (argumentType.getSort()) {
case Type.BOOLEAN:
case Type.BYTE:
case Type.CHAR:
case Type.SHORT:
case Type.INT:
entries.add(opaque(InferredType.INT));
break;
case Type.FLOAT:
entries.add(opaque(InferredType.FLOAT));
break;
case Type.LONG:
entries.add(opaque(InferredType.LONG));
entries.add(opaque(InferredType.TOP));
break;
case Type.DOUBLE:
entries.add(opaque(InferredType.DOUBLE));
entries.add(opaque(InferredType.TOP));
break;
case Type.ARRAY:
case Type.OBJECT:
entries.add(opaque(InferredType.create(argumentType.getDescriptor())));
break;
default:
throw new RuntimeException(
"Unhandled argument type: "
+ argumentType
+ " in "
+ ownerClass
+ "."
+ methodName
+ methodDescriptor);
}
}
return entries;
}
|
Create the slots for local variables at the very beginning of the method with the information
of the declaring class and the method descriptor.
|
createInitialLocalVariableSlots
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static ImmutableList<StackEntry> removeBackFromList(
ImmutableList<StackEntry> list, int countToRemove) {
int origSize = list.size();
int index = origSize - 1;
while (index >= 0 && countToRemove > 0) {
InferredType type = list.get(index).type();
if (type.equals(InferredType.TOP)
&& index > 0
&& list.get(index - 1).type().isCategory2()) {
--index; // A category 2 takes two slots.
}
--index; // Eat this local variable.
--countToRemove;
}
checkState(
countToRemove == 0,
"countToRemove is %s but not 0. index=%s, list=%s",
countToRemove,
index,
list);
return list.subList(0, index + 1);
}
|
Create the slots for local variables at the very beginning of the method with the information
of the declaring class and the method descriptor.
|
removeBackFromList
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private ImmutableList<StackEntry> appendArrayToList(
ImmutableList<StackEntry> list, int size, Object[] array) {
ImmutableList.Builder<StackEntry> builder = ImmutableList.builder();
builder.addAll(list);
for (int i = 0; i < size; ++i) {
InferredType type = convertTypeInStackMapFrame(array[i]);
builder.add(opaque(type));
if (type.isCategory2()) {
builder.add(opaque(InferredType.TOP));
}
}
return builder.build();
}
|
Create the slots for local variables at the very beginning of the method with the information
of the declaring class and the method descriptor.
|
appendArrayToList
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private InferredType convertTypeInStackMapFrame(Object typeInStackMapFrame) {
if (typeInStackMapFrame == Opcodes.TOP) {
return InferredType.TOP;
} else if (typeInStackMapFrame == Opcodes.INTEGER) {
return InferredType.INT;
} else if (typeInStackMapFrame == Opcodes.FLOAT) {
return InferredType.FLOAT;
} else if (typeInStackMapFrame == Opcodes.DOUBLE) {
return InferredType.DOUBLE;
} else if (typeInStackMapFrame == Opcodes.LONG) {
return InferredType.LONG;
} else if (typeInStackMapFrame == Opcodes.NULL) {
return InferredType.NULL;
} else if (typeInStackMapFrame == Opcodes.UNINITIALIZED_THIS) {
return InferredType.UNINITIALIZED_THIS;
} else if (typeInStackMapFrame instanceof String) {
String referenceTypeName = (String) typeInStackMapFrame;
if (referenceTypeName.charAt(0) == '[') {
return InferredType.create(referenceTypeName);
} else {
return InferredType.create('L' + referenceTypeName + ';');
}
} else if (typeInStackMapFrame instanceof Label) {
return InferredType.UNINITIALIZED;
} else {
throw new RuntimeException(
"Cannot reach here. Unhandled element: value="
+ typeInStackMapFrame
+ ", class="
+ typeInStackMapFrame.getClass()
+ ". The current method being desugared is "
+ methodSignature);
}
}
|
Convert the type in stack map frame to inference type.
|
convertTypeInStackMapFrame
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private ImmutableList<StackEntry> convertTypesInStackMapFrame(int size, Object[] array) {
ImmutableList.Builder<StackEntry> builder = ImmutableList.builder();
for (int i = 0; i < size; ++i) {
InferredType type = convertTypeInStackMapFrame(array[i]);
builder.add(opaque(type));
if (type.isCategory2()) {
builder.add(opaque(InferredType.TOP));
}
}
return builder.build();
}
|
Convert the type in stack map frame to inference type.
|
convertTypesInStackMapFrame
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
final StackEntry deriveEntry(InferredType type, boolean hasParams) {
if (boxingInput() != null && boxingInput().description() != null) {
return described(type, boxingInput().description());
} else if (actualValue() != null) {
return subjectFor(type, actualValue());
} else if (isOnSubjectInstance()) {
return subjectFor(type, checkNotNull(receiver()).actualValue());
} else if (BORING_NAMES.contains(name())) {
/*
* TODO(cpovirk): For no-arg instance methods like get(), return "foo.get()," where "foo" is
* the description we had for the receiver (if any).
*/
return opaque(type);
} else {
return described(type, name() + (hasParams ? "(...)" : "()"));
}
}
|
The value being passed to this call if it is a boxing call (e.g., {@code Integer.valueOf}).
|
deriveEntry
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
final boolean isOnSubjectInstance() {
return receiver() != null && receiver().isSubject();
}
|
The value being passed to this call if it is a boxing call (e.g., {@code Integer.valueOf}).
|
isOnSubjectInstance
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
InferredType getElementTypeIfArrayOrThrow() {
String descriptor = descriptor();
checkState(descriptor.charAt(0) == '[', "This type %s is not an array.", this);
return create(descriptor.substring(1));
}
|
If the type is an array, return the element type. Otherwise, throw an exception.
|
getElementTypeIfArrayOrThrow
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public void visit(
int version,
int access,
String name,
String signature,
String superName,
String[] interfaces) {
className = name;
}
|
The method to visit.
<p>We don't really <i>need</i> the method name: We could just visit the whole class, since we
look at data for only the relevant line. But it's nice not to process the whole class,
especially during debugging. (And it might also help avoid triggering any bugs in the
inference code.)
|
visit
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
@Override
public @Nullable MethodVisitor visitMethod(
int access, String name, String desc, String signature, String[] exceptions) {
/*
* Each InferenceMethodVisitor instance may be used only once. Still, it might seem like we
* can get away with creating a single instance at construction time. However, we know only
* the name of the method that we're visiting, not its full signature, so we may need to visit
* multiple methods with that name, each with a fresh visitor.
*/
return methodNameToVisit.equals(name)
? new InferenceMethodVisitor(access, className, name, desc, actualValueAtLine)
: null;
}
|
The method to visit.
<p>We don't really <i>need</i> the method name: We could just visit the whole class, since we
look at data for only the relevant line. But it's nice not to process the whole class,
especially during debugging. (And it might also help avoid triggering any bugs in the
inference code.)
|
visitMethod
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static boolean isThatOrAssertThat(String owner, String name) {
/*
* TODO(cpovirk): Handle CustomSubjectBuilder. That requires looking at the type hierarchy, as
* users always have an instance of a specific subtype. Also keep in mind that the that(...)
* method might accept more than 1 parameter, like `that(className, methodName)` and/or that it
* might have category-2 parameters.
*
* TODO(cpovirk): Handle custom assertThat methods. The challenges are similar.
*/
return (owner.equals("com/google/common/truth/Truth") && name.equals("assertThat"))
|| (owner.equals("com/google/common/truth/StandardSubjectBuilder") && name.equals("that"))
|| (owner.equals("com/google/common/truth/SimpleSubjectBuilder") && name.equals("that"))
|| (owner.equals("com/google/common/truth/Expect") && name.equals("that"));
}
|
The method to visit.
<p>We don't really <i>need</i> the method name: We could just visit the whole class, since we
look at data for only the relevant line. But it's nice not to process the whole class,
especially during debugging. (And it might also help avoid triggering any bugs in the
inference code.)
|
isThatOrAssertThat
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static boolean isBoxing(String owner, String name, String desc) {
return name.equals("valueOf")
&& PRIMITIVE_WRAPPERS.contains(owner)
/*
* Don't handle valueOf(String s[, int radix]). The valueOf support is really here for
* autoboxing, as in "assertThat(primitive)," not for
* "assertThat(Integer.valueOf(...))." Not that there's anything really *wrong* with
* handling manual boxing of primitives -- good thing, since we can't distinguish the two --
* but we're not interested in handling the valueOf methods that *parse*. That's mainly
* because there's a type conversion, so some assertions might succeed on a string and fail
* on the parsed number (or vice versa).
*/
&& !Type.getArgumentTypes(desc)[0].equals(Type.getType(String.class));
}
|
The method to visit.
<p>We don't really <i>need</i> the method name: We could just visit the whole class, since we
look at data for only the relevant line. But it's nice not to process the whole class,
especially during debugging. (And it might also help avoid triggering any bugs in the
inference code.)
|
isBoxing
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static boolean isStatic(int access) {
return isSet(access, Opcodes.ACC_STATIC);
}
|
The method to visit.
<p>We don't really <i>need</i> the method name: We could just visit the whole class, since we
look at data for only the relevant line. But it's nice not to process the whole class,
especially during debugging. (And it might also help avoid triggering any bugs in the
inference code.)
|
isStatic
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static boolean isSet(int flags, int bitmask) {
return (flags & bitmask) == bitmask;
}
|
Returns {@code true} iff <b>all</b> bits in {@code bitmask} are set in {@code flags}. Trivially
returns {@code true} if {@code bitmask} is 0.
|
isSet
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
private static void closeQuietly(@Nullable InputStream stream) {
if (stream == null) {
return;
}
try {
stream.close();
} catch (IOException e) {
// TODO(cpovirk): Log a warning?
}
}
|
Returns {@code true} iff <b>all</b> bits in {@code bitmask} are set in {@code flags}. Trivially
returns {@code true} if {@code bitmask} is 0.
|
closeQuietly
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ActualValueInference.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ActualValueInference.java
|
Apache-2.0
|
static AssertionErrorWithFacts create(
ImmutableList<String> messages, ImmutableList<Fact> facts, @Nullable Throwable cause) {
return new AssertionErrorWithFacts(messages, facts, cause);
}
|
An {@link AssertionError} composed of structured {@link Fact} instances and other string
messages.
|
create
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
Apache-2.0
|
static AssertionError createWithoutFacts(String message, @Nullable Throwable cause) {
return create(ImmutableList.of(message), ImmutableList.of(), cause);
}
|
An {@link AssertionError} composed of structured {@link Fact} instances and other string
messages.
|
createWithoutFacts
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
Apache-2.0
|
static AssertionError createWithoutFactsOrStack(String message, @Nullable Throwable cause) {
AssertionError error = createWithoutFacts(message, cause);
error.setStackTrace(new StackTraceElement[0]);
return error;
}
|
An {@link AssertionError} composed of structured {@link Fact} instances and other string
messages.
|
createWithoutFactsOrStack
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
Apache-2.0
|
static AssertionError createWithoutFactsOrStack(String message) {
return createWithoutFactsOrStack(message, /* cause= */ null);
}
|
An {@link AssertionError} composed of structured {@link Fact} instances and other string
messages.
|
createWithoutFactsOrStack
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
Apache-2.0
|
@Override
public String toString() {
return checkNotNull(getLocalizedMessage());
}
|
An {@link AssertionError} composed of structured {@link Fact} instances and other string
messages.
|
toString
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
Apache-2.0
|
@Override
public ImmutableList<Fact> facts() {
return facts;
}
|
An {@link AssertionError} composed of structured {@link Fact} instances and other string
messages.
|
facts
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/AssertionErrorWithFacts.java
|
Apache-2.0
|
public void isEqualToIgnoringScale(String expected) {
compareValues(new BigDecimal(expected));
}
|
Checks that the actual value is equal to the value of the {@link BigDecimal} created from the
expected string (i.e., checks that {@code actual.comparesTo(new BigDecimal(expected)) == 0}).
<p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and
the scales, use {@link #isEqualTo(Object)}.
|
isEqualToIgnoringScale
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
Apache-2.0
|
public void isEqualToIgnoringScale(long expected) {
compareValues(new BigDecimal(expected));
}
|
Checks that the actual value is equal to the value of the {@link BigDecimal} created from the
expected {@code long} (i.e., checks that {@code actual.comparesTo(new BigDecimal(expected)) ==
0}).
<p><b>Note:</b> The scale of the BigDecimal is ignored. If you want to compare the values and
the scales, use {@link #isEqualTo(Object)}.
|
isEqualToIgnoringScale
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
Apache-2.0
|
@Override // To express more specific javadoc
public void isEqualTo(@Nullable Object expected) {
super.isEqualTo(expected);
}
|
Checks that the actual value (including scale) is equal to the given {@link BigDecimal}.
<p><b>Note:</b> If you only want to compare the values of the BigDecimals and not their scales,
use {@link #isEqualToIgnoringScale(BigDecimal)} instead.
|
isEqualTo
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
Apache-2.0
|
@Override
public void isEquivalentAccordingToCompareTo(@Nullable BigDecimal expected) {
compareValues(expected);
}
|
Checks that the actual value is equivalent to the given value according to {@link
Comparable#compareTo}, (i.e., checks that {@code a.comparesTo(b) == 0}). This method behaves
identically to (the more clearly named) {@link #isEqualToIgnoringScale(BigDecimal)}.
<p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link
#isEqualTo(Object)}.
|
isEquivalentAccordingToCompareTo
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
Apache-2.0
|
private void compareValues(@Nullable BigDecimal expected) {
if (checkNotNull(actual).compareTo(checkNotNull(expected)) != 0) {
failWithoutActual(
numericFact("expected", expected),
numericFact("but was", actual),
simpleFact("(scale is ignored)"));
}
}
|
Checks that the actual value is equivalent to the given value according to {@link
Comparable#compareTo}, (i.e., checks that {@code a.comparesTo(b) == 0}). This method behaves
identically to (the more clearly named) {@link #isEqualToIgnoringScale(BigDecimal)}.
<p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link
#isEqualTo(Object)}.
|
compareValues
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
Apache-2.0
|
static Factory<BigDecimalSubject, BigDecimal> bigDecimals() {
return BigDecimalSubject::new;
}
|
Checks that the actual value is equivalent to the given value according to {@link
Comparable#compareTo}, (i.e., checks that {@code a.comparesTo(b) == 0}). This method behaves
identically to (the more clearly named) {@link #isEqualToIgnoringScale(BigDecimal)}.
<p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link
#isEqualTo(Object)}.
|
bigDecimals
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BigDecimalSubject.java
|
Apache-2.0
|
public void isTrue() {
if (actual == null) {
isEqualTo(true); // fails
} else if (!actual) {
failWithoutActual(simpleFact("expected to be true"));
}
}
|
Checks that the actual value is {@code true}.
|
isTrue
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BooleanSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BooleanSubject.java
|
Apache-2.0
|
public void isFalse() {
if (actual == null) {
isEqualTo(false); // fails
} else if (actual) {
failWithoutActual(simpleFact("expected to be false"));
}
}
|
Checks that the actual value is {@code false}.
|
isFalse
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BooleanSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BooleanSubject.java
|
Apache-2.0
|
static Factory<BooleanSubject, Boolean> booleans() {
return BooleanSubject::new;
}
|
Checks that the actual value is {@code false}.
|
booleans
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/BooleanSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/BooleanSubject.java
|
Apache-2.0
|
public void isAssignableTo(Class<?> clazz) {
if (actual == null || !clazz.isAssignableFrom(actual)) {
failWithActual("expected to be assignable to", clazz.getName());
}
}
|
Checks that the actual value is a subclass of the given class. Classes are considered to be
subclasses of themselves.
|
isAssignableTo
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ClassSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ClassSubject.java
|
Apache-2.0
|
static Factory<ClassSubject, Class<?>> classes() {
return ClassSubject::new;
}
|
Checks that the actual value is a subclass of the given class. Classes are considered to be
subclasses of themselves.
|
classes
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ClassSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ClassSubject.java
|
Apache-2.0
|
public final void isIn(@Nullable Range<T> range) {
T actual = actualAsT();
if (range == null) {
failWithoutActual(
simpleFact("could not perform range check because range is null"),
fact("value to test for membership was", actual));
} else if (actual == null || !range.contains(actual)) {
failWithActual("expected to be in range", range);
}
}
|
Checks that the actual value is in {@code range}.
|
isIn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
public final void isNotIn(@Nullable Range<T> range) {
T actual = actualAsT();
if (range == null) {
failWithoutActual(
simpleFact("could not perform range check because range is null"),
fact("value to test for membership was", actual));
} else if (actual == null) {
failWithActual("expected a non-null value outside range", range);
} else if (range.contains(actual)) {
failWithActual("expected not to be in range", range);
}
}
|
Checks that the actual value is <i>not</i> in {@code range}.
|
isNotIn
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
public void isEquivalentAccordingToCompareTo(@Nullable T expected) {
Comparable<Object> actual = actualAsComparable();
if (expected == null) {
failWithoutActual(
simpleFact(
"expected a value equivalent to null according to compareTo, but compareTo is"
+ " required to reject null"),
fact("was", actual));
} else if (actual == null || actual.compareTo(expected) != 0) {
failWithActual("expected value that sorts equal to", expected);
}
}
|
Checks that the actual value is equivalent to {@code other} according to {@link
Comparable#compareTo}, (i.e., checks that {@code a.comparesTo(b) == 0}).
<p><b>Note:</b> Do not use this method for checking object equality. Instead, use {@link
#isEqualTo(Object)}.
|
isEquivalentAccordingToCompareTo
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
public final void isGreaterThan(@Nullable T other) {
Comparable<Object> actual = actualAsComparable();
if (other == null) {
failWithoutActual(
simpleFact(
"expected a value greater than null according to compareTo, but compareTo is required"
+ " to reject null"),
fact("was", actual));
} else if (actual == null || actual.compareTo(other) <= 0) {
failWithActual("expected to be greater than", other);
}
}
|
Checks that the actual value is greater than {@code other}.
<p>To check that the actual value is greater than <i>or equal to</i> {@code other}, use {@link
#isAtLeast}.
|
isGreaterThan
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
public final void isLessThan(@Nullable T other) {
Comparable<Object> actual = actualAsComparable();
if (other == null) {
failWithoutActual(
simpleFact(
"expected a value less than null according to compareTo, but compareTo is required to"
+ " reject null"),
fact("was", actual));
} else if (actual == null || actual.compareTo(other) >= 0) {
failWithActual("expected to be less than", other);
}
}
|
Checks that the actual value is less than {@code other}.
<p>To check that the actual value is less than <i>or equal to</i> {@code other}, use {@link
#isAtMost}.
|
isLessThan
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
public final void isAtMost(@Nullable T other) {
Comparable<Object> actual = actualAsComparable();
if (other == null) {
failWithoutActual(
simpleFact(
"expected a value that is at most null according to compareTo, but compareTo is"
+ " required to reject null"),
fact("was", actual));
} else if (actual == null || actual.compareTo(other) > 0) {
failWithActual("expected to be at most", other);
}
}
|
Checks that the actual value is less than or equal to {@code other}.
<p>To check that the actual value is <i>strictly</i> less than {@code other}, use {@link
#isLessThan}.
|
isAtMost
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
public final void isAtLeast(@Nullable T other) {
Comparable<Object> actual = actualAsComparable();
if (other == null) {
failWithoutActual(
simpleFact(
"expected a value that is at least null according to compareTo, but compareTo is"
+ " required to reject null"),
fact("was", actual));
} else if (actual == null || actual.compareTo(other) < 0) {
failWithActual("expected to be at least", other);
}
}
|
Checks that the actual value is greater than or equal to {@code other}.
<p>To check that the actual value is <i>strictly</i> greater than {@code other}, use {@link
#isGreaterThan}.
|
isAtLeast
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
static <T extends Comparable<?>> Factory<ComparableSubject<T>, Object> comparables() {
return (metadata, actual) -> new ComparableSubject<T>(metadata, actual) {};
}
|
Factory for {@link ComparableSubject}, with an actual-value type of {@code Object} to work
around the J2CL strangeness documented on {@link #actual}.
|
comparables
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
@SuppressWarnings("unchecked")
private @Nullable Comparable<Object> actualAsComparable() {
return (Comparable<Object>) actual;
}
|
Factory for {@link ComparableSubject}, with an actual-value type of {@code Object} to work
around the J2CL strangeness documented on {@link #actual}.
|
actualAsComparable
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
@SuppressWarnings("unchecked")
private @Nullable T actualAsT() {
return (T) actual;
}
|
Factory for {@link ComparableSubject}, with an actual-value type of {@code Object} to work
around the J2CL strangeness documented on {@link #actual}.
|
actualAsT
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparableSubject.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparableSubject.java
|
Apache-2.0
|
static ImmutableList<Fact> makeComparisonFailureFacts(
ImmutableList<Fact> headFacts,
ImmutableList<Fact> tailFacts,
String expected,
String actual) {
return concat(headFacts, formatExpectedAndActual(expected, actual), tailFacts);
}
|
Contains part of the code responsible for creating a JUnit {@code ComparisonFailure} (if
available) or a plain {@code AssertionError} (if not).
<p>This particular class is responsible for the fallback when a platform offers {@code
ComparisonFailure} but it is not available in a particular test environment. In practice, that
should mean open-source JRE users who choose to exclude our JUnit 4 dependency.
<p>(This class also includes logic to format expected and actual values for easier reading.)
<p>Another part of the fallback logic is {@code Platform.ComparisonFailureWithFacts}, which has a
different implementation under GWT/j2cl, where {@code ComparisonFailure} is also unavailable but
we can't just recover from that at runtime.
|
makeComparisonFailureFacts
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparisonFailures.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparisonFailures.java
|
Apache-2.0
|
@Override
public ImmutableList<Fact> facts() {
return facts;
}
|
An {@link AssertionError} (usually a JUnit {@code ComparisonFailure}, but not under GWT) composed
of structured {@link Fact} instances and other string messages.
|
facts
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java
|
Apache-2.0
|
@UsedByReflection
static ComparisonFailureWithFacts create(
ImmutableList<String> messages,
ImmutableList<Fact> facts,
String expected,
String actual,
@Nullable Throwable cause) {
return new ComparisonFailureWithFacts(messages, facts, expected, actual, cause);
}
|
An {@link AssertionError} (usually a JUnit {@code ComparisonFailure}, but not under GWT) composed
of structured {@link Fact} instances and other string messages.
|
create
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/ComparisonFailureWithFacts.java
|
Apache-2.0
|
public static <A extends @Nullable Object, E extends @Nullable Object> Correspondence<A, E> from(
BinaryPredicate<A, E> predicate, String description) {
return FromBinaryPredicate.create(predicate, description);
}
|
Constructs a {@link Correspondence} that compares actual and expected elements using the given
binary predicate.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if the data you are asserting about contains nulls, your predicate may be invoked
with null arguments. If this causes it to throw a {@link NullPointerException}, then your test
will fail. (See {@link Correspondence#compare} for more detail on how exceptions are handled.)
In particular, if your predicate is an instance method reference on the actual value (as in the
{@code String::contains} example below), your test will fail if it sees null actual values.
<p>Example using an instance method reference:
<pre>{@code
static final Correspondence<String, String> CONTAINS_SUBSTRING =
Correspondence.from(String::contains, "contains");
}</pre>
<p>Example using a static method reference:
<pre>{@code
class MyRecordTestHelper {
static final Correspondence<MyRecord, MyRecord> EQUIVALENCE =
Correspondence.from(MyRecordTestHelper::recordsEquivalent, "is equivalent to");
static boolean recordsEquivalent(MyRecord actual, MyRecord expected) {
// code to check whether records should be considered equivalent for testing purposes
}
}
}</pre>
<p>Example using a lambda:
<pre>{@code
static final Correspondence<Object, Class<?>> INSTANCE_OF =
Correspondence.from((obj, clazz) -> clazz.isInstance(obj), "is an instance of");
}</pre>
@param predicate a {@link BinaryPredicate} taking an actual and expected value (in that order)
and returning whether the actual value corresponds to the expected value in some way
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "contains"}, {@code "is an instance of"}, or {@code "is equivalent to"}
|
from
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
@Override
public boolean compare(A actual, E expected) {
return predicate.apply(actual, expected);
}
|
Returns whether or not the actual and expected values satisfy the condition defined by this
predicate.
|
compare
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
@Override
public String toString() {
return description;
}
|
Returns whether or not the actual and expected values satisfy the condition defined by this
predicate.
|
toString
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
static <A extends @Nullable Object, E extends @Nullable Object>
FromBinaryPredicate<A, E> create(BinaryPredicate<A, E> predicate, String description) {
return new FromBinaryPredicate<>(predicate, description);
}
|
Returns whether or not the actual and expected values satisfy the condition defined by this
predicate.
|
create
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
public static <A extends @Nullable Object, E extends @Nullable Object>
Correspondence<A, E> transforming(
Function<A, ? extends E> actualTransform, String description) {
return Transforming.create(actualTransform, identity(), description);
}
|
Constructs a {@link Correspondence} that compares elements by transforming the actual elements
using the given function and testing for equality with the expected elements. If the
transformed actual element (i.e. the output of the given function) is null, it will correspond
to a null expected element.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if you the data you are asserting about contains null actual values, your
function may be invoked with a null argument. If this causes it to throw a {@link
NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for more
detail on how exceptions are handled.) In particular, this applies if your function is an
instance method reference on the actual value (as in the example below). If you want a null
actual element to correspond to a null expected element, you must ensure that your function
transforms a null input to a null output.
<p>Example:
<pre>{@code
static final Correspondence<MyRecord, Integer> HAS_ID =
Correspondence.transforming(MyRecord::getId, "has an ID of");
}</pre>
This can be used as follows:
<pre>{@code
assertThat(myRecords).comparingElementsUsing(HAS_ID).containsExactly(123, 456, 789);
}</pre>
@param actualTransform a {@link Function} taking an actual value and returning a new value
which will be compared with an expected value to determine whether they correspond
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "has an ID of"}
|
transforming
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
public static <A extends @Nullable Object, E extends @Nullable Object>
Correspondence<A, E> transforming(
Function<A, ?> actualTransform, Function<E, ?> expectedTransform, String description) {
return Transforming.create(actualTransform, expectedTransform, description);
}
|
Constructs a {@link Correspondence} that compares elements by transforming the actual and the
expected elements using the given functions and testing the transformed values for equality. If
an actual element is transformed to null, it will correspond to an expected element that is
also transformed to null.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if you the data you are asserting about contains null actual or expected values,
the appropriate function may be invoked with a null argument. If this causes it to throw a
{@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for
more detail on how exceptions are handled.) In particular, this applies if your function is an
instance method reference on the actual or expected value (as in the example below). If you
want a null actual element to correspond to a null expected element, you must ensure that your
functions both transform a null input to a null output.
<p>If you want to apply the same function to both the actual and expected elements, just
provide the same argument twice.
<p>Example:
<pre>{@code
static final Correspondence<MyRequest, MyResponse> SAME_IDS =
Correspondence.transforming(MyRequest::getId, MyResponse::getId, "has the same ID as");
}</pre>
This can be used as follows:
<pre>{@code
assertThat(myResponses).comparingElementsUsing(SAME_IDS).containsExactlyElementsIn(myRequests);
}</pre>
@param actualTransform a {@link Function} taking an actual value and returning a new value
which will be compared with a transformed expected value to determine whether they
correspond
@param expectedTransform a {@link Function} taking an expected value and returning a new value
which will be compared with a transformed actual value
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "has the same ID as"}
|
transforming
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
@Override
public boolean compare(A actual, E expected) {
return Objects.equals(actualTransform.apply(actual), expectedTransform.apply(expected));
}
|
Constructs a {@link Correspondence} that compares elements by transforming the actual and the
expected elements using the given functions and testing the transformed values for equality. If
an actual element is transformed to null, it will correspond to an expected element that is
also transformed to null.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if you the data you are asserting about contains null actual or expected values,
the appropriate function may be invoked with a null argument. If this causes it to throw a
{@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for
more detail on how exceptions are handled.) In particular, this applies if your function is an
instance method reference on the actual or expected value (as in the example below). If you
want a null actual element to correspond to a null expected element, you must ensure that your
functions both transform a null input to a null output.
<p>If you want to apply the same function to both the actual and expected elements, just
provide the same argument twice.
<p>Example:
<pre>{@code
static final Correspondence<MyRequest, MyResponse> SAME_IDS =
Correspondence.transforming(MyRequest::getId, MyResponse::getId, "has the same ID as");
}</pre>
This can be used as follows:
<pre>{@code
assertThat(myResponses).comparingElementsUsing(SAME_IDS).containsExactlyElementsIn(myRequests);
}</pre>
@param actualTransform a {@link Function} taking an actual value and returning a new value
which will be compared with a transformed expected value to determine whether they
correspond
@param expectedTransform a {@link Function} taking an expected value and returning a new value
which will be compared with a transformed actual value
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "has the same ID as"}
|
compare
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
@Override
public String toString() {
return description;
}
|
Constructs a {@link Correspondence} that compares elements by transforming the actual and the
expected elements using the given functions and testing the transformed values for equality. If
an actual element is transformed to null, it will correspond to an expected element that is
also transformed to null.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if you the data you are asserting about contains null actual or expected values,
the appropriate function may be invoked with a null argument. If this causes it to throw a
{@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for
more detail on how exceptions are handled.) In particular, this applies if your function is an
instance method reference on the actual or expected value (as in the example below). If you
want a null actual element to correspond to a null expected element, you must ensure that your
functions both transform a null input to a null output.
<p>If you want to apply the same function to both the actual and expected elements, just
provide the same argument twice.
<p>Example:
<pre>{@code
static final Correspondence<MyRequest, MyResponse> SAME_IDS =
Correspondence.transforming(MyRequest::getId, MyResponse::getId, "has the same ID as");
}</pre>
This can be used as follows:
<pre>{@code
assertThat(myResponses).comparingElementsUsing(SAME_IDS).containsExactlyElementsIn(myRequests);
}</pre>
@param actualTransform a {@link Function} taking an actual value and returning a new value
which will be compared with a transformed expected value to determine whether they
correspond
@param expectedTransform a {@link Function} taking an expected value and returning a new value
which will be compared with a transformed actual value
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "has the same ID as"}
|
toString
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
static <A extends @Nullable Object, E extends @Nullable Object> Transforming<A, E> create(
Function<? super A, ?> actualTransform,
Function<? super E, ?> expectedTransform,
String description) {
return new Transforming<>(actualTransform, expectedTransform, description);
}
|
Constructs a {@link Correspondence} that compares elements by transforming the actual and the
expected elements using the given functions and testing the transformed values for equality. If
an actual element is transformed to null, it will correspond to an expected element that is
also transformed to null.
<p>The correspondence does not support formatting of diffs (see {@link #formatDiff}). You can
add that behaviour by calling {@link Correspondence#formattingDiffsUsing}.
<p>Note that, if you the data you are asserting about contains null actual or expected values,
the appropriate function may be invoked with a null argument. If this causes it to throw a
{@link NullPointerException}, then your test will fail. (See {@link Correspondence#compare} for
more detail on how exceptions are handled.) In particular, this applies if your function is an
instance method reference on the actual or expected value (as in the example below). If you
want a null actual element to correspond to a null expected element, you must ensure that your
functions both transform a null input to a null output.
<p>If you want to apply the same function to both the actual and expected elements, just
provide the same argument twice.
<p>Example:
<pre>{@code
static final Correspondence<MyRequest, MyResponse> SAME_IDS =
Correspondence.transforming(MyRequest::getId, MyResponse::getId, "has the same ID as");
}</pre>
This can be used as follows:
<pre>{@code
assertThat(myResponses).comparingElementsUsing(SAME_IDS).containsExactlyElementsIn(myRequests);
}</pre>
@param actualTransform a {@link Function} taking an actual value and returning a new value
which will be compared with a transformed expected value to determine whether they
correspond
@param expectedTransform a {@link Function} taking an expected value and returning a new value
which will be compared with a transformed actual value
@param description should fill the gap in a failure message of the form {@code "not true that
<some actual element> is an element that <description> <some expected element>"}, e.g.
{@code "has the same ID as"}
|
create
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
public static Correspondence<Number, Number> tolerance(double tolerance) {
return TolerantNumericEquality.create(tolerance);
}
|
Returns a {@link Correspondence} between {@link Number} instances that considers instances to
correspond (i.e. {@link Correspondence#compare(Object, Object)} returns {@code true}) if the
double values of each instance (i.e. the result of calling {@link Number#doubleValue()} on
them) are finite values within {@code tolerance} of each other.
<ul>
<li>It does not consider instances to correspond if either value is infinite or NaN.
<li>The conversion to double may result in a loss of precision for some numeric types.
<li>The {@link Correspondence#compare(Object, Object)} method throws a {@link
NullPointerException} if either {@link Number} instance is null.
</ul>
@param tolerance an inclusive upper bound on the difference between the double values of the
two {@link Number} instances, which must be a non-negative finite value, i.e. not {@link
Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0}
|
tolerance
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
@Override
public boolean compare(Number actual, Number expected) {
double actualDouble = checkNotNull(actual).doubleValue();
double expectedDouble = checkNotNull(expected).doubleValue();
return MathUtil.equalWithinTolerance(actualDouble, expectedDouble, tolerance);
}
|
Returns a {@link Correspondence} between {@link Number} instances that considers instances to
correspond (i.e. {@link Correspondence#compare(Object, Object)} returns {@code true}) if the
double values of each instance (i.e. the result of calling {@link Number#doubleValue()} on
them) are finite values within {@code tolerance} of each other.
<ul>
<li>It does not consider instances to correspond if either value is infinite or NaN.
<li>The conversion to double may result in a loss of precision for some numeric types.
<li>The {@link Correspondence#compare(Object, Object)} method throws a {@link
NullPointerException} if either {@link Number} instance is null.
</ul>
@param tolerance an inclusive upper bound on the difference between the double values of the
two {@link Number} instances, which must be a non-negative finite value, i.e. not {@link
Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0}
|
compare
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
@Override
public String toString() {
return "is a finite number within " + tolerance + " of";
}
|
Returns a {@link Correspondence} between {@link Number} instances that considers instances to
correspond (i.e. {@link Correspondence#compare(Object, Object)} returns {@code true}) if the
double values of each instance (i.e. the result of calling {@link Number#doubleValue()} on
them) are finite values within {@code tolerance} of each other.
<ul>
<li>It does not consider instances to correspond if either value is infinite or NaN.
<li>The conversion to double may result in a loss of precision for some numeric types.
<li>The {@link Correspondence#compare(Object, Object)} method throws a {@link
NullPointerException} if either {@link Number} instance is null.
</ul>
@param tolerance an inclusive upper bound on the difference between the double values of the
two {@link Number} instances, which must be a non-negative finite value, i.e. not {@link
Double#NaN}, {@link Double#POSITIVE_INFINITY}, or negative, including {@code -0.0}
|
toString
|
java
|
google/truth
|
core/src/main/java/com/google/common/truth/Correspondence.java
|
https://github.com/google/truth/blob/master/core/src/main/java/com/google/common/truth/Correspondence.java
|
Apache-2.0
|
End of preview. Expand
in Data Studio
Java CodeSearch Dataset (Shuu12121/java-treesitter-filtered-datasetsV2)
Dataset Description
This dataset contains Java methods paired with their Javadoc comments, extracted from open-source Java repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.
Each entry includes:
code: The source code of a java function or method.docstring: The docstring or Javadoc associated with the function/method.func_name: The name of the function/method.language: The programming language (always "java").repo: The GitHub repository from which the code was sourced (e.g., "owner/repo").path: The file path within the repository where the function/method is located.url: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).license: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0"). Additional metrics if available (from Lizard tool):ccn: Cyclomatic Complexity Number.params: Number of parameters of the function/method.nloc: Non-commenting lines of code.token_count: Number of tokens in the function/method.
Dataset Structure
The dataset is divided into the following splits:
train: 8,956,411 examplesvalidation: 71,533 examplestest: 109,081 examples
Data Collection
The data was collected by:
- Identifying popular and relevant Java repositories on GitHub.
- Cloning these repositories.
- Parsing Java files (
.java) using tree-sitter to extract functions/methods and their docstrings/Javadoc. - Filtering functions/methods based on code length and presence of a non-empty docstring/Javadoc.
- Using the
lizardtool to calculate code metrics (CCN, NLOC, params). - Storing the extracted data in JSONL format, including repository and license information.
- Splitting the data by repository to ensure no data leakage between train, validation, and test sets.
Intended Use
This dataset can be used for tasks such as:
- Training and evaluating models for code search (natural language to code).
- Code summarization / docstring generation (code to natural language).
- Studies on Java code practices and documentation habits.
Licensing
The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD).
Each sample includes its original license information in the license field.
The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0),
but users should respect the original licenses of the underlying code.
Example Usage
from datasets import load_dataset
# Load the dataset
dataset = load_dataset("Shuu12121/java-treesitter-filtered-datasetsV2")
# Access a split (e.g., train)
train_data = dataset["train"]
# Print the first example
print(train_data[0])
- Downloads last month
- 21