Class: TRuby::IRCodeGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/t_ruby/compiler.rb

Overview

IR-aware code generator for source-preserving transformation

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target_ruby: "3.0") ⇒ IRCodeGenerator

Returns a new instance of IRCodeGenerator.

Parameters:

  • (defaults to: "3.0")

    target Ruby version (e.g., “3.0”, “4.0”)



440
441
442
443
# File 'lib/t_ruby/compiler.rb', line 440

def initialize(target_ruby: "3.0")
  @output = []
  @emitter = CodeEmitter.for_version(target_ruby)
end

Instance Attribute Details

#emitterObject (readonly)

Returns the value of attribute emitter.



437
438
439
# File 'lib/t_ruby/compiler.rb', line 437

def emitter
  @emitter
end

Instance Method Details

#generate(program) ⇒ Object

Generate Ruby code from IR program



446
447
448
449
# File 'lib/t_ruby/compiler.rb', line 446

def generate(program)
  generator = IR::CodeGenerator.new
  generator.generate(program)
end

#generate_with_source(program, source) ⇒ Object

Generate Ruby code while preserving source structure



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
# File 'lib/t_ruby/compiler.rb', line 452

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