* Compute line and column from offset on-demand (lazy position tracking). * Only called when an error occurs, avoiding overhead during successful parsing.
(offset: number)
| 144 | * Only called when an error occurs, avoiding overhead during successful parsing. |
| 145 | */ |
| 146 | function computePosition(offset: number): { |
| 147 | line: number; |
| 148 | column: number; |
| 149 | offset: number; |
| 150 | } { |
| 151 | if (!trackPosition) { |
| 152 | return { line: 0, column: 0, offset: 0 }; |
| 153 | } |
| 154 | let line = 1; |
| 155 | let lastNlPos = -1; |
| 156 | let searchStart = 0; |
| 157 | while (true) { |
| 158 | const nlPos = input.indexOf("\n", searchStart); |
| 159 | if (nlPos === -1 || nlPos >= offset) break; |
| 160 | line++; |
| 161 | lastNlPos = nlPos; |
| 162 | searchStart = nlPos + 1; |
| 163 | } |
| 164 | return { |
| 165 | line, |
| 166 | column: offset - lastNlPos, |
| 167 | offset, |
| 168 | }; |
| 169 | } |
| 170 | |
| 171 | function error(message: string): never { |
| 172 | throw new XmlSyntaxError(message, computePosition(pos)); |