Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

70
LINES

< > BotCompany Repo | #1030697 // SimpleInterpreter

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (3165L/18K).

1  
sclass SimpleInterpreter {
2  
  sclass State {
3  
    new LinkedHashMap<S, O> vars;
4  
    new L stack;
5  
    
6  
    selfType set(S var, O value) {
7  
      vars.put(var, value);
8  
      this;
9  
    }
10  
    
11  
    O eval(Instruction i) {
12  
      i.run(this);
13  
      ret pop();
14  
    }
15  
    
16  
    <A> A eval(Evaluable<A> e) {
17  
      ret e?.get(this);
18  
    }
19  
    
20  
    O get(S var) { ret mapGet(vars, var); }
21  
    
22  
    void push(O value) { stack.add(value); }
23  
    O pop() { ret popLast(stack); }
24  
  }
25  
  
26  
  asclass Instruction {
27  
    abstract void run(State state);
28  
  }
29  
  
30  
  sinterface Evaluable<A> {
31  
    A get(State state);
32  
  }
33  
  
34  
  /*srecord Const(O value) > Instruction {
35  
    void run(State state) {
36  
      state.push(value);
37  
    }
38  
  }*/
39  
  
40  
  srecord Const<A>(A value) implements Evaluable<A> {
41  
    public A get(State state) {
42  
      ret value;
43  
    }
44  
  }
45  
  
46  
  srecord Sequence(L<Instruction> l) > Instruction {
47  
    Sequence(Instruction... l) { this.l = asList(l); }
48  
    
49  
    void run(State state) {
50  
      fOr ping (Instruction i : l)
51  
        i.run(state);
52  
    }
53  
  }
54  
  
55  
  srecord GetVar(Evaluable<S> var) > Instruction {
56  
    void run(State state) {
57  
      state.push(state.get(state.eval(var)));
58  
    }
59  
  }
60  
  
61  
  srecord CallF(Evaluable f, Evaluable... args) > Instruction {
62  
    void run(State state) {
63  
      O realF = state.eval(f);
64  
      O[] realArgs = mapToArray(args, a -> state.eval(a));
65  
      state.push(safeCallF(realF, realArgs));
66  
    }
67  
  }
68  
  
69  
  State newState() { ret new State; }
70  
}

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, vouqrxazstgt

No comments. add comment

Snippet ID: #1030697
Snippet name: SimpleInterpreter
Eternal ID of this version: #1030697/7
Text MD5: ef62cd0f3b880f48e26bd93f472f3da9
Transpilation MD5: efab2d7e6726a8d30d70c8fb57b17a00
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-03-08 20:28:57
Source code size: 1517 bytes / 70 lines
Pitched / IR pitched: No / No
Views / Downloads: 162 / 367
Version history: 6 change(s)
Referenced in: [show references]