mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
849d6a17be | ||
|
|
20ba069fe0 | ||
|
|
c82093f153 | ||
|
|
010785d8db | ||
|
|
69774d445c | ||
|
|
b42c632474 | ||
|
|
f195e363a5 | ||
|
|
40f99152ce | ||
|
|
3b1170b148 | ||
|
|
3a20091d3a | ||
|
|
e5206c3b50 | ||
|
|
fbc736e1cc | ||
|
|
d7da2ba9e7 | ||
|
|
a5784c8f0b | ||
|
|
83fbaca6f2 |
No files matched your search
@@ -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()).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
compiler.compile_single(network.clone(), None).map_err(|e| format!("Compilation failed: {:?}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -438,7 +438,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) {
|
||||
let proto_network = match c.compile_single(scoped_network, None) {
|
||||
Ok(network) => network,
|
||||
Err(e) => return Err((ResolvedDocumentNodeTypesDelta::default(), e)),
|
||||
};
|
||||
|
||||
@@ -166,6 +166,7 @@ impl DocumentNode {
|
||||
original_location: self.original_location,
|
||||
skip_deduplication: self.skip_deduplication,
|
||||
context_features: self.context_features,
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,6 +263,25 @@ 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 {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use crate::document::NodeNetwork;
|
||||
use crate::proto::ProtoNetwork;
|
||||
use crate::proto::{ProtoNetwork, Registry};
|
||||
use std::error::Error;
|
||||
|
||||
pub struct Compiler {}
|
||||
|
||||
impl Compiler {
|
||||
pub fn compile(&self, mut network: NodeNetwork) -> impl Iterator<Item = Result<ProtoNetwork, String>> {
|
||||
pub fn compile<'r>(&self, mut network: NodeNetwork, registry: Option<&'r Registry>) -> impl Iterator<Item = Result<ProtoNetwork, String>> + 'r {
|
||||
network.resolve_scope_inputs();
|
||||
network.generate_node_paths(&[]);
|
||||
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
|
||||
@@ -19,13 +19,17 @@ 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) -> Result<ProtoNetwork, String> {
|
||||
pub fn compile_single(&self, network: NodeNetwork, registry: Option<&Registry>) -> Result<ProtoNetwork, String> {
|
||||
assert_eq!(network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
let Some(proto_network) = self.compile(network).next() else {
|
||||
let Some(proto_network) = self.compile(network, registry).next() else {
|
||||
return Err("Failed to convert graph into proto graph".to_string());
|
||||
};
|
||||
proto_network
|
||||
|
||||
+192
-107
@@ -124,6 +124,20 @@ 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.
|
||||
@@ -134,6 +148,8 @@ 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 {
|
||||
@@ -145,6 +161,7 @@ impl Default for ProtoNode {
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
context_features: Default::default(),
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,6 +202,7 @@ impl ProtoNode {
|
||||
},
|
||||
skip_deduplication: false,
|
||||
context_features: Default::default(),
|
||||
resolved: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,6 +220,10 @@ 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)]
|
||||
@@ -303,6 +325,65 @@ impl ProtoNetwork {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts context nullification nodes to optimize caching.
|
||||
/// This analysis is performed after topological sorting to ensure proper dependency tracking.
|
||||
pub fn insert_context_nullification_nodes(&mut self) -> Result<(), String> {
|
||||
@@ -643,23 +724,29 @@ 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, HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>>,
|
||||
lookup: Cow<'static, Registry>,
|
||||
inferred: HashMap<NodeId, NodeIOTypes>,
|
||||
constructor: HashMap<NodeId, NodeConstructor>,
|
||||
}
|
||||
|
||||
impl TypingContext {
|
||||
/// Creates a new `TypingContext` with the given lookup table.
|
||||
pub fn new(lookup: &'static HashMap<ProtoNodeIdentifier, Vec<RegistryEntry>>) -> Self {
|
||||
pub fn new(lookup: &'static Registry) -> 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.
|
||||
@@ -715,115 +802,113 @@ 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 candidates: Vec<(NodeIOTypes, NodeConstructor)> = impls.iter().map(|entry| (entry.io.clone(), entry.constructor)).collect();
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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 })]);
|
||||
/// 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: 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);
|
||||
}
|
||||
}
|
||||
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 })])
|
||||
}
|
||||
[(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;
|
||||
}
|
||||
return Ok((node_io.clone(), *entry));
|
||||
}
|
||||
}
|
||||
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 })])
|
||||
}
|
||||
|
||||
// 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<_>>();
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
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 })])
|
||||
}
|
||||
[(node_io, constructor)] => {
|
||||
let node_io = node_io.clone();
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// 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 })])
|
||||
}
|
||||
_ => {
|
||||
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 })])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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).unwrap()
|
||||
compiler.compile_single(network, None).unwrap()
|
||||
}
|
||||
|
||||
pub fn load_from_name(name: &str) -> NodeNetwork {
|
||||
|
||||
@@ -314,7 +314,7 @@ fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd:
|
||||
}
|
||||
|
||||
let compiler = Compiler {};
|
||||
compiler.compile_single(network).map_err(|x| x.into())
|
||||
compiler.compile_single(network, Some(&interpreted_executor::node_registry::NODE_REGISTRY)).map_err(|x| x.into())
|
||||
}
|
||||
|
||||
fn create_executor(proto_network: ProtoNetwork, runtime: Arc<DynGraphRuntime>) -> Result<DynamicExecutor, Box<dyn Error>> {
|
||||
|
||||
@@ -476,6 +476,7 @@ 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"),
|
||||
@@ -483,6 +484,7 @@ 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());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -44,7 +44,7 @@ mod tests {
|
||||
use graph_craft::graphene_compiler::Compiler;
|
||||
|
||||
let compiler = Compiler {};
|
||||
let protograph = compiler.compile_single(network).expect("Graph should be generated");
|
||||
let protograph = compiler.compile_single(network, Some(&crate::node_registry::NODE_REGISTRY)).expect("Graph should be generated");
|
||||
|
||||
let _exec = DynamicExecutor::new(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||
}
|
||||
|
||||
@@ -249,20 +249,34 @@ pub fn empty_layout() -> &'static Layout {
|
||||
/// calls it over the proto graph instead.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LayoutMeta {
|
||||
/// Whether the node derives its layout from a carrier input; `false` writes
|
||||
/// a fresh record from `Layout::default`.
|
||||
pub carrier: bool,
|
||||
/// The output element: a concrete write, or carried through from the carrier.
|
||||
/// Input indices whose layouts union to form the base: `[]` writes a fresh
|
||||
/// record, `[i]` derives from a single carrier, `[i, j, ..]` unions routing
|
||||
/// sources.
|
||||
pub sources: Vec<u8>,
|
||||
/// Attributes read from each input. Unused by [`fold`](LayoutMeta::fold);
|
||||
/// recorded for later compiler analysis (read-offset resolution, per-name
|
||||
/// cache dependencies, residency).
|
||||
pub reads: Vec<InputReads>,
|
||||
/// The output element: a concrete write, or carried through from the base.
|
||||
pub element: ElementSpec,
|
||||
/// The attributes the node writes at its acting level.
|
||||
pub writes: Vec<FieldWrite>,
|
||||
/// The attributes removed from the carrier's layout, as `(name, level)`.
|
||||
/// The attributes removed from the base layout, as `(name, level)`.
|
||||
pub removes: Vec<(&'static str, u8)>,
|
||||
/// The depth change the node applies to its carrier: `0` for elementwise and
|
||||
/// flip nodes, `+1` for a creator, `-1` for a reducer.
|
||||
/// The depth change the node applies: `0` for elementwise and flip nodes,
|
||||
/// `+1` for a creator, `-1` for a reducer.
|
||||
pub level_delta: i8,
|
||||
}
|
||||
|
||||
/// The attributes a node reads from one input, recorded on [`LayoutMeta`] for
|
||||
/// later compiler analysis. A read and a write of an attribute carry the same
|
||||
/// [`FieldWrite`] descriptor; the direction is the position on the node.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct InputReads {
|
||||
pub input: u8,
|
||||
pub reads: Vec<FieldWrite>,
|
||||
}
|
||||
|
||||
/// Where a node's output element comes from, for [`LayoutMeta`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ElementSpec {
|
||||
@@ -273,16 +287,21 @@ pub enum ElementSpec {
|
||||
}
|
||||
|
||||
impl LayoutMeta {
|
||||
/// Folds the node's output layout from its carrier's, reproducing what the
|
||||
/// node's constructor derives at wiring. `carrier` is the carrier input's
|
||||
/// layout, or `None` when the node writes a fresh record.
|
||||
pub fn fold(&self, carrier: Option<&Layout>) -> Layout {
|
||||
let carrier = carrier.filter(|_| self.carrier);
|
||||
let base = carrier.map_or_else(Layout::default, |c| c.without(&self.removes));
|
||||
let depth = (carrier.map_or(0, |c| c.depth) as i8 + self.level_delta).max(0) as u8;
|
||||
/// Folds the node's output layout from its inputs', reproducing what the
|
||||
/// node's constructor derives at wiring. `inputs` is indexed by proto-input
|
||||
/// position; [`sources`](LayoutMeta::sources) selects the base layouts, which
|
||||
/// union (empty writes a fresh record).
|
||||
pub fn fold(&self, inputs: &[Option<&Layout>]) -> Layout {
|
||||
let sources: Vec<&Layout> = self.sources.iter().map(|&i| inputs[i as usize].expect("layout fold source input has no layout")).collect();
|
||||
let base = match sources.as_slice() {
|
||||
[] => Layout::default(),
|
||||
sources => Layout::union(sources),
|
||||
}
|
||||
.without(&self.removes);
|
||||
let depth = (base.depth as i8 + self.level_delta).max(0) as u8;
|
||||
let element = match &self.element {
|
||||
ElementSpec::Concrete(element) => *element,
|
||||
ElementSpec::Carried => carrier.map_or_else(ElementWrite::default, |c| c.element),
|
||||
ElementSpec::Carried => base.element,
|
||||
};
|
||||
base.with_writes(depth, element, &self.writes)
|
||||
}
|
||||
|
||||
@@ -12,9 +12,11 @@ use crate::shader_nodes::{ShaderCodegen, ShaderTokens};
|
||||
|
||||
mod classify;
|
||||
mod entries;
|
||||
pub(crate) mod ir;
|
||||
mod metadata;
|
||||
pub(crate) use classify::*;
|
||||
use entries::entries_tokens;
|
||||
use ir::{LazyBinding, ValueBinding};
|
||||
use metadata::generate_node_input_references;
|
||||
|
||||
static NODE_ID: AtomicU64 = AtomicU64::new(0);
|
||||
@@ -50,19 +52,18 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let (data_fields, regular_fields): (Vec<_>, Vec<_>) = fields.iter().partition(|f| f.is_data_field);
|
||||
|
||||
let model = analyze(parsed);
|
||||
let class = model.as_ref().map(|model| &model.class);
|
||||
let record = match class {
|
||||
Some(Class::RecordIo(shape)) => Some(shape.clone()),
|
||||
let node = crate::codegen::ir::build(parsed);
|
||||
let kind = model.as_ref().map(|_| crate::codegen::ir::node_kind(&node));
|
||||
let carrier_present = node.inputs.first().is_some_and(|input| input.subject);
|
||||
let record_io = matches!(kind, Some(crate::codegen::ir::NodeKind::RecordIo));
|
||||
let flip = matches!(kind, Some(crate::codegen::ir::NodeKind::Flip));
|
||||
let carrier_flip = flip && carrier_present;
|
||||
let opaque = matches!(kind, Some(crate::codegen::ir::NodeKind::Opaque));
|
||||
let routing_generic = match (kind, &node.output.shape.element) {
|
||||
(Some(crate::codegen::ir::NodeKind::Routing), crate::codegen::ir::Element::Generic(ident)) => Some(ident.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let routing = match class {
|
||||
Some(Class::Routing(routing)) => Some(routing.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let flip = matches!(class, Some(Class::Flip { .. }));
|
||||
let carrier_flip = matches!(class, Some(Class::Flip { carrier: true }));
|
||||
let opaque = matches!(class, Some(Class::Opaque));
|
||||
let record_skips_carrier = record.as_ref().is_some_and(|shape| shape.skips_carrier());
|
||||
let record_skips_carrier = record_io && !carrier_present;
|
||||
// Record nodes with a `_: ()` primary input have no carrier edge; the unit
|
||||
// field stays visible in the metadata but claims no struct field.
|
||||
let struct_regular_fields: Vec<_> = regular_fields.iter().skip(record_skips_carrier as usize).copied().collect();
|
||||
@@ -173,58 +174,56 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote! { pub(super) #name: #r#gen }
|
||||
});
|
||||
|
||||
let record_state_fields: Vec<TokenStream2> = match &record {
|
||||
Some(shape) => {
|
||||
let mut state = vec![quote!(pub(super) __layout: gcore::record::Layout)];
|
||||
if !shape.skips_carrier() {
|
||||
state.push(quote!(pub(super) __carrier: gcore::record::Layout));
|
||||
state.push(quote!(pub(super) __plan: ::std::vec::Vec<(usize, usize, usize)>));
|
||||
}
|
||||
state.push(quote!(pub(super) __frame_bytes: usize));
|
||||
state.extend(reading_secondary_indices(&struct_regular_fields, shape).into_iter().map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(pub(super) #slot: gcore::record::Layout)
|
||||
}));
|
||||
let total_reads: usize = struct_regular_fields.iter().map(|field| field.attribute_reads.len()).sum();
|
||||
state.extend((0..total_reads).map(|index| {
|
||||
let slot = format_ident!("__read_{index}");
|
||||
quote!(pub(super) #slot: Option<usize>)
|
||||
}));
|
||||
state.extend((0..shape.write_markers.len()).map(|index| {
|
||||
let slot = format_ident!("__write_{index}");
|
||||
quote!(pub(super) #slot: usize)
|
||||
}));
|
||||
state
|
||||
let record_state_fields: Vec<TokenStream2> = if record_io {
|
||||
let mut state = vec![quote!(pub(super) __layout: gcore::record::Layout)];
|
||||
if !record_skips_carrier {
|
||||
state.push(quote!(pub(super) __carrier: gcore::record::Layout));
|
||||
state.push(quote!(pub(super) __plan: ::std::vec::Vec<(usize, usize, usize)>));
|
||||
}
|
||||
None if routing.is_some() => {
|
||||
let mut state = vec![quote!(pub(super) __layout: gcore::record::Layout)];
|
||||
state.extend(routing_value_indices(&struct_regular_fields, routing.as_ref().expect("guarded by the arm")).into_iter().map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(pub(super) #slot: gcore::record::Layout)
|
||||
}));
|
||||
state
|
||||
state.push(quote!(pub(super) __frame_bytes: usize));
|
||||
state.extend(reading_secondary_indices(&struct_regular_fields, record_skips_carrier).into_iter().map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(pub(super) #slot: gcore::record::Layout)
|
||||
}));
|
||||
let total_reads: usize = struct_regular_fields.iter().map(|field| field.attribute_reads.len()).sum();
|
||||
state.extend((0..total_reads).map(|index| {
|
||||
let slot = format_ident!("__read_{index}");
|
||||
quote!(pub(super) #slot: Option<usize>)
|
||||
}));
|
||||
state.extend((0..node.output.shape.attrs.len()).map(|index| {
|
||||
let slot = format_ident!("__write_{index}");
|
||||
quote!(pub(super) #slot: usize)
|
||||
}));
|
||||
state
|
||||
} else if routing_generic.is_some() {
|
||||
let mut state = vec![quote!(pub(super) __layout: gcore::record::Layout)];
|
||||
state.extend(routing_value_indices(&struct_regular_fields, routing_generic.as_ref().expect("guarded by the arm")).into_iter().map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(pub(super) #slot: gcore::record::Layout)
|
||||
}));
|
||||
state
|
||||
} else if opaque {
|
||||
vec![quote!(pub(super) __layout: gcore::record::Layout)]
|
||||
} else if flip {
|
||||
let mut state = vec![quote!(pub(super) __layout: gcore::record::Layout), quote!(pub(super) __frame_bytes: usize)];
|
||||
if carrier_flip {
|
||||
state.push(quote!(pub(super) __plan: ::std::vec::Vec<(usize, usize, usize)>));
|
||||
}
|
||||
None if opaque => vec![quote!(pub(super) __layout: gcore::record::Layout)],
|
||||
None if flip => {
|
||||
let mut state = vec![quote!(pub(super) __layout: gcore::record::Layout), quote!(pub(super) __frame_bytes: usize)];
|
||||
if carrier_flip {
|
||||
state.push(quote!(pub(super) __plan: ::std::vec::Vec<(usize, usize, usize)>));
|
||||
}
|
||||
state.extend((0..struct_regular_fields.len()).map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(pub(super) #slot: gcore::record::Layout)
|
||||
}));
|
||||
state.extend(lazy_read_fields(&struct_regular_fields).into_iter().map(|(index, field)| {
|
||||
let slot = format_ident!("__reads_{index}");
|
||||
let arity = field.attribute_reads.len();
|
||||
quote!(pub(super) #slot: [Option<usize>; #arity])
|
||||
}));
|
||||
if !flip_generic_idents.is_empty() {
|
||||
state.push(quote!(pub(super) __marker: ::core::marker::PhantomData<fn() -> (#(#flip_generic_idents,)*)>));
|
||||
}
|
||||
state
|
||||
state.extend((0..struct_regular_fields.len()).map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(pub(super) #slot: gcore::record::Layout)
|
||||
}));
|
||||
state.extend(lazy_read_fields(&struct_regular_fields).into_iter().map(|(index, field)| {
|
||||
let slot = format_ident!("__reads_{index}");
|
||||
let arity = field.attribute_reads.len();
|
||||
quote!(pub(super) #slot: [Option<usize>; #arity])
|
||||
}));
|
||||
if !flip_generic_idents.is_empty() {
|
||||
state.push(quote!(pub(super) __marker: ::core::marker::PhantomData<fn() -> (#(#flip_generic_idents,)*)>));
|
||||
}
|
||||
None => Vec::new(),
|
||||
state
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
|
||||
let async_source = parsed.injects_async_source_fields();
|
||||
@@ -345,7 +344,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let all_field_inits = data_inits.chain(regular_inits).chain(slot_init);
|
||||
|
||||
// Data fields may not implement Copy, PartialEq, etc., so only derive Debug and Clone
|
||||
let struct_derives = if record.is_some() || routing.is_some() || flip {
|
||||
let struct_derives = if record_io || routing_generic.is_some() || flip {
|
||||
quote!(#[derive(Debug, Clone)])
|
||||
} else if data_fields.is_empty() && !async_source {
|
||||
quote!(#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)])
|
||||
@@ -372,11 +371,11 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
// Record nodes construct through the generated `wire` fn, which resolves
|
||||
// offsets from the carrier layout; `new` cannot fill that state.
|
||||
let routing_layout_param = (routing.is_some() || opaque).then(|| quote!(__layout: &gcore::record::Layout,)).into_iter();
|
||||
let routing_layout_init = (routing.is_some() || opaque).then(|| quote!(__layout: __layout.clone(),)).into_iter();
|
||||
let routing_value_layouts: Vec<usize> = routing
|
||||
let routing_layout_param = (routing_generic.is_some() || opaque).then(|| quote!(__layout: &gcore::record::Layout,)).into_iter();
|
||||
let routing_layout_init = (routing_generic.is_some() || opaque).then(|| quote!(__layout: __layout.clone(),)).into_iter();
|
||||
let routing_value_layouts: Vec<usize> = routing_generic
|
||||
.as_ref()
|
||||
.map(|routing| routing_value_indices(&struct_regular_fields, routing))
|
||||
.map(|generic| routing_value_indices(&struct_regular_fields, generic))
|
||||
.unwrap_or_default();
|
||||
let routing_in_params = routing_value_layouts.iter().map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
@@ -457,7 +456,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote!(where #(#existing,)* #slot_value_type: ::core::clone::Clone + ::core::marker::Send + ::core::marker::Sync + 'static)
|
||||
})
|
||||
.into_iter();
|
||||
let new_impl = match record.is_none() {
|
||||
let new_impl = match !record_io {
|
||||
true => quote! {
|
||||
#[automatically_derived]
|
||||
impl<'n, #(#struct_generic_params,)*> #struct_name<#(#struct_type_params,)*> #(#new_where)*
|
||||
@@ -682,7 +681,7 @@ pub(crate) struct NodeFields<'a> {
|
||||
pub(crate) struct_type_params: Vec<Ident>,
|
||||
}
|
||||
|
||||
pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn, model: &Option<NodeModel>, fields: NodeFields) -> syn::Result<NodePlan> {
|
||||
pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn, model: &Option<Dialect>, fields: NodeFields) -> syn::Result<NodePlan> {
|
||||
let core_types = crate_ident.gcore()?;
|
||||
|
||||
let ctx_param = context_param(parsed);
|
||||
@@ -693,25 +692,36 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let Some(model) = model.as_ref() else {
|
||||
return Ok(NodePlan::default());
|
||||
};
|
||||
let async_fn = matches!(model.dialect, Dialect::AsyncFn);
|
||||
let future_kernel = matches!(model.dialect, Dialect::Future | Dialect::FutureInterrupt);
|
||||
let async_fn = matches!(*model, Dialect::AsyncFn);
|
||||
let future_kernel = matches!(*model, Dialect::Future | Dialect::FutureInterrupt);
|
||||
let async_source = async_fn || future_kernel;
|
||||
let record = match &model.class {
|
||||
Class::RecordIo(shape) => Some(shape.clone()),
|
||||
let node = crate::codegen::ir::build(parsed);
|
||||
let kind = crate::codegen::ir::node_kind(&node);
|
||||
let carrier_present = node.inputs.first().is_some_and(|input| input.subject);
|
||||
let flip = matches!(kind, crate::codegen::ir::NodeKind::Flip);
|
||||
let carrier_flip = flip && carrier_present;
|
||||
let opaque = matches!(kind, crate::codegen::ir::NodeKind::Opaque);
|
||||
let record_io = matches!(kind, crate::codegen::ir::NodeKind::RecordIo);
|
||||
let routing_generic = match (kind, &node.output.shape.element) {
|
||||
(crate::codegen::ir::NodeKind::Routing, crate::codegen::ir::Element::Generic(ident)) => Some(ident.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let routing = match &model.class {
|
||||
Class::Routing(routing) => Some(routing.clone()),
|
||||
let record_token = match (kind, &node.output.shape.element) {
|
||||
(crate::codegen::ir::NodeKind::RecordIo, crate::codegen::ir::Element::Generic(ident)) => Some(ident.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let flip = matches!(model.class, Class::Flip { .. });
|
||||
let carrier_flip = matches!(model.class, Class::Flip { carrier: true });
|
||||
let opaque = matches!(model.class, Class::Opaque);
|
||||
let record_token = match record.as_ref().map(|shape| &shape.carrier) {
|
||||
Some(RecordCarrier::Token(token)) => Some(token.clone()),
|
||||
let skips_carrier = record_io && !carrier_present;
|
||||
// The record-io write set, resolved from the output item and carrier input.
|
||||
let write_markers: Vec<&Type> = node.output.shape.attrs.iter().map(|attr| &attr.marker).collect();
|
||||
let removes: Vec<&Type> = node.output.removes.iter().map(|attr| &attr.marker).collect();
|
||||
let element_write: Option<&Type> = match &node.output.shape.element {
|
||||
crate::codegen::ir::Element::Concrete(ty) => Some(ty),
|
||||
_ => None,
|
||||
};
|
||||
let skips_carrier = record.as_ref().is_some_and(|shape| shape.skips_carrier());
|
||||
let carrier_read_ty: Option<&Type> = node.inputs.first().filter(|input| input.subject).and_then(|input| match &input.shape.element {
|
||||
crate::codegen::ir::Element::Concrete(ty) => Some(ty),
|
||||
_ => None,
|
||||
});
|
||||
let snapshot_ctx = async_fn && matches!(&parsed.input.ty, Type::Path(path) if path.path.segments.last().is_some_and(|segment| segment.ident == "CtxSnapshot"));
|
||||
|
||||
let mut ctx_bounds: Vec<TokenStream2> = match ctx_param {
|
||||
@@ -746,7 +756,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
_ => false,
|
||||
})
|
||||
});
|
||||
let derive_routing = derives && routing.is_some();
|
||||
let derive_routing = derives && routing_generic.is_some();
|
||||
|
||||
let ctx_generic = match ctx_bounds.is_empty() {
|
||||
true => quote!(#ctx_ident),
|
||||
@@ -760,7 +770,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.fn_generics
|
||||
.iter()
|
||||
.filter(|param| match param {
|
||||
GenericParam::Type(type_param) => !derive_routing || Some(&type_param.ident) != routing.as_ref().map(|routing| &routing.generic),
|
||||
GenericParam::Type(type_param) => !derive_routing || Some(&type_param.ident) != routing_generic.as_ref(),
|
||||
_ => true,
|
||||
})
|
||||
.map(|param| match param {
|
||||
@@ -790,7 +800,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.iter()
|
||||
.filter(|param| match param {
|
||||
GenericParam::Type(type_param) => {
|
||||
Some(&type_param.ident) != routing.as_ref().map(|routing| &routing.generic) && Some(&type_param.ident) != record_token.as_ref()
|
||||
Some(&type_param.ident) != routing_generic.as_ref() && Some(&type_param.ident) != record_token.as_ref()
|
||||
}
|
||||
_ => true,
|
||||
})
|
||||
@@ -800,7 +810,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
generics.push(ctx_generic.clone());
|
||||
impl_generics.push(ctx_generic);
|
||||
}
|
||||
if routing.is_some() || record.is_some() || flip {
|
||||
if routing_generic.is_some() || record_io || flip {
|
||||
impl_generics.insert(0, quote!('__record));
|
||||
}
|
||||
if derive_routing {
|
||||
@@ -811,12 +821,12 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let mod_name = format_ident!("_{}_mod", parsed.mod_name);
|
||||
let struct_name = format_ident!("{}Node", parsed.struct_name);
|
||||
let output_type = &parsed.output_type;
|
||||
let trait_output = match (&record, &routing) {
|
||||
(Some(_), _) | (None, Some(_)) => syn::parse_quote!(#core_types::record::RecordValue<'__record>),
|
||||
(None, None) if flip => syn::parse_quote!(#core_types::record::RecordValue<'__record>),
|
||||
(None, None) => slot_value_type(&parsed.output_type),
|
||||
let trait_output = match (record_io, &routing_generic) {
|
||||
(true, _) | (false, Some(_)) => syn::parse_quote!(#core_types::record::RecordValue<'__record>),
|
||||
(false, None) if flip => syn::parse_quote!(#core_types::record::RecordValue<'__record>),
|
||||
(false, None) => slot_value_type(&parsed.output_type),
|
||||
};
|
||||
let raw_lazy = matches!(model.dialect, Dialect::Poll);
|
||||
let raw_lazy = matches!(*model, Dialect::Poll);
|
||||
let injected_name = |ident: &Ident| async_source && (ident == "_runtime" || ident == "_source");
|
||||
let where_predicates: Vec<TokenStream2> = parsed.where_clause.iter().flat_map(|clause| clause.predicates.iter()).map(|predicate| quote!(#predicate)).collect();
|
||||
|
||||
@@ -834,7 +844,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
|
||||
};
|
||||
if matches!((&routing, source_ty), (Some(routing), Type::Path(path)) if path.path.get_ident() == Some(&routing.generic)) {
|
||||
if matches!((&routing_generic, source_ty), (Some(generic), Type::Path(path)) if path.path.get_ident() == Some(generic)) {
|
||||
let source_generic = format_ident!("__Source{index}");
|
||||
generics.push(quote! {
|
||||
#source_generic: for<'__derived> #core_types::record::DerivedRecordEdge<'__derived, #core_types::context::Derived<'__derived, #ctx_ident>>
|
||||
@@ -883,41 +893,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
false => quote!(#core_types::node::Node<#ctx_ident, Output = #output_type>),
|
||||
};
|
||||
|
||||
let routing_source = |ty: &Type| matches!((&routing, ty), (Some(routing), Type::Path(path)) if path.path.get_ident() == Some(&routing.generic));
|
||||
|
||||
let field_role = |index: usize, field: &ParsedField| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => {
|
||||
if record.is_some() && !skips_carrier && index == 0 {
|
||||
InputRole::RecordCarrier
|
||||
} else if carrier_flip && index == 0 {
|
||||
InputRole::FlipCarrier
|
||||
} else if flip && lend.is_some() {
|
||||
InputRole::LendBorrow
|
||||
} else if record.is_some() && !field.attribute_reads.is_empty() {
|
||||
InputRole::ReadingSecondary
|
||||
} else if flip || (routing.is_some() && !routing_source(ty)) {
|
||||
InputRole::RecordValue
|
||||
} else {
|
||||
InputRole::PlainValue
|
||||
}
|
||||
}
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||
if derive_routing && routing_source(output_type) {
|
||||
InputRole::DeriveRoutingSource
|
||||
} else if flip && raw_lazy {
|
||||
InputRole::FlipRawLazyEdge
|
||||
} else if flip {
|
||||
InputRole::FlipLazy
|
||||
} else if opaque && raw_lazy && is_record_value(output_type) {
|
||||
InputRole::OpaqueRecordEdge
|
||||
} else if raw_lazy {
|
||||
InputRole::RawLazy
|
||||
} else {
|
||||
InputRole::Lazy
|
||||
}
|
||||
}
|
||||
};
|
||||
let roles: Vec<InputRole> = regular_fields.iter().enumerate().map(|(index, field)| field_role(index, field)).collect();
|
||||
let routing_source = |ty: &Type| matches!((&routing_generic, ty), (Some(generic), Type::Path(path)) if path.path.get_ident() == Some(generic));
|
||||
|
||||
let lazy_read_out = |field: &ParsedField, output_type: &Type| {
|
||||
let attr_tys = field.attribute_reads.iter().map(|read| {
|
||||
@@ -949,26 +925,25 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#pat: #ty),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||
let source_generic = format_ident!("__Source{index}");
|
||||
match roles[index] {
|
||||
InputRole::DeriveRoutingSource => quote!(#pat: #core_types::record::RecordLazyInput<'_, '__record, #source_generic>),
|
||||
InputRole::OpaqueRecordEdge => quote!(#pat: &#core_types::record::RecordEdgeInput<'_, #source_generic>),
|
||||
InputRole::FlipRawLazyEdge => {
|
||||
match (ir::lazy_binding(&node, index), raw_lazy) {
|
||||
(LazyBinding::DeriveRouting, _) => quote!(#pat: #core_types::record::RecordLazyInput<'_, '__record, #source_generic>),
|
||||
(LazyBinding::OpaqueRecord, _) => quote!(#pat: &#core_types::record::RecordEdgeInput<'_, #source_generic>),
|
||||
(LazyBinding::Element, true) => {
|
||||
let out = lazy_read_out(field, output_type);
|
||||
quote!(#pat: &#core_types::record::ElementEdge<'_, #out, #source_generic>)
|
||||
}
|
||||
InputRole::FlipLazy => {
|
||||
(LazyBinding::Element, false) => {
|
||||
let out = lazy_read_out(field, output_type);
|
||||
quote!(#pat: #core_types::record::ElementLazyInput<'_, #out, #source_generic>)
|
||||
}
|
||||
InputRole::RawLazy => {
|
||||
(LazyBinding::Plain, true) => {
|
||||
let bound = lazy_bound(output_type);
|
||||
quote!(#pat: &impl #bound)
|
||||
}
|
||||
InputRole::Lazy => {
|
||||
(LazyBinding::Plain, false) => {
|
||||
let bound = lazy_bound(output_type);
|
||||
quote!(#pat: #core_types::node::LazyInput<'_, impl #bound>)
|
||||
}
|
||||
_ => unreachable!("value role on a lazy input"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -984,16 +959,16 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
},
|
||||
false => quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #record_value_ty>),
|
||||
},
|
||||
ParsedFieldType::Regular(_) if record.is_some() && !skips_carrier && index == 0 => {
|
||||
ParsedFieldType::Regular(_) if record_io && !skips_carrier && index == 0 => {
|
||||
quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #record_value_ty>)
|
||||
}
|
||||
ParsedFieldType::Regular(_) if record.is_some() && !field.attribute_reads.is_empty() => {
|
||||
ParsedFieldType::Regular(_) if record_io && !field.attribute_reads.is_empty() => {
|
||||
quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #record_value_ty>)
|
||||
}
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) if routing_source(ty) => {
|
||||
quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #record_value_ty>)
|
||||
}
|
||||
ParsedFieldType::Regular(_) if routing.is_some() => {
|
||||
ParsedFieldType::Regular(_) if routing_generic.is_some() => {
|
||||
quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #record_value_ty>)
|
||||
}
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(#node_generic: #core_types::node::Node<#ctx_ident, Output = #ty>),
|
||||
@@ -1077,111 +1052,103 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
|
||||
let bind_body = |index: usize, field: &ParsedField| {
|
||||
let name = &field.pat_ident.ident;
|
||||
let regular_ty = || match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
|
||||
_ => unreachable!("value role on a lazy input"),
|
||||
};
|
||||
let node_output = || match &field.ty {
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type.clone(),
|
||||
_ => unreachable!("lazy role on a value input"),
|
||||
};
|
||||
match roles[index] {
|
||||
// A carrier primary evaluates beyond the node's own frame (in the
|
||||
// record/flip tail), and a raw poll edge is threaded straight through,
|
||||
// so none bind here.
|
||||
InputRole::RecordCarrier | InputRole::FlipCarrier | InputRole::RawLazy => quote!(),
|
||||
// A reading secondary input claims a record edge: the element and
|
||||
// the declared reads copy out right after its eval, before any
|
||||
// later sibling eval can reuse the record stack.
|
||||
InputRole::ReadingSecondary => {
|
||||
let ty = regular_ty();
|
||||
let slot = format_ident!("__in_{index}");
|
||||
let rec_local = format_ident!("__rec_{index}");
|
||||
let bindings: Vec<TokenStream2> = reads_of(index).into_iter().map(|(slot, read)| read_binding(slot, read, quote!(#rec_local))).collect();
|
||||
quote! {
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => match ir::value_binding(&node, index) {
|
||||
// A carrier primary evaluates beyond the node's own frame (in the
|
||||
// record/flip tail), so it does not bind here.
|
||||
ValueBinding::Carrier => quote!(),
|
||||
// A reading secondary input claims a record edge: the element and
|
||||
// the declared reads copy out right after its eval, before any
|
||||
// later sibling eval can reuse the record stack.
|
||||
ValueBinding::ReadingSecondary => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
let rec_local = format_ident!("__rec_{index}");
|
||||
let bindings: Vec<TokenStream2> = reads_of(index).into_iter().map(|(slot, read)| read_binding(slot, read, quote!(#rec_local))).collect();
|
||||
quote! {
|
||||
let #name = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
let #rec_local = self.#slot.rec(&#name);
|
||||
#(#bindings)*
|
||||
let #name: #ty = unsafe { #core_types::record::read_element(#rec_local) };
|
||||
}
|
||||
}
|
||||
// The lend input's frame survives on the record stack until this
|
||||
// node's frame is reclaimed, so the borrow stays valid in place.
|
||||
ValueBinding::Lend => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
let record_local = format_ident!("__record_{index}");
|
||||
quote! {
|
||||
let #record_local = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
let #name = unsafe { #core_types::record::borrow_element::<#ty>(self.#slot.rec(&#record_local)) };
|
||||
}
|
||||
}
|
||||
// A flip value or a routing non-source value rides a record edge; the
|
||||
// element copies out into `name`. The mark/rewind that reclaims the
|
||||
// record's frame is applied by the step lowering (see `reads_out`).
|
||||
ValueBinding::RecordElement => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote! {
|
||||
let #name = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
let #name: #ty = unsafe { #core_types::record::read_element(self.#slot.rec(&#name)) };
|
||||
}
|
||||
}
|
||||
ValueBinding::Plain => quote! {
|
||||
let #name = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
let #rec_local = self.#slot.rec(&#name);
|
||||
#(#bindings)*
|
||||
let #name: #ty = unsafe { #core_types::record::read_element(#rec_local) };
|
||||
}
|
||||
}
|
||||
// The lend input's frame survives on the record stack until this
|
||||
// node's frame is reclaimed, so the borrow stays valid in place.
|
||||
InputRole::LendBorrow => {
|
||||
let ty = regular_ty();
|
||||
let slot = format_ident!("__in_{index}");
|
||||
let record_local = format_ident!("__record_{index}");
|
||||
quote! {
|
||||
let #record_local = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
let #name = unsafe { #core_types::record::borrow_element::<#ty>(self.#slot.rec(&#record_local)) };
|
||||
}
|
||||
}
|
||||
// A flip value or a routing non-source value rides a record edge; the
|
||||
// element copies out into `name`. The mark/rewind that reclaims the
|
||||
// record's frame is applied by the step lowering (see `reads_out`).
|
||||
InputRole::RecordValue => {
|
||||
let ty = regular_ty();
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote! {
|
||||
let #name = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
let #name: #ty = unsafe { #core_types::record::read_element(self.#slot.rec(&#name)) };
|
||||
}
|
||||
}
|
||||
InputRole::PlainValue => quote! {
|
||||
let #name = match __cell.eval_input(#index, &self.#name, __input) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into(),
|
||||
};
|
||||
},
|
||||
},
|
||||
InputRole::DeriveRoutingSource => quote! {
|
||||
let #name = #core_types::record::RecordLazyInput::new(&self.#name, &__cell, #index);
|
||||
},
|
||||
InputRole::FlipRawLazyEdge => {
|
||||
let output_type = node_output();
|
||||
let slot = format_ident!("__in_{index}");
|
||||
match field.attribute_reads.is_empty() {
|
||||
true => quote! {
|
||||
let #name = #core_types::record::ElementEdge::<#output_type, _>::new(&self.#name, &self.#slot);
|
||||
},
|
||||
false => {
|
||||
let arr = format_ident!("__reads_{index}");
|
||||
let read_fn = format_ident!("__{}_read_{}", fn_name, index);
|
||||
quote! {
|
||||
let #name = #core_types::record::ElementEdge::with_reads(&self.#name, &self.#slot, &self.#arr, self::#read_fn);
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => match (ir::lazy_binding(&node, index), raw_lazy) {
|
||||
// A raw poll edge is threaded straight through, so it does not bind here.
|
||||
(LazyBinding::Plain, true) => quote!(),
|
||||
(LazyBinding::DeriveRouting, _) => quote! {
|
||||
let #name = #core_types::record::RecordLazyInput::new(&self.#name, &__cell, #index);
|
||||
},
|
||||
(LazyBinding::Element, true) => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
match field.attribute_reads.is_empty() {
|
||||
true => quote! {
|
||||
let #name = #core_types::record::ElementEdge::<#output_type, _>::new(&self.#name, &self.#slot);
|
||||
},
|
||||
false => {
|
||||
let arr = format_ident!("__reads_{index}");
|
||||
let read_fn = format_ident!("__{}_read_{}", fn_name, index);
|
||||
quote! {
|
||||
let #name = #core_types::record::ElementEdge::with_reads(&self.#name, &self.#slot, &self.#arr, self::#read_fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
InputRole::FlipLazy => {
|
||||
let output_type = node_output();
|
||||
let slot = format_ident!("__in_{index}");
|
||||
match field.attribute_reads.is_empty() {
|
||||
true => quote! {
|
||||
let #name = #core_types::record::ElementLazyInput::<#output_type, _>::new(&self.#name, &__cell, #index, &self.#slot);
|
||||
},
|
||||
false => {
|
||||
let arr = format_ident!("__reads_{index}");
|
||||
let read_fn = format_ident!("__{}_read_{}", fn_name, index);
|
||||
quote! {
|
||||
let #name = #core_types::record::ElementLazyInput::with_reads(&self.#name, &__cell, #index, &self.#slot, &self.#arr, self::#read_fn);
|
||||
(LazyBinding::Element, false) => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
match field.attribute_reads.is_empty() {
|
||||
true => quote! {
|
||||
let #name = #core_types::record::ElementLazyInput::<#output_type, _>::new(&self.#name, &__cell, #index, &self.#slot);
|
||||
},
|
||||
false => {
|
||||
let arr = format_ident!("__reads_{index}");
|
||||
let read_fn = format_ident!("__{}_read_{}", fn_name, index);
|
||||
quote! {
|
||||
let #name = #core_types::record::ElementLazyInput::with_reads(&self.#name, &__cell, #index, &self.#slot, &self.#arr, self::#read_fn);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
InputRole::OpaqueRecordEdge => quote! {
|
||||
let #name = #core_types::record::RecordEdgeInput::new(&self.#name, &self.__layout);
|
||||
},
|
||||
InputRole::Lazy => quote! {
|
||||
let #name = #core_types::node::LazyInput::new(&self.#name, &__cell, #index);
|
||||
(LazyBinding::OpaqueRecord, _) => quote! {
|
||||
let #name = #core_types::record::RecordEdgeInput::new(&self.#name, &self.__layout);
|
||||
},
|
||||
(LazyBinding::Plain, false) => quote! {
|
||||
let #name = #core_types::node::LazyInput::new(&self.#name, &__cell, #index);
|
||||
},
|
||||
},
|
||||
}
|
||||
};
|
||||
@@ -1208,9 +1175,9 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
// evaluated value.
|
||||
ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }) if !flip => quote!(&#name),
|
||||
ParsedFieldType::Regular(_) => quote!(#name),
|
||||
ParsedFieldType::Node(_) => match roles[index] {
|
||||
InputRole::FlipRawLazyEdge | InputRole::OpaqueRecordEdge => quote!(&#name),
|
||||
InputRole::RawLazy => quote!(&self.#name),
|
||||
ParsedFieldType::Node(_) => match (ir::lazy_binding(&node, index), raw_lazy) {
|
||||
(LazyBinding::Element, true) | (LazyBinding::OpaqueRecord, _) => quote!(&#name),
|
||||
(LazyBinding::Plain, true) => quote!(&self.#name),
|
||||
_ => quote!(#name),
|
||||
},
|
||||
}
|
||||
@@ -1280,11 +1247,11 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
// A bare `Attr<M>` in the return type cannot elide its lifetime, so the
|
||||
// kernel gets a fresh one; reference-valued writes name their real
|
||||
// lifetime explicitly and pass through untouched.
|
||||
let kernel_output = record.as_ref().and_then(|_| inject_attr_lifetimes(&parsed.output_type));
|
||||
let kernel_output = record_io.then(|| inject_attr_lifetimes(&parsed.output_type)).flatten();
|
||||
let attr_lifetime = kernel_output.is_some().then(|| quote!('__attr,));
|
||||
let kernel_output = match derive_routing {
|
||||
true => {
|
||||
let generic = &routing.as_ref().expect("derive routing implies routing").generic;
|
||||
let generic = routing_generic.as_ref().expect("derive routing implies routing");
|
||||
let ty = substitute_routing_record(&parsed.output_type, generic, core_types);
|
||||
quote!(#ty)
|
||||
}
|
||||
@@ -1327,7 +1294,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
false => quote!(#core_types::node::StatusCell::new()),
|
||||
};
|
||||
let kernel_call = quote!(self::#fn_name(__input #(, &self.#data_names)* #(, #call_args)*));
|
||||
let lift = match model.dialect {
|
||||
let lift = match *model {
|
||||
Dialect::Interrupt => quote! {
|
||||
match #kernel_call {
|
||||
Ok(value) => __cell.finish(value),
|
||||
@@ -1435,7 +1402,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
#fallback
|
||||
}
|
||||
};
|
||||
let record_tail = record.as_ref().map(|shape| {
|
||||
let record_tail = record_io.then(|| {
|
||||
let tuple_arg = |field: &ParsedField, value: TokenStream2| match field.attribute_reads.is_empty() {
|
||||
true => value,
|
||||
false => {
|
||||
@@ -1443,13 +1410,15 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
quote!((#value #(, #read_pats)*))
|
||||
}
|
||||
};
|
||||
let carrier_arg = match &shape.carrier {
|
||||
RecordCarrier::None => None,
|
||||
RecordCarrier::Token(_) => Some(tuple_arg(regular_fields[0], quote!(#core_types::record::ElToken))),
|
||||
RecordCarrier::Read(ty) => Some(tuple_arg(regular_fields[0], quote!(unsafe { #core_types::record::read_element::<#ty>(__src_rec) }))),
|
||||
let carrier_arg = if skips_carrier {
|
||||
None
|
||||
} else if let Some(ty) = carrier_read_ty {
|
||||
Some(tuple_arg(regular_fields[0], quote!(unsafe { #core_types::record::read_element::<#ty>(__src_rec) })))
|
||||
} else {
|
||||
Some(tuple_arg(regular_fields[0], quote!(#core_types::record::ElToken)))
|
||||
}
|
||||
.into_iter();
|
||||
let value_args = regular_fields.iter().skip(if shape.skips_carrier() { 0 } else { 1 }).map(|field| {
|
||||
let value_args = regular_fields.iter().skip(if skips_carrier { 0 } else { 1 }).map(|field| {
|
||||
let name = &field.pat_ident.ident;
|
||||
match &field.ty {
|
||||
// A lend param binds an owned edge; the kernel borrows the
|
||||
@@ -1459,7 +1428,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
});
|
||||
let record_kernel_call = quote!(self::#fn_name(__input #(, &self.#data_names)* #(, #carrier_arg)* #(, #value_args)*));
|
||||
let carrier_eval = (!shape.skips_carrier()).then(|| {
|
||||
let carrier_eval = (!skips_carrier).then(|| {
|
||||
let name = ®ular_fields[0].pat_ident.ident;
|
||||
quote! {
|
||||
let __src = match __cell.eval_input(0, &self.#name, __input) {
|
||||
@@ -1469,12 +1438,12 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let __src_rec = self.__carrier.rec(&__src);
|
||||
}
|
||||
});
|
||||
let carry = (!shape.skips_carrier()).then(|| quote!(unsafe { #core_types::record::apply_plan(__src_rec, __dst, &self.__plan) };));
|
||||
let carrier_read_bindings: Vec<TokenStream2> = match shape.skips_carrier() {
|
||||
let carry = (!skips_carrier).then(|| quote!(unsafe { #core_types::record::apply_plan(__src_rec, __dst, &self.__plan) };));
|
||||
let carrier_read_bindings: Vec<TokenStream2> = match skips_carrier {
|
||||
true => Vec::new(),
|
||||
false => reads_of(0).into_iter().map(|(slot, read)| read_binding(slot, read, quote!(__src_rec))).collect(),
|
||||
};
|
||||
let kernel_value = match model.dialect {
|
||||
let kernel_value = match *model {
|
||||
Dialect::Interrupt => quote! {
|
||||
match #record_kernel_call {
|
||||
Ok(__value) => __value,
|
||||
@@ -1483,8 +1452,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
},
|
||||
_ => quote!(#record_kernel_call),
|
||||
};
|
||||
let attr_binders: Vec<Ident> = (0..shape.write_markers.len()).map(|index| format_ident!("__attr_{index}")).collect();
|
||||
let element_binder = match &shape.element_write {
|
||||
let attr_binders: Vec<Ident> = (0..write_markers.len()).map(|index| format_ident!("__attr_{index}")).collect();
|
||||
let element_binder = match element_write {
|
||||
Some(_) => quote!(__element),
|
||||
None => quote!(_),
|
||||
};
|
||||
@@ -1512,7 +1481,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
true => quote!(let #element_binder = __kernel_value;),
|
||||
false => quote!(let (#element_binder #(, #slot_binders)*) = __kernel_value;),
|
||||
};
|
||||
let element_store = shape.element_write.as_ref().map(|ty| quote!(unsafe { #core_types::record::write_field::<#ty>(__dst, 0, __element) };));
|
||||
let element_store = element_write.map(|ty| quote!(unsafe { #core_types::record::write_field::<#ty>(__dst, 0, __element) };));
|
||||
let attr_stores = attr_binders.iter().enumerate().map(|(index, binder)| {
|
||||
let slot = format_ident!("__write_{index}");
|
||||
quote!(unsafe { #core_types::record::write_field(__dst, self.#slot, #binder) };)
|
||||
@@ -1538,7 +1507,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
});
|
||||
let flip_tail = flip.then(|| {
|
||||
if matches!(model.dialect, Dialect::Poll) {
|
||||
if matches!(*model, Dialect::Poll) {
|
||||
return match &carried_prelude {
|
||||
Some(prelude) => quote! {
|
||||
#prelude
|
||||
@@ -1554,7 +1523,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
},
|
||||
};
|
||||
}
|
||||
let kernel_value = match model.dialect {
|
||||
let kernel_value = match *model {
|
||||
Dialect::Interrupt => quote! {
|
||||
match #kernel_call {
|
||||
Ok(value) => value,
|
||||
@@ -1588,12 +1557,12 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
Tail::SpawnAsyncFn
|
||||
} else if future_kernel {
|
||||
Tail::SpawnFuture
|
||||
} else if record.is_some() {
|
||||
Tail::Record
|
||||
} else if flip {
|
||||
Tail::Flip
|
||||
} else {
|
||||
Tail::Forward
|
||||
match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => Tail::Record,
|
||||
ir::NodeKind::Flip => Tail::Flip,
|
||||
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
|
||||
}
|
||||
};
|
||||
let lower_tail = |form: Tail| match form {
|
||||
Tail::Forward => lift.clone(),
|
||||
@@ -1625,7 +1594,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
),
|
||||
None => (quote!(), pending_return.clone()),
|
||||
};
|
||||
let acquire = match model.dialect {
|
||||
let acquire = match *model {
|
||||
Dialect::FutureInterrupt => quote! {
|
||||
let __future = match #kernel_call {
|
||||
Ok(future) => future,
|
||||
@@ -1652,29 +1621,26 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
|
||||
let record_bounds: Vec<TokenStream2> = {
|
||||
let mut bounds = match &record {
|
||||
Some(shape) if shape.skips_carrier() => {
|
||||
vec![quote!(#ctx_ident: #core_types::context::ExtractArena<ArenaRef = &'__record #core_types::arena::Arena>)]
|
||||
}
|
||||
None if derive_routing || flip => {
|
||||
vec![quote!(#ctx_ident: #core_types::context::ExtractArena<ArenaRef = &'__record #core_types::arena::Arena>)]
|
||||
}
|
||||
_ => Vec::new(),
|
||||
let arena_bound = (record_io && skips_carrier) || (!record_io && (derive_routing || flip));
|
||||
let mut bounds = if arena_bound {
|
||||
vec![quote!(#ctx_ident: #core_types::context::ExtractArena<ArenaRef = &'__record #core_types::arena::Arena>)]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
// A reading secondary input's element copies out of its record, as
|
||||
// does a concrete carrier read.
|
||||
if let Some(shape) = &record {
|
||||
bounds.extend(reading_secondary_indices(®ular_fields, shape).into_iter().filter_map(|index| match ®ular_fields[index].ty {
|
||||
if record_io {
|
||||
bounds.extend(reading_secondary_indices(®ular_fields, skips_carrier).into_iter().filter_map(|index| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some(quote!(#ty: ::core::clone::Clone)),
|
||||
_ => None,
|
||||
}));
|
||||
if let RecordCarrier::Read(ty) = &shape.carrier {
|
||||
if let Some(ty) = carrier_read_ty {
|
||||
bounds.push(quote!(#ty: ::core::clone::Clone));
|
||||
}
|
||||
}
|
||||
// A routing node's value elements copy out of their records.
|
||||
if let Some(routing) = &routing {
|
||||
bounds.extend(routing_value_indices(®ular_fields, routing).into_iter().filter_map(|index| match ®ular_fields[index].ty {
|
||||
if let Some(generic) = &routing_generic {
|
||||
bounds.extend(routing_value_indices(®ular_fields, generic).into_iter().filter_map(|index| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some(quote!(#ty: ::core::clone::Clone)),
|
||||
_ => None,
|
||||
}));
|
||||
@@ -1700,7 +1666,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
false => Vec::new(),
|
||||
};
|
||||
|
||||
let record_layout_impl = match record.is_some() || routing.is_some() || flip || opaque {
|
||||
let record_layout_impl = match record_io || routing_generic.is_some() || flip || opaque {
|
||||
true => quote! {
|
||||
fn layout(&self) -> &#core_types::record::Layout {
|
||||
&self.__layout
|
||||
@@ -1709,27 +1675,25 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
false => quote!(),
|
||||
};
|
||||
|
||||
let entries = entries_tokens(parsed, &model.class, &struct_name, &data_field_generic_idents, ®ular_fields);
|
||||
let entries = entries_tokens(parsed, &struct_name, &data_field_generic_idents, ®ular_fields);
|
||||
let cfg = crate::shader_nodes::modify_cfg(&parsed.attributes);
|
||||
|
||||
let record_wiring = record.as_ref().map(|shape| {
|
||||
let record_wiring = record_io.then(|| {
|
||||
let layout_fn = format_ident!("{}_layout", fn_name);
|
||||
let write_descs: Vec<TokenStream2> = shape
|
||||
.write_markers
|
||||
let write_descs: Vec<TokenStream2> = write_markers
|
||||
.iter()
|
||||
.map(|marker| quote!(#core_types::record::FieldWrite::of::<#marker>(0)))
|
||||
.collect();
|
||||
let remove_pairs: Vec<TokenStream2> = shape
|
||||
.removes
|
||||
let remove_pairs: Vec<TokenStream2> = removes
|
||||
.iter()
|
||||
.map(|marker| quote!((<#marker as #core_types::attribute::Attribute>::NAME, 0)))
|
||||
.collect();
|
||||
let subtraction = (!remove_pairs.is_empty()).then(|| quote!(.without(&[#(#remove_pairs),*])));
|
||||
let element = match &shape.element_write {
|
||||
let element = match element_write {
|
||||
Some(ty) => quote!(#core_types::record::element_write::<#ty>()),
|
||||
None => quote!(__carrier.element),
|
||||
};
|
||||
let layout_def = match shape.skips_carrier() {
|
||||
let layout_def = match skips_carrier {
|
||||
true => quote! {
|
||||
#vis fn #layout_fn() -> #core_types::record::Layout {
|
||||
#core_types::record::Layout::default().with_writes(0, #element, &[#(#write_descs),*])
|
||||
@@ -1742,49 +1706,43 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
},
|
||||
};
|
||||
let layout_meta_fn = format_ident!("{}_layout_meta", fn_name);
|
||||
let carrier_present = !shape.skips_carrier();
|
||||
let element_spec = match &shape.element_write {
|
||||
let element_spec = match element_write {
|
||||
Some(ty) => quote!(#core_types::record::ElementSpec::Concrete(#core_types::record::element_write::<#ty>())),
|
||||
None => quote!(#core_types::record::ElementSpec::Carried),
|
||||
};
|
||||
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types);
|
||||
let layout_meta_def = quote! {
|
||||
#vis fn #layout_meta_fn() -> #core_types::record::LayoutMeta {
|
||||
#core_types::record::LayoutMeta {
|
||||
carrier: #carrier_present,
|
||||
element: #element_spec,
|
||||
writes: ::std::vec![#(#write_descs),*],
|
||||
removes: ::std::vec![#(#remove_pairs),*],
|
||||
level_delta: 0,
|
||||
}
|
||||
#layout_meta
|
||||
}
|
||||
};
|
||||
let reading_secondaries = reading_secondary_indices(®ular_fields, shape);
|
||||
let reading_secondaries = reading_secondary_indices(®ular_fields, skips_carrier);
|
||||
let edge_args = regular_fields.iter().zip(&node_generics).map(|(field, generic)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
quote!(#name: #generic)
|
||||
});
|
||||
let carrier_layout_param = (!shape.skips_carrier()).then(|| quote!(__carrier_layout: &#core_types::record::Layout,)).into_iter();
|
||||
let carrier_layout_param = (!skips_carrier).then(|| quote!(__carrier_layout: &#core_types::record::Layout,)).into_iter();
|
||||
let input_layout_params = reading_secondaries.iter().map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(#slot: &#core_types::record::Layout,)
|
||||
});
|
||||
let layout_binding = match shape.skips_carrier() {
|
||||
let layout_binding = match skips_carrier {
|
||||
true => quote!(let __layout = self::#layout_fn();),
|
||||
false => quote!(let __layout = self::#layout_fn(__carrier_layout);),
|
||||
};
|
||||
let carry_element = shape.carries_element();
|
||||
let carry_element = element_write.is_none();
|
||||
let plan_binding =
|
||||
(!shape.skips_carrier()).then(|| quote!(let __plan = #core_types::record::copy_plan(__carrier_layout, &__layout, #carry_element, &[#(#remove_pairs),*]);));
|
||||
(!skips_carrier).then(|| quote!(let __plan = #core_types::record::copy_plan(__carrier_layout, &__layout, #carry_element, &[#(#remove_pairs),*]);));
|
||||
let read_inits = flat_reads.iter().enumerate().map(|(slot, (owner, read))| {
|
||||
let marker = &read.marker;
|
||||
let slot = format_ident!("__read_{slot}");
|
||||
let source = match !shape.skips_carrier() && *owner == 0 {
|
||||
let source = match !skips_carrier && *owner == 0 {
|
||||
true => quote!(__carrier_layout),
|
||||
false => format_ident!("__in_{owner}").to_token_stream(),
|
||||
};
|
||||
quote!(let #slot = #source.offset_of(<#marker as #core_types::attribute::Attribute>::NAME, 0);)
|
||||
});
|
||||
let write_inits = shape.write_markers.iter().enumerate().map(|(index, marker)| {
|
||||
let write_inits = write_markers.iter().enumerate().map(|(index, marker)| {
|
||||
let slot = format_ident!("__write_{index}");
|
||||
quote! {
|
||||
let #slot = __layout
|
||||
@@ -1797,14 +1755,14 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let name = &field.pat_ident.ident;
|
||||
quote!(#name,)
|
||||
});
|
||||
let carrier_init = (!shape.skips_carrier()).then(|| quote!(__carrier: __carrier_layout.clone(),)).into_iter();
|
||||
let carrier_init = (!skips_carrier).then(|| quote!(__carrier: __carrier_layout.clone(),)).into_iter();
|
||||
let input_layout_inits = reading_secondaries.iter().map(|index| {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote!(#slot: #slot.clone(),)
|
||||
});
|
||||
let plan_init = (!shape.skips_carrier()).then(|| quote!(__plan,)).into_iter();
|
||||
let plan_init = (!skips_carrier).then(|| quote!(__plan,)).into_iter();
|
||||
let read_names = (0..flat_reads.len()).map(|index| format_ident!("__read_{index}")).map(|slot| quote!(#slot,));
|
||||
let write_names = (0..shape.write_markers.len()).map(|index| format_ident!("__write_{index}")).map(|slot| quote!(#slot,));
|
||||
let write_names = (0..write_markers.len()).map(|index| format_ident!("__write_{index}")).map(|slot| quote!(#slot,));
|
||||
quote! {
|
||||
#layout_def
|
||||
#layout_meta_def
|
||||
@@ -1848,7 +1806,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
false => quote!(self.__frame_bytes == 0),
|
||||
};
|
||||
let reclaim_guard = (flip || record.is_some()).then(|| {
|
||||
let reclaim_guard = (flip || record_io).then(|| {
|
||||
quote! {
|
||||
// SAFETY: an inline node returns its output by value, so nothing above the entry pointer is live when the guard rewinds.
|
||||
let __reclaim_guard = unsafe { #core_types::record::ReclaimGuard::new(#reclaim_active) };
|
||||
@@ -1874,7 +1832,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let eval_body = eval_steps.iter().map(|step| match step {
|
||||
EvalStep::Bind(index, field) => {
|
||||
let body = bind_body(*index, field);
|
||||
match roles[*index].reads_out() {
|
||||
let reads_out = matches!(&field.ty, ParsedFieldType::Regular(_)) && ir::value_binding(&node, *index).reads_out();
|
||||
match reads_out {
|
||||
false => body,
|
||||
true => {
|
||||
let mark = format_ident!("__mark_{index}");
|
||||
|
||||
@@ -1,53 +1,32 @@
|
||||
use super::*;
|
||||
|
||||
/// How a record node's primary input lowers.
|
||||
/// 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 {
|
||||
/// `_: ()`: no carrier edge, the kernel writes a fresh record.
|
||||
None,
|
||||
/// An unbounded generic returned in the element position: the element
|
||||
/// bytes carry through the copy plan and the kernel sees `ElToken`.
|
||||
Token(Ident),
|
||||
/// An element type read at offset 0, monomorphized per its
|
||||
/// implementations list where generic.
|
||||
Read(Type),
|
||||
Token,
|
||||
Read,
|
||||
}
|
||||
|
||||
/// The record io of a node fn: how the carrier lowers, the element write,
|
||||
/// and the markers written and removed. Present exactly when the signature
|
||||
/// declares attribute reads or writes in a shape the record tier supports;
|
||||
/// malformed record io is reported by validation and generates no node impl.
|
||||
/// 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,
|
||||
pub(crate) element_write: Option<Type>,
|
||||
pub(crate) write_markers: Vec<Type>,
|
||||
pub(crate) removes: Vec<Type>,
|
||||
}
|
||||
|
||||
impl RecordShape {
|
||||
pub(crate) fn skips_carrier(&self) -> bool {
|
||||
matches!(self.carrier, RecordCarrier::None)
|
||||
}
|
||||
|
||||
pub(crate) fn carries_element(&self) -> bool {
|
||||
self.element_write.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// The record-tier lowering a node fn resolves to. Exactly one class per node,
|
||||
/// computed once by [`analyze`]; every downstream fragment reads the class
|
||||
/// instead of recomputing the classification predicates.
|
||||
pub(crate) enum Class {
|
||||
RecordIo(RecordShape),
|
||||
Routing(RoutingIo),
|
||||
Flip { carrier: bool },
|
||||
Opaque,
|
||||
}
|
||||
|
||||
/// The effect/return axis of a node's kernel, resolved once from the signature.
|
||||
/// Orthogonal to [`Class`]: it selects the eval tail (finish / merge / spawn)
|
||||
/// and the kernel signature wrapping across every class.
|
||||
/// 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,
|
||||
@@ -71,63 +50,22 @@ pub(crate) fn dialect(parsed: &ParsedNodeFn) -> Dialect {
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of classifying a node fn. A node with no supported lowering
|
||||
/// (an async node with lazy inputs, malformed record io, or a signature no
|
||||
/// class accepts) yields `None` and generates a struct and metadata but no
|
||||
/// `Node` impl.
|
||||
pub(crate) struct NodeModel {
|
||||
pub(crate) class: Class,
|
||||
pub(crate) dialect: Dialect,
|
||||
}
|
||||
|
||||
pub(crate) fn analyze(parsed: &ParsedNodeFn) -> Option<NodeModel> {
|
||||
/// 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 class = if let Some(shape) = record_shape(parsed) {
|
||||
Class::RecordIo(shape)
|
||||
let supported = if record_shape(parsed).is_some() {
|
||||
true
|
||||
} else if has_record_io(parsed) {
|
||||
return None;
|
||||
} else if let Some(routing) = routing_io(parsed) {
|
||||
Class::Routing(routing)
|
||||
} else if record_flip(parsed) {
|
||||
Class::Flip { carrier: flip_carrier(parsed) }
|
||||
} else if record_opaque(parsed) {
|
||||
Class::Opaque
|
||||
} else {
|
||||
return None;
|
||||
routing_io(parsed).is_some() || record_flip(parsed) || record_opaque(parsed)
|
||||
};
|
||||
Some(NodeModel { class, dialect: dialect(parsed) })
|
||||
}
|
||||
|
||||
/// The per-field binding role, resolved once per regular field from the node
|
||||
/// class and field shape. Drives the eval bindings and the lazy-edge input
|
||||
/// types. The `lend` and `reads` axes stay field properties the value arms of
|
||||
/// `kernel_params`/`call_args`/`value_args` consult, since they cross roles.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum InputRole {
|
||||
RecordCarrier,
|
||||
FlipCarrier,
|
||||
ReadingSecondary,
|
||||
LendBorrow,
|
||||
RecordValue,
|
||||
PlainValue,
|
||||
DeriveRoutingSource,
|
||||
OpaqueRecordEdge,
|
||||
FlipRawLazyEdge,
|
||||
FlipLazy,
|
||||
RawLazy,
|
||||
Lazy,
|
||||
}
|
||||
|
||||
impl InputRole {
|
||||
/// A role that copies an element out of a record edge, so its record frame
|
||||
/// must be reclaimed after the read. The step lowering wraps such a bind in
|
||||
/// `mark`/`rewind`, making the stack discipline structural rather than
|
||||
/// hand-threaded through each read-out arm.
|
||||
pub(crate) fn reads_out(self) -> bool {
|
||||
matches!(self, InputRole::ReadingSecondary | InputRole::RecordValue)
|
||||
}
|
||||
supported.then(|| dialect(parsed))
|
||||
}
|
||||
|
||||
/// The tail form of a node's eval, selected from its class and dialect: forward
|
||||
@@ -171,12 +109,12 @@ pub(crate) fn has_lazy_reads(parsed: &ParsedNodeFn) -> bool {
|
||||
|
||||
/// The value inputs of a routing node (every regular field that is not a
|
||||
/// routing source), with their indices into the regular fields.
|
||||
pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], routing: &RoutingIo) -> Vec<usize> {
|
||||
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(&routing.generic)),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => !matches!(ty, Type::Path(path) if path.path.get_ident() == Some(generic)),
|
||||
ParsedFieldType::Node(_) => false,
|
||||
})
|
||||
.map(|(index, _)| index)
|
||||
@@ -196,11 +134,11 @@ pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(u
|
||||
|
||||
/// The indices (into the unit-skipped regular fields) of value inputs whose
|
||||
/// reads resolve against their own wire rather than the carrier's.
|
||||
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], shape: &RecordShape) -> Vec<usize> {
|
||||
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() && (shape.skips_carrier() || *index != 0))
|
||||
.filter(|(index, field)| !field.attribute_reads.is_empty() && (skips_carrier || *index != 0))
|
||||
.map(|(index, _)| index)
|
||||
.collect()
|
||||
}
|
||||
@@ -347,43 +285,43 @@ pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, lend: None, implementations, .. }) = &carrier_field.ty else {
|
||||
return None;
|
||||
};
|
||||
let carrier = match ty {
|
||||
Type::Tuple(tuple) if tuple.elems.is_empty() => RecordCarrier::None,
|
||||
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) => RecordCarrier::Token(token),
|
||||
Some(token) => Some(token),
|
||||
None => {
|
||||
if contains_open_generic(parsed, ty) {
|
||||
return None;
|
||||
}
|
||||
RecordCarrier::Read(ty.clone())
|
||||
None
|
||||
}
|
||||
},
|
||||
};
|
||||
let (element, write_markers, removes) = match writes {
|
||||
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()),
|
||||
};
|
||||
let element_write = match &carrier {
|
||||
RecordCarrier::Token(token) => match bare_ident(&element) {
|
||||
Some(ident) if ident == token => None,
|
||||
_ => return None,
|
||||
},
|
||||
_ => {
|
||||
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;
|
||||
}
|
||||
Some(element)
|
||||
}
|
||||
};
|
||||
}
|
||||
if matches!(carrier, RecordCarrier::None) && !removes.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(RecordShape {
|
||||
carrier,
|
||||
element_write,
|
||||
write_markers,
|
||||
removes,
|
||||
})
|
||||
Some(RecordShape { carrier })
|
||||
}
|
||||
|
||||
pub(crate) fn is_poll_kernel(output: &Type) -> bool {
|
||||
|
||||
@@ -3,15 +3,13 @@ use proc_macro2::TokenStream as TokenStream2;
|
||||
use quote::{format_ident, quote};
|
||||
use syn::{GenericParam, Ident, Type};
|
||||
|
||||
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, class: &Class, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
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 class {
|
||||
Class::RecordIo(_) => record_entries_tokens(parsed, struct_name, regular_fields),
|
||||
Class::Routing(_) => routing_entries_tokens(parsed, struct_name, regular_fields),
|
||||
Class::Flip { .. } => flip_entries_tokens(parsed, struct_name, regular_fields),
|
||||
Class::Opaque => record_opaque_entries_tokens(parsed, struct_name, regular_fields),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +54,8 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
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 carrier_present = flip_carrier(parsed);
|
||||
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
|
||||
@@ -143,15 +142,11 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
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(gcore::record::LayoutMeta {
|
||||
carrier: #carrier_present,
|
||||
element: gcore::record::ElementSpec::Concrete(gcore::record::element_write::<#row_output>()),
|
||||
writes: ::std::vec::Vec::new(),
|
||||
removes: ::std::vec::Vec::new(),
|
||||
level_delta: 0,
|
||||
}),
|
||||
layout_meta: Some(#layout_meta),
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
gcore::registry::record_type::<#row_output>(),
|
||||
@@ -182,303 +177,172 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
}
|
||||
}
|
||||
|
||||
/// The registry row of a routing node: one instance covers every element,
|
||||
/// sources claim generic record edges, and the constructor wraps each source
|
||||
/// in its union translation and stores the union as the node's layout.
|
||||
fn routing_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
let Some(routing) = routing_io(parsed) else {
|
||||
return quote!();
|
||||
};
|
||||
let is_source = |field: &ParsedField| {
|
||||
let ty = match &field.ty {
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => output_type,
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty,
|
||||
};
|
||||
matches!(ty, Type::Path(path) if path.path.get_ident() == Some(&routing.generic))
|
||||
};
|
||||
let values_concrete = regular_fields.iter().filter(|field| !is_source(field)).all(|field| {
|
||||
let (ty, lend) = match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
|
||||
};
|
||||
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
|
||||
});
|
||||
if !values_concrete {
|
||||
return quote!();
|
||||
/// 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 entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
let token_name = routing.generic.to_string();
|
||||
let node = ir::build(parsed);
|
||||
let core_types = quote!(gcore);
|
||||
let lend = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. }));
|
||||
|
||||
let input_types = regular_fields.iter().map(|field| {
|
||||
if is_source(field) {
|
||||
return quote!(gcore::registry::generic_record_edge_type(#token_name));
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::record_edge_type::<#ty>()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
|
||||
}
|
||||
});
|
||||
let source_layouts: Vec<Ident> = regular_fields
|
||||
// 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()
|
||||
.filter(|(_, field)| is_source(field))
|
||||
.map(|(index, _)| format_ident!("__layout_{index}"))
|
||||
.collect();
|
||||
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
if is_source(field) {
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let ty = format_ident!("__ty_{index}");
|
||||
return quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let #ty = #handle.ty().clone();
|
||||
let Some(#layout) = #handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
.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()),
|
||||
};
|
||||
let #name = #handle.downcast_erased::<gcore::registry::ErasedRecordNode>(#ty.clone())?;
|
||||
};
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let layout = format_ident!("__in_layout_{index}");
|
||||
quote! {
|
||||
let #handle = inputs.next().unwrap();
|
||||
let Some(#layout) = #handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = #handle.downcast_record::<#ty>()?;
|
||||
}
|
||||
}
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
|
||||
}
|
||||
});
|
||||
let value_layout_args = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| !is_source(field) && matches!(field.ty, ParsedFieldType::Regular(_)))
|
||||
.map(|(index, _)| {
|
||||
let layout = format_ident!("__in_layout_{index}");
|
||||
quote!(&#layout,)
|
||||
});
|
||||
let source_wraps = regular_fields.iter().enumerate().filter(|(_, field)| is_source(field)).map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
quote!(let #name = gcore::record::RecordSource::new(#name, &#layout, &__union);)
|
||||
});
|
||||
let first_source_ty = regular_fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, field)| is_source(field))
|
||||
.map(|(index, _)| format_ident!("__ty_{index}"))
|
||||
.expect("routing nodes have a source");
|
||||
|
||||
quote! {
|
||||
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
|
||||
vec![gcore::registry::RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#token_name)))),
|
||||
vec![#(#input_types),*],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __union = gcore::record::Layout::union(&[#(&#source_layouts),*]);
|
||||
#(#source_wraps)*
|
||||
let __node = #struct_name::new(#(#names,)* &__union, #(#value_layout_args)*);
|
||||
Ok(gcore::registry::EdgeHandle::new_erased(
|
||||
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
|
||||
#first_source_ty,
|
||||
))
|
||||
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();
|
||||
|
||||
fn record_opaque_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
let is_record = |field: &ParsedField| matches!(&field.ty, ParsedFieldType::Node(NodeParsedField { output_type, .. }) if is_record_value(output_type));
|
||||
let values_concrete = regular_fields.iter().filter(|field| !is_record(field)).all(|field| {
|
||||
let (ty, lend) = match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => (ty, lend.is_some()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => (output_type, false),
|
||||
};
|
||||
!contains_open_generic(parsed, ty) && (lend || !type_disqualifies(ty))
|
||||
// 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 fn_name = &parsed.fn_name;
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
|
||||
let input_types = regular_fields.iter().map(|field| {
|
||||
if is_record(field) {
|
||||
return quote!(gcore::registry::generic_record_edge_type("T"));
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(gcore::registry::edge_type::<#ty>()),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(gcore::registry::edge_type::<#ty>()),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(gcore::registry::edge_type::<#output_type>()),
|
||||
}
|
||||
let 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 = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
if is_record(field) {
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let ty = format_ident!("__ty_{index}");
|
||||
return quote! {
|
||||
|
||||
let 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())?;
|
||||
};
|
||||
}
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => quote!(let #name = inputs.next().unwrap().downcast::<#output_type>()?;),
|
||||
},
|
||||
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 first_record = regular_fields.iter().position(|field| is_record(field)).expect("record-opaque nodes have a record input");
|
||||
let record_layout = format_ident!("__layout_{first_record}");
|
||||
let record_ty = format_ident!("__ty_{first_record}");
|
||||
|
||||
quote! {
|
||||
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
|
||||
vec![gcore::registry::RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed("T")))),
|
||||
vec![#(#input_types),*],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != #arity {
|
||||
return Err(gcore::registry::ConstructionError::Arity { expected: #arity, got: inputs.len() });
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __node = #struct_name::new(#(#names,)* &#record_layout);
|
||||
Ok(gcore::registry::EdgeHandle::new_erased(
|
||||
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
|
||||
#record_ty,
|
||||
))
|
||||
},
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
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();
|
||||
|
||||
fn record_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
let Some(shape) = record_shape(parsed) else {
|
||||
return quote!();
|
||||
let carried_meta = || {
|
||||
let meta = ir::layout_meta_tokens(&node, quote!(gcore::record::ElementSpec::Carried), &core_types);
|
||||
quote!(Some(#meta))
|
||||
};
|
||||
let carrier_in_fields = !shape.skips_carrier();
|
||||
let values_concrete = regular_fields.iter().skip(carrier_in_fields as usize).all(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => !contains_open_generic(parsed, ty) && (lend.is_some() || !type_disqualifies(ty)),
|
||||
_ => false,
|
||||
});
|
||||
if !values_concrete {
|
||||
return quote!();
|
||||
}
|
||||
|
||||
let fn_name = &parsed.fn_name;
|
||||
let entries_name = format_ident!("{}_entries", fn_name);
|
||||
let arity = regular_fields.len();
|
||||
let names: Vec<&Ident> = regular_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
let reading_secondaries = reading_secondary_indices(regular_fields, &shape);
|
||||
|
||||
let input_types = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("record nodes take no lazy inputs")
|
||||
};
|
||||
if carrier_in_fields && index == 0 {
|
||||
return match &shape.carrier {
|
||||
RecordCarrier::Token(token) => {
|
||||
let name = token.to_string();
|
||||
quote!(gcore::registry::generic_record_edge_type(#name))
|
||||
}
|
||||
RecordCarrier::Read(carrier_ty) => quote!(gcore::registry::record_edge_type::<#carrier_ty>()),
|
||||
RecordCarrier::None => unreachable!(),
|
||||
};
|
||||
}
|
||||
match field.attribute_reads.is_empty() {
|
||||
true => quote!(gcore::registry::edge_type::<#ty>()),
|
||||
false => quote!(gcore::registry::record_edge_type::<#ty>()),
|
||||
}
|
||||
});
|
||||
let downcasts = regular_fields.iter().enumerate().map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("record nodes take no lazy inputs")
|
||||
};
|
||||
if carrier_in_fields && index == 0 {
|
||||
return quote! {
|
||||
let __carrier_handle = inputs.next().unwrap();
|
||||
let __carrier_ty = __carrier_handle.ty().clone();
|
||||
let Some(__carrier_layout) = __carrier_handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = __carrier_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__carrier_ty.clone())?;
|
||||
};
|
||||
}
|
||||
if !field.attribute_reads.is_empty() {
|
||||
let layout_local = format_ident!("__in_layout_{index}");
|
||||
return quote! {
|
||||
let __in_handle = inputs.next().unwrap();
|
||||
let __in_ty = __in_handle.ty().clone();
|
||||
let Some(#layout_local) = __in_handle.layout().cloned() else {
|
||||
return Err(gcore::registry::ConstructionError::MissingLayout);
|
||||
};
|
||||
let #name = __in_handle.downcast_erased::<gcore::registry::ErasedRecordNode>(__in_ty)?;
|
||||
};
|
||||
}
|
||||
quote!(let #name = inputs.next().unwrap().downcast::<#ty>()?;)
|
||||
});
|
||||
let wire_layout_arg = carrier_in_fields.then(|| quote!(&__carrier_layout,)).into_iter();
|
||||
let input_layout_args = reading_secondaries.iter().map(|index| {
|
||||
let layout_local = format_ident!("__in_layout_{index}");
|
||||
quote!(&#layout_local,)
|
||||
});
|
||||
let (io_output, construct_output) = match (&shape.carrier, &shape.element_write) {
|
||||
(RecordCarrier::Token(token), _) => {
|
||||
let name = token.to_string();
|
||||
(
|
||||
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_erased(
|
||||
::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>,
|
||||
__carrier_ty,
|
||||
))),
|
||||
)
|
||||
}
|
||||
(_, Some(element)) => (
|
||||
// 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)))),
|
||||
),
|
||||
(_, None) => unreachable!("non-token record nodes write an element"),
|
||||
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"),
|
||||
};
|
||||
|
||||
let layout_meta_fn = format_ident!("{}_layout_meta", fn_name);
|
||||
quote! {
|
||||
pub fn #entries_name() -> ::std::vec::Vec<gcore::registry::RegistryEntry> {
|
||||
vec![gcore::registry::RegistryEntry {
|
||||
layout_meta: Some(self::#layout_meta_fn()),
|
||||
layout_meta: #layout_meta,
|
||||
io: gcore::registry::NodeIOTypes::new(
|
||||
gcore::concrete!(gcore::context::ContextImpl<'static>),
|
||||
#io_output,
|
||||
@@ -490,15 +354,16 @@ fn record_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fie
|
||||
}
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __node = #struct_name::new(#(#names,)* #(#wire_layout_arg)* #(#input_layout_args)*);
|
||||
#construct_output
|
||||
#prelude
|
||||
let __node = #struct_name::new(#(#names,)* #new_layout_args);
|
||||
#wrap
|
||||
},
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&ParsedField]) -> Option<Vec<Vec<Type>>> {
|
||||
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
|
||||
|
||||
@@ -0,0 +1,760 @@
|
||||
//! 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(¶m.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())],
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -648,7 +648,7 @@ impl Parse for NodeFnAttributes {
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_node_fn(attr: TokenStream2, item: TokenStream2) -> syn::Result<ParsedNodeFn> {
|
||||
pub(crate) 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.")))?;
|
||||
|
||||
|
||||
@@ -393,10 +393,11 @@ fn validate_primary_input_expose(parsed: &ParsedNodeFn) {
|
||||
fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
|
||||
let has_skip_impl = parsed.attributes.skip_impl;
|
||||
let routing = crate::codegen::routing_io(parsed);
|
||||
let record_token = crate::codegen::record_shape(parsed).and_then(|shape| match shape.carrier {
|
||||
crate::codegen::RecordCarrier::Token(token) => Some(token),
|
||||
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(),
|
||||
|
||||
@@ -221,6 +221,20 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout_meta_folds_to_construction() {
|
||||
let base = f64_layout(&[]);
|
||||
let carried = multiply_opacity_layout(&base);
|
||||
|
||||
assert_eq!(multiply_opacity_layout_meta().fold(&[Some(&base)]), multiply_opacity_layout(&base));
|
||||
assert_eq!(multiply_opacity_layout_meta().fold(&[Some(&carried)]), multiply_opacity_layout(&carried));
|
||||
assert_eq!(measure_layout_meta().fold(&[Some(&base)]), measure_layout(&base));
|
||||
assert_eq!(strip_opacity_layout_meta().fold(&[Some(&carried)]), strip_opacity_layout(&carried));
|
||||
assert_eq!(relength_layout_meta().fold(&[Some(&base)]), relength_layout(&base));
|
||||
assert_eq!(transfer_opacity_layout_meta().fold(&[Some(&base), None]), transfer_opacity_layout(&base));
|
||||
assert_eq!(source_opacity_layout_meta().fold(&[]), source_opacity_layout());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_then_modify_then_stack() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
|
||||
@@ -221,7 +221,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn create_context_builds_the_render_context_from_the_root_vararg() {
|
||||
let arena = Arena::new(256).unwrap();
|
||||
let arena = Arena::new(4096).unwrap();
|
||||
let generations = [];
|
||||
let scope = EvalScope::new(None, None, None, &generations, &arena);
|
||||
let root = ContextImpl::root(&scope);
|
||||
@@ -240,12 +240,16 @@ mod tests {
|
||||
};
|
||||
let ctx = root.with_varargs(&varargs);
|
||||
|
||||
let graph = CreateContextNode::new(ProbeNode);
|
||||
let GPoll::Final(result) = <CreateContextNode<ProbeNode> as Node<ContextImpl>>::eval(&graph, &ctx) else {
|
||||
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 {
|
||||
panic!("create_context must complete synchronously");
|
||||
};
|
||||
let output: &RenderOutput = unsafe { core_types::record::borrow_element(layout.rec(&result)) };
|
||||
assert_eq!(
|
||||
result.data,
|
||||
output.data,
|
||||
RenderOutputType::Buffer {
|
||||
data: Vec::new(),
|
||||
width: 0,
|
||||
|
||||
Reference in new issue
Block a user