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

Loading…
Cancel
Save