From 08b4d359fa7471ea448ef5ee9b9120887506034f Mon Sep 17 00:00:00 2001 From: Rich Harris Date: Mon, 5 Feb 2024 15:23:31 -0500 Subject: [PATCH] chore: simpler const parsing (#10347) * chore: simpler const parsing * fix * fix --------- Co-authored-by: Rich Harris --- .../src/compiler/phases/1-parse/state/tag.js | 47 ++++++------------- 1 file changed, 14 insertions(+), 33 deletions(-) diff --git a/packages/svelte/src/compiler/phases/1-parse/state/tag.js b/packages/svelte/src/compiler/phases/1-parse/state/tag.js index 9f8a57c055..08f47f5717 100644 --- a/packages/svelte/src/compiler/phases/1-parse/state/tag.js +++ b/packages/svelte/src/compiler/phases/1-parse/state/tag.js @@ -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 + } }) ); }