-
Notifications
You must be signed in to change notification settings - Fork 16
/
mirror.js
288 lines (251 loc) · 8.14 KB
/
mirror.js
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// This file includes the parser and the compiler/LLM classes.
// Compiler/LLM wrapper.
class MirrorCompiler {
async callOpenAI(apiKey, prompt) {
const response = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiKey}`
},
body: JSON.stringify({
model: "gpt-4o",
messages: [{ role: "user", content: prompt }]
})
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error?.message || "Unknown error");
}
return data.choices[0].message.content;
}
}
// Parser.
class MirrorParser {
constructor(input) {
this.tokens = input.match(/[\w]+|->|[.,:()\[\]{}]|"(?:\\"|[^"])*"|\d+|\S/g) || [];
this.current = 0;
}
parse() {
const program = [];
while (!this.isAtEnd()) {
const stmt = this.parseStatement();
if (stmt) {
program.push(stmt);
}
}
return program;
}
parseStatement() {
if (this.match('signature')) {
return this.parseSignature();
} else if (this.match('example')) {
return this.parseExample();
} else if (this.peekIdentifier()) {
return this.parseExpression();
} else {
throw new Error(`Unexpected token: ${this.peek()}`);
}
}
parseSignature() {
const name = this.consumeIdentifier();
this.consume('(');
const parameters = this.parseParameters();
this.consume(')');
this.consume('->');
const returnType = this.parseType();
return { type: 'signature', name, parameters, returnType };
}
parseParameters() {
const parameters = [];
if (!this.check(')')) { // Handle empty parameter lists
do {
const name = this.consumeIdentifier();
this.consume(':');
const paramType = this.parseType();
parameters.push({ name, type: paramType });
} while (this.match(','));
}
return parameters;
}
parseType() {
if (this.match('string', 'number', 'bool')) {
return this.previous();
} else if (this.match('list')) {
this.consume('[');
const innerType = this.parseType();
this.consume(']');
return { type: 'list', innerType };
} else if (this.match('dict')) {
this.consume('[');
const keyType = this.parseType();
this.consume(',');
const valueType = this.parseType();
this.consume(']');
return { type: 'dict', keyType, valueType };
} else {
throw new Error(`Unexpected type: ${this.peek()}`);
}
}
parseExample() {
const name = this.consumeIdentifier();
this.consume('(');
const literals = this.parseLiterals();
this.consume(')');
this.consume('=');
const literal = this.parseLiteral();
return { type: 'example', name, literals, result: literal };
}
parseLiterals() {
const literals = [];
if (!this.check(')')) { // Handle empty literals
do {
literals.push(this.parseLiteral());
} while (this.match(','));
}
return literals;
}
parseLiteral() {
if (this.match('true', 'false')) {
return this.previous();
} else if (this.matchNumber()) {
return parseFloat(this.previous());
} else if (this.matchString()) {
return this.previous().slice(1, -1); // Remove surrounding quotes
} else if (this.match('[')) {
const literals = [];
if (!this.check(']')) { // Handle empty lists
do {
literals.push(this.parseLiteral());
} while (this.match(','));
}
this.consume(']');
return { type: 'list', value: literals };
} else if (this.match('{')) {
const dict = {};
if (!this.check('}')) { // Handle empty dictionaries
do {
const key = this.parseLiteral();
this.consume(':');
const value = this.parseLiteral();
if (typeof key !== 'string') {
throw new Error(`Dictionary keys must be strings. Got: ${JSON.stringify(key)}`);
}
dict[key] = value;
} while (this.match(','));
}
this.consume('}');
return { type: 'dict', value: dict };
} else {
throw new Error(`Unexpected literal: ${this.peek()}`);
}
}
parseExpression() {
const name = this.consumeIdentifier();
this.consume('(');
const mix = this.parseMix();
this.consume(')');
return { type: 'expression', name, mix };
}
parseMix() {
const mix = [];
if (!this.check(')')) { // Handle empty expressions
do {
if (this.peekIdentifier()) {
mix.push(this.parseExpression());
} else {
mix.push(this.parseLiteral());
}
} while (this.match(','));
}
return mix;
}
// Helper methods
match(...types) {
for (const type of types) {
if (this.check(type)) {
this.advance();
return true;
}
}
return false;
}
matchNumber() {
const token = this.peek();
if (/^\d+(\.\d+)?$/.test(token)) {
this.advance();
return true;
}
return false;
}
matchString() {
const token = this.peek();
if (/^".*"$/.test(token)) {
this.advance();
return true;
}
return false;
}
consume(type) {
if (this.check(type)) {
return this.advance();
}
throw new Error(`Expected '${type}', but got '${this.peek()}'`);
}
consumeIdentifier() {
if (this.peekIdentifier()) {
return this.advance();
}
throw new Error(`Expected identifier, but got '${this.peek()}'`);
}
check(type) {
if (this.isAtEnd()) return false;
return this.peek() === type;
}
peek() {
return this.tokens[this.current];
}
peekIdentifier() {
const token = this.peek();
return /^[a-zA-Z_]\w*$/.test(token);
}
previous() {
return this.tokens[this.current - 1];
}
advance() {
if (!this.isAtEnd()) this.current++;
return this.previous();
}
isAtEnd() {
return this.current >= this.tokens.length;
}
}
// TODO: The public functions need to be refactored. There should be a single "compile" function that takes the raw code. Move that behavior from the playground to here.
function extractExpressions(ast) {
return ast.filter(node => node.type === 'expression');
}
// TODO: We should do type checking on the expressions after parsing (before the LLM).
function groupSignaturesWithExamples(ast) {
const signatures = ast.filter(node => node.type === 'signature');
const examples = ast.filter(node => node.type === 'example');
return signatures.map(signature => {
const matchingExamples = examples.filter(example => example.name === signature.name);
return {
...signature,
examples: matchingExamples
};
});
}
// Example usage:
// const input = `
// signature myFunc(a: string, b: number) -> bool
// example test1("hello", 123) = true
// myFunc("world", 456)
// `;
// const parser = new Mirror(input);
// const ast = parser.parse();
// console.log(JSON.stringify(ast, null, 2));
// const expressions = extractExpressions(ast);
// console.log(expressions);
// const signaturesWithExamples = groupSignaturesWithExamples(ast);
// console.log(signaturesWithExamples);