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 <noreply@anthropic.com>
This commit is contained in:
Your NameandClaude Opus 5.5 committed 2026-11-08 18:11:51 +01:00
1 parent 36eacc0011
commit 9b496a7b03
4 files changed
+55 -5

No files matched your search

+13
View File
@@ -25,6 +25,15 @@ pub fn check_project_c(main: &Program, modules: &[(String, Program)], clibs: Vec
c.program(main, modules) 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<cheader::Lib>) -> PResult<HProgram> {
let mut c = Checker::new();
c.clibs = clibs;
c.module_ok = true;
c.program(main, modules)
}
/// What an `import` name stands for. /// What an `import` name stands for.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
enum Target { enum Target {
@@ -123,6 +132,8 @@ struct Local {
} }
struct Checker { struct Checker {
/// A missing `main` is not an error (checking a module on its own).
module_ok: bool,
funcs: HashMap<String, FuncSig>, funcs: HashMap<String, FuncSig>,
/// Top-level constants: uses are replaced by their (call-free) value. /// Top-level constants: uses are replaced by their (call-free) value.
consts: HashMap<String, HExpr>, consts: HashMap<String, HExpr>,
@@ -508,6 +519,7 @@ fn has_break(stmts: &[HStmt]) -> bool {
impl Checker { impl Checker {
fn new() -> Checker { fn new() -> Checker {
Checker { Checker {
module_ok: false,
funcs: HashMap::new(), funcs: HashMap::new(),
consts: HashMap::new(), consts: HashMap::new(),
structs: HashMap::new(), structs: HashMap::new(),
@@ -913,6 +925,7 @@ impl Checker {
fn check_main(&self, p: &Program) -> PResult<()> { fn check_main(&self, p: &Program) -> PResult<()> {
match self.funcs.get("main") { match self.funcs.get("main") {
None if self.module_ok => {}
None => { None => {
return Err(Diag::new( return Err(Diag::new(
"there is no `main` function; a program starts at `func main() { }`", "there is no `main` function; a program starts at `func main() { }`",
+29 -4
View File
@@ -47,8 +47,18 @@ pub fn compile_to_c(src: &str) -> PResult<String> {
pub fn compile_project( pub fn compile_project(
main_path: &str, main_path: &str,
main_src: &str, main_src: &str,
mut read: impl FnMut(&str) -> Option<(String, String)>, read: impl FnMut(&str) -> Option<(String, String)>,
) -> Result<String, String> { ) -> Result<String, String> {
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<crate::hir::HProgram, String> {
let mut seen: HashMap<String, (String, String)> = HashMap::new(); let mut seen: HashMap<String, (String, String)> = HashMap::new();
let loaded = loader::load(main_src, &mut |key| { let loaded = loader::load(main_src, &mut |key| {
let found = read(key); let found = read(key);
@@ -69,8 +79,11 @@ pub fn compile_project(
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect(); 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 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 libs = load_c_headers(&loaded.main, &modules, &dir).map_err(&render)?;
let hir = check::check_project_c(&loaded.main, &modules, libs).map_err(&render)?; if module_ok {
Ok(codegen_c::generate(&hir)) 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. /// 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<String, String> {
}) })
} }
/// 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 { fn unique_name(tag: &str, ext: &str) -> PathBuf {
// the counter makes names differ even when two threads ask in the same nanosecond // 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); 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)> = let modules: Vec<(String, crate::ast::Program)> =
loaded.modules.into_iter().map(|m| (m.key, m.program)).collect(); loaded.modules.into_iter().map(|m| (m.key, m.program)).collect();
let libs = load_c_headers(&loaded.main, &modules, dir)?; 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(()) Ok(())
} }
+1 -1
View File
@@ -197,7 +197,7 @@ fn main() {
Ok(p) => println!("{:#?}", p), Ok(p) => println!("{:#?}", p),
Err(d) => fail(d), Err(d) => fail(d),
}, },
"check" => match driver::compile_file(path) { "check" => match driver::check_file(path) {
Ok(_) => println!("{path}: ok"), Ok(_) => println!("{path}: ok"),
Err(e) => die(&e), Err(e) => die(&e),
}, },
+12
View File
@@ -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]); 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] #[test]
fn fixing_the_code_clears_the_diagnostics() { fn fixing_the_code_clears_the_diagnostics() {
let uri = "file:///tmp/rex-lsp-test/b.rex"; let uri = "file:///tmp/rex-lsp-test/b.rex";