Upgrade to https://github.com/acornjs/acorn.git commit 84eda6bf
[jst.git] / src / locutil.js
1 import {nextLineBreak} from "./whitespace.js"
2
3 // These are used when `options.locations` is on, for the
4 // `startLoc` and `endLoc` properties.
5
6 export class Position {
7   constructor(line, col) {
8     this.line = line
9     this.column = col
10   }
11
12   offset(n) {
13     return new Position(this.line, this.column + n)
14   }
15 }
16
17 export class SourceLocation {
18   constructor(p, start, end) {
19     this.start = start
20     this.end = end
21     if (p.sourceFile !== null) this.source = p.sourceFile
22   }
23 }
24
25 // The `getLineInfo` function is mostly useful when the
26 // `locations` option is off (for performance reasons) and you
27 // want to find the line/column position for a given character
28 // offset. `input` should be the code string that the offset refers
29 // into.
30
31 export function getLineInfo(input, offset) {
32   for (let line = 1, cur = 0;;) {
33     let nextBreak = nextLineBreak(input, cur, offset)
34     if (nextBreak < 0) return new Position(line, offset - cur)
35     ++line
36     cur = nextBreak
37   }
38 }