Class: TRuby::Compiler
- Inherits:
-
Object
- Object
- TRuby::Compiler
- Defined in:
- lib/t_ruby/compiler.rb
Instance Attribute Summary collapse
-
#declaration_loader ⇒ Object
readonly
Returns the value of attribute declaration_loader.
-
#optimizer ⇒ Object
readonly
Returns the value of attribute optimizer.
Instance Method Summary collapse
-
#add_declaration_path(path) ⇒ Object
Add a search path for declaration files.
-
#analyze(source, file: "<source>") ⇒ Array<Diagnostic>
Analyze source code without compiling - returns diagnostics only This is the unified analysis interface for LSP and other tools.
- #compile(input_path) ⇒ Object
-
#compile_from_ir(ir_program, output_path) ⇒ Object
Compile from IR program directly.
-
#compile_string(source, options = {}) ⇒ Hash
Compile T-Ruby source code from a string (useful for WASM/playground).
-
#compile_to_ir(input_path) ⇒ Object
Compile to IR without generating output files.
-
#compile_with_diagnostics(input_path) ⇒ Hash
Compile a file and return result with diagnostics This is the unified compilation interface for CLI and Watcher.
-
#compute_output_path(input_path, output_dir, new_extension) ⇒ String
Compute output path for a source file.
-
#compute_relative_path(input_path) ⇒ String
Compute relative path from source directory.
-
#initialize(config = nil, optimize: true) ⇒ Compiler
constructor
A new instance of Compiler.
-
#load_declaration(name) ⇒ Object
Load external declarations from a file.
-
#optimization_stats ⇒ Object
Get optimization statistics (only available after IR compilation).
- #type_check? ⇒ Boolean
Constructor Details
#initialize(config = nil, optimize: true) ⇒ Compiler
16 17 18 19 20 21 22 23 |
# File 'lib/t_ruby/compiler.rb', line 16 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 |
Instance Attribute Details
#declaration_loader ⇒ Object (readonly)
Returns the value of attribute declaration_loader.
14 15 16 |
# File 'lib/t_ruby/compiler.rb', line 14 def declaration_loader @declaration_loader end |
#optimizer ⇒ Object (readonly)
Returns the value of attribute optimizer.
14 15 16 |
# File 'lib/t_ruby/compiler.rb', line 14 def optimizer @optimizer end |
Instance Method Details
#add_declaration_path(path) ⇒ Object
Add a search path for declaration files
312 313 314 |
# File 'lib/t_ruby/compiler.rb', line 312 def add_declaration_path(path) @declaration_loader.add_search_path(path) end |
#analyze(source, file: "<source>") ⇒ Array<Diagnostic>
Analyze source code without compiling - returns diagnostics only This is the unified analysis interface for LSP and other tools
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 |
# File 'lib/t_ruby/compiler.rb', line 151 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 = Regexp.last_match(2) source_line = source_lines[line_num - 1] if line_num.positive? diagnostics << Diagnostic.new( code: "TR1002", 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., 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., file: file, line: 1, column: 1, severity: Diagnostic::SEVERITY_ERROR ) end diagnostics end |
#compile(input_path) ⇒ Object
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 |
# File 'lib/t_ruby/compiler.rb', line 29 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_from_ir(ir_program, output_path) ⇒ Object
Compile from IR program directly
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/t_ruby/compiler.rb', line 287 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 |
#compile_string(source, options = {}) ⇒ Hash
Compile T-Ruby source code from a string (useful for WASM/playground)
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 |
# File 'lib/t_ruby/compiler.rb', line 239 def compile_string(source, = {}) generate_rbs = .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.], } rescue StandardError => e { ruby: "", rbs: "", errors: ["Compilation error: #{e.message}"], } end |
#compile_to_ir(input_path) ⇒ Object
Compile to IR without generating output files
275 276 277 278 279 280 281 282 283 284 |
# File 'lib/t_ruby/compiler.rb', line 275 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_with_diagnostics(input_path) ⇒ Hash
Compile a file and return result with diagnostics This is the unified compilation interface for CLI and Watcher
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 |
# File 'lib/t_ruby/compiler.rb', line 83 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. == new_diag. && 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. == new_diag. && 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. == new_diag. && 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., file: input_path, severity: Diagnostic::SEVERITY_ERROR ) { success: false, output_path: nil, diagnostics: all_diagnostics, } end end |
#compute_output_path(input_path, output_dir, new_extension) ⇒ String
Compute output path for a source file
326 327 328 329 330 |
# File 'lib/t_ruby/compiler.rb', line 326 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(input_path) ⇒ String
Compute relative path from source directory
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 |
# File 'lib/t_ruby/compiler.rb', line 335 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 |
#load_declaration(name) ⇒ Object
Load external declarations from a file
307 308 309 |
# File 'lib/t_ruby/compiler.rb', line 307 def load_declaration(name) @declaration_loader.load(name) end |
#optimization_stats ⇒ Object
Get optimization statistics (only available after IR compilation)
317 318 319 |
# File 'lib/t_ruby/compiler.rb', line 317 def optimization_stats @optimizer&.stats end |
#type_check? ⇒ Boolean
25 26 27 |
# File 'lib/t_ruby/compiler.rb', line 25 def type_check? @config.type_check? end |