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
- Parser API - Mozilla | MDN
- Issue 6 - esprima - Add location to syntax nodes - ECMAScript parsing infrastructure for multipurpose analysis - Google Project Hosting
- Make line indices configurable by dabbler0 · Pull Request #117 · marijnh/acorn
- 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
.
ESTree Position.line
start with 1
for compatibility with Error.prototype.lineNumber
.