summaryrefslogtreecommitdiff
path: root/prism/templates/lib/prism/dsl.rb.erb
blob: 8dbb540952d9275a42c3f8329d5a37876c61ab4a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
module Prism
  # The DSL module provides a set of methods that can be used to create prism
  # nodes in a more concise manner. For example, instead of writing:
  #
  #     source = Prism::Source.new("[1]")
  #
  #     Prism::ArrayNode.new(
  #       [
  #         Prism::IntegerNode.new(
  #           Prism::IntegerBaseFlags::DECIMAL,
  #           1,
  #           Prism::Location.new(source, 1, 1),
  #           source
  #         )
  #       ],
  #       Prism::Location.new(source, 0, 1),
  #       Prism::Location.new(source, 2, 1),
  #       source
  #     )
  #
  # you could instead write:
  #
  #     source = Prism::Source.new("[1]")
  #
  #     ArrayNode(
  #       IntegerNode(Prism::IntegerBaseFlags::DECIMAL, 1, Location(source, 1, 1)), source),
  #       Location(source, 0, 1),
  #       Location(source, 2, 1),
  #       source
  #     )
  #
  # This is mostly helpful in the context of writing tests, but can also be used
  # to generate trees programmatically.
  module DSL
    private

    # Create a new Location object
    def Location(source = nil, start_offset = 0, length = 0)
      Location.new(source, start_offset, length) # steep:ignore
    end
    <%- nodes.each do |node| -%>

    # Create a new <%= node.name %> node
    def <%= node.name %>(<%= (node.fields.map(&:name) + ["source = nil, location = Location()"]).join(", ") %>)
      <%= node.name %>.new(<%= ["source", *node.fields.map(&:name), "location"].join(", ") %>)
    end
    <%- end -%>
  end
end