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 <noreply@anthropic.com>
This commit is contained in:
Your NameandClaude Sonnet 5.5 committed 2026-11-08 23:54:11 +01:00
1 parent 9b496a7b03
commit 910bde692a
11 files changed
+139 -8

No files matched your search

+5
View File
@@ -33,6 +33,11 @@ func main() {
``` ```
- Folders work too: `import tools.fs` is the file `tools/fs.rex`, used as `fs.name`. - 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`. - Fields are private as well unless written `pub x: int`.
- Every file has its own names, so two files can both define `helper`. - 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. - Import loops and missing files are errors. An error message names the file it is in.
+1
View File
@@ -115,6 +115,7 @@ var s: Shape = Circle{1.0}
```rex ```rex
import utils // utils.rex next to this file import utils // utils.rex next to this file
import tools.fs // tools/fs.rex, used as fs.name 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 import os // built-in: os math time
pub func f() {} // visible to other files pub func f() {} // visible to other files
``` ```
+2 -2
View File
@@ -91,7 +91,7 @@ pub fn compile_file(path: &str) -> Result<String, String> {
let src = std::fs::read_to_string(path).map_err(|e| format!("error: cannot read {path}: {e}"))?; 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 dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();
compile_project(path, &src, |key| { 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)) 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 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 dir = Path::new(path).parent().map(Path::to_path_buf).unwrap_or_default();
let read = |key: &str| { 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)) std::fs::read_to_string(&file).ok().map(|s| (file.display().to_string(), s))
}; };
check_project(path, &src, read, true).map(|_| ()) check_project(path, &src, read, true).map(|_| ())
+4
View File
@@ -409,6 +409,10 @@ fn gap(prev: &Piece, cur: &Piece, before_prev: Option<&Piece>, prev_is_prefix: b
if prev_is_prefix { if prev_is_prefix {
return false; 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 { if prev.kind == Kind::Punct {
match pt { match pt {
"(" | "[" | "." | ".." => return false, "(" | "[" | "." | ".." => return false,
+6 -1
View File
@@ -152,6 +152,11 @@ impl Index {
// import a.b.c // import a.b.c
let mut k = j + 1; let mut k = j + 1;
let mut parts: Vec<String> = Vec::new(); let mut parts: Vec<String> = 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) { while let Some(Tok::Ident(s)) = toks.get(k).map(|t| &t.tok) {
parts.push(s.clone()); parts.push(s.clone());
k += 1; k += 1;
@@ -165,7 +170,7 @@ impl Index {
let aliased = matches!(toks.get(k).map(|t| &t.tok), Some(Tok::Str(_))); let aliased = matches!(toks.get(k).map(|t| &t.tok), Some(Tok::Str(_)));
self.imports.push(Import { self.imports.push(Import {
name: last.clone(), name: last.clone(),
path: if aliased { String::new() } else { parts.join(".") }, path: if aliased { String::new() } else { format!("{ups}{}", parts.join(".")) },
header: None, header: None,
picked: Vec::new(), picked: Vec::new(),
link: None, link: None,
+12 -2
View File
@@ -1,10 +1,20 @@
//! Finds the files a program imports. `import utils` loads `utils.rex` from the //! 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::ast::{Item, Program};
use crate::error::{Diag, PResult}; use crate::error::{Diag, PResult};
use crate::{parser, stdlib}; 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 { pub struct Module {
/// The import path, like `utils` or `a.b`. /// The import path, like `utils` or `a.b`.
pub key: String, pub key: String,
@@ -48,7 +58,7 @@ fn load_imports(
return Err(Diag::new(format!("circular import: {}", cycle.join(" -> ")), i.span).in_module(from)); return Err(Diag::new(format!("circular import: {}", cycle.join(" -> ")), i.span).in_module(from));
} }
let Some((_, src)) = read(&key) else { let Some((_, src)) = read(&key) else {
let file = format!("{}.rex", key.replace('.', "/")); let file = key_file(&key);
return Err(Diag::new( return Err(Diag::new(
format!( format!(
"cannot find module `{key}` (looked for {file} next to your program; built-in modules: {})", "cannot find module `{key}` (looked for {file} next to your program; built-in modules: {})",
+2 -2
View File
@@ -171,7 +171,7 @@ impl Server {
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let here = dir.clone().unwrap_or_default(); let here = dir.clone().unwrap_or_default();
driver::diagnose(text, &here, |key| { 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 // an import that is open in the editor counts with its unsaved changes
for (u, t) in docs { for (u, t) in docs {
if uri_to_path(u).as_deref() == Some(file.as_path()) { 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. /// 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)> { fn module_source(&self, uri: &str, key: &str) -> Option<(String, String)> {
let dir = uri_to_path(uri)?.parent()?.to_path_buf(); 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); let target = path_to_uri(&file);
for (u, t) in &self.docs { for (u, t) in &self.docs {
if uri_to_path(u).as_deref() == Some(file.as_path()) { if uri_to_path(u).as_deref() == Some(file.as_path()) {
+15 -1
View File
@@ -217,7 +217,21 @@ impl Parser {
} }
Import { alias, path, span, c: true, names, link } Import { alias, path, span, c: true, names, link }
} else { } 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) { while self.eat(&Tok::Dot) {
path.push('.'); path.push('.');
path.push_str(&self.ident()?); path.push_str(&self.ident()?);
+6
View File
@@ -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" "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);
}
+66
View File
@@ -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);
}
+20
View File
@@ -267,3 +267,23 @@ fn hover_and_hints_for_c_functions() {
let s = with_header(src, "textDocument/signatureHelp", 3, 22); let s = with_header(src, "textDocument/signatureHelp", 3, 22);
assert_eq!(s.get("activeParameter").and_then(Json::as_i64), Some(2), "{s:?}"); 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:?}");
}