import { CR, LF, isHighSurrogate, isLowSurrogate, splitsCrlf, splitsPair } from "./internal/codeUnits.js"; /** * The unit a position's `character` counts, as client and server negotiated * it: the LSP `PositionEncodingKind`. * * @remarks * `"utf-16"` counts UTF-16 code units, the specification's default and the * only kind every client supports. `"utf-8"` counts UTF-8 bytes and * `"utf-32"` counts Unicode code points. A server reads the kind from the * `positionEncoding` it answered in `initialize`'s `capabilities`; absent, * it is `"utf-16"`. * * @public */ export type LspPositionEncoding = "utf-8" | "utf-16" | "utf-32"; /** * A position in a text document: an LSP `Position`. * * @public */ export interface LspPosition { /** Zero-based line. */ readonly line: number; /** Zero-based offset into the line, in the negotiated {@link LspPositionEncoding}'s units. */ readonly character: number; } /** * The distance in UTF-16 units between checkpoints of the running unit * count. A lookup scans at most this many code units past a checkpoint, so a * long line costs no more than a short one; the table costs two numbers per * checkpoint. */ const STRIDE = 64; /** How many `encoding` units the code point starting at `at` occupies, and how many UTF-16 units it spans. */ const widthAt = (text: string, at: number, encoding: LspPositionEncoding): readonly [units: number, span: number] => { const code = text.charCodeAt(at); if (isHighSurrogate(code) && at + 1 < text.length && isLowSurrogate(text.charCodeAt(at + 1))) { return [encoding === "utf-8" ? 4 : encoding === "utf-32" ? 1 : 2, 2]; } if (encoding !== "utf-8") return [1, 1]; // A lone surrogate counts as the three bytes of the U+FFFD a UTF-8 encoder writes in its place. return [code < 0x80 ? 1 : code < 0x800 ? 2 : 3, 1]; }; const requireInteger = (name: string, value: number): void => { if (!Number.isInteger(value)) { throw new RangeError(`LspPositionIndex: ${name} must be an integer, received ${value}`); } }; const clamp = (value: number, low: number, high: number): number => Math.min(Math.max(value, low), high); /** The last index `i` in the ascending `values` with `values[i] <= target`, or 0. */ const floorIndex = (values: ReadonlyArray, target: number): number => { let low = 0; let high = values.length - 1; while (low < high) { const mid = (low + high + 1) >> 1; if ((values[mid] as number) <= target) low = mid; else high = mid - 1; } return low; }; /** * Converts between UTF-16 offsets into one text and LSP positions in one * negotiated encoding, built once per text and queried many times. * * @remarks * An offset is a UTF-16 code-unit index into the JavaScript string. Lines end * at `\n`, `\r\n` or a lone `\r`, the specification's three line endings. * Building is one forward scan, `O(n)`. A lookup is a binary search for the * line, then: under `"utf-16"`, nothing more; under `"utf-8"` and * `"utf-32"`, a binary search of a running unit count kept every 64 code * units, then a scan of at most 64 units. So a server converting every * diagnostic of a document builds one index and pays `O(log n)` each, even * on a minified one-line file. * * Out-of-range input clamps, never fails, as the specification prescribes * for a `character` past its line ("it defaults back to the line length") * and as `vscode-languageserver-textdocument` and `@effected/source`'s * `LineIndex` do; the clamp is the specification's answer, not a miss, so * there is no `Option`: * * - an offset below `0` reads as `0`, one past the end as the text's length; * - a `line` below `0` reads as offset `0`, one past the last line as the * text's length, and a negative `character` as its line's start; * - a `character` past its line's text reads as the line's end, before its * terminator. * * Nothing is ever answered inside a unit a position cannot name: * * - an offset between the `\r` and `\n` of a `\r\n` reads as the end of its * line, as no position names the middle of a line ending; * - an offset between the halves of a surrogate pair reads as the pair's * start, under every encoding, so `positionAt` never names half a * character; * - a `character` that lands inside a code point (between a pair's halves * under `"utf-16"`, among a character's bytes under `"utf-8"`) reads as * that code point's start, so `offsetAt` never splits one either. * * A lone surrogate is one code point, and three UTF-8 bytes: the bytes of * the U+FFFD a UTF-8 encoder writes for it. A value that is not an integer * (`NaN`, `1.5`) is a programmer error and throws a `RangeError`, since * clamping `NaN` would silently answer "line 0". * * At every code-point boundary that is not inside a `\r\n`, `offsetAt` * inverts `positionAt` exactly. * * @example * ```typescript * import { LspPositionIndex } from "@effected/lsp"; * * const index = LspPositionIndex.make("é\r\nx\u{1F600}y", "utf-8"); * console.log(index.positionAt(6)); * // => { line: 1, character: 5 } * console.log(index.offsetAt({ line: 1, character: 5 })); * // => 6 * console.log(index.offsetAt({ line: 0, character: 99 })); * // => 1 * ``` * * @public */ export class LspPositionIndex { /** The text this index was built over. */ readonly text: string; /** The unit every `character` counts. */ readonly encoding: LspPositionEncoding; // Plain fields, not parameter properties: `__test__/fixtures/lsp-main.ts` runs `src/` under Node's // strip-only type stripping, which refuses them. private readonly starts: ReadonlyArray; private readonly marks: ReadonlyArray; private readonly totals: ReadonlyArray; private constructor( text: string, encoding: LspPositionEncoding, starts: ReadonlyArray, marks: ReadonlyArray, totals: ReadonlyArray, ) { this.text = text; this.encoding = encoding; this.starts = starts; this.marks = marks; this.totals = totals; } /** * Build the index for `text` with one forward scan. * * @param text - The document's text. * @param encoding - The negotiated position encoding; defaults to `"utf-16"`. * @returns The index. */ static make(text: string, encoding: LspPositionEncoding = "utf-16"): LspPositionIndex { const starts: Array = [0]; const length = text.length; for (let at = 0; at < length; at++) { const code = text.charCodeAt(at); if (code === LF || (code === CR && text.charCodeAt(at + 1) !== LF)) starts.push(at + 1); } // Under "utf-16" a unit count is the offset itself, so no table is kept. const marks: Array = [0]; const totals: Array = [0]; if (encoding !== "utf-16") { let at = 0; let units = 0; while (at < length) { const [width, span] = widthAt(text, at, encoding); at += span; units += width; if (at - (marks[marks.length - 1] as number) >= STRIDE) { marks.push(at); totals.push(units); } } } return new LspPositionIndex(text, encoding, starts, marks, totals); } /** The number of lines, at least `1`: the empty text has one, and a text ending in a line ending has an empty last line. */ get lineCount(): number { return this.starts.length; } /** * The LSP position of `offset`. * * @param offset - A UTF-16 offset, clamped to the text; one inside a `\r\n` * reads as the end of its line, one inside a surrogate pair as the pair's start. * @returns The position. */ positionAt(offset: number): LspPosition { requireInteger("offset", offset); let target = clamp(offset, 0, this.text.length); const line = floorIndex(this.starts, target); const start = this.starts[line] as number; target = Math.min(target, this.lineEnd(line)); if (splitsPair(this.text, target)) target--; const character = this.encoding === "utf-16" ? target - start : this.unitsTo(target) - this.unitsTo(start); return { line, character }; } /** * The UTF-16 offset of `position`. * * @param position - The position. A `line` outside the text reads as its * start or end; a `character` past its line's text reads as the line's * end, and one inside a code point as that code point's start. * @returns The offset. */ offsetAt(position: LspPosition): number { requireInteger("line", position.line); requireInteger("character", position.character); if (position.line < 0) return 0; if (position.line >= this.starts.length) return this.text.length; const start = this.starts[position.line] as number; const end = this.lineEnd(position.line); const character = Math.max(position.character, 0); if (this.encoding === "utf-16") { const offset = Math.min(start + character, end); return splitsPair(this.text, offset) ? offset - 1 : offset; } return this.offsetOfUnits(this.unitsTo(start) + character, end); } /** Where `line`'s text ends: the start of its line ending, or the text's length on the last line. */ private lineEnd(line: number): number { if (line + 1 >= this.starts.length) return this.text.length; const next = this.starts[line + 1] as number; return splitsCrlf(this.text, next - 1) ? next - 2 : next - 1; } /** The running unit count at `offset`, a code-point boundary. */ private unitsTo(offset: number): number { const mark = floorIndex(this.marks, offset); let at = this.marks[mark] as number; let units = this.totals[mark] as number; while (at < offset) { const [width, span] = widthAt(this.text, at, this.encoding); at += span; units += width; } return units; } /** The last code-point boundary at or before `limit` whose running unit count does not pass `target`. */ private offsetOfUnits(target: number, limit: number): number { // The checkpoint must not pass the target or the line's end, so a `character` far past the line still // stops at `limit`. const mark = Math.min(floorIndex(this.totals, target), floorIndex(this.marks, limit)); let at = this.marks[mark] as number; let units = this.totals[mark] as number; while (at < limit) { const [width, span] = widthAt(this.text, at, this.encoding); if (units + width > target) break; at += span; units += width; } return at; } }