summaryrefslogtreecommitdiff
path: root/godel/js/compiler.js
blob: e63f5b0ca5f63da3b590a286639f05cf1375e38d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
class StringBuilder {
  constructor() {
    this.stringPieces = [];
  }
  add(s) {
    this.stringPieces.push(s);
  }
  build() {
    return this.stringPieces.join("");
  }
}

const compileGoto = (gotoNode, stringBuilder) => {
  stringBuilder.add(`this.followGoto("${gotoNode.label}");\nreturn;\n`);
};

const compileConditional = (conditionalNode, stringBuilder) => {
  const { variable, goto: gotoNode } = conditionalNode;

  stringBuilder.add(`if (this.get("${variable}") != 0) {\n`);
  compileGoto(gotoNode, stringBuilder);
  stringBuilder.add(`}\n`);
};

const compileAssignment = (assignmentNode, stringBuilder) => {
  const { variable, expr } = assignmentNode;
  if (expr.opr) {
    if (expr.opr == "+") stringBuilder.add(`this.addOne("${variable}");\n`);
    else if (expr.opr == "-")
      stringBuilder.add(`this.subtractOne("${variable}");\n`);
  } else {
    stringBuilder.add("// noop \n");
  }
};

const compileInstruction = (instruction, stringBuilder) => {
  if (instruction.goto) {
    compileGoto(instruction.goto, stringBuilder);
    return; // ignore unreachable addition to instructionPointer
  }

  if (instruction.conditional) {
    compileConditional(instruction.conditional, stringBuilder);
  } else if (instruction.assignment) {
    compileAssignment(instruction.assignment, stringBuilder);
  }

  stringBuilder.add("this.instructionPointer++;\n");
};

const compile = (ast) => {
  const stringBuilder = new StringBuilder();
  stringBuilder.add(`
    class Program {
      constructor() {
        this.variables = new Map(); // variable -> natural number val
        this.labelInstructions = new Map(); // labels to instruction indices
        this.instructions = new Map(); // instruction indices to procedures

        this.instructions.set(0, () => this.main());
        this.instructionPointer = 0;
        this.variables.set("Y", 0);

        // -- program-specific state init --
        this.finalInstruction = ${
          ast.instructions.length + 1
        }; // instruction of the implied "exit" label
        // "E" is the exit label
        this.labelInstructions.set("E", this.finalInstruction); 
      }

      get(variable) {
        if (!this.variables.has(variable)) {
          this.variables.set(variable, 0);
        }
        return this.variables.get(variable);
      }

      addOne(variable) {
        const val = this.get(variable);
        this.variables.set(variable, val + 1);
      }

      subtractOne(variable) {
        const val = this.get(variable);
        this.variables.set(variable, val - 1);
      }

      followGoto(label) {
        this.instructionPointer = this.labelInstructions.get(label);
      }

      step() {
        if (!this.isCompleted()) {
          const procedure = this.instructions.get(this.instructionPointer);
          procedure();
 
        }
        return this.instructionPointer;
      }

      isCompleted() {
        return this.instructionPointer == this.finalInstruction;
      }

      getResult() {
        return this.variables.get("Y");
      }

      run(maxIter=500_000) {
        let iter = 0;
        while (!this.isCompleted() && (++iter) < maxIter) this.step();
        if (iter < maxIter) {
          return this.getResult();
        }
        throw new Error("Too many iterations. To resolve, please ask"
           + " Turing how we can find if a program will halt during compilation.");
      }

      main() {
`);

  stringBuilder.add("// -- build label -> instruction map --\n");
  for (let i = 0; i < ast.instructions.length; i++) {
    const line = ast.instructions[i];
    const instructionIdx = i + 1;
    if (line.label) {
      stringBuilder.add(
        `this.instructions.set(${instructionIdx}, () => this.${line.label}());\n`
      );
      stringBuilder.add(
        `this.labelInstructions.set("${line.label}", ${instructionIdx});\n`
      );
    }
  }

  stringBuilder.add("// -- compiled instructions --\n");
  for (let i = 0; i < ast.instructions.length; i++) {
    let instruction = ast.instructions[i];
    const instructionIdx = i + 1;
    if (instruction.label) {
      stringBuilder.add(
        `  this.followGoto("${instruction.label}");\n}\n\n${instruction.label}() {\n`
      );
      stringBuilder.add(`this.instructionPointer = ${instructionIdx};\n`);
      instruction = instruction.instruction;
    }

    compileInstruction(instruction, stringBuilder);
  }

  stringBuilder.add(`  }\n}\n`);
  stringBuilder.add("// -- \n");
  stringBuilder.add("const program = new Program();\n\n");
  stringBuilder.add("// set the initial Snapshot here\n");
  stringBuilder.add('// program.variables.set("X1", 2);\n\n');
  stringBuilder.add("program.run();\n");
  stringBuilder.add("console.log(program.variables);\n");
  stringBuilder.add("program.getResult();\n");

  return js_beautify(stringBuilder.build(), {
    indent_size: 2,
    wrap_line_length: 100,
  });
};