1pub mod ast;
27pub mod builtins;
28pub mod call_graph;
29pub mod capture_analysis;
30pub mod codegen;
31pub mod config;
32pub mod ffi;
33pub mod lint;
34pub mod parser;
35pub mod resolver;
36pub mod resource_lint;
37pub mod script;
38pub mod stdlib_embed;
39pub mod test_runner;
40pub mod typechecker;
41pub mod types;
42pub mod unification;
43
44pub use ast::Program;
45pub use codegen::CodeGen;
46pub use config::{CompilerConfig, ExternalBuiltin, OptimizationLevel};
47pub use lint::{LintConfig, LintDiagnostic, Linter, Severity};
48pub use parser::Parser;
49pub use resolver::{
50 ResolveResult, Resolver, check_collisions, check_union_collisions, find_stdlib,
51};
52pub use resource_lint::{ProgramResourceAnalyzer, ResourceAnalyzer};
53pub use typechecker::TypeChecker;
54pub use types::{Effect, StackType, Type};
55
56use std::fs;
57use std::io::Write;
58use std::path::Path;
59use std::process::Command;
60use std::sync::OnceLock;
61
62#[cfg(not(docsrs))]
65static RUNTIME_LIB: &[u8] = include_bytes!(env!("SEQ_RUNTIME_LIB_PATH"));
66
67#[cfg(docsrs)]
68static RUNTIME_LIB: &[u8] = &[];
69
70const MIN_CLANG_VERSION: u32 = 15;
73
74static CLANG_VERSION_CHECKED: OnceLock<Result<u32, String>> = OnceLock::new();
77
78fn check_clang_version() -> Result<u32, String> {
82 CLANG_VERSION_CHECKED
83 .get_or_init(|| {
84 let output = Command::new("clang")
85 .arg("--version")
86 .output()
87 .map_err(|e| {
88 format!(
89 "Failed to run clang: {}. \
90 Please install clang {} or later.",
91 e, MIN_CLANG_VERSION
92 )
93 })?;
94
95 if !output.status.success() {
96 let stderr = String::from_utf8_lossy(&output.stderr);
97 return Err(format!(
98 "clang --version failed with exit code {:?}: {}",
99 output.status.code(),
100 stderr
101 ));
102 }
103
104 let version_str = String::from_utf8_lossy(&output.stdout);
105
106 let version = parse_clang_version(&version_str).ok_or_else(|| {
111 format!(
112 "Could not parse clang version from: {}\n\
113 seqc requires clang {} or later (for opaque pointer support).",
114 version_str.lines().next().unwrap_or(&version_str),
115 MIN_CLANG_VERSION
116 )
117 })?;
118
119 let is_apple = version_str.contains("Apple clang");
122 let effective_min = if is_apple { 14 } else { MIN_CLANG_VERSION };
123
124 if version < effective_min {
125 return Err(format!(
126 "clang version {} detected, but seqc requires {} {} or later.\n\
127 The generated LLVM IR uses opaque pointers (requires LLVM 15+).\n\
128 Please upgrade your clang installation.",
129 version,
130 if is_apple { "Apple clang" } else { "clang" },
131 effective_min
132 ));
133 }
134
135 Ok(version)
136 })
137 .clone()
138}
139
140fn parse_clang_version(output: &str) -> Option<u32> {
142 for line in output.lines() {
145 if line.contains("clang version")
146 && let Some(idx) = line.find("version ")
147 {
148 let after_version = &line[idx + 8..];
149 let major: String = after_version
151 .chars()
152 .take_while(|c| c.is_ascii_digit())
153 .collect();
154 if !major.is_empty() {
155 return major.parse().ok();
156 }
157 }
158 }
159 None
160}
161
162pub fn compile_file(source_path: &Path, output_path: &Path, keep_ir: bool) -> Result<(), String> {
164 compile_file_with_config(
165 source_path,
166 output_path,
167 keep_ir,
168 &CompilerConfig::default(),
169 )
170}
171
172pub fn compile_file_with_config(
177 source_path: &Path,
178 output_path: &Path,
179 keep_ir: bool,
180 config: &CompilerConfig,
181) -> Result<(), String> {
182 let source = fs::read_to_string(source_path)
184 .map_err(|e| format!("Failed to read source file: {}", e))?;
185
186 let mut parser = Parser::new(&source);
188 let program = parser.parse()?;
189
190 let (mut program, ffi_includes) = if !program.includes.is_empty() {
192 let stdlib_path = find_stdlib();
193 let mut resolver = Resolver::new(stdlib_path);
194 let result = resolver.resolve(source_path, program)?;
195 (result.program, result.ffi_includes)
196 } else {
197 (program, Vec::new())
198 };
199
200 let mut ffi_bindings = ffi::FfiBindings::new();
202 for ffi_name in &ffi_includes {
203 let manifest_content = ffi::get_ffi_manifest(ffi_name)
204 .ok_or_else(|| format!("FFI manifest '{}' not found", ffi_name))?;
205 let manifest = ffi::FfiManifest::parse(manifest_content)?;
206 ffi_bindings.add_manifest(&manifest)?;
207 }
208
209 for manifest_path in &config.ffi_manifest_paths {
211 let manifest_content = fs::read_to_string(manifest_path).map_err(|e| {
212 format!(
213 "Failed to read FFI manifest '{}': {}",
214 manifest_path.display(),
215 e
216 )
217 })?;
218 let manifest = ffi::FfiManifest::parse(&manifest_content).map_err(|e| {
219 format!(
220 "Failed to parse FFI manifest '{}': {}",
221 manifest_path.display(),
222 e
223 )
224 })?;
225 ffi_bindings.add_manifest(&manifest)?;
226 }
227
228 program.generate_constructors()?;
231
232 check_collisions(&program.words)?;
234
235 check_union_collisions(&program.unions)?;
237
238 if program.find_word("main").is_none() {
240 return Err("No main word defined".to_string());
241 }
242
243 let mut external_names = config.external_names();
246 external_names.extend(ffi_bindings.function_names());
247 program.validate_word_calls_with_externals(&external_names)?;
248
249 let call_graph = call_graph::CallGraph::build(&program);
251
252 let mut type_checker = TypeChecker::new();
254 type_checker.set_call_graph(call_graph.clone());
255
256 if !config.external_builtins.is_empty() {
259 for builtin in &config.external_builtins {
260 if builtin.effect.is_none() {
261 return Err(format!(
262 "External builtin '{}' is missing a stack effect declaration.\n\
263 All external builtins must have explicit effects for type safety.",
264 builtin.seq_name
265 ));
266 }
267 }
268 let external_effects: Vec<(&str, &types::Effect)> = config
269 .external_builtins
270 .iter()
271 .map(|b| (b.seq_name.as_str(), b.effect.as_ref().unwrap()))
272 .collect();
273 type_checker.register_external_words(&external_effects);
274 }
275
276 if !ffi_bindings.functions.is_empty() {
278 let ffi_effects: Vec<(&str, &types::Effect)> = ffi_bindings
279 .functions
280 .values()
281 .map(|f| (f.seq_name.as_str(), &f.effect))
282 .collect();
283 type_checker.register_external_words(&ffi_effects);
284 }
285
286 type_checker.check_program(&program)?;
287
288 let quotation_types = type_checker.take_quotation_types();
290 let statement_types = type_checker.take_statement_top_types();
292
293 let mut codegen = if config.pure_inline_test {
298 CodeGen::new_pure_inline_test()
299 } else {
300 CodeGen::new()
301 };
302 let ir = codegen
303 .codegen_program_with_ffi(
304 &program,
305 quotation_types,
306 statement_types,
307 config,
308 &ffi_bindings,
309 )
310 .map_err(|e| e.to_string())?;
311
312 let ir_path = output_path.with_extension("ll");
314 fs::write(&ir_path, ir).map_err(|e| format!("Failed to write IR file: {}", e))?;
315
316 check_clang_version()?;
318
319 let runtime_path = std::env::temp_dir().join("libseq_runtime.a");
321 {
322 let mut file = fs::File::create(&runtime_path)
323 .map_err(|e| format!("Failed to create runtime lib: {}", e))?;
324 file.write_all(RUNTIME_LIB)
325 .map_err(|e| format!("Failed to write runtime lib: {}", e))?;
326 }
327
328 let opt_flag = match config.optimization_level {
330 config::OptimizationLevel::O0 => "-O0",
331 config::OptimizationLevel::O1 => "-O1",
332 config::OptimizationLevel::O2 => "-O2",
333 config::OptimizationLevel::O3 => "-O3",
334 };
335 let mut clang = Command::new("clang");
336 clang
337 .arg(opt_flag)
338 .arg(&ir_path)
339 .arg("-o")
340 .arg(output_path)
341 .arg("-L")
342 .arg(runtime_path.parent().unwrap())
343 .arg("-lseq_runtime");
344
345 for lib_path in &config.library_paths {
347 clang.arg("-L").arg(lib_path);
348 }
349
350 for lib in &config.libraries {
352 clang.arg("-l").arg(lib);
353 }
354
355 for lib in &ffi_bindings.linker_flags {
357 clang.arg("-l").arg(lib);
358 }
359
360 let output = clang
361 .output()
362 .map_err(|e| format!("Failed to run clang: {}", e))?;
363
364 fs::remove_file(&runtime_path).ok();
366
367 if !output.status.success() {
368 let stderr = String::from_utf8_lossy(&output.stderr);
369 return Err(format!("Clang compilation failed:\n{}", stderr));
370 }
371
372 if !keep_ir {
374 fs::remove_file(&ir_path).ok();
375 }
376
377 Ok(())
378}
379
380pub fn compile_to_ir(source: &str) -> Result<String, String> {
382 compile_to_ir_with_config(source, &CompilerConfig::default())
383}
384
385pub fn compile_to_ir_with_config(source: &str, config: &CompilerConfig) -> Result<String, String> {
387 let mut parser = Parser::new(source);
388 let mut program = parser.parse()?;
389
390 if !program.unions.is_empty() {
392 program.generate_constructors()?;
393 }
394
395 let external_names = config.external_names();
396 program.validate_word_calls_with_externals(&external_names)?;
397
398 let mut type_checker = TypeChecker::new();
399
400 if !config.external_builtins.is_empty() {
403 for builtin in &config.external_builtins {
404 if builtin.effect.is_none() {
405 return Err(format!(
406 "External builtin '{}' is missing a stack effect declaration.\n\
407 All external builtins must have explicit effects for type safety.",
408 builtin.seq_name
409 ));
410 }
411 }
412 let external_effects: Vec<(&str, &types::Effect)> = config
413 .external_builtins
414 .iter()
415 .map(|b| (b.seq_name.as_str(), b.effect.as_ref().unwrap()))
416 .collect();
417 type_checker.register_external_words(&external_effects);
418 }
419
420 type_checker.check_program(&program)?;
421
422 let quotation_types = type_checker.take_quotation_types();
423 let statement_types = type_checker.take_statement_top_types();
424
425 let mut codegen = CodeGen::new();
426 codegen
427 .codegen_program_with_config(&program, quotation_types, statement_types, config)
428 .map_err(|e| e.to_string())
429}
430
431#[cfg(test)]
432mod tests {
433 use super::*;
434
435 #[test]
436 fn test_parse_clang_version_standard() {
437 let output = "clang version 15.0.0 (https://github.com/llvm/llvm-project)\nTarget: x86_64";
438 assert_eq!(parse_clang_version(output), Some(15));
439 }
440
441 #[test]
442 fn test_parse_clang_version_apple() {
443 let output =
444 "Apple clang version 14.0.3 (clang-1403.0.22.14.1)\nTarget: arm64-apple-darwin";
445 assert_eq!(parse_clang_version(output), Some(14));
446 }
447
448 #[test]
449 fn test_parse_clang_version_homebrew() {
450 let output = "Homebrew clang version 17.0.6\nTarget: arm64-apple-darwin23.0.0";
451 assert_eq!(parse_clang_version(output), Some(17));
452 }
453
454 #[test]
455 fn test_parse_clang_version_ubuntu() {
456 let output = "Ubuntu clang version 15.0.7\nTarget: x86_64-pc-linux-gnu";
457 assert_eq!(parse_clang_version(output), Some(15));
458 }
459
460 #[test]
461 fn test_parse_clang_version_invalid() {
462 assert_eq!(parse_clang_version("no version here"), None);
463 assert_eq!(parse_clang_version("version "), None);
464 }
465}