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/11/03 23:05] – Use Java's instanceof-cast syntax ahelwercreating:actions [2026/11/19 02:03] (current) – Fixed input handling ahelwer
Line 151: Line 151:
 <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 189: 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.
Line 256: 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 270: 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.
  
Line 285: Line 285:
  
 Now we can write the central ''getNextStates()'' loop: Now we can write the central ''getNextStates()'' loop:
-<code java [highlight_lines_extra="2,3,4,5,6,7"]>+<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 291: 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 316: 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 336: 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"]>+<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);
Line 347: 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 355: 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 379: 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 393: 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 415: 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="3,7"]> <code java [highlight_lines_extra="3,7"]>
Line 428: 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 467: 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 493: 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 513: 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;
     }     }
Line 527: 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, ''goToState()'' in ''Interpreter'', sets the ''current'' state to the one given:+This calls two methods; one, ''goToState()'' in ''Interpreter'', sets the ''current'' state to the one given:
 <code java> <code java>
   void goToState(Map<String, Object> state) {   void goToState(Map<String, Object> state) {
Line 539: 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 549: 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 568: Line 610:
  
 [[creating:operators|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:safety|Next Page >]] [[creating:operators|< Previous Page]] | [[creating:start#table_of_contents|Table of Contents]] | [[creating:safety|Next Page >]]
- 
  • creating/actions.1762211112.txt.gz
  • Last modified: 2025/11/03 23:05
  • by ahelwer