Skip to content

Instantly share code, notes, and snippets.

@azu
Last active July 27, 2021 11:54
Show Gist options
  • Save azu/8866b2cb9b7a933e01fe to your computer and use it in GitHub Desktop.
Save azu/8866b2cb9b7a933e01fe to your computer and use it in GitHub Desktop.
Why do `line` of location in JavaScript AST(ESTree) start with 1 and not 0?

Major JavaScript parser library like esprima, acorn parse JavaScript code and output AST.

The AST's node has loc object that is defined by ESTree Spec.

interface Node {
    type: string;
    loc: SourceLocation | null;
}
interface SourceLocation {
    source: string | null;
    start: Position;
    end: Position;
}
// Each Position object consists of a line number (**1-indexed**) and a column number (0-indexed):
interface Position {
    line: number; // >= 1
    column: number; // >= 0
}

Each Position object consists of a line number (1-indexed) and a column number (0-indexed):

Q. Why do line of location in JavaScript AST(ESTree) start with 1 and not 0?

A. This 1-based line come from Error.prototype.stack.

@fitzgen (He is SourceMap specification editor) said:

This lib matches the spec, but it would be best if everything was 1-based, as that is what all major browsers use for Error.prototype.stack. -- Document that lines are one-based and columns are zero based. · Issue #118 · mozilla/source-map

Error.prototype.stack is not standardization, but Error.prototype.lineNumber of major browser (like IE, Firefox, Chrome, Safari) start with 1.

Conclusion

ESTree Position.line start with 1 for compatibility with Error.prototype.lineNumber.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment