zaach / jison

Bison in JavaScript.
http://jison.org
4.36k stars 450 forks source link

Enhance `showPosition()` to Accurately Display Error Position by Line Number #406

Open satyajitnayk opened 11 months ago

satyajitnayk commented 11 months ago

@zaach @JamieSlome can we enhance showPosition() ?? The showPosition() function, found here, can be enhanced to provide a detailed error context according to the specific line number.

This modification ensures that the ----^ indicator accurately reflects the error position on the relevant line, rather than defaulting to the last line:

            showPosition: function showPosition() {
                var pre = this.pastInput();
                var upcoming = this.upcomingInput();
                var allText = pre + upcoming;
                var lines = allText.split("\n");

                // Calculate line number and column of the caret
                var errorLine = pre.split("\n").length;
                var errorColumn = pre.length - pre.lastIndexOf("\n") - 1;

                // Build the output with caret under the error position
                var output = "";
                for (var i = 0; i < lines.length; i++) {
                    output += lines[i] + "\n";
                    if (i === errorLine - 1) {
                        output += new Array(errorColumn + 1).join("-") + "^" + "\n";
                    }
                }
                return output;
            }
  1. Current error message:
    ...LLO{{/if}}
    {{#if}
    HELLO
    {{/i
    -----------------------^
  2. New error message:
    Parse error on line 2:
    ...LLO{{/if}}
    {{#if}
    ---------^
    HELLO
    {{/i