mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
62b7ccf40c | ||
|
|
9b45af854a |
No files matched your search
@@ -369,6 +369,40 @@ impl ProtoNetwork {
|
||||
nullification_node_id
|
||||
}
|
||||
|
||||
/// Splices the selected `Ref` adapters between the consumer at `consumer_index` and its
|
||||
/// producers, keeping the node vec topologically sorted and ids stable. `materialized` carries
|
||||
/// the adapter ids already spliced during this update so shared producers get one adapter.
|
||||
fn insert_ref_adapters(&mut self, consumer_index: usize, adapters: &[RefAdapter], materialized: &mut HashSet<NodeId>) {
|
||||
let mut consumer_index = consumer_index;
|
||||
for adapter in adapters {
|
||||
let (_, consumer) = &self.nodes[consumer_index];
|
||||
let producer = consumer.unwrap_construction_nodes()[adapter.input_index];
|
||||
let mut path = consumer.original_location.path.clone();
|
||||
|
||||
// A path extension with a placeholder value which should not conflict with existing paths
|
||||
if let Some(path) = path.as_mut() {
|
||||
path.push(NodeId(11));
|
||||
}
|
||||
|
||||
let node = ProtoNode {
|
||||
construction_args: ConstructionArgs::Nodes(vec![producer]),
|
||||
call_argument: concrete!(Context),
|
||||
identifier: adapter.identifier.clone(),
|
||||
original_location: OriginalLocation { path, ..Default::default() },
|
||||
..Default::default()
|
||||
};
|
||||
let id = node.stable_node_id().expect("adapter nodes always produce a stable id");
|
||||
if materialized.insert(id) {
|
||||
self.nodes.insert(consumer_index, (id, node));
|
||||
consumer_index += 1;
|
||||
}
|
||||
let (_, consumer) = &mut self.nodes[consumer_index];
|
||||
if let ConstructionArgs::Nodes(args) = &mut consumer.construction_args {
|
||||
args[adapter.input_index] = id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn find_context_dependencies(&mut self, id: NodeId) -> (ContextModification, Option<NodeId>) {
|
||||
let mut branch_dependencies = Vec::new();
|
||||
let mut combined_deps = ContextModification::default();
|
||||
@@ -657,15 +691,39 @@ impl TypingContext {
|
||||
|
||||
/// Updates the `TypingContext` with a given proto network. This will infer the types of the nodes
|
||||
/// and store them in the `inferred` field. The proto network has to be topologically sorted
|
||||
/// and contain fully resolved stable node ids.
|
||||
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), GraphErrors> {
|
||||
for (id, node) in network.nodes.iter() {
|
||||
self.infer(*id, node)?;
|
||||
/// and contain fully resolved stable node ids. When a node's inputs disagree with every
|
||||
/// implementation only on `Ref`-ness, the matching lend/clone_out adapter is spliced into the
|
||||
/// network and inference resumes with the adapter in place.
|
||||
pub fn update(&mut self, network: &mut ProtoNetwork) -> Result<(), GraphErrors> {
|
||||
let mut materialized_adapters = HashSet::new();
|
||||
let mut index = 0;
|
||||
while index < network.nodes.len() {
|
||||
let (id, node) = &network.nodes[index];
|
||||
match self.infer(*id, node) {
|
||||
Ok(_) => index += 1,
|
||||
Err(errors) => match self.select_ref_adapters(node) {
|
||||
Some(adapters) => network.insert_ref_adapters(index, &adapters, &mut materialized_adapters),
|
||||
None => return Err(errors),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn select_ref_adapters(&self, node: &ProtoNode) -> Option<Vec<RefAdapter>> {
|
||||
let ConstructionArgs::Nodes(args) = &node.construction_args else { return None };
|
||||
let inputs = args.iter().map(|id| self.inferred.get(id).map(NodeIOTypes::ty)).collect::<Option<Vec<_>>>()?;
|
||||
let candidates: Vec<&NodeIOTypes> = self.lookup.get(&node.identifier)?.iter().map(|entry| &entry.io).collect();
|
||||
let adapters = select_ref_adapters_over(&node.call_argument, &inputs, &candidates)?;
|
||||
let constructible = adapters.iter().all(|adapter| {
|
||||
self.lookup
|
||||
.get(&adapter.identifier)
|
||||
.is_some_and(|entries| entries.iter().any(|entry| entry.io.inputs.len() == 1 && valid_type(&inputs[adapter.input_index], &entry.io.inputs[0])))
|
||||
});
|
||||
constructible.then_some(adapters)
|
||||
}
|
||||
|
||||
pub fn remove_inference(&mut self, node_id: NodeId) -> Option<NodeIOTypes> {
|
||||
self.constructor.remove(&node_id);
|
||||
self.inferred.remove(&node_id)
|
||||
@@ -721,33 +779,6 @@ impl TypingContext {
|
||||
return Err(vec![GraphError::new(node, GraphErrorType::UnexpectedGenerics { index, inputs })]);
|
||||
}
|
||||
|
||||
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
||||
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
||||
fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
match (from, to) {
|
||||
// Direct comparison of two concrete types.
|
||||
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
||||
// Direct comparison of two function types.
|
||||
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
||||
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
||||
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
||||
// This allows us to supply anything to a function that is satisfied with `()`.
|
||||
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
||||
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
||||
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
||||
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
||||
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||
// TODO: Add proper generic counting which is not based on the name
|
||||
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
|
||||
// Reject unknown type relationships.
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
// List of all implementations that match the input types
|
||||
let valid_output_types = candidates
|
||||
.iter()
|
||||
@@ -850,6 +881,87 @@ impl TypingContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks if a proposed input to a particular (primary or secondary) input connector is valid for its type signature.
|
||||
/// `from` indicates the value given to a input, `to` indicates the input's allowed type as specified by its type signature.
|
||||
fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
match (from, to) {
|
||||
// Direct comparison of two concrete types.
|
||||
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
|
||||
// Direct comparison of two function types.
|
||||
// Note: in the presence of subtyping, functions are considered on a "greater than or equal to" basis of its function type's generality.
|
||||
// That means we compare their types with a contravariant relationship, which means that a more general type signature may be substituted for a more specific type signature.
|
||||
// For example, we allow `T -> V` to be substituted with `T' -> V` or `() -> V` where T' and () are more specific than T.
|
||||
// This allows us to supply anything to a function that is satisfied with `()`.
|
||||
// In other words, we are implementing these two relations, where the >= operator means that the left side is more general than the right side:
|
||||
// - `T >= T' ⇒ (T' -> V) >= (T -> V)` (functions are contravariant in their input types)
|
||||
// - `V >= V' ⇒ (T -> V) >= (T -> V')` (functions are covariant in their output types)
|
||||
// While these two relations aren't a truth about the universe, they are a design decision that we are employing in our language design that is also common in other languages.
|
||||
// For example, Rust implements these same relations as it describes here: <https://doc.rust-lang.org/nomicon/subtyping.html>
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// A lend edge is substitutable exactly when the lent values are.
|
||||
(Type::Ref(in1), Type::Ref(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,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct RefAdapter {
|
||||
input_index: usize,
|
||||
identifier: ProtoNodeIdentifier,
|
||||
}
|
||||
|
||||
/// Picks the lend or clone_out adapter that reconciles a proposed edge with a wanted edge when they
|
||||
/// differ only by one `Ref` layer around a concrete output.
|
||||
fn ref_adapter(proposed: &Type, wanted: &Type) -> Option<ProtoNodeIdentifier> {
|
||||
let (Type::Fn(_, proposed_output), Type::Fn(_, wanted_output)) = (proposed, wanted) else {
|
||||
return None;
|
||||
};
|
||||
match (proposed_output.as_ref(), wanted_output.as_ref()) {
|
||||
(Type::Ref(inner), wanted_output @ Type::Concrete(_)) if valid_type(inner, wanted_output) => Some(ProtoNodeIdentifier::new("graphene_core::debug::CloneNode")),
|
||||
(proposed_output @ Type::Concrete(_), Type::Ref(inner)) if valid_type(proposed_output, inner) => Some(ProtoNodeIdentifier::new("graphene_core::memo::LendNode")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects adapters for the single implementation the inputs match modulo `Ref`-ness, or `None`
|
||||
/// when no or several implementations do.
|
||||
fn select_ref_adapters_over(call_argument: &Type, inputs: &[Type], candidates: &[&NodeIOTypes]) -> Option<Vec<RefAdapter>> {
|
||||
let mut selected = None;
|
||||
for candidate in candidates {
|
||||
if !valid_type(&candidate.call_argument, call_argument) || candidate.inputs.len() != inputs.len() {
|
||||
continue;
|
||||
}
|
||||
let mut adapters = Vec::new();
|
||||
let mut fits = true;
|
||||
for (input_index, (proposed, wanted)) in inputs.iter().zip(&candidate.inputs).enumerate() {
|
||||
if valid_type(proposed, wanted) {
|
||||
continue;
|
||||
}
|
||||
match ref_adapter(proposed, wanted) {
|
||||
Some(identifier) => adapters.push(RefAdapter { input_index, identifier }),
|
||||
None => {
|
||||
fits = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !fits || adapters.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if selected.is_some() {
|
||||
return None;
|
||||
}
|
||||
selected = Some(adapters);
|
||||
}
|
||||
selected
|
||||
}
|
||||
|
||||
/// Returns a list of all generic types used in the node
|
||||
fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
|
||||
let inputs = [&types.call_argument].into_iter().chain(types.inputs.iter().map(|x| x.nested_type()));
|
||||
@@ -1161,3 +1273,126 @@ mod test {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod ref_adapter_test {
|
||||
use super::*;
|
||||
|
||||
fn adapter_lookup() -> &'static HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
static LOOKUP: std::sync::LazyLock<HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>> = std::sync::LazyLock::new(|| {
|
||||
let unused: NodeConstructor = |_| Err(ConstructionError::Arity { expected: 0, got: 0 });
|
||||
[
|
||||
(
|
||||
ProtoNodeIdentifier::new("wants_ref"),
|
||||
vec![RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), concrete!(String), vec![lend_edge_type::<String>()]),
|
||||
constructor: unused,
|
||||
}],
|
||||
),
|
||||
(
|
||||
ProtoNodeIdentifier::new("wants_ref_ambiguously"),
|
||||
vec![
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), concrete!(String), vec![lend_edge_type::<String>()]),
|
||||
constructor: unused,
|
||||
},
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), concrete!(f64), vec![lend_edge_type::<String>()]),
|
||||
constructor: unused,
|
||||
},
|
||||
],
|
||||
),
|
||||
(
|
||||
ProtoNodeIdentifier::new("graphene_core::memo::LendNode"),
|
||||
vec![RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), ref_type::<String>(), vec![edge_type::<String>()]),
|
||||
constructor: unused,
|
||||
}],
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect()
|
||||
});
|
||||
&LOOKUP
|
||||
}
|
||||
|
||||
fn string_value() -> ProtoNode {
|
||||
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String("lent".to_string()).into()), vec![])
|
||||
}
|
||||
|
||||
fn consumer(identifier: &str, producer: NodeId) -> ProtoNode {
|
||||
ProtoNode {
|
||||
identifier: ProtoNodeIdentifier::with_owned_string(identifier.to_string()),
|
||||
call_argument: concrete!(Context),
|
||||
construction_args: ConstructionArgs::Nodes(vec![producer]),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ref_only_mismatch_splices_the_lend_adapter() {
|
||||
let mut network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), string_value()), (NodeId(1), consumer("wants_ref", NodeId(0)))],
|
||||
};
|
||||
|
||||
let mut typing = TypingContext::new(adapter_lookup());
|
||||
typing.update(&mut network).unwrap();
|
||||
|
||||
assert_eq!(network.nodes.len(), 3);
|
||||
let (adapter_id, adapter) = &network.nodes[1];
|
||||
assert_eq!(adapter.identifier.as_str(), "graphene_core::memo::LendNode");
|
||||
assert_eq!(adapter.unwrap_construction_nodes(), vec![NodeId(0)]);
|
||||
assert_eq!(network.nodes[2].1.unwrap_construction_nodes(), vec![*adapter_id]);
|
||||
assert_eq!(typing.type_of(*adapter_id).unwrap().return_value, ref_type::<String>());
|
||||
assert_eq!(typing.type_of(NodeId(1)).unwrap().return_value, concrete!(String));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumers_sharing_a_producer_share_one_adapter() {
|
||||
let mut network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(2),
|
||||
nodes: vec![
|
||||
(NodeId(0), string_value()),
|
||||
(NodeId(1), consumer("wants_ref", NodeId(0))),
|
||||
(NodeId(2), consumer("wants_ref", NodeId(0))),
|
||||
],
|
||||
};
|
||||
|
||||
let mut typing = TypingContext::new(adapter_lookup());
|
||||
typing.update(&mut network).unwrap();
|
||||
|
||||
assert_eq!(network.nodes.len(), 4);
|
||||
let adapters: Vec<NodeId> = network
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, node)| node.identifier.as_str() == "graphene_core::memo::LendNode")
|
||||
.map(|(id, _)| *id)
|
||||
.collect();
|
||||
let [adapter_id] = adapters.as_slice() else {
|
||||
panic!("expected exactly one shared adapter, got {adapters:?}");
|
||||
};
|
||||
let consumers: Vec<Vec<NodeId>> = network
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, node)| node.identifier.as_str() == "wants_ref")
|
||||
.map(|(_, node)| node.unwrap_construction_nodes())
|
||||
.collect();
|
||||
assert_eq!(consumers, vec![vec![*adapter_id], vec![*adapter_id]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ambiguous_ref_mismatch_stays_an_error() {
|
||||
let mut network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![(NodeId(0), string_value()), (NodeId(1), consumer("wants_ref_ambiguously", NodeId(0)))],
|
||||
};
|
||||
|
||||
let mut typing = TypingContext::new(adapter_lookup());
|
||||
assert!(typing.update(&mut network).is_err());
|
||||
assert_eq!(network.nodes.len(), 2, "an ambiguous mismatch must not materialize adapters");
|
||||
}
|
||||
}
|
||||
@@ -71,9 +71,9 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
||||
}
|
||||
|
||||
impl DynamicExecutor {
|
||||
pub fn new(proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&proto_network)?;
|
||||
typing_context.update(&mut proto_network)?;
|
||||
let output = proto_network.output;
|
||||
let sources = proto_network.source_ids();
|
||||
let tree = BorrowTree::new(proto_network, &typing_context)?;
|
||||
@@ -102,9 +102,9 @@ impl DynamicExecutor {
|
||||
|
||||
/// Updates the existing [`BorrowTree`] to reflect the new [`ProtoNetwork`], reusing nodes where possible.
|
||||
#[cfg_attr(debug_assertions, inline(never))]
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
pub fn update(&mut self, mut proto_network: ProtoNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
self.output = proto_network.output;
|
||||
self.typing_context.update(&proto_network).map_err(|e| {
|
||||
self.typing_context.update(&mut proto_network).map_err(|e| {
|
||||
// If there is an error then get types that have been resolved before the error
|
||||
let add = proto_network
|
||||
.nodes
|
||||
@@ -546,4 +546,75 @@ mod test {
|
||||
let result: Option<GPoll<u32>> = tree.eval(NodeId(0), &ctx);
|
||||
assert_eq!(result, Some(GPoll::Final(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 a_lend_adapter_is_spliced_between_a_value_and_a_ref_consumer() {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(1),
|
||||
nodes: vec![
|
||||
(NodeId(0), string_value("lent")),
|
||||
(NodeId(1), proto_node("graphene_core::debug::CloneNode", vec![NodeId(0)])),
|
||||
],
|
||||
};
|
||||
|
||||
let executor = DynamicExecutor::new(network).unwrap();
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::String("lent".to_string())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flipped_ref_parameter_gets_its_producer_lend_spliced() {
|
||||
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 result: Option<GPoll<graphene_std::list::List<graphene_std::raster::color::Color>>> = executor.tree().eval(NodeId(2), &ctx);
|
||||
assert!(matches!(result, Some(GPoll::Final(_))), "the palette must evaluate through the spliced lend, got {result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clone_out_adapter_is_spliced_between_a_lending_producer_and_an_owned_consumer() {
|
||||
let network = ProtoNetwork {
|
||||
inputs: vec![],
|
||||
output: NodeId(3),
|
||||
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)])),
|
||||
(NodeId(3), proto_node("graphene_core::debug::CloneNode", vec![NodeId(2)])),
|
||||
],
|
||||
};
|
||||
|
||||
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 lend path must replay across evaluations"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,14 +13,14 @@ use graphene_std::raster::GPU;
|
||||
use graphene_std::raster::color::Color;
|
||||
use graphene_std::raster::*;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::registry::{ConstructionError, EdgeHandle, ErasedNode, NodeIOTypes, RegistryEntry};
|
||||
use graphene_std::registry::{ConstructionError, EdgeHandle, ErasedLendNode, ErasedNode, NodeIOTypes, RegistryEntry, lend_edge_type, ref_type};
|
||||
use graphene_std::render_node::RenderIntermediate;
|
||||
use graphene_std::runtime::RuntimeHandle;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Context, Graphic, ProtoNodeIdentifier, SourceId, concrete, fn_type};
|
||||
use node_registry_macros::{async_node, convert_node, into_node};
|
||||
use node_registry_macros::{async_node, clone_node, convert_node, frame_memo_node, into_node, lend_node};
|
||||
use std::collections::HashMap;
|
||||
#[cfg(feature = "gpu")]
|
||||
use wgpu_executor::WgpuExecutorHandle;
|
||||
@@ -295,6 +295,270 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>> {
|
||||
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]),
|
||||
// ============
|
||||
// REF ADAPTERS
|
||||
// ============
|
||||
lend_node!(()),
|
||||
clone_node!(()),
|
||||
frame_memo_node!(()),
|
||||
lend_node!(RuntimeHandle),
|
||||
clone_node!(RuntimeHandle),
|
||||
frame_memo_node!(RuntimeHandle),
|
||||
lend_node!(SourceId),
|
||||
clone_node!(SourceId),
|
||||
frame_memo_node!(SourceId),
|
||||
lend_node!(bool),
|
||||
clone_node!(bool),
|
||||
frame_memo_node!(bool),
|
||||
lend_node!(List<Artboard>),
|
||||
clone_node!(List<Artboard>),
|
||||
frame_memo_node!(List<Artboard>),
|
||||
lend_node!(List<Graphic>),
|
||||
clone_node!(List<Graphic>),
|
||||
frame_memo_node!(List<Graphic>),
|
||||
lend_node!(List<Vector>),
|
||||
clone_node!(List<Vector>),
|
||||
frame_memo_node!(List<Vector>),
|
||||
lend_node!(List<Raster<CPU>>),
|
||||
clone_node!(List<Raster<CPU>>),
|
||||
frame_memo_node!(List<Raster<CPU>>),
|
||||
lend_node!(List<Color>),
|
||||
clone_node!(List<Color>),
|
||||
frame_memo_node!(List<Color>),
|
||||
lend_node!(Image<Color>),
|
||||
clone_node!(Image<Color>),
|
||||
frame_memo_node!(Image<Color>),
|
||||
lend_node!(List<GradientStops>),
|
||||
clone_node!(List<GradientStops>),
|
||||
frame_memo_node!(List<GradientStops>),
|
||||
lend_node!(List<String>),
|
||||
clone_node!(List<String>),
|
||||
frame_memo_node!(List<String>),
|
||||
lend_node!(List<NodeId>),
|
||||
clone_node!(List<NodeId>),
|
||||
frame_memo_node!(List<NodeId>),
|
||||
lend_node!(List<f64>),
|
||||
clone_node!(List<f64>),
|
||||
frame_memo_node!(List<f64>),
|
||||
lend_node!(List<u8>),
|
||||
clone_node!(List<u8>),
|
||||
frame_memo_node!(List<u8>),
|
||||
lend_node!(List<bool>),
|
||||
clone_node!(List<bool>),
|
||||
frame_memo_node!(List<bool>),
|
||||
lend_node!(List<DAffine2>),
|
||||
clone_node!(List<DAffine2>),
|
||||
frame_memo_node!(List<DAffine2>),
|
||||
lend_node!(List<BlendMode>),
|
||||
clone_node!(List<BlendMode>),
|
||||
frame_memo_node!(List<BlendMode>),
|
||||
lend_node!(List<graphene_std::vector::style::GradientType>),
|
||||
clone_node!(List<graphene_std::vector::style::GradientType>),
|
||||
frame_memo_node!(List<graphene_std::vector::style::GradientType>),
|
||||
lend_node!(List<graphene_std::vector::style::GradientSpreadMethod>),
|
||||
clone_node!(List<graphene_std::vector::style::GradientSpreadMethod>),
|
||||
frame_memo_node!(List<graphene_std::vector::style::GradientSpreadMethod>),
|
||||
lend_node!(AttributeDyn),
|
||||
clone_node!(AttributeDyn),
|
||||
frame_memo_node!(AttributeDyn),
|
||||
lend_node!(AttributeValueDyn),
|
||||
clone_node!(AttributeValueDyn),
|
||||
frame_memo_node!(AttributeValueDyn),
|
||||
lend_node!(ListDyn),
|
||||
clone_node!(ListDyn),
|
||||
frame_memo_node!(ListDyn),
|
||||
#[cfg(target_family = "wasm")]
|
||||
lend_node!(CanvasHandle),
|
||||
#[cfg(target_family = "wasm")]
|
||||
clone_node!(CanvasHandle),
|
||||
#[cfg(target_family = "wasm")]
|
||||
frame_memo_node!(CanvasHandle),
|
||||
lend_node!(f64),
|
||||
clone_node!(f64),
|
||||
frame_memo_node!(f64),
|
||||
lend_node!(f32),
|
||||
clone_node!(f32),
|
||||
frame_memo_node!(f32),
|
||||
lend_node!(u32),
|
||||
clone_node!(u32),
|
||||
frame_memo_node!(u32),
|
||||
lend_node!(u64),
|
||||
clone_node!(u64),
|
||||
frame_memo_node!(u64),
|
||||
lend_node!(DVec2),
|
||||
clone_node!(DVec2),
|
||||
frame_memo_node!(DVec2),
|
||||
lend_node!(String),
|
||||
clone_node!(String),
|
||||
frame_memo_node!(String),
|
||||
lend_node!(DAffine2),
|
||||
clone_node!(DAffine2),
|
||||
frame_memo_node!(DAffine2),
|
||||
lend_node!(Footprint),
|
||||
clone_node!(Footprint),
|
||||
frame_memo_node!(Footprint),
|
||||
lend_node!(RenderOutput),
|
||||
clone_node!(RenderOutput),
|
||||
frame_memo_node!(RenderOutput),
|
||||
lend_node!(std::sync::Arc<PlatformEditorApi>),
|
||||
clone_node!(std::sync::Arc<PlatformEditorApi>),
|
||||
frame_memo_node!(std::sync::Arc<PlatformEditorApi>),
|
||||
#[cfg(feature = "gpu")]
|
||||
lend_node!(List<Raster<GPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
clone_node!(List<Raster<GPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
frame_memo_node!(List<Raster<GPU>>),
|
||||
lend_node!(Option<f64>),
|
||||
clone_node!(Option<f64>),
|
||||
frame_memo_node!(Option<f64>),
|
||||
lend_node!(Option<Color>),
|
||||
clone_node!(Option<Color>),
|
||||
frame_memo_node!(Option<Color>),
|
||||
lend_node!(Graphic),
|
||||
clone_node!(Graphic),
|
||||
frame_memo_node!(Graphic),
|
||||
lend_node!(glam::f32::Vec2),
|
||||
clone_node!(glam::f32::Vec2),
|
||||
frame_memo_node!(glam::f32::Vec2),
|
||||
lend_node!(glam::f32::Affine2),
|
||||
clone_node!(glam::f32::Affine2),
|
||||
frame_memo_node!(glam::f32::Affine2),
|
||||
lend_node!(graphene_std::vector::style::Stroke),
|
||||
clone_node!(graphene_std::vector::style::Stroke),
|
||||
frame_memo_node!(graphene_std::vector::style::Stroke),
|
||||
lend_node!(graphene_std::text::Font),
|
||||
clone_node!(graphene_std::text::Font),
|
||||
frame_memo_node!(graphene_std::text::Font),
|
||||
lend_node!(List<BrushStroke>),
|
||||
clone_node!(List<BrushStroke>),
|
||||
frame_memo_node!(List<BrushStroke>),
|
||||
lend_node!(DocumentNode),
|
||||
clone_node!(DocumentNode),
|
||||
frame_memo_node!(DocumentNode),
|
||||
lend_node!(graphene_std::ContextModification),
|
||||
clone_node!(graphene_std::ContextModification),
|
||||
frame_memo_node!(graphene_std::ContextModification),
|
||||
lend_node!(graphene_std::transform::Footprint),
|
||||
clone_node!(graphene_std::transform::Footprint),
|
||||
frame_memo_node!(graphene_std::transform::Footprint),
|
||||
lend_node!(Box<graphene_std::vector::VectorModification>),
|
||||
clone_node!(Box<graphene_std::vector::VectorModification>),
|
||||
frame_memo_node!(Box<graphene_std::vector::VectorModification>),
|
||||
lend_node!(graphene_std::blending::BlendMode),
|
||||
clone_node!(graphene_std::blending::BlendMode),
|
||||
frame_memo_node!(graphene_std::blending::BlendMode),
|
||||
lend_node!(graphene_std::raster::LuminanceCalculation),
|
||||
clone_node!(graphene_std::raster::LuminanceCalculation),
|
||||
frame_memo_node!(graphene_std::raster::LuminanceCalculation),
|
||||
lend_node!(graphene_std::vector::QRCodeErrorCorrectionLevel),
|
||||
clone_node!(graphene_std::vector::QRCodeErrorCorrectionLevel),
|
||||
frame_memo_node!(graphene_std::vector::QRCodeErrorCorrectionLevel),
|
||||
lend_node!(graphene_std::extract_xy::XY),
|
||||
clone_node!(graphene_std::extract_xy::XY),
|
||||
frame_memo_node!(graphene_std::extract_xy::XY),
|
||||
lend_node!(graphene_std::text_nodes::StringCapitalization),
|
||||
clone_node!(graphene_std::text_nodes::StringCapitalization),
|
||||
frame_memo_node!(graphene_std::text_nodes::StringCapitalization),
|
||||
lend_node!(graphene_std::raster::RedGreenBlue),
|
||||
clone_node!(graphene_std::raster::RedGreenBlue),
|
||||
frame_memo_node!(graphene_std::raster::RedGreenBlue),
|
||||
lend_node!(graphene_std::raster::RedGreenBlueAlpha),
|
||||
clone_node!(graphene_std::raster::RedGreenBlueAlpha),
|
||||
frame_memo_node!(graphene_std::raster::RedGreenBlueAlpha),
|
||||
lend_node!(graphene_std::animation::RealTimeMode),
|
||||
clone_node!(graphene_std::animation::RealTimeMode),
|
||||
frame_memo_node!(graphene_std::animation::RealTimeMode),
|
||||
lend_node!(graphene_std::raster::NoiseType),
|
||||
clone_node!(graphene_std::raster::NoiseType),
|
||||
frame_memo_node!(graphene_std::raster::NoiseType),
|
||||
lend_node!(graphene_std::raster::FractalType),
|
||||
clone_node!(graphene_std::raster::FractalType),
|
||||
frame_memo_node!(graphene_std::raster::FractalType),
|
||||
lend_node!(graphene_std::raster::CellularDistanceFunction),
|
||||
clone_node!(graphene_std::raster::CellularDistanceFunction),
|
||||
frame_memo_node!(graphene_std::raster::CellularDistanceFunction),
|
||||
lend_node!(graphene_std::raster::CellularReturnType),
|
||||
clone_node!(graphene_std::raster::CellularReturnType),
|
||||
frame_memo_node!(graphene_std::raster::CellularReturnType),
|
||||
lend_node!(graphene_std::raster::DomainWarpType),
|
||||
clone_node!(graphene_std::raster::DomainWarpType),
|
||||
frame_memo_node!(graphene_std::raster::DomainWarpType),
|
||||
lend_node!(graphene_std::raster::RelativeAbsolute),
|
||||
clone_node!(graphene_std::raster::RelativeAbsolute),
|
||||
frame_memo_node!(graphene_std::raster::RelativeAbsolute),
|
||||
lend_node!(graphene_std::raster::SelectiveColorChoice),
|
||||
clone_node!(graphene_std::raster::SelectiveColorChoice),
|
||||
frame_memo_node!(graphene_std::raster::SelectiveColorChoice),
|
||||
lend_node!(graphene_std::vector::misc::GridType),
|
||||
clone_node!(graphene_std::vector::misc::GridType),
|
||||
frame_memo_node!(graphene_std::vector::misc::GridType),
|
||||
lend_node!(graphene_std::vector::misc::ArcType),
|
||||
clone_node!(graphene_std::vector::misc::ArcType),
|
||||
frame_memo_node!(graphene_std::vector::misc::ArcType),
|
||||
lend_node!(graphene_std::vector::misc::RowsOrColumns),
|
||||
clone_node!(graphene_std::vector::misc::RowsOrColumns),
|
||||
frame_memo_node!(graphene_std::vector::misc::RowsOrColumns),
|
||||
lend_node!(graphene_std::vector::misc::MergeByDistanceAlgorithm),
|
||||
clone_node!(graphene_std::vector::misc::MergeByDistanceAlgorithm),
|
||||
frame_memo_node!(graphene_std::vector::misc::MergeByDistanceAlgorithm),
|
||||
lend_node!(graphene_std::vector::misc::ExtrudeJoiningAlgorithm),
|
||||
clone_node!(graphene_std::vector::misc::ExtrudeJoiningAlgorithm),
|
||||
frame_memo_node!(graphene_std::vector::misc::ExtrudeJoiningAlgorithm),
|
||||
lend_node!(graphene_std::vector::misc::PointSpacingType),
|
||||
clone_node!(graphene_std::vector::misc::PointSpacingType),
|
||||
frame_memo_node!(graphene_std::vector::misc::PointSpacingType),
|
||||
lend_node!(graphene_std::vector::style::StrokeCap),
|
||||
clone_node!(graphene_std::vector::style::StrokeCap),
|
||||
frame_memo_node!(graphene_std::vector::style::StrokeCap),
|
||||
lend_node!(graphene_std::vector::style::StrokeJoin),
|
||||
clone_node!(graphene_std::vector::style::StrokeJoin),
|
||||
frame_memo_node!(graphene_std::vector::style::StrokeJoin),
|
||||
lend_node!(graphene_std::vector::style::StrokeAlign),
|
||||
clone_node!(graphene_std::vector::style::StrokeAlign),
|
||||
frame_memo_node!(graphene_std::vector::style::StrokeAlign),
|
||||
lend_node!(graphene_std::vector::style::PaintOrder),
|
||||
clone_node!(graphene_std::vector::style::PaintOrder),
|
||||
frame_memo_node!(graphene_std::vector::style::PaintOrder),
|
||||
lend_node!(graphene_std::vector::style::GradientType),
|
||||
clone_node!(graphene_std::vector::style::GradientType),
|
||||
frame_memo_node!(graphene_std::vector::style::GradientType),
|
||||
lend_node!(graphene_std::vector::style::GradientSpreadMethod),
|
||||
clone_node!(graphene_std::vector::style::GradientSpreadMethod),
|
||||
frame_memo_node!(graphene_std::vector::style::GradientSpreadMethod),
|
||||
lend_node!(Option<DAffine2>),
|
||||
clone_node!(Option<DAffine2>),
|
||||
frame_memo_node!(Option<DAffine2>),
|
||||
lend_node!(graphene_std::transform::ReferencePoint),
|
||||
clone_node!(graphene_std::transform::ReferencePoint),
|
||||
frame_memo_node!(graphene_std::transform::ReferencePoint),
|
||||
lend_node!(graphene_std::vector::misc::CentroidType),
|
||||
clone_node!(graphene_std::vector::misc::CentroidType),
|
||||
frame_memo_node!(graphene_std::vector::misc::CentroidType),
|
||||
lend_node!(graphene_std::vector::misc::BooleanOperation),
|
||||
clone_node!(graphene_std::vector::misc::BooleanOperation),
|
||||
frame_memo_node!(graphene_std::vector::misc::BooleanOperation),
|
||||
lend_node!(graphene_std::text::TextAlign),
|
||||
clone_node!(graphene_std::text::TextAlign),
|
||||
frame_memo_node!(graphene_std::text::TextAlign),
|
||||
lend_node!(graphene_std::transform::ScaleType),
|
||||
clone_node!(graphene_std::transform::ScaleType),
|
||||
frame_memo_node!(graphene_std::transform::ScaleType),
|
||||
lend_node!(graphene_std::vector::misc::InterpolationDistribution),
|
||||
clone_node!(graphene_std::vector::misc::InterpolationDistribution),
|
||||
frame_memo_node!(graphene_std::vector::misc::InterpolationDistribution),
|
||||
lend_node!(RenderIntermediate),
|
||||
clone_node!(RenderIntermediate),
|
||||
frame_memo_node!(RenderIntermediate),
|
||||
lend_node!(wgpu_executor::WgpuExecutorHandle),
|
||||
clone_node!(wgpu_executor::WgpuExecutorHandle),
|
||||
frame_memo_node!(wgpu_executor::WgpuExecutorHandle),
|
||||
lend_node!(Option<wgpu_executor::WgpuExecutorHandle>),
|
||||
clone_node!(Option<wgpu_executor::WgpuExecutorHandle>),
|
||||
frame_memo_node!(Option<wgpu_executor::WgpuExecutorHandle>),
|
||||
lend_node!(wgpu_executor::WgpuPipelineCache),
|
||||
clone_node!(wgpu_executor::WgpuPipelineCache),
|
||||
frame_memo_node!(wgpu_executor::WgpuPipelineCache),
|
||||
];
|
||||
// =============
|
||||
// CONVERT NODES
|
||||
@@ -486,7 +750,67 @@ mod node_registry_macros {
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! lend_node {
|
||||
($type:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new("graphene_core::memo::LendNode"),
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), ref_type::<$type>(), vec![fn_type!(Context, $type)]),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 1 {
|
||||
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let node = graphene_core::memo::LendNode::new(inputs.next().unwrap().downcast::<$type>()?);
|
||||
Ok(EdgeHandle::new_ref(std::sync::Arc::new(node) as std::sync::Arc<ErasedLendNode<$type>>))
|
||||
},
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! clone_node {
|
||||
($type:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new("graphene_core::debug::CloneNode"),
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), concrete!($type), vec![lend_edge_type::<$type>()]),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 1 {
|
||||
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let node = graphene_core::debug::CloneNode::new(inputs.next().unwrap().downcast_lend::<$type>()?);
|
||||
Ok(EdgeHandle::new(std::sync::Arc::new(node) as std::sync::Arc<ErasedNode<$type>>))
|
||||
},
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
macro_rules! frame_memo_node {
|
||||
($type:ty) => {
|
||||
(
|
||||
ProtoNodeIdentifier::new("graphene_core::memo::FrameMemoNode"),
|
||||
RegistryEntry {
|
||||
io: NodeIOTypes::new(concrete!(Context), ref_type::<$type>(), vec![fn_type!(Context, $type)]),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 1 {
|
||||
return Err(ConstructionError::Arity { expected: 1, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
let node = graphene_core::memo::FrameMemoNode::new(inputs.next().unwrap().downcast::<$type>()?);
|
||||
Ok(EdgeHandle::new_ref(std::sync::Arc::new(node) as std::sync::Arc<ErasedLendNode<$type>>))
|
||||
},
|
||||
},
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) use async_node;
|
||||
pub(crate) use clone_node;
|
||||
pub(crate) use convert_node;
|
||||
pub(crate) use frame_memo_node;
|
||||
pub(crate) use into_node;
|
||||
pub(crate) use lend_node;
|
||||
}
|
||||
@@ -88,8 +88,12 @@ pub fn edge_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn ref_type<T: 'static>() -> Type {
|
||||
Type::Ref(Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn lend_edge_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Ref(Box::new(concrete!(T)))))
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(ref_type::<T>()))
|
||||
}
|
||||
|
||||
pub fn cache_key<C: CacheHash + ?Sized>(ctx: &C) -> u64 {
|
||||
|
||||
@@ -633,6 +633,27 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
]);
|
||||
}
|
||||
|
||||
let has_lend = parsed.fields.iter().any(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. })));
|
||||
let declared_arena_lifetime = ctx_param.and_then(|ctx_param| {
|
||||
ctx_param.bounds.iter().find_map(|bound| {
|
||||
let TypeParamBound::Trait(trait_bound) = bound else { return None };
|
||||
let segment = trait_bound.path.segments.last()?;
|
||||
if segment.ident != "ExtractArena" {
|
||||
return None;
|
||||
}
|
||||
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
|
||||
match args.args.first() {
|
||||
Some(GenericArgument::Lifetime(lifetime)) => Some(lifetime.clone()),
|
||||
_ => None,
|
||||
}
|
||||
})
|
||||
});
|
||||
let introduced_lend_lifetime = (has_lend && declared_arena_lifetime.is_none()).then(|| Lifetime::new("'__lend", proc_macro2::Span::call_site()));
|
||||
let lend_lifetime = declared_arena_lifetime.or_else(|| introduced_lend_lifetime.clone());
|
||||
if let Some(lifetime) = &introduced_lend_lifetime {
|
||||
ctx_bounds.push(quote!(#core_types::context::ExtractArena<ArenaRef = &#lifetime #core_types::arena::Arena>));
|
||||
}
|
||||
|
||||
let derives = ctx_param.is_some_and(|ctx_param| {
|
||||
ctx_param.bounds.iter().any(|bound| match bound {
|
||||
TypeParamBound::Trait(trait_bound) => trait_bound.path.segments.last().is_some_and(|segment| segment.ident == "DeriveCtx"),
|
||||
@@ -655,6 +676,9 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
if ctx_param.is_none() {
|
||||
generics.push(ctx_generic);
|
||||
}
|
||||
if let Some(lifetime) = &introduced_lend_lifetime {
|
||||
generics.insert(0, quote!(#lifetime));
|
||||
}
|
||||
|
||||
let fn_name = &parsed.fn_name;
|
||||
let mod_name = format_ident!("_{}_mod", parsed.mod_name);
|
||||
@@ -702,6 +726,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let kernel_params = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).map(|field| {
|
||||
let pat = &field.pat_ident;
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(#pat: &#ty),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#pat: #ty),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) if raw_lazy => {
|
||||
let bound = lazy_bound(output_type);
|
||||
@@ -715,6 +740,10 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
});
|
||||
|
||||
let node_bounds = regular_fields.iter().zip(&node_generics).map(|(field, node_generic)| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => {
|
||||
let lifetime = lend_lifetime.as_ref().expect("lend fields imply the lend lifetime");
|
||||
quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = &#lifetime #ty>)
|
||||
}
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #ty>),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||
let bound = lazy_bound(output_type);
|
||||
@@ -722,6 +751,23 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
});
|
||||
|
||||
let mut lend_outlives: Vec<TokenStream2> = regular_fields
|
||||
.iter()
|
||||
.filter_map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => {
|
||||
let lifetime = lend_lifetime.as_ref().expect("lend fields imply the lend lifetime");
|
||||
Some(quote!(#ty: #lifetime))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if let Type::Reference(reference) = &trait_output
|
||||
&& let Some(lifetime) = &reference.lifetime
|
||||
{
|
||||
let inner = &reference.elem;
|
||||
lend_outlives.push(quote!(#inner: #lifetime));
|
||||
}
|
||||
|
||||
let mut async_bounds = match (async_fn, future_kernel) {
|
||||
(false, false) => Vec::new(),
|
||||
(false, true) => vec![quote!(#trait_output: Clone)],
|
||||
@@ -1007,6 +1053,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
impl<#(#generics,)* #(#node_generics,)*> #core_types::node::Node<#ctx_ident> for #mod_name::#struct_name<#(#struct_type_params,)*>
|
||||
where
|
||||
#(#node_bounds,)*
|
||||
#(#lend_outlives,)*
|
||||
#(#clampable_bounds,)*
|
||||
#(#async_bounds,)*
|
||||
#(#where_predicates,)*
|
||||
@@ -1181,22 +1228,60 @@ fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic
|
||||
return quote!();
|
||||
}
|
||||
|
||||
let ref_output_inner = match slot_value_type(&parsed.output_type) {
|
||||
Type::Reference(reference) => Some((*reference.elem).clone()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(inner) = &ref_output_inner {
|
||||
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
|
||||
let open_generics = 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,
|
||||
});
|
||||
if open_generics.into_iter().any(|generic| type_contains_ident(inner, generic)) {
|
||||
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 lend_flags: Vec<bool> = regular_fields
|
||||
.iter()
|
||||
.map(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. })))
|
||||
.collect();
|
||||
|
||||
let entries = rows.iter().map(|row| {
|
||||
let types = row.iter();
|
||||
let edge_types = row.iter().map(|ty| quote!(gcore::registry::SharedEdge<gcore::registry::ErasedNode<#ty>>));
|
||||
let input_types = row.iter().zip(&lend_flags).map(|(ty, lend)| match lend {
|
||||
true => quote!(gcore::registry::lend_edge_type::<#ty>()),
|
||||
false => quote!(gcore::registry::edge_type::<#ty>()),
|
||||
});
|
||||
let edge_types = row.iter().zip(&lend_flags).map(|(ty, lend)| match lend {
|
||||
true => quote!(gcore::registry::SharedEdge<gcore::registry::ErasedLendNode<#ty>>),
|
||||
false => quote!(gcore::registry::SharedEdge<gcore::registry::ErasedNode<#ty>>),
|
||||
});
|
||||
let output = quote!(<#struct_name<#(#edge_types),*> as gcore::node::Node<gcore::context::ContextImpl<'static>>>::Output);
|
||||
let downcasts = names.iter().zip(row.iter()).map(|(name, ty)| quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;));
|
||||
let (io_output, construct) = match &ref_output_inner {
|
||||
Some(inner) => (
|
||||
quote!(gcore::registry::ref_type::<#inner>()),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_ref(::std::sync::Arc::new(#struct_name::new(#(#names),*)) as ::std::sync::Arc<gcore::registry::ErasedLendNode<#inner>>))),
|
||||
),
|
||||
None => (
|
||||
quote!(gcore::concrete!(#output)),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new(::std::sync::Arc::new(#struct_name::new(#(#names),*)) as ::std::sync::Arc<gcore::registry::ErasedNode<#output>>))),
|
||||
),
|
||||
};
|
||||
let downcasts = names.iter().zip(row.iter()).zip(&lend_flags).map(|((name, ty), lend)| match lend {
|
||||
true => quote!(let #name = inputs.next().unwrap().downcast_lend::<#ty>()?;),
|
||||
false => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
|
||||
});
|
||||
quote! {
|
||||
gcore::registry::RegistryEntry {
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
gcore::concrete!(#output),
|
||||
vec![#(gcore::registry::edge_type::<#types>()),*],
|
||||
#io_output,
|
||||
vec![#(#input_types),*],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
@@ -1204,7 +1289,7 @@ fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
Ok(gcore::registry::EdgeHandle::new(::std::sync::Arc::new(#struct_name::new(#(#names),*)) as ::std::sync::Arc<gcore::registry::ErasedNode<#output>>))
|
||||
#construct
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,6 +240,8 @@ impl Parse for NumberRange {
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegularParsedField {
|
||||
pub ty: Type,
|
||||
/// The original reference tokens when the parameter was written `&T`; `ty` holds the peeled inner type.
|
||||
pub lend: Option<syn::TypeReference>,
|
||||
pub exposed: bool,
|
||||
pub value_source: ParsedValueSource,
|
||||
pub number_soft_min: Option<NumberBound>,
|
||||
@@ -904,6 +906,11 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
|
||||
let (ty, lend) = match ty {
|
||||
Type::Reference(reference) => ((*reference.elem).clone(), Some(reference)),
|
||||
ty => (ty, None),
|
||||
};
|
||||
|
||||
// Error if a float literal is given for a bound on an integer-typed field
|
||||
if is_integer_type(&ty) {
|
||||
let bound_attrs = [
|
||||
@@ -936,6 +943,7 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
|
||||
number_hard_max,
|
||||
number_mode_range,
|
||||
ty,
|
||||
lend,
|
||||
value_source,
|
||||
implementations,
|
||||
gpu_image,
|
||||
@@ -1048,6 +1056,7 @@ impl ParsedNodeFn {
|
||||
widget_override: ParsedWidgetOverride::Hidden,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty,
|
||||
lend: None,
|
||||
exposed: false,
|
||||
value_source,
|
||||
number_soft_min: None,
|
||||
@@ -1218,6 +1227,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1308,6 +1318,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(DVec2),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1380,6 +1391,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::Default(quote!(50.)),
|
||||
@@ -1450,6 +1462,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1532,6 +1545,7 @@ mod tests {
|
||||
description: String::from("b"),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(f64),
|
||||
exposed: false,
|
||||
value_source: ParsedValueSource::None,
|
||||
@@ -1617,6 +1631,7 @@ mod tests {
|
||||
description: String::new(),
|
||||
widget_override: ParsedWidgetOverride::None,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
lend: None,
|
||||
ty: parse_quote!(String),
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::None,
|
||||
|
||||
@@ -232,6 +232,7 @@ impl PerPixelAdjustCodegen<'_> {
|
||||
widget_override: Default::default(),
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
|
||||
lend: None,
|
||||
exposed: true,
|
||||
value_source: ParsedValueSource::Scope(Box::new(parse_quote!("graphene_std::platform_application_io::WgpuExecutorNode"))),
|
||||
number_soft_min: None,
|
||||
|
||||
@@ -12,6 +12,7 @@ pub fn validate_node_fn(parsed: &ParsedNodeFn) -> syn::Result<()> {
|
||||
validate_min_max,
|
||||
validate_range_slider_bounds,
|
||||
validate_async_source,
|
||||
validate_lend_fields,
|
||||
];
|
||||
|
||||
for validator in validators {
|
||||
@@ -63,6 +64,30 @@ fn validate_async_source(parsed: &ParsedNodeFn) {
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_lend_fields(parsed: &ParsedNodeFn) {
|
||||
let future_kernel = crate::codegen::is_source_kernel(&parsed.output_type);
|
||||
for field in &parsed.fields {
|
||||
let ParsedFieldType::Regular(RegularParsedField { lend: Some(reference), .. }) = &field.ty else {
|
||||
continue;
|
||||
};
|
||||
if let Some(mutability) = &reference.mutability {
|
||||
emit_error!(mutability.span(), "reference parameters are read-only lends; `&mut` is not supported");
|
||||
}
|
||||
if let Some(lifetime) = &reference.lifetime {
|
||||
emit_error!(lifetime.span(), "reference parameters use the eval lifetime implicitly; write a bare `&T`");
|
||||
}
|
||||
if field.is_data_field {
|
||||
emit_error!(field.pat_ident.span(), "`#[data]` fields are node-resident state and cannot be references");
|
||||
}
|
||||
if parsed.is_async || future_kernel {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"source kernels move their inputs into the spawned task, so they cannot take reference parameters"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_min_max(parsed: &ParsedNodeFn) {
|
||||
for field in &parsed.fields {
|
||||
if let ParsedField {
|
||||
|
||||
@@ -29,8 +29,8 @@ fn unwrap_option<T: Default>(_: impl Ctx, #[implementations(Option<f64>, Option<
|
||||
input.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Meant for debugging purposes, not general use. Clones the input value.
|
||||
/// Clones the value borrowed from a lending edge. Doubles as the checker-inserted clone-out adapter.
|
||||
#[node_macro::node(category("Debug"))]
|
||||
fn clone<'i, T: Clone + 'i>(_: impl Ctx, #[implementations(&List<Raster<CPU>>)] value: &'i T) -> T {
|
||||
fn clone<T: Clone>(_: impl Ctx, #[implementations(List<Raster<CPU>>)] value: &T) -> T {
|
||||
value.clone()
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use core_types::arena::{Arena, ArenaCell};
|
||||
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll};
|
||||
use core_types::context::{Ctx, CtxSnapshot, DeriveCtx, ExtractAll, ExtractArena};
|
||||
use core_types::frame_table::{FrameTable, Lookup};
|
||||
use core_types::gpoll::{Extent, Finality, GPoll, Interrupt};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
@@ -102,6 +102,12 @@ pub fn park<T: Send + Sync>(arena: &Arena, result: GPoll<T>) -> GPoll<&T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adapts an owned edge to a lending one by parking each result in the eval arena.
|
||||
#[node_macro::node(category(""), path(graphene_core::memo), skip_impl)]
|
||||
fn lend<'e, T: Send + Sync>(ctx: impl Ctx + ExtractArena<'e>, value: T) -> GPoll<&'e T> {
|
||||
park(ctx.arena(), GPoll::Final(value))
|
||||
}
|
||||
|
||||
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.
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user