From 8616f13a71e3fc186e01bdb4ada60503f233be99 Mon Sep 17 00:00:00 2001 From: Adam Joseph Date: Wed, 26 Oct 2022 05:16:04 -0700 Subject: feat(tvix/eval): builtins.import without RefCell CL/6867 added support for builtins.import, which required a cyclic reference import->globals->builtins->import. This was implemented using a RefCell, which makes it possible to mutate the builtins during evaluation. The commit message for CL/6867 expressed a desire to eliminate this possibility: This opens up a potentially dangerous footgun in which we could mutate the builtins at runtime leading to different compiler invocations seeing different builtins, so it'd be nice to have some kind of "finalised" status for them or some such, but I'm not sure how to represent that atm. This CL replaces the RefCell with Rc::new_cyclic(), making the globals/builtins immutable once again. At VM runtime (once opcodes start executing) everything is the same as before this CL, except that the Rc> introduced by CL/6867 is turned into an rc::Weak<>. The function passed to Rc::new_cyclic works very similarly to overlays in nixpkgs: a function takes its own result as an argument. However instead of laziness "breaking the cycle", Rust's Rc::new_cyclic() instead uses an rc::Weak. This is done to prevent memory leaks rather than divergence. This CL also resolves the following TODO from CL/6867: // TODO: encapsulate this import weirdness in builtins The main disadvantage of this CL is the fact that the VM now must ensure that it holds a strong reference to the globals while a program is executing; failure to do so will cause a panic when the weak reference in the builtins is upgrade()d. In theory it should be possible to create strong reference cycles the same way Rc::new_cyclic() creates weak cycles, but these cycles would cause a permanent memory leak -- without either an rc::Weak or RefCell there is no way to break the cycle. At some point we will have to implement some form of cycle collection; whatever library we choose for that purpose is likely to provide an "immutable strong reference cycle" primitive similar to Rc::new_cyclic(), and we should be able to simply drop it in. Signed-off-by: Adam Joseph Change-Id: I34bb5821628eb97e426bdb880b02e2097402adb7 Reviewed-on: https://cl.tvl.fyi/c/depot/+/7097 Tested-by: BuildkiteCI Reviewed-by: tazjin --- corp/tvixbolt/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'corp/tvixbolt/src/main.rs') diff --git a/corp/tvixbolt/src/main.rs b/corp/tvixbolt/src/main.rs index eaeffe38cb33..3aeb403482a2 100644 --- a/corp/tvixbolt/src/main.rs +++ b/corp/tvixbolt/src/main.rs @@ -313,7 +313,7 @@ fn eval(model: &Model) -> Output { &root_expr, Some("/nixbolt".into()), file.clone(), - Rc::new(RefCell::new(tvix_eval::global_builtins())), + tvix_eval::prepare_globals(Box::new(tvix_eval::global_builtins(source.clone()))), &mut compilation_observer, ) .unwrap(); -- cgit 1.4.1