Compare commits

..
Author SHA1 Message Date
Dennis Kobert fb94d99807 Port the stale math-nodes and raster-nodes tests onto record wires 2026-08-11 09:54:48 +00:00
Dennis Kobert 264601c5f7 Return records from eval_batch through a RecordBatch view 2026-08-11 09:26:36 +00:00
Dennis Kobert 5db7e1816a Make Node::layout non-optional, defaulting to a shared empty layout 2026-08-11 09:20:02 +00:00
Dennis Kobert 5b02edfd9a Split the node macro codegen into classify, entries, and metadata modules 2026-08-10 16:15:31 +00:00
Dennis Kobert 7c0a4073e9 Select the eval tail form by class and dialect through an explicit Tail step 2026-08-10 15:57:58 +00:00
Dennis Kobert 275100eab0 Model the eval body as an EvalStep sequence with a structural stack discipline 2026-08-10 15:34:12 +00:00
Dennis Kobert 42cd2a4303 Resolve the dialect and input-role axes as node-model sum types 2026-08-10 15:21:59 +00:00
Dennis Kobert e4f81fc947 Drive the node macro from a single analyze pass, NodePlan, and shared NodeFields 2026-08-10 13:33:58 +00:00
Dennis Kobert 492cf18cb0 Flip the passthrough node onto record wires by dropping its dead lifetime 2026-08-10 13:33:58 +00:00
Dennis Kobert 05630bab6e Port the repeat node tests onto record-wire lazy inputs 2026-08-10 10:41:40 +00:00
Dennis Kobert a465948ad4 Always-spill records, retiring inline-16 and reclaiming read-out record frames 2026-08-10 10:29:22 +00:00
Dennis Kobert 63cf0151e2 Change stack return to standart sret semantics 2026-08-08 07:33:33 +00:00
Dennis Kobert 9c7a633d5b Adopt tuple attribute io and the carrier lowering, deleting the bridge adapters for record-only wires 2026-08-06 18:48:16 +00:00
Dennis Kobert 166241b0e8 Flip nested-generic nodes onto record wires by unifying row types against field types 2026-08-06 13:36:46 +00:00
Dennis Kobert ea49f3c2fc Delete the Ref wire type and its lend edge surface 2026-08-06 12:24:50 +00:00
Dennis Kobert 100f81c307 Retire the lend machinery and flip the clone node onto record wires 2026-08-06 11:57:18 +00:00
Dennis Kobert 886ff03ef2 Construct value nodes as native record sources 2026-08-06 10:24:44 +00:00
Dennis Kobert 7a1d1f3238 Define the frame memo through the record-opaque class over same-frame byte copies 2026-08-06 09:57:21 +00:00
Dennis Kobert 612afb7ebb Capture the input context snapshot on the monitor io record 2026-08-06 09:37:48 +00:00
Dennis Kobert daf3f25d21 Define the monitor through the record-opaque class and move introspection to element reads 2026-08-06 09:07:57 +00:00
Dennis Kobert a2de2a9c09 Add the record-opaque kernel class to the node macro and define memoize through it 2026-08-06 08:28:52 +00:00
Dennis Kobert 98be2b8c79 Carry erased element and re-park glue on layouts and collapse memoize to a generic record row 2026-08-06 08:01:19 +00:00
Dennis Kobert 83fda4f08c Update the core-types runtime tests to record wires 2026-08-06 06:46:28 +00:00
Dennis Kobert 20c6ba19d3 Flip async source nodes onto record wires by lifting their slot values 2026-08-05 23:54:42 +00:00
Dennis Kobert 7eeb7d84cd Flip poll kernels and derived-context lazy nodes onto record wires and land record roots at the host rim 2026-08-05 23:42:24 +00:00
Dennis Kobert 7ddc66adbe Flip lazy-input nodes onto record wires through the element lazy input 2026-08-05 23:12:43 +00:00
Dennis Kobert c20a243fc2 Flip lend-parameter nodes onto record wires and keep the clone adapter plain 2026-08-05 22:57:51 +00:00
Dennis Kobert 3eecc31bfd Flip generic value nodes onto record wires through phantom struct parameters 2026-08-05 22:39:25 +00:00
Dennis Kobert 7099f056dc Flip concrete value nodes onto record wires with bridge rows for every value type 2026-08-05 22:18:50 +00:00
Dennis Kobert 9680d34abf Carry record elements by the drop-glue rule and unify the lift and extract adapters 2026-08-05 22:17:50 +00:00
Dennis Kobert 592b2fbe32 Turn context modification into a generic record routing node and park droppable elements as arena references 2026-08-05 19:25:17 +00:00
Dennis Kobert 60f80682c5 Collapse duplicate proto nodes when assigning stable ids 2026-08-05 19:25:17 +00:00
Dennis Kobert 9fc4fcc7a0 Inline records of at most 16 bytes into the two-word RecordValue with layout-resolved storage 2026-08-05 17:23:09 +00:00
Dennis Kobert 7915800d73 Add per-field erased-read glue, the record monitor with introspection capture, and rename record constructors to new 2026-08-05 15:22:20 +00:00
Dennis Kobert c91be74a55 Add the Record wire type, record registry rows, lift and extract adapters, and executor stack reservation 2026-08-05 12:24:20 +00:00
Dennis Kobert abe2a565d1 Drop the list driver, make attribute values Copy over arena references, and land record-tier offset io on a per-thread record stack 2026-08-05 09:47:03 +00:00
Dennis Kobert 6154e4d219 Add the attribute census, node macro attribute io over list wires, and the rank-0 record tier 2026-08-04 22:05:02 +00:00
Dennis Kobert 62b7ccf40c Support bare reference parameters and lending outputs in the node macro and make the clone node the clone-out adapter 2026-08-03 18:29:16 +00:00
Dennis Kobert 9b45af854a Emit Ref wire types for lending rows and splice lend/clone_out adapters in the type checker 2026-08-03 16:33:27 +00:00
34 changed files with 6888 additions and 1066 deletions

No files matched your search

@@ -10,11 +10,10 @@ use graphene_std::blending::BlendMode;
use graphene_std::color::SRGBA8;
use graphene_std::gradient::GradientStops;
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::vector::Vector;
use graphene_std::vector::style::{FillChoice, FillChoiceUI, GradientSpreadMethod, GradientType};
use graphene_std::{Artboard, Color, CtxSnapshot, Graphic};
use graphene_std::{Artboard, Color, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -167,8 +166,8 @@ macro_rules! generate_layout_downcast {
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
if false { None }
$(
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<CtxSnapshot, $ty>>() {
Some(io.output.layout_with_breadcrumb($data))
else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
Some(element.layout_with_breadcrumb($data))
}
)*
else { None }
@@ -178,8 +177,8 @@ macro_rules! generate_layout_downcast {
fn generate_layout(introspected_data: &Arc<dyn std::any::Any + Send + Sync + 'static>, data: &mut LayoutData) -> Option<Vec<LayoutGroup>> {
// `List<NodeId>` is interpreted as a path (e.g. the value produced by `path_of_subgraph`), shown as a
// `List` where each item's NodeId resolves against the prefix made up of the items above it.
if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<NodeId>>>() {
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, data));
if let Some(list) = introspected_data.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
}
generate_layout_downcast!(introspected_data, data, [
List<Artboard>,
@@ -323,7 +323,7 @@ pub(crate) fn property_from_type(
Type::Generic(_) => vec![TextLabel::new("Generic Type (Not Supported)").widget_instance()].into(),
Type::Fn(_, out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Future(out) => return property_from_type(node_id, index, out, number_options, unit, display_decimal_places, step, context),
Type::Ref(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
Type::Record(inner) => return property_from_type(node_id, index, inner, number_options, unit, display_decimal_places, step, context),
};
extra_widgets.push(widgets);
+6 -24
View File
@@ -10,12 +10,11 @@ use graphene_std::application_io::{ExportFormat, NodeGraphUpdateMessage, RenderC
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::color::SRGBA8;
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::raster::{CPU, Raster};
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
use graphene_std::transform::Footprint;
use graphene_std::vector::{Vector, graphic_types};
use graphene_std::{ATTR_TRANSFORM, CtxSnapshot, Graphic, NodeInputDecleration};
use graphene_std::{ATTR_TRANSFORM, Graphic, NodeInputDecleration};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -900,18 +899,9 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
}
// TODO: Eventually remove this document upgrade code
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under.
/// Extract a monitor node's captured output element.
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
if let Some(io) = data.downcast_ref::<IORecord<(), T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<Footprint, T>>() {
return Some(io.output.clone());
}
if let Some(io) = data.downcast_ref::<IORecord<CtxSnapshot, T>>() {
return Some(io.output.clone());
}
None
data.downcast_ref::<T>().cloned()
}
// Re-export for usage by tests in other modules
@@ -927,9 +917,7 @@ mod test {
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::NodeNetwork;
use graphene_std::CtxSnapshot;
use graphene_std::NodeInputDecleration;
use graphene_std::memo::IORecord;
use test_prelude::LayerNodeIdentifier;
/// Stores all of the monitor nodes that have been attached to a graph
@@ -990,17 +978,11 @@ mod test {
where
Input::Result: Send + Sync + Clone + 'static,
{
// This is quite inflexible since it only allows the footprint as inputs.
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Input::Result>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Input::Result>>() {
Some(x.output.clone())
} else if let Some(x) = dynamic.downcast_ref::<IORecord<CtxSnapshot, Input::Result>>() {
Some(x.output.clone())
} else {
let element = dynamic.downcast_ref::<Input::Result>().cloned();
if element.is_none() {
warn!("cannot downcast type for introspection");
None
}
element
}
/// Grab all of the values of the input every time it occurs in the graph.
+12 -13
View File
@@ -11,7 +11,6 @@ use graphene_std::application_io::{ApplicationIo, ExportFormat, NodeGraphUpdateM
use graphene_std::bounds::RenderBoundingBox;
use graphene_std::core_types::gpoll::GPoll;
use graphene_std::list::List;
use graphene_std::memo::IORecord;
use graphene_std::ops::ConvertAsync;
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
@@ -21,7 +20,7 @@ use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRunti
use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode;
use graphene_std::{Artboard, CtxSnapshot, Graphic};
use graphene_std::{Artboard, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use spin::Mutex;
@@ -502,30 +501,30 @@ impl NodeRuntime {
};
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<Graphic>>>() {
if let Some(list) = introspected_data.downcast_ref::<List<Graphic>>() {
if update_thumbnails {
let bounds = graphene_std::renderer::graphic_list_bounding_box(&io.output, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
let bounds = graphene_std::renderer::graphic_list_bounding_box(list, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
}
}
// Artboard thumbnail bounds come from the clipping rectangles, not the content union, since the renderer
// clips content to those rectangles so anything outside isn't visible
else if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<Artboard>>>() {
else if let Some(list) = introspected_data.downcast_ref::<List<Artboard>>() {
if update_thumbnails {
let bounds = artboard_clip_bounds(&io.output);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
let bounds = artboard_clip_bounds(list);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
}
}
// Vector list: vector modifications
else if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<Vector>>>() {
else if let Some(list) = introspected_data.downcast_ref::<List<Vector>>() {
// Insert the vector modify
self.vector_modify.insert(parent_network_node_id, io.output.element(0).cloned().unwrap_or_default());
self.vector_modify.insert(parent_network_node_id, list.element(0).cloned().unwrap_or_default());
}
// String list: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<String>>>() {
else if let Some(list) = introspected_data.downcast_ref::<List<String>>() {
if update_thumbnails {
let bounds = graphene_std::renderer::text_list_bounding_box(&io.output, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
let bounds = graphene_std::renderer::text_list_bounding_box(list, DAffine2::IDENTITY);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
}
}
// Other
+40 -16
View File
@@ -11,7 +11,7 @@ use core_types::node::Node;
use core_types::registry::{EdgeHandle, edge_type};
use core_types::transform::Footprint;
use core_types::uuid::NodeId;
use core_types::value::value_edge;
use core_types::value::record_value_edge;
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
use dyn_any::DynAny;
pub use dyn_any::StaticType;
@@ -269,13 +269,13 @@ macro_rules! tagged_value {
// ===============
// MANUAL VARIANTS
// ===============
Self::None => Ok(value_edge(())),
Self::None => Ok(record_value_edge(())),
Self::TypeDefault(td) => {
// Same direct-construction path as `to_dynany` for the same reason as in `to_dynany`.
let name = td.name.as_ref();
macro_rules! check {
($type_default:ty) => {
if name == std::any::type_name::<$type_default>() { return Ok(value_edge(<$type_default>::default())); }
if name == std::any::type_name::<$type_default>() { return Ok(record_value_edge(<$type_default>::default())); }
};
}
for_each_type_default!(check);
@@ -283,33 +283,33 @@ macro_rules! tagged_value {
}
Self::F64Array(values) => {
let list: List<f64> = values.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(value_edge(list))
Ok(record_value_edge(list))
}
Self::Color(color) => {
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(value_edge(list))
Ok(record_value_edge(list))
}
Self::Gradient(stops) => Ok(value_edge(List::<GradientStops>::new_from_element(stops))),
Self::Gradient(stops) => Ok(record_value_edge(List::<GradientStops>::new_from_element(stops))),
Self::BrushStrokes(strokes) => {
let list: List<BrushStroke> = strokes.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(value_edge(list))
Ok(record_value_edge(list))
}
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Ok(value_edge(x)), )*
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::RenderOutput(x) => Ok(value_edge(x)),
Self::RenderOutput(x) => Ok(record_value_edge(x)),
Self::NodeIdPath(path) => {
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(value_edge(list))
Ok(record_value_edge(list))
}
Self::DocumentNode(node) => Ok(value_edge(node)),
Self::ContextModification(modification) => Ok(value_edge(modification)),
Self::EditorApi(x) => Ok(value_edge(x)),
Self::ResourceHash(x) => Ok(value_edge(x)),
Self::DocumentNode(node) => Ok(record_value_edge(node)),
Self::ContextModification(modification) => Ok(record_value_edge(modification)),
Self::EditorApi(x) => Ok(record_value_edge(x)),
Self::ResourceHash(x) => Ok(record_value_edge(x)),
}
}
@@ -336,6 +336,30 @@ macro_rules! tagged_value {
if ty == edge_type::<RenderOutput>() {
return Ok(handle.downcast::<RenderOutput>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(TaggedValue::RenderOutput));
}
// =======================
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
// =======================
if ty == core_types::registry::record_edge_type::<()>() {
return Ok(handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?.eval(ctx).map(|_| TaggedValue::None));
}
$(
if ty == core_types::registry::record_edge_type::<$ty>() {
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
return Ok(handle
.downcast_record::<$ty>()
.map_err(|e| format!("{e:?}"))?
.eval(ctx)
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
}
)*
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
let layout = handle.layout().ok_or_else(|| "a record edge must carry its layout".to_string())?.clone();
return Ok(handle
.downcast_record::<RenderOutput>()
.map_err(|e| format!("{e:?}"))?
.eval(ctx)
.map(|value| TaggedValue::RenderOutput(unsafe { core_types::record::read_element::<RenderOutput>(layout.rec(&value)) })));
}
Err(format!("Cannot convert edge of type {ty} to TaggedValue"))
}
@@ -389,7 +413,7 @@ macro_rules! tagged_value {
pub fn from_type(input: &Type) -> Option<Self> {
match input {
Type::Generic(_) => None,
Type::Ref(_) => None,
Type::Record(inner) => Self::from_type(inner),
Type::Concrete(concrete_type) => {
let name = concrete_type.name.as_ref();
// TODO: Add default implementations for types such as TaggedValue::Subpaths, and use the defaults here and in document_node_types
@@ -650,7 +674,7 @@ impl TaggedValue {
match ty {
Type::Generic(_) => None,
Type::Ref(_) => None,
Type::Record(_) => None,
Type::Concrete(concrete_type) => {
let ty = concrete_type.id?;
use std::any::TypeId;
+54 -33
View File
@@ -258,6 +258,11 @@ impl ProtoNetwork {
self.replace_node_id(&outwards_edges, NodeId(index as u64), sni);
self.nodes[index].0 = sni;
}
// Equal nodes hash to one id; the copies must go, or a pass that
// rewrites one of them (like adapter splicing) leaves the others stale.
let mut seen = HashSet::new();
self.nodes.retain(|(id, _)| seen.insert(*id));
}
// TODO: Remove
@@ -658,8 +663,8 @@ impl TypingContext {
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
/// and store them in the `inferred` field. The proto network has to be topologically sorted
/// and contain fully resolved stable node ids.
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> {
for (id, node) in network.nodes.iter() {
pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
for (id, node) in &network.nodes {
self.infer(*id, node)?;
}
@@ -689,10 +694,10 @@ impl TypingContext {
}
let inputs = match node.construction_args {
// If the node has a value input we can infer the return type from it
// A value node is a native record source, so it types as a record
// of its value.
ConstructionArgs::Value(ref v) => {
// TODO: This should return a reference to the value
let types = NodeIOTypes::new(concrete!(Context), v.ty(), vec![]);
let types = NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(v.ty())), vec![]);
self.inferred.insert(node_id, types.clone());
return Ok(types);
}
@@ -721,33 +726,6 @@ impl TypingContext {
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
}
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
fn valid_type(from: &Type, to: &Type) -> bool {
match (from, to) {
// Direct comparison of two concrete types.
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
// Direct comparison of two function types.
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
// This allows us to supply anything to a function that is satisfied with `()`.
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
// TODO: Add proper generic counting which is not based on the name
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
// Reject unknown type relationships.
_ => false,
}
}
// List of all implementations that match the input types
let valid_output_types = candidates
.iter()
@@ -850,6 +828,36 @@ impl TypingContext {
}
}
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
fn valid_type(from: &Type, to: &Type) -> bool {
match (from, to) {
// Direct comparison of two concrete types.
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
// Direct comparison of two function types.
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
// This allows us to supply anything to a function that is satisfied with `()`.
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
// A lend edge is substitutable exactly when the lent values are.
// A record edge is substitutable exactly when the elements are.
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
// TODO: Add proper generic counting which is not based on the name
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
// Reject unknown type relationships.
_ => false,
}
}
/// Returns a list of all generic types used in the node
fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
let inputs = [&types.call_argument].into_iter().chain(types.inputs.iter().map(|x| x.nested_type()));
@@ -868,10 +876,23 @@ fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
/// Checks if a generic type can be substituted with a concrete type and returns the concrete type
fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> {
fn record_element(ty: Option<&Type>) -> Option<&Type> {
match ty {
Some(Type::Record(inner)) => Some(inner.as_ref()),
_ => None,
}
}
let inputs = [(Some(&types.call_argument), Some(input))]
.into_iter()
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())));
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())))
.chain(
types
.inputs
.iter()
.map(|x| record_element(x.fn_output()))
.zip(parameters.iter().map(|x| record_element(x.fn_output()))),
);
let concrete_inputs = inputs.filter(|(ni, _)| matches!(ni, Some(Type::Generic(input)) if generic == input));
let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
let out_ty = outputs
@@ -71,9 +71,9 @@ pub struct ResolvedDocumentNodeTypesDelta {
}
impl DynamicExecutor {
pub fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
typing_context.update(&proto_network)?;
typing_context.update(&mut proto_network)?;
let output = proto_network.output;
let sources = proto_network.source_ids();
let tree = BorrowTree::new(proto_network, &typing_context)?;
@@ -102,9 +102,9 @@ impl DynamicExecutor {
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
#[cfg_attr(debug_assertions, inline(never))]
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.output = proto_network.output;
self.typing_context.update(&proto_network).map_err(|e| {
self.typing_context.update(&mut proto_network).map_err(|e| {
// If there is an error then get types that have been resolved before the error
let add = proto_network
.nodes
@@ -145,8 +145,17 @@ impl DynamicExecutor {
}
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
/// A monitor's record capture materializes its element here against the
/// arena, inside the introspection window, so consumers downcast the
/// element type directly. The captured input context stays on the
/// serialized io record for consumers that need it.
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
self.tree.introspect(node_path)
let result = self.tree.introspect(node_path)?;
if let Some(io) = result.downcast_ref::<core_types::memo::IORecord<core_types::context::CtxSnapshot, core_types::record::RecordCapture>>() {
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
return io.output.materialize_element(&arena).map(Arc::from).ok_or(IntrospectError::NoData);
}
Ok(result)
}
pub fn input_type(&self) -> Option<Type> {
@@ -181,6 +190,7 @@ where
return Err("Output node not found in executor".into());
};
let mut arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
core_types::record::stack::reserve(self.tree.stack_need());
let result = eval_root(&mut arena, &self.runtime, &input, |ctx| match TaggedValue::from_edge(handle.duplicate(), ctx) {
Ok(poll) => poll.map(Ok),
Err(error) => GPoll::Final(Err(error)),
@@ -261,23 +271,36 @@ pub struct BorrowTree {
nodes: HashMap<NodeId, (EdgeHandle, Path)>,
/// A hashmap from the document path to the proto node ID.
source_map: HashMap<Path, (NodeId, NodeTypes)>,
/// The record-stack reserve, folded from the graph at construction.
stack_need: usize,
}
impl BorrowTree {
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
let mut nodes = BorrowTree::default();
let output = proto_network.output;
let mut deps = HashMap::new();
for (id, node) in proto_network.nodes {
if let ConstructionArgs::Nodes(ids) = &node.construction_args {
deps.insert(id, ids.clone());
}
nodes.push_node(id, node, typing_context)?
}
nodes.stack_need = stack_peak(output, &deps, &|id| nodes.frame_bytes(id));
Ok(nodes)
}
/// Pushes new nodes into the tree and return orphaned nodes
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<(Vec<Path>, HashSet<NodeId>), GraphErrors> {
let output = proto_network.output;
let mut old_nodes: HashSet<_> = self.nodes.keys().copied().collect();
let mut new_nodes: Vec<_> = Vec::new();
let mut deps = HashMap::new();
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
for (id, node) in proto_network.nodes {
if let ConstructionArgs::Nodes(ids) = &node.construction_args {
deps.insert(id, ids.clone());
}
if !self.nodes.contains_key(&id) {
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
self.push_node(id, node, typing_context)?;
@@ -286,6 +309,7 @@ impl BorrowTree {
}
old_nodes.remove(&id);
}
self.stack_need = stack_peak(output, &deps, &|id| self.frame_bytes(id));
Ok((new_nodes, old_nodes))
}
@@ -469,6 +493,38 @@ impl BorrowTree {
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
&self.source_map
}
/// The record-stack reserve of an evaluation, folded from the graph at
/// construction (see [`stack_peak`]).
pub fn stack_need(&self) -> usize {
self.stack_need
}
fn frame_bytes(&self, id: NodeId) -> usize {
self.nodes.get(&id).and_then(|(handle, _)| handle.layout()).map_or(0, |layout| layout.frame_bytes())
}
}
/// Peak record-stack bytes for evaluating `output`'s cone. A node holds its
/// inputs' frames until it returns, so its need is its own frame plus every
/// input's frame plus the deepest input's peak. Memoized over shared cones.
fn stack_peak(output: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize) -> usize {
fn peak(id: NodeId, deps: &HashMap<NodeId, Vec<NodeId>>, frame_bytes: &dyn Fn(NodeId) -> usize, memo: &mut HashMap<NodeId, usize>) -> usize {
if let Some(&cached) = memo.get(&id) {
return cached;
}
let mut held = 0;
let mut deepest = 0;
for &child in deps.get(&id).map_or(&[][..], Vec::as_slice) {
let child_frame = frame_bytes(child);
held += child_frame;
deepest = deepest.max(peak(child, deps, frame_bytes, memo).saturating_sub(child_frame));
}
let need = frame_bytes(id) + held + deepest;
memo.insert(id, need);
need
}
peak(output, deps, frame_bytes, &mut HashMap::new())
}
#[cfg(test)]
@@ -487,6 +543,19 @@ mod test {
}
}
#[test]
fn stack_peak_folds_a_diamond_chain() {
// S3 <- S2 <- S1 <- S0, each consuming the node below on both inputs.
let deps = HashMap::from([
(NodeId(1), vec![NodeId(0), NodeId(0)]),
(NodeId(2), vec![NodeId(1), NodeId(1)]),
(NodeId(3), vec![NodeId(2), NodeId(2)]),
]);
let frame = |_: NodeId| 1;
assert_eq!(stack_peak(NodeId(0), &deps, &frame), 1);
assert_eq!(stack_peak(NodeId(3), &deps, &frame), 7);
}
#[test]
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
let mut arena = Arena::new(64).unwrap();
@@ -537,13 +606,196 @@ mod test {
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(2u32).into()), vec![]);
let context = TypingContext::default();
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let handle = tree.get(NodeId(0)).unwrap();
let layout = handle.layout().unwrap().clone();
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let result: Option<GPoll<u32>> = tree.eval(NodeId(0), &ctx);
assert_eq!(result, Some(GPoll::Final(2)));
let GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert_eq!(unsafe { core_types::record::read_element::<u32>(layout.rec(&value)) }, 2);
}
fn proto_node(identifier: &'static str, args: Vec<NodeId>) -> ProtoNode {
let mut node = ProtoNode::default();
node.identifier = graph_craft::ProtoNodeIdentifier::new(identifier);
node.call_argument = core_types::concrete!(core_types::context::Context);
node.construction_args = ConstructionArgs::Nodes(args);
node
}
fn string_value(value: &str) -> ProtoNode {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
}
#[test]
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
let arena = Arena::new(1 << 20).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = executor
.tree()
.get(NodeId(1))
.unwrap()
.downcast_record::<graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>>()
.unwrap();
let result = edge.eval(&ctx);
assert!(matches!(result, GPoll::Final(_)), "the flipped clone must evaluate over record wires, got a non-final poll");
}
#[test]
fn a_flipped_ref_parameter_reads_the_borrow_from_its_record_wire() {
let raster_list = TaggedValue::from_type(&core_types::concrete!(graphene_std::list::List<graphene_std::raster_types::Raster<graphene_std::raster_types::CPU>>)).unwrap();
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(raster_list.into()), vec![])),
(NodeId(1), ProtoNode::value(ConstructionArgs::Value(TaggedValue::U32(4).into()), vec![])),
(NodeId(2), proto_node("raster_nodes::image_color_palette::ImageColorPaletteNode", vec![NodeId(0), NodeId(1)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = executor
.tree()
.get(NodeId(2))
.unwrap()
.downcast_record::<graphene_std::list::List<graphene_std::raster::color::Color>>()
.unwrap();
let result = edge.eval(&ctx);
assert!(matches!(result, GPoll::Final(_)), "the palette must evaluate through its record wires, got a non-final poll");
}
#[test]
fn a_value_edge_is_a_record_wire_end_to_end() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(0),
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![]))],
};
let executor = DynamicExecutor::new(network).unwrap();
let value = executor.tree().get(NodeId(0)).unwrap();
assert_eq!(value.ty(), &core_types::registry::record_edge_type::<f64>());
assert!(value.layout().is_some());
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn a_record_monitor_row_forwards_and_introspects_through_the_executor() {
let mut monitor = proto_node("graphene_core::memo::MonitorNode", vec![NodeId(0)]);
monitor.original_location.path = Some(vec![NodeId(9)]);
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])), (NodeId(1), monitor)],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
let element = executor.introspect(&[NodeId(9)]).unwrap();
let element = element.downcast_ref::<f64>().expect("a record capture materializes to its element");
assert_eq!(*element, 7.);
}
#[test]
fn a_memoize_row_wires_generically_and_replays_over_record_wires() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(1),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(String::from("cached")).into()), vec![])),
(NodeId(1), proto_node("graphene_core::memo::MemoizeNode", vec![NodeId(0)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String(String::from("cached"))));
assert_eq!(
(&executor).execute(()).unwrap(),
GPoll::Final(TaggedValue::String(String::from("cached"))),
"the second execution replays the deep copy against a reset arena"
);
}
fn modification_value() -> ProtoNode {
let modification = core_types::ContextModification::from_sources(core_types::context::ContextFeatures::all(), &[]);
ProtoNode::value(ConstructionArgs::Value(TaggedValue::ContextModification(modification).into()), vec![])
}
#[test]
fn a_context_modification_row_wires_over_a_value_wire() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), modification_value()),
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn nested_context_modifications_forward_the_layout() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(4),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), modification_value()),
(NodeId(2), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(0), NodeId(1)])),
(NodeId(3), modification_value()),
(NodeId(4), proto_node("graphene_core::context_modification::ContextModificationNode", vec![NodeId(2), NodeId(3)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
}
#[test]
fn stacked_frame_memos_replay_over_record_wires() {
let network = ProtoNetwork {
inputs: vec![],
output: NodeId(2),
nodes: vec![
(NodeId(0), string_value("memoized")),
(NodeId(1), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(0)])),
(NodeId(2), proto_node("graphene_core::memo::FrameMemoNode", vec![NodeId(1)])),
],
};
let executor = DynamicExecutor::new(network).unwrap();
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("memoized".to_string())));
assert_eq!(
(&executor).execute(()).unwrap(),
GPoll::Final(TaggedValue::String("memoized".to_string())),
"the frame memo must replay across evaluations"
);
}
}
@@ -1,9 +1,6 @@
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::DocumentNode;
use graph_craft::document::value::RenderOutput;
use graphene_std::application_io::Texture;
use graphene_std::brush::brush_stroke::BrushStroke;
use graphene_std::gradient::GradientStops;
use graphene_std::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
#[cfg(target_family = "wasm")]
@@ -20,7 +17,7 @@ use graphene_std::transform::Footprint;
use graphene_std::uuid::NodeId;
use graphene_std::vector::Vector;
use graphene_std::{Artboard, Context, Graphic, ProtoNodeIdentifier, SourceId, concrete, fn_type};
use node_registry_macros::{async_node, convert_node, into_node};
use node_registry_macros::{convert_node, into_node};
use std::collections::HashMap;
#[cfg(feature = "gpu")]
use wgpu_executor::WgpuExecutorHandle;
@@ -109,192 +106,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
// =============
// MONITOR NODES
// =============
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => ()]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<Vector>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<GradientStops>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => IVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => DVec2]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => DAffine2]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => u32]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => u64]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => BlendMode]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => Texture]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::application_io::resource::Resource]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<NodeId>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<u8>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => AttributeDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => Graphic]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::LuminanceCalculation]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlue]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RedGreenBlueAlpha]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::NoiseType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::FractalType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularDistanceFunction]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::CellularReturnType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::DomainWarpType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::RelativeAbsolute]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::adjustments::SelectiveColorChoice]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
async_node!(graphene_core::memo::MonitorNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
// Context nullification
#[cfg(feature = "gpu")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => std::sync::Arc<PlatformEditorApi>, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RuntimeHandle, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => SourceId, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => RenderOutput, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeDyn, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => ListDyn, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<DAffine2>, Context => graphene_std::ContextModification]),
#[cfg(target_family = "wasm")]
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => CanvasHandle, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => std::sync::Arc<PlatformEditorApi>, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuExecutorHandle, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Option<wgpu_executor::WgpuExecutorHandle>, Context => graphene_std::ContextModification]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache, Context => graphene_std::ContextModification]),
// ==========
// MEMO NODES
// ==========
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ()]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RuntimeHandle]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => SourceId]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => bool]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Artboard>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Graphic>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Vector>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Image<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientStops>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<NodeId>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<u8>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientType>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::vector::style::GradientSpreadMethod>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeDyn]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => AttributeValueDyn]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => ListDyn]),
#[cfg(target_family = "wasm")]
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => CanvasHandle]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f64]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => f32]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u32]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => u64]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DVec2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => String]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DAffine2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Footprint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderOutput]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => std::sync::Arc<PlatformEditorApi>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<f64>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<Color>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Graphic]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Vec2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => glam::f32::Affine2]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::Stroke]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::Font]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BrushStroke>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => DocumentNode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::ContextModification]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::Footprint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Box<graphene_std::vector::VectorModification>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::blending::BlendMode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::LuminanceCalculation]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::QRCodeErrorCorrectionLevel]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::extract_xy::XY]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text_nodes::StringCapitalization]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlue]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RedGreenBlueAlpha]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::animation::RealTimeMode]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::NoiseType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::FractalType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularDistanceFunction]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::CellularReturnType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::DomainWarpType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::RelativeAbsolute]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::raster::SelectiveColorChoice]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::GridType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ArcType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::RowsOrColumns]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::MergeByDistanceAlgorithm]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::ExtrudeJoiningAlgorithm]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::PointSpacingType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeCap]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeJoin]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::StrokeAlign]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::PaintOrder]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::style::GradientSpreadMethod]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ReferencePoint]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::CentroidType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::BooleanOperation]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::text::TextAlign]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::transform::ScaleType]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => graphene_std::vector::misc::InterpolationDistribution]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => RenderIntermediate]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuExecutorHandle]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Option<wgpu_executor::WgpuExecutorHandle>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => wgpu_executor::WgpuPipelineCache]),
];
// =============
// CONVERT NODES
@@ -322,6 +136,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
.flatten(),
);
let mut map: HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> = HashMap::new();
let insert = |map: &mut HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>, id: ProtoNodeIdentifier, entry: RegistryEntry| {
let rows = map.entry(id).or_default();
@@ -359,43 +174,27 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
pub static NODE_REGISTRY: once_cell::sync::Lazy<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = once_cell::sync::Lazy::new(node_registry);
mod node_registry_macros {
macro_rules! async_node {
// This `params` variant of the macro wraps the normal `fn_params` variant and is used as a shorthand for writing `T` instead of `() => T`
($path:ty, input: $input:ty, params: [$($type:ty),*]) => {
async_node!($path, input: $input, fn_params: [ $(() => $type),*])
};
($path:ty, input: $input:ty, fn_params: [$first_arg:ty => $first:ty $(, $arg:ty => $type:ty)*]) => {
(
ProtoNodeIdentifier::new(stringify!($path)),
RegistryEntry {
io: NodeIOTypes::new(concrete!($input), concrete!($first), vec![fn_type!($first_arg, $first) $(, fn_type!($arg, $type))*]),
constructor: |inputs| {
let expected = [stringify!($first) $(, stringify!($type))*].len();
if inputs.len() != expected {
return Err(ConstructionError::Arity { expected, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let node = <$path>::new(inputs.next().unwrap().downcast::<$first>()? $(, inputs.next().unwrap().downcast::<$type>()?)*);
Ok(EdgeHandle::new(std::sync::Arc::new(node) as std::sync::Arc<ErasedNode<$first>>))
},
},
)
};
}
macro_rules! into_node {
(from: $from:ty, to: $to:ty) => {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::IntoNode<", stringify!($to), ">"]),
RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), concrete!($to), vec![fn_type!(Context, $from)]),
io: NodeIOTypes::new(
concrete!(Context),
core_types::registry::record_type::<$to>(),
vec![core_types::registry::record_edge_type::<$from>()],
),
constructor: |inputs| {
if inputs.len() != 1 {
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let node = graphene_std::ops::IntoNode::<$to, _>::new(inputs.next().unwrap().downcast::<$from>()?);
Ok(EdgeHandle::new(std::sync::Arc::new(node) as std::sync::Arc<ErasedNode<$to>>))
let handle = inputs.next().unwrap();
let Some(layout) = handle.layout().cloned() else {
return Err(ConstructionError::MissingLayout);
};
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
},
},
)
@@ -449,21 +248,41 @@ mod node_registry_macros {
RegistryEntry {
io: NodeIOTypes::new(
concrete!(Context),
concrete!($to),
vec![fn_type!(Context, $from), fn_type!(Context, $convert), fn_type!(Context, RuntimeHandle), fn_type!(Context, SourceId)],
core_types::registry::record_type::<$to>(),
vec![
core_types::registry::record_edge_type::<$from>(),
core_types::registry::record_edge_type::<$convert>(),
core_types::registry::record_edge_type::<RuntimeHandle>(),
core_types::registry::record_edge_type::<SourceId>(),
],
),
constructor: |inputs| {
if inputs.len() != 4 {
return Err(ConstructionError::Arity { expected: 4, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let node = graphene_std::ops::ConvertAsyncNode::<$to, _, _, _, _>::new(
inputs.next().unwrap().downcast::<$from>()?,
inputs.next().unwrap().downcast::<$convert>()?,
inputs.next().unwrap().downcast::<RuntimeHandle>()?,
inputs.next().unwrap().downcast::<SourceId>()?,
let mut claim = || {
let handle = inputs.next().unwrap();
let Some(layout) = handle.layout().cloned() else {
return Err(ConstructionError::MissingLayout);
};
Ok((handle, layout))
};
let (value, value_layout) = claim()?;
let (converter, converter_layout) = claim()?;
let (runtime, runtime_layout) = claim()?;
let (source, source_layout) = claim()?;
let node = graphene_std::ops::ConvertAsyncNode::<$to, _, _, _, _, $from, $convert>::new(
value.downcast_record::<$from>()?,
converter.downcast_record::<$convert>()?,
runtime.downcast_record::<RuntimeHandle>()?,
source.downcast_record::<SourceId>()?,
&value_layout,
&converter_layout,
&runtime_layout,
&source_layout,
);
Ok(EdgeHandle::new(std::sync::Arc::new(node) as std::sync::Arc<ErasedNode<$to>>))
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
},
},
)
@@ -472,21 +291,69 @@ mod node_registry_macros {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
RegistryEntry {
io: NodeIOTypes::new(concrete!(Context), concrete!($to), vec![fn_type!(Context, $from), fn_type!(Context, $convert)]),
io: NodeIOTypes::new(
concrete!(Context),
core_types::registry::record_type::<$to>(),
vec![core_types::registry::record_edge_type::<$from>(), core_types::registry::record_edge_type::<$convert>()],
),
constructor: |inputs| {
if inputs.len() != 2 {
return Err(ConstructionError::Arity { expected: 2, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
let node = graphene_std::ops::ConvertNode::<$to, _, _>::new(inputs.next().unwrap().downcast::<$from>()?, inputs.next().unwrap().downcast::<$convert>()?);
Ok(EdgeHandle::new(std::sync::Arc::new(node) as std::sync::Arc<ErasedNode<$to>>))
let value = inputs.next().unwrap();
let Some(value_layout) = value.layout().cloned() else {
return Err(ConstructionError::MissingLayout);
};
let converter = inputs.next().unwrap();
let Some(converter_layout) = converter.layout().cloned() else {
return Err(ConstructionError::MissingLayout);
};
let node = graphene_std::ops::ConvertNode::<$to, _, _, $from, $convert>::new(
value.downcast_record::<$from>()?,
converter.downcast_record::<$convert>()?,
&value_layout,
&converter_layout,
);
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
},
},
)
};
}
pub(crate) use async_node;
pub(crate) use convert_node;
pub(crate) use into_node;
}
#[cfg(test)]
mod tests {
use super::*;
use graphene_std::Type;
fn is_record_edge(ty: &Type) -> bool {
match ty {
Type::Fn(_, output) => matches!(&**output, Type::Record(_)),
_ => false,
}
}
/// One wire kind: every row consumes and produces record wires. A plain
/// io type here would need a bridge adapter, and those are gone.
#[test]
fn every_registry_row_is_record_typed() {
let mut plain: Vec<String> = Vec::new();
for (id, entries) in NODE_REGISTRY.iter() {
for entry in entries {
let plain_output = !matches!(entry.io.return_value, Type::Record(_));
let plain_inputs: Vec<usize> = entry.io.inputs.iter().enumerate().filter(|(_, ty)| !is_record_edge(ty)).map(|(index, _)| index).collect();
if plain_output || !plain_inputs.is_empty() {
plain.push(format!("{} plain_output={plain_output} plain_inputs={plain_inputs:?}", id.as_str()));
}
}
}
plain.sort();
assert!(plain.is_empty(), "plain io remains in the registry:\n{}", plain.join("\n"));
}
}
+1 -1
View File
@@ -187,7 +187,7 @@ impl Drop for Arena {
pub struct ArenaWeak<T> {
word: u64,
_marker: PhantomData<*const T>,
_marker: PhantomData<fn() -> T>,
}
impl<T> Clone for ArenaWeak<T> {
@@ -0,0 +1,310 @@
//! Attribute markers and their census. A marker declares an attribute name
//! once, fixing its value type and its name-specific default; the census
//! collects every declaration so name resolution, defaults, and diagnostics
//! run at graph compile time. One name belongs to one marker, so a name can
//! never mean two different types.
//!
//! Values are `Copy` and pack directly into record fields. Data with drop
//! glue rides the arena instead: the marker declares a reference value
//! (`&str`), the writing kernel parks the payload in the arena, and the
//! record field carries the eval-lifetime reference.
use crate::list::AnyAttributeValue;
use glam::{DAffine2, DVec2};
use std::any::TypeId;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::marker::PhantomData;
use std::ops::Deref;
use std::sync::{LazyLock, Mutex};
/// Declares an attribute name: one marker per name, fixing the value type and
/// the name-specific default. Declare markers through the [`attribute!`]
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
pub trait Attribute: 'static {
/// The name as it appears in documents and diagnostics.
const NAME: &'static str;
/// The value type every read and write of this name shares. The lifetime
/// is the evaluation the value flows in; non-reference values ignore it.
type Value<'e>: Copy + Default + std::fmt::Debug;
/// The name-specific default, filled where an item lacks the attribute.
/// Producing a value for any `'e` from no inputs, reference defaults can
/// only point at `'static` data, which is what lets the census fill them
/// as plain bytes.
fn default<'e>() -> Self::Value<'e> {
Default::default()
}
/// # Safety
/// `ptr` must point at a live field of this marker's value type.
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
/// field storage; `None` for plain values, which ride the byte copy.
const REPARK: Option<unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>> = None;
}
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
/// (yielding the declared default where the attribute is absent upstream), an
/// `Attr<A>` in the return tuple is a write, and the same marker on both
/// sides is a modify.
pub struct Attr<'e, A: Attribute>(pub A::Value<'e>);
impl<'e, A: Attribute> Deref for Attr<'e, A> {
type Target = A::Value<'e>;
fn deref(&self) -> &A::Value<'e> {
&self.0
}
}
impl<'e, A: Attribute> Clone for Attr<'e, A> {
fn clone(&self) -> Self {
*self
}
}
impl<'e, A: Attribute> Copy for Attr<'e, A> {}
impl<'e, A: Attribute> std::fmt::Debug for Attr<'e, A> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple(A::NAME).field(&self.0).finish()
}
}
/// A deletion of `A` in a node's return tuple: the name leaves the output
/// layout, so downstream reads yield the declared default again. Functionally
/// a write of the default; the value carries nothing.
pub struct RemoveAttr<A: Attribute>(PhantomData<A>);
impl<A: Attribute> RemoveAttr<A> {
pub const fn new() -> Self {
RemoveAttr(PhantomData)
}
}
impl<A: Attribute> Default for RemoveAttr<A> {
fn default() -> Self {
Self::new()
}
}
/// A census row: what is known about one declared attribute name.
#[derive(Clone, Copy, Debug)]
pub struct AttributeInfo {
pub name: &'static str,
pub value_type: TypeId,
pub value_type_name: &'static str,
pub default: fn() -> Box<dyn AnyAttributeValue>,
pub size: usize,
pub align: usize,
/// Writes the declared default's bytes into a `size`-long slice.
pub write_default_bytes: fn(&mut [u8]),
}
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
assert_eq!(out.len(), size_of::<A::Value<'static>>());
let value: A::Value<'static> = A::default();
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
}
/// All declared attribute names, keyed by name.
pub static ATTRIBUTE_REGISTRY: LazyLock<Mutex<HashMap<&'static str, AttributeInfo>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
/// Registers `A` into the census. Called by the [`attribute!`] expansion at
/// startup (ctor natively, a `__node_registry_attribute_*` export on wasm).
/// Re-registration at the same value type is idempotent; a second marker
/// claiming the name at a different value type panics.
pub fn register<A: Attribute>()
where
A::Value<'static>: AnyAttributeValue,
{
let info = AttributeInfo {
name: A::NAME,
value_type: TypeId::of::<A::Value<'static>>(),
value_type_name: std::any::type_name::<A::Value<'static>>(),
default: || Box::new(A::default()),
size: size_of::<A::Value<'static>>(),
align: align_of::<A::Value<'static>>(),
write_default_bytes: write_default_bytes::<A>,
};
let conflict = match ATTRIBUTE_REGISTRY.lock().unwrap().entry(A::NAME) {
Entry::Vacant(vacant) => {
vacant.insert(info);
None
}
Entry::Occupied(occupied) => (occupied.get().value_type != info.value_type).then(|| occupied.get().value_type_name),
};
if let Some(existing) = conflict {
panic!("attribute `{}` is declared at two value types: {existing} and {}", A::NAME, info.value_type_name);
}
}
/// Looks up a declared name.
pub fn info(name: &str) -> Option<AttributeInfo> {
ATTRIBUTE_REGISTRY.lock().unwrap().get(name).copied()
}
/// The name-specific default for `name`, if the name is declared.
pub fn default_value(name: &str) -> Option<Box<dyn AnyAttributeValue>> {
info(name).map(|info| (info.default)())
}
/// Declares attribute markers: for each entry, the marker struct, its
/// [`Attribute`] impl, and the census registration.
///
/// ```
/// core_types::attribute! {
/// /// How visible the content is.
/// pub Opacity("opacity"): f64 = 1.;
/// /// The item's label, parked in the arena by the writer.
/// pub Label("label"): &str;
/// }
/// ```
///
/// The trailing `= expr` is the name-specific default; without it the value
/// type's `Default` applies. A `&T` value carries the eval lifetime, so its
/// default must be `'static` data.
#[macro_export]
macro_rules! attribute {
() => {};
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): &$value:ty $(= $default:expr)?; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $marker;
impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = &'e $value;
$(
fn default<'e>() -> Self::Value<'e> {
$default
}
)?
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
}
const REPARK: ::core::option::Option<unsafe fn(&dyn $crate::list::AnyAttributeValue, *mut u8, &$crate::arena::Arena) -> ::core::option::Option<()>> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference attribute replays its owned clone");
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::attribute!(@register $marker);
$crate::attribute!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $marker:ident($name:literal): $value:ty $(= $default:expr)?; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $marker;
impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = $value;
$(
fn default<'e>() -> Self::Value<'e> {
$default
}
)?
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
}
}
$crate::attribute!(@register $marker);
$crate::attribute!($($rest)*);
};
(@register $marker:ident) => {
const _: () = {
#[cfg(not(target_family = "wasm"))]
#[$crate::ctor::ctor]
fn register() {
$crate::attribute::register::<$marker>();
}
#[cfg(target_family = "wasm")]
#[unsafe(export_name = concat!("__node_registry_attribute_", stringify!($marker)))]
extern "C" fn register() {
$crate::attribute::register::<$marker>();
}
};
};
}
attribute! {
/// Item's `DAffine2` transformation, composed multiplicatively through nested groups.
pub Transform("transform"): DAffine2;
/// Item's `BlendMode`, controlling how it composites with content beneath it.
pub BlendMode("blend_mode"): crate::blending::BlendMode;
/// Item's opacity multiplier, composed multiplicatively through nested groups.
/// Affects content clipped to the item.
pub Opacity("opacity"): f64 = 1.;
/// Item's fill opacity multiplier. Like opacity but does not affect content clipped to the item.
pub OpacityFill("opacity_fill"): f64 = 1.;
/// Whether an item inherits the alpha of the content beneath it (clipping mask).
pub ClippingMask("clipping_mask"): bool;
/// Artboard's top-left corner in document coordinates.
pub Location("location"): DVec2;
/// A regex named-capture-group's name, or empty for unnamed groups.
pub Name("name"): &str;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn census_carries_declared_names() {
let row = info("opacity").unwrap();
assert_eq!(row.value_type, TypeId::of::<f64>());
assert_eq!(info("transform").unwrap().value_type, TypeId::of::<DAffine2>());
assert!(info("never_declared").is_none());
}
#[test]
fn name_specific_default_overrides_the_type_default() {
assert_eq!(<Opacity as Attribute>::default(), 1.);
assert_eq!(<Name as Attribute>::default(), "");
}
#[test]
fn erased_default_downcasts_to_the_declared_type() {
let value = default_value("opacity_fill").unwrap();
assert_eq!(*value.as_any().downcast_ref::<f64>().unwrap(), 1.);
}
#[test]
fn reference_values_register_at_the_static_instantiation() {
let row = info("name").unwrap();
assert_eq!(row.value_type, TypeId::of::<&'static str>());
assert_eq!(row.size, size_of::<&str>());
}
#[test]
fn reregistration_at_the_same_type_is_idempotent() {
register::<Opacity>();
register::<Opacity>();
assert_eq!(info("opacity").unwrap().value_type, TypeId::of::<f64>());
}
#[test]
#[should_panic(expected = "two value types")]
fn a_second_marker_at_a_different_type_panics() {
struct Conflict;
impl Attribute for Conflict {
const NAME: &'static str = "opacity";
type Value<'e> = bool;
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
Box::new(unsafe { ptr.cast::<bool>().read() })
}
}
register::<Conflict>();
}
}
@@ -1,6 +1,7 @@
extern crate log;
pub mod arena;
pub mod attribute;
pub mod bounds;
pub mod consts;
pub mod context;
@@ -12,6 +13,7 @@ pub mod memo;
pub mod misc;
pub mod node;
pub mod ops;
pub mod record;
pub mod registry;
pub mod render_complexity;
pub mod runtime;
+150 -11
View File
@@ -6,8 +6,8 @@ use std::ops::Range;
#[derive(Debug)]
pub enum BatchStatus<'a, T> {
Lent(&'a [T], Finality),
Filled(FilledBatch<'a, T>, Finality),
Lent(RecordBatch<'a, T>, Finality),
Filled(RecordBatch<'a, T>, Finality),
Pending,
Error(GraphError),
NeedBuffer,
@@ -57,6 +57,121 @@ pub unsafe fn assume_init_prefix_mut<T>(scratch: &mut [MaybeUninit<T>], len: usi
unsafe { std::slice::from_raw_parts_mut(scratch.as_mut_ptr().cast::<T>(), len) }
}
/// A borrow-for-scope view over a batch of records whose element type is `T`,
/// paired with their shared [`Layout`](crate::record::Layout). Row-major backed
/// today; the interface (`len`/`layout`/`get`/`for_each`) is storage-agnostic so
/// a columnar backing can replace it without touching consumers.
#[derive(Debug)]
pub struct RecordBatch<'a, T> {
lanes: LaneStore<'a, T>,
layout: &'a crate::record::Layout,
}
#[derive(Debug)]
enum LaneStore<'a, T> {
/// Borrows resident storage (the `Lent` status): no drop obligation.
Borrowed(&'a [T]),
/// Owns the caller scratch's initialized prefix (the `Filled` status).
Owned(FilledBatch<'a, T>),
}
impl<'a, T> RecordBatch<'a, T> {
pub fn lent(values: &'a [T], layout: &'a crate::record::Layout) -> Self {
Self { lanes: LaneStore::Borrowed(values), layout }
}
pub fn filled(filled: FilledBatch<'a, T>, layout: &'a crate::record::Layout) -> Self {
Self { lanes: LaneStore::Owned(filled), layout }
}
fn lanes(&self) -> &[T] {
match &self.lanes {
LaneStore::Borrowed(values) => values,
LaneStore::Owned(filled) => filled.values(),
}
}
pub fn len(&self) -> usize {
self.lanes().len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn layout(&self) -> &crate::record::Layout {
self.layout
}
/// Lends lane `lane`'s record to `f` for the callback's scope only.
pub fn get<R>(&self, lane: usize, f: impl FnOnce(RecordLane<'_, T>) -> R) -> R {
f(RecordLane { value: &self.lanes()[lane], layout: self.layout })
}
/// Lends every lane's record in order, each for its callback's scope only.
pub fn for_each(&self, mut f: impl FnMut(usize, RecordLane<'_, T>)) {
for (lane, value) in self.lanes().iter().enumerate() {
f(lane, RecordLane { value, layout: self.layout });
}
}
/// Hands the owned scratch prefix back to the caller, cancelling the drop
/// obligation. Panics on a lent batch, which owns nothing to return.
pub fn into_values(self) -> &'a mut [T] {
match self.lanes {
LaneStore::Owned(filled) => filled.into_values(),
LaneStore::Borrowed(_) => panic!("into_values on a lent batch"),
}
}
}
/// One lane's record, lent for a callback scope. Derefs to the raw lane value;
/// for record elements, [`rec`](RecordLane::rec) and [`attr`](RecordLane::attr)
/// read the record through its layout.
#[derive(Debug)]
pub struct RecordLane<'r, T> {
value: &'r T,
layout: &'r crate::record::Layout,
}
impl<T> std::ops::Deref for RecordLane<'_, T> {
type Target = T;
fn deref(&self) -> &T {
self.value
}
}
impl<T> RecordLane<'_, T> {
pub fn layout(&self) -> &crate::record::Layout {
self.layout
}
}
impl<'e> RecordLane<'_, crate::record::RecordValue<'e>> {
/// The record pointer, resolved through the layout.
pub fn rec(&self) -> crate::record::Rec {
self.layout.rec(self.value)
}
/// The element at offset 0.
///
/// # Safety
/// `U` must be the record's element type, proven at the consumer's wiring.
pub unsafe fn element<U: Copy>(&self) -> U {
unsafe { self.rec().element::<U>() }
}
/// Attribute `A` at the record's top level, or its census default when the
/// layout does not carry it.
pub fn attr<A: crate::attribute::Attribute>(&self) -> A::Value<'e> {
match self.layout.offset_of(A::NAME, 0) {
Some(offset) => unsafe { self.rec().read::<A::Value<'e>>(offset) },
None => A::default(),
}
}
}
pub trait Node<Input> {
type Output;
@@ -71,7 +186,15 @@ pub trait Node<Input> {
None
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
/// The record layout of this node's output; the shared empty layout for
/// element-only producers. Consumers read their carrier's layout through
/// this at wiring, and the wiring layer derives stack sizing from the same
/// layouts, in the dynamic executor and exported source alike.
fn layout(&self) -> &crate::record::Layout {
crate::record::empty_layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
@@ -111,7 +234,7 @@ pub trait Node<Input> {
}
}
// SAFETY: all `len` lanes were written by the loop above.
BatchStatus::Filled(unsafe { FilledBatch::new(scratch, len) }, finality)
BatchStatus::Filled(RecordBatch::filled(unsafe { FilledBatch::new(scratch, len) }, self.layout()), finality)
}
}
@@ -133,7 +256,11 @@ where
(**self).serialize()
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
@@ -159,7 +286,11 @@ where
(**self).serialize()
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
@@ -185,7 +316,11 @@ where
(**self).serialize()
}
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
fn layout(&self) -> &crate::record::Layout {
(**self).layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
@@ -317,10 +452,12 @@ mod tests {
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = Double.eval_batch(&input, 2..6, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
let BatchStatus::Filled(batch, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes.values(), &[4, 6, 8, 10]);
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(*lane));
assert_eq!(got, vec![4, 6, 8, 10]);
assert_eq!(finality, Finality::AllFinal);
}
@@ -379,10 +516,12 @@ mod tests {
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = PartialAtThree.eval_batch(&input, 0..4, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
let BatchStatus::Filled(batch, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes.values(), &[0, 1, 2, 3]);
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(*lane));
assert_eq!(got, vec![0, 1, 2, 3]);
assert_eq!(finality, Finality::Partial);
}
File diff suppressed because it is too large. Load diff
+50 -22
View File
@@ -74,10 +74,12 @@ pub use crate::NodeIOTypes;
pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T> + Send + Sync;
#[cfg(target_family = "wasm")]
pub type ErasedNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = T>;
/// Element-independent by erasure; the wire's `Type::Record(El)` keeps element reads proven at wiring.
#[cfg(not(target_family = "wasm"))]
pub type ErasedLendNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = &'c T> + Send + Sync;
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>> + Send + Sync;
#[cfg(target_family = "wasm")]
pub type ErasedLendNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = &'c T>;
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>>;
#[cfg(not(target_family = "wasm"))]
type DynEdge = dyn std::any::Any + Send + Sync;
@@ -88,8 +90,17 @@ pub fn edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(T)))
}
pub fn lend_edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Ref(Box::new(concrete!(T)))))
pub fn record_type<T: 'static>() -> Type {
Type::Record(Box::new(concrete!(T)))
}
pub fn record_edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
}
/// The record edge type of a token row, generic over the element.
pub fn generic_record_edge_type(name: &'static str) -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
}
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
@@ -102,6 +113,7 @@ pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
pub enum ConstructionError {
Arity { expected: usize, got: usize },
Type { expected: Box<Type>, found: Box<Type> },
MissingLayout,
}
pub struct SharedEdge<N: ?Sized> {
@@ -135,9 +147,22 @@ where
type Output = N::Output;
fn eval(&self, input: &Input) -> crate::gpoll::GPoll<Self::Output> {
// Every node advances the record stack by exactly its own frame: it keeps
// its output and reclaims its inputs. A mismatch is a leaked or
// over-released frame.
#[cfg(debug_assertions)]
let sp_before = crate::record::stack::sp();
// SAFETY: `own` keeps the payload alive for `self`'s lifetime and Arc
// payloads are address stable.
unsafe { self.ptr.as_ref() }.eval(input)
let result = unsafe { self.ptr.as_ref() }.eval(input);
#[cfg(debug_assertions)]
debug_assert_eq!(
crate::record::stack::sp(),
sp_before + self.layout().frame_bytes(),
"{} left the record stack misaligned",
std::any::type_name::<N>(),
);
result
}
fn extent(&self, input: &Input) -> crate::gpoll::GPoll<crate::gpoll::Extent> {
@@ -150,7 +175,12 @@ where
unsafe { self.ptr.as_ref() }.serialize()
}
fn eval_batch<'a>(&self, input: &'a Input, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<Self::Output>]>) -> crate::node::BatchStatus<'a, Self::Output>
fn layout(&self) -> &crate::record::Layout {
// SAFETY: as in eval.
unsafe { self.ptr.as_ref() }.layout()
}
fn eval_batch<'a>(&'a self, input: &'a Input, range: std::ops::Range<u64>, scratch: Option<&'a mut [std::mem::MaybeUninit<Self::Output>]>) -> crate::node::BatchStatus<'a, Self::Output>
where
Input: crate::context::InjectIndex + Copy,
{
@@ -163,6 +193,7 @@ pub struct EdgeHandle {
node: Box<DynEdge>,
share: fn(&DynEdge) -> Box<DynEdge>,
serialize: fn(&DynEdge) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
layout: fn(&DynEdge) -> Option<&crate::record::Layout>,
ty: Type,
}
@@ -184,8 +215,8 @@ impl EdgeHandle {
Self::new_erased(node, edge_type::<T>())
}
pub fn new_ref<T: 'static>(node: std::sync::Arc<ErasedLendNode<T>>) -> Self {
Self::new_erased(node, lend_edge_type::<T>())
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
Self::new_erased(node, record_edge_type::<T>())
}
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
@@ -197,6 +228,7 @@ impl EdgeHandle {
node: Box::new(SharedEdge::new(node)),
share: |edge| Box::new(edge.downcast_ref::<SharedEdge<N>>().expect("share hook matches the stored edge type").share()),
serialize: |edge| Node::<ContextImpl>::serialize(edge.downcast_ref::<SharedEdge<N>>().expect("serialize hook matches the stored edge type")),
layout: |edge| Some(Node::<ContextImpl>::layout(edge.downcast_ref::<SharedEdge<N>>().expect("layout hook matches the stored edge type"))),
ty,
}
}
@@ -210,6 +242,7 @@ impl EdgeHandle {
node: (self.share)(&*self.node),
share: self.share,
serialize: self.serialize,
layout: self.layout,
ty: self.ty.clone(),
}
}
@@ -218,12 +251,16 @@ impl EdgeHandle {
(self.serialize)(&*self.node)
}
pub fn layout(&self) -> Option<&crate::record::Layout> {
(self.layout)(&*self.node)
}
pub fn downcast<T: 'static>(self) -> Result<SharedEdge<ErasedNode<T>>, ConstructionError> {
self.downcast_erased(edge_type::<T>())
}
pub fn downcast_lend<T: 'static>(self) -> Result<SharedEdge<ErasedLendNode<T>>, ConstructionError> {
self.downcast_erased(lend_edge_type::<T>())
pub fn downcast_record<T: 'static>(self) -> Result<SharedEdge<ErasedRecordNode>, ConstructionError> {
self.downcast_erased(record_edge_type::<T>())
}
pub fn downcast_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedEdge<N>, ConstructionError> {
@@ -340,9 +377,9 @@ mod tests {
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let lending = EdgeHandle::new_ref(Arc::new(LendNode("held".to_string())) as Arc<ErasedLendNode<String>>);
let upstream = lending.downcast_lend::<String>().unwrap();
let node: Arc<ErasedSplitEdge> = Arc::new(SplitNode { content: upstream });
let node: Arc<ErasedSplitEdge> = Arc::new(SplitNode {
content: LendNode("held".to_string()),
});
let handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>));
assert_eq!(*handle.ty(), concrete!(SplitBorrow<'static>));
@@ -482,15 +519,6 @@ mod tests {
found: Box::new(edge_type::<f64>()),
}
);
let lent = EdgeHandle::new_ref(Arc::new(LendNode("typed".to_string())) as Arc<ErasedLendNode<String>>);
assert_eq!(
construct(&entry, vec![lent]).unwrap_err(),
ConstructionError::Type {
expected: Box::new(edge_type::<String>()),
found: Box::new(lend_edge_type::<String>()),
}
);
}
#[test]
+88 -9
View File
@@ -171,6 +171,7 @@ mod tests {
use crate::context::{ContextImpl, Ctx, CtxSnapshot, EvalScope, ExtractFootprint, ExtractVarArgs, VarArgLink, VarArgSlots};
use crate::gpoll::GPoll;
use crate::node::Node;
use crate::record::{Layout, RecordExtract, RecordLift, element_write, stack};
use crate::transform::Footprint;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
@@ -257,6 +258,19 @@ mod tests {
}
}
fn element_layout<T: Clone + Send + Sync + 'static>() -> Layout {
Layout::default().with_writes(0, element_write::<T>(), &[])
}
fn lifted<T: Clone + Send + Sync + 'static>(value: T) -> RecordLift<T, SourceNode<T>> {
RecordLift::new(SourceNode(value))
}
fn extract<El: Clone + Send + Sync + 'static, N>(graph: N) -> RecordExtract<El, N> {
stack::reserve(1 << 12);
RecordExtract::new(graph, &element_layout::<El>())
}
static SLOW_DOUBLE_RUNS: AtomicU32 = AtomicU32::new(0);
#[node_macro::node(category(""))]
@@ -328,7 +342,14 @@ mod tests {
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = SlowDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(7u64));
let graph = extract::<f64, _>(SlowDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(7u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
@@ -348,7 +369,14 @@ mod tests {
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = PreviewDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(1u64));
let graph = extract::<f64, _>(PreviewDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(1u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(-1.0));
runtime.drain();
@@ -363,7 +391,14 @@ mod tests {
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = StrictDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(2u64));
let graph = extract::<f64, _>(StrictDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(2u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
@@ -378,7 +413,14 @@ mod tests {
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = StagedDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(8u64));
let graph = extract::<f64, _>(StagedDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(8u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "the prologue runs synchronously on the miss");
@@ -398,7 +440,16 @@ mod tests {
let gate = Arc::new(std::sync::atomic::AtomicBool::new(false));
let runtime = Arc::new(MockRuntime::default());
let graph = StagedSumNode::new(SourceNode(40.0f64), GatedSource(gate.clone(), 2.0), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(9u64));
let graph = extract::<f64, _>(StagedSumNode::new(
lifted(40.0f64),
RecordLift::<f64, _>::new(GatedSource(gate.clone(), 2.0)),
lifted(RuntimeHandle(runtime.clone())),
lifted(9u64),
&element_layout::<f64>(),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(runtime.drain(), Vec::<SourceId>::new(), "an interrupted prologue must not spawn or claim the slot");
@@ -422,7 +473,14 @@ mod tests {
let ctx = root.with_varargs(&link);
let runtime = Arc::new(MockRuntime::default());
let graph = SnapshotVarargNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(5u64));
let graph = extract::<f64, _>(SnapshotVarargNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(5u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
@@ -439,7 +497,14 @@ mod tests {
let ctx = root.with_footprint(&footprint);
let runtime = Arc::new(MockRuntime::default());
let graph = SnapshotResolutionNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(3u64));
let graph = extract::<u32, _>(SnapshotResolutionNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(3u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
@@ -545,7 +610,14 @@ mod tests {
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[13]);
let graph = InlineDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(13u64));
let graph = extract::<f64, _>(InlineDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(13u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
@@ -561,7 +633,14 @@ mod tests {
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[11]);
let graph = EpilogueDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(11u64));
let graph = extract::<f64, _>(EpilogueDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(11u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
+8 -7
View File
@@ -235,7 +235,8 @@ pub enum Type {
Fn(Box<Type>, Box<Type>),
/// Represents a future which promises to return the inner type.
Future(Box<Type>),
Ref(Box<Type>),
/// A packed record wire over the element type; the layout stays node-resident metadata.
Record(Box<Type>),
}
impl Default for Type {
@@ -309,7 +310,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.size),
Self::Fn(_, _) => None,
Self::Future(_) => None,
Self::Ref(_) => None,
Self::Record(_) => None,
}
}
@@ -319,7 +320,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.align),
Self::Fn(_, _) => None,
Self::Future(_) => None,
Self::Ref(_) => None,
Self::Record(_) => None,
}
}
@@ -329,7 +330,7 @@ impl Type {
Self::Concrete(_) => self,
Self::Fn(_, output) => output.nested_type(),
Self::Future(output) => output.nested_type(),
Self::Ref(inner) => inner.nested_type(),
Self::Record(inner) => inner.nested_type(),
}
}
@@ -342,7 +343,7 @@ impl Type {
Self::Concrete(_) => None,
Self::Fn(_, output) => output.replace_nested(f),
Self::Future(output) => output.replace_nested(f),
Self::Ref(inner) => inner.replace_nested(f),
Self::Record(inner) => inner.replace_nested(f),
}
}
@@ -352,7 +353,7 @@ impl Type {
Type::Concrete(ty) => simplify_identifier_name(&ty.name),
Type::Fn(call_arg, return_value) => format!("{} called with {}", return_value.identifier_name(), call_arg.identifier_name()),
Type::Future(ty) => ty.identifier_name(),
Type::Ref(ty) => ty.identifier_name(),
Type::Record(ty) => ty.identifier_name(),
}
}
}
@@ -447,7 +448,7 @@ impl std::fmt::Display for Type {
Type::Concrete(ty) => write!(f, "{ty}"),
Type::Fn(_, return_value) => write!(f, "{return_value}"),
Type::Future(ty) => write!(f, "{ty}"),
Type::Ref(ty) => write!(f, "{ty}"),
Type::Record(ty) => write!(f, "{ty}"),
}
}
}
@@ -13,6 +13,43 @@ pub fn value_edge<T: Clone + crate::WasmNotSend + crate::WasmNotSync + 'static>(
crate::registry::EdgeHandle::new(std::sync::Arc::new(ClonedNode(value)) as std::sync::Arc<crate::registry::ErasedNode<T>>)
}
/// The node behind every value edge: clones its constant onto the record
/// wire per evaluation.
pub struct ValueSource<T> {
value: T,
layout: crate::record::Layout,
}
impl<T: Clone + Send + Sync + 'static> ValueSource<T> {
pub fn new(value: T) -> Self {
Self {
value,
layout: crate::record::Layout::default().with_writes(0, crate::record::element_write::<T>(), &[]),
}
}
}
impl<'e, C, T> crate::node::Node<C> for ValueSource<T>
where
C: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
T: Clone + Send + Sync + 'static,
{
type Output = crate::record::RecordValue<'e>;
fn eval(&self, input: &C) -> crate::gpoll::GPoll<crate::record::RecordValue<'e>> {
crate::record::lift_poll(crate::gpoll::GPoll::Final(self.value.clone()), &self.layout, input.arena())
}
fn layout(&self) -> &crate::record::Layout {
&self.layout
}
}
/// The native record edge of a constant.
pub fn record_value_edge<T: Clone + Send + Sync + 'static>(value: T) -> crate::registry::EdgeHandle {
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
}
impl<T: Clone> ClonedNode<T> {
pub const fn new(value: T) -> ClonedNode<T> {
ClonedNode(value)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,715 @@
use super::*;
/// How a record node's primary input lowers.
#[derive(Clone)]
pub(crate) enum RecordCarrier {
/// `_: ()`: no carrier edge, the kernel writes a fresh record.
None,
/// An unbounded generic returned in the element position: the element
/// bytes carry through the copy plan and the kernel sees `ElToken`.
Token(Ident),
/// An element type read at offset 0, monomorphized per its
/// implementations list where generic.
Read(Type),
}
/// The record io of a node fn: how the carrier lowers, the element write,
/// and the markers written and removed. Present exactly when the signature
/// declares attribute reads or writes in a shape the record tier supports;
/// malformed record io is reported by validation and generates no node impl.
#[derive(Clone)]
pub(crate) struct RecordShape {
pub(crate) carrier: RecordCarrier,
pub(crate) element_write: Option<Type>,
pub(crate) write_markers: Vec<Type>,
pub(crate) removes: Vec<Type>,
}
impl RecordShape {
pub(crate) fn skips_carrier(&self) -> bool {
matches!(self.carrier, RecordCarrier::None)
}
pub(crate) fn carries_element(&self) -> bool {
self.element_write.is_none()
}
}
/// The record-tier lowering a node fn resolves to. Exactly one class per node,
/// computed once by [`analyze`]; every downstream fragment reads the class
/// instead of recomputing the classification predicates.
pub(crate) enum Class {
RecordIo(RecordShape),
Routing(RoutingIo),
Flip { carrier: bool },
Opaque,
}
/// The effect/return axis of a node's kernel, resolved once from the signature.
/// Orthogonal to [`Class`]: it selects the eval tail (finish / merge / spawn)
/// and the kernel signature wrapping across every class.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Dialect {
Sync,
Interrupt,
Poll,
AsyncFn,
Future,
FutureInterrupt,
}
pub(crate) fn dialect(parsed: &ParsedNodeFn) -> Dialect {
if parsed.is_async {
return Dialect::AsyncFn;
}
match kernel_kind(&parsed.output_type) {
KernelKind::Plain => Dialect::Sync,
KernelKind::Interrupt(_) => Dialect::Interrupt,
KernelKind::Poll(_) => Dialect::Poll,
KernelKind::Future(_) => Dialect::Future,
KernelKind::FutureInterrupt(_) => Dialect::FutureInterrupt,
}
}
/// The result of classifying a node fn. A node with no supported lowering
/// (an async node with lazy inputs, malformed record io, or a signature no
/// class accepts) yields `None` and generates a struct and metadata but no
/// `Node` impl.
pub(crate) struct NodeModel {
pub(crate) class: Class,
pub(crate) dialect: Dialect,
}
pub(crate) fn analyze(parsed: &ParsedNodeFn) -> Option<NodeModel> {
if parsed.is_async && parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
return None;
}
let class = if let Some(shape) = record_shape(parsed) {
Class::RecordIo(shape)
} else if has_record_io(parsed) {
return None;
} else if let Some(routing) = routing_io(parsed) {
Class::Routing(routing)
} else if record_flip(parsed) {
Class::Flip { carrier: flip_carrier(parsed) }
} else if record_opaque(parsed) {
Class::Opaque
} else {
return None;
};
Some(NodeModel { class, dialect: dialect(parsed) })
}
/// The per-field binding role, resolved once per regular field from the node
/// class and field shape. Drives the eval bindings and the lazy-edge input
/// types. The `lend` and `reads` axes stay field properties the value arms of
/// `kernel_params`/`call_args`/`value_args` consult, since they cross roles.
#[derive(Clone, Copy)]
pub(crate) enum InputRole {
RecordCarrier,
FlipCarrier,
ReadingSecondary,
LendBorrow,
RecordValue,
PlainValue,
DeriveRoutingSource,
OpaqueRecordEdge,
FlipRawLazyEdge,
FlipLazy,
RawLazy,
Lazy,
}
impl InputRole {
/// A role that copies an element out of a record edge, so its record frame
/// must be reclaimed after the read. The step lowering wraps such a bind in
/// `mark`/`rewind`, making the stack discipline structural rather than
/// hand-threaded through each read-out arm.
pub(crate) fn reads_out(self) -> bool {
matches!(self, InputRole::ReadingSecondary | InputRole::RecordValue)
}
}
/// The tail form of a node's eval, selected from its class and dialect: forward
/// the kernel's own record, assemble a record (io or flip carrier), or spawn a
/// source and lift its completion.
#[derive(Clone, Copy)]
pub(crate) enum Tail {
Forward,
Record,
Flip,
SpawnAsyncFn,
SpawnFuture,
}
/// One statement group of a node's `eval` body, lowered in order: the input
/// binds first (one per input), then the numeric clamps, then the tail that
/// assembles the output record and closes the dialect.
pub(crate) enum EvalStep<'a> {
Bind(usize, &'a ParsedField),
Clamp(&'a ParsedField),
Tail(Tail),
}
/// Whether the signature declares record-tier attribute io: value-input reads
/// or return-tuple writes. Reads on lazy inputs belong to the record lowering
/// of the flip class instead.
pub(crate) fn has_record_io(parsed: &ParsedNodeFn) -> bool {
let value_reads = parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
value_reads || record_writes(&slot_value_type(&parsed.output_type)).is_some()
}
pub(crate) fn has_lazy_reads(parsed: &ParsedNodeFn) -> bool {
parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Node(_)))
}
/// The value inputs of a routing node (every regular field that is not a
/// routing source), with their indices into the regular fields.
pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], routing: &RoutingIo) -> Vec<usize> {
regular_fields
.iter()
.enumerate()
.filter(|(_, field)| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => !matches!(ty, Type::Path(path) if path.path.get_ident() == Some(&routing.generic)),
ParsedFieldType::Node(_) => false,
})
.map(|(index, _)| index)
.collect()
}
/// The lazy inputs declaring attribute reads, with their indices into the
/// unit-skipped regular fields.
pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a ParsedField)> {
regular_fields
.iter()
.enumerate()
.filter(|(_, field)| matches!(field.ty, ParsedFieldType::Node(_)) && !field.attribute_reads.is_empty())
.map(|(index, field)| (index, *field))
.collect()
}
/// The indices (into the unit-skipped regular fields) of value inputs whose
/// reads resolve against their own wire rather than the carrier's.
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], shape: &RecordShape) -> Vec<usize> {
regular_fields
.iter()
.enumerate()
.filter(|(index, field)| !field.attribute_reads.is_empty() && (shape.skips_carrier() || *index != 0))
.map(|(index, _)| index)
.collect()
}
/// Every attribute read in field order with the owning field's index, flat so
/// read slots are numbered across inputs.
pub(crate) fn field_reads<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a AttributeRead)> {
regular_fields
.iter()
.enumerate()
.flat_map(|(index, field)| field.attribute_reads.iter().map(move |read| (index, read)))
.collect()
}
/// Substitutes bare generic idents with their row-assigned types.
pub(crate) fn substitute_ident_types(ty: &Type, assignments: &[(Ident, Type)]) -> Type {
struct Subst<'a> {
assignments: &'a [(Ident, Type)],
}
impl VisitMut for Subst<'_> {
fn visit_type_mut(&mut self, ty: &mut Type) {
if let Type::Path(path) = ty
&& path.qself.is_none()
&& let Some(ident) = path.path.get_ident()
&& let Some((_, replacement)) = self.assignments.iter().find(|(generic, _)| generic == ident)
{
*ty = replacement.clone();
return;
}
syn::visit_mut::visit_type_mut(self, ty);
}
}
let mut ty = ty.clone();
Subst { assignments }.visit_type_mut(&mut ty);
ty
}
/// Replaces the routing generic in a derive-routing kernel's return type with
/// the routing record value, since the kernel's edges rebind to '__record.
pub(crate) fn substitute_routing_record(output: &Type, generic: &Ident, core_types: &TokenStream2) -> Type {
struct Subst<'a> {
generic: &'a Ident,
replacement: Type,
}
impl VisitMut for Subst<'_> {
fn visit_type_mut(&mut self, ty: &mut Type) {
if let Type::Path(path) = ty
&& path.qself.is_none()
&& path.path.get_ident() == Some(self.generic)
{
*ty = self.replacement.clone();
return;
}
syn::visit_mut::visit_type_mut(self, ty);
}
}
let mut ty = output.clone();
let mut subst = Subst {
generic,
replacement: syn::parse_quote!(#core_types::record::RecordValue<'__record>),
};
subst.visit_type_mut(&mut ty);
ty
}
pub(crate) fn inject_attr_lifetimes(output: &Type) -> Option<Type> {
struct Injector {
changed: bool,
}
impl VisitMut for Injector {
fn visit_path_segment_mut(&mut self, segment: &mut syn::PathSegment) {
if segment.ident == "Attr"
&& let PathArguments::AngleBracketed(args) = &mut segment.arguments
&& !args.args.iter().any(|arg| matches!(arg, GenericArgument::Lifetime(_)))
{
args.args.insert(0, GenericArgument::Lifetime(Lifetime::new("'__attr", proc_macro2::Span::call_site())));
self.changed = true;
}
syn::visit_mut::visit_path_segment_mut(self, segment);
}
}
let mut ty = output.clone();
let mut injector = Injector { changed: false };
injector.visit_type_mut(&mut ty);
injector.changed.then_some(ty)
}
pub(crate) fn contains_open_generic(parsed: &ParsedNodeFn, ty: &Type) -> bool {
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
parsed
.fn_generics
.iter()
.any(|param| matches!(param, GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() && type_contains_ident(ty, &type_param.ident)))
}
pub(crate) fn unbounded_generic(parsed: &ParsedNodeFn, ty: &Type) -> Option<Ident> {
let ident = bare_ident(ty)?.clone();
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
parsed
.fn_generics
.iter()
.find(|param| matches!(param, GenericParam::Type(type_param) if type_param.ident == ident && type_param.bounds.is_empty() && Some(&type_param.ident) != ctx_ident.as_ref()))?;
if let Some(where_clause) = &parsed.where_clause
&& tokens_contain_ident(where_clause.to_token_stream(), &ident)
{
return None;
}
Some(ident)
}
pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
let value = match kernel_kind(&parsed.output_type) {
KernelKind::Plain => parsed.output_type.clone(),
KernelKind::Interrupt(inner) => inner,
_ => return None,
};
let writes = record_writes(&value);
let has_reads = parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
if !has_reads && writes.is_none() {
return None;
}
if parsed.is_async || parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
return None;
}
let reads_well_placed = parsed.fields.iter().all(|field| {
field.attribute_reads.is_empty() || (!field.is_data_field && matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: None, .. })))
});
if !reads_well_placed {
return None;
}
let carrier_field = parsed.fields.first()?;
if carrier_field.is_data_field {
return None;
}
let ParsedFieldType::Regular(RegularParsedField { ty, lend: None, implementations, .. }) = &carrier_field.ty else {
return None;
};
let carrier = match ty {
Type::Tuple(tuple) if tuple.elems.is_empty() => RecordCarrier::None,
ty => match implementations.is_empty().then(|| unbounded_generic(parsed, ty)).flatten() {
Some(token) => RecordCarrier::Token(token),
None => {
if contains_open_generic(parsed, ty) {
return None;
}
RecordCarrier::Read(ty.clone())
}
},
};
let (element, write_markers, removes) = match writes {
Some(RecordWrites { element, markers, removes }) => (element, markers, removes),
None => (value, Vec::new(), Vec::new()),
};
let element_write = match &carrier {
RecordCarrier::Token(token) => match bare_ident(&element) {
Some(ident) if ident == token => None,
_ => return None,
},
_ => {
if contains_open_generic(parsed, &element) {
return None;
}
Some(element)
}
};
if matches!(carrier, RecordCarrier::None) && !removes.is_empty() {
return None;
}
Some(RecordShape {
carrier,
element_write,
write_markers,
removes,
})
}
pub(crate) fn is_poll_kernel(output: &Type) -> bool {
matches!(kernel_kind(output), KernelKind::Poll(_))
}
/// A routing family: an unbounded generic shared by lazy inputs (and
/// optionally the first parameter) and returned whole, instantiated at
/// `RecordValue` so opaque records flow through the kernel. Detected only
/// when the family's fields carry no implementations lists, so the existing
/// per-type row spelling keeps its meaning.
#[derive(Clone)]
pub(crate) struct RoutingIo {
pub(crate) generic: Ident,
}
/// Whether a flipped node's primary input is a carrier: the first parameter
/// after the context, when it is an owned or lent value input. A carrier's
/// fields pass through to the output; every production layout is element-only
/// until attribute adoption, so the copy plan is empty and behavior is
/// unchanged. Async kernels carry fields per eval around the slot (only the
/// element crosses the future boundary), so their carrier must be owned: the
/// future captures the element by value.
pub(crate) fn flip_carrier(parsed: &ParsedNodeFn) -> bool {
if !record_flip(parsed) {
return false;
}
let Some(first) = parsed.fields.first() else { return false };
if first.is_data_field {
return false;
}
let ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) = &first.ty else {
return false;
};
if matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty()) {
return false;
}
let async_kernel = parsed.is_async || matches!(kernel_kind(&parsed.output_type), KernelKind::Future(_) | KernelKind::FutureInterrupt(_));
!(async_kernel && lend.is_some())
}
/// Whether a plain node's lowering flips onto record wires: sync,
/// fully-concrete value-input nodes in this cut; batch, shader, async, lend,
/// lazy, and generic nodes keep the plain lowering until their record forms
/// land.
pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() {
return false;
}
// Shader nodes flip like any value node: the kernel doubles as the
// shader body on the spirv target, but the struct and Node impl are
// std-gated, so the record machinery never reaches the shader build.
if parsed.attributes.batch.is_some() || parsed.attributes.plain {
return false;
}
if type_disqualifies(&slot_value_type(&parsed.output_type)) {
return false;
}
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
for param in &parsed.fn_generics {
match param {
GenericParam::Type(type_param) if Some(&type_param.ident) == ctx_ident.as_ref() => {}
// Registry rows assign a generic by unifying a field's type with
// the row's, so a generic without an extractable position keeps
// the plain lowering. A `skip_impl` node's rows are hand-written
// with explicit types, so no extractable position is needed.
GenericParam::Type(type_param) => {
let extractable = parsed.fields.iter().filter(|field| !field.is_data_field).any(|field| {
let ty = match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
};
generic_extractable(ty, &type_param.ident)
});
if !extractable && !parsed.attributes.skip_impl {
return false;
}
}
GenericParam::Lifetime(_) | GenericParam::Const(_) => return false,
}
}
true
}
/// Whether unifying a value of `field_ty`'s shape can bind `generic`: the
/// generic sits bare or under path type arguments, the shapes
/// [`generic_assignment`] walks.
pub(crate) fn generic_extractable(field_ty: &Type, generic: &Ident) -> bool {
match field_ty {
Type::Path(path) if path.qself.is_none() && path.path.get_ident() == Some(generic) => true,
Type::Path(path) => path.path.segments.iter().any(|segment| match &segment.arguments {
PathArguments::AngleBracketed(args) => args.args.iter().any(|argument| match argument {
GenericArgument::Type(inner) => generic_extractable(inner, generic),
_ => false,
}),
_ => false,
}),
_ => false,
}
}
/// Binds `generic` by unifying `field_ty` against `row_ty`: where the field
/// names the generic, the row's corresponding subtree is the assignment.
pub(crate) fn generic_assignment(field_ty: &Type, row_ty: &Type, generic: &Ident) -> Option<Type> {
if matches!(field_ty, Type::Path(path) if path.qself.is_none() && path.path.get_ident() == Some(generic)) {
return Some(row_ty.clone());
}
let (Type::Path(field_path), Type::Path(row_path)) = (field_ty, row_ty) else {
return None;
};
let field_segment = field_path.path.segments.last()?;
let row_segment = row_path.path.segments.last()?;
let (PathArguments::AngleBracketed(field_args), PathArguments::AngleBracketed(row_args)) = (&field_segment.arguments, &row_segment.arguments) else {
return None;
};
field_args.args.iter().zip(row_args.args.iter()).find_map(|(field_arg, row_arg)| match (field_arg, row_arg) {
(GenericArgument::Type(field_inner), GenericArgument::Type(row_inner)) => generic_assignment(field_inner, row_inner, generic),
_ => None,
})
}
pub(crate) fn is_record_value(ty: &Type) -> bool {
matches!(ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "RecordValue"))
}
/// Whether a kernel operates on whole records: it names `RecordValue` in its
/// output, receives raw record edges paired with the node's layout, and
/// takes on the record APIs' unsafe contracts itself.
pub(crate) fn record_opaque(parsed: &ParsedNodeFn) -> bool {
is_record_value(&slot_value_type(&parsed.output_type))
}
pub(crate) fn routing_io(parsed: &ParsedNodeFn) -> Option<RoutingIo> {
if has_record_io(parsed) || parsed.is_async {
return None;
}
if !matches!(kernel_kind(&parsed.output_type), KernelKind::Plain | KernelKind::Interrupt(_)) {
return None;
}
let value = slot_value_type(&parsed.output_type);
let Type::Path(path) = &value else { return None };
let ident = path.path.get_ident()?.clone();
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
parsed
.fn_generics
.iter()
.find(|param| matches!(param, GenericParam::Type(type_param) if type_param.ident == ident && type_param.bounds.is_empty() && Some(&type_param.ident) != ctx_ident.as_ref()))?;
if let Some(where_clause) = &parsed.where_clause
&& tokens_contain_ident(where_clause.to_token_stream(), &ident)
{
return None;
}
let mut sources = 0;
for (index, field) in parsed.fields.iter().enumerate() {
match &field.ty {
ParsedFieldType::Node(NodeParsedField {
output_type,
input_type,
implementations,
}) => {
if bare_ident(output_type) == Some(&ident) {
// A source forwards its whole record opaquely; declared
// reads contradict that and are rejected by validation.
if !implementations.is_empty() || type_contains_ident(input_type, &ident) || !field.attribute_reads.is_empty() {
return None;
}
sources += 1;
} else if type_contains_ident(output_type, &ident) || type_contains_ident(input_type, &ident) {
return None;
}
}
ParsedFieldType::Regular(RegularParsedField { ty, implementations, lend, .. }) => {
if bare_ident(ty) == Some(&ident) {
if index != 0 || field.is_data_field || !implementations.is_empty() || lend.is_some() {
return None;
}
sources += 1;
} else if type_contains_ident(ty, &ident) {
return None;
}
}
}
}
(sources > 0).then(|| RoutingIo { generic: ident })
}
pub(crate) fn bare_ident(ty: &Type) -> Option<&Ident> {
let Type::Path(path) = ty else { return None };
path.path.get_ident()
}
pub(crate) fn tokens_contain_ident(tokens: TokenStream2, ident: &Ident) -> bool {
tokens.into_iter().any(|token| match token {
proc_macro2::TokenTree::Ident(candidate) => &candidate == ident,
proc_macro2::TokenTree::Group(group) => tokens_contain_ident(group.stream(), ident),
_ => false,
})
}
pub(crate) fn slot_value_type(output: &Type) -> Type {
match kernel_kind(output) {
KernelKind::Plain => output.clone(),
KernelKind::Poll(inner) | KernelKind::Interrupt(inner) => inner,
KernelKind::Future(payload) | KernelKind::FutureInterrupt(payload) => match kernel_kind(&payload) {
KernelKind::Poll(inner) | KernelKind::Interrupt(inner) => inner,
_ => payload,
},
}
}
pub(crate) fn is_source_kernel(output: &Type) -> bool {
matches!(kernel_kind(output), KernelKind::Future(_) | KernelKind::FutureInterrupt(_))
}
pub(crate) enum KernelKind {
Plain,
Interrupt(Type),
Poll(Type),
Future(Type),
FutureInterrupt(Type),
}
pub(crate) fn source_future_payload(segment: &syn::PathSegment) -> Type {
let PathArguments::AngleBracketed(args) = &segment.arguments else {
return syn::parse_quote!(());
};
args.args
.iter()
.find_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty.clone()),
_ => None,
})
.unwrap_or_else(|| syn::parse_quote!(()))
}
pub(crate) fn kernel_kind(output: &Type) -> KernelKind {
let plain = || KernelKind::Plain;
let Type::Path(path) = output else { return plain() };
let Some(segment) = path.path.segments.last() else { return plain() };
match segment.ident.to_string().as_str() {
"GPoll" => {
let PathArguments::AngleBracketed(args) = &segment.arguments else { return plain() };
let inner = args.args.iter().find_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty.clone()),
_ => None,
});
inner.map(KernelKind::Poll).unwrap_or_else(plain)
}
"SourceFuture" => KernelKind::Future(source_future_payload(segment)),
"Result" => {
let PathArguments::AngleBracketed(args) = &segment.arguments else { return plain() };
let mut types = args.args.iter().filter_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty),
_ => None,
});
let (Some(inner), Some(Type::Path(error_path))) = (types.next(), types.next()) else {
return plain();
};
if error_path.path.segments.last().is_none_or(|segment| segment.ident != "Interrupt") {
return plain();
}
if let Type::Path(inner_path) = inner
&& let Some(inner_segment) = inner_path.path.segments.last()
&& inner_segment.ident == "SourceFuture"
{
return KernelKind::FutureInterrupt(source_future_payload(inner_segment));
}
KernelKind::Interrupt(inner.clone())
}
_ => plain(),
}
}
pub(crate) fn context_param(parsed: &ParsedNodeFn) -> Option<&TypeParam> {
let Type::Path(path) = &parsed.input.ty else {
return None;
};
let ident = path.path.get_ident()?;
parsed.fn_generics.iter().find_map(|param| match param {
GenericParam::Type(type_param) if &type_param.ident == ident => Some(type_param),
_ => None,
})
}
pub(crate) fn type_disqualifies(ty: &Type) -> bool {
struct Disqualifier {
found: bool,
}
impl<'ast> Visit<'ast> for Disqualifier {
fn visit_type_reference(&mut self, _: &'ast syn::TypeReference) {
self.found = true;
}
fn visit_type_impl_trait(&mut self, _: &'ast syn::TypeImplTrait) {
self.found = true;
}
fn visit_lifetime(&mut self, _: &'ast Lifetime) {
self.found = true;
}
}
let mut visitor = Disqualifier { found: false };
visitor.visit_type(ty);
visitor.found
}
pub(crate) fn desugar_extract_lifetime(bound: &TypeParamBound, core_types: &TokenStream2) -> TokenStream2 {
let TypeParamBound::Trait(trait_bound) = bound else {
return quote!(#bound);
};
let Some(segment) = trait_bound.path.segments.last() else {
return quote!(#bound);
};
if segment.ident != "ExtractArena" {
return quote!(#bound);
}
let PathArguments::AngleBracketed(args) = &segment.arguments else {
return quote!(#bound);
};
if args.args.len() != 1 {
return quote!(#bound);
}
let Some(GenericArgument::Lifetime(lifetime)) = args.args.first() else {
return quote!(#bound);
};
quote!(#core_types::context::ExtractArena<ArenaRef = &#lifetime #core_types::arena::Arena>)
}
@@ -0,0 +1,519 @@
use super::*;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{GenericParam, Ident, Type};
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, class: &Class, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
if !data_field_generic_idents.is_empty() {
return quote!();
}
match class {
Class::RecordIo(_) => record_entries_tokens(parsed, struct_name, regular_fields),
Class::Routing(_) => routing_entries_tokens(parsed, struct_name, regular_fields),
Class::Flip { .. } => flip_entries_tokens(parsed, struct_name, regular_fields),
Class::Opaque => record_opaque_entries_tokens(parsed, struct_name, regular_fields),
}
}
/// The registry rows of a flipped plain node: every wire is a record wire,
/// inputs resolve their layouts off the claimed handles, and the output is an
/// element-only record of the kernel's return type.
fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let Some(rows) = implementation_rows(parsed, regular_fields) else {
return quote!();
};
let rows: Vec<&Vec<Type>> = rows.iter().filter(|row| row.iter().all(|ty| !type_disqualifies(ty))).collect();
if rows.is_empty() {
return quote!();
}
let output = slot_value_type(&parsed.output_type);
let field_type = |field: &ParsedField| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type.clone(),
};
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
let generic_positions: Option<Vec<(Ident, usize)>> = parsed
.fn_generics
.iter()
.filter_map(|param| match param {
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(&type_param.ident),
_ => None,
})
.map(|generic| {
regular_fields
.iter()
.position(|field| generic_extractable(&field_type(field), generic))
.map(|index| (generic.clone(), index))
})
.collect();
let Some(generic_positions) = generic_positions else {
return quote!();
};
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let node_underscores: Vec<TokenStream2> = regular_fields.iter().map(|_| quote!(_)).collect();
// Shorthand associated types in the output only resolve against the
// generics' bounds, so rows name the output through a bounded alias. Only
// output-reaching generics (directly or through a kept bound) may appear:
// an unused alias parameter is an error.
let candidate_params: Vec<&GenericParam> = parsed
.fn_generics
.iter()
.filter(|param| matches!(param, GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref()))
.collect();
let param_ident = |param: &&GenericParam| match param {
GenericParam::Type(type_param) => type_param.ident.clone(),
_ => unreachable!("candidates are type parameters"),
};
let mut kept: Vec<bool> = candidate_params.iter().map(|param| type_contains_ident(&output, &param_ident(param))).collect();
loop {
let mut grew = false;
for index in 0..candidate_params.len() {
if kept[index] {
continue;
}
let ident = param_ident(&candidate_params[index]);
let mentioned = candidate_params.iter().zip(&kept).any(|(param, kept)| {
*kept
&& match param {
GenericParam::Type(type_param) => type_param.bounds.iter().any(|bound| {
let bound: Type = syn::parse_quote!(dyn #bound);
type_contains_ident(&bound, &ident)
}),
_ => false,
}
});
if mentioned {
kept[index] = true;
grew = true;
}
}
if !grew {
break;
}
}
let alias_params: Vec<&GenericParam> = candidate_params.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(param, _)| *param).collect();
let alias_param_idents: Vec<Ident> = alias_params.iter().map(|param| param_ident(param)).collect();
let alias_param_tokens: Vec<TokenStream2> = alias_params.iter().map(|param| quote!(#param)).collect();
let output_alias = format_ident!("__{}_output", fn_name);
let alias_def = match alias_param_tokens.is_empty() {
true => quote!(#[allow(non_camel_case_types)] type #output_alias = #output;),
false => quote!(#[allow(non_camel_case_types, type_alias_bounds)] type #output_alias<#(#alias_param_tokens,)*> = #output;),
};
let entries = rows.iter().filter_map(|row| {
let assignments: Vec<(Ident, Type)> = generic_positions
.iter()
.map(|(generic, index)| generic_assignment(&field_type(regular_fields[*index]), &row[*index], generic).map(|assigned| (generic.clone(), assigned)))
.collect::<Option<_>>()?;
if type_disqualifies(&substitute_ident_types(&output, &assignments)) {
return None;
}
let assignment_types: Vec<TokenStream2> = assignments.iter().map(|(_, ty)| quote!(#ty)).collect();
let alias_arguments: Vec<TokenStream2> = assignments
.iter()
.filter(|(generic, _)| alias_param_idents.contains(generic))
.map(|(_, ty)| quote!(#ty))
.collect();
let row_output = match alias_arguments.is_empty() {
true => quote!(#output_alias),
false => quote!(#output_alias<#(#alias_arguments),*>),
};
let assignment_types = assignment_types.iter();
let turbofish = quote!(::<#(#node_underscores,)* #(#assignment_types,)*>);
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_edge_type::<#ty>()));
let downcasts = names.iter().zip(row.iter()).enumerate().map(|(index, (name, ty))| {
let handle = format_ident!("__handle_{index}");
let layout = format_ident!("__layout_{index}");
quote! {
let #handle = inputs.next().unwrap();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_record::<#ty>()?;
}
});
let layout_args = (0..arity).map(|index| {
let layout = format_ident!("__layout_{index}");
quote!(&#layout,)
});
Some(quote! {
gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
gcore::registry::record_type::<#row_output>(),
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __node = #struct_name #turbofish::new(#(#names,)* #(#layout_args)*);
Ok(gcore::registry::EdgeHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
},
}
})
});
let entries: Vec<TokenStream2> = entries.collect();
if entries.is_empty() {
return quote!();
}
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
#alias_def
vec![#(#entries),*]
}
}
}
/// The registry row of a routing node: one instance covers every element,
/// sources claim generic record edges, and the constructor wraps each source
/// in its union translation and stores the union as the node's layout.
fn routing_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let Some(routing) = routing_io(parsed) else {
return quote!();
};
let is_source = |field: &ParsedField| {
let ty = match &field.ty {
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
};
matches!(ty, Type::Path(path) if path.path.get_ident() == Some(&routing.generic))
};
let values_concrete = regular_fields.iter().filter(|field| !is_source(field)).all(|field| {
let (ty, lend) = match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
};
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
});
if !values_concrete {
return quote!();
}
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let token_name = routing.generic.to_string();
let input_types = regular_fields.iter().map(|field| {
if is_source(field) {
return quote!(gcore::registry::generic_record_edge_type(#token_name));
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::record_edge_type::<#ty>()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
}
});
let source_layouts: Vec<Ident> = regular_fields
.iter()
.enumerate()
.filter(|(_, field)| is_source(field))
.map(|(index, _)| format_ident!("__layout_{index}"))
.collect();
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
let name = &field.pat_ident.ident;
if is_source(field) {
let layout = format_ident!("__layout_{index}");
let handle = format_ident!("__handle_{index}");
let ty = format_ident!("__ty_{index}");
return quote! {
let #handle = inputs.next().unwrap();
let #ty = #handle.ty().clone();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
};
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
let handle = format_ident!("__handle_{index}");
let layout = format_ident!("__in_layout_{index}");
quote! {
let #handle = inputs.next().unwrap();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_record::<#ty>()?;
}
}
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
}
});
let value_layout_args = regular_fields
.iter()
.enumerate()
.filter(|(_, field)| !is_source(field) && matches!(field.ty, ParsedFieldType::Regular(_)))
.map(|(index, _)| {
let layout = format_ident!("__in_layout_{index}");
quote!(&#layout,)
});
let source_wraps = regular_fields.iter().enumerate().filter(|(_, field)| is_source(field)).map(|(index, field)| {
let name = &field.pat_ident.ident;
let layout = format_ident!("__layout_{index}");
quote!(let #name = gcore::record::RecordSource::new(#name, &#layout, &__union);)
});
let first_source_ty = regular_fields
.iter()
.enumerate()
.find(|(_, field)| is_source(field))
.map(|(index, _)| format_ident!("__ty_{index}"))
.expect("routing nodes have a source");
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
vec![gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#token_name)))),
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __union = gcore::record::Layout::union(&[#(&#source_layouts),*]);
#(#source_wraps)*
let __node = #struct_name::new(#(#names,)* &__union, #(#value_layout_args)*);
Ok(gcore::registry::EdgeHandle::new_erased(
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
#first_source_ty,
))
},
}]
}
}
}
fn record_opaque_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let is_record = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Node(NodeParsedField { output_type, .. }) if is_record_value(output_type));
let values_concrete = regular_fields.iter().filter(|field| !is_record(field)).all(|field| {
let (ty, lend) = match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
};
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
});
if !values_concrete {
return quote!();
}
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let input_types = regular_fields.iter().map(|field| {
if is_record(field) {
return quote!(gcore::registry::generic_record_edge_type("T"));
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(gcore::registry::edge_type::<#ty>()),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::edge_type::<#ty>()),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
}
});
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
let name = &field.pat_ident.ident;
if is_record(field) {
let layout = format_ident!("__layout_{index}");
let handle = format_ident!("__handle_{index}");
let ty = format_ident!("__ty_{index}");
return quote! {
let #handle = inputs.next().unwrap();
let #ty = #handle.ty().clone();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
};
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
}
});
let first_record = regular_fields.iter().position(|field| is_record(field)).expect("record-opaque nodes have a record input");
let record_layout = format_ident!("__layout_{first_record}");
let record_ty = format_ident!("__ty_{first_record}");
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
vec![gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed("T")))),
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __node = #struct_name::new(#(#names,)* &#record_layout);
Ok(gcore::registry::EdgeHandle::new_erased(
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
#record_ty,
))
},
}]
}
}
}
fn record_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
let Some(shape) = record_shape(parsed) else {
return quote!();
};
let carrier_in_fields = !shape.skips_carrier();
let values_concrete = regular_fields.iter().skip(carrier_in_fields as usize).all(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => !contains_open_generic(parsed, ty) && (lend.is_some() || !type_disqualifies(ty)),
_ => false,
});
if !values_concrete {
return quote!();
}
let fn_name = &parsed.fn_name;
let entries_name = format_ident!("{}_entries", fn_name);
let arity = regular_fields.len();
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
let reading_secondaries = reading_secondary_indices(regular_fields, &shape);
let input_types = regular_fields.iter().enumerate().map(|(index, field)| {
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("record nodes take no lazy inputs")
};
if carrier_in_fields && index == 0 {
return match &shape.carrier {
RecordCarrier::Token(token) => {
let name = token.to_string();
quote!(gcore::registry::generic_record_edge_type(#name))
}
RecordCarrier::Read(carrier_ty) => quote!(gcore::registry::record_edge_type::<#carrier_ty>()),
RecordCarrier::None => unreachable!(),
};
}
match field.attribute_reads.is_empty() {
true => quote!(gcore::registry::edge_type::<#ty>()),
false => quote!(gcore::registry::record_edge_type::<#ty>()),
}
});
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
let name = &field.pat_ident.ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("record nodes take no lazy inputs")
};
if carrier_in_fields && index == 0 {
return quote! {
let __carrier_handle = inputs.next().unwrap();
let __carrier_ty = __carrier_handle.ty().clone();
let Some(__carrier_layout) = __carrier_handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = __carrier_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__carrier_ty.clone())?;
};
}
if !field.attribute_reads.is_empty() {
let layout_local = format_ident!("__in_layout_{index}");
return quote! {
let __in_handle = inputs.next().unwrap();
let __in_ty = __in_handle.ty().clone();
let Some(#layout_local) = __in_handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = __in_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__in_ty)?;
};
}
quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;)
});
let wire_layout_arg = carrier_in_fields.then(|| quote!(&__carrier_layout,)).into_iter();
let input_layout_args = reading_secondaries.iter().map(|index| {
let layout_local = format_ident!("__in_layout_{index}");
quote!(&#layout_local,)
});
let (io_output, construct_output) = match (&shape.carrier, &shape.element_write) {
(RecordCarrier::Token(token), _) => {
let name = token.to_string();
(
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
quote!(Ok(gcore::registry::EdgeHandle::new_erased(
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
__carrier_ty,
))),
)
}
(_, Some(element)) => (
quote!(gcore::registry::record_type::<#element>()),
quote!(Ok(gcore::registry::EdgeHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
),
(_, None) => unreachable!("non-token record nodes write an element"),
};
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
vec![gcore::registry::RegistryEntry {
io: gcore::registry::NodeIOTypes::new(
gcore::concrete!(gcore::context::ContextImpl<'static>),
#io_output,
vec![#(#input_types),*],
),
constructor: |inputs| {
if inputs.len() != #arity {
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
#(#downcasts)*
let __node = #struct_name::new(#(#names,)* #(#wire_layout_arg)* #(#input_layout_args)*);
#construct_output
},
}]
}
}
}
fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&ParsedField]) -> Option<Vec<Vec<Type>>> {
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
let open_generics: Vec<&Ident> = parsed
.fn_generics
.iter()
.filter_map(|param| match param {
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(&type_param.ident),
_ => None,
})
.collect();
let candidates: Vec<Vec<Type>> = regular_fields
.iter()
.map(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => match implementations.is_empty() {
false => Some(implementations.iter().cloned().collect()),
true => open_generics.iter().all(|generic| !crate::codegen::type_contains_ident(ty, generic)).then(|| vec![ty.clone()]),
},
ParsedFieldType::Node(NodeParsedField { output_type, implementations, .. }) => match implementations.is_empty() {
false => Some(implementations.iter().map(|implementation| implementation.output.clone()).collect()),
true => open_generics
.iter()
.all(|generic| !crate::codegen::type_contains_ident(output_type, generic))
.then(|| vec![output_type.clone()]),
},
})
.collect::<Option<_>>()?;
let row_count = candidates.iter().map(|types| types.len()).max().unwrap_or(1).max(1);
Some((0..row_count).map(|row| candidates.iter().map(|types| types[row.min(types.len() - 1)].clone()).collect()).collect())
}
@@ -0,0 +1,173 @@
use super::*;
/// Generates strongly typed utilites to access inputs
pub(crate) fn generate_node_input_references(
parsed: &ParsedNodeFn,
fn_generics: &[crate::GenericParam],
field_idents: &[&PatIdent],
core_types: &TokenStream2,
identifier: &Ident,
cfg: &TokenStream2,
) -> TokenStream2 {
let inputs_module_name = format_ident!("{}", parsed.struct_name.to_string().to_case(Case::Snake));
let mut generated_input_accessor = Vec::new();
if !parsed.attributes.skip_impl {
let (mut modified, mut generic_collector) = FilterUsedGenerics::new(fn_generics);
for (input_index, (parsed_input, input_ident)) in parsed.fields.iter().zip(field_idents).enumerate() {
let mut ty = match &parsed_input.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
}
.clone();
// We only want the necessary generics.
let used = generic_collector.filter_unnecessary_generics(&mut modified, &mut ty);
// TODO: figure out a better name that doesn't conflict with so many types
let struct_name = format_ident!("{}Input", input_ident.ident.to_string().to_case(Case::Pascal));
let (fn_generic_params, phantom_data_declerations) = generate_phantom_data(used.iter());
// Only create structs with phantom data where necessary.
generated_input_accessor.push(if phantom_data_declerations.is_empty() {
quote! {
pub struct #struct_name;
}
} else {
quote! {
pub struct #struct_name <#(#used),*>{
#(#phantom_data_declerations,)*
}
}
});
generated_input_accessor.push(quote! {
impl <#(#used),*> #core_types::NodeInputDecleration for #struct_name <#(#fn_generic_params),*> {
const INDEX: usize = #input_index;
fn identifier() -> #core_types::ProtoNodeIdentifier {
#inputs_module_name::IDENTIFIER.clone()
}
type Result = #ty;
}
})
}
}
quote! {
#cfg
pub mod #inputs_module_name {
use super::*;
/// The `ProtoNodeIdentifier` of this node without any generics attached to it
pub const IDENTIFIER: #core_types::ProtoNodeIdentifier = #identifier();
#(#generated_input_accessor)*
}
}
}
/// It is necessary to generate PhantomData for each fn generic to avoid compiler errors.
pub(crate) fn generate_phantom_data<'a>(fn_generics: impl Iterator<Item = &'a crate::GenericParam>) -> (Vec<TokenStream2>, Vec<TokenStream2>) {
let mut phantom_data_declerations = Vec::new();
let mut fn_generic_params = Vec::new();
for fn_generic_param in fn_generics {
let field_name = format_ident!("phantom_{}", phantom_data_declerations.len());
match fn_generic_param {
crate::GenericParam::Lifetime(lifetime_param) => {
let lifetime = &lifetime_param.lifetime;
fn_generic_params.push(quote! {#lifetime});
phantom_data_declerations.push(quote! {#field_name: core::marker::PhantomData<&#lifetime ()>})
}
crate::GenericParam::Type(type_param) => {
let generic_name = &type_param.ident;
fn_generic_params.push(quote! {#generic_name});
phantom_data_declerations.push(quote! {#field_name: core::marker::PhantomData<#generic_name>});
}
_ => {}
}
}
(fn_generic_params, phantom_data_declerations)
}
/// Get only the necessary generics.
struct FilterUsedGenerics {
all: Vec<crate::GenericParam>,
used: Vec<bool>,
}
impl VisitMut for FilterUsedGenerics {
fn visit_lifetime_mut(&mut self, used_lifetime: &mut Lifetime) {
for (generic, used) in self.all.iter().zip(self.used.iter_mut()) {
let crate::GenericParam::Lifetime(lifetime_param) = generic else { continue };
if used_lifetime == &lifetime_param.lifetime {
*used = true;
}
}
}
fn visit_path_mut(&mut self, path: &mut syn::Path) {
for (index, (generic, used)) in self.all.iter().zip(self.used.iter_mut()).enumerate() {
let crate::GenericParam::Type(type_param) = generic else { continue };
if path.leading_colon.is_none() && !path.segments.is_empty() && path.segments[0].arguments.is_none() && path.segments[0].ident == type_param.ident {
*used = true;
// Sometimes the generics conflict with the type name so we rename the generics.
path.segments[0].ident = format_ident!("G{index}");
}
}
for mut el in Punctuated::pairs_mut(&mut path.segments) {
self.visit_path_segment_mut(el.value_mut());
}
}
}
impl FilterUsedGenerics {
fn new(fn_generics: &[crate::GenericParam]) -> (Vec<crate::GenericParam>, Self) {
let mut all_possible_generics = fn_generics.to_vec();
// The 'n lifetime may also be needed; we must add it in
all_possible_generics.insert(0, syn::GenericParam::Lifetime(syn::LifetimeParam::new(Lifetime::new("'n", proc_macro2::Span::call_site()))));
let modified = all_possible_generics
.iter()
.cloned()
.enumerate()
.map(|(index, mut generic)| {
let crate::GenericParam::Type(type_param) = &mut generic else { return generic };
// Sometimes the generics conflict with the type name so we rename the generics.
type_param.ident = format_ident!("G{index}");
generic
})
.collect::<Vec<_>>();
let generic_collector = Self {
used: vec![false; all_possible_generics.len()],
all: all_possible_generics,
};
(modified, generic_collector)
}
fn used<'a>(&'a self, modified: &'a [crate::GenericParam]) -> impl Iterator<Item = &'a crate::GenericParam> {
modified.iter().zip(&self.used).filter(|(_, used)| **used).map(move |(value, _)| value)
}
fn filter_unnecessary_generics(&mut self, modified: &mut Vec<syn::GenericParam>, ty: &mut Type) -> Vec<syn::GenericParam> {
self.used.fill(false);
// Find out which generics are necessary to support the node input
self.visit_type_mut(ty);
// Sometimes generics may reference other generics. This is a non-optimal way of dealing with that.
for _ in 0..=self.all.len() {
for (index, item) in modified.iter_mut().enumerate() {
if self.used[index] {
self.visit_generic_param_mut(item);
}
}
}
self.used(&*modified).cloned().collect()
}
}
+212 -2
View File
@@ -7,8 +7,8 @@ use syn::punctuated::Punctuated;
use syn::spanned::Spanned;
use syn::token::{Comma, RArrow};
use syn::{
AttrStyle, Attribute, Error, Expr, FnArg, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, ReturnType, TraitBound, Type, TypeImplTrait, TypeParam,
TypeParamBound, Visibility, WhereClause, parse_quote,
AttrStyle, Attribute, Error, Expr, FnArg, GenericArgument, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, PathArguments, ReturnType,
TraitBound, Type, TypeImplTrait, TypeParam, TypeParamBound, Visibility, WhereClause, parse_quote,
};
use crate::codegen::generate_node_code;
@@ -39,6 +39,74 @@ pub(crate) struct ParsedNodeFn {
pub(crate) description: String,
}
/// An `Attr<Marker>` slot in a parameter's read tuple: a declared attribute
/// read on that input's wire, not a wired input of its own.
#[derive(Clone, Debug)]
pub(crate) struct AttributeRead {
pub(crate) pat_ident: PatIdent,
pub(crate) marker: Type,
}
/// The write half of a record kernel's return: the element type in the first
/// tuple slot, then the attribute markers written and the ones removed. `None`
/// unless the value is a well-formed write tuple (a non-marker element first,
/// then only `Attr` and `RemoveAttr` slots, at least one).
pub(crate) struct RecordWrites {
pub(crate) element: Type,
pub(crate) markers: Vec<Type>,
pub(crate) removes: Vec<Type>,
}
pub(crate) fn record_writes(value: &Type) -> Option<RecordWrites> {
let Type::Tuple(tuple) = value else { return None };
let mut slots = tuple.elems.iter();
let element = slots.next()?;
if attr_marker(element).is_some() || remove_attr_marker(element).is_some() {
return None;
}
let mut markers = Vec::new();
let mut removes = Vec::new();
for slot in slots {
if let Some(marker) = attr_marker(slot) {
markers.push(marker);
} else if let Some(marker) = remove_attr_marker(slot) {
removes.push(marker);
} else {
return None;
}
}
(!markers.is_empty() || !removes.is_empty()).then(|| RecordWrites {
element: element.clone(),
markers,
removes,
})
}
/// Returns the marker type of an `Attr<Marker>` type, if `ty` is one.
pub(crate) fn attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "Attr")
}
/// Returns the marker type of a `RemoveAttr<Marker>` type, if `ty` is one.
pub(crate) fn remove_attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "RemoveAttr")
}
fn marker_of(ty: &Type, wrapper: &str) -> Option<Type> {
let Type::Path(path) = ty else { return None };
let segment = path.path.segments.last()?;
if segment.ident != wrapper {
return None;
}
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
let mut types = args.args.iter().filter_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty),
_ => None,
});
let marker = types.next()?;
types.next().is_none().then(|| marker.clone())
}
#[derive(Debug, Default, Clone)]
pub(crate) struct NodeFnAttributes {
pub(crate) category: Option<LitStr>,
@@ -64,6 +132,8 @@ pub(crate) struct NodeFnAttributes {
pub(crate) batch: Option<Path>,
/// Whether partial upstream values are mapped to `Pending` instead of flowing into this node
pub(crate) no_partial: bool,
/// Whether this node keeps the plain-wire lowering during the record transition
pub(crate) plain: bool,
}
#[derive(Clone, Debug, Default)]
@@ -127,6 +197,9 @@ pub struct ParsedField {
pub number_step: Option<LitFloat>,
pub unit: Option<LitStr>,
pub is_data_field: bool,
/// The attribute reads destructured from this input's tuple, resolved
/// against this input's wire.
pub(crate) attribute_reads: Vec<AttributeRead>,
}
#[derive(Clone, Debug)]
@@ -240,6 +313,8 @@ impl Parse for NumberRange {
#[derive(Clone, Debug)]
pub struct RegularParsedField {
pub ty: Type,
/// The original reference tokens when the parameter was written `&T`; `ty` holds the peeled inner type.
pub lend: Option<syn::TypeReference>,
pub exposed: bool,
pub value_source: ParsedValueSource,
pub number_soft_min: Option<NumberBound>,
@@ -324,6 +399,7 @@ impl Parse for NodeFnAttributes {
let mut extent = None;
let mut batch = None;
let mut no_partial = false;
let mut plain = false;
let content = input;
// let content;
@@ -509,6 +585,13 @@ impl Parse for NodeFnAttributes {
//
// Example usage:
// #[node_macro::node(..., no_partial, ...)]
"plain" => {
let path = meta.require_path_only()?;
if plain {
return Err(Error::new_spanned(path, "Multiple 'plain' attributes are not allowed"));
}
plain = true;
}
"no_partial" => {
let path = meta.require_path_only()?;
if no_partial {
@@ -560,6 +643,7 @@ impl Parse for NodeFnAttributes {
extent,
batch,
no_partial,
plain,
})
}
}
@@ -651,8 +735,24 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
context_features,
});
} else if let Pat::Ident(pat_ident) = &**pat {
if attr_marker(ty).is_some() {
return Err(Error::new_spanned(pat_ident, "an attribute read binds to an input: destructure it as `(value, Attr<..>)`"));
}
let field = parse_field(pat_ident.clone(), (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat_ident, format!("Failed to parse argument '{}': {}", pat_ident.ident, e)))?;
fields.push(field);
} else if let Pat::Tuple(pat_tuple) = &**pat {
let field = parse_read_tuple(pat_tuple, ty, attrs, index)?;
fields.push(field);
} else if let Pat::Wild(wild) = &**pat {
let pat_ident = PatIdent {
attrs: wild.attrs.clone(),
by_ref: None,
mutability: None,
ident: format_ident!("_unit{}", index, span = wild.underscore_token.span),
subpat: None,
};
let field = parse_field(pat_ident, (**ty).clone(), attrs).map_err(|e| Error::new_spanned(pat, format!("Failed to parse argument: {e}")))?;
fields.push(field);
} else {
return Err(Error::new_spanned(pat, "Expected a simple identifier for the field name"));
}
@@ -665,6 +765,85 @@ fn parse_inputs(inputs: &Punctuated<FnArg, Comma>) -> syn::Result<(Input, Vec<Pa
Ok((input, fields))
}
/// Splits a lazy input's `Output = (T, Attr<..>..)` tuple into the element
/// type (the wire type) and the declared reads on that edge. A tuple without
/// `Attr` slots is an ordinary tuple output and passes through untouched.
fn split_lazy_reads(output_type: Type) -> syn::Result<(Type, Vec<AttributeRead>)> {
let Type::Tuple(tuple) = &output_type else {
return Ok((output_type, Vec::new()));
};
if !tuple.elems.iter().any(|slot| attr_marker(slot).is_some()) {
return Ok((output_type, Vec::new()));
}
let spelling = "a lazy input with attribute reads declares `Output = (T, Attr<..>)`";
let mut slots = tuple.elems.iter();
let element = slots.next().ok_or_else(|| Error::new_spanned(tuple, spelling))?;
if attr_marker(element).is_some() {
return Err(Error::new_spanned(element, spelling));
}
let attribute_reads: Vec<AttributeRead> = slots
.enumerate()
.map(|(index, slot)| {
let marker = attr_marker(slot).ok_or_else(|| Error::new_spanned(slot, spelling))?;
Ok(AttributeRead {
pat_ident: PatIdent {
attrs: Vec::new(),
by_ref: None,
mutability: None,
ident: format_ident!("__lazy_read_{}", index, span = slot.span()),
subpat: None,
},
marker,
})
})
.collect::<syn::Result<_>>()?;
Ok((element.clone(), attribute_reads))
}
/// Parses a `(value, reads..): (T, Attr<..>..)` parameter: the value component
/// is an ordinary field of the value type, each `Attr` component a read bound
/// to this input's wire.
fn parse_read_tuple(pat_tuple: &syn::PatTuple, ty: &Type, attrs: &[Attribute], index: usize) -> syn::Result<ParsedField> {
let spelling = "an input with attribute reads destructures as `(value, Attr<..>)` over `(T, Attr<..>)`";
let Type::Tuple(ty_tuple) = ty else {
return Err(Error::new_spanned(ty, spelling));
};
if pat_tuple.elems.len() != ty_tuple.elems.len() || ty_tuple.elems.len() < 2 {
return Err(Error::new_spanned(pat_tuple, spelling));
}
let mut slots = pat_tuple.elems.iter().zip(ty_tuple.elems.iter());
let (value_pat, value_ty) = slots.next().expect("length checked above");
if attr_marker(value_ty).is_some() {
return Err(Error::new_spanned(value_ty, spelling));
}
let value_ident = match value_pat {
Pat::Ident(pat_ident) => pat_ident.clone(),
Pat::Wild(wild) => PatIdent {
attrs: wild.attrs.clone(),
by_ref: None,
mutability: None,
ident: format_ident!("_value{}", index, span = wild.underscore_token.span),
subpat: None,
},
_ => return Err(Error::new_spanned(value_pat, "Expected a simple identifier for the value component")),
};
let attribute_reads: Vec<AttributeRead> = slots
.map(|(pat, ty)| {
let marker = attr_marker(ty).ok_or_else(|| Error::new_spanned(ty, spelling))?;
let Pat::Ident(pat_ident) = pat else {
return Err(Error::new_spanned(pat, "Expected a simple identifier for the attribute read"));
};
Ok(AttributeRead {
pat_ident: pat_ident.clone(),
marker,
})
})
.collect::<syn::Result<_>>()?;
let mut field = parse_field(value_ident.clone(), value_ty.clone(), attrs).map_err(|e| Error::new_spanned(&value_ident, format!("Failed to parse argument '{}': {}", value_ident.ident, e)))?;
field.attribute_reads = attribute_reads;
Ok(field)
}
/// Parse context feature identifiers from the trait bounds of a context parameter.
fn parse_context_feature_idents(ty: &Type) -> Vec<Ident> {
let mut features = Vec::new();
@@ -883,6 +1062,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
.transpose()?
.unwrap_or_default();
let (output_type, attribute_reads) = split_lazy_reads(output_type)?;
Ok(ParsedField {
pat_ident,
ty: ParsedFieldType::Node(NodeParsedField {
@@ -897,6 +1077,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_step,
unit,
is_data_field,
attribute_reads,
})
} else {
let implementations = extract_attribute(attrs, "implementations")
@@ -904,6 +1085,11 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
.transpose()?
.unwrap_or_default();
let (ty, lend) = match ty {
Type::Reference(reference) => ((*reference.elem).clone(), Some(reference)),
ty => (ty, None),
};
// Error if a float literal is given for a bound on an integer-typed field
if is_integer_type(&ty) {
let bound_attrs = [
@@ -936,6 +1122,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_hard_max,
number_mode_range,
ty,
lend,
value_source,
implementations,
gpu_image,
@@ -947,6 +1134,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_step,
unit,
is_data_field,
attribute_reads: Vec::new(),
})
}
}
@@ -1048,6 +1236,7 @@ impl ParsedNodeFn {
widget_override: ParsedWidgetOverride::Hidden,
ty: ParsedFieldType::Regular(RegularParsedField {
ty,
lend: None,
exposed: false,
value_source,
number_soft_min: None,
@@ -1062,6 +1251,7 @@ impl ParsedNodeFn {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
};
self.fields.push(hidden_field(
"_runtime",
@@ -1198,6 +1388,7 @@ mod tests {
extent: None,
batch: None,
no_partial: false,
plain: false,
},
fn_name: Ident::new("add", Span::call_site()),
struct_name: Ident::new("Add", Span::call_site()),
@@ -1218,6 +1409,7 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1233,6 +1425,7 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::from("Multi\nLine\n"),
@@ -1272,6 +1465,7 @@ mod tests {
extent: None,
batch: None,
no_partial: false,
plain: false,
},
fn_name: Ident::new("transform", Span::call_site()),
struct_name: Ident::new("Transform", Span::call_site()),
@@ -1301,6 +1495,7 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
},
ParsedField {
pat_ident: pat_ident("translate"),
@@ -1308,6 +1503,7 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(DVec2),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1323,6 +1519,7 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
},
],
body: TokenStream2::new(),
@@ -1360,6 +1557,7 @@ mod tests {
extent: None,
batch: None,
no_partial: false,
plain: false,
},
fn_name: Ident::new("circle", Span::call_site()),
struct_name: Ident::new("Circle", Span::call_site()),
@@ -1380,6 +1578,7 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::Default(quote!(50.)),
@@ -1395,6 +1594,7 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: "Test\n".into(),
@@ -1430,6 +1630,7 @@ mod tests {
extent: None,
batch: None,
no_partial: false,
plain: false,
},
fn_name: Ident::new("levels", Span::call_site()),
struct_name: Ident::new("Levels", Span::call_site()),
@@ -1450,6 +1651,7 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1470,6 +1672,7 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1512,6 +1715,7 @@ mod tests {
extent: None,
batch: None,
no_partial: false,
plain: false,
},
fn_name: Ident::new("add", Span::call_site()),
struct_name: Ident::new("Add", Span::call_site()),
@@ -1532,6 +1736,7 @@ mod tests {
description: String::from("b"),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(f64),
exposed: false,
value_source: ParsedValueSource::None,
@@ -1547,6 +1752,7 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1597,6 +1803,7 @@ mod tests {
extent: None,
batch: None,
no_partial: false,
plain: false,
},
fn_name: Ident::new("load_image", Span::call_site()),
struct_name: Ident::new("LoadImage", Span::call_site()),
@@ -1617,6 +1824,7 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
lend: None,
ty: parse_quote!(String),
exposed: true,
value_source: ParsedValueSource::None,
@@ -1632,6 +1840,7 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1667,6 +1876,7 @@ mod tests {
extent: None,
batch: None,
no_partial: false,
plain: false,
},
fn_name: Ident::new("custom_node", Span::call_site()),
struct_name: Ident::new("CustomNode", Span::call_site()),
@@ -232,6 +232,7 @@ impl PerPixelAdjustCodegen<'_> {
widget_override: Default::default(),
ty: ParsedFieldType::Regular(RegularParsedField {
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
lend: None,
exposed: true,
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
number_soft_min: None,
@@ -246,6 +247,7 @@ impl PerPixelAdjustCodegen<'_> {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
});
// find exactly one gpu_image field, runtime doesn't support more than 1 atm
+231 -2
View File
@@ -1,6 +1,6 @@
use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField};
use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, attr_marker, record_writes, remove_attr_marker};
use proc_macro_error2::emit_error;
use quote::quote;
use quote::{ToTokens, quote};
use syn::spanned::Spanned;
use syn::{GenericParam, Type};
@@ -12,6 +12,9 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
validate_min_max,
validate_range_slider_bounds,
validate_async_source,
validate_lend_fields,
validate_record_io,
validate_lazy_reads,
];
for validator in validators {
@@ -21,6 +24,190 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
Ok(())
}
fn validate_record_io(parsed: &ParsedNodeFn) {
let value = crate::codegen::slot_value_type(&parsed.output_type);
if let Type::Tuple(tuple) = &value {
let has_marker_slot = tuple.elems.iter().any(|slot| attr_marker(slot).is_some() || remove_attr_marker(slot).is_some());
if has_marker_slot && record_writes(&value).is_none() {
emit_error!(
parsed.output_type.span(),
"a record return tuple is the element first, then only `Attr<..>` writes and `RemoveAttr<..>` deletions"
);
}
} else if attr_marker(&value).is_some() || remove_attr_marker(&value).is_some() {
emit_error!(parsed.output_type.span(), "an attribute write needs an element in the first tuple slot, e.g. `(T, Attr<..>)`");
}
let writes = record_writes(&value);
let has_reads = parsed
.fields
.iter()
.any(|field| !field.attribute_reads.is_empty() && matches!(field.ty, ParsedFieldType::Regular(_)));
if !has_reads && writes.is_none() {
return;
}
if parsed.is_async || crate::codegen::is_source_kernel(&parsed.output_type) {
emit_error!(parsed.output_type.span(), "attribute io is not supported on async source kernels");
}
if crate::codegen::is_poll_kernel(&parsed.output_type) {
emit_error!(parsed.output_type.span(), "attribute io needs a plain or `Result<_, Interrupt>` kernel, not a `GPoll` one");
}
for field in parsed.fields.iter().skip(1) {
if matches!(field.ty, ParsedFieldType::Node(_)) {
emit_error!(field.pat_ident.span(), "record nodes take no lazy inputs yet");
}
}
for (index, field) in parsed.fields.iter().enumerate() {
if field.attribute_reads.is_empty() {
continue;
}
if field.is_data_field {
emit_error!(field.pat_ident.span(), "a `#[data]` field has no wire to read attributes from");
continue;
}
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }) => {
emit_error!(field.pat_ident.span(), "attribute reads need an owned value; take `T` instead of `&T`");
}
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => {
if matches!(ty, Type::Tuple(tuple) if tuple.elems.is_empty()) {
emit_error!(field.pat_ident.span(), "attribute-only inputs are not supported yet; the value component cannot be `()`");
}
let is_token_carrier = index == 0 && implementations.is_empty() && crate::codegen::unbounded_generic(parsed, ty).is_some();
if !is_token_carrier && crate::codegen::contains_open_generic(parsed, ty) {
emit_error!(
field.pat_ident.span(),
"a reading input's value is monomorphic for now; use a concrete type or an unbounded passthrough generic in the primary input"
);
}
}
// Lazy-input reads are validated by `validate_lazy_reads`; a
// record-io node already rejects lazy inputs above.
ParsedFieldType::Node(_) => {}
}
}
let Some(carrier) = parsed.fields.first() else {
emit_error!(
parsed.fn_name.span(),
"attribute io needs a primary input as the first parameter after the context (`_: ()` for none)"
);
return;
};
let carrier_ty = match &carrier.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend: None, .. }) if !carrier.is_data_field => Some(ty),
_ => None,
};
let Some(carrier_ty) = carrier_ty else {
emit_error!(
carrier.pat_ident.span(),
"a record node's primary input is an owned element, an unbounded passthrough generic, or `_: ()`; not `#[data]`, `&T`, or `impl Node`"
);
return;
};
let no_carrier = matches!(carrier_ty, Type::Tuple(tuple) if tuple.elems.is_empty());
let token = match (no_carrier, &carrier.ty) {
(false, ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. })) if implementations.is_empty() => crate::codegen::unbounded_generic(parsed, ty),
_ => None,
};
let element = writes.as_ref().map(|writes| &writes.element).unwrap_or(&value);
match &token {
Some(token) => {
if !matches!(crate::codegen::bare_ident(element), Some(ident) if ident == token) {
emit_error!(
parsed.output_type.span(),
"a generic element passes through unchanged: return `{}` in the first tuple position",
token
);
}
}
None => {
if let Some(ident) = crate::codegen::unbounded_generic(parsed, element) {
emit_error!(parsed.output_type.span(), "the returned generic element `{}` has no matching input", ident);
} else if !no_carrier && crate::codegen::contains_open_generic(parsed, carrier_ty) {
emit_error!(
carrier.pat_ident.span(),
"record element reads are monomorphic for now; use a concrete element type or an unbounded passthrough generic"
);
} else if crate::codegen::contains_open_generic(parsed, element) {
emit_error!(parsed.output_type.span(), "a written element must be a concrete type");
}
}
}
for field in &parsed.fields {
let mut seen_reads: Vec<String> = Vec::new();
for read in &field.attribute_reads {
let marker = read.marker.to_token_stream().to_string();
if seen_reads.contains(&marker) {
emit_error!(read.pat_ident.span(), "attribute `{}` is read twice from `{}`", marker, field.pat_ident.ident);
}
seen_reads.push(marker);
}
}
if let Some(writes) = &writes {
let mut seen_writes: Vec<String> = Vec::new();
for marker in &writes.markers {
let written = marker.to_token_stream().to_string();
if seen_writes.contains(&written) {
emit_error!(parsed.output_type.span(), "attribute `{}` is written twice", written);
}
seen_writes.push(written);
}
let mut seen_removes: Vec<String> = Vec::new();
for marker in &writes.removes {
let removed = marker.to_token_stream().to_string();
if seen_removes.contains(&removed) {
emit_error!(parsed.output_type.span(), "attribute `{}` is removed twice", removed);
}
if seen_writes.contains(&removed) {
emit_error!(parsed.output_type.span(), "attribute `{}` is both written and removed", removed);
}
seen_removes.push(removed);
}
if no_carrier && !writes.removes.is_empty() {
emit_error!(parsed.output_type.span(), "a node without a primary input writes a fresh record; there is nothing to remove");
}
}
}
fn validate_lazy_reads(parsed: &ParsedNodeFn) {
if !crate::codegen::has_lazy_reads(parsed) {
return;
}
if !crate::codegen::record_flip(parsed) {
emit_error!(
parsed.fn_name.span(),
"attribute reads on a lazy input need the record lowering; routing, `plain`, shader, batch, and non-row-assignable generic nodes keep the plain one"
);
}
for field in &parsed.fields {
let ParsedFieldType::Node(NodeParsedField { output_type, .. }) = &field.ty else {
continue;
};
if field.attribute_reads.is_empty() {
continue;
}
if crate::codegen::unbounded_generic(parsed, output_type).is_some() {
emit_error!(
field.pat_ident.span(),
"an unbounded generic source forwards its whole record; attribute reads need a concrete output type"
);
}
let mut seen: Vec<String> = Vec::new();
for read in &field.attribute_reads {
let marker = read.marker.to_token_stream().to_string();
if seen.contains(&marker) {
emit_error!(read.marker.span(), "attribute `{}` is read twice from `{}`", marker, field.pat_ident.ident);
}
seen.push(marker);
}
}
}
fn validate_async_source(parsed: &ParsedNodeFn) {
let snapshot_ctx = matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
@@ -63,6 +250,30 @@ fn validate_async_source(parsed: &ParsedNodeFn) {
}
}
fn validate_lend_fields(parsed: &ParsedNodeFn) {
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
for field in &parsed.fields {
let ParsedFieldType::Regular(RegularParsedField { lend: Some(reference), .. }) = &field.ty else {
continue;
};
if let Some(mutability) = &reference.mutability {
emit_error!(mutability.span(), "reference parameters are read-only lends; `&mut` is not supported");
}
if let Some(lifetime) = &reference.lifetime {
emit_error!(lifetime.span(), "reference parameters use the eval lifetime implicitly; write a bare `&T`");
}
if field.is_data_field {
emit_error!(field.pat_ident.span(), "`#[data]` fields are node-resident state and cannot be references");
}
if parsed.is_async || future_kernel {
emit_error!(
field.pat_ident.span(),
"source kernels move their inputs into the spawned task, so they cannot take reference parameters"
);
}
}
}
fn validate_min_max(parsed: &ParsedNodeFn) {
for field in &parsed.fields {
if let ParsedField {
@@ -181,6 +392,18 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
let has_skip_impl = parsed.attributes.skip_impl;
let routing = crate::codegen::routing_io(parsed);
let record_token = crate::codegen::record_shape(parsed).and_then(|shape| match shape.carrier {
crate::codegen::RecordCarrier::Token(token) => Some(token),
_ => None,
});
let opaque_record_generic = |ty: &Type| {
let ident = match ty {
Type::Path(path) => path.path.get_ident(),
_ => None,
};
ident.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref())
};
if !has_skip_impl && !parsed.fn_generics.is_empty() {
for field in &parsed.fields {
@@ -192,6 +415,9 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
let pat_ident = &field.pat_ident;
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => {
if opaque_record_generic(ty) {
continue;
}
if contains_generic_param(ty, &parsed.fn_generics) && implementations.is_empty() {
emit_error!(
ty.span(),
@@ -209,6 +435,9 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
implementations,
..
}) => {
if opaque_record_generic(output_type) {
continue;
}
if (contains_generic_param(input_type, &parsed.fn_generics) || contains_generic_param(output_type, &parsed.fn_generics)) && implementations.is_empty() {
emit_error!(
pat_ident.span(),
@@ -1,14 +1,5 @@
use core::f64;
use core_types::Color;
use core_types::context::{Context, ContextModification, Ctx, DeriveCtx};
use core_types::gpoll::GPoll;
use core_types::list::{AttributeDyn, AttributeValueDyn, List, ListDyn};
use core_types::transform::Footprint;
use core_types::uuid::NodeId;
use glam::{DAffine2, DVec2};
use graphic_types::vector_types::GradientStops;
use graphic_types::{Artboard, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
use core_types::gpoll::Interrupt;
/// Filters out what should be unused components of the context based on the specified requirements.
/// This node is inserted by the compiler to "zero out" unused context components.
@@ -16,36 +7,10 @@ use raster_types::{CPU, GPU, Raster};
fn context_modification<T>(
ctx: impl Ctx + DeriveCtx,
/// The data to pass through, evaluated with the stripped down context.
#[implementations(
Context -> (),
Context -> bool,
Context -> u32,
Context -> u64,
Context -> f32,
Context -> f64,
Context -> String,
Context -> DAffine2,
Context -> Footprint,
Context -> DVec2,
Context -> List<String>,
Context -> List<NodeId>,
Context -> List<f64>,
Context -> List<u8>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Artboard>,
Context -> List<GradientStops>,
Context -> AttributeDyn,
Context -> AttributeValueDyn,
Context -> ListDyn,
)]
value: impl Node<Context<'_>, Output = T>,
/// The parts of the context to keep when evaluating the input value. All other parts are nullified.
modification: ContextModification,
) -> GPoll<T> {
) -> Result<T, Interrupt> {
let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
value.eval(&ctx.nullified(modification.features, &scope))
}
+2 -2
View File
@@ -29,8 +29,8 @@ fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<
input.unwrap_or_default()
}
/// Meant for debugging purposes, not general use. Clones the input value.
/// Clones the element out of its record wire.
#[node_macro::node(category("Debug"))]
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&List<Raster<CPU>>)] value: &'i T) -> T {
fn clone<T: Clone>(_: impl Ctx, #[implementations(List<Raster<CPU>>)] value: &T) -> T {
value.clone()
}
+2
View File
@@ -5,6 +5,8 @@ pub mod debug;
pub mod extract_xy;
pub mod memo;
pub mod ops;
#[cfg(test)]
mod record;
// Re-export all nodes
pub use animation::*;
+121 -100
View File
@@ -1,51 +1,63 @@
use core_types::arena::{Arena, ArenaCell};
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll};
use core_types::arena::ArenaCell;
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ExtractArena};
use core_types::frame_table::{FrameTable, Lookup};
use core_types::gpoll::{Extent, Finality, GPoll, Interrupt};
use core_types::gpoll::{Extent, Finality, GPoll};
use core_types::graphene_hash::CacheHash;
use core_types::memo::*;
use core_types::memo::IORecord;
use core_types::node::Node;
use core_types::record::{OwnedRecord, RecordCapture, RecordValue, copy_record_bytes, record_from_bytes};
use core_types::registry::cache_key;
use std::sync::Arc;
use std::sync::Mutex;
/// Helps speed up repeated renders in a computationally-heavy part of the node graph.
///
/// Stores the last evaluated data that flowed through this node and immediately returns that data on subsequent renders if the context has not changed.
#[node_macro::node(category("General"), path(graphene_core::memo), skip_impl, extent(memoize_extent))]
fn memoize<I: CacheHash, T: Clone>(input: I, #[data] cache: Arc<Mutex<Option<(u64, T, Finality)>>>, content: impl Node<I, Output = T>) -> GPoll<T> {
let key = cache_key(&input);
if let Some((hash, value, finality)) = cache.lock().unwrap().as_ref()
/// Stores a deep copy of the last record that flowed through this node and replays it on subsequent renders if the context has not changed.
#[node_macro::node(category("General"), path(graphene_core::memo), extent(memoize_extent))]
fn memoize<'e>(
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
#[data] cache: Arc<Mutex<Option<(u64, OwnedRecord, Finality)>>>,
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
) -> GPoll<RecordValue<'e>> {
let key = cache_key(&ctx);
if let Some((hash, copy, finality)) = cache.lock().unwrap().as_ref()
&& *hash == key
{
return match finality {
Finality::AllFinal => GPoll::Final(value.clone()),
Finality::Partial => GPoll::Partial(value.clone()),
return match copy.replay(content.layout(), ctx.arena()) {
Some(value) => match finality {
Finality::AllFinal => GPoll::Final(value),
Finality::Partial => GPoll::Partial(value),
},
None => GPoll::arena_exhausted(),
};
}
let result = content.eval(input);
match &result {
GPoll::Final(value) => *cache.lock().unwrap() = Some((key, value.clone(), Finality::AllFinal)),
GPoll::Partial(value) => *cache.lock().unwrap() = Some((key, value.clone(), Finality::Partial)),
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => {}
let result = content.eval(&ctx);
let publishable = match &result {
GPoll::Final(value) => Some((value, Finality::AllFinal)),
GPoll::Partial(value) => Some((value, Finality::Partial)),
GPoll::Pending | GPoll::Fallback(_) | GPoll::Error(_) => None,
};
if let Some((value, finality)) = publishable {
// SAFETY: the value came from this edge, so it carries the edge's layout.
let copy = unsafe { OwnedRecord::copy_out(content.layout(), content.layout().rec(value)) };
*cache.lock().unwrap() = Some((key, copy, finality));
}
result
}
fn memoize_extent<C, T, NodeContent>(node: &MemoizeNode<T, NodeContent>, ctx: &C) -> GPoll<Extent>
fn memoize_extent<C, NodeContent>(node: &MemoizeNode<NodeContent>, ctx: &C) -> GPoll<Extent>
where
T: Clone,
NodeContent: Node<C, Output = T>,
NodeContent: Node<C>,
{
node.content.extent(ctx)
}
#[node_macro::node(category(""), path(graphene_core::memo), skip_impl, extent(frame_memo_extent))]
fn frame_memo<'e, T: Clone + 'static + Send + Sync>(
#[node_macro::node(category(""), path(graphene_core::memo), extent(frame_memo_extent))]
fn frame_memo<'e>(
ctx: impl Ctx + CacheHash + ExtractArena<'e>,
#[data] cell: ArenaCell<FrameTable<T, 32>>,
content: impl Node<Context<'_>, Output = T>,
) -> GPoll<&'e T> {
#[data] cell: ArenaCell<FrameTable<Box<[u8]>, 32>>,
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
) -> GPoll<RecordValue<'e>> {
let arena = ctx.arena();
let table = match cell.load(arena) {
Some(table) => table,
@@ -54,84 +66,71 @@ fn frame_memo<'e, T: Clone + 'static + Send + Sync>(
cell.store(weak);
table
}
None => return park(arena, content.eval(ctx)),
None => return content.eval(&ctx),
},
};
// SAFETY: published bytes are same-frame copies of this edge's records,
// so they carry the edge's layout with live parked references.
let revive = |bytes: &'e Box<[u8]>| unsafe { record_from_bytes(content.layout(), bytes) };
match table.lookup(cache_key(ctx)) {
Lookup::Hit(Finality::AllFinal, value) => GPoll::Final(value),
Lookup::Hit(Finality::Partial, value) => GPoll::Partial(value),
Lookup::Vacant(slot) => match content.eval(ctx) {
GPoll::Final(value) => GPoll::Final(slot.publish(value, Finality::AllFinal)),
GPoll::Partial(value) => GPoll::Partial(slot.publish(value, Finality::Partial)),
Lookup::Hit(Finality::AllFinal, bytes) => GPoll::Final(revive(bytes)),
Lookup::Hit(Finality::Partial, bytes) => GPoll::Partial(revive(bytes)),
Lookup::Vacant(slot) => match content.eval(&ctx) {
GPoll::Final(value) => {
// SAFETY: the value came from this edge, so it carries the edge's layout.
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
GPoll::Final(revive(slot.publish(bytes, Finality::AllFinal)))
}
GPoll::Partial(value) => {
// SAFETY: as above.
let bytes = unsafe { copy_record_bytes(content.layout(), content.layout().rec(&value)) };
GPoll::Partial(revive(slot.publish(bytes, Finality::Partial)))
}
unpublishable => {
slot.release();
park(arena, unpublishable)
unpublishable
}
},
Lookup::Full => park(arena, content.eval(ctx)),
Lookup::Full => content.eval(&ctx),
}
}
fn frame_memo_extent<C, T, NodeContent>(node: &FrameMemoNode<T, NodeContent>, ctx: &C) -> GPoll<Extent>
fn frame_memo_extent<C, NodeContent>(node: &FrameMemoNode<NodeContent>, ctx: &C) -> GPoll<Extent>
where
T: Clone + 'static + Send + Sync,
NodeContent: Node<C, Output = T>,
NodeContent: Node<C>,
{
node.content.extent(ctx)
}
pub fn park<T: Send + Sync>(arena: &Arena, result: GPoll<T>) -> GPoll<&T> {
match result {
GPoll::Final(value) => match arena.alloc(value) {
Some((parked, _)) => GPoll::Final(parked),
None => GPoll::arena_exhausted(),
},
GPoll::Partial(value) => match arena.alloc(value) {
Some((parked, _)) => GPoll::Partial(parked),
None => GPoll::arena_exhausted(),
},
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
match arena.alloc(value) {
Some((parked, _)) => GPoll::Fallback(Box::new((parked, error))),
None => GPoll::arena_exhausted(),
}
}
GPoll::Pending => GPoll::Pending,
GPoll::Error(error) => GPoll::Error(error),
}
}
type MonitorValue<T> = Arc<Mutex<Option<Arc<IORecord<CtxSnapshot, T>>>>>;
type MonitorValue = Arc<Mutex<Option<IORecord<CtxSnapshot, RecordCapture>>>>;
/// The Monitor node is used by the editor to access the data flowing through it.
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"), skip_impl)]
fn monitor<T: Clone + 'static + Send + Sync>(
ctx: impl Ctx + DeriveCtx + ExtractAll,
#[allow(clippy::type_complexity)]
#[data]
io: MonitorValue<T>,
content: impl Node<Context<'_>, Output = T>,
) -> Result<T, Interrupt> {
let output = content.eval(&ctx.derived())?;
*io.lock().unwrap() = Some(Arc::new(IORecord {
input: CtxSnapshot::capture(ctx),
output: output.clone(),
}));
Ok(output)
#[node_macro::node(category(""), path(graphene_core::memo), serialize(serialize_monitor), properties("monitor_properties"))]
fn monitor<'e>(ctx: impl Ctx + DeriveCtx + ExtractAll + ExtractArena<'e>, #[data] io: MonitorValue, content: impl Node<Context<'_>, Output = RecordValue<'e>>) -> GPoll<RecordValue<'e>> {
let result = content.eval(&ctx);
if let GPoll::Final(value) | GPoll::Partial(value) = &result {
// SAFETY: the value came from this edge, so it carries the edge's layout.
let captured = unsafe { RecordCapture::capture(content.layout(), content.layout().rec(value), ctx.arena()) };
*io.lock().unwrap() = captured.map(|output| IORecord {
input: CtxSnapshot::capture(ctx),
output,
});
}
result
}
fn serialize_monitor<T: Clone + 'static + Send + Sync>(io: &MonitorValue<T>) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
let io = io.lock().unwrap();
io.as_ref().map(|output| output.clone() as Arc<dyn std::any::Any + Send + Sync>)
io.as_ref().map(|io| Arc::new(io.clone()) as Arc<dyn std::any::Any + Send + Sync>)
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::SourceId;
use core_types::arena::Arena;
use core_types::context::{ContextImpl, EvalScope};
use core_types::registry::{EdgeHandle, ErasedLendNode, ErasedNode};
use core_types::registry::{EdgeHandle, ErasedNode, ErasedRecordNode};
use std::sync::atomic::{AtomicU32, Ordering};
struct CountingNode(AtomicU32);
@@ -165,25 +164,39 @@ mod tests {
}
fn scope_fixture<'a>(generations: &'a [(SourceId, u64)], arena: &'a Arena) -> EvalScope<'a> {
core_types::record::stack::reserve(1 << 16);
EvalScope::new(Some(0.5), None, None, generations, arena)
}
fn element_layout<T: Clone + Send + Sync + 'static>() -> core_types::record::Layout {
core_types::record::Layout::default().with_writes(0, core_types::record::element_write::<T>(), &[])
}
#[test]
fn monitor_serialize_exposes_the_io_record_through_the_edge() {
fn monitor_serialize_exposes_the_capture_through_the_edge() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = EdgeHandle::new(Arc::new(MonitorNode::new(ValueNode(11u32))) as Arc<ErasedNode<u32>>);
assert!(handle.serialize().is_none(), "no record before the first eval");
let layout = element_layout::<u32>();
let monitor = MonitorNode::new(core_types::record::RecordLift::<u32, _>::new(ValueNode(11u32)), &layout);
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
assert!(handle.serialize().is_none(), "no capture before the first eval");
let edge = handle.duplicate().downcast::<u32>().unwrap();
assert_eq!(edge.eval(&ctx), GPoll::Final(11));
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
let GPoll::Final(_) = edge.eval(&ctx) else {
panic!("expected a final record");
};
let record = handle.serialize().expect("the eval landed a record");
let record = record.downcast_ref::<IORecord<CtxSnapshot, u32>>().expect("the record is the monitor io");
assert_eq!(record.output, 11);
let io = handle.serialize().expect("the eval landed a capture");
let io = io.downcast_ref::<IORecord<CtxSnapshot, RecordCapture>>().expect("the capture is the monitor io");
assert!(
core_types::context::ExtractFootprint::try_footprint(&io.input).is_none(),
"the root context has no footprint to capture"
);
let element = io.output.materialize_element(&arena).expect("the capture materializes inside the window");
assert_eq!(*element.downcast_ref::<u32>().unwrap(), 11);
}
#[test]
@@ -193,7 +206,9 @@ mod tests {
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let memoized = MemoizeNode::new(CountingNode(AtomicU32::new(0)));
let layout = element_layout::<u32>();
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
@@ -208,7 +223,9 @@ mod tests {
let scope_before = scope_fixture(&before, &arena);
let scope_after = scope_fixture(&after, &arena);
let memoized = MemoizeNode::new(CountingNode(AtomicU32::new(0)));
let layout = element_layout::<u32>();
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0))), &layout);
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
@@ -222,7 +239,9 @@ mod tests {
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let memoized = MemoizeNode::new(PartialCountingNode(AtomicU32::new(0)));
let layout = element_layout::<u32>();
let memoized = MemoizeNode::new(core_types::record::RecordLift::<u32, _>::new(PartialCountingNode(AtomicU32::new(0))), &layout);
let memoized = core_types::record::RecordExtract::<u32, _>::new(memoized, &layout);
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
@@ -235,33 +254,35 @@ mod tests {
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Arc::new(CountingNode(AtomicU32::new(0))) as Arc<ErasedNode<u32>>);
let memoized = EdgeHandle::new(Arc::new(MemoizeNode::new(edge.downcast::<u32>().unwrap())) as Arc<ErasedNode<u32>>);
let stacked = MemoizeNode::new(memoized.downcast::<u32>().unwrap());
let layout = element_layout::<u32>();
let edge = EdgeHandle::new_record::<u32>(Arc::new(core_types::record::RecordLift::<u32, _>::new(CountingNode(AtomicU32::new(0)))) as Arc<ErasedRecordNode>);
let memoized = EdgeHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
}
#[test]
fn frame_memo_turns_an_owned_edge_into_a_lending_edge() {
fn frame_memo_shares_one_record_copy_per_frame() {
let arena = Arena::new(4096).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let edge = EdgeHandle::new(Arc::new(ValueNode("lent out".to_string())) as Arc<ErasedNode<String>>);
let lending = EdgeHandle::new_ref(Arc::new(FrameMemoNode::new(edge.downcast::<String>().unwrap())) as Arc<ErasedLendNode<String>>);
assert_eq!(*lending.ty(), core_types::registry::lend_edge_type::<String>());
let layout = element_layout::<String>();
let memo = FrameMemoNode::new(core_types::record::RecordLift::<String, _>::new(ValueNode("lent out".to_string())), &layout);
let node = lending.downcast_lend::<String>().unwrap();
let GPoll::Final(first) = node.eval(&ctx) else {
panic!("lend must fill the frame table and lend");
let GPoll::Final(first) = memo.eval(&ctx) else {
panic!("the miss must fill the frame table");
};
let GPoll::Final(second) = node.eval(&ctx) else {
panic!("second eval must lend the published value");
let GPoll::Final(second) = memo.eval(&ctx) else {
panic!("the hit must revive the published record");
};
let first: &String = unsafe { core_types::record::borrow_element(layout.rec(&first)) };
let second: &String = unsafe { core_types::record::borrow_element(layout.rec(&second)) };
assert_eq!(first, "lent out");
assert!(std::ptr::eq(first, second));
assert!(std::ptr::eq(first, second), "the hit shares the parked payload");
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ use std::marker::PhantomData;
/// Passes-through the input value without changing it. This is useful for rerouting wires for organization purposes.
#[node_macro::node(category("General"), skip_impl)]
fn passthrough<'i, T: 'i + Send>(_: impl Ctx, content: T) -> T {
fn passthrough<T: Send>(_: impl Ctx, content: T) -> T {
content
}
File diff suppressed because it is too large. Load diff
@@ -12,7 +12,7 @@ use wgpu::util::DeviceExt;
use wgpu_executor::{WgpuExecutor, WgpuPipeline, WgpuPipelineCache};
#[node_macro::node(category(""))]
fn render_background<'a>(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, data: RenderOutput) -> RenderOutput {
fn render_background(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, data: RenderOutput) -> RenderOutput {
let footprint = ctx.footprint();
let render_params = ctx
.vararg(0)
+110 -31
View File
@@ -1060,9 +1060,10 @@ mod graphene_test {
use core_types::context::{ContextImpl, EvalScope, ExtractIndex};
use core_types::gpoll::{Finality, GPoll};
use core_types::node::{BatchStatus, Node};
use core_types::registry::{EdgeHandle, ErasedNode, construct};
use core_types::record::{Layout, RecordLift, RecordValue, stack};
use core_types::registry::{ErasedRecordNode, construct};
use core_types::value::record_value_edge;
use std::mem::MaybeUninit;
use std::sync::Arc;
struct SourceNode<T>(T);
@@ -1088,14 +1089,42 @@ mod graphene_test {
EvalScope::new(None, None, None, &[], arena)
}
fn reserve_for(layouts: &[&Layout]) {
stack::reserve(layouts.iter().map(|layout| layout.frame_bytes()).sum::<usize>().max(1 << 12));
}
/// Lifts a plain-element test source onto a record wire, returned beside its
/// element-only layout for the generated node's constructor.
fn lifted<T, N>(node: N) -> (RecordLift<T, N>, Layout)
where
T: Clone + Send + Sync + 'static,
N: for<'c> Node<ContextImpl<'c>, Output = T>,
{
let lift = RecordLift::<T, _>::new(node);
let layout = Node::<ContextImpl>::layout(&lift).clone();
(lift, layout)
}
fn element<T: Copy>(layout: &Layout, value: &RecordValue<'_>) -> T {
unsafe { layout.rec(value).element::<T>() }
}
#[test]
fn generated_add_evaluates_through_the_node_path() {
let arena = Arena::new(64).unwrap();
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let graph = AddNode::new(SourceNode(1.0f64), SourceNode(2.0f64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(3.0));
let (a, la) = lifted(SourceNode(1.0f64));
let (b, lb) = lifted(SourceNode(2.0f64));
let graph = AddNode::<_, _, f64, f64>::new(a, b, &la, &lb);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&la, &lb, &out]);
let GPoll::Final(value) = Node::eval(&graph, &ctx) else {
panic!("expected a final record");
};
assert_eq!(element::<f64>(&out, &value), 3.0);
}
#[test]
@@ -1104,13 +1133,21 @@ mod graphene_test {
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let erased: Box<ErasedNode<f64>> = Box::new(AddNode::new(IndexNode, SourceNode(10.0f64)));
let (index, li) = lifted(IndexNode);
let (src, ls) = lifted(SourceNode(10.0f64));
let node = AddNode::<_, _, f64, f64>::new(index, src, &li, &ls);
let out = Node::<ContextImpl>::layout(&node).clone();
reserve_for(&[&li, &ls, &out]);
let erased: Box<ErasedRecordNode> = Box::new(node);
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = erased.eval_batch(&ctx, 2..6, Some(&mut scratch));
let BatchStatus::Filled(lanes, finality) = status else {
let BatchStatus::Filled(batch, finality) = status else {
panic!("expected filled, got {status:?}");
};
assert_eq!(lanes.values(), &[12.0, 13.0, 14.0, 15.0]);
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(unsafe { lane.element::<f64>() }));
assert_eq!(got, vec![12.0, 13.0, 14.0, 15.0]);
assert_eq!(finality, Finality::AllFinal);
}
@@ -1120,12 +1157,16 @@ mod graphene_test {
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = logical_or_entries();
let value = EdgeHandle::new(Arc::new(SourceNode(true)) as Arc<ErasedNode<bool>>);
let other_value = EdgeHandle::new(Arc::new(SourceNode(false)) as Arc<ErasedNode<bool>>);
let wired = construct(&entries[0], vec![value, other_value]).unwrap().downcast::<bool>().unwrap();
let entries = super::_logical_or_mod::logical_or_entries();
let wired = construct(&entries[0], vec![record_value_edge(true), record_value_edge(false)]).unwrap();
let layout = wired.layout().unwrap().clone();
let edge = wired.downcast_record::<bool>().unwrap();
reserve_for(&[&layout]);
assert_eq!(Node::eval(&wired, &ctx), GPoll::Final(true));
let GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert!(element::<bool>(&layout, &value));
}
#[test]
@@ -1144,18 +1185,22 @@ mod graphene_test {
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = add_entries();
let entries = super::_add_mod::add_entries();
assert_eq!(entries.len(), 6);
assert_eq!(entries[0].io.inputs, vec![core_types::concrete!(f64), core_types::concrete!(f64)]);
assert_eq!(entries[0].io.return_value, core_types::concrete!(f64));
assert_eq!(entries[3].io.inputs, vec![core_types::concrete!(DVec2), core_types::concrete!(DVec2)]);
assert_eq!(entries[3].io.return_value, core_types::concrete!(DVec2));
assert_eq!(entries[0].io.inputs, vec![core_types::registry::record_edge_type::<f64>(), core_types::registry::record_edge_type::<f64>()]);
assert_eq!(entries[0].io.return_value, core_types::registry::record_type::<f64>());
assert_eq!(entries[3].io.inputs, vec![core_types::registry::record_edge_type::<DVec2>(), core_types::registry::record_edge_type::<DVec2>()]);
assert_eq!(entries[3].io.return_value, core_types::registry::record_type::<DVec2>());
let augend = EdgeHandle::new(Arc::new(SourceNode(1.5f64)) as Arc<ErasedNode<f64>>);
let addend = EdgeHandle::new(Arc::new(SourceNode(2.5f64)) as Arc<ErasedNode<f64>>);
let wired = construct(&entries[0], vec![augend, addend]).unwrap().downcast::<f64>().unwrap();
let wired = construct(&entries[0], vec![record_value_edge(1.5f64), record_value_edge(2.5f64)]).unwrap();
let layout = wired.layout().unwrap().clone();
let edge = wired.downcast_record::<f64>().unwrap();
reserve_for(&[&layout]);
assert_eq!(Node::eval(&wired, &ctx), GPoll::Final(4.0));
let GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert_eq!(element::<f64>(&layout, &value), 4.0);
}
#[test]
@@ -1180,9 +1225,17 @@ mod graphene_test {
let taken = Arc::new(AtomicU32::new(0));
let untaken = Arc::new(AtomicU32::new(0));
let graph = SwitchNode::new(SourceNode(true), CountingSource(taken.clone(), 1.0), CountingSource(untaken.clone(), 2.0));
let (cond, lc) = lifted(SourceNode(true));
let (if_true, lt) = lifted(CountingSource(taken.clone(), 1.0));
let (if_false, lf) = lifted(CountingSource(untaken.clone(), 2.0));
let graph = SwitchNode::<_, _, _, f64>::new(cond, if_true, if_false, &lc, &lt, &lf);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&lc, &lt, &lf, &out]);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(1.0));
let GPoll::Final(value) = Node::eval(&graph, &ctx) else {
panic!("expected a final record");
};
assert_eq!(element::<f64>(&out, &value), 1.0);
assert_eq!(taken.load(Ordering::Relaxed), 1);
assert_eq!(untaken.load(Ordering::Relaxed), 0);
}
@@ -1213,11 +1266,23 @@ mod graphene_test {
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let pending = SwitchNode::new(SourceNode(true), PendingSource, PartialSource);
assert_eq!(Node::eval(&pending, &ctx), GPoll::Pending);
let (c1, lc1) = lifted(SourceNode(true));
let (p1, lp1) = lifted(PendingSource);
let (pa1, lpa1) = lifted(PartialSource);
let pending = SwitchNode::<_, _, _, f64>::new(c1, p1, pa1, &lc1, &lp1, &lpa1);
let partial = SwitchNode::new(SourceNode(false), PendingSource, PartialSource);
assert_eq!(Node::eval(&partial, &ctx), GPoll::Partial(7.0));
let (c2, lc2) = lifted(SourceNode(false));
let (p2, lp2) = lifted(PendingSource);
let (pa2, lpa2) = lifted(PartialSource);
let partial = SwitchNode::<_, _, _, f64>::new(c2, p2, pa2, &lc2, &lp2, &lpa2);
let out = Node::<ContextImpl>::layout(&partial).clone();
reserve_for(&[&lc1, &lp1, &lpa1, &lc2, &lp2, &lpa2, &out]);
assert!(matches!(Node::eval(&pending, &ctx), GPoll::Pending));
let GPoll::Partial(value) = Node::eval(&partial, &ctx) else {
panic!("expected a partial record");
};
assert_eq!(element::<f64>(&out, &value), 7.0);
}
#[test]
@@ -1236,8 +1301,17 @@ mod graphene_test {
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let graph = SwitchNode::new(PartialCondition, SourceNode(1.0f64), SourceNode(2.0f64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(1.0));
let (cond, lc) = lifted(PartialCondition);
let (if_true, lt) = lifted(SourceNode(1.0f64));
let (if_false, lf) = lifted(SourceNode(2.0f64));
let graph = SwitchNode::<_, _, _, f64>::new(cond, if_true, if_false, &lc, &lt, &lf);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&lc, &lt, &lf, &out]);
let GPoll::Partial(value) = Node::eval(&graph, &ctx) else {
panic!("expected a partial record");
};
assert_eq!(element::<f64>(&out, &value), 1.0);
}
#[test]
@@ -1256,11 +1330,16 @@ mod graphene_test {
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let graph = AddNode::new(FallbackNode, SourceNode(5.0f64));
let (fallback, lfb) = lifted(FallbackNode);
let (src, ls) = lifted(SourceNode(5.0f64));
let graph = AddNode::<_, _, f64, f64>::new(fallback, src, &lfb, &ls);
let out = Node::<ContextImpl>::layout(&graph).clone();
reserve_for(&[&lfb, &ls, &out]);
let GPoll::Fallback(boxed) = Node::eval(&graph, &ctx) else {
panic!("fallback must propagate with the computed stand-in");
};
assert_eq!(boxed.0, 5.0);
assert_eq!(element::<f64>(&out, &boxed.0), 5.0);
assert!(boxed.1.kind == "upstream failed");
assert_eq!(boxed.1.trace, vec![0]);
}
@@ -6,7 +6,7 @@ use raster_types::{CPU, Raster};
#[node_macro::node(category("Color"))]
fn image_color_palette(
_: impl Ctx,
image: List<Raster<CPU>>,
image: &List<Raster<CPU>>,
#[default(4)]
#[hard(1..)]
count: u32,
@@ -69,7 +69,7 @@ mod test {
fn test_image_color_palette() {
let result = image_color_palette(
&(),
List::new_from_element(Raster::new_cpu(Image {
&List::new_from_element(Raster::new_cpu(Image {
width: 100,
height: 100,
data: vec![Color::from_rgbaf32(0., 0., 0., 1.).unwrap(); 10000],
+34 -11
View File
@@ -35,11 +35,14 @@ fn repeat<T: Into<Graphic> + Default + Send + Clone + 'static>(
for index in 0..count {
let index = if reverse { count - index - 1 } else { index };
let mark = core_types::record::stack::sp();
let generated_content = content.eval(&ctx.promoted(&spilled, index))?;
for generated_row in generated_content.into_iter() {
result_list.push(generated_row);
}
// SAFETY: generated_content is an owned list fully moved into result_list, so no record borrow into this iteration's frames remains.
unsafe { core_types::record::stack::rewind(mark) };
}
Ok(result_list)
@@ -76,6 +79,7 @@ pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
let translation = index as f64 * direction / total;
let transform = DAffine2::from_angle(angle) * DAffine2::from_translation(translation);
let mark = core_types::record::stack::sp();
let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
for row_index in 0..generated_content.len() {
@@ -88,6 +92,8 @@ pub fn repeat_array<T: Into<Graphic> + Default + Send + Clone + 'static>(
result_list.push(row);
}
// SAFETY: rows are cloned into result_list and generated_content is owned, so no record borrow into this iteration's frames remains.
unsafe { core_types::record::stack::rewind(mark) };
}
Ok(result_list)
@@ -120,6 +126,7 @@ fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
let translation = DAffine2::from_translation(radius * DVec2::Y);
let transform = angle * translation;
let mark = core_types::record::stack::sp();
let generated_content = content.eval(&ctx.promoted(&spilled, index as u64))?;
for row_index in 0..generated_content.len() {
@@ -132,6 +139,8 @@ fn repeat_radial<T: Into<Graphic> + Default + Send + Clone + 'static>(
result_list.push(row);
}
// SAFETY: rows are cloned into result_list and generated_content is owned, so no record borrow into this iteration's frames remains.
unsafe { core_types::record::stack::rewind(mark) };
}
Ok(result_list)
@@ -168,12 +177,15 @@ fn repeat_on_points<T: Into<Graphic> + Default + Send + Clone + 'static>(
let transformed_point = transform.transform_point2(point);
let scoped = ctx.push_position(transformed_point);
let mark = core_types::record::stack::sp();
let generated_content = content.eval(&scoped.ctx().promoted(&spilled, index as u64))?;
for mut generated_row in generated_content.into_iter() {
generated_row.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM).translation = transformed_point;
result_list.push(generated_row);
}
// SAFETY: generated_content is an owned list fully moved into result_list, so no record borrow into this iteration's frames remains.
unsafe { core_types::record::stack::rewind(mark) };
}
}
@@ -187,7 +199,8 @@ mod test {
use core_types::context::{ContextImpl, EvalScope, ExtractIndex, ExtractPosition};
use core_types::gpoll::GPoll;
use core_types::list::Item;
use core_types::node::{LazyInput, Node, StatusCell};
use core_types::node::{Node, StatusCell};
use core_types::record::{ElementLazyInput, RecordLift};
use vector_types::subpath::Subpath;
const TEST_POSITION: &str = "test-position";
@@ -240,6 +253,7 @@ mod test {
macro_rules! test_ctx {
($ctx:ident, $cell:ident) => {
core_types::record::stack::reserve(1 << 16);
let arena = Arena::new(4096).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
@@ -254,10 +268,13 @@ mod test {
let x_translations = |values: [f64; 3]| values.map(|x| DVec2::new(x, 0.)).to_vec();
let forward = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, false).unwrap();
let lift = RecordLift::<List<Vector>, _>::new(IndexProbe);
let layout = Node::<ContextImpl>::layout(&lift).clone();
let forward = super::repeat(&ctx, ElementLazyInput::new(&lift, &cell, 0, &layout), 3, false).unwrap();
assert_eq!(row_translations(&forward, ATTR_TRANSFORM), x_translations([0., 1., 2.]));
let reversed = super::repeat(&ctx, LazyInput::new(&IndexProbe, &cell, 0), 3, true).unwrap();
let reversed = super::repeat(&ctx, ElementLazyInput::new(&lift, &cell, 0, &layout), 3, true).unwrap();
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), x_translations([2., 1., 0.]));
}
@@ -267,8 +284,9 @@ mod test {
let direction = DVec2::new(1.5, 0.);
let count = 3;
let content = ValueNode(single_default_vector());
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), direction, 0., count).unwrap();
let lift = RecordLift::<List<Vector>, _>::new(ValueNode(single_default_vector()));
let layout = Node::<ContextImpl>::layout(&lift).clone();
let repeated = super::repeat_array(&ctx, ElementLazyInput::new(&lift, &cell, 0, &layout), direction, 0., count).unwrap();
assert_eq!(repeated.len(), count as usize);
for (index, translation) in row_translations(&repeated, ATTR_TRANSFORM).into_iter().enumerate() {
@@ -281,8 +299,9 @@ mod test {
fn repeat_array_single_copy_stays_finite() {
test_ctx!(ctx, cell);
let content = ValueNode(single_default_vector());
let repeated = super::repeat_array(&ctx, LazyInput::new(&content, &cell, 0), DVec2::new(12., 10.), 45., 1).unwrap();
let lift = RecordLift::<List<Vector>, _>::new(ValueNode(single_default_vector()));
let layout = Node::<ContextImpl>::layout(&lift).clone();
let repeated = super::repeat_array(&ctx, ElementLazyInput::<List<Vector>, _>::new(&lift, &cell, 0, &layout), DVec2::new(12., 10.), 45., 1).unwrap();
assert_eq!(repeated.len(), 1);
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, 0);
@@ -294,8 +313,9 @@ mod test {
test_ctx!(ctx, cell);
let (radius, count) = (5., 4);
let content = ValueNode(single_default_vector());
let repeated = super::repeat_radial(&ctx, LazyInput::new(&content, &cell, 0), 0., radius, count).unwrap();
let lift = RecordLift::<List<Vector>, _>::new(ValueNode(single_default_vector()));
let layout = Node::<ContextImpl>::layout(&lift).clone();
let repeated = super::repeat_radial(&ctx, ElementLazyInput::<List<Vector>, _>::new(&lift, &cell, 0, &layout), 0., radius, count).unwrap();
assert_eq!(repeated.len(), count as usize);
for index in 0..count as usize {
@@ -311,11 +331,14 @@ mod test {
let positions = [DVec2::new(40., 20.), DVec2::ONE, DVec2::new(-42., 9.), DVec2::new(10., 345.)];
let points = List::new_from_element(Vector::from_subpath(Subpath::from_anchors(positions, false)));
let generated = super::repeat_on_points(&ctx, points.clone(), LazyInput::new(&PositionProbe, &cell, 0), false).unwrap();
let lift = RecordLift::<List<Vector>, _>::new(PositionProbe);
let layout = Node::<ContextImpl>::layout(&lift).clone();
let generated = super::repeat_on_points(&ctx, points.clone(), ElementLazyInput::new(&lift, &cell, 0, &layout), false).unwrap();
assert_eq!(row_translations(&generated, ATTR_TRANSFORM), positions.to_vec());
assert_eq!(row_translations(&generated, TEST_POSITION), positions.to_vec());
let reversed = super::repeat_on_points(&ctx, points, LazyInput::new(&PositionProbe, &cell, 0), true).unwrap();
let reversed = super::repeat_on_points(&ctx, points, ElementLazyInput::new(&lift, &cell, 0, &layout), true).unwrap();
let mut expected = positions.to_vec();
expected.reverse();
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), expected);