chore: simpler const parsing (#10347)

* chore: simpler const parsing

* fix

* fix

---------

Co-authored-by: Rich Harris <rich.harris@vercel.com>
pull/10407/head
Rich Harris 9 months ago committed by GitHub
parent a84d02ff08
commit 08b4d359fa
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -550,42 +550,17 @@ function special(parser) {
}
if (parser.eat('const')) {
// {@const a = b}
const start_index = parser.index - 5;
parser.require_whitespace();
parser.allow_whitespace();
let end_index = parser.index;
/** @type {import('estree').VariableDeclaration | undefined} */
let declaration = undefined;
const id = read_context(parser);
parser.allow_whitespace();
// Can't use parse_expression_at here, so we try to parse until we find the correct range
const dummy_spaces = parser.template.substring(0, start_index).replace(/[^\n]/g, ' ');
while (true) {
end_index = parser.template.indexOf('}', end_index + 1);
if (end_index === -1) break;
try {
const node = parse(
dummy_spaces + parser.template.substring(start_index, end_index),
parser.ts
).body[0];
if (node?.type === 'VariableDeclaration') {
declaration = node;
break;
}
} catch (e) {
continue;
}
}
parser.eat('=', true);
parser.allow_whitespace();
if (
declaration === undefined ||
declaration.declarations.length !== 1 ||
declaration.declarations[0].init === undefined
) {
error(start, 'invalid-const');
}
const init = read_expression(parser);
parser.allow_whitespace();
parser.index = end_index;
parser.eat('}', true);
parser.append(
@ -593,7 +568,13 @@ function special(parser) {
type: 'ConstTag',
start,
end: parser.index,
declaration
declaration: {
type: 'VariableDeclaration',
kind: 'const',
declarations: [{ type: 'VariableDeclarator', id, init }],
start: start + 1,
end: parser.index - 1
}
})
);
}

Loading…
Cancel
Save