-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtransform.rb
More file actions
1748 lines (1570 loc) · 62 KB
/
Copy pathtransform.rb
File metadata and controls
1748 lines (1570 loc) · 62 KB
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
require 'ast'
require 'scanner'
#
# Parts of the compiler class that mainly transform the source tree
#
# Ideally these will be broken out of the Compiler class at some point
# For now they're moved here to start refactoring.
#
class Compiler
include AST
# Rewrite pattern matching :in clauses into :when clauses with conditions
# Transforms [:in, [:pattern, ConstName, [:pattern_key, :a], ...], body]
# Into: [:when, condition_with_bindings, body]
#
# IMPORTANT: This runs in compile() AFTER preprocess(), which means it runs AFTER
# find_vars/rewrite_env_vars. Pattern-bound variables won't be identified for closure
# capture, so they won't work correctly in nested closures.
# See rewrite_env_vars() and docs/KNOWN_ISSUES.md for details.
def rewrite_pattern_matching(exp)
# First pass: Find and wrap case statements containing :in nodes
exp.depth_first do |e|
next :skip if e[0] == :sexp
if e[0] == :case && e.size >= 3 && e[2].is_a?(Array)
# Check if any branch is an :in node
has_in = e[2].any? { |branch| branch.is_a?(Array) && branch[0] == :in }
if has_in
value_expr = e[1]
case_branches = e[2]
else_clause = e[3] if e.size > 3
# Create new case that uses __case_value
new_case = [:case, :__case_value, case_branches]
new_case << else_clause if else_clause
# Wrap in :let with proper :do block structure:
# [:let, [:__case_value], [:do, assign, case_stmt]]
e[0] = :let
e[1] = [:__case_value]
e[2] = [:do,
[:assign, :__case_value, value_expr],
new_case
]
# Remove any extra elements
e.slice!(3..-1) if e.size > 3
# Skip further processing of this node to avoid infinite loop
next :skip
end
end
end
# Second pass: Transform :in nodes to :when nodes
exp.depth_first do |e|
next :skip if e[0] == :sexp
# Find :in nodes with bare name patterns (e.g., in a)
if e[0] == :in && e[1].is_a?(Symbol)
var_name = e[1]
body = e[2]
# Transform to: when (var_name = __case_value; true) then body end
# This always matches and binds the value to the variable
binding = [:do, [:assign, var_name, :__case_value], [:sexp, true]]
# Replace :in with :when
e[0] = :when
e[1] = binding
# e[2] remains the body
end
# Find :in nodes with :as_pattern (e.g., in Integer => n)
if e[0] == :in && e[1].is_a?(Array) && e[1][0] == :as_pattern
as_pattern = e[1]
type_name = as_pattern[1]
var_name = as_pattern[2]
body = e[2]
# Transform to: when (__case_value.is_a?(TypeName) && (var = __case_value; true))
type_check = [:callm, :__case_value, :is_a?, [type_name]]
binding = [:do, [:assign, var_name, :__case_value], [:sexp, true]]
condition = [:and, type_check, binding]
# Replace :in with :when
e[0] = :when
e[1] = condition
# e[2] remains the body
end
# Find :in nodes with :pattern children (constant-qualified patterns)
if e[0] == :in && e[1].is_a?(Array) && e[1][0] == :pattern
pattern = e[1]
const_name = pattern[1]
pattern_elements = pattern[2..-1]
body = e[2]
# Build variable bindings and value checks
bindings = []
checks = []
pattern_elements.each do |elem|
if elem.is_a?(Array) && elem[0] == :pattern_key
# Keyword shorthand: a: binds key :a to variable a
var_name = elem[1]
# Create: var_name = __case_value[:var_name]
bindings << [:assign, var_name, [:callm, :__case_value, :[], [[:sexp, var_name.inspect.to_sym]]]]
elsif elem.is_a?(Array) && elem[0] == :pair
# Full key-value: a: 0 checks __case_value[:a] == 0
key = elem[1]
expected_value = elem[2]
# Create: __case_value[key] == expected_value
checks << [:eq, [:callm, :__case_value, :[], [key]], expected_value]
elsif elem.is_a?(Array) && elem[0] == :hash_splat
# Hash splat: ** or **rest
# In pattern matching, this allows additional keys beyond those checked
# If a variable is provided, it should capture remaining keys
# For now, we just ignore it (allows extra keys by default)
# TODO: Implement proper rest binding if variable name provided
rest_var = elem[1]
# Future: bind remaining keys to rest_var if needed
end
end
# Create condition: __case_value.is_a?(ConstName) && checks && bindings
type_check = [:callm, :__case_value, :is_a?, [const_name]]
condition = type_check
# Add value checks
checks.each do |check|
condition = [:and, condition, check]
end
# Add bindings
if !bindings.empty?
binding_block = [:do] + bindings + [[:sexp, true]]
condition = [:and, condition, binding_block]
end
# Replace :in with :when
e[0] = :when
e[1] = condition
# e[2] remains the body
end
# Find :in nodes with bare :hash patterns (e.g., in a: 1, b: 2)
if e[0] == :in && e[1].is_a?(Array) && e[1][0] == :hash
hash_pattern = e[1]
pairs = hash_pattern[1..-1]
body = e[2]
# Build conditions for each key-value pair
# Each pair is [:pair, [:sexp, :key], value]
checks = []
pairs.each do |pair|
key = pair[1]
expected_value = pair[2]
# Create: __case_value[key] == expected_value
checks << [:eq, [:callm, :__case_value, :[], [key]], expected_value]
end
# Combine all checks with && (and)
# Start with type check: __case_value.is_a?(Hash)
type_check = [:callm, :__case_value, :is_a?, [:Hash]]
condition = type_check
checks.each do |check|
condition = [:and, condition, check]
end
# Replace :in with :when
e[0] = :when
e[1] = condition
# e[2] remains the body
end
# Handle bare hash splat pattern: in ** or in **rest
# This matches any hash
if e[0] == :in && e[1].is_a?(Array) && e[1][0] == :hash_splat
hash_splat = e[1]
rest_var = hash_splat[1]
body = e[2]
# Match any hash
type_check = [:callm, :__case_value, :is_a?, [:Hash]]
condition = type_check
# If rest_var is provided, bind it to the matched hash
if rest_var
binding = [:do, [:assign, rest_var, :__case_value], [:sexp, true]]
condition = [:and, condition, binding]
end
# Replace :in with :when
e[0] = :when
e[1] = condition
# e[2] remains the body
end
end
exp
end
# For 'bare' blocks, or "Proc" objects created with 'proc', we
# replace the standard return with ":preturn", which ensures the
# return is forced to exit the defining scope, instead of "just"
# exiting the block itself and then Proc#call.
#
# FIXME: Note that this does *not* attempt to detect an "escaped"
# block that is returning outside of where it should. At some point
# we need to add a way of handling this (e.g. MRI raises a LocalJumpError),
# but that is trickier to do in a sane way (one option would be
# to keep track of any blocks that get defined, and for any return
# from a scope that have defined this to mark the created "Proc"
# objets accordingly).
#
def rewrite_proc_return(exp)
exp.depth_first do |e|
next :skip if e[0] == :sexp
if e[0] == :return
e[0] = :preturn
end
end
exp
end
# This replaces the old lambda handling with a rewrite.
# The advantage of handling it as a rewrite phase is that it's
# much easier to debug - it can be turned on and off to
# see how the code gets transformed.
def rewrite_lambda(exp)
seen = false
exp.depth_first do |e|
next :skip if e[0] == :sexp
if e[0] == :lambda || e[0] == :proc
seen = true
# args can be an array, :block symbol, or nil
args = e[1]
args = E[] if !args || args == :block
body = e[2] || nil
rescue_clause = e[3] # May be nil
ensure_clause = e[4] # May be nil
if e[0] == :proc && body
body = rewrite_proc_return(body)
end
# If there's a rescue or ensure clause, wrap the body in a block node
# This mirrors how begin/rescue/ensure works
# Block structure: [:block, args, body, rescue_clause, ensure_clause]
if rescue_clause || ensure_clause
body = E[:block, E[], body, rescue_clause, ensure_clause]
end
# Calculate arity correctly:
# - Count required params (those without defaults)
# - If any optional params exist, arity is -(required_count + 1)
# - Otherwise arity is just the count
required_count = 0
has_optional = false
args.each do |a|
if a.is_a?(Array)
if a[1] == :default && a[2] != :nil
# Has a non-nil default - optional parameter
has_optional = true
elsif [:rest, :keyrest].include?(a[1])
# Splat or keyword rest - makes it variable arity
has_optional = true
elsif [:block].include?(a[1])
# Block parameter doesn't affect arity
else
required_count += 1
end
else
required_count += 1
end
end
len = has_optional ? -(required_count + 1) : required_count
# Handle args that might already have default values from parser
# Parser returns either symbols or [name, :default, value] tuples
normalized_args = args.collect do |a|
if a.is_a?(Array) && a[1] == :default
# Already in [name, :default, value] format
a
elsif a.is_a?(Array) && [:rest, :block, :keyrest, :key, :keyreq].include?(a[1])
# Special parameter types (splat, block, keyword args, etc.) - don't add default
a
elsif a.is_a?(Array) && a[0] == :destruct
# Destructuring parameters [:destruct, :a, :b] - don't add default
a
else
# Simple symbol - wrap it with default :nil
[a, :default, :nil]
end
end
e.replace(
E[:do,
[:assign, [:index, :__env__,0], [:stackframe]],
[:assign, :__tmp_proc,
[:defun, "__lambda_#{@e.get_local[1..-1]}",
[:self,:__closure__,:__env__] + normalized_args,
body
]
],
# FIXME: Compiler bug: This works
[:sexp, [:call, :__new_proc, [:__tmp_proc, :__env__, :self, len, :__closure__]]]
# But this crashes:
#E[exp.position,:sexp, E[:call, :__new_proc, E[:__tmp_proc, :__env__, :self, len]]]
]
)
end
end
return seen
end
# Convert :ternalt to :pair for method call keyword arguments
# In method calls, :ternalt nodes need to be converted to :pair nodes
# Hash/array contexts are handled by treeoutput.rb, but method args are not
# Ternary operators (?:) use :ternalt inside :ternif and should NOT be converted
# foo(a: 42) => [:call, [:foo, [:ternalt, :a, 42]]] => [:call, [:foo, [:pair, [:sexp, :a], 42]]]
# foo(a:) => [:call, [:foo, [:ternalt, :a, nil]]] => [:call, [:foo, [:pair, [:sexp, :a], :a]]]
def convert_ternalt_in_calls(exp)
# Walk the tree and convert :ternalt to :pair only inside :call and :callm nodes
exp.depth_first do |e|
next :skip if e[0] == :sexp
# Only process :call and :callm nodes to convert their :ternalt arguments
if e.is_a?(Array) && (e[0] == :call || e[0] == :callm)
# Get arguments array index (different for :call vs :callm)
args_index = e[0] == :call ? 2 : 3
next unless e[args_index].is_a?(Array)
# e[args_index] is the arguments array
e[args_index].each do |arg|
if arg.is_a?(Array) && arg[0] == :ternalt
# Convert [:ternalt, key, value] to [:pair, [:sexp, :key], value]
key = arg[1]
value = arg[2]
# If no value provided (keyword argument shorthand), use the key name as the value
if value.nil?
value = key
end
# key must be a symbol for keyword arguments
if key.is_a?(Symbol)
arg.replace(E[:pair, E[:sexp, key.inspect.to_sym], value])
end
end
end
end
end
end
# Group keyword argument :pair and :hash_splat nodes into a :hash in method calls
# After convert_ternalt_in_calls, we have [:pair, ...] nodes that need to be grouped
# foo(a: 1, b: 2) => [:call, :foo, [[:pair, ...], [:pair, ...]]]
# becomes => [:call, :foo, [[:hash, [:pair, ...], [:pair, ...]]]]
# foo(x, a: 1) => [:call, :foo, [x, [:pair, ...]]]
# becomes => [:call, :foo, [x, [:hash, [:pair, ...]]]]
# foo(**h) => [:call, :foo, [[:hash_splat, h]]]
# becomes => [:call, :foo, [h]] (just use h directly as hash)
def group_keyword_arguments(exp)
exp.depth_first do |e|
next :skip if e[0] == :sexp
# Only process :call and :callm nodes
if e.is_a?(Array) && (e[0] == :call || e[0] == :callm)
args_index = e[0] == :call ? 2 : 3
next unless e[args_index].is_a?(Array)
args = e[args_index]
new_args = []
pairs_and_splats = []
args.each do |arg|
if arg.is_a?(Array) && (arg[0] == :pair || arg[0] == :hash_splat)
pairs_and_splats << arg
else
# Non-keyword argument - flush any accumulated pairs
if !pairs_and_splats.empty?
new_args << E[:hash, *pairs_and_splats]
pairs_and_splats = []
end
new_args << arg
end
end
# Flush remaining pairs/splats at end
if !pairs_and_splats.empty?
new_args << E[:hash, *pairs_and_splats]
end
# Replace args array
e[args_index] = new_args
end
end
end
# Rewrite defined? operator to return appropriate string or false
# This must happen BEFORE rewrite_strconst so strings get properly handled
def rewrite_defined(exp)
exp.depth_first do |e|
next :skip if e[0] == :sexp
if e.is_a?(Array) && e[0] == :"defined?"
arg = e[1]
result = nil
# Analyze the argument to determine its type
if arg.is_a?(Array)
case arg[0]
# Assignment operators - all map to "assignment"
when :assign, :massign, :iasgn, :op_asgn, :or_asgn, :and_asgn,
:mul_assign, :div_assign, :mod_assign, :pow_assign,
:and_bitwise_assign, :or_bitwise_assign, :xor_assign,
:shl_assign, :shr_assign
result = "assignment"
# For other cases, return false
else
STDERR.puts "Warning: defined? for #{arg[0].inspect} not implemented, returning false"
result = false
end
elsif arg.is_a?(Symbol)
# For variables, return false for now
STDERR.puts "Warning: defined? for variable #{arg.inspect} not implemented, returning false"
result = false
else
STDERR.puts "Warning: defined? for #{arg.inspect} not implemented, returning false"
result = false
end
# Replace the defined? node with the result
# rewrite_strconst will handle string constant conversion
if result == false
e.replace(E[:false])
else
e.replace(E[result])
end
end
end
end
# Re-write string constants outside %s() to
# %s(call __get_string [original string constant])
def rewrite_strconst(exp)
exp.depth_first do |e|
next :skip if e[0] == :sexp
is_call = e[0] == :call || e[0] == :callm
e.each_with_index do |s,i|
if s.is_a?(String)
lab = @string_constants[s]
if !lab
lab = @e.get_local
@string_constants[s] = lab
end
e[i] = E[:sexp, E[:call, :__get_string, lab.to_sym]]
# FIXME: This is a horrible workaround to deal with a parser
# inconsistency that leaves calls with a single argument with
# the argument "bare" if it's not an array, which breaks with
# this rewrite.
e[i] = E[e[i]] if is_call && i > 1
end
end
end
end
def symbol_name(v)
s = "__S_#{clean_method_name(v)}"
s.to_sym
end
# Rewrite a numeric constant outside %s() to
# %s(sexp (__int num))
def rewrite_integer_constant(exp)
exp.depth_first do |e|
next :skip if e[0] == :sexp
is_call = e[0] == :call || e[0] == :callm
# FIXME: e seems to get aliased by v
ex = e
e.each_with_index do |v,i|
if v.is_a?(Integer)
ex[i] = E[:sexp, v*2+1]
# FIXME: This is a horrible workaround to deal with a parser
# inconsistency that leaves calls with a single argument with
# the argument "bare" if it's not an array, which breaks with
# this rewrite.
ex[i] = E[ex[i]] if is_call && i > 1
end
end
end
end
# Rewrite a symbol constant outside %s() to
# %s(sexp __[num]) and output a list later
def rewrite_symbol_constant(exp)
@symbols = Set[]
exp.depth_first do |e|
next :skip if e[0] == :sexp
is_call = e[0] == :call || e[0] == :callm
# FIXME: e seems to get aliased by v
ex = e
e.each_with_index do |v,i|
name = v.to_s
if v.is_a?(Symbol) && name[0] == ?:
#STDERR.puts v.inspect
if !@symbols.member?(v)
@symbols << name[1..-1]
end
ex[i] = E[:sexp, symbol_name(name[1..-1])]
# FIXME: This is a horrible workaround to deal with a parser
# inconsistency that leaves calls with a single argument with
# the argument "bare" if it's not an array, which breaks with
# this rewrite.
ex[i] = E[ex[i]] if is_call && i > 1
end
end
end
end
# Rewrite operators that should be treated as method calls
# so that e.g. (+ 1 2) is turned into (callm 1 + 2)
#
def rewrite_operators(exp)
exp.depth_first do |e|
next :skip if e[0] == :sexp
if e[0].is_a?(Symbol) && OPER_METHOD.member?(e[0].to_s)
# Handle unary minus specially: [:-, operand] => [:callm, 0, :-, [operand]]
if e[0] == :- && e.length == 2
e[3] = E[e[1]] # args = [operand]
e[2] = :- # method = :-
e[1] = E[:sexp, 1] # object = 0 (tagged as fixnum: 0*2+1 = 1)
e[0] = :callm # op = :callm
# Handle unary plus: [:+, operand] => [:callm, operand, :+@, []]
elsif e[0] == :+ && e.length == 2
e[3] = E[] # args = []
e[2] = :+@ # method = :+@
e[1] = e[1] # object = operand
e[0] = :callm # op = :callm
else
e[3] = E[e[2]] if e[2]
e[2] = e[0]
e[0] = :callm
end
end
end
end
# 1. If I see an assign node, the variable on the left hand is defined
# for the remainder of this scope and on any sub-scope.
# 2. If a sub-scope is lambda, any variable that is _used_ within it
# should be transferred from outer active scopes to env.
# 3. Once all nodes for the current scope have been processed, a :let
# node should be added with the remaining variables (after moving to
# env).
# 4. If this is the outermost node, __env__ should be added to the let.
def in_scopes(scopes, n)
scopes.reverse.collect {|s| s.member?(n) ? s : nil}.compact
end
def is_special_name?(v)
# FIXME: This is/was broken because it'd prevent valid variable names
# like "eq" from being recognized. The proper fix to this is to type
# the AST properly, but for now this seems to be an improvement
#Compiler::Keywords.member?(v) ||
v == :nil || v == :self ||
v.to_s[0] == ?@ ||
v == :true || v == :false || v.to_s[0] < ?a
end
def push_var(scopes, env, v)
sc = in_scopes(scopes,v)
if sc.size == 0 && !env.member?(v) && !is_special_name?(v)
scopes[-1] << v
end
end
def find_vars_ary(ary, scopes, env, freq, in_lambda = false, in_assign = false, current_params = Set.new)
vars = []
ary.each do |e|
vars2, env2 = find_vars(e, scopes, env, freq, in_lambda, in_assign, current_params)
vars += vars2
env += env2
end
return vars
end
# FIXME: Rewrite using "depth first"?
def find_vars(e, scopes, env, freq, in_lambda = false, in_assign = false, current_params = Set.new)
return [],env, false if !e
e = [e] if !e.is_a?(Array)
e.each do |n|
if n.is_a?(Array)
if n[0] == :assign
vars1, env1 = find_vars(n[1], scopes + [Set.new],env, freq, in_lambda, true, current_params)
vars2, env2 = find_vars(n[2..-1], scopes + [Set.new],env, freq, in_lambda, false, current_params)
env = env1 + env2
vars = vars1+vars2
vars.each {|v| push_var(scopes,env,v) if !is_special_name?(v) }
elsif n[0] == :lambda || n[0] == :proc
# Extract parameter names (handle arrays like [:param, default])
params_raw = n[1] || []
param_names = params_raw.is_a?(Array) ? params_raw.collect { |p| p.is_a?(Array) ? p[0] : p } : []
param_scope = Set.new(param_names)
# Pass a copy of param_scope as current_params to prevent it from being modified
vars, env2= find_vars(n[2], scopes + [param_scope], env, freq, true, false, Set.new(param_names))
# Clean out proc/lambda arguments from the %s(let ..) and the environment we're building
# Use param_names (symbols) not n[1] (which may contain [:param, :default, value] tuples)
vars -= param_names
# Don't remove params from env2 - if they're captured by nested lambdas,
# they need to propagate up. The rewrite_env_vars will add initialization.
env += env2
n[2] = E[n.position,:let, vars, *n[2]] if n[2]
else
if n[0] == :callm
# Wrap receiver if it's an array (AST node) to prevent element-by-element iteration
receiver = n[1].is_a?(Array) ? [n[1]] : n[1]
vars, env = find_vars(receiver, scopes, env, freq, in_lambda, false, current_params)
if n[3]
nodes = n[3]
nodes = [nodes] if !nodes.is_a?(Array)
nodes.each do |n2|
vars2, env2 = find_vars([n2], scopes+[Set.new], env, freq, in_lambda, false, current_params)
vars += vars2
env += env2
end
end
# If a block is provided, we need to find variables there too
if n[4]
vars3, env3 = find_vars([n[4]], scopes, env, freq, in_lambda, false, current_params)
vars += vars3
env += env3
end
elsif n[0] == :call
# Wrap receiver if it's an array (AST node) to prevent element-by-element iteration
receiver = n[1].is_a?(Array) ? [n[1]] : n[1]
vars, env = find_vars(receiver, scopes, env, freq, in_lambda, false, current_params)
if n[2]
nodes = n[2]
nodes = [nodes] if !nodes.is_a?(Array)
nodes.each do |n2|
vars2, env2 = find_vars([n2], scopes+[Set.new], env, freq, in_lambda, false, current_params)
vars += vars2
env += env2
end
end
if n[3]
vars2, env2 = find_vars([n[3]], scopes, env, freq, in_lambda, false, current_params)
vars += vars2
env += env2
end
elsif n[0] == :deref
# [:deref, parent, const_name] - only process parent (n[1]), not const_name (n[2])
# Const names in deref expressions are not variable references
# But parent could be an expression or variable that needs processing
parent = n[1].is_a?(Array) ? [n[1]] : n[1]
vars, env = find_vars(parent, scopes, env, freq, in_lambda, false, current_params)
else
vars, env = find_vars(n[1..-1], scopes, env, freq, in_lambda, false, current_params)
end
vars.each {|v| push_var(scopes,env,v); }
end
elsif n.is_a?(Symbol)
sc = in_scopes(scopes[0..-2],n)
freq[n] += 1 if !is_special_name?(n)
if sc.size == 0
push_var(scopes,env,n) if in_assign && !is_special_name?(n)
elsif in_lambda && !current_params.include?(n)
sc.first.delete(n)
env << n
end
end
end
## FIXME: putting the below on one line breaks.
last_scope = scopes[-1]
a = last_scope.to_a
return a, env
# return scopes[-1].to_a, env
end
def rewrite_env_vars(exp, env)
seen = false
exp.depth_first do |e|
# Handle lambda/proc/defun/defm specially - process body but not parameter list
if e.is_a?(Array) && (e[0] == :lambda || e[0] == :proc || e[0] == :defun || e[0] == :defm)
# Get parameter list and body index
# defm is [:defm, name, [params], body] - params at index 2, body at index 3
# defun is [:defun, name, [params], body] - params at index 2, body at index 3
# lambda/proc is [:lambda, [params], body] - params at index 1, body at index 2
if e[0] == :defun || e[0] == :defm
param_list = e[2]
body_index = 3
else
param_list = e[1]
body_index = 2
end
# Extract parameter names (handle tuples like [:param, :default, :nil])
# Note: using .collect instead of .map (map doesn't exist in lib/core/array.rb)
# param_list can be an array or a symbol like :block (for block arguments)
params = param_list.is_a?(Array) ? param_list.collect { |p| p.is_a?(Array) ? p[0] : p } : []
# Find which parameters are in env (need initialization)
# Note: using reject with negation because .select doesn't exist in lib/core/array.rb
captured_params = params.reject { |p| !env.include?(p) }
# First, process the body to rewrite variable references
if e[body_index]
# FIXME: seen |= ... failed to compile
if rewrite_env_vars(e[body_index], env)
seen = true
end
end
# Then insert initialization for captured parameters (after rewriting)
# This way the RHS (parameter) won't be rewritten
if !captured_params.empty? && e[body_index]
# Note: using .collect instead of .map (map doesn't exist in lib/core/array.rb)
param_inits = captured_params.collect do |p|
idx = env.index(p)
E[:assign, E[:index, :__env__, idx], p]
end
# Insert at start of body
body = e[body_index]
if body.is_a?(Array) && body[0] == :let
# Insert after let declaration
e[body_index] = E[body.position, :let, body[1], *param_inits, *body[2..-1]]
elsif body.is_a?(Array) && body[0] == :do
e[body_index] = E[:do, *param_inits, *body[1..-1]]
else
e[body_index] = E[:do, *param_inits, body]
end
seen = true
end
next :skip # Don't let depth_first process children (would rewrite params)
end
# We need to expand "yield" before we rewrite.
# yield becomes __closure__.call(args...)
# Proc#call sets @env[1] to caller's stackframe for break support.
if e.is_a?(Array) && e[0] == :call && e[1] == :yield
seen = true
args = e[2] || []
e[0] = :callm
e[1] = :__closure__
e[2] = :call
e[3] = args.is_a?(Array) ? args : [args]
end
e.each_with_index do |ex, i|
# FIXME: This is necessary in order to avoid rewriting compiler keywords in some
# circumstances. The proper solution would be to introduce more types of
# expression nodes in the parser
# Skip AST operator symbols at index 0 - they're not variable references
next if i == 0 && (ex == :index || ex == :deref)
# Also skip :callm at position 0
next if i == 0 && ex == :callm
# Skip constant names in :deref nodes - they're constant/module names, not variables
# [:deref, parent, const_name] - only skip const_name (position 2), not parent (position 1)
# The parent might be a variable like: a = Object; a::CONST
next if i == 2 && e[0] == :deref && ex.is_a?(Symbol)
# Skip variable names in :pattern_key nodes - these will be handled by rewrite_pattern_matching
# [:pattern_key, var_name] - the var_name at position 1 should not be rewritten here
#
# IMPORTANT LIMITATION: This prevents literal [:index, :__env__, N] in assembly, but means
# pattern-bound variables won't be captured in __env__ for nested closures. This is because
# find_vars runs BEFORE rewrite_pattern_matching creates the pattern bindings.
#
# Example that FAILS with nested closures:
# 1.times { case {x: 42} in {x:}; 1.times { puts x }; end } # ERROR: undefined method 'x'
#
# Example that WORKS (single-level closure):
# 1.times { case {x: 42} in {x:}; puts x; end } # OK: prints 42
#
# See docs/KNOWN_ISSUES.md - "Pattern Matching with Nested Closures"
next if i == 1 && e[0] == :pattern_key && ex.is_a?(Symbol)
num = env.index(ex)
if num
seen = true
e[i] = E[:index, :__env__, num]
end
end
end
seen
end
# Visit the child nodes as follows:
# * On first assign, add to the set of variables
# * On descending into a :lambda block, add a new "scope"
# * On assign inside a block (:lambda node),
# * if the variable is found up the scope chain: Move it to the
# "env" set
# * otherwise add to the innermost scope
# Finally:
# * Insert :let nodes at the top and at all lambda nodes, if not empty
# (add an __env__ var to the topmost :let if the env set is not empty.
# * Insert an :env node immediately below the top :let node if the env
# set is not empty.
# Alt: insert (assign __env__ (array [no-of-env-entries]))
# Carry out a second pass:
# * For all _uses_ of a variable in the env set, rewrite to
# (index [position])
# => This can be done in a separate function.
def rewrite_let_env(exp)
exp.depth_first(:defm) do |e|
args = Set[*e[2].collect{|a| a.kind_of?(Array) ? a[0] : a}]
# Count number of "regular" arguments (non "rest", non "block")
# FIXME: There are cleaner ways, but in the interest of
# self-hosting, I'll do this for now.
ac = 0
e[2].each{|a| ac += 1 if ! a.kind_of?(Array)}
scopes = [args.dup] # We don't want "args" above to get updated
ri = -1
r = e[2][ri]
# FIXME: compiler bug; rest does not correctly get initialized to
# nil in the control flows where it's not assigned.
rest = nil
if r
if r[-1] != :rest
ri -= 1
r = e[2][ri]
end
if r && r[-1] == :rest
rest = r[0]
end
if rest
# FIXME: This is a hacky workaround
if rest != :__copysplat
r[0] = :__splat
end
end
end
# We use this to assign registers
freq = Hash.new(0)
s = Set.new
vars,env= find_vars(e[3],scopes,s, freq)
env << :__closure__
# For "preturn". see Compiler#compile_preturn
aenv = [:__stackframe__] + env.to_a
env << :__stackframe__
body = e[3]
prologue = nil
vars -= args.to_a
seen = false
if env.size > 0
seen = rewrite_env_vars(body, aenv)
notargs = env - args - [:__closure__]
# FIXME: Due to compiler bug
ex = e
extra_assigns = (env - notargs).to_a.collect do |a|
ai = aenv.index(a)
# FIXME: "ex" instead of "e" due to compiler bug.
E[ex.position, :assign, E[ex.position,:index, :__env__, ai], a]
end
prologue = [E[:sexp, E[:assign, :__env__, E[:call, :__alloc_env, aenv.size]]]]
if !extra_assigns.empty?
prologue.concat(extra_assigns)
end
if body.empty?
body = [:nil]
end
end
# FIXME: seen |= ... and seen = seen | ... both failed to compile.
if rewrite_lambda(body)
seen = true
end
if seen
vars << :__env__
vars << :__tmp_proc # Used in rewrite_lambda. Same caveats as for __env_
end
if rest && rest != :__copysplat
# rest might be a symbol or an indexed env access [:index, :__env__, N]
# after variable renaming. Extract the symbol if needed.
rest_sym = rest.is_a?(Symbol) ? rest : rest
rest_target = rest # Use original rest as assignment target
vars << rest_sym if rest_sym.is_a?(Symbol)
# FIXME: @bug Removing the E[] below causes segmentation fault
rest_func =
[E[:sexp,
# Corrected to take into account statically provided arguments.
[:assign, rest_target, [:__splat_to_Array, :__splat, [:sub, :numargs, ac]]]
]]
else
rest_func = nil
end
e[3] = []
if rest_func
e[3].concat(rest_func)
end
if seen && prologue # seen && prologue
e[3].concat(prologue)
end
# FIXME: When body is a single expression node (like :block from ensure),
# concat would flatten its contents incorrectly. Detect this case and wrap it.
# A single expression node has a keyword symbol as its first element.
if body.is_a?(Array) && body[0].is_a?(Symbol) && Compiler::Keywords.include?(body[0])
e[3] << body
else
e[3].concat(body)
end
# FIXME: Compiler bug: Changing the below to "if !vars.empty?" causes seg fault.
empty = vars.empty?
if empty == false
e[3] = E[e.position,:let, vars, *e[3]]
# We store the variables by descending frequency for future use in register
# allocation.
# FIXME: Compiler bug: -v fails.
e[3].extra[:varfreq] = freq.sort_by {|k,v| 0 - v }.collect{|a| a.first }
else
e[3] = E[e.position, :do, *e[3]]
end
# Recursively process the rewritten body to handle nested defms (e.g., eigenclass methods)
rewrite_let_env(e[3])
:skip
end
# Handle top-level procs (those not inside any :defm)
# These need environment setup and lambda rewriting too
# This fixes blocks like: [1].each { |x| puts x } at top level
if rewrite_lambda(exp)
# If we found any procs at top level, we need to set up the environment
# Look for the first :do or :let that wraps top-level code and add __env__ and __tmp_proc
if exp[0] == :do
# Check if __env__ is already declared (avoid duplicates)
has_env = false
exp.each do |e|
if e.is_a?(Array) && e[0] == :let && e[1].is_a?(Array) && e[1].include?(:__env__)
has_env = true
break
end
end
if !has_env
# Wrap the top-level code in a let that declares __env__, __tmp_proc, and __closure__
# __closure__ must be 0 at top level since there's no enclosing closure
# __tmp_proc is used by rewrite_lambda to hold the temporary proc
inner = exp[1..-1].dup
exp.clear
exp << :do
let_body = E[:do,
E[:sexp, E[:assign, :__closure__, 0]],
E[:sexp, E[:assign, :__env__, E[:call, :__alloc_env, 2]]]]
inner.each { |e| let_body << e }
exp << E[:let, [:__closure__, :__tmp_proc, :__env__], let_body]
end
end
end
end
def rewrite_range(exp)
exp.depth_first do |e|
if e[0] == :range
e.replace(E[:callm, :Range, :new, e[1..-1]])
elsif e[0] == :exclusive_range
# For exclusive range (...), pass true as third argument
e.replace(E[:callm, :Range, :new, e[1], e[2], true])
end
:next
end
end