creating:actions

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:actions [2025/06/19 21:36] – Finished probable final draft of actions tutorial ahelwercreating:actions [2026/11/19 02:03] (current) – Fixed input handling ahelwer
Line 146: Line 146:
 </code> </code>
  
-===== Reading & Priming State Variables =====+===== Reading, Priming, & Setting State Variables =====
  
 To resolve variable values, modify the ever-more-complicated ''visitVariableExpr()'' method of the ''Interpreter'' class to first check whether it's resolving a variable, falling back to an ''environment'' lookup if not: To resolve variable values, modify the ever-more-complicated ''visitVariableExpr()'' method of the ''Interpreter'' class to first check whether it's resolving a variable, falling back to an ''environment'' lookup if not:
 <code java [highlight_lines_extra="2,3,4,5"]> <code java [highlight_lines_extra="2,3,4,5"]>
   public Object visitVariableExpr(Expr.Variable expr) {   public Object visitVariableExpr(Expr.Variable expr) {
-    Object referent =+    Object callee =
       variables.containsKey(expr.name.lexeme)       variables.containsKey(expr.name.lexeme)
       ? (primed ? next : current).get(expr.name.lexeme)       ? (primed ? next : current).get(expr.name.lexeme)
       : environment.get(expr.name);       : environment.get(expr.name);
  
-    if (!(referent instanceof TlaCallable)) {+    if (!(callee instanceof TlaCallable)) {
 </code> </code>
  
Line 171: Line 171:
 The ''primed'' field is initialized to ''true'', since the interpreter builds the system's initial state in the ''next'' field so we want all expressions to be implicitly primed at first. The ''primed'' field is initialized to ''true'', since the interpreter builds the system's initial state in the ''next'' field so we want all expressions to be implicitly primed at first.
 We can now finally define the prime operator for real, in ''visitUnaryExpr()'' in the ''Interpreter'' class: We can now finally define the prime operator for real, in ''visitUnaryExpr()'' in the ''Interpreter'' class:
-<code java [highlight_lines_extra="4,5,6,7,8,9,10,11,12"]>+<code java [highlight_lines_extra="4,5,6,7,8,9,10,11,12,13,14"]>
   public Object visitUnaryExpr(Expr.Unary expr) {   public Object visitUnaryExpr(Expr.Unary expr) {
     switch (expr.operator.type) {     switch (expr.operator.type) {
Line 177: Line 177:
         if (primed) {         if (primed) {
           throw new RuntimeError(expr.operator,           throw new RuntimeError(expr.operator,
-              "Cannot double-prime expression nor prime initial state.");+              current == null 
 +              ? "Cannot prime expression in initial state." 
 +              : "Cannot double-prime expression.");
         } try {         } try {
           primed = true;           primed = true;
Line 187: Line 189:
 </code> </code>
  
-Double-priming an expression or priming an expression in the initial state are both fatal errors in TLA⁺.+Double-priming an expression or - in the initial state - priming an expression at all are both fatal errors in TLA⁺.
 The meaning of priming an expression is that all state variables within that expression are primed, so the way the expression is evaluated is fundamentally changed. The meaning of priming an expression is that all state variables within that expression are primed, so the way the expression is evaluated is fundamentally changed.
 This is why the prime operator somewhat uniquely modifies the state of the ''Interpreter'' instance itself. This is why the prime operator somewhat uniquely modifies the state of the ''Interpreter'' instance itself.
 Similar to in ''executeBlock()'', we wrap this ''Interpreter'' state modification inside a ''try''/''finally'' block to ensure that if the evaluation produces a runtime exception, ''primed'' is reset to ''false'' so the ''Interpreter'' instance is not left in a corrupted state. Similar to in ''executeBlock()'', we wrap this ''Interpreter'' state modification inside a ''try''/''finally'' block to ensure that if the evaluation produces a runtime exception, ''primed'' is reset to ''false'' so the ''Interpreter'' instance is not left in a corrupted state.
- 
-===== Setting State Variables ===== 
  
 We can retrieve state variable values, but what about assigning them? We can retrieve state variable values, but what about assigning them?
Line 198: Line 198:
 This requires modifying the ''EQUAL'' case of ''visitBinaryExpr()'' in the ''Interpreter'' class. This requires modifying the ''EQUAL'' case of ''visitBinaryExpr()'' in the ''Interpreter'' class.
 If the ''left'' operand is an ''UnboundVariable'' instance, then bind the ''left'' state variable to the value of ''right'': If the ''left'' operand is an ''UnboundVariable'' instance, then bind the ''left'' state variable to the value of ''right'':
-<code java [highlight_lines_extra="2,3,4,5,6"]>+<code java [highlight_lines_extra="2,3,4,5"]>
       case EQUAL:       case EQUAL:
-        if (left instanceof State.UnboundVariable) { +        if (left instanceof UnboundVariable var) {
-          UnboundVariable var = (UnboundVariable)left;+
           next.put(var.name().lexeme, right);           next.put(var.name().lexeme, right);
           return true;           return true;
Line 208: Line 207:
 </code> </code>
  
-We only modify variable values in ''next'', not ''current''; variable values in ''current'' should be considered immutable. +We only modify variable values in ''next'', not ''current''; variable values in ''current'' should be considered immutable, and we will never let an ''UnboundVariable'' value into the ''current'' state.
- +
-Although we won't yet use it, now is also a good time to define our ''step()'' method, which transitions the ''Interpreter'' instance to the next state; it has two associated helper methods, ''isComplete()'' and ''clearNext()'': +
-<code java> +
-  void step(Token location) { +
-    if (!isComplete()) { +
-      throw new RuntimeError(location, +
-          "Cannot step to incomplete next state."); +
-    } +
- +
-    primed = false; +
-    current = next; +
-    clearNext(); +
-  } +
- +
-  private void isComplete() { +
-    return !variables.isEmpty() && next.values().stream() +
-        .noneMatch(v -> v instanceof UnboundVariable); +
-  } +
- +
-  private void clearNext() { +
-    next = new HashMap<>(); +
-    for (Token variable : variables.values()) { +
-      next.put(variable.lexeme, new UnboundVariable(variable)); +
-    } +
-  } +
-</code> +
- +
-''isComplete()'' checks to ensure the next state is completely defined, and ''clearNext()'' resets the value of ''next''. +
- +
-Now we see things taking shape: ''Interpreter'' is initialized with ''current'' set to ''null'' and ''primed'' set to ''true'', ready to define the system's initial state. +
-The system's initial state is defined by setting the values of all declared variables in ''next'', using expressions like ''x = 0''. +
-Then, ''step()'' is called, which sets ''current'' to ''next'' and ''primed'' to ''false''; the system is now in its initial state, ready to take steps to next states. +
-The values of variables in ''next'' are subsequently set using expressions like ''x' = 1 - x'', then ''step()'' is called again, and so on.+
  
 ===== Nondeterminism ===== ===== Nondeterminism =====
Line 269: Line 235:
 </code> </code>
  
-We also update ''clearNext()'' to wipe the new ''possibleNext'' field: +When our interpreter finds multiple possible next states, it tosses them into ''possibleNext'' for later consideration and continues evaluating & binding the variables in the next state currently under construction.
-<code java [highlight_lines_extra="2"]> +
-  private void clearNext() { +
-    possibleNext = new HashSet<>(); +
-    next = new HashMap<>(); +
-</code> +
- +
-When our interpreter finds multiple possible next states, it tosses them into ''possibleNext'' for later consideration and continues evaluating & binding the variables in the current state.+
 Then some top-level loop churns through the ''possibleNext'' set, either ruling out or accepting each possible next state until none remain. Then some top-level loop churns through the ''possibleNext'' set, either ruling out or accepting each possible next state until none remain.
 We will write this very critical top-level loop now; create a new method ''getNextStates()'' in the ''Interpreter'' class: We will write this very critical top-level loop now; create a new method ''getNextStates()'' in the ''Interpreter'' class:
Line 297: Line 256:
     Set<Map<String, Object>> confirmedNext = new HashSet<>();     Set<Map<String, Object>> confirmedNext = new HashSet<>();
     clearNext();     clearNext();
-    possibleNext.add(new HashMap<>(next));+    possibleNext.add(Map.copyOf(next));
     try {     try {
       while (!possibleNext.isEmpty()) {       while (!possibleNext.isEmpty()) {
Line 311: Line 270:
  
 We use the familiar ''try''/''finally'' approach when evaluating expressions within a modified ''Interpreter'' state to ensure runtime exceptions do not corrupt the ''Interpreter'' instance. We use the familiar ''try''/''finally'' approach when evaluating expressions within a modified ''Interpreter'' state to ensure runtime exceptions do not corrupt the ''Interpreter'' instance.
-We also use the ''new HashMap<>(next)'' copy constructor to copy ''next'' before putting it in ''possibleNext'', which avoids a //very// subtle bug: since evaluating the action modifies the values in ''next'', and we put ''next'' into a ''HashMap<>'' which records its position by calculating a hash of the value of ''next'', if we subsequently modify the same object put into the ''HashMap<>'' then that value will get "lost" in the datastructure, because its hash value changed.+We also use ''Map.copyOf(next)'' to copy ''next'' and make it immutable before putting it in ''possibleNext'', which avoids a //very// subtle bug: since evaluating the action modifies the values in ''next'', and we put ''next'' into a ''HashSet<>'' which records its position by calculating a hash of the value of ''next'', if we subsequently modify the same object put into the ''HashSet<>'' then that value will get "lost" in the datastructure, because its hash value changed.
 For more on this peculiar issue, consult the Java ''[[https://docs.oracle.com/javase/8/docs/api/java/util/Map.html|Map<>]]'' documentation which warns against using mutable objects as keys. For more on this peculiar issue, consult the Java ''[[https://docs.oracle.com/javase/8/docs/api/java/util/Map.html|Map<>]]'' documentation which warns against using mutable objects as keys.
  
-Now we can write the central loop: +This code also requires a new ''clearNext()'' helper method in the ''Interpreter'' class, which does what you might expect from the name; it clears ''possibleNext'' then unbinds all variables in ''next'': 
-<code java [highlight_lines_extra="2,3,4,5,6,7"]>+<code java> 
 +  private void clearNext() { 
 +    possibleNext = new HashSet<>(); 
 +    next = new HashMap<>(); 
 +    for (Token variable : variables.values()) { 
 +      next.put(variable.lexeme, new UnboundVariable(variable)); 
 +    } 
 +  } 
 +</code> 
 + 
 +Now we can write the central ''getNextStates()'' loop: 
 +<code java [highlight_lines_extra="2,3,4,5,6,7,8,9"]>
       while (!possibleNext.isEmpty()) {       while (!possibleNext.isEmpty()) {
         Map<String, Object> trunk = possibleNext.iterator().next();         Map<String, Object> trunk = possibleNext.iterator().next();
Line 321: Line 291:
         Object satisfied = evaluate(action);         Object satisfied = evaluate(action);
         checkBooleanOperand(location, satisfied);         checkBooleanOperand(location, satisfied);
-        if ((boolean)satisfied && isComplete()) confirmedNext.add(next);+        if ((boolean)satisfied && isComplete()) { 
 +          confirmedNext.add(Map.copyOf(next)); 
 +        }
         possibleNext.remove(trunk);         possibleNext.remove(trunk);
       }       }
Line 327: Line 299:
  
 Note again the judicious use of ''HashMap<>'' copy constructors to avoid the mutable ''HashMap<>'' key bug. Note again the judicious use of ''HashMap<>'' copy constructors to avoid the mutable ''HashMap<>'' key bug.
 +This code requires yet another ''Interpreter'' helper method to check whether a next state candidate is complete (has all variables assigned to concrete values):
 +<code java>
 +  private boolean isComplete() {
 +    return !variables.isEmpty() && next.values().stream()
 +        .noneMatch(v -> v instanceof UnboundVariable);
 +  }
 +</code>
  
 It's worth spending some time considering the ''getNextStates()'' method. It's worth spending some time considering the ''getNextStates()'' method.
Line 339: Line 318:
 Let's get concrete. Let's get concrete.
 How do we add states to ''possibleNext'' while evaluating disjunction? How do we add states to ''possibleNext'' while evaluating disjunction?
-For each disjunct, we use a fresh copy of the ''next'' state, then evaluate the disjunct and add the resulting modified ''next'' state to ''possibleNext''.+For each disjunct, we use a fresh copy of the ''next'' state, then evaluate the disjunct and - if the disjunct evaluates to true - add the resulting modified ''next'' state to ''possibleNext''.
 As described above, this state will either already be in ''possibleNext'' (so be de-duplicated) or have bound the value of at least one more state variable. As described above, this state will either already be in ''possibleNext'' (so be de-duplicated) or have bound the value of at least one more state variable.
 We need to evaluate every disjunct to ensure we find all possible next states, which is why TLA⁺ disjunction does not short-circuit. We need to evaluate every disjunct to ensure we find all possible next states, which is why TLA⁺ disjunction does not short-circuit.
 +We also need to ensure that at the end of evaluation, ''next'' points to a state resulting from a true disjunct.
 Modify the ''OR'' handling code in ''visitVariadicExpr()'' as highlighted: Modify the ''OR'' handling code in ''visitVariadicExpr()'' as highlighted:
-<code java [highlight_lines_extra="3,5,8"]>+<code java [highlight_lines_extra="3,4,6,10,11,15"]>
       case OR:       case OR:
         boolean result = false;         boolean result = false;
         Map<String, Object> trunk = next;         Map<String, Object> trunk = next;
 +        Map<String, Object> lastValidNext = trunk;
         for (Expr disjunct : expr.parameters) {         for (Expr disjunct : expr.parameters) {
           next = new HashMap<>(trunk);           next = new HashMap<>(trunk);
           Object junctResult = evaluate(disjunct);           Object junctResult = evaluate(disjunct);
           checkBooleanOperand(expr.operator, junctResult);           checkBooleanOperand(expr.operator, junctResult);
-          possibleNext.add(new HashMap<>(next)); +          if ((boolean)junctResult) { 
-          result |= (boolean)junctResult;+            possibleNext.add(Map.copyOf(next)); 
 +            lastValidNext = next; 
 +            result = true; 
 +          }
         }         }
 +        next = lastValidNext;
         return result;         return result;
       default:       default:
Line 359: Line 344:
  
 There are two other operators to support for binding state variables: the set membership ''\in'' operator, and the ''\E'' existential quantification operator. There are two other operators to support for binding state variables: the set membership ''\in'' operator, and the ''\E'' existential quantification operator.
-Actions like ''x' \in {0, 1}'' or ''\E v \in {0, 1} : x' = v'' are equivalent to ''x' = 0 \/ x' = 1''.+Actions like ''x' \in {0, 1}'' or ''\E v \in {0, 1} : x' = v'' are equivalent to ''x' = 0 \/ x' = 1''; ''x' \in {}'' and ''\E v \in {} : TRUE'' should always evaluate to false.
 Add the following code to the ''IN'' case in ''visitBinaryExpr()'': Add the following code to the ''IN'' case in ''visitBinaryExpr()'':
-<code java [highlight_lines_extra="3,4,5,6,7,8,9,10,11,12,13"]>+<code java [highlight_lines_extra="3,4,5,6,7,8,9,10,11"]>
       case IN:       case IN:
         checkSetOperand(expr.operator, right);         checkSetOperand(expr.operator, right);
-        if (left instanceof State.UnboundVariable) { +        if (left instanceof UnboundVariable var) {
-          UnboundVariable var = (UnboundVariable)left;+
           Map<String, Object> trunk = next;           Map<String, Object> trunk = next;
           for (Object element : (Set<?>)right) {           for (Object element : (Set<?>)right) {
Line 371: Line 355:
             next.put(var.name().lexeme, element);             next.put(var.name().lexeme, element);
             left = element;             left = element;
-            possibleNext.add(new HashMap<>(next));+            possibleNext.add(Map.copyOf(next));
           }           }
-          return true; 
         }         }
         return ((Set<?>)right).contains(left);         return ((Set<?>)right).contains(left);
Line 379: Line 362:
  
 Then update the ''EXISTS'' case of ''visitQuantFnExpr()'' as highlighted: Then update the ''EXISTS'' case of ''visitQuantFnExpr()'' as highlighted:
-<code java [highlight_lines_extra="3,5,8"]>+<code java [highlight_lines_extra="3,4,6,10,11,15"]>
       } case EXISTS: {       } case EXISTS: {
         boolean result = false;         boolean result = false;
-        State current = state; 
         Map<String, Object> trunk = next;         Map<String, Object> trunk = next;
 +        Map<String, Object> lastValidNext = trunk;
         for (Environment binding : bindings) {         for (Environment binding : bindings) {
           next = new HashMap<>(trunk);           next = new HashMap<>(trunk);
           Object junctResult = executeBlock(expr.body, binding);           Object junctResult = executeBlock(expr.body, binding);
           checkBooleanOperand(expr.op, junctResult);           checkBooleanOperand(expr.op, junctResult);
-          possibleNext.add(new HashMap<>(next)); +          if ((boolean)junctResult) { 
-          result |= (boolean)junctResult;+            possibleNext.add(Map.copyOf(next)); 
 +            lastValidNext = next; 
 +            result = true; 
 +          }
         }         }
 +        next = lastValidNext;
         return result;         return result;
 </code> </code>
Line 403: Line 390:
 Well, not quite - the ''ENABLED'' operator can possibly be evaluated //inside// an action, so inside a call to ''getNextStates()''! Well, not quite - the ''ENABLED'' operator can possibly be evaluated //inside// an action, so inside a call to ''getNextStates()''!
 This means we need some extra ceremony to stash the current values of ''next'' and ''possibleNext'', then restore them using the standard ''try''/''finally'' block method. This means we need some extra ceremony to stash the current values of ''next'' and ''possibleNext'', then restore them using the standard ''try''/''finally'' block method.
 +''ENABLED'' also accepts incomplete states, so ''getNextStates()'' will need to be modified to support that.
 Add the highlighted code to the ''ENABLED'' case in ''visitUnaryExpr()'': Add the highlighted code to the ''ENABLED'' case in ''visitUnaryExpr()'':
-<code java [highlight_lines_extra="2,3,4,5,6,7,8,9,10"]>+<code java [highlight_lines_extra="2,3,4,5,6,7,8,9"]>
       } case ENABLED: {       } case ENABLED: {
         Map<String, Object> oldNext = next;         Map<String, Object> oldNext = next;
         Set<Map<String,Object>> oldPossibleNext = possibleNext;         Set<Map<String,Object>> oldPossibleNext = possibleNext;
         try {         try {
-          clearNext(); +          return !getNextStates(expr.operator, expr.expr, true).isEmpty();
-          return !getNextStates(expr.operator, expr.expr).isEmpty();+
         } finally {         } finally {
           next = oldNext;           next = oldNext;
Line 417: Line 404:
       } case NOT: {       } case NOT: {
 </code> </code>
 +
 +Then modify ''getNextStates()'' by adding a new parameter, ''acceptIncompleteStates'', which allows it to add incomplete states to the ''confirmedNext'' set as required by ''ENABLED'':
 +<code java [highlight_lines_extra="1,11"]>
 +  List<Map<String, Object>> getNextStates(Token location, Expr action, boolean acceptIncompleteStates) {
 +    Set<Map<String, Object>> confirmedNext = new HashSet<>();
 +    clearNext();
 +    possibleNext.add(Map.copyOf(next));
 +    try {
 +      while (!possibleNext.isEmpty()) {
 +        Map<String, Object> trunk = possibleNext.iterator().next();
 +        next = new HashMap<>(trunk);
 +        Object satisfied = evaluate(action);
 +        checkBooleanOperand(location, satisfied);
 +        if ((boolean)satisfied && (isComplete() || acceptIncompleteStates)) {
 +          confirmedNext.add(Map.copyOf(next));
 +        }
 +</code>
 +
 +This change lets ''ENABLED Action'' only have ''Action'' determine the value of //some// of the spec's variables, instead of requiring it determine all of them.
  
 This is a big milestone: we now have fully defined //everything// in our minimal TLA⁺ language subset! This is a big milestone: we now have fully defined //everything// in our minimal TLA⁺ language subset!
Line 432: Line 438:
   private void checkIsValue(Object... operands) {   private void checkIsValue(Object... operands) {
     for (Object operand : operands) {     for (Object operand : operands) {
-      if (operand instanceof UnboundVariable) { +      if (operand instanceof UnboundVariable var) {
-        UnboundVariable var = (UnboundVariable)operand;+
         throw new RuntimeError(var.name(), "Use of unbound variable.");         throw new RuntimeError(var.name(), "Use of unbound variable.");
       }       }
Line 440: Line 445:
 </code> </code>
  
-In our ''EQUALS'' handling logic, we can only bind the value of ''right'' to a variable if ''right'' has a defined concrete value.+In our ''EQUAL'' handling logic, we can only bind the value of ''right'' to a variable if ''right'' has a defined concrete value.
 Also, two values can only be compared for equality if they are both defined: Also, two values can only be compared for equality if they are both defined:
-<code java [highlight_lines_extra="4,8"]>+<code java [highlight_lines_extra="3,7"]>
       case EQUAL:       case EQUAL:
-        if (left instanceof UnboundVariable) { +        if (left instanceof UnboundVariable var) {
-          UnboundVariable var = (UnboundVariable)left;+
           checkIsValue(right);           checkIsValue(right);
           next.put(var.name().lexeme, right);           next.put(var.name().lexeme, right);
Line 454: Line 458:
 </code> </code>
  
-A null check must also must be added to the ''LEFT_BRACE'' case in ''visitVariadicExpr()'':+A null check must also be added to the ''LEFT_BRACE'' case in ''visitVariadicExpr()'':
 <code java [highlight_lines_extra="5"]> <code java [highlight_lines_extra="5"]>
       case LEFT_BRACE:       case LEFT_BRACE:
Line 493: Line 497:
 One decent approach is to hijack ''Stmt.Print'' statements to trigger steps if they happen to define possible next states. One decent approach is to hijack ''Stmt.Print'' statements to trigger steps if they happen to define possible next states.
 For this, add the following code to the bottom of the ''run()'' method in the ''TlaPlus'' class: For this, add the following code to the bottom of the ''run()'' method in the ''TlaPlus'' class:
-<code java [highlight_lines_extra="4,5,6,7,8,9"]>+<code java [highlight_lines_extra="4,5,6,7,8,9,10,11,12,13"]>
     // Stop if there was a syntax error.     // Stop if there was a syntax error.
     if (hadError) return;     if (hadError) return;
  
     if (replMode && statements.size() == 1     if (replMode && statements.size() == 1
-        && statements.get(0) instanceof Stmt.Print) { +        && statements.get(0) instanceof Stmt.Print action) { 
-      tryStep((Stmt.Print)statements.get(0));+      try { 
 +        tryStep(action); 
 +      } catch (RuntimeError error) { 
 +        runtimeError(error); 
 +      }
     } else {     } else {
       interpreter.interpret(statements);       interpreter.interpret(statements);
Line 519: Line 527:
  
     List<Map<String, Object>> nextStates =     List<Map<String, Object>> nextStates =
-      interpreter.getNextStates(action.location, action.expression);+      interpreter.getNextStates(action.location, action.expression, false);
     if (nextStates.isEmpty()) {     if (nextStates.isEmpty()) {
       action.accept(interpreter);       action.accept(interpreter);
Line 539: Line 547:
 <code java [highlight_lines_extra="8,9,10,11,12"]> <code java [highlight_lines_extra="8,9,10,11,12"]>
     List<Map<String, Object>> nextStates =     List<Map<String, Object>> nextStates =
-      interpreter.getNextStates(action.location, action.expression);+      interpreter.getNextStates(action.location, action.expression, false);
     if (nextStates.isEmpty()) {     if (nextStates.isEmpty()) {
-      System.out.println(false);+      action.accept(interpreter);
       return;       return;
     }     }
  
     Map<String, Object> nextState = pickNext(nextStates);     Map<String, Object> nextState = pickNext(nextStates);
-    interpreter.setNextState(nextState); +    interpreter.goToState(nextState);
-    interpreter.step(action.location);+
     System.out.println(true);     System.out.println(true);
     System.out.println(nextState);     System.out.println(nextState);
Line 554: Line 561:
  
 We also print out ''true'' - the value ''Stmt.Print'' would have printed - and display the value of the next state for the user. We also print out ''true'' - the value ''Stmt.Print'' would have printed - and display the value of the next state for the user.
-This called two methods; one, in ''Interpreter'', sets the value of ''next'':+This calls two methods; one, ''goToState()'' in ''Interpreter'', sets the ''current'' state to the one given:
 <code java> <code java>
-  void setNextState(Map<String, Object> next) { +  void goToState(Map<String, Object> state) { 
-    this.next = next;+    current = state; 
 +    primed = state == null; 
 +    clearNext();
   }   }
 </code> </code>
Line 564: Line 573:
 If there are multiple possible next states, the user is prompted to choose one: If there are multiple possible next states, the user is prompted to choose one:
 <code java> <code java>
-  private static Map<String, Object> pickNext(List<Map<String, Object>> nextStates) {+  private static Map<String, Object> pickNext(List<Map<String, Object>> nextStates) throws IOException {
     if (nextStates.size() == 1) {     if (nextStates.size() == 1) {
       return nextStates.get(0);       return nextStates.get(0);
Line 574: Line 583:
  
       System.out.print("> ");       System.out.print("> ");
-      try (java.util.Scanner in = new java.util.Scanner(System.in)) { +      return nextStates.get(Integer.parseInt(reader.readLine()));
-        return nextStates.get(in.nextInt()); +
-      }+
     }     }
   }   }
 +</code>
 +
 +Since we are reading from ''System.in'' here, the ''throws IOException'' clause percolates back up the call stack:
 +<code java [highlight_lines_extra="1"]>
 +  private static void tryStep(Stmt.Print action) throws IOException {
 +    Object result = interpreter.executeBlock(action.expression, interpreter.globals);
 +</code>
 +<code java [highlight_lines_extra="1"]>
 +  private static void run(String source, boolean replMode) throws IOException {
 +    Scanner scanner = new Scanner(source);
 </code> </code>
  
Line 590: Line 607:
 This was a pivotal chapter; excellent work making it to the end. This was a pivotal chapter; excellent work making it to the end.
 You can find the expected state of the codebase in [[https://github.com/tlaplus/devkit/tree/main/8-actions|this repository]]. You can find the expected state of the codebase in [[https://github.com/tlaplus/devkit/tree/main/8-actions|this repository]].
-See you in the [[creating:closures|next chapter on closures!]] +Now we can put it all together and build a real model checker in [[creating:safety|the next chapter]]!
- +
-[[creating:operators|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:closures|Next Page >]]+
  
 +[[creating:operators|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:safety|Next Page >]]
  • creating/actions.1750368985.txt.gz
  • Last modified: 2025/06/19 21:36
  • by ahelwer