plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


9ba372c — Peter John 2026-11-12T22:52:08+05:30
loader: a program imports its own files from any of its folders; an imported file's main is its module's
compiler/cli/src/game.rs CHANGED
@@ -372,16 +372,19 @@ fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
372
372
  }
373
373
 
374
374
  /// The entry file and every file it imports, transitively (std included), read the way the
375
- /// loader resolves imports: `import a/b` is `<lib>/a/b.plum`.
375
+ /// loader resolves imports (`plum_core::loader::importCandidates`): `import a/b` is the
376
+ /// nearest `a/b.plum` from the importing file's folder up, else `<lib>/a/b.plum`. An import
377
+ /// with no file yet is watched where its importer's folder would have it.
376
378
  fn sourceFiles(entry: &Path, lib: &Path) -> Vec<PathBuf> {
377
- let mut seen = vec![entry.to_path_buf()];
379
+ let mut seen = vec![fs::canonicalize(entry).unwrap_or_else(|_| entry.to_path_buf())];
378
380
  let mut i = 0;
379
381
  while i < seen.len() {
380
382
  if let Ok(text) = fs::read_to_string(&seen[i]) {
381
383
  for l in text.lines() {
382
384
  let Some(rest) = l.trim().strip_prefix("import ") else { continue };
383
385
  let path = rest.trim().trim_matches('"');
384
- let file = lib.join(format!("{path}.plum"));
386
+ let candidates = plum_core::loader::importCandidates(path, &seen[i], lib);
387
+ let file = candidates.iter().find(|c| c.is_file()).or(candidates.first()).cloned().unwrap_or_else(|| lib.join(format!("{path}.plum")));
385
388
  if !seen.contains(&file) {
386
389
  seen.push(file);
387
390
  }
compiler/core/src/loader.rs CHANGED
@@ -58,9 +58,9 @@ pub fn loadAndMergeWithOverridesDiag(
58
58
  visited.insert(entry_canon.clone());
59
59
  let imports = entry_source.imports.clone();
60
60
  let mut parsed = prefetch(&entry_canon, &imports, lib_path, overrides);
61
- let mut files = vec![Loaded { path: entry_canon, text: entry_text, source: entry_source }];
61
+ let mut files = vec![Loaded { path: entry_canon.clone(), text: entry_text, source: entry_source }];
62
62
  for import in &imports {
63
- collectImport(import, lib_path, overrides, &mut parsed, &mut visited, &mut files)?;
63
+ collectImport(import, &entry_canon, lib_path, overrides, &mut parsed, &mut visited, &mut files)?;
64
64
  }
65
65
  shadowStdTypes(&mut files, lib_path)?;
66
66
  nativeOnlyInStd(&files, lib_path)?;
@@ -133,33 +133,60 @@ fn isStdFile(path: &Path, lib_path: &Path) -> bool {
133
133
  path.starts_with(stdDirOf(lib_path))
134
134
  }
135
135
 
136
+ /// Where `import <path>` in the file `from` may be, in the order they are tried. `std/..`
137
+ /// is only `<lib_path>/std/...`. Any other path is looked for in `from`'s folder, then in
138
+ /// each folder above it, nearest first, and last under `lib_path`: so a game's files
139
+ /// import each other by their path from the game's folder (`import OrbitRunner`,
140
+ /// `import actors/Ship`), from whichever of its folders they are in.
141
+ pub fn importCandidates(path: &str, from: &Path, lib_path: &Path) -> Vec<PathBuf> {
142
+ let file = format!("{path}.plum");
143
+ let mut out = Vec::new();
144
+ if path != "std" && !path.starts_with("std/") {
145
+ let mut dir = from.parent();
146
+ while let Some(d) = dir {
147
+ out.push(d.join(&file));
148
+ dir = d.parent();
149
+ }
150
+ }
151
+ out.push(lib_path.join(&file));
152
+ out
153
+ }
154
+
136
- /// `import std/x` -> `<lib_path>/std/x.plum`, canonicalized.
155
+ /// `import std/x` -> `<lib_path>/std/x.plum`, canonicalized; any other import, the first of
156
+ /// its [`importCandidates`] that exists, seen from the file `from` that imports it.
137
- fn resolveImport(import: &Import, lib_path: &Path) -> Loaded_<PathBuf> {
157
+ pub fn resolveImport(import: &Import, from: &Path, lib_path: &Path) -> Loaded_<PathBuf> {
138
- let resolved_path = match import.path.strip_prefix("std/") {
158
+ let candidates = importCandidates(&import.path, from, lib_path);
139
- Some(rest) => format!("std/{}", rest),
140
- None => import.path.clone(),
159
+ for c in &candidates {
160
+ if c.is_file() {
161
+ if let Ok(file) = std::fs::canonicalize(c) {
162
+ return Ok(file);
141
- };
163
+ }
164
+ }
165
+ }
142
- let target = lib_path.join(format!("{}.plum", resolved_path));
166
+ let target = candidates.last().cloned().unwrap_or_else(|| lib_path.join(format!("{}.plum", import.path)));
143
- std::fs::canonicalize(&target).map_err(|_| {
167
+ if candidates.len() > 1 {
144
- load(format!(
168
+ return Err(load(format!(
145
- "import '{}': no such file '{}'",
169
+ "import '{}': no such file '{}', in a folder above it, or '{}'",
146
170
  import.path,
171
+ candidates[0].display(),
147
172
  target.display()
148
- ))
173
+ )));
149
- })
174
+ }
175
+ Err(load(format!("import '{}': no such file '{}'", import.path, target.display())))
150
176
  }
151
177
 
152
178
  /// Parses `import`'s file and (transitively) its own imports into `files`, in the
153
179
  /// order they are merged (a file before its imports; diamonds and cycles once).
154
180
  fn collectImport(
155
181
  import: &Import,
182
+ from: &Path,
156
183
  lib_path: &Path,
157
184
  overrides: &HashMap<PathBuf, String>,
158
185
  parsed: &mut Parsed,
159
186
  visited: &mut HashSet<PathBuf>,
160
187
  files: &mut Vec<Loaded>,
161
188
  ) -> Loaded_<()> {
162
- let target_canon = resolveImport(import, lib_path)?;
189
+ let target_canon = resolveImport(import, from, lib_path)?;
163
190
  if !visited.insert(target_canon.clone()) {
164
191
  // Already loaded — a diamond import or a cycle.
165
192
  return Ok(());
@@ -172,9 +199,9 @@ fn collectImport(
172
199
  let source = source?;
173
200
  checkBuiltinImports(&target_canon, &source, lib_path)?;
174
201
  let nested = source.imports.clone();
175
- files.push(Loaded { path: target_canon, text, source });
202
+ files.push(Loaded { path: target_canon.clone(), text, source });
176
203
  for n in &nested {
177
- collectImport(n, lib_path, overrides, parsed, visited, files)?;
204
+ collectImport(n, &target_canon, lib_path, overrides, parsed, visited, files)?;
178
205
  }
179
206
  Ok(())
180
207
  }
@@ -222,9 +249,9 @@ fn prefetch(entry: &Path, imports: &[Import], lib_path: &Path, overrides: &HashM
222
249
  if n <= 1 {
223
250
  return HashMap::new();
224
251
  }
225
- let resolved = |imports: &[Import]| -> Vec<PathBuf> { imports.iter().filter_map(|i| resolveImport(i, lib_path).ok()).collect() };
252
+ let resolved = |from: &Path, imports: &[Import]| -> Vec<PathBuf> { imports.iter().filter_map(|i| resolveImport(i, from, lib_path).ok()).collect() };
226
253
  let mut work = Work { queue: Vec::new(), seen: HashSet::from([entry.to_path_buf()]), busy: 0, done: HashMap::new() };
227
- for p in resolved(imports) {
254
+ for p in resolved(entry, imports) {
228
255
  if work.seen.insert(p.clone()) {
229
256
  work.queue.push(p);
230
257
  }
@@ -243,7 +270,7 @@ fn prefetch(entry: &Path, imports: &[Import], lib_path: &Path, overrides: &HashM
243
270
  // where a sequential walk would; this thread must not die busy.
244
271
  let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| readAndParse(&path, overrides))).ok();
245
272
  let more = match &r {
246
- Some((_, Ok(src))) => resolved(&src.imports),
273
+ Some((_, Ok(src))) => resolved(&path, &src.imports),
247
274
  _ => Vec::new(),
248
275
  };
249
276
  w = work.lock().unwrap_or_else(|e| e.into_inner());
@@ -307,7 +334,7 @@ fn resolveFileModules(files: &mut [Loaded], lib_path: &Path) -> Loaded_<()> {
307
334
  .imports
308
335
  .iter()
309
336
  .filter_map(|imp| {
310
- let target = resolveImport(imp, lib_path).ok()?;
337
+ let target = resolveImport(imp, &f.path, lib_path).ok()?;
311
338
  let alias = crate::modules::moduleAlias(&imp.path);
312
339
  Some((alias, *index.get(&target)?))
313
340
  })
@@ -345,7 +372,7 @@ fn shadowStdTypes(files: &mut [Loaded], lib_path: &Path) -> Loaded_<()> {
345
372
  }
346
373
  user.extend(declaredTypes(&f.source));
347
374
  for imp in &f.source.imports {
348
- if let Ok(p) = resolveImport(imp, lib_path) {
375
+ if let Ok(p) = resolveImport(imp, &f.path, lib_path) {
349
376
  direct.insert(p);
350
377
  }
351
378
  }
compiler/core/src/modules.rs CHANGED
@@ -46,10 +46,12 @@ pub fn moduleAlias(importPath: &str) -> String {
46
46
  importPath.rsplit('/').next().unwrap_or(importPath).to_lowercase()
47
47
  }
48
48
 
49
- /// A top-level function a module may rename: not a method, export or `main`. (A host
49
+ /// A top-level function file `file` may rename: not a method or export, and not the
50
+ /// program's `main`. The `main` of an imported file (a driver or test importing a game's
51
+ /// main file, which has its own) is an ordinary function there; the entry is file 0. (A
50
- /// import keeps its host name: see `sourceFnName`.)
52
+ /// host import keeps its host name: see `sourceFnName`.)
51
- fn renamable(f: &Fn) -> bool {
53
+ fn renamable(f: &Fn, file: usize) -> bool {
52
- f.type_param.is_none() && !f.is_export && !f.is_test && f.name != "main"
54
+ f.type_param.is_none() && !f.is_export && !f.is_test && (f.name != "main" || file != 0)
53
55
  }
54
56
 
55
57
  /// The name a function was written with: `clear@gfx` is `clear`.
@@ -127,7 +129,7 @@ pub fn resolveModules(infos: Vec<ModuleInfo>, sources: &mut [&mut Source]) -> Re
127
129
  if !f.is_test && ownFns.insert(f.name.clone()) {
128
130
  *fnCount.entry(f.name.clone()).or_default() += 1;
129
131
  }
130
- if !f.is_test && !renamable(f) {
132
+ if !f.is_test && !renamable(f, i) {
131
133
  fnFixed[i].insert(f.name.clone());
132
134
  } else if !f.is_test && !infos[i].isStd {
133
135
  *userCount.entry(f.name.clone()).or_default() += 1;
@@ -588,7 +590,7 @@ pub fn fnLocals(f: &Fn) -> HashSet<String> {
588
590
  fn rewriteFile(world: &World, file: usize, source: &mut Source, errors: &mut Vec<Diagnostic>) {
589
591
  for item in &mut source.items {
590
592
  match item {
591
- Item::Fn(f) if renamable(f) && world.fnCollide.contains(&f.name) && !world.fnFixed[file].contains(&f.name) => {
593
+ Item::Fn(f) if renamable(f, file) && world.fnCollide.contains(&f.name) && !world.fnFixed[file].contains(&f.name) => {
592
594
  f.name = mangle(&f.name, &world.infos[file].name);
593
595
  }
594
596
  Item::Const(c) if isModuleConst(c) && world.constCollide.contains(&c.name) => {
compiler/core/tests/core/loader_test.rs CHANGED
@@ -695,3 +695,41 @@ fn parenGroupingGetsAHintToUseBraces() {
695
695
  let err = parseErrorOf("fun f() =\n x := foo(* 2)\n");
696
696
  assert!(!err.contains("grouping"), "{err}");
697
697
  }
698
+
699
+ /// A game outside the lib path imports its own files by their path from its folder, from
700
+ /// whichever of its folders the importing file is in: `import state` from
701
+ /// `screens/Play.plum` finds the game's `state.plum`, a folder up.
702
+ #[test]
703
+ fn aProgramImportsItsOwnFilesFromAnyOfItsFolders() {
704
+ let dir = TempDir::new().unwrap();
705
+ let lib_path = dir.path().join("libs");
706
+ fs::create_dir_all(&lib_path).unwrap();
707
+ let game = dir.path().join("game");
708
+ writeLibFile(&game, "state", "fun reset(u: Unit) -> Unit = u\n");
709
+ writeLibFile(&game, "actors/Ship", "import state\n\nstruct Ship(u: Unit)\n\nfun fly(u: Unit) -> Unit = state.reset(u)\n");
710
+ writeLibFile(&game, "screens/Play", "import state\nimport actors/Ship\n\nfun run(s: Ship) -> Unit = ship.fly(state.reset(s.u))\n");
711
+ let entry = writeLibFile(&game, "Game", "import screens/Play\nimport actors/Ship\n\nfun main(u: Unit) -> Unit = play.run(Ship(u: u))\n");
712
+ let merged = loadAndMergeDiag(&entry, &lib_path).unwrap_or_else(|e| panic!("{e:?}"));
713
+ let structs = merged.items.iter().filter(|i| matches!(i, plum_core::ast::Item::Enum(s) if s.name == "Ship")).count();
714
+ assert_eq!(structs, 1, "each file is loaded once");
715
+ }
716
+
717
+ /// The nearest file wins: a file beside the importer before one further up, and either
718
+ /// before the lib path's. `std/..` is only ever the lib path's.
719
+ #[test]
720
+ fn theNearestImportWinsAndStdIsTheLibPaths() {
721
+ let dir = TempDir::new().unwrap();
722
+ let lib_path = dir.path().join("libs");
723
+ let game = dir.path().join("game");
724
+ writeLibFile(&lib_path, "util", "fun fromLib(u: Unit) -> Unit = u\n");
725
+ writeLibFile(&game, "util", "fun fromGame(u: Unit) -> Unit = u\n");
726
+ writeLibFile(&game, "sub/util", "fun fromSub(u: Unit) -> Unit = u\n");
727
+ writeLibFile(&game, "std/Fake", "fun fake(u: Unit) -> Unit = u\n");
728
+ let from = game.join("sub/main.plum");
729
+ let found = plum_core::loader::resolveImport(&plum_core::ast::Import { path: "util".into() }, &from, &lib_path).unwrap();
730
+ assert!(found.ends_with("game/sub/util.plum"), "{}", found.display());
731
+ let up = plum_core::loader::resolveImport(&plum_core::ast::Import { path: "util".into() }, &game.join("main.plum"), &lib_path).unwrap();
732
+ assert!(up.ends_with("game/util.plum"), "{}", up.display());
733
+ let std = plum_core::loader::resolveImport(&plum_core::ast::Import { path: "std/Fake".into() }, &from, &lib_path);
734
+ assert!(std.is_err(), "std/.. resolved beside the program");
735
+ }