Skip to main content

Library/Fn/OXC/
Compile.rs

1//! OXC-based compilation module
2//!
3//! This module provides the compilation functionality using the OXC compiler.
4//!
5//! DIAGNOSTIC LOGGING:
6//! - Full lifecycle tracking of file compilation
7//! - Memory allocation tracking for each file
8//! - File path and nesting level analysis
9
10use std::{
11	io::Write,
12	sync::atomic::{AtomicUsize, Ordering},
13};
14
15use tracing::{debug, error, info, trace};
16
17static FILE_PROCESS_COUNT:AtomicUsize = AtomicUsize::new(0);
18
19/// Calculate directory nesting depth for a path
20fn get_nesting_depth(path:&str) -> usize {
21	path.chars().filter(|&c| c == std::path::MAIN_SEPARATOR || c == '/').count()
22}
23
24#[tracing::instrument(skip(options))]
25/// Compiles TypeScript files from input directory to output directory
26///
27/// # Arguments
28///
29/// * `options` - Compilation options including entry, pattern, config, output
30///   directory
31/// * `_parallel` - Whether to use parallel compilation (currently unused - runs
32///   sequentially)
33pub async fn Fn(options:crate::Struct::SWC::Option, _parallel:bool) -> anyhow::Result<()> {
34	info!("=== OXC Compilation START ===");
35
36	tracing_subscriber::fmt::init();
37
38	let compiler = std::sync::Arc::new(crate::Fn::OXC::Compiler::Compiler::new(options.config.clone()));
39
40	// Get the input base path
41	let input_base = options.entry[0][0].clone();
42
43	let output_base = options.output.clone();
44
45	let pattern = options.pattern.clone();
46
47	info!("Compilation from {} to {}", input_base, output_base);
48
49	debug!("Pattern: {}, Parallel: {}", pattern, _parallel);
50
51	// Use walkdir to find all TypeScript files in the input directory
52	let walk_start = std::time::Instant::now();
53
54	let ts_files:Vec<String> = walkdir::WalkDir::new(&input_base)
55		.follow_links(true)
56		.into_iter()
57		.filter_map(|e| {
58			let entry = e.ok()?;
59			let path = entry.path();
60			if path.is_file() && path.to_string_lossy().ends_with(&pattern) {
61				Some(path.to_string_lossy().to_string())
62			} else {
63				None
64			}
65		})
66		.collect();
67
68	info!(
69		"File discovery completed in {:?}, found {} TypeScript files",
70		walk_start.elapsed(),
71		ts_files.len()
72	);
73
74	// Analyze file distribution by nesting depth
75	let mut depth_dist = std::collections::HashMap::new();
76
77	for f in &ts_files {
78		let depth = get_nesting_depth(f);
79
80		*depth_dist.entry(depth).or_insert(0) += 1;
81	}
82
83	debug!("File distribution by depth: {:?}", depth_dist);
84
85	// Sort files by nesting depth to process nested files last (diagnostic)
86	let mut sorted_files = ts_files.clone();
87
88	sorted_files.sort_by_key(|f| get_nesting_depth(f));
89
90	trace!("File list (sorted by depth):");
91
92	for (i, f) in sorted_files.iter().enumerate() {
93		trace!("  [{}] {} (depth={})", i, f, get_nesting_depth(f));
94	}
95
96	// Process files sequentially to avoid OXC globals issues
97	let mut count = 0;
98
99	let mut error = 0;
100
101	let mut current_file = 0;
102
103	let total_files = sorted_files.len();
104
105	info!("Starting sequential file processing ({} files)...", total_files);
106
107	for file_path in sorted_files {
108		current_file += 1;
109
110		let file_id = FILE_PROCESS_COUNT.fetch_add(1, Ordering::SeqCst);
111
112		let depth = get_nesting_depth(&file_path);
113
114		print!(".");
115
116		std::io::stdout().flush().unwrap();
117
118		info!(
119			"[File #{file_id}] Processing [{}/{}]: {} (depth={})",
120			current_file, total_files, file_path, depth
121		);
122
123		match tokio::fs::read_to_string(&file_path).await {
124			Ok(input) => {
125				trace!("[File #{file_id}] Read {} bytes", input.len());
126
127				// Calculate relative path from input base
128				let input_path = std::path::Path::new(&file_path);
129
130				let base_path = std::path::Path::new(&input_base);
131
132				let relative_path = input_path.strip_prefix(base_path).unwrap_or(input_path);
133
134				// Create output path preserving directory structure
135				let output_path = std::path::Path::new(&output_base).join(relative_path).with_extension("js");
136
137				debug!("[File #{file_id}] Output path: {}", output_path.display());
138
139				let compile_start = std::time::Instant::now();
140
141				match compiler.compile_file_to(&file_path, input, &output_path, options.use_define_for_class_fields) {
142					Ok(output) => {
143						info!(
144							"[File #{file_id}] SUCCESS in {:?}: {} -> {}",
145							compile_start.elapsed(),
146							file_path,
147							output
148						);
149
150						count += 1;
151					},
152
153					Err(e) => {
154						error!(
155							"[File #{file_id}] FAILED in {:?}: {} - Error: {}",
156							compile_start.elapsed(),
157							file_path,
158							e
159						);
160
161						error += 1;
162					},
163				}
164			},
165
166			Err(e) => {
167				error!("[File #{file_id}] READ FAILED: {} - Error: {}", file_path, e);
168
169				error += 1;
170			},
171		}
172	}
173
174	println!();
175
176	let outlook = compiler.outlook.lock().unwrap();
177
178	info!("=== OXC Compilation COMPLETE ===");
179
180	info!(
181		"Total: {} files, Successful: {}, Failed: {}, Time: {:?}",
182		outlook.count, count, error, outlook.elapsed
183	);
184
185	// Print summary
186	println!("\n=== Compilation Summary ===");
187
188	println!("Total files processed: {}", outlook.count);
189
190	println!("Successful: {}", count);
191
192	println!("Failed: {}", error);
193
194	println!("Time elapsed: {:?}\n", outlook.elapsed);
195
196	Ok(())
197}