module: a global reflecting the current unit

`module` is now a global table describing the unit that is executing:
`name` (basename of the file), `path` and `dir` (when loaded from a
file).  It is mutable like any table, so a unit can tag itself.

- module.{h,c}: cat_module_table(name, path), plus a small enter/leave
  stack (cat_module_enter/leave) that swaps `module` for the duration
  of an import and restores the caller's afterwards.
- vm.h: the enter/leave stack lives on the VM (self-contained, no
  globals shared between VMs).
- stdlib: installs an initial `module` (name "main"); dofile/use now
  enter the imported unit and leave after it returns.
- main.c: the CLI enters the script's basename/path before running it.
- tests/module.cat + tests/module_lib.cat: name/dir/mutation + the
  swap-and-restore around `use` (105 total, all green).
This commit is contained in:
Minus committed 2026-11-17 18:38:05 +00:00
1 parent a950219f1a
commit cc893ff677
8 files changed
+151 -4

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
-- tests/module.cat -- the `module` global reflects the current unit.
--
-- `module` is a global table: `name` is the basename of the running
-- file, `path` its path and `dir` its directory. Importing another
-- file (use/dofile) swaps `module` for the duration of that file and
-- restores the caller's afterwards.
print("name:", module.name)
print("dir:", module.dir)
-- a user may mutate it like any table
module.extra = "tagged"
print("extra:", module.extra)
use("tests/module_lib.cat")
print("back:", module.name)
print("extra kept:", module.extra)
+4
View File
@@ -0,0 +1,4 @@
-- tests/module_lib.cat -- a helper imported by tests/module.cat.
-- While this file runs, `module` reflects THIS unit.
print("lib name:", module.name)
print("lib dir:", module.dir)
+11
View File
@@ -174,6 +174,17 @@ check "repr-list" "list: [a, b, _repr_]" "`echo "$out" | sed -
out=`printf 'x = 50\nx\nx + 5\n' | $BIN | tr '>' '\n' | grep -oE '[0-9]+'`
check "repl-echo" "50" "`echo "$out" | sed -n 1p`"
check "repl-state" "55" "`echo "$out" | sed -n 2p`"
# ---- the `module` global ---------------------------------------------
out=`$BIN tests/module.cat`
check "module-name" "name: module.cat" "`echo "$out" | sed -n 1p`"
check "module-dir" "dir: tests" "`echo "$out" | sed -n 2p`"
check "module-mut" "extra: tagged" "`echo "$out" | sed -n 3p`"
check "module-imp" "lib name: module_lib.cat" "`echo "$out" | sed -n 4p`"
check "module-impdir" "lib dir: tests" "`echo "$out" | sed -n 5p`"
check "module-back" "back: module.cat" "`echo "$out" | sed -n 6p`"
check "module-kept" "extra kept: tagged" "`echo "$out" | sed -n 7p`"
# ---- bytecode injection (fc_fn) --------------------------------------
out=`$BIN tests/bc.cat`