Debian Codegraph @

lib/prism/translation/ripper/lexer.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 class Lexer < Ripper # :nodoc:
10 # :stopdoc:
11 class State
12
13 attr_reader :to_int, :to_s
14
15 def initialize(i)
16 @to_int = i
17 @to_s = Ripper.lex_state_name(i)
18 freeze
19 end
20
21 def [](index)
22 case index
23 when 0, :to_int
24 @to_int
25 when 1, :to_s
26 @to_s
27 else
28 nil
29 end
30 end
31
32 alias to_i to_int
33 alias inspect to_s
34 def pretty_print(q) q.text(to_s) end
35 def ==(i) super or to_int == i end
36 def &(i) self.class.new(to_int & i) end
37 def |(i) self.class.new(to_int | i) end
38 def allbits?(i) to_int.allbits?(i) end
39 def anybits?(i) to_int.anybits?(i) end
40 def nobits?(i) to_int.nobits?(i) end
41
42 # Instances are frozen and there are only a handful of them so we cache them here.
43 STATES = Hash.new { |h,k| h[k] = State.new(k) }
44
45 def self.cached(i)
46 STATES[i]
47 end
48 end
49
50 class Elem
51 attr_accessor :pos, :event, :tok, :state, :message
52
53 def initialize(pos, event, tok, state, message = nil)
54 @pos = pos
55 @event = event
56 @tok = tok
57 @state = State.cached(state)
58 @message = message
59 end
60
61 def [](index)
62 case index
63 when 0, :pos
64 @pos
65 when 1, :event
66 @event
67 when 2, :tok
68 @tok
69 when 3, :state
70 @state
71 when 4, :message
72 @message
73 else
74 nil
75 end
76 end
77
78 def inspect
79 "#<#{self.class}: #{event}@#{pos[0]}:#{pos[1]}:#{state}: #{tok.inspect}#{": " if message}#{message}>"
80 end
81
82 alias to_s inspect
83
84 def pretty_print(q)
85 q.group(2, "#<#{self.class}:", ">") {
86 q.breakable
87 q.text("#{event}@#{pos[0]}:#{pos[1]}")
88 q.breakable
89 state.pretty_print(q)
90 q.breakable
91 q.text("token: ")
92 tok.pretty_print(q)
93 if message
94 q.breakable
95 q.text("message: ")
96 q.text(message)
97 end
98 }
99 end
100
101 def to_a
102 if @message
103 [@pos, @event, @tok, @state, @message]
104 else
105 [@pos, @event, @tok, @state]
106 end
107 end
108 end
109
110 # Pretty much just the same as Prism.lex_compat.
111 def lex(raise_errors: false)
112 Ripper.lex(@source, filename, lineno, raise_errors: raise_errors)
113 end
114
115 # Returns the lex_compat result wrapped in `Elem`. Errors are omitted.
116 # Since ripper is a streaming parser, tokens are expected to be emitted in the order
117 # that the parser encounters them. This is not implemented.
118 def parse(...)
119 lex(...).map do |position, event, token, state|
120 Elem.new(position, event, token, state.to_int)
121 end
122 end
123
124 # Similar to parse but ripper sorts the elements by position in the source. Also
125 # includes errors. Since prism does error recovery, in cases of syntax errors
126 # the result may differ greatly compared to ripper.
127 def scan(...)
128 parse(...)
129 end
130
131 # :startdoc:
132 end
133 end
134 end
135 end