Track the index of each loop level in the compiler

This commit is contained in:
Dennis Kobert committed 2026-11-21 17:55:27 +01:00
1 parent efdf51023b
commit 5ca0ed032f
12 files changed
+235 -38

No files matched your search

@@ -28,6 +28,7 @@ impl DocumentNode {
original_location: self.original_location,
compile_metadata: self.compile_metadata.unwrap_or_default(),
upstream_context_features: Default::default(),
upstream_index_levels: 0,
}
}
}
+118 -19
View File
@@ -127,6 +127,8 @@ pub struct ProtoNode {
pub(crate) compile_metadata: NodeCompileMetadata,
/// The context features read by this node and everything upstream of it.
pub upstream_context_features: ContextFeatures,
/// The loop levels whose index this node and everything upstream of it read, as a bitmask where bit `k` is the `k`-th innermost loop.
pub upstream_index_levels: u64,
}
impl Default for ProtoNode {
@@ -138,6 +140,7 @@ impl Default for ProtoNode {
original_location: OriginalLocation::default(),
compile_metadata: Default::default(),
upstream_context_features: ContextFeatures::empty(),
upstream_index_levels: 0,
}
}
}
@@ -169,6 +172,7 @@ impl ProtoNode {
},
compile_metadata: Default::default(),
upstream_context_features: ContextFeatures::empty(),
upstream_index_levels: 0,
}
}
@@ -304,22 +308,42 @@ impl ProtoNetwork {
.collect()
}
fn resolves_to_value(&self, mut id: NodeId) -> bool {
fn resolves_to_value(&self, id: NodeId) -> bool {
self.constant_value(id).is_some()
}
/// The value feeding this node, following nodes which forward their first input.
fn constant_value(&self, mut id: NodeId) -> Option<&TaggedValue> {
loop {
let Some((node_id, node)) = self.nodes.get(id.0 as usize) else { return false };
let (node_id, node) = self.nodes.get(id.0 as usize)?;
debug_assert_eq!(*node_id, id, "Node IDs must be dense indices");
match &node.construction_args {
ConstructionArgs::Value(_) => return true,
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => match inputs.first() {
Some(&input) => id = input,
None => return false,
},
_ => return false,
ConstructionArgs::Value(value) => return Some(&**value),
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => id = *inputs.first()?,
_ => return None,
}
}
}
/// The loop levels a node reads the index from itself, assuming all levels when the level isn't known at compile time.
fn own_index_levels(&self, node: &ProtoNode) -> u64 {
if !node.compile_metadata.extract.contains(ContextFeatures::INDEX) {
return 0;
}
let ConstructionArgs::Nodes(inputs) = &node.construction_args else { return u64::MAX };
let level_value = node
.compile_metadata
.index_level_input
.and_then(|index| inputs.get(index as usize))
.and_then(|&input| self.constant_value(input));
match level_value {
Some(TaggedValue::Integer(level)) => u32::try_from((*level).max(0)).ok().and_then(|level| 1_u64.checked_shl(level)).unwrap_or(u64::MAX),
_ => u64::MAX,
}
}
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_deps: ContextModification) -> NodeId {
let (_, node) = &self.nodes[node_id.0 as usize];
let mut path = node.original_location.path.clone();
@@ -330,6 +354,7 @@ impl ProtoNetwork {
}
let features = context_deps.features;
let index_levels = node.upstream_index_levels;
let forwarding = NodeCompileMetadata {
forwards_input: true,
..Default::default()
@@ -348,6 +373,7 @@ impl ProtoNetwork {
},
compile_metadata: forwarding,
upstream_context_features: features,
upstream_index_levels: index_levels,
},
));
@@ -379,6 +405,7 @@ impl ProtoNetwork {
},
compile_metadata: forwarding,
upstream_context_features: features,
upstream_index_levels: index_levels,
},
));
nullification_node_id
@@ -427,16 +454,34 @@ impl ProtoNetwork {
};
// Compute the dependencies for each branch and combine all of them
for &node in &inputs {
// An index injection without a loop body replaces the whole index stack for everything upstream
let replaces_index_stack = dependencies.inject.contains(ContextFeatures::INDEX) && dependencies.loop_body_inputs == 0;
let mut index_levels = self.own_index_levels(&self.nodes[node_index].1);
for (input_index, &node) in inputs.iter().enumerate() {
let branch = self.find_context_dependencies(node, analyzed);
self.nodes[node.0 as usize].1.upstream_context_features = branch.0.features;
// A loop body's innermost index is the one this node pushes, so its outer levels are one closer to us
let branch_index_levels = self.nodes[node.0 as usize].1.upstream_index_levels;
index_levels |= if replaces_index_stack {
0
} else if dependencies.is_loop_body_input(input_index) {
branch_index_levels >> 1
} else {
branch_index_levels
};
combined_deps.features |= branch.0.features;
combined_deps.sources.extend(&branch.0.sources);
branch_dependencies.push(branch);
}
// Remove requirements which this node provides and add requirements we have
let features = (combined_deps.features & !dependencies.inject) | dependencies.extract;
self.nodes[node_index].1.upstream_index_levels = index_levels;
// Remove requirements which this node provides and add requirements we have, with the index tracked per loop level instead
let inject = dependencies.inject - ContextFeatures::INDEX;
let mut features = (combined_deps.features & !inject) | (dependencies.extract - ContextFeatures::INDEX);
features.set(ContextFeatures::INDEX, index_levels != 0);
// If we either introduce new dependencies, we can cache all children which don't yet need that dependency
let we_introduces_new_deps = !combined_deps.features.contains(features);
@@ -451,14 +496,8 @@ impl ProtoNetwork {
}
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
// Which dependencies do we supply (and don't need ourselves)?
let net_injections = dependencies.inject.difference(dependencies.extract);
// Which dependencies still need to be met after this node?
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
// Do we satisfy any existing dependencies?
let we_supply_existing_deps = !combined_deps.features.difference(remaining_deps_from_children).is_empty();
// Do we satisfy any existing dependencies, so they are no longer needed after this node?
let we_supply_existing_deps = !combined_deps.features.difference(features).is_empty();
let new_deps = ContextModification {
features,
@@ -1330,6 +1369,66 @@ mod test {
assert!(warnings(true).is_empty());
}
fn loop_test_node(name: &'static str, inputs: Vec<NodeId>, compile_metadata: NodeCompileMetadata) -> ProtoNode {
ProtoNode {
identifier: ProtoNodeIdentifier::new(name),
call_argument: concrete!(()),
construction_args: ConstructionArgs::Nodes(inputs),
compile_metadata,
..Default::default()
}
}
fn integer_value(value: i64) -> ProtoNode {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(value).into()), vec![])
}
const INDEX_READER: NodeCompileMetadata = NodeCompileMetadata {
extract: ContextFeatures::INDEX,
inject: ContextFeatures::empty(),
footprint_invariant: false,
forwards_input: false,
constant_inputs: 0b1,
loop_body_inputs: 0,
index_level_input: Some(0),
};
/// A loop evaluating its second input once per row of its first input.
const MAP: NodeCompileMetadata = NodeCompileMetadata {
extract: ContextFeatures::empty(),
inject: ContextFeatures::INDEX,
footprint_invariant: false,
forwards_input: false,
constant_inputs: 0,
loop_body_inputs: 0b10,
index_level_input: None,
};
#[test]
fn nested_loops_keep_the_outer_index_for_the_inner_body() {
let nodes = vec![
(NodeId(0), integer_value(1)),
(NodeId(1), loop_test_node("index_reader", vec![NodeId(0)], INDEX_READER)),
(NodeId(2), integer_value(2)),
(NodeId(3), loop_test_node("inner_map", vec![NodeId(2), NodeId(1)], MAP)),
(NodeId(4), integer_value(3)),
(NodeId(5), loop_test_node("outer_map", vec![NodeId(4), NodeId(3)], MAP)),
];
let mut network = ProtoNetwork {
inputs: vec![],
output: NodeId(5),
nodes,
};
network.insert_context_nullification_nodes().unwrap();
let node_named = |name: &str| &network.nodes.iter().find(|(_, node)| node.identifier.as_str() == name).unwrap().1;
assert!(node_named("inner_map").upstream_context_features.contains(ContextFeatures::INDEX));
assert_eq!(node_named("inner_map").upstream_index_levels, 0b1);
assert_eq!(node_named("outer_map").upstream_index_levels, 0);
assert!(!node_named("outer_map").upstream_context_features.contains(ContextFeatures::INDEX));
}
#[test]
fn constant_inputs_must_resolve_to_values_through_forwarding_nodes() {
let value = || ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("name".into()).into()), vec![]);
+15 -1
View File
@@ -233,11 +233,25 @@ pub struct NodeCompileMetadata {
pub forwards_input: bool,
#[cfg_attr(feature = "serde", serde(default))]
pub constant_inputs: u64,
/// Inputs evaluated inside the loop scope this node pushes an index for.
#[cfg_attr(feature = "serde", serde(default))]
pub loop_body_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>,
}
impl NodeCompileMetadata {
pub fn requires_constant_input(&self, index: usize) -> bool {
index < u64::BITS as usize && self.constant_inputs & (1 << index) != 0
Self::contains_input(self.constant_inputs, index)
}
pub fn is_loop_body_input(&self, index: usize) -> bool {
Self::contains_input(self.loop_body_inputs, index)
}
fn contains_input(mask: u64, index: usize) -> bool {
index < u64::BITS as usize && mask & (1 << index) != 0
}
}
@@ -60,6 +60,18 @@ pub struct FieldMetadata {
pub progression: bool,
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
pub constant: bool,
pub index_role: FieldIndexRole,
/// Whether the node evaluates the input itself (an `impl Node` parameter) rather than receiving its value.
pub lazy: bool,
}
/// How an input takes part in loop index tracking.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum FieldIndexRole {
#[default]
None,
/// This input's constant value selects which loop level's index is read, from `#[index_level]`.
Level,
}
#[derive(Clone, Debug)]
+16
View File
@@ -318,6 +318,20 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
quote!(#constant)
})
.collect();
let index_role: Vec<_> = regular_fields
.iter()
.map(|field| match field.index_role {
ParsedIndexRole::None => quote!(gcore::registry::FieldIndexRole::None),
ParsedIndexRole::Level => quote!(gcore::registry::FieldIndexRole::Level),
})
.collect();
let lazy: Vec<_> = regular_fields
.iter()
.map(|field| {
let lazy = matches!(field.ty, ParsedFieldType::Node(_));
quote!(#lazy)
})
.collect();
let exposed: Vec<_> = regular_fields
.iter()
@@ -1078,6 +1092,8 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
multiline: #multiline,
progression: #progression,
constant: #constant,
index_role: #index_role,
lazy: #lazy,
},
)*
],
+31 -2
View File
@@ -123,6 +123,15 @@ impl Parse for ParsedWidgetOverride {
}
}
/// How a field takes part in loop index tracking, from `#[index_level]`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ParsedIndexRole {
#[default]
None,
/// This field's constant value selects which loop level's index the node reads.
Level,
}
#[derive(Clone, Debug)]
pub struct ParsedField {
pub pat_ident: PatIdent,
@@ -136,6 +145,7 @@ pub struct ParsedField {
pub multiline: bool,
pub progression: bool,
pub constant: bool,
pub index_role: ParsedIndexRole,
pub is_data_field: bool,
}
@@ -169,6 +179,7 @@ impl ParsedField {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
}
}
@@ -856,8 +867,14 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
let exposed = extract_attribute(attrs, "expose").is_some();
// The `#[constant]` marker makes the compiler reject inputs not fed by a value known at compile time
let constant = extract_attribute(attrs, "constant").is_some();
let index_role = match extract_attribute(attrs, "index_level") {
Some(_) => ParsedIndexRole::Level,
None => ParsedIndexRole::None,
};
// The `#[constant]` marker makes the compiler reject inputs not fed by a value known at compile time.
// An `#[index_level]` must be constant too, so the compiler knows which loop's index is read.
let constant = extract_attribute(attrs, "constant").is_some() || index_role == ParsedIndexRole::Level;
// Gives a synchronous node its `SourceId`, as async nodes get it, so it can bump its own generation
let source_id = extract_attribute(attrs, "source_id").is_some();
@@ -888,6 +905,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
"Data fields (#[data]) cannot be #[constant]. They are internal state, not node parameters",
));
}
if index_role != ParsedIndexRole::None {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot be #[index_level]"));
}
if source_id {
return Err(Error::new_spanned(&pat_ident, "Data fields (#[data]) cannot have #[source_id] attribute"));
}
@@ -1035,6 +1055,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
multiline,
progression,
constant,
index_role,
is_data_field,
})
} else {
@@ -1087,6 +1108,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
multiline,
progression,
constant,
index_role,
is_data_field,
})
}
@@ -1386,6 +1408,7 @@ mod tests {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
}],
body: TokenStream2::new(),
@@ -1448,6 +1471,7 @@ mod tests {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
},
ParsedField {
@@ -1472,6 +1496,7 @@ mod tests {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
},
],
@@ -1535,6 +1560,7 @@ mod tests {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
}],
body: TokenStream2::new(),
@@ -1601,6 +1627,7 @@ mod tests {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
}],
body: TokenStream2::new(),
@@ -1670,6 +1697,7 @@ mod tests {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
}],
body: TokenStream2::new(),
@@ -1764,6 +1792,7 @@ mod tests {
multiline: false,
progression: false,
constant: false,
index_role: ParsedIndexRole::None,
is_data_field: false,
}],
body: TokenStream2::new(),
+1
View File
@@ -88,6 +88,7 @@ fn read_index(
///
/// In programming terms: inside the double loop `i { j { ... } }`, *Loop Level* 0 = `j` and 1 = `i`. After inserting a third loop `k { ... }`, inside it, levels would be 0 = `k`, 1 = `j`, and 2 = `i`.
#[hard(0..)]
#[index_level]
loop_level: Item<i64>,
) -> Result<Item<f64>, ReadContextError> {
// The graph outside any loop runs once, as index 0
+6 -4
View File
@@ -1,7 +1,9 @@
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{AttributeValueDyn, Item, List, ListDyn, NodeIdPath};
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, Interrupt, OwnedContextImpl};
use core_types::{
ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, AnyHash, BlendMode, CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectIndex, Interrupt, OwnedContextImpl,
};
use glam::{DAffine2, DVec2};
use graphic_types::graphic::{Graphic, IntoGraphicList, is_lone_anonymous_leaf};
use graphic_types::{Artboard, Vector};
@@ -398,7 +400,7 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
#[node_macro::node(category("Data: List"), icon("NodeMap"), footprint_invariant)]
fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
#[implementations(
List<String>,
List<bool>,
@@ -448,7 +450,7 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
/// Feeds the content through the same steps over and over, each time starting from the previous result. Inside the steps, a **Read** node like **Read String** or **Read Vector** reads the result so far, and **Read Index** reads how many times around it has been.
#[node_macro::node(category("Routing"), icon("NodeIterate"))]
fn iterate<T: AnyHash + Send + Sync + CacheHash + Clone>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
/// The starting value, which the steps rework each time around.
#[implementations(String, f64, Vector, Graphic, Raster<CPU>, Color, Gradient)]
content: Item<T>,
@@ -619,7 +621,7 @@ fn write_layer_path<T: 'static + Send>(
/// monomorphizes over `T` instead of the cartesian product `(T, U)`.
#[node_macro::node(category("Data: Attribute"), icon("NodeWriteAttribute"))]
fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
/// The list to set the named attribute on (one value per item).
#[implementations(
List<String>,
+5 -5
View File
@@ -1,7 +1,7 @@
use crate::gcore::Context;
use core::f64::consts::TAU;
use core_types::list::{Item, List};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectVarArgs, Interrupt, OwnedContextImpl};
use core_types::{ATTR_TRANSFORM, CloneVarArgs, Color, Ctx, ExtractAll, InjectIndex, InjectVarArgs, Interrupt, OwnedContextImpl};
use glam::{DAffine2, DVec2};
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
@@ -10,7 +10,7 @@ use vector_types::vector::{no_paths, paths_from_list_row_attributes};
#[node_macro::node(category("Graphic"), icon("NodeRepeat"))]
fn repeat<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
#[implementations(
Context -> List<String>,
Context -> List<bool>,
@@ -55,7 +55,7 @@ fn repeat<T: Send + Clone + 'static>(
#[node_macro::node(category("Graphic"), icon("NodeRepeatArray"))]
fn repeat_array<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
#[implementations(
Context -> List<String>,
Context -> List<bool>,
@@ -116,7 +116,7 @@ fn repeat_array<T: Send + Clone + 'static>(
#[node_macro::node(category("Graphic"), icon("NodeRepeatRadial"))]
fn repeat_radial<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Ctx,
ctx: impl ExtractAll + CloneVarArgs + Ctx + InjectIndex,
#[implementations(
Context -> List<String>,
Context -> List<bool>,
@@ -173,7 +173,7 @@ fn repeat_radial<T: Send + Clone + 'static>(
#[node_macro::node(category("Graphic"), icon("NodeRepeatOnPoints"), name("Repeat on Points"))]
fn repeat_on_points<T: Send + Clone + 'static>(
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs,
ctx: impl ExtractAll + CloneVarArgs + Sync + Ctx + InjectVarArgs + InjectIndex,
points: List<Vector>,
#[implementations(
Context -> List<String>,
+2 -2
View File
@@ -13,7 +13,7 @@ use core_types::graphene_hash::CacheHash;
use core_types::list::{Item, List};
use core_types::math::float_noise::round_away_float_noise;
use core_types::misc::{format_f64, parse_f64};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, OwnedContextImpl};
use core_types::{CloneVarArgs, Context, Ctx, ExtractAll, ExtractVarArgs, InjectIndex, OwnedContextImpl};
use dyn_any::DynAny;
use glam::DVec2;
use rand::{RngExt, SeedableRng};
@@ -965,7 +965,7 @@ fn string_join(
/// Iterates over a list of strings, evaluating the mapped operation for each one. Use the **Read String** node to access the current string inside the loop.
#[node_macro::node(category("String"), icon("NodeStringMap"))]
fn string_map(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
strings: List<String>,
#[expose]
#[implementations(Context -> Item<String>)]
+2 -2
View File
@@ -11,7 +11,7 @@ use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId;
use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_FORM, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx,
ExtractAll, InjectFootprint, OwnedContextImpl,
ExtractAll, InjectFootprint, InjectIndex, OwnedContextImpl,
};
use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DMat2, DVec2};
@@ -2045,7 +2045,7 @@ fn path_is_closed(
#[node_macro::node(category("Vector: Point"), icon("NodeMapPoints"), path(graphene_core::vector))]
fn map_points<V: MapVectorItems + Send>(
ctx: impl Ctx + CloneVarArgs + ExtractAll,
ctx: impl Ctx + CloneVarArgs + ExtractAll + InjectIndex,
#[implementations(Graphic, Vector)] content: Item<V>,
mapped: impl Node<Context<'static>, Output = Item<DVec2>>,
) -> Result<Item<V>, Interrupt> {
+26 -3
View File
@@ -205,12 +205,17 @@ impl Preprocessor {
context_features,
..
} = metadata;
let constant_inputs = fields.iter().enumerate().filter(|(_, field)| field.constant).fold(0, |mask, (index, _)| mask | 1 << index);
let input_mask = |predicate: &dyn Fn(&FieldMetadata) -> bool| fields.iter().enumerate().filter(|(_, field)| predicate(field)).fold(0, |mask, (index, _)| mask | 1 << index);
let context_metadata = NodeCompileMetadata::from(context_features.as_slice());
let pushes_index = context_metadata.inject.contains(ContextFeatures::INDEX);
let node_compile_metadata = NodeCompileMetadata {
footprint_invariant: *footprint_invariant,
forwards_input: *forwards_input,
constant_inputs,
..NodeCompileMetadata::from(context_features.as_slice())
constant_inputs: input_mask(&|field| field.constant),
loop_body_inputs: if pushes_index { input_mask(&|field| field.lazy) } else { 0 },
index_level_input: fields.iter().position(|field| field.index_role == FieldIndexRole::Level).map(|index| index as u8),
..context_metadata
};
compile_metadata.insert(id.clone(), node_compile_metadata);
@@ -864,4 +869,22 @@ mod tests {
assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input");
}
}
#[test]
fn loop_index_roles_reach_the_compile_metadata() {
use graphene_std::context::read_index;
use graphene_std::graphic::map;
let preprocessor = Preprocessor::new();
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_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");
let read_index_metadata = compile_metadata(&read_index::IDENTIFIER);
let loop_level_index = <read_index::LoopLevelInput as NodeParameter>::INDEX;
assert_eq!(read_index_metadata.index_level_input, Some(loop_level_index as u8));
assert!(read_index_metadata.requires_constant_input(loop_level_index), "The loop level must be a constant");
}
}