Compare commits

...
Author SHA1 Message Date
Dennis Kobert e10d56c261 Box the largest message and update payloads 2026-09-09 15:39:37 +00:00
Dennis Kobert f566e8ee17 Sort key mappings and node positions by key 2026-09-09 15:39:32 +00:00
Dennis Kobert 6910a12f71 Drop redundant conversions, assertions and struct updates 2026-09-09 15:39:17 +00:00
Dennis Kobert f726014c93 Elide the arena lifetimes that the signatures do not need 2026-09-09 15:39:12 +00:00
Dennis Kobert 23313bd5ae Name the crate cluster tuple as a type alias 2026-09-09 15:39:12 +00:00
Dennis Kobert a06039c6c8 Explain why the selective color and spline loops index by range 2026-09-09 15:39:12 +00:00
Dennis Kobert 7cd6e7cd04 Collapse nested conditionals into let-chains and match guards 2026-09-09 15:31:36 +00:00
Dennis KobertandClaude Fable 5 0a4288eca6 Read a named attribute at each value type it can hold
One read node per value type, mirroring master's read family. A name
means one value type, so there is no coercion between them: master's
number read silently widened integers, and these refuse instead, which
is the same rule the write side already enforces.

Each takes any record wire through the opaque reading input and serves
the name's own default where the attribute is absent, so the value
carries the declared type either way.

The gradient enums join the value-type rows now that a family exists to
read them at.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:36:00 +00:00
Dennis KobertandClaude Fable 5 5baeb8fd46 Accept any record wire on an input read only for its attributes
An element generic declared on a reading input, absent from the output
and from every other input, has nowhere to go and nothing to be: the
node reads its declared attributes and never the element. That is an
attr-to-element map, so it accepts any upstream record wire.

The blessing is inferred rather than marked, since the signature already
says it. The two substrate pieces were both in place: the element rides
as the byte-carried token, so the registry takes one generic row instead
of a row per element type, and the reads resolve against the input's own
layout as they always have. Only the passthrough rule stood in the way,
in the three places that enforced it.

A generic the output carries, or one on an input with no reads, is
unchanged and still owes an implementations list.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 12:15:40 +00:00
Dennis KobertandClaude Fable 5 f04d439b33 Name the attribute read for the type it reads
The read is a number read, not a read of whatever the name holds: our
model has no coercion, so a name written at another value type is a graph
error rather than a conversion. The name says so.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 11:35:38 +00:00
Dennis KobertandClaude Fable 5 6e22d6a412 Serve a declared name's census default on an absent read
An absent read of a name the census declares now serves that name's own
default rather than its value type's, which is the rule for a declared
name. The census stages it exactly as it fills any absent field, as the
declared default's bytes, so the read reuses the census's own mechanism
instead of a second one; the compiler takes them when the name folds and
`set_layout` installs them beside the offset.

A name the census does not declare keeps the value type's default, which
is that case's own rule. One name carries one value type, checked when
the name folds, so the row's value type and width agree with the read's.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 11:13:41 +00:00
Dennis KobertandClaude Fable 5 5eb80721dd Resolve a named read's offset when the graph compiles
The fold already holds the name and the read input's finished layout, so
the offset falls out there rather than at construction: `RecordLayout`
carries the resolved numbers and `set_layout` copies them into the read
slots. Constructors are untouched, and census-marker reads keep their
current installation.

A read meets the value type the name was written at, so a disagreement
between a read here and a write upstream is the same graph error as two
writes disagreeing; the one-name-one-type check now spans reads and
writes together. An absent attribute stays absent and the read serves
the forced default rather than reporting it.

`read_attribute` is the catalog's get half, typed and never `Option` at
the kernel boundary, with the name declared exactly as the write side
declares it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 10:50:08 +00:00
Dennis KobertandClaude Fable 5 fc94487d0b Keep the name placeholder out of the kernel entirely
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
the kernel neither declares it nor is passed it; the return type's
`Named<X, V>` is the only tie between the write slot and the folded name.

The wire is untouched: the input keeps its declared position and crosses
as constant text, so a document's input order is unchanged. The
placeholder stays a concrete token, so it adds no generic for the node
to carry and none to go unconstrained.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 10:20:22 +00:00
Dennis KobertandClaude Fable 5 37c0d0852d Carry the new layout fields through the hand-built fixtures
The record fixtures spell their metas and resolved layouts out in full,
so the name-from-input fields reach them as empty. `named_value!`'s
example moves to `ignore`: its `for T` arm implements a core-types trait
on the value type, which only core-types itself may do.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 09:43:52 +00:00
Dennis KobertandClaude Fable 5 9b92edc0e9 Write an attribute under a name the graph supplies
`Named<X>` in parameter position declares where a placeholder's name is
wired, and the macro gives that input constant text; `Attr<Named<X, V>>`
in the return writes under it. The kernel is handed the bare placeholder,
since the name is spent resolving the layout and a folded offset is all
the write needs, so the hot path matches a marker node's exactly.

A name-generic write names its value type through the wired generic,
which only an implementations row resolves, so those nodes emit their
layout meta per row rather than sharing one across rows.

`write_attribute` is the catalog's set half, restoring the identifier
master's documents carry with its input positions. Its name input is a
constant, so those documents resolve without migration, and the reset
marker that stood in for the missing node retires with it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 09:26:17 +00:00
Dennis KobertandClaude Fable 5 348e9022a6 Fold attribute names out of their constant inputs when the graph compiles
`compute_layouts` resolves every name-from-input write against the text
its name input carries, so a folded meta is indistinguishable from a
marker node's and the layout holds a `&'static str` from there on. That
leaves nowhere for a name to be computed, which is the whole of the
rule: a name input that is not a constant is refused right here, per
node, with the path the editor pins its diagnostic to.

One name carries one value type, checked across the census and the
names a node folds together, so no graph can declare one field at two
widths. `compute_layouts` returns those refusals rather than panicking.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 08:51:05 +00:00
Dennis KobertandClaude Fable 5 0001cdf04d Carry a name-generic attribute's value type as its own row
An attribute's name and its value type separate: `AttrValue` declares
everything `Attribute` does except the name and its name-specific
default, and `Named<X, V>` pairs one with a name the graph supplies.
The value type stays concrete in the signature while the name varies
per instance, so a computed name has nowhere to come from.

`LayoutMeta` gains the name-from-input variant the fold consumes: a
`FieldWrite` template with every facet minted from the concrete type
and only the name left as a placeholder, plus the input position the
name's constant sits at. `fold_name` resolves one, preferring the
census row's descriptor where the name is declared so a known name
keeps its census default. `RecordLayout` carries the folded names so
`set_layout` can resolve offsets without a marker's `NAME`.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-09 08:41:53 +00:00
53 changed files with 1579 additions and 214 deletions

No files matched your search

+4 -8
View File
@@ -492,15 +492,11 @@ mod test {
if let FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::DialogColumn1,
diff,
} = response
} = response && let DiffUpdate::Layout(sub_layout) = &diff[0].new_value
&& let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0]
&& let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget
{
if let DiffUpdate::Layout(sub_layout) = &diff[0].new_value {
if let LayoutGroup::Row(WidgetRow { widgets }) = &sub_layout.0[0] {
if let Widget::TextLabel(TextLabel { value, .. }) = &*widgets[0].widget {
print_problem_to_terminal_on_failure(value);
}
}
}
print_problem_to_terminal_on_failure(value);
}
}
}
@@ -465,7 +465,7 @@ pub fn input_mappings(zoom_with_scroll: bool) -> Mapping {
];
let (mut key_up, mut key_down, mut key_up_no_repeat, mut key_down_no_repeat, mut double_click, mut wheel_scroll, mut pointer_move, mut pointer_shake) = mappings;
let sort = |list: &mut KeyMappingEntries| list.0.sort_by(|a, b| b.modifiers.count_ones().cmp(&a.modifiers.count_ones()));
let sort = |list: &mut KeyMappingEntries| list.0.sort_by_key(|entry| std::cmp::Reverse(entry.modifiers.count_ones()));
// Sort the sublists of `key_up`, `key_down`, `key_up_no_repeat`, and `key_down_no_repeat`
for list in [&mut key_up, &mut key_down, &mut key_up_no_repeat, &mut key_down_no_repeat] {
for sublist in list {
@@ -4105,10 +4105,11 @@ mod document_message_handler_tests {
async fn get_layer_by_bounds(editor: &mut EditorTestUtils, min_x: f64, min_y: f64) -> Option<LayerNodeIdentifier> {
let document = editor.active_document();
for layer in document.metadata().all_layers() {
if let Some(bbox) = document.metadata().bounding_box_viewport(layer) {
if (bbox[0].x - min_x).abs() < 1. && (bbox[0].y - min_y).abs() < 1. {
return Some(layer);
}
if let Some(bbox) = document.metadata().bounding_box_viewport(layer)
&& (bbox[0].x - min_x).abs() < 1.
&& (bbox[0].y - min_y).abs() < 1.
{
return Some(layer);
}
}
None
@@ -4163,9 +4164,8 @@ mod document_message_handler_tests {
.await;
// The operation completed without crashing
// Verifying application still functions by performing another operation
// Verifying application still functions by performing another operation, which panics if the folder move left the editor broken
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
assert!(true, "Application didn't crash after folder move operation");
}
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
@@ -157,7 +157,8 @@ pub enum NodeGraphMessage {
SetInputValue {
node_id: NodeId,
input_index: usize,
value: TaggedValue,
// Boxed to keep the whole editor message tree small; `TaggedValue` alone is 568 bytes
value: Box<TaggedValue>,
},
SetInput {
input_connector: InputConnector,
@@ -1765,6 +1765,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
NodeGraphMessage::SetInputValue { node_id, input_index, value } => {
use graphene_std::vector::generator_nodes::*;
let value = *value;
let reference = network_interface.reference(&node_id, selection_network_path);
let is_text_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::text::text::IDENTIFIER));
let is_stroke_node = reference.as_ref().is_some_and(|r| *r == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER));
@@ -44,7 +44,12 @@ pub(crate) fn string_properties(text: &str) -> Vec<LayoutGroup> {
fn optionally_update_value<T>(value: impl Fn(&T) -> Option<TaggedValue> + 'static + Send + Sync, node_id: NodeId, input_index: usize) -> impl Fn(&T) -> Message + 'static + Send + Sync {
move |input_value: &T| match value(input_value) {
Some(value) => NodeGraphMessage::SetInputValue { node_id, input_index, value }.into(),
Some(value) => NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: Box::new(value),
}
.into(),
None => Message::NoOp,
}
}
@@ -867,7 +872,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: TaggedValue::Resource(resource_id),
value: Box::new(TaggedValue::Resource(resource_id)),
}
.into(),
]),
@@ -1437,7 +1442,7 @@ fn build_shared_spectrum_section(node_id: NodeId, context: &mut NodePropertiesCo
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F32(percent.clamp(0., 100.) as f32),
value: Box::new(TaggedValue::F32(percent.clamp(0., 100.) as f32)),
}
.into()
}
@@ -1594,7 +1599,7 @@ fn spectrum_slider_row(
NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32),
value: Box::new(TaggedValue::F32(position_to_value(new_position).clamp(value_min, value_max) as f32)),
}
.into()
})
@@ -2148,13 +2153,13 @@ pub(crate) fn string_capitalization_properties(node_id: NodeId, context: &mut No
NodeGraphMessage::SetInputValue {
node_id,
input_index: UseJoinerInput::INDEX,
value: TaggedValue::Bool(true),
value: Box::new(TaggedValue::Bool(true)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: JoinerInput::INDEX,
value: TaggedValue::String(value.clone()),
value: Box::new(TaggedValue::String(value.clone())),
}
.into(),
]),
@@ -2214,13 +2219,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
NodeGraphMessage::SetInputValue {
node_id,
input_index: IndividualCornerRadiiInput::INDEX,
value: TaggedValue::Bool(false),
value: Box::new(TaggedValue::Bool(false)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: TaggedValue::F64(uniform_val),
value: Box::new(TaggedValue::F64(uniform_val)),
}
.into(),
]),
@@ -2234,13 +2239,13 @@ pub(crate) fn rectangle_properties(node_id: NodeId, context: &mut NodeProperties
NodeGraphMessage::SetInputValue {
node_id,
input_index: IndividualCornerRadiiInput::INDEX,
value: TaggedValue::Bool(true),
value: Box::new(TaggedValue::Bool(true)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: CornerRadiusInput::INDEX,
value: TaggedValue::F64Array(individual_val_for_switch.clone()),
value: Box::new(TaggedValue::F64Array(individual_val_for_switch.clone())),
}
.into(),
]),
@@ -2549,13 +2554,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::INDEX,
value: TaggedValue::Color(color),
value: Box::new(TaggedValue::Color(color)),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupColorInput::INDEX,
value: TaggedValue::Color(color),
value: Box::new(TaggedValue::Color(color)),
}
.into(),
]),
@@ -2566,13 +2571,13 @@ pub(crate) fn fill_properties(node_id: NodeId, context: &mut NodePropertiesConte
NodeGraphMessage::SetInputValue {
node_id,
input_index: FillInput::INDEX,
value: TaggedValue::Gradient(gradient.clone()),
value: Box::new(TaggedValue::Gradient(gradient.clone())),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: BackupGradientInput::INDEX,
value: TaggedValue::Gradient(gradient),
value: Box::new(TaggedValue::Gradient(gradient)),
}
.into(),
]),
@@ -106,12 +106,10 @@ fn overlay_bezier_handle_specific_point(
let not_under_anchor = |position: DVec2, anchor: DVec2| position.distance_squared(anchor) >= HIDE_HANDLE_DISTANCE * HIDE_HANDLE_DISTANCE;
match bezier.handles {
BezierHandles::Quadratic { handle } => {
if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) {
let end = if start == point_to_render { bezier.start } else { bezier.end };
overlay_context.line(handle, end, None, None);
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
}
BezierHandles::Quadratic { handle } if not_under_anchor(handle, bezier.start) && not_under_anchor(handle, bezier.end) => {
let end = if start == point_to_render { bezier.start } else { bezier.end };
overlay_context.line(handle, end, None, None);
overlay_context.manipulator_handle(handle, is_selected(ManipulatorPointId::PrimaryHandle(segment_id)), None);
}
BezierHandles::Cubic { handle_start, handle_end } => {
if not_under_anchor(handle_start, bezier.start) && (point_to_render == start) {
@@ -2729,12 +2729,12 @@ impl NodeNetworkInterface {
DocumentNodeClickTargets {
node_click_target,
port_click_targets,
node_type_metadata: NodeTypeClickTargets::Layer(LayerClickTargets {
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
visibility_click_target,
lock_click_target,
grip_click_target,
name_click_target,
}),
})),
}
};
@@ -5311,7 +5311,7 @@ impl NodeNetworkInterface {
})
.collect::<Vec<(NodeId, i32)>>();
node_ids_with_position.sort_unstable_by(|a, b| a.1.cmp(&b.1));
node_ids_with_position.sort_unstable_by_key(|entry| entry.1);
Some(node_ids_with_position.into_iter().map(|(node_id, _)| node_id).collect::<Vec<_>>())
}
@@ -6953,7 +6953,7 @@ pub struct LayerTransientMetadata {
#[derive(Debug, Clone)]
pub enum NodeTypeClickTargets {
Layer(LayerClickTargets),
Layer(Box<LayerClickTargets>),
Node, // No transient click targets are stored exclusively for nodes
}
@@ -1024,12 +1024,6 @@ 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") {
@@ -1051,12 +1045,6 @@ 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
}
@@ -2616,10 +2604,12 @@ mod tests {
use super::*;
#[test]
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"]);
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"}}}"#
));
}
#[test]
@@ -52,7 +52,7 @@ pub enum PortfolioMessage {
reopened: bool,
#[serde(skip, default)]
#[derivative(Debug = "ignore", PartialEq = "ignore", Clone(clone_with = "clone_to_none"))]
gdd: Option<document_format::GddV1>,
gdd: Option<Box<document_format::GddV1>>,
},
DestroyAllDocuments,
EditorPreferences,
@@ -305,7 +305,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Document was closed before its working copy finished mounting.
return;
};
document.set_storage(gdd);
document.set_storage(gdd.map(|gdd| *gdd));
if !reopened {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.retire_storage_interaction();
@@ -1914,7 +1914,7 @@ impl PortfolioMessageHandler {
Message::Portfolio(PortfolioMessage::DocumentStorageMounted {
document_id,
reopened,
gdd: Some(gdd),
gdd: Some(Box::new(gdd)),
})
};
future.into()
@@ -69,6 +69,8 @@ impl SpiralTurns {
self.handle_state == SpiralTurnsState::Dragging
}
// Records one snapshot of the spiral's parameters; grouping them would only move the same fields into a struct
#[allow(clippy::too_many_arguments)]
pub fn store_initial_parameters(
&mut self,
layer: LayerNodeIdentifier,
@@ -613,7 +613,7 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
let input_index = graphene_std::vector::stroke::WeightInput::INDEX;
let value = TaggedValue::F64(weight);
let value = Box::new(TaggedValue::F64(weight));
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else if weight > 0. {
let color = Some(Color::BLACK);
@@ -825,7 +825,7 @@ pub fn set_stroke_color_for_selected_layers(color: Option<Color>, weight: f64, d
for layer in layers {
if let Some(node_id) = get_stroke_id(layer, &document.network_interface) {
let input_index = graphene_std::vector::stroke::PaintInput::INDEX;
let value = TaggedValue::Color(color);
let value = Box::new(TaggedValue::Color(color));
responses.add(NodeGraphMessage::SetInputValue { node_id, input_index, value });
} else {
let stroke = graphene_std::vector::style::Stroke::new(weight);
@@ -896,7 +896,7 @@ pub fn set_proto_node_input_for_selected_layers(
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index,
value: value.clone(),
value: Box::new(value.clone()),
});
}
}
@@ -88,11 +88,8 @@ impl ShapeType {
}
pub fn tooltip_description(&self) -> String {
(match self {
// TODO: Add descriptions to all the shape tools
_ => "",
})
.into()
// TODO: Add descriptions to all the shape tools
String::new()
}
pub fn icon_name(&self) -> String {
@@ -677,7 +677,6 @@ mod tests {
down: [10., 15.].map(|y| Rect::from_square(DVec2::new(0., y), 2.)).to_vec(),
left: [-12., -15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
right: [12., 15.].map(|x| Rect::from_square(DVec2::new(x, 0.), 2.)).to_vec(),
..Default::default()
};
let source = Rect::from_square(DVec2::new(0.3, 0.4), 2.);
let snap_results = &mut SnapResults::default();
@@ -2146,7 +2146,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_node_id,
input_index: 1,
value: TaggedValue::Gradient(GradientStops::new([
value: Box::new(TaggedValue::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2157,7 +2157,7 @@ mod test_gradient {
midpoint: 0.5,
color: Color::BLUE,
},
])),
]))),
})
.await;
@@ -2183,7 +2183,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_node_id,
input_index: 1,
value: TaggedValue::Gradient(GradientStops::new([
value: Box::new(TaggedValue::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2194,7 +2194,7 @@ mod test_gradient {
midpoint: 0.5,
color: Color::BLUE,
},
])),
]))),
})
.await;
@@ -2826,7 +2826,7 @@ mod test_gradient {
.handle_message(NodeGraphMessage::SetInputValue {
node_id: gradient_value_id,
input_index: 1,
value: TaggedValue::Gradient(GradientStops::new([
value: Box::new(TaggedValue::Gradient(GradientStops::new([
GradientStop {
position: 0.,
midpoint: 0.5,
@@ -2837,7 +2837,7 @@ mod test_gradient {
midpoint: 0.5,
color: Color::BLUE,
},
])),
]))),
})
.await;
@@ -118,7 +118,7 @@ fn create_text_widgets(tool: &TextTool, font_catalog: &FontCatalog, document: &D
NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::FontInput::INDEX,
value: TaggedValue::Resource(resource_id),
value: Box::new(TaggedValue::Resource(resource_id)),
}
.into(),
]),
@@ -349,7 +349,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::SizeInput::INDEX,
value: TaggedValue::F64(font_size),
value: Box::new(TaggedValue::F64(font_size)),
});
}
}
@@ -364,7 +364,7 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Text
responses.add(NodeGraphMessage::SetInputValue {
node_id,
input_index: graphene_std::text::text::AlignInput::INDEX,
value: TaggedValue::TextAlign(align),
value: Box::new(TaggedValue::TextAlign(align)),
});
}
}
+2 -2
View File
@@ -47,7 +47,7 @@ pub struct CompilationResponse {
}
pub enum NodeGraphUpdate {
ExecutionResponse(ExecutionResponse),
ExecutionResponse(Box<ExecutionResponse>),
CompilationResponse(CompilationResponse),
EyedropperPreview(Raster<CPU>),
NodeGraphUpdateMessage(NodeGraphUpdateMessage),
@@ -368,7 +368,7 @@ impl NodeGraphExecutor {
responses: existing_responses,
vector_modify,
inspect_result,
} = execution_response;
} = *execution_response;
while let Some(&(queued_execution_id, _)) = self.futures.front() {
if queued_execution_id < execution_id {
+1 -1
View File
@@ -104,7 +104,7 @@ impl InternalNodeGraphUpdateSender {
}
fn send_execution_response(&self, response: ExecutionResponse) {
self.0.send(NodeGraphUpdate::ExecutionResponse(response)).expect("Failed to send response")
self.0.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response")
}
fn send_eyedropper_preview(&self, raster: Raster<CPU>) {
@@ -20,7 +20,9 @@ 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();
proto_network
.compute_layouts()
.map_err(|errors| errors.iter().map(|error| format!("{:?}", error.error)).collect::<Vec<_>>().join("\n"))?;
proto_network.generate_stable_node_ids();
Ok(proto_network)
})
+122 -1
View File
@@ -378,7 +378,9 @@ impl ProtoNetwork {
Ok(())
}
pub fn compute_layouts(&mut self) {
pub fn compute_layouts(&mut self) -> Result<(), GraphErrors> {
self.fold_attribute_names()?;
let mut errors = GraphErrors::new();
for index in 0..self.nodes.len() {
let lane_invariant = self.nodes[index].1.lane_invariant_inputs;
let layout = {
@@ -388,6 +390,9 @@ 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| {
@@ -395,6 +400,10 @@ 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)
@@ -412,6 +421,79 @@ 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
@@ -737,9 +819,47 @@ 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>,
@@ -764,6 +884,7 @@ 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"),
@@ -193,9 +193,7 @@ 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)
}
@@ -721,7 +719,7 @@ mod test {
fn build_executor(mut network: ProtoNetwork) -> DynamicExecutor {
network.resolve_types(&node_registry::NODE_REGISTRY).unwrap();
network.compute_layouts();
network.compute_layouts().unwrap();
DynamicExecutor::new(network).unwrap()
}
@@ -737,6 +735,193 @@ 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, SourceHandle, NodeIOTypes, RegistryEntry};
use graphene_std::registry::{ConstructionError, NodeIOTypes, RegistryEntry, SourceHandle};
#[cfg(feature = "gpu")]
use graphene_std::runtime::RuntimeHandle;
@@ -227,7 +227,9 @@ 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>
))
},
},
)
+10 -2
View File
@@ -251,7 +251,12 @@ impl Arena {
// 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.
@@ -772,7 +777,10 @@ 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");
@@ -155,6 +155,278 @@ 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(self, _: &$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 {
@@ -342,7 +342,6 @@ impl AttributeDyn {
pub fn is_empty(&self) -> bool {
self.0.len() == 0
}
}
impl Clone for AttributeDyn {
@@ -136,7 +136,6 @@ 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.
@@ -114,6 +114,29 @@ 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
@@ -366,6 +366,76 @@ 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
@@ -387,6 +457,19 @@ 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,
@@ -423,6 +506,10 @@ 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,
@@ -467,13 +554,66 @@ 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
@@ -21,12 +21,12 @@ mod serve;
mod test_support;
mod testkit;
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 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 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, 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, NamedRead, NamedWrite,
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 promote::{Promotion, assert_promoted, register_element_promote, register_field_promote, register_retained_heap};
@@ -57,10 +57,7 @@ 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 });
}
@@ -278,6 +278,9 @@ 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)
}
@@ -500,12 +500,7 @@ 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.
@@ -522,7 +517,9 @@ 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
@@ -533,7 +530,9 @@ 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>>(),
@@ -555,8 +554,14 @@ 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();
@@ -588,7 +593,11 @@ 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]
@@ -610,8 +619,14 @@ 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);
@@ -15,6 +15,13 @@ 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;
@@ -47,7 +47,7 @@ impl MergeByDistanceExt for Vector {
// Collect points and segments to delete at the end to avoid invalidating indices
let mut points_to_delete = FxHashSet::default();
let mut segments_to_delete = FxHashSet::default();
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position.into_iter()) {
for (mut collapse_set, average_pos) in collapse.into_iter().zip(average_position) {
// Remove any segments where both endpoints are in the collapse set
segments_to_delete.extend(self.segment_domain.iter().filter_map(|(id, start_offset, end_offset, _)| {
let start = self.point_domain.ids()[start_offset];
+98 -14
View File
@@ -240,6 +240,18 @@ 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)
@@ -796,7 +808,9 @@ 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()),
_ => None,
// 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),
};
// 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();
@@ -980,6 +994,11 @@ 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 {
@@ -1088,7 +1107,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)| !injected_name(&field.pat_ident.ident)).map(|(index, field)| {
let kernel_params = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).map(|(index, field)| {
let pat = &field.pat_ident;
match &field.ty {
ParsedFieldType::Regular(RegularParsedField { ty, .. }) if ir::materialized_levels(&node, index) > 0 => {
@@ -1239,7 +1258,15 @@ 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) };
}
@@ -1517,7 +1544,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)| !injected_name(&field.pat_ident.ident)).map(|(index, field)| {
let call_args = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).map(|(index, field)| {
let name = &field.pat_ident.ident;
match &field.ty {
// A lend param binds an owned input; the kernel borrows the
@@ -1719,13 +1746,15 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
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)| !injected_name(&field.pat_ident.ident)).collect();
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();
// 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)))
@@ -2010,7 +2039,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 }).map(|field| {
let value_args = regular_fields.iter().skip(if skips_carrier { 0 } else { 1 }).filter(|field| !kernel_omits(field)).map(|field| {
let name = &field.pat_ident.ident;
match &field.ty {
// A lend param binds an owned input; the kernel borrows the
@@ -2517,15 +2546,50 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
self.__layout = __resolved.layout;
})
} else if record_io {
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");
}
});
// 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 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
@@ -2565,7 +2629,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! {
@@ -2581,8 +2645,11 @@ 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
@@ -2619,7 +2686,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
@@ -2646,6 +2713,12 @@ 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(),
@@ -2664,6 +2737,16 @@ 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}");
@@ -2710,6 +2793,7 @@ 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)*
@@ -266,6 +266,36 @@ 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());
@@ -362,6 +392,13 @@ 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;
+22 -7
View File
@@ -157,7 +157,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);
let layout_meta = crate::codegen::ir::layout_meta_tokens(&node, element_spec, &core_types, &assignments);
Some(quote! {
gcore::registry::RegistryEntry {
layout_meta: Some(#layout_meta),
@@ -397,7 +397,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,7 +432,25 @@ 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);
(quote!(), quote!(#carrier_arg #(#value_layout_args)*), quote!(Some(self::#layout_meta_fn())))
// 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)
}
ir::NodeKind::Routing => {
let source_layouts = base_indices.iter().map(|index| format_ident!("__layout_{index}"));
@@ -641,10 +659,7 @@ mod tests {
.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}"
);
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}");
+236 -1
View File
@@ -67,6 +67,10 @@ 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()
@@ -261,7 +265,10 @@ 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.
pub(crate) fn layout_meta_tokens(node: &Node, element_spec: TokenStream2, core_types: &TokenStream2) -> TokenStream2 {
/// `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 {
let sources = layout_sources(node).into_iter().map(|index| index as u8);
let reads = node
.inputs
@@ -274,6 +281,8 @@ 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;
@@ -290,6 +299,10 @@ 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,
@@ -354,6 +367,7 @@ 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;
@@ -362,6 +376,102 @@ 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.
@@ -527,6 +637,10 @@ 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.
@@ -739,6 +853,127 @@ 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(
+59
View File
@@ -110,6 +110,42 @@ 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()?;
@@ -222,6 +258,9 @@ pub struct ParsedField {
pub(crate) attribute_reads: Vec<AttributeRead>,
}
// Both variants are large parsed-syntax payloads (888/672 bytes), so boxing one still leaves the other large while forcing a
// deref on every pattern match across codegen; this is built once per node at compile time, never on a hot path
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug)]
pub enum ParsedFieldType {
Regular(RegularParsedField),
@@ -333,6 +372,10 @@ 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.
@@ -1231,9 +1274,18 @@ 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,
@@ -1356,6 +1408,7 @@ impl ParsedNodeFn {
widget_override: ParsedWidgetOverride::Hidden,
ty: ParsedFieldType::Regular(RegularParsedField {
ty,
name_source: None,
list_levels: 0,
lend: None,
exposed: false,
@@ -1533,6 +1586,7 @@ 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),
@@ -1631,6 +1685,7 @@ 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),
@@ -1710,6 +1765,7 @@ 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),
@@ -1787,6 +1843,7 @@ 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),
@@ -1876,6 +1933,7 @@ 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),
@@ -1968,6 +2026,7 @@ 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,6 +232,7 @@ 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,
+20 -4
View File
@@ -127,12 +127,22 @@ 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) => {
if !matches!(crate::codegen::bare_ident(element), Some(ident) if ident == 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) {
emit_error!(parsed.output_type.span(), "a generic element passes through unchanged: return `{}` in the first tuple position", token);
}
}
@@ -164,7 +174,10 @@ 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) {
@@ -424,13 +437,16 @@ 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.is_some() && (ident == routing.as_ref().map(|routing| &routing.generic) || ident == record_token.as_ref() || ident == opaque_reading.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::{SourceHandle, ErasedRecordNode};
use core_types::registry::{ErasedRecordNode, SourceHandle};
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>>
+71 -12
View File
@@ -662,6 +662,9 @@ 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)
};
@@ -671,6 +674,9 @@ 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(),
@@ -764,6 +770,10 @@ 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,
@@ -800,6 +810,10 @@ 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,
@@ -844,6 +858,10 @@ 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,
@@ -894,6 +912,10 @@ 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,
@@ -992,6 +1014,10 @@ 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,
@@ -1060,6 +1086,10 @@ 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,
@@ -1134,6 +1164,10 @@ 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,
@@ -1178,6 +1212,10 @@ 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,
@@ -1187,6 +1225,10 @@ 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,
@@ -1262,6 +1304,10 @@ 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,
@@ -1315,6 +1361,10 @@ 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,
@@ -1531,6 +1581,9 @@ 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)])
};
@@ -1609,6 +1662,10 @@ 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,
@@ -1662,6 +1719,10 @@ 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,
@@ -1772,6 +1833,10 @@ 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,
@@ -1898,6 +1963,10 @@ 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,
@@ -2443,13 +2512,7 @@ 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)],
);
@@ -2482,11 +2545,7 @@ 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 {
+69 -1
View File
@@ -1,4 +1,4 @@
use core_types::attribute::{Attr, EditorLayerPath, Transform as TransformAttr};
use core_types::attribute::{Attr, EditorLayerPath, Name0, Named, Transform as TransformAttr, WireValue};
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::extent::{ExtentIn, LevelIn, ListIn, ValueIn};
use core_types::gpoll::{Extent, GPoll, GraphError, Interrupt, Level};
@@ -11,6 +11,7 @@ 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,
@@ -368,6 +369,73 @@ 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<T>(
_: impl Ctx,
/// The content whose lanes carry the attribute; its element is never read.
(content, value): (T, Attr<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>(
+10
View File
@@ -285,6 +285,9 @@ 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)
};
@@ -294,6 +297,9 @@ 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(),
@@ -420,6 +426,10 @@ 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,
@@ -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;
use core_types::{Color, Ctx};
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
pub use graph_craft::application_io::*;
+3
View File
@@ -272,6 +272,9 @@ 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,6 +1053,9 @@ 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(),
@@ -1114,6 +1117,9 @@ 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(),
@@ -1160,6 +1166,9 @@ 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(),
@@ -950,6 +950,8 @@ fn selective_color<T: Adjust<Color> + Clone + Send + Sync + no_std_types::contex
(SelectiveColorChoice::Blacks, (k_c, k_m, k_y, k_k)),
];
let mut sum = Vec3::ZERO;
// Indexed rather than iterated because this compiles to SPIR-V, whose backend rejects the arbitrary pointer offset an array iterator produces
#[allow(clippy::needless_range_loop)]
for i in 0..array.len() {
let (color_parameter_group, (c, m, y, k)) = array[i];
@@ -63,6 +63,8 @@ impl CubicSplines {
assert!(augmented_matrix[row][row].abs() > f32::EPSILON);
let scale_factor = augmented_matrix[row_below_current][row] / augmented_matrix[row][row];
// `col` indexes two distinct rows at once, one of them mutably, so an iterator would need a split borrow
#[allow(clippy::needless_range_loop)]
for col in row..5 {
augmented_matrix[row_below_current][col] -= augmented_matrix[row][col] * scale_factor
}
+58 -58
View File
@@ -29,76 +29,76 @@ pub fn message_handler_data_attr_impl(attr: TokenStream, input_item: TokenStream
if segment.ident != "MessageHandler" {
return Err(syn::Error::new(segment.ident.span(), "Expected MessageHandler trait"));
}
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
if args.args.len() >= 2 {
// Extract the message type (M) and context struct type (C) from the trait params
let message_type = &args.args[0];
let data_type = &args.args[1];
if let syn::PathArguments::AngleBracketed(args) = &segment.arguments
&& args.args.len() >= 2
{
// Extract the message type (M) and context struct type (C) from the trait params
let message_type = &args.args[0];
let data_type = &args.args[1];
let impl_item = match data_type {
syn::GenericArgument::Type(t) => {
match t {
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
// Get just the base identifier (ToolMessageData) without generics
let type_name = &type_path.path.segments.first().unwrap().ident;
let impl_item = match data_type {
syn::GenericArgument::Type(t) => {
match t {
syn::Type::Path(type_path) if !type_path.path.segments.is_empty() => {
// Get just the base identifier (ToolMessageData) without generics
let type_name = &type_path.path.segments.first().unwrap().ident;
let handler_data_line_number = type_name.span().start().line;
let handler_data_line_number = type_name.span().start().line;
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
syn::Type::Tuple(_) => quote! {
quote! {
#input_item
impl #message_type {
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#type_name)), #type_name::field_types(), #type_name::path(), #type_name::line_number())
}
},
syn::Type::Reference(type_reference) => {
let message_type = call_site_ident(format!("{input_type}Message"));
let type_ident = match &*type_reference.elem {
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
};
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
let type_line_number = type_ident.span().start().line;
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
}
}
syn::Type::Tuple(_) => quote! {
#input_item
impl #message_type {
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
},
syn::Type::Reference(type_reference) => {
let message_type = call_site_ident(format!("{input_type}Message"));
let type_ident = match &*type_reference.elem {
syn::Type::Path(type_path) => &type_path.path.segments.first().unwrap().ident,
_ => return Err(syn::Error::new(type_reference.elem.span(), "Expected type path")),
};
_ => quote! {
#input_item
},
};
return Ok(impl_item);
}
let type_line_number = type_ident.span().start().line;
let tr = clean_rust_type_syntax(type_reference.to_token_stream().to_string());
quote! {
#input_item
impl #message_type {
pub fn message_handler_data_str() -> MessageData {
MessageData::new(format!("{}", #tr), #type_ident::field_types(), #type_ident::path(), #type_ident::line_number())
}
pub fn message_handler_str() -> MessageData {
MessageData::new(format!("{}", stringify!(#input_type)), #input_type::field_types(), #input_type::path(), #input_type::line_number())
}
}
}
}
_ => return Err(syn::Error::new(t.span(), "Unsupported type format")),
}
}
_ => quote! {
#input_item
},
};
return Ok(impl_item);
}
}
Ok(input_item)
+4 -1
View File
@@ -249,6 +249,9 @@ fn dot_to_svg(dot: &str) -> Result<String> {
String::from_utf8(output.stdout).with_context(|| "SVG output was not valid UTF-8")
}
/// A subgraph cluster's id, label, fill color, and the predicate picking its crates.
type Cluster<'a> = (&'a str, &'a str, &'a str, Box<dyn Fn(&CrateInfo) -> bool>);
fn generate_dot(crates: &[CrateInfo]) -> String {
let mut out = String::new();
out.push_str("digraph CrateHierarchy {\n");
@@ -257,7 +260,7 @@ fn generate_dot(crates: &[CrateInfo]) -> String {
out.push_str(" edge [color=gray];\n\n");
// Define subgraph clusters
let clusters: &[(&str, &str, &str, Box<dyn Fn(&CrateInfo) -> bool>)] = &[
let clusters: &[Cluster] = &[
(
"cluster_core",
"Core Components",