Newer
Older
Jenny Zhang
committed
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
// src/utils/ast.js
// Function to create a new AST node
function Node(type, value, left, right) {
return {
type: type,
value: value,
left: left,
right: right
};
}
const precedence = {
'imply': 1,
'or': 2,
'and': 3,
'not': 4,
'symbol': 5,
'true': 5,
'false': 5
};
function astToString(node, parentPrecedence = 0) {
if (!node) return "";
let currentPrecedence = precedence[node.type];
let left = astToString(node.left, currentPrecedence);
let right = astToString(node.right, currentPrecedence);
let result;
switch (node.type) {
case 'not':
result = `!${left}`;
break;
case 'and':
result = `${left}&${right}`;
break;
case 'or':
result = `${left}||${right}`;
break;
case 'imply':
result = `${left}->${right}`;
break;
case 'symbol':
result = node.value;
break;
case 'true':
result = 'true';
break;
case 'false':
result = 'false';
break;
default:
throw new Error(`Unknown node type: ${node.type}`);
}
if (currentPrecedence < parentPrecedence) {
result = `(${result})`;
}
return result;
}
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
function astToLaTeX(node, parentPrecedence = 0) {
if (!node) return "";
let currentPrecedence = precedence[node.type];
let left = astToLaTeX(node.left, currentPrecedence);
let right = astToLaTeX(node.right, currentPrecedence);
let result;
switch (node.type) {
case 'not':
result = `\\neg ${left}`;
break;
case 'and':
result = `${left} \\land ${right}`;
break;
case 'or':
result = `${left} \\lor ${right}`;
break;
case 'imply':
result = `${left} \\rightarrow ${right}`;
break;
case 'symbol':
result = `\\mathit{${node.value}}`;
break;
case 'true':
result = '\\top';
break;
case 'false':
result = '\\bot';
break;
default:
throw new Error(`Unknown node type: ${node.type}`);
}
if (currentPrecedence < parentPrecedence) {
result = `(${result})`;
}
return result;
}
Jenny Zhang
committed
var ast = {};
ast.Not = Node.bind(null, 'not');
ast.And = Node.bind(null, 'and');
ast.Or = Node.bind(null, 'or');
ast.Imply = Node.bind(null, 'imply');
ast.Symbol = Node.bind(null, 'symbol');
ast.True = Node.bind(null, 'true');
ast.False = Node.bind(null, 'false');
ast.astToString = astToString;
ast.astToLaTeX = astToLaTeX;
Jenny Zhang
committed
module.exports = ast; // Export the AST module