-
-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathparser.cr
454 lines (371 loc) · 11.5 KB
/
parser.cr
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
module Mint
class Parser
include Helpers
# The errors found.
getter errors : Array(Error) = [] of Error
# The position of the cursor, which is at the character we are currently
# parsing.
getter position : Location = Location.new
# The input which is an array of characters because this way it's faster in
# cases where the original code contains multi-byte characters.
getter input : Array(Char)
# The abstract syntax tree.
getter ast = Ast.new
# The parsed file, we save it so we can show parse errors.
getter file : File
def initialize(input : String, path : String)
@file = File.new(input, path)
@input = input.chars
end
# Parses a thing (an ast node). Yielding the start position so the thing
# getting parsed can use it. If the block returns nil or we rollback to
# the start position since it means the parsing has failed.
# track - if true we save the resulting node
def parse(*, track : Bool = true, &)
operators_size = ast.operators.size
keywords_size = ast.keywords.size
nodes_size = ast.nodes.size
start_position = position
(yield position, nodes_size, @errors.size).tap do |node|
case node
when Ast::Node
ast.nodes[nodes_size..-1].each { |child| child.parent ||= node unless child == node }
ast.nodes << node if track
when Nil
ast.operators.delete_at(operators_size...)
ast.keywords.delete_at(keywords_size...)
ast.nodes.delete_at(nodes_size...)
@position = start_position
end
end
end
def error(name : Symbol, &) : Nil
errors << Error.new(name).tap { |error| with error yield }
end
# Moves the cursor forward by one character.
def step
position, line, column =
@position.to_tuple
case char
when '\n'
column = 0_i64
line += 1
else
column += 1
end
@position =
Location.new(offset: position + 1, line: line, column: column)
end
# Returns whether or not the cursor is at the end of the file.
def eof? : Bool
@position.offset == input.size
end
# Checks if we reached the end of the file, adds an error otherwise.
def eof! : Bool
whitespace
error :expected_eof do
expected "the end of the file", word
snippet self
end unless eof?
true
end
# Returns the current character.
def char : Char
input[position.offset]? || '\0'
end
# If the character is parsed with the given block, moves the cursor forward.
def char(& : Char -> Bool)
step if yield char
end
# If the character is the current character, moves the cursor forward.
def char!(expected : Char)
char { |current| current == expected }
end
# Returns the next character.
def next_char : Char
input[position.offset + 1]? || '\0'
end
# Returns the previous character.
def previous_char : Char
input[position.offset - 1]? || '\0'
end
# Returns the current word (sequence of ascii lowercase letters).
def ascii_word : String
index = position.offset
word = ""
while (input[index]? || '\0').ascii_letter?
word += input[index]
index += 1
end
word
end
# Parses any number of ascii latters or numbers.
def ascii_letters_or_numbers(*, extra_char : Char? = nil)
chars { |char| char.ascii_letter? || char.ascii_number? || char == extra_char }
end
# Parses any number of ascii uppercase latters, numbers or underscore and
# must start with an uppercase letter.
def ascii_uppercase_and_underscore
chars { |char| char.ascii_uppercase? || char.ascii_number? || char == '_' }
end
# Consumes characters while the yielded value is true or we reach the end
# of the file.
def chars(& : Char -> Bool)
while char != '\0' && (yield char)
step
end
end
# Consumes characters while the yielded value is in one of the given
# characters.
def chars(*next_chars : Char)
chars &.in?(next_chars)
end
# Starts to parse something, if the cursor moved during, return the parsed
# string.
def gather(&) : String?
start_position = position.offset
yield
if position.offset > start_position
result = file.contents[start_position, position.offset - start_position]
result unless result.empty?
end
end
# Consumes characters until the yielded value is true.
def consume(& : -> Bool) : Nil
while yield
step
end
end
# Returns the word (non whitespace sequence) a the cursor.
def word : String?
start_position = position
word = ""
while !(eof? || whitespace?)
word += char
step
end
@position = start_position
word
end
# Returns the word (non whitespace sequence) a the position.
def word(position : Location)
current = position.offset
word = ""
while (char = input[current]?) && !char.ascii_whitespace?
word += char
end
word
end
# Returns whether or not the word is at the current position.
def word?(word) : Bool
word.chars.each_with_index.all? do |char, i|
input[position.offset + i]? == char
end
end
# Consumes a word and steps the cursor forward if successful.
def word!(expected : String) : Bool
if word?(expected)
expected.size.times { step }
true
else
false
end
end
# Consumes a word and saves it as a keyword for syntax highlighting.
def keyword!(expected : String) : Bool
start_position = position
word!(expected).tap do |result|
@ast.keywords << {from: start_position, to: position} if result
end
end
# Consumes all available whitespace.
def whitespace : Nil
chars &.ascii_whitespace?
end
# Returns whether the current character is a whitespace.
def whitespace? : Bool
char.ascii_whitespace?
end
# Consumes all available whitespace and returns true / false whether
# there were any.
def whitespace! : Bool
if whitespace?
whitespace
true
else
false
end
end
# Parses a variable identifier.
def identifier_variable : String?
return unless char.ascii_lowercase?
gather { ascii_letters_or_numbers }
end
# Parses a constant identifier.
def identifier_constant : String?
return unless char.ascii_uppercase?
gather { ascii_uppercase_and_underscore }
end
# Parses a type identifier.
def identifier_type : String?
parse do
name = gather do
next unless char.ascii_uppercase?
ascii_letters_or_numbers
end
next if char == '_' # If there is an underscore it's a constant...
next unless name
parse do
next unless char! '.'
next unless other = identifier_type
name += ".#{other}"
end
name
end
end
# Parse many things separated by whitespace.
def many(parse_whitespace : Bool = true, & : -> T?) : Array(T) forall T
result = [] of T
loop do
# Using parse here will not consume the whitespace if
# the parsing is not successfull.
item = parse(track: false) do
# Consume whitespace
whitespace if parse_whitespace
yield
end
# Break if the block didn't yield anything
break unless item
# Add item to results
result << item
end
result
end
# Parses a list of things, which ends in the terminator character and are
# separated by the separator character.
def list(terminator : Char?, separator : Char, & : -> T?) : Array(T) forall T
result = [] of T
loop do
item = parse(track: false) do
# Consume whitespace before the next thing
whitespace
# Return nil if we reached the end
next if char == terminator
yield
end
# Break if the block didn't yield anything
break unless item
# Add item to results
result << item
# Using parse here will not consume whitespace if there is no separator.
parsed_separator = parse do
# Consume whitespace before the separator
whitespace
# Break if there is no separator, consume it otherwise
next unless char! separator
# This is needed to actually finish the consuming.
true
end
break unless parsed_separator
end
result
end
# Parses a block surrounded by brackets.
def brackets(opening_bracket_error : Proc(Nil)? = nil,
closing_bracket_error : Proc(Nil)? = nil,
empty_check : Proc(T, Nil)? = nil,
& : -> T?) : T? forall T
parse(track: false) do
unless char! '{'
case item = opening_bracket_error
when Proc(Nil)
next item.call
else
next
end
end
whitespace
result = yield.tap { |value| empty_check.try(&.call(value)) }
whitespace
unless char! '}'
case item = closing_bracket_error
when Proc(Nil)
next item.call
else
next
end
end
result
end
end
# Parses a thing, if succeeds it discards all errors while parsing it.
def oneof(& : -> T?) : T? forall T
# Copy the errors for later use.
errors = self.errors.dup
# Empty the errors, since we want to gather them.
@errors = [] of Error
yield.tap do |result|
if result
# Restore the original errors
@errors = errors
else
# Restore the original errors and add the new ones.
@errors = errors + @errors
end
end
end
# Parses a raw part of the input until we reach the terminator or an
# interpolation (if it's needed).
def raw(terminator : Char, stop_on_interpolation : Bool = true) : String?
gather do
while char != '\0'
break if previous_char != '\\' &&
char == terminator
break if stop_on_interpolation &&
previous_char != '\\' &&
next_char == '{' &&
char == '#'
step
end
end
end
# Parses a raw part of the input until we reach the terminator or an
# interpolation.
def raw(token : String) : String?
raw { !word?(token) }
end
# Parses a raw part of the input until we reach the terminator or an
# interpolation.
def raw(& : -> Bool) : String?
gather do
while char != '\0' && yield
break if previous_char != '\\' &&
next_char == '{' &&
char == '#'
step
end
end
end
# Returns the last non whitespace position.
def last_non_whitespace_position
position, line, column =
@position.to_tuple
while input[position - 1]?.try(&.ascii_whitespace?)
case previous_char
when '\n'
current = position - 2
column = 0_i64
line -= 1
while input[current]? && (input[current] != '\n')
current -= 1
column += 1
end
else
column -= 1
end
position -= 1
end
Location.new(offset: position, line: line, column: column)
end
end
end