Compare commits

...
Author SHA1 Message Date
Dennis Kobert b11b065c6b Warn when a loop indexes footprint dependent rows 2026-11-21 17:56:36 +01:00
11 changed files with 91 additions and 11 deletions

No files matched your search

@@ -53,7 +53,8 @@ impl Compiler {
if !errors.is_empty() {
return Err(CompileError::Graph(errors));
}
let warnings = proto_network.footprint_invariance_violations();
let mut warnings = proto_network.footprint_invariance_violations();
warnings.extend(proto_network.footprint_dependent_index_violations());
proto_network.generate_stable_node_ids();
Ok(CompiledNetwork { network: proto_network, warnings })
+60 -1
View File
@@ -290,6 +290,24 @@ impl ProtoNetwork {
.collect()
}
/// Loops whose body reads the pushed index while the rows it enumerates depend on the footprint.
pub(crate) fn footprint_dependent_index_violations(&self) -> GraphErrors {
self.nodes
.iter()
.filter(|(_, node)| {
let ConstructionArgs::Nodes(inputs) = &node.construction_args else { return false };
let metadata = node.compile_metadata;
let input = |index: usize| &self.nodes[inputs[index].0 as usize].1;
let body_reads_pushed_index = (0..inputs.len()).any(|index| metadata.is_loop_body_input(index) && input(index).upstream_index_levels & 1 != 0);
let index_follows_footprint = (0..inputs.len()).any(|index| metadata.is_used_as_index_input(index) && input(index).upstream_context_features.contains(ContextFeatures::FOOTPRINT));
body_reads_pushed_index && index_follows_footprint
})
.map(|(_, node)| GraphError::new(node, GraphErrorType::FootprintDependentIndex))
.collect()
}
pub(crate) fn non_constant_inputs(&self) -> GraphErrors {
self.nodes
.iter()
@@ -648,6 +666,7 @@ pub enum GraphErrorType {
valid: Vec<NodeIOTypes>,
},
FootprintDependentInput,
FootprintDependentIndex,
NonConstantInput {
index: usize,
},
@@ -702,6 +721,10 @@ impl Debug for GraphErrorType {
f,
"Warning: an upstream node adapts to the visible canvas area, so this node's output changes when the view is panned or zoomed"
),
GraphErrorType::FootprintDependentIndex => write!(
f,
"Warning: the items this node loops over adapt to the visible canvas area, so the index read inside the loop changes when the view is panned or zoomed"
),
GraphErrorType::NonConstantInput { index } => write!(f, "Input {} must be a fixed value rather than computed by other nodes", index + 1),
GraphErrorType::MissingResource { index } => write!(
f,
@@ -1390,10 +1413,11 @@ mod test {
forwards_input: false,
constant_inputs: 0b1,
loop_body_inputs: 0,
used_as_index_inputs: 0,
index_level_input: Some(0),
};
/// A loop evaluating its second input once per row of its first input.
/// A loop over its first input's rows, evaluating its second input per row.
const MAP: NodeCompileMetadata = NodeCompileMetadata {
extract: ContextFeatures::empty(),
inject: ContextFeatures::INDEX,
@@ -1401,9 +1425,44 @@ mod test {
forwards_input: false,
constant_inputs: 0,
loop_body_inputs: 0b10,
used_as_index_inputs: 0b01,
index_level_input: None,
};
#[test]
fn loops_warn_when_their_body_reads_an_index_over_footprint_dependent_rows() {
let footprint_reader = NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT,
..Default::default()
};
let warnings = |loop_level: i64, rows_read_footprint: bool| {
let rows_metadata = if rows_read_footprint { footprint_reader } else { NodeCompileMetadata::default() };
let nodes = vec![
(NodeId(0), integer_value(loop_level)),
(NodeId(1), loop_test_node("index_reader", vec![NodeId(0)], INDEX_READER)),
(NodeId(2), integer_value(2)),
(NodeId(3), loop_test_node("rows", vec![NodeId(2)], rows_metadata)),
(NodeId(4), loop_test_node("map", vec![NodeId(3), NodeId(1)], MAP)),
];
let mut network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes,
};
network.insert_context_nullification_nodes().unwrap();
network.footprint_dependent_index_violations()
};
let violations = warnings(0, true);
assert_eq!(violations.len(), 1);
assert_eq!(violations[0].identifier, "map");
assert!(violations[0].error == GraphErrorType::FootprintDependentIndex);
assert!(warnings(1, true).is_empty(), "Reading an outer loop's index doesn't depend on the map's rows");
assert!(warnings(0, false).is_empty());
}
#[test]
fn nested_loops_keep_the_outer_index_for_the_inner_body() {
let nodes = vec![
@@ -236,6 +236,9 @@ pub struct NodeCompileMetadata {
/// Inputs evaluated inside the loop scope this node pushes an index for.
#[cfg_attr(feature = "serde", serde(default))]
pub loop_body_inputs: u64,
/// Inputs whose rows the pushed loop index enumerates.
#[cfg_attr(feature = "serde", serde(default))]
pub used_as_index_inputs: u64,
/// The input whose constant value selects the loop level this node reads the index from.
#[cfg_attr(feature = "serde", serde(default))]
pub index_level_input: Option<u8>,
@@ -250,6 +253,10 @@ impl NodeCompileMetadata {
Self::contains_input(self.loop_body_inputs, index)
}
pub fn is_used_as_index_input(&self, index: usize) -> bool {
Self::contains_input(self.used_as_index_inputs, index)
}
fn contains_input(mask: u64, index: usize) -> bool {
index < u64::BITS as usize && mask & (1 << index) != 0
}
@@ -70,6 +70,8 @@ pub struct FieldMetadata {
pub enum FieldIndexRole {
#[default]
None,
/// The loop index enumerates this input's rows, from `#[used_as_index]`.
UsedAsIndex,
/// This input's constant value selects which loop level's index is read, from `#[index_level]`.
Level,
}
+1
View File
@@ -322,6 +322,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
.iter()
.map(|field| match field.index_role {
ParsedIndexRole::None => quote!(gcore::registry::FieldIndexRole::None),
ParsedIndexRole::UsedAsIndex => quote!(gcore::registry::FieldIndexRole::UsedAsIndex),
ParsedIndexRole::Level => quote!(gcore::registry::FieldIndexRole::Level),
})
.collect();
+9 -5
View File
@@ -123,11 +123,13 @@ impl Parse for ParsedWidgetOverride {
}
}
/// How a field takes part in loop index tracking, from `#[index_level]`.
/// How a field takes part in loop index tracking, from `#[used_as_index]` or `#[index_level]`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ParsedIndexRole {
#[default]
None,
/// The loop index enumerates this field's rows.
UsedAsIndex,
/// This field's constant value selects which loop level's index the node reads.
Level,
}
@@ -867,9 +869,11 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
let exposed = extract_attribute(attrs, "expose").is_some();
let index_role = match extract_attribute(attrs, "index_level") {
Some(_) => ParsedIndexRole::Level,
None => ParsedIndexRole::None,
let index_role = match (extract_attribute(attrs, "used_as_index"), extract_attribute(attrs, "index_level")) {
(None, None) => ParsedIndexRole::None,
(Some(_), None) => ParsedIndexRole::UsedAsIndex,
(None, Some(_)) => ParsedIndexRole::Level,
(Some(_), Some(_)) => return Err(Error::new_spanned(&pat_ident, "A field cannot be both #[used_as_index] and #[index_level]")),
};
// The `#[constant]` marker makes the compiler reject inputs not fed by a value known at compile time.
@@ -906,7 +910,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
));
}
if index_role != ParsedIndexRole::None {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot be #[index_level]"));
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot be #[used_as_index] or #[index_level]"));
}
if source_id {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute"));
+3 -1
View File
@@ -398,7 +398,7 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
Ok(result)
}
#[node_macro::node(category("Data: List"), icon("NodeMap"), version(2), footprint_invariant)]
#[node_macro::node(category("Data: List"), icon("NodeMap"), version(2))]
fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
#[implementations(
@@ -416,6 +416,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
List<Gradient>,
List<Artboard>,
)]
#[used_as_index]
content: List<Item>,
#[implementations(
Context -> List<String>,
@@ -641,6 +642,7 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
List<GradientForm>,
List<GradientSpread>,
)]
#[used_as_index]
content: List<T>,
/// The attribute name (key) to write or replace.
#[constant]
+1 -1
View File
@@ -174,7 +174,7 @@ fn repeat_radial<T: Send + Clone + 'static>(
#[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Repeat on Points"), version(2))]
fn repeat_on_points<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs + InjectIndex,
points: List<Vector>,
#[used_as_index] points: List<Vector>,
#[implementations(
Context -> List<String>,
Context -> List<bool>,
+1 -1
View File
@@ -966,7 +966,7 @@ fn string_join(
#[node_macro::node(category("String"), icon("NodeStringMap"), version(2))]
fn string_map(
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
strings: List<String>,
#[used_as_index] strings: List<String>,
#[expose]
#[implementations(Context -> Item<String>)]
mapped: impl Node<Context<'static>, Output = Item<String>>,
+3 -1
View File
@@ -2046,7 +2046,9 @@ fn path_is_closed(
#[node_macro::node(category("Vector: Point"), icon("NodeMapPoints"), path(graphene_core::vector), version(2))]
fn map_points<V: MapVectorItems + Send>(
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
#[implementations(Graphic, Vector)] content: Item<V>,
#[implementations(Graphic, Vector)]
#[used_as_index]
content: Item<V>,
mapped: impl Node<Context<'static>, Output = Item<DVec2>>,
) -> Result<Item<V>, Interrupt> {
let mut content = content;
+2
View File
@@ -214,6 +214,7 @@ impl Preprocessor {
forwards_input: *forwards_input,
constant_inputs: input_mask(&|field| field.constant),
loop_body_inputs: if pushes_index { input_mask(&|field| field.lazy) } else { 0 },
used_as_index_inputs: input_mask(&|field| field.index_role == FieldIndexRole::UsedAsIndex),
index_level_input: fields.iter().position(|field| field.index_role == FieldIndexRole::Level).map(|index| index as u8),
..context_metadata
};
@@ -879,6 +880,7 @@ mod tests {
let compile_metadata = |identifier: &ProtoNodeIdentifier| preprocessor.compile_metadata.get(identifier).copied().unwrap_or_default();
let map_metadata = compile_metadata(&map::IDENTIFIER);
assert!(map_metadata.is_used_as_index_input(<map::ContentInput as NodeParameter>::INDEX));
assert!(map_metadata.is_loop_body_input(<map::MappedInput as NodeParameter>::INDEX));
assert_eq!(map_metadata.loop_body_inputs.count_ones(), 1, "Only the mapped lambda runs inside the loop");