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:
1 parent
a950219f1a
commit
cc893ff677
8 files changed
+151
-4
No files matched your search
+14
-1
@@ -10,6 +10,7 @@
|
||||
#include "cat/stdlib/toml.h"
|
||||
#include "cat/compiler.h"
|
||||
#include "cat/bytecode.h"
|
||||
#include "cat/module.h"
|
||||
#include "cat/types/empty.h"
|
||||
#include "cat/types/bool.h"
|
||||
#include "cat/types/number.h"
|
||||
@@ -477,14 +478,24 @@ static int lf_dofile(CAT_VM_State *vm, CAT_VALUE_Value **args, int nargs,
|
||||
fclose(f);
|
||||
cat_error_clear(&e);
|
||||
fn = cat_compiler_compile(src, &e);
|
||||
free(src);
|
||||
if (fn == NULL) {
|
||||
fprintf(stderr, "dofile: %s\n", e.message);
|
||||
free(src);
|
||||
*out = cat_types_empty();
|
||||
return 0;
|
||||
}
|
||||
/* `module` reflects the imported unit while it runs, then the
|
||||
* caller's `module` is restored. The name is the basename. */
|
||||
{
|
||||
const char *p = cat_types_text_bytes(args[0]);
|
||||
const char *base = strrchr(p, '/');
|
||||
base = (base != NULL) ? base + 1 : p;
|
||||
cat_module_enter(vm, base, p);
|
||||
}
|
||||
cat_error_clear(&e);
|
||||
cat_vm_run(vm, fn, out);
|
||||
cat_module_leave(vm);
|
||||
free(src);
|
||||
/* The compiled chunk is intentionally NOT freed: any `function`
|
||||
* definitions in it became globals whose closures point into this
|
||||
* bytecode tree. The chunk lives as long as the VM does. */
|
||||
@@ -614,5 +625,7 @@ int cat_stdlib_stdlib_install(CAT_VM_State *vm)
|
||||
cat_vm_set_global(vm, "ffi", cat_types_ffi_module());
|
||||
/* the empty object: the value for "no value" (catscript has no nil) */
|
||||
cat_vm_set_global(vm, "empty", cat_types_empty());
|
||||
/* `module` reflects the unit currently executing (name/path/dir) */
|
||||
cat_vm_set_global(vm, "module", cat_module_table("main", NULL));
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user