locutil.js 1.0 KB

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