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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# Error raised when problems are detected in the input grammar.
attr_reader :file, :line, :column
@file = file
if column.nil?
@line = line.line
@column = line.column
else
@line = line
@column = column
end
super( % [@file, @line, @column, msg])
end
end
# Base parser class providing common functionality for both re2c and
# Lemon parsers.
# Convenient representation of a position in an input file.
@line = nil
@column = nil
@offset = nil
# Line number.
#
# @!attribute [r]
# @return [Integer]
attr_reader :line
# Column number.
#
# @!attribute [r]
# @return [Integer]
attr_reader :column
# Byte offset from the start of the file.
# @!attribute [r]
# @return [Integer]
attr_reader :offset
# Initialize the file-position object, optionally specifying the initial
# position within the file.
#
# @param [Integer] _line Initial line value.
# @param [Integer] _column Initial column number.
# @param [Integer] _offset Initial byte offset.
@line = _line || 1
@column = _column || 0
@offset = _offset || 0
end
# Create an updated position object by examining a string of consumed
# data and updating internal variables in a duplicated FilePosition
# as necessary.
#
# @param [String] consumed_data Input data between the current position
# and the desired new position in the input.
self.dup.update!(consumed_data)
end
# Update the position in-place by examining a string of consumed data and
# updating internal variables as necessary.
#
# @param [String] consumed_data Input data between the current position
# and the desired new position in the input.
@offset += consumed_data.length
@line += (nl = consumed_data.count())
@column =
if nl > 0
.match(consumed_data)[0].length
else
@column + consumed_data.length
end
self
end
% [self.class, self.object_id, self.to_s]
end
% [@line, @column]
end
end
# Token-instance data structure.
= ::Struct.new(:type, :value, :string, :position)
# Stores the information necessary to recognize, fetch, and create
# a TokenInstance for a given token type in the input file.
# Fetch procedure used if none is explicitly passed to {#initialize}.
# This implementation simply uses the regular-expression passed to
# {#initialize}.
= lambda { input.slice!(m.regexp) }
@type = nil
@match_regexp = nil
@fetch_proc = nil
# The type of token that this object defines.
#
# @!attribute [r]
# @return [Symbol]
attr_reader :type
# The regular expression that, when it matches against the beginning of
# an input string, will cause a parser to call this definition's
# `fetch` method.
#
# @!attribute [r]
# @return [Regexp]
attr_reader :match_regexp
# Initialize a token definition, specifying the token type, initial
# regular expression, and (optionally) a block or proc to be used for
# fetching the data for this type of token.
#
# @param [Symbol] _type Token-type being defined.
#
# @param [Regexp] _regexp Regular expression that matches partial-initial
# or full instances of this token type. If it matches only part of
# the full token string, a proc (`_fetch_proc`) or block must be
# passed to `#initialize`.
#
# @param [Proc,nil] _fetch_proc If non-`nil`, a procedure that accepts an
# input string and the MatchData from the definition's match regexp,
# and returns the initial part of the input string that represents
# this token. It is expected that the proc will modify the input
# in-place, e.g. using {String#slice!}.
raise APIUsageError() if
block_given? and not _fetch_proc.nil?
if _fetch_proc.nil?
_fetch_proc = block if block_given?
_fetch_proc ||= DEFAULT_FETCH_PROC
end
@type = _type
@match_regexp = _regexp
raise APIUsageError.new( %
[self.class.name, __method__]) unless
_fetch_proc.kind_of?(Proc) or _fetch_proc.kind_of?(Regexp)
@fetch_proc =
case _fetch_proc
when Proc
_fetch_proc
when Regexp
proc { input.slice!(_fetch_proc) }
end
end
# Attempt to fetch an instance of this token type from the given input
# string. If the definition matches, removes the matching initial part
# of the input, updates the given position, and returns a corresponding
# TokenInstance; otherwise returns `nil`.
#
# @param [String] input Remaining input data.
#
# @param [FilePosition] _position Current position in the input file.
#
# @return [TokenInstance,nil] Instance of this token type found at the
# start of `input`, or `nil` if no such instance was found.
if not (m = @match_regexp.match(input)).nil?
tok_position = _position.dup
pre_length = input.length
value = _binding.instance_exec(input, m, &@fetch_proc)
removed = value
value, removed = value if value.kind_of?(Array)
unless value.nil?
# Modify the buffer if the fetch proc didn't.
input.slice!(0, removed.length) if input.length == pre_length
_position.update!(removed) # update file position
return TokenInstance.new(@type, value, removed, tok_position)
end
else
nil
end
end
end
# State data for a parser.
=
@input_string = nil
@buffer = nil
@filename = nil
@position = nil
@prev_token = nil
# Grammar context into which parsed data is stored.
#
# @!attribute [r]
# @return [ReLemon::Context]
attr_reader :context
# Name of the file being parsed, if applicable.
#
# @!attribute [r]
# @return [String]
attr_reader :filename
# Portion of `input_string` that has yet to be tokenized or parsed.
#
# @!attribute [r]
# @return [String]
attr_reader :buffer
# The full, unmodified string on which a parse was requested.
#
# @!attribute [r]
# @return [String]
attr_reader :input_string
# Token returned by `next_token()` for the PREVIOUS run of
# e.g. `handle_token()`.
#
# @!attribute [r]
# @return [TokenInstance]
attr_reader :prev_token
unless (removed = @buffer.slice!(self.class.const_get(:INPUT_TRIM_REGEXP))).nil?
@position.update!(removed)
end
end
# Whether the state's unparsed-data buffer is empty.
#
# @attribute [r]
# @return [Boolean]
@buffer.empty?
end
# Initialize a new parse-state object.
#
# @param [String] _input_string String to parse.
#
# @param [Hash] opts Options hash.
# @option opts [ReLemon::Context] :context Context to store parsed data in.
# @option opts [String] :filename File name to use when reporting errors
# @option opts [Integer] :line Initial line number.
# @option opts [Integer] :column Initial column number.
# @option opts [Integer] :offset Initial byte offset.
@input_options = opts
@input_string = _input_string.clone.freeze
@buffer = _input_string.clone
@filename = opts[:filename]
@position = opts[:position] || FilePosition.new(opts[:line], opts[:column], opts[:offset])
@trim_input = opts.fetch(:trim_input, false)
@prev_token = nil
@token_set = nil
@terminate_parse_requested = false
end
attr_accessor :token_set
@terminate_parse_requested = true
[nil,]
end
# Update the parser-state's `line` and `column` values given a string of
# consumed data.
@position.update!(consumed_data)
end
# Get the line and column number corresponding to the first character in
# the parse state's buffer.
#
# @return [Array<Integer>]
@position
end
remove_junk_from_top() if @trim_input
buf = @buffer
return nil if buf.empty?
o = nil
@token_set.each { break unless (o = defn.fetch(buf, self.position, self)).nil? }
if o.nil?
lim = [buf.length, 32].min
raise GrammarError.new( % [buf[0...lim], lim < buf.length ? : ],
filename, self.position)
else
if @input_options[:dump_tokens]
$stderr.puts(o.inspect)
$stderr.flush()
end
return o
end
end
# Run the parsing algorithm on the input string, and return the context.
# @return [ReLemon::Context]
while not empty?
last_buf = @buffer.clone
tok = next_token()
break if @terminate_parse_requested
raise + @buffer + if @buffer.length == last_buf.length
# It's possible the buffer was empty except for some whitespace,
# which may have been discarded by `next_token`.
handle_token(tok) unless tok.nil?
@prev_token = tok
end
finish()
end
end
# Define singleton methods on classes/modules that include Parser.
_module.instance_exec do
const_set(:FilePosition, ::ReLemon::Parser::FilePosition)
const_set(:ParseState, Class.new(::ReLemon::Parser::ParseState) do
define_method(:initialize) do
super(*a, **opts)
@token_set = _module.const_get(:TOKENS)
end
end)
# Parse a named file.
# begin
# oldwd = Dir.pwd
# Dir.chdir(File.dirname(file))
self::ParseState.new(File.read(file),
options.merge(filename: file)).
run()
# ensure
# Dir.chdir(oldwd)
# end
end
self::ParseState.new(buf, options.has_key?(:filename) ? options : options.merge(filename: )).
run()
end
end
end
# class << self
# include IINet::Util::Memoizer
# def anchor_regexp(re)
# source = re.source
# if source =~ /\A\\A/ or source =~ /\A\^/
# re
# elsif full
# /\A#{source}\z/
# else
# /\A#{source}/
# end
# end
# memoize(:anchor)
# end
end
end