From a4f826e9f8ab65d8ed8feab747559060b2fa6f69 Mon Sep 17 00:00:00 2001 From: Pharex38 Date: Sat, 24 Oct 2026 14:01:42 +0300 Subject: [PATCH] Fix the token value of comments, which included the preceding character The comment scanner took its start one character before the '/', so getTokenValue() returned e.g. ' // c' or ',/* c */'. stripComments uses that value with a replace character, so it added one character per comment instead of keeping the offsets. --- src/impl/scanner.ts | 2 +- src/test/json.test.ts | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/impl/scanner.ts b/src/impl/scanner.ts index daad8ff..e2cb32c 100644 --- a/src/impl/scanner.ts +++ b/src/impl/scanner.ts @@ -247,7 +247,7 @@ export function createScanner(text: string, ignoreTrivia: boolean = false): JSON // comments case CharacterCodes.slash: { - const start = pos - 1; + const start = pos; // Single-line comment if (text.charCodeAt(pos + 1) === CharacterCodes.slash) { pos += 2; diff --git a/src/test/json.test.ts b/src/test/json.test.ts index e658bf5..fb1f241 100644 --- a/src/test/json.test.ts +++ b/src/test/json.test.ts @@ -8,7 +8,7 @@ import * as assert from 'node:assert'; import { suite, test } from 'node:test'; import { SyntaxKind, createScanner, parse, getLocation, Node, ParseError, parseTree, ParseErrorCode, - ParseOptions, Segment, findNodeAtLocation, getNodeValue, getNodePath, ScanError, visit, JSONVisitor, JSONPath + ParseOptions, Segment, findNodeAtLocation, getNodeValue, getNodePath, ScanError, visit, JSONVisitor, JSONPath, stripComments } from '../main.js'; function assertKinds(text: string, ...kinds: SyntaxKind[]): void { @@ -142,6 +142,25 @@ suite('JSON', () => { assertKinds(',', SyntaxKind.CommaToken); }); + test('comment token value', () => { + for (const [text, comment] of [['[1, // line', '// line'], ['{"a":1,/* block */}', '/* block */'], ['/* first */', '/* first */']]) { + const scanner = createScanner(text); + let kind: SyntaxKind; + while ((kind = scanner.scan()) !== SyntaxKind.LineCommentTrivia && kind !== SyntaxKind.BlockCommentTrivia) { + assert.notStrictEqual(kind, SyntaxKind.EOF, text); + } + assert.strictEqual(scanner.getTokenValue(), comment, text); + } + }); + + test('stripComments keeps offsets with a replace character', () => { + const text = '{"a": 1, /* x\n y */ "b": 2} // end'; + const stripped = stripComments(text, ' '); + assert.strictEqual(stripped, '{"a": 1, \n "b": 2} '); + assert.strictEqual(stripped.length, text.length); + assert.strictEqual(stripComments(text), '{"a": 1, "b": 2} '); + }); + test('comments', () => { assertKinds('// this is a comment', SyntaxKind.LineCommentTrivia); assertKinds('// this is a comment\n', SyntaxKind.LineCommentTrivia, SyntaxKind.LineBreakTrivia);