!default variables can override if the value is null

This commit is contained in:
Connor Skees 2020-08-17 02:42:43 -04:00
parent a7eb78d249
commit befcb15cb5
4 changed files with 67 additions and 7 deletions

View File

@ -41,7 +41,7 @@ impl<'a> Parser<'a> {
if default {
let config_val = self.module_config.get(ident);
if self.at_root && !self.flags.in_control_flow() {
if !self.global_scope.var_exists(ident) {
if !self.global_scope.default_var_exists(ident) {
let value = if let Some(config_val) = config_val {
config_val
} else {
@ -57,7 +57,7 @@ impl<'a> Parser<'a> {
self.parse_value_from_vec(val_toks, true)?.node
};
if global && !self.global_scope.var_exists(ident) {
if global && !self.global_scope.default_var_exists(ident) {
self.global_scope.insert_var(ident, value.clone());
}
self.scopes.insert_default_var(ident, value);

View File

@ -36,6 +36,10 @@ impl Scope {
}
}
fn get_var_no_err(&self, name: Identifier) -> Option<&Value> {
self.vars.get(&name)
}
pub fn insert_var(&mut self, s: Identifier, v: Value) -> Option<Value> {
self.vars.insert(s, v)
}
@ -83,6 +87,26 @@ impl Scope {
pub fn merge_module(&mut self, other: Module) {
self.merge(other.scope);
}
pub fn default_var_exists(&mut self, s: Identifier) -> bool {
if let Some(default_var) = self.get_var_no_err(s) {
if default_var.is_null() {
false
} else {
true
}
} else {
false
}
}
pub fn insert_default_var(&mut self, s: Identifier, v: Value) -> Option<Value> {
if self.default_var_exists(s) {
None
} else {
self.insert_var(s, v)
}
}
}
#[derive(Debug, Default)]
@ -153,11 +177,7 @@ impl Scopes {
pub fn insert_default_var(&mut self, s: Identifier, v: Value) -> Option<Value> {
if let Some(scope) = self.0.last_mut() {
if scope.var_exists(s) {
None
} else {
scope.insert_var(s, v)
}
scope.insert_default_var(s, v)
} else {
panic!()
}

View File

@ -237,6 +237,16 @@ test!(
"$a: red; a {\n color: variable-exists('a')\n}\n",
"a {\n color: true;\n}\n"
);
test!(
variable_exists_local_is_null,
"a {\n $a: null; color: variable-exists(a)\n}\n",
"a {\n color: true;\n}\n"
);
test!(
variable_exists_global_is_null,
"$a: null; a {\n color: variable-exists(a)\n}\n",
"a {\n color: true;\n}\n"
);
error!(
variable_exists_not_string,
"a {\n color: variable-exists(12px)\n}\n", "Error: $name: 12px is not a string."

View File

@ -152,6 +152,36 @@ test!(
" /**/ $a /**/ : /**/ red /**/ ; /**/ ",
"/**/\n/**/\n"
);
test!(
default_var_overrides_when_null_declared_global,
"$a: null;
$a: red !default;
a {
color: $a;
}",
"a {\n color: red;\n}\n"
);
test!(
default_var_overrides_when_null_declared_local,
"a {
$a: null;
$a: red !default;
color: $a;
}",
"a {\n color: red;\n}\n"
);
test!(
default_var_overrides_when_null_declared_local_with_global_flags,
"a {
$a: null !global;
$a: red !default !global;
color: $a;
}",
"a {\n color: red;\n}\n"
);
// https://github.com/Kixiron/lasso/issues/7
test!(
regression_test_for_lasso_0_3_0,