import { Position } from "./position.js" import type { SerializedPosition } from "./position.js" export type SerializedLocation = { start: SerializedPosition end: SerializedPosition } export class Location { readonly start: Position readonly end: Position static from(location: SerializedLocation): Location static from(line: number, column: number, endLine: number, endColumn: number): Location static from(locationOrLine: SerializedLocation | number, column?: number, endLine?: number, endColumn?: number): Location { if (typeof locationOrLine === "number") { const start = Position.from(locationOrLine, column!) const end = Position.from(endLine!, endColumn!) return new Location(start, end) } else { const start = Position.from(locationOrLine.start) const end = Position.from(locationOrLine.end) return new Location(start, end) } } static fromOptional(location: SerializedLocation | null): Location { return (location ? Location.from(location) : null) as unknown as Location } static get zero() { return new Location(Position.zero, Position.zero) } constructor(start: Position, end: Position) { this.start = start this.end = end } contains(position: Position): boolean { return position.compare(this.start) >= 0 && position.compare(this.end) < 0 } covers(other: Location): boolean { return this.start.compare(other.start) <= 0 && other.end.compare(this.end) <= 0 } isEmpty(): boolean { return this.start.equals(this.end) } toHash(): SerializedLocation { return { start: this.start.toHash(), end: this.end.toHash(), } } toJSON(): SerializedLocation { return this.toHash() } treeInspect(): string { return `${this.start.treeInspect()}-${this.end.treeInspect()}` } treeInspectWithLabel(): string { return `(location: ${this.treeInspect()})` } inspect(): string { return `#` } toString(): string { return this.inspect() } }