-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcompiler.rb
More file actions
954 lines (799 loc) · 31.4 KB
/
compiler.rb
File metadata and controls
954 lines (799 loc) · 31.4 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
# frozen_string_literal: true
require "fileutils"
module TRuby
# Pattern for method names that supports Unicode characters
# \p{L} matches any Unicode letter, \p{N} matches any Unicode number
IDENTIFIER_CHAR = '[\p{L}\p{N}_]'
METHOD_NAME_PATTERN = "#{IDENTIFIER_CHAR}+[?!]?".freeze
# Visibility modifiers for method definitions
VISIBILITY_PATTERN = '(?:(?:private|protected|public)\s+)?'
class Compiler
attr_reader :declaration_loader, :optimizer
def initialize(config = nil, optimize: true)
@config = config || Config.new
@optimize = optimize
@declaration_loader = DeclarationLoader.new
@optimizer = IR::Optimizer.new if optimize
@type_inferrer = ASTTypeInferrer.new if type_check?
setup_declaration_paths if @config
end
def type_check?
@config.type_check?
end
def compile(input_path)
unless File.exist?(input_path)
raise ArgumentError, "File not found: #{input_path}"
end
# Handle .rb files separately
if input_path.end_with?(".rb")
return copy_ruby_file(input_path)
end
unless input_path.end_with?(".trb")
raise ArgumentError, "Expected .trb or .rb file, got: #{input_path}"
end
source = File.read(input_path)
# Parse with IR support
parser = Parser.new(source)
parser.parse
# Run type checking if enabled
if type_check? && parser.ir_program
check_types(parser.ir_program, input_path)
end
# Transform source to Ruby code
output = transform_with_ir(source, parser)
# Compute output path (respects preserve_structure setting)
output_path = compute_output_path(input_path, @config.ruby_dir, ".rb")
FileUtils.mkdir_p(File.dirname(output_path))
File.write(output_path, output)
# Generate .rbs file if enabled in config
if @config.compiler["generate_rbs"]
rbs_path = compute_output_path(input_path, @config.rbs_dir, ".rbs")
FileUtils.mkdir_p(File.dirname(rbs_path))
generate_rbs_from_ir_to_path(rbs_path, parser.ir_program)
end
# Generate .d.trb file if enabled in config (legacy support)
# TODO: Add compiler.generate_dtrb option in future
if @config.compiler.key?("generate_dtrb") && @config.compiler["generate_dtrb"]
generate_dtrb_file(input_path, @config.ruby_dir)
end
output_path
end
# Compile a file and return result with diagnostics
# This is the unified compilation interface for CLI and Watcher
# @param input_path [String] Path to the input file
# @return [Hash] Result with :success, :output_path, :diagnostics keys
def compile_with_diagnostics(input_path)
source = File.exist?(input_path) ? File.read(input_path) : nil
all_diagnostics = []
# Run analyze first to get all diagnostics (colon spacing, etc.)
if source
all_diagnostics = analyze(source, file: input_path)
end
begin
output_path = compile(input_path)
# Compilation succeeded, but we may still have diagnostics from analyze
{
success: all_diagnostics.empty?,
output_path: all_diagnostics.empty? ? output_path : nil,
diagnostics: all_diagnostics,
}
rescue TypeCheckError => e
# Skip if already reported by analyze (same message and location)
new_diag = Diagnostic.from_type_check_error(e, file: input_path, source: source)
unless all_diagnostics.any? { |d| d.message == new_diag.message && d.line == new_diag.line }
all_diagnostics << new_diag
end
{
success: false,
output_path: nil,
diagnostics: all_diagnostics,
}
rescue ParseError => e
new_diag = Diagnostic.from_parse_error(e, file: input_path, source: source)
unless all_diagnostics.any? { |d| d.message == new_diag.message && d.line == new_diag.line }
all_diagnostics << new_diag
end
{
success: false,
output_path: nil,
diagnostics: all_diagnostics,
}
rescue Scanner::ScanError => e
new_diag = Diagnostic.from_scan_error(e, file: input_path, source: source)
unless all_diagnostics.any? { |d| d.message == new_diag.message && d.line == new_diag.line }
all_diagnostics << new_diag
end
{
success: false,
output_path: nil,
diagnostics: all_diagnostics,
}
rescue ArgumentError => e
all_diagnostics << Diagnostic.new(
code: "TR0001",
message: e.message,
file: input_path,
severity: Diagnostic::SEVERITY_ERROR
)
{
success: false,
output_path: nil,
diagnostics: all_diagnostics,
}
end
end
# Analyze source code without compiling - returns diagnostics only
# This is the unified analysis interface for LSP and other tools
# @param source [String] T-Ruby source code
# @param file [String] File path for error reporting (optional)
# @return [Array<Diagnostic>] Array of diagnostic objects
def analyze(source, file: "<source>")
diagnostics = []
source_lines = source.split("\n")
# Run ErrorHandler checks (syntax validation, duplicate definitions, etc.)
error_handler = ErrorHandler.new(source)
errors = error_handler.check
errors.each do |error|
# Parse line number from "Line N: message" format
next unless error =~ /^Line (\d+):\s*(.+)$/
line_num = Regexp.last_match(1).to_i
message = Regexp.last_match(2)
source_line = source_lines[line_num - 1] if line_num.positive?
diagnostics << Diagnostic.new(
code: "TR1002",
message: message,
file: file,
line: line_num,
column: 1,
source_line: source_line,
severity: Diagnostic::SEVERITY_ERROR
)
end
# Run TokenDeclarationParser for colon spacing and declaration syntax validation
begin
scanner = Scanner.new(source)
tokens = scanner.scan_all
decl_parser = ParserCombinator::TokenDeclarationParser.new
decl_parser.parse_program(tokens)
if decl_parser.has_errors?
decl_parser.errors.each do |err|
source_line = source_lines[err.line - 1] if err.line.positive? && err.line <= source_lines.length
diagnostics << Diagnostic.new(
code: "TR1003",
message: err.message,
file: file,
line: err.line,
column: err.column,
source_line: source_line,
severity: Diagnostic::SEVERITY_ERROR
)
end
end
rescue Scanner::ScanError
# Scanner errors will be caught below in the main parse section
rescue StandardError
# Ignore TokenDeclarationParser errors for now - regex parser is authoritative
end
begin
# Parse source with regex-based parser for IR generation
parser = Parser.new(source)
parser.parse
# Run type checking if enabled and IR is available
if type_check? && parser.ir_program
begin
check_types(parser.ir_program, file)
rescue TypeCheckError => e
diagnostics << Diagnostic.from_type_check_error(e, file: file, source: source)
end
end
rescue ParseError => e
diagnostics << Diagnostic.from_parse_error(e, file: file, source: source)
rescue Scanner::ScanError => e
diagnostics << Diagnostic.from_scan_error(e, file: file, source: source)
rescue StandardError => e
diagnostics << Diagnostic.new(
code: "TR0001",
message: e.message,
file: file,
line: 1,
column: 1,
severity: Diagnostic::SEVERITY_ERROR
)
end
diagnostics
end
# Compile T-Ruby source code from a string (useful for WASM/playground)
# @param source [String] T-Ruby source code
# @param options [Hash] Options for compilation
# @option options [Boolean] :rbs Whether to generate RBS output (default: true)
# @return [Hash] Result with :ruby, :rbs, :errors keys
def compile_string(source, options = {})
generate_rbs = options.fetch(:rbs, true)
parser = Parser.new(source)
parser.parse
# Transform source to Ruby code
ruby_output = transform_with_ir(source, parser)
# Generate RBS if requested
rbs_output = ""
if generate_rbs && parser.ir_program
generator = IR::RBSGenerator.new
rbs_output = generator.generate(parser.ir_program)
end
{
ruby: ruby_output,
rbs: rbs_output,
errors: [],
}
rescue ParseError => e
{
ruby: "",
rbs: "",
errors: [e.message],
}
rescue StandardError => e
{
ruby: "",
rbs: "",
errors: ["Compilation error: #{e.message}"],
}
end
# Compile to IR without generating output files
def compile_to_ir(input_path)
unless File.exist?(input_path)
raise ArgumentError, "File not found: #{input_path}"
end
source = File.read(input_path)
parser = Parser.new(source)
parser.parse
parser.ir_program
end
# Compile from IR program directly
def compile_from_ir(ir_program, output_path)
out_dir = File.dirname(output_path)
FileUtils.mkdir_p(out_dir)
# Optimize if enabled
program = ir_program
if @optimize && @optimizer
result = @optimizer.optimize(program)
program = result[:program]
end
# Generate Ruby code
generator = IRCodeGenerator.new
output = generator.generate(program)
File.write(output_path, output)
output_path
end
# Load external declarations from a file
def load_declaration(name)
@declaration_loader.load(name)
end
# Add a search path for declaration files
def add_declaration_path(path)
@declaration_loader.add_search_path(path)
end
# Get optimization statistics (only available after IR compilation)
def optimization_stats
@optimizer&.stats
end
# Compute output path for a source file
# @param input_path [String] path to source file
# @param output_dir [String] base output directory
# @param new_extension [String] new file extension (e.g., ".rb", ".rbs")
# @return [String] computed output path (always preserves directory structure)
def compute_output_path(input_path, output_dir, new_extension)
relative = compute_relative_path(input_path)
base = relative.sub(/\.[^.]+$/, new_extension)
File.join(output_dir, base)
end
# Compute relative path from source directory
# @param input_path [String] path to source file
# @return [String] relative path preserving directory structure
def compute_relative_path(input_path)
# Use realpath to resolve symlinks (e.g., /var vs /private/var on macOS)
absolute_input = resolve_path(input_path)
source_dirs = @config.source_include
# Check if file is inside any source_include directory
if source_dirs.size > 1
# Multiple source directories: include the source dir name in output
# src/models/user.trb → src/models/user.trb
source_dirs.each do |src_dir|
absolute_src = resolve_path(src_dir)
next unless absolute_input.start_with?("#{absolute_src}/")
# Return path relative to parent of source dir (includes src dir name)
parent_of_src = File.dirname(absolute_src)
return absolute_input.sub("#{parent_of_src}/", "")
end
else
# Single source directory: exclude the source dir name from output
# src/models/user.trb → models/user.trb
src_dir = source_dirs.first
if src_dir
absolute_src = resolve_path(src_dir)
if absolute_input.start_with?("#{absolute_src}/")
return absolute_input.sub("#{absolute_src}/", "")
end
end
end
# File outside source directories: use path relative to current working directory
# external/foo.trb → external/foo.trb
cwd = resolve_path(".")
if absolute_input.start_with?("#{cwd}/")
return absolute_input.sub("#{cwd}/", "")
end
# Absolute path from outside cwd: use basename only
File.basename(input_path)
end
private
# Check types in IR program and raise TypeCheckError if mismatches found
# @param ir_program [IR::Program] IR program to check
# @param file_path [String] source file path for error messages
def check_types(ir_program, file_path)
ir_program.declarations.each do |decl|
case decl
when IR::MethodDef
check_method_return_type(decl, nil, file_path)
check_yield_arguments(decl, nil, file_path)
when IR::ClassDecl
decl.body.each do |member|
next unless member.is_a?(IR::MethodDef)
check_method_return_type(member, decl, file_path)
check_yield_arguments(member, decl, file_path)
end
end
end
end
# Check if method's inferred return type matches declared return type
# @param method [IR::MethodDef] method to check
# @param class_def [IR::ClassDef, nil] containing class if any
# @param file_path [String] source file path for error messages
def check_method_return_type(method, class_def, file_path)
# Skip if no explicit return type annotation
return unless method.return_type
declared_type = normalize_type(method.return_type.to_rbs)
# Create type environment for the class context
class_env = create_class_env(class_def) if class_def
# Infer actual return type
inferred_type = @type_inferrer.infer_method_return_type(method, class_env)
inferred_type = normalize_type(inferred_type || "nil")
# Check compatibility
return if types_compatible?(inferred_type, declared_type)
location = method.location ? "#{file_path}:#{method.location}" : file_path
method_name = class_def ? "#{class_def.name}##{method.name}" : method.name
raise TypeCheckError.new(
message: "Return type mismatch in method '#{method_name}': " \
"declared '#{declared_type}' but inferred '#{inferred_type}'",
location: location,
expected: declared_type,
actual: inferred_type
)
end
# Check yield statements match block parameter signature
# @param method [IR::MethodDef] method to check
# @param class_def [IR::ClassDecl, nil] containing class if any
# @param file_path [String] source file path for error messages
def check_yield_arguments(method, class_def, file_path)
# Find block parameter with FunctionType annotation
block_param = method.params.find { |p| p.kind == :block }
return unless block_param&.type_annotation.is_a?(IR::FunctionType)
block_type = block_param.type_annotation
expected_types = block_type.param_types
expected_arg_count = expected_types.length
# Find all yield statements in method body
yields = find_yields_in_body(method.body)
return if yields.empty?
location = method.location ? "#{file_path}:#{method.location}" : file_path
method_name = class_def ? "#{class_def.name}##{method.name}" : method.name
# Create type environment for inference
type_env = create_method_type_env(method, class_def)
yields.each do |yield_node|
actual_arg_count = yield_node.arguments.length
# Check argument count first
if actual_arg_count != expected_arg_count
raise TypeCheckError.new(
message: "Yield argument count mismatch in '#{method_name}': " \
"block expects #{expected_arg_count} argument(s) but yield passes #{actual_arg_count}",
location: location,
expected: "#{expected_arg_count} argument(s)",
actual: "#{actual_arg_count} argument(s)"
)
end
# Check argument types
yield_node.arguments.each_with_index do |arg, idx|
expected_type = normalize_type(expected_types[idx].to_rbs)
inferred_type = infer_yield_arg_type(arg, type_env)
next if inferred_type.nil? || types_compatible?(inferred_type, expected_type)
raise TypeCheckError.new(
message: "Yield argument type mismatch in '#{method_name}' at position #{idx + 1}: " \
"expected '#{expected_type}' but got '#{inferred_type}'",
location: location,
expected: expected_type,
actual: inferred_type
)
end
end
end
# Create type environment for method context
def create_method_type_env(method, class_def)
env = class_def ? create_class_env(class_def) : TypeEnv.new
# Add method parameters to environment
method.params.each do |param|
next if param.kind == :block
param_type = param.type_annotation&.to_rbs || "untyped"
env.define(param.name, param_type)
end
env
end
# Infer type of a yield argument expression
def infer_yield_arg_type(arg, env)
return nil unless @type_inferrer
inferred = @type_inferrer.infer_expression(arg, env)
normalize_type(inferred)
rescue StandardError
nil # If inference fails, skip type checking for this arg
end
# Find all yield nodes in a method body
# @param node [IR::Node] IR node to search
# @return [Array<IR::Yield>] yield nodes found
def find_yields_in_body(node)
yields = []
return yields unless node
case node
when IR::Yield
yields << node
when IR::Block
node.statements.each { |stmt| yields.concat(find_yields_in_body(stmt)) }
when IR::Conditional
yields.concat(find_yields_in_body(node.then_branch))
yields.concat(find_yields_in_body(node.else_branch))
when IR::Loop
yields.concat(find_yields_in_body(node.body))
when IR::Assignment
yields.concat(find_yields_in_body(node.value))
when IR::Return
yields.concat(find_yields_in_body(node.value))
end
yields
end
# Create type environment for class context
# @param class_def [IR::ClassDecl] class declaration
# @return [TypeEnv] type environment with instance variables
def create_class_env(class_def)
env = TypeEnv.new
# Register instance variables from class
class_def.instance_vars&.each do |ivar|
type = ivar.type_annotation&.to_rbs || "untyped"
env.define_instance_var(ivar.name, type)
end
env
end
# Normalize type string for comparison
# @param type [String] type string
# @return [String] normalized type string
def normalize_type(type)
return "untyped" if type.nil?
normalized = type.to_s.strip
# Normalize boolean types (bool/Boolean/TrueClass/FalseClass -> bool)
case normalized
when "Boolean", "TrueClass", "FalseClass"
"bool"
else
normalized
end
end
# Check if inferred type is compatible with declared type
# @param inferred [String] inferred type
# @param declared [String] declared type
# @return [Boolean] true if compatible
def types_compatible?(inferred, declared)
# Exact match
return true if inferred == declared
# untyped is compatible with anything
return true if inferred == "untyped" || declared == "untyped"
# void is compatible with anything (no return value check)
return true if declared == "void"
# nil is compatible with nullable types
return true if inferred == "nil" && declared.end_with?("?")
# Subtype relationships
return true if subtype_of?(inferred, declared)
# Handle generic types (e.g., Array[untyped] is compatible with Array[String])
if inferred.include?("[") && declared.include?("[")
inferred_base = inferred.split("[").first
declared_base = declared.split("[").first
if inferred_base == declared_base
# Extract type arguments
inferred_args = inferred[/\[(.+)\]/, 1]
declared_args = declared[/\[(.+)\]/, 1]
# untyped type argument is compatible with any type argument
return true if inferred_args == "untyped" || declared_args == "untyped"
end
end
# Handle union types in declared
if declared.include?("|")
declared_types = declared.split("|").map(&:strip)
return true if declared_types.include?(inferred)
return true if declared_types.any? { |t| types_compatible?(inferred, t) }
end
# Handle union types in inferred - all must be compatible
if inferred.include?("|")
inferred_types = inferred.split("|").map(&:strip)
return inferred_types.all? { |t| types_compatible?(t, declared) }
end
false
end
# Check if subtype is a subtype of supertype
# @param subtype [String] potential subtype
# @param supertype [String] potential supertype
# @return [Boolean] true if subtype
def subtype_of?(subtype, supertype)
# Handle nullable - X is subtype of X?
return true if supertype.end_with?("?") && supertype[0..-2] == subtype
# Numeric hierarchy
return true if subtype == "Integer" && supertype == "Numeric"
return true if subtype == "Float" && supertype == "Numeric"
# Object is supertype of everything
return true if supertype == "Object"
false
end
# Resolve path to absolute path, following symlinks
# Falls back to expand_path if realpath fails (e.g., file doesn't exist yet)
def resolve_path(path)
File.realpath(path)
rescue Errno::ENOENT
File.expand_path(path)
end
def setup_declaration_paths
# Add default declaration paths
@declaration_loader.add_search_path(@config.out_dir)
@declaration_loader.add_search_path(@config.src_dir)
@declaration_loader.add_search_path("./types")
@declaration_loader.add_search_path("./lib/types")
end
# Transform using IR system
def transform_with_ir(source, parser)
ir_program = parser.ir_program
return source unless ir_program
# Run optimization passes if enabled
if @optimize && @optimizer
result = @optimizer.optimize(ir_program)
ir_program = result[:program]
end
# Generate Ruby code using IR-aware generator with target Ruby version
generator = IRCodeGenerator.new(target_ruby: @config.target_ruby)
generator.generate_with_source(ir_program, source)
end
# Generate RBS from IR to a specific path
def generate_rbs_from_ir_to_path(rbs_path, ir_program)
return unless ir_program
generator = IR::RBSGenerator.new
rbs_content = generator.generate(ir_program)
File.write(rbs_path, rbs_content) unless rbs_content.strip.empty?
end
def generate_dtrb_file(input_path, out_dir)
dtrb_path = compute_output_path(input_path, out_dir, DeclarationGenerator::DECLARATION_EXTENSION)
FileUtils.mkdir_p(File.dirname(dtrb_path))
generator = DeclarationGenerator.new
generator.generate_file_to_path(input_path, dtrb_path)
end
# Copy .rb file to output directory and generate .rbs signature
def copy_ruby_file(input_path)
unless File.exist?(input_path)
raise ArgumentError, "File not found: #{input_path}"
end
# Compute output path (respects preserve_structure setting)
output_path = compute_output_path(input_path, @config.ruby_dir, ".rb")
FileUtils.mkdir_p(File.dirname(output_path))
# Copy the .rb file to output directory
FileUtils.cp(input_path, output_path)
# Generate .rbs file if enabled in config
if @config.compiler["generate_rbs"]
rbs_path = compute_output_path(input_path, @config.rbs_dir, ".rbs")
FileUtils.mkdir_p(File.dirname(rbs_path))
generate_rbs_from_ruby_to_path(rbs_path, input_path)
end
output_path
end
# Generate RBS from Ruby file using rbs prototype to a specific path
def generate_rbs_from_ruby_to_path(rbs_path, input_path)
result = `rbs prototype rb #{input_path} 2>/dev/null`
File.write(rbs_path, result) unless result.strip.empty?
end
end
# IR-aware code generator for source-preserving transformation
class IRCodeGenerator
attr_reader :emitter
# @param target_ruby [String] target Ruby version (e.g., "3.0", "4.0")
def initialize(target_ruby: "3.0")
@output = []
@emitter = CodeEmitter.for_version(target_ruby)
end
# Generate Ruby code from IR program
def generate(program)
generator = IR::CodeGenerator.new
generator.generate(program)
end
# Generate Ruby code while preserving source structure
def generate_with_source(program, source)
result = source.dup
# Collect type alias names to remove
program.declarations
.select { |d| d.is_a?(IR::TypeAlias) }
.map(&:name)
# Collect interface names to remove
program.declarations
.select { |d| d.is_a?(IR::Interface) }
.map(&:name)
# Remove type alias definitions
result = result.gsub(/^\s*type\s+\w+\s*=\s*.+?$\n?/, "")
# Remove interface definitions (multi-line)
result = result.gsub(/^\s*interface\s+\w+.*?^\s*end\s*$/m, "")
# Remove parameter type annotations using IR info
# Enhanced: Handle complex types (generics, unions, etc.)
result = erase_parameter_types(result)
# Remove return type annotations
result = erase_return_types(result)
# Apply version-specific transformations
result = @emitter.transform(result)
# Clean up extra blank lines
result.gsub(/\n{3,}/, "\n\n")
end
private
# Erase parameter type annotations
def erase_parameter_types(source)
result = source.dup
# Match function definitions and remove type annotations from parameters
# Also supports visibility modifiers: private def, protected def, public def
result.gsub!(/^(\s*#{TRuby::VISIBILITY_PATTERN}def\s+#{TRuby::METHOD_NAME_PATTERN}\s*\()([^)]+)(\)\s*)(?::\s*[^\n]+)?(\s*$)/) do |_match|
indent = ::Regexp.last_match(1)
params = ::Regexp.last_match(2)
close_paren = ::Regexp.last_match(3)
ending = ::Regexp.last_match(4)
# Remove type annotations from each parameter
cleaned_params = remove_param_types(params)
"#{indent}#{cleaned_params}#{close_paren.rstrip}#{ending}"
end
result
end
# Remove type annotations from parameter list
def remove_param_types(params_str)
return params_str if params_str.strip.empty?
params = []
current = ""
depth = 0
brace_depth = 0
params_str.each_char do |char|
case char
when "<", "[", "("
depth += 1
current += char
when ">", "]", ")"
depth -= 1
current += char
when "{"
brace_depth += 1
current += char
when "}"
brace_depth -= 1
current += char
when ","
if depth.zero? && brace_depth.zero?
cleaned = clean_param(current.strip)
params.concat(Array(cleaned)) if cleaned
current = ""
else
current += char
end
else
current += char
end
end
cleaned = clean_param(current.strip) unless current.empty?
params.concat(Array(cleaned)) if cleaned
params.join(", ")
end
# Clean a single parameter (remove type annotation, preserve default value)
# Returns String or Array of Strings (for keyword args group)
def clean_param(param)
param = param.strip
return nil if param.empty?
# 0. 블록 파라미터: &name: Type -> &name
if param.start_with?("&")
match = param.match(/^&(\w+)(?::\s*.+)?$/)
return "&#{match[1]}" if match
return param
end
# 1. 더블 스플랫: **name: Type -> **name
if param.start_with?("**")
match = param.match(/^\*\*(\w+)(?::\s*.+)?$/)
return "**#{match[1]}" if match
return param
end
# 2. 키워드 인자 그룹: { ... } 또는 { ... }: InterfaceName
if param.start_with?("{")
return clean_keyword_args_group(param)
end
# 3. Hash 리터럴: name: { ... } -> name
if param.match?(/^\w+:\s*\{/)
match = param.match(/^(\w+):\s*\{.+\}(?::\s*\w+)?$/)
return match[1] if match
return param
end
# 4. 일반 파라미터: name: Type = value -> name = value 또는 name: Type -> name
# Match: name: Type = value (with default value)
if (match = param.match(/^(#{TRuby::IDENTIFIER_CHAR}+)\s*:\s*.+?\s*(=\s*.+)$/))
"#{match[1]} #{match[2]}"
# Match: name: Type (without default value)
elsif (match = param.match(/^(#{TRuby::IDENTIFIER_CHAR}+)\s*:/))
match[1]
else
param
end
end
# 키워드 인자 그룹을 Ruby 키워드 인자로 변환
# { name: String, age: Integer = 0 } -> name:, age: 0
# { name:, age: 0 }: UserParams -> name:, age: 0
def clean_keyword_args_group(param)
# { ... }: InterfaceName 또는 { ... } 형태 파싱
interface_match = param.match(/^\{(.+)\}\s*:\s*\w+\s*$/)
inline_match = param.match(/^\{(.+)\}\s*$/) unless interface_match
inner_content = if interface_match
interface_match[1]
elsif inline_match
inline_match[1]
else
return param
end
# 내부 파라미터 분리
parts = split_nested_content(inner_content)
keyword_params = []
parts.each do |part|
part = part.strip
next if part.empty?
if interface_match
# interface 참조: name: default_value 또는 name:
if (match = part.match(/^(\w+):\s*(.*)$/))
name = match[1]
default_value = match[2].strip
keyword_params << if default_value.empty?
"#{name}:"
else
"#{name}: #{default_value}"
end
end
elsif (match = part.match(/^(\w+):\s*(.+)$/))
# 인라인 타입: name: Type = default 또는 name: Type
name = match[1]
type_and_default = match[2].strip
# Type = default 분리
default_value = extract_default_value(type_and_default)
keyword_params << if default_value
"#{name}: #{default_value}"
else
"#{name}:"
end
end
end
keyword_params
end
# 중첩된 내용을 콤마로 분리
def split_nested_content(content)
StringUtils.split_by_comma(content)
end
# 타입과 기본값에서 기본값만 추출
def extract_default_value(type_and_default)
StringUtils.extract_default_value(type_and_default)
end
# Erase return type annotations
def erase_return_types(source)
result = source.dup
# Remove return type after parentheses: ): Type or ): Type<Foo> etc.
result.gsub!(/\)\s*:\s*[^\n]+?(?=\s*$)/m) do |_match|
")"
end
# Remove return type for methods without parentheses: def method_name: Type
result.gsub!(/^(\s*#{TRuby::VISIBILITY_PATTERN}def\s+#{TRuby::METHOD_NAME_PATTERN})\s*:\s*[^\n]+?(?=\s*$)/m) do |_match|
::Regexp.last_match(1)
end
result
end
end
end