Skip to content

Commit 211707c

Browse files
waynzhota-meshi
andauthored
Fix comments order (#265)
* Fix comments order * chore: update * Add test * Update index.js --------- Co-authored-by: Yosuke Ota <[email protected]>
1 parent 01ed265 commit 211707c

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

src/ast/nodes.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import type { ScopeManager } from "eslint-scope"
77
import type { ParseError } from "./errors"
88
import type { HasLocation } from "./locations"
99
import type { Token } from "./tokens"
10-
// eslint-disable-next-line node/no-extraneous-import -- ignore
1110
import type { TSESTree } from "@typescript-eslint/utils"
1211

1312
//------------------------------------------------------------------------------

src/script-setup/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,10 @@ export function parseScriptSetupElements(
308308
}
309309
result.ast.tokens.sort((a, b) => a.range[0] - b.range[0])
310310
}
311+
312+
if (result.ast.comments != null) {
313+
result.ast.comments.sort((a, b) => a.range[0] - b.range[0])
314+
}
311315
result.ast.body.sort((a, b) => a.range[0] - b.range[0])
312316

313317
const programStartOffset = result.ast.body.reduce(

test/index.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -896,6 +896,44 @@ describe("Basic tests", async () => {
896896
assert.strictEqual(messages.length, 1)
897897
assert.strictEqual(messages[0].message, "'c' is not defined.")
898898
})
899+
900+
it("should sort comments by their original source position", () => {
901+
const code = `<script lang="ts" setup>
902+
const test = () => {
903+
// first
904+
return false
905+
}
906+
</script>
907+
908+
<script lang="ts">
909+
/**
910+
* second
911+
*/
912+
export default {}
913+
</script>
914+
915+
<template>
916+
<div @click="test" />
917+
</template>`
918+
919+
const result = parseForESLint(code, { sourceType: "module" })
920+
const comments = result.ast.comments
921+
922+
// Should have 2 comments
923+
assert.strictEqual(comments.length, 2)
924+
925+
// Comments should be sorted by their original position in source code
926+
assert.strictEqual(comments[0].type, "Line")
927+
assert.strictEqual(comments[0].value, " first")
928+
assert.strictEqual(comments[0].loc.start.line, 3)
929+
930+
assert.strictEqual(comments[1].type, "Block")
931+
assert.strictEqual(comments[1].value, "*\n * second\n ")
932+
assert.strictEqual(comments[1].loc.start.line, 9)
933+
934+
// Verify comments are sorted by range
935+
assert.ok(comments[0].range[0] < comments[1].range[0])
936+
})
899937
})
900938
})
901939

0 commit comments

Comments
 (0)