Skip to main content

Library/Fn/OXC/
Parser.rs

1//! OXC TypeScript Parser module
2//!
3//! This module provides TypeScript source code parsing using the OXC parser.
4//!
5//! DIAGNOSTIC LOGGING:
6//! - All operations log with tracing::debug! for memory lifecycle tracking
7//! - Use RUST_LOG=debug to see detailed parser operations
8
9use std::sync::atomic::{AtomicUsize, Ordering};
10
11use oxc_allocator::Allocator;
12use oxc_parser::{Parser, ParserReturn};
13use oxc_span::SourceType;
14use tracing::{debug, info, trace, warn};
15
16/// Result of parsing a TypeScript source file
17///
18/// CRITICAL FIX FOR SEGFAULT:
19/// The Program has 'static lifetime via safe transmute. ParseResult owns BOTH
20/// the Program AND the Allocator, ensuring they're dropped together.
21///
22/// The ORIGINAL segfault occurred when code did:
23///   let mut program = parse_result.program;  // Moves Program out!
24///   Transformer::transform(&parse_result.allocator, ...);
25///   // parse_result dropped here -> allocator freed -> program is dangling!
26///
27/// THE FIX in Compiler.rs - NEVER move Program out:
28///   let program = &mut parse_result.program;  // Borrow mutably
29///   Transformer::transform(&parse_result.allocator, program, ...);
30///   // parse_result stays in scope -> allocator stays alive -> no segfault!
31pub struct ParseResult {
32	/// The parsed AST program with 'static lifetime (safe transmute)
33	pub program:oxc_ast::ast::Program<'static>,
34
35	/// The allocator used for the AST - owns the memory for the Program
36	/// CRITICAL: Must not be dropped separately from program
37	pub allocator:Allocator,
38
39	/// Any parsing errors encountered
40	pub errors:Vec<String>,
41
42	/// File path for debugging
43	pub file_path:String,
44}
45
46/// Parser configuration options
47#[derive(Debug, Clone)]
48pub struct ParserConfig {
49	/// Target ECMAScript version (e.g., "es2024")
50	pub target:String,
51
52	/// Whether to support JSX syntax
53	pub jsx:bool,
54
55	/// Whether to support decorators
56	pub decorators:bool,
57
58	/// Whether to support TypeScript
59	pub typescript:bool,
60}
61
62impl Default for ParserConfig {
63	fn default() -> Self { Self { target:"es2024".to_string(), jsx:false, decorators:true, typescript:true } }
64}
65
66impl ParserConfig {
67	/// Create a new parser configuration
68	pub fn new(target:String, jsx:bool, decorators:bool, typescript:bool) -> Self {
69		Self { target, jsx, decorators, typescript }
70	}
71}
72
73/// Parse TypeScript source code into an AST
74///
75/// # Arguments
76/// * `source_text` - The TypeScript source code to parse
77/// * `file_path` - The path to the source file (used for determining file type)
78/// * `config` - Parser configuration options
79///
80/// # Returns
81/// A ParseResult containing the parsed AST and any errors
82static PARSE_COUNT:AtomicUsize = AtomicUsize::new(0);
83
84#[tracing::instrument(skip(source_text, config))]
85pub fn parse(source_text:&str, file_path:&str, config:&ParserConfig) -> Result<ParseResult, Vec<String>> {
86	let parse_id = PARSE_COUNT.fetch_add(1, Ordering::SeqCst);
87
88	info!("[Parser #{parse_id}] Starting parse of: {}", file_path);
89
90	trace!("[Parser #{parse_id}] Source text length: {} bytes", source_text.len());
91
92	let allocator = Allocator::default();
93
94	trace!("[Parser #{parse_id}] Allocator created at: {:p}", &allocator);
95
96	// Determine source type based on file extension and config
97	let source_type = determine_source_type(file_path, config);
98
99	info!("[Parser #{parse_id}] Parsing {} as {:?}", file_path, source_type);
100
101	let parse_start = std::time::Instant::now();
102
103	// Parse the source code
104	let parser_return:ParserReturn = Parser::new(&allocator, source_text, source_type).parse();
105
106	info!("[Parser #{parse_id}] Parse completed in {:?}", parse_start.elapsed());
107
108	let errors:Vec<String> = parser_return.errors.iter().map(|e| e.to_string()).collect();
109
110	if !errors.is_empty() {
111		warn!("[Parser #{parse_id}] Parsing errors for {}: {:?}", file_path, errors);
112
113		return Err(errors);
114	}
115
116	// SAFETY: Transmute program lifetime to 'static.
117	// This is SAFE because:
118	// 1. ParseResult owns BOTH the Program AND the Allocator
119	// 2. The Program's memory comes from the Allocator
120	// 3. Both are dropped together when ParseResult is dropped
121	// 4. The Program NEVER outlives the Allocator
122	//
123	// CRITICAL BUG FIX: The original segfault happened because code did:
124	//   let mut program = parse_result.program;  // Moves Program out!
125	//   Transformer::transform(&parse_result.allocator, ...);
126	//   // parse_result dropped -> allocator freed -> program is dangling!
127	//
128	// THE FIX in Compiler.rs:
129	//   let program = &mut parse_result.program;  // Borrow mutably, don't move!
130	//   Transformer::transform(&parse_result.allocator, program, ...);
131	//   // parse_result stays in scope -> allocator stays alive
132	let program = unsafe {
133		std::mem::transmute::<oxc_ast::ast::Program<'_>, oxc_ast::ast::Program<'static>>(parser_return.program)
134	};
135
136	debug!("[Parser #{parse_id}] Program transmute complete at: {:p}", &program);
137
138	trace!(
139		"[Parser #{parse_id}] AST body pointer: {:p}, len: {}",
140		program.body.as_ptr(),
141		program.body.len()
142	);
143
144	info!(
145		"[Parser #{parse_id}] SUCCESS: ParseResult<'static> created (allocator={:p})",
146		&allocator
147	);
148
149	Ok(ParseResult { program, allocator, errors:vec![], file_path:file_path.to_string() })
150}
151
152/// Determine the source type based on file path and configuration
153fn determine_source_type(file_path:&str, _config:&ParserConfig) -> SourceType {
154	let path = std::path::Path::new(file_path);
155
156	let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("");
157
158	match extension {
159		"ts" | "mts" => SourceType::ts(),
160
161		"tsx" => SourceType::tsx(),
162
163		"mjs" => SourceType::mjs(),
164
165		"cjs" => SourceType::cjs(),
166
167		"js" => SourceType::unambiguous(),
168
169		"jsx" => SourceType::jsx(),
170
171		_ => SourceType::unambiguous(),
172	}
173}