Skip to content

Commit 8d0c5dc

Browse files
committed
fix: accept SQBRPYTHON factory loops that wrap specs in a call
A factory loop now records every name its iterable loads, so loops over enumerate(SPECS) or sorted(SPECS) read the spec instead of the builtin.
1 parent f6c6c3f commit 8d0c5dc

4 files changed

Lines changed: 41 additions & 13 deletions

File tree

‎crates/sqlbuild-pysource/src/node_units/_helpers/functions.rs‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! A function's decorators, signature and body shape, and the decorated functions inside it.
22
3+
use ruff_python_ast::visitor::{Visitor, walk_expr};
34
use ruff_python_ast::{Decorator, Expr, Parameter, Stmt, StmtFunctionDef};
45
use ruff_python_parser::{Mode, ParseOptions};
56
use ruff_text_size::Ranged;
@@ -55,7 +56,7 @@ pub(crate) fn unit_function(function: &StmtFunctionDef, source: &UnitText<'_>) -
5556
.iter()
5657
.filter_map(|node| match node {
5758
CpythonNode::Stmt(Stmt::For(loop_statement)) => {
58-
Some(root_name(&loop_statement.iter))
59+
Some(loaded_names(&loop_statement.iter))
5960
}
6061
_ => None,
6162
})
@@ -192,13 +193,23 @@ fn string_expression(text: &str) -> Option<Expr> {
192193
Some(*parsed.try_into_expression()?.into_syntax().body)
193194
}
194195

195-
/// The name an iterable is read from: `SPECS` for `SPECS`, `SPECS.items()`, `SPECS[1:]` or `SPECS.rows`.
196-
fn root_name(expression: &Expr) -> Option<String> {
197-
match expression {
198-
Expr::Name(name) => Some(name.id.to_string()),
199-
Expr::Attribute(attribute) => root_name(&attribute.value),
200-
Expr::Call(call) => root_name(&call.func),
201-
Expr::Subscript(subscript) => root_name(&subscript.value),
202-
_ => None,
196+
/// Every name `expression` loads, in source order: `enumerate` and `SPECS` for `enumerate(SPECS.items())`.
197+
fn loaded_names(expression: &Expr) -> Vec<String> {
198+
let mut names = LoadedNames::default();
199+
names.visit_expr(expression);
200+
names.names
201+
}
202+
203+
#[derive(Default)]
204+
struct LoadedNames {
205+
names: Vec<String>,
206+
}
207+
208+
impl<'a> Visitor<'a> for LoadedNames {
209+
fn visit_expr(&mut self, expression: &'a Expr) {
210+
if let Expr::Name(name) = expression {
211+
self.names.push(name.id.to_string());
212+
}
213+
walk_expr(self, expression);
203214
}
204215
}

‎crates/sqlbuild-pysource/src/node_units/models.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,8 @@ pub struct UnitFunction {
7171
pub delegation: Option<bool>,
7272
/// The decorated functions defined anywhere in the body.
7373
pub inner: Vec<UnitFunction>,
74-
/// The name each `for` loop in the body reads its iterable from, such as `SPECS` for `SPECS.items()`; `None` when it reads no name.
75-
pub loops: Vec<Option<String>>,
74+
/// The names each `for` loop's iterable in the body loads, such as `enumerate` and `SPECS` for `enumerate(SPECS.items())`.
75+
pub loops: Vec<Vec<String>>,
7676
}
7777

7878
/// A decorator by its last name, the keywords it is called with and the names its `depends_on` reads.

‎crates/sqlbuild-pysource/src/node_units/tests/test_node_unit_module.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ fn given_declaration_when_reading_then_signature_body_and_inner_declarations_are
131131
inner: vec![],
132132
loops: vec![],
133133
}],
134-
loops: vec![Some("TABLES".to_owned()), Some("specs".to_owned())],
134+
loops: vec![names(&["TABLES"]), names(&["specs"])],
135135
},
136136
},
137137
FunctionTestCase {

‎crates/sqlbuild-rules/src/python_rules/tests/test_node_units.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -637,7 +637,7 @@ fn given_valid_shapes_and_hidden_mistakes_when_evaluating_unit_rules_then_report
637637
expected_faults: vec![],
638638
},
639639
PythonRunTestCase {
640-
description: "a factory may read specs through a method or a module attribute, and loop again inside",
640+
description: "a factory may read specs through a method, a module attribute or a builtin call, and loop again inside",
641641
files: &[
642642
(
643643
"python/orders/regions/constants.py",
@@ -667,6 +667,23 @@ def region_exports():
667667
"#,
668668
),
669669
("python/orders/regions/main.py", TASK_MAIN),
670+
("python/orders/ranked/constants.py", "SPECS: dict = {}\n"),
671+
(
672+
"python/orders/ranked/node.py",
673+
r#"from .constants import SPECS
674+
from .main import main
675+
676+
677+
@factory
678+
def ranked_exports():
679+
for rank, region in enumerate(sorted(SPECS)):
680+
681+
@task(name=f"export_{rank}_{region}", description="E.")
682+
def export(ctx: TaskContext) -> None:
683+
return main(ctx=ctx, region=region)
684+
"#,
685+
),
686+
("python/orders/ranked/main.py", TASK_MAIN),
670687
],
671688
config: json!({ "select": ["SQBRPYTHON010"] }),
672689
expected_faults: vec![],

0 commit comments

Comments
 (0)