creating:expressions

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
creating:expressions [2025/04/11 20:24] – Completed chapter 6 tutorial ahelwercreating:expressions [2026/11/17 04:20] (current) – Fixed operator precedence bugs ahelwer
Line 1: Line 1:
-======= Handling Constant TLA⁺ Expressions =======+======= Parsing Constant TLA⁺ Expressions =======
  
-This tutorial page covers the next three chapters in //Crafting Interpreters//:+This tutorial page covers the next two chapters in //Crafting Interpreters//:
   - [[https://craftinginterpreters.com/representing-code.html|Chapter 5: Representing Code]]   - [[https://craftinginterpreters.com/representing-code.html|Chapter 5: Representing Code]]
   - [[https://craftinginterpreters.com/parsing-expressions.html|Chapter 6: Parsing Expressions]]   - [[https://craftinginterpreters.com/parsing-expressions.html|Chapter 6: Parsing Expressions]]
-  - [[https://craftinginterpreters.com/evaluating-expressions.html|Chapter 7: Evaluating Expressions]] 
  
 Same as the book, we //could// build a parser for our entire minimal TLA⁺ language subset before moving on to interpreting it, but that would be boring! Same as the book, we //could// build a parser for our entire minimal TLA⁺ language subset before moving on to interpreting it, but that would be boring!
Line 38: Line 37:
 ternary        → "IF" expression "THEN" expression "ELSE" expression; ternary        → "IF" expression "THEN" expression "ELSE" expression;
 variadic       → "{" ( expression ( "," expression )* )? "}" variadic       → "{" ( expression ( "," expression )* )? "}"
-operator       → "=" | "+" | "-" | ".." | "/\" | "\/" | "<"  | "\in" ;+operator       → "=" | "+" | "-" | ".." | "<"  | "\in" ;
 </code> </code>
 There are a few interesting differences. There are a few interesting differences.
Line 51: Line 50:
 The only difference between ''{1, 2, 3}'' and an operator like ''constructSet(1, 2, 3)'' is syntactic sugar. The only difference between ''{1, 2, 3}'' and an operator like ''constructSet(1, 2, 3)'' is syntactic sugar.
 This is the perspective of a language implementer. This is the perspective of a language implementer.
-Later on we will extend the definition of ''variadic'' to include vertically-aligned conjunction & disjunction lists.+ 
 +Note that we //could// also include the conjunction ''/\'' and disjunction ''\/'' infix operators here but they have odd parsing interactions with vertically-aligned conjunction & disjunction lists, so we will handle them in a later chapter dedicated to that topic.
  
 ===== Section 5.2: Implementing Syntax Trees ===== ===== Section 5.2: Implementing Syntax Trees =====
Line 59: Line 59:
  
 <code java [highlight_lines_extra="19,20,21"]> <code java [highlight_lines_extra="19,20,21"]>
-package com.craftinginterpreters.tool;+package tool;
  
 import java.io.IOException; import java.io.IOException;
Line 94: Line 94:
     PrintWriter writer = new PrintWriter(path, "UTF-8");     PrintWriter writer = new PrintWriter(path, "UTF-8");
  
-    writer.println("package com.craftinginterpreters.tla;");+    writer.println("package tla;");
     writer.println();     writer.println();
     writer.println("import java.util.List;");     writer.println("import java.util.List;");
Line 207: Line 207:
  
 <code java [highlight_lines_extra="1"]> <code java [highlight_lines_extra="1"]>
-package com.craftinginterpreters.tla;+package tla;
  
 class AstPrinter implements Expr.Visitor<String> { class AstPrinter implements Expr.Visitor<String> {
Line 242: Line 242:
  
   @Override   @Override
-  public string visitTernaryExpr(Expr.Ternary expr) {+  public String visitTernaryExpr(Expr.Ternary expr) {
     return parenthesize(expr.operator.lexeme, expr.first,     return parenthesize(expr.operator.lexeme, expr.first,
                         expr.second, expr.third);                         expr.second, expr.third);
Line 248: Line 248:
  
   @Override   @Override
-  public string visitVariadicExpr(Expr.Variadic expr) {+  public String visitVariadicExpr(Expr.Variadic expr) {
     return parenthesize(expr.operator.lexeme,     return parenthesize(expr.operator.lexeme,
                         expr.parameters.toArray(Expr[]::new));                         expr.parameters.toArray(Expr[]::new));
Line 277: Line 277:
 In [[https://craftinginterpreters.com/parsing-expressions.html|Chapter 6]], we finally build a parse tree out of our tokens! In [[https://craftinginterpreters.com/parsing-expressions.html|Chapter 6]], we finally build a parse tree out of our tokens!
  
-===== Chapter 6.1: Ambiguity and the Parsing Game =====+===== Section 6.1: Ambiguity and the Parsing Game =====
  
 First, as in [[https://craftinginterpreters.com/parsing-expressions.html#ambiguity-and-the-parsing-game|section 6.1 of the book]], we have to disambiguate our grammar. First, as in [[https://craftinginterpreters.com/parsing-expressions.html#ambiguity-and-the-parsing-game|section 6.1 of the book]], we have to disambiguate our grammar.
Line 299: Line 299:
 Worry not, it can still be made terse and understandable! Worry not, it can still be made terse and understandable!
  
-===== Chapter 6.2: Recursive Descent Parsing =====+===== Section 6.2: Recursive Descent Parsing =====
  
 [[https://craftinginterpreters.com/parsing-expressions.html#recursive-descent-parsing|Section 6.2]] is where we start writing our parser in the recursive descent style. [[https://craftinginterpreters.com/parsing-expressions.html#recursive-descent-parsing|Section 6.2]] is where we start writing our parser in the recursive descent style.
Line 310: Line 310:
  
 <code java [highlight_lines_extra="1,4,6"]> <code java [highlight_lines_extra="1,4,6"]>
-package com.craftinginterpreters.tla;+package tla;
  
 import java.util.List; import java.util.List;
 import java.util.ArrayList; import java.util.ArrayList;
  
-import static com.craftinginterpreters.tla.TokenType.*;+import static tla.TokenType.*;
  
 class Parser { class Parser {
Line 398: Line 398:
  
 Now we have to define a table of operators with their details. Now we have to define a table of operators with their details.
-For this, create a new file ''Operator.java'' containing a class recording operator fix type, token type, associativity, and precedence range:+First use the handy Java 17 [[https://openjdk.org/jeps/395|records]] feature to quickly define a new ''Operator'' dataclass; this will hold the attributes of the operators we want to parse. 
 +Put it at the top of the ''Parser'' class:
  
-<code java> +<code java [highlight_lines_extra="2,3,4"]> 
-package com.craftinginterpreters.tla;+class Parser { 
 +  static enum Fix { PREFIX, INFIX, POSTFIX } 
 +  static record Operator(Fix fix, TokenType token, 
 +      boolean assoc, int lowPrec, int highPrec) { }
  
-enum Fix { +  private final List<Token> tokens;
-  PREFIX, INFIX, POSTFIX +
-} +
- +
-class Operator { +
-  final Fix fix; +
-  final TokenType token; +
-  final boolean assoc; +
-  final int lowPrec; +
-  final int highPrec; +
- +
-  public Operator(Fix fix, TokenType token, boolean assoc, +
-                  int lowPrec, int highPrec) { +
-    this.fix = fix; +
-    this.token = token; +
-    this.assoc = assoc; +
-    this.lowPrec = lowPrec; +
-    this.highPrec = highPrec; +
-  } +
-}+
 </code> </code>
  
-For convenience, import the ''Fix'' enum values in ''Parser.java'' so they can be referenced directly: +You can find operator attributes on page 271 of //[[https://lamport.azurewebsites.net/tla/book.html|Specifying Systems]]// by Leslie Lamport, or [[https://github.com/tlaplus/tlaplus/blob/417491ec7e1839191744eb10ccd3e4ee11035e95/tlatools/org.lamport.tlatools/src/tla2sany/parser/Operators.java#L130-L234|this TLA⁺ tools source file]].
- +
-<code java [highlight_lines_extra="7"]> +
-package com.craftinginterpreters.tla; +
- +
-import java.util.List; +
-import java.util.ArrayList; +
- +
-import static com.craftinginterpreters.tla.TokenType.*; +
-import static com.craftinginterpreters.tla.Fix.*; +
- +
-class Parser { +
-</code> +
- +
- +
-You can find operator attributes on page 271 of //[[https://lamport.azurewebsites.net/tla/book.html|Specifying Systems]]// by Leslie Lamport, or [[https://github.com/tlaplus/tlaplus/blob/13e5a39b5368a6da4906b8ed1c2c1114d2e7de15/tlatools/org.lamport.tlatools/src/tla2sany/parser/Operators.java#L130-L234|this TLA⁺ tools source file]].+
 We use a small subset of these operators. We use a small subset of these operators.
-Record their attributes in a table in ''Parser.java'', below ''operatorExpression()'':+Record their attributes in a table in ''Parser.java'', below ''operatorExpression()''; note associativity is only meaningful for infix operators, so we'll set it to ''false'' for everything else:
  
 <code java> <code java>
-  private static final Operator[] operators = new Operator[] { +  static final Operator[] operators = new Operator[] { 
-    new Operator(PREFIX,  NEGATION,   true,   4,  4 ), +    new Operator(Fix.PREFIX,  NOT,        false,  4,  4 ), 
-    new Operator(PREFIX,  ENABLED,    false,  4,  15), +    new Operator(Fix.PREFIX,  ENABLED,    false,  4,  15), 
-    new Operator(PREFIX,  MINUS,      true,   12, 12), +    new Operator(Fix.PREFIX,  MINUS,      false,  12, 12), 
-    new Operator(INFIX,   AND,        true,   3,  3 ), +    new Operator(Fix.INFIX,   IN,         false,  5,  5 ), 
-    new Operator(INFIX,   OR,         true,   3,  3 ), +    new Operator(Fix.INFIX,   EQUAL,      false,  5,  5 ), 
-    new Operator(INFIX,   IN,         false,  5,  5 ), +    new Operator(Fix.INFIX,   LESS_THAN,  false,  5,  5 ), 
-    new Operator(INFIX,   EQUAL,      false,  5,  5 ), +    new Operator(Fix.INFIX,   DOT_DOT,    false,  9,  9 ), 
-    new Operator(INFIX,   LESS_THAN,  false,  5,  5 ), +    new Operator(Fix.INFIX,   PLUS,       true,   10, 10), 
-    new Operator(INFIX,   DOT_DOT,    false,  9,  9 ), +    new Operator(Fix.INFIX,   MINUS,      true,   11, 11), 
-    new Operator(INFIX,   PLUS,       true,   10, 10), +    new Operator(Fix.POSTFIX, PRIME,      false,  15, 15),
-    new Operator(INFIX,   MINUS,      true,   11, 11), +
-    new Operator(POSTFIX, PRIME,      false,  15, 15),+
   };   };
 </code> </code>
Line 486: Line 454:
 Here is how we modify ''operatorExpression()'' to parse infix operators. Here is how we modify ''operatorExpression()'' to parse infix operators.
 You can see a strong resemblance to the infix operator parsing code given in the book (new lines highlighted): You can see a strong resemblance to the infix operator parsing code given in the book (new lines highlighted):
-<code java [highlight_lines_extra="4,7,8,9,10,11"]>+<code java [highlight_lines_extra="2,7,8,9,10,11"]>
   private Expr operatorExpression(int prec) {   private Expr operatorExpression(int prec) {
 +    Operator op;
 +
     if (prec == 16) return primary();     if (prec == 16) return primary();
  
-    Operator op; 
-  
     Expr expr = operatorExpression(prec + 1);     Expr expr = operatorExpression(prec + 1);
-    while ((op = matchOp(INFIX, prec)) != null) {+    while ((op = matchOp(Fix.INFIX, prec)) != null) {
       Token operator = previous();       Token operator = previous();
       Expr right = operatorExpression(op.highPrec + 1);       Expr right = operatorExpression(op.highPrec + 1);
       expr = new Expr.Binary(expr, operator, right);       expr = new Expr.Binary(expr, operator, right);
     }     }
- +
     return expr;     return expr;
   }   }
Line 505: Line 473:
 We use Java's combined conditional-assignment atop the ''while'' loop to make our code more terse, both checking whether any operators were matched and getting details of the matched operator if so. We use Java's combined conditional-assignment atop the ''while'' loop to make our code more terse, both checking whether any operators were matched and getting details of the matched operator if so.
 The interior of the ''while'' loop is largely identical to infix parsing logic from the book, except for when we recurse to a higher precedence level: in the book the code recurses one level above the matched operator's precedence, but here we go one level above the //upper bound// of the matched operator's precedence. The interior of the ''while'' loop is largely identical to infix parsing logic from the book, except for when we recurse to a higher precedence level: in the book the code recurses one level above the matched operator's precedence, but here we go one level above the //upper bound// of the matched operator's precedence.
-It takes a bit of thinking to understand why this works for parsing expressions according to the precedence rules we want, but it does. 
-Take a minute to ponder it. 
-If you still don't get it, wait until we have a fully-functional expression parser then play around with this line to see how it changes the behavior. 
  
 Our code implements precedence ranges, but assumes all infix operators are associative. Our code implements precedence ranges, but assumes all infix operators are associative.
 We need to modify the loop to return immediately if the infix operator is not associative: We need to modify the loop to return immediately if the infix operator is not associative:
 <code java [highlight_lines_extra="5"]> <code java [highlight_lines_extra="5"]>
-    while ((op = matchOp(INFIX, prec)) != null) {+    while ((op = matchOp(Fix.INFIX, prec)) != null) {
       Token operator = previous();       Token operator = previous();
       Expr right = operatorExpression(op.highPrec + 1);       Expr right = operatorExpression(op.highPrec + 1);
Line 521: Line 486:
  
 And that's how we parse infix operators! And that's how we parse infix operators!
-That was the most complicated case, so let's move on to prefix operators. +Next up is postfix operators. 
-Again our code resembles the prefix operator parsing logic given in the book. +These are not covered in the book, but they pretty much resemble infix operators without matching an expression on the right-hand side of the operator. 
-Add this snippet near the top of ''operatorExpression()'':+Add the highlighted code below the ''INFIX'' logic in ''operatorExpression()'':
  
-<code java [highlight_lines_extra="5,6,7,8,9,10"]> +<code java [highlight_lines_extra="3,4,5,6"]> 
-  private Expr operatorExpression(int prec) { +    }
-    if (prec == 16) return primary();+
  
-    Operator op; +    while ((op = matchOp(Fix.POSTFIX, prec)) != null) {
-    if ((op = matchOp(PREFIX, prec)) != null) {+
       Token opToken = previous();       Token opToken = previous();
-      Expr expr = operatorExpression( +      expr = new Expr.Unary(opToken, expr);
-                    op.assoc ? op.lowPrec : op.highPrec + 1); +
-      return new Expr.Unary(opToken, expr);+
     }     }
  
-    Expr expr = operatorExpression(prec + 1);+    return expr; 
 +  }
 </code> </code>
  
-Of note is the expression ''op.assoc ? op.lowPrec : op.highPrec + 1'' controlling the precedence level at which we recurse. +Easy enough. 
-To understand this expression, it is helpful to consider an example. +Now the surprisingly tricky prefix operator case. 
-The negative prefix operator ''-1'' is associative, so we should be able to parse the expression ''--1'' as ''-(-1)''. +Again our code resembles the prefix operator parsing logic given in the book. 
-In order to do that after consuming the first ''-'' we have to recurse into ''operatorExpression()'' //at the same precedence level//. +Add this snippet near the top of ''operatorExpression()''; it requires a new matching helper, ''matchPrefixOp()'':
-Then we will consume the second ''-'', then again recurse and ultimately consume ''1'' in our yet-to-be-defined ''primary'' method. +
-In contrast, the prefix operator ''ENABLED'' is not associative and has range 4-15. +
-In that case we want to reject the expression ''ENABLED ENABLED TRUE'', so we recurse at a level higher than ''ENABLED'''s upper precedence bound. +
-Thus the second ''ENABLED'' will not be matched and we will report a parse error using methods defined in chapter section 6.3. +
- +
-All that remains is to parse postfix operators. +
-These are not covered in the book, but they pretty much resemble infix operators without matching an expression on the right-hand side of the operator. +
-Add the highlighted code below the ''INFIX'' logic in ''operatorExpression()'': +
 <code java [highlight_lines_extra="3,4,5,6,7"]> <code java [highlight_lines_extra="3,4,5,6,7"]>
 +  private Expr operatorExpression(int prec) {
 +    Operator op;
 +    if ((op = matchPrefixOp(prec)) != null) {
 +      Token opToken = previous();
 +      Expr expr = operatorExpression(op.highPrec + 1);
 +      return new Expr.Unary(opToken, expr);
     }     }
  
-    while ((op = matchOp(POSTFIX, prec)) != null) { +    if (prec == 16) return primary(); 
-      Token opToken = previous(); +</code> 
-      expr = new Expr.Unary(opToken, expr); + 
-      if (!op.assoc) break;+I wish we could re-use ''matchOp()'', but prefix operators are more finicky than that. 
 +The difficulty arises when parsing an expression like ''--1'': the negative prefix operator has range 12-12, but after the first negative operator we recurse with ''operatorExpression(op.highPrec + 1)'', which evaluates to ''operatorExpression(13)''. 
 +Calling ''matchOp(Fix.PREFIX, 13)'' would not successfully match the second negative operator. 
 +It turns out we need to match prefix operators when they are equal to **or less than** the current precedence, instead of only when equal to the current precedence. 
 +So, add another helper: 
 +<code java> 
 +  private Operator matchPrefixOp(int prec) { 
 +    for (Operator op : operators) { 
 +      if (op.fix == Fix.PREFIX && op.lowPrec <= prec) { 
 +        if (match(op.token)) return op; 
 +      }
     }     }
  
-    return expr+    return null;
   }   }
 </code> </code>
 +
 +You might be tempted to just ignore precedence entirely for prefix operators, but then we would match the operator "too early" in the recursive descent; to see where this goes awry, try removing ''op.lowPrec <= prec'' from ''matchPrefixOp()'' and trace how that would parse the expression ''-1 + 2''.
  
 And that completes our operator parsing logic! And that completes our operator parsing logic!
Line 616: Line 587:
     if (match(LEFT_BRACE)) {     if (match(LEFT_BRACE)) {
       Token operator = previous();       Token operator = previous();
-      List<Expr> elements = new ArrayList<Expr>(); +      List<Expr> elements = new ArrayList<>(); 
-      if (RIGHT_BRACE != peek().type) {+      if (!check(RIGHT_BRACE)) {
         do {         do {
           elements.add(expression());           elements.add(expression());
Line 649: Line 620:
 <code java> <code java>
   private ParseError error(Token token, String message) {   private ParseError error(Token token, String message) {
-    Lox.error(token, message);+    TlaPlus.error(token, message);
     return new ParseError();     return new ParseError();
   }   }
Line 668: Line 639:
 Add the ''ParseError'' class definition at the top of the ''Parser'' class: Add the ''ParseError'' class definition at the top of the ''Parser'' class:
  
-<code java [highlight_lines_extra="2"]>+<code java [highlight_lines_extra="5"]>
 class Parser { class Parser {
 +  static enum Fix { PREFIX, INFIX, POSTFIX }
 +  static record Operator(Fix fix, TokenType token,
 +      boolean assoc, int lowPrec, int highPrec) { }
   private static class ParseError extends RuntimeException {}   private static class ParseError extends RuntimeException {}
  
Line 681: Line 655:
   private void synchronize() {   private void synchronize() {
     advance();     advance();
-    +
     while(!isAtEnd()) {     while(!isAtEnd()) {
       if (previous().type == EQUAL_EQUAL) return;       if (previous().type == EQUAL_EQUAL) return;
-      +
       advance();       advance();
     }     }
Line 693: Line 667:
 For an example, see SANY's very complicated ''[[https://github.com/tlaplus/tlaplus/blob/13e5a39b5368a6da4906b8ed1c2c1114d2e7de15/tlatools/org.lamport.tlatools/javacc/tla%2B.jj#L229-L392|belchDEF()]]'' method. For an example, see SANY's very complicated ''[[https://github.com/tlaplus/tlaplus/blob/13e5a39b5368a6da4906b8ed1c2c1114d2e7de15/tlatools/org.lamport.tlatools/javacc/tla%2B.jj#L229-L392|belchDEF()]]'' method.
 We won't be doing that here, but it's a good technique to know about; looking ahead then inserting synthetic tokens to disambiguate syntax is a common method when parsing complicated & ambiguous languages like TLA⁺. We won't be doing that here, but it's a good technique to know about; looking ahead then inserting synthetic tokens to disambiguate syntax is a common method when parsing complicated & ambiguous languages like TLA⁺.
 +
 +One additional TLA⁺-specific modification here is a helper to check for overlapping operator precedence.
 +Expressions like ''%%ENABLED TRUE'%%'' should produce an error, as ''ENABLED'' has precedence 4-15 and the prime operator has precedence 15-15 - a conflict.
 +Add the helper:
 +<code java>
 +  private void checkPrecOverlap(Operator op) {
 +    for (Operator next : operators) {
 +      if (next.fix == Fix.PREFIX || !check(next.token)) continue;
 +      if (op == next && op.assoc) continue;
 +      if (op.lowPrec <= next.highPrec && next.lowPrec <= op.highPrec) {
 +        throw error(peek(), "Conflicting operator precedence.");
 +      }
 +    }
 +  }
 +</code>
 +
 +Then add calls to this helper in ''operatorExpression()'':
 +
 +<code java [highlight_lines_extra="6,16"]>
 +  private Expr operatorExpression(int prec) {
 +    Operator op;
 +    if ((op = matchPrefixOp(prec)) != null) {
 +      Token opToken = previous();
 +      Expr expr = operatorExpression(op.highPrec + 1);
 +      checkPrecOverlap(op);
 +      return new Expr.Unary(opToken, expr);
 +    }
 +
 +    if (prec == 16) return primary();
 +
 +    Expr expr = operatorExpression(prec + 1);
 +    while ((op = matchOp(Fix.INFIX, prec)) != null) {
 +      Token operator = previous();
 +      Expr right = operatorExpression(op.highPrec + 1);
 +      checkPrecOverlap(op);
 +      expr = new Expr.Binary(expr, operator, right);
 +      if (!op.assoc) return expr;
 +    }
 +</code>
  
 ===== Section 6.4: Wiring up the Parser ===== ===== Section 6.4: Wiring up the Parser =====
  
 In [[https://craftinginterpreters.com/parsing-expressions.html#wiring-up-the-parser|section 6.4]] we finally arrive at the point where you can parse TLA⁺ expressions in your REPL. In [[https://craftinginterpreters.com/parsing-expressions.html#wiring-up-the-parser|section 6.4]] we finally arrive at the point where you can parse TLA⁺ expressions in your REPL.
-In the ''run()'' method of the ''TlaPlus'' class, delete the code printing out the scanned tokens (or not, it can be informative to keep around) and replace it with this:+As in the book, add error reporting to the end of the ''primary()'' method in the ''Parser'' class:
  
 +<code java [highlight_lines_extra="4"]>
 +      return new Expr.Variadic(operator, elements);
 +    }
 +
 +    throw error(peek(), "Expect expression.");
 +  }
 +</code>
 +
 +Also add a new ''parse()'' method to the ''Parser'' class:
 +<code java>
 +  Expr parse() {
 +    try {
 +      return expression();
 +    } catch (ParseError error) {
 +      return null;
 +    }
 +  }
 +</code>
 +
 +In the ''run()'' method of the ''TlaPlus'' class, delete the code printing out the scanned tokens (or not, it can be informative to keep around) and replace it with this:
 <code java [highlight_lines_extra="3,4,6,7,9"]> <code java [highlight_lines_extra="3,4,6,7,9"]>
     List<Token> tokens = scanner.scanTokens();     List<Token> tokens = scanner.scanTokens();
Line 717: Line 750:
 ({ (+ 1 2) (IF true 3 4) ({)) ({ (+ 1 2) (IF true 3 4) ({))
 </code> </code>
 +If you got out of sync, you can find a snapshot of the expected state of the code in [[https://github.com/tlaplus/devkit/tree/main/3-expressions|this repo directory]].
 +Next tutorial: [[creating:evaluation|Evaluating Constant TLA⁺ Expressions]]!
 +
 +====== Challenges ======
 +
 +Here are some optional challenges to flesh out your TLA⁺ interpreter, roughly ranked from simplest to most difficult.
  
 +[[creating:scanning|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:evaluation|Next Page >]]
  • creating/expressions.1744403081.txt.gz
  • Last modified: 2025/04/11 20:24
  • by ahelwer