Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
creating:jlists [2025/04/21 20:21] – Created page with introduction ahelwer | creating:jlists [2025/05/21 18:21] (current) – Disjunction does not short-circuit ahelwer | ||
---|---|---|---|
Line 14: | Line 14: | ||
/\ B | /\ B | ||
/\ \/ C | /\ \/ C | ||
- | \/ D | + | \/ D |
</ | </ | ||
Here, ''/ | Here, ''/ | ||
- | If a set of conjuncts or disjuncts are vertically aligned (have the same start column) then those juncts are grouped together. | + | If a set of conjuncts or disjuncts |
So, we want to parse the above example as '' | So, we want to parse the above example as '' | ||
This is a very nice language feature, but parsing these lists properly is the greatest challenge we've yet faced. | This is a very nice language feature, but parsing these lists properly is the greatest challenge we've yet faced. | ||
It is only a slight exaggeration to say the purpose of this entire tutorial series is to teach you how to parse these jlists. | It is only a slight exaggeration to say the purpose of this entire tutorial series is to teach you how to parse these jlists. | ||
Let's begin! | Let's begin! | ||
+ | |||
+ | ====== A First Attempt ====== | ||
+ | |||
+ | Before we increase the complexity of our parser, let's convince ourselves it is necessary. | ||
+ | We will attempt to parse jlists using familiar recursive descent techniques, then see where it goes wrong. | ||
+ | At first this seems like it should be possible! | ||
+ | Our jlists resemble the set constructor '' | ||
+ | There isn't really a terminating token but that does not seem to be an obstacle. | ||
+ | So, try adding this to the '' | ||
+ | |||
+ | <code java [highlight_lines_extra=" | ||
+ | return new Expr.Variadic(operator, | ||
+ | } | ||
+ | |||
+ | if (match(AND, OR)) { | ||
+ | Token op = previous(); | ||
+ | List< | ||
+ | do { | ||
+ | juncts.add(expression()); | ||
+ | } while (matchBullet(op.type, | ||
+ | return new Expr.Variadic(op, | ||
+ | } | ||
+ | |||
+ | throw error(peek(), | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Remember our special '' | ||
+ | Now we put it to use in a new helper function for the '' | ||
+ | <code java> | ||
+ | private boolean matchBullet(TokenType op, int column) { | ||
+ | if (peek().type == op && peek().column == column) { | ||
+ | advance(); | ||
+ | return true; | ||
+ | } | ||
+ | |||
+ | return false; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | '' | ||
+ | In this way our jlist parsing logic will only add another expression if it finds another vertically-aligned ''/ | ||
+ | This all... kind of works? | ||
+ | You can parse a surprisingly broad set of jlists with just our simple logic! | ||
+ | Try it out; here are some jlists that can now be parsed: | ||
+ | <code haskell> | ||
+ | op == | ||
+ | /\ 1 | ||
+ | /\ 2 | ||
+ | </ | ||
+ | <code haskell> | ||
+ | op == | ||
+ | \/ 1 | ||
+ | \/ 2 | ||
+ | </ | ||
+ | <code haskell> | ||
+ | op == | ||
+ | /\ 1 | ||
+ | /\ \/ 2 | ||
+ | \/ 3 | ||
+ | </ | ||
+ | Make them as nested and wild as you like, our code will handle them! | ||
+ | So are we done? | ||
+ | Unfortunately not. | ||
+ | Here's the proverbial wrench: TLA⁺ also allows '' | ||
+ | We skipped defining them in the expressions chapter where we learned how to parse operators of different precedences; | ||
+ | |||
+ | <code java [highlight_lines_extra=" | ||
+ | private static final Operator[] operators = new Operator[] { | ||
+ | new Operator(Fix.PREFIX, | ||
+ | new Operator(Fix.PREFIX, | ||
+ | new Operator(Fix.PREFIX, | ||
+ | new Operator(Fix.INFIX, | ||
+ | new Operator(Fix.INFIX, | ||
+ | new Operator(Fix.INFIX, | ||
+ | </ | ||
+ | |||
+ | Just like that, our jlist parsing code no longer works. | ||
+ | '' | ||
+ | So, a jlist like: | ||
+ | <code haskell> | ||
+ | op == | ||
+ | /\ 1 | ||
+ | /\ 2 | ||
+ | /\ 3 | ||
+ | </ | ||
+ | is parsed as a jlist with a single conjunct, the expression '' | ||
+ | This is awful! | ||
+ | How can we fix it? | ||
+ | |||
+ | ====== Beyond Context-Free ====== | ||
+ | |||
+ | The answer to our parsing problem is deceptively simple: before matching a token in '' | ||
+ | If the token instead starts to the left or equal to the current jlist' | ||
+ | If we aren't currently parsing a jlist then '' | ||
+ | |||
+ | For readers who have taken a computer science class in formal languages, alarm bells should be going off - changing the parse behavior depending on the current context is a //big// change! | ||
+ | In theoretical terms, our parser is currently // | ||
+ | The context - or surrounding code being parsed - does not change how '' | ||
+ | However, if we want to parse jlists correctly we will need to break this limitation and move to the more powerful // | ||
+ | |||
+ | What does this change mean in practical terms? | ||
+ | First, it means we cannot easily write the formal TLA⁺ grammar in Backus-Naur Form (BNF) as we learned to do in [[https:// | ||
+ | Although grammar notation [[https:// | ||
+ | Thus formal TLA⁺ grammars exclude jlists and use BNF to define the non-jlist parts of the language, then use plain language to describe how jlists work. | ||
+ | Second - returning to our parser implementation here - it means that our '' | ||
+ | |||
+ | Ultimately the shape of this state is a stack of nested jlists. | ||
+ | Each entry in the stack records the column of a jlist' | ||
+ | When we start parsing a new jlist, we push its column to this stack. | ||
+ | When we finish parsing a jlist, we pop from the stack. | ||
+ | The top of this stack is the " | ||
+ | |||
+ | We'll be using Java's '' | ||
+ | It only needs to hold the jlist column. | ||
+ | Define a new class variable near the top of the '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | private final List< | ||
+ | private int current = 0; | ||
+ | private final boolean replMode; | ||
+ | private final ArrayDeque< | ||
+ | </ | ||
+ | |||
+ | Import '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | package tla; | ||
+ | |||
+ | import java.util.List; | ||
+ | import java.util.ArrayList; | ||
+ | import java.util.ArrayDeque; | ||
+ | |||
+ | import static tla.TokenType.*; | ||
+ | |||
+ | class Parser { | ||
+ | </ | ||
+ | |||
+ | Now augment our jlist parsing logic in '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | if (match(AND, OR)) { | ||
+ | Token op = previous(); | ||
+ | jlists.push(op.column); | ||
+ | List< | ||
+ | do { | ||
+ | juncts.add(expression()); | ||
+ | } while (matchBullet(op.type, | ||
+ | jlists.pop(); | ||
+ | return new Expr.Variadic(op, | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Then add this critical line to the '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | private boolean check(TokenType type) { | ||
+ | if (isAtEnd()) return false; | ||
+ | if (!jlists.isEmpty() && peek().column <= jlists.peek()) return false; | ||
+ | return peek().type == type; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | This works! | ||
+ | We can parse jlists again! | ||
+ | It's a bit tricky to figure out how this changes things in practice, so let's take a close look at our infix operator parsing code in '' | ||
+ | <code java> | ||
+ | Expr expr = operatorExpression(prec + 1); | ||
+ | while ((op = matchOp(Fix.INFIX, | ||
+ | Token operator = previous(); | ||
+ | Expr right = operatorExpression(op.highPrec + 1); | ||
+ | expr = new Expr.Binary(expr, | ||
+ | if (!op.assoc) return expr; | ||
+ | } | ||
+ | </ | ||
+ | Consider what happens when trying to parse this TLA⁺ snippet: | ||
+ | <code haskell> | ||
+ | op == | ||
+ | /\ 1 | ||
+ | /\ 2 | ||
+ | </ | ||
+ | The parser will: | ||
+ | - look for an expression following '' | ||
+ | - find ''/ | ||
+ | - find '' | ||
+ | - call '' | ||
+ | - in '' | ||
+ | - never enter the infix op parsing loop and return '' | ||
+ | - in the jlist loop, call '' | ||
+ | |||
+ | If the line we added in '' | ||
+ | But we pre-empted it! | ||
+ | So now ''/ | ||
+ | Note that our '' | ||
+ | |||
+ | There is one other benefit we've unlocked. | ||
+ | It isn't enough to parse valid jlists, we must also reject invalid ones! | ||
+ | The TLA⁺ language specification requires that the parser reject attempts to defeat vertical alignment encapsulation by abusing delimiters like '' | ||
+ | What this means is that inputs like the following should fail to parse: | ||
+ | <code haskell> | ||
+ | op == | ||
+ | /\ 1 | ||
+ | /\ (2 | ||
+ | ) | ||
+ | /\ 3 | ||
+ | </ | ||
+ | Indeed, our parser will detect an error here. | ||
+ | The parentheses parsing logic will call '' | ||
+ | This gives rise to a parse error. | ||
+ | |||
+ | ====== Error Recovery ====== | ||
+ | |||
+ | Talk of parsing errors nicely segues us onto the topic of error recovery. | ||
+ | Recall that on error, we call '' | ||
+ | Jlists complicate this a bit! | ||
+ | What happens if an error occurs while parsing a jlist and we enter '' | ||
+ | Well, nonsensical things happen. | ||
+ | To fix this we just wipe out our jlist stack at the top of '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | private void synchronize() { | ||
+ | jlists.clear(); | ||
+ | advance(); | ||
+ | |||
+ | while (!isAtEnd()) { | ||
+ | </ | ||
+ | |||
+ | Done. | ||
+ | You've successfully parsed vertically-aligned conjunction & disjunction lists in TLA⁺! | ||
+ | This puts you in rarified air. | ||
+ | Only a handful of people in the world possess this knowledge, and now you are among them. | ||
+ | |||
+ | ====== Evaluation ====== | ||
+ | |||
+ | Now that we can parse jlists, let's interpret them. | ||
+ | Similar to the logical operators covered in the book, conjunction lists short-circuit. | ||
+ | That means conjuncts are evaluated in order and, if a single conjunct is false, evaluation immediately stops and returns false. | ||
+ | In an odd contrast, disjunction lists do //not// short-circuit; | ||
+ | |||
+ | Add conjunction list evaluation logic to '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | return set; | ||
+ | case AND: | ||
+ | for (Expr conjunct : expr.parameters) { | ||
+ | Object result = evaluate(conjunct); | ||
+ | checkBooleanOperand(expr.operator, | ||
+ | if (!(boolean)result) return false; | ||
+ | } | ||
+ | return true; | ||
+ | default: | ||
+ | // Unreachable. | ||
+ | return null | ||
+ | </ | ||
+ | |||
+ | Then add the disjunction list logic right below that: | ||
+ | <code java [highlight_lines_extra=" | ||
+ | return true; | ||
+ | case OR: | ||
+ | boolean result = false; | ||
+ | for (Expr disjunct : expr.parameters) { | ||
+ | Object junctResult = evaluate(disjunct); | ||
+ | checkBooleanOperand(expr.operator, | ||
+ | result |= (Boolean)junctResult; | ||
+ | } | ||
+ | return result; | ||
+ | default: | ||
+ | // Unreachable. | ||
+ | return null; | ||
+ | </ | ||
+ | |||
+ | Remember we also parsed the ''/ | ||
+ | This is a bit annoying! | ||
+ | They should function in the exact same way as their respective jlists, but now we have to copy a duplicate of our evaluation logic to '' | ||
+ | So, we'll perform a trick which also has its parallel in chapter 9 of the book: [[https:// | ||
+ | We will flatten infix ''/ | ||
+ | |||
+ | In the '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | Expr expr = operatorExpression(prec + 1); | ||
+ | while ((op = matchOp(Fix.INFIX, | ||
+ | Token operator = previous(); | ||
+ | Expr right = operatorExpression(op.highPrec + 1); | ||
+ | expr = flattenInfix(expr, | ||
+ | if (!op.assoc) return expr; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Define '' | ||
+ | <code java> | ||
+ | private Expr flattenInfix(Expr left, Token op, Expr right) { | ||
+ | if (op.type == AND) { | ||
+ | | ||
+ | } else if (op.type == OR) { | ||
+ | | ||
+ | } else { | ||
+ | return new Expr.Binary(left, | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | The helper returns a regular binary expression except when the operator is '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | private Expr flattenInfix(Expr left, Token op, Expr right) { | ||
+ | if (op.type == AND) { | ||
+ | List< | ||
+ | conjuncts.add(left); | ||
+ | conjuncts.add(right); | ||
+ | return new Expr.Variadic(op, | ||
+ | } else if (op.type == OR) { | ||
+ | List< | ||
+ | disjuncts.add(left); | ||
+ | disjuncts.add(right); | ||
+ | return new Expr.Variadic(op, | ||
+ | } else { | ||
+ | return new Expr.Binary(left, | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | ====== Further Desugaring ====== | ||
+ | |||
+ | This is all right, but it could be even better! | ||
+ | An expression like '' | ||
+ | <code haskell> | ||
+ | /\ /\ /\ 1 | ||
+ | /\ 2 | ||
+ | /\ 3 | ||
+ | /\ 4 | ||
+ | </ | ||
+ | Which is quite a lot of nesting! | ||
+ | It would be nice if it were instead translated to a single flat jlist with four conjuncts. | ||
+ | This rewrite is safe because conjunction & disjunction are associative. | ||
+ | So, define a new '' | ||
+ | Here's what it looks like: | ||
+ | <code java> | ||
+ | private Expr flattenJLists(Token op, List< | ||
+ | List< | ||
+ | for (Expr junct : juncts) { | ||
+ | Expr.Variadic vjunct; | ||
+ | if ((vjunct = asVariadicOp(op, | ||
+ | flattened.addAll(vjunct.parameters); | ||
+ | } else { | ||
+ | flattened.add(junct); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | return new Expr.Variadic(op, | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | This uses Java's conditional-assign syntax along with the '' | ||
+ | <code java> | ||
+ | private Expr.Variadic asVariadicOp(Token op, Expr expr) { | ||
+ | if (expr instanceof Expr.Variadic) { | ||
+ | Expr.Variadic vExpr = (Expr.Variadic)expr; | ||
+ | if (vExpr.operator.type == op.type) return vExpr; | ||
+ | } | ||
+ | |||
+ | return null; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Replace the calls to '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | private Expr flattenInfix(Expr left, Token op, Expr right) { | ||
+ | if (op.type == AND) { | ||
+ | List< | ||
+ | conjuncts.add(left); | ||
+ | conjuncts.add(right); | ||
+ | return flattenJLists(op, | ||
+ | } else if (op.type == OR) { | ||
+ | List< | ||
+ | disjuncts.add(left); | ||
+ | disjuncts.add(right); | ||
+ | return flattenJLists(op, | ||
+ | } else { | ||
+ | return new Expr.Binary(left, | ||
+ | } | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Do the same in the jlist parsing loop in '' | ||
+ | <code java [highlight_lines_extra=" | ||
+ | if (match(AND, OR)) { | ||
+ | Token op = previous(); | ||
+ | jlists.push(op.column); | ||
+ | List< | ||
+ | do { | ||
+ | juncts.add(expression()); | ||
+ | } while (matchBullet(op.type, | ||
+ | jlists.pop(); | ||
+ | return flattenJLists(op, | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | Infix ''/ | ||
+ | So concludes this lynchpin tutorial on conjunction & disjunction lists. | ||
+ | Good job making it to the end! | ||
+ | If your code got out of sync during this tutorial, you can find its expected state [[https:// | ||
+ | Continue on the [[creating: | ||
+ | |||
+ | ====== Challenges ====== | ||
+ | |||
+ | Here are a number of optional challenges, in roughly increasing levels of difficulty. | ||
+ | |||
+ | - Python uses indentation to determine statement membership in a code block. Does this make Python context-sensitive? | ||
+ | - It's tempting to summarize this chapter as us solving the jlist parsing problem by making jlists have higher precedence than infix operators, but that is not quite the case. Think carefully about what precedence means; is there a difference between what might be called //lexical// precedence - where one interpretation of a token takes higher precedence than another - and parsing precedence? Did we make use of that here? What are some ways that parsers can deal with the problem of the same token having multiple possible meanings? | ||
+ | - Jlists are not the only context-sensitive language construct in TLA⁺. Nested proof steps are another. Take some time to read the [[https:// | ||
+ | - Write unit tests for your jlist parsing code. Think of every weird jlist case you can. Look at [[https:// | ||
+ | - If you are familiar with the [[https:// | ||
+ | - Most courses in formal languages skip directly from context-free grammars to Turing machines, but this misses a number of automata of intermediate power. See whether it is possible to use [[https:// | ||
[[creating: | [[creating: | ||