|
53 | 53 | } |
54 | 54 | } |
55 | 55 |
|
| 56 | + function pad(s, length) { |
| 57 | + if (s.length > length) { |
| 58 | + return s |
| 59 | + } |
| 60 | + return Array(length - s.length + 1).join(" ") + s |
| 61 | + } |
| 62 | + |
| 63 | + function lastNLines(string, numLines) { |
| 64 | + var position = string.length |
| 65 | + var lineBreaks = 0; |
| 66 | + while (true) { |
| 67 | + var idx = string.lastIndexOf("\n", position - 1) |
| 68 | + if (idx === -1) { |
| 69 | + break; |
| 70 | + } else { |
| 71 | + lineBreaks++ |
| 72 | + } |
| 73 | + position = idx |
| 74 | + if (lineBreaks === numLines) { |
| 75 | + break; |
| 76 | + } |
| 77 | + if (position === 0) { |
| 78 | + break; |
| 79 | + } |
| 80 | + } |
| 81 | + var startPosition = |
| 82 | + lineBreaks < numLines ? |
| 83 | + 0 : |
| 84 | + position + 1 |
| 85 | + return string.substring(startPosition).split("\n") |
| 86 | + } |
| 87 | + |
56 | 88 | function objectToRules(object) { |
57 | 89 | var keys = Object.getOwnPropertyNames(object) |
58 | 90 | var result = [] |
|
524 | 556 |
|
525 | 557 | // throw, if no rule with {error: true} |
526 | 558 | if (group.shouldThrow) { |
527 | | - throw new Error(this.formatError(token, "invalid syntax")) |
| 559 | + var err = new Error(this.formatError(token, "invalid syntax")) |
| 560 | + throw err; |
528 | 561 | } |
529 | 562 |
|
530 | 563 | if (group.pop) this.popState() |
|
565 | 598 | col: this.col, |
566 | 599 | } |
567 | 600 | } |
568 | | - var start = Math.max(0, token.offset - token.col + 1) |
569 | | - var eol = token.lineBreaks ? token.text.indexOf('\n') : token.text.length |
570 | | - var firstLine = this.buffer.substring(start, token.offset + eol) |
571 | | - message += " at line " + token.line + " col " + token.col + ":\n\n" |
572 | | - message += " " + firstLine + "\n" |
573 | | - message += " " + Array(token.col).join(" ") + "^" |
574 | | - return message |
| 601 | + |
| 602 | + var numLinesAround = 2 |
| 603 | + var firstDisplayedLine = Math.max(token.line - numLinesAround, 1) |
| 604 | + var lastDisplayedLine = token.line + numLinesAround |
| 605 | + var lastLineDigits = String(lastDisplayedLine).length |
| 606 | + var displayedLines = lastNLines( |
| 607 | + this.buffer, |
| 608 | + (this.line - token.line) + numLinesAround + 1 |
| 609 | + ) |
| 610 | + .slice(0, 5) |
| 611 | + var errorLines = [] |
| 612 | + errorLines.push(message + " at line " + token.line + " col " + token.col + ":") |
| 613 | + errorLines.push("") |
| 614 | + for (var i = 0; i < displayedLines.length; i++) { |
| 615 | + var line = displayedLines[i] |
| 616 | + var lineNo = firstDisplayedLine + i |
| 617 | + errorLines.push(pad(String(lineNo), lastLineDigits) + " " + line); |
| 618 | + if (lineNo === token.line) { |
| 619 | + errorLines.push(pad("", lastLineDigits + token.col + 1) + "^") |
| 620 | + } |
| 621 | + } |
| 622 | + return errorLines.join("\n") |
575 | 623 | } |
576 | 624 |
|
577 | 625 | Lexer.prototype.clone = function() { |
|
0 commit comments