mirror of
https://github.com/microsoft/regorus.git
synced 2026-08-05 02:16:11 +00:00
fix: Imports without a name binding (#543)
Handle imports that don't use the `as` clause to create a binding. These imports are bound to the last identifier in the imported path. Fix both interpreter and compiler. Add tests. fixes #541 Signed-off-by: Anand Krishnamoorthi <anakrish@microsoft.com>
This commit is contained in:
committed by
GitHub
parent
740db8a0f5
commit
9426b2ec02
@@ -335,7 +335,18 @@ impl<'a> Compiler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// No rule found - undefined variable
|
||||
// No rule found; fall back to module-level imports.
|
||||
let import_key = format!("{}.{}", &self.current_package, root);
|
||||
if let Some(import_expr) = self.policy.inner.imports.get(&import_key) {
|
||||
let import_reg =
|
||||
self.compile_rego_expr_with_span(import_expr, import_expr.span(), false)?;
|
||||
if chain.components.is_empty() {
|
||||
return Ok(import_reg);
|
||||
}
|
||||
return self.compile_chain_access(import_reg, &chain.components, span);
|
||||
}
|
||||
|
||||
// No rule or import found - undefined variable
|
||||
Err(CompilerError::UndefinedVariable {
|
||||
name: root.to_string(),
|
||||
}
|
||||
|
||||
@@ -337,8 +337,9 @@ impl Analyzer {
|
||||
}
|
||||
|
||||
for import in &m.imports {
|
||||
if let Some(var) = &import.r#as {
|
||||
scope.unscoped.insert(var.source_str());
|
||||
// Ensure default alias imports (e.g. import data.pkg.mod) are visible to this scope.
|
||||
if let Some(alias_span) = import_alias_span(import) {
|
||||
scope.unscoped.insert(alias_span.source_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1167,8 +1168,8 @@ pub fn compute_module_globals(
|
||||
|
||||
// Add import aliases specific to this module
|
||||
for import in &m.imports {
|
||||
if let Some(var) = &import.r#as {
|
||||
crate::Rc::make_mut(&mut module_globals).insert(var.text().to_string());
|
||||
if let Some(alias_span) = import_alias_span(import) {
|
||||
crate::Rc::make_mut(&mut module_globals).insert(alias_span.text().to_string());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1198,3 +1199,20 @@ pub fn compute_module_globals(
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// Extract the binding name an import contributes, even without an explicit `as` clause.
|
||||
fn import_alias_span(import: &Import) -> Option<Span> {
|
||||
if let Some(alias) = &import.r#as {
|
||||
return Some(alias.clone());
|
||||
}
|
||||
|
||||
match import.refr.as_ref() {
|
||||
RefDot { field, .. } => Some(field.0.clone()),
|
||||
RefBrack { index, .. } => match index.as_ref() {
|
||||
Expr::String { span, .. } => Some(span.clone()),
|
||||
_ => None,
|
||||
},
|
||||
Var { span, .. } => Some(span.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user