-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathir.rb
More file actions
1395 lines (1141 loc) · 34.1 KB
/
ir.rb
File metadata and controls
1395 lines (1141 loc) · 34.1 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
# frozen_string_literal: true
module TRuby
module IR
# Base class for all IR nodes
class Node
attr_accessor :location, :type_info, :metadata
def initialize(location: nil)
@location = location
@type_info = nil
@metadata = {}
end
def accept(visitor)
visitor.visit(self)
end
def children
[]
end
def transform(&block)
block.call(self)
end
end
# Program - root node containing all top-level declarations
class Program < Node
attr_accessor :declarations, :source_file
def initialize(declarations: [], source_file: nil, **opts)
super(**opts)
@declarations = declarations
@source_file = source_file
end
def children
@declarations
end
end
# Type alias declaration: type Name = Definition
class TypeAlias < Node
attr_accessor :name, :definition, :type_params
def initialize(name:, definition:, type_params: [], **opts)
super(**opts)
@name = name
@definition = definition
@type_params = type_params
end
end
# Interface declaration
class Interface < Node
attr_accessor :name, :members, :extends, :type_params
def initialize(name:, members: [], extends: [], type_params: [], **opts)
super(**opts)
@name = name
@members = members
@extends = extends
@type_params = type_params
end
def children
@members
end
end
# Interface member (method signature)
class InterfaceMember < Node
attr_accessor :name, :type_signature, :optional
def initialize(name:, type_signature:, optional: false, **opts)
super(**opts)
@name = name
@type_signature = type_signature
@optional = optional
end
end
# Class declaration
class ClassDecl < Node
attr_accessor :name, :superclass, :implements, :type_params, :body, :instance_vars
def initialize(name:, superclass: nil, implements: [], type_params: [], body: [], instance_vars: [], **opts)
super(**opts)
@name = name
@superclass = superclass
@implements = implements
@type_params = type_params
@body = body
@instance_vars = instance_vars
end
def children
@body
end
end
# Instance variable declaration
class InstanceVariable < Node
attr_accessor :name, :type_annotation
def initialize(name:, type_annotation: nil, **opts)
super(**opts)
@name = name
@type_annotation = type_annotation
end
end
# Module declaration
class ModuleDecl < Node
attr_accessor :name, :body
def initialize(name:, body: [], **opts)
super(**opts)
@name = name
@body = body
end
def children
@body
end
end
# Method definition
class MethodDef < Node
attr_accessor :name, :params, :return_type, :body, :visibility, :type_params
def initialize(name:, params: [], return_type: nil, body: nil, visibility: :public, type_params: [], **opts)
super(**opts)
@name = name
@params = params
@return_type = return_type
@body = body
@visibility = visibility
@type_params = type_params
end
def children
[@body].compact
end
end
# Method parameter
class Parameter < Node
attr_accessor :name, :type_annotation, :default_value, :kind
# kind: :required, :optional, :rest, :keyrest, :block
def initialize(name:, type_annotation: nil, default_value: nil, kind: :required, **opts)
super(**opts)
@name = name
@type_annotation = type_annotation
@default_value = default_value
@kind = kind
end
end
# Block of statements
class Block < Node
attr_accessor :statements
def initialize(statements: [], **opts)
super(**opts)
@statements = statements
end
def children
@statements
end
end
# Variable assignment
class Assignment < Node
attr_accessor :target, :value, :type_annotation
def initialize(target:, value:, type_annotation: nil, **opts)
super(**opts)
@target = target
@value = value
@type_annotation = type_annotation
end
def children
[@value]
end
end
# Variable reference
class VariableRef < Node
attr_accessor :name, :scope
# scope: :local, :instance, :class, :global
def initialize(name:, scope: :local, **opts)
super(**opts)
@name = name
@scope = scope
end
end
# Method call
class MethodCall < Node
attr_accessor :receiver, :method_name, :arguments, :block, :type_args
def initialize(method_name:, receiver: nil, arguments: [], block: nil, type_args: [], **opts)
super(**opts)
@receiver = receiver
@method_name = method_name
@arguments = arguments
@block = block
@type_args = type_args
end
def children
([@receiver, @block] + @arguments).compact
end
end
# Literal values
class Literal < Node
attr_accessor :value, :literal_type
def initialize(value:, literal_type:, **opts)
super(**opts)
@value = value
@literal_type = literal_type
end
end
# Array literal
class ArrayLiteral < Node
attr_accessor :elements, :element_type
def initialize(elements: [], element_type: nil, **opts)
super(**opts)
@elements = elements
@element_type = element_type
end
def children
@elements
end
end
# Hash literal
class HashLiteral < Node
attr_accessor :pairs, :key_type, :value_type
def initialize(pairs: [], key_type: nil, value_type: nil, **opts)
super(**opts)
@pairs = pairs
@key_type = key_type
@value_type = value_type
end
end
# Hash pair (key => value)
class HashPair < Node
attr_accessor :key, :value
def initialize(key:, value:, **opts)
super(**opts)
@key = key
@value = value
end
def children
[@key, @value]
end
end
# Conditional (if/unless)
class Conditional < Node
attr_accessor :condition, :then_branch, :else_branch, :kind
# kind: :if, :unless, :ternary
def initialize(condition:, then_branch:, else_branch: nil, kind: :if, **opts)
super(**opts)
@condition = condition
@then_branch = then_branch
@else_branch = else_branch
@kind = kind
end
def children
[@condition, @then_branch, @else_branch].compact
end
end
# Case/when expression
class CaseExpr < Node
attr_accessor :subject, :when_clauses, :else_clause
def initialize(subject: nil, when_clauses: [], else_clause: nil, **opts)
super(**opts)
@subject = subject
@when_clauses = when_clauses
@else_clause = else_clause
end
def children
([@subject, @else_clause] + @when_clauses).compact
end
end
# When clause
class WhenClause < Node
attr_accessor :patterns, :body
def initialize(patterns:, body:, **opts)
super(**opts)
@patterns = patterns
@body = body
end
def children
[@body] + @patterns
end
end
# Loop constructs
class Loop < Node
attr_accessor :kind, :condition, :body
# kind: :while, :until, :loop
def initialize(kind:, body:, condition: nil, **opts)
super(**opts)
@kind = kind
@condition = condition
@body = body
end
def children
[@condition, @body].compact
end
end
# For loop / each iteration
class ForLoop < Node
attr_accessor :variable, :iterable, :body
def initialize(variable:, iterable:, body:, **opts)
super(**opts)
@variable = variable
@iterable = iterable
@body = body
end
def children
[@iterable, @body]
end
end
# Return statement
class Return < Node
attr_accessor :value
def initialize(value: nil, **opts)
super(**opts)
@value = value
end
def children
[@value].compact
end
end
# Binary operation
class BinaryOp < Node
attr_accessor :operator, :left, :right
def initialize(operator:, left:, right:, **opts)
super(**opts)
@operator = operator
@left = left
@right = right
end
def children
[@left, @right]
end
end
# Unary operation
class UnaryOp < Node
attr_accessor :operator, :operand
def initialize(operator:, operand:, **opts)
super(**opts)
@operator = operator
@operand = operand
end
def children
[@operand]
end
end
# Type cast / assertion
class TypeCast < Node
attr_accessor :expression, :target_type, :kind
# kind: :as, :assert
def initialize(expression:, target_type:, kind: :as, **opts)
super(**opts)
@expression = expression
@target_type = target_type
@kind = kind
end
def children
[@expression]
end
end
# Type guard (is_a?, respond_to?)
class TypeGuard < Node
attr_accessor :expression, :type_check, :narrowed_type
def initialize(expression:, type_check:, narrowed_type: nil, **opts)
super(**opts)
@expression = expression
@type_check = type_check
@narrowed_type = narrowed_type
end
def children
[@expression]
end
end
# Lambda/Proc definition
class Lambda < Node
attr_accessor :params, :body, :return_type
def initialize(body:, params: [], return_type: nil, **opts)
super(**opts)
@params = params
@body = body
@return_type = return_type
end
def children
[@body]
end
end
# Begin/rescue/ensure block
class BeginBlock < Node
attr_accessor :body, :rescue_clauses, :else_clause, :ensure_clause
def initialize(body:, rescue_clauses: [], else_clause: nil, ensure_clause: nil, **opts)
super(**opts)
@body = body
@rescue_clauses = rescue_clauses
@else_clause = else_clause
@ensure_clause = ensure_clause
end
def children
[@body, @else_clause, @ensure_clause].compact + @rescue_clauses
end
end
# Rescue clause
class RescueClause < Node
attr_accessor :exception_types, :variable, :body
def initialize(body:, exception_types: [], variable: nil, **opts)
super(**opts)
@exception_types = exception_types
@variable = variable
@body = body
end
def children
[@body]
end
end
# Raw Ruby code (for passthrough)
class RawCode < Node
attr_accessor :code
def initialize(code:, **opts)
super(**opts)
@code = code
end
end
#==========================================================================
# Type Representation Nodes
#==========================================================================
# Base type node
class TypeNode < Node
def to_rbs
raise NotImplementedError
end
def to_trb
raise NotImplementedError
end
end
# Simple type (String, Integer, etc.)
class SimpleType < TypeNode
attr_accessor :name
def initialize(name:, **opts)
super(**opts)
@name = name
end
def to_rbs
@name
end
def to_trb
@name
end
end
# Generic type (Array<String>, Map<K, V>)
class GenericType < TypeNode
attr_accessor :base, :type_args
def initialize(base:, type_args: [], **opts)
super(**opts)
@base = base
@type_args = type_args
end
def to_rbs
"#{@base}[#{@type_args.map(&:to_rbs).join(", ")}]"
end
def to_trb
"#{@base}<#{@type_args.map(&:to_trb).join(", ")}>"
end
end
# Union type (String | Integer | nil)
class UnionType < TypeNode
attr_accessor :types
def initialize(types: [], **opts)
super(**opts)
@types = types
end
def to_rbs
@types.map(&:to_rbs).join(" | ")
end
def to_trb
@types.map(&:to_trb).join(" | ")
end
end
# Intersection type (Readable & Writable)
class IntersectionType < TypeNode
attr_accessor :types
def initialize(types: [], **opts)
super(**opts)
@types = types
end
def to_rbs
@types.map(&:to_rbs).join(" & ")
end
def to_trb
@types.map(&:to_trb).join(" & ")
end
end
# Function/Proc type ((String, Integer) -> Boolean)
class FunctionType < TypeNode
attr_accessor :param_types, :return_type
def initialize(return_type:, param_types: [], **opts)
super(**opts)
@param_types = param_types
@return_type = return_type
end
def to_rbs
params = @param_types.map(&:to_rbs).join(", ")
"^(#{params}) -> #{@return_type.to_rbs}"
end
def to_trb
params = @param_types.map(&:to_trb).join(", ")
"(#{params}) -> #{@return_type.to_trb}"
end
end
# Tuple type ([String, Integer, Boolean])
class TupleType < TypeNode
attr_accessor :element_types
def initialize(element_types: [], **opts)
super(**opts)
@element_types = element_types
end
def to_rbs
"[#{@element_types.map(&:to_rbs).join(", ")}]"
end
def to_trb
"[#{@element_types.map(&:to_trb).join(", ")}]"
end
end
# Nullable type (String?)
class NullableType < TypeNode
attr_accessor :inner_type
def initialize(inner_type:, **opts)
super(**opts)
@inner_type = inner_type
end
def to_rbs
"#{@inner_type.to_rbs}?"
end
def to_trb
"#{@inner_type.to_trb}?"
end
end
# Literal type (literal value as type)
class LiteralType < TypeNode
attr_accessor :value
def initialize(value:, **opts)
super(**opts)
@value = value
end
def to_rbs
@value.inspect
end
def to_trb
@value.inspect
end
end
#==========================================================================
# Visitor Pattern
#==========================================================================
class Visitor
def visit(node)
method_name = "visit_#{node.class.name.split("::").last.gsub(/([A-Z])/, '_\1').downcase.sub(/^_/, "")}"
if respond_to?(method_name)
send(method_name, node)
else
visit_default(node)
end
end
def visit_default(node)
node.children.each { |child| visit(child) }
end
def visit_children(node)
node.children.each { |child| visit(child) }
end
end
#==========================================================================
# IR Builder - Converts parsed AST to IR
#==========================================================================
class Builder
def initialize
@type_registry = {}
end
# Build IR from parser output
def build(parse_result, source: nil)
# Build type aliases
declarations = (parse_result[:type_aliases] || []).map do |alias_info|
build_type_alias(alias_info)
end
# Build interfaces
(parse_result[:interfaces] || []).each do |interface_info|
declarations << build_interface(interface_info)
end
# Build classes
(parse_result[:classes] || []).each do |class_info|
declarations << build_class(class_info)
end
# Build functions/methods
(parse_result[:functions] || []).each do |func_info|
declarations << build_method(func_info)
end
Program.new(declarations: declarations, source_file: source)
end
# Build from source code
def build_from_source(source)
parser = Parser.new(source)
result = parser.parse
build(result, source: source)
end
private
def build_type_alias(info)
TypeAlias.new(
name: info[:name],
definition: parse_type(info[:definition])
)
end
def build_interface(info)
members = (info[:members] || []).map do |member|
InterfaceMember.new(
name: member[:name],
type_signature: parse_type(member[:type])
)
end
Interface.new(
name: info[:name],
members: members
)
end
def build_class(info)
# Build methods
methods = (info[:methods] || []).map do |method_info|
build_method(method_info)
end
# Build instance variables
instance_vars = (info[:instance_vars] || []).map do |ivar|
InstanceVariable.new(
name: ivar[:name],
type_annotation: ivar[:type] ? parse_type(ivar[:type]) : nil
)
end
ClassDecl.new(
name: info[:name],
superclass: info[:superclass],
body: methods,
instance_vars: instance_vars
)
end
def build_method(info)
params = (info[:params] || []).map do |param|
Parameter.new(
name: param[:name],
type_annotation: param[:type] ? parse_type(param[:type]) : nil
)
end
# 본문 IR이 있으면 사용 (BodyParser에서 파싱됨)
body = info[:body_ir]
MethodDef.new(
name: info[:name],
params: params,
return_type: info[:return_type] ? parse_type(info[:return_type]) : nil,
body: body,
visibility: info[:visibility] || :public
)
end
def parse_type(type_str)
return nil unless type_str
type_str = type_str.strip
# Union type
if type_str.include?("|")
types = type_str.split("|").map { |t| parse_type(t.strip) }
return UnionType.new(types: types)
end
# Intersection type
if type_str.include?("&")
types = type_str.split("&").map { |t| parse_type(t.strip) }
return IntersectionType.new(types: types)
end
# Nullable type
if type_str.end_with?("?")
inner = parse_type(type_str[0..-2])
return NullableType.new(inner_type: inner)
end
# Generic type
if type_str.include?("<") && type_str.include?(">")
match = type_str.match(/^(\w+)<(.+)>$/)
if match
base = match[1]
args = parse_generic_args(match[2])
return GenericType.new(base: base, type_args: args)
end
end
# Function type
if type_str.include?("->")
match = type_str.match(/^\((.*)?\)\s*->\s*(.+)$/)
if match
param_types = match[1] ? match[1].split(",").map { |t| parse_type(t.strip) } : []
return_type = parse_type(match[2])
return FunctionType.new(param_types: param_types, return_type: return_type)
end
end
# Simple type
SimpleType.new(name: type_str)
end
def parse_generic_args(args_str)
args = []
current = ""
depth = 0
args_str.each_char do |char|
case char
when "<"
depth += 1
current += char
when ">"
depth -= 1
current += char
when ","
if depth.zero?
args << parse_type(current.strip)
current = ""
else
current += char
end
else
current += char
end
end
args << parse_type(current.strip) unless current.empty?
args
end
end
#==========================================================================
# Code Generator - Converts IR to Ruby code
#==========================================================================
class CodeGenerator < Visitor
attr_reader :output
def initialize
@output = []
@indent = 0
end
def generate(program)
@output = []
visit(program)
@output.join("\n")
end
def visit_program(node)
node.declarations.each do |decl|
visit(decl)
@output << ""
end
end
def visit_type_alias(node)
# Type aliases are erased in Ruby output
emit_comment("type #{node.name} = #{node.definition.to_trb}")
end
def visit_interface(node)
# Interfaces are erased in Ruby output
emit_comment("interface #{node.name}")
node.members.each do |member|
emit_comment(" #{member.name}: #{member.type_signature.to_trb}")
end
emit_comment("end")
end
def visit_method_def(node)
params_str = node.params.map(&:name).join(", ")
emit("def #{node.name}(#{params_str})")
@indent += 1
if node.body
visit(node.body)
end
@indent -= 1
emit("end")
end
def visit_block(node)
node.statements.each { |stmt| visit(stmt) }
end
def visit_assignment(node)
emit("#{node.target} = #{generate_expression(node.value)}")
end
def visit_return(node)
if node.value
emit("return #{generate_expression(node.value)}")
else
emit("return")
end
end
def visit_conditional(node)
keyword = node.kind == :unless ? "unless" : "if"
emit("#{keyword} #{generate_expression(node.condition)}")
@indent += 1
visit(node.then_branch) if node.then_branch
@indent -= 1
if node.else_branch
emit("else")
@indent += 1
visit(node.else_branch)
@indent -= 1
end
emit("end")
end
def visit_raw_code(node)
node.code.each_line do |line|
emit(line.rstrip)
end
end
private
def emit(text)
@output << ((" " * @indent) + text)
end
def emit_comment(text)
emit("# #{text}")
end
def generate_expression(node)
case node
when Literal
node.value.inspect
when VariableRef
node.name
when MethodCall
args = node.arguments.map { |a| generate_expression(a) }.join(", ")
if node.receiver
"#{generate_expression(node.receiver)}.#{node.method_name}(#{args})"
else
"#{node.method_name}(#{args})"
end
when BinaryOp
"(#{generate_expression(node.left)} #{node.operator} #{generate_expression(node.right)})"
when UnaryOp
"#{node.operator}#{generate_expression(node.operand)}"
else
node.to_s
end
end
end
#==========================================================================
# RBS Generator - Converts IR to RBS type definitions
#==========================================================================
class RBSGenerator < Visitor
attr_reader :output
def initialize(enable_inference: true)
@output = []
@indent = 0
@enable_inference = enable_inference
@inferrer = TRuby::ASTTypeInferrer.new if enable_inference
@class_env = nil # 현재 클래스의 타입 환경
end