From 64e7539536a726010c4bd5538519ee9c5b77a99a Mon Sep 17 00:00:00 2001 From: Bastiaan Marinus van de Weerd Date: Tue, 11 Jun 2024 21:59:57 -0400 Subject: [PATCH] Allow optional globals be omitted. --- src/execution.rs | 12 ++++++++++-- tests/it/execution.rs | 22 ++++++++++++++++++++++ tests/it/lazy_execution.rs | 22 ++++++++++++++++++++++ 3 files changed, 54 insertions(+), 2 deletions(-) diff --git a/src/execution.rs b/src/execution.rs index 033f240..facf728 100644 --- a/src/execution.rs +++ b/src/execution.rs @@ -68,9 +68,17 @@ impl File { for global in &self.globals { match globals.get(&global.name) { None => { - if let Some(default) = &global.default { + let default_or_null = global + .default + .as_ref() + .map(|default| default.to_string().into()) + .or_else(|| { + (global.quantifier == CaptureQuantifier::ZeroOrOne) + .then_some(Value::Null) + }); + if let Some(default_or_null) = default_or_null { globals - .add(global.name.clone(), default.to_string().into()) + .add(global.name.clone(), default_or_null) .map_err(|_| { ExecutionError::DuplicateVariable(format!( "global variable {} already defined", diff --git a/tests/it/execution.rs b/tests/it/execution.rs index 7d69907..86e21f8 100644 --- a/tests/it/execution.rs +++ b/tests/it/execution.rs @@ -290,6 +290,28 @@ fn can_omit_global_variable_with_default() { ); } +#[test] +fn can_omit_optional_global_variable() { + check_execution( + "pass", + indoc! {r#" + global pkgname? + + (module) + { + node n + if (is-null pkgname) { + attr (n) pkgname = "none" + } + } + "#}, + indoc! {r#" + node 0 + pkgname: "none" + "#}, + ); +} + #[test] fn cannot_omit_global_variable() { fail_execution( diff --git a/tests/it/lazy_execution.rs b/tests/it/lazy_execution.rs index 3e0395a..9864d2a 100644 --- a/tests/it/lazy_execution.rs +++ b/tests/it/lazy_execution.rs @@ -291,6 +291,28 @@ fn can_omit_global_variable_with_default() { ); } +#[test] +fn can_omit_optional_global_variable() { + check_execution( + "pass", + indoc! {r#" + global pkgname? + + (module) + { + node n + if (is-null pkgname) { + attr (n) pkgname = "none" + } + } + "#}, + indoc! {r#" + node 0 + pkgname: "none" + "#}, + ); +} + #[test] fn cannot_omit_global_variable() { fail_execution(