1pub mod ast;
27pub mod builtins;
28pub mod call_graph;
29pub mod capture_analysis;
30pub mod chan_yield_lint;
31pub mod codegen;
32pub mod config;
33pub mod error_flag_lint;
34pub mod ffi;
35pub mod lint;
36pub mod normalize;
37pub mod parser;
38pub mod resolver;
39pub mod resource_lint;
40pub mod script;
41pub mod stdlib_embed;
42pub mod test_runner;
43pub mod typechecker;
44pub mod types;
45pub mod unification;
46
47pub use ast::Program;
48pub use chan_yield_lint::ChanYieldAnalyzer;
49pub use codegen::CodeGen;
50pub use config::{CompilerConfig, ExternalBuiltin, OptimizationLevel};
51pub use error_flag_lint::ErrorFlagAnalyzer;
52pub use lint::{LintConfig, LintDiagnostic, Linter, Severity};
53pub use parser::Parser;
54pub use resolver::{
55 ResolveResult, Resolver, check_collisions, check_union_collisions, find_stdlib,
56};
57pub use resource_lint::{ProgramResourceAnalyzer, ResourceAnalyzer};
58pub use typechecker::TypeChecker;
59pub use types::{Effect, StackType, Type};
60
61use std::fs;
62use std::io::Write;
63use std::path::Path;
64use std::process::Command;
65use std::sync::OnceLock;
66
67#[cfg(not(docsrs))]
70static RUNTIME_LIB: &[u8] = include_bytes!(env!("SEQ_RUNTIME_LIB_PATH"));
71
72#[cfg(docsrs)]
73static RUNTIME_LIB: &[u8] = &[];
74
75#[cfg(not(docsrs))]
83static RUNTIME_LIB_BASE: &[u8] = include_bytes!(env!("SEQ_RUNTIME_BASE_LIB_PATH"));
84
85#[cfg(docsrs)]
86static RUNTIME_LIB_BASE: &[u8] = &[];
87
88const CAPABILITY_PREFIXES: &[&str] = &["net.http.", "net.tls.", "crypto.", "regex.", "compress."];
92
93fn program_needs_full_runtime(program: &Program) -> bool {
97 program
98 .referenced_word_calls()
99 .iter()
100 .any(|w| CAPABILITY_PREFIXES.iter().any(|p| w.starts_with(p)))
101}
102
103const MIN_CLANG_VERSION: u32 = 15;
106
107static CLANG_VERSION_CHECKED: OnceLock<Result<u32, String>> = OnceLock::new();
110
111fn check_clang_version() -> Result<u32, String> {
115 CLANG_VERSION_CHECKED
116 .get_or_init(|| {
117 let output = Command::new("clang")
118 .arg("--version")
119 .output()
120 .map_err(|e| {
121 format!(
122 "Failed to run clang: {}. \
123 Please install clang {} or later.",
124 e, MIN_CLANG_VERSION
125 )
126 })?;
127
128 if !output.status.success() {
129 let stderr = String::from_utf8_lossy(&output.stderr);
130 return Err(format!(
131 "clang --version failed with exit code {:?}: {}",
132 output.status.code(),
133 stderr
134 ));
135 }
136
137 let version_str = String::from_utf8_lossy(&output.stdout);
138
139 let version = parse_clang_version(&version_str).ok_or_else(|| {
144 format!(
145 "Could not parse clang version from: {}\n\
146 seqc requires clang {} or later (for opaque pointer support).",
147 version_str.lines().next().unwrap_or(&version_str),
148 MIN_CLANG_VERSION
149 )
150 })?;
151
152 let is_apple = version_str.contains("Apple clang");
155 let effective_min = if is_apple { 14 } else { MIN_CLANG_VERSION };
156
157 if version < effective_min {
158 return Err(format!(
159 "clang version {} detected, but seqc requires {} {} or later.\n\
160 The generated LLVM IR uses opaque pointers (requires LLVM 15+).\n\
161 Please upgrade your clang installation.",
162 version,
163 if is_apple { "Apple clang" } else { "clang" },
164 effective_min
165 ));
166 }
167
168 Ok(version)
169 })
170 .clone()
171}
172
173fn parse_clang_version(output: &str) -> Option<u32> {
175 for line in output.lines() {
178 if line.contains("clang version")
179 && let Some(idx) = line.find("version ")
180 {
181 let after_version = &line[idx + 8..];
182 let major: String = after_version
184 .chars()
185 .take_while(|c| c.is_ascii_digit())
186 .collect();
187 if !major.is_empty() {
188 return major.parse().ok();
189 }
190 }
191 }
192 None
193}
194
195pub fn compile_file(source_path: &Path, output_path: &Path, keep_ir: bool) -> Result<(), String> {
197 compile_file_with_config(
198 source_path,
199 output_path,
200 keep_ir,
201 &CompilerConfig::default(),
202 )
203}
204
205pub fn compile_file_with_config(
210 source_path: &Path,
211 output_path: &Path,
212 keep_ir: bool,
213 config: &CompilerConfig,
214) -> Result<(), String> {
215 let source = fs::read_to_string(source_path)
217 .map_err(|e| format!("Failed to read source file: {}", e))?;
218
219 let mut parser = Parser::new(&source);
221 let program = parser.parse()?;
222
223 let (mut program, ffi_includes) = if !program.includes.is_empty() {
225 let stdlib_path = find_stdlib();
226 let mut resolver = Resolver::new(stdlib_path);
227 let result = resolver.resolve(source_path, program)?;
228 (result.program, result.ffi_includes)
229 } else {
230 (program, Vec::new())
231 };
232
233 let mut ffi_bindings = ffi::FfiBindings::new();
235 for ffi_name in &ffi_includes {
236 let manifest_content = ffi::get_ffi_manifest(ffi_name)
237 .ok_or_else(|| format!("FFI manifest '{}' not found", ffi_name))?;
238 let manifest = ffi::FfiManifest::parse(manifest_content)?;
239 ffi_bindings.add_manifest(&manifest)?;
240 }
241
242 for manifest_path in &config.ffi_manifest_paths {
244 let manifest_content = fs::read_to_string(manifest_path).map_err(|e| {
245 format!(
246 "Failed to read FFI manifest '{}': {}",
247 manifest_path.display(),
248 e
249 )
250 })?;
251 let manifest = ffi::FfiManifest::parse(&manifest_content).map_err(|e| {
252 format!(
253 "Failed to parse FFI manifest '{}': {}",
254 manifest_path.display(),
255 e
256 )
257 })?;
258 ffi_bindings.add_manifest(&manifest)?;
259 }
260
261 program.fixup_union_types();
265
266 program.generate_constructors()?;
269
270 normalize::lower_literal_if_combinators(&mut program);
274
275 check_collisions(&program.words)?;
277
278 check_union_collisions(&program.unions)?;
280
281 if program.find_word("main").is_none() {
283 return Err("No main word defined".to_string());
284 }
285
286 let mut external_names = config.external_names();
289 external_names.extend(ffi_bindings.function_names());
290 program.validate_word_calls_with_externals(&external_names)?;
291
292 let call_graph = call_graph::CallGraph::build(&program);
294
295 let mut type_checker = TypeChecker::new();
297 type_checker.set_call_graph(call_graph.clone());
298
299 if !config.external_builtins.is_empty() {
302 for builtin in &config.external_builtins {
303 if builtin.effect.is_none() {
304 return Err(format!(
305 "External builtin '{}' is missing a stack effect declaration.\n\
306 All external builtins must have explicit effects for type safety.",
307 builtin.seq_name
308 ));
309 }
310 }
311 let external_effects: Vec<(&str, &types::Effect)> = config
312 .external_builtins
313 .iter()
314 .map(|b| (b.seq_name.as_str(), b.effect.as_ref().unwrap()))
315 .collect();
316 type_checker.register_external_words(&external_effects);
317 }
318
319 if !ffi_bindings.functions.is_empty() {
321 let ffi_effects: Vec<(&str, &types::Effect)> = ffi_bindings
322 .functions
323 .values()
324 .map(|f| (f.seq_name.as_str(), &f.effect))
325 .collect();
326 type_checker.register_external_words(&ffi_effects);
327 }
328
329 type_checker.check_program(&program)?;
330
331 let quotation_types = type_checker.take_quotation_types();
333 let statement_types = type_checker.take_statement_top_types();
335 let aux_max_depths = type_checker.take_aux_max_depths();
337 let quotation_aux_depths = type_checker.take_quotation_aux_depths();
339 let resolved_sugar = type_checker.take_resolved_sugar();
341
342 let mut codegen = if config.pure_inline_test {
347 CodeGen::new_pure_inline_test()
348 } else {
349 CodeGen::new()
350 };
351 codegen.set_aux_slot_counts(aux_max_depths);
352 codegen.set_quotation_aux_slot_counts(quotation_aux_depths);
353 codegen.set_resolved_sugar(resolved_sugar);
354 codegen.set_source_file(source_path.to_path_buf());
355 codegen.set_call_graph(call_graph);
356 let ir = codegen
357 .codegen_program_with_ffi(
358 &program,
359 quotation_types,
360 statement_types,
361 config,
362 &ffi_bindings,
363 )
364 .map_err(|e| e.to_string())?;
365
366 let ir_path = output_path.with_extension("ll");
368 fs::write(&ir_path, ir).map_err(|e| format!("Failed to write IR file: {}", e))?;
369
370 check_clang_version()?;
372
373 let (runtime_bytes, variant) = if program_needs_full_runtime(&program) {
379 (RUNTIME_LIB, "full")
380 } else {
381 (RUNTIME_LIB_BASE, "base")
382 };
383 let runtime_dir =
384 std::env::temp_dir().join(format!("seq_runtime_{variant}_{}", std::process::id()));
385 let runtime_path = runtime_dir.join("libseq_runtime.a");
386 fs::create_dir_all(&runtime_dir)
387 .map_err(|e| format!("Failed to create runtime lib dir: {}", e))?;
388 {
389 let mut file = fs::File::create(&runtime_path)
390 .map_err(|e| format!("Failed to create runtime lib: {}", e))?;
391 file.write_all(runtime_bytes)
392 .map_err(|e| format!("Failed to write runtime lib: {}", e))?;
393 }
394
395 let opt_flag = match config.optimization_level {
397 config::OptimizationLevel::O0 => "-O0",
398 config::OptimizationLevel::O1 => "-O1",
399 config::OptimizationLevel::O2 => "-O2",
400 config::OptimizationLevel::O3 => "-O3",
401 };
402 let mut clang = Command::new("clang");
403 clang
404 .arg(opt_flag)
405 .arg("-g")
409 .arg(&ir_path)
410 .arg("-o")
411 .arg(output_path)
412 .arg("-L")
413 .arg(runtime_path.parent().unwrap())
414 .arg("-lseq_runtime")
415 .arg("-lm");
421
422 for lib_path in &config.library_paths {
424 clang.arg("-L").arg(lib_path);
425 }
426
427 for lib in &config.libraries {
429 clang.arg("-l").arg(lib);
430 }
431
432 for lib in &ffi_bindings.linker_flags {
434 clang.arg("-l").arg(lib);
435 }
436
437 if cfg!(target_os = "macos") {
445 clang.arg("-Wl,-dead_strip");
446 } else if cfg!(target_os = "linux") {
447 clang.arg("-Wl,--gc-sections");
448 }
449
450 let output = clang
451 .output()
452 .map_err(|e| format!("Failed to run clang: {}", e))?;
453
454 fs::remove_file(&runtime_path).ok();
456 fs::remove_dir(&runtime_dir).ok();
457
458 if !output.status.success() {
459 let stderr = String::from_utf8_lossy(&output.stderr);
460 return Err(format!("Clang compilation failed:\n{}", stderr));
461 }
462
463 if !keep_ir {
465 fs::remove_file(&ir_path).ok();
466 }
467
468 Ok(())
469}
470
471pub fn compile_to_ir(source: &str) -> Result<String, String> {
473 compile_to_ir_with_config(source, &CompilerConfig::default())
474}
475
476pub fn compile_to_ir_with_config(source: &str, config: &CompilerConfig) -> Result<String, String> {
478 let mut parser = Parser::new(source);
479 let mut program = parser.parse()?;
480
481 if !program.unions.is_empty() {
483 program.generate_constructors()?;
484 }
485
486 normalize::lower_literal_if_combinators(&mut program);
487
488 let external_names = config.external_names();
489 program.validate_word_calls_with_externals(&external_names)?;
490
491 let mut type_checker = TypeChecker::new();
492
493 if !config.external_builtins.is_empty() {
496 for builtin in &config.external_builtins {
497 if builtin.effect.is_none() {
498 return Err(format!(
499 "External builtin '{}' is missing a stack effect declaration.\n\
500 All external builtins must have explicit effects for type safety.",
501 builtin.seq_name
502 ));
503 }
504 }
505 let external_effects: Vec<(&str, &types::Effect)> = config
506 .external_builtins
507 .iter()
508 .map(|b| (b.seq_name.as_str(), b.effect.as_ref().unwrap()))
509 .collect();
510 type_checker.register_external_words(&external_effects);
511 }
512
513 type_checker.check_program(&program)?;
514
515 let call_graph = call_graph::CallGraph::build(&program);
517
518 let quotation_types = type_checker.take_quotation_types();
519 let statement_types = type_checker.take_statement_top_types();
520 let aux_max_depths = type_checker.take_aux_max_depths();
521 let quotation_aux_depths = type_checker.take_quotation_aux_depths();
522 let resolved_sugar = type_checker.take_resolved_sugar();
523
524 let mut codegen = CodeGen::new();
525 codegen.set_aux_slot_counts(aux_max_depths);
526 codegen.set_quotation_aux_slot_counts(quotation_aux_depths);
527 codegen.set_resolved_sugar(resolved_sugar);
528 codegen.set_call_graph(call_graph);
529 codegen
530 .codegen_program_with_config(&program, quotation_types, statement_types, config)
531 .map_err(|e| e.to_string())
532}
533
534#[cfg(test)]
535#[path = "lib/tests.rs"]
536mod tests;