Debian Codegraph @

lib/prism/translation/ripper/sexp.rb

raw symbols SCIP
1 # frozen_string_literal: true
2 # :markup: markdown
3
4 require_relative "../ripper"
5
6 module Prism
7 module Translation
8 class Ripper
9 # This class mirrors the ::Ripper::SexpBuilder subclass of ::Ripper that
10 # returns the arrays of [type, *children].
11 class SexpBuilder < Ripper
12 # :stopdoc:
13
14 attr_reader :error
15
16 private
17
18 def dedent_element(e, width)
19 if (n = dedent_string(e[1], width)) > 0
20 e[2][1] += n
21 end
22 e
23 end
24
25 def on_heredoc_dedent(val, width)
26 sub = proc do |cont|
27 cont.map! do |e|
28 if Array === e
29 case e[0]
30 when :@tstring_content
31 e = dedent_element(e, width)
32 when /_add\z/
33 e[1] = sub[e[1]]
34 end
35 elsif String === e
36 dedent_string(e, width)
37 end
38 e
39 end
40 end
41 sub[val]
42 val
43 end
44
45 events = private_instance_methods(false).grep(/\Aon_/) {$'.to_sym}
46 (PARSER_EVENTS - events).each do |event|
47 module_eval(<<-End, __FILE__, __LINE__ + 1)
48 def on_#{event}(*args)
49 args.unshift :#{event}
50 end
51 End
52 end
53
54 SCANNER_EVENTS.each do |event|
55 module_eval(<<-End, __FILE__, __LINE__ + 1)
56 def on_#{event}(tok)
57 [:@#{event}, tok, [lineno(), column()]]
58 end
59 End
60 end
61
62 def on_error(mesg)
63 @error = mesg
64 end
65 remove_method :on_parse_error
66 alias on_parse_error on_error
67 alias compile_error on_error
68
69 # :startdoc:
70 end
71
72 # This class mirrors the ::Ripper::SexpBuilderPP subclass of ::Ripper that
73 # returns the same values as ::Ripper::SexpBuilder except with a couple of
74 # niceties that flatten linked lists into arrays.
75 class SexpBuilderPP < SexpBuilder
76 # :stopdoc:
77
78 private
79
80 def on_heredoc_dedent(val, width)
81 val.map! do |e|
82 next e if Symbol === e and /_content\z/ =~ e
83 if Array === e and e[0] == :@tstring_content
84 e = dedent_element(e, width)
85 elsif String === e
86 dedent_string(e, width)
87 end
88 e
89 end
90 val
91 end
92
93 def _dispatch_event_new
94 []
95 end
96
97 def _dispatch_event_push(list, item)
98 list.push item
99 list
100 end
101
102 def on_mlhs_paren(list)
103 [:mlhs, *list]
104 end
105
106 def on_mlhs_add_star(list, star)
107 list.push([:rest_param, star])
108 end
109
110 def on_mlhs_add_post(list, post)
111 list.concat(post)
112 end
113
114 PARSER_EVENT_TABLE.each do |event, arity|
115 if /_new\z/ =~ event and arity == 0
116 alias_method "on_#{event}", :_dispatch_event_new
117 elsif /_add\z/ =~ event
118 alias_method "on_#{event}", :_dispatch_event_push
119 end
120 end
121
122 # :startdoc:
123 end
124 end
125 end
126 end