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/06/18 20:42] – Fixed stale line of code due to print changes 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 46: 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 60: 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.
 +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. Use ''peek()'' to get the first token in the expression for error location reporting.
-We'll return to this method later to add parsing logic for operator definitions. 
 <code java> <code java>
   private Stmt statement() {   private Stmt statement() {
Line 72: 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 90: Line 90:
 </code> </code>
  
-Same as the book, modify the old ''interpret()'' method to accept a list of statements. +Same as the book, overwrite 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'':+The new 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 136: Line 136:
 </code> </code>
  
-Still in ''run()'', 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"]>+<code java [highlight_lines_extra="3,4"]>
     if (hadError) return;     if (hadError) return;
  
 +    System.out.println(new AstPrinter().print(statements));
     interpreter.interpret(statements);     interpreter.interpret(statements);
   }   }
Line 146: 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 164: 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(true);     interpreter = new Interpreter(true);
-    InputStreamReader input = new InputStreamReader(System.in); 
-    BufferedReader reader = new BufferedReader(input); 
  
     for (;;) {     for (;;) {
Line 182: Line 181:
 We just used an ''Interpreter'' constructor accepting a parameter indicating whether we're operating in REPL mode. 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: Write that constructor now, although don't yet do anything with the parameter:
-<code Java>+<code java>
   public Interpreter(boolean replMode) {   public Interpreter(boolean replMode) {
  
Line 194: 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 206: Line 205:
 </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 247: 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 281: 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 319: 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 336: 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 347: 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 359: 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 408: 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 430: 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 441: 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 449: Line 460:
 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]]. 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. 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]]''.   - 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]]''.
Line 455: Line 466:
  
 [[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.1750279326.txt.gz
  • Last modified: 2025/06/18 20:42
  • by ahelwer