Compare commits

..
40 changed files with 246 additions and 2394 deletions

No files matched your search

@@ -1024,6 +1024,12 @@ fn replace_optional_f64_null(input: &str) -> String {
result
}
/// Serialized proto identifiers of the pre-flip Merge and Artboard layer internals.
/// A document containing any of them predates the leveled-records flip and rebuilds its
/// layer definitions through the same reset mechanism as the `SourceNodeIdNode` entry in
/// `document_migration_reset_node_definition`.
pub const FLIP_RESET_NODE_MARKERS: &[&str] = &["graphic_nodes::graphic::WriteAttributeNode"];
pub fn document_migration_reset_node_definition(document_serialized_content: &str) -> bool {
// Upgrade a document being opened to use fresh copies of all nodes
if document_serialized_content.contains("node_output_index") {
@@ -1045,6 +1051,12 @@ pub fn document_migration_reset_node_definition(document_serialized_content: &st
return true;
}
// The leveled-records flip replaced the layer internals; documents from before it rebuild
// their layer definitions.
if FLIP_RESET_NODE_MARKERS.iter().any(|marker| document_serialized_content.contains(marker)) {
return true;
}
false
}
@@ -1421,18 +1433,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Rebuild stale Rasterize subgraphs from before the async-source conversion gave the inner proto node a unit primary input (5 inputs, now 6).
if let DocumentNodeImplementation::Network(inner) = &node.implementation
&& inner
.nodes
.values()
.any(|n| n.inputs.len() == 5 && matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(id) if id.as_str().contains("rasterize")))
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Rasterize".into()))
&& let Some(node_definition) = resolve_document_node_type(&DefinitionIdentifier::Network("Rasterize".into()))
{
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
}
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
@@ -2604,12 +2604,10 @@ mod tests {
use super::*;
#[test]
fn a_written_attribute_no_longer_resets_the_layer_definitions() {
// The node resolves natively again, so a document carrying it keeps
// its own layer internals instead of rebuilding them.
assert!(!document_migration_reset_node_definition(
r#"{"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}}}"#
));
fn the_flip_reset_markers_keep_the_historical_merge_internals_spelling() {
// The node itself is removed; the marker matches its spelling in
// documents saved before the flip, which must stay stable.
assert_eq!(FLIP_RESET_NODE_MARKERS, &["graphic_nodes::graphic::WriteAttributeNode"]);
}
#[test]
+4 -12
View File
@@ -502,9 +502,7 @@ impl NodeRuntime {
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
if type_id == std::any::TypeId::of::<Graphic>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
// SAFETY: the batch is resident for the read.
let item = unsafe { GroupItem::from_resident(batch) };
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
let group = Graphic::Group(Group { row: None, content: item });
@@ -516,9 +514,7 @@ impl NodeRuntime {
// clips content to those rectangles so anything outside isn't visible
else if type_id == std::any::TypeId::of::<Artboard>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
// SAFETY: the batch is resident for the read.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Artboard>::new(&item)?;
let bounds = artboard_clip_bounds(&run);
@@ -528,9 +524,7 @@ impl NodeRuntime {
}
// Vector run: vector modifications
else if type_id == std::any::TypeId::of::<Vector>() {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
// SAFETY: the batch is resident for the read.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<Vector>::new(&item)?;
use graphene_std::core_types::lane::LaneSource;
@@ -540,9 +534,7 @@ impl NodeRuntime {
// String run: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
else if type_id == std::any::TypeId::of::<String>() {
if update_thumbnails {
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
// lifetime, so the item cannot escape this read window, which the
// frames outlive.
// SAFETY: the batch is resident for the read.
let item = unsafe { GroupItem::from_resident(batch) };
let run = RunView::<String>::new(&item)?;
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
@@ -20,9 +20,7 @@ impl Compiler {
proto_networks.map(move |mut proto_network| {
proto_network.insert_context_nullification_nodes()?;
let _ = proto_network.resolve_types(registry);
proto_network
.compute_layouts()
.map_err(|errors| errors.iter().map(|error| format!("{:?}", error.error)).collect::<Vec<_>>().join("\n"))?;
proto_network.compute_layouts();
proto_network.generate_stable_node_ids();
Ok(proto_network)
})
+1 -122
View File
@@ -378,9 +378,7 @@ impl ProtoNetwork {
Ok(())
}
pub fn compute_layouts(&mut self) -> Result<(), GraphErrors> {
self.fold_attribute_names()?;
let mut errors = GraphErrors::new();
pub fn compute_layouts(&mut self) {
for index in 0..self.nodes.len() {
let lane_invariant = self.nodes[index].1.lane_invariant_inputs;
let layout = {
@@ -390,9 +388,6 @@ impl ProtoNetwork {
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
lane_invariant,
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
layout,
}),
ConstructionArgs::Nodes(inputs) => node.resolved.layout_meta.as_ref().and_then(|meta| {
@@ -400,10 +395,6 @@ impl ProtoNetwork {
.iter()
.map(|input| self.nodes[input.0 as usize].1.resolved.layout.as_ref().map(|resolved| &resolved.layout))
.collect();
// A read meets the name's value type where the name was
// written, so a disagreement upstream is caught here
// rather than read as the wrong type at run time.
errors.extend(read_type_conflicts(node, meta, &input_layouts));
meta.sources.iter().all(|&source| input_layouts[source as usize].is_some()).then(|| core_types::record::RecordLayout {
lane_invariant,
..meta.resolve(&input_layouts)
@@ -421,79 +412,6 @@ impl ProtoNetwork {
self.nodes[index].1.resolved.layout = layout;
}
self.stack_need = self.fold_stack_peak();
errors.is_empty().then_some(()).ok_or(errors)
}
/// Resolves every name-from-input write against the constant its name
/// input carries, leaving each node's meta indistinguishable from a marker
/// node's. A name input that is not a constant is refused here, which is
/// the whole of the no-runtime-names rule: past this point a name is a
/// `&'static str` in a layout, so there is nowhere for one to be computed.
fn fold_attribute_names(&mut self) -> Result<(), GraphErrors> {
let mut errors = GraphErrors::new();
for index in 0..self.nodes.len() {
let Some(meta) = &self.nodes[index].1.resolved.layout_meta else { continue };
if meta.named_writes.is_empty() && meta.named_reads.is_empty() {
continue;
}
let ConstructionArgs::Nodes(inputs) = &self.nodes[index].1.construction_args else {
continue;
};
// Writes first, then reads: both draw their names the same way, and
// the one-name-one-type check runs over them together.
let sources: Vec<(u8, std::any::TypeId)> = meta
.named_writes
.iter()
.map(|named| (named.name_input, named.template.type_id))
.chain(meta.named_reads.iter().map(|named| (named.name_input, named.template.type_id)))
.collect();
let names: Vec<Result<&'static str, GraphErrorType>> = sources
.iter()
.map(
|&(name_input, _)| match inputs.get(name_input as usize).map(|input| &self.nodes[input.0 as usize].1.construction_args) {
Some(ConstructionArgs::Value(value)) => match &**value {
value::TaggedValue::String(name) => Ok(core_types::attribute::intern_name(name)),
other => Err(GraphErrorType::AttributeName(format!("an attribute name must be text, but input {} is {}", name_input + 1, other.ty()))),
},
_ => Err(GraphErrorType::AttributeName(format!(
"input {} must be a constant, since attribute names resolve when the graph compiles rather than when it runs",
name_input + 1
))),
},
)
.collect();
let node = &self.nodes[index].1;
let mut folded: Vec<(&'static str, std::any::TypeId)> = Vec::new();
let mut failed = false;
for (name, &(_, type_id)) in names.iter().zip(&sources) {
match name {
Err(error) => {
errors.push(GraphError::new(node, error.clone()));
failed = true;
}
Ok(name) => {
if let Some(conflict) = one_name_one_type(name, type_id, &folded) {
errors.push(GraphError::new(node, conflict));
failed = true;
}
folded.push((name, type_id));
}
}
}
if failed {
continue;
}
let writes = self.nodes[index].1.resolved.layout_meta.as_ref().expect("checked above").named_writes.len();
let meta = self.nodes[index].1.resolved.layout_meta.as_mut().expect("checked above");
for (position, name) in names.into_iter().enumerate() {
let name = name.expect("every name resolved");
match position < writes {
true => meta.fold_name(position, name),
false => meta.fold_read_name(name),
}
}
}
errors.is_empty().then_some(()).ok_or(errors)
}
/// Peak record-stack bytes for evaluating [`output`](Self::output)'s cone. A node holds its
@@ -819,47 +737,9 @@ impl ProtoNetwork {
Ok(())
}
}
/// Reports each name-from-input read whose value type disagrees with the field
/// the name already names on the input it reads. An absent field is no
/// conflict: the read serves the name's forced default.
fn read_type_conflicts(node: &ProtoNode, meta: &core_types::record::LayoutMeta, inputs: &[Option<&core_types::record::Layout>]) -> GraphErrors {
meta.named_reads
.iter()
.zip(&meta.folded_read_names)
.filter_map(|(read, name)| {
let layout = inputs.get(read.input as usize).copied().flatten()?;
let field = layout.fields.iter().find(|field| field.name == *name && field.level == read.template.level)?;
(field.type_id != read.template.type_id).then(|| {
GraphError::new(
node,
GraphErrorType::AttributeName(format!("attribute `{name}` is read at one value type but written at another, and one name carries one value type")),
)
})
})
.collect()
}
/// Reports a folded name that disagrees with a type the same name already
/// carries, over the census and the names this node folded together. One name
/// means one value type everywhere, so the layouts a graph folds can never
/// declare a field twice at two widths.
fn one_name_one_type(name: &str, value_type: std::any::TypeId, folded: &[(&'static str, std::any::TypeId)]) -> Option<GraphErrorType> {
let census = core_types::attribute::info(name);
let declared = census
.filter(|row| row.value_type != value_type)
.map(|row| row.value_type_name.to_string())
.or_else(|| folded.iter().find(|(other, ty)| *other == name && *ty != value_type).map(|_| "another type on this node".to_string()))?;
Some(GraphErrorType::AttributeName(format!(
"attribute `{name}` is already declared at {declared}, and one name carries one value type"
)))
}
#[derive(Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum GraphErrorType {
NodeNotFound(NodeId),
/// A name-from-input attribute write whose name could not be resolved: it
/// is not a constant, or it disagrees with the name's declared value type.
AttributeName(String),
UnexpectedGenerics {
index: usize,
inputs: Vec<Type>,
@@ -884,7 +764,6 @@ impl Debug for GraphErrorType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GraphErrorType::NodeNotFound(id) => write!(f, "Input node {id} is not present in the typing context"),
GraphErrorType::AttributeName(error) => write!(f, "{error}"),
GraphErrorType::UnexpectedGenerics { index, inputs } => write!(f, "Generic inputs should not exist but found at {index}: {inputs:?}"),
GraphErrorType::NoImplementations => write!(f, "No implementations found"),
GraphErrorType::NoConstructor => write!(f, "No construct found for node"),
@@ -33,20 +33,6 @@ fn over_budget(used: usize, budget: usize) -> bool {
used >= budget / 8 * 7
}
/// The deep element glue is filled by runtime registration: ctors at load
/// natively, host-invoked exports on wasm. A lifetime-carrying element whose
/// glue never registered takes the shallow clone-out path, which brands its
/// arena borrows `'static` for a memo to hold across a reset, so a missed
/// registration is caught here rather than at the first capture.
fn assert_deep_element_glue() {
for (name, registered) in [
("graphic", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Graphic<'static>>())),
("artboard", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Artboard<'static>>())),
] {
assert!(registered, "deep element glue for `{name}` is missing; run `__node_registry_deep_element_{name}` first");
}
}
fn new_arena(capacity: usize) -> Arena {
Arena::new(capacity).unwrap_or_else(|| {
log::error!("arena generations exhausted; continuing without frame caching");
@@ -80,7 +66,6 @@ fn noop_runtime() -> Arc<DynGraphRuntime> {
impl Default for DynamicExecutor {
fn default() -> Self {
assert_deep_element_glue();
Self {
output: Default::default(),
tree: Default::default(),
@@ -111,7 +96,6 @@ pub struct ResolvedDocumentNodeTypesDelta {
impl DynamicExecutor {
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
assert_deep_element_glue();
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
typing_context.update(&mut proto_network)?;
let output = proto_network.output;
@@ -193,7 +177,9 @@ impl DynamicExecutor {
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
let result = self.tree.introspect(node_path)?;
if result.downcast_ref::<core_types::context::CtxSnapshot>().is_some() {
return self.introspect_with(node_path, graphic_types::boundary::batch_to_legacy).map(Arc::from);
return self
.introspect_with(node_path, graphic_types::boundary::batch_to_legacy)
.map(Arc::from);
}
Ok(result)
}
@@ -719,7 +705,7 @@ mod test {
fn build_executor(mut network: ProtoNetwork) -> DynamicExecutor {
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
network.compute_layouts().unwrap();
network.compute_layouts();
DynamicExecutor::new(network).unwrap()
}
@@ -735,193 +721,6 @@ mod test {
ProtoNode::value(ConstructionArgs::Value(TaggedValue::String(value.to_string()).into()), vec![])
}
/// A record source, a constant name, and a value wired into the write node.
fn write_attribute_network(name: &str, value: TaggedValue) -> ProtoNetwork {
ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(3),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), string_value(name)),
(NodeId(2), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![])),
(NodeId(3), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(1), NodeId(2)])),
],
}
}
#[test]
fn a_constant_name_folds_into_the_written_layout() {
let executor = build_executor(write_attribute_network("novel:count", TaggedValue::F64(2.5)));
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(3)).unwrap();
let layout = handle.layout().clone();
let offset = layout.offset_of("novel:count", 0).expect("the folded name names a field of the output layout");
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("expected a final record");
};
let rec = layout.rec(&value);
assert_eq!(unsafe { rec.element::<f64>() }, 7., "the element passes through the write");
assert_eq!(unsafe { rec.read::<f64>(offset) }, 2.5, "the value lands under the folded name");
}
#[test]
fn a_census_name_writes_at_its_declared_value_type() {
let path = vec![NodeId(7), NodeId(8)];
let executor = build_executor(write_attribute_network("editor:layer_path", TaggedValue::NodeIdPath(path.clone())));
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(3)).unwrap();
let layout = handle.layout().clone();
let offset = layout.offset_of("editor:layer_path", 0).expect("a census name folds onto its census field");
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("expected a final record");
};
assert_eq!(unsafe { layout.rec(&value).read::<&[NodeId]>(offset) }, path.as_slice());
}
/// Reads `read_name` off a record that a write of `write_name` produced.
fn read_attribute_network(write_name: &str, read_name: &str, value: TaggedValue) -> ProtoNetwork {
read_attribute_network_over(TaggedValue::F64(7.), write_name, read_name, value)
}
/// The same graph over any content element, which the read never looks at.
fn read_attribute_network_over(content: TaggedValue, write_name: &str, read_name: &str, value: TaggedValue) -> ProtoNetwork {
ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(5),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(content.into()), vec![])),
(NodeId(1), string_value(write_name)),
(NodeId(2), ProtoNode::value(ConstructionArgs::Value(value.into()), vec![])),
(NodeId(3), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(1), NodeId(2)])),
(NodeId(4), string_value(read_name)),
(NodeId(5), proto_node("graphic_nodes::graphic::ReadNumberAttributeNode", vec![NodeId(3), NodeId(4)])),
],
}
}
fn read_back(network: ProtoNetwork) -> f64 {
let executor = build_executor(network);
let arena = Arena::new(1 << 12).unwrap();
let generations = [];
let scope = EvalScope::new(None, None, None, &generations, &arena);
let ctx = ContextImpl::root(&scope);
let handle = executor.tree().get(NodeId(5)).unwrap();
let layout = handle.layout().clone();
let edge = handle.duplicate().downcast_record::<f64>().unwrap();
let frames = core_types::record::test_frames(executor.tree().stack_need());
let GPoll::Final(value) = core_types::record::serve_input(&edge, &ctx, &frames) else {
panic!("expected a final record");
};
unsafe { core_types::record::read_element::<f64>(layout.rec(&value)) }
}
#[test]
fn a_named_read_serves_the_written_value() {
assert_eq!(read_back(read_attribute_network("novel:count", "novel:count", TaggedValue::F64(2.5))), 2.5);
}
#[test]
fn an_absent_named_read_serves_the_forced_default() {
// Nothing upstream writes `novel:absent`, so the read collapses to the
// value type's default rather than reporting absence.
assert_eq!(read_back(read_attribute_network("novel:count", "novel:absent", TaggedValue::F64(2.5))), 0.);
}
#[test]
fn one_read_node_serves_every_content_element() {
// The read never looks at the element, so one registry row covers any
// upstream record wire rather than a row per element type.
assert_eq!(read_back(read_attribute_network_over(TaggedValue::F64(7.), "novel:count", "novel:count", TaggedValue::F64(2.5))), 2.5);
assert_eq!(
read_back(read_attribute_network_over(TaggedValue::Bool(true), "novel:count", "novel:count", TaggedValue::F64(2.5))),
2.5
);
assert_eq!(
read_back(read_attribute_network_over(TaggedValue::DVec2(glam::DVec2::ONE), "novel:count", "novel:count", TaggedValue::F64(2.5))),
2.5
);
}
#[test]
fn a_census_named_read_round_trips_its_written_value() {
// A declared name folds onto its census field, so the read resolves
// against the same offset the write installed.
assert_eq!(read_back(read_attribute_network("opacity", "opacity", TaggedValue::F64(0.5))), 0.5);
}
#[test]
fn an_absent_census_named_read_serves_the_census_default() {
// `opacity` is declared `f64` defaulting to 1, so its absence reads as
// the census default rather than the value type's.
assert_eq!(read_back(read_attribute_network("novel:count", "opacity", TaggedValue::F64(2.5))), 1.);
}
#[test]
fn a_named_read_disagreeing_with_its_write_is_refused() {
// The name is written at a path upstream and read at `f64` here, which
// is the one-name-one-type rule spanning a write and a read.
let mut network = read_attribute_network("novel:count", "novel:count", TaggedValue::NodeIdPath(vec![NodeId(1)]));
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
let errors = network.compute_layouts().expect_err("a name at two value types must be refused");
assert!(
errors.iter().any(|error| format!("{:?}", error.error).contains("one name carries one value type")),
"the refusal names the one-name-one-type rule, got {errors:?}"
);
}
#[test]
fn a_runtime_attribute_name_is_refused_when_the_graph_compiles() {
// The outer node's name comes off another node rather than sitting on
// the wire as text. It still types as a string, so only the fold can
// reject it, which is the case the design rules out entirely.
let mut network = ProtoNetwork {
stack_need: 0,
inputs: vec![],
output: NodeId(6),
nodes: vec![
(NodeId(0), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(7.).into()), vec![])),
(NodeId(1), string_value("novel:count")),
(NodeId(2), string_value("inner:name")),
(NodeId(3), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(1.).into()), vec![])),
// Carries a string element, so its output types as a name.
(NodeId(4), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(1), NodeId(2), NodeId(3)])),
(NodeId(5), ProtoNode::value(ConstructionArgs::Value(TaggedValue::F64(2.5).into()), vec![])),
(NodeId(6), proto_node("graphic_nodes::graphic::WriteAttributeNode", vec![NodeId(0), NodeId(4), NodeId(5)])),
],
};
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
let errors = network.compute_layouts().expect_err("a non-constant name must be refused");
assert!(
errors.iter().any(|error| format!("{:?}", error.error).contains("must be a constant")),
"the refusal names the constant requirement, got {errors:?}"
);
}
#[test]
fn one_name_carries_one_value_type() {
// `opacity` is declared `f64` in the census, so writing a path there is
// a graph error rather than a second field of the same name.
let mut network = write_attribute_network("opacity", TaggedValue::NodeIdPath(vec![NodeId(1)]));
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
let errors = network.compute_layouts().expect_err("a name at two value types must be refused");
assert!(
errors.iter().any(|error| format!("{:?}", error.error).contains("one name carries one value type")),
"the refusal names the one-name-one-type rule, got {errors:?}"
);
}
#[test]
fn the_clone_node_clones_the_element_out_of_its_record_wire() {
let network = ProtoNetwork {
@@ -7,7 +7,7 @@ use graphene_std::raster::GPU;
#[cfg(feature = "gpu")]
use graphene_std::SourceId;
use graphene_std::raster::{CPU, Raster};
use graphene_std::registry::{ConstructionError, NodeIOTypes, RegistryEntry, SourceHandle};
use graphene_std::registry::{ConstructionError, SourceHandle, NodeIOTypes, RegistryEntry};
#[cfg(feature = "gpu")]
use graphene_std::runtime::RuntimeHandle;
@@ -227,9 +227,7 @@ mod node_registry_macros {
let handle = inputs.next().unwrap();
let layout = handle.layout().clone();
let node = graphene_std::ops::IntoNode::<$to, _, $from>::new(handle.downcast_record::<$from>()?, &layout);
Ok(SourceHandle::new_record::<$to>(
std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>
))
Ok(SourceHandle::new_record::<$to>(std::sync::Arc::new(node) as std::sync::Arc<core_types::registry::ErasedRecordNode>))
},
},
)
+14 -99
View File
@@ -27,12 +27,11 @@ pub struct Arena {
/// a park costs one pointer in the arena and owns its content outside it.
retained_heap: AtomicUsize,
/// Where [`Arena::move_park`] sent each moved park, as its offset here to
/// the header's address in the receiving arena, the moved type's key and
/// that arena's generation, so a payload two records share is moved once
/// while a mistyped sharer, a sharer naming another destination, and a
/// sharer whose destination has since flushed are all refused. Cleared by
/// [`Arena::reset`], so a forwarding holds for one generation.
forwarded: Mutex<HashMap<usize, (usize, TypeId, u64)>>,
/// the header's address in the receiving arena and the moved type's key, so
/// a payload two records share is moved once and a mistyped sharer is
/// refused. Cleared by [`Arena::reset`], so a forwarding holds for one
/// generation.
forwarded: Mutex<HashMap<usize, (usize, TypeId)>>,
}
impl std::fmt::Debug for Arena {
@@ -54,9 +53,6 @@ struct DropEntry {
/// The glue a tombstoned entry carries: its payload was moved to another arena,
/// which now owns the obligation.
///
/// # Safety
/// None: the payload is neither read nor dropped, so any pointer is accepted.
unsafe fn inert(_: *mut u8) {}
/// The entry parking `offset`, `None` where the arena holds no obligation for
@@ -240,23 +236,14 @@ impl Arena {
// Built before the write so an unencodable offset drops `value` here
// rather than stranding it in the arena without drop glue.
let weak = ArenaWeak::new(self.generation(), offset)?;
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
unsafe { ptr.write(value) };
if std::mem::needs_drop::<T>() {
/// # Safety
/// `p` must address the live `T` this entry was registered for.
unsafe fn glue<T>(p: *mut u8) {
// SAFETY: the caller's contract.
unsafe { p.cast::<T>().drop_in_place() }
}
self.drops.lock().unwrap().push(DropEntry {
offset,
type_of,
drop_fn: glue::<T>,
retained,
});
self.drops.lock().unwrap().push(DropEntry { offset, type_of, drop_fn: glue::<T>, retained });
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
}
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
@@ -277,12 +264,6 @@ impl Arena {
/// fan-out sharer's second move reaches the one header and the obligation
/// is never duplicated.
///
/// A forwarding is to one destination generation, since the returned
/// pointer is only the caller's to publish where it lands in the `dst` it
/// named: a second move to another arena, or to one that has flushed since,
/// is refused rather than answered with a foreign or freed header. The
/// refusal reads as a decline, so the caller takes its clone path.
///
/// `dst` is credited `retained`, which is what a clone of the payload would
/// have credited it, and this arena is debited what its own park recorded,
/// so neither counter reads worse than it did before the move.
@@ -309,11 +290,8 @@ impl Arena {
(offset < self.buf.len()).then_some(())?;
let type_of = TypeId::of::<T::Static>();
let mut forwarded = self.forwarded.lock().unwrap();
if let Some(&(moved, moved_type, moved_generation)) = forwarded.get(&offset) {
if let Some(&(moved, moved_type)) = forwarded.get(&offset) {
(moved_type == type_of).then_some(())?;
// Generations are globally unique, so the match is `dst` itself and
// its current epoch; anything else declines.
(moved_generation == dst.generation()).then_some(())?;
return Some(moved as *const T::Static);
}
let mut entries = self.drops.lock().unwrap();
@@ -327,10 +305,7 @@ impl Arena {
let parked = std::mem::replace(&mut entries[entry].retained, 0);
entries[entry].drop_fn = inert;
drop(entries);
/// # Safety
/// `p` must address the live `T` this entry was registered for.
unsafe fn glue<T>(p: *mut u8) {
// SAFETY: the caller's contract.
unsafe { p.cast::<T>().drop_in_place() }
}
dst.drops.lock().unwrap().push(DropEntry {
@@ -341,7 +316,7 @@ impl Arena {
});
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
forwarded.insert(offset, (target as usize, type_of, dst.generation()));
forwarded.insert(offset, (target as usize, type_of));
Some(target.cast_const())
}
@@ -360,7 +335,6 @@ impl Arena {
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
let size = size_of::<T>().checked_mul(len)?;
let offset = self.reserve(size, align_of::<T>())?;
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
// `&mut self`, so the slice cannot outlive the generation.
@@ -370,13 +344,9 @@ impl Arena {
/// The generation-checked handle for a region this arena holds, `None` for
/// a pointer from anywhere else. The handle keeps the region's provenance,
/// so a cache stores one where it would otherwise launder an address.
///
/// The offset must sit below the bump watermark, not merely inside the
/// backbone: [`ArenaWeak::upgrade`] hands out a `&T` at it, so only bytes a
/// reservation already handed out may be minted into a handle.
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
(offset < self.offset.load(Ordering::Acquire)).then_some(())?;
(offset < self.buf.len()).then_some(())?;
ArenaWeak::new(self.generation(), offset)
}
@@ -392,14 +362,13 @@ impl Arena {
self.forwarded.get_mut().unwrap().clear();
self.generation.store(PARKED_GENERATION, Ordering::Release);
for entry in entries.into_iter().rev() {
// Debited before the glue runs: a panicking destructor drops the
// remaining entries unglued, so a hint subtracted afterwards would
// strand on the counter for the arena's whole life.
let retained = self.retained_heap.get_mut();
*retained = retained.saturating_sub(entry.retained);
// SAFETY: registered at alloc time; insert-only means the region was
// never overwritten within this generation.
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
// Decremented as each payload's heap is freed, so an unwinding reset
// leaves the counter matching what is still parked.
let retained = self.retained_heap.get_mut();
*retained = retained.saturating_sub(entry.retained);
}
*self.offset.get_mut() = 0;
*self.exhausted.get_mut() = false;
@@ -581,57 +550,6 @@ mod tests {
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
}
#[test]
fn handles_mint_only_over_reserved_bytes() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
let arena = Arena::new(1024).unwrap();
let (value, _) = arena.alloc(41u32).unwrap();
let ptr = std::ptr::from_ref(value).cast::<u8>();
assert!(arena.handle_at(ptr).is_some(), "a byte the bump handed out mints a handle");
let unreserved = ptr.wrapping_add(64);
assert!(arena.contains(unreserved), "the fixture stays inside the backbone");
assert!(arena.handle_at(unreserved).is_none(), "a byte past the watermark mints nothing");
}
#[test]
fn a_forwarding_answers_only_the_destination_it_recorded() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Probe(#[allow(dead_code)] String);
unsafe impl dyn_any::StaticType for Probe {
type Static = Probe;
}
let transient = Arena::new(1024).unwrap();
let mut first = Arena::new(1024).unwrap();
let second = Arena::new(1024).unwrap();
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
unsafe { transient.move_park::<Probe>(src, &first, 21) }.unwrap();
assert!(unsafe { transient.move_park::<Probe>(src, &second, 21) }.is_none(), "a sharer naming another destination is refused");
first.reset();
assert!(unsafe { transient.move_park::<Probe>(src, &first, 21) }.is_none(), "a flushed destination is refused too");
}
#[test]
fn a_panicking_destructor_does_not_strand_the_retained_hint() {
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
struct Bomb;
impl Drop for Bomb {
fn drop(&mut self) {
panic!("payload destructor");
}
}
let mut arena = Arena::new(1024).unwrap();
arena.alloc_sized(Bomb, 64).unwrap();
assert_eq!(arena.retained_heap(), 64);
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
assert!(unwound.is_err(), "the panic must propagate out of reset");
assert_eq!(arena.retained_heap(), 0, "the hint is debited before the glue that panics");
}
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
/// is never observed by a concurrently constructing test.
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
@@ -777,10 +695,7 @@ mod tests {
let (parked, _) = transient.alloc_sized_keyed(Owner(String::from("a keyed park")), 0).unwrap();
let src = std::ptr::from_ref(parked).cast::<u8>();
assert!(
unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(),
"a park of another type of the same size is refused"
);
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "a park of another type of the same size is refused");
unsafe { transient.move_park::<Owner>(src, &persistent, 0) }.unwrap();
assert!(unsafe { transient.move_park::<Twin>(src, &persistent, 0) }.is_none(), "the forwarding refuses the same mistype");
@@ -20,35 +20,15 @@ use std::sync::{LazyLock, Mutex};
/// Declares an attribute name: one marker per name, fixing the value type and
/// the name-specific default. Declare markers through the [`attribute!`]
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`] and emits
/// an impl meeting the obligations below.
///
/// # Safety
///
/// [`REPARK`](Self::REPARK) must be `Some` for every marker whose
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`. The
/// plain-value arm of the census writer retypes the value [`from_stored`] hands
/// it from the stored form's lifetime to the field's, which is only a relabel
/// where the value borrows nothing; a re-parking marker instead writes a
/// reference into the arena it is given.
///
/// [`from_stored`](Self::from_stored) must accept exactly the erased form
/// [`read_erased`](Self::read_erased) produces, and [`read_erased`] must read
/// its `ptr` as this marker's own `Value`. The two are each other's inverse
/// across every persistence seam, so a marker that reads one type and stores
/// another writes a value of the wrong type into the field.
pub unsafe trait Attribute: 'static {
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
pub trait Attribute: 'static {
/// The name as it appears in documents and diagnostics.
const NAME: &'static str;
/// The value type every read and write of this name shares. The lifetime
/// is the evaluation the value flows in; non-reference values ignore it.
/// The value outlives that evaluation, so its `'static` instantiation is
/// the one the census registers and layouts stamp their type id from.
///
/// `Send + Sync` because a record's bytes are these values: `RecordValue`
/// is `Send + Sync` over whatever the field writes put there, and the write
/// path never consults the census, so the bound has to sit here.
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
type Value<'e>: Copy + Default + std::fmt::Debug + 'e;
/// The name-specific default, filled where an item lacks the attribute.
/// Producing a value for any `'e` from no inputs, reference defaults can
/// only point at `'static` data, which is what lets the census fill them
@@ -155,278 +135,6 @@ impl<A: Attribute> Default for RemoveAttr<A> {
}
}
/// The value-type half of an attribute: everything [`Attribute`] declares
/// except the name and its name-specific default. A name-generic write pairs
/// one of these with a name taken from the graph, so the value type stays
/// concrete in the signature while the name varies per instance.
///
/// # Safety
///
/// The obligations are [`Attribute`]'s, at this trait's value type:
/// [`REPARK`](Self::REPARK) must be `Some` for every row whose
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`, and
/// [`from_stored`](Self::from_stored) and [`read_erased`](Self::read_erased)
/// must be each other's inverse.
pub unsafe trait AttrValue: 'static {
/// The value type every write of this row shares, as [`Attribute::Value`].
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
/// Borrows the value out of legacy list storage, as [`Attribute::from_stored`].
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>>;
/// # Safety
/// `ptr` must point at a live field of this row's value type.
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue>;
/// Re-parks an owned clone into fresh field storage, as [`Attribute::REPARK`].
const REPARK: Option<crate::list::ReparkFn> = None;
}
/// The [`Attribute::NAME`] a [`Named`] marker carries before the compiler
/// fills it. A layout never holds it: the fold replaces it with the
/// instance's constant, and a node whose name input is not constant is
/// refused at that same point.
pub const NAMED_PLACEHOLDER: &str = "";
/// A name-generic attribute write. `X` is a placeholder that distinguishes
/// name-generic attributes within one signature, so a node writing two of
/// them takes two names; `V` fixes the value type. The name is absent by
/// construction: it comes from the instance's constant text input, folded
/// into the layout at graph compile time, so a computed name cannot exist.
///
/// Written `Named<X>` in parameter position, it declares where `X`'s name is
/// wired: the macro gives that input constant text, and the kernel receives
/// only the placeholder, since a folded name is a layout fact rather than a
/// value the kernel needs.
pub struct Named<X, V = Text>(PhantomData<fn() -> (X, V)>);
impl<X, V> Default for Named<X, V> {
fn default() -> Self {
Named(PhantomData)
}
}
/// The placeholders a signature distinguishes its name-generic attributes by.
/// A node writing one name uses [`Name0`]; a second name on the same node
/// takes [`Name1`], and so on, which is all the placeholder has to do.
pub struct Name0;
/// The second name-generic attribute in one signature. See [`Name0`].
pub struct Name1;
/// The third name-generic attribute in one signature. See [`Name0`].
pub struct Name2;
// SAFETY: every obligation is discharged by `V`, which carries the same
// contract at the same value type; only the name differs, and the compiler
// fold replaces the placeholder before a layout sees it.
unsafe impl<X: 'static, V: AttrValue> Attribute for Named<X, V> {
const NAME: &'static str = NAMED_PLACEHOLDER;
type Value<'e> = V::Value<'e>;
fn from_stored<'a>(stored: &'a dyn std::any::Any) -> Option<Self::Value<'a>> {
V::from_stored(stored)
}
unsafe fn read_erased(ptr: *const u8) -> Box<dyn AnyAttributeValue> {
// SAFETY: the caller's contract, at `V`'s own value type.
unsafe { V::read_erased(ptr) }
}
const REPARK: Option<crate::list::ReparkFn> = V::REPARK;
}
/// The value a name-generic write takes off the wire, and the row it lands
/// in. A plain row is its own wire form; a reference row's wire form is the
/// owned payload the kernel parks in the arena, so the field can carry a
/// borrow of it for the evaluation.
pub trait WireValue: 'static {
/// The row this value is written at, fixing the field's value type.
type Row: AttrValue;
/// Moves the value into `arena` where the row borrows it, or hands it back
/// unchanged where the row stores it plainly. `None` reports exhaustion.
fn park<'e>(self, arena: &'e crate::arena::Arena) -> Option<<Self::Row as AttrValue>::Value<'e>>;
}
/// Declares [`WireValue`] rows. `for T` is a plain value, carried and stored
/// as itself; `Wire => Row` parks `Wire`'s payload in the arena and stores the
/// borrow `Row` names.
#[macro_export]
macro_rules! wire_value {
() => {};
(for $value:ty; $($rest:tt)*) => {
impl $crate::attribute::WireValue for $value {
type Row = $value;
fn park<'e>(self, _: &'e $crate::arena::Arena) -> ::core::option::Option<$value> {
::core::option::Option::Some(self)
}
}
$crate::wire_value!($($rest)*);
};
($wire:ty => $row:ty; $($rest:tt)*) => {
impl $crate::attribute::WireValue for $wire {
type Row = $row;
fn park<'e>(self, arena: &'e $crate::arena::Arena) -> ::core::option::Option<<$row as $crate::attribute::AttrValue>::Value<'e>> {
let (parked, _) = arena.alloc(self)?;
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
}
}
$crate::wire_value!($($rest)*);
};
}
wire_value! {
for f64;
for u32;
for u64;
for bool;
for DVec2;
for DAffine2;
for crate::Color;
for crate::blending::BlendMode;
::std::vec::Vec<crate::uuid::NodeId> => NodeIdPath;
::std::string::String => Text;
}
/// Interns a folded attribute name for the `&'static str` a layout field
/// holds. Census names never reach here; a document's novel names are finite
/// and repeat across instances, so the leak is one allocation per name.
pub fn intern_name(name: &str) -> &'static str {
static NAMES: LazyLock<Mutex<std::collections::HashSet<&'static str>>> = LazyLock::new(|| Mutex::new(std::collections::HashSet::new()));
let mut names = NAMES.lock().unwrap();
if let Some(interned) = names.get(name) {
return interned;
}
let interned: &'static str = Box::leak(name.to_owned().into_boxed_str());
names.insert(interned);
interned
}
/// Declares [`AttrValue`] rows, the value types a name-generic attribute can
/// be written at. `for T` implements the row on an existing plain value type;
/// `Row: &T` and `Row: Option<&T>` declare a token naming a reference value,
/// whose payload the writing kernel parks in the arena.
///
/// ```ignore
/// core_types::named_value! {
/// /// Plain rows, implemented on the value type itself.
/// for f64;
/// /// A reference row, whose token names the borrowed value.
/// pub Text: &str;
/// }
/// ```
///
/// The `for T` arm implements this crate's trait on `T`, so rows over types
/// this crate does not own are declared here rather than by a caller.
#[macro_export]
macro_rules! named_value {
() => {};
($(#[$meta:meta])* for $value:ty; $($rest:tt)*) => {
// SAFETY: a plain value type cannot name `'e`, so no re-park is owed,
// and the two glue fns below are each other's inverse at `$value`.
unsafe impl $crate::attribute::AttrValue for $value {
type Value<'e> = $value;
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored.downcast_ref::<$value>().copied()
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
}
}
$crate::named_value!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $row:ident: Option<&$value:ty>; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $row;
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
// are each other's inverse at `Option<&$value>`.
unsafe impl $crate::attribute::AttrValue for $row {
type Value<'e> = ::core::option::Option<&'e $value>;
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored
.downcast_ref::<::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned>>()
.map(|owned| owned.as_ref().map(::std::borrow::Borrow::borrow))
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<::core::option::Option<&$value>>().read() }.map(|value| <$value as ::std::borrow::ToOwned>::to_owned(value)))
}
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned> =
value.as_any().downcast_ref().expect("an optional reference row replays its owned clone");
let parked = match owned {
::core::option::Option::Some(owned) => {
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
}
::core::option::Option::None => ::core::option::Option::None,
};
unsafe { dst.cast::<::core::option::Option<&$value>>().write(parked) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::named_value!($($rest)*);
};
($(#[$meta:meta])* $vis:vis $row:ident: &$value:ty; $($rest:tt)*) => {
$(#[$meta])*
$vis struct $row;
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
// are each other's inverse at `&$value`.
unsafe impl $crate::attribute::AttrValue for $row {
type Value<'e> = &'e $value;
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
stored.downcast_ref::<<$value as ::std::borrow::ToOwned>::Owned>().map(::std::borrow::Borrow::borrow)
}
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
}
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference row replays its owned clone");
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
::core::option::Option::Some(())
}
::core::option::Option::Some(repark)
};
}
$crate::named_value!($($rest)*);
};
}
named_value! {
for f64;
for u32;
for u64;
for bool;
for DVec2;
for DAffine2;
for crate::Color;
for crate::blending::BlendMode;
/// A document node path, the value type of `editor:layer_path`.
pub NodeIdPath: &[crate::uuid::NodeId];
/// Free text, parked in the arena by the writing kernel.
pub Text: &str;
}
/// A census row: what is known about one declared attribute name.
#[derive(Clone, Copy, Debug)]
pub struct AttributeInfo {
@@ -443,25 +151,13 @@ pub struct AttributeInfo {
/// Writes a legacy stored value into a field of this marker, parking
/// droppable payloads. A wrong-typed stored value leaves the field
/// untouched; `None` reports arena exhaustion.
///
/// `dst` must address a live field of *this row's* value type: the glue
/// writes its own `Value`'s worth of bytes there, so a caller resolving the
/// field by [`name`](Self::name) checks [`size`](Self::size) and
/// [`value_type`](Self::value_type) against the field first. The fields
/// here are public and the struct is `Copy`, so a row is a claim about a
/// marker rather than a proof about a field.
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
}
/// The default's object representation, staged through zeroed storage so a
/// value with padding or an unused payload (`Option<f64>`'s `None`) hands the
/// caller deterministic bytes rather than whatever the stack held.
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
assert_eq!(out.len(), size_of::<A::Value<'static>>());
let mut staged = std::mem::MaybeUninit::<A::Value<'static>>::zeroed();
staged.write(A::default());
// SAFETY: the staging holds a live value of the type `out` is sized for.
unsafe { std::ptr::copy_nonoverlapping(staged.as_ptr().cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
let value: A::Value<'static> = A::default();
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
}
fn field_write_at<A: Attribute>(level: u8) -> crate::record::FieldWrite
@@ -471,15 +167,12 @@ where
crate::record::FieldWrite::of::<A>(level)
}
/// # Safety
/// `dst` must address a live field of `A`'s value type.
unsafe fn write_stored<A: Attribute>(stored: &dyn AnyAttributeValue, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
if A::from_stored(stored.as_any()).is_none() {
// A wrong-typed stored value reads as absent, so the field keeps its default.
return Some(());
}
match A::REPARK {
// SAFETY: the caller's contract; the glue is this marker's own.
Some(repark) => unsafe { repark(stored, dst, arena) },
None => {
let value = A::from_stored(stored.as_any()).expect("checked above");
@@ -558,10 +251,7 @@ macro_rules! attribute {
$(#[$meta])*
$vis struct $marker;
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
// as each other's inverse.
unsafe impl $crate::attribute::Attribute for $marker {
impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = ::core::option::Option<&'e $value>;
@@ -600,10 +290,7 @@ macro_rules! attribute {
$(#[$meta])*
$vis struct $marker;
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
// as each other's inverse.
unsafe impl $crate::attribute::Attribute for $marker {
impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = &'e $value;
$(
@@ -638,10 +325,7 @@ macro_rules! attribute {
$(#[$meta])*
$vis struct $marker;
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
// as each other's inverse.
unsafe impl $crate::attribute::Attribute for $marker {
impl $crate::attribute::Attribute for $marker {
const NAME: &'static str = $name;
type Value<'e> = $value;
$(
@@ -797,8 +481,7 @@ mod tests {
#[should_panic(expected = "two value types")]
fn a_second_marker_at_a_different_type_panics() {
struct Conflict;
// SAFETY: `bool` borrows nothing, so the plain-value arm is the right one.
unsafe impl Attribute for Conflict {
impl Attribute for Conflict {
const NAME: &'static str = "opacity";
type Value<'e> = bool;
+1 -5
View File
@@ -342,6 +342,7 @@ impl AttributeDyn {
pub fn is_empty(&self) -> bool {
self.0.len() == 0
}
}
impl Clone for AttributeDyn {
@@ -374,7 +375,6 @@ impl CacheHash for AttributeDyn {
}
}
// SAFETY: the type carries no lifetime, so it is its own static form.
unsafe impl StaticType for AttributeDyn {
type Static = Self;
}
@@ -418,7 +418,6 @@ impl CacheHash for AttributeValueDyn {
}
}
// SAFETY: as for AttributeDyn.
unsafe impl StaticType for AttributeValueDyn {
type Static = Self;
}
@@ -502,7 +501,6 @@ impl CacheHash for ListDyn {
}
}
// SAFETY: as for AttributeDyn.
unsafe impl StaticType for ListDyn {
type Static = Self;
}
@@ -1192,8 +1190,6 @@ impl<T> ApplyTransform for List<T> {
}
}
// SAFETY: the list carries its lifetime only through T, so substituting T's
// static form substitutes the list's and keeps the layout identical.
unsafe impl<T: StaticTypeSized> StaticType for List<T> {
type Static = List<T::Static>;
}
+3 -3
View File
@@ -106,10 +106,9 @@ pub struct RecordBatchMut<'a> {
impl<'a> RecordBatchMut<'a> {
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
/// which serve in ascending order with no gaps, so the initialized prefix is
/// a fact rather than a contract.
/// which is what makes the initialized prefix a fact rather than a contract.
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
debug_assert!(len.checked_mul(layout.lane_stride()).is_some_and(|need| need <= scratch.len() * 8));
debug_assert!(len * layout.lane_stride() <= scratch.len() * 8);
Self { scratch, len, layout }
}
@@ -136,6 +135,7 @@ impl<'a> RecordBatchMut<'a> {
// SAFETY: the constructor's contract; the exclusive borrow is consumed.
unsafe { RecordBatch::new(self.scratch.as_ptr().cast(), self.len, self.layout) }
}
}
/// One lane's record: its pointer paired with the batch's layout.
@@ -50,10 +50,9 @@ impl std::fmt::Debug for RecordValue<'_> {
}
}
// SAFETY: `element_write` requires the element `Send + Sync` and every field holds an
// `Attribute::Value`, which the trait bounds `Send + Sync`, so the record bytes behind
// the pointer are thread-safe; `'e` ties the pointer's validity to the shared arena and
// record-stack discipline.
// SAFETY: `element_write` requires the element `Send + Sync` and attribute payloads
// are `Copy` or arena-backed, so the record bytes behind the pointer are thread-safe;
// `'e` ties the pointer's validity to the shared arena and record-stack discipline.
unsafe impl Send for RecordValue<'_> {}
// SAFETY: as `Send`.
unsafe impl Sync for RecordValue<'_> {}
@@ -114,29 +113,6 @@ pub unsafe fn read_at<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<
})
}
/// [`read_at`] for a name-generic read, whose marker carries the value type
/// but not the name and so cannot know the name's own default. `absent` is
/// that default's bytes, which the compiler takes from the census once the
/// name is folded; without one the value type's default applies, which is
/// exactly the rule for a name the census does not declare.
///
/// # Safety
/// As [`read_at`]. `absent`, where present, must hold the object
/// representation of `A::Value`, which the compiler takes from the census row
/// for the folded name after checking that row's value type against `A`'s. A
/// reference-valued default addresses `'static` data, so the value it yields
/// outlives any evaluation.
pub unsafe fn read_at_defaulting<'e, A: attribute::Attribute>(rec: Rec<'_>, offset: Option<usize>, absent: Option<&[u8]>) -> attribute::Attr<'e, A> {
attribute::Attr(match (offset, absent) {
// SAFETY: the caller's contract.
(Some(offset), _) => unsafe { rec.read::<A::Value<'e>>(offset) },
// SAFETY: the caller's contract; the bytes are unaligned storage, so
// the value is read out rather than referenced in place.
(None, Some(bytes)) => unsafe { bytes.as_ptr().cast::<A::Value<'e>>().read_unaligned() },
(None, None) => A::default(),
})
}
/// The read-less [`DerivedLazyInput`] glue: the token alone.
///
/// # Safety
@@ -245,9 +221,7 @@ pub(in crate::record) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::Sta
/// # Safety
/// `src` must be a record of the plan's source layout and `dst` a buffer of
/// the plan's target layout; both are proven at wiring. The two records must
/// not overlap: a plan routinely carries identity moves, so each entry copies
/// non-overlapping and an aliasing pair is undefined on the first copy.
/// the plan's target layout; both are proven at wiring.
pub unsafe fn apply_plan(src: Rec<'_>, dst: *mut u8, plan: &[(usize, usize, usize)]) {
for &(from, to, size) in plan {
unsafe { std::ptr::copy_nonoverlapping(src.ptr().add(from), dst.add(to), size) };
@@ -111,7 +111,6 @@ impl<'e> Frames<'e> {
inline: RecordValue::zeroed(),
frame,
free: self.reborrow(),
filled_fields: false,
}
}
@@ -90,10 +90,7 @@ where
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
return BatchStatus::InvalidRange;
};
// Checked: a wrapped product would size the scratch below the run.
let Some(words) = len.checked_mul(node.layout().lane_stride()).map(|bytes| bytes / 8) else {
return BatchStatus::InvalidRange;
};
let words = len * node.layout().lane_stride() / 8;
let exhausted = || {
BatchStatus::Error(crate::gpoll::GraphError {
kind: crate::gpoll::ErrorKind::ArenaExhausted,
@@ -214,7 +211,6 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> {
/// `rec` must be a record of the layout the offsets were resolved against
/// and `El` its element type; both are proven at wiring.
unsafe fn element_only<El: Clone>(rec: Rec<'_>, _reads: &[Option<usize>]) -> El {
// SAFETY: the caller's contract.
unsafe { read_element::<El>(rec) }
}
@@ -517,8 +513,6 @@ impl<El: Clone + 'static, N> RecordExtract<El, N> {
// The element copies out by value, so the input's claim dies with
// the scope.
let scope = frames.scope();
// SAFETY: the served value is a record of `self.layout`, whose element is
// `El` by the wiring that built this extract.
serve_input(&self.edge, input, &scope).map(|value| unsafe { read_element::<El>(self.layout.rec(&value)) })
}
}
@@ -28,17 +28,11 @@ impl FieldWrite {
where
A::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
{
/// # Safety
/// `ptr` must address a live `V`.
unsafe fn content_hash<V: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
let mut state = state;
// SAFETY: the caller's contract.
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
}
/// # Safety
/// `a` and `b` must both address a live `V`.
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
// SAFETY: the caller's contract.
unsafe { *a.cast::<V>() == *b.cast::<V>() }
}
Self {
@@ -138,18 +132,12 @@ impl Eq for ElementWrite {}
impl Default for ElementWrite {
fn default() -> Self {
/// # Safety
/// None: the empty element has no bytes, so nothing is read.
unsafe fn clone_out(_ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
Box::new(())
}
/// # Safety
/// None: nothing is written, the empty element having no slot.
unsafe fn repark(_value: &(dyn std::any::Any + Send + Sync), _dst: *mut u8, _arena: &crate::arena::Arena) -> Option<()> {
Some(())
}
/// # Safety
/// None: the move always declines, so `parked` is never read.
unsafe fn park_move(_parked: *const u8, _promotion: &Promotion<'_>) -> Option<*const u8> {
None
}
@@ -167,11 +155,6 @@ impl Default for ElementWrite {
}
}
/// The widest alignment a record may need. Frames are a `Vec<u64>`, lanes
/// stride at a multiple of 8, and run slabs come from `alloc_scratch::<u64>`,
/// so nothing below a record can promise more.
pub const MAX_ALIGN: usize = 8;
/// A record layout: the element at offset 0, then the written attributes in
/// canonical order (descending alignment, then size, then name, then level).
/// Layouts are derived data, a pure function of the upstream write set.
@@ -215,9 +198,8 @@ impl Layout {
/// The union of this layout's fields and `writes` over `element` at
/// `depth`, in canonical order. A (name, level) written at a different
/// size is a type conflict and panics, as does an element or attribute
/// wider than [`MAX_ALIGN`]; the census keeps declared names to one type,
/// so these only fire on wiring bugs.
/// size is a type conflict and panics; the census keeps declared names to
/// one type, so this only fires on wiring bugs.
pub fn with_writes(&self, depth: u8, element: ElementWrite, writes: &[FieldWrite]) -> Layout {
let mut merged: Vec<FieldWrite> = self.fields.iter().map(FieldDesc::as_write).collect();
for &write in writes {
@@ -226,10 +208,6 @@ impl Layout {
None => merged.push(write),
}
}
assert!(element.align <= MAX_ALIGN, "a record element aligns to at most {MAX_ALIGN} bytes, but this one needs {}", element.align);
for write in &merged {
assert!(write.align <= MAX_ALIGN, "attribute `{}` aligns to at most {MAX_ALIGN} bytes, but needs {}", write.name, write.align);
}
merged.sort_by(|a, b| b.align.cmp(&a.align).then(b.size.cmp(&a.size)).then(a.name.cmp(b.name)).then(a.level.cmp(&b.level)));
let mut offset = element.size;
let mut align = element.align.max(1);
@@ -366,76 +344,6 @@ pub struct RecordLayout {
/// over input positions. Empty is the safe default: an uninstalled layout
/// rebinds every input per lane.
pub lane_invariant: u32,
/// The names the fold gave this node's name-from-input writes, in the
/// order the signature declares its placeholders. A marker-only node
/// leaves it empty; `set_layout` resolves its offsets through these
/// instead of through a marker's `NAME`.
pub named_writes: Vec<&'static str>,
/// The offsets the fold resolved for this node's name-from-input reads, in
/// placeholder order. `None` is an absent attribute, which the read serves
/// as the name's forced default. Resolved in the compiler, where the folded
/// name and the read input's finished layout sit together, so `set_layout`
/// only copies the numbers into the read slots.
pub named_reads: Vec<Option<usize>>,
/// The census default's bytes for each absent name-from-input read whose
/// name the census declares, in the same order. A name the census does not
/// declare has `None` and reads as its value type's default, which is that
/// case's own rule; a read that resolved to an offset needs no default.
pub named_read_defaults: Vec<Option<Box<[u8]>>>,
}
/// A write whose name comes from the graph rather than from a marker: the
/// input carrying the name, and the field descriptor with every facet but the
/// name already minted from the concrete value type.
#[derive(Clone, Copy, Debug)]
pub struct NamedWrite {
/// The proto input position holding the name's constant text.
pub name_input: u8,
/// The write this becomes once the fold supplies the name.
pub template: FieldWrite,
}
impl NamedWrite {
/// The template for a name-generic marker's write at `level`. Every facet
/// but the name is the concrete value type's, exactly as for a census
/// marker; [`FieldWrite::name`] holds the placeholder until the fold runs.
pub fn of<X: 'static, V: crate::attribute::AttrValue>(name_input: u8, level: u8) -> Self
where
V::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
{
Self {
name_input,
template: FieldWrite::of::<crate::attribute::Named<X, V>>(level),
}
}
}
/// A read whose name comes from the graph rather than from a marker. The
/// compiler resolves it to an offset in the read input's own layout, where
/// the folded name and that finished layout already sit together.
#[derive(Clone, Copy, Debug)]
pub struct NamedRead {
/// The proto input the attribute is read from.
pub input: u8,
/// The proto input holding the name's constant text.
pub name_input: u8,
/// The read's field form, every facet but the name minted from the
/// concrete value type, as for a write.
pub template: FieldWrite,
}
impl NamedRead {
/// The template for a name-generic marker's read at `level`.
pub fn of<X: 'static, V: crate::attribute::AttrValue>(input: u8, name_input: u8, level: u8) -> Self
where
V::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
{
Self {
input,
name_input,
template: FieldWrite::of::<crate::attribute::Named<X, V>>(level),
}
}
}
/// Declarative record-io metadata for a node type, emitted by the macro into
@@ -457,19 +365,6 @@ pub struct LayoutMeta {
pub element: ElementSpec,
/// The attributes the node writes at its acting level.
pub writes: Vec<FieldWrite>,
/// The attributes the node writes under a name taken from the graph. The
/// compiler fold turns each into a [`writes`](Self::writes) entry and
/// empties this, so a folded meta is indistinguishable from a marker
/// node's; one still carrying an entry has not been folded.
pub named_writes: Vec<NamedWrite>,
/// The names the fold gave [`named_writes`](Self::named_writes), in
/// placeholder order. Empty until the fold runs.
pub folded_names: Vec<&'static str>,
/// The attributes the node reads under a name taken from the graph.
pub named_reads: Vec<NamedRead>,
/// The names the fold gave [`named_reads`](Self::named_reads), in
/// placeholder order. Empty until the fold runs.
pub folded_read_names: Vec<&'static str>,
/// The attributes removed from the base layout, as `(name, level)`.
pub removes: Vec<(&'static str, u8)>,
/// The depth change the node applies: `0` for elementwise and flip nodes,
@@ -506,10 +401,6 @@ impl LayoutMeta {
reads: Vec::new(),
element: ElementSpec::Concrete(element),
writes: Vec::new(),
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
removes: Vec::new(),
level_delta: 0,
folded: None,
@@ -554,66 +445,13 @@ impl LayoutMeta {
// A reducer collapses its carrier's levels, so it writes a fresh record rather than copying fields down.
_ => Vec::new(),
};
// A named read resolves against the input it reads, whose layout is
// finished by the time this node folds. An absent attribute stays
// `None`, which the read serves as the name's forced default.
let named_reads: Vec<Option<usize>> = self
.named_reads
.iter()
.zip(&self.folded_read_names)
.map(|(read, name)| inputs.get(read.input as usize).copied().flatten().and_then(|layout| layout.offset_of(name, read.template.level)))
.collect();
// An absent read serves the name's own default, which for a declared
// name is the census's rather than the value type's. The census stages
// it the same way it fills any absent field: as the declared default's
// bytes. One name carries one value type, checked when the name folds,
// so the size agreement below is a guard rather than a branch.
let named_read_defaults = self
.named_reads
.iter()
.zip(&self.folded_read_names)
.zip(&named_reads)
.map(|((read, name), offset)| {
let row = offset.is_none().then(|| attribute::info(name))??;
(row.value_type == read.template.type_id && row.size == read.template.size).then(|| {
let mut bytes = vec![0u8; row.size];
(row.write_default_bytes)(&mut bytes);
bytes.into_boxed_slice()
})
})
.collect();
RecordLayout {
layout,
frame_bytes,
plan,
lane_invariant: 0,
named_writes: self.folded_names.clone(),
named_reads,
named_read_defaults,
}
}
/// Folds `name` into the name-from-input write at `index`, taking the
/// census row's descriptor where the name is declared so a known name
/// keeps its census default, and the template's otherwise. The write
/// joins [`writes`](Self::writes) in placeholder order.
pub fn fold_name(&mut self, index: usize, name: &'static str) {
let named = self.named_writes[index];
let census = attribute::info(name).map(|row| (row.field_write_at)(named.template.level));
let write = match census {
Some(write) if write.type_id == named.template.type_id => write,
_ => FieldWrite { name, ..named.template },
};
self.writes.push(write);
self.folded_names.push(name);
}
/// Records the name of the name-from-input read at `index`. The offset
/// itself waits for [`resolve`](Self::resolve), which is where the read
/// input's finished layout arrives.
pub fn fold_read_name(&mut self, name: &'static str) {
self.folded_read_names.push(name);
}
}
/// Field-by-field carry from `from`'s layout into `to`'s, computed at
@@ -660,32 +498,22 @@ pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Ele
where
T::Static: Clone + Send + Sync,
{
/// # Safety
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
unsafe fn clone_out<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync>
where
T::Static: Clone + Send + Sync,
{
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
// SAFETY: the caller's contract; the glue is registered for this element type.
return unsafe { (deep.clone_out)(ptr) };
}
// SAFETY: a lifetime-carrying element type registers deep glue, so this
// shallow path only erases borrow-free values. The registration is a
// whole-program convention rather than something this call can check:
// the executor asserts the in-tree types registered before it evaluates,
// which is where a missed wasm registration export is caught.
// SAFETY: a lifetime-carrying element type registers deep glue, so
// this shallow path only erases borrow-free values.
Box::new(unsafe { erase_static(read_element::<T>(Rec::new(ptr))) })
}
/// # Safety
/// `dst` must be fresh element storage of a record whose element is `T`, and
/// `value` must be the clone-out this glue produced for that element type.
unsafe fn repark<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &crate::arena::Arena) -> Option<()>
where
T::Static: Clone + Send + Sync,
{
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
// SAFETY: the caller's contract; the glue is registered for this element type.
return unsafe { (deep.repark)(value, dst, arena) };
}
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
@@ -730,17 +558,11 @@ pub fn element_write_hashed<T: Clone + Send + Sync + graphene_hash::CacheHash +
where
T::Static: Clone + Send + Sync,
{
/// # Safety
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
unsafe fn content_hash<T: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
let mut state = state;
// SAFETY: the caller's contract.
unsafe { borrow_element::<T>(Rec::new(ptr)) }.cache_hash(&mut state);
}
/// # Safety
/// `a` and `b` must each address a live element of `T` in that same form.
unsafe fn content_eq<T: PartialEq>(a: *const u8, b: *const u8) -> bool {
// SAFETY: the caller's contract.
unsafe { borrow_element::<T>(Rec::new(a)) == borrow_element::<T>(Rec::new(b)) }
}
ElementWrite {
@@ -797,18 +619,6 @@ mod tests {
assert_eq!(layout.align, 8);
}
#[test]
#[should_panic(expected = "a record element aligns to at most 8 bytes")]
fn an_over_aligned_element_is_refused_at_wiring() {
Layout::default().with_writes(0, element_write::<u128>(), &[]);
}
#[test]
#[should_panic(expected = "attribute `wide` aligns to at most 8 bytes")]
fn an_over_aligned_attribute_is_refused_at_wiring() {
Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("wide", 16, 16)]);
}
#[test]
#[should_panic(expected = "two different types")]
fn type_conflicts_panic() {
@@ -21,16 +21,16 @@ mod serve;
mod test_support;
mod testkit;
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_at_defaulting, read_element, token_only, write_element, write_element_sized, write_field};
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_element, token_only, write_element, write_element_sized, write_field};
pub use frames::{FrameArena, FrameScope, Frames};
pub use input::{DerivedLazyInput, DerivedRecordInput, ElementInput, ElementLazyInput, LevelStatus, RecordExtract, RecordInput, RecordLazyInput, fill_frames, materialize_batch, materialize_level};
pub use layout::{
ElToken, ElementSpec, ElementWrite, ElementWritePick, ElementWritePickHashed, ElementWritePickPlain, FieldDesc, FieldOffset, FieldWrite, InputReads, Layout, LayoutMeta, NamedRead, NamedWrite,
RecordLayout, copy_plan, element_dims, element_parked, element_write, element_write_hashed, empty_layout,
ElToken, ElementSpec, ElementWrite, ElementWritePick, ElementWritePickHashed, ElementWritePickPlain, FieldDesc, FieldOffset, FieldWrite, InputReads, Layout, LayoutMeta, RecordLayout, copy_plan,
element_dims, element_parked, element_write, element_write_hashed, empty_layout,
};
pub use owned::{OwnedRecord, deepen_field_value, has_deep_element_glue, register_deep_element_clone, register_deep_field_value, replay_field_value};
pub use owned::{OwnedRecord, deepen_field_value, register_deep_element_clone, register_deep_field_value, replay_field_value};
pub use promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
pub use route::{RecordSource, SourcePlan};
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView, run_to_owned_list};
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
pub use serve::{FrameClaim, MaterializedSpan, Served, SlotRun, serve_input};
pub use testkit::{LiftedSource, ServedRecord, capture, test_frames};
@@ -32,13 +32,6 @@ pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<
DEEP_ELEMENT_CLONES.lock().unwrap().get(&type_id).copied()
}
/// Whether elements of a type registered deep glue. The shallow clone path is
/// only sound for types that did not need to, so a host that drives the
/// registration itself checks the types it owes before it evaluates anything.
pub fn has_deep_element_glue(type_id: std::any::TypeId) -> bool {
DEEP_ELEMENT_CLONES.lock().unwrap().contains_key(&type_id)
}
/// Deep-copy overrides for field values whose content borrows the
/// evaluation's arena (a graphic list holding native groups), keyed by the
/// field's owned value form. Consulted at the persistence seams only:
@@ -57,7 +50,10 @@ static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections:
/// Registers the deep copy-out and replay pair for field values of `T`.
/// Called at startup from the crate that owns the type.
pub fn register_deep_field_value<T: 'static>(copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>, replay: crate::list::FieldReplayFn) {
pub fn register_deep_field_value<T: 'static>(
copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
replay: crate::list::FieldReplayFn,
) {
DEEP_FIELD_VALUES.lock().unwrap().insert(std::any::TypeId::of::<T>(), DeepFieldGlue { copy_out, replay });
}
@@ -91,10 +87,7 @@ pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &cr
pub struct OwnedRecord {
pub(in crate::record) bytes: Box<[u8]>,
pub(in crate::record) element: Option<Box<dyn std::any::Any + Send + Sync>>,
/// Each copied field's index in the copy's layout, that field's declared
/// value type, and the owned value. The type rides along so a replay can
/// re-check the field it resolves rather than trusting the caller's claim.
fields: Vec<(usize, std::any::TypeId, Box<dyn crate::list::AnyAttributeValue>)>,
fields: Vec<(usize, Box<dyn crate::list::AnyAttributeValue>)>,
}
impl std::fmt::Debug for OwnedRecord {
@@ -107,61 +100,35 @@ impl OwnedRecord {
/// # Safety
/// `rec` must be a live record of `layout`.
pub unsafe fn copy_out(layout: &Layout, rec: Rec<'_>) -> OwnedRecord {
// The element-to-field seam is never written, so the copy stays untyped:
// a `&[u8]` over the frame would read those bytes.
let mut staged = Vec::<u8>::with_capacity(layout.size);
// SAFETY: the caller's contract sizes the record at `layout.size`, which
// is the capacity just reserved, so the copy fills exactly the staging.
let bytes = unsafe {
std::ptr::copy_nonoverlapping(rec.ptr(), staged.as_mut_ptr(), layout.size);
staged.set_len(layout.size);
staged.into_boxed_slice()
};
// SAFETY: the caller's contract; a parked element sits at offset 0.
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(rec.ptr(), layout.size) }.into();
let element = layout.element.parked.then(|| unsafe { (layout.element.clone_out)(rec.ptr()) });
let fields = layout
.fields
.iter()
.enumerate()
.filter(|(_, field)| field.repark.is_some())
// SAFETY: the caller's contract; each field reads its own descriptor's offset.
.map(|(index, field)| (index, field.type_id, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
.map(|(index, field)| (index, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
.collect();
OwnedRecord { bytes, element, fields }
}
/// Replays the copy into a caller's claim, re-parking droppable payloads
/// against `arena`; `None` reports arena exhaustion. The claim's layout must
/// be the one the copy was taken at, which the checks below establish rather
/// than assume: the copy carries no layout of its own, so a mismatched claim
/// would otherwise write past the frame or re-park a field through another
/// field's glue.
/// against `arena`; the claim's layout is the one the copy was taken at,
/// and `None` reports arena exhaustion.
pub fn replay_into(&self, slot: &mut FrameClaim<'_, '_>, arena: &crate::arena::Arena) -> Option<()> {
let layout = slot.layout;
assert_eq!(self.bytes.len(), layout.size, "a replay lands in the layout the copy was taken at");
assert_eq!(self.element.is_some(), layout.element.parked, "a replay lands in the layout the copy was taken at");
for &(index, type_id, _) in &self.fields {
let field = layout.fields.get(index).expect("a replay lands in the layout the copy was taken at");
assert_eq!(field.type_id, type_id, "a replay lands in the layout the copy was taken at");
}
self.write_into(layout, slot.dst(), arena)
}
/// `dst` is a claimed frame of `layout`, and `replay_into`'s asserts have
/// established that `layout` is the one the copy was taken at.
fn write_into(&self, layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
// SAFETY: the copy is `layout.size` bytes and the claim is a frame of it.
unsafe { std::ptr::copy_nonoverlapping(self.bytes.as_ptr(), dst, self.bytes.len()) };
if let Some(element) = &self.element {
// SAFETY: the element was cloned out of this layout's own slot at offset 0.
unsafe { (layout.element.repark)(&**element, dst, arena) }?;
}
for (index, _, value) in &self.fields {
for (index, value) in &self.fields {
let field = &layout.fields[*index];
let repark = field.repark.expect("copied fields carry re-park glue");
let resident = replay_field_value(&**value, arena)?;
// SAFETY: the asserts matched this index's field type, so the glue and
// the value agree; the write lands in that field's own region.
unsafe { repark(resident.as_deref().unwrap_or(&**value), dst.add(field.offset), arena) }?;
}
Some(())
@@ -175,34 +142,6 @@ mod tests {
use crate::record::frames::FrameArena;
use crate::record::layout::{FieldWrite, element_write};
#[test]
fn a_padded_layout_copies_out_without_reading_its_seam() {
// A 4-byte element before an 8-aligned field leaves [4, 8) unwritten.
let layout = Layout::default().with_writes(0, element_write::<u32>(), &[FieldWrite::of::<crate::attribute::Opacity>(0)]);
let offset = layout.offset_of("opacity", 0).unwrap();
assert_eq!((layout.element.size, offset), (4, 8), "the fixture needs the element-to-field seam");
let arena = crate::arena::Arena::new(1024).unwrap();
let scratch = arena.alloc_scratch::<u64>(layout.frame_bytes().div_ceil(8)).unwrap();
let base: *mut u8 = scratch.as_mut_ptr().cast();
unsafe { write_element(base, 7u32, &arena) }.unwrap();
unsafe { write_field::<f64>(base, offset, 0.5) };
let copy = unsafe { OwnedRecord::copy_out(&layout, Rec::new(base.cast_const())) };
let replay_arena = crate::arena::Arena::new(1024).unwrap();
let mut frame_arena = FrameArena::new();
frame_arena.reserve(layout.frame_bytes());
let frames = frame_arena.frames();
let mut slot = frames.claim(&layout);
copy.replay_into(&mut slot, &replay_arena).unwrap();
// SAFETY: the replay completes the record in the claimed frame.
let value = unsafe { slot.finish() };
let rec = layout.rec(&value);
assert_eq!(unsafe { read_element::<u32>(rec) }, 7);
assert_eq!(unsafe { rec.read::<f64>(offset) }, 0.5);
}
#[test]
fn owned_records_replay_re_parked_payloads_after_the_source_dies() {
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
@@ -99,7 +99,6 @@ pub(in crate::record) unsafe fn promote_record(layout: &Layout, dst: *mut u8, pr
None => {
// SAFETY: as above, and the clone owns its content.
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
// SAFETY: the clone is this element's own type, back into its slot.
unsafe { (layout.element.repark)(&*owned, dst, promotion.persistent) }?;
}
},
@@ -244,7 +243,6 @@ impl MaterializedSpan {
// SAFETY: the caller's contract on the lane, into the lane's own
// region of the freshly reserved slab.
let dst = unsafe { base.add(lane * stride) };
// SAFETY: as above; `layout.size` bytes of a lane fit its own stride.
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, layout.size) };
// SAFETY: the copy images a record of this layout.
unsafe { promote_record(layout, dst, promotion) }?;
@@ -48,11 +48,9 @@ impl SourcePlan {
/// # Safety
/// `src` must be a record of this plan's source layout and `dst` a
/// buffer of the plan's union layout that does not overlap `src`. The
/// returned view borrows `dst`, so `'d` must not outlive it.
/// buffer of the plan's union layout. The returned view borrows `dst`, so
/// `'d` must not outlive it.
pub unsafe fn translate<'d>(&self, src: Rec<'_>, dst: *mut u8) -> Rec<'d> {
// SAFETY: the caller's contract; the plan's moves and fills name only
// offsets of the layouts it was built from.
unsafe {
apply_plan(src, dst, &self.moves);
for (offset, bytes) in &self.fills {
+29 -195
View File
@@ -2,53 +2,9 @@
use super::access::write_element;
use super::layout::{ElementWrite, FieldOffset, FieldWrite, Layout, element_write_hashed};
use super::owned::{deep_field_glue, deepen_field_value, replay_field_value};
use super::owned::deep_field_glue;
use super::promote::{Promotion, promote_record};
/// A group's element is compared and hashed by content, so it needs glue: the
/// byte fallback would read a padded element type's uninitialized padding.
fn assert_element_glue(layout: &Layout) {
assert!(
layout.element.size == 0 || layout.element.content_hash.is_some(),
"a run's element adopts only with content glue; declare it with `element_write_hashed`"
);
}
/// Whether a lane of `layout` names payloads a byte copy would leave parked in
/// the source arena.
fn holds_parked(layout: &Layout) -> bool {
layout.element.parked || layout.fields.iter().any(|field| field.repark.is_some())
}
/// Re-parks one copied lane's payloads into `arena`, so a lane copied across
/// arenas owns what it names instead of pointing back at the source's parks.
/// The counterpart of [`promote_record`] for a copy whose target is a serving
/// arena rather than the persistent region, so every reference clones.
/// `None` reports arena exhaustion.
///
/// # Safety
/// `dst` must image a live record of `layout` whose parked references still
/// resolve, which is the source lane's own image before this rewrites it.
unsafe fn readopt_record(layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
if layout.element.parked {
// SAFETY: the caller's contract; the clone owns all of its content.
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
// SAFETY: the clone is the element's own type, into its own slot.
unsafe { (layout.element.repark)(&*owned, dst, arena) }?;
}
for field in &layout.fields {
let Some(repark) = field.repark else { continue };
// SAFETY: a parked field slot holds one reference at its offset.
let slot = unsafe { dst.add(field.offset) };
// SAFETY: the slot images a parked field of this descriptor.
let value = deepen_field_value(unsafe { (field.read_erased)(slot.cast_const()) });
let resident = replay_field_value(&*value, arena)?;
// SAFETY: the replay produced this field's own value type.
unsafe { repark(resident.as_deref().unwrap_or(&*value), slot, arena) }?;
}
Some(())
}
/// Builds a resident run lane by lane: fresh frames in the arena at a layout
/// derived from the element glue and field writes, elements pushed in order
/// and attributes written onto pushed lanes. The finished item's frames are
@@ -66,7 +22,7 @@ impl<'e> RunBuilder<'e> {
/// `None` reports arena exhaustion.
pub fn new(arena: &'e crate::arena::Arena, element: ElementWrite, fields: &[FieldWrite], len: usize) -> Option<Self> {
let layout = Layout::default().with_writes(0, element, fields);
assert_element_glue(&layout);
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
}
@@ -96,8 +52,6 @@ impl<'e> RunBuilder<'e> {
// `lane` is below `len`; the element slot and each field's region are
// disjoint parts of this lane.
let base = unsafe { self.frames.add(lane * stride) };
// SAFETY: the element slot is fresh, and the assert above matched `T` to
// the layout's element type.
unsafe { write_element(base, element, self.arena) }?;
for field in &self.layout.fields {
// SAFETY: as above; the field region is within the lane.
@@ -135,23 +89,13 @@ impl<'e> RunBuilder<'e> {
/// Writes a legacy stored value on an already pushed lane through the
/// census glue, parking droppable payloads. A marker outside the layout's
/// fields is dropped, as is one whose row and field agree on the name but
/// not on the value type; a wrong-typed stored value leaves the field's
/// fields is dropped; a wrong-typed stored value leaves the field's
/// default. `None` reports arena exhaustion.
pub fn attr_stored(&mut self, lane: usize, info: &crate::attribute::AttributeInfo, value: &dyn crate::list::AnyAttributeValue) -> Option<()> {
assert!(lane < self.pushed, "attributes write onto pushed lanes");
let Some(field) = self.layout.fields.iter().find(|field| field.name == info.name && field.level == 0) else {
return Some(());
};
let (offset, size, type_id) = (field.offset, field.size, field.type_id);
// The row reaches the field by name alone, so the writer's own value type
// is checked against the field before its glue writes there, as `push`
// checks the default writer's.
if info.size != size || info.value_type != type_id {
return Some(());
}
// SAFETY: the offset comes from the builder's own layout, and the field
// was just checked to hold the writer's own value type at its size.
let Some(offset) = self.layout.offset_of(info.name, 0) else { return Some(()) };
// SAFETY: the offset comes from the builder's own layout, and the
// census writer verifies the stored type before touching the field.
unsafe { (info.write_stored)(value, self.frames.add(lane * self.layout.lane_stride() + offset), self.arena) }
}
@@ -216,11 +160,10 @@ impl<'e> GroupItem<'e> {
/// Copies the batch's lanes into the arena and clones its layout.
/// Returns `None` when the arena is exhausted. Parked regions must carry
/// the content glue, so equality and hashing never fall back to pointer
/// bytes. A copied lane's parked payloads re-park into `arena`, so the
/// adopted run names nothing the source arena's reset frees.
/// bytes.
pub fn adopt(batch: crate::node::RecordBatch<'_>, arena: &'e crate::arena::Arena) -> Option<Self> {
let layout = batch.layout().clone();
assert_element_glue(&layout);
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
}
@@ -238,16 +181,9 @@ impl<'e> GroupItem<'e> {
}
let scratch = arena.alloc_scratch::<u64>((batch.len() * stride).div_ceil(8))?;
let frames = scratch.as_mut_ptr().cast::<u8>();
let parked = holds_parked(&layout);
for lane in 0..batch.len() {
// SAFETY: both sides hold `len` lanes at the shared layout's stride.
let dst = unsafe { frames.add(lane * stride) };
// SAFETY: as above; the scratch was reserved for exactly these lanes.
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, stride) };
if parked {
// SAFETY: the copy images a live record of this layout.
unsafe { readopt_record(&layout, dst, arena) }?;
}
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), frames.add(lane * stride), stride) };
}
Some(Self {
layout,
@@ -303,14 +239,11 @@ impl<'e> GroupItem<'e> {
/// A `GroupItem` over the batch's frames, without copying.
///
/// # Safety
/// The item borrows the batch's frames at `'e`, so the frames must stay
/// valid for the whole of `'e` and nothing derived from the item may outlive
/// it. Arena-resident batches span the evaluation; a caller's serve scratch
/// spans only the window it lends the batch for, which is sound exactly when
/// `'e` is bounded to that window.
/// The frames must stay valid for the evaluation. Arena-resident batches
/// qualify, caller stack scratch does not.
pub unsafe fn from_resident(batch: crate::node::RecordBatch<'e>) -> Self {
let layout = batch.layout().clone();
assert_element_glue(&layout);
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
for field in &layout.fields {
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
}
@@ -346,19 +279,11 @@ impl<'e> GroupItem<'e> {
let frames = self.frames();
// SAFETY: the constructors store `len` lanes of `layout` at the
// layout's stride, and the erased glue reads each lane's own region.
// A lane's seam and stride tail are never written, so the copy stays
// untyped: a `&[u8]` over the frames would read those bytes.
let mut staged = Vec::<u8>::with_capacity(self.len * stride);
let bytes = unsafe {
std::ptr::copy_nonoverlapping(frames, staged.as_mut_ptr(), self.len * stride);
staged.set_len(self.len * stride);
staged.into_boxed_slice()
};
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(frames, self.len * stride) }.into();
let elements = self
.layout
.element
.parked
// SAFETY: as above; a parked element sits at each lane's offset 0.
.then(|| (0..self.len).map(|lane| unsafe { (self.layout.element.clone_out)(frames.add(lane * stride)) }).collect());
let fields = self
.layout
@@ -367,7 +292,6 @@ impl<'e> GroupItem<'e> {
.enumerate()
.filter(|(_, field)| field.repark.is_some())
.map(|(index, field)| {
// SAFETY: as above; each lane reads this descriptor's own offset.
let mut values: Vec<_> = (0..self.len).map(|lane| unsafe { (field.read_erased)(frames.add(lane * stride + field.offset)) }).collect();
if let Some(glue) = values.first().and_then(|value| deep_field_glue(value.as_any().type_id())) {
for value in &mut values {
@@ -392,9 +316,8 @@ impl<'e> GroupItem<'e> {
/// `arena`, sharing only where its lanes already live there.
pub fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<GroupItem<'a>> {
let ItemStorage::Owned(owned) = &self.storage else {
// A resident item re-serves at the target arena's own lifetime, so
// its lanes copy and their parked payloads re-park there rather
// than relabeling the borrow.
// A resident item re-serves at the target arena's own lifetime,
// so its lanes copy rather than relabeling the borrow.
return GroupItem::adopt(self.lanes(), arena);
};
let stride = self.layout.lane_stride();
@@ -405,7 +328,6 @@ impl<'e> GroupItem<'e> {
unsafe { std::ptr::copy_nonoverlapping(owned.bytes.as_ptr(), frames, owned.bytes.len()) };
if let Some(elements) = &owned.elements {
for (lane, element) in elements.iter().enumerate() {
// SAFETY: as above; the clone is this element's own type, into its lane's slot.
unsafe { (self.layout.element.repark)(&**element, frames.add(lane * stride), arena) }?;
}
}
@@ -414,8 +336,6 @@ impl<'e> GroupItem<'e> {
let repark = field.repark.expect("copied fields carry re-park glue");
let glue = values.first().and_then(|value| deep_field_glue(value.as_any().type_id()));
for (lane, value) in values.iter().enumerate() {
// SAFETY: the copy took these values through this field's own glue,
// so each writes its own type into its lane's region of the field.
match glue {
Some(glue) => match (glue.replay)(&**value, arena)? {
Some(resident) => unsafe { repark(&*resident, frames.add(lane * stride + field.offset), arena) }?,
@@ -480,25 +400,6 @@ impl<'e> GroupItem<'e> {
}
}
/// One typed run as an owned legacy list, elements cloned and every attribute
/// copied through its erased read. The owned result outlives the evaluation the
/// run was materialized in, so an async source can carry it across its await.
pub fn run_to_owned_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &GroupItem) -> Option<crate::list::List<T>> {
let lanes = item.typed_lanes::<T>()?;
let mut list = crate::list::List::new();
for lane in 0..lanes.len() {
list.push(crate::list::Item::new_from_element(lanes.element_ref(lane).clone()));
}
for field in &item.layout().fields {
for lane in 0..lanes.len() {
// SAFETY: the offset comes from the item's own layout.
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
list.set_attribute_value_dyn(field.name, lane, crate::list::AttributeValueDyn(value));
}
}
Some(list)
}
/// A run read at its element type. Record fields hold each marker's value
/// verbatim, so lane reads are plain typed reads at a hoisted offset.
pub struct RunView<'a, T> {
@@ -621,26 +522,15 @@ impl<'e> Group<'e> {
}
/// Compares one record region of `layout` by content. Regions without glue
/// compare as bytes, which is the content for unparked values. Only written
/// spans are read: the element's own bytes and each field's own bytes, never
/// the element-to-field seam or the lane's stride tail, which no writer
/// touches. The element always carries glue (`assert_element_glue`) and
/// `FieldWrite::of` always installs field glue, so a padded value's own
/// padding never reaches the byte fallback either.
///
/// # Safety
/// `a` and `b` must both be live records of `layout`.
/// compare as bytes, which is the content for unparked values.
unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool {
// SAFETY: the caller's contract; each call reads a written span of the layout.
let bytes_eq = |offset: usize, size: usize| unsafe { std::slice::from_raw_parts(a.add(offset), size) == std::slice::from_raw_parts(b.add(offset), size) };
let element = match layout.element.content_eq {
// SAFETY: the caller's contract; the glue is the element's own.
Some(eq) => unsafe { eq(a, b) },
None => bytes_eq(0, layout.element.size),
};
element
&& layout.fields.iter().all(|field| match field.content_eq {
// SAFETY: as above, at this descriptor's own offset.
Some(eq) => unsafe { eq(a.add(field.offset), b.add(field.offset)) },
None => bytes_eq(field.offset, field.size),
})
@@ -648,21 +538,14 @@ unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool
/// Hashes one record region of `layout` by content, with the byte fallback
/// of [`record_content_eq`].
///
/// # Safety
/// `ptr` must be a live record of `layout`.
unsafe fn record_content_hash(layout: &Layout, ptr: *const u8, state: &mut dyn core::hash::Hasher) {
match layout.element.content_hash {
// SAFETY: the caller's contract; the glue is the element's own.
Some(hash) => unsafe { hash(ptr, state) },
// SAFETY: as above; the element's own bytes are written.
None => state.write(unsafe { std::slice::from_raw_parts(ptr, layout.element.size) }),
}
for field in &layout.fields {
match field.content_hash {
// SAFETY: as above, at this descriptor's own offset.
Some(hash) => unsafe { hash(ptr.add(field.offset), state) },
// SAFETY: as above; the field's own bytes are written.
None => state.write(unsafe { std::slice::from_raw_parts(ptr.add(field.offset), field.size) }),
}
}
@@ -724,6 +607,7 @@ impl graphene_hash::CacheHash for Group<'_> {
mod tests {
use super::*;
use crate::record::access::{read_element, write_field};
use crate::record::layout::element_write;
use crate::record::test_support::f64_field;
#[test]
@@ -734,7 +618,7 @@ mod tests {
let arena = crate::arena::Arena::new(4096).unwrap();
let transform = DAffine2::from_translation((5., 6.).into());
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
for lane in 0..2 {
let lane = builder.push(lane as f64).unwrap();
builder.attr::<Transform>(lane, transform);
@@ -764,7 +648,7 @@ mod tests {
use crate::lane::LaneSource;
let arena = crate::arena::Arena::new(1024).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[], 1).unwrap();
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[], 1).unwrap();
builder.push(0f64).unwrap();
let item = builder.finish();
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
@@ -776,7 +660,7 @@ mod tests {
fn an_interior_run_already_persistent_is_shared() {
let transient = crate::arena::Arena::new(4096).unwrap();
let persistent = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
let stride = layout.lane_stride();
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
@@ -798,7 +682,7 @@ mod tests {
#[test]
fn adopting_within_one_region_shares_the_run() {
let arena = crate::arena::Arena::new(4096).unwrap();
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
let stride = layout.lane_stride();
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
@@ -818,7 +702,7 @@ mod tests {
#[test]
fn adopted_lanes_round_trip_through_the_group_item() {
let arena = crate::arena::Arena::new(1024).unwrap();
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
let stride = layout.lane_stride();
let offset = layout.offset_of("opacity", 0).unwrap();
@@ -846,34 +730,6 @@ mod tests {
}
}
#[test]
fn a_cross_arena_adopt_re_parks_what_the_lanes_name() {
use crate::lane::LaneSource;
let mut source = crate::arena::Arena::new(1 << 16).unwrap();
let target = crate::arena::Arena::new(1 << 16).unwrap();
let adopted = {
let mut builder = RunBuilder::new(&source, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)], 2).unwrap();
for lane in 0..2 {
let lane = builder.push(format!("element {lane}")).unwrap();
let (name, _) = source.alloc(format!("field {lane}")).unwrap();
builder.attr::<crate::attribute::Name>(lane, name.as_str());
}
let item = builder.finish();
GroupItem::adopt(item.lanes(), &target).unwrap()
};
// The adopted run must own what it names: the source's flush frees every
// payload the lanes were built over.
source.reset();
let run = RunView::<String>::new(&adopted).expect("the run holds string elements");
for lane in 0..2 {
assert_eq!(run.element(lane).map(String::as_str), Some(format!("element {lane}").as_str()), "lane {lane}");
assert_eq!(run.attr::<crate::attribute::Name>(lane), format!("field {lane}"), "lane {lane}");
}
}
#[test]
fn group_content_equality_and_hashing_read_through_the_park() {
use graphene_hash::CacheHash;
@@ -912,21 +768,20 @@ mod tests {
fn owned_items_replay_re_parked_payloads_after_the_source_dies() {
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
let stride = layout.lane_stride();
// Word storage: the parked element and the `&str` field are 8-aligned.
let mut bytes = vec![0u64; (stride * 2).div_ceil(8)];
let mut bytes = vec![0u8; stride * 2];
let owned = {
let arena = crate::arena::Arena::new(1024).unwrap();
for lane in 0..2 {
let base = unsafe { bytes.as_mut_ptr().cast::<u8>().add(lane * stride) };
let base = unsafe { bytes.as_mut_ptr().add(lane * stride) };
unsafe { write_element(base, format!("element {lane}"), &arena) }.unwrap();
let (name, _) = arena.alloc(format!("field {lane}")).unwrap();
unsafe { write_field::<&str>(base, layout.offset_of("name", 0).unwrap(), name.as_str()) };
}
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 2, &layout)) };
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 2, &layout)) };
item.copy_out()
};
bytes.fill(u64::MAX);
bytes.fill(u8::MAX);
let arena = crate::arena::Arena::new(1024).unwrap();
let replayed = owned.replay(&arena).unwrap();
@@ -988,26 +843,6 @@ mod tests {
assert_eq!(run.attr::<crate::attribute::EditorLayerPath>(0), &[crate::uuid::NodeId(3)]);
}
#[test]
fn a_census_row_pointed_at_another_field_writes_nothing() {
use crate::attribute::{Attribute, Opacity, Transform};
use crate::lane::LaneSource;
let arena = crate::arena::Arena::new(1 << 16).unwrap();
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Opacity>(0)], 1).unwrap();
let lane = builder.push(0f64).unwrap();
// The transform writer renamed onto the 8-byte opacity field: a
// 48-byte write past the lane if the name were the only check.
let mut forged = crate::attribute::info(Transform::NAME).unwrap();
forged.name = Opacity::NAME;
builder.attr_stored(lane, &forged, &glam::DAffine2::from_translation((5., 6.).into())).unwrap();
let item = builder.finish();
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
assert_eq!(run.attr::<Opacity>(0), 1., "the mistyped row leaves the census default");
}
#[test]
fn a_wrong_typed_or_undeclared_column_leaves_the_default() {
use crate::lane::LaneSource;
@@ -1027,11 +862,10 @@ mod tests {
#[should_panic(expected = "an owned item replays")]
fn an_owned_item_refuses_reads() {
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[]);
// Word storage: the parked element slot holds an 8-aligned reference.
let mut bytes = vec![0u64; layout.lane_stride().div_ceil(8)];
let mut bytes = vec![0u8; layout.lane_stride()];
let arena = crate::arena::Arena::new(1024).unwrap();
unsafe { write_element(bytes.as_mut_ptr().cast(), String::from("parked"), &arena) }.unwrap();
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 1, &layout)) };
unsafe { write_element(bytes.as_mut_ptr(), String::from("parked"), &arena) }.unwrap();
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 1, &layout)) };
item.copy_out().lanes();
}
}
@@ -20,13 +20,8 @@ pub struct SlotRun<'a> {
}
impl<'a> SlotRun<'a> {
/// `None` where the scratch cannot hold `len` lanes. The products are
/// checked: the stride is a multiple of 8, so a wrapped one would pass the
/// capacity test vacuously.
pub(in crate::record) fn new(scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
let need = len.checked_mul(layout.lane_stride())?;
let capacity = scratch.len().checked_mul(8)?;
(capacity >= need).then_some(SlotRun { scratch, layout, len, filled: 0 })
(scratch.len() * 8 >= len * layout.lane_stride()).then_some(SlotRun { scratch, layout, len, filled: 0 })
}
pub fn layout(&self) -> &'a Layout {
@@ -46,24 +41,20 @@ impl<'a> SlotRun<'a> {
inline: RecordValue::zeroed(),
frame: (self.layout.frame_bytes() != 0).then_some(frame),
free: frames.reborrow(),
filled_fields: false,
}
}
/// Records lane `lane` as served; the proof came from that lane's slot. An
/// inline record rides the value's own storage, so it takes the one copy
/// the run makes. Lanes serve in ascending order with no gaps, so the
/// filled count is an initialized prefix rather than a high-water mark.
/// the run makes.
pub fn served(&mut self, lane: usize, proof: &Served<'_>) {
assert!(lane < self.len, "lane {lane} out of bounds for a run of {}", self.len);
assert_eq!(lane, self.filled, "lane {lane} serves out of order after {} filled lanes", self.filled);
if self.layout.size == 0 {
let stride = self.layout.lane_stride();
// SAFETY: in-bounds by the assert against the capacity check `new`
// made, and the lane takes the whole inline record.
// SAFETY: in-bounds by the capacity check `new` made, and the lane
// takes the whole inline record.
unsafe { std::ptr::copy_nonoverlapping(self.layout.rec(proof.record()).ptr(), self.scratch.as_mut_ptr().cast::<u8>().add(lane * stride), stride) };
}
self.filled = lane + 1;
self.filled = self.filled.max(lane + 1);
}
/// The served lanes as the caller's exclusive batch.
@@ -83,9 +74,6 @@ pub struct FrameClaim<'e, 'l> {
pub(in crate::record) inline: RecordValue<'static>,
pub(in crate::record) frame: Option<*mut u8>,
pub(in crate::record) free: Frames<'e>,
/// Set by the writes that fill the declared fields, so the safe closers can
/// refuse a field-bearing frame that was never filled.
pub(in crate::record) filled_fields: bool,
}
impl<'e, 'l> FrameClaim<'e, 'l> {
@@ -119,27 +107,17 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
///
/// # Safety
/// `src` must be a live record of the plan's source layout, and the plan
/// must be the wiring-resolved plan of this frame's layout. `src` must not
/// overlap this frame; an input's frame is split off beyond the claim, so
/// serving the source through [`Self::frames`] establishes it.
/// must be the wiring-resolved plan of this frame's layout.
pub unsafe fn carry(&mut self, src: Rec<'_>, plan: &[(usize, usize, usize)]) {
unsafe { apply_plan(src, self.dst(), plan) };
self.filled_fields = true;
}
/// Writes a field at its wiring-resolved offset.
///
/// # Safety
/// `offset` must be this layout's resolved offset for a field of `T`. A
/// generated write offset defaults to 0 until `set_layout` installs it, so
/// the debug assertion catches a serve that ran before the install.
/// `offset` must be this layout's resolved offset for a field of `T`.
pub unsafe fn attr_at<T>(&mut self, offset: usize, value: T) {
debug_assert!(
self.layout.fields.iter().any(|field| field.offset == offset),
"attribute write at an offset this layout does not carry; the layout must install before serving"
);
unsafe { write_field(self.dst(), offset, value) };
self.filled_fields = true;
}
/// Writes the element; `None` reports arena exhaustion for a parked
@@ -154,17 +132,9 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// Lifts a kernel's poll into the frame and closes it: the element
/// writes on value polls, every poll keeps the frame claimed, and arena
/// exhaustion of a parked element reports as an error poll. Panics where
/// the element does not match the wired layout, or where a field-bearing
/// layout closes on a frame no carry or field write ever filled, since the
/// [`Served`] proof certifies the whole record and the fields would be the
/// prior frame's bytes.
/// the element does not match the wired layout.
pub fn lift<T: Send + Sync + dyn_any::StaticTypeSized>(mut self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
self.check_element::<T>();
assert!(
self.layout.fields.is_empty() || self.filled_fields,
"a layout with {} fields must carry or write them before lifting",
self.layout.fields.len()
);
let frame_bytes = self.layout.frame_bytes();
let dst = self.dst();
// SAFETY: the frame is this layout's fresh claim, the element check
@@ -180,7 +150,6 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// references outlive the serving evaluation.
pub unsafe fn fill_copy(&mut self, src: *const u8) {
unsafe { std::ptr::copy_nonoverlapping(src, self.dst(), self.layout.size) };
self.filled_fields = true;
}
/// The served record. The frame stays claimed for the consumer; the drop
@@ -227,12 +196,10 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
/// Translates a source record into the frame through a wiring-resolved plan.
///
/// # Safety
/// `src` must be a live record of `plan`'s source layout, `plan` must
/// translate into this frame's layout, and `src` must not overlap this
/// frame, as [`Self::carry`] requires.
/// `src` must be a live record of `plan`'s source layout, and `plan` must
/// translate into this frame's layout.
pub unsafe fn translate(&mut self, src: Rec<'_>, plan: &SourcePlan) {
unsafe { plan.translate(src, self.dst()) };
self.filled_fields = true;
}
}
@@ -345,35 +312,6 @@ mod tests {
frames.claim(&layout).element(1u32, &arena);
}
#[test]
fn a_run_refuses_a_lane_count_whose_stride_product_overflows() {
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 4];
let mut frame_arena = FrameArena::new();
frame_arena.reserve(64);
let frames = frame_arena.frames();
let wrapping = usize::MAX / layout.lane_stride() + 1;
assert!(frames.run(&mut scratch, wrapping, &layout).is_none(), "a wrapped capacity product must not pass the check");
}
#[test]
#[should_panic(expected = "serves out of order")]
fn a_run_refuses_a_gapped_serve() {
let arena = crate::arena::Arena::new(1024).unwrap();
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 8];
let mut frame_arena = FrameArena::new();
frame_arena.reserve(1 << 10);
let frames = frame_arena.frames();
let mut run = frames.run(&mut scratch, 3, &layout).unwrap();
let lane_frames = frames.scope();
let slot = run.slot(2, &lane_frames);
let GPoll::Final(proof) = slot.lift_served(GPoll::Final(1.0f64), &arena) else {
panic!("expected a final record");
};
run.served(2, &proof);
}
#[test]
fn a_claim_shortens_onto_a_derived_lifetime() {
fn shorten<'long: 'short, 'short, 'l>(claim: FrameClaim<'long, 'l>) -> FrameClaim<'short, 'l> {
@@ -127,22 +127,12 @@ impl<N: ?Sized> SharedSource<N> {
/// Re-derives the cached pointer from the owned payload. An exclusive
/// re-borrow of the payload invalidates the pointer taken before it, so
/// every mutation through `own` ends here, an unwinding one included.
/// every mutation through `own` ends here.
pub fn rederive(&mut self) {
self.ptr = std::ptr::NonNull::from(&*self.own);
}
}
/// Re-derives on the way out of an exclusive re-borrow, so a mutation that
/// panics cannot leave the cached pointer retired for a caller that catches.
struct Rederive<'a, N: ?Sized>(&'a mut SharedSource<N>);
impl<N: ?Sized> Drop for Rederive<'_, N> {
fn drop(&mut self) {
self.0.rederive();
}
}
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the source is exactly as
// thread safe as the payload it shares.
unsafe impl<N: ?Sized + Send + Sync> Send for SharedSource<N> {}
@@ -217,9 +207,6 @@ unsafe impl Send for SourceHandle {}
#[cfg(target_family = "wasm")]
unsafe impl Sync for SourceHandle {}
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
compile_error!("SourceHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the stored node bounded instead");
impl SourceHandle {
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
Self::new_erased(node, record_source_type::<T>())
@@ -237,11 +224,9 @@ impl SourceHandle {
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedSource<N>>().expect("layout hook matches the stored edge type")),
set_layout: |edge, layout| {
let shared = edge.downcast_mut::<SharedSource<N>>().expect("set_layout hook matches the stored edge type");
// The re-borrow below retires the cached pointer, so the rederive
// is a guard: a panicking `set_layout` must not leave it stale.
let guard = Rederive(shared);
let node = std::sync::Arc::get_mut(&mut guard.0.own).expect("layout is installed before the node is shared");
let node = std::sync::Arc::get_mut(&mut shared.own).expect("layout is installed before the node is shared");
Node::<ContextImpl>::set_layout(node, layout);
shared.rederive();
},
ty,
}
@@ -30,9 +30,6 @@ unsafe impl Send for RuntimeHandle {}
#[cfg(target_family = "wasm")]
unsafe impl Sync for RuntimeHandle {}
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
compile_error!("RuntimeHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the payload bounded instead");
impl std::fmt::Debug for RuntimeHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
@@ -105,9 +102,6 @@ unsafe impl<S> Send for GraphRuntime<S> {}
#[cfg(target_family = "wasm")]
unsafe impl<S> Sync for GraphRuntime<S> {}
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
compile_error!("GraphRuntime's wasm Send/Sync are unbounded in S and rest on a single-threaded build; a +atomics target needs S bounded instead");
impl<S> GraphRuntime<S> {
pub fn new(spawner: S) -> Self {
Self {
@@ -278,9 +272,6 @@ mod tests {
plan: Vec::new(),
layout: layout.clone(),
lane_invariant: u32::MAX,
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
});
RecordExtract::new(graph, &layout)
}
@@ -50,7 +50,6 @@ impl<'e> Artboard<'e> {
/// # Safety
/// `ptr` must point at a live parked `Artboard` element field.
unsafe fn deep_clone_artboard(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
// SAFETY: the caller's contract.
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(ptr)) };
let mut content = artboard.0.clone();
for element in content.iter_element_values_mut() {
@@ -73,7 +72,6 @@ unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *
*element = crate::graphic::map_groups_to_resident(element, arena)?;
}
crate::graphic::map_attribute_groups_to_resident(&mut content, arena)?;
// SAFETY: the caller's contract on `dst`; the replayed content is an `Artboard`.
unsafe { core_types::record::write_element(dst, Artboard(content), arena) }
}
@@ -85,14 +83,12 @@ unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *
/// `src` must point at a live parked `Artboard` element field, and `dst` at
/// the element field the promoted reference is written to.
unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
// SAFETY: the caller's contract on `src`.
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(src)) };
if !crate::graphic::list_contains_groups(&artboard.0) {
// SAFETY: a parked element slot holds one reference at offset 0, and
// content no group is reachable from, elements and item attribute values
// alike, owns all of itself.
let header = unsafe { src.cast::<*const u8>().read() };
// SAFETY: as above; the group-free check establishes the own-all-content half.
if let Some(moved) = unsafe { promotion.move_park::<Artboard>(header, 0) } {
// SAFETY: as above, into the promoted image's own element slot.
unsafe { dst.cast::<*const Artboard>().write(moved) };
@@ -105,7 +101,6 @@ unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types:
content.push(core_types::list::Item::from_parts(crate::graphic::map_groups_to_persistent(&element, promotion)?, attributes));
}
crate::graphic::map_attribute_groups_to_persistent(&mut content, promotion)?;
// SAFETY: the caller's contract on `dst`; the promoted content is an `Artboard`.
unsafe { core_types::record::write_element(dst, Artboard(content), promotion.persistent()) }
}
@@ -54,7 +54,6 @@ pub fn map_groups_to_resident<'a>(graphic: &Graphic<'a>, arena: &'a core_types::
/// # Safety
/// `ptr` must point at a live parked `Graphic` element field.
unsafe fn deep_clone_graphic(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
// SAFETY: the caller's contract.
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(ptr)) };
Box::new(map_groups_to_owned(graphic))
}
@@ -69,7 +68,6 @@ unsafe fn deep_repark_graphic(value: &(dyn std::any::Any + Send + Sync), dst: *m
let graphic = value.downcast_ref::<Graphic>().expect("an element replays at its own type");
let resident = map_groups_to_resident(graphic, arena)?;
let retained = graphic_retained_heap(&resident);
// SAFETY: the caller's contract; the resident form is a `Graphic` for `dst`.
unsafe { core_types::record::write_element_sized(dst, resident, arena, retained) }
}
@@ -167,14 +165,12 @@ pub(crate) fn map_attribute_groups_to_persistent(list: &mut List<Graphic<'_>>, p
/// `src` must point at a live parked `Graphic` element field, and `dst` at the
/// element field the promoted reference is written to.
unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
// SAFETY: the caller's contract on `src`.
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(src)) };
if !graphic_contains_groups(graphic) {
// SAFETY: a parked element slot holds one reference at offset 0, and a
// graphic no group is reachable from, elements and item attribute values
// alike, owns all of its content.
let header = unsafe { src.cast::<*const u8>().read() };
// SAFETY: as above; the group-free check establishes the own-all-content half.
if let Some(moved) = unsafe { promotion.move_park::<Graphic<'static>>(header, graphic_retained_heap(graphic)) } {
// SAFETY: as above, into the promoted image's own element slot.
unsafe { dst.cast::<*const Graphic<'static>>().write(moved) };
@@ -183,7 +179,6 @@ unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::
}
let promoted = map_groups_to_persistent(graphic, promotion)?;
let retained = graphic_retained_heap(&promoted);
// SAFETY: the caller's contract on `dst`; the promoted form is a `Graphic`.
unsafe { core_types::record::write_element_sized(dst, promoted, promotion.persistent(), retained) }
}
@@ -275,8 +270,6 @@ fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, are
*element = map_groups_to_resident(element, arena)?;
}
map_attribute_groups_to_resident(&mut list, arena)?;
// SAFETY: every group the clone carried, in an element or an item attribute
// value, now names `arena`, whose borrow the replayed field is read at.
let list = unsafe { core_types::record::erase_static(list) };
Some(Some(Box::new(Some(list))))
}
@@ -500,7 +493,12 @@ mod run_tests {
}
/// The promoted paint of one lane, at the layout the promote published.
fn promoted_paint<'p>(span: &core_types::record::MaterializedSpan, layout: &core_types::record::Layout, lane: usize, persistent: &'p core_types::arena::Arena) -> &'p List<Graphic<'p>> {
fn promoted_paint<'p>(
span: &core_types::record::MaterializedSpan,
layout: &core_types::record::Layout,
lane: usize,
persistent: &'p core_types::arena::Arena,
) -> &'p List<Graphic<'p>> {
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
let batch = span.batch(persistent, layout).expect("the span resolves in its own region");
// SAFETY: the promote wrote a record of `layout` into every lane.
@@ -517,9 +515,7 @@ mod run_tests {
// list the evaluation parked.
let published = native_group_paint(&inner_vector, &persistent);
let interior = {
let Some(Graphic::Group(group)) = published.element(0) else {
panic!("the paint carries a native group")
};
let Some(Graphic::Group(group)) = published.element(0) else { panic!("the paint carries a native group") };
group.content.lanes().get(0).rec().ptr()
};
// SAFETY: the list serves only while `persistent` is live, and the
@@ -530,9 +526,7 @@ mod run_tests {
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
let Some(Graphic::Group(group)) = served.element(0) else {
panic!("the promote keeps the group form")
};
let Some(Graphic::Group(group)) = served.element(0) else { panic!("the promote keeps the group form") };
assert_eq!(group.content.lanes().get(0).rec().ptr(), interior, "a persistent interior is shared pointer for pointer");
assert!(
persistent.occupancy() - occupied <= layout.frame_bytes() + size_of::<List<Graphic>>() + align_of::<List<Graphic>>(),
@@ -554,14 +548,8 @@ mod run_tests {
let (layout, span, _frames) = promote_paint_field(Some(paint), 2, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
let Some(Graphic::Vector(vector)) = served.element(0) else {
panic!("the promote keeps the vector")
};
assert_eq!(
vector.point_domain.positions().as_ptr(),
heap,
"the promote moved the header, so the served paint names the pre-promote heap"
);
let Some(Graphic::Vector(vector)) = served.element(0) else { panic!("the promote keeps the vector") };
assert_eq!(vector.point_domain.positions().as_ptr(), heap, "the promote moved the header, so the served paint names the pre-promote heap");
assert!(std::ptr::eq(served, promoted_paint(&span, &layout, 1, &persistent)), "a paint two lanes share moves once");
transient.reset();
@@ -593,11 +581,7 @@ mod run_tests {
let served = promoted_paint(&span, &layout, 0, &persistent);
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the promoted list");
let held = held.as_ref().expect("the stroke is present");
assert_eq!(
map_groups_to_legacy(held.element(0).unwrap()),
expected,
"the attribute-held group serves from persistent storage after the reset"
);
assert_eq!(map_groups_to_legacy(held.element(0).unwrap()), expected, "the attribute-held group serves from persistent storage after the reset");
}
#[test]
@@ -619,14 +603,8 @@ mod run_tests {
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
let served = promoted_paint(&span, &layout, 0, &persistent);
let Some(Graphic::Vector(vector)) = served.element(0) else {
panic!("the promote keeps the vector")
};
assert_eq!(
vector.point_domain.positions().as_ptr(),
heap,
"the promote moved the header, so the served paint names the pre-promote heap"
);
let Some(Graphic::Vector(vector)) = served.element(0) else { panic!("the promote keeps the vector") };
assert_eq!(vector.point_domain.positions().as_ptr(), heap, "the promote moved the header, so the served paint names the pre-promote heap");
transient.reset();
let served = promoted_paint(&span, &layout, 0, &persistent);
@@ -4,7 +4,7 @@ use super::walk::push_lane_paint_into_interiors;
use super::{Graphic, detable_items};
use crate::markers::{ATTR_FILL, ATTR_STROKE};
use core_types::Color;
use core_types::list::{Item, List};
use core_types::list::{AttributeValueDyn, Item, List};
use raster_types::{CPU, GPU, Raster};
use vector_types::{GradientStops, Vector};
@@ -12,7 +12,19 @@ use vector_types::{GradientStops, Vector};
/// through its erased read. Content keeps its native form; the legacy
/// conversions layer their mapping on top.
pub fn run_to_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
core_types::record::run_to_owned_list(item)
let lanes = item.typed_lanes::<T>()?;
let mut list = List::new();
for lane in 0..lanes.len() {
list.push(Item::new_from_element(lanes.element_ref(lane).clone()));
}
for field in &item.layout().fields {
for lane in 0..lanes.len() {
// SAFETY: the offset comes from the item's own layout.
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
list.set_attribute_value_dyn(field.name, lane, AttributeValueDyn(value));
}
}
Some(list)
}
/// Converts the group content of the list's paint attribute values to legacy
@@ -15,13 +15,6 @@ core_types::attribute! {
pub EditorClickTarget("editor:click_target"): Option<&crate::Vector>;
}
// The value types a name-generic attribute can name here, so a compile-time
// named write or read reaches this crate's enums like any other plain value.
core_types::named_value! {
for crate::gradient::GradientSpreadMethod;
for crate::gradient::GradientType;
}
pub const ATTR_SPREAD_METHOD: &str = SpreadMethod::NAME;
pub const ATTR_GRADIENT_TYPE: &str = GradientType::NAME;
pub const ATTR_EDITOR_CLICK_TARGET: &str = EditorClickTarget::NAME;
+44 -181
View File
@@ -240,18 +240,6 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let slot = format_ident!("__read_{index}");
quote!(pub(super) #slot: Option<usize>)
}));
// A name-generic read carries the folded name's own default beside its
// offset, since its marker names the value type but not the name.
state.extend(
field_reads(&struct_regular_fields)
.iter()
.enumerate()
.filter(|(_, (_, read))| crate::parsing::named_marker(&read.marker).is_some())
.map(|(index, _)| {
let slot = format_ident!("__read_default_{index}");
quote!(pub(super) #slot: Option<::std::boxed::Box<[u8]>>)
}),
);
state.extend((0..node.output.shape.attrs.len()).map(|index| {
let slot = format_ident!("__write_{index}");
quote!(pub(super) #slot: usize)
@@ -808,9 +796,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
// its generic stays a struct parameter.
let record_token = match (kind, &node.output.shape.element) {
(crate::codegen::ir::NodeKind::RecordIo, crate::codegen::ir::Element::Generic(ident)) if !gather_carrier => Some(ident.clone()),
// An opaque reading input's element is byte-carried the same way, even
// though the output replaces it rather than carrying it through.
_ => crate::codegen::classify::opaque_reading_carrier(parsed),
_ => None,
};
// 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();
@@ -994,11 +980,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let output_type = &parsed.output_type;
let raw_lazy = matches!(*model, Dialect::Poll);
let injected_name = |ident: &Ident| async_source && (ident == "_runtime" || ident == "_source");
// A name input declares where a placeholder's name is wired and nothing
// more: the name is spent resolving the layout when the graph compiles, so
// it reaches neither the kernel's parameters nor its call. The wire input
// stays, since the fold reads the constant off it.
let kernel_omits = |field: &ParsedField| injected_name(&field.pat_ident.ident) || matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { name_source: Some(_), .. }));
let where_predicates: Vec<TokenStream2> = parsed.where_clause.iter().flat_map(|clause| clause.predicates.iter()).map(|predicate| quote!(#predicate)).collect();
let NodeFields {
@@ -1107,7 +1088,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
});
quote!((#value_param #(, #read_pats)*): (#value_ty #(, #read_tys)*))
};
let kernel_params = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).map(|(index, field)| {
let kernel_params = regular_fields.iter().enumerate().filter(|(_, field)| !injected_name(&field.pat_ident.ident)).map(|(index, field)| {
let pat = &field.pat_ident;
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) if ir::materialized_levels(&node, index) > 0 => {
@@ -1258,15 +1239,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let read_binding = |slot: usize, read: &AttributeRead, rec: TokenStream2| {
let pat = &read.pat_ident;
let marker = &read.marker;
let default_slot = format_ident!("__read_default_{slot}");
let slot = format_ident!("__read_{slot}");
// A name-generic marker carries the value type but not the name, so it
// cannot know the name's own default; the compiler supplies it.
if crate::parsing::named_marker(marker).is_some() {
return quote! {
let #pat = unsafe { #core_types::record::read_at_defaulting::<#marker>(#rec, self.#slot, self.#default_slot.as_deref()) };
};
}
quote! {
let #pat = unsafe { #core_types::record::read_at::<#marker>(#rec, self.#slot) };
}
@@ -1292,9 +1265,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
// A lazy input claims beyond every input frame this node holds, and its
// cursor is shared, so the inputs a kernel drives claim past each other.
// The snapshot copies the cursor where it stands, so every frame the node
// still reads after the kernel runs (the carrier's included) must have been
// claimed before it.
let lazy_frames_entry = quote! {
let __lazy_frames = __frame.frames().reborrow();
};
@@ -1544,7 +1514,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
(!tokens.is_empty()).then_some(tokens)
};
let call_args = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).map(|(index, field)| {
let call_args = regular_fields.iter().enumerate().filter(|(_, field)| !injected_name(&field.pat_ident.ident)).map(|(index, field)| {
let name = &field.pat_ident.ident;
match &field.ty {
// A lend param binds an owned input; the kernel borrows the
@@ -1744,17 +1714,12 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let fn_where = &parsed.where_clause;
let body = if level_delta > 0 { rewrite_emit(&parsed.body) } else { parsed.body.clone() };
let vis = &parsed.vis;
// The input index rides along: an async kernel's param type depends on the
// field's value binding, which is indexed off the node's inputs.
let kernel_indexed: Vec<(usize, &&ParsedField)> = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).collect();
let kernel_fields: Vec<&&ParsedField> = kernel_indexed.iter().map(|(_, field)| *field).collect();
let kernel_fields: Vec<&&ParsedField> = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).collect();
// 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. An async source's value
// outlives the evaluation, so its writes are `'static` instead.
let attr_injected = record_io
.then(|| inject_attr_lifetimes(&parsed.output_type, if async_source { "'static" } else { "'__attr" }))
.flatten();
let attr_injected = record_io.then(|| inject_attr_lifetimes(&parsed.output_type, if async_source { "'static" } else { "'__attr" })).flatten();
let attr_lifetime = (attr_injected.is_some() && !async_source).then(|| quote!('__attr,));
let lane_injected = gather_carrier
.then(|| crate::codegen::classify::inject_lane_lifetime(attr_injected.as_ref().unwrap_or(&parsed.output_type)))
@@ -1789,18 +1754,12 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
};
quote!(#pat: #ty)
});
let value_kernel_params = kernel_indexed.iter().map(|(index, field)| {
let value_kernel_params = kernel_fields.iter().map(|field| {
let pat = &field.pat_ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
unreachable!("async source fields are eager values");
};
// A materialized level is a borrowed arena view, which cannot cross
// into a `'static` future; the prologue snapshots it to the owned
// legacy list and the kernel takes that instead.
match ir::materialized_levels(&node, *index) > 0 {
true => quote!(#pat: #core_types::list::List<#ty>),
false => quote!(#pat: #ty),
}
quote!(#pat: #ty)
});
let params = snapshot_param.chain(data_kernel_params).chain(value_kernel_params);
quote! {
@@ -1848,17 +1807,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
.map(|field| &field.pat_ident.ident)
.collect();
let tail_form = if async_fn {
Tail::SpawnAsyncFn
} else if future_kernel {
Tail::SpawnFuture
} else {
match ir::node_kind(&node) {
ir::NodeKind::RecordIo => Tail::Record,
ir::NodeKind::Flip => Tail::Flip,
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
}
};
// A carried tail claims the node's frame first, evaluates the carrier
// beyond it, and carries its fields; every exit closes the frame through
// `lift_poll_into`.
@@ -1902,37 +1850,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
}
})
});
// A record tail's carrier claim, the one the plan and the kernel read
// `__src_rec` out of.
let carrier_eval = (record_io && !skips_carrier && !lazy_carrier).then(|| {
let name = &regular_fields[0].pat_ident.ident;
quote! {
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
Ok(value) => value,
Err(interrupt) => return interrupt.into()
};
let __src_rec = self.__carrier.rec(&__src);
}
});
// The carrier's record stays claimed and readable through the kernel call, so
// its claim runs before the lazy snapshot and the lazy handles claim past it
// rather than over it. With no lazy input there is no snapshot and the claim
// stays in the tail.
let has_lazy = regular_fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_)));
let hoisted_carrier = match (has_lazy, tail_form) {
(false, _) => TokenStream2::new(),
(true, Tail::Record) => carrier_eval.clone().unwrap_or_default(),
(true, _) => carried_prelude.clone().unwrap_or_default(),
};
let carried_prelude = match has_lazy {
true => None,
false => carried_prelude,
};
let carrier_eval = match has_lazy {
true => None,
false => carrier_eval,
};
let lazy_entry = quote!(#hoisted_carrier #lazy_frames_entry);
// Async slots persist plain values across evaluations; the source lifts
// the slot value onto its record input at every merge point, into the
// carried frame when the node has a carrier.
@@ -2039,7 +1956,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
Some(tuple_arg(regular_fields[0], quote!(#core_types::record::ElToken)))
}
.into_iter();
let value_args = regular_fields.iter().skip(if skips_carrier { 0 } else { 1 }).filter(|field| !kernel_omits(field)).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 input; the kernel borrows the
@@ -2049,6 +1966,16 @@ 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 = (!skips_carrier && !lazy_carrier).then(|| {
let name = &regular_fields[0].pat_ident.ident;
quote! {
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
Ok(value) => value,
Err(interrupt) => return interrupt.into()
};
let __src_rec = self.__carrier.rec(&__src);
}
});
let carry = (!skips_carrier && !lazy_carrier).then(|| quote!(unsafe { __frame.carry(__src_rec, &self.__plan) };));
// A lazy carrier's source record is the token the kernel returned; its
// content frames sit above the claim and stay readable until its drop.
@@ -2170,37 +2097,28 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
__cell.merge(__frame.lift_served(#core_types::gpoll::GPoll::Final(__kernel_value), #core_types::context::ExtractArena::arena(__input)))
}
});
let tail_form = if async_fn {
Tail::SpawnAsyncFn
} else if future_kernel {
Tail::SpawnFuture
} else {
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(),
Tail::Record => record_tail.clone().expect("a record-io node has a record tail"),
Tail::Flip => flip_tail.clone().expect("a flip node has a flip tail"),
Tail::SpawnAsyncFn => {
// The level is still live here (the prologue materialized it into the
// evaluation's arena), so the owned copy is taken before the future
// is built, as the owned-attr crossing does.
let kernel_value_args: Vec<TokenStream2> = kernel_indexed
.iter()
.map(|(index, field)| {
let name = &field.pat_ident.ident;
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
return quote!(#name.clone());
};
match ir::materialized_levels(&node, *index) > 0 {
true => quote! {
match #core_types::record::run_to_owned_list::<#ty>(&#name.as_group_item()) {
::core::option::Option::Some(__owned) => __owned,
::core::option::Option::None => return #core_types::gpoll::GPoll::Error(::std::boxed::Box::new(
#core_types::gpoll::GraphError::new(::std::concat!("the materialized level of ", ::std::stringify!(#name), " holds another element type")),
)),
}
},
false => quote!(#name.clone()),
}
})
.collect();
let kernel_value_names: Vec<&Ident> = kernel_fields.iter().map(|field| &field.pat_ident.ident).collect();
let snapshot_binding = snapshot_ctx.then(|| quote!(let __snapshot = #core_types::context::CtxSnapshot::capture(__input);)).into_iter();
let snapshot_arg = snapshot_ctx.then(|| quote!(__snapshot)).into_iter();
let future_args = snapshot_arg.chain(data_names.iter().map(|name| quote!(self.#name.clone()))).chain(kernel_value_args);
let future_args = snapshot_arg
.chain(data_names.iter().map(|name| quote!(self.#name.clone())))
.chain(kernel_value_names.iter().map(|name| quote!(#name.clone())));
let completion = future_completion(&parsed.output_type);
let tail = spawn_tail(completion, inflight.clone());
let prelude = carried_prelude.iter();
@@ -2307,7 +2225,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let clamp = clamp_tokens(field);
(field, quote!(#body #clamp))
}),
&lazy_entry,
&lazy_frames_entry,
);
// The rebind path with nothing hoisted: every non-carrier input binds
// fresh per lane, so an index-dependent input reaches its own lane.
@@ -2324,7 +2242,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let clamp = clamp_tokens(field);
(field, quote!(#body #clamp))
}),
&lazy_entry,
&lazy_frames_entry,
);
// A hoisted value is moved into every lane's kernel call, so each
// lane consumes a clone; view and borrow binds copy freely.
@@ -2546,50 +2464,15 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
self.__layout = __resolved.layout;
})
} else if record_io {
// A name-generic write has no marker name to look up: the compiler
// folded its name out of the graph, so the offset resolves through the
// name the resolved layout carries.
let mut folded = 0usize;
let write_installs: Vec<TokenStream2> = write_markers
.iter()
.enumerate()
.map(|(index, marker)| {
let slot = format_ident!("__write_{index}");
let name = match crate::parsing::named_marker(marker).is_some() {
true => {
let position = folded;
folded += 1;
quote!(__resolved.named_writes[#position])
}
false => quote!(<#marker as #core_types::attribute::Attribute>::NAME),
};
quote! {
self.#slot = __resolved.layout.offset_of(#name, 0).expect("a written attribute is always part of the wired layout");
}
})
.collect();
// A name-generic read's offset was resolved against the input it reads,
// which only the compiler sees, so installing it is a copy.
let mut folded_read = 0usize;
let read_installs: Vec<TokenStream2> = flat_reads
.iter()
.enumerate()
.filter(|(_, (_, read))| crate::parsing::named_marker(&read.marker).is_some())
.map(|(slot, _)| {
let default_slot = format_ident!("__read_default_{slot}");
let slot = format_ident!("__read_{slot}");
let position = folded_read;
folded_read += 1;
quote! {
self.#slot = __resolved.named_reads[#position];
self.#default_slot = __resolved.named_read_defaults[#position].clone();
}
})
.collect();
let write_installs = write_markers.iter().enumerate().map(|(index, marker)| {
let slot = format_ident!("__write_{index}");
quote! {
self.#slot = __resolved.layout.offset_of(<#marker as #core_types::attribute::Attribute>::NAME, 0).expect("a written attribute is always part of the wired layout");
}
});
let plan = (!skips_carrier || gather_carrier).then(|| quote!(self.__plan = __resolved.plan;));
Some(quote! {
#(#write_installs)*
#(#read_installs)*
self.__frame_bytes = __resolved.frame_bytes;
self.__lane_invariant = __resolved.lane_invariant;
#plan
@@ -2629,7 +2512,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
}
None => quote!(#core_types::record::ElementSpec::Carried),
};
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types, &[]);
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types);
// A flipped shader node's struct and impl are std-gated; its layout meta must be too.
let cfg = crate::shader_nodes::modify_cfg(&parsed.attributes);
quote! {
@@ -2645,11 +2528,8 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let record_wiring = record_io.then(|| {
let layout_fn = format_ident!("{}_layout", fn_name);
// A name-generic write is absent here: this free layout fn derives a
// layout without a graph, and only the graph carries the name.
let write_descs: Vec<TokenStream2> = write_markers
.iter()
.filter(|marker| crate::parsing::named_marker(marker).is_none())
.map(|marker| quote!(#core_types::record::FieldWrite::of::<#marker>(0)))
.collect();
let remove_pairs: Vec<TokenStream2> = removes
@@ -2686,7 +2566,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
}
None => quote!(#core_types::record::ElementSpec::Carried),
};
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, core_types, &[]);
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 {
#layout_meta
@@ -2713,12 +2593,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
let read_inits = flat_reads.iter().enumerate().map(|(slot, (owner, read))| {
let marker = &read.marker;
let slot = format_ident!("__read_{slot}");
// A name-generic read has no marker name to look up here; the
// compiler resolved its offset against the input's own layout, so
// `set_layout` installs the number.
if crate::parsing::named_marker(marker).is_some() {
return quote!(let #slot = ::core::option::Option::None;);
}
let source = match !skips_carrier && *owner == 0 {
true => quote!(__carrier_layout),
false => format_ident!("__in_{owner}").to_token_stream(),
@@ -2737,16 +2611,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
});
let plan_default = (!skips_carrier || gather_carrier).then(|| quote!(__plan: ::std::vec::Vec::new(),)).into_iter();
let read_names = (0..flat_reads.len()).map(|index| format_ident!("__read_{index}")).map(|slot| quote!(#slot,));
// The folded name's default arrives with the layout, so the constructor
// leaves the slot empty and `set_layout` fills it.
let read_default_inits = flat_reads
.iter()
.enumerate()
.filter(|(_, (_, read))| crate::parsing::named_marker(&read.marker).is_some())
.map(|(index, _)| {
let slot = format_ident!("__read_default_{index}");
quote!(#slot: ::core::option::Option::None,)
});
let write_defaults = (0..write_markers.len()).map(|index| format_ident!("__write_{index}")).map(|slot| quote!(#slot: 0,));
let mat_cache_defaults = materialized_indices(&regular_fields, &node).into_iter().map(|index| {
let slot = format_ident!("__mat_cache_{index}");
@@ -2793,7 +2657,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
__frame_bytes: 0,
__lane_invariant: 0,
#(#read_names)*
#(#read_default_inits)*
#(#write_defaults)*
#(#mat_cache_defaults)*
#(#slot_default)*
@@ -2831,7 +2694,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
EvalStep::Bind(index, field) => {
let body = bind_body(*index, field, false, &quote!(__frame.frames()));
match matches!(field.ty, ParsedFieldType::Node(_)) && !std::mem::replace(&mut lazy_declared, true) {
true => quote!(#lazy_entry #body),
true => quote!(#lazy_frames_entry #body),
false => body,
}
}
@@ -266,36 +266,6 @@ pub(crate) fn contains_open_generic(parsed: &ParsedNodeFn, ty: &Type) -> bool {
.any(|param| matches!(param, GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() && type_contains_ident(ty, &type_param.ident)))
}
/// The element generic of a primary input that is read but never looked at:
/// declared as an unbounded passthrough, carrying attribute reads, and absent
/// from everywhere else in the signature. Such a node maps its declared
/// attributes onto a fresh element, so it accepts any upstream record wire and
/// registers one generic row rather than a row per element type.
///
/// Inferred rather than marked: a generic with nowhere to go and nothing to be
/// is opaque by construction, and the signature already says so.
pub(crate) fn opaque_reading_carrier(parsed: &ParsedNodeFn) -> Option<Ident> {
let carrier = parsed.fields.first()?;
if carrier.is_data_field || carrier.attribute_reads.is_empty() {
return None;
}
let ParsedFieldType::Regular(RegularParsedField { ty, lend: None, implementations, .. }) = &carrier.ty else {
return None;
};
if !implementations.is_empty() {
return None;
}
let token = unbounded_generic(parsed, ty)?;
// A token that reaches the output or another input is a passthrough
// element, which the node does carry; only one going nowhere is opaque.
let escapes = type_contains_ident(&parsed.output_type, &token)
|| parsed.fields.iter().skip(1).any(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => type_contains_ident(ty, &token),
ParsedFieldType::Node(NodeParsedField { input_type, output_type, .. }) => type_contains_ident(input_type, &token) || type_contains_ident(output_type, &token),
});
(!escapes).then_some(token)
}
pub(crate) fn unbounded_generic(parsed: &ParsedNodeFn, ty: &Type) -> Option<Ident> {
let ident = bare_ident(ty)?.clone();
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
@@ -392,13 +362,6 @@ pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
None => (value, Vec::new(), Vec::new()),
};
match &token {
// An opaque reading carrier never looks at its element, so it writes a
// fresh one instead of passing the token through.
Some(_) if opaque_reading_carrier(parsed).is_some() => {
if contains_open_generic(parsed, &element) {
return None;
}
}
Some(token) => {
if !matches!(bare_ident(&element), Some(ident) if ident == token) {
return None;
+18 -174
View File
@@ -6,25 +6,13 @@ use syn::spanned::Spanned;
use syn::{GenericParam, Ident, Type};
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
// A data-field generic is monomorphized by hand, so those nodes carry their own rows.
if !data_field_generic_idents.is_empty() {
return quote!();
}
let entries = match crate::codegen::ir::node_kind(&crate::codegen::ir::build(parsed)) {
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),
};
// Validation already rejects a generic input without implementations, so an
// empty row set here is an emitter gap, not an unregistered shape.
if entries.is_empty() && !parsed.attributes.skip_impl {
emit_error!(
parsed.fn_name.span(),
"no registry rows were generated for `{}`, so a document cannot resolve it",
parsed.fn_name;
help = "give every generic input an #[implementations(...)] list, or mark the node skip_impl if it registers its rows by hand"
);
}
entries
}
/// The registry rows of a flipped plain node: every input is a record input,
@@ -157,7 +145,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
quote!(&#layout,)
});
let element_spec = quote!(gcore::record::ElementSpec::Concrete({ use gcore::record::{ElementWritePickHashed as _, ElementWritePickPlain as _}; (&gcore::record::ElementWritePick::<#row_output>(::core::marker::PhantomData)).element_write() }));
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, &core_types, &assignments);
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, &core_types);
Some(quote! {
gcore::registry::RegistryEntry {
layout_meta: Some(#layout_meta),
@@ -273,34 +261,27 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
// (erased routing generics included) is row-invariant. The carried list
// mirrors the struct's carried generic parameters in declaration order.
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
let ranked = |index: usize| matches!(&regular_fields[index].ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0);
// A record-io node's plain secondary reaches the constructor concrete, so its generic monomorphizes the row like a ranked element does.
let record_secondary =
|index: usize| matches!(ir::node_kind(&node), ir::NodeKind::RecordIo) && index > 0 && !node.inputs[index].subject && matches!(&regular_fields[index].ty, ParsedFieldType::Regular(_));
let names_generic = |index: usize, generic: &Ident| match &regular_fields[index].ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => crate::codegen::type_contains_ident(ty, generic),
_ => false,
};
let solves_generic = |index: usize, generic: &Ident| match &regular_fields[index].ty {
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => !implementations.is_empty() && generic_extractable(ty, generic),
_ => false,
};
let carried_generic_idents: Vec<Ident> = parsed
let ranked_generic_idents: Vec<Ident> = parsed
.fn_generics
.iter()
.filter_map(|param| match param {
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(type_param.ident.clone()),
_ => None,
})
.filter(|ident| (0..regular_fields.len()).any(|index| (ranked(index) || record_secondary(index)) && names_generic(index, ident)))
.filter(|ident| {
regular_fields.iter().any(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => *list_levels > 0 && crate::codegen::type_contains_ident(ty, ident),
_ => false,
})
})
.collect();
// Ranked sources come first, so a generic a ranked input already carries keeps sourcing its rows from that input.
let carried_source = |generic: &Ident| {
(0..regular_fields.len())
.find(|&index| ranked(index) && solves_generic(index, generic))
.or_else(|| (0..regular_fields.len()).find(|&index| record_secondary(index) && solves_generic(index, generic)))
let ranked_source = |generic: &Ident| {
regular_fields.iter().position(|field| match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, implementations, .. }) => *list_levels > 0 && !implementations.is_empty() && generic_extractable(ty, generic),
_ => false,
})
};
let carried: Option<Vec<(Ident, usize)>> = carried_generic_idents.iter().map(|ident| carried_source(ident).map(|index| (ident.clone(), index))).collect();
let carried: Option<Vec<(Ident, usize)>> = ranked_generic_idents.iter().map(|ident| ranked_source(ident).map(|index| (ident.clone(), index))).collect();
let Some(carried) = carried else {
return quote!();
};
@@ -318,7 +299,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
let row_ty = ir::strip_ilist(&impls[row.min(impls.len() - 1)]).0;
let field_ty = match &regular_fields[*index].ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
_ => unreachable!("carried sources are regular fields"),
_ => unreachable!("ranked sources are regular fields"),
};
generic_assignment(&field_ty, &row_ty, generic).map(|ty| (generic.clone(), ty))
})
@@ -397,7 +378,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
.collect();
let carried_meta = || {
let meta = ir::layout_meta_tokens(&node, quote!(gcore::record::ElementSpec::Carried), &core_types, &[]);
let meta = ir::layout_meta_tokens(&node, quote!(gcore::record::ElementSpec::Carried), &core_types);
quote!(Some(#meta))
};
@@ -432,25 +413,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
ir::NodeKind::RecordIo => {
let carrier_arg = (node.inputs.first().is_some_and(|input| input.subject) && ir::materialized_levels(&node, 0) == 0).then(|| quote!(&__layout_0,));
let layout_meta_fn = format_ident!("{}_layout_meta", fn_name);
// A name-generic write names its value type through a wired
// generic, which only the row resolves, so such a node's
// meta is emitted per row instead of shared across them.
let named = node.output.shape.attrs.iter().any(|attr| crate::parsing::named_marker(&attr.marker).is_some());
let meta = match named {
false => quote!(Some(self::#layout_meta_fn())),
true => {
let element_spec = match &node.output.shape.element {
ir::Element::Concrete(element) => {
let ty = substitute_ident_types(element, assignments);
quote!(gcore::record::ElementSpec::Concrete({ use gcore::record::{ElementWritePickHashed as _, ElementWritePickPlain as _}; (&gcore::record::ElementWritePick::<#ty>(::core::marker::PhantomData)).element_write() }))
}
_ => quote!(gcore::record::ElementSpec::Carried),
};
let meta = ir::layout_meta_tokens(&node, element_spec, &core_types, assignments);
quote!(Some(#meta))
}
};
(quote!(), quote!(#carrier_arg #(#value_layout_args)*), meta)
(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}"));
@@ -547,122 +510,3 @@ pub(crate) fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&Pars
let row_count = candidates.iter().map(|types| types.len()).max().unwrap_or(1).max(1);
Some((0..row_count).map(|row| candidates.iter().map(|types| types[row.min(types.len() - 1)].clone()).collect()).collect())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parsing::parse_node_fn;
/// The macro's own pipeline up to the entries emitter, so a test node's rows
/// match what `#[node]` would generate.
fn entries_of(attr: TokenStream2, item: TokenStream2) -> String {
let mut parsed = parse_node_fn(attr, item).unwrap();
parsed.replace_impl_trait_in_input();
if parsed.injects_async_source_fields() {
parsed.inject_async_source_fields(&quote!(gcore));
}
let regular_fields: Vec<&ParsedField> = parsed.fields.iter().filter(|field| !field.is_data_field).collect();
let data_field_generic_idents: Vec<Ident> = parsed
.fn_generics
.iter()
.filter_map(|param| match param {
GenericParam::Type(type_param) => Some(type_param.ident.clone()),
_ => None,
})
.filter(|ident| {
parsed
.fields
.iter()
.any(|field| field.is_data_field && matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { ty, .. }) if crate::codegen::type_contains_ident(ty, ident)))
})
.collect();
entries_tokens(&parsed, &format_ident!("TestNode"), &data_field_generic_idents, &regular_fields).to_string()
}
/// A record-io async source whose only generic sits on a plain secondary:
/// the shape the rasterize node has. One row per implementation, or the
/// node never reaches the registry.
#[test]
fn record_io_source_rows_an_implementations_generic_secondary() {
let entries = entries_of(
quote!(category("")),
quote!(
async fn rasterize<T: Send + Clone>(
_: impl Ctx,
_: (),
#[implementations(List<Vector>, List<Raster<CPU>>, List<Graphic>, List<Color>, List<GradientStops>)] data: List<T>,
footprint: Footprint,
canvas: CanvasHandle,
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>) {
todo!()
}
),
);
assert!(entries.contains("fn rasterize_entries"), "a registrable record-io source must emit its entries fn");
for element in ["Vector", "Raster < CPU >", "Graphic", "Color", "GradientStops"] {
let row = format!("record_source_type :: < List < {element} > > ()");
assert!(entries.contains(&row), "the implementations row {element} is missing: {entries}");
}
assert_eq!(entries.matches("constructor :").count(), 5, "one row per implementation");
assert!(!entries.contains("< T >"), "every row instantiates the carried generic");
}
/// The same shape without implementations stays unregistered: nothing names
/// the rows, so a silent empty emission is the intended answer.
#[test]
fn record_io_source_without_implementations_stays_unregistered() {
let entries = entries_of(
quote!(category(""), skip_impl),
quote!(
async fn rasterize_open<T: Send + Clone>(_: impl Ctx, _: (), data: List<T>) -> (Raster<CPU>, Attr<Transform>) {
todo!()
}
),
);
assert!(entries.is_empty(), "an unsourced generic secondary registers nothing: {entries}");
}
/// A ranked element generic keeps sourcing its rows from the ranked input.
#[test]
fn ranked_generic_still_rows_from_its_ranked_input() {
let entries = entries_of(
quote!(category("")),
quote!(
fn count<T: Send + Clone>(_: impl Ctx, _: (), #[implementations(IList<f64>, IList<u32>)] items: IList<T>) -> (u32, Attr<Opacity>) {
todo!()
}
),
);
assert!(entries.contains("fn count_entries"), "a ranked record-io node still emits: {entries}");
assert_eq!(entries.matches("constructor :").count(), 2, "one row per ranked implementation");
}
/// An async source's materialized input crosses the future boundary as an
/// owned snapshot: the prologue materializes the level while the evaluation
/// is live, bridges it to the legacy list, and the kernel takes that.
#[test]
fn async_source_takes_a_materialized_input_as_an_owned_list() {
let generated = crate::parsing::new_node_fn(
quote!(category("")),
quote!(
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
_: impl Ctx,
_: (),
#[implementations(Vector, Raster<CPU>, Graphic)] data: IList<T>,
footprint: Footprint,
) -> (Raster<CPU>, Attr<Transform>) {
todo!()
}
),
)
.expect("the async materialized shape generates")
.to_string();
assert!(generated.contains("data : :: core_types :: list :: List < T >"), "the kernel takes the owned legacy list: {generated}");
assert!(generated.contains("run_to_owned_list"), "the prologue snapshots the materialized level: {generated}");
assert!(generated.contains("record :: materialize_batch"), "the level still materializes in the prologue: {generated}");
for element in ["Vector", "Raster < CPU >", "Graphic"] {
let row = format!("record_source_type :: < {element} > ()");
assert!(generated.contains(&row), "the row carries the leveled element {element}: {generated}");
}
}
}
+1 -236
View File
@@ -67,10 +67,6 @@ fn inputs(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) ->
shape: item_shape(&element, depth, &field.attribute_reads, generics),
subject: subject(index, field, carrier_subject, routing.as_ref()),
lend: matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { lend: Some(_), .. })),
name_source: match &field.ty {
ParsedFieldType::Regular(RegularParsedField { name_source, .. }) => name_source.clone(),
ParsedFieldType::Node(_) => None,
},
}
})
.collect()
@@ -265,10 +261,7 @@ fn ilist_inner(ty: &Type) -> Option<Type> {
/// 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.
/// `assignments` binds the row's concrete types to the signature's generics,
/// which a name-generic write needs: its value type is written as a projection
/// through the wired generic, so only the row resolves it.
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2, assignments: &[(Ident, Type)]) -> TokenStream2 {
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
let sources = layout_sources(node).into_iter().map(|index| index as u8);
let reads = node
.inputs
@@ -281,8 +274,6 @@ pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_t
quote!(#core_types::record::InputReads { input: #index, reads: ::std::vec![#(#descs),*] })
});
let writes = field_writes(&node.output.shape.attrs, core_types);
let named_writes = named_field_writes(node, core_types, assignments);
let named_reads = named_field_reads(node, core_types, assignments);
let removes = node.output.removes.iter().map(|attr| {
let marker = &attr.marker;
let level = attr.level;
@@ -299,10 +290,6 @@ pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_t
reads: ::std::vec![#(#reads),*],
element: #element_spec,
writes: ::std::vec![#(#writes),*],
named_writes: ::std::vec![#(#named_writes),*],
folded_names: ::std::vec![],
named_reads: ::std::vec![#(#named_reads),*],
folded_read_names: ::std::vec![],
removes: ::std::vec![#(#removes),*],
level_delta: #level_delta,
folded: #folded,
@@ -367,7 +354,6 @@ pub(crate) fn folded_subject(node: &Node) -> Option<(u8, u8)> {
fn field_writes(attrs: &[LevelAttr], core_types: &TokenStream2) -> Vec<TokenStream2> {
attrs
.iter()
.filter(|attr| crate::parsing::named_marker(&attr.marker).is_none())
.map(|attr| {
let marker = &attr.marker;
let level = attr.level;
@@ -376,102 +362,6 @@ fn field_writes(attrs: &[LevelAttr], core_types: &TokenStream2) -> Vec<TokenStre
.collect()
}
/// Emits one `NamedWrite` per name-generic write, pairing the template minted
/// from the concrete value type with the input its placeholder's name sits at.
fn named_field_writes(node: &Node, core_types: &TokenStream2, assignments: &[(Ident, Type)]) -> Vec<TokenStream2> {
node.output
.shape
.attrs
.iter()
.filter_map(|attr| {
let (placeholder, value) = crate::parsing::named_marker(&attr.marker)?;
let value = qualify_projection(node, &crate::codegen::classify::substitute_ident_types(&value, assignments), assignments);
// Only a row resolves a value type written through a generic, so
// the row-free meta omits the write rather than naming a type that
// is not in scope there.
if node.generics.iter().any(|generic| mentions_ident(&value, &generic.ident)) {
return None;
}
let input = name_input(node, &placeholder)? as u8;
let level = attr.level;
Some(quote!(#core_types::record::NamedWrite::of::<#placeholder, #value>(#input, #level)))
})
.collect()
}
/// Emits one `NamedRead` per name-generic read, pairing the template minted
/// from the concrete value type with the input read and the input its
/// placeholder's name sits at.
fn named_field_reads(node: &Node, core_types: &TokenStream2, assignments: &[(Ident, Type)]) -> Vec<TokenStream2> {
node.inputs
.iter()
.enumerate()
.flat_map(|(input, source)| source.shape.attrs.iter().map(move |attr| (input, attr)))
.filter_map(|(input, attr)| {
let (placeholder, value) = crate::parsing::named_marker(&attr.marker)?;
let value = qualify_projection(node, &crate::codegen::classify::substitute_ident_types(&value, assignments), assignments);
if node.generics.iter().any(|generic| mentions_ident(&value, &generic.ident)) {
return None;
}
let name = name_input(node, &placeholder)? as u8;
let input = input as u8;
let level = attr.level;
Some(quote!(#core_types::record::NamedRead::of::<#placeholder, #value>(#input, #name, #level)))
})
.collect()
}
/// Rewrites `V::Assoc` into `<Row as Bound>::Assoc` once the row assigns `V`.
/// A value type reached through an associated type needs the generic's own
/// bound to name the projection, which only the signature carries.
fn qualify_projection(node: &Node, ty: &Type, assignments: &[(Ident, Type)]) -> Type {
let Type::Path(path) = ty else { return ty.clone() };
if path.qself.is_some() || path.path.segments.len() < 2 {
return ty.clone();
}
let base = &path.path.segments[0].ident;
let Some(generic) = node.generics.iter().find(|generic| &generic.ident == base) else {
return ty.clone();
};
let Some((_, row)) = assignments.iter().find(|(ident, _)| ident == base) else {
return ty.clone();
};
let mut bounds = generic.bounds.iter().filter_map(|bound| match bound {
TypeParamBound::Trait(bound) => Some(&bound.path),
_ => None,
});
let (Some(bound), None) = (bounds.next(), bounds.next()) else {
return ty.clone();
};
let rest = path.path.segments.iter().skip(1);
syn::parse_quote!(<#row as #bound>::#(#rest)::*)
}
/// Whether `ty` names `ident` anywhere, so a type written through a generic
/// can be told from one already concrete.
fn mentions_ident(ty: &Type, ident: &Ident) -> bool {
struct Search<'a> {
ident: &'a Ident,
found: bool,
}
impl syn::visit::Visit<'_> for Search<'_> {
fn visit_ident(&mut self, found: &Ident) {
self.found |= found == self.ident;
}
}
let mut search = Search { ident, found: false };
syn::visit::Visit::visit_type(&mut search, ty);
search.found
}
/// The input position carrying `placeholder`'s name, which is the parameter
/// declared at that placeholder.
pub(crate) fn name_input(node: &Node, placeholder: &Type) -> Option<usize> {
node.inputs.iter().position(|input| input.name_source.as_ref().is_some_and(|declared| declared == placeholder))
}
fn level_delta(node: &Node) -> i8 {
// A folded subject contributes no base layout, so the delta is relative to
// the fresh (empty) base.
@@ -637,10 +527,6 @@ pub(crate) struct Input {
pub(crate) subject: bool,
/// Written `&T`; the kernel borrows the evaluated element.
pub(crate) lend: bool,
/// The placeholder this input names, written `Named<X>`. Such an input
/// carries constant text the compiler folds into a layout name, so it is
/// never evaluated per lane.
pub(crate) name_source: Option<Type>,
}
/// `Lazy` = `impl Node<..>`, the kernel drives it.
@@ -853,127 +739,6 @@ mod tests {
);
}
#[test]
fn a_named_write_takes_its_name_from_the_declared_input() {
let mut parsed = crate::parsing::parse_node_fn(
quote!(category("")),
quote!(
fn tag<'e, V: WireValue>(ctx: impl Ctx + ExtractArena<'e>, content: f64, name: Named<Name0>, value: V) -> (f64, Attr<'e, Named<Name0, V::Row>>) {
(content, Attr(value))
}
),
)
.unwrap();
parsed.replace_impl_trait_in_input();
let node = build(&parsed);
let attrs = &node.output.shape.attrs;
assert_eq!(attrs.len(), 1, "the write is recorded on the output");
let (placeholder, _) = crate::parsing::named_marker(&attrs[0].marker).expect("the marker is name-generic");
assert_eq!(name_input(&node, &placeholder), Some(1), "the name comes from the `Named<Name0>` parameter");
// The row resolves the value type written through the wired generic.
let assignments = vec![(syn::parse_quote!(V), syn::parse_quote!(f64))];
let emitted = named_field_writes(&node, &quote!(gcore), &assignments);
assert_eq!(emitted.len(), 1, "the row carries the named write, got {emitted:?}");
assert!(emitted[0].to_string().contains("WireValue"), "the projection is qualified by the generic's bound, got {}", emitted[0]);
}
#[test]
fn a_name_input_is_omitted_from_the_kernel_but_kept_on_the_wire() {
let mut parsed = crate::parsing::parse_node_fn(
quote!(category("")),
quote!(
fn tag<'e, V: WireValue>(ctx: impl Ctx + ExtractArena<'e>, content: f64, name: Named<Name0>, value: V) -> (f64, Attr<'e, Named<Name0, V::Row>>) {
(content, Attr(value))
}
),
)
.unwrap();
parsed.replace_impl_trait_in_input();
let node = build(&parsed);
// The name keeps its wired position, so a document's input order is
// untouched, while the kernel neither declares nor is passed it.
assert_eq!(node.inputs.len(), 3, "the wire keeps content, name and value");
assert!(node.inputs[1].name_source.is_some(), "the name sits at its declared position");
let named: Vec<usize> = node.inputs.iter().enumerate().filter(|(_, input)| input.name_source.is_some()).map(|(index, _)| index).collect();
assert_eq!(named, vec![1], "exactly one input names a placeholder");
// A name input's wire type is plain text, which is what the fold reads.
let ParsedFieldType::Regular(RegularParsedField { ty, name_source, .. }) = &parsed.fields[1].ty else {
panic!("the name is a regular input");
};
assert!(name_source.is_some(), "the parameter declares a placeholder");
assert_eq!(quote!(#ty).to_string(), "String", "the name crosses as constant text");
// The placeholder is a concrete token, so it adds no generic for the
// struct to carry and none to go unconstrained.
let generics: Vec<String> = node.generics.iter().map(|generic| generic.ident.to_string()).collect();
assert_eq!(generics, vec!["V".to_string()], "only the value generic rides the node");
}
#[test]
fn a_reading_input_whose_element_goes_nowhere_is_opaque() {
let mut parsed = crate::parsing::parse_node_fn(
quote!(category("")),
quote!(
fn peek<'e, T>(_: impl Ctx, (content, opacity): (T, Attr<'e, Opacity>)) -> f64 {
let _ = content;
*opacity
}
),
)
.unwrap();
parsed.replace_impl_trait_in_input();
let token = crate::codegen::classify::opaque_reading_carrier(&parsed).expect("the element generic is opaque");
assert_eq!(token.to_string(), "T");
// The node still reads, so it keeps the record-io tail, and the element
// rides it as the byte-carried token: one row covers every element type.
let node = build(&parsed);
assert!(matches!(node_kind(&node), NodeKind::RecordIo), "an opaque reading input still reads attributes");
assert!(
matches!(crate::codegen::record_shape(&parsed), Some(shape) if matches!(shape.carrier, crate::codegen::RecordCarrier::Token)),
"the element is carried as a token rather than read"
);
assert_eq!(node.inputs[0].shape.attrs.len(), 1, "the declared read survives the blessing");
}
#[test]
fn an_element_generic_the_node_uses_is_not_opaque() {
// Returned rather than dropped, so the element is carried, not opaque:
// the usual passthrough rule still governs it.
let mut carried = crate::parsing::parse_node_fn(
quote!(category("")),
quote!(
fn keep<'e, T>(_: impl Ctx, (content, opacity): (T, Attr<'e, Opacity>)) -> (T, Attr<'e, Opacity>) {
(content, opacity)
}
),
)
.unwrap();
carried.replace_impl_trait_in_input();
assert!(crate::codegen::classify::opaque_reading_carrier(&carried).is_none(), "an element the output carries is not opaque");
// No reads at all, so the generic is an ordinary element and still owes
// an implementations list.
let mut plain = crate::parsing::parse_node_fn(
quote!(category("")),
quote!(
fn plain<T>(_: impl Ctx, content: T) -> f64 {
let _ = content;
0.
}
),
)
.unwrap();
plain.replace_impl_trait_in_input();
assert!(
crate::codegen::classify::opaque_reading_carrier(&plain).is_none(),
"a generic element without reads still needs implementations"
);
}
#[test]
fn bridge_record_remove() {
assert_bridge(
-56
View File
@@ -110,42 +110,6 @@ pub(crate) fn remove_attr_marker(ty: &Type) -> Option<Type> {
marker_of(ty, "RemoveAttr")
}
/// Splits a `Named<X, V>` marker into its placeholder and value type. A write
/// of one takes its name from the input the placeholder is declared at rather
/// than from the marker, so the name folds at graph compile time.
pub(crate) fn named_marker(ty: &Type) -> Option<(Type, Type)> {
let mut args = named_arguments(ty)?.into_iter();
let (placeholder, value) = (args.next()?, args.next()?);
args.next().is_none().then_some((placeholder, value))
}
/// The placeholder a `Named<X>` parameter declares. Such a parameter is the
/// name source for every `Attr<Named<X, _>>` the signature writes, and crosses
/// the wire as constant text.
pub(crate) fn named_source(ty: &Type) -> Option<Type> {
let mut args = named_arguments(ty)?.into_iter();
let placeholder = args.next()?;
args.next().is_none().then_some(placeholder)
}
fn named_arguments(ty: &Type) -> Option<Vec<Type>> {
let Type::Path(path) = ty else { return None };
let segment = path.path.segments.last()?;
if segment.ident != "Named" {
return None;
}
let PathArguments::AngleBracketed(args) = &segment.arguments else { return None };
Some(
args.args
.iter()
.filter_map(|argument| match argument {
GenericArgument::Type(ty) => Some(ty.clone()),
_ => None,
})
.collect(),
)
}
fn marker_of(ty: &Type, wrapper: &str) -> Option<Type> {
let Type::Path(path) = ty else { return None };
let segment = path.path.segments.last()?;
@@ -369,10 +333,6 @@ impl Parse for NumberRange {
#[derive(Clone, Debug)]
pub struct RegularParsedField {
pub ty: Type,
/// The placeholder this parameter names, written `Named<X>`. Its `ty` is
/// rewritten to `String`, since the wire carries the name as constant text
/// while the kernel takes only the placeholder.
pub name_source: Option<Type>,
/// `IList` nesting stripped from `ty` at parse; `ty` holds the element row.
pub list_levels: u8,
/// The original reference tokens when the parameter was written `&T`; `ty` holds the peeled inner type.
@@ -1271,18 +1231,9 @@ fn parse_field(pat_ident: PatIdent, ty: Type, attrs: &[Attribute]) -> syn::Resul
}
}
// A `Named<X>` parameter declares where `X`'s name is wired: the input
// carries constant text, the kernel takes only the placeholder.
let name_source = named_source(&ty);
let ty = match name_source {
Some(_) => parse_quote!(String),
None => ty,
};
Ok(ParsedField {
pat_ident,
ty: ParsedFieldType::Regular(RegularParsedField {
name_source,
exposed,
number_soft_min,
number_soft_max,
@@ -1405,7 +1356,6 @@ impl ParsedNodeFn {
widget_override: ParsedWidgetOverride::Hidden,
ty: ParsedFieldType::Regular(RegularParsedField {
ty,
name_source: None,
list_levels: 0,
lend: None,
exposed: false,
@@ -1583,7 +1533,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
name_source: None,
lend: None,
list_levels: 0,
ty: parse_quote!(f64),
@@ -1682,7 +1631,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
name_source: None,
lend: None,
list_levels: 0,
ty: parse_quote!(DVec2),
@@ -1762,7 +1710,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
name_source: None,
lend: None,
list_levels: 0,
ty: parse_quote!(f64),
@@ -1840,7 +1787,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
name_source: None,
lend: None,
list_levels: 0,
ty: parse_quote!(f64),
@@ -1930,7 +1876,6 @@ mod tests {
description: String::from("b"),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
name_source: None,
lend: None,
list_levels: 0,
ty: parse_quote!(f64),
@@ -2023,7 +1968,6 @@ mod tests {
description: String::new(),
widget_override: ParsedWidgetOverride::None,
ty: ParsedFieldType::Regular(RegularParsedField {
name_source: None,
lend: None,
list_levels: 0,
ty: parse_quote!(String),
@@ -232,7 +232,6 @@ impl PerPixelAdjustCodegen<'_> {
widget_override: Default::default(),
ty: ParsedFieldType::Regular(RegularParsedField {
ty: parse_quote!(#wgpu_executor::WgpuExecutorHandle),
name_source: None,
list_levels: 0,
lend: None,
exposed: true,
+4 -28
View File
@@ -127,22 +127,12 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
_ => None,
};
if async_source && token.is_some() {
emit_error!(
carrier.pat_ident.span(),
"an async source's element crosses the future boundary as a value; a passthrough generic element has none"
);
emit_error!(carrier.pat_ident.span(), "an async source's element crosses the future boundary as a value; a passthrough generic element has none");
}
let element = writes.as_ref().map(|writes| &writes.element).unwrap_or(&value);
match &token {
Some(token) => {
// An opaque reading input never looks at its element, so it writes
// a fresh one rather than carrying the input's through.
let opaque_reading = crate::codegen::classify::opaque_reading_carrier(parsed).is_some();
if opaque_reading {
if crate::codegen::contains_open_generic(parsed, element) {
emit_error!(parsed.output_type.span(), "an opaque reading input writes a concrete element, since `{}` is never read", token);
}
} else if !matches!(crate::codegen::bare_ident(element), Some(ident) if ident == token) {
if !matches!(crate::codegen::bare_ident(element), Some(ident) if ident == token) {
emit_error!(parsed.output_type.span(), "a generic element passes through unchanged: return `{}` in the first tuple position", token);
}
}
@@ -174,10 +164,7 @@ fn validate_record_io(parsed: &ParsedNodeFn) {
let mut seen_writes: Vec<String> = Vec::new();
for write in &writes.markers {
if write.owned && !async_source {
emit_error!(
parsed.output_type.span(),
"an owned attribute crossing belongs to an async source; a synchronous write parks its value in the kernel"
);
emit_error!(parsed.output_type.span(), "an owned attribute crossing belongs to an async source; a synchronous write parks its value in the kernel");
}
let written = write.marker.to_token_stream().to_string();
if seen_writes.contains(&written) {
@@ -277,14 +264,6 @@ fn validate_async_source(parsed: &ParsedNodeFn) {
"`async fn` source nodes cannot take `impl Node` inputs: the spawned future outlives any borrow of the graph, so it cannot evaluate other nodes; use the sync-prologue form (return `SourceFuture`) to evaluate lazy inputs before spawning"
);
}
// One level snapshots to one owned legacy list; a deeper input has no
// owned form to cross the future boundary with.
if matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 1) {
emit_error!(
field.pat_ident.span(),
"`async fn` source nodes take a materialized input as an owned snapshot of one level, so nested `IList` is unsupported; flatten to a single `IList` or use the sync-prologue form (return `SourceFuture`)"
);
}
}
}
}
@@ -437,16 +416,13 @@ fn validate_implementations_for_generics(parsed: &ParsedNodeFn) {
(crate::codegen::ir::NodeKind::RecordIo, crate::codegen::ir::Element::Generic(ident)) => Some(ident.clone()),
_ => None,
};
// An opaque reading carrier's element is never looked at, so it needs no
// rows: the node registers one generic row and accepts any record wire.
let opaque_reading = crate::codegen::classify::opaque_reading_carrier(parsed);
let opaque_record_generic = |ty: &Type| {
let (stripped, _) = crate::codegen::ir::strip_ilist(ty);
let ident = match &stripped {
Type::Path(path) => path.path.get_ident(),
_ => None,
};
ident.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref() || ident == opaque_reading.as_ref())
ident.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref())
};
if !has_skip_impl && !parsed.fn_generics.is_empty() {
+1 -1
View File
@@ -262,7 +262,7 @@ mod tests {
use core_types::context::{ContextImpl, EvalScope};
use core_types::node::Node;
use core_types::record::LiftedSource;
use core_types::registry::{ErasedRecordNode, SourceHandle};
use core_types::registry::{SourceHandle, ErasedRecordNode};
use std::sync::atomic::{AtomicU32, Ordering};
fn lifted<T: Clone + Send + Sync + core_types::StaticTypeSized>(value: T) -> LiftedSource<T, impl for<'c> Fn(&ContextImpl<'c>) -> GPoll<T>>
+14 -117
View File
@@ -360,15 +360,6 @@ fn offset(_: impl Ctx, element: f64, by: &f64) -> f64 {
element + *by
}
/// Test-only flip node holding a borrow of its lent carrier across a lazy
/// input's evaluation: the borrow points into the carrier's frame, so the lazy
/// input's claim has to start beyond it.
#[node_macro::node(category("Test"))]
fn lend_across_lazy(ctx: impl Ctx, element: &f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<f64, Interrupt> {
let added = addend.eval(ctx)?;
Ok(*element + added)
}
#[node_macro::node(category("Test"))]
async fn double_async(_: impl Ctx, element: f64) -> f64 {
element * 2.
@@ -662,9 +653,6 @@ mod tests {
// The fixtures wire constants into every eager input, which the compiler
// pass records as lane-invariant.
let resolved = core_types::record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
lane_invariant: u32::MAX,
..meta.resolve(inputs)
};
@@ -674,9 +662,6 @@ mod tests {
fn install_flip<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
let bundle = core_types::record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
layout: layout.clone(),
@@ -770,10 +755,6 @@ mod tests {
let frames = frames_for(&[&base, &count_layout]);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -810,10 +791,6 @@ mod tests {
let frames = frames_for(&[&base, &count_layout]);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -858,10 +835,6 @@ mod tests {
let frames = frames_for(&[&base, &count_layout, &reverse_layout]);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -912,10 +885,6 @@ mod tests {
&[Some(&base)],
);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1014,10 +983,6 @@ mod tests {
field: Some((Length::NAME, 7.)),
};
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0, 1],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1086,10 +1051,6 @@ mod tests {
field: Some((Opacity::NAME, 0.25)),
};
let meta = || core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0, 1],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1164,10 +1125,6 @@ mod tests {
field: Some((Length::NAME, 7.)),
};
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0, 1],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1212,10 +1169,6 @@ mod tests {
let content_layout = leveled_f64_layout(&[]);
let meta = || core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1225,10 +1178,6 @@ mod tests {
folded: None,
};
let extend_meta = || core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0, 1],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1304,10 +1253,6 @@ mod tests {
let layout = leveled_f64_layout(&[]);
let frames = frames_for(&[&layout]);
let meta = || core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1361,10 +1306,6 @@ mod tests {
};
let (index_edge, index_layout) = lifted_value(index);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1581,9 +1522,6 @@ mod tests {
let evals = std::cell::Cell::new(0u32);
let mut node = MirrorNode::new(RecordSource::new(content, &layout, &layout), counting_value(true, &evals));
let resolved = core_types::record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
lane_invariant: 0,
..mirror_layout_meta().resolve(&[Some(&layout)])
};
@@ -1662,10 +1600,6 @@ mod tests {
&[Some(&base)],
);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1719,10 +1653,6 @@ mod tests {
&[Some(&base)],
);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1833,10 +1763,6 @@ mod tests {
let (count_edge, count_layout) = lifted_value(2u32);
let (reverse_edge, reverse_layout) = lifted_value(false);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -1963,10 +1889,6 @@ mod tests {
let frames = frames_for(&[&base, &count_layout, &out]);
let meta = core_types::record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![0],
reads: vec![],
element: core_types::record::ElementSpec::Carried,
@@ -2420,35 +2342,6 @@ mod tests {
assert_eq!(served.attr::<Opacity>(), 0.25);
}
#[test]
fn a_lent_carrier_borrow_survives_a_lazy_inputs_claim() {
let arena = Arena::new(1024).unwrap();
let generations = [];
let scope = scope_fixture(&generations, &arena);
let ctx = ContextImpl::root(&scope);
let carrier_layout = f64_layout(&["opacity"]);
let addend_layout = f64_layout(&["opacity"]);
assert!(carrier_layout.frame_bytes() != 0, "the lend must borrow into a spilled frame for the claims to overlap");
let frames = frames_for(&[&carrier_layout, &addend_layout]);
let node = install(
LendAcrossLazyNode::new(
f64_record_source(&carrier_layout, 2., vec![("opacity", 0.25)]),
f64_record_source(&addend_layout, 40., vec![("opacity", 0.5)]),
&carrier_layout,
&addend_layout,
),
lend_across_lazy_layout_meta(),
&[Some(&carrier_layout), None],
);
let GPoll::Final(served) = core_types::record::capture(&node, &ctx, &frames) else {
panic!("expected a final record");
};
assert_eq!(served.element::<f64>(), 42., "the lazy input claims beyond the carrier's frame, so the borrow keeps its element");
assert_eq!(served.attr::<Opacity>(), 0.25);
}
struct InlineRuntime;
impl core_types::runtime::Runtime for InlineRuntime {
@@ -2512,7 +2405,13 @@ mod tests {
let frames = frames_for(&[&source_layout]);
let node = install(
FadeAsyncNode::new(f64_record_source(&source_layout, 3., vec![("length", 9.)]), ValueSource::new(0.5), runtime, source_id, &source_layout),
FadeAsyncNode::new(
f64_record_source(&source_layout, 3., vec![("length", 9.)]),
ValueSource::new(0.5),
runtime,
source_id,
&source_layout,
),
fade_async_layout_meta(),
&[Some(&source_layout)],
);
@@ -2545,7 +2444,11 @@ mod tests {
let layout = measure_async_layout();
let frames = frames_for(&[&layout]);
let node = install(MeasureAsyncNode::new(ValueSource::new(()), ValueSource::new(-4.), runtime, source_id), measure_async_layout_meta(), &[]);
let node = install(
MeasureAsyncNode::new(ValueSource::new(()), ValueSource::new(-4.), runtime, source_id),
measure_async_layout_meta(),
&[],
);
assert_eq!(Node::<ContextImpl>::layout(&node), &layout);
let GPoll::Final(served) = core_types::record::capture(&node, &ctx, &frames) else {
@@ -2956,14 +2859,8 @@ mod tests {
let frames = frames_for(&[&layout]);
let base = {
let probe = frames.scope();
let mut claim = probe.claim(&layout);
claim.element(0f64, &arena).expect("the arena holds the element");
for name in ["opacity", "length"] {
// SAFETY: the offset is this claim's own layout's, at the f64 the field was declared with.
unsafe { claim.attr_at(layout.offset_of(name, 0).expect("the fixture declares the field"), 0f64) };
}
// SAFETY: the element and both fields complete the record.
let value = unsafe { claim.finish() };
// SAFETY: nothing reads the probe's record; only its address is taken.
let value = unsafe { probe.claim(&layout).finish() };
layout.rec(&value).ptr()
};
+1 -69
View File
@@ -1,4 +1,4 @@
use core_types::attribute::{Attr, EditorLayerPath, Name0, Named, Transform as TransformAttr, WireValue};
use core_types::attribute::{Attr, EditorLayerPath, Transform as TransformAttr};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::extent::{ExtentIn, LevelIn, ListIn, ValueIn};
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt, Level};
@@ -11,7 +11,6 @@ use graphic_types::graphic::{Graphic, IntoGraphicList};
use graphic_types::{ATTR_EDITOR_MERGED_LAYERS, Artboard, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::gradient::{GradientSpreadMethod, GradientType as GradientTypeValue};
use vector_types::{GradientStop, GradientStops, ReferencePoint};
/// Resolves a signed index over `total` lanes: negatives count from the end,
@@ -369,73 +368,6 @@ pub fn stamp_layer_path<'e, T>(ctx: impl Ctx + ExtractArena<'e>, element: T, pat
Ok((element, Attr(parked.as_slice())))
}
/// Writes `value` onto each lane under the attribute `name` names. The name is
/// constant text the compiler folds into the layout when the graph compiles, so
/// the write costs exactly what a marker node's does; a name that is not
/// constant is refused there rather than resolved here.
#[node_macro::node(category("Attributes: Write"))]
pub fn write_attribute<'e, T, V: WireValue>(
ctx: impl Ctx + ExtractArena<'e>,
content: T,
/// The attribute name, folded into the layout when the graph compiles.
name: Named<Name0>,
#[implementations(f64, u32, u64, bool, DVec2, DAffine2, Color, Vec<NodeId>, String)] value: V,
) -> Result<(T, Attr<'e, Named<Name0, V::Row>>), Interrupt> {
let parked = value.park(ctx.arena()).ok_or(GraphError {
kind: core_types::gpoll::ErrorKind::ArenaExhausted,
trace: Vec::new(),
})?;
Ok((content, Attr(parked)))
}
// The attribute reads: one node per value type, since a name means one type
// and there is no coercion between them. Each takes any record wire, never
// looks at its element, and serves the name's own default where the attribute
// is absent, so the value always carries the declared type.
//
// The name is constant text the compiler folds into an offset when the graph
// compiles; a name written at another value type is a graph error rather than
// a conversion.
macro_rules! attribute_reads {
($($(#[$meta:meta])* $node:ident: $row:ty => $value:ty;)*) => {
$(
$(#[$meta])*
#[node_macro::node(category("Attributes: Read"))]
pub fn $node<'e, T>(
_: impl Ctx,
/// The content whose lanes carry the attribute; its element is never read.
(content, value): (T, Attr<'e, Named<Name0, $row>>),
/// The attribute name, folded into an offset when the graph compiles.
name: Named<Name0>,
) -> $value {
let _ = content;
*value
}
)*
};
}
attribute_reads! {
/// Reads a named `f64` attribute, such as `opacity` or `font_size`.
read_number_attribute: f64 => f64;
/// Reads a named `u64` attribute, such as a regex match's `start` or `end`.
read_integer_attribute: u64 => u64;
/// Reads a named `bool` attribute, such as `clipping_mask` or `clip`.
read_bool_attribute: bool => bool;
/// Reads a named `DVec2` attribute, such as an artboard's `location` or `dimensions`.
read_coordinate_attribute: DVec2 => DVec2;
/// Reads a named `DAffine2` attribute, such as `transform`.
read_transform_attribute: DAffine2 => DAffine2;
/// Reads a named `Color` attribute, such as an artboard's `background`.
read_color_attribute: Color => Color;
/// Reads a named `BlendMode` attribute, such as `blend_mode`.
read_blend_mode_attribute: core_types::blending::BlendMode => core_types::blending::BlendMode;
/// Reads a named gradient-shape attribute, such as `gradient_type`.
read_gradient_type_attribute: GradientTypeValue => GradientTypeValue;
/// Reads a named gradient-spread attribute, such as `spread_method`.
read_spread_method_attribute: GradientSpreadMethod => GradientSpreadMethod;
}
/// Joins two levels of the same type, the base's lanes followed by the new's.
#[node_macro::node(category("General"), extent(extend_extent))]
pub fn extend<T>(
+4 -19
View File
@@ -285,9 +285,6 @@ mod tests {
// The fixtures wire constants into every eager input, which the compiler
// pass records as lane-invariant.
let resolved = record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
lane_invariant: u32::MAX,
..meta.resolve(inputs)
};
@@ -297,9 +294,6 @@ mod tests {
fn install_flip<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
let bundle = record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
layout: layout.clone(),
@@ -426,10 +420,6 @@ mod tests {
fn routing_meta(source: u8, level_delta: i8) -> record::LayoutMeta {
record::LayoutMeta {
named_writes: Vec::new(),
folded_names: Vec::new(),
named_reads: Vec::new(),
folded_read_names: Vec::new(),
sources: vec![source],
reads: vec![],
element: record::ElementSpec::Carried,
@@ -760,11 +750,10 @@ mod tests {
let copy = unsafe { (out.element.clone_out)(out.rec(&value).ptr()) };
let replay_arena = Arena::new(1 << 16).unwrap();
// Word storage: a parked element slot holds an 8-aligned reference.
let mut slot = [0u64; 1];
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr().cast(), &replay_arena) }.expect("the arena holds the replay");
let mut slot = [0u8; 8];
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr(), &replay_arena) }.expect("the arena holds the replay");
// SAFETY: the re-park wrote a parked `Graphic` element into `slot`.
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr().cast())) }) else {
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr())) }) else {
panic!("the replay restores the group element");
};
let item = &group.content;
@@ -891,11 +880,7 @@ mod tests {
let head = ctx.index_head();
let group = {
// SAFETY: the element is cloned out inside the scope, so no borrow
// into the frame escapes it. The clone is shallow, so the `'static`
// the `GraphicSource` rows infer launders a borrow of `arena`: it is
// contained because `arena` outlives every use below and this test
// never resets it, so the interior stays resident for the whole
// generation the group is read in.
// into the frame escapes it.
let scope = frames.scope();
let GPoll::Final(value) = record::serve_input(&wrapped, &ctx.promoted(&head, 0), &scope) else {
panic!("expected a final record");
@@ -9,13 +9,13 @@ use core_types::gpoll::GPoll;
#[cfg(target_family = "wasm")]
use core_types::list::List;
#[cfg(target_family = "wasm")]
use core_types::ATTR_TRANSFORM;
#[cfg(target_family = "wasm")]
use core_types::math::bbox::Bbox;
use core_types::runtime::SourceFuture;
#[cfg(target_family = "wasm")]
use core_types::transform::Footprint;
#[cfg(target_family = "wasm")]
use core_types::{ATTR_TRANSFORM, WasmNotSend};
use core_types::{Color, Ctx};
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
pub use graph_craft::application_io::*;
@@ -204,17 +204,17 @@ fn create_canvas(_: impl Ctx) -> CanvasHandle {
/// Renders a view of the input graphic within an area defined by the *Footprint*.
#[cfg(target_family = "wasm")]
#[node_macro::node(category(""))]
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
async fn rasterize<T: WasmNotSend + Clone>(
_: impl Ctx,
_: (),
#[implementations(
Vector,
Raster<CPU>,
Graphic,
Color,
GradientStops,
List<Vector>,
List<Raster<CPU>>,
List<Graphic>,
List<Color>,
List<GradientStops>,
)]
mut data: IList<T>,
mut data: List<T>,
footprint: Footprint,
mut canvas: CanvasHandle,
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)
-3
View File
@@ -272,9 +272,6 @@ mod tests {
plan: Vec::new(),
layout: layout.clone(),
lane_invariant: u32::MAX,
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
},
);
let GPoll::Final(result) = core_types::record::serve_input(&graph, &ctx, &frames) else {
-9
View File
@@ -1053,9 +1053,6 @@ mod graphene_test {
fn installed<N: Node<ContextImpl<'static>>>(mut node: N, layout: &Layout) -> N {
node.set_layout(core_types::record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
layout: layout.clone(),
@@ -1117,9 +1114,6 @@ mod graphene_test {
let mut wired = construct(&entries[0], vec![record_value_source(true), record_value_source(false)]).unwrap();
let layout = out_layout::<bool>();
wired.set_layout(core_types::record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
layout: layout.clone(),
@@ -1166,9 +1160,6 @@ mod graphene_test {
let mut wired = construct(&entries[0], vec![record_value_source(1.5f64), record_value_source(2.5f64)]).unwrap();
let layout = out_layout::<f64>();
wired.set_layout(core_types::record::RecordLayout {
named_writes: Vec::new(),
named_reads: Vec::new(),
named_read_defaults: Vec::new(),
frame_bytes: layout.frame_bytes(),
plan: Vec::new(),
layout: layout.clone(),