From 9b496a7b03229062512d6b3029f9a68462e86dc5 Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 8 Nov 2026 18:11:51 +0100 Subject: [PATCH] Let a file without main be checked as a module Editor diagnostics and 'rex check' no longer report a missing main: the file may be a module other files import. 'rex build' and 'rex run' still need it. Co-Authored-By: Claude Opus 5.5 --- src/check.rs | 13 +++++++++++++ src/driver.rs | 33 +++++++++++++++++++++++++++++---- src/main.rs | 2 +- tests/lsp.rs | 12 ++++++++++++ 4 files changed, 55 insertions(+), 5 deletions(-) diff --git a/src/check.rs b/src/check.rs index 1edeb94..d953ad2 100644 --- a/src/check.rs +++ b/src/check.rs @@ -25,6 +25,15 @@ pub fn check_project_c(main: &Program, modules: &[(String, Program)], clibs: Vec c.program(main, modules) } +/// Like `check_project_c`, for checking without building (editors, `rex check`): a main file +/// without `main` is fine there, as it may be a module that other files import. +pub fn check_module_c(main: &Program, modules: &[(String, Program)], clibs: Vec) -> PResult { + let mut c = Checker::new(); + c.clibs = clibs; + c.module_ok = true; + c.program(main, modules) +} + /// What an `import` name stands for. #[derive(Clone, Debug)] enum Target { @@ -123,6 +132,8 @@ struct Local { } struct Checker { + /// A missing `main` is not an error (checking a module on its own). + module_ok: bool, funcs: HashMap, /// Top-level constants: uses are replaced by their (call-free) value. consts: HashMap, @@ -508,6 +519,7 @@ fn has_break(stmts: &[HStmt]) -> bool { impl Checker { fn new() -> Checker { Checker { + module_ok: false, funcs: HashMap::new(), consts: HashMap::new(), structs: HashMap::new(), @@ -913,6 +925,7 @@ impl Checker { fn check_main(&self, p: &Program) -> PResult<()> { match self.funcs.get("main") { + None if self.module_ok => {} None => { return Err(Diag::new( "there is no `main` function; a program starts at `func main() { }`", diff --git a/src/driver.rs b/src/driver.rs index 3ffc07c..5a78f1a 100644 --- a/src/driver.rs +++ b/src/driver.rs @@ -47,8 +47,18 @@ pub fn compile_to_c(src: &str) -> PResult { pub fn compile_project( main_path: &str, main_src: &str, - mut read: impl FnMut(&str) -> Option<(String, String)>, + read: impl FnMut(&str) -> Option<(String, String)>, ) -> Result { + Ok(codegen_c::generate(&check_project(main_path, main_src, read, false)?)) +} + +/// Load and check a program; `module_ok`: the main file may lack `main` (it is a module). +fn check_project( + main_path: &str, + main_src: &str, + mut read: impl FnMut(&str) -> Option<(String, String)>, + module_ok: bool, +) -> Result { let mut seen: HashMap = HashMap::new(); let loaded = loader::load(main_src, &mut |key| { let found = read(key); @@ -69,8 +79,11 @@ pub fn compile_project( loaded.modules.into_iter().map(|m| (m.key, m.program)).collect(); let dir = Path::new(main_path).parent().map(Path::to_path_buf).unwrap_or_default(); let libs = load_c_headers(&loaded.main, &modules, &dir).map_err(&render)?; - let hir = check::check_project_c(&loaded.main, &modules, libs).map_err(&render)?; - Ok(codegen_c::generate(&hir)) + if module_ok { + check::check_module_c(&loaded.main, &modules, libs).map_err(&render) + } else { + check::check_project_c(&loaded.main, &modules, libs).map_err(&render) + } } /// Compile the program whose main file is `path`; imports are found next to it. @@ -83,6 +96,18 @@ pub fn compile_file(path: &str) -> Result { }) } +/// Check the file at `path` (and what it imports) without building it. Unlike +/// `compile_file`, a file without `main` is fine: it may be a module. +pub fn check_file(path: &str) -> Result<(), String> { + let src = std::fs::read_to_string(path).map_err(|e| format!("error: cannot read {path}: {e}"))?; + let dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default(); + let read = |key: &str| { + let file = dir.join(format!("{}.rex", key.replace('.', "/"))); + std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s)) + }; + check_project(path, &src, read, true).map(|_| ()) +} + fn unique_name(tag: &str, ext: &str) -> PathBuf { // the counter makes names differ even when two threads ask in the same nanosecond static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -192,6 +217,6 @@ pub fn diagnose( let modules: Vec<(String, crate::ast::Program)> = loaded.modules.into_iter().map(|m| (m.key, m.program)).collect(); let libs = load_c_headers(&loaded.main, &modules, dir)?; - check::check_project_c(&loaded.main, &modules, libs)?; + check::check_module_c(&loaded.main, &modules, libs)?; Ok(()) } diff --git a/src/main.rs b/src/main.rs index 51f4014..f6de2a6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -197,7 +197,7 @@ fn main() { Ok(p) => println!("{:#?}", p), Err(d) => fail(d), }, - "check" => match driver::compile_file(path) { + "check" => match driver::check_file(path) { Ok(_) => println!("{path}: ok"), Err(e) => die(&e), }, diff --git a/tests/lsp.rs b/tests/lsp.rs index b4b3699..ab69aa0 100644 --- a/tests/lsp.rs +++ b/tests/lsp.rs @@ -81,6 +81,18 @@ fn errors_show_up_as_diagnostics() { assert!(d[0].get("message").and_then(Json::as_str).unwrap().contains("string"), "{:?}", d[0]); } +#[test] +fn a_module_without_main_has_no_errors() { + // a file that other files import doesn't need `main`; its other errors still show + let module = "pub func double(n: int): int {\n return n * 2\n}\n"; + let broken = "pub func double(n: int): int {\n return \"no\"\n}\n"; + let mut msgs = vec![open("file:///tmp/rex-lsp-test/m.rex", module), open("file:///tmp/rex-lsp-test/n.rex", broken)]; + msgs.extend(exit_messages()); + let (out, _) = talk(msgs); + assert_eq!(out[0].path(&["params", "diagnostics"]), Some(&Json::Arr(vec![])), "{:?}", out[0]); + assert_eq!(out[1].path(&["params", "diagnostics"]).map(|d| matches!(d, Json::Arr(a) if a.len() == 1)), Some(true)); +} + #[test] fn fixing_the_code_clears_the_diagnostics() { let uri = "file:///tmp/rex-lsp-test/b.rex";