node.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import {Parser} from "./state"
  2. import {SourceLocation} from "./location"
  3. // Start an AST node, attaching a start offset.
  4. const pp = Parser.prototype
  5. export class Node {}
  6. pp.startNode = function() {
  7. let node = new Node
  8. node.start = this.start
  9. if (this.options.locations)
  10. node.loc = new SourceLocation(this, this.startLoc)
  11. if (this.options.directSourceFile)
  12. node.sourceFile = this.options.directSourceFile
  13. if (this.options.ranges)
  14. node.range = [this.start, 0]
  15. return node
  16. }
  17. pp.startNodeAt = function(pos, loc) {
  18. let node = new Node
  19. if (Array.isArray(pos)){
  20. if (this.options.locations && loc === undefined) {
  21. // flatten pos
  22. loc = pos[1]
  23. pos = pos[0]
  24. }
  25. }
  26. node.start = pos
  27. if (this.options.locations)
  28. node.loc = new SourceLocation(this, loc)
  29. if (this.options.directSourceFile)
  30. node.sourceFile = this.options.directSourceFile
  31. if (this.options.ranges)
  32. node.range = [pos, 0]
  33. return node
  34. }
  35. // Finish an AST node, adding `type` and `end` properties.
  36. pp.finishNode = function(node, type) {
  37. node.type = type
  38. node.end = this.lastTokEnd
  39. if (this.options.locations)
  40. node.loc.end = this.lastTokEndLoc
  41. if (this.options.ranges)
  42. node.range[1] = this.lastTokEnd
  43. return node
  44. }
  45. // Finish node at given position
  46. pp.finishNodeAt = function(node, type, pos, loc) {
  47. node.type = type
  48. if (Array.isArray(pos)){
  49. if (this.options.locations && loc === undefined) {
  50. // flatten pos
  51. loc = pos[1]
  52. pos = pos[0]
  53. }
  54. }
  55. node.end = pos
  56. if (this.options.locations)
  57. node.loc.end = loc
  58. if (this.options.ranges)
  59. node.range[1] = pos
  60. return node
  61. }