Interpreter

Intent
For a small language, represent each rule of its grammar with a class; a sentence becomes a tree of those objects, and each one knows how to evaluate itself.
Application
Coaches write WODs in their own notation, like "3 x (10 burpees + 15 air-squats)". Turn each rule of that notation into a class and let the tree interpret itself.
WodControllerSplitCounter (regex)

SplitCounter, highlighted in red, gets "3 x (10 burpees + …)" from the controller and chops it up with regular expressions.

The nested round "3 x (5 pull-ups)", highlighted in red, doesn't match the pattern and gets lost; only the burpees are left.

The WodExpression interface appears, highlighted, with two of the rules implementing it: Repeat and Movement.

The tree's two leaves, Movement 10 burpees and Movement 15 air-squats, highlighted; the first adds its reps to the Tally.

Repeat 3 x, highlighted, passes Sequence the factor multiplied by 3.

The whole tree highlighted: Repeat calls Sequence with factor 3 and Sequence calls its two movements.

WodParser, highlighted, turns "3 x (…)" into the expression tree.

POST /api/wods/totals travels from the coach to the controller, which hands the text to WodParser and interprets the tree with a new Tally; WodParser and Tally are highlighted.

The SpEL tree for "reps * rounds + 10": SpelExpressionParser creates OpPlus, highlighted, which holds OpMultiply, also highlighted, with reps and rounds, and the literal 10.

Final view: the coach, the controller, WodParser, the tree of Repeat, Sequence and both movements, and the Tally, all inside the Spring context.

Step 1 of 10

Tricks with the text

Coaches write WODs in their own notation: "3 x (10 burpees + 15 air-squats)". The app has to know how many reps of each movement that adds up to.

The first version, SplitCounter, uses a regular expression to strip one "N x ( … )" and splits the rest on the "+". With one round it works: 30 burpees and 45 air-squats.

Step 2 of 10

Nesting gets lost

"2 x (3 x (5 pull-ups) + 10 burpees)". The regular expression strips the outer round, splits on "+" and finds "3 x (5 pull-ups)", which doesn't match "N movement". It skips it without a word: 20 burpees and no pull-ups. The SplitCounterTest test proves it.

Fixing it with more regular expressions never ends: every level of nesting is another case.

Step 3 of 10

One class per rule

Interpreter turns each rule of the notation into a class. They all share the WodExpression interface, with a single method: interpret(tally, factor).

The interface is sealed: the rules are exactly three, Movement, Sequence and Repeat.

Step 4 of 10

The smallest rule

Movement is a terminal expression: "10 burpees" contains no other expressions. When interpreted, it adds its reps, multiplied by the factor, to the Tally.

The Tally is the pattern's context: the place where the expressions leave the result.

Step 5 of 10

Rules that contain others

Repeat ("3 x ( … )") and Sequence ("a + b") are nonterminal expressions: they contain others. Repeat interprets its body with the factor multiplied by its rounds (and Sequence, its parts one after another, with the same factor).

So in "2 x (3 x (5 pull-ups))" the movement gets factor 6 without anyone counting levels.

(In the book, interpret takes only the context. The factor could live in the Tally, with Repeat pushing and popping a multiplier; passing it as an argument keeps the context a plain accumulator.)

Step 6 of 10

A sentence is a tree

"3 x (10 burpees + 15 air-squats)" is this tree: a Repeat of 3 with a Sequence inside, and two Movements as leaves. The test builds it by hand and interprets it: 75 reps.

The shape is a Composite's: leaves and nodes that contain nodes, all with the same operation. The difference is where the classes come from: here they come from the grammar (Sequence exists because the notation has +, not because the box groups anything), the tree stands for a sentence of a language and it's interpreted against a context. The same tree could be read with another context, say one that draws it on the whiteboard.

Step 7 of 10

From text to tree

Nobody writes trees by hand: WodParser turns the text into the tree. It has one method per grammar rule (sequence and term), and they call each other where the grammar is recursive. Movement names are a single word, with hyphens (air-squats).

If the text is wrong, it says where: "expected ')' at position 15". The parser caps the length (200 characters), the depth (5 levels) and the numbers (1 to 1000); the Tally refuses more than 100,000 reps.

With the tree, the case that broke the earlier version works: "2 x (3 x (5 pull-ups) + 10 burpees)" gives 30 pull-ups and 20 burpees, and no expression knows how deep it is.

Step 8 of 10

Over HTTP

POST /api/wods/totals with the nested WOD answers the totals per movement and the 50 reps. A badly written notation answers 400 with the error's position.

Step 9 of 10

Spring already does it for you

SpEL, Spring's expression language (the one in @Value("#{...}"), @PreAuthorize or @Cacheable(condition = ...)), is an Interpreter. parseExpression("reps * rounds + 10") builds a tree of nodes: an OpPlus with an OpMultiply and a literal inside. When evaluating, each node works out its value by asking its children.

The test evaluates the expression with SimpleEvaluationContext, which only allows reading properties. Never evaluate SpEL coming from outside with the full context: it can call any class.

Step 10 of 10

Recap

You started chopping text with regular expressions and ended up with:

  • An abstract expression, WodExpression, with interpret().
  • A terminal, Movement, and two nonterminals, Sequence and Repeat.
  • A context, Tally, where the result builds up, and a parser that builds the tree.

Its neighbours: the structure is a Composite, but Composite is about part–whole objects and Interpreter about giving meaning to the sentences of a grammar. If you need many different operations over the tree (counting, validating, printing), a Visitor, or a switch over the sealed interface, takes them out of the classes. And an Iterator can walk the tree without interpreting it.

When not to use it: if the grammar is big or changes a lot, a parser generator (ANTLR) or an existing language (SpEL, JSON with a schema) saves you writing dozens of classes. And if there's no nesting, there's no recursion to model: splitting the text is enough.

Cheatsheet →

Code

SplitCounter.java

public Map<String, Integer> count(String wod) {
    int rounds = 1;
    String body = wod.strip();
    Matcher m = ROUNDS.matcher(body);
    if (m.matches()) { rounds = Integer.parseInt(m.group(1)); body = m.group(2); }
    Map<String, Integer> totals = new LinkedHashMap<>();
    for (String part : body.split("\\+")) {
        Matcher mv = MOVEMENT.matcher(part.strip());
        if (mv.matches()) totals.merge(mv.group(2), Integer.parseInt(mv.group(1)) * rounds, Integer::sum);
        // "3 x (5 pull-ups)" doesn't match: skipped without a word
    }
    return totals;
}

SplitCounter.java

public Map<String, Integer> count(String wod) {
    int rounds = 1;
    String body = wod.strip();
    Matcher m = ROUNDS.matcher(body);
    if (m.matches()) { rounds = Integer.parseInt(m.group(1)); body = m.group(2); }
    Map<String, Integer> totals = new LinkedHashMap<>();
    for (String part : body.split("\\+")) {
        Matcher mv = MOVEMENT.matcher(part.strip());
        if (mv.matches()) totals.merge(mv.group(2), Integer.parseInt(mv.group(1)) * rounds, Integer::sum);
        // "3 x (5 pull-ups)" doesn't match: skipped without a word
    }
    return totals;
}

WodExpression.java

/** One rule of the WOD notation. Each kind of expression knows how to interpret itself. */
public sealed interface WodExpression permits Movement, Sequence, Repeat {
    /** Adds this expression's reps to the tally; factor is how many times the rounds around it repeat. */
    void interpret(Tally tally, long factor);
}

Movement.java

/** Terminal expression: "10 burpees". */
public record Movement(int reps, String name) implements WodExpression {
    @Override
    public void interpret(Tally tally, long factor) {
        tally.add(name, reps * factor);
    }
}

Repeat.java

/** Nonterminal expression: "3 x ( … )". It interprets its body with the factor multiplied. */
public record Repeat(int times, WodExpression body) implements WodExpression {
    @Override
    public void interpret(Tally tally, long factor) {
        body.interpret(tally, factor * times);
    }
}

WodInterpreterTest.java

WodExpression wod = new Repeat(3, new Sequence(java.util.List.of(
    new Movement(10, "burpees"),
    new Movement(15, "air-squats"))));
Tally tally = new Tally();
wod.interpret(tally, 1);
assertThat(tally.reps()).isEqualTo(75);

WodParser.java

private WodExpression sequence(Cursor c, int depth) {
    List<WodExpression> parts = new ArrayList<>(List.of(term(c, depth)));
    while (c.accept('+')) parts.add(term(c, depth));
    return parts.size() == 1 ? parts.get(0) : new Sequence(parts);
}

private WodExpression term(Cursor c, int depth) {
    int n = c.number();
    String word = c.word();
    if (!word.equals("x")) return new Movement(n, word);              // "10 burpees"
    if (depth + 1 > MAX_DEPTH) throw new InvalidWodException("at most " + MAX_DEPTH + " levels of rounds");
    c.expect('(');
    WodExpression body = sequence(c, depth + 1);
    c.expect(')');
    return new Repeat(n, body);                                        // "3 x ( … )"
}

WodApiTest.java

mvc.perform(post("/api/wods/totals").contentType(MediaType.APPLICATION_JSON)
        .content("{\"wod\":\"2 x (3 x (5 pull-ups) + 10 burpees)\"}"))
   .andExpect(status().isOk())
   .andExpect(jsonPath("$.totals.pull-ups").value(30))
   .andExpect(jsonPath("$.totals.burpees").value(20))
   .andExpect(jsonPath("$.reps").value(50));

SpringDoesItTooTest.java

SpelExpression expr = (SpelExpression) new SpelExpressionParser().parseExpression("reps * rounds + 10");
SpelNode root = expr.getAST();                       // OpPlus( OpMultiply(reps, rounds), 10 )

var ctx = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Integer total = expr.getValue(ctx, new Round(15, 3), Integer.class);

WodInterpreterTest.java

WodExpression wod = parser.parse("2 x (3 x (5 pull-ups) + 10 burpees)");
Tally tally = new Tally();
wod.interpret(tally, 1);

assertThat(tally.totals()).containsExactly(Map.entry("pull-ups", 30), Map.entry("burpees", 20));

Quiz

1. In "2 x (5 pull-ups + 10 burpees)", what is a terminal expression?

2. Coaches want to write "21-15-9 thrusters". What do you change?

3. Why does Repeat pass factor × times to its body instead of adding itself?

4. What makes a Spring SpEL expression an Interpreter?

Cheatsheet →

Run it