Class BinaryStubWriterTest

java.lang.Object
org.checkerframework.framework.stubifier.BinaryStubWriterTest

public class BinaryStubWriterTest extends Object
Tests for BinaryStubWriter.
  • Constructor Details

    • BinaryStubWriterTest

      public BinaryStubWriterTest()
  • Method Details

    • jdkWriterDemotesUnannotatedMethodRecords

      public void jdkWriterDemotesUnannotatedMethodRecords() throws IOException
      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 MethodRecord objects 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 (see BinaryStubReader#applyFakeOverride).

      Throws:
      IOException
    • builtinStubWriterKeepsUnannotatedMemberRecords

      public void builtinStubWriterKeepsUnannotatedMemberRecords() throws IOException
      A built-in stub file's writer keeps every member record in full, annotated or not: BinaryStubReader marks each matched member with @FromStubFile, and a member with no record is never matched.
      Throws:
      IOException
    • jdkWriterDropsUnannotatedConstructorRecords

      public void jdkWriterDropsUnannotatedConstructorRecords() throws IOException
      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

      public void jdkWriterKeepsTheClassRecordOfAnEntirelyUnannotatedClass() throws IOException
      A class with no annotated members at all still gets a class record from the annotated-JDK writer: its presence in BinaryStubData.classes is what stops AnnotationFileElementTypes from falling back to text-parsing the class.
      Throws:
      IOException
    • implementerOutputDoesNotDependOnTheInterfaceBeingInTheSameWriter

      public void implementerOutputDoesNotDependOnTheInterfaceBeingInTheSameWriter() throws IOException
      A multi-directory JavaStubifier run creates a fresh BinaryStubWriter per directory (see JavaStubifier.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 record describe() 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

      public void aCountTooLargeForItsLengthPrefixFailsRatherThanTruncating() throws IOException
      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.writeShort silently keeps only the low 16 bits. A count of 65536 would be written as 0, and BinaryStubData -- 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

      public void aTypePathTooLongForItsLengthPrefixFailsRatherThanTruncating() throws IOException
      The 8-bit counterpart of aCountTooLargeForItsLengthPrefixFailsRatherThanTruncating(), reached through a real call site: a type path has one ARRAY step per array dimension, and its length is a u1 (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

      public void annotationOnAnEnclosingTypesTypeArgumentIsDropped() throws IOException
      An annotation on a type argument of an enclosing type is dropped, not encoded.

      extractTypeAnnotations descends into a ClassOrInterfaceType's own type arguments but not into its scope's, so the @Deprecated on Outer's type argument below produces no TypeAnno, while the one on Inner'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's DECLARED case reads only getTypeArguments(), never getScope(), 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

      public void aFailedAnnotationDoesNotConsumeAPoolIndex() throws IOException
      A failed serialization must not consume an annotation-pool index.

      AnnotationPool.addAnnotation used to record the new index before serializing the annotation into it. When writeAnnotationInline then threw -- here on null, which is not a legal annotation value, so the annotation is dropped -- the index was handed out but serializedAnnos never 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 process calls, as JavaStubifier does 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.

      hasTypeUse and isTypeUseOnly both used to read "class did not load" as "no @Target", which routes the annotation to declAnnos only. If the annotation is really TYPE_USE-only, BinaryStubReader.filterApplicable then discards it against the real @Target at 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 makes BinaryStubFileGenerator skip the file, which then keeps its (correct) text parsing.

    • unresolvableSimpleAnnotationNameIsNotAFailure

      public void unresolvableSimpleAnnotationNameIsNotAFailure() throws IOException
      An annotation whose simple name resolves to nothing, in a compilation unit with no asterisk import, is not a failure: nothing (no java.lang match, no explicit import, no asterisk import -- there is none) could have supplied the name, so neither BinaryStubReader nor the text parser can resolve it either ( AnnotationFileParser.getAnnotation looks the as-written name up with Elements.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 @SuppressFBWarnings and @ConstructorProperties (used by same-package visibility, with no import) reach this case today. Contrast with unresolvableSimpleNameWithAsteriskImportFailsRatherThanBeingDropped(), 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 via Class.forName and failed, but that only proves the package is absent from the stubifier's own build classpath -- not that a checker's Elements, 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 that BinaryStubReader can never resolve either, dropping an annotation the text parser could have resolved, with no diagnostic on either side.
    • annotationWithoutTargetIsADeclarationAnnotation

      public void annotationWithoutTargetIsADeclarationAnnotation() throws IOException
      An annotation that loads but declares no @Target -- java.lang.SuppressWarnings really is one, through reflection -- must be treated as a declaration annotation, not as an unloadable class. This is the distinction between the NO_TARGET and NOT_LOADABLE sentinels.
      Throws:
      IOException
    • nestedClassOfTheFirstProcessedClassIsNotMistakenForTopLevel

      public void nestedClassOfTheFirstProcessedClassIsNotMistakenForTopLevel() throws IOException
      Regression test for a constant-pool sentinel bug: ClassRecord#outerNameIndex uses 0 to mean "top-level class" (see BinaryStubWriter.makeClassRecord's outermostFqn.isEmpty() ? 0 : pool.addString(outermostFqn)), but the constant pool does not reserve index 0 for an empty string -- the first string ever added to the pool gets index 0. 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 own outerNameIndex is that same, correct index 0 -- become indistinguishable from an actual top-level class.
      Throws:
      IOException
    • multidimensionalVarargsAnnotationPathHasOneStepPerArrayLevel

      public void multidimensionalVarargsAnnotationPathHasOneStepPerArrayLevel() throws IOException
      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, matching AnnotationFileParser's annotateInnermostComponentType (reached, on the text side, via annotateAsArray's call to it before descending the declared array levels). For a multidimensional vararg like this one -- equivalent to String[][] args -- that is two levels below the overall parameter type: one ARRAY step 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 single ARRAY step, which for this case pointed at the middle String[] level instead of the innermost String.
      Throws:
      IOException
    • varargsDeclaredTypeAnnotationPathStartsWithTheImplicitArrayStep

      public void varargsDeclaredTypeAnnotationPathStartsWithTheImplicitArrayStep() throws IOException
      Regression test for a varargs type-path off-by-one: an annotation embedded in the declared type of a vararg parameter (the @Nullable of List<@Nullable String>... args) must carry a leading ARRAY step for the vararg's implicit array level. JavaParser's Parameter.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's resolvePath hit a TYPE_ARGUMENT step on an AnnotatedArrayType, 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

      public void varargsFullyQualifiedElementTypeAnnotationGetsTheImplicitArrayStep() throws IOException
      The empty-path counterpart of varargsDeclaredTypeAnnotationPathStartsWithTheImplicitArrayStep(): 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 through extractTypeAnnotations(p.getType(), ...) with an empty path within the declared type. Without the implicit array level's leading ARRAY step, 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 (annotate on the array's component type).
      Throws:
      IOException
    • parenthesizedAnnotationValueDoesNotCrash

      public void parenthesizedAnnotationValueDoesNotCrash() throws IOException
      Regression test for an EnclosedExpr crash: redundant parentheses around an annotation value (e.g. @SuppressWarnings(("unchecked"))) are legal Java, but writeValue had no case for the parenthesized-expression AST node and fell through to its "unsupported annotation value" branch, throwing IOException -- which BinaryStubWriter.processTypes(com.github.javaparser.ast.CompilationUnit) rethrows as an uncaught RuntimeException, aborting the entire binary stub generation run over one such value anywhere in the source tree.
      Throws:
      IOException
    • mixedTargetAnnotationOnReturnTypeIsStoredInBothPlaces

      public void mixedTargetAnnotationOnReturnTypeIsStoredInBothPlaces() throws IOException
      Confirms a mixed-target annotation (valid in both declaration and TYPE_USE positions, e.g. org.checkerframework.checker.mustcall.qual.MustCallAlias, whose @Target includes both METHOD and TYPE_USE) written in declaration-position before a method's return type is stored in both MethodRecord.declAnnos and MethodRecord.returnTypeAnnos, not just one -- matching the dual-storage pattern documented at BinaryStubWriter.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

      public void recordComponentAnnotationsAndAccessorFlagAreWritten() throws IOException
      Confirms a record declaration is written as a KIND_RECORD class record with one ComponentRecord per header component, in header order, each carrying its own type annotations and hasAccessor flag: a component with an explicit zero-argument accessor of the same name in the record body must have hasAccessor == true, and one without must have hasAccessor == false -- matching AnnotationFileParser's hasAccessorInStubs semantics.
      Throws:
      IOException
    • explicitCanonicalConstructorProducesOverride

      public void explicitCanonicalConstructorProducesOverride() throws IOException
      Confirms an explicit (non-compact) canonical constructor -- one whose parameter types match the record header's components in count and order -- produces a canonicalConstructorParamAnnos override carrying the constructor's own parameter annotations, matching AnnotationFileParser's RecordStub#componentsInCanonicalConstructor.
      Throws:
      IOException
    • compactCanonicalConstructorDoesNotProduceOverride

      public void compactCanonicalConstructorDoesNotProduceOverride() throws IOException
      Confirms a compact canonical constructor (no parameter list of its own to carry annotations) does not produce a canonicalConstructorParamAnnos override, leaving the record components' own annotations as the source of truth.
      Throws:
      IOException
    • staticImportedConstantIsWrittenWithItsImportClasses

      public void staticImportedConstantIsWrittenWithItsImportClasses() throws IOException
      A bare reference to a statically-imported constant (e.g. MAX_VALUE from import 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

      public void classLiteralInCurrentPackageIsFullyQualified() throws IOException
      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" -- which BinaryStubReader#resolveSingleValue's single Elements.getTypeElement(fqName) call cannot resolve, silently dropping the class-literal annotation element.
      Throws:
      IOException
    • scopedClassLiteralIsFullyQualified

      public void scopedClassLiteralIsFullyQualified() throws IOException
      T20(b): a scoped class-literal type like Map.Entry must be qualified through its outermost scope, not skipped just because ClassOrInterfaceType.getScope() is present. Before this fix, fullyQualify(Type, CompilationUnit) qualified a ClassOrInterfaceType only when !cit.getScope().isPresent(), so Map.Entry was written as-is even with import java.util.Map; in scope.
      Throws:
      IOException
    • constantExpressionIsWrittenAsATree

      public void constantExpressionIsWrittenAsATree() throws IOException
      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: 1 is an int, 2.5f a float.
      Throws:
      IOException
    • stringValueIsUnescaped

      public void stringValueIsUnescaped() throws IOException
      A string value is written unescaped, as StringLiteralExpr#asString gives it and as the text parser reads it: "\\d+\t" is the four characters backslash, d, plus, tab.
      Throws:
      IOException
    • resolvesAnnotationNamedThroughItsEnclosingClass

      public void resolvesAnnotationNamedThroughItsEnclosingClass() throws IOException
      An annotation named through its enclosing class, as java.lang.invoke.VarHandle writes @MethodHandle.PolymorphicSignature, is resolved to its binary name so that its @Target can be read. Such a name does not load as written: the binary name separates the nesting with $.
      Throws:
      IOException
    • resolvesAFullyQualifiedNestedAnnotationName

      public void resolvesAFullyQualifiedNestedAnnotationName() throws IOException
      The same annotation written out fully qualified resolves too: the writer tries each split point of a dotted name, so java.lang.invoke.MethodHandle.PolymorphicSignature and MethodHandle.PolymorphicSignature reach the same binary name.
      Throws:
      IOException
    • resolvesADoublyNestedAnnotationName

      public void resolvesADoublyNestedAnnotationName() throws IOException
      An annotation nested two deep resolves: every segment after the package becomes a $, not just the last one.
      Throws:
      IOException