imports: use name imports by module name

`use` only accepted a path expression, so `use math` read `math` as a
global and failed.  Now the operand may be a bare module name.

- compiler: `use NAME` emits the name as a constant (a path expression
  still works, e.g. `use "std/io/io.cat"` or `use (expr)`).
- stdlib: `use_resolve` maps a name to a path, trying, in order:
  <name>, <name>.cat, std/<name>/<name>.cat, <name>/<name>.cat,
  std/<name>.cat.  A path (contains `.cat` or `/`) is used as-is.
- stdlib: a missing module now raises (per project rule: no silent
  failure) -- "cannot import module 'X'" -- instead of doing nothing.
- tests/import.cat: `use math`, `use io` and a path string (109 total,
  all green).
This commit is contained in:
Minus committed 2026-11-17 18:40:10 +00:00
1 parent cc893ff677
commit 83629d0e1e
4 files changed
+81 -8

No files matched your search

+11 -4
View File
@@ -744,12 +744,19 @@ static void stat(Compiler *c)
}
case CAT_LEXER_TOK_USE:
/* `use expr` imports another catscript source file: it reads,
* compiles and runs that file in the current VM (like dofile),
* so its definitions become available here. */
/* `use name` imports a module: its source is read, compiled and
* run in the current VM, so its definitions become available
* here. The operand is a module name (`math`) or a path
* (`"std/math/math.cat"`); the runtime resolves names. */
next(c);
emit(c, CAT_BYTECODE_OP_GETGLOBAL, add_string(c, "use"), 0, line);
expr(c);
if (check(c, CAT_LEXER_TOK_NAME)) {
emit(c, CAT_BYTECODE_OP_CONST, add_string(c, c->tok.text),
0, line);
next(c);
} else {
expr(c);
}
emit(c, CAT_BYTECODE_OP_CALL, 1, 0, line);
emit(c, CAT_BYTECODE_OP_POP, 0, 0, line);
accept(c, CAT_LEXER_TOK_SEMI);