Skip to content

Gabriel Darbord

3 posts by Gabriel Darbord

Checking FAST-Java against the Java Language Specification

FAST-Java is the Moose metamodel of Java syntax trees. An importer builds a model from source with the Java parser of SmaCC, and an exporter writes a model back as source. Analyses, rewriting rules and interpreters built on FAST-Java can only be as right as that model.

This autumn we set out to answer one question: does FAST-Java handle all of Java? Unit tests and sample projects only show that it handles what they contain. This post is about how we answered the question instead, and what we fixed along the way. We did it with Claude, Anthropic’s AI model, and the last section says how. A second post presents FAST-Java v5, which grew out of this work.

FAST-Java is syntactic: it models what a program writes, not what its names resolve to. Compliance is therefore about the grammar and about what the model keeps of it. Every program that javac’s parser accepts makes a round trip through FAST-Java:

The round trip through FAST-Java

import

export

Source

FAST-Java model

Export

Same javac tree?

On the way, we check four things:

  1. Import. SmaCC parses the program and the importer builds one compilation unit, with no error.
  2. Positions. Every entity spans whole tokens of the source.
  3. Meaning. The export has the same javac syntax tree as the program, so the import lost nothing the program means.
  4. Comments. Each comment is imported once, attached to code, and written back by the export.

The other direction matters too: the parser should refuse what Java does not allow, rather than build a tree no Java program has.

Writing a source back exactly as it was is not on the list. Redundant parentheses, x -> against (x) ->, or @A() against @A are style, and the model does not keep them. The meaning check compares trees, not text.

Reading the Java Language Specification (JLS) and writing probes by hand, we twice recorded a gap in the parser that turned out not to be Java at all. Since then, every probe goes through javac before it counts, and javac decides every check above. It says which programs are valid. Its parser’s trees, compared with parentheses skipped, say whether two programs mean the same.

javac runs as a small Java server that Pharo queries over HTTP. Thousands of checks then pay for a single JVM start-up.

The sources of JDK 8 and JDK 25, every module included, hold 32,999 files written by people who know Java well. We import each one, run the checks, export it and compare. We call this run the census.

The census began with java.base alone, a fifth of JDK 25. Widening it to both whole JDKs found a grammar gap and several model defects that no file of java.base exercises. One example: outer.new Inner() { } came back as new Inner() { }, which instantiates a different type.

How the comparison is made matters as much as the corpus. We first compared the token streams of the source and of its export. Parentheses were left out, since the exporter writes its own from operator precedence. That looked safe, and it was not. When javac compared the trees instead, nearly a thousand JDK files turned out to export a different program:

SourceExported as
a - (b + c)a - b + c
((T[]) o)[0](T[]) o[0]
record R(int a) { R { } }record R(int a) { R() { } }

The last one is a different constructor, and a token comparison sees it as one more pair of parentheses. The census has compared javac trees ever since.

Comments got the same treatment last. Each comment the file writes must be imported once, belong to code, and come back once from the export. That check caught exports that wrote a comment twice, or lost one. In one case a line comment after the update of a for swallowed the parenthesis closing the header:

for (int i = 0; i < n;
i++ // next
) { }

With v4.6.0 and v5.0.0, every file passes every check:

CorpusFilesPass every check
JDK 8 sources17,63117,631
JDK 25 sources15,36815,368

FAST-Java reads Java through SmaCC’s Java grammar, which John Brant maintains. From October 19 to November 19, thirteen pull requests to SmaCC brought that grammar in line with the JLS. Each fix followed the same steps:

  1. Find a refusal.
  2. Trace it to the JLS production that allows the program.
  3. Confirm with javac that the program is Java.
  4. Change the grammar.
  5. Check that the whole JDK still parses.

Among what the grammar reads now:

JLSConstructExample
7.3Compact compilation unita file holding only void main() { }
7.5.5Module importimport module java.base;
8.8.7Statements before super(...)C(int x) { check(x); super(x); }
14.30.1Record patterno instanceof Point(var x, var y)
14.11.1null with defaultcase null, default ->
4.11Type annotationsjava.util.@A List, String @A [], (@A Object) o
3.10.2Hexadecimal float0x1p-24f
3.10.7Space escape"\s"

Some fixes go the other way. The grammar accepted yield;, sealed class A permits B<T> and 0x1.8, and javac refuses all three.

Unicode escapes took more than a grammar rule. JLS 3.3 translates \uXXXX before anything else reads the text, so an escape can change how the rest is read:

char c = '\u005cn'; // the escape writes a backslash: c is a newline

No token regular expression can express that. The scanner now reads through a stream that translates escapes, and every token still knows its position in the text as written.

A grammar change can break its consumers without any parse error, if a production starts building a different node class. So the later changes also compared the parse trees of the files that parsed before them, node by node, and kept them identical. Where an earlier change had to reshape a node, as for patterns, the old accessors stayed as deprecated readers of the new ones. Many thanks to John Brant for reviewing and merging all of them.

The JDK is a large corpus but a biased one. It writes what its authors needed, and newer features such as record patterns barely appear in it. No corpus can show what it does not contain. The last step therefore tests FAST-Java against the grammar of the JLS itself.

From a JLS goal to a test

no, try another

yes

fails

Goals from the JLS grammar

Smallest program

javac accepts it?

The four checks

Reduced program, as a test

  • Grammar. Each JLS edition is published as HTML, with every production marked up. A reader takes chapters 3 to 19 of an edition and builds its grammar. Chapter 19 is not enough on its own: it is a summary, and SE 25’s names productions it does not define.

  • Goals. From that grammar, a list of what some program must contain, taken from the grammar-testing literature:

    Two kinds of goals cover what the grammar says only in prose: samples, such as a non-ASCII letter in an identifier, and every contextual keyword used as a name.

  • Programs. For each goal not yet covered, a generator builds the smallest program that holds it. When javac refuses that program, the generator tries others:

    • the goal reached from another place;
    • one more choice nearby, like the sealed that a permits clause needs;
    • the goal inside an enclosing construct, like a switch expression around a yield.

    For SE 25, about 1,200 programs cover 2,786 goals.

  • Checks. The four checks above, on every program javac accepts. For the comment check, a comment is written before every token.

  • Reduction. A failing program is shrunk on its derivation tree. Each step is still a program of the grammar, still accepted by javac, and still failing the same way. Failures are grouped by cause, and the reduced program of each cause becomes a FAST-Java test.

Here is what the generator writes for the production of a wildcard:

Wildcard:
{Annotation} ? [WildcardBounds]
GoalProgram
No annotation, no boundsa < ? > a ( ) ;
Bounds with extendsa < ? extends a > a ( ) ;
Bounds with supera < ? super a > a ( ) ;
One annotationa < @ a ? > a ( ) ;
Two annotationsa < @ a @ a ( ) ? > a ( ) ;
An annotation with a single elementa < @ a ( 0 ) ? > a ( ) ;

Each program is a whole compact compilation unit, declaring a method whose return type writes the wildcard. Such programs mean nothing, but javac’s parser accepts every one.

The first runs found five more places where the grammar refused Java, now fixed in SmaCC:

Object o = (@A String[]) null; // an annotated array type
<T> @A void m() { } // annotations after type parameters
Inner i = a.new @A Inner(); // an annotated qualified creation
int seven = 0_7; // underscores after an octal 0
catch (@A E | @B F e) { } // annotations in a multi-catch

They also found what FAST-Java dropped. The report gives each failure group its reduced program and what the export wrote, as for these two:

ProgramExported asLost
enum a { a { } }enum a { a }the body that makes a an anonymous class
enum a { a ( new byte @ a [ this ] ) }enum a { a(new byte[this]) }the annotation on the brackets

Every fix shipped in v4.6.0. On v4.6.0 and v5.0.0, nearly every goal passes, with the same results:

JLSGoalsPassFailRefused by javac
SE 82,2902,278210
SE 172,6582,65125
SE 212,7142,70725
SE 252,7862,77826

The goals javac refuses are places where the grammar allows more than the language: final final int a, for example, which the JLS rules out in prose. The two that fail are the default modifier of an interface method. The generator writes it only on a method without a body, which javac’s parser accepts and its compiler refuses. SmaCC refuses it as well. A default method with a body imports fine, and the JDK is full of them.

  • Rules javac checks after parsing. The oracle only parses. A program such as @A(this.x) is syntactically fine and still not Java, because an annotation needs a constant. The generator writes a constant there for that reason, but other rules of that kind remain, so every failure group needs that question asked.
  • Combinations beyond pairs. Context-dependent coverage pairs each alternative with each place it is used, not with everything around it. Corpora stay useful for what real code combines.
  • Preview features. Their grammar enters the JLS only once they are final.

The grammar of each edition is data, so a new edition starts with a diff against the previous one. The productions it adds or changes get tested first, then everything is run again. SE 26 writes the same grammar as SE 25, so it needed nothing new.

The tool is grammar-coverage, a set of Pharo packages and a single-file javac server. Its README says how to run it on a JLS edition or on a corpus. Its core knows no language: Java supplies the grammar reader, the samples, javac and the FAST-Java checks. Another FAST language would supply its own.

We did this work with Claude, Anthropic’s AI model, through Claude Code. Claude worked in live Pharo images through an MCP server, and in headless images for the long runs. It wrote most of the code: the SmaCC grammar changes, the FAST-Java fixes and their tests, and grammar-coverage. It also ran the censuses, traced failures back to the JLS, and drafted the pull requests, the commit messages and these two posts.

I set the direction, reviewed every change before merging it, and made the design calls. Several of them overruled a first proposal:

  • Claude first made the export token-exact, with model properties recording redundant parentheses. I turned those pull requests down: the model keeps what changes meaning, not how code is spelled.
  • When it gave a package declaration the trait that holds modifiers, I asked why a package should be able to hold public. That question became the rule that annotations are not modifiers.
  • Its first fix for comments written twice kept a record of the comments already written. I asked for a fix without that state, and now each node writes its own comments and no other.
  • Fixes went to v4 first, because it was the version in production, and were then ported to v5.

The oracles mattered as much as the reviews. The two probes recorded as parser gaps that were not Java were Claude’s, and javac caught them. Twice, a change to the v5 metamodel passed every test and broke more than a thousand JDK files, and the census caught it. An agent writes a fix quickly; javac, the JDK and the grammar say whether the fix is right.

FAST-Java v5: a model of what Java writes

FAST-Java v5.0.0 is out. It is the first release of a new major version of the Moose metamodel of Java syntax trees, and it breaks code written for v4. MIGRATION.md says what to write instead.

Checking FAST-Java against the Java Language Specification found more than missing constructs. The model could also hold programs that no Java compiler accepts, and it described the same text in different ways depending on where it stood. Fixes that kept every reader working went into v4 releases. The others change what a reader finds in the model, so they make a major version.

v5 does not read more Java than v4.6.0: both import and export the same programs, as the checks below show. What changes is how the model says it. Each construct gets one entity of its own, and the model cannot hold what Java cannot write.

The model holds what Java writes, and nothing else

Section titled “The model holds what Java writes, and nothing else”

A model that can hold what Java cannot write is no help to an analysis, and lets a transformation build code that does not compile. v5 removes those possibilities wherever the JLS rules them out.

Annotations are not modifiers. For @Deprecated public final void m():

v4v5
modifiers@Deprecated, public, finalpublic, final
annotations—@Deprecated

Both keep their positions, so the export still writes them in the order of the source. Code that picked the annotations out of the modifiers now reads them directly:

"v4"
aMethod modifiers select: [ :each | each isAnnotation ].
"v5"
aMethod annotations.

The other changes of this kind:

  • An array creation is not a class instance creation. new int[3] no longer inherits arguments, a receiver or type arguments, which JLS 15.10.1 never writes.
  • A type is not a variable. In v4, a type could be assigned to, used as a try resource or written as an annotation element. Now it can only be what Java lets it be: a type, or the receiver of a method reference such as String::length.
  • Relations are typed as narrowly as the grammar allows. Ten relations hold class types rather than any type, such as a superclass, the interfaces a class implements, or the types a catch catches. We first checked over 6,013 JDK files that none of them ever held anything else.
  • An element-value pair is not an assignment. @A(x = 1) names an element of A and assigns nothing. It is a FASTJavaElementValuePair. v4 read it as an assignment, which made its value an expression, though an annotation is not one.
  • An element value is a constant. javac’s parser reads @A(this) and @A(m()), but JLS 9.7.1 requires a constant there and javac refuses both. The import refuses them too, with an error that names the rule.
  • A permits clause holds type names. JLS 8.1.6 writes only names after permits, without type arguments or annotations.
  • A text block is a literal of its own. It is a FASTJavaTextBlock, and its value is what stands between its two runs of three quotes, where v4 kept two of the quotes at each end.

v4 often chose an entity’s class from where it stood. v5 reads the same text the same way everywhere.

A dotted name is one entity. JLS 6.5 leaves a dotted name ambiguous until it is resolved: in com.foo.Bar.CONSTANT, only name resolution can tell that com.foo is a package, Bar a type and CONSTANT a field. FAST-Java does not resolve names. v4 read a dotted name as a FASTJavaQualifiedName outside type declarations and as a FASTJavaClassProperty inside them. v5 reads it the same way everywhere, as a chain of FASTJavaQualifiedName:

The namespaces of a dotted name

namespace

namespace

namespace

CONSTANT

Bar

foo

com

super is an entity. v4 read the keyword in four ways, v5 in one:

Writtenv4v5
super.go()an identifier named superFASTJavaSuper
super.fa variable named superFASTJavaSuper
super::gonothing at allFASTJavaSuper
T.super.go()a field access named superFASTJavaSuper, qualified by T

this is one entity in the same way, qualified or not.

var is inferred only where Java infers it. v4 read var as the inferred type wherever a type was written. JLS 14.4.1 and 15.27.1 infer it only for a local variable and a lambda parameter:

Writtenv5 reads var as
var x = 1;the inferred type
for (var s : list)the inferred type
(var a) -> athe inferred type
void m(var p)a type named var

v5.0.0 passes the same checks as v4.6.0:

  • its whole test suite;
  • every file of the JDK 8 and JDK 25 sources, 32,999 in all, imported, exported and compared with javac;
  • the programs generated from the grammars of JLS SE 8, 17, 21 and 25, with the same results goal for goal.

The first post explains these checks.

MIGRATION.md has one section per change, each with a table of what to write instead. For example:

v4v5
FASTJavaClassPropertyFASTJavaQualifiedName
aClassProperty fieldNameaQualifiedName name
aClassProperty typeaQualifiedName namespace

Two changes break silently, so look for them in your code:

  • A type no longer has a name. Reading it answers #noname instead of raising, so look for its senders.
  • aModel allWithType: FASTJavaStringLiteral no longer answers text blocks, which are a subclass now.

FAST-Java-Deprecated is gone with the major. Every method it held already named its replacement.

Like the compliance work, v5 was written with Claude, Anthropic’s AI model. Claude wrote most of the code and the migration notes. I set the principles above and reviewed every change. The first post says more about how we worked.

Building and sharing Moose models with MooseNexus

Building a Moose model is often only the first step of an analysis. We also need to know which source project produced it, which dependencies were used, which tools extracted it, and how another person can build or retrieve the same model.

MooseNexus brings these steps into one repeatable workflow. It builds Moose models, records how they were produced, stores them as versioned artifacts, and can share them through an artifact registry.

This post first uses the MooseNexus API from a Moose image, then performs the same kind of build with the command-line interface. The final section explains how an artifact registry can store and distribute the resulting models and images.

MooseNexus sits between a source project and the Moose model that we want to analyze.

A source project and build specification flow through model extraction into a versioned artifact, which can be stored locally or in a shared registry.

From source project to versioned model artifact: MooseNexus records the result locally and can publish it to a shared artifact registry.

A build starts with two pieces of information:

  • the directory containing the source project;
  • coordinates that identify it: a group, a name, and a version.

MooseNexus then imports the project metadata, resolves the dependencies needed for extraction, runs the model extractor, and records the result. For Java projects it can recognize Maven and Gradle projects. Projects without a supported build descriptor can be described explicitly as unmanaged projects.

The result is more than a model file. A model artifact also records its source-project identity, dependency-resolution result, and build provenance, including the Moose, Pharo, MooseNexus, and extractor versions. This information makes it possible to inspect how a model was produced and to select a compatible environment later.

By default, projects and artifacts are kept in a local repository below ~/.moose. The important principle is similar to Maven coordinates: com.example:demo:1.0.0 identifies one version of a project independently of the machine on which it was analyzed.

The main API entry point is MooseNexusBuildSpec. A build specification describes the intended result; MooseNexus handles the individual import, dependency, extraction, and storage steps.

For a Java project, load the Java runtime group in a Moose image:

Metacello new
githubUser: 'moosetechnology'
project: 'MooseNexus'
commitish: 'v1.x.x'
path: 'src';
baseline: 'MooseNexus';
load: 'Java'.

The floating v1.x.x tag selects the newest compatible version in the MooseNexus 1.x series. Use an exact release tag when the build must be fully reproducible.

Let us build a model for a project located at /path/to/demo. We first give it stable coordinates:

coordinates := MooseNexusCoordinates
group: 'com.example'
name: 'demo'
version: '1.0.0'.

The coordinates identify the project in the local repository and, later, in an artifact registry. They do not need to be the same as Maven or Gradle coordinates, although using the same identity can be convenient.

Create a build specification from the coordinates and source directory:

spec := MooseNexusBuildSpec
coordinates: coordinates
sourceDirectory: '/path/to/demo' asFileReference.
spec
modelName: 'demo-model';
modelComment: 'Model used for the architecture analysis'.

The source directory can be anywhere; it does not have to be a Git checkout. For a Maven or Gradle project, MooseNexus detects the appropriate importer from the directory. The explicit coordinates remain the identity of the MooseNexus artifact.

This separation is useful: the build tool describes how the software project is assembled, while the build specification describes the model artifact that we want MooseNexus to produce.

Execute the specification in the default repository:

result := spec execute.

This performs the complete workflow and records the project below the default ~/.moose repository. The result gives access to three useful objects:

result project.
result modelArtifact.
result dependencyResolutionResult.

Use executeIn: with a MooseNexusRepository when the artifact should be stored elsewhere:

repository := MooseNexusRepository
localDirectory: '/path/to/model-repository' asFileReference.
result := spec executeIn: repository.

Building records the artifact but does not force it into the current image. Import it explicitly when it is time to analyze it:

model := result project importModel: result modelArtifact.

The imported model is registered in MooseModel root. Keeping the build and import steps separate also lets headless jobs produce artifacts without retaining a full analysis image.

For most clients, execute or executeIn: is the API to keep. MooseNexus also exposes the individual build phases, but those are mainly useful when an application needs custom orchestration.

The MooseNexus CLI runs the same ideas without requiring us to prepare a Moose image by hand. It creates an isolated workspace, provisions a compatible Moose/Pharo runtime, loads MooseNexus, executes a build specification, and stores the result.

Install it with npm. The CLI requires Node.js 22 or later:

Terminal window
npm install --global @moosetechnology/moosenexus

For Java extraction, the default setup also requires Docker. We can check the available tools before starting a build:

Terminal window
moosenexus doctor

The interactive wizard is the easiest way to discover the commands:

Terminal window
moosenexus --wizard

For a Maven or Gradle project, a direct build can be as small as:

Terminal window
moosenexus build-model \
com.example:demo:1.0.0 \
/path/to/demo

This creates a model artifact and installs it in the local MooseNexus repository. To create a ready-to-open Moose image containing the imported model instead, use build-image:

Terminal window
moosenexus build-image \
com.example:demo:1.0.0 \
/path/to/demo \
--adopt

The built image is first stored as an immutable artifact. --adopt also copies it to the standard Pharo images directory, where it becomes a working image that we can open and modify.

The two outputs serve different needs:

  • a model artifact is smaller and can be imported into a compatible existing Moose image;
  • an image artifact is a ready-to-open environment containing the model and its compatible runtime.

An image artifact is selective rather than a copy of the complete build workspace. Its portable ZIP contains:

  • at its root, the .image file, its .changes file when available, the available Pharo .sources files, meta-inf.ston, pharo.version, and a CLI build report;
  • under pharo-local/MooseNexus/, the recorded project metadata, model artifact, and a copy of the analyzed source project.

Other image-local directories, such as pharo-local/iceberg, and the Pharo VM are not included. MooseNexus does not scan these files for credentials or remove secrets: the source copy, saved image, or changes file may contain sensitive information. Review an artifact before publishing it.

An installed image artifact can be adopted several times, much like making working copies from a template. Each adoption creates a separate writable image while leaving the repository artifact unchanged:

Terminal window
moosenexus adopt-image com.example:demo:1.0.0
moosenexus adopt-image com.example:demo:1.0.0 --adopt-as demo-alice

By default, these copies are placed in the standard Pharo images directory and appear in Pharo Launcher. This is not a Launcher template: MooseNexus copies the image files and launcher metadata from an installed artifact. The recorded project and source copy remain in the local MooseNexus repository rather than being duplicated into every adopted image.

Use moosenexus artifacts to see what is installed locally. Build options can also be kept in a YAML file and passed with --config, which is preferable for repeatable scripts and continuous integration. --dry-run shows the resolved workflow without executing it, and --json produces machine-readable output for automation.

The important need here is artifact storage and distribution: a shared place where versioned Moose models and images can be published, found, and retrieved.

MooseNexus currently implements this with the Open Container Initiative distribution conventions. Although OCI is best known for container images, its registries can store other versioned artifacts as well. Reusing that standard gives MooseNexus an existing upload, download, authentication, and access-control ecosystem instead of inventing a Moose-specific artifact server.

An organization can therefore use infrastructure it may already have—such as Harbor, Sonatype Nexus, Artifactory, or another OCI-compatible registry—to distribute Moose models and images. MooseNexus defines what goes into the artifact, while ORAS performs the standard registry upload and download.

A MooseNexus model bundle contains:

  • the exported model;
  • an archive of the analyzed sources;
  • the project metadata;
  • the model manifest, including build and extractor provenance.

Including the sources makes the artifact inspectable and helps reproduce the model, but it is also important to remember before publishing: a model bundle can contain proprietary source code. Use a registry and access policy appropriate for the project.

First authenticate ORAS with the target registry:

Terminal window
oras login registry.example.com

Then add a registry and namespace to the build command:

Terminal window
moosenexus build-model \
com.example:demo:1.0.0 \
/path/to/demo \
--registry registry.example.com \
--namespace team/models

MooseNexus still installs the artifact locally and also publishes it under a reference derived from the project coordinates, for example:

registry.example.com/team/models/moosenexus/com.example/demo:1.0.0

Another machine can retrieve the model with the same coordinates:

Terminal window
moosenexus pull-model \
com.example:demo:1.0.0 \
--registry registry.example.com \
--namespace team/models

pull-model installs the artifact in the local MooseNexus repository. It can then be imported through the API shown earlier. Use pull-image ... --adopt when the published artifact is a Moose image and a ready-to-open copy is wanted instead.

Publication is always explicit: building locally does not silently upload anything. MooseNexus also keeps registry credentials outside its own configuration and relies on the authenticated ORAS installation.

Both interfaces use the same project coordinates, build specification, repository, and artifact concepts.

Use the API when…Use the CLI when…
the build is part of a Moose applicationthe build should start from a clean, isolated runtime
an image needs custom import or extraction policya shell script or CI job should run the build
the resulting model will be analyzed immediatelya model or ready-to-open image should be produced and shared

The API is the stable foundation, and the CLI automates the surrounding runtime setup. Starting with the CLI is often easier; moving to a Smalltalk build specification gives more control without changing the underlying model-artifact workflow.

MooseNexus therefore turns a one-off model extraction into a named, versioned, and shareable build result. That becomes especially valuable when a model must outlive the image in which it was first created—or when another person, machine, or CI job needs to produce the same analysis input.