creating:jlists

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:jlists [2025/04/28 18:39] – Simplified jlist parsing logic ahelwercreating:jlists [2026/11/19 03:00] (current) – Minor change to interpretation code of OR ahelwer
Line 3: Line 3:
 [[https://craftinginterpreters.com/control-flow.html|Chapter 9]] of //Crafting Interpreters// covers control flow - ''if'', ''while'', ''for'', and all that. [[https://craftinginterpreters.com/control-flow.html|Chapter 9]] of //Crafting Interpreters// covers control flow - ''if'', ''while'', ''for'', and all that.
 TLA⁺ doesn't really have that, because TLA⁺ specifications aren't imperative programs. TLA⁺ doesn't really have that, because TLA⁺ specifications aren't imperative programs.
-However, TLA⁺ //does// have something similar.+However, TLA⁺ //does// have something somewhat analogous.
 When specifying a system's actions, we commonly need to do two things: write preconditions or "guards" controlling whether an action can be taken, and specify the set of possible next-state transitions. When specifying a system's actions, we commonly need to do two things: write preconditions or "guards" controlling whether an action can be taken, and specify the set of possible next-state transitions.
 For the former we use conjunction (aka logical "and"), and for the latter we use disjunction (aka logical "or"). For the former we use conjunction (aka logical "and"), and for the latter we use disjunction (aka logical "or").
Line 64: Line 64:
  
 ''matchBullet()'' consumes a ''/\'' or ''\/'' token only if it is of the expected type and column. ''matchBullet()'' consumes a ''/\'' or ''\/'' token only if it is of the expected type and column.
-In this way our jlist parsing logic will only add another expression if it finds another vertically-aligned ''/\'' or ''\/'' token on the next line.+In this way our jlist parsing logic will only add another expression if it finds another vertically-aligned ''/\'' or ''\/'' token on a subsequent line.
 This all... kind of works? This all... kind of works?
 You can parse a surprisingly broad set of jlists with just our simple logic! You can parse a surprisingly broad set of jlists with just our simple logic!
Line 88: Line 88:
 Unfortunately not. Unfortunately not.
 Here's the proverbial wrench: TLA⁺ also allows ''\/'' and ''/\'' as //infix operators//. Here's the proverbial wrench: TLA⁺ also allows ''\/'' and ''/\'' as //infix operators//.
-We skipped defining them in the expressions chapter where we learned how to parse operators of different precedences; let's add them to ''operators'' table in our ''Token'' class now:+We skipped defining them in the expressions chapter where we learned how to parse operators of different precedences; let's add them to the ''operators'' table in our ''Parser'' class now:
  
 <code java [highlight_lines_extra="5,6"]> <code java [highlight_lines_extra="5,6"]>
-private static final Operator[] operators = new Operator[] { +  static final Operator[] operators = new Operator[] { 
-    new Operator(Fix.PREFIX,  NOT,        true,   4,  4 ),+    new Operator(Fix.PREFIX,  NOT,        false,  4,  4 ),
     new Operator(Fix.PREFIX,  ENABLED,    false,  4,  15),     new Operator(Fix.PREFIX,  ENABLED,    false,  4,  15),
-    new Operator(Fix.PREFIX,  MINUS,      true,   12, 12),+    new Operator(Fix.PREFIX,  MINUS,      false,  12, 12),
     new Operator(Fix.INFIX,   AND,        true,   3,  3 ),     new Operator(Fix.INFIX,   AND,        true,   3,  3 ),
     new Operator(Fix.INFIX,   OR,         true,   3,  3 ),     new Operator(Fix.INFIX,   OR,         true,   3,  3 ),
Line 126: Line 126:
 What does this change mean in practical terms? 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://craftinginterpreters.com/representing-code.html|Chapter 5: Representing Code]]. First, it means we cannot easily write the formal TLA⁺ grammar in Backus-Naur Form (BNF) as we learned to do in [[https://craftinginterpreters.com/representing-code.html|Chapter 5: Representing Code]].
-Although grammar notation [[https://en.wikipedia.org/wiki/Context-sensitive_grammar|does exist]] for context-sensitive languages, it is unintuitive and more of a hindrance to langage implementers than a help.+Although grammar notation [[https://en.wikipedia.org/wiki/Context-sensitive_grammar|does exist]] for context-sensitive languages, it is unintuitive and more of a hindrance to language implementers than a help.
 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. 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 ''Parser'' class carries some additional mutable state in a class variable, and its methods change their behavior based on that state.+Second - returning to our parser implementation here - it means that our ''Parser'' class carries some additional mutable state in an instance field, and its methods change their behavior based on that state.
  
 Ultimately the shape of this state is a stack of nested jlists. Ultimately the shape of this state is a stack of nested jlists.
Line 138: Line 138:
 We'll be using Java's ''[[https://docs.oracle.com/javase/8/docs/api/java/util/ArrayDeque.html|ArrayDeque]]'' class as a stack. We'll be using Java's ''[[https://docs.oracle.com/javase/8/docs/api/java/util/ArrayDeque.html|ArrayDeque]]'' class as a stack.
 It only needs to hold the jlist column. It only needs to hold the jlist column.
-Define a new class variable near the top of the ''Parser'' class:+Define a new instance field near the top of the ''Parser'' class:
 <code java [highlight_lines_extra="4"]> <code java [highlight_lines_extra="4"]>
   private final List<Token> tokens;   private final List<Token> tokens;
Line 184: Line 184:
 This works! This works!
 We can parse jlists again! 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 ''operatorExpression()'':+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 ''operatorExpression()'', presented below without change:
 <code java> <code java>
     Expr expr = operatorExpression(prec + 1);     Expr expr = operatorExpression(prec + 1);
Line 190: Line 190:
       Token operator = previous();       Token operator = previous();
       Expr right = operatorExpression(op.highPrec + 1);       Expr right = operatorExpression(op.highPrec + 1);
 +      checkPrecOverlap(op);
       expr = new Expr.Binary(expr, operator, right);       expr = new Expr.Binary(expr, operator, right);
       if (!op.assoc) return expr;       if (!op.assoc) return expr;
Line 249: Line 250:
 This puts you in rarified air. This puts you in rarified air.
 Only a handful of people in the world possess this knowledge, and now you are among them. 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; this is because they are used to express nondeterminism, as you will learn several chapters from now.
 +
 +Add conjunction list evaluation logic to ''visitVariadicExpr()'' in the ''Interpreter'' class, below the set constructor logic:
 +<code java [highlight_lines_extra="2,3,4,5,6,7,8"]>
 +        return set;
 +      case AND:
 +        for (Expr conjunct : expr.parameters) {
 +          Object result = evaluate(conjunct);
 +          checkBooleanOperand(expr.operator, result);
 +          if (!(boolean)result) return false;
 +        }
 +        return true;
 +      default:
 +        // Unreachable.
 +        return null;
 +</code>
 +
 +Then add the disjunction list logic right below that:
 +<code java [highlight_lines_extra="2,3,4,5,6,7,8,9,10,11"]>
 +        return true;
 +      case OR:
 +        boolean result = false;
 +        for (Expr disjunct : expr.parameters) {
 +          Object junctResult = evaluate(disjunct);
 +          checkBooleanOperand(expr.operator, junctResult);
 +          if ((boolean)junctResult) {
 +            result = true;
 +          }
 +        }
 +        return result;
 +      default:
 +        // Unreachable.
 +        return null;
 +</code>
 +
 +Remember we also parsed the ''/\'' and ''\/'' //infix// operators, so we need to evaluate those as well.
 +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 ''visitBinaryExpr()''.
 +So, we'll perform a trick which also has its parallel in chapter 9 of the book: [[https://craftinginterpreters.com/control-flow.html#desugaring|desugaring]]!
 +We will flatten infix ''/\'' and ''\/'' operators so they actually form a jlist.
 +
 +In the ''Parser'' class, modify the infix operator parsing loop in ''operatorExpression()'' by replacing the ''expr ='' line with a call to a new helper, ''flattenInfix()'':
 +<code java [highlight_lines_extra="6"]>
 +    Expr expr = operatorExpression(prec + 1);
 +    while ((op = matchOp(Fix.INFIX, prec)) != null) {
 +      Token operator = previous();
 +      Expr right = operatorExpression(op.highPrec + 1);
 +      checkPrecOverlap(op);
 +      expr = flattenInfix(expr, operator, right);
 +      if (!op.assoc) return expr;
 +    }
 +</code>
 +
 +Define ''flattenInfix()'' above ''matchBullet()'' in the ''Parser'' class:
 +<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, op, right);
 +    }
 +  }
 +</code>
 +The helper returns a regular binary expression except when the operator is ''AND'' or ''OR''; in those cases, we return two-parameter instances of ''Expr.Variadic'' instead:
 +<code java [highlight_lines_extra="3,4,5,6,8,9,10,11"]>
 +  private Expr flattenInfix(Expr left, Token op, Expr right) {
 +    if (op.type == AND) {
 +      List<Expr> conjuncts = new ArrayList<>();
 +      conjuncts.add(left);
 +      conjuncts.add(right);
 +      return new Expr.Variadic(op, conjuncts);    
 +    } else if (op.type == OR) {
 +      List<Expr> disjuncts = new ArrayList<>();
 +      disjuncts.add(left);
 +      disjuncts.add(right);
 +      return new Expr.Variadic(op, disjuncts);
 +    } else {
 +      return new Expr.Binary(left, op, right);
 +    }
 +  }
 +</code>
 +
 +====== Further Desugaring ======
 +
 +This is all right, but it could be even better!
 +An expression like ''1 /\ 2 /\ 3 /\ 4'' will be translated to:
 +<code haskell>
 +/\ /\ /\ 1
 +      /\ 2
 +   /\ 3
 +/\ 4
 +</code>
 +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 ''flattenJLists()'' helper which accepts a list of juncts, then builds a new jlist by flattening any nested jlists inside the juncts if they're the same type as the containing jlist.
 +Here's what it looks like:
 +<code java>
 +  private Expr flattenJLists(Token op, List<Expr> juncts) {
 +    List<Expr> flattened = new ArrayList<>();
 +    for (Expr junct : juncts) {
 +      if (junct instanceof Expr.Variadic vjunct
 +          && vjunct.operator.type == op.type) {
 +        flattened.addAll(vjunct.parameters);
 +      } else {
 +        flattened.add(junct);
 +      }
 +    }
 +
 +    return new Expr.Variadic(op, flattened);
 +  }
 +</code>
 +
 +Replace the calls to ''new Expr.Variadic()'' in ''flattenInfix()'' with calls to ''flattenJLists()'' instead:
 +<code java [highlight_lines_extra="6,11"]>
 +  private Expr flattenInfix(Expr left, Token op, Expr right) {
 +    if (op.type == AND) {
 +      List<Expr> conjuncts = new ArrayList<>();
 +      conjuncts.add(left);
 +      conjuncts.add(right);
 +      return flattenJLists(op, conjuncts);
 +    } else if (op.type == OR) {
 +      List<Expr> disjuncts = new ArrayList<>();
 +      disjuncts.add(left);
 +      disjuncts.add(right);
 +      return flattenJLists(op, disjuncts);
 +    } else {
 +      return new Expr.Binary(left, op, right);
 +    }
 +  }
 +</code>
 +
 +Do the same in the jlist parsing loop in ''primary()'':
 +<code java [highlight_lines_extra="9"]>
 +    if (match(AND, OR)) {
 +      Token op = previous();
 +      jlists.push(op.column);
 +      List<Expr> juncts = new ArrayList<>();
 +      do {
 +        juncts.add(expression());
 +      } while (matchBullet(op.type, op.column));
 +      jlists.pop();
 +      return flattenJLists(op, juncts);
 +    }
 +</code>
 +
 +Infix ''/\'' and ''\/'' operators will now be interpreted by our jlist evaluation code, and jlists will be as flat as they possibly can be.
 +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://github.com/tlaplus/devkit/tree/main/6-jlists|here]]. If your code got out of sync during this tutorial, you can find its expected state [[https://github.com/tlaplus/devkit/tree/main/6-jlists|here]].
 Continue on the [[creating:operators|next page]], where we learn to parse operators with parameters! Continue on the [[creating:operators|next page]], where we learn to parse operators with parameters!
Line 264: Line 422:
  
 [[creating:statements|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:operators|Next Page >]] [[creating:statements|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:operators|Next Page >]]
- 
  • creating/jlists.1745865572.txt.gz
  • Last modified: 2025/04/28 18:39
  • by ahelwer