Skip to content

Instantly share code, notes, and snippets.

@azu azu/estree-loc-line.md
Last active Apr 8, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.