Few helpers. Now getLineRange throws on out of bounds line.
This commit is contained in:
parent
85bc9b05e1
commit
9c72959cd3
1 changed files with 33 additions and 5 deletions
36
src/index.ts
36
src/index.ts
|
|
@ -240,11 +240,12 @@ export class SourceText {
|
|||
return this.sliceByCp(startCp, endCp);
|
||||
}
|
||||
|
||||
getLineRange(line: number): { start: CodePointIndex, end: CodePointIndex } {
|
||||
|
||||
tryGetLineRange(line: number): CodePointSpan | undefined {
|
||||
const lineIndex = line - 1;
|
||||
|
||||
if (lineIndex < 0 || lineIndex >= this.lineStarts.length) {
|
||||
// TODO: This is a bit suspicious. Maybe return undefined?
|
||||
return { start: 0, end: 0 };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const start = this.lineStarts[lineIndex];
|
||||
|
|
@ -252,7 +253,15 @@ export class SourceText {
|
|||
? this.lineStarts[lineIndex + 1]
|
||||
: this.#chars.length;
|
||||
|
||||
return { start, end };
|
||||
return rawSpan(start, end);
|
||||
}
|
||||
|
||||
getLineRange(line: number): { start: CodePointIndex, end: CodePointIndex } {
|
||||
const range = this.tryGetLineRange(line);
|
||||
if (range === undefined) {
|
||||
throw new Error(`Line ${line} is out of bounds (line count: ${this.lineCount})`);
|
||||
}
|
||||
return range;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -308,6 +317,10 @@ export class SourceRegion {
|
|||
return span(loc, loc);
|
||||
}
|
||||
|
||||
get codePointSpan(): CodePointSpan {
|
||||
return rawSpan(this.span.start.index, this.span.end.index);
|
||||
}
|
||||
|
||||
*codePoints(): IterableIterator<[CodePointIndex, CodePoint]> {
|
||||
const start = this.span.start.index;
|
||||
const end = this.span.end.index;
|
||||
|
|
@ -378,6 +391,16 @@ export type SourceLocation = {
|
|||
column: number; // 1-based
|
||||
}
|
||||
|
||||
export function containsSpan(outer: CodePointSpan, inner: CodePointSpan): boolean {
|
||||
return outer.start <= inner.start && inner.end <= outer.end;
|
||||
}
|
||||
|
||||
export function containsIndex(span: CodePointSpan, index: CodePointIndex): boolean {
|
||||
return span.start <= index && index < span.end;
|
||||
}
|
||||
|
||||
// === Cursor ===
|
||||
|
||||
export class SourceCursor {
|
||||
private index: CodePointIndex;
|
||||
|
||||
|
|
@ -431,6 +454,11 @@ export class SourceCursor {
|
|||
return this.region.slice(span);
|
||||
}
|
||||
|
||||
|
||||
location(): SourceLocation {
|
||||
return this.region.source.getLocation(this.index);
|
||||
}
|
||||
|
||||
moveToNextLineStart(): void {
|
||||
const loc = this.region.source.getLocation(this.index);
|
||||
const nextLine = loc.line + 1;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue