-
Notifications
You must be signed in to change notification settings - Fork 595
/
Copy pathjsoutput.ts
475 lines (414 loc) · 14.4 KB
/
jsoutput.ts
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
namespace pxt.blocks {
export enum NT {
Prefix, // op + map(children)
Postfix, // map(children) + op
Infix, // children.length == 2, child[0] op child[1]
Block, // { } are implicit
NewLine
}
export interface JsNode {
type: NT;
children: JsNode[];
op: string;
id?: string;
glueToBlock?: GlueMode;
canIndentInside?: boolean;
noFinalNewline?: boolean;
}
export enum GlueMode {
None = 0,
WithSpace = 1,
NoSpace = 2
}
const reservedWords = ["break", "case", "catch", "class", "const", "continue", "debugger",
"default", "delete", "do", "else", "enum", "export", "extends", "false", "finally",
"for", "function", "if", "import", "in", "instanceof", "new", "null", "return",
"super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while",
"with"];
let placeholders: Map<Map<any>> = {};
export function backtickLit(s: string) {
return "`" + s.replace(/[\\`${}]/g, f => "\\" + f) + "`"
}
export function stringLit(s: string) {
if (s.length > 20 && /\n/.test(s))
return backtickLit(s)
else return JSON.stringify(s)
}
export function mkNode(tp: NT, pref: string, children: JsNode[]): JsNode {
return {
type: tp,
op: pref,
children: children
}
}
export function mkNewLine() {
return mkNode(NT.NewLine, "", [])
}
export function mkPrefix(pref: string, children: JsNode[]) {
return mkNode(NT.Prefix, pref, children)
}
export function mkPostfix(children: JsNode[], post: string) {
return mkNode(NT.Postfix, post, children)
}
export function mkInfix(child0: JsNode, op: string, child1: JsNode) {
return mkNode(NT.Infix, op, child0 == null ? [child1] : [child0, child1])
}
export function mkText(s: string) {
return mkPrefix(s, [])
}
export function mkBlock(nodes: JsNode[]) {
return mkNode(NT.Block, "", nodes)
}
export function mkGroup(nodes: JsNode[]) {
return mkPrefix("", nodes)
}
export function mkStmt(...nodes: JsNode[]) {
let last = nodes[nodes.length - 1]
if (last && last.type == NT.Block) {
// OK - no newline needed
} else {
nodes.push(mkNewLine())
}
return mkGroup(nodes)
}
export function mkCommaSep(nodes: JsNode[], withNewlines = false) {
const r: JsNode[] = []
for (const n of nodes) {
if (withNewlines) {
if (r.length > 0) r.push(mkText(","));
r.push(mkNewLine());
} else if (r.length > 0) {
r.push(mkText(", "))
}
r.push(n)
}
if (withNewlines) r.push(mkNewLine());
return mkGroup(r)
}
// A series of utility functions for constructing various J* AST nodes.
export namespace Helpers {
export function mkArrayLiteral(args: JsNode[], withNewlines?: boolean) {
return mkGroup([
mkText("["),
mkCommaSep(args, withNewlines),
mkText("]")
])
}
export function mkNumberLiteral(x: number) {
return mkText(x.toString())
}
export function mkBooleanLiteral(x: boolean) {
return mkText(x ? "true" : "false")
}
export function mkStringLiteral(x: string) {
return mkText(stringLit(x))
}
export function mkPropertyAccess(name: string, thisArg: JsNode) {
return mkGroup([
mkInfix(thisArg, ".", mkText(name)),
])
}
export function mkCall(name: string, args: JsNode[], externalInputs = false, method = false) {
if (method)
return mkGroup([
mkInfix(args[0], ".", mkText(name)),
mkText("("),
mkCommaSep(args.slice(1), externalInputs),
mkText(")")
])
else
return mkGroup([
mkText(name),
mkText("("),
mkCommaSep(args, externalInputs),
mkText(")")
])
}
// Call function [name] from the standard device library with arguments
// [args].
export function stdCall(name: string, args: JsNode[], externalInputs: boolean) {
return mkCall(name, args, externalInputs);
}
// Call extension method [name] on the first argument
export function extensionCall(name: string, args: JsNode[], externalInputs: boolean) {
return mkCall(name, args, externalInputs, true);
}
// Call function [name] from the specified [namespace] in the micro:bit
// library.
export function namespaceCall(namespace: string, name: string, args: JsNode[], externalInputs: boolean) {
return mkCall(namespace + "." + name, args, externalInputs);
}
export function mathCall(name: string, args: JsNode[]) {
return namespaceCall("Math", name, args, false)
}
export function mkGlobalRef(name: string) {
return mkText(name)
}
export function mkSimpleCall(p: string, args: JsNode[]): JsNode {
U.assert(args.length == 2);
return mkInfix(args[0], p, args[1])
}
export function mkWhile(condition: JsNode, body: JsNode[]): JsNode {
return mkGroup([
mkText("while ("),
condition,
mkText(")"),
mkBlock(body)
])
}
export function mkComment(text: string) {
return mkText("// " + text)
}
export function mkMultiComment(text: string) {
let group = [
mkText("/**"),
mkNewLine()
];
text.split("\n").forEach((c, i, arr) => {
if (c) {
group.push(mkText(" * " + c));
group.push(mkNewLine());
// Add an extra line so we can convert it back to new lines
if (i < arr.length - 1) {
group.push(mkText(" * "));
group.push(mkNewLine());
}
}
});
return mkGroup(group.concat([
mkText(" */"),
mkNewLine()
]));
}
export function mkAssign(x: JsNode, e: JsNode): JsNode {
return mkSimpleCall("=", [x, e])
}
export function mkParenthesizedExpression(expression: JsNode): JsNode {
return isParenthesized(flattenNode([expression]).output) ? expression : mkGroup([mkText("("), expression, mkText(")")]);
}
}
export import H = Helpers;
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
const infixPriTable: Map<number> = {
// 0 = comma/sequence
// 1 = spread (...)
// 2 = yield, yield*
// 3 = assignment
"=": 3,
"+=": 3,
"-=": 3,
"?": 4,
":": 4,
"||": 5,
"&&": 6,
"|": 7,
"^": 8,
"&": 9,
// 10 = equality
"==": 10,
"!=": 10,
"===": 10,
"!==": 10,
// 11 = comparison (excludes in, instanceof)
"<": 11,
">": 11,
"<=": 11,
">=": 11,
// 12 = bitwise shift
">>": 12,
">>>": 12,
"<<": 12,
"+": 13,
"-": 13,
"*": 14,
"/": 14,
"%": 14,
"**": 15,
"!": 16,
"~": 16,
"P-": 16,
"P+": 16,
"++": 16,
"--": 16,
".": 18,
}
export interface BlockSourceInterval {
id: string;
startLine: number; // 0-indexed of the line itself
startPos: number; // 0-indexed from start of file including newlines
endLine: number;
endPos: number;
}
export function flattenNode(app: JsNode[]) {
let sourceMap: BlockSourceInterval[] = [];
let sourceMapById: pxt.Map<BlockSourceInterval> = {};
let output = ""
let indent = ""
let variables: Map<string>[] = [{}];
let currentLine = 0;
function append(s: string) {
// At runtime sometimes `s` is a number.
if (typeof(s) === 'string') {
currentLine += (s.match(/\n/g) || []).length;
}
output += s;
}
function flatten(e0: JsNode) {
function rec(e: JsNode, outPrio: number) {
if (e.type != NT.Infix) {
for (let c of e.children)
rec(c, -1)
return
}
let r: JsNode[] = []
function pushOp(c: string) {
if (c[0] == "P") c = c.slice(1)
r.push(mkText(c))
}
let infixPri = U.lookup(infixPriTable, e.op)
if (infixPri == null) U.oops("bad infix op: " + e.op)
if (infixPri < outPrio) pushOp("(");
if (e.children.length == 1) {
pushOp(e.op)
rec(e.children[0], infixPri)
r.push(e.children[0])
} else {
let bindLeft = infixPri != 3 && e.op != "**"
let letType: string = undefined;
rec(e.children[0], bindLeft ? infixPri : infixPri + 0.1)
r.push(e.children[0])
if (letType && letType != "number") {
pushOp(": ")
pushOp(letType)
}
if (e.op == ".")
pushOp(".")
else
pushOp(" " + e.op + " ")
rec(e.children[1], !bindLeft ? infixPri : infixPri + 0.1)
r.push(e.children[1])
}
if (infixPri < outPrio) pushOp(")");
e.type = NT.Prefix
e.op = ""
e.children = r
}
rec(e0, -1)
}
let root = mkGroup(app)
flatten(root)
emit(root)
// never return empty string - TS compiler service thinks it's an error
if (!output)
append("\n");
return { output, sourceMap }
function emit(n: JsNode) {
if (n.glueToBlock) {
removeLastIndent()
if (n.glueToBlock == GlueMode.WithSpace) {
append(" ");
}
}
let startLine = currentLine;
let startPos = output.length;
switch (n.type) {
case NT.Infix:
U.oops("no infix should be left")
break
case NT.NewLine:
append("\n" + indent)
break
case NT.Block:
block(n)
break
case NT.Prefix:
if (n.canIndentInside)
append(n.op.replace(/\n/g, "\n" + indent + " "))
else
append(n.op)
n.children.forEach(emit)
break
case NT.Postfix:
n.children.forEach(emit)
if (n.canIndentInside)
append(n.op.replace(/\n/g, "\n" + indent + " "))
else
append(n.op)
break
default:
break
}
let endLine = currentLine;
// end position is non-inclusive
let endPos = Math.max(output.length, 1);
if (n.id) {
if (sourceMapById[n.id]) {
const node = sourceMapById[n.id];
node.startLine = Math.min(node.startLine, startLine);
node.endLine = Math.max(node.endLine, endLine);
node.startPos = Math.min(node.startPos, startPos);
node.endPos = Math.max(node.endPos, endPos);
}
else {
const interval: BlockSourceInterval = {
id: n.id,
startLine: startLine, startPos, endLine: endLine, endPos
}
sourceMapById[n.id] = interval;
sourceMap.push(interval)
}
}
}
function write(s: string) {
append(s.replace(/\n/g, "\n" + indent))
}
function removeLastIndent() {
// Note: performance of this regular expression degrades with program size, and could therefore become a perf issue.
output = output.replace(/\n *$/, function () {
currentLine--;
return "";
});
}
function block(n: JsNode) {
let finalNl = n.noFinalNewline ? "" : "\n";
if (n.children.length == 0) {
write(" {\n\t\n}" + finalNl)
return
}
let vars = U.clone<Map<string>>(variables[variables.length - 1] || {});
variables.push(vars);
indent += " "
if (output[output.length - 1] != " ")
write(" ")
write("{\n")
for (let nn of n.children)
emit(nn)
indent = indent.slice(4)
removeLastIndent()
write("\n}" + finalNl)
variables.pop();
}
}
export function isReservedWord(str: string) {
return reservedWords.indexOf(str) !== -1;
}
export function isParenthesized(fnOutput: string): boolean {
if (fnOutput[0] !== "(" || fnOutput[fnOutput.length - 1] !== ")") {
return false;
}
let unclosedParentheses = 1;
for (let i = 1; i < fnOutput.length; i++) {
const c = fnOutput[i];
if (c === "(") {
unclosedParentheses++;
}
else if (c === ")") {
unclosedParentheses--;
if (unclosedParentheses === 0) {
return i === fnOutput.length - 1;
}
}
}
return false;
}
}