From 910bde692a13affcaaed88e3bcd991e07802d65b Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 8 Nov 2026 23:54:11 +0100 Subject: [PATCH] Import files from folders above: import ..a.b, import ...a.b Leading dots go up one folder less than their count (.. is one up, ... is two). The language server index and formatter understand them, and a missing file is reported with its real path. Co-Authored-By: Claude Sonnet 5.5 --- docs/10-modules-and-stdlib.md | 5 +++ docs/11-cheatsheet.md | 1 + src/driver.rs | 4 +-- src/fmt.rs | 4 +++ src/index.rs | 7 +++- src/loader.rs | 14 ++++++-- src/lsp.rs | 4 +-- src/parser.rs | 16 ++++++++- tests/fmt.rs | 6 ++++ tests/imports.rs | 66 +++++++++++++++++++++++++++++++++++ tests/lsp.rs | 20 +++++++++++ 11 files changed, 139 insertions(+), 8 deletions(-) create mode 100644 tests/imports.rs diff --git a/docs/10-modules-and-stdlib.md b/docs/10-modules-and-stdlib.md index a726cbc..c51e082 100644 --- a/docs/10-modules-and-stdlib.md +++ b/docs/10-modules-and-stdlib.md @@ -33,6 +33,11 @@ func main() { ``` - Folders work too: `import tools.fs` is the file `tools/fs.rex`, used as `fs.name`. +- Dots at the start go **up** a folder: `import ..shared.utils` is `../shared/utils.rex`, and + `import ...engine.engine` is `../../engine/engine.rex` (one dot fewer than the number of folders + up, so `..` is one folder up, `...` is two). It is still used as `utils.name` / `engine.name`. + Every import is counted from the folder of the file you run, also inside other files, so a + file in `engine/` that needs its neighbour `engine/util.rex` writes the same path as you would. - Fields are private as well unless written `pub x: int`. - Every file has its own names, so two files can both define `helper`. - Import loops and missing files are errors. An error message names the file it is in. diff --git a/docs/11-cheatsheet.md b/docs/11-cheatsheet.md index 85a6989..80f2689 100644 --- a/docs/11-cheatsheet.md +++ b/docs/11-cheatsheet.md @@ -115,6 +115,7 @@ var s: Shape = Circle{1.0} ```rex import utils // utils.rex next to this file import tools.fs // tools/fs.rex, used as fs.name +import ..shared // ../shared.rex (...x = two folders up) import os // built-in: os math time pub func f() {} // visible to other files ``` diff --git a/src/driver.rs b/src/driver.rs index 5a78f1a..330059c 100644 --- a/src/driver.rs +++ b/src/driver.rs @@ -91,7 +91,7 @@ pub fn compile_file(path: &str) -> Result { 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(); compile_project(path, &src, |key| { - let file = dir.join(format!("{}.rex", key.replace('.', "/"))); + let file = dir.join(loader::key_file(key)); std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s)) }) } @@ -102,7 +102,7 @@ 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('.', "/"))); + let file = dir.join(loader::key_file(key)); std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s)) }; check_project(path, &src, read, true).map(|_| ()) diff --git a/src/fmt.rs b/src/fmt.rs index c436868..0eac68e 100644 --- a/src/fmt.rs +++ b/src/fmt.rs @@ -409,6 +409,10 @@ fn gap(prev: &Piece, cur: &Piece, before_prev: Option<&Piece>, prev_is_prefix: b if prev_is_prefix { return false; } + // `import ..a`, `import ...a`: the dots start the path + if prev.kind == Kind::Word && pt == "import" && (ct == "." || ct == "..") { + return true; + } if prev.kind == Kind::Punct { match pt { "(" | "[" | "." | ".." => return false, diff --git a/src/index.rs b/src/index.rs index 5829f64..97d063b 100644 --- a/src/index.rs +++ b/src/index.rs @@ -152,6 +152,11 @@ impl Index { // import a.b.c let mut k = j + 1; let mut parts: Vec = Vec::new(); + let mut ups = String::new(); + while let Some(Tok::DotDot | Tok::Dot) = toks.get(k).map(|t| &t.tok) { + ups.push_str(if toks[k].tok == Tok::DotDot { ".." } else { "." }); + k += 1; + } while let Some(Tok::Ident(s)) = toks.get(k).map(|t| &t.tok) { parts.push(s.clone()); k += 1; @@ -165,7 +170,7 @@ impl Index { let aliased = matches!(toks.get(k).map(|t| &t.tok), Some(Tok::Str(_))); self.imports.push(Import { name: last.clone(), - path: if aliased { String::new() } else { parts.join(".") }, + path: if aliased { String::new() } else { format!("{ups}{}", parts.join(".")) }, header: None, picked: Vec::new(), link: None, diff --git a/src/loader.rs b/src/loader.rs index 2801009..55f5af8 100644 --- a/src/loader.rs +++ b/src/loader.rs @@ -1,10 +1,20 @@ //! Finds the files a program imports. `import utils` loads `utils.rex` from the -//! folder of the main file; `import a.b` loads `a/b.rex`. +//! folder of the main file; `import a.b` loads `a/b.rex`; `import ..a` loads `../a.rex`. use crate::ast::{Item, Program}; use crate::error::{Diag, PResult}; use crate::{parser, stdlib}; +/// The file a module key stands for, relative to the main file's folder: `a.b` is `a/b.rex`, +/// and each dot at the start beyond the first goes one folder up (`..a` is `../a.rex`, +/// `...a` is `../../a.rex`). +pub fn key_file(key: &str) -> String { + let dots = key.chars().take_while(|c| *c == '.').count(); + let rest = &key[dots..]; + let ups = "../".repeat(dots.saturating_sub(1)); + format!("{ups}{}.rex", rest.replace('.', "/")) +} + pub struct Module { /// The import path, like `utils` or `a.b`. pub key: String, @@ -48,7 +58,7 @@ fn load_imports( return Err(Diag::new(format!("circular import: {}", cycle.join(" -> ")), i.span).in_module(from)); } let Some((_, src)) = read(&key) else { - let file = format!("{}.rex", key.replace('.', "/")); + let file = key_file(&key); return Err(Diag::new( format!( "cannot find module `{key}` (looked for {file} next to your program; built-in modules: {})", diff --git a/src/lsp.rs b/src/lsp.rs index b629bc8..5a08c02 100644 --- a/src/lsp.rs +++ b/src/lsp.rs @@ -171,7 +171,7 @@ impl Server { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let here = dir.clone().unwrap_or_default(); driver::diagnose(text, &here, |key| { - let file = dir.as_ref()?.join(format!("{}.rex", key.replace('.', "/"))); + let file = dir.as_ref()?.join(crate::loader::key_file(key)); // an import that is open in the editor counts with its unsaved changes for (u, t) in docs { if uri_to_path(u).as_deref() == Some(file.as_path()) { @@ -399,7 +399,7 @@ impl Server { /// The source of the module `key` as seen from the file `uri`: open in the editor, or on disk. fn module_source(&self, uri: &str, key: &str) -> Option<(String, String)> { let dir = uri_to_path(uri)?.parent()?.to_path_buf(); - let file = dir.join(format!("{}.rex", key.replace('.', "/"))); + let file = dir.join(crate::loader::key_file(key)); let target = path_to_uri(&file); for (u, t) in &self.docs { if uri_to_path(u).as_deref() == Some(file.as_path()) { diff --git a/src/parser.rs b/src/parser.rs index d4deadc..89e0bed 100644 --- a/src/parser.rs +++ b/src/parser.rs @@ -217,7 +217,21 @@ impl Parser { } Import { alias, path, span, c: true, names, link } } else { - let mut path = self.ident()?; + // `..a.b` is one folder up, `...a.b` two up: the dots stay at the start of the path + let mut path = String::new(); + loop { + if self.eat(&Tok::DotDot) { + path.push_str(".."); + } else if !path.is_empty() && self.eat(&Tok::Dot) { + path.push('.'); + } else { + break; + } + } + if !path.is_empty() && path.len() < 2 { + return self.unexpected("a name"); + } + path.push_str(&self.ident()?); while self.eat(&Tok::Dot) { path.push('.'); path.push_str(&self.ident()?); diff --git a/tests/fmt.rs b/tests/fmt.rs index 3683e87..8c4c9bb 100644 --- a/tests/fmt.rs +++ b/tests/fmt.rs @@ -113,3 +113,9 @@ fn step_as_a_name_and_c_imports() { "import \"raylib.h\" { Color, RED }\nimport \"zlib.h\" link \"z\"\n\nfunc step(dt: f32) {}\n\nfunc main() {\n step(1.0)\n for i in 0..10 step 2 { print(i) }\n}\n" ); } + +#[test] +fn import_paths_going_up_keep_their_dots() { + let src = "import ...engine.engine\nimport ..side\nimport a.b\n\nfunc main() {\n for i in 0..3 { print(i) }\n}\n"; + assert_eq!(fmt(src), src); +} diff --git a/tests/imports.rs b/tests/imports.rs new file mode 100644 index 0000000..3ac61f0 --- /dev/null +++ b/tests/imports.rs @@ -0,0 +1,66 @@ +//! Importing files from other folders: `import ..a.b` (one folder up), `import ...a.b` (two up). + +use std::path::PathBuf; +use std::process::{Command, Output}; + +fn tree(files: &[(&str, &str)]) -> PathBuf { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("rex-imports-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + for (name, text) in files { + let f = dir.join(name); + std::fs::create_dir_all(f.parent().unwrap()).unwrap(); + std::fs::write(f, text).unwrap(); + } + dir +} + +fn rex(dir: &PathBuf, sub: &str, file: &str) -> Output { + Command::new(env!("CARGO_BIN_EXE_rex")).args(["run", file]).current_dir(dir.join(sub)).output().unwrap() +} + +#[test] +fn key_to_file() { + use rex::loader::key_file; + assert_eq!(key_file("utils"), "utils.rex"); + assert_eq!(key_file("a.b"), "a/b.rex"); + assert_eq!(key_file("..a"), "../a.rex"); + assert_eq!(key_file("..a.b"), "../a/b.rex"); + assert_eq!(key_file("...a.b"), "../../a/b.rex"); +} + +#[test] +fn import_from_a_folder_above() { + let dir = tree(&[ + ("engine/engine.rex", "pub struct Ball {\n pub x: float\n pub func moved(): float { return x + 1.0 }\n}\n\npub func hi(): int { return 7 }\n"), + ("game/app/main.rex", "import ...engine.engine\n\nfunc main() {\n var b = engine.Ball{2.0}\n print(engine.hi(), b.moved())\n}\n"), + ("game/side.rex", "pub func two(): int { return 2 }\n"), + ("game/app/other.rex", "import ..side\n\nfunc main() {\n print(side.two())\n}\n"), + ]); + let o = rex(&dir, "game/app", "main.rex"); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + assert_eq!(String::from_utf8_lossy(&o.stdout), "7 3.0\n"); + let o = rex(&dir, "game/app", "other.rex"); + assert!(o.status.success(), "{}", String::from_utf8_lossy(&o.stderr)); + assert_eq!(String::from_utf8_lossy(&o.stdout), "2\n"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn a_missing_file_above_names_the_path() { + let dir = tree(&[("a/main.rex", "import ..nope\n\nfunc main() { }\n")]); + let o = rex(&dir, "a", "main.rex"); + let err = String::from_utf8_lossy(&o.stderr).to_string(); + assert!(!o.status.success()); + assert!(err.contains("cannot find module `..nope`") && err.contains("../nope.rex"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn one_dot_is_not_an_import_path() { + let dir = tree(&[("a/main.rex", "import .nope\n\nfunc main() { }\n")]); + let o = rex(&dir, "a", "main.rex"); + assert!(!o.status.success()); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/tests/lsp.rs b/tests/lsp.rs index ab69aa0..81a6272 100644 --- a/tests/lsp.rs +++ b/tests/lsp.rs @@ -267,3 +267,23 @@ fn hover_and_hints_for_c_functions() { let s = with_header(src, "textDocument/signatureHelp", 3, 22); assert_eq!(s.get("activeParameter").and_then(Json::as_i64), Some(2), "{s:?}"); } + +#[test] +fn imports_from_a_folder_above_are_found() { + let dir = std::env::temp_dir().join(format!("rex-lsp-up-{}", std::process::id())); + std::fs::create_dir_all(dir.join("engine")).unwrap(); + std::fs::create_dir_all(dir.join("game")).unwrap(); + std::fs::write(dir.join("engine/engine.rex"), "pub func twice(x: int): int { return x * 2 }\n").unwrap(); + let uri = format!("file://{}/game/main.rex", dir.display()); + let src = "import ..engine.engine\nfunc main() {\n print(engine.twice(2))\n}\n"; + // hover on `twice` reads the signature from the file above + let mut msgs = vec![request(1, "initialize", Json::obj(vec![])), open(&uri, src)]; + msgs.push(request(2, "textDocument/hover", at(&uri, 2, 17))); + msgs.extend(exit_messages()); + let (out, _) = talk(msgs); + let _ = std::fs::remove_dir_all(&dir); + let diags = out.iter().find(|m| m.get("method").is_some()).unwrap(); + assert_eq!(diags.path(&["params", "diagnostics"]), Some(&Json::Arr(vec![])), "{diags:?}"); + let hover = out.iter().find(|m| m.get("id") == Some(&Json::Num(2.0))).unwrap(); + assert!(format!("{hover:?}").contains("twice"), "{hover:?}"); +}