Class BinaryStubWriterTest
BinaryStubWriter.-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classEnclosesBinaryStubWriterTest.Enclosing.DoublyNested, whose binary name has two$separators. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoidA count that does not fit its length prefix must fail the file, not truncate.voidA failed serialization must not consume an annotation-pool index.voidAn annotation on a type argument of an enclosing type is dropped, not encoded.voidAn annotation that loads but declares no@Target--java.lang.SuppressWarningsreally is one, through reflection -- must be treated as a declaration annotation, not as an unloadable class.voidThe 8-bit counterpart ofaCountTooLargeForItsLengthPrefixFailsRatherThanTruncating(), reached through a real call site: a type path has one ARRAY step per array dimension, and its length is au1(JVMS 4.7.20.1).voidA built-in stub file's writer keeps every member record in full, annotated or not:BinaryStubReadermarks each matched member with@FromStubFile, and a member with no record is never matched.voidT20(a): a class literal naming an unimported class in the stub file's own package must be qualified against that package, mirroring the text parser's package-prefix fallback (AnnotationFileParser.findTypeOfName).voidConfirms a compact canonical constructor (no parameter list of its own to carry annotations) does not produce acanonicalConstructorParamAnnosoverride, leaving the record components' own annotations as the source of truth.voidA constant expression is written as its tree of operations, for the reader to evaluate as the text parser does; parentheses are not written.voidConfirms an explicit (non-compact) canonical constructor -- one whose parameter types match the record header's components in count and order -- produces acanonicalConstructorParamAnnosoverride carrying the constructor's own parameter annotations, matchingAnnotationFileParser'sRecordStub#componentsInCanonicalConstructor.voidA multi-directoryJavaStubifierrun creates a freshBinaryStubWriterper directory (seeJavaStubifier.process), so an interface in one directory and its implementer in another are processed by different writers.voidThe annotated-JDK writer omits field records carrying no annotations and demotes unannotated method records to bare presence-only signature entries.voidAn unannotated constructor is dropped entirely by the annotated-JDK writer, with no presence-only entry either: a constructor can never be a fake override (both the binary reader and the text parser skip the fake-override path for constructors), so an all-empty constructor record is a true no-op.voidA class with no annotated members at all still gets a class record from the annotated-JDK writer: its presence inBinaryStubData.classesis what stopsAnnotationFileElementTypesfrom falling back to text-parsing the class.voidConfirms a mixed-target annotation (valid in both declaration andTYPE_USEpositions, e.g.voidRegression test for a varargs type-path bug: a declaration-position, type-use-applicable annotation on a vararg parameter (e.g.voidRegression test for a constant-pool sentinel bug:ClassRecord#outerNameIndexuses0to mean "top-level class" (seeBinaryStubWriter.makeClassRecord'soutermostFqn.isEmpty() ? 0 : pool.addString(outermostFqn)), but the constant pool does not reserve index0for an empty string -- the first string ever added to the pool gets index0.voidRegression test for anEnclosedExprcrash: redundant parentheses around an annotation value (e.g.voidConfirms a record declaration is written as aKIND_RECORDclass record with oneComponentRecordper header component, in header order, each carrying its own type annotations andhasAccessorflag: a component with an explicit zero-argument accessor of the same name in the record body must havehasAccessor == true, and one without must havehasAccessor == false-- matchingAnnotationFileParser'shasAccessorInStubssemantics.voidAn annotation nested two deep resolves: every segment after the package becomes a$, not just the last one.voidThe same annotation written out fully qualified resolves too: the writer tries each split point of a dotted name, sojava.lang.invoke.MethodHandle.PolymorphicSignatureandMethodHandle.PolymorphicSignaturereach the same binary name.voidAn annotation named through its enclosing class, asjava.lang.invoke.VarHandlewrites@MethodHandle.PolymorphicSignature, is resolved to its binary name so that its@Targetcan be read.voidT20(b): a scoped class-literal type likeMap.Entrymust be qualified through its outermost scope, not skipped just becauseClassOrInterfaceType.getScope()is present.voidA bare reference to a statically-imported constant (e.g.voidA string value is written unescaped, asStringLiteralExpr#asStringgives it and as the text parser reads it:"\\d+\t"is the four characters backslash, d, plus, tab.voidA fully-qualified annotation name whose class is not on the stubifier classpath must abort the file rather than be routed by guesswork.voidAn annotation whose simple name resolves to nothing, in a compilation unit with no asterisk import, is not a failure: nothing (nojava.langmatch, no explicit import, no asterisk import -- there is none) could have supplied the name, so neitherBinaryStubReadernor the text parser can resolve it either (AnnotationFileParser.getAnnotationlooks the as-written name up withElements.getTypeElement, which fails the same way on a bare, unqualified name), and the binary form's routing of it cannot matter.voidAn annotation whose simple name resolves to nothing IS a failure when the compilation unit has an asterisk import:BinaryStubWriter.fullyQualifyAnnotationName(java.lang.String)tried the asterisk-imported package viaClass.forNameand failed, but that only proves the package is absent from the stubifier's own build classpath -- not that a checker'sElements, resolving against whatever classpath its invocation supplies, would also fail.voidRegression test for a varargs type-path off-by-one: an annotation embedded in the declared type of a vararg parameter (the@NullableofList<@Nullable String>... args) must carry a leadingARRAYstep for the vararg's implicit array level.voidThe empty-path counterpart ofvarargsDeclaredTypeAnnotationPathStartsWithTheImplicitArrayStep(): an annotation written inside a fully-qualified vararg element type (java.lang.@Nullable String... args) is attached by JavaParser to the type, not to the parameter declaration, so it reaches the writer throughextractTypeAnnotations(p.getType(), ...)with an empty path within the declared type.
-
Constructor Details
-
BinaryStubWriterTest
public BinaryStubWriterTest()
-
-
Method Details
-
jdkWriterDemotesUnannotatedMethodRecords
The annotated-JDK writer omits field records carrying no annotations and demotes unannotated method records to bare presence-only signature entries.69.6% of the annotated JDK's method records and 85.6% of its field records are all-empty, costing about a quarter of the compressed file and 22,398
MethodRecordobjects per load when written in full. An unannotated method's signature must still be recorded, though: on a JDK where the class does not really declare the method, the declaration is a fake override whose presence alone resets the member's type at that subtype (seeBinaryStubReader#applyFakeOverride).- Throws:
IOException
-
builtinStubWriterKeepsUnannotatedMemberRecords
A built-in stub file's writer keeps every member record in full, annotated or not:BinaryStubReadermarks each matched member with@FromStubFile, and a member with no record is never matched.- Throws:
IOException
-
jdkWriterDropsUnannotatedConstructorRecords
An unannotated constructor is dropped entirely by the annotated-JDK writer, with no presence-only entry either: a constructor can never be a fake override (both the binary reader and the text parser skip the fake-override path for constructors), so an all-empty constructor record is a true no-op.- Throws:
IOException
-
jdkWriterKeepsTheClassRecordOfAnEntirelyUnannotatedClass
A class with no annotated members at all still gets a class record from the annotated-JDK writer: its presence inBinaryStubData.classesis what stopsAnnotationFileElementTypesfrom falling back to text-parsing the class.- Throws:
IOException
-
implementerOutputDoesNotDependOnTheInterfaceBeingInTheSameWriter
A multi-directoryJavaStubifierrun creates a freshBinaryStubWriterper directory (seeJavaStubifier.process), so an interface in one directory and its implementer in another are processed by different writers. This pins that the split does not change the implementer's binary output: whether an unannotated method is retained as a presence-only fake-override signature (ClassRecord.presenceOnlyMethodSigs) depends only on the implementer's own declaration, never on whether the interface it overrides was processed by the same writer. Both writers below recorddescribe()identically.The retention is unconditional (see
BinaryStubWriter.addMethodRecord) precisely so that no cross-writer -- hence no cross-directory -- interface knowledge is needed: the fake-override match itself is a read-time search over the real class hierarchy (BinaryStubReader.applyFakeOverride,FakeOverrideResolver), which no writer-side state feeds. A future change that made omission depend on the interfaces a writer happens to have seen would be unsafe across directories and would fail this test.- Throws:
IOException
-
aCountTooLargeForItsLengthPrefixFailsRatherThanTruncating
A count that does not fit its length prefix must fail the file, not truncate.Every length prefix in the format is an unsigned 16-bit value, and
DataOutputStream.writeShortsilently keeps only the low 16 bits. A count of 65536 would be written as 0, andBinaryStubData-- which cannot tell a truncated count from a real one -- would then read every subsequent field of the file from the wrong offset. Nothing in a real stub file comes close to the limit; the guard is what makes the day one does a build failure rather than a silently wrong annotated JDK.- Throws:
IOException
-
aTypePathTooLongForItsLengthPrefixFailsRatherThanTruncating
The 8-bit counterpart ofaCountTooLargeForItsLengthPrefixFailsRatherThanTruncating(), reached through a real call site: a type path has one ARRAY step per array dimension, and its length is au1(JVMS 4.7.20.1). A 256-dimensional array would write a length of 0, and the reader would then take the next annotation's bytes for the enclosing record's fields.Java caps array types at 255 dimensions, so a stub declaring 256 is already invalid; the point is that the writer says so rather than emitting a corrupt file.
- Throws:
IOException
-
annotationOnAnEnclosingTypesTypeArgumentIsDropped
An annotation on a type argument of an enclosing type is dropped, not encoded.extractTypeAnnotationsdescends into aClassOrInterfaceType's own type arguments but not into its scope's, so the@DeprecatedonOuter's type argument below produces noTypeAnno, while the one onInner's does. Encoding it would need a JVMS nested-type (kind 1) path step, which neither side emits.This is not a divergence from the text parser:
AnnotationFileParser.annotate'sDECLAREDcase reads onlygetTypeArguments(), nevergetScope(), so it drops the same annotation. The test pins the gap so a future change to either side has to confront it.- Throws:
IOException
-
aFailedAnnotationDoesNotConsumeAPoolIndex
A failed serialization must not consume an annotation-pool index.AnnotationPool.addAnnotationused to record the new index before serializing the annotation into it. WhenwriteAnnotationInlinethen threw -- here onnull, which is not a legal annotation value, so the annotation is dropped -- the index was handed out butserializedAnnosnever received a corresponding entry. Every later annotation's index shifted down by one relative to the pool it is written into, so a reader given such a file would apply the wrong annotation, or none, rather than fail.Here the writer is reused across two
processcalls, asJavaStubifierdoes across the files of one directory, so the surviving state is observable.- Throws:
IOException
-
unloadableQualifiedAnnotationFailsRatherThanBeingMisrouted
public void unloadableQualifiedAnnotationFailsRatherThanBeingMisrouted()A fully-qualified annotation name whose class is not on the stubifier classpath must abort the file rather than be routed by guesswork.hasTypeUseandisTypeUseOnlyboth used to read "class did not load" as "no@Target", which routes the annotation todeclAnnosonly. If the annotation is reallyTYPE_USE-only,BinaryStubReader.filterApplicablethen discards it against the real@Targetat checker runtime and the annotation disappears from the binary form with no diagnostic anywhere. The stubifier's classpath (stubparser plus checker-qual) is narrower than any checker's, so a stub naming a third-party annotation would hit exactly this. Failing makesBinaryStubFileGeneratorskip the file, which then keeps its (correct) text parsing. -
unresolvableSimpleAnnotationNameIsNotAFailure
An annotation whose simple name resolves to nothing, in a compilation unit with no asterisk import, is not a failure: nothing (nojava.langmatch, no explicit import, no asterisk import -- there is none) could have supplied the name, so neitherBinaryStubReadernor the text parser can resolve it either (AnnotationFileParser.getAnnotationlooks the as-written name up withElements.getTypeElement, which fails the same way on a bare, unqualified name), and the binary form's routing of it cannot matter. The annotated JDK's own@SuppressFBWarningsand@ConstructorProperties(used by same-package visibility, with no import) reach this case today. Contrast withunresolvableSimpleNameWithAsteriskImportFailsRatherThanBeingDropped(), where an asterisk import exists and this IS a failure.- Throws:
IOException
-
unresolvableSimpleNameWithAsteriskImportFailsRatherThanBeingDropped
public void unresolvableSimpleNameWithAsteriskImportFailsRatherThanBeingDropped()An annotation whose simple name resolves to nothing IS a failure when the compilation unit has an asterisk import:BinaryStubWriter.fullyQualifyAnnotationName(java.lang.String)tried the asterisk-imported package viaClass.forNameand failed, but that only proves the package is absent from the stubifier's own build classpath -- not that a checker'sElements, resolving against whatever classpath its invocation supplies, would also fail. Silently treating this the same as the no-import case above would route the annotation as a bare, unqualified name thatBinaryStubReadercan never resolve either, dropping an annotation the text parser could have resolved, with no diagnostic on either side. -
annotationWithoutTargetIsADeclarationAnnotation
An annotation that loads but declares no@Target--java.lang.SuppressWarningsreally is one, through reflection -- must be treated as a declaration annotation, not as an unloadable class. This is the distinction between theNO_TARGETandNOT_LOADABLEsentinels.- Throws:
IOException
-
nestedClassOfTheFirstProcessedClassIsNotMistakenForTopLevel
Regression test for a constant-pool sentinel bug:ClassRecord#outerNameIndexuses0to mean "top-level class" (seeBinaryStubWriter.makeClassRecord'soutermostFqn.isEmpty() ? 0 : pool.addString(outermostFqn)), but the constant pool does not reserve index0for an empty string -- the first string ever added to the pool gets index0. If an outer class happens to be the first class processed in the whole writer's lifetime (as it is here, being the very first and only file processed by a fresh writer), its own fully-qualified name is stored at pool index 0, so any of its nested classes -- whose ownouterNameIndexis that same, correct index 0 -- become indistinguishable from an actual top-level class.- Throws:
IOException
-
multidimensionalVarargsAnnotationPathHasOneStepPerArrayLevel
Regression test for a varargs type-path bug: a declaration-position, type-use-applicable annotation on a vararg parameter (e.g.@Nullable String[]... args) must apply to the innermost array component, matchingAnnotationFileParser'sannotateInnermostComponentType(reached, on the text side, viaannotateAsArray's call to it before descending the declared array levels). For a multidimensional vararg like this one -- equivalent toString[][] args-- that is two levels below the overall parameter type: oneARRAYstep for the vararg's own implicit array level, plus one more for the explicit[]already present in the declared type (String[]). The previous code hardcoded a singleARRAYstep, which for this case pointed at the middleString[]level instead of the innermostString.- Throws:
IOException
-
varargsDeclaredTypeAnnotationPathStartsWithTheImplicitArrayStep
Regression test for a varargs type-path off-by-one: an annotation embedded in the declared type of a vararg parameter (the@NullableofList<@Nullable String>... args) must carry a leadingARRAYstep for the vararg's implicit array level. JavaParser'sParameter.getType()is the element type (List<String>here), but the reader (BinaryStubReader.applyMethodRecords) resolves the recorded paths against the full array parameter type. The previous code extracted the paths with no prefix, so the reader'sresolvePathhit aTYPE_ARGUMENTstep on anAnnotatedArrayType, returned null, and the annotation was silently dropped -- while the text parser (AnnotationFileParser.processParameters) anchors the declared type at the array's component type and keeps it.- Throws:
IOException
-
varargsFullyQualifiedElementTypeAnnotationGetsTheImplicitArrayStep
The empty-path counterpart ofvarargsDeclaredTypeAnnotationPathStartsWithTheImplicitArrayStep(): an annotation written inside a fully-qualified vararg element type (java.lang.@Nullable String... args) is attached by JavaParser to the type, not to the parameter declaration, so it reaches the writer throughextractTypeAnnotations(p.getType(), ...)with an empty path within the declared type. Without the implicit array level's leadingARRAYstep, the empty path lands the annotation on the array type itself instead of the element type -- the text parser puts it on the element type (annotateon the array's component type).- Throws:
IOException
-
parenthesizedAnnotationValueDoesNotCrash
Regression test for anEnclosedExprcrash: redundant parentheses around an annotation value (e.g.@SuppressWarnings(("unchecked"))) are legal Java, butwriteValuehad no case for the parenthesized-expression AST node and fell through to its "unsupported annotation value" branch, throwingIOException-- whichBinaryStubWriter.processTypes(com.github.javaparser.ast.CompilationUnit)rethrows as an uncaughtRuntimeException, aborting the entire binary stub generation run over one such value anywhere in the source tree.- Throws:
IOException
-
mixedTargetAnnotationOnReturnTypeIsStoredInBothPlaces
Confirms a mixed-target annotation (valid in both declaration andTYPE_USEpositions, e.g.org.checkerframework.checker.mustcall.qual.MustCallAlias, whose@Targetincludes bothMETHODandTYPE_USE) written in declaration-position before a method's return type is stored in bothMethodRecord.declAnnosandMethodRecord.returnTypeAnnos, not just one -- matching the dual-storage pattern documented atBinaryStubWriter.isTypeUseOnly(com.github.javaparser.ast.expr.AnnotationExpr)and confirming a review claim that such annotations are silently dropped for method return types does not reproduce against the current code.- Throws:
IOException
-
recordComponentAnnotationsAndAccessorFlagAreWritten
Confirms a record declaration is written as aKIND_RECORDclass record with oneComponentRecordper header component, in header order, each carrying its own type annotations andhasAccessorflag: a component with an explicit zero-argument accessor of the same name in the record body must havehasAccessor == true, and one without must havehasAccessor == false-- matchingAnnotationFileParser'shasAccessorInStubssemantics.- Throws:
IOException
-
explicitCanonicalConstructorProducesOverride
Confirms an explicit (non-compact) canonical constructor -- one whose parameter types match the record header's components in count and order -- produces acanonicalConstructorParamAnnosoverride carrying the constructor's own parameter annotations, matchingAnnotationFileParser'sRecordStub#componentsInCanonicalConstructor.- Throws:
IOException
-
compactCanonicalConstructorDoesNotProduceOverride
Confirms a compact canonical constructor (no parameter list of its own to carry annotations) does not produce acanonicalConstructorParamAnnosoverride, leaving the record components' own annotations as the source of truth.- Throws:
IOException
-
staticImportedConstantIsWrittenWithItsImportClasses
A bare reference to a statically-imported constant (e.g.MAX_VALUEfromimport static java.lang.Integer.MAX_VALUE;) is written as a name together with the classes the file's static imports can import it from, for the reader to resolve as the text parser does (AnnotationConstants.findConstant). Without the classes, the reader could look only in the enclosing class and would miss a constant of an unrelated class.- Throws:
IOException
-
classLiteralInCurrentPackageIsFullyQualified
T20(a): a class literal naming an unimported class in the stub file's own package must be qualified against that package, mirroring the text parser's package-prefix fallback (AnnotationFileParser.findTypeOfName). Before this fix,fullyQualify(String, CompilationUnit)tried only the explicit imports and asterisk imports, leaving the class literal as the bare simple name"BinaryStubWriter"-- whichBinaryStubReader#resolveSingleValue's singleElements.getTypeElement(fqName)call cannot resolve, silently dropping the class-literal annotation element.- Throws:
IOException
-
scopedClassLiteralIsFullyQualified
T20(b): a scoped class-literal type likeMap.Entrymust be qualified through its outermost scope, not skipped just becauseClassOrInterfaceType.getScope()is present. Before this fix,fullyQualify(Type, CompilationUnit)qualified aClassOrInterfaceTypeonly when!cit.getScope().isPresent(), soMap.Entrywas written as-is even withimport java.util.Map;in scope.- Throws:
IOException
-
constantExpressionIsWrittenAsATree
A constant expression is written as its tree of operations, for the reader to evaluate as the text parser does; parentheses are not written. Literals keep their types:1is anint,2.5fafloat.- Throws:
IOException
-
stringValueIsUnescaped
A string value is written unescaped, asStringLiteralExpr#asStringgives it and as the text parser reads it:"\\d+\t"is the four characters backslash, d, plus, tab.- Throws:
IOException
-
resolvesAnnotationNamedThroughItsEnclosingClass
An annotation named through its enclosing class, asjava.lang.invoke.VarHandlewrites@MethodHandle.PolymorphicSignature, is resolved to its binary name so that its@Targetcan be read. Such a name does not load as written: the binary name separates the nesting with$.- Throws:
IOException
-
resolvesAFullyQualifiedNestedAnnotationName
The same annotation written out fully qualified resolves too: the writer tries each split point of a dotted name, sojava.lang.invoke.MethodHandle.PolymorphicSignatureandMethodHandle.PolymorphicSignaturereach the same binary name.- Throws:
IOException
-
resolvesADoublyNestedAnnotationName
An annotation nested two deep resolves: every segment after the package becomes a$, not just the last one.- Throws:
IOException
-