mod aggregate_validation; mod ast; mod codegen; mod diagnostic; mod intrinsics; mod lexer; mod modules; mod parser; mod sema; mod suggest; use diagnostic::{Diagnostic, DiagnosticSet}; use std::ffi::OsString; use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode}; const HELP: &str = "vacac — compile Vaca source files Usage: vacac [-o ] [--emit-obj ] vacac --run vacac --check vacac --emit-llvm Options may appear before or after . Use `--` before a source path that begins with `-`. Output paths may not overwrite the source file or a --link-object input. Options: -o Set executable output path (default: a.out) --emit-obj Set object-file output path --link-object Add an object file to the linker (repeatable) --link-search Add a native library search directory (repeatable) --link-lib Link a native library (repeatable; e.g. m) --run Build and run the program without keeping build artifacts --check Type-check and verify without writing build artifacts --emit-llvm Write verified LLVM IR to a file -O0, -O1, -O2, -O3 Set the emitted-code optimization level (not with --check) --gc=precise|off Select precise tracing or legacy allocation (default: precise) --json Output diagnostics as JSON on errors -q, --quiet Suppress successful compiler status messages -h, --help Show this help -V, --version Show version information "; enum OutputMode { Executable { output: PathBuf, object: Option, }, Run, Check, EmitLlvm(PathBuf), } struct Options { source: PathBuf, mode: OutputMode, quiet: bool, json: bool, optimization_level: Option, precise_gc: bool, link_objects: Vec, link_search: Vec, link_libs: Vec, program_args: Vec, } enum ParseArgs { Help, Version, Options(Options), } struct ParseError { message: String, json: bool, } impl ParseError { fn new(json: bool, message: impl Into) -> Self { Self { message: message.into(), json, } } } fn json_requested(args: impl IntoIterator) -> bool { let mut args = args.into_iter(); while let Some(argument) = args.next() { match argument.to_str() { Some("--") => return false, Some("-o") | Some("--emit-obj") | Some("--link-object") | Some("--link-search") | Some("--link-lib") | Some("--emit-llvm") => { args.next(); } Some("--json") => return true, _ => {} } } false } fn parse_args() -> Result { let json = json_requested(std::env::args_os().skip(1)); let mut args = std::env::args_os().skip(1); let mut source: Option = None; let mut positional_only = false; let mut output = PathBuf::from("a.out"); let mut object = None; let mut output_was_set = false; let mut object_was_set = false; let mut link_objects = Vec::new(); let mut link_search = Vec::new(); let mut link_libs = Vec::new(); let mut program_args = Vec::new(); let mut saw_separator = false; let mut mode: Option = None; let mut quiet = false; let mut optimization_level = None; let mut precise_gc = None; macro_rules! fail { ($($arg:tt)*) => { return Err(ParseError::new(json, format!($($arg)*))) }; } while let Some(arg) = args.next() { if !positional_only { match arg.to_str() { Some("-h") | Some("--help") => return Ok(ParseArgs::Help), Some("-V") | Some("--version") => return Ok(ParseArgs::Version), Some("--") => { positional_only = true; saw_separator = true; continue; } Some("-o") => { output = args .next() .map(PathBuf::from) .ok_or_else(|| ParseError::new(json, "-o requires a path"))?; output_was_set = true; continue; } Some("--emit-obj") => { if object_was_set { fail!("--emit-obj may be specified only once"); } object = Some( args.next() .map(PathBuf::from) .ok_or_else(|| ParseError::new(json, "--emit-obj requires a path"))?, ); object_was_set = true; continue; } Some("--link-object") => { link_objects.push( args.next().map(PathBuf::from).ok_or_else(|| { ParseError::new(json, "--link-object requires a path") })?, ); continue; } Some("--link-search") => { link_search.push(args.next().map(PathBuf::from).ok_or_else(|| { ParseError::new(json, "--link-search requires a directory") })?); continue; } Some("--link-lib") => { link_libs.push(args.next().ok_or_else(|| { ParseError::new(json, "--link-lib requires a library name") })?); continue; } Some("--check") => { set_mode(&mut mode, OutputMode::Check, json)?; continue; } Some("--run") => { set_mode(&mut mode, OutputMode::Run, json)?; continue; } Some("--emit-llvm") => { let path = args .next() .map(PathBuf::from) .ok_or_else(|| ParseError::new(json, "--emit-llvm requires a path"))?; set_mode(&mut mode, OutputMode::EmitLlvm(path), json)?; continue; } Some("-O0") => { set_optimization_level(&mut optimization_level, codegen::OptLevel::O0, json)?; continue; } Some("-O1") => { set_optimization_level(&mut optimization_level, codegen::OptLevel::O1, json)?; continue; } Some("-O2") => { set_optimization_level(&mut optimization_level, codegen::OptLevel::O2, json)?; continue; } Some("-O3") => { set_optimization_level(&mut optimization_level, codegen::OptLevel::O3, json)?; continue; } Some("--quiet") | Some("-q") => { quiet = true; continue; } Some("--json") => continue, Some("--gc=precise" | "--gc=off") => { if precise_gc.replace(arg == "--gc=precise").is_some() { fail!("--gc may be specified only once"); } continue; } Some(flag) if flag == "--gc" || flag.starts_with("--gc=") => { fail!("unsupported GC mode: {flag} (supported: --gc=precise, --gc=off)"); } Some(flag) if flag.starts_with("-O") => { fail!("unsupported optimization level: {flag} (supported: -O0, -O1, -O2, -O3)"); } Some(flag) if flag.starts_with('-') => { fail!("unknown argument: {flag} (try --help)"); } _ => {} } } if source.is_some() { if saw_separator && positional_only { program_args.push(arg); continue; } fail!( "unexpected argument: {} (try --help)", arg.to_string_lossy() ); } source = Some(PathBuf::from(arg)); } let Some(source) = source else { fail!("missing source file (try --help)"); }; if !program_args.is_empty() && !matches!(mode, Some(OutputMode::Run)) { fail!("program arguments after `--` require --run"); } let mode = match mode { Some(OutputMode::Check) => { if !link_objects.is_empty() || !link_search.is_empty() || !link_libs.is_empty() { fail!("linker inputs cannot be used with --check"); } if output_was_set || object_was_set { fail!("-o and --emit-obj cannot be used with --check"); } if optimization_level.is_some() { fail!("optimization levels cannot be used with --check"); } OutputMode::Check } Some(OutputMode::EmitLlvm(path)) => { if !link_objects.is_empty() || !link_search.is_empty() || !link_libs.is_empty() { fail!("linker inputs cannot be used with --emit-llvm"); } if output_was_set || object_was_set { fail!("-o and --emit-obj cannot be used with --emit-llvm"); } OutputMode::EmitLlvm(path) } Some(OutputMode::Run) => { if output_was_set || object_was_set { fail!("-o and --emit-obj cannot be used with --run"); } OutputMode::Run } None => OutputMode::Executable { output, object }, Some(OutputMode::Executable { .. }) => unreachable!(), }; Ok(ParseArgs::Options(Options { source, mode, quiet, json, optimization_level, precise_gc: precise_gc.unwrap_or(true), link_objects, link_search, link_libs, program_args, })) } fn set_optimization_level( slot: &mut Option, level: codegen::OptLevel, json: bool, ) -> Result<(), ParseError> { if slot.is_some() { return Err(ParseError::new( json, "optimization level may be specified only once", )); } *slot = Some(level); Ok(()) } fn set_mode( mode: &mut Option, new_mode: OutputMode, json: bool, ) -> Result<(), ParseError> { if mode.is_some() { return Err(ParseError::new( json, "output mode options may be specified only once; --check, --run, and --emit-llvm are mutually exclusive", )); } *mode = Some(new_mode); Ok(()) } fn object_path(output: &Path) -> PathBuf { let mut path = output.to_path_buf(); path.set_extension("o"); path } /// Resolve a path to an absolute form with `.`/`..` and symlinks removed. /// Output paths may not exist yet, so a missing path falls back to resolving /// its parent directory. fn normalized_path(path: &Path) -> PathBuf { if let Ok(resolved) = std::fs::canonicalize(path) { return resolved; } let parent = match path.parent() { Some(parent) if !parent.as_os_str().is_empty() => parent, _ => Path::new("."), }; match (std::fs::canonicalize(parent), path.file_name()) { (Ok(parent), Some(name)) => parent.join(name), _ => path.to_path_buf(), } } fn same_file(left: &Path, right: &Path) -> bool { normalized_path(left) == normalized_path(right) || shares_identity(left, right) } /// Existing hard links have distinct names but share one file, so overwriting /// either destroys the other. #[cfg(unix)] fn shares_identity(left: &Path, right: &Path) -> bool { use std::os::unix::fs::MetadataExt; match (std::fs::metadata(left), std::fs::metadata(right)) { (Ok(left), Ok(right)) => left.dev() == right.dev() && left.ino() == right.ino(), _ => false, } } #[cfg(not(unix))] fn shares_identity(_left: &Path, _right: &Path) -> bool { false } /// Refuse to run when an output would be written over one of the compiler's /// inputs. Overwriting the source file or a `--link-object` input destroys /// user data, and a single path cannot be both the executable and its object. fn reject_output_collisions( program: &parser::Program, mode: &OutputMode, link_objects: &[PathBuf], ) -> Result<(), Diagnostic> { let mut outputs: Vec<(&str, PathBuf)> = Vec::new(); match mode { OutputMode::Executable { output, object } => { let object = object.clone().unwrap_or_else(|| object_path(output)); if same_file(&object, output) { return Err(Diagnostic::new(format!( "object file output path `{}` is the same as the executable output path `{}`", object.display(), output.display() ))); } outputs.push(("executable", output.clone())); outputs.push(("object file", object)); } OutputMode::EmitLlvm(path) => outputs.push(("LLVM IR", path.clone())), OutputMode::Run | OutputMode::Check => {} } for (kind, output) in &outputs { for source in &program.sources { if same_file(output, Path::new(&source.path)) { return Err(Diagnostic::new(format!( "{kind} output path `{}` would overwrite the source file `{}`", output.display(), source.path ))); } } for input in link_objects { if same_file(output, input) { return Err(Diagnostic::new(format!( "{kind} output path `{}` would overwrite the linker input `{}`", output.display(), input.display() ))); } } } Ok(()) } /// Qualify relative paths that begin with `-` so the linker cannot mistake them /// for command-line options. fn linker_argument(path: &Path) -> OsString { if path.as_os_str().as_encoded_bytes().first() == Some(&b'-') { let mut prefixed = OsString::from("./"); prefixed.push(path.as_os_str()); prefixed } else { path.as_os_str().to_os_string() } } fn run(parsed: ParseArgs) -> Result { let options = match parsed { ParseArgs::Help => { print!("{HELP}"); return Ok(0); } ParseArgs::Version => { println!("vacac {}", env!("CARGO_PKG_VERSION")); return Ok(0); } ParseArgs::Options(options) => options, }; let Options { source: source_path, mode, quiet, json: _, optimization_level, precise_gc, link_objects, link_search, link_libs, program_args, } = options; let mut program = modules::load(&source_path)?; reject_output_collisions(&program, &mode, &link_objects)?; let file = source_path.display().to_string(); sema::check(&mut program).map_err(|e| { if e.source_id.is_some() || e.span.and_then(|span| span.file).is_some() { e.with_sources(&program.sources) } else { e.with_file(file.clone()) } })?; match mode { OutputMode::Check => { codegen::check(&program, precise_gc).map_err(|e| { backend_diagnostic(&program, &source_path, "code generation failed", e) })?; if !quiet { println!("checked {}", source_path.display()); } } OutputMode::EmitLlvm(path) => { codegen::emit_llvm(&program, &path, optimization_level, precise_gc).map_err(|e| { backend_diagnostic(&program, &source_path, "LLVM IR emission failed", e) })?; if !quiet { println!("wrote {}", path.display()); } } OutputMode::Executable { output, object } => { let object = object.unwrap_or_else(|| object_path(&output)); codegen::emit_object(&program, &object, optimization_level, precise_gc).map_err( |e| backend_diagnostic(&program, &source_path, "code generation failed", e), )?; let status = link_object( &object, &output, &link_objects, &link_search, &link_libs, precise_gc, )?; if !status.success() { return Err(Diagnostic::new(format!("linker exited with status {status}")).into()); } if !quiet { println!("built {}", output.display()); } } OutputMode::Run => { let temp = TempBuildDir::new()?; let executable = temp.path().join("program"); let object = temp.path().join("program.o"); codegen::emit_object(&program, &object, optimization_level, precise_gc).map_err( |e| backend_diagnostic(&program, &source_path, "code generation failed", e), )?; let status = link_object( &object, &executable, &link_objects, &link_search, &link_libs, precise_gc, )?; if !status.success() { return Err(Diagnostic::new(format!("linker exited with status {status}")).into()); } let status = Command::new(&executable) .args(&program_args) .status() .map_err(|e| Diagnostic::new(format!("failed to run program: {e}")))?; return Ok(status.code().unwrap_or(1)); } } Ok(0) } fn link_object( object: &Path, output: &Path, link_objects: &[PathBuf], link_search: &[PathBuf], link_libs: &[OsString], precise_gc: bool, ) -> Result { let mut command = Command::new("cc"); command .arg(linker_argument(object)) .args(link_objects.iter().map(|path| linker_argument(path))) .arg("-o") .arg(linker_argument(output)); let runtime = TempBuildDir::new()?; let stdlib_source = runtime.path().join("stdlib.c"); std::fs::write(&stdlib_source, include_bytes!("../runtime/stdlib.c")) .map_err(|e| Diagnostic::new(format!("could not write standard-library runtime: {e}")))?; command.args(["-std=c11", "-O2"]).arg(stdlib_source); if precise_gc { let source = runtime.path().join("gc.c"); std::fs::write(&source, include_bytes!("../runtime/gc.c")) .map_err(|e| Diagnostic::new(format!("could not write GC runtime source: {e}")))?; let header = runtime.path().join("vaca_gc.h"); std::fs::write(&header, include_bytes!("../runtime/vaca_gc.h")) .map_err(|e| Diagnostic::new(format!("could not write GC runtime header: {e}")))?; command.arg(source); } for path in link_search { command.arg("-L").arg(linker_argument(path)); } for library in link_libs { let mut argument = OsString::from("-l"); argument.push(library); command.arg(argument); } command .arg("-lm") .status() .map_err(|e| Diagnostic::new(format!("failed to run cc: {e}"))) } struct TempBuildDir(PathBuf); impl TempBuildDir { fn new() -> Result { let base = std::env::temp_dir(); for attempt in 0..100 { let path = base.join(format!("vacac-run-{}-{attempt}", std::process::id())); let mut builder = std::fs::DirBuilder::new(); #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; builder.mode(0o700); } match builder.create(&path) { Ok(()) => return Ok(Self(path)), Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, Err(error) => { return Err(Diagnostic::new(format!( "cannot create temporary build directory: {error}" ))); } } } Err(Diagnostic::new( "cannot create unique temporary build directory", )) } fn path(&self) -> &Path { &self.0 } } impl Drop for TempBuildDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } fn backend_diagnostic( program: &parser::Program, root_path: &Path, context: &str, mut error: Diagnostic, ) -> Diagnostic { let known_source = error .source_id .or_else(|| error.span.and_then(|span| span.file)) .is_some_and(|source_id| source_id < program.sources.len()); if known_source { error = error.with_sources(&program.sources); } else if error.span.is_some() && !program.sources.is_empty() { error.source_id = Some(0); if let Some(span) = error.span.as_mut() && span.file.is_none() { span.file = Some(0); } error = error.with_sources(&program.sources); } else if error.span.is_none() { error.file = Some(root_path.display().to_string()); error.message = format!("{context}: {}", error.message); } error } fn main() -> ExitCode { let parsed = match parse_args() { Ok(parsed) => parsed, Err(error) => { let diagnostic = Diagnostic::new(error.message); if error.json { eprintln!("{}", diagnostic.render_json()); } else { eprintln!("vacac: {}", diagnostic.render_human()); } return ExitCode::from(1); } }; let json_diagnostics = matches!(&parsed, ParseArgs::Options(options) if options.json); match run(parsed) { Ok(code) => ExitCode::from(code as u8), Err(errors) => { if json_diagnostics { for error in errors.diagnostics { eprintln!("{}", error.render_json()); } } else { for error in errors.diagnostics { eprintln!("vacac: {}", error.render_human()); } } ExitCode::from(1) } } } #[cfg(test)] mod tests { use super::*; #[test] fn backend_diagnostics_keep_the_originating_module_file_and_excerpt() { let program = parser::Program { enums: Vec::new(), structs: Vec::new(), globals: Vec::new(), functions: Vec::new(), extern_functions: Vec::new(), traits: Vec::new(), impls: Vec::new(), modules: Vec::new(), uses: Vec::new(), sources: vec![ crate::diagnostic::SourceFile::disk( Path::new("root.vca"), "fn main() -> i64 { 0 }\n", ), crate::diagnostic::SourceFile::disk( Path::new("nested/child.vca"), "pub fn value() { missing }\n", ), ], functions_are_qualified: true, lambda_captures: std::collections::HashMap::new(), }; let diagnostic = Diagnostic::at( diagnostic::SourceSpan { line: 1, column: 18, end_column: 25, file: Some(1), }, "undefined variable `missing`", ); let diagnostic = backend_diagnostic( &program, Path::new("root.vca"), "code generation failed", diagnostic, ); assert_eq!(diagnostic.file.as_deref(), Some("nested/child.vca")); assert_eq!( diagnostic.source_line.as_deref(), Some("pub fn value() { missing }") ); assert!(diagnostic.render_human().contains("nested/child.vca:1:18")); } #[test] fn json_prescan_respects_option_values_and_the_separator() { let args = |values: &[&str]| { values .iter() .map(|value| OsString::from(*value)) .collect::>() }; assert!(json_requested(args(&["--json", "app.vca"]))); assert!(!json_requested(args(&["-o", "--json", "--unknown"]))); assert!(json_requested(args(&["-o", "--", "--json", "--unknown"]))); assert!(!json_requested(args(&["--run", "--", "--json"]))); for option in [ "--emit-obj", "--link-object", "--link-search", "--link-lib", "--emit-llvm", ] { assert!(!json_requested(args(&[option, "--json"]))); } } #[cfg(unix)] #[test] fn temporary_build_directories_are_private() { use std::os::unix::fs::PermissionsExt; let directory = TempBuildDir::new().unwrap(); let mode = std::fs::metadata(directory.path()) .unwrap() .permissions() .mode() & 0o777; assert_eq!( mode & 0o077, 0, "temporary build directory mode is {mode:o}" ); assert_eq!( mode & 0o700, 0o700, "temporary build directory mode is {mode:o}" ); } }