Skip to content
Source
Sign inSign up
TanStack/container
Open History to see the last commit

stage-assignment-parser.mjs

67 lines2.9 KB

1import {readFileSync,writeFileSync} from 'node:fs'
2​
3// Keep right-associative assignment state in the runtime allocator instead of
4// consuming one native parser frame per assignment. Other grammar recursion
5// remains unchanged, including logical assignment and destructuring.
6export function stageAssignmentParser(path){
7 let source=readFileSync(path,'utf8')
8 const start=source.indexOf('static __exception int js_parse_assign_expr2(JSParseState *s, int parse_flags)\n{')
9 const end=source.indexOf('\nstatic __exception int js_parse_assign_expr(JSParseState *s)',start)
10 if(start<0||end<0)throw Error('Missing assignment parser')
11 let body=source.slice(start,end)
12 const replace=(from,to)=>{
13 if(body.split(from).length!==2)throw Error('Unexpected assignment parser patch site')
14 body=body.replace(from,to)
15 }
16 const recursiveStart=body.indexOf(' if (js_parse_assign_expr2(s, parse_flags)) {',body.indexOf(" if (op == '=' ||"))
17 const recursiveEnd=body.indexOf(' } else if (op >= TOK_LAND_ASSIGN',recursiveStart)
18 if(recursiveStart<0||recursiveEnd<0)throw Error('Missing assignment recursion')
19 const finish=body.slice(recursiveStart,recursiveEnd)
20 const emission=finish.slice(finish.indexOf(" if (op == '=')"))
21 body=body.slice(0,recursiveStart)+` AssignmentFrame *frame = js_malloc(s->ctx, sizeof(*frame));
22 if (!frame) {
23 JS_FreeAtom(s->ctx, name);
24 return -1;
25 }
26 frame->previous = assignments;
27 frame->opcode = opcode; frame->op = op; frame->scope = scope;
28 frame->name = name; frame->name0 = name0;
29 frame->label = label; frame->token = op_token_ptr;
30 assignments = frame;
31 goto assignment_next;
32`+body.slice(recursiveEnd)
33 // Route every terminal parser branch through the same ownership cleanup.
34 body=body.replace(/(^[ \t]*)return\s+([^;]+);/gm,(_,indent,value)=>`${indent}do { result = (${value}); goto assignment_complete; } while (0);`)
35 replace(' JSAtom name;\n',` JSAtom name;
36 typedef struct AssignmentFrame {
37 struct AssignmentFrame *previous;
38 int opcode, op, scope, label;
39 JSAtom name, name0;
40 const uint8_t *token;
41 } AssignmentFrame;
42 AssignmentFrame *assignments = NULL;
43 int result;
44 assignment_next:
45 name0 = JS_ATOM_NULL;
46`)
47 const close=body.lastIndexOf('\n}')
48 body=body.slice(0,close)+`
49 assignment_complete:
50 while (assignments) {
51 AssignmentFrame *frame = assignments;
52 int label = frame->label;
53 const uint8_t *op_token_ptr = frame->token;
54 opcode = frame->opcode; op = frame->op; scope = frame->scope;
55 name = frame->name; name0 = frame->name0;
56 assignments = frame->previous;
57 js_free(s->ctx, frame);
58 if (result < 0) {
59 JS_FreeAtom(s->ctx, name);
60 continue;
61 }
62${emission}
63 }
64 return result;
65`+body.slice(close)
66 writeFileSync(path,source.slice(0,start)+body+source.slice(end))