creating:statements

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:statements [2025/04/19 19:47] – Use internal wiki links, add link to code repo ahelwercreating:statements [2026/11/19 02:59] (current) – Fixed highlighting ahelwer
Line 1: Line 1:
 ======= Handling TLA⁺ Statements ======= ======= Handling TLA⁺ Statements =======
  
-Here we cover [[https://craftinginterpreters.com/statements-and-state.html|Chapter 8: Statements and State]] of book //Crafting Interpreters//.+Here we cover [[https://craftinginterpreters.com/statements-and-state.html|Chapter 8: Statements and State]] of the book //Crafting Interpreters//.
 We'll implement the ability to associate identifiers with values, then subsequently use those identifiers in expressions. We'll implement the ability to associate identifiers with values, then subsequently use those identifiers in expressions.
 While Lox was designed with a dual REPL/file execution model in mind, TLA⁺ was not - so the behavior of our interpreter will vary quite a bit from the book! While Lox was designed with a dual REPL/file execution model in mind, TLA⁺ was not - so the behavior of our interpreter will vary quite a bit from the book!
 We'll have to implement parser & interpreter //modes//. We'll have to implement parser & interpreter //modes//.
 When the user runs our TLA⁺ interpreter as a REPL, we want to support operator redefinition and the ability to see the value of simple expressions - like the Python REPL. When the user runs our TLA⁺ interpreter as a REPL, we want to support operator redefinition and the ability to see the value of simple expressions - like the Python REPL.
-In contast, when the user runs our TLA⁺ interpreter against a file it should be an error for multiple operators to use the same name.+In contrast, when the user runs our TLA⁺ interpreter against a file it should be an error for multiple operators to use the same name.
 The parser also should not accept standalone expressions in the middle of the file. The parser also should not accept standalone expressions in the middle of the file.
  
Line 24: Line 24:
  
     defineAst(outputDir, "Stmt", Arrays.asList(     defineAst(outputDir, "Stmt", Arrays.asList(
-      "Print    : Expr expression"+      "Print    : Token location, Expr expression"
     ));     ));
   }   }
 </code> </code>
 +
 +The ''Print'' class contains a ''Token'' instance to support reporting error locations.
  
 ===== Parsing statements ===== ===== Parsing statements =====
Line 44: Line 46:
 </code> </code>
  
-Modify ''parse()'' in the ''Parser'' class, same as in the book:+Entirely replace ''parse()'' in the ''Parser'' class, same as in the book:
  
 <code java> <code java>
Line 58: Line 60:
  
 Our ''statement()'' method is different from the book; if we're in REPL mode we parse & return a statement wrapped in a ''Stmt.Print'' object, and error otherwise. Our ''statement()'' method is different from the book; if we're in REPL mode we parse & return a statement wrapped in a ''Stmt.Print'' object, and error otherwise.
-We'll return to this method later to add parsing logic for operator definitions. +In other words, we automatically promote naked expressions into print statements. 
 +Use ''peek()'' to get the first token in the expression for error location reporting.
 <code java> <code java>
   private Stmt statement() {   private Stmt statement() {
-    if (replMode) return new Stmt.Print(expression());+    if (replMode) return new Stmt.Print(peek(), expression());
  
     throw error(peek(), "Expected statement.");     throw error(peek(), "Expected statement.");
Line 70: Line 72:
 ===== Executing statements ===== ===== Executing statements =====
  
-Add ''Stmt'' to the list of interfaces implemented by the ''Interpreter'' class: +Add the ''Stmt'' visitor to the list of interfaces implemented by the ''Interpreter'' class:
 <code java [highlight_lines_extra="2"]> <code java [highlight_lines_extra="2"]>
 class Interpreter implements Expr.Visitor<Object>, class Interpreter implements Expr.Visitor<Object>,
Line 79: Line 80:
  
 Now add a visitor method for the ''Stmt.Print'' class, after ''evaluate()'' in the ''Interpreter'' class. Now add a visitor method for the ''Stmt.Print'' class, after ''evaluate()'' in the ''Interpreter'' class.
-This is identical to the book except for one thing, which we will change to improve the testability of our interpreter: +This is identical to the book: 
- +<code java>
-<code java [highlight_lines_extra="4"]>+
   @Override   @Override
   public Void visitPrintStmt(Stmt.Print stmt) {   public Void visitPrintStmt(Stmt.Print stmt) {
     Object value = evaluate(stmt.expression);     Object value = evaluate(stmt.expression);
-    out.println(stringify(value));+    System.out.println(stringify(value));
     return null;     return null;
   }   }
 </code> </code>
  
-Instead of printing directly to ''System.out'', we add a ''[[https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html|PrintStream]]'' field to the ''Interpreter'' class called ''out''. +Same as the book, overwrite the old ''interpret()'' method to accept a list of statements. 
-''System.out'' implements the ''PrintStream'' interface, but so do other things, and if we want to write unit tests for this class it helps to be able to intercept its output. +The new method is identical to the book except for using ''TlaPlus'' instead of ''Lox'':
-Add a constructor for the ''Interpreter'' class along with the field; also add a ''replMode'' parameter, although don't make use of it just yet: +
- +
-<code java [highlight_lines_extra="3,5,6,7"]> +
-class Interpreter implements Expr.Visitor<Object>, +
-                             Stmt.Visitor<Void> { +
-  private final PrintStream out; +
- +
-  public Interpreter(PrintStream out, boolean replMode) { +
-    this.out = out; +
-  } +
-</code> +
- +
-Same as the book, modify the old ''interpret()'' method to accept a list of statements. +
-The changed method is identical to the book except for using ''TlaPlus'' instead of ''Lox'': +
 <code java [highlight_lines_extra="7"]> <code java [highlight_lines_extra="7"]>
   void interpret(List<Stmt> statements) {   void interpret(List<Stmt> statements) {
Line 120: Line 105:
  
 Also add the ''execute()'' helper method to the ''Interpreter'' class: Also add the ''execute()'' helper method to the ''Interpreter'' class:
- 
 <code java> <code java>
   private void execute(Stmt stmt) {   private void execute(Stmt stmt) {
Line 127: Line 111:
 </code> </code>
  
-At the top of ''Interpreter.java'', import the classes we're now using: +At the top of ''Interpreter.java'', add an import for the ''List'' class that is now being used by ''interpret()'': 
- +<code java [highlight_lines_extra="5"]>
-<code java [highlight_lines_extra="5,6"]>+
 package tla; package tla;
  
Line 135: Line 118:
 import java.util.HashSet; import java.util.HashSet;
 import java.util.List; import java.util.List;
-import java.io.PrintStream; 
 </code> </code>
  
Line 154: Line 136:
 </code> </code>
  
-Then replace the call to the interpreter with this: +Still in ''run()'', replace the call to the printer & interpreter with this: 
- +<code java [highlight_lines_extra="3,4"]>
-<code java [highlight_lines_extra="3"]>+
     if (hadError) return;     if (hadError) return;
  
 +    System.out.println(new AstPrinter().print(statements));
     interpreter.interpret(statements);     interpreter.interpret(statements);
   }   }
Line 165: Line 147:
 A bit more tidying up is necessary. A bit more tidying up is necessary.
 We need to detect when we're in REPL vs. file mode and propagate that information to our various methods and classes. We need to detect when we're in REPL vs. file mode and propagate that information to our various methods and classes.
-Remove the ''final'' annotation on the ''interpreter'' field of the ''TlaPlus'' class and leave it uninitialized by default:+Remove the ''final'' modifier on the ''interpreter'' field of the ''TlaPlus'' class and leave it uninitialized by default:
  
 <code java [highlight_lines_extra="2"]> <code java [highlight_lines_extra="2"]>
Line 176: Line 158:
 <code java [highlight_lines_extra="2,4"]> <code java [highlight_lines_extra="2,4"]>
   private static void runFile(String path) throws IOException {   private static void runFile(String path) throws IOException {
-    interpreter = new Interpreter(System.out, false);+    interpreter = new Interpreter(false);
     byte[] bytes = Files.readAllBytes(Paths.get(path));     byte[] bytes = Files.readAllBytes(Paths.get(path));
     run(new String(bytes, StandardCharsets.UTF_8), false);     run(new String(bytes, StandardCharsets.UTF_8), false);
Line 183: Line 165:
 Similarly modify the ''runPrompt'' method: Similarly modify the ''runPrompt'' method:
  
-<code java [highlight_lines_extra="2,10"]>+<code java [highlight_lines_extra="2,8"]>
   private static void runPrompt() throws IOException {   private static void runPrompt() throws IOException {
-    interpreter = new Interpreter(System.out, true); +    interpreter = new Interpreter(true);
-    InputStreamReader input = new InputStreamReader(System.in); +
-    BufferedReader reader = new BufferedReader(input);+
  
     for (;;) {     for (;;) {
Line 196: Line 176:
       hadError = false;       hadError = false;
     }     }
 +  }
 +</code>
 +
 +We just used an ''Interpreter'' constructor accepting a parameter indicating whether we're operating in REPL mode.
 +Write that constructor now, although don't yet do anything with the parameter:
 +<code java>
 +  public Interpreter(boolean replMode) {
 +
   }   }
 </code> </code>
Line 205: Line 193:
 In [[https://craftinginterpreters.com/statements-and-state.html#global-variables|section 8.2]] we introduce global variables in the sense of top-level operator definitions. In [[https://craftinginterpreters.com/statements-and-state.html#global-variables|section 8.2]] we introduce global variables in the sense of top-level operator definitions.
 Operator definitions in TLA⁺ take the form ''name == expr''. Operator definitions in TLA⁺ take the form ''name == expr''.
-They can be parameterized with arguments, but we won't be implementing that until the tutorial covering chapter 10.+They can be parameterized with arguments, but we won't be implementing that until the tutorial covering chapter 10 of //Crafting Interpreters//.
 For now we are simply assigning a name to a value. For now we are simply assigning a name to a value.
  
Line 212: Line 200:
 <code java [highlight_lines_extra="3"]> <code java [highlight_lines_extra="3"]>
     defineAst(outputDir, "Stmt", Arrays.asList(     defineAst(outputDir, "Stmt", Arrays.asList(
-      "Print    : Expr expression",+      "Print    : Token location, Expr expression",
       "OpDef    : Token name, Expr body"       "OpDef    : Token name, Expr body"
     ));     ));
 </code> </code>
  
-Also generate a ''Expr.Variable'' class for expressions referring to the operators:+Also generate an ''Expr.Variable'' class for expressions referring to the operators:
  
 <code java [highlight_lines_extra="5"]> <code java [highlight_lines_extra="5"]>
Line 258: Line 246:
 That single line difference calls three separate functions we still need to define. That single line difference calls three separate functions we still need to define.
 While Lox is a nice unambiguous language with semicolon-delimited statements, TLA⁺ is a wholly different beast! While Lox is a nice unambiguous language with semicolon-delimited statements, TLA⁺ is a wholly different beast!
-In TLA⁺ it is quite difficult to know where each definition ends and another beings.+In TLA⁺ it is quite difficult to know where each definition ends and another begins.
 We have to resort to the somewhat drastic measure of cloning our parser then looking several tokens ahead in the stream in search of a ''=='', at which point we will know for certain we are about to parse a new definition. We have to resort to the somewhat drastic measure of cloning our parser then looking several tokens ahead in the stream in search of a ''=='', at which point we will know for certain we are about to parse a new definition.
 This type of unbounded lookahead is inelegant and can lead to poor parser performance, but it simply has to be done. This type of unbounded lookahead is inelegant and can lead to poor parser performance, but it simply has to be done.
Line 292: Line 280:
 </code> </code>
  
-So we clone the parser, used the cloned parser to look ahead to see whether we're at the start of an operator definition, and - if so - throw away the cloned parser then use our original parser to parse the operator definition like normal.+So we clone the parser, use the cloned parser to look ahead to see whether we're at the start of an operator definition, and - if so - throw away the cloned parser then use our original parser to parse the operator definition like normal.
  
 Incidentally, we can now fill out our ''synchronize()'' error recovery method! Incidentally, we can now fill out our ''synchronize()'' error recovery method!
Line 330: Line 318:
  
 In [[https://craftinginterpreters.com/statements-and-state.html#environments|section 8.3]] we build the infrastructure for assigning values to variables then retrieving them. In [[https://craftinginterpreters.com/statements-and-state.html#environments|section 8.3]] we build the infrastructure for assigning values to variables then retrieving them.
-Create a new file, ''Environment.java'':+Create a new file, ''Environment.java'' (changes relative to book highlighted):
  
 <code java [highlight_lines_extra="1"]> <code java [highlight_lines_extra="1"]>
Line 347: Line 335:
 This requires defining a constructor: This requires defining a constructor:
  
-<code java [highlight_lines_extra=""]>+<code java [highlight_lines_extra="2,5,6,7"]>
 class Environment { class Environment {
   private final boolean allowRedefinition;   private final boolean allowRedefinition;
Line 358: Line 346:
 </code> </code>
  
-Then, our ''define()'' method looks like this:+Then, our ''define()'' method looks like this (changes relative to book highlighted):
  
 <code java [highlight_lines_extra="1,2,3,4"]> <code java [highlight_lines_extra="1,2,3,4"]>
Line 370: Line 358:
 </code> </code>
  
-Note that we changed the method signature to accept a ''Token'' instead of a ''String'' for the name, so that the ''RuntimeError'' can be constructed properly.+Compared to the book we changed the method signature to accept a ''Token'' instead of a ''String'' for the name, so that the ''RuntimeError'' can be constructed properly.
  
 Our ''get()'' method is unchanged from the book: Our ''get()'' method is unchanged from the book:
Line 386: Line 374:
  
 Now add an ''Environment'' instance as a field of your ''Interpreter'' class; here's where we make use of the ''replMode'' constructor parameter we added up above: Now add an ''Environment'' instance as a field of your ''Interpreter'' class; here's where we make use of the ''replMode'' constructor parameter we added up above:
- +<code java [highlight_lines_extra="3,6"]>
-<code java [highlight_lines_extra="3,7"]>+
 class Interpreter implements Expr.Visitor<Object>, class Interpreter implements Expr.Visitor<Object>,
                              Stmt.Visitor<Void> {                              Stmt.Visitor<Void> {
   private Environment environment;   private Environment environment;
-  private final PrintStream out; 
  
-  public Interpreter(PrintStream out, boolean replMode) {+  public Interpreter(boolean replMode) {
     this.environment = new Environment(replMode);     this.environment = new Environment(replMode);
-    this.out = out; 
   }   }
 </code> </code>
  
-Now add a visitor method in the ''Interpreter'' class for the ''Expr.Variable'' class, which retrieves the value of the variable from the environment: +Add a visitor method in the ''Interpreter'' class for the ''Expr.Variable'' class, which retrieves the value of the variable from the environment:
 <code java> <code java>
   @Override   @Override
Line 407: Line 391:
   }   }
 </code> </code>
- 
  
 ====== Section 8.4: Assignment ====== ====== Section 8.4: Assignment ======
Line 424: Line 407:
  
 And that's it! And that's it!
-Your interpreter should now support definitions: +Your interpreter should now support definitions (some output omitted below):
 <code> <code>
 > x == 2 > x == 2
Line 446: Line 428:
 </code> </code>
  
-Initialize it to ''null'' in the current constructor, then add a copy constructor: +Initialize it to ''null'' in the current constructor, then add a second constructor:
 <code java [highlight_lines_extra="2,6,7,8,9"]> <code java [highlight_lines_extra="2,6,7,8,9"]>
   Environment(boolean allowRedefinition) {   Environment(boolean allowRedefinition) {
Line 457: Line 438:
     this.enclosing = enclosing;     this.enclosing = enclosing;
     this.allowRedefinition = enclosing.allowRedefinition;     this.allowRedefinition = enclosing.allowRedefinition;
 +  }
 +</code>
 +
 +Finally, update ''get()'':
 +<code java [highlight_lines_extra="6"]>
 +  Object get(Token name) {
 +    if (values.containsKey(name.lexeme)) {
 +      return values.get(name.lexeme);
 +    }
 +
 +    if (enclosing != null) return enclosing.get(name);
 +
 +    throw new RuntimeError(name,
 +        "Undefined variable '" + name.lexeme + "'.");
   }   }
 </code> </code>
Line 463: Line 458:
  
 Next up, our greatest parsing challenge yet: [[creating:jlists|conjunction & disjunction lists]]! Next up, our greatest parsing challenge yet: [[creating:jlists|conjunction & disjunction lists]]!
-If your code got out of sync during this tutorial, you can find a snapshot of its expected state in [[https://github.com/tlaplus-community/tlaplus-creator/tree/main/5-statements|this repo directory]].+If your code got out of sync during this tutorial, you can find a snapshot of its expected state in [[https://github.com/tlaplus/devkit/tree/main/5-statements|this repo directory]].
  
-====== Section 8.5: Challenges ======+====== Challenges ======
  
-  - Write some unit tests for your interpreter. Use a ''[[https://docs.oracle.com/javase/8/docs/api/java/io/ByteArrayOutputStream.html|ByteArrayOutputStream]]'' instance as a parameter to the ''PrintStream'' constructor, then pass your ''PrintStream'' instance into the ''Interpreter'' class to capture its output.+  - Write some unit tests for your interpreter. Capture the ''System.out'' output; use the ''[[https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#setOut-java.io.PrintStream-|System.setOut()]]'' method with a ''[[https://docs.oracle.com/javase/8/docs/api/java/io/PrintStream.html|PrintStream]]'' instance constructed using a ''[[https://docs.oracle.com/javase/8/docs/api/java/io/ByteArrayOutputStream.html|ByteArrayOutputStream]]''.
   - The ''isAtOpDefStart()'' and ''operatorDefinition()'' methods have some duplicated logic that will only grow more involved when we add operator parameter support. Can you find a way to factor out this logic into a single method?   - The ''isAtOpDefStart()'' and ''operatorDefinition()'' methods have some duplicated logic that will only grow more involved when we add operator parameter support. Can you find a way to factor out this logic into a single method?
  
 [[creating:evaluation|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:jlists|Next Page >]] [[creating:evaluation|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:jlists|Next Page >]]
- 
  • creating/statements.1745092059.txt.gz
  • Last modified: 2025/04/19 19:47
  • by ahelwer