Compare commits

..
Author SHA1 Message Date
Dennis Kobert 187fec20d7 Seed the u64 fx hasher and guard against zero-word absorption 2026-07-31 12:43:43 +00:00
Dennis Kobert deea1089bb Delete the dead OwnedContextImpl 2026-07-31 12:03:01 +00:00
Dennis Kobert 46ea7a7043 Fix the clippy lints introduced by the refactor 2026-07-31 10:55:29 +00:00
Dennis Kobert 1dc9c14ed0 Delete the dead introspect_node helper 2026-07-31 10:28:57 +00:00
Dennis Kobert a1c014db2c Pin cache key and source id hashing to u64 fx state 2026-07-31 10:28:57 +00:00
Dennis Kobert d9c8532e71 Test retain filter placement, source set divergence, and excluding keying 2026-07-31 10:28:57 +00:00
Dennis Kobert c925f4ec39 Migrate short-arity async source document nodes to the hidden inputs 2026-07-31 10:28:57 +00:00
Dennis Kobert 4556e320df Cleanup 2026-07-30 20:48:30 +00:00
Dennis Kobert 07b95ba59b Remove vestigial async from the execution path 2026-07-30 20:16:04 +00:00
Dennis Kobert 9e248cf90c Wire up async runtimes 2026-07-30 19:12:29 +00:00
Dennis Kobert 93aa99433f Add wasm send / sync 2026-07-30 17:41:31 +00:00
Dennis Kobert 41fc175088 Share one graph runtime between the editor api scope and the executor 2026-07-30 17:26:39 +00:00
Dennis Kobert f13806efcd Fmt 2026-07-30 19:11:22 +02:00
Dennis Kobert e2a8420fee Fix ExtractFootprint annotations causing cache invalidation 2026-07-30 19:09:49 +02:00
Dennis Kobert f4247986f0 Wire source ids through flattening, the nullification pass, and slot keying 2026-07-30 15:46:10 +00:00
Dennis Kobert c7fef30cf1 Delete the old erased node machinery 2026-07-30 11:51:13 +00:00
Dennis Kobert b079ec9c2c Migrate legacy document call arguments to the context call convention 2026-07-30 11:26:12 +00:00
Dennis Kobert 9cdf9cec6b Share scope values as owned Arc handles 2026-07-30 11:26:12 +00:00
Dennis Kobert 9bdf4541d0 Replace borrowed scope injections with arcs 2026-07-30 10:58:51 +00:00
Dennis Kobert 382ad9d15c Add missing send / sync impls and make rasterize node async 2026-07-30 10:28:50 +00:00
Dennis Kobert b70b28bbe3 Restore serialize-based introspection through the typed edges 2026-07-30 10:15:51 +00:00
Dennis Kobert bb736002cf Add the async convert trait and restore the GPU texture download 2026-07-30 09:54:20 +00:00
Dennis Kobert 149a39faac Convert values to typed edges and flip the interpreted executor 2026-07-30 09:54:19 +00:00
Dennis Kobert b74c64ebcd Retarget typing and row consumers onto the registry entries 2026-07-30 09:54:19 +00:00
Dennis Kobert bb67b47301 Carry full function types in the registry rows 2026-07-30 09:54:19 +00:00
Dennis Kobert 683ca34fac Add the graph runtime with the completion epilogue 2026-07-30 09:54:19 +00:00
Dennis Kobert db796be8e8 Make every edge a shared payload pointer with an owning Arc 2026-07-27 18:23:42 +00:00
Dennis Kobert 88d9c637e7 Merge the wiring surface into the registry and express the memo nodes as macro kernels 2026-07-27 16:06:42 +00:00
Dennis Kobert c3fdc97f81 Convert create_context to a sync derivation kernel over the bare-root contract 2026-07-27 11:40:16 +00:00
Dennis Kobert 3d17fa0f0c Make the arena unwind safe and the slot locks poison tolerant 2026-07-27 11:40:16 +00:00
Dennis Kobert 9e83632647 Make the GPU render and dispatch pipelines synchronous 2026-07-27 10:47:44 +00:00
Dennis Kobert 6392c02dee Add the sync-prologue async source form 2026-07-27 10:47:44 +00:00
Dennis Kobert 470ffdab43 Add vararg slot cloning and snapshot vararg capture 2026-07-27 10:47:44 +00:00
Dennis Kobert 28d9e3cbe3 Convert the remaining nodes and mark genuine async sources 2026-07-26 22:58:40 +00:00
Dennis Kobert 28d37d30d0 Store the wgpu executor as an Arc and restore the upload texture node 2026-07-26 22:58:40 +00:00
Dennis Kobert cf66f8396b Emit the async source tier from the node macro 2026-07-26 22:58:40 +00:00
Dennis Kobert be5c78421a Add the async source runtime vocabulary and context snapshot 2026-07-26 22:58:40 +00:00
Dennis Kobert f0f7d6a5d7 Start adapting nodes to new version 2026-07-26 20:59:12 +00:00
Dennis Kobert 44277c9636 Update node macro to new syntax 2026-07-26 20:58:11 +00:00
Dennis Kobert 99f94503c3 Reshape ContextImpl into the borrowed graphene context 2026-07-25 19:33:41 +00:00
Dennis Kobert 925075337b Add the generation-scoped arena and the FrameTable frame memo store 2026-07-25 17:05:40 +00:00
Dennis Kobert df70222d61 Add the GNode trait with the spec-loop batch default; give InjectIndex its method 2026-07-25 17:05:01 +00:00
Dennis Kobert 1f9e0cc37b Add the GPoll evaluation vocabulary and an inert Type::Ref variant 2026-07-25 17:03:32 +00:00
64 changed files with 1539 additions and 8685 deletions

No files matched your search

Generated
+4
View File
@@ -4880,11 +4880,15 @@ dependencies = [
"core-types",
"dyn-any",
"glam",
"graphene-core",
"graphic-types",
"kurbo",
"log",
"node-macro",
"raster-types",
"serde",
"tokio",
"vector-nodes",
"vector-types",
]
@@ -14,7 +14,7 @@ use crate::{NetworkId, NodeMetadataSource, PeerId, Position, Registry};
/// Test networks with Import inputs will fail compilation (which is expected).
fn verify_network_compiles(network: &NodeNetwork) -> Result<(), String> {
let compiler = Compiler {};
compiler.compile_single(network.clone(), None).map_err(|e| format!("Compilation failed: {:?}", e))?;
compiler.compile_single(network.clone()).map_err(|e| format!("Compilation failed: {:?}", e))?;
Ok(())
}
@@ -246,10 +246,10 @@ fn test_nested_network_flattening() {
#[test]
fn test_metadata_preservation() {
// Create a network with nodes that have non-default metadata
let context_features = ContextDependencies::new(
core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
core_types::context::ContextFeatures::empty(),
);
let context_features = ContextDependencies {
extract: core_types::context::ContextFeatures::FOOTPRINT | core_types::context::ContextFeatures::REAL_TIME,
..Default::default()
};
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
@@ -10,10 +10,11 @@ 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, Graphic};
use graphene_std::{Artboard, Color, CtxSnapshot, Graphic};
use std::any::Any;
use std::sync::Arc;
@@ -166,8 +167,8 @@ macro_rules! generate_layout_downcast {
($introspected_data:expr, $data:expr, [ $($ty:ty),* $(,)? ]) => {
if false { None }
$(
else if let Some(element) = $introspected_data.downcast_ref::<$ty>() {
Some(element.layout_with_breadcrumb($data))
else if let Some(io) = $introspected_data.downcast_ref::<IORecord<CtxSnapshot, $ty>>() {
Some(io.output.layout_with_breadcrumb($data))
}
)*
else { None }
@@ -177,8 +178,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(list) = introspected_data.downcast_ref::<List<NodeId>>() {
return Some(table_node_id_path_layout_with_breadcrumb(list, data));
if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<NodeId>>>() {
return Some(table_node_id_path_layout_with_breadcrumb(&io.output, 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::Record(inner) => return property_from_type(node_id, index, inner, 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),
};
extra_widgets.push(widgets);
@@ -95,6 +95,34 @@ impl NodeNetworkInterface {
}
}
}
/// Append the hidden runtime and source-id inputs to async-source protonodes saved before their injection.
/// Runs after the identifier replacement pass, so it matches only current identifier spellings.
pub fn migrate_async_source_inputs(&mut self) {
const PRE_INJECTION_ARITIES: [(&str, usize); 5] = [
("graphene_std::platform_application_io::GetRequestNode", 4),
("graphene_std::platform_application_io::PostRequestNode", 5),
("graphene_std::platform_application_io::LoadResourceNode", 2),
("graphene_std::platform_application_io::RasterizeNode", 3),
("graphene_std::platform_application_io::ResourceNode", 2),
];
fix_network(self.document_network_mut());
fn fix_network(network: &mut NodeNetwork) {
for node in network.nodes.values_mut() {
if let Some(network) = node.implementation.get_network_mut() {
fix_network(network);
}
if let DocumentNodeImplementation::ProtoNode(protonode) = &node.implementation
&& let Some(base) = protonode.as_str().split('<').next()
&& let Some((_, arity)) = PRE_INJECTION_ARITIES.iter().find(|(identifier, _)| *identifier == base)
&& node.inputs.len() == *arity
{
node.inputs.push(NodeInput::scope("graphene_std::runtime::RuntimeNode"));
node.inputs.push(NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId));
}
}
}
}
}
// Public immutable getters for the network interface
@@ -1148,6 +1148,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
document.network_interface.migrate_async_source_inputs();
// The "Brush" wrapper network was replaced with the `brush` proto node directly. Convert old `Network("Brush")` instances to the proto node, forwarding all 3 inputs (Background, Trace, Cache) one-to-one.
// This must run as a pre-pass before the recursive iteration below: replacing the outer Brush's network impl orphans its child paths, and the recursive iteration would log errors for those stale paths.
let brush_layers: Vec<(NodeId, Vec<NodeId>)> = document
+24 -6
View File
@@ -10,11 +10,12 @@ 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, Graphic, NodeInputDecleration};
use graphene_std::{ATTR_TRANSFORM, CtxSnapshot, Graphic, NodeInputDecleration};
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
use std::any::Any;
use std::sync::Arc;
@@ -899,9 +900,18 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
}
// TODO: Eventually remove this document upgrade code
/// Extract a monitor node's captured output element.
/// Extract a monitor node's recorded output, trying each context type the runtime may have evaluated it under.
fn introspected_output<T: Clone + Send + Sync + 'static>(data: &Arc<dyn Any + Send + Sync>) -> Option<T> {
data.downcast_ref::<T>().cloned()
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
}
// Re-export for usage by tests in other modules
@@ -917,7 +927,9 @@ 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
@@ -978,11 +990,17 @@ mod test {
where
Input::Result: Send + Sync + Clone + 'static,
{
let element = dynamic.downcast_ref::<Input::Result>().cloned();
if element.is_none() {
// 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 {
warn!("cannot downcast type for introspection");
None
}
element
}
/// Grab all of the values of the input every time it occurs in the graph.
+18 -32
View File
@@ -11,16 +11,17 @@ 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};
use graphene_std::raster_types::Raster;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender, SvgSegment};
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use graphene_std::runtime::{DynGraphRuntime, DynNotifier, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner};
use graphene_std::transform::RenderQuality;
use graphene_std::vector::Vector;
use graphene_std::vector::style::RenderMode;
use graphene_std::{Artboard, Graphic};
use graphene_std::{Artboard, CtxSnapshot, Graphic};
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use spin::Mutex;
@@ -141,14 +142,8 @@ impl Default for TokioSpawner {
#[cfg(not(target_family = "wasm"))]
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
fn spawn(&self, task: SourceFuture) {
self.0.as_ref().expect("runtime lives until drop").spawn(task);
}
}
@@ -168,12 +163,8 @@ pub struct WasmSpawner;
#[cfg(target_family = "wasm")]
impl Spawner for WasmSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
fn spawn(&self, task: SourceFuture) {
wasm_bindgen_futures::spawn_local(task);
false
}
}
@@ -226,11 +217,6 @@ impl NodeRuntime {
}
}
#[cfg(test)]
pub fn take_dirty(&self) -> bool {
self.executor.take_dirty()
}
pub async fn run(&mut self) -> Option<Texture> {
let mut preferences = None;
let mut graph = None;
@@ -438,7 +424,7 @@ impl NodeRuntime {
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let c = Compiler {};
let proto_network = match c.compile_single(scoped_network, None) {
let proto_network = match c.compile_single(scoped_network) {
Ok(network) => network,
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
};
@@ -501,30 +487,30 @@ impl NodeRuntime {
};
// Graphic list: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if let Some(list) = introspected_data.downcast_ref::<List<Graphic>>() {
if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<Graphic>>>() {
if update_thumbnails {
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)
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)
}
}
// 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(list) = introspected_data.downcast_ref::<List<Artboard>>() {
else if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<Artboard>>>() {
if update_thumbnails {
let bounds = artboard_clip_bounds(list);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, list, bounds, responses)
let bounds = artboard_clip_bounds(&io.output);
Self::render_thumbnail(&mut self.thumbnail_renders, parent_network_node_id, &io.output, bounds, responses)
}
}
// Vector list: vector modifications
else if let Some(list) = introspected_data.downcast_ref::<List<Vector>>() {
else if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<Vector>>>() {
// Insert the vector modify
self.vector_modify.insert(parent_network_node_id, list.element(0).cloned().unwrap_or_default());
self.vector_modify.insert(parent_network_node_id, io.output.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(list) = introspected_data.downcast_ref::<List<String>>() {
else if let Some(io) = introspected_data.downcast_ref::<IORecord<CtxSnapshot, List<String>>>() {
if update_thumbnails {
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)
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)
}
}
// Other
-21
View File
@@ -53,27 +53,6 @@ impl EditorTestUtils {
}
runtime.run().await;
// An async source reports `Pending` on the evaluation that starts it and marks the runtime dirty once
// it completes, so the value only reaches the render on a follow-up evaluation. The superseded response's
// `Pending` error is ignored, but its messages carry the incremental resolved-types delta and must be
// dispatched, or the editor's type map desyncs permanently.
while runtime.take_dirty() {
let mut superseded_messages = VecDeque::new();
let _ = editor.poll_node_graph_evaluation(&mut superseded_messages);
for message in superseded_messages {
editor.handle_message(message);
}
let portfolio = &mut editor.dispatcher.message_handlers.portfolio_message_handler;
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
runtime.run().await;
}
let mut messages = VecDeque::new();
if let Err(e) = editor.poll_node_graph_evaluation(&mut messages) {
return Err(format!("Graph should render\n\n{e}"));
+1 -2
View File
@@ -166,7 +166,6 @@ impl DocumentNode {
original_location: self.original_location,
skip_deduplication: self.skip_deduplication,
context_features: self.context_features,
resolved: Default::default(),
}
}
}
@@ -1009,7 +1008,7 @@ impl NodeNetwork {
DocumentNodeMetadata::SourceId => {
let source_id = Self::source_id_for_path(path);
if let Some(context_features) = context_features.as_deref_mut() {
context_features.add_sources(&[source_id]);
core_types::context::merge_sorted_sources(&mut context_features.sources, &[source_id]);
}
(TaggedValue::U64(source_id).into(), false)
}
+16 -59
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::record_value_edge;
use core_types::value::value_edge;
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
use dyn_any::DynAny;
pub use dyn_any::StaticType;
@@ -263,38 +263,19 @@ macro_rules! tagged_value {
}
}
/// `None` for values whose element type is only known dynamically ([`Self::TypeDefault`]).
pub fn element_write(&self) -> Option<core_types::record::ElementWrite> {
Some(match self {
Self::None => core_types::record::element_write::<()>(),
Self::TypeDefault(_) => return None,
Self::F64Array(_) => core_types::record::element_write::<List<f64>>(),
Self::Color(_) => core_types::record::element_write::<List<Color>>(),
Self::Gradient(_) => core_types::record::element_write::<List<GradientStops>>(),
Self::BrushStrokes(_) => core_types::record::element_write::<List<BrushStroke>>(),
$( Self::$identifier(_) => core_types::record::element_write::<$ty>(), )*
Self::RenderOutput(_) => core_types::record::element_write::<RenderOutput>(),
Self::NodeIdPath(_) => core_types::record::element_write::<List<NodeId>>(),
Self::DocumentNode(_) => core_types::record::element_write::<DocumentNode>(),
Self::ContextModification(_) => core_types::record::element_write::<ContextModification>(),
Self::EditorApi(_) => core_types::record::element_write::<Arc<PlatformEditorApi>>(),
Self::ResourceHash(_) => core_types::record::element_write::<ResourceHash>(),
})
}
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a `ClonedNode` edge typed by [`Self::ty`].
pub fn to_edge(self) -> Result<EdgeHandle, String> {
match self {
// ===============
// MANUAL VARIANTS
// ===============
Self::None => Ok(record_value_edge(())),
Self::None => Ok(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(record_value_edge(<$type_default>::default())); }
if name == std::any::type_name::<$type_default>() { return Ok(value_edge(<$type_default>::default())); }
};
}
for_each_type_default!(check);
@@ -302,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(record_value_edge(list))
Ok(value_edge(list))
}
Self::Color(color) => {
let list: List<Color> = color.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(record_value_edge(list))
Ok(value_edge(list))
}
Self::Gradient(stops) => Ok(record_value_edge(List::<GradientStops>::new_from_element(stops))),
Self::Gradient(stops) => Ok(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(record_value_edge(list))
Ok(value_edge(list))
}
// =======================
// AUTO-GENERATED VARIANTS
// =======================
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
$( Self::$identifier(x) => Ok(value_edge(x)), )*
// =======================
// NON-SERIALIZED VARIANTS
// =======================
Self::RenderOutput(x) => Ok(record_value_edge(x)),
Self::RenderOutput(x) => Ok(value_edge(x)),
Self::NodeIdPath(path) => {
let list: List<NodeId> = path.into_iter().map(core_types::list::Item::new_from_element).collect();
Ok(record_value_edge(list))
Ok(value_edge(list))
}
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)),
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)),
}
}
@@ -355,30 +336,6 @@ 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"))
}
@@ -432,7 +389,7 @@ macro_rules! tagged_value {
pub fn from_type(input: &Type) -> Option<Self> {
match input {
Type::Generic(_) => None,
Type::Record(inner) => Self::from_type(inner),
Type::Ref(_) => None,
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
@@ -693,7 +650,7 @@ impl TaggedValue {
match ty {
Type::Generic(_) => None,
Type::Record(_) => None,
Type::Ref(_) => None,
Type::Concrete(concrete_type) => {
let ty = concrete_type.id?;
use std::any::TypeId;
@@ -1,11 +1,11 @@
use crate::document::NodeNetwork;
use crate::proto::{ProtoNetwork, Registry};
use crate::proto::ProtoNetwork;
use std::error::Error;
pub struct Compiler {}
impl Compiler {
pub fn compile<'r>(&self, mut network: NodeNetwork, registry: Option<&'r Registry>) -> impl Iterator<Item = Result<ProtoNetwork, String>> + 'r {
pub fn compile(&self, mut network: NodeNetwork) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
network.resolve_scope_inputs();
network.generate_node_paths(&[]);
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
@@ -19,17 +19,13 @@ impl Compiler {
proto_networks.map(move |mut proto_network| {
proto_network.insert_context_nullification_nodes()?;
if let Some(registry) = registry {
let _ = proto_network.resolve_types(registry);
proto_network.compute_layouts();
}
proto_network.generate_stable_node_ids();
Ok(proto_network)
})
}
pub fn compile_single(&self, network: NodeNetwork, registry: Option<&Registry>) -> Result<ProtoNetwork, String> {
pub fn compile_single(&self, network: NodeNetwork) -> Result<ProtoNetwork, String> {
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
let Some(proto_network) = self.compile(network, registry).next() else {
let Some(proto_network) = self.compile(network).next() else {
return Err("Failed to convert graph into proto graph".to_string());
};
proto_network
+144 -250
View File
@@ -124,20 +124,6 @@ impl ConstructionArgs {
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Resolved {
pub io: Option<NodeIOTypes>,
pub layout_meta: Option<core_types::record::LayoutMeta>,
pub layout: Option<core_types::record::Layout>,
}
impl PartialEq for Resolved {
fn eq(&self, _: &Self) -> bool {
true
}
}
impl Eq for Resolved {}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// A proto node is an intermediate step between the `DocumentNode` and the boxed struct that actually runs the node (found in the [`BorrowTree`]).
/// At different stages in the compilation process, this struct will be transformed into a reduced (more restricted) form acting as a subset of its original form, but that restricted form is still valid in the earlier stage in the compilation process before it was transformed.
@@ -148,8 +134,6 @@ pub struct ProtoNode {
pub original_location: OriginalLocation,
pub skip_deduplication: bool,
pub(crate) context_features: ContextDependencies,
#[serde(skip)]
pub(crate) resolved: Resolved,
}
impl Default for ProtoNode {
@@ -161,7 +145,6 @@ impl Default for ProtoNode {
original_location: OriginalLocation::default(),
skip_deduplication: false,
context_features: Default::default(),
resolved: Default::default(),
}
}
}
@@ -202,7 +185,6 @@ impl ProtoNode {
},
skip_deduplication: false,
context_features: Default::default(),
resolved: Default::default(),
}
}
@@ -220,10 +202,6 @@ impl ProtoNode {
_ => panic!("tried to unwrap nodes from non node construction args \n node: {self:#?}"),
}
}
pub fn resolved_layout(&self) -> Option<&core_types::record::Layout> {
self.resolved.layout.as_ref()
}
}
#[derive(Clone, Copy, PartialEq)]
@@ -280,11 +258,6 @@ 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
@@ -322,66 +295,7 @@ impl ProtoNetwork {
}
pub fn source_ids(&self) -> Vec<SourceId> {
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources().iter().copied()).collect()
}
pub fn resolve_types(&mut self, registry: &Registry) -> Result<(), String> {
self.reorder_ids()?;
for index in 0..self.nodes.len() {
let resolved = {
let node = &self.nodes[index].1;
match &node.construction_args {
ConstructionArgs::Value(value) => Resolved {
io: Some(NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(value.ty())), vec![])),
..Default::default()
},
_ => {
let inputs: Vec<Type> = match &node.construction_args {
ConstructionArgs::Nodes(nodes) => nodes
.iter()
.map(|input| {
self.nodes[input.0 as usize]
.1
.resolved
.io
.as_ref()
.map(|io| io.ty())
.ok_or_else(|| format!("input {input:?} of {} is not yet typed", node.identifier.as_str()))
})
.collect::<Result<_, _>>()?,
ConstructionArgs::Inline(inline) => vec![inline.ty.clone()],
ConstructionArgs::Value(_) => unreachable!(),
};
let impls = registry.get(&node.identifier).ok_or_else(|| format!("no implementations for {}", node.identifier.as_str()))?;
let (io, entry) = resolve_entry(node, &inputs, impls).map_err(|errors| format!("{errors:?}"))?;
Resolved {
io: Some(io),
layout_meta: entry.layout_meta.clone(),
layout: None,
}
}
}
};
self.nodes[index].1.resolved = resolved;
}
Ok(())
}
pub fn compute_layouts(&mut self) {
for index in 0..self.nodes.len() {
let layout = {
let node = &self.nodes[index].1;
match &node.construction_args {
ConstructionArgs::Value(value) => value.element_write().map(|element| core_types::record::Layout::default().with_writes(0, element, &[])),
ConstructionArgs::Nodes(inputs) => node.resolved.layout_meta.as_ref().and_then(|meta| {
let input_layouts: Vec<Option<&core_types::record::Layout>> = inputs.iter().map(|input| self.nodes[input.0 as usize].1.resolved.layout.as_ref()).collect();
meta.sources.iter().all(|&source| input_layouts[source as usize].is_some()).then(|| meta.fold(&input_layouts))
}),
ConstructionArgs::Inline(_) => None,
}
};
self.nodes[index].1.resolved.layout = layout;
}
self.nodes.iter().flat_map(|(_, node)| node.context_features.sources.iter().copied()).collect()
}
/// Inserts context nullification nodes to optimize caching.
@@ -460,10 +374,10 @@ impl ProtoNetwork {
let mut combined_deps = ContextModification::default();
let node_index = id.0 as usize;
let (extract, inject, own_deps) = {
let dependencies = &self.nodes[node_index].1.context_features;
let own_deps = ContextModification::from_sources(dependencies.extract, dependencies.sources());
(dependencies.extract, dependencies.inject, own_deps)
let context_features = self.nodes[node_index].1.context_features.clone();
let own_deps = ContextModification {
features: context_features.extract,
sources: context_features.sources.clone(),
};
let mut inputs = match &self.nodes[node_index].1.construction_args {
@@ -483,7 +397,7 @@ impl ProtoNetwork {
let mut new_deps = combined_deps.clone();
// Remove requirements which this node provides
new_deps &= !inject;
new_deps &= !context_features.inject;
// Add requirements we have
new_deps |= own_deps;
@@ -501,7 +415,7 @@ impl ProtoNetwork {
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
// Which dependencies do we supply (and don't need ourselves)?
let net_injections = inject.difference(extract);
let net_injections = context_features.inject.difference(context_features.extract);
// Which dependencies still need to be met after this node?
let remaining_deps_from_children = combined_deps.features.difference(net_injections);
@@ -724,34 +638,28 @@ impl Debug for GraphError {
}
pub type GraphErrors = Vec<GraphError>;
pub type Registry = HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>;
/// The `TypingContext` is used to store the types of the nodes indexed by their stable node id.
#[derive(Default, Clone, dyn_any::DynAny)]
pub struct TypingContext {
lookup: Cow<'static, Registry>,
lookup: Cow<'static, HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>,
inferred: HashMap<NodeId, NodeIOTypes>,
constructor: HashMap<NodeId, NodeConstructor>,
}
impl TypingContext {
/// Creates a new `TypingContext` with the given lookup table.
pub fn new(lookup: &'static Registry) -> Self {
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>) -> Self {
Self {
lookup: Cow::Borrowed(lookup),
..Default::default()
}
}
pub fn registry(&self) -> &Registry {
&self.lookup
}
/// 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: &mut ProtoNetwork) -> Result<(), GraphErrors> {
for (id, node) in &network.nodes {
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> {
for (id, node) in network.nodes.iter() {
self.infer(*id, node)?;
}
@@ -781,10 +689,10 @@ impl TypingContext {
}
let inputs = match node.construction_args {
// A value node is a native record source, so it types as a record
// of its value.
// If the node has a value input we can infer the return type from it
ConstructionArgs::Value(ref v) => {
let types = NodeIOTypes::new(concrete!(Context), Type::Record(Box::new(v.ty())), vec![]);
// TODO: This should return a reference to the value
let types = NodeIOTypes::new(concrete!(Context), v.ty(), vec![]);
self.inferred.insert(node_id, types.clone());
return Ok(types);
}
@@ -802,144 +710,143 @@ impl TypingContext {
};
// Get the node input type from the proto node declaration
let call_argument = &node.call_argument;
let impls = self.lookup.get(&node.identifier).ok_or_else(|| vec![GraphError::new(node, GraphErrorType::NoImplementations)])?;
let (node_io, entry) = resolve_entry(node, &inputs, impls)?;
self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, entry.constructor);
Ok(node_io)
}
}
let candidates: Vec<(NodeIOTypes, NodeConstructor)> = impls.iter().map(|entry| (entry.io.clone(), entry.constructor)).collect();
/// Selects the single registry entry matching the node's resolved input types,
/// substituting generics. Stateless and stable-id-free.
fn resolve_entry<'a>(node: &ProtoNode, inputs: &[Type], impls: &'a [RegistryEntry]) -> Result<(NodeIOTypes, &'a RegistryEntry), GraphErrors> {
let call_argument = &node.call_argument;
let candidates: Vec<(NodeIOTypes, &RegistryEntry)> = impls.iter().map(|entry| (entry.io.clone(), entry)).collect();
if let Some(index) = inputs.iter().position(|p| {
matches!(p,
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
}) {
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
}
if let Some(index) = inputs.iter().position(|p| {
matches!(p,
Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))
}) {
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs: inputs.to_vec() })]);
}
// List of all implementations that match the input types
let valid_output_types = candidates
.iter()
.filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
.collect::<Vec<_>>();
// Attempt to substitute generic types with concrete types and save the list of results
let substitution_results = valid_output_types
.iter()
.map(|(node_io, entry)| {
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
.iter()
.map(|generic| check_generic(node_io, call_argument, inputs, generic).map(|x| (generic.to_string(), x)))
.collect();
generics_lookup.map(|generics_lookup| {
let mut new_node_io = node_io.clone();
replace_generics(&mut new_node_io, &generics_lookup);
(new_node_io, *entry)
})
})
.collect::<Vec<_>>();
// Collect all substitutions that are valid
let valid_impls = substitution_results.iter().filter_map(|result| result.as_ref().ok()).collect::<Vec<_>>();
match valid_impls.as_slice() {
[] => {
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
let mut best_errors = usize::MAX;
let mut error_inputs = Vec::new();
for (node_io, _) in &candidates {
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
let current_errors = [call_argument]
.into_iter()
.chain(inputs)
.cloned()
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
.enumerate()
.filter(|(_, (p1, p2))| !valid_type(p1, p2))
.map(|(index, expected)| (index - 1 + convert_node_index_offset, expected))
.collect::<Vec<_>>();
if current_errors.len() < best_errors {
best_errors = current_errors.len();
error_inputs.clear();
}
if current_errors.len() <= best_errors {
error_inputs.push(current_errors);
}
/// 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,
}
let inputs = [call_argument]
.into_iter()
.chain(inputs)
.enumerate()
.filter_map(|(i, t)| {
if i == 0 {
None
} else {
let number = i + convert_node_index_offset;
Some(format!("• Input {number}: {t}"))
}
}
// List of all implementations that match the input types
let valid_output_types = candidates
.iter()
.filter(|(node_io, _)| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
.collect::<Vec<_>>();
// Attempt to substitute generic types with concrete types and save the list of results
let substitution_results = valid_output_types
.iter()
.map(|(node_io, constructor)| {
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
.iter()
.map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x)))
.collect();
generics_lookup.map(|generics_lookup| {
let mut new_node_io = node_io.clone();
replace_generics(&mut new_node_io, &generics_lookup);
(new_node_io, *constructor)
})
.collect::<Vec<_>>()
.join("\n");
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
}
[(node_io, entry)] => Ok((node_io.clone(), *entry)),
// If two types are available and one of them accepts () an input, always choose that one
[first, second] => {
if first.0.call_argument != second.0.call_argument {
for (node_io, entry) in [first, second] {
if node_io.call_argument != concrete!(()) {
continue;
})
.collect::<Vec<_>>();
// Collect all substitutions that are valid
let valid_impls = substitution_results.iter().filter_map(|result| result.as_ref().ok()).collect::<Vec<_>>();
match valid_impls.as_slice() {
[] => {
let convert_node_index_offset = node.original_location.auto_convert_index.unwrap_or(0);
let mut best_errors = usize::MAX;
let mut error_inputs = Vec::new();
for (node_io, _) in &candidates {
// For errors on Convert nodes, offset the input index so it correctly corresponds to the node it is connected to.
let current_errors = [call_argument]
.into_iter()
.chain(&inputs)
.cloned()
.zip([&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned())
.enumerate()
.filter(|(_, (p1, p2))| !valid_type(p1, p2))
.map(|(index, expected)| (index - 1 + convert_node_index_offset, expected))
.collect::<Vec<_>>();
if current_errors.len() < best_errors {
best_errors = current_errors.len();
error_inputs.clear();
}
if current_errors.len() <= best_errors {
error_inputs.push(current_errors);
}
return Ok((node_io.clone(), *entry));
}
let inputs = [call_argument]
.into_iter()
.chain(&inputs)
.enumerate()
.filter_map(|(i, t)| {
if i == 0 {
None
} else {
let number = i + convert_node_index_offset;
Some(format!("• Input {number}: {t}"))
}
})
.collect::<Vec<_>>()
.join("\n");
Err(vec![GraphError::new(node, GraphErrorType::InvalidImplementations { inputs, error_inputs })])
}
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
}
[(node_io, constructor)] => {
let node_io = node_io.clone();
_ => {
let inputs = [call_argument].into_iter().chain(inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
}
}
}
// Save the inferred type
self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, *constructor);
Ok(node_io)
}
// If two types are available and one of them accepts () an input, always choose that one
[first, second] => {
if first.0.call_argument != second.0.call_argument {
for (node_io, constructor) in [first, second] {
if node_io.call_argument != concrete!(()) {
continue;
}
/// 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,
// Save the inferred type
self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, *constructor);
return Ok(node_io.clone());
}
}
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
}
_ => {
let inputs = [call_argument].into_iter().chain(&inputs).map(ToString::to_string).collect::<Vec<_>>().join(", ");
let valid = valid_output_types.into_iter().map(|(node_io, _)| node_io.clone()).collect();
Err(vec![GraphError::new(node, GraphErrorType::MultipleImplementations { inputs, valid })])
}
}
}
}
@@ -961,23 +868,10 @@ 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| record_element(x.fn_output()))
.zip(parameters.iter().map(|x| record_element(x.fn_output()))),
);
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| 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
@@ -1139,7 +1033,7 @@ mod test {
let value::TaggedValue::ContextModification(modification) = &**value else {
panic!("filter payload must be a context modification")
};
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources().to_vec())
(*id, node(memoized[0]).identifier.as_str().to_string(), modification.sources.clone())
})
.collect()
}
@@ -1205,7 +1099,7 @@ mod test {
identifier: ProtoNodeIdentifier::with_owned_string(name.to_string()),
call_argument: concrete!(()),
construction_args: ConstructionArgs::Nodes(vec![NodeId(0)]),
context_features: ContextDependencies::from_sources(&sources),
context_features: ContextDependencies { sources, ..Default::default() },
..Default::default()
};
ProtoNetwork {
+1 -1
View File
@@ -10,7 +10,7 @@ pub fn load_network(document_string: &str) -> NodeNetwork {
pub fn compile(network: NodeNetwork) -> ProtoNetwork {
let compiler = Compiler {};
compiler.compile_single(network, None).unwrap()
compiler.compile_single(network).unwrap()
}
pub fn load_from_name(name: &str) -> NodeNetwork {
+1 -1
View File
@@ -22,7 +22,7 @@ fn execute_until_final(executor: &DynamicExecutor, render_config: RenderConfig,
GPoll::Final(value) => return Ok(value),
GPoll::Fallback(boxed) => {
let (value, error) = *boxed;
log::warn!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
log::error!("Node graph evaluation reported an error alongside its fallback output: {error:?}");
return Ok(value);
}
GPoll::Partial(_) | GPoll::Pending => {
+7 -13
View File
@@ -13,7 +13,7 @@ use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::load_network;
use graphene_std::application_io::{ApplicationIo, NodeGraphUpdateMessage, NodeGraphUpdateSender};
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner, poll_once};
use graphene_std::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, RuntimeHandle, SourceFuture, Spawner};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::error::Error;
@@ -31,20 +31,14 @@ impl NodeGraphUpdateSender for UpdateLogger {
struct TokioSpawner(Option<tokio::runtime::Runtime>);
impl TokioSpawner {
fn new() -> Result<Self, std::io::Error> {
Ok(Self(Some(tokio::runtime::Runtime::new()?)))
fn new() -> Self {
Self(Some(tokio::runtime::Runtime::new().expect("Failed to start the async source runtime")))
}
}
impl Spawner for TokioSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
let runtime = self.0.as_ref().expect("runtime lives until drop");
let _guard = runtime.enter();
if poll_once(&mut task) {
return true;
}
runtime.spawn(task);
false
fn spawn(&self, task: SourceFuture) {
self.0.as_ref().expect("runtime lives until drop").spawn(task);
}
}
@@ -208,7 +202,7 @@ fn main() -> Result<(), Box<dyn Error>> {
let preferences = EditorPreferences {
max_render_region_size: EditorPreferences::default().max_render_region_size,
};
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()?) as Box<DynSpawner>));
let graph_runtime: Arc<DynGraphRuntime> = Arc::new(GraphRuntime::new(Box::new(TokioSpawner::new()) as Box<DynSpawner>));
let (completion_sender, completion_receiver) = std::sync::mpsc::channel();
graph_runtime.set_notifier(Arc::new(move || {
let _ = completion_sender.send(());
@@ -314,7 +308,7 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
}
let compiler = Compiler {};
compiler.compile_single(network, Some(&interpreted_executor::node_registry::NODE_REGISTRY)).map_err(|x| x.into())
compiler.compile_single(network).map_err(|x| x.into())
}
fn create_executor(proto_network: ProtoNetwork, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
@@ -1,5 +1,6 @@
use criterion::BenchmarkGroup;
use criterion::measurement::Measurement;
use futures::executor::block_on;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi;
@@ -13,12 +14,10 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
let executor = DynamicExecutor::new(proto_network.clone()).unwrap();
let executor = block_on(DynamicExecutor::new(proto_network.clone())).unwrap();
(executor, proto_network)
}
// Some benches in this module's include set drive the demos themselves.
#[allow(dead_code)]
pub fn bench_for_each_demo<M: Measurement, F>(group: &mut BenchmarkGroup<M>, f: F)
where
F: Fn(&str, &mut BenchmarkGroup<M>),
@@ -2,7 +2,6 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig;
fn subsequent_evaluations(c: &mut Criterion) {
@@ -10,7 +9,9 @@ fn subsequent_evaluations(c: &mut Criterion) {
let context = RenderConfig::default();
bench_for_each_demo(&mut group, |name, g| {
let (executor, _) = setup_network(name);
g.bench_function(name, |b| b.iter(|| Executor::execute(&&executor, std::hint::black_box(context)).unwrap()));
g.bench_function(name, |b| {
b.iter(|| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap())
});
});
group.finish();
}
@@ -1,7 +1,6 @@
mod benchmark_util;
use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig;
use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -12,7 +11,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
// Warm up the cache by running once
let context = RenderConfig::default();
let _ = Executor::execute(&&executor, context);
let _ = futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), context));
executor
}
@@ -21,7 +20,7 @@ fn setup_run_cached(name: &str) -> DynamicExecutor {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_cached)]
pub fn run_cached(executor: DynamicExecutor) -> DynamicExecutor {
let context = RenderConfig::default();
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
// Return the executor so its teardown happens outside the measured section
executor
@@ -9,11 +9,14 @@ use interpreted_executor::dynamic_executor::DynamicExecutor;
fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name);
let proto_network = compile(network);
let empty = ProtoNetwork::default();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
c.bench_function(name, |b| {
b.iter_batched(
|| (DynamicExecutor::new(ProtoNetwork::default()).unwrap(), proto_network.clone()),
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|| (executor.clone(), proto_network.clone()),
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
criterion::BatchSize::SmallInput,
)
});
@@ -30,10 +33,10 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
let network = load_from_name(name);
let proto_network = compile(network);
let executor = DynamicExecutor::new(proto_network).unwrap();
let executor = futures::executor::block_on(DynamicExecutor::new(proto_network)).unwrap();
let footprint = Footprint::default();
c.bench_function(name, |b| b.iter(|| (&executor).execute(footprint)));
c.bench_function(name, |b| b.iter(|| futures::executor::block_on((&executor).execute(footprint))));
}
fn run_once_demo(c: &mut Criterion) {
let mut g = c.benchmark_group("Run Once no render");
@@ -2,7 +2,6 @@ mod benchmark_util;
use benchmark_util::{bench_for_each_demo, setup_network};
use criterion::{Criterion, criterion_group, criterion_main};
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io::RenderConfig;
fn run_once(c: &mut Criterion) {
@@ -12,7 +11,7 @@ fn run_once(c: &mut Criterion) {
g.bench_function(name, |b| {
b.iter_batched(
|| setup_network(name),
|(executor, _)| Executor::execute(&&executor, std::hint::black_box(context)).unwrap(),
|(executor, _)| futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), std::hint::black_box(context))).unwrap(),
criterion::BatchSize::SmallInput,
)
});
@@ -1,7 +1,6 @@
mod benchmark_util;
use benchmark_util::setup_network;
use graph_craft::graphene_compiler::Executor;
use graphene_std::application_io;
use gungraun::prelude::*;
use interpreted_executor::dynamic_executor::DynamicExecutor;
@@ -16,7 +15,7 @@ fn setup_run_once(name: &str) -> DynamicExecutor {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_run_once)]
pub fn run_once(executor: DynamicExecutor) -> DynamicExecutor {
let context = application_io::RenderConfig::default();
black_box(Executor::execute(&&executor, black_box(context)).unwrap());
black_box(futures::executor::block_on(executor.tree().eval_tagged_value(executor.output(), black_box(context))).unwrap());
// Return the executor so its teardown happens outside the measured section
executor
@@ -13,10 +13,10 @@ fn update_executor(c: &mut Criterion) {
|| {
let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default();
let executor = DynamicExecutor::new(empty).unwrap();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
(executor, proto_network)
},
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|(mut executor, network)| futures::executor::block_on(executor.update(std::hint::black_box(network))),
criterion::BatchSize::SmallInput,
)
});
@@ -9,7 +9,7 @@ use std::hint::black_box;
fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let (_, proto_network) = setup_network(name);
let empty = ProtoNetwork::default();
let executor = DynamicExecutor::new(empty).unwrap();
let executor = futures::executor::block_on(DynamicExecutor::new(empty)).unwrap();
(executor, proto_network)
}
@@ -17,7 +17,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
let (mut executor, network) = setup;
let _ = black_box(executor.update(black_box(network)));
let _ = black_box(futures::executor::block_on(executor.update(black_box(network))));
// Return the executor so its teardown happens outside the measured section
executor
@@ -17,13 +17,6 @@ use std::sync::{Arc, Mutex, PoisonError};
const ARENA_CAPACITY: usize = 1 << 20;
fn new_arena() -> Arena {
Arena::new(ARENA_CAPACITY).unwrap_or_else(|| {
log::error!("arena generations exhausted; continuing without frame caching");
Arena::parked()
})
}
/// An executor of a node graph that does not require an online compilation server, and instead uses `Box<dyn ...>`.
pub struct DynamicExecutor {
output: NodeId,
@@ -49,7 +42,7 @@ impl Default for DynamicExecutor {
tree: Default::default(),
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena()),
arena: Mutex::new(Arena::new(ARENA_CAPACITY)),
runtime: noop_runtime(),
live_sources: Vec::new(),
}
@@ -71,9 +64,9 @@ pub struct ResolvedDocumentNodeTypesDelta {
}
impl DynamicExecutor {
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
pub fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
typing_context.update(&mut proto_network)?;
typing_context.update(&proto_network)?;
let output = proto_network.output;
let sources = proto_network.source_ids();
let tree = BorrowTree::new(proto_network, &typing_context)?;
@@ -85,7 +78,7 @@ impl DynamicExecutor {
output,
typing_context,
orphaned_nodes: HashSet::new(),
arena: Mutex::new(new_arena()),
arena: Mutex::new(Arena::new(ARENA_CAPACITY)),
runtime,
live_sources: sources,
})
@@ -102,9 +95,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, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
self.output = proto_network.output;
self.typing_context.update(&mut proto_network).map_err(|e| {
self.typing_context.update(&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,17 +138,8 @@ 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> {
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)
self.tree.introspect(node_path)
}
pub fn input_type(&self) -> Option<Type> {
@@ -190,7 +174,6 @@ 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)),
@@ -271,36 +254,23 @@ 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)?;
@@ -309,7 +279,6 @@ impl BorrowTree {
}
old_nodes.remove(&id);
}
self.stack_need = stack_peak(output, &deps, &|id| self.frame_bytes(id));
Ok((new_nodes, old_nodes))
}
@@ -476,7 +445,6 @@ impl BorrowTree {
.clone()
.to_edge()
.map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(error))])?;
debug_assert!(proto_node.resolved_layout().map_or(true, |expected| node.layout() == Some(expected)), "layout pass disagrees with construction for {}", proto_node.identifier.as_str());
self.store_node(node, id, path.into());
}
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
@@ -484,7 +452,6 @@ impl BorrowTree {
let construction_nodes = self.node_deps(ids);
let constructor = typing_context.constructor(id).ok_or_else(|| vec![GraphError::new(&proto_node, GraphErrorType::NoConstructor)])?;
let node = constructor(construction_nodes).map_err(|error| vec![GraphError::new(&proto_node, GraphErrorType::ConstructionFailed(format!("{error:?}")))])?;
debug_assert!(proto_node.resolved_layout().map_or(true, |expected| node.layout() == Some(expected)), "layout pass disagrees with construction for {}", proto_node.identifier.as_str());
self.store_node(node, id, path.into());
}
};
@@ -495,38 +462,6 @@ 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)]
@@ -540,27 +475,12 @@ mod test {
struct InertSpawner;
impl Spawner for InertSpawner {
fn spawn(&self, _task: SourceFuture) -> bool {
false
}
}
#[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);
fn spawn(&self, _task: SourceFuture) {}
}
#[test]
fn eval_root_builds_the_bare_root_with_the_call_argument_as_vararg_0() {
let mut arena = Arena::new(64).unwrap();
let mut arena = Arena::new(64);
let runtime = GraphRuntime::new(InertSpawner);
let argument = 21.5f64;
let result = eval_root(&mut arena, &runtime, &argument, |ctx| {
@@ -572,7 +492,7 @@ mod test {
#[test]
fn eval_root_resets_the_arena_at_eval_start() {
let mut arena = Arena::new(64).unwrap();
let mut arena = Arena::new(64);
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
eval_root(&mut arena, &runtime, &(), |ctx| {
@@ -589,7 +509,7 @@ mod test {
#[test]
fn a_panicking_eval_reports_the_error_and_resets_the_arena() {
let mut arena = Arena::new(64).unwrap();
let mut arena = Arena::new(64);
let runtime = GraphRuntime::new(InertSpawner);
let cell = ArenaCell::new();
let result: GPoll<()> = eval_root(&mut arena, &runtime, &(), |ctx| {
@@ -608,196 +528,13 @@ 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 handle = tree.get(NodeId(0)).unwrap();
let layout = handle.layout().unwrap().clone();
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
let _node = tree.get(NodeId(0)).unwrap();
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
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"
);
let result: Option<GPoll<u32>> = tree.eval(NodeId(0), &ctx);
assert_eq!(result, Some(GPoll::Final(2)));
}
}
+1 -1
View File
@@ -44,7 +44,7 @@ mod tests {
use graph_craft::graphene_compiler::Compiler;
let compiler = Compiler {};
let protograph = compiler.compile_single(network, Some(&crate::node_registry::NODE_REGISTRY)).expect("Graph should be generated");
let protograph = compiler.compile_single(network).expect("Graph should be generated");
let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
}
@@ -1,6 +1,9 @@
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")]
@@ -17,7 +20,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::{convert_node, into_node};
use node_registry_macros::{async_node, convert_node, into_node};
use std::collections::HashMap;
#[cfg(feature = "gpu")]
use wgpu_executor::WgpuExecutorHandle;
@@ -106,9 +109,183 @@ 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 => 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]),
#[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 => 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::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
@@ -136,7 +313,6 @@ 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();
@@ -174,28 +350,43 @@ 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 {
layout_meta: None,
io: NodeIOTypes::new(
concrete!(Context),
core_types::registry::record_type::<$to>(),
vec![core_types::registry::record_edge_type::<$from>()],
),
io: NodeIOTypes::new(concrete!(Context), concrete!($to), vec![fn_type!(Context, $from)]),
constructor: |inputs| {
if inputs.len() != 1 {
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
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>))
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>>))
},
},
)
@@ -247,44 +438,23 @@ mod node_registry_macros {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
RegistryEntry {
layout_meta: None,
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>(),
core_types::registry::record_edge_type::<RuntimeHandle>(),
core_types::registry::record_edge_type::<SourceId>(),
],
concrete!($to),
vec![fn_type!(Context, $from), fn_type!(Context, $convert), fn_type!(Context, RuntimeHandle), fn_type!(Context, SourceId)],
),
constructor: |inputs| {
if inputs.len() != 4 {
return Err(ConstructionError::Arity { expected: 4, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
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,
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>()?,
);
Ok(EdgeHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
Ok(EdgeHandle::new(std::sync::Arc::new(node) as std::sync::Arc<ErasedNode<$to>>))
},
},
)
@@ -293,70 +463,21 @@ mod node_registry_macros {
(
ProtoNodeIdentifier::new(concat!["graphene_core::ops::ConvertNode<", stringify!($to), ">"]),
RegistryEntry {
layout_meta: None,
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>()],
),
io: NodeIOTypes::new(concrete!(Context), concrete!($to), vec![fn_type!(Context, $from), fn_type!(Context, $convert)]),
constructor: |inputs| {
if inputs.len() != 2 {
return Err(ConstructionError::Arity { expected: 2, got: inputs.len() });
}
let mut inputs = inputs.into_iter();
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>))
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>>))
},
},
)
};
}
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"));
}
}
+31 -10
View File
@@ -30,14 +30,22 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
call_argument: concrete!(Context),
inputs: vec![NodeInput::import(core_types::Type::Fn(Box::new(concrete!(Context)), Box::new(generic!(T))), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render_intermediate::IDENTIFIER),
context_features: graphene_std::ContextDependencies::new(ContextFeatures::VARARGS, ContextFeatures::INDEX),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::INDEX,
..Default::default()
},
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
..Default::default()
},
..Default::default()
},
DocumentNode {
@@ -48,14 +56,22 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(1), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::VARARGS),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::VARARGS,
..Default::default()
},
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
..Default::default()
},
..Default::default()
},
DocumentNode {
@@ -65,18 +81,23 @@ pub fn wrap_network_in_scope(network: NodeNetwork, editor_api: Arc<PlatformEdito
NodeInput::node(NodeId(3), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
context_features: graphene_std::ContextDependencies::new(ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS, ContextFeatures::empty()),
context_features: graphene_std::ContextDependencies {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
..Default::default()
},
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
context_features: graphene_std::ContextDependencies::new(
ContextFeatures::INDEX | ContextFeatures::VARARGS,
ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
),
context_features: graphene_std::ContextDependencies {
// We add the extract index annotation here to force the compiler to add a context nullification node before this node so the render context is properly nullified so the render cache node can do its's work
extract: ContextFeatures::INDEX | ContextFeatures::VARARGS,
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
..Default::default()
},
..Default::default()
},
]
+25 -170
View File
@@ -4,15 +4,6 @@ use std::mem::MaybeUninit;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
/// Handle word layout: 24 generation bits above 40 offset bits, so a 1 TiB arena is
/// addressable and generations run out after ~3 days of 60fps resets.
const OFFSET_BITS: u32 = 40;
const OFFSET_MASK: u64 = (1 << OFFSET_BITS) - 1;
const GENERATION_MASK: u64 = (1 << (64 - OFFSET_BITS)) - 1;
/// Out of the encodable range, so no handle, including `NULL`, matches it.
const PARKED_GENERATION: u64 = GENERATION_MASK + 1;
pub struct Arena {
generation: AtomicU64,
offset: AtomicUsize,
@@ -33,66 +24,22 @@ struct DropEntry {
// SAFETY: disjoint regions are handed out by an atomic bump; a region is written
// only by its allocating caller before publication, and cross-thread hand-off is
// ordered by the Release/Acquire pair on the published handle word. Payloads are
// `Send + Sync` by the bound on every allocating method.
// ordered by the Release/Acquire pair on the published handle word.
unsafe impl Sync for Arena {}
unsafe impl Send for Arena {}
impl std::panic::UnwindSafe for Arena {}
impl std::panic::RefUnwindSafe for Arena {}
/// Shared by all arenas, so a foreign handle misses like a stale one.
static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
static LIVE_ARENAS: AtomicUsize = AtomicUsize::new(0);
/// `None` past [`GENERATION_MASK`], where a reissued generation would let an ancient
/// handle upgrade against a current arena. Recovered by `reset_generation_counter`.
fn next_generation() -> Option<u64> {
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
(generation <= GENERATION_MASK).then_some(generation)
}
/// Rewinds the shared generation counter so previously issued values are reused.
/// Returns `false` without rewinding when an [`Arena`] is live at the time of the
/// check, which is a debugging aid rather than a guarantee.
///
/// # Safety
///
/// No [`ArenaWeak`] minted before this call may be upgraded afterwards. Dropping
/// every [`Arena`] is not sufficient, since nodes also hold handles in
/// [`ArenaCell`]s; those nodes must be dropped too. No arena may be constructed
/// concurrently either, since the live check and the rewind are separate steps.
pub unsafe fn reset_generation_counter() -> bool {
if LIVE_ARENAS.load(Ordering::Acquire) != 0 {
return false;
}
NEXT_GENERATION.store(1, Ordering::Release);
true
}
impl Arena {
pub fn new(capacity: usize) -> Option<Self> {
let generation = next_generation()?;
pub fn new(capacity: usize) -> Self {
let buf = (0..capacity).map(|_| UnsafeCell::new(MaybeUninit::uninit())).collect();
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Some(Self {
generation: AtomicU64::new(generation),
Self {
// Starts at 1 so the null handle word (0) can never upgrade.
generation: AtomicU64::new(1),
offset: AtomicUsize::new(0),
buf,
drops: Mutex::new(Vec::new()),
})
}
/// An arena that refuses every allocation and resolves no handle, so a caller that
/// cannot fail can degrade instead of propagating exhaustion.
pub fn parked() -> Self {
LIVE_ARENAS.fetch_add(1, Ordering::Release);
Self {
generation: AtomicU64::new(PARKED_GENERATION),
offset: AtomicUsize::new(0),
buf: Box::new([]),
drops: Mutex::new(Vec::new()),
}
}
@@ -121,11 +68,8 @@ impl Arena {
Some(start)
}
pub fn alloc<T: Send + Sync>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
pub fn alloc<T>(&self, value: T) -> Option<(&T, ArenaWeak<T>)> {
let offset = self.reserve(size_of::<T>(), align_of::<T>())?;
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
let weak = ArenaWeak::new(self.generation(), offset)?;
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
unsafe { ptr.write(value) };
@@ -136,10 +80,10 @@ impl Arena {
self.drops.lock().unwrap().push(DropEntry { offset, drop_fn: glue::<T> });
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
Some((unsafe { &*ptr }, weak))
Some((unsafe { &*ptr }, ArenaWeak::new(self.generation(), offset)))
}
pub fn alloc_slice_copy<T: Copy + Send + Sync>(&self, src: &[T]) -> Option<&[T]> {
pub fn alloc_slice_copy<T: Copy>(&self, src: &[T]) -> Option<&[T]> {
let buf = self.alloc_scratch::<T>(src.len())?;
for (slot, &value) in buf.iter_mut().zip(src) {
slot.write(value);
@@ -151,7 +95,7 @@ impl Arena {
// Not drop-tracked: callers must either consume every written lane or
// restrict themselves to `Copy` payloads (leak, not UB, otherwise).
#[allow(clippy::mut_from_ref)]
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
pub fn alloc_scratch<T>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
let size = size_of::<T>().checked_mul(len)?;
let offset = self.reserve(size, align_of::<T>())?;
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
@@ -160,34 +104,27 @@ impl Arena {
Some(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
}
/// `false` once generations are exhausted, parking the arena on [`PARKED_GENERATION`]
/// where every handle misses and further allocation is refused.
pub fn reset(&mut self) -> bool {
pub fn reset(&mut self) {
let base = self.base();
let entries = std::mem::take(self.drops.get_mut().unwrap());
self.generation.store(PARKED_GENERATION, Ordering::Release);
for entry in entries.into_iter().rev() {
for entry in self.drops.get_mut().unwrap().drain(..) {
// SAFETY: registered at alloc time; insert-only means the region was
// never overwritten within this generation.
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
}
*self.offset.get_mut() = 0;
let Some(generation) = next_generation() else { return false };
self.generation.store(generation, Ordering::Release);
true
self.generation.fetch_add(1, Ordering::Release);
}
}
impl Drop for Arena {
fn drop(&mut self) {
self.reset();
LIVE_ARENAS.fetch_sub(1, Ordering::Release);
}
}
pub struct ArenaWeak<T> {
word: u64,
_marker: PhantomData<fn() -> T>,
_marker: PhantomData<*const T>,
}
impl<T> Clone for ArenaWeak<T> {
@@ -200,22 +137,20 @@ impl<T> Copy for ArenaWeak<T> {}
impl<T> ArenaWeak<T> {
pub const NULL: Self = ArenaWeak { word: 0, _marker: PhantomData };
/// `None` once either field leaves its encodable range, so an oversized or parked
/// arena refuses to hand out a handle rather than truncating it to a live address.
fn new(generation: u64, offset: usize) -> Option<Self> {
let offset = u64::try_from(offset).ok().filter(|offset| *offset <= OFFSET_MASK)?;
(generation <= GENERATION_MASK).then_some(Self {
word: (generation << OFFSET_BITS) | offset,
fn new(generation: u64, offset: usize) -> Self {
debug_assert!(offset < u32::MAX as usize);
Self {
word: ((generation & 0xFFFF_FFFF) << 32) | offset as u64,
_marker: PhantomData,
})
}
}
pub fn upgrade(self, arena: &Arena) -> Option<&T> {
let generation = self.word >> OFFSET_BITS;
if generation != arena.generation() {
let generation = self.word >> 32;
if generation != arena.generation() & 0xFFFF_FFFF {
return None;
}
let offset = (self.word & OFFSET_MASK) as usize;
let offset = (self.word & 0xFFFF_FFFF) as usize;
// SAFETY: same generation means the entry was fully written before its
// word was published (Release) and cannot move or be overwritten within
// a generation (insert-only); the Acquire load that produced this word
@@ -274,13 +209,11 @@ impl<T> ArenaCell<T> {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::PoisonError;
use std::sync::atomic::AtomicU32;
#[test]
fn alloc_upgrade_reset_miss() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let mut arena = Arena::new(1024);
let cell = ArenaCell::new();
let (value, weak) = arena.alloc(41u32).unwrap();
assert_eq!(*value, 41);
@@ -292,8 +225,7 @@ mod tests {
#[test]
fn capacity_survives_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(64 + align_of::<u32>() - 1).unwrap();
let mut arena = Arena::new(64 + align_of::<u32>() - 1);
for _ in 0..10 {
for _ in 0..16 {
assert!(arena.alloc(0u32).is_some());
@@ -305,7 +237,6 @@ mod tests {
#[test]
fn panics_leave_the_arena_coherent() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
assert_ref_unwind_safe::<Arena>();
@@ -316,7 +247,7 @@ mod tests {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
let mut arena = Arena::new(1024);
let cell = ArenaCell::new();
let result = std::panic::catch_unwind(|| {
let (_, weak) = arena.alloc(Probe("pre-panic".into())).unwrap();
@@ -331,84 +262,8 @@ mod tests {
assert!(arena.alloc(0u32).is_some(), "the arena stays usable");
}
#[test]
fn a_panicking_destructor_leaves_no_resolvable_handle() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
panic!("payload destructor");
}
}
let mut arena = Arena::new(1024).unwrap();
let cell = ArenaCell::new();
let (_, weak) = arena.alloc(Bomb).unwrap();
cell.store(weak);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
assert!(unwound.is_err(), "the panic must propagate out of reset");
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
}
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
/// is never observed by a concurrently constructing test.
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
#[test]
fn an_exhausted_reset_parks_the_arena_and_refuses_handles() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let mut arena = Arena::new(1024).unwrap();
let (_, weak) = arena.alloc(41u32).unwrap();
let restore = NEXT_GENERATION.swap(GENERATION_MASK + 1, Ordering::Relaxed);
assert!(!arena.reset(), "an exhausted counter must report failure");
NEXT_GENERATION.store(restore, Ordering::Relaxed);
assert_eq!(weak.upgrade(&arena), None, "a parked arena resolves no handle");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&arena), None, "not even the null handle");
assert!(arena.alloc(0u32).is_none(), "a parked arena refuses allocation");
}
#[test]
fn the_generation_counter_rewinds_only_without_live_arenas() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let arena = Arena::new(64).unwrap();
assert!(!unsafe { reset_generation_counter() }, "a live arena must block the rewind");
drop(arena);
}
#[test]
fn handles_do_not_upgrade_against_a_foreign_arena() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (_, weak) = first.alloc(41u32).unwrap();
assert_eq!(weak.upgrade(&first), Some(&41));
assert_eq!(weak.upgrade(&second), None, "a handle must not resolve against another arena");
assert_eq!(ArenaWeak::<u32>::NULL.upgrade(&second), None, "the null handle never upgrades");
}
#[test]
fn reset_drops_dependents_before_their_dependencies() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static ORDER: Mutex<Vec<u32>> = Mutex::new(Vec::new());
struct Probe(u32);
impl Drop for Probe {
fn drop(&mut self) {
ORDER.lock().unwrap().push(self.0);
}
}
let mut arena = Arena::new(1024).unwrap();
for id in 0..3 {
arena.alloc(Probe(id)).unwrap();
}
arena.reset();
assert_eq!(*ORDER.lock().unwrap(), vec![2, 1, 0], "later allocations may borrow earlier ones, so they drop first");
}
#[test]
fn drop_glue_runs_on_reset() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
static DROPS: AtomicU32 = AtomicU32::new(0);
struct Probe(#[allow(dead_code)] String);
impl Drop for Probe {
@@ -416,7 +271,7 @@ mod tests {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
let mut arena = Arena::new(1024).unwrap();
let mut arena = Arena::new(1024);
arena.alloc(Probe("owns heap".into())).unwrap();
arena.alloc(Probe("me too".into())).unwrap();
assert_eq!(DROPS.load(Ordering::Relaxed), 0);
@@ -1,310 +0,0 @@
//! 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>();
}
}
+31 -116
View File
@@ -199,63 +199,17 @@ impl ContextFeatures {
pub struct ContextDependencies {
pub extract: ContextFeatures,
pub inject: ContextFeatures,
#[cfg_attr(feature = "serde", serde(default, deserialize_with = "deserialize_sorted_sources"))]
sources: Vec<SourceId>,
}
impl ContextDependencies {
pub fn new(extract: ContextFeatures, inject: ContextFeatures) -> Self {
Self { extract, inject, sources: Vec::new() }
}
pub fn sources(&self) -> &[SourceId] {
&self.sources
}
pub fn add_sources(&mut self, sources: &[SourceId]) {
merge_sorted_sources(&mut self.sources, sources);
}
pub fn from_sources(sources: &[SourceId]) -> Self {
let mut dependencies = Self::default();
dependencies.add_sources(sources);
dependencies
}
/// Must stay sorted.
#[cfg_attr(feature = "serde", serde(default))]
pub sources: Vec<SourceId>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, graphene_hash::CacheHash, dyn_any::DynAny, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ContextModification {
pub features: ContextFeatures,
#[cfg_attr(feature = "serde", serde(deserialize_with = "deserialize_sorted_sources"))]
sources: Vec<SourceId>,
}
impl ContextModification {
pub fn sources(&self) -> &[SourceId] {
&self.sources
}
pub fn add_sources(&mut self, sources: &[SourceId]) {
merge_sorted_sources(&mut self.sources, sources);
}
pub fn from_sources(features: ContextFeatures, sources: &[SourceId]) -> Self {
let mut modification = Self { features, sources: Vec::new() };
modification.add_sources(sources);
modification
}
}
/// Restores the sorted-and-deduplicated invariant that `contains` and `difference`
/// rely on for binary search, which arbitrary serialized input can violate.
#[cfg(feature = "serde")]
fn deserialize_sorted_sources<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<SourceId>, D::Error> {
use serde::Deserialize;
let mut sources = Vec::deserialize(deserializer)?;
sources.sort_unstable();
sources.dedup();
Ok(sources)
/// Must stay sorted.
pub sources: Vec<SourceId>,
}
impl core::ops::BitOrAssign<&ContextModification> for ContextModification {
@@ -285,12 +239,10 @@ impl core::ops::BitAndAssign<ContextFeatures> for ContextModification {
impl ContextModification {
pub fn contains(&self, other: &Self) -> bool {
debug_assert!(self.sources.is_sorted() && other.sources.is_sorted());
self.features.contains(other.features) && other.sources.iter().all(|id| self.sources.binary_search(id).is_ok())
}
pub fn difference(&self, other: &Self) -> Self {
debug_assert!(other.sources.is_sorted());
Self {
features: self.features.difference(other.features),
sources: self.sources.iter().copied().filter(|id| other.sources.binary_search(id).is_err()).collect(),
@@ -302,12 +254,12 @@ impl ContextModification {
}
}
/// Sorts and deduplicates unconditionally, so the result is ordered no matter what
/// order the inputs arrived in.
pub fn merge_sorted_sources(sources: &mut Vec<SourceId>, other: &[SourceId]) {
sources.extend_from_slice(other);
sources.sort_unstable();
sources.dedup();
for &id in other {
if let Err(insert_at) = sources.binary_search(&id) {
sources.insert(insert_at, id);
}
}
}
impl From<&[ContextFeature]> for ContextDependencies {
@@ -782,8 +734,8 @@ pub struct CtxSnapshot {
real_time: Option<f64>,
animation_time: Option<f64>,
pointer_position: Option<DVec2>,
index: Option<Vec<usize>>,
positions: Option<Vec<DVec2>>,
index: Vec<usize>,
positions: Vec<DVec2>,
varargs: Vec<Vec<OwnedSlot>>,
generations: Vec<(SourceId, u64)>,
}
@@ -798,8 +750,8 @@ impl CtxSnapshot {
real_time: ctx.try_real_time(),
animation_time: ctx.try_animation_time(),
pointer_position: ctx.try_pointer_position(),
index: ctx.try_index().map(|levels| levels.collect()),
positions: ctx.try_position().map(|positions| positions.collect()),
index: ctx.try_index().map(|levels| levels.collect()).unwrap_or_default(),
positions: ctx.try_position().map(|positions| positions.collect()).unwrap_or_default(),
varargs: std::iter::successors(ctx.varargs_head(), |link| link.outer)
.map(|link| link.args.iter().map(|slot| slot.clone_slot()).collect())
.collect(),
@@ -810,6 +762,10 @@ impl CtxSnapshot {
pub fn generations(&self) -> &[(SourceId, u64)] {
&self.generations
}
pub fn scope<'s>(&'s self, arena: &'s Arena) -> EvalScope<'s> {
EvalScope::new(self.real_time, self.animation_time, self.pointer_position, &self.generations, arena)
}
}
impl ExtractFootprint for CtxSnapshot {
@@ -838,13 +794,13 @@ impl ExtractPointerPosition for CtxSnapshot {
impl ExtractIndex for CtxSnapshot {
fn try_index(&self) -> Option<impl Iterator<Item = usize>> {
self.index.as_ref().map(|levels| levels.iter().copied())
Some(self.index.iter().copied())
}
}
impl ExtractPosition for CtxSnapshot {
fn try_position(&self) -> Option<impl Iterator<Item = DVec2>> {
self.positions.as_ref().map(|positions| positions.iter().copied())
Some(self.positions.iter().copied())
}
}
@@ -989,21 +945,6 @@ impl<'a> ContextImpl<'a> {
..*self
}
}
/// The promote half of decompose-and-promote: derives the context for the
/// content of one copy at a pushed structure level. `copy` becomes the
/// enclosing level's index (held in `frame`, which the caller owns for the
/// derived context's scope) and `inner` is the content's lane within that
/// copy. The structure node computes `copy`/`inner` from its own
/// extent-driven decomposition of the current lane.
pub fn push_level<'s>(&self, frame: &'s mut IndexLink<'s>, copy: u64, inner: u64) -> ContextImpl<'s>
where
'a: 's,
{
frame.index = copy;
frame.outer = self.index.outer;
self.promoted(frame, inner)
}
}
impl Ctx for ContextImpl<'_> {}
@@ -1184,7 +1125,7 @@ mod context_impl_tests {
#[test]
fn equal_contexts_hash_equal() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [(0, 1), (1, 3)];
let scope = scope_fixture(&generations, &arena);
let a = ContextImpl::root(&scope);
@@ -1194,7 +1135,7 @@ mod context_impl_tests {
#[test]
fn each_axis_changes_the_hash() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [(0, 1)];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1218,7 +1159,7 @@ mod context_impl_tests {
#[test]
fn index_level_order_matters() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1236,7 +1177,7 @@ mod context_impl_tests {
#[test]
fn axis_boundaries_are_unambiguous() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1254,7 +1195,7 @@ mod context_impl_tests {
#[test]
fn retain_scopes_generation_invalidation() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let initial = [(0, 1), (1, 3)];
let bumped_unretained = [(0, 2), (1, 3)];
let bumped_retained = [(0, 1), (1, 4)];
@@ -1270,7 +1211,7 @@ mod context_impl_tests {
#[test]
fn excluding_keys_ignore_own_source_bumps() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let initial = [(7, 1), (9, 5)];
let own_bumped = [(7, 2), (9, 5)];
let other_bumped = [(7, 1), (9, 6)];
@@ -1285,7 +1226,7 @@ mod context_impl_tests {
#[test]
fn unretained_scope_sees_every_bump() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let initial = [(0, 1)];
let bumped = [(0, 2)];
let hash_with = |generations: &[(SourceId, u64)]| {
@@ -1297,7 +1238,7 @@ mod context_impl_tests {
#[test]
fn set_index_is_visible_and_keeps_outer_levels() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1310,7 +1251,7 @@ mod context_impl_tests {
#[test]
fn vararg_chain_concatenates_innermost_first() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1341,7 +1282,7 @@ mod context_impl_tests {
#[test]
fn snapshot_captures_vararg_levels() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -1384,35 +1325,9 @@ mod context_impl_tests {
assert!(matches!(empty.vararg(0), Err(VarArgsResult::NoVarArgs)));
}
#[test]
fn sources_are_normalized_regardless_of_insertion_order() {
let mut dependencies = ContextDependencies::default();
dependencies.add_sources(&[9, 3, 9]);
dependencies.add_sources(&[5, 1]);
assert_eq!(dependencies.sources(), &[1, 3, 5, 9]);
let modification = ContextModification::from_sources(ContextFeatures::empty(), &[7, 2, 7]);
assert_eq!(modification.sources(), &[2, 7]);
}
#[test]
fn a_snapshot_preserves_an_absent_position_axis() {
let arena = Arena::new(64).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
let absent = CtxSnapshot::capture(&root);
assert!(absent.try_position().is_none(), "capturing an unpositioned context must not invent a position stack");
let position = DVec2::new(1., 2.);
let positioned = CtxSnapshot::capture(&root.with_position(&PositionLink { position, outer: None }));
assert_eq!(positioned.try_position().map(|p| p.collect::<Vec<_>>()), Some(vec![position]));
}
#[test]
fn scope_arena_reaches_kernels_through_extract_arena() {
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -1,6 +1,6 @@
use crate::gpoll::Finality;
use std::cell::UnsafeCell;
use std::mem::{ManuallyDrop, MaybeUninit};
use std::mem::MaybeUninit;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
const SLOT_EMPTY: u8 = 0;
@@ -17,13 +17,6 @@ struct FrameSlot<T> {
value: UnsafeCell<MaybeUninit<T>>,
}
// SAFETY: the key CAS reserves a slot for one writer, and the Release store of its
// state publishes the value to every Acquire load in `lookup`, so concurrent access
// is ordered. Sharing the table hands out `&T` and drops `T` on whichever thread
// drops the table, which is what the `Send + Sync` bounds cover.
unsafe impl<T: Send + Sync, const CAP: usize> Sync for FrameTable<T, CAP> {}
unsafe impl<T: Send, const CAP: usize> Send for FrameTable<T, CAP> {}
pub enum Lookup<'t, T> {
Hit(Finality, &'t T),
Vacant(VacantSlot<'t, T>),
@@ -52,8 +45,8 @@ impl<T, const CAP: usize> FrameTable<T, CAP> {
}
pub fn lookup(&self, hash: u64) -> Lookup<'_, T> {
// Only hash 0 is remapped, so distinct hashes stay distinct keys.
let key = if hash == 0 { 1 } else { hash };
// Keys are forced odd so the empty sentinel (0) can never collide.
let key = hash | 1;
for probe in 0..CAP {
let slot = &self.slots[(key as usize).wrapping_add(probe) % CAP];
let stored = slot.key.load(Ordering::Acquire);
@@ -88,27 +81,18 @@ impl<T, const CAP: usize> Drop for FrameTable<T, CAP> {
impl<'t, T> VacantSlot<'t, T> {
pub fn publish(self, value: T, finality: Finality) -> &'t T {
let slot = ManuallyDrop::new(self).slot;
// SAFETY: the CAS in `lookup` reserved this slot exclusively for us and
// its state is still SLOT_EMPTY, so nobody reads the value yet.
let lent = unsafe { &*(*slot.value.get()).write(value) };
let lent = unsafe { &*(*self.slot.value.get()).write(value) };
let state = match finality {
Finality::AllFinal => SLOT_FINAL,
Finality::Partial => SLOT_PARTIAL,
};
slot.state.store(state, Ordering::Release);
self.slot.state.store(state, Ordering::Release);
lent
}
pub fn release(self) {
drop(self);
}
}
/// Frees the reservation, so an early return or panic between `lookup` and
/// `publish` cannot retire the slot for the rest of the table's life.
impl<T> Drop for VacantSlot<'_, T> {
fn drop(&mut self) {
self.slot.key.store(0, Ordering::Release);
}
}
@@ -139,33 +123,6 @@ mod tests {
assert!(matches!(table.lookup(7), Lookup::Vacant(_)));
}
#[test]
fn a_dropped_reservation_frees_the_slot() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(7) else { unreachable!() };
drop(slot);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an abandoned reservation must not retire the slot");
}
#[test]
fn neighboring_hashes_do_not_share_an_entry() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(6) else { unreachable!() };
slot.publish(600, Finality::AllFinal);
assert!(matches!(table.lookup(7), Lookup::Vacant(_)), "an even hash must not answer for its odd neighbor");
}
#[test]
fn the_zero_hash_round_trips() {
let table = FrameTable::<u32, 8>::new();
let Lookup::Vacant(slot) = table.lookup(0) else { unreachable!() };
slot.publish(11, Finality::AllFinal);
let Lookup::Hit(_, value) = table.lookup(0) else {
panic!("the remapped sentinel hash must still hit");
};
assert_eq!(*value, 11);
}
#[test]
fn distinct_keys_probe_past_collisions_until_full() {
let table = FrameTable::<u32, 4>::new();
@@ -1,7 +1,6 @@
extern crate log;
pub mod arena;
pub mod attribute;
pub mod bounds;
pub mod consts;
pub mod context;
@@ -13,7 +12,6 @@ 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;
+34 -251
View File
@@ -6,49 +6,14 @@ use std::ops::Range;
#[derive(Debug)]
pub enum BatchStatus<'a, T> {
Lent(RecordBatch<'a, T>, Finality),
Filled(RecordBatch<'a, T>, Finality),
Lent(&'a [T], Finality),
Filled(&'a mut [T], Finality),
Pending,
Error(GraphError),
NeedBuffer,
InvalidRange,
}
/// Owns the initialized prefix of a caller-supplied scratch buffer, dropping every
/// lane unless [`FilledBatch::into_values`] hands the obligation back to the caller.
#[derive(Debug)]
pub struct FilledBatch<'a, T> {
values: &'a mut [T],
}
impl<'a, T> FilledBatch<'a, T> {
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
pub unsafe fn new(scratch: &'a mut [MaybeUninit<T>], len: usize) -> Self {
Self {
values: unsafe { assume_init_prefix_mut(scratch, len) },
}
}
pub fn values(&self) -> &[T] {
self.values
}
pub fn into_values(self) -> &'a mut [T] {
let mut guard = std::mem::ManuallyDrop::new(self);
std::mem::take(&mut guard.values)
}
}
impl<T> Drop for FilledBatch<'_, T> {
fn drop(&mut self) {
// SAFETY: every lane was initialized when the guard was built and none has
// been moved out, since `into_values` consumes the guard instead.
unsafe { std::ptr::drop_in_place(self.values as *mut [T]) }
}
}
/// # Safety
///
/// The first `len` elements of `scratch` must be initialized, and `len` must not exceed `scratch.len()`.
@@ -57,121 +22,6 @@ 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;
@@ -181,41 +31,19 @@ pub trait Node<Input> {
GPoll::Final(Extent::Free)
}
/// The count of items at one absolute nesting level (innermost `0`). The
/// leveled primitive a structure node overrides to report a pushed level's
/// size; the scalar base is one item at every level. Uncertainty rides the
/// `GPoll` status axis, as with [`extent`](Node::extent).
fn extent_at(&self, _input: &Input, _level: u8) -> GPoll<Extent> {
GPoll::Final(Extent::Exactly(1))
}
/// The node's domain depth (number of nesting levels; `0` = scalar), baked
/// into the record layout at wiring.
fn depth(&self) -> u8 {
self.layout().depth
}
/// Introspection access to node-resident records; `None` for ordinary nodes.
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
None
}
/// 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>
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
let Some(scratch) = scratch else {
return BatchStatus::NeedBuffer;
};
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
let Some(len) = range.end.checked_sub(range.start).map(|len| len as usize) else {
return BatchStatus::InvalidRange;
};
if scratch.len() < len {
@@ -248,7 +76,7 @@ pub trait Node<Input> {
}
}
// SAFETY: all `len` lanes were written by the loop above.
BatchStatus::Filled(RecordBatch::filled(unsafe { FilledBatch::new(scratch, len) }, self.layout()), finality)
BatchStatus::Filled(unsafe { assume_init_prefix_mut(scratch, len) }, finality)
}
}
@@ -266,19 +94,7 @@ where
(**self).extent(input)
}
fn extent_at(&self, input: &Input, level: u8) -> GPoll<Extent> {
(**self).extent_at(input, level)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
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>
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
@@ -300,19 +116,7 @@ where
(**self).extent(input)
}
fn extent_at(&self, input: &Input, level: u8) -> GPoll<Extent> {
(**self).extent_at(input, level)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
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>
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
@@ -334,19 +138,7 @@ where
(**self).extent(input)
}
fn extent_at(&self, input: &Input, level: u8) -> GPoll<Extent> {
(**self).extent_at(input, level)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
(**self).serialize()
}
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>
fn eval_batch<'a>(&self, input: &'a Input, range: Range<u64>, scratch: Option<&'a mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'a, Self::Output>
where
Input: InjectIndex + Copy,
{
@@ -447,6 +239,28 @@ impl<'a, N> LazyInput<'a, N> {
}
}
impl<'a, Input, N> Node<Input> for LazyInput<'a, N>
where
N: Node<Input>,
{
type Output = N::Output;
fn eval(&self, input: &Input) -> GPoll<Self::Output> {
self.node.eval(input)
}
fn extent(&self, input: &Input) -> GPoll<Extent> {
self.node.extent(input)
}
fn eval_batch<'b>(&self, input: &'b Input, range: Range<u64>, scratch: Option<&'b mut [MaybeUninit<Self::Output>]>) -> BatchStatus<'b, Self::Output>
where
Input: InjectIndex + Copy,
{
self.node.eval_batch(input, range, scratch)
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -478,42 +292,13 @@ 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(batch, finality) = status else {
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(*lane));
assert_eq!(got, vec![4, 6, 8, 10]);
assert_eq!(lanes, &[4, 6, 8, 10]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn a_dropped_filled_batch_reclaims_every_lane() {
static DROPS: AtomicU32 = AtomicU32::new(0);
#[derive(Clone)]
struct Probe;
impl Drop for Probe {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::Relaxed);
}
}
struct Probes;
impl Node<TestInput> for Probes {
type Output = Probe;
fn eval(&self, _input: &TestInput) -> GPoll<Probe> {
GPoll::Final(Probe)
}
}
let input = TestInput { index: 0 };
let mut scratch = [const { MaybeUninit::uninit() }; 3];
let status = Probes.eval_batch(&input, 0..3, Some(&mut scratch));
assert!(matches!(status, BatchStatus::Filled(..)));
drop(status);
assert_eq!(DROPS.load(Ordering::Relaxed), 3, "an unconsumed batch must not leak its lanes");
}
#[test]
fn probe_without_scratch_requests_a_buffer() {
let input = TestInput { index: 0 };
@@ -542,12 +327,10 @@ 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(batch, finality) = status else {
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
let mut got = Vec::new();
batch.for_each(|_, lane| got.push(*lane));
assert_eq!(got, vec![0, 1, 2, 3]);
assert_eq!(lanes, &[0, 1, 2, 3]);
assert_eq!(finality, Finality::Partial);
}
File diff suppressed because it is too large. Load diff
+26 -66
View File
@@ -20,8 +20,6 @@ pub struct NodeMetadata {
pub context_features: Vec<ContextFeature>,
pub memoize: bool,
pub inject_scope: bool,
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
pub async_source_fields: bool,
}
// Translation struct between macro and definition
@@ -74,12 +72,10 @@ 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 ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>> + Send + Sync;
pub type ErasedLendNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = &'c T> + Send + Sync;
#[cfg(target_family = "wasm")]
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>, Output = crate::record::RecordValue<'c>>;
pub type ErasedLendNode<T> = dyn for<'c> Node<ContextImpl<'c>, Output = &'c T>;
#[cfg(not(target_family = "wasm"))]
type DynEdge = dyn std::any::Any + Send + Sync;
@@ -90,17 +86,8 @@ pub fn edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), 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 lend_edge_type<T: 'static>() -> Type {
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Ref(Box::new(concrete!(T)))))
}
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
@@ -113,7 +100,6 @@ 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> {
@@ -147,22 +133,9 @@ 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.
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
unsafe { self.ptr.as_ref() }.eval(input)
}
fn extent(&self, input: &Input) -> crate::gpoll::GPoll<crate::gpoll::Extent> {
@@ -170,22 +143,12 @@ where
unsafe { self.ptr.as_ref() }.extent(input)
}
fn extent_at(&self, input: &Input, level: u8) -> crate::gpoll::GPoll<crate::gpoll::Extent> {
// SAFETY: as in eval.
unsafe { self.ptr.as_ref() }.extent_at(input, level)
}
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
// SAFETY: as in eval.
unsafe { self.ptr.as_ref() }.serialize()
}
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>
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>
where
Input: crate::context::InjectIndex + Copy,
{
@@ -198,7 +161,6 @@ 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,
}
@@ -220,8 +182,8 @@ impl EdgeHandle {
Self::new_erased(node, 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_ref<T: 'static>(node: std::sync::Arc<ErasedLendNode<T>>) -> Self {
Self::new_erased(node, lend_edge_type::<T>())
}
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
@@ -233,7 +195,6 @@ 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,
}
}
@@ -247,7 +208,6 @@ impl EdgeHandle {
node: (self.share)(&*self.node),
share: self.share,
serialize: self.serialize,
layout: self.layout,
ty: self.ty.clone(),
}
}
@@ -256,16 +216,12 @@ 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_record<T: 'static>(self) -> Result<SharedEdge<ErasedRecordNode>, ConstructionError> {
self.downcast_erased(record_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_erased<N: ?Sized + 'static>(self, expected: Type) -> Result<SharedEdge<N>, ConstructionError> {
@@ -283,10 +239,6 @@ pub type NodeConstructor = fn(Vec<EdgeHandle>) -> Result<EdgeHandle, Constructio
pub struct RegistryEntry {
pub io: NodeIOTypes,
pub constructor: NodeConstructor,
/// Declarative record-io metadata for the compiler layout pass; `None` for
/// nodes whose layout the pass does not yet fold (routing/opaque, hand-written
/// rows), which keep the construction-time path.
pub layout_meta: Option<crate::record::LayoutMeta>,
}
pub fn construct(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
@@ -381,14 +333,14 @@ mod tests {
type ErasedSplitEdge = dyn for<'c> Node<ContextImpl<'c>, Output = SplitBorrow<'c>> + Send + Sync;
let arena = Arena::new(4096).unwrap();
let arena = Arena::new(4096);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let node: Arc<ErasedSplitEdge> = Arc::new(SplitNode {
content: LendNode("held".to_string()),
});
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 handle = EdgeHandle::new_erased(node, concrete!(SplitBorrow<'static>));
assert_eq!(*handle.ty(), concrete!(SplitBorrow<'static>));
@@ -439,7 +391,7 @@ mod tests {
}
}
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -491,7 +443,7 @@ mod tests {
}
}
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
@@ -511,7 +463,6 @@ mod tests {
Ok(EdgeHandle::new(Arc::new(ValueNode(0u32)) as Arc<ErasedNode<u32>>))
}
let entry = RegistryEntry {
layout_meta: None,
io: NodeIOTypes::new(concrete!(Context), concrete!(u32), vec![edge_type::<String>()]),
constructor: construct_strlen,
};
@@ -529,11 +480,20 @@ 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]
fn duplicated_edges_share_one_instance_and_outlive_each_other() {
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
+40 -193
View File
@@ -16,8 +16,7 @@ pub type DynRuntime = dyn Runtime + Send + Sync;
pub type DynRuntime = dyn Runtime;
pub trait Runtime {
/// Returns true when the future completed during the call, so its result is already observable.
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool;
fn spawn(&self, source: SourceId, future: SourceFuture);
}
#[derive(Clone)]
@@ -41,14 +40,7 @@ impl graphene_hash::CacheHash for RuntimeHandle {
}
pub trait Spawner {
/// Returns true when the task completed during the call, so its result is already observable.
fn spawn(&self, task: SourceFuture) -> bool;
}
/// Polls `task` once with a no-op waker, returning true if it completed.
pub fn poll_once(task: &mut SourceFuture) -> bool {
let mut context = std::task::Context::from_waker(std::task::Waker::noop());
task.as_mut().poll(&mut context).is_ready()
fn spawn(&self, task: SourceFuture);
}
#[cfg(not(target_family = "wasm"))]
@@ -62,21 +54,17 @@ pub type DynNotifier = dyn Fn() + Send + Sync;
pub type DynNotifier = dyn Fn();
impl<S: Spawner + ?Sized> Spawner for Box<S> {
fn spawn(&self, task: SourceFuture) -> bool {
fn spawn(&self, task: SourceFuture) {
(**self).spawn(task)
}
}
/// Polls each task once inline. Tasks that are not immediately ready never complete.
/// Dropped tasks never complete.
pub struct NoopSpawner;
impl Spawner for NoopSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
log::warn!("async source is not immediately ready and no host spawner is wired; the task is dropped");
false
fn spawn(&self, _task: SourceFuture) {
log::warn!("async source spawned before a host spawner is wired; the task is dropped");
}
}
@@ -141,26 +129,21 @@ impl<S> GraphRuntime<S> {
}
impl<S: Spawner> Runtime for GraphRuntime<S> {
fn spawn(&self, source: SourceId, mut future: SourceFuture) -> bool {
fn spawn(&self, source: SourceId, future: SourceFuture) {
let generations = Arc::clone(&self.generations);
let dirty = Arc::clone(&self.dirty);
let notifier = Arc::clone(&self.notifier);
let mut first = true;
self.spawner.spawn(Box::pin(std::future::poll_fn(move |task_context| {
let poll = future.as_mut().poll(task_context);
if poll.is_ready() && !first {
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(generation) = generations.get_mut(&source) {
*generation += 1;
dirty.store(true, Ordering::Release);
drop(generations);
let notifier = Arc::clone(&notifier.lock().unwrap_or_else(PoisonError::into_inner));
notifier();
}
self.spawner.spawn(Box::pin(async move {
future.await;
let mut generations = generations.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(generation) = generations.get_mut(&source) {
*generation += 1;
dirty.store(true, Ordering::Release);
drop(generations);
let notifier = Arc::clone(&notifier.lock().unwrap_or_else(PoisonError::into_inner));
notifier();
}
first = false;
poll
})))
}));
}
}
@@ -171,7 +154,6 @@ 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};
@@ -182,9 +164,8 @@ mod tests {
}
impl Runtime for MockRuntime {
fn spawn(&self, source: SourceId, future: SourceFuture) -> bool {
fn spawn(&self, source: SourceId, future: SourceFuture) {
self.futures.lock().unwrap().push((source, future));
false
}
}
@@ -208,34 +189,11 @@ mod tests {
}
impl Spawner for CollectSpawner {
fn spawn(&self, mut task: SourceFuture) -> bool {
if poll_once(&mut task) {
return true;
}
fn spawn(&self, task: SourceFuture) {
self.tasks.lock().unwrap().push(task);
false
}
}
struct YieldOnce(bool);
impl Future for YieldOnce {
type Output = ();
fn poll(mut self: Pin<&mut Self>, task_context: &mut std::task::Context<'_>) -> std::task::Poll<()> {
if self.0 {
return std::task::Poll::Ready(());
}
self.0 = true;
task_context.waker().wake_by_ref();
std::task::Poll::Pending
}
}
fn yield_once() -> YieldOnce {
YieldOnce(false)
}
impl CollectSpawner {
fn drain(&self) -> usize {
let tasks = std::mem::take(&mut *self.tasks.lock().unwrap());
@@ -258,19 +216,6 @@ 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(""))]
@@ -336,20 +281,13 @@ mod tests {
#[test]
fn async_source_spawns_once_and_lands_via_the_slot() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(SlowDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(7u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let graph = SlowDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(7u64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
@@ -363,20 +301,13 @@ mod tests {
#[test]
fn async_source_reports_the_placeholder_while_in_flight() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(PreviewDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(1u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let graph = PreviewDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(1u64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(-1.0));
runtime.drain();
@@ -385,20 +316,13 @@ mod tests {
#[test]
fn no_partial_maps_the_placeholder_frame_to_pending() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StrictDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(2u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let graph = StrictDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(2u64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
@@ -407,20 +331,13 @@ mod tests {
#[test]
fn prologue_runs_sync_and_spawns_once() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(StagedDoubleNode::new(
lifted(21.0f64),
lifted(RuntimeHandle(runtime.clone())),
lifted(8u64),
&element_layout::<f64>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let graph = StagedDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(8u64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
assert_eq!(STAGED_RUNS.load(Ordering::Relaxed), 1, "the prologue runs synchronously on the miss");
@@ -433,23 +350,14 @@ mod tests {
#[test]
fn prologue_interrupt_defers_the_spawn() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let gate = Arc::new(std::sync::atomic::AtomicBool::new(false));
let runtime = Arc::new(MockRuntime::default());
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>(),
));
let graph = StagedSumNode::new(SourceNode(40.0f64), GatedSource(gate.clone(), 2.0), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(9u64));
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");
@@ -461,7 +369,7 @@ mod tests {
#[test]
fn async_kernels_read_captured_varargs() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -473,14 +381,7 @@ mod tests {
let ctx = root.with_varargs(&link);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<f64, _>(SnapshotVarargNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(5u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let graph = SnapshotVarargNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(5u64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
@@ -489,7 +390,7 @@ mod tests {
#[test]
fn async_kernels_read_the_captured_context_snapshot() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let root = ContextImpl::root(&scope);
@@ -497,14 +398,7 @@ mod tests {
let ctx = root.with_footprint(&footprint);
let runtime = Arc::new(MockRuntime::default());
let graph = extract::<u32, _>(SnapshotResolutionNode::new(
lifted(()),
lifted(RuntimeHandle(runtime.clone())),
lifted(3u64),
&element_layout::<()>(),
&element_layout::<RuntimeHandle>(),
&element_layout::<u64>(),
));
let graph = SnapshotResolutionNode::new(SourceNode(()), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(3u64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Pending);
runtime.drain();
@@ -516,7 +410,7 @@ mod tests {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
assert_eq!(runtime.snapshot(), vec![(7, 0)], "no bump before the future completes");
assert!(!runtime.take_dirty());
@@ -537,7 +431,7 @@ mod tests {
observed.store(dirty_at_notify.load(Ordering::Acquire), Ordering::Relaxed);
}));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
assert_eq!(runtime.spawner().drain(), 1);
assert!(observed_dirty.load(Ordering::Relaxed), "the notifier must observe the dirty flag already set");
}
@@ -550,7 +444,7 @@ mod tests {
let flag = Arc::clone(&notified);
runtime.set_notifier(Arc::new(move || flag.store(true, Ordering::Relaxed)));
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
assert!(!notified.load(Ordering::Relaxed));
@@ -561,7 +455,7 @@ mod tests {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
runtime.retain_sources(&[]);
assert_eq!(runtime.spawner().drain(), 1);
@@ -573,7 +467,7 @@ mod tests {
fn retain_sources_preserves_live_generations() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
Runtime::spawn(&runtime, 7, Box::pin(yield_once()));
Runtime::spawn(&runtime, 7, Box::pin(async {}));
runtime.spawner().drain();
runtime.retain_sources(&[7, 9]);
@@ -585,62 +479,15 @@ mod tests {
#[node_macro::node(category(""))]
async fn epilogue_double(_: impl Ctx, value: f64) -> f64 {
yield_once().await;
value * 2.
}
#[node_macro::node(category(""))]
async fn inline_double(_: impl Ctx, value: f64) -> f64 {
value * 2.
}
#[test]
fn an_immediately_ready_task_completes_inline_without_invalidating() {
let runtime = GraphRuntime::new(CollectSpawner::default());
runtime.retain_sources(&[7]);
assert!(Runtime::spawn(&runtime, 7, Box::pin(async {})));
assert_eq!(runtime.spawner().drain(), 0);
assert_eq!(runtime.snapshot(), vec![(7, 0)], "inline completion must not bump the generation");
assert!(!runtime.take_dirty());
}
#[test]
fn an_immediately_ready_kernel_returns_final_on_the_first_eval() {
let arena = Arena::new(64).unwrap();
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[13]);
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);
let ctx = ContextImpl::root(&scope);
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(42.0));
assert!(!runtime.take_dirty());
assert_eq!(runtime.snapshot(), vec![(13, 0)]);
assert_eq!(runtime.spawner().drain(), 0);
}
#[test]
fn a_source_slot_lands_through_the_runtime_while_downstream_keys_invalidate() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let runtime = Arc::new(GraphRuntime::new(CollectSpawner::default()));
runtime.retain_sources(&[11]);
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 graph = EpilogueDoubleNode::new(SourceNode(21.0f64), SourceNode(RuntimeHandle(runtime.clone())), SourceNode(11u64));
let snapshot = runtime.snapshot();
let scope = EvalScope::new(None, None, None, &snapshot, &arena);
+8 -9
View File
@@ -235,8 +235,7 @@ pub enum Type {
Fn(Box<Type>, Box<Type>),
/// Represents a future which promises to return the inner type.
Future(Box<Type>),
/// A packed record wire over the element type; the layout stays node-resident metadata.
Record(Box<Type>),
Ref(Box<Type>),
}
impl Default for Type {
@@ -310,7 +309,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.size),
Self::Fn(_, _) => None,
Self::Future(_) => None,
Self::Record(_) => None,
Self::Ref(_) => None,
}
}
@@ -320,7 +319,7 @@ impl Type {
Self::Concrete(ty) => Some(ty.align),
Self::Fn(_, _) => None,
Self::Future(_) => None,
Self::Record(_) => None,
Self::Ref(_) => None,
}
}
@@ -330,7 +329,7 @@ impl Type {
Self::Concrete(_) => self,
Self::Fn(_, output) => output.nested_type(),
Self::Future(output) => output.nested_type(),
Self::Record(inner) => inner.nested_type(),
Self::Ref(inner) => inner.nested_type(),
}
}
@@ -343,7 +342,7 @@ impl Type {
Self::Concrete(_) => None,
Self::Fn(_, output) => output.replace_nested(f),
Self::Future(output) => output.replace_nested(f),
Self::Record(inner) => inner.replace_nested(f),
Self::Ref(inner) => inner.replace_nested(f),
}
}
@@ -353,7 +352,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::Record(ty) => ty.identifier_name(),
Type::Ref(ty) => ty.identifier_name(),
}
}
}
@@ -368,7 +367,7 @@ pub fn simplify_identifier_name(ty: &str) -> String {
/// Converts a Rust-internal type name to its user-facing form.
pub fn make_type_user_readable(ty: &str) -> String {
let ty = ty
.replace("ContextImpl", "Context")
.replace("Option<Arc<OwnedContextImpl>>", "Context")
.replace("Raster<CPU>", "Raster")
.replace("Raster<GPU>", "Raster")
.replace("DAffine2", "Transform")
@@ -448,7 +447,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::Record(ty) => write!(f, "{ty}"),
Type::Ref(ty) => write!(f, "{ty}"),
}
}
}
@@ -13,43 +13,6 @@ 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)
@@ -5,7 +5,7 @@ use core_types::shaders::buffer_struct::BufferStruct;
use raster_types::{GPU, Raster};
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::{Mutex, PoisonError};
use std::sync::Mutex;
use wgpu::util::{BufferInitDescriptor, DeviceExt};
use wgpu::{
BindGroupDescriptor, BindGroupEntry, BindGroupLayoutDescriptor, BindGroupLayoutEntry, BindingResource, BindingType, Buffer, BufferBinding, BufferBindingType, BufferUsages, ColorTargetState, Face,
@@ -34,7 +34,7 @@ impl PerPixelAdjustShaderRuntime {
impl ShaderRuntime {
pub fn run_per_pixel_adjust<T: BufferStruct>(&self, shaders: &Shaders<'_>, textures: List<Raster<GPU>>, args: Option<&T>) -> List<Raster<GPU>> {
let mut cache = self.per_pixel_adjust.pipeline_cache.lock().unwrap_or_else(PoisonError::into_inner);
let mut cache = self.per_pixel_adjust.pipeline_cache.lock().unwrap();
let pipeline = cache
.entry(shaders.fragment_shader_name.to_owned())
.or_insert_with(|| PerPixelAdjustGraphicsPipeline::new(&self.context, shaders));
File diff suppressed because it is too large. Load diff
@@ -1,653 +0,0 @@
use super::*;
/// How a record node's primary input lowers: `None` writes a fresh record,
/// `Token` carries the element bytes through as `ElToken`, `Read` reads a
/// concrete element at offset 0. The element and write set fold from the IR.
#[derive(Clone)]
pub(crate) enum RecordCarrier {
None,
Token,
Read,
}
/// A well-formed record-io node: only the carrier form is retained, so
/// [`skips_carrier`] can gate the fresh-record path. Malformed record io yields
/// `None` from [`record_shape`] and generates no node impl.
#[derive(Clone)]
pub(crate) struct RecordShape {
pub(crate) carrier: RecordCarrier,
}
impl RecordShape {
pub(crate) fn skips_carrier(&self) -> bool {
matches!(self.carrier, RecordCarrier::None)
}
}
/// The effect/return axis of a node's kernel, resolved once from the signature.
/// It selects the eval tail (finish / merge / spawn) and the kernel signature
/// wrapping across every node kind.
#[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 dialect of a node fn that lowers to a `Node` impl, or `None` when no
/// lowering supports the signature (an async node with lazy inputs, malformed
/// record io, or a shape no kind accepts). The kind itself is derived from the
/// intent IR ([`crate::codegen::ir::node_kind`]); this only gates support.
pub(crate) fn analyze(parsed: &ParsedNodeFn) -> Option<Dialect> {
if parsed.is_async && parsed.fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_))) {
return None;
}
let supported = if record_shape(parsed).is_some() {
true
} else if has_record_io(parsed) {
return None;
} else {
routing_io(parsed).is_some() || record_flip(parsed) || record_opaque(parsed)
};
supported.then(|| dialect(parsed))
}
/// 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], generic: &Ident) -> 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(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], skips_carrier: bool) -> Vec<usize> {
regular_fields
.iter()
.enumerate()
.filter(|(index, field)| !field.attribute_reads.is_empty() && (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 token = match ty {
Type::Tuple(tuple) if tuple.elems.is_empty() => None,
ty => match implementations.is_empty().then(|| unbounded_generic(parsed, ty)).flatten() {
Some(token) => Some(token),
None => {
if contains_open_generic(parsed, ty) {
return None;
}
None
}
},
};
let carrier = match ty {
Type::Tuple(tuple) if tuple.elems.is_empty() => RecordCarrier::None,
_ if token.is_some() => RecordCarrier::Token,
_ => RecordCarrier::Read,
};
let (element, _, removes) = match writes {
Some(RecordWrites { element, markers, removes }) => (element, markers, removes),
None => (value, Vec::new(), Vec::new()),
};
match &token {
Some(token) => {
if !matches!(bare_ident(&element), Some(ident) if ident == token) {
return None;
}
}
None => {
if contains_open_generic(parsed, &element) {
return None;
}
}
}
if matches!(carrier, RecordCarrier::None) && !removes.is_empty() {
return None;
}
Some(RecordShape { carrier })
}
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>)
}
@@ -1,396 +0,0 @@
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, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
if !data_field_generic_idents.is_empty() {
return quote!();
}
match crate::codegen::ir::node_kind(&crate::codegen::ir::build(parsed)) {
crate::codegen::ir::NodeKind::Flip => flip_entries_tokens(parsed, struct_name, regular_fields),
_ => single_row_entries(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();
let node = crate::codegen::ir::build(parsed);
let core_types = quote!(gcore);
// 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,)
});
let element_spec = quote!(gcore::record::ElementSpec::Concrete(gcore::record::element_write::<#row_output>()));
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, &core_types);
Some(quote! {
gcore::registry::RegistryEntry {
layout_meta: Some(#layout_meta),
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),*]
}
}
}
/// Which record wire an input claims and how its value is recovered. Base slots
/// are the record edges whose layouts form the output; value slots are record
/// edges read for their layout; plain and lazy slots are ordinary edges.
enum SlotKind {
/// A generic record edge whose element is only known at runtime; the runtime
/// type is captured for the output wrap or the union.
BaseGeneric(String),
/// A concrete record carrier read for its layout.
BaseConcrete(Type),
/// A concrete record edge read for its layout only.
Value(Type),
/// A plain value edge.
Plain(Type),
/// A lazy node edge.
Lazy(Type),
}
impl SlotKind {
fn is_base(&self) -> bool {
matches!(self, SlotKind::BaseGeneric(_) | SlotKind::BaseConcrete(_))
}
}
/// The single registry row shared by record-io, routing, and opaque nodes: one
/// instance covers the wire, each input's edge type and downcast follow its
/// slot, and the output layout folds from the base slots.
fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
use crate::codegen::ir;
let fn_name = &parsed.fn_name;
let node = ir::build(parsed);
let core_types = quote!(gcore);
let lend = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }));
// A subject is its record edge (concrete carrier or erased generic); a
// non-subject value rides a record edge when it reads its layout, else plain.
let slots: Vec<SlotKind> = regular_fields
.iter()
.enumerate()
.map(|(index, field)| {
let input = &node.inputs[index];
if input.subject {
return match &input.shape.element {
ir::Element::Concrete(ty) => SlotKind::BaseConcrete(ty.clone()),
ir::Element::Generic(ident) => SlotKind::BaseGeneric(ident.to_string()),
ir::Element::Opaque => SlotKind::BaseGeneric("T".to_string()),
};
}
match &field.ty {
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => SlotKind::Lazy(output_type.clone()),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => match ir::value_binding(&node, index) {
ir::ValueBinding::ReadingSecondary | ir::ValueBinding::RecordElement => SlotKind::Value(ty.clone()),
_ => SlotKind::Plain(ty.clone()),
},
}
})
.collect();
// Every non-base value/plain/lazy input must be concrete.
let values_concrete = regular_fields.iter().zip(&slots).all(|(field, slot)| match slot {
SlotKind::BaseGeneric(_) | SlotKind::BaseConcrete(_) => true,
SlotKind::Value(ty) | SlotKind::Plain(ty) | SlotKind::Lazy(ty) => !contains_open_generic(parsed, ty) && (lend(field) || !type_disqualifies(ty)),
});
if !values_concrete {
return quote!();
}
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 = slots.iter().map(|slot| match slot {
SlotKind::BaseGeneric(name) => quote!(gcore::registry::generic_record_edge_type(#name)),
SlotKind::BaseConcrete(ty) | SlotKind::Value(ty) => quote!(gcore::registry::record_edge_type::<#ty>()),
SlotKind::Plain(ty) | SlotKind::Lazy(ty) => quote!(gcore::registry::edge_type::<#ty>()),
});
let downcasts = names.iter().zip(&slots).enumerate().map(|(index, (name, slot))| {
let handle = format_ident!("__handle_{index}");
let layout = format_ident!("__layout_{index}");
let ty = format_ident!("__ty_{index}");
match slot {
SlotKind::BaseGeneric(_) | SlotKind::BaseConcrete(_) => 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())?;
},
SlotKind::Value(value_ty) => quote! {
let #handle = inputs.next().unwrap();
let Some(#layout) = #handle.layout().cloned() else {
return Err(gcore::registry::ConstructionError::MissingLayout);
};
let #name = #handle.downcast_record::<#value_ty>()?;
},
SlotKind::Plain(value_ty) | SlotKind::Lazy(value_ty) => quote!(let #name = inputs.next().unwrap().downcast::<#value_ty>()?;),
}
});
let base_indices: Vec<usize> = slots.iter().enumerate().filter(|(_, slot)| slot.is_base()).map(|(index, _)| index).collect();
let value_indices: Vec<usize> = slots.iter().enumerate().filter(|(_, slot)| matches!(slot, SlotKind::Value(_))).map(|(index, _)| index).collect();
let value_layout_args: Vec<TokenStream2> = value_indices
.iter()
.map(|index| {
let layout = format_ident!("__layout_{index}");
quote!(&#layout,)
})
.collect();
let carried_meta = || {
let meta = ir::layout_meta_tokens(&node, quote!(gcore::record::ElementSpec::Carried), &core_types);
quote!(Some(#meta))
};
// The output wire and node wrap follow the output element: a concrete element
// is a typed record; a generic or opaque element is an erased record carrying
// the first base slot's runtime type.
let (io_output, wrap) = match &node.output.shape.element {
ir::Element::Concrete(element) => (
quote!(gcore::registry::record_type::<#element>()),
quote!(Ok(gcore::registry::EdgeHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
),
element => {
let name = match element {
ir::Element::Generic(ident) => ident.to_string(),
_ => "T".to_string(),
};
let base_ty = format_ident!("__ty_{}", base_indices[0]);
(
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>, #base_ty))),
)
}
};
let (prelude, new_layout_args, layout_meta) = match ir::node_kind(&node) {
ir::NodeKind::RecordIo => {
let carrier_arg = node.inputs.first().is_some_and(|input| input.subject).then(|| quote!(&__layout_0,));
let layout_meta_fn = format_ident!("{}_layout_meta", fn_name);
(quote!(), quote!(#carrier_arg #(#value_layout_args)*), quote!(Some(self::#layout_meta_fn())))
}
ir::NodeKind::Routing => {
let source_layouts = base_indices.iter().map(|index| format_ident!("__layout_{index}"));
let source_wraps = base_indices.iter().map(|index| {
let name = names[*index];
let layout = format_ident!("__layout_{index}");
quote!(let #name = gcore::record::RecordSource::new(#name, &#layout, &__union);)
});
let prelude = quote! {
let __union = gcore::record::Layout::union(&[#(&#source_layouts),*]);
#(#source_wraps)*
};
(prelude, quote!(&__union, #(#value_layout_args)*), carried_meta())
}
ir::NodeKind::Opaque => {
let record_layout = format_ident!("__layout_{}", base_indices[0]);
(quote!(), quote!(&#record_layout), carried_meta())
}
ir::NodeKind::Flip => unreachable!("flip has its own multi-row emitter"),
};
quote! {
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
vec![gcore::registry::RegistryEntry {
layout_meta: #layout_meta,
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)*
#prelude
let __node = #struct_name::new(#(#names,)* #new_layout_args);
#wrap
},
}]
}
}
}
pub(crate) 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())
}
-760
View File
@@ -1,760 +0,0 @@
//! The intent IR: a node built from its signature, from which lowering derives.
#![allow(dead_code)]
use crate::codegen::classify::{
Dialect, RoutingIo, bare_ident, context_param, dialect, flip_carrier, generic_assignment, generic_extractable, is_record_value, record_shape, routing_io, slot_value_type,
};
use crate::codegen::entries::implementation_rows;
use crate::parsing::{AttributeRead, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RecordWrites, RegularParsedField, record_writes};
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{GenericArgument, GenericParam, Ident, PathArguments, Type, TypeParamBound};
pub(crate) fn build(parsed: &ParsedNodeFn) -> Node {
let generics = generics(parsed);
let generic_idents: Vec<Ident> = generics.iter().map(|generic| generic.ident.clone()).collect();
let fields: Vec<&ParsedField> = parsed.fields.iter().filter(|field| !field.is_data_field).collect();
Node {
kernel: Kernel { fn_name: parsed.fn_name.clone() },
monomorphizations: monomorphizations(parsed, &fields, &generic_idents),
inputs: inputs(parsed, &fields, &generic_idents),
output: output(parsed, &generic_idents),
generics,
effect: effect(parsed),
derives: derives(parsed),
}
}
fn derives(parsed: &ParsedNodeFn) -> bool {
context_param(parsed).is_some_and(|ctx| {
ctx.bounds
.iter()
.any(|bound| matches!(bound, TypeParamBound::Trait(trait_bound) if trait_bound.path.segments.last().is_some_and(|segment| segment.ident == "DeriveCtx")))
})
}
fn generics(parsed: &ParsedNodeFn) -> Vec<Generic> {
let ctx = context_param(parsed).map(|param| param.ident.clone());
parsed
.fn_generics
.iter()
.filter_map(|param| match param {
GenericParam::Type(param) if Some(&param.ident) != ctx.as_ref() => Some(Generic {
ident: param.ident.clone(),
bounds: param.bounds.iter().cloned().collect(),
}),
_ => None,
})
.collect()
}
fn inputs(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) -> Vec<Input> {
let routing = routing_io(parsed);
let carrier_subject = flip_carrier(parsed) || record_shape(parsed).map_or(false, |shape| !shape.skips_carrier());
fields
.iter()
.enumerate()
.map(|(index, &field)| {
let evaluation = match &field.ty {
ParsedFieldType::Node(_) => Evaluation::Lazy,
ParsedFieldType::Regular(_) => Evaluation::Eager,
};
Input {
ident: field.pat_ident.ident.clone(),
evaluation,
shape: item_shape(field_element_type(field), &field.attribute_reads, generics),
subject: subject(index, field, carrier_subject, routing.as_ref()),
lend: matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. })),
}
})
.collect()
}
fn subject(index: usize, field: &ParsedField, carrier_subject: bool, routing: Option<&RoutingIo>) -> bool {
match &field.ty {
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => is_record_value(output_type) || routing.is_some_and(|routing| bare_ident(output_type) == Some(&routing.generic)),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => routing.is_some_and(|routing| bare_ident(ty) == Some(&routing.generic)) || (index == 0 && carrier_subject),
}
}
fn output(parsed: &ParsedNodeFn, generics: &[Ident]) -> Output {
let value = slot_value_type(&parsed.output_type);
let (element, writes, removes) = match record_writes(&value) {
Some(RecordWrites { element, markers, removes }) => (element, markers, removes),
None => (value, Vec::new(), Vec::new()),
};
let (element, depth) = strip_ilist(&element);
Output {
shape: ItemShape {
element: element_of(&element, generics),
depth,
attrs: writes.into_iter().map(|marker| LevelAttr { marker, level: 0 }).collect(),
},
removes: removes.into_iter().map(|marker| LevelAttr { marker, level: 0 }).collect(),
}
}
fn monomorphizations(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) -> Vec<ImplRow> {
if generics.is_empty() {
return Vec::new();
}
let Some(rows) = implementation_rows(parsed, fields) else {
return Vec::new();
};
let positions: Option<Vec<(Ident, usize)>> = generics
.iter()
.map(|generic| fields.iter().position(|&field| generic_extractable(field_element_type(field), generic)).map(|index| (generic.clone(), index)))
.collect();
let Some(positions) = positions else {
return Vec::new();
};
rows.iter()
.filter_map(|row| {
let assignments = positions
.iter()
.map(|(generic, index)| generic_assignment(field_element_type(fields[*index]), &row[*index], generic).map(|ty| (generic.clone(), ty)))
.collect::<Option<Vec<_>>>()?;
Some(ImplRow { assignments })
})
.collect()
}
fn effect(parsed: &ParsedNodeFn) -> Effect {
match dialect(parsed) {
Dialect::Sync => Effect::Pure,
Dialect::Interrupt => Effect::Fallible,
Dialect::Poll => Effect::Progressive,
Dialect::AsyncFn | Dialect::Future | Dialect::FutureInterrupt => Effect::AsyncSource,
}
}
fn field_element_type(field: &ParsedField) -> &Type {
match &field.ty {
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
}
}
fn item_shape(element: &Type, reads: &[AttributeRead], generics: &[Ident]) -> ItemShape {
let (element, depth) = strip_ilist(element);
ItemShape {
element: element_of(&element, generics),
depth,
attrs: reads.iter().map(|read| LevelAttr { marker: read.marker.clone(), level: 0 }).collect(),
}
}
fn element_of(ty: &Type, generics: &[Ident]) -> Element {
if is_record_value(ty) {
return Element::Opaque;
}
match bare_ident(ty) {
Some(ident) if generics.contains(ident) => Element::Generic(ident.clone()),
_ => Element::Concrete(ty.clone()),
}
}
fn strip_ilist(ty: &Type) -> (Type, u8) {
let mut element = ty.clone();
let mut depth = 0;
while let Some(inner) = ilist_inner(&element) {
element = inner;
depth += 1;
}
(element, depth)
}
fn ilist_inner(ty: &Type) -> Option<Type> {
let Type::Path(path) = ty else { return None };
let segment = path.path.segments.last()?;
if segment.ident != "IList" {
return None;
}
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
args.args.iter().find_map(|arg| match arg {
GenericArgument::Type(inner) => Some(inner.clone()),
_ => None,
})
}
/// Emits the `LayoutMeta` literal from the IR. `element_spec` is supplied by the
/// caller since it is the one row-dependent facet; the rest folds from the node.
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
let sources = node.inputs.iter().enumerate().filter(|(_, input)| input.subject).map(|(index, _)| index as u8);
let reads = node.inputs.iter().enumerate().filter_map(|(index, input)| {
(matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty()).then(|| {
let descs = field_writes(&input.shape.attrs, core_types);
let index = index as u8;
quote!(#core_types::record::InputReads { input: #index, reads: ::std::vec![#(#descs),*] })
})
});
let writes = field_writes(&node.output.shape.attrs, core_types);
let removes = node.output.removes.iter().map(|attr| {
let marker = &attr.marker;
let level = attr.level;
quote!((<#marker as #core_types::attribute::Attribute>::NAME, #level))
});
let level_delta = level_delta(node);
quote! {
#core_types::record::LayoutMeta {
sources: ::std::vec![#(#sources),*],
reads: ::std::vec![#(#reads),*],
element: #element_spec,
writes: ::std::vec![#(#writes),*],
removes: ::std::vec![#(#removes),*],
level_delta: #level_delta,
}
}
}
fn field_writes(attrs: &[LevelAttr], core_types: &TokenStream2) -> Vec<TokenStream2> {
attrs
.iter()
.map(|attr| {
let marker = &attr.marker;
let level = attr.level;
quote!(#core_types::record::FieldWrite::of::<#marker>(#level))
})
.collect()
}
fn level_delta(node: &Node) -> i8 {
let subject_depth = node.inputs.iter().find(|input| input.subject).map_or(0, |input| input.shape.depth as i8);
node.output.shape.depth as i8 - subject_depth
}
/// How an eager value input binds in eval.
pub(crate) enum ValueBinding {
Carrier,
Lend,
ReadingSecondary,
RecordElement,
Plain,
}
/// How a lazy (`impl Node`) input binds in eval. The `Poll` effect further
/// selects the borrowed vs `__cell`-driven form within `Element`/`Plain`.
pub(crate) enum LazyBinding {
Element,
Plain,
DeriveRouting,
OpaqueRecord,
}
impl ValueBinding {
/// Copies an element out of a record edge, so the frame is reclaimed after.
pub(crate) fn reads_out(&self) -> bool {
matches!(self, ValueBinding::ReadingSecondary | ValueBinding::RecordElement)
}
}
#[derive(Clone, Copy)]
pub(crate) enum NodeKind {
Flip,
RecordIo,
Routing,
Opaque,
}
pub(crate) fn node_kind(node: &Node) -> NodeKind {
if matches!(node.output.shape.element, Element::Opaque) {
NodeKind::Opaque
} else if has_attr_io(node) {
NodeKind::RecordIo
} else if is_routing(node) {
NodeKind::Routing
} else {
NodeKind::Flip
}
}
/// Routing forwards an unbounded generic from a source whole; a bounded generic
/// or one transformed into a different output type works on the element and flips.
fn is_routing(node: &Node) -> bool {
let Element::Generic(output) = &node.output.shape.element else { return false };
node.monomorphizations.is_empty()
&& node.generics.iter().any(|generic| &generic.ident == output && generic.bounds.is_empty())
&& node.inputs.iter().any(|input| input.subject && matches!(&input.shape.element, Element::Generic(generic) if generic == output))
}
fn has_attr_io(node: &Node) -> bool {
// Reads on lazy inputs ride the flip; only eager reads make a record-io node.
node.inputs.iter().any(|input| matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty()) || !node.output.shape.attrs.is_empty() || !node.output.removes.is_empty()
}
pub(crate) fn value_binding(node: &Node, index: usize) -> ValueBinding {
let input = &node.inputs[index];
let kind = node_kind(node);
if matches!(kind, NodeKind::RecordIo | NodeKind::Flip) && index == 0 && input.subject {
ValueBinding::Carrier
} else if matches!(kind, NodeKind::Flip) && input.lend {
ValueBinding::Lend
} else if matches!(kind, NodeKind::RecordIo) && !input.shape.attrs.is_empty() {
ValueBinding::ReadingSecondary
} else if matches!(kind, NodeKind::Flip) || (matches!(kind, NodeKind::Routing) && !input.subject) {
ValueBinding::RecordElement
} else {
ValueBinding::Plain
}
}
pub(crate) fn lazy_binding(node: &Node, index: usize) -> LazyBinding {
let input = &node.inputs[index];
let kind = node_kind(node);
if node.derives && matches!(kind, NodeKind::Routing) && input.subject {
LazyBinding::DeriveRouting
} else if matches!(kind, NodeKind::Flip) {
LazyBinding::Element
} else if matches!(input.shape.element, Element::Opaque) {
LazyBinding::OpaqueRecord
} else {
LazyBinding::Plain
}
}
pub(crate) struct Node {
pub(crate) kernel: Kernel,
pub(crate) generics: Vec<Generic>,
/// Correlated rows (zipped `#[implementations]`, not crossed); empty = erased.
pub(crate) monomorphizations: Vec<ImplRow>,
pub(crate) inputs: Vec<Input>,
pub(crate) output: Output,
pub(crate) effect: Effect,
/// The context is derived (a `DeriveCtx` bound), so routing sources rebind it.
pub(crate) derives: bool,
}
/// The kernel fn the node wraps.
pub(crate) struct Kernel {
pub(crate) fn_name: Ident,
}
pub(crate) struct Generic {
pub(crate) ident: Ident,
pub(crate) bounds: Vec<TypeParamBound>,
}
/// One monomorphization: a concrete type per monomorphized generic.
pub(crate) struct ImplRow {
pub(crate) assignments: Vec<(Ident, Type)>,
}
pub(crate) struct Input {
pub(crate) ident: Ident,
pub(crate) evaluation: Evaluation,
pub(crate) shape: ItemShape,
/// This input's layout folds into the output.
pub(crate) subject: bool,
/// Written `&T`; the kernel borrows the evaluated element.
pub(crate) lend: bool,
}
/// `Lazy` = `impl Node<..>`, the kernel drives it.
pub(crate) enum Evaluation {
Eager,
Lazy,
}
pub(crate) struct Output {
pub(crate) shape: ItemShape,
pub(crate) removes: Vec<LevelAttr>,
}
/// An item's ranked layout; `attrs` are reads on an input, writes on the output.
pub(crate) struct ItemShape {
pub(crate) element: Element,
pub(crate) depth: u8,
pub(crate) attrs: Vec<LevelAttr>,
}
pub(crate) enum Element {
Concrete(Type),
/// Indexes [`Node::generics`].
Generic(Ident),
/// A whole erased record; the element type is unknown.
Opaque,
}
/// An attribute at a nesting level; `0` = innermost (the element's level).
pub(crate) struct LevelAttr {
pub(crate) marker: Type,
pub(crate) level: u8,
}
pub(crate) enum Effect {
Pure,
Fallible,
Progressive,
AsyncSource,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::codegen::classify::{Dialect, analyze, context_param, dialect, record_flip, record_opaque, unbounded_generic};
use crate::parsing::parse_node_fn;
use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, quote};
/// The layout facts every emitter expresses, derived from either the intent
/// IR or the resolved class, so the two paths can be checked equal.
#[derive(Debug, PartialEq)]
struct Facts {
sources: Vec<usize>,
carried: bool,
writes: Vec<String>,
removes: Vec<String>,
delta: i8,
}
fn markers<'a>(types: impl IntoIterator<Item = &'a Type>) -> Vec<String> {
types.into_iter().map(|ty| ty.to_token_stream().to_string()).collect()
}
fn facts_from_ir(node: &Node) -> Facts {
let carried = match &node.output.shape.element {
Element::Opaque => true,
Element::Generic(_) => node.monomorphizations.is_empty(),
Element::Concrete(_) => false,
};
let subject_depth = node.inputs.iter().find(|input| input.subject).map_or(0, |input| input.shape.depth as i8);
Facts {
sources: node.inputs.iter().enumerate().filter(|(_, input)| input.subject).map(|(index, _)| index).collect(),
carried,
writes: markers(node.output.shape.attrs.iter().map(|attr| &attr.marker)),
removes: markers(node.output.removes.iter().map(|attr| &attr.marker)),
delta: node.output.shape.depth as i8 - subject_depth,
}
}
/// The kinds a supported node resolves to, from the classify predicates in
/// `analyze`'s order; the frozen oracle the IR's `node_kind` must reproduce.
struct Kinds {
record_io: bool,
routing: bool,
flip: bool,
opaque: bool,
}
fn kinds(parsed: &ParsedNodeFn) -> Kinds {
let record_io = record_shape(parsed).is_some();
let routing = !record_io && routing_io(parsed).is_some();
let flip = !record_io && !routing && record_flip(parsed);
let opaque = !record_io && !routing && !flip && record_opaque(parsed);
Kinds { record_io, routing, flip, opaque }
}
fn skips_carrier(parsed: &ParsedNodeFn) -> bool {
record_shape(parsed).is_some_and(|shape| shape.skips_carrier())
}
fn routing_generic(parsed: &ParsedNodeFn) -> Option<Ident> {
kinds(parsed).routing.then(|| routing_io(parsed).map(|routing| routing.generic)).flatten()
}
fn token_carrier(parsed: &ParsedNodeFn) -> bool {
let element = record_writes(&slot_value_type(&parsed.output_type)).map_or_else(|| slot_value_type(&parsed.output_type), |writes| writes.element);
kinds(parsed).record_io && unbounded_generic(parsed, &element).is_some()
}
fn facts_from_signature(parsed: &ParsedNodeFn) -> Facts {
let fields: Vec<&ParsedField> = parsed.fields.iter().filter(|field| !field.is_data_field).collect();
let source_ty = |field: &ParsedField| match &field.ty {
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type.clone(),
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
};
let kinds = kinds(parsed);
if kinds.flip {
Facts {
sources: if flip_carrier(parsed) { vec![0] } else { vec![] },
carried: false,
writes: vec![],
removes: vec![],
delta: 0,
}
} else if kinds.opaque {
let record = fields.iter().position(|field| matches!(&field.ty, ParsedFieldType::Node(NodeParsedField { output_type, .. }) if is_record_value(output_type)));
Facts {
sources: record.into_iter().collect(),
carried: true,
writes: vec![],
removes: vec![],
delta: 0,
}
} else if kinds.routing {
let generic = routing_generic(parsed).expect("routing has a generic");
Facts {
sources: fields.iter().enumerate().filter(|(_, field)| bare_ident(&source_ty(field)) == Some(&generic)).map(|(index, _)| index).collect(),
carried: true,
writes: vec![],
removes: vec![],
delta: 0,
}
} else {
let (write_markers, removes) = record_writes(&slot_value_type(&parsed.output_type)).map_or((Vec::new(), Vec::new()), |writes| (writes.markers, writes.removes));
Facts {
sources: if skips_carrier(parsed) { vec![] } else { vec![0] },
carried: token_carrier(parsed),
writes: markers(write_markers.iter()),
removes: markers(removes.iter()),
delta: 0,
}
}
}
fn assert_bridge(attr: TokenStream2, item: TokenStream2) -> Node {
let mut parsed = parse_node_fn(attr, item).unwrap();
parsed.replace_impl_trait_in_input();
analyze(&parsed).expect("representative resolves to a supported node");
let node = build(&parsed);
assert_eq!(facts_from_ir(&node), facts_from_signature(&parsed));
node
}
#[test]
fn bridge_flip_concrete() {
assert_bridge(quote!(category("")), quote!(fn negate(_: impl Ctx, x: f64) -> f64 { -x }));
}
#[test]
fn bridge_flip_generic() {
assert_bridge(
quote!(category("")),
quote! {
fn add<A: core::ops::Add<B>, B>(_: impl Ctx, #[implementations(f64, u32)] augend: A, #[implementations(f64, u32)] addend: B) -> <A as core::ops::Add<B>>::Output { augend + addend }
},
);
}
#[test]
fn bridge_record_write() {
assert_bridge(quote!(category("")), quote!(fn set_opacity(_: impl Ctx, val: f64) -> (f64, Attr<Opacity>) { (val, Attr(1.)) }));
}
#[test]
fn bridge_record_remove() {
assert_bridge(quote!(category("")), quote!(fn strip(_: impl Ctx, val: f64) -> (f64, RemoveAttr<Opacity>) { (val, RemoveAttr) }));
}
#[test]
fn bridge_record_fresh() {
assert_bridge(quote!(category("")), quote!(fn make(_: impl Ctx, _: (), fill: f64) -> (f64, Attr<Opacity>) { (fill, Attr(1.)) }));
}
#[test]
fn bridge_routing() {
assert_bridge(
quote!(category("")),
quote! {
fn switch<T>(_: impl Ctx, condition: bool, off: impl Node<(), Output = T>, on: impl Node<(), Output = T>) -> T { if condition { on.eval(()) } else { off.eval(()) } }
},
);
}
#[test]
fn bridge_opaque() {
assert_bridge(
quote!(category("")),
quote! {
fn memo<'e>(_: impl Ctx, #[data] cache: Store, content: impl Node<Context<'_>, Output = RecordValue<'e>>) -> GPoll<RecordValue<'e>> { content.eval(()) }
},
);
}
fn ctx_derives(parsed: &ParsedNodeFn) -> bool {
context_param(parsed).is_some_and(|ctx| {
ctx.bounds
.iter()
.any(|bound| matches!(bound, TypeParamBound::Trait(trait_bound) if trait_bound.path.segments.last().is_some_and(|segment| segment.ident == "DeriveCtx")))
})
}
/// The frozen `field_role` classification the IR bindings must reproduce.
fn reference_label(parsed: &ParsedNodeFn, raw: bool, index: usize, field: &ParsedField) -> &'static str {
let Kinds {
record_io: record,
routing,
flip,
opaque,
} = kinds(parsed);
let skips_carrier = skips_carrier(parsed);
let carrier_flip = flip && flip_carrier(parsed);
let derives = ctx_derives(parsed);
let generic = routing_generic(parsed);
let routing_source = |ty: &Type| generic.as_ref().is_some_and(|generic| bare_ident(ty) == Some(generic));
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => {
if record && !skips_carrier && index == 0 {
"carrier"
} else if carrier_flip && index == 0 {
"carrier"
} else if flip && lend.is_some() {
"lend"
} else if record && !field.attribute_reads.is_empty() {
"reading"
} else if flip || (routing && !routing_source(ty)) {
"record"
} else {
"plain"
}
}
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
if derives && routing && routing_source(output_type) {
"derive-routing"
} else if flip && raw {
"flip-raw"
} else if flip {
"flip-lazy"
} else if opaque && raw && is_record_value(output_type) {
"opaque-record"
} else if raw {
"raw-lazy"
} else {
"lazy"
}
}
}
}
fn ir_label(node: &Node, index: usize, field: &ParsedField, raw: bool) -> &'static str {
match &field.ty {
ParsedFieldType::Regular(_) => match value_binding(node, index) {
ValueBinding::Carrier => "carrier",
ValueBinding::Lend => "lend",
ValueBinding::ReadingSecondary => "reading",
ValueBinding::RecordElement => "record",
ValueBinding::Plain => "plain",
},
ParsedFieldType::Node(_) => match (lazy_binding(node, index), raw) {
(LazyBinding::DeriveRouting, _) => "derive-routing",
(LazyBinding::OpaqueRecord, _) => "opaque-record",
(LazyBinding::Element, true) => "flip-raw",
(LazyBinding::Element, false) => "flip-lazy",
(LazyBinding::Plain, true) => "raw-lazy",
(LazyBinding::Plain, false) => "lazy",
},
}
}
fn assert_bindings(attr: TokenStream2, item: TokenStream2) {
let mut parsed = parse_node_fn(attr, item).unwrap();
parsed.replace_impl_trait_in_input();
analyze(&parsed).expect("representative resolves to a supported node");
let raw = matches!(dialect(&parsed), Dialect::Poll);
let node = build(&parsed);
let kinds = kinds(&parsed);
let expected_kind = if kinds.record_io {
"record-io"
} else if kinds.routing {
"routing"
} else if kinds.flip {
"flip"
} else {
"opaque"
};
let actual_kind = match node_kind(&node) {
NodeKind::RecordIo => "record-io",
NodeKind::Flip => "flip",
NodeKind::Routing => "routing",
NodeKind::Opaque => "opaque",
};
assert_eq!(actual_kind, expected_kind, "node_kind of {}", parsed.fn_name);
let fields: Vec<&ParsedField> = parsed.fields.iter().filter(|field| !field.is_data_field).collect();
for (index, field) in fields.iter().enumerate() {
assert_eq!(
ir_label(&node, index, field, raw),
reference_label(&parsed, raw, index, field),
"field {index} of {}",
parsed.fn_name
);
}
}
#[test]
fn bindings_flip() {
assert_bindings(quote!(category("")), quote!(fn negate(_: impl Ctx, x: f64) -> f64 { -x }));
assert_bindings(quote!(category("")), quote!(fn add2(_: impl Ctx, a: f64, b: f64) -> f64 { a + b }));
}
#[test]
fn bindings_lend() {
assert_bindings(quote!(category("")), quote!(fn borrow(_: impl Ctx, prim: f64, other: &f64) -> f64 { prim + *other }));
}
#[test]
fn bindings_reading_secondary() {
assert_bindings(quote!(category("")), quote!(fn read_op(_: impl Ctx, carrier: f64, (other, op): (f64, Attr<Opacity>)) -> f64 { carrier + other }));
}
#[test]
fn bindings_flip_lazy() {
assert_bindings(quote!(category("")), quote!(fn apply(_: impl Ctx, inner: impl Node<(), Output = f64>) -> f64 { inner.eval(()) }));
}
#[test]
fn bindings_flip_lazy_reads() {
assert_bindings(
quote!(category("")),
quote!(fn apply_reads(_: impl Ctx, carrier: f64, inner: impl Node<(), Output = (f64, Attr<Opacity>)>) -> f64 { carrier + inner.eval(()).0 }),
);
}
#[test]
fn bindings_flip_raw() {
assert_bindings(quote!(category("")), quote!(fn poll_apply(_: impl Ctx, inner: impl Node<(), Output = f64>) -> GPoll<f64> { inner.eval(()) }));
}
#[test]
fn bindings_skip_impl_generic() {
// A bounded generic forwarded whole (passthrough) flips, not routes.
assert_bindings(quote!(category(""), skip_impl), quote!(fn passthrough<T: Send>(_: impl Ctx, content: T) -> T { content }));
// A generic transformed into a different output type flips.
assert_bindings(
quote!(category(""), skip_impl),
quote!(fn into_ty<T: Send + Into<O>, O: Send>(_: impl Ctx, value: T, #[data] _out: PhantomData<O>) -> O { value.into() }),
);
}
#[test]
fn bindings_routing() {
assert_bindings(
quote!(category("")),
quote!(fn switch<T>(_: impl Ctx, condition: bool, off: impl Node<(), Output = T>, on: impl Node<(), Output = T>) -> T { if condition { on.eval(()) } else { off.eval(()) } }),
);
}
#[test]
fn bindings_derive_routing() {
assert_bindings(quote!(category("")), quote!(fn ctx_mod<T>(_: impl Ctx + DeriveCtx, inner: impl Node<(), Output = T>) -> T { inner.eval(()) }));
}
#[test]
fn bindings_opaque() {
assert_bindings(
quote!(category("")),
quote!(fn memo<'e>(_: impl Ctx, #[data] cache: Store, content: impl Node<Context<'_>, Output = RecordValue<'e>>) -> GPoll<RecordValue<'e>> { content.eval(()) }),
);
}
#[test]
fn monomorphizations_key_by_generic() {
let node = assert_bridge(
quote!(category("")),
quote! {
fn add<A: core::ops::Add<B>, B>(_: impl Ctx, #[implementations(f64, u32)] augend: A, #[implementations(f64, u32)] addend: B) -> <A as core::ops::Add<B>>::Output { augend + addend }
},
);
let rows: Vec<Vec<(String, String)>> = node
.monomorphizations
.iter()
.map(|row| row.assignments.iter().map(|(generic, ty)| (generic.to_string(), ty.to_token_stream().to_string())).collect())
.collect();
assert_eq!(
rows,
vec![
vec![("A".to_string(), "f64".to_string()), ("B".to_string(), "f64".to_string())],
vec![("A".to_string(), "u32".to_string()), ("B".to_string(), "u32".to_string())],
]
);
}
}
@@ -1,173 +0,0 @@
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()
}
}
+4 -218
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, GenericArgument, GenericParam, Ident, ItemFn, Lit, LitFloat, LitInt, LitStr, Meta, Pat, PatIdent, PatType, Path, PathArguments, ReturnType,
TraitBound, Type, TypeImplTrait, TypeParam, TypeParamBound, Visibility, WhereClause, parse_quote,
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,
};
use crate::codegen::generate_node_code;
@@ -39,74 +39,6 @@ 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>,
@@ -132,8 +64,6 @@ 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)]
@@ -197,9 +127,6 @@ 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)]
@@ -313,8 +240,6 @@ 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>,
@@ -399,7 +324,6 @@ 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;
@@ -585,13 +509,6 @@ 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 {
@@ -643,12 +560,11 @@ impl Parse for NodeFnAttributes {
extent,
batch,
no_partial,
plain,
})
}
}
pub(crate) fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNodeFn> {
fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNodeFn> {
let attributes = syn::parse2::<NodeFnAttributes>(attr.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node_fn attributes:\n{e}")))?;
let input_fn = syn::parse2::<ItemFn>(item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse function: {e}. Make sure it's a valid Rust function.")))?;
@@ -735,24 +651,8 @@ 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"));
}
@@ -765,85 +665,6 @@ 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();
@@ -1062,7 +883,6 @@ 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 {
@@ -1077,7 +897,6 @@ 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")
@@ -1085,11 +904,6 @@ 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 = [
@@ -1122,7 +936,6 @@ 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,
@@ -1134,7 +947,6 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
number_step,
unit,
is_data_field,
attribute_reads: Vec::new(),
})
}
}
@@ -1186,7 +998,7 @@ pub fn new_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenS
let crate_ident = CrateIdent::default();
let mut parsed_node = parse_node_fn(attr, item.clone()).map_err(|e| Error::new(e.span(), format!("Failed to parse node function:\n{e}")))?;
parsed_node.replace_impl_trait_in_input();
if parsed_node.injects_async_source_fields() {
if parsed_node.is_async || crate::codegen::is_source_kernel(&parsed_node.output_type) {
let core_types = crate_ident.gcore()?.clone();
parsed_node.inject_async_source_fields(&core_types);
}
@@ -1218,10 +1030,6 @@ impl ParsedNodeFn {
}
}
pub fn injects_async_source_fields(&self) -> bool {
self.is_async || crate::codegen::is_source_kernel(&self.output_type)
}
pub fn inject_async_source_fields(&mut self, core_types: &TokenStream2) {
let hidden_field = |name: &str, ty: Type, value_source: ParsedValueSource| ParsedField {
pat_ident: PatIdent {
@@ -1236,7 +1044,6 @@ impl ParsedNodeFn {
widget_override: ParsedWidgetOverride::Hidden,
ty: ParsedFieldType::Regular(RegularParsedField {
ty,
lend: None,
exposed: false,
value_source,
number_soft_min: None,
@@ -1251,7 +1058,6 @@ impl ParsedNodeFn {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
};
self.fields.push(hidden_field(
"_runtime",
@@ -1388,7 +1194,6 @@ 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()),
@@ -1409,7 +1214,6 @@ 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,
@@ -1425,7 +1229,6 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::from("Multi\nLine\n"),
@@ -1465,7 +1268,6 @@ 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()),
@@ -1495,7 +1297,6 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
},
ParsedField {
pat_ident: pat_ident("translate"),
@@ -1503,7 +1304,6 @@ 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,
@@ -1519,7 +1319,6 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
},
],
body: TokenStream2::new(),
@@ -1557,7 +1356,6 @@ 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()),
@@ -1578,7 +1376,6 @@ 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.)),
@@ -1594,7 +1391,6 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: "Test\n".into(),
@@ -1630,7 +1426,6 @@ 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()),
@@ -1651,7 +1446,6 @@ 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,
@@ -1672,7 +1466,6 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1715,7 +1508,6 @@ 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()),
@@ -1736,7 +1528,6 @@ 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,
@@ -1752,7 +1543,6 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1803,7 +1593,6 @@ 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()),
@@ -1824,7 +1613,6 @@ 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,
@@ -1840,7 +1628,6 @@ mod tests {
number_step: None,
unit: None,
is_data_field: false,
attribute_reads: Vec::new(),
}],
body: TokenStream2::new(),
description: String::new(),
@@ -1876,7 +1663,6 @@ 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()),
@@ -231,10 +231,9 @@ impl PerPixelAdjustCodegen<'_> {
description: "".to_string(),
widget_override: Default::default(),
ty: ParsedFieldType::Regular(RegularParsedField {
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
lend: None,
ty: parse_quote!(std::sync::Arc<WgpuExecutor>),
exposed: true,
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorArcNode"))),
number_soft_min: None,
number_soft_max: None,
number_hard_min: None,
@@ -247,7 +246,6 @@ 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
+2 -241
View File
@@ -1,6 +1,6 @@
use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField, attr_marker, record_writes, remove_attr_marker};
use crate::parsing::{Implementation, NodeParsedField, ParsedField, ParsedFieldType, ParsedNodeFn, RegularParsedField};
use proc_macro_error2::emit_error;
use quote::{ToTokens, quote};
use quote::quote;
use syn::spanned::Spanned;
use syn::{GenericParam, Type};
@@ -12,9 +12,6 @@ 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 {
@@ -24,202 +21,9 @@ 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);
if let Some(placeholder) = &parsed.attributes.placeholder
&& !parsed.is_async
&& !future_kernel
{
emit_error!(
placeholder.span(),
"`placeholder` applies only to async and source kernels; a synchronous node never reports `Partial`, so the stand-in is unused"
);
}
if parsed.is_async && future_kernel {
emit_error!(
parsed.output_type.span(),
@@ -250,30 +54,6 @@ 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 {
@@ -392,19 +172,6 @@ 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 node = crate::codegen::ir::build(parsed);
let record_token = match (crate::codegen::ir::node_kind(&node), &node.output.shape.element) {
(crate::codegen::ir::NodeKind::RecordIo, crate::codegen::ir::Element::Generic(ident)) => Some(ident.clone()),
_ => 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 {
@@ -416,9 +183,6 @@ 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(),
@@ -436,9 +200,6 @@ 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,5 +1,14 @@
use core::f64;
use core_types::Color;
use core_types::context::{Context, ContextModification, Ctx, DeriveCtx};
use core_types::gpoll::Interrupt;
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};
/// 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.
@@ -7,10 +16,36 @@ use core_types::gpoll::Interrupt;
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,
) -> Result<T, Interrupt> {
let scope = ctx.scope().nullified(modification.features, Some(modification.sources()));
) -> GPoll<T> {
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()
}
/// Clones the element out of its record wire.
/// Meant for debugging purposes, not general use. Clones the input value.
#[node_macro::node(category("Debug"))]
fn clone<T: Clone>(_: impl Ctx, #[implementations(List<Raster<CPU>>)] value: &T) -> T {
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&List<Raster<CPU>>)] value: &'i T) -> T {
value.clone()
}
-2
View File
@@ -5,8 +5,6 @@ pub mod debug;
pub mod extract_xy;
pub mod memo;
pub mod ops;
#[cfg(test)]
mod record;
// Re-export all nodes
pub use animation::*;
+106 -129
View File
@@ -1,63 +1,47 @@
use core_types::arena::ArenaCell;
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ExtractArena};
use core_types::arena::{Arena, ArenaCell};
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll};
use core_types::frame_table::{FrameTable, Lookup};
use core_types::gpoll::{Extent, Finality, GPoll};
use core_types::gpoll::{Extent, Finality, GPoll, Interrupt};
use core_types::graphene_hash::CacheHash;
use core_types::memo::IORecord;
use core_types::memo::*;
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 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()
/// 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()
&& *hash == key
{
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(),
return match finality {
Finality::AllFinal => GPoll::Final(value.clone()),
Finality::Partial => GPoll::Partial(value.clone()),
};
}
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));
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(_) => {}
}
result
}
fn memoize_extent<C, NodeContent>(node: &MemoizeNode<NodeContent>, ctx: &C) -> GPoll<Extent>
fn memoize_extent<C, T, NodeContent>(node: &MemoizeNode<T, NodeContent>, ctx: &C) -> GPoll<Extent>
where
NodeContent: Node<C>,
T: Clone,
NodeContent: Node<C, Output = T>,
{
node.content.extent(ctx)
}
#[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<Box<[u8]>, 32>>,
content: impl Node<Context<'_>, Output = RecordValue<'e>>,
) -> GPoll<RecordValue<'e>> {
#[node_macro::node(category(""), path(graphene_core::memo), skip_impl, extent(frame_memo_extent))]
fn frame_memo<'e, T: Clone + 'static>(ctx: impl Ctx + CacheHash + ExtractArena<'e>, #[data] cell: ArenaCell<FrameTable<T, 32>>, content: impl Node<Context<'_>, Output = T>) -> GPoll<&'e T> {
let arena = ctx.arena();
let table = match cell.load(arena) {
Some(table) => table,
@@ -66,71 +50,86 @@ fn frame_memo<'e>(
cell.store(weak);
table
}
None => return content.eval(&ctx),
None => return park(arena, 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, 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)))
}
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)),
unpublishable => {
slot.release();
unpublishable
park(arena, unpublishable)
}
},
Lookup::Full => content.eval(&ctx),
Lookup::Full => park(arena, content.eval(ctx)),
}
}
fn frame_memo_extent<C, NodeContent>(node: &FrameMemoNode<NodeContent>, ctx: &C) -> GPoll<Extent>
fn frame_memo_extent<C, T, NodeContent>(node: &FrameMemoNode<T, NodeContent>, ctx: &C) -> GPoll<Extent>
where
NodeContent: Node<C>,
T: Clone + 'static,
NodeContent: Node<C, Output = T>,
{
node.content.extent(ctx)
}
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"))]
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,
});
pub fn park<T>(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),
}
result
}
fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
type MonitorValue<T> = Arc<Mutex<Option<Arc<IORecord<CtxSnapshot, T>>>>>;
/// 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)
}
fn serialize_monitor<T: Clone + 'static + Send + Sync>(io: &MonitorValue<T>) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
let io = io.lock().unwrap();
io.as_ref().map(|io| Arc::new(io.clone()) as Arc<dyn std::any::Any + Send + Sync>)
io.as_ref().map(|output| output.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::Type;
use core_types::concrete;
use core_types::context::{ContextImpl, EvalScope};
use core_types::registry::{EdgeHandle, ErasedNode, ErasedRecordNode};
use core_types::registry::{EdgeHandle, ErasedLendNode, ErasedNode};
use std::sync::atomic::{AtomicU32, Ordering};
struct CountingNode(AtomicU32);
@@ -164,51 +163,35 @@ 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_capture_through_the_edge() {
let arena = Arena::new(1024).unwrap();
fn monitor_serialize_exposes_the_io_record_through_the_edge() {
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
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 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 edge = handle.duplicate().downcast_record::<u32>().unwrap();
let GPoll::Final(_) = edge.eval(&ctx) else {
panic!("expected a final record");
};
let edge = handle.duplicate().downcast::<u32>().unwrap();
assert_eq!(edge.eval(&ctx), GPoll::Final(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);
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);
}
#[test]
fn memoize_caches_across_evals() {
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
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);
let memoized = MemoizeNode::new(CountingNode(AtomicU32::new(0)));
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
assert_eq!(memoized.eval(&ctx), GPoll::Final(1));
@@ -216,16 +199,14 @@ mod tests {
#[test]
fn memo_invalidates_on_generation_bump() {
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let source: SourceId = 7;
let before = [(source, 1)];
let after = [(source, 2)];
let scope_before = scope_fixture(&before, &arena);
let scope_after = scope_fixture(&after, &arena);
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);
let memoized = MemoizeNode::new(CountingNode(AtomicU32::new(0)));
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
assert_eq!(memoized.eval(&ContextImpl::root(&scope_before)), GPoll::Final(1));
@@ -234,14 +215,12 @@ mod tests {
#[test]
fn memo_replays_partiality_on_hit() {
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
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);
let memoized = MemoizeNode::new(PartialCountingNode(AtomicU32::new(0)));
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
assert_eq!(memoized.eval(&ctx), GPoll::Partial(1));
@@ -249,40 +228,38 @@ mod tests {
#[test]
fn memoized_edges_stack_and_rewire() {
let arena = Arena::new(1024).unwrap();
let arena = Arena::new(1024);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
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);
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());
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
assert_eq!(stacked.eval(&ctx), GPoll::Final(1));
}
#[test]
fn frame_memo_shares_one_record_copy_per_frame() {
let arena = Arena::new(4096).unwrap();
fn frame_memo_turns_an_owned_edge_into_a_lending_edge() {
let arena = Arena::new(4096);
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let layout = element_layout::<String>();
let memo = FrameMemoNode::new(core_types::record::RecordLift::<String, _>::new(ValueNode("lent out".to_string())), &layout);
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 GPoll::Final(first) = memo.eval(&ctx) else {
panic!("the miss must fill the frame table");
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(second) = memo.eval(&ctx) else {
panic!("the hit must revive the published record");
let GPoll::Final(second) = node.eval(&ctx) else {
panic!("second eval must lend the published value");
};
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), "the hit shares the parked payload");
assert!(std::ptr::eq(first, second));
}
}
+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<T: Send>(_: impl Ctx, content: T) -> T {
fn passthrough<'i, T: 'i + 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(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(composite_background_pipeline::IDENTIFIER)] pipeline: WgpuPipelineCache, data: RenderOutput) -> RenderOutput {
fn render_background<'a>(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)
+4 -8
View File
@@ -221,7 +221,7 @@ mod tests {
#[test]
fn create_context_builds_the_render_context_from_the_root_vararg() {
let arena = Arena::new(4096).unwrap();
let arena = Arena::new(256);
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let root = ContextImpl::root(&scope);
@@ -240,16 +240,12 @@ mod tests {
};
let ctx = root.with_varargs(&varargs);
let probe = core_types::record::RecordLift::<RenderOutput, _>::new(ProbeNode);
let layout = Node::<ContextImpl>::layout(&probe).clone();
core_types::record::stack::reserve(layout.frame_bytes().max(1 << 12));
let graph = CreateContextNode::new(probe, &layout);
let GPoll::Final(result) = Node::<ContextImpl>::eval(&graph, &ctx) else {
let graph = CreateContextNode::new(ProbeNode);
let GPoll::Final(result) = <CreateContextNode<ProbeNode> as Node<ContextImpl>>::eval(&graph, &ctx) else {
panic!("create_context must complete synchronously");
};
let output: &RenderOutput = unsafe { core_types::record::borrow_element(layout.rec(&result)) };
assert_eq!(
output.data,
result.data,
RenderOutputType::Buffer {
data: Vec::new(),
width: 0,
+47 -118
View File
@@ -989,6 +989,8 @@ fn normalize(_: impl Ctx, vector: DVec2) -> DVec2 {
#[cfg(test)]
mod test {
use super::*;
use core_types::Node;
use core_types::generic::FnNode;
#[test]
pub fn dot_product_function() {
@@ -1027,6 +1029,12 @@ mod test {
assert_eq!(result, 0.);
}
#[test]
pub fn foo() {
let fnn = FnNode::new(|(a, b)| (b, a));
assert_eq!(fnn.eval((1u32, 2u32)), (2, 1));
}
#[test]
pub fn add_vectors() {
assert_eq!(super::add(&(), DVec2::ONE, DVec2::ONE), DVec2::ONE * 2.);
@@ -1060,10 +1068,9 @@ 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::record::{Layout, RecordLift, RecordValue, stack};
use core_types::registry::{ErasedRecordNode, construct};
use core_types::value::record_value_edge;
use core_types::registry::{EdgeHandle, ErasedNode, construct};
use std::mem::MaybeUninit;
use std::sync::Arc;
struct SourceNode<T>(T);
@@ -1089,84 +1096,44 @@ 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 arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
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);
let graph = AddNode::new(SourceNode(1.0f64), SourceNode(2.0f64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Final(3.0));
}
#[test]
fn generated_add_batches_through_the_erased_edge() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
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 erased: Box<ErasedNode<f64>> = Box::new(AddNode::new(IndexNode, SourceNode(10.0f64)));
let mut scratch = [const { MaybeUninit::uninit() }; 4];
let status = erased.eval_batch(&ctx, 2..6, Some(&mut scratch));
let BatchStatus::Filled(batch, finality) = status else {
let BatchStatus::Filled(lanes, finality) = status else {
panic!("expected filled, got {status:?}");
};
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!(lanes, &[12.0, 13.0, 14.0, 15.0]);
assert_eq!(finality, Finality::AllFinal);
}
#[test]
fn generated_wire_constructor_resolves_and_wires() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
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]);
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 GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert!(element::<bool>(&layout, &value));
assert_eq!(Node::eval(&wired, &ctx), GPoll::Final(true));
}
#[test]
@@ -1181,26 +1148,22 @@ mod graphene_test {
#[test]
fn generic_add_registers_one_entry_per_implementation() {
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let entries = super::_add_mod::add_entries();
let entries = add_entries();
assert_eq!(entries.len(), 6);
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>());
assert_eq!(entries[0].io.inputs, vec![core_types::concrete!(f64), core_types::concrete!(f64)]);
assert_eq!(entries[0].io.output, core_types::concrete!(f64));
assert_eq!(entries[3].io.inputs, vec![core_types::concrete!(DVec2), core_types::concrete!(DVec2)]);
assert_eq!(entries[3].io.output, core_types::concrete!(DVec2));
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]);
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 GPoll::Final(value) = edge.eval(&ctx) else {
panic!("expected a final record");
};
assert_eq!(element::<f64>(&layout, &value), 4.0);
assert_eq!(Node::eval(&wired, &ctx), GPoll::Final(4.0));
}
#[test]
@@ -1219,23 +1182,15 @@ mod graphene_test {
}
}
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
let taken = Arc::new(AtomicU32::new(0));
let untaken = Arc::new(AtomicU32::new(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]);
let graph = SwitchNode::new(SourceNode(true), CountingSource(taken.clone(), 1.0), CountingSource(untaken.clone(), 2.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!(Node::eval(&graph, &ctx), GPoll::Final(1.0));
assert_eq!(taken.load(Ordering::Relaxed), 1);
assert_eq!(untaken.load(Ordering::Relaxed), 0);
}
@@ -1262,27 +1217,15 @@ mod graphene_test {
}
}
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
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 pending = SwitchNode::new(SourceNode(true), PendingSource, PartialSource);
assert_eq!(Node::eval(&pending, &ctx), GPoll::Pending);
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);
let partial = SwitchNode::new(SourceNode(false), PendingSource, PartialSource);
assert_eq!(Node::eval(&partial, &ctx), GPoll::Partial(7.0));
}
#[test]
@@ -1297,21 +1240,12 @@ mod graphene_test {
}
}
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
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);
let graph = SwitchNode::new(PartialCondition, SourceNode(1.0f64), SourceNode(2.0f64));
assert_eq!(Node::eval(&graph, &ctx), GPoll::Partial(1.0));
}
#[test]
@@ -1326,20 +1260,15 @@ mod graphene_test {
}
}
let arena = Arena::new(64).unwrap();
let arena = Arena::new(64);
let scope = scope_fixture(&arena);
let ctx = ContextImpl::root(&scope);
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 graph = AddNode::new(FallbackNode, SourceNode(5.0f64));
let GPoll::Fallback(boxed) = Node::eval(&graph, &ctx) else {
panic!("fallback must propagate with the computed stand-in");
};
assert_eq!(element::<f64>(&out, &boxed.0), 5.0);
assert_eq!(boxed.0, 5.0);
assert!(boxed.1.kind == "upstream failed");
assert_eq!(boxed.1.trace, vec![0]);
}
@@ -201,8 +201,8 @@ mod test {
use raster_types::Image;
use raster_types::Raster;
#[test]
fn color_overlay_multiply() {
#[tokio::test]
async fn color_overlay_multiply() {
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
let image = Image::new(1, 1, image_color);
@@ -212,7 +212,7 @@ mod test {
// 100% of the output should come from the multiplied value
let opacity = 100.;
let result = super::color_overlay(&(), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
let result = super::color_overlay((), List::new_from_element(Raster::new_cpu(image.clone())), overlay_color, BlendMode::Multiply, opacity);
let result = result.element(0).unwrap().clone();
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 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,
@@ -68,8 +68,8 @@ mod test {
#[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],
@@ -77,6 +77,6 @@ mod test {
})),
1,
);
assert_eq!(result, List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
assert_eq!(futures::executor::block_on(result), List::new_from_element(Color::from_rgbaf32(0., 0., 0., 1.).unwrap()));
}
}
+6
View File
@@ -24,3 +24,9 @@ log = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
[dev-dependencies]
graphene-core = { workspace = true }
vector-nodes = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt"] }
kurbo = { workspace = true }
-165
View File
@@ -35,14 +35,11 @@ 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)
@@ -79,7 +76,6 @@ 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() {
@@ -92,8 +88,6 @@ 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)
@@ -126,7 +120,6 @@ 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() {
@@ -139,8 +132,6 @@ 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)
@@ -177,170 +168,14 @@ 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) };
}
}
Ok(result_list)
}
#[cfg(test)]
mod test {
use super::*;
use core_types::arena::Arena;
use core_types::context::{ContextImpl, EvalScope, ExtractIndex, ExtractPosition};
use core_types::gpoll::GPoll;
use core_types::list::Item;
use core_types::node::{Node, StatusCell};
use core_types::record::{ElementLazyInput, RecordLift};
use vector_types::subpath::Subpath;
const TEST_POSITION: &str = "test-position";
struct ValueNode<T>(T);
impl<T: Clone, Input> Node<Input> for ValueNode<T> {
type Output = T;
fn eval(&self, _input: &Input) -> GPoll<T> {
GPoll::Final(self.0.clone())
}
}
/// Returns one default `Vector` whose transform records the innermost context index in its x translation.
struct IndexProbe;
impl<Input: ExtractIndex> Node<Input> for IndexProbe {
type Output = List<Vector>;
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
let index = input.try_index().and_then(|mut levels| levels.next()).expect("repeat must push an index level");
let mut list = List::new();
list.push(Item::new_from_element(Vector::default()).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(index as f64, 0.))));
GPoll::Final(list)
}
}
/// Returns one default `Vector` recording the innermost context position under `TEST_POSITION`.
struct PositionProbe;
impl<Input: ExtractPosition> Node<Input> for PositionProbe {
type Output = List<Vector>;
fn eval(&self, input: &Input) -> GPoll<List<Vector>> {
let position = input.try_position().and_then(|mut positions| positions.next()).expect("repeat_on_points must push a position level");
let mut list = List::new();
list.push(Item::new_from_element(Vector::default()).with_attribute(TEST_POSITION, DAffine2::from_translation(position)));
GPoll::Final(list)
}
}
fn single_default_vector() -> List<Vector> {
List::new_from_element(Vector::default())
}
fn row_translations(list: &List<Vector>, key: &str) -> Vec<DVec2> {
(0..list.len()).map(|index| list.attribute_cloned_or_default::<DAffine2>(key, index).translation).collect()
}
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);
let $ctx = ContextImpl::root(&scope);
let $cell = StatusCell::default();
};
}
#[test]
fn repeat_pushes_the_iteration_index_in_order() {
test_ctx!(ctx, cell);
let x_translations = |values: [f64; 3]| values.map(|x| DVec2::new(x, 0.)).to_vec();
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, ElementLazyInput::new(&lift, &cell, 0, &layout), 3, true).unwrap();
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), x_translations([2., 1., 0.]));
}
#[test]
fn repeat_array_spaces_copies_along_the_direction() {
test_ctx!(ctx, cell);
let direction = DVec2::new(1.5, 0.);
let count = 3;
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() {
let expected = index as f64 * direction / (count - 1) as f64;
assert!(translation.abs_diff_eq(expected, 1e-10), "copy {index}: {translation:?} != {expected:?}");
}
}
#[test]
fn repeat_array_single_copy_stays_finite() {
test_ctx!(ctx, cell);
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);
assert!(transform.abs_diff_eq(DAffine2::IDENTITY, 1e-10), "single copy must not divide by zero: {transform:?}");
}
#[test]
fn repeat_radial_rotates_copies_around_the_center() {
test_ctx!(ctx, cell);
let (radius, count) = (5., 4);
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 {
let transform: DAffine2 = repeated.attribute_cloned_or_default(ATTR_TRANSFORM, index);
let expected = DAffine2::from_angle((TAU / count as f64) * index as f64) * DAffine2::from_translation(radius * DVec2::Y);
assert!(transform.abs_diff_eq(expected, 1e-10), "copy {index}: {transform:?} != {expected:?}");
}
}
#[test]
fn repeat_on_points_pushes_each_point_as_the_position() {
test_ctx!(ctx, cell);
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 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, ElementLazyInput::new(&lift, &cell, 0, &layout), true).unwrap();
let mut expected = positions.to_vec();
expected.reverse();
assert_eq!(row_translations(&reversed, ATTR_TRANSFORM), expected);
}
}
@@ -411,11 +411,11 @@ mod tests {
#[test]
fn isometric_grid_test() {
// Doesn't crash with weird angles
grid(&(), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
grid(&(), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
grid((), (), GridType::Isometric, 0., 5, 5, (0., 0.).into());
grid((), (), GridType::Isometric, 90., 5, 5, (90., 90.).into());
// Works properly
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (30., 30.).into());
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
@@ -430,7 +430,7 @@ mod tests {
#[test]
fn skew_isometric_grid_test() {
let grid = grid(&(), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
let grid = grid((), (), GridType::Isometric, 10., 5, 5, (40., 30.).into());
assert_eq!(grid.element(0).unwrap().point_domain.ids().len(), 5 * 5);
assert_eq!(grid.element(0).unwrap().segment_bezier_iter().count(), 4 * 5 + 4 * 9);
for (_, bezier, _, _) in grid.element(0).unwrap().segment_bezier_iter() {
@@ -443,7 +443,7 @@ mod tests {
#[test]
fn qr_code_test() {
let qr = qr_code(&(), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
let qr = qr_code((), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
assert!(qr.element(0).unwrap().point_domain.ids().len() > 0);
assert!(qr.element(0).unwrap().segment_domain.ids().len() > 0);
}
+60 -45
View File
@@ -3261,10 +3261,24 @@ fn centroid(ctx: impl Ctx + DeriveCtx, content: impl Node<Context<'_>, Output =
#[cfg(test)]
mod test {
use super::*;
use core_types::Node;
use kurbo::{CubicBez, Ellipse, Point, Rect};
use std::future::Future;
use std::pin::Pin;
use vector_types::vector::algorithms::bezpath_algorithms::{TValue, trim_pathseg};
use vector_types::vector::misc::pathseg_abs_diff_eq;
#[derive(Clone)]
pub struct FutureWrapperNode<T: Clone>(T);
impl<'i, T: 'i + Clone + Send> Node<'i, Footprint> for FutureWrapperNode<T> {
type Output = Pin<Box<dyn Future<Output = T> + 'i + Send>>;
fn eval(&'i self, _input: Footprint) -> Self::Output {
let value = self.0.clone();
Box::pin(async move { value })
}
}
fn vector_node_from_bezpath(bezpath: BezPath) -> List<Vector> {
List::new_from_element(Vector::from_bezpath(bezpath))
}
@@ -3275,9 +3289,9 @@ mod test {
Item::new_from_element(row).with_attribute(ATTR_TRANSFORM, transform)
}
#[test]
fn bounding_box() {
let bounding_box = super::bounding_box(&(), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY)));
#[tokio::test]
async fn bounding_box() {
let bounding_box = super::bounding_box((), vector_node_from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY))).await;
let bounding_box = bounding_box.element(0).unwrap();
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
let manipulator_groups_anchors = bounding_box
@@ -3295,7 +3309,7 @@ mod test {
let square = Vector::from_bezpath(Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY));
let mut square = List::new_from_element(square);
square.with_attribute_mut_or_default(ATTR_TRANSFORM, 0, |t: &mut DAffine2| *t *= DAffine2::from_angle(std::f64::consts::FRAC_PI_4));
let bounding_box = super::bounding_box(&(), square);
let bounding_box = BoundingBoxNode { content: FutureWrapperNode(square) }.eval(Footprint::default()).await;
let bounding_box = bounding_box.element(0).unwrap();
assert_eq!(bounding_box.region_manipulator_groups().count(), 1);
let manipulator_groups_anchors = bounding_box
@@ -3312,15 +3326,15 @@ mod test {
assert_eq!(manipulator_groups_anchors[i], expected_bounding_box[i]);
}
}
#[test]
fn copy_to_points() {
#[tokio::test]
async fn copy_to_points() {
let points = Rect::new(-10., -10., 10., 10.).to_path(DEFAULT_ACCURACY);
let element = Rect::new(-1., -1., 1., 1.).to_path(DEFAULT_ACCURACY);
let expected_points = Vector::from_bezpath(points.clone()).point_domain.positions().to_vec();
let copy_to_points = super::copy_to_points(&Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0);
let flatten_path = super::flatten_path(&Footprint::default(), copy_to_points);
let copy_to_points = super::copy_to_points(Footprint::default(), vector_node_from_bezpath(points), vector_node_from_bezpath(element), 1., 1., 0., 0, 0., 0).await;
let flatten_path = super::flatten_path(Footprint::default(), copy_to_points).await;
let flattened_copy_to_points = flatten_path.element(0).unwrap();
assert_eq!(flattened_copy_to_points.region_manipulator_groups().count(), expected_points.len());
@@ -3335,34 +3349,35 @@ mod test {
}
}
#[test]
fn sample_polyline() {
#[tokio::test]
async fn sample_polyline() {
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false);
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 30., 0, 0., 0., false).await;
let sample_polyline = sample_polyline.element(0).unwrap();
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 0., DVec2::X * 30., DVec2::X * 60., DVec2::X * 90.]) {
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
}
}
#[test]
fn sample_polyline_adaptive_spacing() {
#[tokio::test]
async fn sample_polyline_adaptive_spacing() {
let path = BezPath::from_vec(vec![PathEl::MoveTo(Point::ZERO), PathEl::CurveTo(Point::ZERO, Point::new(100., 0.), Point::new(100., 0.))]);
let sample_polyline = super::sample_polyline(&Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true);
let sample_polyline = super::sample_polyline(Footprint::default(), vector_node_from_bezpath(path), PointSpacingType::Separation, 18., 0, 45., 10., true).await;
let sample_polyline = sample_polyline.element(0).unwrap();
assert_eq!(sample_polyline.point_domain.positions().len(), 4);
for (pos, expected) in sample_polyline.point_domain.positions().iter().zip([DVec2::X * 45., DVec2::X * 60., DVec2::X * 75., DVec2::X * 90.]) {
assert!(pos.distance(expected) < 1e-3, "Expected {expected} found {pos}");
}
}
#[test]
fn poisson() {
#[tokio::test]
async fn poisson() {
let poisson_points = super::scatter_points(
&Footprint::default(),
Footprint::default(),
vector_node_from_bezpath(Ellipse::from_rect(Rect::new(-50., -50., 50., 50.)).to_path(DEFAULT_ACCURACY)),
10. * std::f64::consts::SQRT_2,
0,
);
)
.await;
let poisson_points = poisson_points.element(0).unwrap();
assert!(
(20..=40).contains(&poisson_points.point_domain.positions().len()),
@@ -3373,33 +3388,33 @@ mod test {
assert!(point.length() < 50. + 1., "Expected point in circle {point}")
}
}
#[test]
fn path_length() {
#[tokio::test]
async fn path_length() {
let bezpath = Rect::new(100., 100., 201., 201.).to_path(DEFAULT_ACCURACY);
let transform = DAffine2::from_scale(DVec2::new(2., 2.));
let row = create_vector_item(bezpath, transform);
let list = (0..5).map(|_| row.clone()).collect::<List<Vector>>();
let length = super::path_length(&Footprint::default(), list);
let length = super::path_length(Footprint::default(), list).await;
// 101 (each rectangle edge length) * 4 (rectangle perimeter) * 2 (scale) * 5 (number of rows)
assert_eq!(length, 101. * 4. * 2. * 5.);
}
#[test]
fn spline() {
let spline = super::spline(&Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY)));
#[tokio::test]
async fn spline() {
let spline = super::spline(Footprint::default(), vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY))).await;
let spline = spline.element(0).unwrap();
assert_eq!(spline.stroke_bezpath_iter().count(), 1);
assert_eq!(spline.point_domain.positions(), &[DVec2::ZERO, DVec2::new(100., 0.), DVec2::new(100., 100.), DVec2::new(0., 100.)]);
}
#[test]
fn morph() {
#[tokio::test]
async fn morph() {
let mut rectangles = vector_node_from_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
let mut second_rectangle = rectangles.clone_item(0).unwrap();
*second_rectangle.attribute_mut_or_insert_default::<DAffine2>(ATTR_TRANSFORM) *= DAffine2::from_translation((-100., -100.).into());
rectangles.push(second_rectangle);
let morphed = super::morph(&Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default());
let morphed = super::morph(Footprint::default(), rectangles, 0.5, false, InterpolationDistribution::default(), List::default()).await;
let morphed_element = morphed.element(0).unwrap();
// Geometry stays in local space (original rectangle coordinates)
assert_eq!(
@@ -3410,8 +3425,8 @@ mod test {
assert!((morphed.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, 0).translation - DVec2::new(-50., -50.)).length() < 1e-3);
}
#[test]
fn morph_interpolates_fill() {
#[tokio::test]
async fn morph_interpolates_fill() {
let rect = || {
let mut v = Vector::default();
v.append_bezpath(Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY));
@@ -3428,7 +3443,7 @@ mod test {
let mut content = List::new_from_item(item_a);
content.push(item_b);
let morphed = super::morph(&Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default());
let morphed = super::morph(Footprint::default(), content, 0.5, false, InterpolationDistribution::default(), List::default()).await;
let fill = graphic_list_at(&morphed, 0, ATTR_FILL).expect("Morph should keep the fill paint at the midpoint");
@@ -3455,10 +3470,10 @@ mod test {
);
}
#[test]
fn bevel_rect() {
#[tokio::test]
async fn bevel_rect() {
let source = Rect::new(0., 0., 100., 100.).to_path(DEFAULT_ACCURACY);
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 8);
@@ -3477,8 +3492,8 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(10., 100.), Point::new(0., 90.))));
}
#[test]
fn bevel_open_curve() {
#[tokio::test]
async fn bevel_open_curve() {
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
let mut source = BezPath::new();
@@ -3486,7 +3501,7 @@ mod test {
source.line_to(Point::ZERO);
source.push(curve.as_path_el());
let beveled = super::bevel(&(), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = super::bevel((), vector_node_from_bezpath(source), 2_f64.sqrt() * 10.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 4);
@@ -3501,8 +3516,8 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
}
#[test]
fn bevel_with_transform() {
#[tokio::test]
async fn bevel_with_transform() {
let curve = PathSeg::Cubic(CubicBez::new(Point::ZERO, Point::new(10., 0.), Point::new(10., 100.), Point::new(100., 0.)));
let mut source = BezPath::new();
@@ -3515,7 +3530,7 @@ mod test {
vector_list.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_scale_angle_translation(DVec2::splat(10.), 1., DVec2::new(99., 77.)));
let beveled = super::bevel(&(), List::new_from_element(vector), 2_f64.sqrt() * 10.);
let beveled = super::bevel((), List::new_from_element(vector), 2_f64.sqrt() * 10.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 4);
@@ -3530,15 +3545,15 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(-8.2, 0.), trimmed.start())));
}
#[test]
fn bevel_too_high() {
#[tokio::test]
async fn bevel_too_high() {
let mut source = BezPath::new();
source.move_to(Point::ZERO);
source.line_to(Point::new(100., 0.));
source.line_to(Point::new(100., 100.));
source.line_to(Point::new(0., 100.));
let beveled = super::bevel(&Footprint::default(), vector_node_from_bezpath(source), 999.);
let beveled = super::bevel(Footprint::default(), vector_node_from_bezpath(source), 999.);
let beveled = beveled.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 6);
@@ -3554,15 +3569,15 @@ mod test {
contains_segment(beveled.clone(), PathSeg::Line(Line::new(Point::new(100., 50.), Point::new(50., 100.))));
}
#[test]
fn bevel_repeated_point() {
#[tokio::test]
async fn bevel_repeated_point() {
let line = PathSeg::Line(Line::new(Point::ZERO, Point::new(100., 0.)));
let point = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::ZERO, Point::ZERO, Point::new(100., 0.)));
let curve = PathSeg::Cubic(CubicBez::new(Point::new(100., 0.), Point::new(110., 0.), Point::new(110., 200.), Point::new(200., 0.)));
let subpath = BezPath::from_path_segments([line, point, curve].into_iter());
let beveled_list = super::bevel(&Footprint::default(), vector_node_from_bezpath(subpath), 5.);
let beveled_list = super::bevel(Footprint::default(), vector_node_from_bezpath(subpath), 5.);
let beveled = beveled_list.element(0).unwrap();
assert_eq!(beveled.point_domain.positions().len(), 6);
+10 -21
View File
@@ -116,13 +116,7 @@ impl Preprocessor {
for (id, metadata) in core_types::registry::NODE_METADATA.lock().unwrap().iter() {
let id = id.clone();
let NodeMetadata {
fields,
memoize,
inject_scope,
async_source_fields,
..
} = metadata;
let NodeMetadata { fields, memoize, inject_scope, .. } = metadata;
let Some(implementations) = node_registry.get(&id) else { continue };
let valid_call_args: HashSet<_> = implementations.iter().map(|entry| entry.io.call_argument.clone()).collect();
let first_node_io = implementations.first().map(|entry| &entry.io).unwrap_or(const { &NodeIOTypes::empty() });
@@ -137,20 +131,16 @@ impl Preprocessor {
input_type = &const { generic!(D) };
}
let mut inputs: Vec<_> = node_inputs(fields, first_node_io);
let wrapper_input_count = inputs.len() - if *async_source_fields { 2 } else { 0 };
// The injected fields must not surface as wrapper inputs, and the `_source` reflection must sit on
// the kernel itself so the source id lands on a node that survives flattening.
let injected_inputs = inputs.split_off(wrapper_input_count);
let network_inputs = (0..wrapper_input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).chain(injected_inputs).collect();
let inputs: Vec<_> = node_inputs(fields, first_node_io);
let input_count = inputs.len();
let network_inputs = (0..input_count).map(|i| NodeInput::node(NodeId(i as u64), 0)).collect();
let passthrough_node = ops::passthrough::IDENTIFIER;
let mut generated_nodes = 0;
let mut nodes: HashMap<_, _, _> = node_io_types
.iter()
.take(wrapper_input_count)
.take(input_count)
.enumerate()
.map(|(i, inputs)| {
(
@@ -195,7 +185,7 @@ impl Preprocessor {
})
.collect();
if generated_nodes == 0 && !memoize && !inject_scope && !async_source_fields {
if generated_nodes == 0 && !memoize && !inject_scope {
continue;
}
@@ -209,14 +199,13 @@ impl Preprocessor {
..Default::default()
};
let main_node_id = NodeId(wrapper_input_count as u64);
nodes.insert(main_node_id, document_node);
nodes.insert(NodeId(input_count as u64), document_node);
// If memoize is requested, append a Memoize node after the main node and redirect the export through it
let export_node_id = if *memoize {
let memoize_node_id = NodeId(wrapper_input_count as u64 + 1);
let memoize_node_id = NodeId(input_count as u64 + 1);
let memoize_node = DocumentNode {
inputs: vec![NodeInput::node(main_node_id, 0)],
inputs: vec![NodeInput::node(NodeId(input_count as u64), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_core::memo::memoize::IDENTIFIER.clone()),
visible: true,
..Default::default()
@@ -224,7 +213,7 @@ impl Preprocessor {
nodes.insert(memoize_node_id, memoize_node);
memoize_node_id
} else {
main_node_id
NodeId(input_count as u64)
};
let node = DocumentNode {