Merge pull request #3 from Simponic/godel

L-Program and Godel Numbers
This commit is contained in:
Elizabeth Hunt 2023-11-17 12:13:30 -07:00 committed by GitHub
commit eaca9073eb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 12156 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
**/.DS_STORE

View File

@ -0,0 +1,488 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace !important;
height: 300px;
color: black;
direction: ltr;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler,
.CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {
}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker {
color: black;
}
.CodeMirror-guttermarker-subtle {
color: #999;
}
/* CURSOR */
.CodeMirror-cursor {
border-left: 1px solid black;
border-right: none;
width: 0;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.cm-fat-cursor .CodeMirror-cursor {
width: auto;
border: 0 !important;
background: #7e7;
}
.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-fat-cursor .CodeMirror-line::selection,
.cm-fat-cursor .CodeMirror-line > span::selection,
.cm-fat-cursor .CodeMirror-line > span > span::selection {
background: transparent;
}
.cm-fat-cursor .CodeMirror-line::-moz-selection,
.cm-fat-cursor .CodeMirror-line > span::-moz-selection,
.cm-fat-cursor .CodeMirror-line > span > span::-moz-selection {
background: transparent;
}
.cm-fat-cursor {
caret-color: transparent;
}
@-moz-keyframes blink {
0% {
}
50% {
background-color: transparent;
}
100% {
}
}
@-webkit-keyframes blink {
0% {
}
50% {
background-color: transparent;
}
100% {
}
}
@keyframes blink {
0% {
}
50% {
background-color: transparent;
}
100% {
}
}
/* Can style cursor different in overwrite (non-insert) mode */
.CodeMirror-overwrite .CodeMirror-cursor {
}
.cm-tab {
display: inline-block;
text-decoration: inherit;
}
.CodeMirror-rulers {
position: absolute;
left: 0;
right: 0;
top: -50px;
bottom: 0;
overflow: hidden;
}
.CodeMirror-ruler {
border-left: 1px solid #ccc;
top: 0;
bottom: 0;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {
color: blue;
}
.cm-s-default .cm-quote {
color: #090;
}
.cm-negative {
color: #d44;
}
.cm-positive {
color: #292;
}
.cm-header,
.cm-strong {
font-weight: bold;
}
.cm-em {
font-style: italic;
}
.cm-link {
text-decoration: underline;
}
.cm-strikethrough {
text-decoration: line-through;
}
.cm-s-default .cm-keyword {
color: #708;
}
.cm-s-default .cm-atom {
color: #219;
}
.cm-s-default .cm-number {
color: #164;
}
.cm-s-default .cm-def {
color: #00f;
}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {
}
.cm-s-default .cm-variable-2 {
color: #05a;
}
.cm-s-default .cm-variable-3,
.cm-s-default .cm-type {
color: #085;
}
.cm-s-default .cm-comment {
color: #a50;
}
.cm-s-default .cm-string {
color: #a11;
}
.cm-s-default .cm-string-2 {
color: #f50;
}
.cm-s-default .cm-meta {
color: #555;
}
.cm-s-default .cm-qualifier {
color: #555;
}
.cm-s-default .cm-builtin {
color: #30a;
}
.cm-s-default .cm-bracket {
color: #997;
}
.cm-s-default .cm-tag {
color: #170;
}
.cm-s-default .cm-attribute {
color: #00c;
}
.cm-s-default .cm-hr {
color: #999;
}
.cm-s-default .cm-link {
color: #00c;
}
.cm-s-default .cm-error {
color: #f00;
}
.cm-invalidchar {
color: #f00;
}
.CodeMirror-composing {
border-bottom: 2px solid;
}
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {
color: #0b0;
}
div.CodeMirror span.CodeMirror-nonmatchingbracket {
color: #a22;
}
.CodeMirror-matchingtag {
background: rgba(255, 150, 0, 0.3);
}
.CodeMirror-activeline-background {
background: #e8f2ff;
}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 50px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -50px;
margin-right: -50px;
padding-bottom: 50px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
z-index: 0;
}
.CodeMirror-sizer {
position: relative;
border-right: 50px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actual scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar,
.CodeMirror-hscrollbar,
.CodeMirror-scrollbar-filler,
.CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
outline: none;
}
.CodeMirror-vscrollbar {
right: 0;
top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0;
left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0;
bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0;
bottom: 0;
}
.CodeMirror-gutters {
position: absolute;
left: 0;
top: 0;
min-height: 100%;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
vertical-align: top;
margin-bottom: -50px;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
background: none !important;
border: none !important;
}
.CodeMirror-gutter-background {
position: absolute;
top: 0;
bottom: 0;
z-index: 4;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper ::selection {
background-color: transparent;
}
.CodeMirror-gutter-wrapper ::-moz-selection {
background-color: transparent;
}
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre.CodeMirror-line,
.CodeMirror pre.CodeMirror-line-like {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0;
-webkit-border-radius: 0;
border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
-webkit-font-variant-ligatures: contextual;
font-variant-ligatures: contextual;
}
.CodeMirror-wrap pre.CodeMirror-line,
.CodeMirror-wrap pre.CodeMirror-line-like {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
padding: 0.1px; /* Force widget margins to stay inside of the container */
}
.CodeMirror-widget {
}
.CodeMirror-rtl pre {
direction: rtl;
}
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-cursor {
position: absolute;
pointer-events: none;
}
.CodeMirror-measure pre {
position: static;
}
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
div.CodeMirror-dragcursors {
visibility: visible;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected {
background: #d9d9d9;
}
.CodeMirror-focused .CodeMirror-selected {
background: #d7d4f0;
}
.CodeMirror-crosshair {
cursor: crosshair;
}
.CodeMirror-line::selection,
.CodeMirror-line > span::selection,
.CodeMirror-line > span > span::selection {
background: #d7d4f0;
}
.CodeMirror-line::-moz-selection,
.CodeMirror-line > span::-moz-selection,
.CodeMirror-line > span > span::-moz-selection {
background: #d7d4f0;
}
.cm-searching {
background-color: #ffa;
background-color: rgba(255, 255, 0, 0.4);
}
/* Used to force a border model for a node */
.cm-force-border {
padding-right: 0.1px;
}
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after {
content: "";
}
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext {
background: none;
}

File diff suppressed because it is too large Load Diff

82
godel/css/styles.css Normal file
View File

@ -0,0 +1,82 @@
* {
margin: 0;
}
button {
background: #bbbbbb;
border: 1px solid white;
border-radius: 0.2rem;
padding: 0.3rem;
display: inline-block;
cursor: pointer;
}
button:hover {
background: #cccccc;
}
body {
font-family: "Trebuchet MS", sans-serif;
background-color: #aaaaaa;
}
.container {
display: flex;
width: 90%;
margin-left: auto;
margin-right: auto;
flex-direction: column;
gap: 1rem;
padding: 2rem;
}
.textarea-container {
display: flex;
flex-direction: column;
gap: 1rem;
box-shadow: 5px 5px 5px #666666;
border: 2px solid white;
border-radius: 0.25rem;
padding: 1rem;
flex: 1;
}
.source-container {
display: flex;
flex-direction: row;
gap: 1rem;
height: 100%;
}
textarea {
border-radius: 0.25rem;
}
.CodeMirror {
height: 50vh;
}
.error {
color: red;
}
.success {
color: green;
}
hr {
border-top: 2px solid black;
border-bottom: none;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
}
@media only screen and (max-width: 1000px) {
.source-container {
flex-direction: column;
}
}

77
godel/grammar.peg Normal file
View File

@ -0,0 +1,77 @@
Program = lines: (ProgramInstruction / (_/[\n]))* {
return { instructions: lines.filter((line) => typeof line !== "string" || line.trim() != "") };
}
ProgramInstruction = _? instruction: (LabeledInstruction / Instruction) _? [\n]? {
let x = 0;
let y = 0;
if (instruction.label) {
x = instruction.label.godel;
y = instruction.instruction.godel;
} else {
y = instruction.godel;
}
return { instruction, godel: ((2 ** x) * ((2 * y) + 1) - 1) };
}
LabeledInstruction = label:Label _ instruction:Instruction {
return { label, instruction };
}
Label = "[" _? label:LABEL_V _? "]" {
return label;
}
Instruction = conditional: Conditional { return { conditional, godel: conditional.godel }; }
/ assignment: Assignment { return { assignment, godel: assignment.godel }; }
/ goto: Goto { return { goto, godel: goto.godel }; }
Goto = GOTO _ label: LABEL_V {
return { label, godel: label.godel + 2 };
}
Conditional = "IF" _ variable: VAR _? "!=" _? "0" _ goto: Goto {
const y = variable.godel - 1;
const x = goto.godel;
return { variable, goto, godel: ((2 ** x) * ((2 * y) + 1) - 1) };
}
Assignment = variable: VAR _ "<-" _ expr: Expression {
if (expr.left.symbol != variable.symbol) {
error("left hand variable must match right hand");
}
const x = expr.instructionNumber;
const y = variable.godel - 1;
return { variable, expr, godel: ((2 ** x) * ((2 * y) + 1) - 1) };
}
Expression = left: VAR _ opr: OPERATION _ "1" {
const instructionNumber = { "+" : 1, "-" : 2 }[opr];
return { left, opr, instructionNumber };
} / left: VAR {
return { left, instructionNumber: 0 };
}
VAR = symbol:"Y" { return { symbol, godel: 1 }; } / symbol:("X" / "Z") ind:Integer+ {
const index = parseInt(ind);
const order = ["X", "Z"];
const godel = index * order.length + order.indexOf(symbol);
return { symbol: symbol + ind, godel };
}
GOTO = "GOTO"
OPERATION = "+" / "-"
LABEL_V = symbol:END_LABEL { return symbol } / symbol:[A-E] ind:Integer+ {
const index = parseInt(ind);
const godel = (symbol.charCodeAt(0) - "A".charCodeAt(0) + 1) + 5*(index-1);
return { symbol: symbol + ind, godel };
}
END_LABEL = "E1"
Integer "integer"
= [0-9]+ { return parseInt(text(), 10); }
_ "whitespace" = [ \t]+ { }

96
godel/index.html Normal file
View File

@ -0,0 +1,96 @@
<!DOCTYPE html>
<html>
<head>
<title>Liz's L-Program Compiler</title>
<link rel="stylesheet" type="text/css" href=
"codemirror/codemirror.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="container">
<h1>Liz's L-Program Compiler</h1>
<p><i>Developed for Kulyukin's CS5000</i></p>
<hr>
<div class="source-container">
<div class="textarea-container">
<h3>L Source</h3>
<textarea id=
"instructions">// 0. primitive instructions only
// 1. labels match the regex [A-E](:digit:)+.
// 2. variables are initialized to zero and match
// (Y | (X|Z)(:digit:)+).
// 3. instructions must be delimited by a newline.
// 4. anything following the comment token "//" up to a
// newline are ignored.
// 5. by default, a computation that takes more than 500_000
// "procedures", it will be halted.
// 6. the implicit exit label "E1" exists; thus to exit
// prematurely, "GOTO E1".
// 7. input your initial snapshot in the "variables" map
// on the Program in the compiled JS output
// 8. for a more detailed view on the grammar, it's at
// /godel/grammar.peg
// THIS PROGRAM COMPUTES X1 + X2
// Y &lt;- X1
[ A1 ] IF X1 != 0 GOTO A2
GOTO B1
[ A2 ] X1 &lt;- X1 - 1
Y &lt;- Y + 1
GOTO A1
// Z1 &lt;- X2
[ B1 ] IF X2 != 0 GOTO B2
GOTO C1
[ B2 ] X2 &lt;- X2 - 1
Z1 &lt;- Z1 + 1
GOTO B1
// Y &lt;- Y + Z1
[ C1 ] IF Z1 != 0 GOTO C2
GOTO E1
[ C2 ] Z1 &lt;- Z1 - 1
Y &lt;- Y + 1
GOTO C1</textarea>
<div>
<button id="compile">Compile</button> <button id=
"copy">Copy</button>
</div>
<div>
<span style="margin-left: 0.5rem" id=
"compile_status"></span>
</div>
</div>
<div class="textarea-container">
<h3>Compiled JS</h3>
<textarea id="compiled"></textarea>
<div>
<button id="eval">Eval</button>
</div>
<div>
<span style="margin-left: 0.5rem" id=
"eval_status"></span>
</div>
</div>
</div>
<div class="textarea-container">
<h3>Godel</h3>
<p>Sequence:</p>
<pre id="godel_sequence"></pre>
<div>
<p>Number: <button id="godel_number_comp" style=
"display: none">Compute (this might take a
while)</button></p>
</div>
<pre id="godel_number"></pre>
</div>
</div>
<script src="codemirror/codemirror.js"></script>
<script src="js-beautify/js-beautify.js"></script>
<script src="js/observable.js"></script>
<script src="js/parser.js"></script>
<script src="js/compiler.js"></script>
<script src="js/main.js"></script>
</body>
</html>

File diff suppressed because one or more lines are too long

182
godel/js/compiler.js Normal file
View File

@ -0,0 +1,182 @@
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.symbol}");\nreturn;\n`);
};
const compileConditional = (conditionalNode, stringBuilder) => {
const {
variable: { symbol: variable },
goto: gotoNode,
} = conditionalNode;
stringBuilder.add(`if (this.get("${variable}") != 0) {\n`);
compileGoto(gotoNode, stringBuilder);
stringBuilder.add(`}\n`);
};
const compileAssignment = (assignmentNode, stringBuilder) => {
const {
variable: { symbol: 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 godelSequence = [];
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
// "E1" is the exit label
this.labelInstructions.set("E1", 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 instruction = ast.instructions[i];
godelSequence.push(instruction.godel);
const line = instruction.instruction;
const instructionIdx = i + 1;
if (line.label) {
const symbol = line.label.symbol;
stringBuilder.add(
`this.instructions.set(${instructionIdx}, () => this.${symbol}());\n`
);
stringBuilder.add(
`this.labelInstructions.set("${symbol}", ${instructionIdx});\n`
);
}
}
stringBuilder.add("// -- compiled instructions --\n");
for (let i = 0; i < ast.instructions.length; i++) {
let instruction = ast.instructions[i].instruction;
const instructionIdx = i + 1;
if (instruction.label) {
const symbol = instruction.label.symbol;
stringBuilder.add(
` this.followGoto("${symbol}");\n}\n\n${symbol}() {\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: js_beautify(stringBuilder.build(), {
indent_size: 2,
wrap_line_length: 100,
}),
godelSequence,
};
};

27
godel/js/godelWorker.js Normal file
View File

@ -0,0 +1,27 @@
const isPrime = (n) =>
!Array(Math.ceil(Math.sqrt(n)))
.fill(0)
.map((_, i) => i + 2) // first prime is 2
.some((i) => n !== i && n % i === 0);
const primesCache = [2];
const p = (i) => {
if (primesCache.length <= i) {
let x = primesCache.at(-1);
while (primesCache.length <= i) {
if (isPrime(++x)) primesCache.push(x);
}
}
return primesCache.at(i - 1);
};
const computeGodelNumber = (godelSequence) =>
godelSequence.reduce((acc, num, i) => {
const prime = p(i + 1);
return BigInt(acc) * BigInt(prime) ** BigInt(num);
}, 1) - BigInt(1);
self.addEventListener("message", (e) => {
const godelNumber = computeGodelNumber(e.data);
postMessage(godelNumber);
});

175
godel/js/main.js Normal file
View File

@ -0,0 +1,175 @@
const MESSAGES = {
COMPILE: "COMPILE",
COMPILE_RESULT: "COMPILE_RESULT",
EVAL: "EVAL",
EVAL_STATUS: "EVAL_RESULT",
};
// -- the "real" code --
const state = new Observable();
const prepareSource = (text) => text.replaceAll(/\/\/.*/g, "").trim();
const main = () => {
let program;
state.subscribe((msg) => {
if (msg.type == MESSAGES.COMPILE) {
const { value } = msg;
const source = prepareSource(value);
try {
const ast = parser.parse(source);
const { js, godelSequence } = compile(ast);
state.notify({
type: MESSAGES.COMPILE_RESULT,
success: true,
js,
godelSequence,
});
} catch (e) {
console.error(e);
state.notify({
type: MESSAGES.COMPILE_RESULT,
error: e.toString(),
});
}
}
if (msg.type == MESSAGES.EVAL) {
const source = compiledEditorEl.getValue();
try {
const result = eval(source);
state.notify({
type: MESSAGES.EVAL_RESULT,
success: true,
value: result,
});
} catch (e) {
state.notify({
type: MESSAGES.EVAL_RESULT,
error: e.toString(),
});
}
}
});
};
main();
// -- a bit of some hacky ui code --
const codeMirrorConfig = {
lineNumbers: true,
};
const instructionsEl = document.getElementById("instructions");
const instructionsEditorEl = CodeMirror.fromTextArea(
instructionsEl,
codeMirrorConfig
);
const compileButton = document.getElementById("compile");
const evalButton = document.getElementById("eval");
const evalStatusEl = document.getElementById("eval_status");
const compileStatusEl = document.getElementById("compile_status");
const compiledEl = document.getElementById("compiled");
const compiledEditorEl = CodeMirror.fromTextArea(compiledEl, codeMirrorConfig);
const godelSequenceEl = document.getElementById("godel_sequence");
const godelNumberEl = document.getElementById("godel_number");
const godelNumberComputeBtn = document.getElementById("godel_number_comp");
const copyStateButton = document.getElementById("copy");
// hackily copy the program state and put it in the clipboard
copyStateButton.addEventListener("click", () => {
const instructions = btoa(instructionsEditorEl.getValue());
navigator.clipboard
.writeText(
window.location.href.split("?")[0] + `?instructions=${instructions}`
)
.then(() => alert("copied to clipboard"));
});
state.subscribe((msg) => {
if (msg.type == MESSAGES.COMPILE_RESULT) {
evalStatusEl.classList.remove("error");
evalStatusEl.classList.remove("success");
evalStatusEl.innerHTML = "";
if (msg.success) {
const { js, godelSequence } = msg;
compiledEditorEl.setValue(js);
godelSequenceEl.innerHTML = `[${godelSequence.join(", ")}]`;
godelNumberComputeBtn.style.display = "inline";
compileStatusEl.classList.add("success");
compileStatusEl.classList.remove("error");
compileStatusEl.innerHTML = `Successful compile at ${new Date().toLocaleString()}!`;
} else if (msg.error) {
compiledEditorEl.setValue("");
godelSequenceEl.innerHTML = "";
godelNumberEl.innerHTML = "";
godelNumberComputeBtn.style.display = "none";
compileStatusEl.classList.remove("success");
compileStatusEl.classList.add("error");
compileStatusEl.innerHTML = msg.error;
}
}
});
state.subscribe((msg) => {
if (msg.type == MESSAGES.COMPILE_RESULT) {
if (msg.success) {
const { godelSequence } = msg;
godelNumberComputeBtn.onclick = () => {
godelNumberEl.innerHTML = "working...";
const worker = new Worker("js/godelWorker.js");
worker.addEventListener("message", (e) => {
const godelNumber = e.data;
godelNumberEl.innerHTML = godelNumber.toString();
});
worker.postMessage(godelSequence);
};
} else if (msg.error) {
godelNumberComputeBtn.onclick = () => {};
}
}
});
state.subscribe((msg) => {
if (msg.type == MESSAGES.EVAL_RESULT) {
if (msg.success) {
evalStatusEl.classList.add("success");
evalStatusEl.classList.remove("error");
evalStatusEl.innerHTML = `Result: ${msg.value}`;
} else if (msg.error) {
evalStatusEl.classList.remove("success");
evalStatusEl.classList.add("error");
evalStatusEl.innerHTML = msg.error;
}
}
});
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("instructions")) {
instructionsEditorEl.setValue(atob(urlParams.get("instructions")));
}
compileButton.addEventListener("click", () => {
state.notify({
type: MESSAGES.COMPILE,
value: instructionsEditorEl.getValue(),
});
});
evalButton.addEventListener("click", () => {
state.notify({
type: MESSAGES.EVAL,
});
});

14
godel/js/observable.js Normal file
View File

@ -0,0 +1,14 @@
class Observable {
constructor() {
this.observers = [];
}
subscribe(f) {
this.observers.push(f);
}
unsubscribe(f) {
this.observers = this.observers.filter((subscriber) => subscriber !== f);
}
notify(data) {
this.observers.forEach((observer) => observer(data));
}
}

1056
godel/js/parser.js Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,72 @@
class TuringMachine {
constructor(tape = [], rules = [], initialState = "q0", acceptState = "f") {
this.tape = tape;
this.rules = this.parseRules(rules);
this.state = initialState;
this.head = 0;
this.acceptState = acceptState;
this.iteration = 0;
}
getStateStatus() {
return `State: ${this.state}, Step: ${this.iteration}`;
}
getHead() {
return this.head;
}
getState() {
return this.state;
}
getTapeAtCell(idx) {
return this.tape[idx];
}
setTapeAtCell(idx, val) {
this.tape[idx] = val;
}
isAccepting() {
return this.state == this.acceptState;
}
parseRules(rules) {
const parsedRules = {};
for (const [currentState, readSymbol, action, newState] of rules) {
const key = `${currentState},${readSymbol}`;
const value = `${newState},${action}`;
parsedRules[key] = value;
}
return parsedRules;
}
step() {
const currentSymbol = this.tape[this.head];
const key = `${this.state},${currentSymbol}`;
if (!(key in this.rules)) {
return false;
}
const rule = this.rules[key];
const [newState, action] = rule.split(",");
this.state = newState;
this.iteration++;
if (action === "R") {
this.head += 1;
} else if (action === "L") {
this.head -= 1;
} else {
this.tape[this.head] = action;
}
if (this.isAccepting()) {
return false;
}
return this.head >= 0 && this.head < this.tape.length;
}
}

View File

@ -44,6 +44,17 @@
</div>
</a>
<a class="project" href="/godel/">
<div class="project-logo-container">
<i class="fa-solid fa-microchip"></i>
</div>
<div class="project-body">
<h1>Godel Explorer</h1>
<p>Compile L-Programs into JavaScript and Godel numbers.</p>
</div>
</a>
<a class="project" href="/turing-machine/">
<div class="project-logo-container">
<i class="fa-solid fa-tape"></i>