summaryrefslogtreecommitdiff
path: root/prism/templates/lib/prism/node.rb.erb
blob: 12a984e5a28bb49ba6d829add7e8d5a9a9ede840 (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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
module Prism
  # This represents a node in the tree. It is the parent class of all of the
  # various node types.
  class Node
    # A pointer to the source that this node was created from.
    attr_reader :source
    private :source

    # A Location instance that represents the location of this node in the
    # source.
    def location
      location = @location
      return location if location.is_a?(Location)
      @location = Location.new(source, location >> 32, location & 0xFFFFFFFF)
    end

    # The start offset of the node in the source. This method is effectively a
    # delegate method to the location object.
    def start_offset
      location = @location
      location.is_a?(Location) ? location.start_offset : location >> 32
    end

    # The end offset of the node in the source. This method is effectively a
    # delegate method to the location object.
    def end_offset
      location = @location
      location.is_a?(Location) ? location.end_offset : ((location >> 32) + (location & 0xFFFFFFFF))
    end

    def newline? # :nodoc:
      @newline ? true : false
    end

    def set_newline_flag(newline_marked) # :nodoc:
      line = location.start_line
      unless newline_marked[line]
        newline_marked[line] = true
        @newline = true
      end
    end

    # Slice the location of the node from the source.
    def slice
      location.slice
    end

    # Similar to inspect, but respects the current level of indentation given by
    # the pretty print object.
    def pretty_print(q)
      q.seplist(inspect.chomp.each_line, -> { q.breakable }) do |line|
        q.text(line.chomp)
      end
      q.current_group.break
    end

    # Convert this node into a graphviz dot graph string.
    def to_dot
      # @type self: node
      DotVisitor.new.tap { |visitor| accept(visitor) }.to_dot
    end

    # --------------------------------------------------------------------------
    # :section: Node interface
    # These methods are effectively abstract methods that must be implemented by
    # the various subclasses of Node. They are here to make it easier to work
    # with typecheckers.
    # --------------------------------------------------------------------------

    # Accepts a visitor and calls back into the specialized visit function.
    def accept(visitor)
      raise NoMethodError, "undefined method `accept' for #{inspect}"
    end

    # Returns an array of child nodes, including `nil`s in the place of optional
    # nodes that were not present.
    def child_nodes
      raise NoMethodError, "undefined method `child_nodes' for #{inspect}"
    end

    alias deconstruct child_nodes

    # Returns an array of child nodes, excluding any `nil`s in the place of
    # optional nodes that were not present.
    def compact_child_nodes
      raise NoMethodError, "undefined method `compact_child_nodes' for #{inspect}"
    end

    # Returns an array of child nodes and locations that could potentially have
    # comments attached to them.
    def comment_targets
      raise NoMethodError, "undefined method `comment_targets' for #{inspect}"
    end

    # Returns a symbol symbolizing the type of node that this represents. This
    # is particularly useful for case statements and array comparisons.
    def type
      raise NoMethodError, "undefined method `type' for #{inspect}"
    end

    # Returns a string representation of the node.
    def inspect(inspector = NodeInspector.new)
      raise NoMethodError, "undefined method `inspect' for #{inspect}"
    end
  end
  <%- nodes.each do |node| -%>

  <%- node.each_comment_line do |line| -%>
  #<%= line %>
  <%- end -%>
  class <%= node.name -%> < Node
    # def initialize: (<%= (node.fields.map { |field| "#{field.rbs_class} #{field.name}" } + ["Location location"]).join(", ") %>) -> void
    def initialize(source, <%= (node.fields.map(&:name) + ["location"]).join(", ") %>)
      @source = source
      @newline = false
      @location = location
      <%- node.fields.each do |field| -%>
      <%- if Prism::Template::CHECK_FIELD_KIND && field.respond_to?(:check_field_kind) -%>
      raise <%= field.name %>.inspect unless <%= field.check_field_kind %>
      <%- end -%>
      @<%= field.name %> = <%= field.name %>
      <%- end -%>
    end

    # def accept: (Visitor visitor) -> void
    def accept(visitor)
      visitor.visit_<%= node.human %>(self)
    end
    <%- if node.newline == false -%>

    def set_newline_flag(newline_marked) # :nodoc:
      # Never mark <%= node.name %> with a newline flag, mark children instead
    end
    <%- elsif node.newline.is_a?(String) -%>

    def set_newline_flag(newline_marked) # :nodoc:
      <%- field = node.fields.find { |f| f.name == node.newline } or raise node.newline -%>
      <%- case field -%>
      <%- when Prism::Template::NodeField -%>
      <%= field.name %>.set_newline_flag(newline_marked)
      <%- when Prism::Template::NodeListField -%>
      first = <%= field.name %>.first
      first.set_newline_flag(newline_marked) if first
      <%- else raise field.class.name -%>
      <%- end -%>
    end
    <%- end -%>

    # def child_nodes: () -> Array[nil | Node]
    def child_nodes
      [<%= node.fields.map { |field|
        case field
        when Prism::Template::NodeField, Prism::Template::OptionalNodeField then field.name
        when Prism::Template::NodeListField then "*#{field.name}"
        end
      }.compact.join(", ") %>]
    end

    # def compact_child_nodes: () -> Array[Node]
    def compact_child_nodes
      <%- if node.fields.any? { |field| field.is_a?(Prism::Template::OptionalNodeField) } -%>
      compact = [] #: Array[Prism::node]
      <%- node.fields.each do |field| -%>
      <%- case field -%>
      <%- when Prism::Template::NodeField -%>
      compact << <%= field.name %>
      <%- when Prism::Template::OptionalNodeField -%>
      compact << <%= field.name %> if <%= field.name %>
      <%- when Prism::Template::NodeListField -%>
      compact.concat(<%= field.name %>)
      <%- end -%>
      <%- end -%>
      compact
      <%- else -%>
      [<%= node.fields.map { |field|
        case field
        when Prism::Template::NodeField then field.name
        when Prism::Template::NodeListField then "*#{field.name}"
        end
      }.compact.join(", ") %>]
      <%- end -%>
    end

    # def comment_targets: () -> Array[Node | Location]
    def comment_targets
      [<%= node.fields.map { |field|
        case field
        when Prism::Template::NodeField, Prism::Template::LocationField then field.name
        when Prism::Template::OptionalNodeField, Prism::Template::NodeListField, Prism::Template::OptionalLocationField then "*#{field.name}"
        end
      }.compact.join(", ") %>] #: Array[Prism::node | Location]
    end

    # def copy: (<%= (node.fields.map { |field| "?#{field.name}: #{field.rbs_class}" } + ["?location: Location"]).join(", ") %>) -> <%= node.name %>
    def copy(<%= (node.fields.map(&:name) + ["location"]).map { |field| "#{field}: self.#{field}" }.join(", ") %>)
      <%= node.name %>.new(<%= ["source", *node.fields.map(&:name), "location"].join(", ") %>)
    end

    # def deconstruct: () -> Array[nil | Node]
    alias deconstruct child_nodes

    # def deconstruct_keys: (Array[Symbol] keys) -> { <%= (node.fields.map { |field| "#{field.name}: #{field.rbs_class}" } + ["location: Location"]).join(", ") %> }
    def deconstruct_keys(keys)
      { <%= (node.fields.map { |field| "#{field.name}: #{field.name}" } + ["location: location"]).join(", ") %> }
    end

    <%- node.fields.each do |field| -%>
    <%- if field.comment.nil? -%>
    # <%= "private " if field.is_a?(Prism::Template::FlagsField) %>attr_reader <%= field.name %>: <%= field.rbs_class %>
    <%- else -%>
    <%- field.each_comment_line do |line| -%>
    #<%= line %>
    <%- end -%>
    <%- end -%>
    <%- case field -%>
    <%- when Prism::Template::LocationField -%>
    def <%= field.name %>
      location = @<%= field.name %>
      return location if location.is_a?(Location)
      @<%= field.name %> = Location.new(source, location >> 32, location & 0xFFFFFFFF)
    end
    <%- when Prism::Template::OptionalLocationField -%>
    def <%= field.name %>
      location = @<%= field.name %>
      case location
      when nil
        nil
      when Location
        location
      else
        @<%= field.name %> = Location.new(source, location >> 32, location & 0xFFFFFFFF)
      end
    end
    <%- else -%>
    attr_reader :<%= field.name -%><%= "\n    private :#{field.name}" if field.is_a?(Prism::Template::FlagsField) %>
    <%- end -%>

    <%- end -%>
    <%- node.fields.each do |field| -%>
    <%- case field -%>
    <%- when Prism::Template::LocationField -%>
    <%- raise unless field.name.end_with?("_loc") -%>
    <%- next if node.fields.any? { |other| other.name == field.name.delete_suffix("_loc") } -%>

    # def <%= field.name.delete_suffix("_loc") %>: () -> String
    def <%= field.name.delete_suffix("_loc") %>
      <%= field.name %>.slice
    end
    <%- when Prism::Template::OptionalLocationField -%>
    <%- raise unless field.name.end_with?("_loc") -%>
    <%- next if node.fields.any? { |other| other.name == field.name.delete_suffix("_loc") } -%>

    # def <%= field.name.delete_suffix("_loc") %>: () -> String?
    def <%= field.name.delete_suffix("_loc") %>
      <%= field.name %>&.slice
    end
    <%- when Prism::Template::FlagsField -%>
    <%- flags.find { |flag| flag.name == field.kind }.tap { |flag| raise "Expected to find #{field.kind}" unless flag }.values.each do |value| -%>

    # def <%= value.name.downcase %>?: () -> bool
    def <%= value.name.downcase %>?
      <%= field.name %>.anybits?(<%= field.kind %>::<%= value.name %>)
    end
    <%- end -%>
    <%- end -%>
    <%- end -%>

    # def inspect(NodeInspector inspector) -> String
    def inspect(inspector = NodeInspector.new)
      inspector << inspector.header(self)
      <%- node.fields.each_with_index do |field, index| -%>
      <%- pointer, preadd = index == node.fields.length - 1 ? ["└── ", "    "] : ["├── ", "│   "] -%>
      <%- case field -%>
      <%- when Prism::Template::NodeListField -%>
      inspector << "<%= pointer %><%= field.name %>: #{inspector.list("#{inspector.prefix}<%= preadd %>", <%= field.name %>)}"
      <%- when Prism::Template::ConstantListField -%>
      inspector << "<%= pointer %><%= field.name %>: #{<%= field.name %>.inspect}\n"
      <%- when Prism::Template::NodeField -%>
      inspector << "<%= pointer %><%= field.name %>:\n"
      inspector << inspector.child_node(<%= field.name %>, "<%= preadd %>")
      <%- when Prism::Template::OptionalNodeField -%>
      if (<%= field.name %> = self.<%= field.name %>).nil?
        inspector << "<%= pointer %><%= field.name %>: ∅\n"
      else
        inspector << "<%= pointer %><%= field.name %>:\n"
        inspector << <%= field.name %>.inspect(inspector.child_inspector("<%= preadd %>")).delete_prefix(inspector.prefix)
      end
      <%- when Prism::Template::ConstantField, Prism::Template::StringField, Prism::Template::UInt8Field, Prism::Template::UInt32Field, Prism::Template::IntegerField, Prism::Template::DoubleField -%>
      inspector << "<%= pointer %><%= field.name %>: #{<%= field.name %>.inspect}\n"
      <%- when Prism::Template::OptionalConstantField -%>
      if (<%= field.name %> = self.<%= field.name %>).nil?
        inspector << "<%= pointer %><%= field.name %>: ∅\n"
      else
        inspector << "<%= pointer %><%= field.name %>: #{<%= field.name %>.inspect}\n"
      end
      <%- when Prism::Template::FlagsField -%>
      <%- flag = flags.find { |flag| flag.name == field.kind }.tap { |flag| raise unless flag } -%>
      flags = [<%= flag.values.map { |value| "(\"#{value.name.downcase}\" if #{value.name.downcase}?)" }.join(", ") %>].compact
      inspector << "<%= pointer %><%= field.name %>: #{flags.empty? ? "∅" : flags.join(", ")}\n"
      <%- when Prism::Template::LocationField, Prism::Template::OptionalLocationField -%>
      inspector << "<%= pointer %><%= field.name %>: #{inspector.location(<%= field.name %>)}\n"
      <%- else -%>
      <%- raise -%>
      <%- end -%>
      <%- end -%>
      inspector.to_str
    end

    # Sometimes you want to check an instance of a node against a list of
    # classes to see what kind of behavior to perform. Usually this is done by
    # calling `[cls1, cls2].include?(node.class)` or putting the node into a
    # case statement and doing `case node; when cls1; when cls2; end`. Both of
    # these approaches are relatively slow because of the constant lookups,
    # method calls, and/or array allocations.
    #
    # Instead, you can call #type, which will return to you a symbol that you
    # can use for comparison. This is faster than the other approaches because
    # it uses a single integer comparison, but also because if you're on CRuby
    # you can take advantage of the fact that case statements with all symbol
    # keys will use a jump table.
    #
    # def type: () -> Symbol
    def type
      :<%= node.human %>
    end

    # Similar to #type, this method returns a symbol that you can use for
    # splitting on the type of the node without having to do a long === chain.
    # Note that like #type, it will still be slower than using == for a single
    # class, but should be faster in a case statement or an array comparison.
    #
    # def self.type: () -> Symbol
    def self.type
      :<%= node.human %>
    end
  end
  <%- end -%>
  <%- flags.each_with_index do |flag, flag_index| -%>

  # <%= flag.comment %>
  module <%= flag.name %>
    <%- flag.values.each_with_index do |value, index| -%>
    # <%= value.comment %>
    <%= value.name %> = 1 << <%= index %>
<%= "\n" if value != flag.values.last -%>
    <%- end -%>
  end
  <%- end -%>
end