|
1 | 1 | import { parse as xmlToolsParse } from "@xml-tools/parser";
|
2 | 2 | import type { Parser } from "./types";
|
3 | 3 |
|
| 4 | +type LocatedError = Error & { |
| 5 | + loc: { |
| 6 | + start: { line: number; column: number }; |
| 7 | + end: { line: number; column: number }; |
| 8 | + }; |
| 9 | +}; |
| 10 | + |
4 | 11 | const parser: Parser = {
|
5 | 12 | parse(text) {
|
6 | 13 | const { lexErrors, parseErrors, cst } = xmlToolsParse(text);
|
7 | 14 |
|
8 |
| - if (lexErrors.length > 0 || parseErrors.length > 0) { |
9 |
| - throw Error("Error parsing XML"); |
| 15 | + // If there are any lexical errors, throw the first of them as an error. |
| 16 | + if (lexErrors.length > 0) { |
| 17 | + const lexError = lexErrors[0]; |
| 18 | + const error = new Error(lexError.message) as LocatedError; |
| 19 | + |
| 20 | + error.loc = { |
| 21 | + start: { line: lexError.line, column: lexError.column }, |
| 22 | + end: { line: lexError.line, column: lexError.column + lexError.length } |
| 23 | + }; |
| 24 | + |
| 25 | + throw error; |
| 26 | + } |
| 27 | + |
| 28 | + // If there are any parse errors, throw the first of them as an error. |
| 29 | + if (parseErrors.length > 0) { |
| 30 | + const parseError = parseErrors[0]; |
| 31 | + const error = new Error(parseError.message) as LocatedError; |
| 32 | + |
| 33 | + const { token } = parseError; |
| 34 | + error.loc = { |
| 35 | + start: { line: token.startLine!, column: token.startColumn! }, |
| 36 | + end: { line: token.endLine!, column: token.endColumn! } |
| 37 | + }; |
| 38 | + |
| 39 | + throw error; |
10 | 40 | }
|
11 | 41 |
|
| 42 | + // Otherwise return the CST. |
12 | 43 | return cst;
|
13 | 44 | },
|
14 | 45 | astFormat: "xml",
|
|
0 commit comments