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).

sclass SimpleInterpreter {
  sclass State {
    new LinkedHashMap<S, O> vars;
    new L stack;
    
    selfType set(S var, O value) {
      vars.put(var, value);
      this;
    }
    
    O eval(Instruction i) {
      i.run(this);
      ret pop();
    }
    
    <A> A eval(Evaluable<A> e) {
      ret e?.get(this);
    }
    
    O get(S var) { ret mapGet(vars, var); }
    
    void push(O value) { stack.add(value); }
    O pop() { ret popLast(stack); }
  }
  
  asclass Instruction {
    abstract void run(State state);
  }
  
  sinterface Evaluable<A> {
    A get(State state);
  }
  
  /*srecord Const(O value) > Instruction {
    void run(State state) {
      state.push(value);
    }
  }*/
  
  srecord Const<A>(A value) implements Evaluable<A> {
    public A get(State state) {
      ret value;
    }
  }
  
  srecord Sequence(L<Instruction> l) > Instruction {
    Sequence(Instruction... l) { this.l = asList(l); }
    
    void run(State state) {
      fOr ping (Instruction i : l)
        i.run(state);
    }
  }
  
  srecord GetVar(Evaluable<S> var) > Instruction {
    void run(State state) {
      state.push(state.get(state.eval(var)));
    }
  }
  
  srecord CallF(Evaluable f, Evaluable... args) > Instruction {
    void run(State state) {
      O realF = state.eval(f);
      O[] realArgs = mapToArray(args, a -> state.eval(a));
      state.push(safeCallF(realF, realArgs));
    }
  }
  
  State newState() { ret new State; }
}

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: 217 / 448
Version history: 6 change(s)
Referenced in: #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)