This repository has been archived by the owner on Jun 24, 2022. It is now read-only.
forked from prettier/plugin-ruby
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.rb
executable file
·2650 lines (2332 loc) · 81.2 KB
/
parser.rb
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env ruby
# We implement our own version checking here instead of using Gem::Version so
# that we can use the --disable-gems flag.
RUBY_MAJOR, RUBY_MINOR, RUBY_PATCH, * = RUBY_VERSION.split('.').map(&:to_i)
if (RUBY_MAJOR < 2) || ((RUBY_MAJOR == 2) && (RUBY_MINOR < 5))
warn(
"Ruby version #{RUBY_VERSION} not supported. " \
'Please upgrade to 2.5.0 or above.'
)
exit 1
end
require 'delegate'
require 'json'
require 'ripper'
module Prettier
end
class Prettier::Parser < Ripper
# Represents a line in the source. If this class is being used, it means that
# every character in the string is 1 byte in length, so we can just return the
# start of the line + the index.
class SingleByteString
def initialize(start)
@start = start
end
def [](byteindex)
@start + byteindex
end
end
# Represents a line in the source. If this class is being used, it means that
# there are characters in the string that are multi-byte, so we will build up
# an array of indices, such that array[byteindex] will be equal to the index
# of the character within the string.
class MultiByteString
def initialize(start, line)
@indices = []
line
.each_char
.with_index(start) do |char, index|
char.bytesize.times { @indices << index }
end
end
def [](byteindex)
@indices[byteindex]
end
end
attr_reader :source, :lines, :scanner_events
# This is an attr_accessor so Stmts objects can grab comments out of this
# array and attach them to themselves.
attr_accessor :comments
def initialize(source, *args)
super(source, *args)
@source = source
@lines = source.split("\n")
@comments = []
@embdoc = nil
@__end__ = nil
@heredocs = []
@scanner_events = []
@line_counts = []
# Here we're going to build up a list of SingleByteString or MultiByteString
# objects. They're each going to represent a string in the source. They are
# used by the `char_pos` method to determine where we are in the source
# string.
last_index = 0
@source.lines.each do |line|
if line.size == line.bytesize
@line_counts << SingleByteString.new(last_index)
else
@line_counts << MultiByteString.new(last_index, line)
end
last_index += line.size
end
end
def self.parse(source)
builder = new(source)
response = builder.parse
response unless builder.error?
end
private
# This represents the current place in the source string that we've gotten to
# so far. We have a memoized line_counts object that we can use to get the
# number of characters that we've had to go through to get to the beginning of
# this line, then we add the number of columns into this line that we've gone
# through.
def char_pos
@line_counts[lineno - 1][column]
end
# As we build up a list of scanner events, we'll periodically need to go
# backwards and find the ones that we've already hit in order to determine the
# location information for nodes that use them. For example, if you have a
# module node then you'll look backward for a @module scanner event to
# determine your start location.
#
# This works with nesting since we're deleting scanner events from the list
# once they've been used up. For example if you had nested module declarations
# then the innermost declaration would grab the last @module event (which
# would happen to be the innermost keyword). Then the outer one would only be
# able to grab the first one. In this way all of the scanner events act as
# their own stack.
def find_scanner_event(type, body = :any, consume: true)
index =
scanner_events.rindex do |scanner_event|
scanner_event[:type] == type &&
(body == :any || (scanner_event[:body] == body))
end
consume ? scanner_events.delete_at(index) : (index && scanner_events[index])
end
# Scanner events occur when the lexer hits a new token, like a keyword or an
# end. These nodes always contain just one argument which is a string
# representing the content. For the most part these can just be printed
# directly, which very few exceptions.
defined = %i[
comment
embdoc
embdoc_beg
embdoc_end
heredoc_beg
heredoc_end
ignored_nl
]
(SCANNER_EVENTS - defined).each do |event|
define_method(:"on_#{event}") do |value|
ec = char_pos + value.size
node = {
type: :"@#{event}",
body: value,
sl: lineno,
el: lineno,
sc: char_pos,
ec: ec
}
scanner_events << node
node
end
end
# We keep track of each comment as it comes in and then eventually add
# them to the top of the generated AST so that prettier can start adding
# them back into the final representation. Comments come in including
# their starting pound sign and the newline at the end, so we also chop
# those off.
#
# If there is an encoding magic comment at the top of the file, ripper
# will actually change into that encoding for the storage of the string.
# This will break everything, so we need to force the encoding back into
# UTF-8 so that the JSON library won't break.
def on_comment(value)
@comments << {
type: :@comment,
value: value[1..-1].chomp.force_encoding('UTF-8'),
inline: value.strip != lines[lineno - 1],
sl: lineno,
el: lineno,
sc: char_pos,
ec: char_pos + value.length - 1
}
end
# ignored_nl is a special kind of scanner event that passes nil as the value,
# so we can't do our normal tracking of value.size. Instead of adding a
# condition to the main SCANNER_EVENTS loop above, we'll just explicitly
# define the method here. You can trigger the ignored_nl event with the
# following snippet:
#
# foo.bar
# .baz
#
def on_ignored_nl(value)
{
type: :ignored_nl,
body: nil,
sl: lineno,
el: lineno,
sc: char_pos,
ec: char_pos
}
end
prepend(
Module.new do
private
# Handles __END__ syntax, which allows individual scripts to keep content
# after the main ruby code that can be read through DATA. It looks like:
#
# foo.bar
#
# __END__
# some other content that isn't normally read by ripper
def on___end__(*)
@__end__ = super(lines[lineno..-1].join("\n"))
end
# Like comments, we need to force the encoding here so JSON doesn't break.
def on_ident(value)
super(value.force_encoding('UTF-8'))
end
# Like comments, we need to force the encoding here so JSON doesn't break.
def on_tstring_content(value)
super(value.force_encoding('UTF-8'))
end
end
)
# A BEGIN node is a parser event that represents the use of the BEGIN
# keyword, which hooks into the lifecycle of the interpreter. It's a bit
# of a legacy from the stream operating days, and gets its inspiration
# from tools like awk. Whatever is inside the "block" will get executed
# when the program starts. The syntax looks like the following:
#
# BEGIN {
# # execute stuff here
# }
#
def on_BEGIN(stmts)
beging = find_scanner_event(:@lbrace)
ending = find_scanner_event(:@rbrace)
stmts.bind(find_next_statement_start(beging[:ec]), ending[:sc])
find_scanner_event(:@kw, 'BEGIN').merge!(
type: :BEGIN,
body: [beging, stmts],
el: ending[:el],
ec: ending[:ec]
)
end
# A END node is a parser event that represents the use of the END keyword,
# which hooks into the lifecycle of the interpreter. It's a bit of a
# legacy from the stream operating days, and gets its inspiration from
# tools like awk. Whatever is inside the "block" will get executed when
# the program ends. The syntax looks like the following:
#
# END {
# # execute stuff here
# }
#
def on_END(stmts)
beging = find_scanner_event(:@lbrace)
ending = find_scanner_event(:@rbrace)
stmts.bind(find_next_statement_start(beging[:ec]), ending[:sc])
find_scanner_event(:@kw, 'END').merge!(
type: :END,
body: [beging, stmts],
el: ending[:el],
ec: ending[:ec]
)
end
# alias is a parser event that represents when you're using the alias
# keyword with regular arguments. This can be either symbol literals or
# bare words. You can optionally use parentheses with this keyword, so we
# either track the location information based on those or the final
# argument to the alias method.
def on_alias(left, right)
beging = find_scanner_event(:@kw, 'alias')
paren = source[beging[:ec]...left[:sc]].include?('(')
ending = paren ? find_scanner_event(:@rparen) : right
{
type: :alias,
body: [left, right],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# aref nodes are when you're pulling a value out of a collection at a
# specific index. Put another way, it's any time you're calling the method
# #[]. As an example:
#
# foo[index]
#
# The nodes usually contains two children, the collection and the index.
# In some cases, you don't necessarily have the second child node, because
# you can call procs with a pretty esoteric syntax. In the following
# example, you wouldn't have a second child, and "foo" would be the first
# child:
#
# foo[]
#
def on_aref(collection, index)
find_scanner_event(:@lbracket)
ending = find_scanner_event(:@rbracket)
{
type: :aref,
body: [collection, index],
sl: collection[:sl],
sc: collection[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# aref_field is a parser event that is very similar to aref except that it
# is being used inside of an assignment.
def on_aref_field(collection, index)
find_scanner_event(:@lbracket)
ending = find_scanner_event(:@rbracket)
{
type: :aref_field,
body: [collection, index],
sl: collection[:sl],
sc: collection[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# args_new is a parser event that represents the beginning of a list of
# arguments to any method call or an array. It can be followed by any
# number of args_add events, which we'll append onto an array body.
def on_args_new
{
type: :args,
body: [],
sl: lineno,
sc: char_pos,
el: lineno,
ec: char_pos
}
end
# args_add is a parser event that represents a single argument inside a
# list of arguments to any method call or an array. It accepts as
# arguments the parent args node as well as an arg which can be anything
# that could be passed as an argument.
def on_args_add(args, arg)
if args[:body].empty?
arg.merge(type: :args, body: [arg])
else
args.merge!(body: args[:body] << arg, el: arg[:el], ec: arg[:ec])
end
end
# args_add_block is a parser event that represents a list of arguments and
# potentially a block argument. If no block is passed, then the second
# argument will be false.
def on_args_add_block(args, block)
ending = block || args
args.merge(
type: :args_add_block,
body: [args, block],
el: ending[:el],
ec: ending[:ec]
)
end
# args_add_star is a parser event that represents adding a splat of values
# to a list of arguments. If accepts as arguments the parent args node as
# well as the part that is being splatted.
def on_args_add_star(args, part)
beging = find_scanner_event(:@op, '*')
ending = part || beging
{
type: :args_add_star,
body: [args, part],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# args_forward is a parser event that represents forwarding all kinds of
# arguments onto another method call.
def on_args_forward
find_scanner_event(:@op, '...').merge!(type: :args_forward)
end
# arg_paren is a parser event that represents wrapping arguments to a
# method inside a set of parentheses.
def on_arg_paren(args)
beging = find_scanner_event(:@lparen)
rparen = find_scanner_event(:@rparen)
# If the arguments exceed the ending of the parentheses, then we know we
# have a heredoc in the arguments, and we need to use the bounds of the
# arguments to determine how large the arg_paren is.
ending = (args && args[:el] > rparen[:el]) ? args : rparen
{
type: :arg_paren,
body: [args],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# Array nodes can contain a myriad of subnodes because of the special
# array literal syntax like %w and %i. As a result, we may be looking for
# an left bracket, or we may be just looking at the children to get the
# bounds.
def on_array(contents)
if !contents || %i[args args_add_star].include?(contents[:type])
beging = find_scanner_event(:@lbracket)
ending = find_scanner_event(:@rbracket)
{
type: :array,
body: [contents],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
else
ending = find_scanner_event(:@tstring_end)
contents[:ec] = ending[:ec]
ending.merge!(
type: :array,
body: [contents],
sl: contents[:sl],
sc: contents[:sc]
)
end
end
# aryptn is a parser event that represents matching against an array pattern
# using the Ruby 2.7+ pattern matching syntax.
def on_aryptn(const, preargs, splatarg, postargs)
pieces = [const, *preargs, splatarg, *postargs].compact
{
type: :aryptn,
body: [const, preargs, splatarg, postargs],
sl: pieces[0][:sl],
sc: pieces[0][:sc],
el: pieces[-1][:el],
ec: pieces[-1][:ec]
}
end
# assign is a parser event that represents assigning something to a
# variable or constant. It accepts as arguments the left side of the
# expression before the equals sign and the right side of the expression.
def on_assign(left, right)
left.merge(
type: :assign,
body: [left, right],
el: right[:el],
ec: right[:ec]
)
end
# assoc_new is a parser event that contains a key-value pair within a
# hash. It is a child event of either an assoclist_from_args or a
# bare_assoc_hash.
def on_assoc_new(key, value)
{
type: :assoc_new,
body: [key, value],
sl: key[:sl],
sc: key[:sc],
el: value[:el],
ec: value[:ec]
}
end
# assoc_splat is a parser event that represents splatting a value into a
# hash (either a hash literal or a bare hash in a method call).
def on_assoc_splat(contents)
find_scanner_event(:@op, '**').merge!(
type: :assoc_splat,
body: [contents],
el: contents[:el],
ec: contents[:ec]
)
end
# assoclist_from_args is a parser event that contains a list of all of the
# associations inside of a hash literal. Its parent node is always a hash.
# It accepts as an argument an array of assoc events (either assoc_new or
# assoc_splat).
def on_assoclist_from_args(assocs)
{
type: :assoclist_from_args,
body: assocs,
sl: assocs[0][:sl],
sc: assocs[0][:sc],
el: assocs[-1][:el],
ec: assocs[-1][:ec]
}
end
# bare_assoc_hash is a parser event that represents a hash of contents
# being passed as a method argument (and therefore has omitted braces). It
# accepts as an argument an array of assoc events (either assoc_new or
# assoc_splat).
def on_bare_assoc_hash(assoc_news)
{
type: :bare_assoc_hash,
body: assoc_news,
sl: assoc_news[0][:sl],
sc: assoc_news[0][:sc],
el: assoc_news[-1][:el],
ec: assoc_news[-1][:ec]
}
end
# begin is a parser event that represents the beginning of a begin..end chain.
# It includes a bodystmt event that has all of the consequent clauses.
def on_begin(bodystmt)
beging = find_scanner_event(:@kw, 'begin')
ec =
if bodystmt[:body][1..-1].any?
bodystmt[:ec]
else
find_scanner_event(:@kw, 'end')[:ec]
end
bodystmt.bind(beging[:ec], ec)
beging.merge!(
type: :begin,
body: [bodystmt],
el: bodystmt[:el],
ec: bodystmt[:ec]
)
end
# binary is a parser event that represents a binary operation between two
# values.
def on_binary(left, oper, right)
# On most Ruby implementations, oper is a Symbol that represents that
# operation being performed. For instance in the example `1 < 2`, the `oper`
# object would be `:<`. However, on JRuby, it's an `@op` node, so here we're
# going to explicitly convert it into the same normalized form.
oper = scanner_events.delete(oper)[:body] unless oper.is_a?(Symbol)
{
type: :binary,
body: [left, oper, right],
sl: left[:sl],
sc: left[:sc],
el: right[:el],
ec: right[:ec]
}
end
# block_var is a parser event that represents the parameters being passed to
# block. Effectively they're everything contained within the pipes.
def on_block_var(params, locals)
index =
scanner_events.rindex do |event|
event[:type] == :@op && %w[| ||].include?(event[:body]) &&
event[:sc] < params[:sc]
end
beging = scanner_events[index]
ending = scanner_events[-1]
{
type: :block_var,
body: [params, locals],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# blockarg is a parser event that represents defining a block variable on
# a method definition.
def on_blockarg(ident)
find_scanner_event(:@op, '&').merge!(
type: :blockarg,
body: [ident],
el: ident[:el],
ec: ident[:ec]
)
end
# bodystmt can't actually determine its bounds appropriately because it
# doesn't necessarily know where it started. So the parent node needs to
# report back down into this one where it goes.
class BodyStmt < SimpleDelegator
def bind(sc, ec)
merge!(sc: sc, ec: ec)
parts = self[:body]
# Here we're going to determine the bounds for the stmts
consequent = parts[1..-1].compact.first
self[:body][0].bind(sc, consequent ? consequent[:sc] : ec)
# Next we're going to determine the rescue clause if there is one
if parts[1]
consequent = parts[2..-1].compact.first
self[:body][1].bind_end(consequent ? consequent[:sc] : ec)
end
end
end
# bodystmt is a parser event that represents all of the possible combinations
# of clauses within the body of a method or block.
def on_bodystmt(stmts, rescued, ensured, elsed)
BodyStmt.new(
type: :bodystmt,
body: [stmts, rescued, ensured, elsed],
sl: lineno,
sc: char_pos,
el: lineno,
ec: char_pos
)
end
# brace_block is a parser event that represents passing a block to a
# method call using the {..} operators. It accepts as arguments an
# optional block_var event that represents any parameters to the block as
# well as a stmts event that represents the statements inside the block.
def on_brace_block(block_var, stmts)
beging = find_scanner_event(:@lbrace)
ending = find_scanner_event(:@rbrace)
stmts.bind((block_var || beging)[:ec], ending[:sc])
{
type: :brace_block,
body: [block_var, stmts],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# break is a parser event that represents using the break keyword. It
# accepts as an argument an args or args_add_block event that contains all
# of the arguments being passed to the break.
def on_break(args_add_block)
beging = find_scanner_event(:@kw, 'break')
# You can hit this if you are passing no arguments to break but it has a
# comment right after it. In that case we can just use the location
# information straight from the keyword.
if args_add_block[:type] == :args
return beging.merge!(type: :break, body: [args_add_block])
end
beging.merge!(
type: :break,
body: [args_add_block],
el: args_add_block[:el],
ec: args_add_block[:ec]
)
end
# call is a parser event representing a method call with no arguments. It
# accepts as arguments the receiver of the method, the operator being used
# to send the method (., ::, or &.), and the value that is being sent to
# the receiver (which can be another nested call as well).
#
# There is one esoteric syntax that comes into play here as well. If the
# sending argument to this method is the symbol :call, then it represents
# calling a lambda in a very odd looking way, as in:
#
# foo.(1, 2, 3)
#
def on_call(receiver, oper, sending)
ending = sending
if sending == :call
ending = oper
# Special handling here for Ruby <= 2.5 because the oper argument to this
# method wasn't a parser event here it was just a plain symbol.
ending = receiver if RUBY_MAJOR <= 2 && RUBY_MINOR <= 5
end
{
type: :call,
body: [receiver, oper, sending],
sl: receiver[:sl],
sc: receiver[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# case is a parser event that represents the beginning of a case chain.
# It accepts as arguments the switch of the case and the consequent
# clause.
def on_case(switch, consequent)
beging =
if event = find_scanner_event(:@kw, 'case', consume: false)
scanner_events.delete(event).merge!(type: :case)
else
keyword = find_scanner_event(:@kw, 'in', consume: false)
switch.merge(type: :rassign, keyword: keyword)
end
beging.merge!(
body: [switch, consequent],
el: consequent[:el],
ec: consequent[:ec]
)
end
# Finds the next position in the source string that begins a statement. This
# is used to bind statements lists and make sure they don't include a
# preceding comment. For example, we want the following comment to be attached
# to the class node and not the statement node:
#
# class Foo # :nodoc:
# ...
# end
#
# By finding the next non-space character, we can make sure that the bounds of
# the statement list are correct.
def find_next_statement_start(position)
remaining = source[position..-1]
if remaining.sub(/\A +/, '')[0] == '#'
return position + remaining.index("\n")
end
position
end
# class is a parser event that represents defining a class. It accepts as
# arguments the name of the class, the optional name of the superclass,
# and the bodystmt event that represents the statements evaluated within
# the context of the class.
def on_class(const, superclass, bodystmt)
beging = find_scanner_event(:@kw, 'class')
ending = find_scanner_event(:@kw, 'end')
bodystmt.bind(
find_next_statement_start((superclass || const)[:ec]),
ending[:sc]
)
{
type: :class,
body: [const, superclass, bodystmt],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# command is a parser event representing a method call with arguments and
# no parentheses. It accepts as arguments the name of the method and the
# arguments being passed to the method.
def on_command(ident, args)
{
type: :command,
body: [ident, args],
sl: ident[:sl],
sc: ident[:sc],
el: args[:el],
ec: args[:ec]
}
end
# command_call is a parser event representing a method call on an object
# with arguments and no parentheses. It accepts as arguments the receiver
# of the method, the operator being used to send the method, the name of
# the method, and the arguments being passed to the method.
def on_command_call(receiver, oper, ident, args)
ending = args || ident
{
type: :command_call,
body: [receiver, oper, ident, args],
sl: receiver[:sl],
sc: receiver[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# A const_path_field is a parser event that is always the child of some
# kind of assignment. It represents when you're assigning to a constant
# that is being referenced as a child of another variable. For example:
#
# foo::X = 1
#
def on_const_path_field(left, const)
{
type: :const_path_field,
body: [left, const],
sl: left[:sl],
sc: left[:sc],
el: const[:el],
ec: const[:ec]
}
end
# A const_path_ref is a parser event that is a very similar to
# const_path_field except that it is not involved in an assignment. It
# looks like the following example:
#
# foo::X
#
def on_const_path_ref(left, const)
{
type: :const_path_ref,
body: [left, const],
sl: left[:sl],
sc: left[:sc],
el: const[:el],
ec: const[:ec]
}
end
# A const_ref is a parser event that represents the name of the constant
# being used in a class or module declaration. In the following example it
# is the @const scanner event that has the contents of Foo.
#
# class Foo; end
#
def on_const_ref(const)
const.merge(type: :const_ref, body: [const])
end
# A def is a parser event that represents defining a regular method on the
# current self object. It accepts as arguments the ident (the name of the
# method being defined), the params (the parameter declaration for the
# method), and a bodystmt node which represents the statements inside the
# method. As an example, here are the parts that go into this:
#
# def foo(bar) do baz end
# │ │ │
# │ │ └> bodystmt
# │ └> params
# └> ident
#
# You can also have single-line methods since Ruby 3.0+, which have slightly
# different syntax but still flow through this method. Those look like:
#
# def foo = bar
# | |
# | └> stmt
# └> ident
#
def on_def(ident, params, bodystmt)
# Make sure to delete this scanner event in case you're defining something
# like def class which would lead to this being a kw and causing all kinds
# of trouble
scanner_events.delete(ident)
# Find the beginning of the method definition, which works for single-line
# and normal method definitions.
beging = find_scanner_event(:@kw, 'def')
# If we don't have a bodystmt node, then we have a single-line method
if bodystmt[:type] != :bodystmt
return(
{
type: :defsl,
body: [ident, params, bodystmt],
sl: beging[:sl],
sc: beging[:sc],
el: bodystmt[:el],
ec: bodystmt[:ec]
}
)
end
if params[:type] == :params && !params[:body].any?
location = ident[:ec]
params.merge!(sc: location, ec: location)
end
ending = find_scanner_event(:@kw, 'end')
bodystmt.bind(find_next_statement_start(params[:ec]), ending[:sc])
{
type: :def,
body: [ident, params, bodystmt],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# A defs is a parser event that represents defining a singleton method on
# an object. It accepts the same arguments as the def event, as well as
# the target and operator that on which this method is being defined. As
# an example, here are the parts that go into this:
#
# def foo.bar(baz) do baz end
# │ │ │ │ │
# │ │ │ │ │
# │ │ │ │ └> bodystmt
# │ │ │ └> params
# │ │ └> ident
# │ └> oper
# └> target
#
def on_defs(target, oper, ident, params, bodystmt)
# Make sure to delete this scanner event in case you're defining something
# like def class which would lead to this being a kw and causing all kinds
# of trouble
scanner_events.delete(ident)
if params[:type] == :params && !params[:body].any?
location = ident[:ec]
params.merge!(sc: location, ec: location)
end
beging = find_scanner_event(:@kw, 'def')
ending = find_scanner_event(:@kw, 'end')
bodystmt.bind(find_next_statement_start(params[:ec]), ending[:sc])
{
type: :defs,
body: [target, oper, ident, params, bodystmt],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end
# A defined node represents the rather unique defined? operator. It can be
# used with and without parentheses. If they're present, we use them to
# determine our bounds, otherwise we use the value that's being passed to
# the operator.
def on_defined(value)
beging = find_scanner_event(:@kw, 'defined?')
paren = source[beging[:ec]...value[:sc]].include?('(')
ending = paren ? find_scanner_event(:@rparen) : value
beging.merge!(
type: :defined,
body: [value],
el: ending[:el],
ec: ending[:ec]
)
end
# do_block is a parser event that represents passing a block to a method
# call using the do..end keywords. It accepts as arguments an optional
# block_var event that represents any parameters to the block as well as
# a bodystmt event that represents the statements inside the block.
def on_do_block(block_var, bodystmt)
beging = find_scanner_event(:@kw, 'do')
ending = find_scanner_event(:@kw, 'end')
bodystmt.bind((block_var || beging)[:ec], ending[:sc])
{
type: :do_block,
body: [block_var, bodystmt],
sl: beging[:sl],
sc: beging[:sc],
el: ending[:el],
ec: ending[:ec]
}
end