From f575a998cf01f9e1ee1373166a4cc5efac12f124 Mon Sep 17 00:00:00 2001 From: poplolioi11 <340387725+poplolioi11@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:49:39 +0800 Subject: [PATCH] fix(syntax): handle column offset at file start --- fluent-syntax/src/index.ts | 5 ++++ fluent-syntax/test/offset_test.js | 42 +++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 fluent-syntax/test/offset_test.js diff --git a/fluent-syntax/src/index.ts b/fluent-syntax/src/index.ts index ebeb2ff1..64330818 100644 --- a/fluent-syntax/src/index.ts +++ b/fluent-syntax/src/index.ts @@ -36,6 +36,11 @@ export function lineOffset(source: string, pos: number): number { } export function columnOffset(source: string, pos: number): number { + // lastIndexOf clamps a negative fromIndex to zero. + if (pos === 0) { + return 0; + } + // Find the last line break starting backwards from the index just before // pos. This allows us to correctly handle ths case where the character at // pos is a line break as well. diff --git a/fluent-syntax/test/offset_test.js b/fluent-syntax/test/offset_test.js new file mode 100644 index 00000000..216637f6 --- /dev/null +++ b/fluent-syntax/test/offset_test.js @@ -0,0 +1,42 @@ +import assert from "assert"; +import { columnOffset, lineOffset } from "../src/index.ts"; + +suite("columnOffset", function () { + test("file start before a leading LF", function () { + const source = "\nhello = Hello"; + assert.strictEqual(lineOffset(source, 0), 0); + assert.strictEqual(columnOffset(source, 0), 0); + }); + + test("file start in an LF-only source", function () { + assert.strictEqual(columnOffset("\n", 0), 0); + }); + + test("file start in an empty source", function () { + assert.strictEqual(columnOffset("", 0), 0); + }); + + test("file start in a nonempty first line", function () { + assert.strictEqual(columnOffset("hello", 0), 0); + }); + + test("file start before CRLF", function () { + assert.strictEqual(columnOffset("\r\nhello", 0), 0); + }); + + test("position on a line break", function () { + assert.strictEqual(columnOffset("hello\nworld", 5), 5); + }); + + test("position immediately after a line break", function () { + assert.strictEqual(columnOffset("hello\nworld", 6), 0); + }); + + test("position between consecutive line breaks", function () { + assert.strictEqual(columnOffset("\n\nhello", 1), 0); + }); + + test("end of the last line", function () { + assert.strictEqual(columnOffset("hello\nworld", 11), 5); + }); +});