Skip to content

Commit 3b46852

Browse files
committed
fix: properly assign trailing comments
Trailing comments were added even if they started before the node end, which violates the definition of trailing comments. This fixes that, with the consequence that some comments no longer show up in the AST at all. Previously they were stuffed _somewhere_, but arguably at the wrong positions. For example the last comment in a function body got assigned as a trailing comma for the body, which is wrong, because the body ends _after_ the comma. The special case is comments at the end of an expression tag - they are added even if there are multiple, and they are added regardless of whether they are separated by newlines or not. This ensures the expression tag end is calculated correctly. Fixes #12466
1 parent 9666215 commit 3b46852

File tree

5 files changed

+131
-87
lines changed

5 files changed

+131
-87
lines changed

.changeset/fast-toes-act.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: properly assign trailing comments

packages/svelte/src/compiler/phases/1-parse/acorn.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,17 +105,22 @@ function get_comment_handlers(source) {
105105

106106
if (comments[0]) {
107107
const parent = path.at(-1);
108+
108109
if (parent === undefined || node.end !== parent.end) {
109110
const slice = source.slice(node.end, comments[0].start);
110111

111-
if (/^[,) \t]*$/.test(slice)) {
112+
if (node.end <= comments[0].start && /^[,) \t]*$/.test(slice)) {
112113
node.trailingComments = [/** @type {CommentWithLocation} */ (comments.shift())];
113114
}
114115
}
115116
}
116117
}
117118
});
118-
if (comments.length > 0) {
119+
120+
// Special case: Trailing comments after the root node (which can only happen for expression tags) get added
121+
// regardless of line breaks between the root node and the comments. This ensures that we can later detect
122+
// the end of the expression tag correctly.
123+
if (comments.length > 0 && comments[0].start >= ast.end) {
119124
(ast.trailingComments ||= []).push(...comments.splice(0));
120125
}
121126
}

packages/svelte/tests/parser-legacy/samples/javascript-comments/input.svelte

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,17 @@
55
66
/** a comment */
77
function asd() {
8-
8+
foo;
9+
/* comment belonging to noone */
910
}
1011
</script>
1112

1213
<button
1314
on:click={// comment
1415
() => {
1516
/* another comment */
16-
fn();
17+
fn(); // a trailing comment
18+
/* comment belonging to noone */
1719
}}
1820
>
1921
{/* leading block comment */ a}

0 commit comments

Comments
 (0)