mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a4288eca6 | ||
|
|
5baeb8fd46 | ||
|
|
f04d439b33 | ||
|
|
6e22d6a412 | ||
|
|
5eb80721dd | ||
|
|
fc94487d0b | ||
|
|
37c0d0852d | ||
|
|
9b92edc0e9 | ||
|
|
348e9022a6 | ||
|
|
0001cdf04d | ||
|
|
c2845def11 | ||
|
|
b8bd9499fc | ||
|
|
e92ced1e4a | ||
|
|
e322d8957d | ||
|
|
296185b7fc | ||
|
|
b321c094d2 | ||
|
|
d4768d606f | ||
|
|
148008c695 | ||
|
|
2b5845464c | ||
|
|
5e388cb38f | ||
|
|
49daf2895e | ||
|
|
682d3dafbd | ||
|
|
ad03b5b0bf | ||
|
|
324925aedb | ||
|
|
e78a987e3e | ||
|
|
2c8fa44eb4 | ||
|
|
6b22316077 | ||
|
|
98cabee4c6 | ||
|
|
e0848abc59 | ||
|
|
f237a5ee50 | ||
|
|
df99ab3a72 | ||
|
|
0fc4424a09 | ||
|
|
e9a3199456 | ||
|
|
ef8312806d | ||
|
|
548cbfbf4e | ||
|
|
313c591f70 | ||
|
|
f07f708ee8 | ||
|
|
5f73044b6b | ||
|
|
11aedd8196 | ||
|
|
f4f266b1ba | ||
|
|
77e4e8c894 | ||
|
|
c231bd0eb8 | ||
|
|
095e0bb4ff | ||
|
|
369f7db992 | ||
|
|
79750fb52d | ||
|
|
f7360688f2 | ||
|
|
00920823aa | ||
|
|
0426a01e82 | ||
|
|
02f9cf3e6b | ||
|
|
33f7257e47 | ||
|
|
2921f44e5c | ||
|
|
1e91511f93 | ||
|
|
daf0231c0c | ||
|
|
92adc524ca | ||
|
|
9f0e0ebc96 | ||
|
|
a911bcc165 | ||
|
|
5bedfa4d11 | ||
|
|
e52af0cee0 | ||
|
|
fbdba0e545 | ||
|
|
6cdab6b95d | ||
|
|
e92faf763d | ||
|
|
305c36fb25 | ||
|
|
fc9e69a7a7 | ||
|
|
c9525d76c4 | ||
|
|
451922c217 | ||
|
|
92ea594a2a |
No files matched your search
@@ -20,9 +20,7 @@ pub fn load_demo(file_name: &str) -> DocumentMessageHandler {
|
||||
DocumentMessageHandler::deserialize_document(&content).unwrap_or_else(|e| panic!("Failed to deserialize {path}: {e:?}"))
|
||||
}
|
||||
|
||||
/// Dev tool for the flip: runs each demo through the full open-time migration and writes the
|
||||
/// re-saved form into the directory named by `DEMO_OUT`, so the CLI can render migrated copies
|
||||
/// while the checked-in originals stay pristine until the flip's re-save.
|
||||
/// Dev tool: writes each demo's migrated re-save into the directory named by `DEMO_OUT`, leaving the checked-in originals untouched.
|
||||
#[test]
|
||||
#[ignore = "dev tool: set DEMO_OUT and run explicitly"]
|
||||
fn migrate_demo_artwork_into_demo_out() {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -1433,6 +1421,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Rebuild stale Rasterize subgraphs from before the async-source conversion gave the inner proto node a unit primary input (5 inputs, now 6).
|
||||
if let DocumentNodeImplementation::Network(inner) = &node.implementation
|
||||
&& inner
|
||||
.nodes
|
||||
.values()
|
||||
.any(|n| n.inputs.len() == 5 && matches!(&n.implementation, DocumentNodeImplementation::ProtoNode(id) if id.as_str().contains("rasterize")))
|
||||
&& document.network_interface.reference(node_id, network_path) == Some(DefinitionIdentifier::Network("Rasterize".into()))
|
||||
&& let Some(node_definition) = resolve_document_node_type(&DefinitionIdentifier::Network("Rasterize".into()))
|
||||
{
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_definition.default_node_template());
|
||||
}
|
||||
|
||||
// Upgrade old nodes to use `Context` instead of `()` or `Footprint` as their call argument
|
||||
if node.call_argument == graph_craft::concrete!(()) || node.call_argument == graph_craft::concrete!(graphene_std::transform::Footprint) {
|
||||
document.network_interface.set_call_argument(node_id, network_path, graph_craft::concrete!(graphene_std::Context));
|
||||
@@ -2604,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]
|
||||
|
||||
@@ -576,7 +576,7 @@ mod test_artboard {
|
||||
|
||||
/// A leveled wire introspects as its whole legacy list, so each `extend`
|
||||
/// occurrence yields one list rather than one element.
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard> {
|
||||
async fn get_artboards(editor: &mut EditorTestUtils) -> List<Artboard<'_>> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
|
||||
@@ -208,8 +208,7 @@ mod test_fill {
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
/// Paint inputs are single-typed now, so the monitored wire carries the
|
||||
/// colors themselves and the `Graphic` conversion sits downstream of it.
|
||||
/// The monitored fill wire carries `Color`; the `Graphic` conversion sits downstream of the monitor.
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Color> {
|
||||
let instrumented = match editor.eval_graph().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
|
||||
@@ -179,6 +179,8 @@ impl Spawner for WasmSpawner {
|
||||
impl NodeRuntime {
|
||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>) -> Self {
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
// The box is a trait object, so `Box::default()` cannot name the concrete spawner.
|
||||
#[allow(clippy::box_default)]
|
||||
let spawner: Box<DynSpawner> = Box::new(TokioSpawner::new());
|
||||
#[cfg(target_family = "wasm")]
|
||||
let spawner: Box<DynSpawner> = Box::new(WasmSpawner);
|
||||
@@ -500,7 +502,9 @@ impl NodeRuntime {
|
||||
// Graphic run: thumbnail (text-aware bounds, since the `BoundingBox` trait can't lay out `Graphic::Text` content)
|
||||
if type_id == std::any::TypeId::of::<Graphic>() {
|
||||
if update_thumbnails {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let bounds = graphene_std::renderer::graphic_list_bounding_box(&RunView::<Graphic>::new(&item)?, DAffine2::IDENTITY);
|
||||
let group = Graphic::Group(Group { row: None, content: item });
|
||||
@@ -512,7 +516,9 @@ impl NodeRuntime {
|
||||
// clips content to those rectangles so anything outside isn't visible
|
||||
else if type_id == std::any::TypeId::of::<Artboard>() {
|
||||
if update_thumbnails {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<Artboard>::new(&item)?;
|
||||
let bounds = artboard_clip_bounds(&run);
|
||||
@@ -522,7 +528,9 @@ impl NodeRuntime {
|
||||
}
|
||||
// Vector run: vector modifications
|
||||
else if type_id == std::any::TypeId::of::<Vector>() {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<Vector>::new(&item)?;
|
||||
use graphene_std::core_types::lane::LaneSource;
|
||||
@@ -532,7 +540,9 @@ impl NodeRuntime {
|
||||
// String run: thumbnail (bounds need text layout, which the `BoundingBox` trait can't do for a bare `String`)
|
||||
else if type_id == std::any::TypeId::of::<String>() {
|
||||
if update_thumbnails {
|
||||
// SAFETY: the batch is resident for the read.
|
||||
// SAFETY: `introspect_with`'s closure is higher-ranked over the batch's
|
||||
// lifetime, so the item cannot escape this read window, which the
|
||||
// frames outlive.
|
||||
let item = unsafe { GroupItem::from_resident(batch) };
|
||||
let run = RunView::<String>::new(&item)?;
|
||||
let bounds = graphene_std::renderer::text_list_bounding_box(&run, DAffine2::IDENTITY);
|
||||
@@ -544,10 +554,10 @@ impl NodeRuntime {
|
||||
Some(())
|
||||
}
|
||||
});
|
||||
if result.is_err() {
|
||||
if let Err(_error) = result {
|
||||
// TODO: Fix the root of the issue causing the spam of this warning (this at least temporarily disables it in release builds)
|
||||
#[cfg(debug_assertions)]
|
||||
warn!("Failed to introspect monitor node {}", result.unwrap_err());
|
||||
warn!("Failed to introspect monitor node {}", _error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+119
-131
@@ -1,173 +1,161 @@
|
||||
# Creating Nodes In Graphite
|
||||
# The Graphite Node Graph
|
||||
|
||||
## Purpose of Nodes
|
||||
Graphite is a node based image editor. Everything it renders comes from evaluating a graph of nodes, and this directory holds that system: the types nodes are built on, the node library, the macro that turns a plain Rust function into a node, and the compiler and executor that turn a saved document into a running graph.
|
||||
|
||||
Graphite is an image editor which is centered around a node based editing workflow, which allows operations to be visually connected in a graph. This is flexible as it allows all operations to be viewed or modified at any time without losing original data. The node system has been designed to be as general as possible with all data types being representable and a broad selection of nodes for a variety of use cases being planned.
|
||||
This is an orientation document, not a specification. It says what lives where and what the vocabulary means. The code is the ground truth, and the module level `//!` headers under `libraries/core-types/src/` carry the real design detail.
|
||||
|
||||
## The Document Graph
|
||||
## Crate map
|
||||
|
||||
The graph that is presented to users in the editor is known as the document graph, and is defined in the `NodeNetwork` struct. Each node that has been placed in this graph has the following properties:
|
||||
Foundations, in `libraries/`:
|
||||
|
||||
```rs
|
||||
pub struct DocumentNode {
|
||||
pub inputs: Vec<NodeInput>,
|
||||
pub call_argument: Type,
|
||||
pub implementation: DocumentNodeImplementation,
|
||||
pub skip_deduplication: bool,
|
||||
pub visible: bool,
|
||||
pub original_location: OriginalLocation,
|
||||
}
|
||||
```
|
||||
(Explanatory comments omitted; the actual definition is currently found in [`node-graph/graph-craft/src/document.rs`](https://github.com/GraphiteEditor/Graphite/blob/master/node-graph/graph-craft/src/document.rs))
|
||||
| Crate | Directory | What it is |
|
||||
| --- | --- | --- |
|
||||
| `core-types` | `libraries/core-types` | The `Node` trait, records, attributes, the arena, contexts, and the node registry. Everything else sits on it. |
|
||||
| `no-std-types` | `libraries/no-std-types` | `no_std` primitives shared with the GPU shader crates: color, blending, choice types. |
|
||||
| `graphene-hash` | `libraries/graphene-hash` | `CacheHash`, which hashes floats by bit pattern so cache keys stay stable. |
|
||||
| `graphic-types` | `libraries/graphic-types` | Document element types: `Graphic`, `Vector`, `Artboard`, and their attribute markers. |
|
||||
| `raster-types` | `libraries/raster-types` | `Image`, `Raster<CPU>` and `Raster<GPU>`, `Texture`, and the pixel traits. |
|
||||
| `vector-types` | `libraries/vector-types` | Vector geometry: `Vector`, subpaths, point and segment domains, gradients, styles. |
|
||||
| `rendering` | `libraries/rendering` | The `Render` trait and the SVG and Vello backends. |
|
||||
| `graphene-application-io` | `libraries/application-io` | Traits for reaching the host: GPU access, resource loading, `EditorApi`. |
|
||||
| `graphene-resource` | `libraries/resources` | Content addressed binary blobs and their async loading. |
|
||||
| `graphene-canvas-utils` | `libraries/canvas-utils` | HTML canvas helpers, and nothing at all off wasm. |
|
||||
| `wgpu-executor` | `libraries/wgpu-executor` | The GPU backend: wgpu context, pipeline and texture caches, the Vello renderer. |
|
||||
|
||||
Each `DocumentNode` is of a particular type, for example the "Opacity" node type. You can define your own type of document node in `editor/src/messages/portfolio/document/node_graph/node_graph_message_handler/document_node_types.rs`. A sample document node type definition for the opacity node is shown:
|
||||
The node library, in `nodes/`:
|
||||
|
||||
```rs
|
||||
DocumentNodeDefinition {
|
||||
name: "Opacity",
|
||||
category: "Image Adjustments",
|
||||
implementation: DocumentNodeImplementation::proto("graphene_core::raster::OpacityNode"),
|
||||
inputs: vec![
|
||||
DocumentInputType::value("Image", TaggedValue::ImageFrame(ImageFrame::empty()), true),
|
||||
DocumentInputType::value("Factor", TaggedValue::F32(100.), false),
|
||||
],
|
||||
outputs: vec![DocumentOutputType::new("Image", FrontendGraphDataType::Raster)],
|
||||
properties: node_properties::multiply_opacity,
|
||||
..Default::default()
|
||||
},
|
||||
```
|
||||
| Crate | Directory | What it is |
|
||||
| --- | --- | --- |
|
||||
| `graphene-core` | `nodes/gcore` | Core nodes: arithmetic, context modification, memoization, animation, and the pilot record nodes. |
|
||||
| `graphene-std` | `nodes/gstd` | The standard library. Re-exports every other node crate and adds the render pipeline, text, and platform IO nodes. |
|
||||
| `blending-nodes` | `nodes/blending` | Blend mode, opacity, and fill. |
|
||||
| `brush-nodes` | `nodes/brush` | Brush strokes, stamping, and brush rendering. |
|
||||
| `graphic-nodes` | `nodes/graphic` | Grouping and artboard construction over `Graphic`. |
|
||||
| `math-nodes` | `nodes/math` | The expression parser node plus arithmetic, random, and vector math. |
|
||||
| `path-bool-nodes` | `nodes/path-bool` | Boolean path operations on vector geometry. |
|
||||
| `raster-nodes` | `nodes/raster` | Color adjustments, blending, and filters. Written `no_std` capable so the kernels double as GPU shaders. |
|
||||
| `repeat-nodes` | `nodes/repeat` | Grid, linear, and circular repeats. |
|
||||
| `text-nodes` | `nodes/text` | Font loading, glyph shaping, text to path, and string operations. |
|
||||
| `transform-nodes` | `nodes/transform` | Translation, rotation, scale, skew, and footprint aware transforms. |
|
||||
| `vector-nodes` | `nodes/vector` | Shape generators, path operations, and vector modification. |
|
||||
|
||||
The identifier here must be the same as that of the proto-node which will be discussed soon (usually the path to the node implementation).
|
||||
Compiler and runtime:
|
||||
|
||||
> [!NOTE]
|
||||
> Nodes defined in `graphene_core` are re-exported by `graphene_std`. However if the strings for the type names do not match exactly then you will encounter an error.
|
||||
| Crate | Directory | What it is |
|
||||
| --- | --- | --- |
|
||||
| `graph-craft` | `graph-craft` | The document graph and its lowering: `NodeNetwork` and `DocumentNode` down to `ProtoNetwork`, plus type inference. |
|
||||
| `preprocessor` | `preprocessor` | The pass over a freshly loaded document: expands proto nodes into their definitions, injects scopes, resolves resource inputs. |
|
||||
| `interpreted-executor` | `interpreted-executor` | The dynamic executor. Instantiates a `ProtoNetwork` into a tree of boxed nodes and evaluates it. |
|
||||
| `node-macro` | `node-macro` | `#[node]` and friends. Generates the node struct, its `Node` impl, the registry entries, and the editor metadata. |
|
||||
| `graphene-cli` | `graphene-cli` | Headless CLI: load a document, compile it, run it, export the result. |
|
||||
|
||||
## Properties panel
|
||||
## Core concepts
|
||||
|
||||
The input names are shown in the graph when an input is exposed (with a dot in the properties panel). The default input is used when a node is first created or when a link is disconnected. An input is comprised from a `TaggedValue` (allowing serialization of a dynamic type with serde) in addition to an exposed boolean, which defines if the input is shown as a dot in the node graph UI by default. In the opacity node, the "Color" input is shown but the "Factor" input is hidden from the graph by default, allowing for a less cluttered graph.
|
||||
### Nodes
|
||||
|
||||
The properties field is a function that defines a number input, which can be seen by selecting the opacity node in the graph. The code for this property is shown below:
|
||||
`Node` lives in `libraries/core-types/src/node.rs` and has exactly one required method, `serve`. A node serves its output record through a frame claim its caller hands it, and returns a proof that only the claim's own closing methods can mint, so a served record is of the claimed layout by construction rather than by convention. Each node claims its frame out of the free space its caller left, so the frame space divides without bookkeeping.
|
||||
|
||||
```rs
|
||||
pub fn multiply_opacity(document_node: &DocumentNode, node_id: NodeId, _context: &mut NodePropertiesContext) -> Vec<LayoutGroup> {
|
||||
let factor = number_widget(document_node, node_id, 1, "Factor", NumberInput::default().min(0.).max(100.).unit("%"), true);
|
||||
Everything else on the trait has a default. `extent_at` and `extent` report how many items the node produces at a nesting level, `layout` reports the record layout, and `eval_batch` serves a whole range at once. The default `eval_batch` advertises no support and drivers fall back to per lane serves with copy out, so an override exists to beat that loop and never for correctness.
|
||||
|
||||
vec![LayoutGroup::Row { widgets: factor }]
|
||||
Kernels written with the macro do not see `serve`. They receive typed inputs and call `eval` on them, and the generated code handles the claim, the protocol, and status folding.
|
||||
|
||||
### Records
|
||||
|
||||
A record is what flows between nodes: the element at offset 0 plus one field per attribute written upstream. Its `Layout` is computed at wiring time from the upstream write set and is never serialized. Records of inline layouts live in the `RecordValue` itself, and larger ones live as per lane views on the evaluation's `Frames`, which the root owns and every node claims its own frame out of. Only generated and wiring code touches offsets, so a safe kernel cannot misalign a field.
|
||||
|
||||
`libraries/core-types/src/record/` is split by abstraction level, and each module's `//!` header states its job:
|
||||
|
||||
| Module | Concern |
|
||||
| --- | --- |
|
||||
| `layout` | Wiring time shape facts: the layout a record takes and the writes it folds from. |
|
||||
| `access` | Raw typed access to a record at a wiring proven layout. |
|
||||
| `frames` | The evaluation's record frame storage. |
|
||||
| `serve` | The serving protocol: a node's own frame claim and the proof it closes with. |
|
||||
| `input` | Consumer side bindings onto a record input, and the drivers they run. |
|
||||
| `route` | Producer side routing: a source's translation into the union layout. |
|
||||
| `promote` | Transient to persistent promotion of records and their parked payloads. |
|
||||
| `owned` | The owned crossing: deep copies that outlive the evaluation their content borrowed. |
|
||||
| `run` | Runs and groups: many records of one layout, resident or owned. |
|
||||
| `testkit` | Law test scaffolding over the record tier. |
|
||||
|
||||
Two words are used precisely throughout. An input is the consumer side of a connection, and a source is the producer side. Neither is called a wire; that word belongs to the editor UI.
|
||||
|
||||
### Attributes
|
||||
|
||||
An attribute is a named, typed channel that rides along with an element. A marker declares the name once, fixing its value type and its name specific default, and a census collects every declaration so name resolution, defaults, and diagnostics all happen at graph compile time. One name belongs to one marker, so a name can never mean two types. Declare markers with `core_types::attribute!`:
|
||||
|
||||
```rust
|
||||
core_types::attribute! {
|
||||
/// The measured length of an element.
|
||||
pub Length("length"): f64;
|
||||
/// A label parked in the arena by whoever writes it.
|
||||
pub Label("label"): &str;
|
||||
}
|
||||
```
|
||||
|
||||
## Graphene (proto node executor)
|
||||
Values are `Copy` and pack directly into record fields. Anything with drop glue rides the arena instead: the marker declares a reference value such as `&str`, the writing kernel parks the payload in the arena, and the record field carries a reference good for the evaluation.
|
||||
|
||||
The graphene crate (found in `gcore/`) and the graphene standard library (found in `gstd/`) is where actual implementation for nodes are located.
|
||||
In a kernel, `Attr<A>` as a parameter is a read, yielding the declared default where nothing upstream wrote it. `Attr<A>` in the return tuple is a write, and the same marker on both sides is a modify. `OwnedAttr<A>` carries a value across the evaluation boundary, and `RemoveAttr<A>` subtracts the attribute from the layout. See `libraries/core-types/src/attribute.rs`, and `nodes/gcore/src/record.rs` for worked examples of every form.
|
||||
|
||||
Implementing a node is done by defining a `struct` implementing the `Node` trait. The `Node` trait has a required function named `eval` that takes one generic input. A sample implementation for an opacity node acting on a color is seen below:
|
||||
### The arena
|
||||
|
||||
```rs
|
||||
use crate::{Color, Node};
|
||||
Two regions, both in `libraries/core-types/src/arena.rs`. The transient arena is reset at the top of every evaluation, so anything parked in it lives exactly as long as the evaluation that parked it. The persistent region backs promoted memo levels; it is flushed whole between evaluations and never during one, so no flush can land while a promoted value is still readable.
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct OpacityNode<OpacityMultiplierInput> {
|
||||
opacity_multiplier: OpacityMultiplierInput,
|
||||
}
|
||||
`Arena::move_park` is the promotion. It copies a payload's header into the receiving region, hands over the drop obligation, and tombstones the source entry in place. The heap the payload owns is neither copied nor freed, since ownership travels with the obligation, and a payload two records share moves once. Region sizes and the flush policy live in `interpreted-executor/src/dynamic_executor.rs`.
|
||||
|
||||
impl<'i, OpacityMultiplierInput: Node<'i, (), Output = f64> + 'i> Node<'i, Color> for OpacityNode<OpacityMultiplierInput> {
|
||||
type Output = Color;
|
||||
fn eval(&'i self, color: Color) -> Color {
|
||||
let opacity_multiplier = self.opacity_multiplier.eval(()) as f32 / 100.;
|
||||
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier)
|
||||
}
|
||||
}
|
||||
```
|
||||
### Serving
|
||||
|
||||
The `eval` function can only take one input. To support more than one input, the node struct can store references to other nodes. This can be seen here, as the `opacity_multiplier` field, which is generic and is constrained to the trait `Node<'i, (), Output = f64>`. This means that it is a node with the input of `()` (no input is required to compute the opacity) and an output of an `f64`.
|
||||
Evaluating a graph is a walk of `serve` calls down from the root. The root claims the frame buffer, each node claims its own frame out of what its caller left, and status rides the `GPoll` return: `Final`, `Partial` for a result that is correct but incomplete, `Pending` for work not yet ready, `Error`, and `Fallback` for a usable value paired with the error that degraded it. `StatusCell` folds each input's status into the serving node's own, which is what lets a kernel be written as though its inputs simply returned values.
|
||||
|
||||
To compute the value when executing the `OpacityNode`, we need to call `self.opacity_multiplier.eval(())`. This evaluates the node that provides the `opacity_multiplier` input, with the input value of `()`— nothing. This occurs each time the opacity node is run.
|
||||
## Adding a node
|
||||
|
||||
To test this:
|
||||
```rs
|
||||
#[test]
|
||||
fn test_opacity_node() {
|
||||
let opacity_node = OpacityNode {
|
||||
opacity_multiplier: crate::value::CopiedNode(10_f64), // set opacity to 10%
|
||||
};
|
||||
assert_eq!(opacity_node.eval(Color::WHITE), Color::from_rgbaf32_unchecked(1., 1., 1., 0.1));
|
||||
}
|
||||
```
|
||||
Write a function and put `#[node_macro::node]` on it. The macro generates the node struct, the `Node` implementation, the registry entries, and the metadata the editor builds its catalog and properties panel from.
|
||||
|
||||
The `graphene_core::value::CopiedNode` is a node that, when evaluated, copies `10_f32` and returns it.
|
||||
```rust
|
||||
use core_types::Ctx;
|
||||
use core_types::attribute::{Attr, Opacity};
|
||||
|
||||
## Creating a new node
|
||||
|
||||
Instead of manually implementing the `Node` trait with complex generics, one can use the `node` macro, which can be applied to a function like `opacity`. This will generate the struct, implementation, node_registry entry, document node definition and properties panel entries:
|
||||
|
||||
```rs
|
||||
/// Scales the opacity attribute of every element passing through.
|
||||
#[node_macro::node(category("Raster: Adjustments"))]
|
||||
fn opacity(_input: (), #[default(424242)] color: Color, #[range] #[soft(0..100)] opacity_multiplier: f64) -> Color {
|
||||
let opacity_multiplier = opacity_multiplier as f32 / 100.;
|
||||
Color::from_rgbaf32_unchecked(color.r(), color.g(), color.b(), color.a() * opacity_multiplier)
|
||||
fn multiply_opacity(
|
||||
_: impl Ctx,
|
||||
/// The element and its current opacity.
|
||||
(element, opacity): (f64, Attr<Opacity>),
|
||||
/// The factor to scale the opacity by.
|
||||
#[default(1.)]
|
||||
#[range]
|
||||
#[soft(0..2)]
|
||||
factor: f64,
|
||||
) -> (f64, Attr<Opacity>) {
|
||||
(element, Attr(*opacity * factor))
|
||||
}
|
||||
```
|
||||
|
||||
## Additional Macro Options
|
||||
Reading that back: the first parameter is the evaluation context. A tuple parameter is a record input, binding the element alongside the attributes this kernel reads, while a plain parameter is an ordinary value input the user can set. The return tuple is the write set, and returning `Attr<Opacity>` after reading it makes this a modify rather than a fresh write.
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, and `range` attributes to influence how the properties are generated. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
Doc comments are not decoration. The one on the function becomes the node's description in the editor's catalog, and the one on each parameter becomes that input's description.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
Options on the invocation are `category`, `name`, `path`, `properties` (naming a function in `editor/src/messages/portfolio/document/node_graph/node_properties.rs` for a custom panel), `extent` (naming a function that computes the node's extent, for nodes that change the item count), and `skip_impl`.
|
||||
|
||||
When the document graph is executed, the following steps occur:
|
||||
- The `NodeNetwork` is flattened using `NodeNetwork::flatten`. This involves removing any `DocumentNodeImplementation::Network` - which allow for nested document node networks. Instead, all of the inner nodes are moved into a single node graph.
|
||||
- The `NodeNetwork` is converted into a proto-graph. Each node's inputs are stored as a list of node IDs in the `ConstructionArgs` struct in the `ProtoNode`. Converting a document graph into a proto graph is done with `NodeNetwork::into_proto_networks`.
|
||||
- The newly created `ProtoNode`s are then converted into the corresponding constructor functions using the mapping defined in `node-graph/interpreted-executor/src/node_registry.rs`. This is done by `BorrowTree::push_node`.
|
||||
- The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation.
|
||||
- The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes.
|
||||
Per parameter there are `#[default(..)]`, `#[expose]`, `#[name(..)]`, `#[widget(..)]`, and `#[implementations(..)]`, which enumerates the concrete type rows a generic node registers. For numbers, `#[range]` renders a draggable slider, `#[soft(a..b)]` sets its suggested extent, and `#[hard(a..b)]` sets the enforced clamp. Either endpoint may be omitted and both are inclusive, so there is no `..=` form. Typed values may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` only means anything together with `#[range]`. The macro checks these and will reject a `#[range]` missing an end, or a `#[soft]` bound equal to its `#[hard]` counterpart.
|
||||
|
||||
The definition for the constructor of a node that applies the opacity transformation to each pixel of an image:
|
||||
```rs
|
||||
(
|
||||
// Matches against the string defined in the document node.
|
||||
ProtoNodeIdentifier::new("graphene_core::raster::OpacityNode"),
|
||||
// This function is run when converting the `ProtoNode` struct into the desired struct.
|
||||
|args| {
|
||||
Box::pin(async move {
|
||||
// Creates an instance of the struct that defines the node.
|
||||
let node = construct_node!(args, graphene_core::raster::OpacityNode<_>, [f64]).await;
|
||||
// Create a new map image node, that calls the `node` for each pixel.
|
||||
let map_node = graphene_std::raster::MapImageNode::new(graphene_core::value::ValueNode::new(node));
|
||||
// Wraps this in a type erased future `Box<Pin<dyn core::future::Future<Output = T> + 'n>>` - this allows it to work with async.
|
||||
let map_node = graphene_std::any::FutureWrapperNode::new(map_node);
|
||||
// The `DynAnyNode` downcasts its input from a `Box<dyn DynAny>` i.e. dynamically typed, to the desired statically typed input value. It then runs the wrapped node and converts the result back into a dynamically typed `Box<dyn DynAny>`.
|
||||
let any: DynAnyNode<Image<Color>, _, _> = graphene_std::any::DynAnyNode::new(graphene_core::value::ValueNode::new(map_node));
|
||||
// Nodes are stored as type erased, which means they are `Box<dyn NodeIo + Node>`. This allows us to create dynamic graphs, using dynamic dispatch so we do not have to know all node combinations at compile time.
|
||||
any.into_type_erased()
|
||||
})
|
||||
},
|
||||
// Defines the call argument, return value, and inputs.
|
||||
NodeIOTypes::new(concrete!(Image<Color>), concrete!(Image<Color>), vec![fn_type!((), f64)]),
|
||||
),
|
||||
```
|
||||
Registration is automatic. The macro emits a `ctor` constructor that inserts into `NODE_REGISTRY` and `NODE_METADATA` in `libraries/core-types/src/registry.rs` at process start, and `interpreted-executor/src/node_registry.rs` takes that table and adds a hand written set of conversion nodes to build the registry the compiler consumes. There is no separate definition table to edit; writing the function is the whole job. On wasm the `ctor` attribute is skipped and registration is driven explicitly instead.
|
||||
|
||||
Nodes in the borrow stack take a `Box<dyn DynAny>` as input and output another `Box<dyn DynAny>`, to allow for any type. To use a specific type, we must downcast the values that have been passed in.
|
||||
However the `OpacityNode` only works on one pixel at a time, so we first insert a `MapImageNode` to call the `OpacityNode` for every pixel in the image.
|
||||
Finally we call `.into_type_erased()` on the result and that is inserted into the borrow stack.
|
||||
## From a document to a result
|
||||
|
||||
We also need to add an implementation so that the user can change the opacity of just a single color. To simplify this process for raster nodes, a `raster_node!` macro is available which can simplify the definition of the opacity node to:
|
||||
```rs
|
||||
raster_node!(graphene_core::raster::OpacityNode<_>, params: [f64]),
|
||||
```
|
||||
A saved document arrives as a `NodeNetwork`. The preprocessor expands each proto node reference into the `DocumentNode` template built from its registry metadata, reconciling saved inputs against what the current definition expects, which is what lets old documents load against new node definitions. `NodeNetwork::flatten` then dissolves nested networks into one graph, `into_proto_networks` lowers it to a `ProtoNetwork`, and `TypingContext` resolves types against the registry. The executor pushes each `ProtoNode` into its `BorrowTree`, which keeps a node alive as long as anything references it, and `eval_root` resets the transient arena, sizes the frame buffer to the graph's need, and serves the output.
|
||||
|
||||
There is also the more general `register_node!` for nodes that do not need to run per pixel.
|
||||
```rs
|
||||
register_node!(graphene_core::transform_nodes::SetTransformNode<_>, input: Vector, params: [DAffine2]),
|
||||
```
|
||||
## Deeper reading
|
||||
|
||||
The design documentation for the record tier is the `//!` headers in the source. Read `libraries/core-types/src/record/mod.rs` first, then the submodule headers in the table above, then `node.rs`, `attribute.rs`, and `arena.rs`.
|
||||
|
||||
Two RFCs cover work adjacent to this system:
|
||||
|
||||
- [`rfcs/document-format.md`](rfcs/document-format.md), the `.gdd` on disk format and its CRDT delta model.
|
||||
- [`rfcs/fine-grained-context-caching.md`](rfcs/fine-grained-context-caching.md), a compilation pass that nullifies unused parts of the context to avoid needless cache invalidation.
|
||||
|
||||
## Debugging
|
||||
|
||||
Debugging inside your node can be done with the `log::debug!()` macro, for example `log::debug!("The opacity is {opacity_multiplier}");`.
|
||||
`log::debug!()` works inside a node body. For running a graph without the editor in the way, `graphene-cli` loads a document, compiles it, evaluates it, and can list every registered node.
|
||||
|
||||
We need a utility to easily view a graph as the various steps are applied. We also need a way to transparently see which constructors are being run, which nodes are being evaluated, and in what order.
|
||||
|
||||
## Conclusion
|
||||
|
||||
While we simplify the writing of nodes using the macro by hiding some of the details, creating nodes involves many files and concepts. We will work to continue making this system easier to use.
|
||||
|
||||
Any contributions you might have would be greatly appreciated. If any parts of this guide are outdated or difficult to understand, please feel free to ask for help in the Graphite Discord. We are very happy to answer any questions :)
|
||||
If any of this is wrong or unclear, please ask in the Graphite Discord. We are happy to help.
|
||||
@@ -315,7 +315,7 @@ pub enum DocumentNodeImplementation {
|
||||
Network(NodeNetwork),
|
||||
/// This describes a (document) node implemented as a proto node.
|
||||
///
|
||||
/// A proto node identifier which can be found in `node_registry.rs`.
|
||||
/// A proto node identifier, resolved against `NODE_REGISTRY` in `core-types/src/registry.rs`.
|
||||
#[serde(alias = "Unresolved")] // TODO: Eventually remove this alias document upgrade code
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// The Extract variant is a tag which tells the compilation process to do something special: it invokes language-level functionality built for use by the ExtractNode to enable metaprogramming.
|
||||
|
||||
@@ -7,10 +7,10 @@ use core_types::color::SRGBA8;
|
||||
use core_types::context::Context;
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::list::List;
|
||||
use core_types::registry::EdgeHandle;
|
||||
use core_types::registry::SourceHandle;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::value::{leveled_record_value_edge, record_value_edge};
|
||||
use core_types::value::{leveled_record_value_source, record_value_source};
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Type, TypeDescriptor};
|
||||
use dyn_any::DynAny;
|
||||
pub use dyn_any::StaticType;
|
||||
@@ -310,12 +310,12 @@ macro_rules! tagged_value {
|
||||
}
|
||||
|
||||
/// Materializes the value as [`Self::to_dynany`] does, wrapped in a value source typed by [`Self::ty`].
|
||||
pub fn to_edge(self) -> Result<EdgeHandle, String> {
|
||||
pub fn to_edge(self) -> Result<SourceHandle, String> {
|
||||
match self {
|
||||
// ===============
|
||||
// MANUAL VARIANTS
|
||||
// ===============
|
||||
Self::None => Ok(record_value_edge(())),
|
||||
Self::None => Ok(record_value_source(())),
|
||||
Self::TypeDefault(td) => {
|
||||
let name = td.name.as_ref();
|
||||
// The list-typed defaults serve an empty level; the rest construct
|
||||
@@ -323,7 +323,7 @@ macro_rules! tagged_value {
|
||||
macro_rules! check_level {
|
||||
($list:ty, $element:ty) => {
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<$list>()) {
|
||||
return Ok(leveled_record_value_edge(Vec::<$element>::new()));
|
||||
return Ok(leveled_record_value_source(Vec::<$element>::new()));
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -332,51 +332,51 @@ macro_rules! tagged_value {
|
||||
check_level!(List<Raster<CPU>>, Raster<CPU>);
|
||||
// One default lane rather than an empty level: an unwired path input
|
||||
// starts from a blank vector, as the legacy path modify synthesized itself.
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_edge(vec![Vector::default()])); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<List<Vector>>()) { return Ok(leveled_record_value_source(vec![Vector::default()])); }
|
||||
check_level!(List<String>, String);
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_edge(DocumentNode::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_edge(Resource::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<DocumentNode>()) { return Ok(record_value_source(DocumentNode::default())); }
|
||||
if name == core_types::normalize_type_name(std::any::type_name::<Resource>()) { return Ok(record_value_source(Resource::default())); }
|
||||
Self::from_type_or_none(&Type::Concrete(td)).to_edge()
|
||||
}
|
||||
Self::F64Array(values) => Ok(leveled_record_value_edge(values)),
|
||||
Self::Color(color) => Ok(leveled_record_value_edge(color.into_iter().collect::<Vec<_>>())),
|
||||
Self::Gradient(stops) => Ok(leveled_record_value_edge(vec![stops])),
|
||||
Self::BrushStrokes(strokes) => Ok(leveled_record_value_edge(strokes)),
|
||||
Self::F64Array(values) => Ok(leveled_record_value_source(values)),
|
||||
Self::Color(color) => Ok(leveled_record_value_source(color.into_iter().collect::<Vec<_>>())),
|
||||
Self::Gradient(stops) => Ok(leveled_record_value_source(vec![stops])),
|
||||
Self::BrushStrokes(strokes) => Ok(leveled_record_value_source(strokes)),
|
||||
// =======================
|
||||
// AUTO-GENERATED VARIANTS
|
||||
// =======================
|
||||
$( Self::$identifier(x) => Ok(record_value_edge(x)), )*
|
||||
$( Self::$identifier(x) => Ok(record_value_source(x)), )*
|
||||
// =======================
|
||||
// NON-SERIALIZED VARIANTS
|
||||
// =======================
|
||||
Self::RenderOutput(x) => Ok(record_value_edge(x)),
|
||||
Self::NodeIdPath(path) => Ok(record_value_edge(path)),
|
||||
Self::DocumentNode(node) => Ok(record_value_edge(node)),
|
||||
Self::ContextModification(modification) => Ok(record_value_edge(modification)),
|
||||
Self::EditorApi(x) => Ok(record_value_edge(x)),
|
||||
Self::ResourceHash(x) => Ok(record_value_edge(x)),
|
||||
Self::RenderOutput(x) => Ok(record_value_source(x)),
|
||||
Self::NodeIdPath(path) => Ok(record_value_source(path)),
|
||||
Self::DocumentNode(node) => Ok(record_value_source(node)),
|
||||
Self::ContextModification(modification) => Ok(record_value_source(modification)),
|
||||
Self::EditorApi(x) => Ok(record_value_source(x)),
|
||||
Self::ResourceHash(x) => Ok(record_value_source(x)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates a typed source and converts the landed value into a tagged value, with the coverage of [`Self::try_from_any`].
|
||||
pub fn from_edge<'f>(handle: EdgeHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||
pub fn from_edge<'f>(handle: SourceHandle, ctx: &Context<'f>, frames: &core_types::record::Frames<'f>) -> Result<GPoll<Self>, String> {
|
||||
let ty = handle.ty().clone();
|
||||
// =======================
|
||||
// RECORD WIRES, WHICH LAND AS THEIR ELEMENT
|
||||
// =======================
|
||||
if ty == core_types::registry::record_edge_type::<()>() {
|
||||
if ty == core_types::registry::record_source_type::<()>() {
|
||||
let edge = handle.downcast_record::<()>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_input(&edge, ctx, frames).map(|_| TaggedValue::None));
|
||||
}
|
||||
$(
|
||||
if ty == core_types::registry::record_edge_type::<$ty>() {
|
||||
if ty == core_types::registry::record_source_type::<$ty>() {
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<$ty>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||
.map(|value| TaggedValue::$identifier(unsafe { core_types::record::read_element::<$ty>(layout.rec(&value)) })));
|
||||
}
|
||||
)*
|
||||
if ty == core_types::registry::record_edge_type::<RenderOutput>() {
|
||||
if ty == core_types::registry::record_source_type::<RenderOutput>() {
|
||||
let layout = handle.layout().clone();
|
||||
let edge = handle.downcast_record::<RenderOutput>().map_err(|e| format!("{e:?}"))?;
|
||||
return Ok(core_types::record::serve_input(&edge, ctx, frames)
|
||||
@@ -919,27 +919,27 @@ mod typedefault_dispatch {
|
||||
mod leveled_edges {
|
||||
use super::*;
|
||||
use core_types::descriptor;
|
||||
use core_types::registry::record_edge_type;
|
||||
use core_types::registry::record_source_type;
|
||||
|
||||
#[test]
|
||||
fn list_variants_produce_leveled_edges_typed_by_element() {
|
||||
let edge = TaggedValue::F64Array(vec![1., 2., 3.]).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<f64>());
|
||||
assert_eq!(edge.ty(), &record_source_type::<f64>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
|
||||
let edge = TaggedValue::Color(Some(Color::default())).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<Color>());
|
||||
assert_eq!(edge.ty(), &record_source_type::<Color>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
|
||||
let edge = TaggedValue::TypeDefault(descriptor!(List<Graphic>)).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<Graphic>());
|
||||
assert_eq!(edge.ty(), &record_source_type::<Graphic>());
|
||||
assert_eq!(edge.layout().depth, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_variants_keep_their_rank_zero_edges() {
|
||||
let edge = TaggedValue::Bool(true).to_edge().unwrap();
|
||||
assert_eq!(edge.ty(), &record_edge_type::<bool>());
|
||||
assert_eq!(edge.ty(), &record_source_type::<bool>());
|
||||
assert_eq!(edge.layout().depth, 0);
|
||||
}
|
||||
|
||||
@@ -961,7 +961,7 @@ mod leveled_edges {
|
||||
#[cfg(test)]
|
||||
mod record_defaults {
|
||||
use super::*;
|
||||
use core_types::registry::record_edge_type;
|
||||
use core_types::registry::record_source_type;
|
||||
|
||||
// The registry can present a record row first (wasm registration order),
|
||||
// so primitive defaults must parse through the record wrapping.
|
||||
@@ -969,7 +969,7 @@ mod record_defaults {
|
||||
fn primitive_defaults_parse_through_record_wires() {
|
||||
let leveled = core_types::registry::record_type::<f64>();
|
||||
assert_eq!(TaggedValue::from_primitive_string("2.", &leveled), Some(TaggedValue::F64(2.)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("5", &record_edge_type::<u32>()), Some(TaggedValue::U32(5)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("true", &record_edge_type::<bool>()), Some(TaggedValue::Bool(true)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("5", &record_source_type::<u32>()), Some(TaggedValue::U32(5)));
|
||||
assert_eq!(TaggedValue::from_primitive_string("true", &record_source_type::<bool>()), Some(TaggedValue::Bool(true)));
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
|
||||
@@ -70,11 +70,12 @@ impl core::fmt::Display for ProtoNetwork {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
/// Defines the arguments used to construct the boxed node struct. This is used to call the constructor function in the `node_registry.rs` file - which is hidden behind a wall of macros.
|
||||
/// Defines the arguments used to construct the boxed node struct, passed to the
|
||||
/// constructor registered in `NODE_REGISTRY` (`core-types/src/registry.rs`).
|
||||
pub enum ConstructionArgs {
|
||||
/// A value of a type that is known, allowing serialization (serde::Deserialize is not object safe)
|
||||
Value(MemoHash<value::TaggedValue>),
|
||||
/// A list of nodes used as inputs to the constructor function in `node_registry.rs`.
|
||||
/// A list of nodes used as inputs to the registered constructor.
|
||||
/// The bool indicates whether to treat the node as lambda node.
|
||||
// TODO: use a struct for clearer naming.
|
||||
Nodes(Vec<NodeId>),
|
||||
@@ -377,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 = {
|
||||
@@ -387,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| {
|
||||
@@ -394,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)
|
||||
@@ -411,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
|
||||
@@ -736,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>,
|
||||
@@ -763,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"),
|
||||
@@ -1041,7 +1163,6 @@ fn valid_type(from: &Type, to: &Type) -> bool {
|
||||
// Graphite doesn't have subtyping currently, but it used to have it, and may do so again, so we make sure to compare types in this way to make things easier.
|
||||
// More details explained here: <https://github.com/GraphiteEditor/Graphite/issues/1741>
|
||||
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
|
||||
// A lend input is substitutable exactly when the lent values are.
|
||||
// A record input is substitutable exactly when the elements are.
|
||||
(Type::Record(in1), Type::Record(in2)) => valid_type(in1, in2),
|
||||
// If either the proposed input or the allowed input are generic, we allow the substitution (meaning this is a valid subtype).
|
||||
|
||||
@@ -2,7 +2,7 @@ use crate::node_registry;
|
||||
use core_types::arena::Arena;
|
||||
use core_types::context::{ContextImpl, DynSlot, EvalScope, ExtractAnimationTime, ExtractPointerPosition, ExtractRealTime, VarArg, VarArgLink, VarArgSlots};
|
||||
use core_types::gpoll::GPoll;
|
||||
use core_types::registry::EdgeHandle;
|
||||
use core_types::registry::SourceHandle;
|
||||
use core_types::runtime::{DynGraphRuntime, DynSpawner, GraphRuntime, NoopSpawner};
|
||||
use graph_craft::Type;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -33,6 +33,20 @@ fn over_budget(used: usize, budget: usize) -> bool {
|
||||
used >= budget / 8 * 7
|
||||
}
|
||||
|
||||
/// The deep element glue is filled by runtime registration: ctors at load
|
||||
/// natively, host-invoked exports on wasm. A lifetime-carrying element whose
|
||||
/// glue never registered takes the shallow clone-out path, which brands its
|
||||
/// arena borrows `'static` for a memo to hold across a reset, so a missed
|
||||
/// registration is caught here rather than at the first capture.
|
||||
fn assert_deep_element_glue() {
|
||||
for (name, registered) in [
|
||||
("graphic", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Graphic<'static>>())),
|
||||
("artboard", core_types::record::has_deep_element_glue(std::any::TypeId::of::<graphic_types::Artboard<'static>>())),
|
||||
] {
|
||||
assert!(registered, "deep element glue for `{name}` is missing; run `__node_registry_deep_element_{name}` first");
|
||||
}
|
||||
}
|
||||
|
||||
fn new_arena(capacity: usize) -> Arena {
|
||||
Arena::new(capacity).unwrap_or_else(|| {
|
||||
log::error!("arena generations exhausted; continuing without frame caching");
|
||||
@@ -66,6 +80,7 @@ fn noop_runtime() -> Arc<DynGraphRuntime> {
|
||||
|
||||
impl Default for DynamicExecutor {
|
||||
fn default() -> Self {
|
||||
assert_deep_element_glue();
|
||||
Self {
|
||||
output: Default::default(),
|
||||
tree: Default::default(),
|
||||
@@ -96,6 +111,7 @@ pub struct ResolvedDocumentNodeTypesDelta {
|
||||
|
||||
impl DynamicExecutor {
|
||||
pub fn new(mut proto_network: ProtoNetwork) -> Result<Self, GraphErrors> {
|
||||
assert_deep_element_glue();
|
||||
let mut typing_context = TypingContext::new(&node_registry::NODE_REGISTRY);
|
||||
typing_context.update(&mut proto_network)?;
|
||||
let output = proto_network.output;
|
||||
@@ -177,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, |layout, batch, arena| graphic_types::boundary::batch_to_legacy(layout, batch, arena))
|
||||
.map(Arc::from);
|
||||
return self.introspect_with(node_path, graphic_types::boundary::batch_to_legacy).map(Arc::from);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
@@ -197,7 +211,7 @@ impl DynamicExecutor {
|
||||
let edge = self
|
||||
.tree
|
||||
.get_by_path(node_path)
|
||||
.and_then(EdgeHandle::record_edge)
|
||||
.and_then(SourceHandle::record_source)
|
||||
.ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let arena = self.arena.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let persistent = self.persistent.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
@@ -363,7 +377,7 @@ impl std::fmt::Display for IntrospectError {
|
||||
///
|
||||
/// # Fields
|
||||
///
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`EdgeHandle`] and [`Path`].
|
||||
/// * `nodes`: A [`HashMap`] of [`NodeId`]s to tuples of [`SourceHandle`] and [`Path`].
|
||||
/// This stores the actual node instances and their associated paths.
|
||||
///
|
||||
/// * `source_map`: A [`HashMap`] from [`Path`] to tuples of [`NodeId`] and [`NodeTypes`].
|
||||
@@ -373,7 +387,7 @@ impl std::fmt::Display for IntrospectError {
|
||||
#[derive(Default)]
|
||||
pub struct BorrowTree {
|
||||
/// A hashmap of node IDs and dynamically typed nodes.
|
||||
nodes: HashMap<NodeId, (EdgeHandle, Path)>,
|
||||
nodes: HashMap<NodeId, (SourceHandle, Path)>,
|
||||
/// A hashmap from the document path to the proto node ID.
|
||||
source_map: HashMap<Path, (NodeId, NodeTypes)>,
|
||||
/// The record-stack reserve, folded from the graph at construction.
|
||||
@@ -410,27 +424,27 @@ impl BorrowTree {
|
||||
Ok((new_nodes, old_nodes))
|
||||
}
|
||||
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<EdgeHandle> {
|
||||
fn node_deps(&self, nodes: &[NodeId]) -> Vec<SourceHandle> {
|
||||
nodes.iter().map(|node| self.nodes.get(node).unwrap().0.duplicate()).collect()
|
||||
}
|
||||
|
||||
fn store_node(&mut self, node: EdgeHandle, id: NodeId, path: Path) {
|
||||
fn store_node(&mut self, node: SourceHandle, id: NodeId, path: Path) {
|
||||
self.nodes.insert(id, (node, path));
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the captured io record for a monitor node. The node path must match the document node path.
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the captured context snapshot for a monitor node. The node path must match the document node path.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let (node, _path) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||
node.serialize().ok_or(IntrospectError::NoData)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: NodeId) -> Option<EdgeHandle> {
|
||||
pub fn get(&self, id: NodeId) -> Option<SourceHandle> {
|
||||
self.nodes.get(&id).map(|(node, _)| node.duplicate())
|
||||
}
|
||||
|
||||
/// The edge handle for the node at a document path.
|
||||
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<EdgeHandle> {
|
||||
pub fn get_by_path(&self, node_path: &[NodeId]) -> Option<SourceHandle> {
|
||||
let (id, _) = self.source_map.get(node_path)?;
|
||||
self.get(*id)
|
||||
}
|
||||
@@ -705,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()
|
||||
}
|
||||
|
||||
@@ -721,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 {
|
||||
@@ -788,7 +989,7 @@ mod test {
|
||||
|
||||
let executor = build_executor(network);
|
||||
let value = executor.tree().get(NodeId(0)).unwrap();
|
||||
assert_eq!(value.ty(), &core_types::registry::record_edge_type::<f64>());
|
||||
assert_eq!(value.ty(), &core_types::registry::record_source_type::<f64>());
|
||||
assert_eq!(value.layout().depth, 0);
|
||||
assert_eq!((&executor).execute(()).unwrap(), GPoll::Final(TaggedValue::F64(7.)));
|
||||
}
|
||||
|
||||
@@ -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, EdgeHandle, NodeIOTypes, RegistryEntry};
|
||||
use graphene_std::registry::{ConstructionError, NodeIOTypes, RegistryEntry, SourceHandle};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::runtime::RuntimeHandle;
|
||||
|
||||
@@ -217,7 +217,7 @@ mod node_registry_macros {
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>()],
|
||||
vec![core_types::registry::record_source_type::<$from>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 1 {
|
||||
@@ -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(EdgeHandle::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>
|
||||
))
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -284,10 +286,10 @@ mod node_registry_macros {
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![
|
||||
core_types::registry::record_edge_type::<$from>(),
|
||||
core_types::registry::record_edge_type::<$convert>(),
|
||||
core_types::registry::record_edge_type::<RuntimeHandle>(),
|
||||
core_types::registry::record_edge_type::<SourceId>(),
|
||||
core_types::registry::record_source_type::<$from>(),
|
||||
core_types::registry::record_source_type::<$convert>(),
|
||||
core_types::registry::record_source_type::<RuntimeHandle>(),
|
||||
core_types::registry::record_source_type::<SourceId>(),
|
||||
],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
@@ -314,7 +316,7 @@ mod node_registry_macros {
|
||||
&runtime_layout,
|
||||
&source_layout,
|
||||
);
|
||||
Ok(EdgeHandle::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>))
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -327,7 +329,7 @@ mod node_registry_macros {
|
||||
io: NodeIOTypes::new(
|
||||
concrete!(Context),
|
||||
core_types::registry::record_type::<$to>(),
|
||||
vec![core_types::registry::record_edge_type::<$from>(), core_types::registry::record_edge_type::<$convert>()],
|
||||
vec![core_types::registry::record_source_type::<$from>(), core_types::registry::record_source_type::<$convert>()],
|
||||
),
|
||||
constructor: |inputs| {
|
||||
if inputs.len() != 2 {
|
||||
@@ -344,7 +346,7 @@ mod node_registry_macros {
|
||||
&value_layout,
|
||||
&converter_layout,
|
||||
);
|
||||
Ok(EdgeHandle::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>))
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -27,11 +27,12 @@ pub struct Arena {
|
||||
/// a park costs one pointer in the arena and owns its content outside it.
|
||||
retained_heap: AtomicUsize,
|
||||
/// Where [`Arena::move_park`] sent each moved park, as its offset here to
|
||||
/// the header's address in the receiving arena and the moved type's key, so
|
||||
/// a payload two records share is moved once and a mistyped sharer is
|
||||
/// refused. Cleared by [`Arena::reset`], so a forwarding holds for one
|
||||
/// generation.
|
||||
forwarded: Mutex<HashMap<usize, (usize, TypeId)>>,
|
||||
/// the header's address in the receiving arena, the moved type's key and
|
||||
/// that arena's generation, so a payload two records share is moved once
|
||||
/// while a mistyped sharer, a sharer naming another destination, and a
|
||||
/// sharer whose destination has since flushed are all refused. Cleared by
|
||||
/// [`Arena::reset`], so a forwarding holds for one generation.
|
||||
forwarded: Mutex<HashMap<usize, (usize, TypeId, u64)>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Arena {
|
||||
@@ -53,6 +54,9 @@ struct DropEntry {
|
||||
|
||||
/// The glue a tombstoned entry carries: its payload was moved to another arena,
|
||||
/// which now owns the obligation.
|
||||
///
|
||||
/// # Safety
|
||||
/// None: the payload is neither read nor dropped, so any pointer is accepted.
|
||||
unsafe fn inert(_: *mut u8) {}
|
||||
|
||||
/// The entry parking `offset`, `None` where the arena holds no obligation for
|
||||
@@ -196,7 +200,7 @@ impl Arena {
|
||||
let count = COUNT.fetch_add(1, Ordering::Relaxed);
|
||||
if reserved.is_none() {
|
||||
eprintln!("arena> EXHAUSTED after {count} allocations, wanted {size} bytes\n{}", std::backtrace::Backtrace::force_capture());
|
||||
} else if count % 20000 == 0 {
|
||||
} else if count.is_multiple_of(20000) {
|
||||
eprintln!("arena> {count} allocations, offset {}, this {size} bytes", self.offset.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
@@ -236,14 +240,23 @@ impl Arena {
|
||||
// Built before the write so an unencodable offset drops `value` here
|
||||
// rather than stranding it in the arena without drop glue.
|
||||
let weak = ArenaWeak::new(self.generation(), offset)?;
|
||||
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<T>();
|
||||
// SAFETY: freshly reserved, aligned, in-bounds, unaliased.
|
||||
unsafe { ptr.write(value) };
|
||||
if std::mem::needs_drop::<T>() {
|
||||
/// # Safety
|
||||
/// `p` must address the live `T` this entry was registered for.
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
self.drops.lock().unwrap().push(DropEntry { offset, type_of, drop_fn: glue::<T>, retained });
|
||||
self.drops.lock().unwrap().push(DropEntry {
|
||||
offset,
|
||||
type_of,
|
||||
drop_fn: glue::<T>,
|
||||
retained,
|
||||
});
|
||||
self.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
}
|
||||
// SAFETY: initialized above; insert-only, so no `&mut` to it can exist.
|
||||
@@ -264,6 +277,12 @@ impl Arena {
|
||||
/// fan-out sharer's second move reaches the one header and the obligation
|
||||
/// is never duplicated.
|
||||
///
|
||||
/// A forwarding is to one destination generation, since the returned
|
||||
/// pointer is only the caller's to publish where it lands in the `dst` it
|
||||
/// named: a second move to another arena, or to one that has flushed since,
|
||||
/// is refused rather than answered with a foreign or freed header. The
|
||||
/// refusal reads as a decline, so the caller takes its clone path.
|
||||
///
|
||||
/// `dst` is credited `retained`, which is what a clone of the payload would
|
||||
/// have credited it, and this arena is debited what its own park recorded,
|
||||
/// so neither counter reads worse than it did before the move.
|
||||
@@ -290,8 +309,11 @@ impl Arena {
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
let type_of = TypeId::of::<T::Static>();
|
||||
let mut forwarded = self.forwarded.lock().unwrap();
|
||||
if let Some(&(moved, moved_type)) = forwarded.get(&offset) {
|
||||
if let Some(&(moved, moved_type, moved_generation)) = forwarded.get(&offset) {
|
||||
(moved_type == type_of).then_some(())?;
|
||||
// Generations are globally unique, so the match is `dst` itself and
|
||||
// its current epoch; anything else declines.
|
||||
(moved_generation == dst.generation()).then_some(())?;
|
||||
return Some(moved as *const T::Static);
|
||||
}
|
||||
let mut entries = self.drops.lock().unwrap();
|
||||
@@ -305,7 +327,10 @@ impl Arena {
|
||||
let parked = std::mem::replace(&mut entries[entry].retained, 0);
|
||||
entries[entry].drop_fn = inert;
|
||||
drop(entries);
|
||||
/// # Safety
|
||||
/// `p` must address the live `T` this entry was registered for.
|
||||
unsafe fn glue<T>(p: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { p.cast::<T>().drop_in_place() }
|
||||
}
|
||||
dst.drops.lock().unwrap().push(DropEntry {
|
||||
@@ -316,7 +341,7 @@ impl Arena {
|
||||
});
|
||||
dst.retained_heap.fetch_add(retained, Ordering::Relaxed);
|
||||
let _ = self.retained_heap.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| Some(current.saturating_sub(parked)));
|
||||
forwarded.insert(offset, (target as usize, type_of));
|
||||
forwarded.insert(offset, (target as usize, type_of, dst.generation()));
|
||||
Some(target.cast_const())
|
||||
}
|
||||
|
||||
@@ -335,6 +360,7 @@ impl Arena {
|
||||
pub fn alloc_scratch<T: Send + Sync>(&self, len: usize) -> Option<&mut [MaybeUninit<T>]> {
|
||||
let size = size_of::<T>().checked_mul(len)?;
|
||||
let offset = self.reserve(size, align_of::<T>())?;
|
||||
// SAFETY: `reserve` returned `offset`, so it is within the backbone.
|
||||
let ptr = unsafe { self.base().add(offset) }.cast::<MaybeUninit<T>>();
|
||||
// SAFETY: exclusive region; lifetime tied to `&self`, and `reset` takes
|
||||
// `&mut self`, so the slice cannot outlive the generation.
|
||||
@@ -344,9 +370,13 @@ impl Arena {
|
||||
/// The generation-checked handle for a region this arena holds, `None` for
|
||||
/// a pointer from anywhere else. The handle keeps the region's provenance,
|
||||
/// so a cache stores one where it would otherwise launder an address.
|
||||
///
|
||||
/// The offset must sit below the bump watermark, not merely inside the
|
||||
/// backbone: [`ArenaWeak::upgrade`] hands out a `&T` at it, so only bytes a
|
||||
/// reservation already handed out may be minted into a handle.
|
||||
pub fn handle_at(&self, ptr: *const u8) -> Option<ArenaWeak<u8>> {
|
||||
let offset = (ptr as usize).checked_sub(self.base() as usize)?;
|
||||
(offset < self.buf.len()).then_some(())?;
|
||||
(offset < self.offset.load(Ordering::Acquire)).then_some(())?;
|
||||
ArenaWeak::new(self.generation(), offset)
|
||||
}
|
||||
|
||||
@@ -362,13 +392,14 @@ impl Arena {
|
||||
self.forwarded.get_mut().unwrap().clear();
|
||||
self.generation.store(PARKED_GENERATION, Ordering::Release);
|
||||
for entry in entries.into_iter().rev() {
|
||||
// Debited before the glue runs: a panicking destructor drops the
|
||||
// remaining entries unglued, so a hint subtracted afterwards would
|
||||
// strand on the counter for the arena's whole life.
|
||||
let retained = self.retained_heap.get_mut();
|
||||
*retained = retained.saturating_sub(entry.retained);
|
||||
// SAFETY: registered at alloc time; insert-only means the region was
|
||||
// never overwritten within this generation.
|
||||
unsafe { (entry.drop_fn)(base.add(entry.offset)) }
|
||||
// Decremented as each payload's heap is freed, so an unwinding reset
|
||||
// leaves the counter matching what is still parked.
|
||||
let retained = self.retained_heap.get_mut();
|
||||
*retained = retained.saturating_sub(entry.retained);
|
||||
}
|
||||
*self.offset.get_mut() = 0;
|
||||
*self.exhausted.get_mut() = false;
|
||||
@@ -550,6 +581,57 @@ mod tests {
|
||||
assert!(cell.load(&arena).is_none(), "a half-dropped generation must resolve no handle");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_mint_only_over_reserved_bytes() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let (value, _) = arena.alloc(41u32).unwrap();
|
||||
let ptr = std::ptr::from_ref(value).cast::<u8>();
|
||||
assert!(arena.handle_at(ptr).is_some(), "a byte the bump handed out mints a handle");
|
||||
|
||||
let unreserved = ptr.wrapping_add(64);
|
||||
assert!(arena.contains(unreserved), "the fixture stays inside the backbone");
|
||||
assert!(arena.handle_at(unreserved).is_none(), "a byte past the watermark mints nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forwarding_answers_only_the_destination_it_recorded() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Probe(#[allow(dead_code)] String);
|
||||
unsafe impl dyn_any::StaticType for Probe {
|
||||
type Static = Probe;
|
||||
}
|
||||
let transient = Arena::new(1024).unwrap();
|
||||
let mut first = Arena::new(1024).unwrap();
|
||||
let second = Arena::new(1024).unwrap();
|
||||
|
||||
let (parked, _) = transient.alloc_sized_keyed(Probe(String::from("shared by two records")), 21).unwrap();
|
||||
let src = std::ptr::from_ref(parked).cast::<u8>();
|
||||
unsafe { transient.move_park::<Probe>(src, &first, 21) }.unwrap();
|
||||
|
||||
assert!(unsafe { transient.move_park::<Probe>(src, &second, 21) }.is_none(), "a sharer naming another destination is refused");
|
||||
first.reset();
|
||||
assert!(unsafe { transient.move_park::<Probe>(src, &first, 21) }.is_none(), "a flushed destination is refused too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panicking_destructor_does_not_strand_the_retained_hint() {
|
||||
let _guard = COUNTER_GUARD.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
struct Bomb;
|
||||
impl Drop for Bomb {
|
||||
fn drop(&mut self) {
|
||||
panic!("payload destructor");
|
||||
}
|
||||
}
|
||||
let mut arena = Arena::new(1024).unwrap();
|
||||
arena.alloc_sized(Bomb, 64).unwrap();
|
||||
assert_eq!(arena.retained_heap(), 64);
|
||||
|
||||
let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| arena.reset()));
|
||||
assert!(unwound.is_err(), "the panic must propagate out of reset");
|
||||
assert_eq!(arena.retained_heap(), 0, "the hint is debited before the glue that panics");
|
||||
}
|
||||
|
||||
/// Held by every test that perturbs [`NEXT_GENERATION`], so a swapped-out counter
|
||||
/// is never observed by a concurrently constructing test.
|
||||
static COUNTER_GUARD: Mutex<()> = Mutex::new(());
|
||||
@@ -695,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");
|
||||
|
||||
|
||||
@@ -20,15 +20,35 @@ use std::sync::{LazyLock, Mutex};
|
||||
|
||||
/// Declares an attribute name: one marker per name, fixing the value type and
|
||||
/// the name-specific default. Declare markers through the [`attribute!`]
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`].
|
||||
pub trait Attribute: 'static {
|
||||
/// macro, which also registers them into the [`ATTRIBUTE_REGISTRY`] and emits
|
||||
/// an impl meeting the obligations below.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// [`REPARK`](Self::REPARK) must be `Some` for every marker whose
|
||||
/// [`Value<'e>`](Self::Value) can carry a borrow shorter than `'static`. The
|
||||
/// plain-value arm of the census writer retypes the value [`from_stored`] hands
|
||||
/// it from the stored form's lifetime to the field's, which is only a relabel
|
||||
/// where the value borrows nothing; a re-parking marker instead writes a
|
||||
/// reference into the arena it is given.
|
||||
///
|
||||
/// [`from_stored`](Self::from_stored) must accept exactly the erased form
|
||||
/// [`read_erased`](Self::read_erased) produces, and [`read_erased`] must read
|
||||
/// its `ptr` as this marker's own `Value`. The two are each other's inverse
|
||||
/// across every persistence seam, so a marker that reads one type and stores
|
||||
/// another writes a value of the wrong type into the field.
|
||||
pub unsafe trait Attribute: 'static {
|
||||
/// The name as it appears in documents and diagnostics.
|
||||
const NAME: &'static str;
|
||||
/// The value type every read and write of this name shares. The lifetime
|
||||
/// is the evaluation the value flows in; non-reference values ignore it.
|
||||
/// The value outlives that evaluation, so its `'static` instantiation is
|
||||
/// the one the census registers and layouts stamp their type id from.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + 'e;
|
||||
///
|
||||
/// `Send + Sync` because a record's bytes are these values: `RecordValue`
|
||||
/// is `Send + Sync` over whatever the field writes put there, and the write
|
||||
/// path never consults the census, so the bound has to sit here.
|
||||
type Value<'e>: Copy + Default + std::fmt::Debug + Send + Sync + 'e;
|
||||
/// The name-specific default, filled where an item lacks the attribute.
|
||||
/// Producing a value for any `'e` from no inputs, reference defaults can
|
||||
/// only point at `'static` data, which is what lets the census fill them
|
||||
@@ -48,7 +68,7 @@ pub trait Attribute: 'static {
|
||||
|
||||
/// Re-parks the owned clone [`Self::read_erased`] produced into fresh
|
||||
/// field storage; `None` for plain values, which ride the byte copy.
|
||||
const REPARK: Option<unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>> = None;
|
||||
const REPARK: Option<crate::list::ReparkFn> = None;
|
||||
}
|
||||
|
||||
/// A kernel-facing attribute value. A parameter `Attr<A>` is a read of `A`
|
||||
@@ -135,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<'e>(self, _: &'e $crate::arena::Arena) -> ::core::option::Option<$value> {
|
||||
::core::option::Option::Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
$crate::wire_value!($($rest)*);
|
||||
};
|
||||
($wire:ty => $row:ty; $($rest:tt)*) => {
|
||||
impl $crate::attribute::WireValue for $wire {
|
||||
type Row = $row;
|
||||
|
||||
fn park<'e>(self, arena: &'e $crate::arena::Arena) -> ::core::option::Option<<$row as $crate::attribute::AttrValue>::Value<'e>> {
|
||||
let (parked, _) = arena.alloc(self)?;
|
||||
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
|
||||
}
|
||||
}
|
||||
|
||||
$crate::wire_value!($($rest)*);
|
||||
};
|
||||
}
|
||||
|
||||
wire_value! {
|
||||
for f64;
|
||||
for u32;
|
||||
for u64;
|
||||
for bool;
|
||||
for DVec2;
|
||||
for DAffine2;
|
||||
for crate::Color;
|
||||
for crate::blending::BlendMode;
|
||||
::std::vec::Vec<crate::uuid::NodeId> => NodeIdPath;
|
||||
::std::string::String => Text;
|
||||
}
|
||||
|
||||
/// Interns a folded attribute name for the `&'static str` a layout field
|
||||
/// holds. Census names never reach here; a document's novel names are finite
|
||||
/// and repeat across instances, so the leak is one allocation per name.
|
||||
pub fn intern_name(name: &str) -> &'static str {
|
||||
static NAMES: LazyLock<Mutex<std::collections::HashSet<&'static str>>> = LazyLock::new(|| Mutex::new(std::collections::HashSet::new()));
|
||||
let mut names = NAMES.lock().unwrap();
|
||||
if let Some(interned) = names.get(name) {
|
||||
return interned;
|
||||
}
|
||||
let interned: &'static str = Box::leak(name.to_owned().into_boxed_str());
|
||||
names.insert(interned);
|
||||
interned
|
||||
}
|
||||
|
||||
/// Declares [`AttrValue`] rows, the value types a name-generic attribute can
|
||||
/// be written at. `for T` implements the row on an existing plain value type;
|
||||
/// `Row: &T` and `Row: Option<&T>` declare a token naming a reference value,
|
||||
/// whose payload the writing kernel parks in the arena.
|
||||
///
|
||||
/// ```ignore
|
||||
/// core_types::named_value! {
|
||||
/// /// Plain rows, implemented on the value type itself.
|
||||
/// for f64;
|
||||
/// /// A reference row, whose token names the borrowed value.
|
||||
/// pub Text: &str;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The `for T` arm implements this crate's trait on `T`, so rows over types
|
||||
/// this crate does not own are declared here rather than by a caller.
|
||||
#[macro_export]
|
||||
macro_rules! named_value {
|
||||
() => {};
|
||||
($(#[$meta:meta])* for $value:ty; $($rest:tt)*) => {
|
||||
// SAFETY: a plain value type cannot name `'e`, so no re-park is owed,
|
||||
// and the two glue fns below are each other's inverse at `$value`.
|
||||
unsafe impl $crate::attribute::AttrValue for $value {
|
||||
type Value<'e> = $value;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<$value>().copied()
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<$value>().read() })
|
||||
}
|
||||
}
|
||||
|
||||
$crate::named_value!($($rest)*);
|
||||
};
|
||||
($(#[$meta:meta])* $vis:vis $row:ident: Option<&$value:ty>; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $row;
|
||||
|
||||
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
|
||||
// are each other's inverse at `Option<&$value>`.
|
||||
unsafe impl $crate::attribute::AttrValue for $row {
|
||||
type Value<'e> = ::core::option::Option<&'e $value>;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored
|
||||
.downcast_ref::<::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned>>()
|
||||
.map(|owned| owned.as_ref().map(::std::borrow::Borrow::borrow))
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<::core::option::Option<&$value>>().read() }.map(|value| <$value as ::std::borrow::ToOwned>::to_owned(value)))
|
||||
}
|
||||
|
||||
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
|
||||
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||
let owned: &::core::option::Option<<$value as ::std::borrow::ToOwned>::Owned> =
|
||||
value.as_any().downcast_ref().expect("an optional reference row replays its owned clone");
|
||||
let parked = match owned {
|
||||
::core::option::Option::Some(owned) => {
|
||||
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||
::core::option::Option::Some(::std::borrow::Borrow::borrow(parked))
|
||||
}
|
||||
::core::option::Option::None => ::core::option::Option::None,
|
||||
};
|
||||
unsafe { dst.cast::<::core::option::Option<&$value>>().write(parked) };
|
||||
::core::option::Option::Some(())
|
||||
}
|
||||
::core::option::Option::Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
$crate::named_value!($($rest)*);
|
||||
};
|
||||
($(#[$meta:meta])* $vis:vis $row:ident: &$value:ty; $($rest:tt)*) => {
|
||||
$(#[$meta])*
|
||||
$vis struct $row;
|
||||
|
||||
// SAFETY: the reference arm emits `REPARK`, and the two glue fns below
|
||||
// are each other's inverse at `&$value`.
|
||||
unsafe impl $crate::attribute::AttrValue for $row {
|
||||
type Value<'e> = &'e $value;
|
||||
|
||||
fn from_stored<'a>(stored: &'a dyn ::std::any::Any) -> ::core::option::Option<Self::Value<'a>> {
|
||||
stored.downcast_ref::<<$value as ::std::borrow::ToOwned>::Owned>().map(::std::borrow::Borrow::borrow)
|
||||
}
|
||||
|
||||
unsafe fn read_erased(ptr: *const u8) -> ::std::boxed::Box<dyn $crate::list::AnyAttributeValue> {
|
||||
::std::boxed::Box::new(unsafe { ptr.cast::<&$value>().read() }.to_owned())
|
||||
}
|
||||
|
||||
const REPARK: ::core::option::Option<$crate::list::ReparkFn> = {
|
||||
unsafe fn repark(value: &dyn $crate::list::AnyAttributeValue, dst: *mut u8, arena: &$crate::arena::Arena) -> ::core::option::Option<()> {
|
||||
let owned: &<$value as ::std::borrow::ToOwned>::Owned = value.as_any().downcast_ref().expect("a reference row replays its owned clone");
|
||||
let (parked, _) = arena.alloc(<$value as ::std::borrow::ToOwned>::to_owned(::std::borrow::Borrow::borrow(owned)))?;
|
||||
unsafe { dst.cast::<&$value>().write(::std::borrow::Borrow::borrow(parked)) };
|
||||
::core::option::Option::Some(())
|
||||
}
|
||||
::core::option::Option::Some(repark)
|
||||
};
|
||||
}
|
||||
|
||||
$crate::named_value!($($rest)*);
|
||||
};
|
||||
}
|
||||
|
||||
named_value! {
|
||||
for f64;
|
||||
for u32;
|
||||
for u64;
|
||||
for bool;
|
||||
for DVec2;
|
||||
for DAffine2;
|
||||
for crate::Color;
|
||||
for crate::blending::BlendMode;
|
||||
/// A document node path, the value type of `editor:layer_path`.
|
||||
pub NodeIdPath: &[crate::uuid::NodeId];
|
||||
/// Free text, parked in the arena by the writing kernel.
|
||||
pub Text: &str;
|
||||
}
|
||||
|
||||
/// A census row: what is known about one declared attribute name.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AttributeInfo {
|
||||
@@ -151,13 +443,25 @@ pub struct AttributeInfo {
|
||||
/// Writes a legacy stored value into a field of this marker, parking
|
||||
/// droppable payloads. A wrong-typed stored value leaves the field
|
||||
/// untouched; `None` reports arena exhaustion.
|
||||
///
|
||||
/// `dst` must address a live field of *this row's* value type: the glue
|
||||
/// writes its own `Value`'s worth of bytes there, so a caller resolving the
|
||||
/// field by [`name`](Self::name) checks [`size`](Self::size) and
|
||||
/// [`value_type`](Self::value_type) against the field first. The fields
|
||||
/// here are public and the struct is `Copy`, so a row is a claim about a
|
||||
/// marker rather than a proof about a field.
|
||||
pub write_stored: unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>,
|
||||
}
|
||||
|
||||
/// The default's object representation, staged through zeroed storage so a
|
||||
/// value with padding or an unused payload (`Option<f64>`'s `None`) hands the
|
||||
/// caller deterministic bytes rather than whatever the stack held.
|
||||
fn write_default_bytes<A: Attribute>(out: &mut [u8]) {
|
||||
assert_eq!(out.len(), size_of::<A::Value<'static>>());
|
||||
let value: A::Value<'static> = A::default();
|
||||
unsafe { std::ptr::copy_nonoverlapping((&raw const value).cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
|
||||
let mut staged = std::mem::MaybeUninit::<A::Value<'static>>::zeroed();
|
||||
staged.write(A::default());
|
||||
// SAFETY: the staging holds a live value of the type `out` is sized for.
|
||||
unsafe { std::ptr::copy_nonoverlapping(staged.as_ptr().cast::<u8>(), out.as_mut_ptr(), size_of::<A::Value<'static>>()) };
|
||||
}
|
||||
|
||||
fn field_write_at<A: Attribute>(level: u8) -> crate::record::FieldWrite
|
||||
@@ -167,12 +471,15 @@ where
|
||||
crate::record::FieldWrite::of::<A>(level)
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `dst` must address a live field of `A`'s value type.
|
||||
unsafe fn write_stored<A: Attribute>(stored: &dyn AnyAttributeValue, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
if A::from_stored(stored.as_any()).is_none() {
|
||||
// A wrong-typed stored value reads as absent, so the field keeps its default.
|
||||
return Some(());
|
||||
}
|
||||
match A::REPARK {
|
||||
// SAFETY: the caller's contract; the glue is this marker's own.
|
||||
Some(repark) => unsafe { repark(stored, dst, arena) },
|
||||
None => {
|
||||
let value = A::from_stored(stored.as_any()).expect("checked above");
|
||||
@@ -251,7 +558,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = ::core::option::Option<&'e $value>;
|
||||
|
||||
@@ -290,7 +600,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = &'e $value;
|
||||
$(
|
||||
@@ -325,7 +638,10 @@ macro_rules! attribute {
|
||||
$(#[$meta])*
|
||||
$vis struct $marker;
|
||||
|
||||
impl $crate::attribute::Attribute for $marker {
|
||||
// SAFETY: the reference-valued arms emit `REPARK`, the plain arm's value
|
||||
// type cannot name `'e`, and `read_erased` and `from_stored` are emitted
|
||||
// as each other's inverse.
|
||||
unsafe impl $crate::attribute::Attribute for $marker {
|
||||
const NAME: &'static str = $name;
|
||||
type Value<'e> = $value;
|
||||
$(
|
||||
@@ -381,7 +697,7 @@ attribute! {
|
||||
/// Maps the unit square `[(0, 0), (1, 1)]` (top-left convention) onto the 'Text' node's
|
||||
/// text frame in this item's local space. Each item carries the frame relative to its own
|
||||
/// glyph origin so it survives 'Index Elements' filtering. The Text tool reads this to
|
||||
/// position its drag cage. Stored as an affine to allow non-axis-aligned frames in the future.
|
||||
/// position its drag cage.
|
||||
pub EditorTextFrame("editor:text_frame"): DAffine2;
|
||||
/// Byte offset where a regex match begins ('Regex Find All' and 'Regex Capture' text nodes).
|
||||
pub Start("start"): u64;
|
||||
@@ -481,7 +797,8 @@ mod tests {
|
||||
#[should_panic(expected = "two value types")]
|
||||
fn a_second_marker_at_a_different_type_panics() {
|
||||
struct Conflict;
|
||||
impl Attribute for Conflict {
|
||||
// SAFETY: `bool` borrows nothing, so the plain-value arm is the right one.
|
||||
unsafe impl Attribute for Conflict {
|
||||
const NAME: &'static str = "opacity";
|
||||
type Value<'e> = bool;
|
||||
|
||||
|
||||
@@ -85,6 +85,12 @@ pub trait AnyAttributeValue: std::any::Any + Send + Sync {
|
||||
fn into_attribute(self: Box<Self>, key: &str, preceding_defaults: usize) -> Box<dyn AnyAttribute>;
|
||||
}
|
||||
|
||||
/// Re-parks an owned attribute value into fresh field storage; `None` reports arena exhaustion.
|
||||
pub type ReparkFn = unsafe fn(&dyn AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>;
|
||||
|
||||
/// Replays an owned attribute value into a serving arena; `Some(None)` is unchanged, `None` reports arena exhaustion.
|
||||
pub type FieldReplayFn = fn(&dyn AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn AnyAttributeValue>>>;
|
||||
|
||||
impl<T: Clone + Send + Sync + Default + Sized + Debug + PartialEq + CacheHash + 'static> AnyAttributeValue for T {
|
||||
/// Clones this value into a new boxed trait object.
|
||||
fn clone_box(&self) -> Box<dyn AnyAttributeValue> {
|
||||
@@ -336,7 +342,6 @@ impl AttributeDyn {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.len() == 0
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
impl Clone for AttributeDyn {
|
||||
@@ -369,6 +374,7 @@ impl CacheHash for AttributeDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the type carries no lifetime, so it is its own static form.
|
||||
unsafe impl StaticType for AttributeDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -412,6 +418,7 @@ impl CacheHash for AttributeValueDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for AttributeValueDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -495,6 +502,7 @@ impl CacheHash for ListDyn {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: as for AttributeDyn.
|
||||
unsafe impl StaticType for ListDyn {
|
||||
type Static = Self;
|
||||
}
|
||||
@@ -1184,6 +1192,8 @@ impl<T> ApplyTransform for List<T> {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: the list carries its lifetime only through T, so substituting T's
|
||||
// static form substitutes the list's and keeps the layout identical.
|
||||
unsafe impl<T: StaticTypeSized> StaticType for List<T> {
|
||||
type Static = List<T::Static>;
|
||||
}
|
||||
|
||||
@@ -106,9 +106,10 @@ pub struct RecordBatchMut<'a> {
|
||||
|
||||
impl<'a> RecordBatchMut<'a> {
|
||||
/// Minted only by a [`crate::record::SlotRun`] finishing its served lanes,
|
||||
/// which is what makes the initialized prefix a fact rather than a contract.
|
||||
/// which serve in ascending order with no gaps, so the initialized prefix is
|
||||
/// a fact rather than a contract.
|
||||
pub(crate) fn new(scratch: &'a mut [MaybeUninit<u64>], len: usize, layout: &'a crate::record::Layout) -> Self {
|
||||
debug_assert!(len * layout.lane_stride() <= scratch.len() * 8);
|
||||
debug_assert!(len.checked_mul(layout.lane_stride()).is_some_and(|need| need <= scratch.len() * 8));
|
||||
Self { scratch, len, layout }
|
||||
}
|
||||
|
||||
@@ -135,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.
|
||||
@@ -212,8 +212,7 @@ impl<'a, T> Deref for Lane<'a, T> {
|
||||
}
|
||||
|
||||
/// A materialized nesting level handed to a folding kernel: a thin element-typed
|
||||
/// view over the [`RecordBatch`] the level was collected into. The eventual
|
||||
/// `List` once `IList` is renamed.
|
||||
/// view over the [`RecordBatch`] the level was collected into.
|
||||
#[derive(Debug)]
|
||||
pub struct List<'a, T> {
|
||||
batch: RecordBatch<'a>,
|
||||
|
||||
@@ -38,7 +38,6 @@ impl<'r> Rec<'r> {
|
||||
|
||||
/// An opaque record value: every non-empty record spills to a claimed frame
|
||||
/// and the value carries its pointer, while an empty record carries nothing.
|
||||
/// Only [`Layout::rec`] reads it, against the wiring-proven layout.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RecordValue<'e> {
|
||||
pub(in crate::record) ptr: *const u8,
|
||||
@@ -51,9 +50,10 @@ impl std::fmt::Debug for RecordValue<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `element_write` requires the element `Send + Sync` and attribute payloads
|
||||
// are `Copy` or arena-backed, so the record bytes behind the pointer are thread-safe;
|
||||
// `'e` ties the pointer's validity to the shared arena and record-stack discipline.
|
||||
// SAFETY: `element_write` requires the element `Send + Sync` and every field holds an
|
||||
// `Attribute::Value`, which the trait bounds `Send + Sync`, so the record bytes behind
|
||||
// the pointer are thread-safe; `'e` ties the pointer's validity to the shared arena and
|
||||
// record-stack discipline.
|
||||
unsafe impl Send for RecordValue<'_> {}
|
||||
// SAFETY: as `Send`.
|
||||
unsafe impl Sync for RecordValue<'_> {}
|
||||
@@ -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
|
||||
@@ -222,7 +245,9 @@ pub(in crate::record) unsafe fn lift_poll_into<'e, T: Send + Sync + dyn_any::Sta
|
||||
|
||||
/// # Safety
|
||||
/// `src` must be a record of the plan's source layout and `dst` a buffer of
|
||||
/// the plan's target layout; both are proven at wiring.
|
||||
/// the plan's target layout; both are proven at wiring. The two records must
|
||||
/// not overlap: a plan routinely carries identity moves, so each entry copies
|
||||
/// non-overlapping and an aliasing pair is undefined on the first copy.
|
||||
pub unsafe fn apply_plan(src: Rec<'_>, dst: *mut u8, plan: &[(usize, usize, usize)]) {
|
||||
for &(from, to, size) in plan {
|
||||
unsafe { std::ptr::copy_nonoverlapping(src.ptr().add(from), dst.add(to), size) };
|
||||
|
||||
@@ -111,6 +111,7 @@ impl<'e> Frames<'e> {
|
||||
inline: RecordValue::zeroed(),
|
||||
frame,
|
||||
free: self.reborrow(),
|
||||
filled_fields: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,7 +177,6 @@ mod tests {
|
||||
let scope = frames.scope();
|
||||
let mut claim = scope.claim(&layout);
|
||||
addresses.push(claim.dst() as usize);
|
||||
drop(claim);
|
||||
drop(scope);
|
||||
assert_eq!(frames.free_words(), free, "the scope returns its claims");
|
||||
}
|
||||
|
||||
@@ -90,7 +90,10 @@ where
|
||||
let Some(len) = range.end.checked_sub(range.start).and_then(|len| usize::try_from(len).ok()) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
let words = len * node.layout().lane_stride() / 8;
|
||||
// Checked: a wrapped product would size the scratch below the run.
|
||||
let Some(words) = len.checked_mul(node.layout().lane_stride()).map(|bytes| bytes / 8) else {
|
||||
return BatchStatus::InvalidRange;
|
||||
};
|
||||
let exhausted = || {
|
||||
BatchStatus::Error(crate::gpoll::GraphError {
|
||||
kind: crate::gpoll::ErrorKind::ArenaExhausted,
|
||||
@@ -207,15 +210,16 @@ impl<'a, 'e, N> RecordInput<'a, 'e, N> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw lazy input handed to a poll kernel whose input rides records while
|
||||
/// the kernel consumes the plain element.
|
||||
/// # Safety
|
||||
/// `rec` must be a record of the layout the offsets were resolved against
|
||||
/// and `El` its element type; both are proven at wiring.
|
||||
unsafe fn element_only<El: Clone>(rec: Rec<'_>, _reads: &[Option<usize>]) -> El {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { read_element::<El>(rec) }
|
||||
}
|
||||
|
||||
/// The raw lazy input handed to a poll kernel whose input rides records while
|
||||
/// the kernel consumes the plain element.
|
||||
pub struct ElementInput<'a, 'e, Out, N> {
|
||||
node: &'a N,
|
||||
layout: &'a Layout,
|
||||
@@ -513,6 +517,8 @@ impl<El: Clone + 'static, N> RecordExtract<El, N> {
|
||||
// The element copies out by value, so the input's claim dies with
|
||||
// the scope.
|
||||
let scope = frames.scope();
|
||||
// SAFETY: the served value is a record of `self.layout`, whose element is
|
||||
// `El` by the wiring that built this extract.
|
||||
serve_input(&self.edge, input, &scope).map(|value| unsafe { read_element::<El>(self.layout.rec(&value)) })
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ pub struct FieldWrite {
|
||||
pub align: usize,
|
||||
pub type_id: std::any::TypeId,
|
||||
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||
pub repark: Option<unsafe fn(&dyn crate::list::AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>>,
|
||||
pub repark: Option<crate::list::ReparkFn>,
|
||||
/// Hashes the field's content. `None` means the stored bytes are the
|
||||
/// content, which holds for every unparked value.
|
||||
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||
@@ -28,12 +28,18 @@ impl FieldWrite {
|
||||
where
|
||||
A::Value<'static>: graphene_hash::CacheHash + PartialEq + 'static,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live `V`.
|
||||
unsafe fn content_hash<V: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
let mut state = state;
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { &*ptr.cast::<V>() }.cache_hash(&mut state);
|
||||
}
|
||||
/// # Safety
|
||||
/// `a` and `b` must both address a live `V`.
|
||||
unsafe fn content_eq<V: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||
unsafe { &*a.cast::<V>() == &*b.cast::<V>() }
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { *a.cast::<V>() == *b.cast::<V>() }
|
||||
}
|
||||
Self {
|
||||
name: A::NAME,
|
||||
@@ -64,7 +70,7 @@ pub struct FieldDesc {
|
||||
pub align: usize,
|
||||
pub type_id: std::any::TypeId,
|
||||
pub read_erased: unsafe fn(*const u8) -> Box<dyn crate::list::AnyAttributeValue>,
|
||||
pub repark: Option<unsafe fn(&dyn crate::list::AnyAttributeValue, *mut u8, &crate::arena::Arena) -> Option<()>>,
|
||||
pub repark: Option<crate::list::ReparkFn>,
|
||||
/// Hashes the field's content. `None` means the stored bytes are the
|
||||
/// content, which holds for every unparked value.
|
||||
pub content_hash: Option<unsafe fn(*const u8, &mut dyn core::hash::Hasher)>,
|
||||
@@ -132,12 +138,18 @@ impl Eq for ElementWrite {}
|
||||
|
||||
impl Default for ElementWrite {
|
||||
fn default() -> Self {
|
||||
/// # Safety
|
||||
/// None: the empty element has no bytes, so nothing is read.
|
||||
unsafe fn clone_out(_ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
Box::new(())
|
||||
}
|
||||
/// # Safety
|
||||
/// None: nothing is written, the empty element having no slot.
|
||||
unsafe fn repark(_value: &(dyn std::any::Any + Send + Sync), _dst: *mut u8, _arena: &crate::arena::Arena) -> Option<()> {
|
||||
Some(())
|
||||
}
|
||||
/// # Safety
|
||||
/// None: the move always declines, so `parked` is never read.
|
||||
unsafe fn park_move(_parked: *const u8, _promotion: &Promotion<'_>) -> Option<*const u8> {
|
||||
None
|
||||
}
|
||||
@@ -155,6 +167,11 @@ impl Default for ElementWrite {
|
||||
}
|
||||
}
|
||||
|
||||
/// The widest alignment a record may need. Frames are a `Vec<u64>`, lanes
|
||||
/// stride at a multiple of 8, and run slabs come from `alloc_scratch::<u64>`,
|
||||
/// so nothing below a record can promise more.
|
||||
pub const MAX_ALIGN: usize = 8;
|
||||
|
||||
/// A record layout: the element at offset 0, then the written attributes in
|
||||
/// canonical order (descending alignment, then size, then name, then level).
|
||||
/// Layouts are derived data, a pure function of the upstream write set.
|
||||
@@ -198,8 +215,9 @@ impl Layout {
|
||||
|
||||
/// The union of this layout's fields and `writes` over `element` at
|
||||
/// `depth`, in canonical order. A (name, level) written at a different
|
||||
/// size is a type conflict and panics; the census keeps declared names to
|
||||
/// one type, so this only fires on wiring bugs.
|
||||
/// size is a type conflict and panics, as does an element or attribute
|
||||
/// wider than [`MAX_ALIGN`]; the census keeps declared names to one type,
|
||||
/// so these only fire on wiring bugs.
|
||||
pub fn with_writes(&self, depth: u8, element: ElementWrite, writes: &[FieldWrite]) -> Layout {
|
||||
let mut merged: Vec<FieldWrite> = self.fields.iter().map(FieldDesc::as_write).collect();
|
||||
for &write in writes {
|
||||
@@ -208,6 +226,10 @@ impl Layout {
|
||||
None => merged.push(write),
|
||||
}
|
||||
}
|
||||
assert!(element.align <= MAX_ALIGN, "a record element aligns to at most {MAX_ALIGN} bytes, but this one needs {}", element.align);
|
||||
for write in &merged {
|
||||
assert!(write.align <= MAX_ALIGN, "attribute `{}` aligns to at most {MAX_ALIGN} bytes, but needs {}", write.name, write.align);
|
||||
}
|
||||
merged.sort_by(|a, b| b.align.cmp(&a.align).then(b.size.cmp(&a.size)).then(a.name.cmp(b.name)).then(a.level.cmp(&b.level)));
|
||||
let mut offset = element.size;
|
||||
let mut align = element.align.max(1);
|
||||
@@ -334,7 +356,6 @@ pub fn empty_layout() -> &'static Layout {
|
||||
EMPTY.get_or_init(Layout::default)
|
||||
}
|
||||
|
||||
/// Declarative record-io metadata for a node type, emitted by the macro into
|
||||
/// A record node's output layout with the frame size and carrier copy plan derived from it.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct RecordLayout {
|
||||
@@ -345,8 +366,79 @@ 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
|
||||
/// its registry entry so the compiler can fold each input's layout without
|
||||
/// running the node's constructor. [`fold`](LayoutMeta::fold) reproduces the
|
||||
/// layout the constructor derives at wiring today; the compiler layout pass
|
||||
@@ -365,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,
|
||||
@@ -401,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,
|
||||
@@ -436,22 +545,75 @@ impl LayoutMeta {
|
||||
let layout = self.fold(inputs);
|
||||
let frame_bytes = layout.frame_bytes();
|
||||
let plan = match self.sources.first() {
|
||||
// A reducer collapses its carrier's levels, so it writes a fresh record rather than copying fields down.
|
||||
Some(&source) if self.level_delta >= 0 => {
|
||||
let from = inputs[source as usize].expect("layout resolve source input has no layout");
|
||||
let carry_element = matches!(self.element, ElementSpec::Carried);
|
||||
let removes: Vec<(&str, u8)> = self.removes.clone();
|
||||
copy_plan(from, &layout, carry_element, &removes)
|
||||
}
|
||||
// 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
|
||||
@@ -498,22 +660,32 @@ pub fn element_write<T: Clone + Send + Sync + dyn_any::StaticTypeSized>() -> Ele
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
|
||||
unsafe fn clone_out<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||
// SAFETY: the caller's contract; the glue is registered for this element type.
|
||||
return unsafe { (deep.clone_out)(ptr) };
|
||||
}
|
||||
// SAFETY: a lifetime-carrying element type registers deep glue, so
|
||||
// this shallow path only erases borrow-free values.
|
||||
// SAFETY: a lifetime-carrying element type registers deep glue, so this
|
||||
// shallow path only erases borrow-free values. The registration is a
|
||||
// whole-program convention rather than something this call can check:
|
||||
// the executor asserts the in-tree types registered before it evaluates,
|
||||
// which is where a missed wasm registration export is caught.
|
||||
Box::new(unsafe { erase_static(read_element::<T>(Rec::new(ptr))) })
|
||||
}
|
||||
/// # Safety
|
||||
/// `dst` must be fresh element storage of a record whose element is `T`, and
|
||||
/// `value` must be the clone-out this glue produced for that element type.
|
||||
unsafe fn repark<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &crate::arena::Arena) -> Option<()>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
if let Some(deep) = deep_element_glue(std::any::TypeId::of::<T::Static>()) {
|
||||
// SAFETY: the caller's contract; the glue is registered for this element type.
|
||||
return unsafe { (deep.repark)(value, dst, arena) };
|
||||
}
|
||||
let retained = retained_measure(std::any::TypeId::of::<T::Static>()).map_or(0, |measure| measure(value));
|
||||
@@ -558,11 +730,17 @@ pub fn element_write_hashed<T: Clone + Send + Sync + graphene_hash::CacheHash +
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
/// # Safety
|
||||
/// `ptr` must address a live element of `T` in the form [`element_parked`] picks.
|
||||
unsafe fn content_hash<T: graphene_hash::CacheHash>(ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
let mut state = state;
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { borrow_element::<T>(Rec::new(ptr)) }.cache_hash(&mut state);
|
||||
}
|
||||
/// # Safety
|
||||
/// `a` and `b` must each address a live element of `T` in that same form.
|
||||
unsafe fn content_eq<T: PartialEq>(a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { borrow_element::<T>(Rec::new(a)) == borrow_element::<T>(Rec::new(b)) }
|
||||
}
|
||||
ElementWrite {
|
||||
@@ -619,6 +797,18 @@ mod tests {
|
||||
assert_eq!(layout.align, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "a record element aligns to at most 8 bytes")]
|
||||
fn an_over_aligned_element_is_refused_at_wiring() {
|
||||
Layout::default().with_writes(0, element_write::<u128>(), &[]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "attribute `wide` aligns to at most 8 bytes")]
|
||||
fn an_over_aligned_attribute_is_refused_at_wiring() {
|
||||
Layout::default().with_writes(0, element_write::<f64>(), &[sized_field("wide", 16, 16)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "two different types")]
|
||||
fn type_conflicts_panic() {
|
||||
@@ -656,7 +846,7 @@ mod tests {
|
||||
#[derive(Clone, dyn_any::DynAny)]
|
||||
struct Opaque;
|
||||
|
||||
let hashed = (&ElementWritePick::<String>(std::marker::PhantomData)).element_write();
|
||||
let hashed = ElementWritePick::<String>(std::marker::PhantomData).element_write();
|
||||
assert!(hashed.content_hash.is_some() && hashed.content_eq.is_some());
|
||||
let plain = (&ElementWritePick::<Opaque>(std::marker::PhantomData)).element_write();
|
||||
assert!(plain.content_hash.is_none() && plain.content_eq.is_none());
|
||||
|
||||
@@ -21,16 +21,16 @@ mod serve;
|
||||
mod test_support;
|
||||
mod testkit;
|
||||
|
||||
pub use access::{Rec, RecordValue, apply_plan, borrow_element, erase_static, read_at, read_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, register_deep_element_clone, register_deep_field_value, replay_field_value};
|
||||
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};
|
||||
pub use route::{RecordSource, SourcePlan};
|
||||
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView};
|
||||
pub use run::{Group, GroupItem, RunBuilder, RunColumn, RunView, run_to_owned_list};
|
||||
pub use serve::{FrameClaim, MaterializedSpan, Served, SlotRun, serve_input};
|
||||
pub use testkit::{LiftedSource, ServedRecord, capture, test_frames};
|
||||
@@ -32,6 +32,13 @@ pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<
|
||||
DEEP_ELEMENT_CLONES.lock().unwrap().get(&type_id).copied()
|
||||
}
|
||||
|
||||
/// Whether elements of a type registered deep glue. The shallow clone path is
|
||||
/// only sound for types that did not need to, so a host that drives the
|
||||
/// registration itself checks the types it owes before it evaluates anything.
|
||||
pub fn has_deep_element_glue(type_id: std::any::TypeId) -> bool {
|
||||
DEEP_ELEMENT_CLONES.lock().unwrap().contains_key(&type_id)
|
||||
}
|
||||
|
||||
/// Deep-copy overrides for field values whose content borrows the
|
||||
/// evaluation's arena (a graphic list holding native groups), keyed by the
|
||||
/// field's owned value form. Consulted at the persistence seams only:
|
||||
@@ -43,17 +50,14 @@ pub(in crate::record) fn deep_element_glue(type_id: std::any::TypeId) -> Option<
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::record) struct DeepFieldGlue {
|
||||
pub(in crate::record) copy_out: fn(&dyn crate::list::AnyAttributeValue) -> Option<Box<dyn crate::list::AnyAttributeValue>>,
|
||||
pub(in crate::record) replay: fn(&dyn crate::list::AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>>,
|
||||
pub(in crate::record) replay: crate::list::FieldReplayFn,
|
||||
}
|
||||
|
||||
static DEEP_FIELD_VALUES: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<std::any::TypeId, DeepFieldGlue>>> = std::sync::LazyLock::new(Default::default);
|
||||
|
||||
/// 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: fn(&dyn crate::list::AnyAttributeValue, &crate::arena::Arena) -> Option<Option<Box<dyn crate::list::AnyAttributeValue>>>,
|
||||
) {
|
||||
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 });
|
||||
}
|
||||
|
||||
@@ -87,7 +91,10 @@ pub fn replay_field_value(value: &dyn crate::list::AnyAttributeValue, arena: &cr
|
||||
pub struct OwnedRecord {
|
||||
pub(in crate::record) bytes: Box<[u8]>,
|
||||
pub(in crate::record) element: Option<Box<dyn std::any::Any + Send + Sync>>,
|
||||
fields: Vec<(usize, Box<dyn crate::list::AnyAttributeValue>)>,
|
||||
/// Each copied field's index in the copy's layout, that field's declared
|
||||
/// value type, and the owned value. The type rides along so a replay can
|
||||
/// re-check the field it resolves rather than trusting the caller's claim.
|
||||
fields: Vec<(usize, std::any::TypeId, Box<dyn crate::list::AnyAttributeValue>)>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for OwnedRecord {
|
||||
@@ -100,35 +107,61 @@ impl OwnedRecord {
|
||||
/// # Safety
|
||||
/// `rec` must be a live record of `layout`.
|
||||
pub unsafe fn copy_out(layout: &Layout, rec: Rec<'_>) -> OwnedRecord {
|
||||
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(rec.ptr(), layout.size) }.into();
|
||||
// The element-to-field seam is never written, so the copy stays untyped:
|
||||
// a `&[u8]` over the frame would read those bytes.
|
||||
let mut staged = Vec::<u8>::with_capacity(layout.size);
|
||||
// SAFETY: the caller's contract sizes the record at `layout.size`, which
|
||||
// is the capacity just reserved, so the copy fills exactly the staging.
|
||||
let bytes = unsafe {
|
||||
std::ptr::copy_nonoverlapping(rec.ptr(), staged.as_mut_ptr(), layout.size);
|
||||
staged.set_len(layout.size);
|
||||
staged.into_boxed_slice()
|
||||
};
|
||||
// SAFETY: the caller's contract; a parked element sits at offset 0.
|
||||
let element = layout.element.parked.then(|| unsafe { (layout.element.clone_out)(rec.ptr()) });
|
||||
let fields = layout
|
||||
.fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, field)| field.repark.is_some())
|
||||
.map(|(index, field)| (index, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
|
||||
// SAFETY: the caller's contract; each field reads its own descriptor's offset.
|
||||
.map(|(index, field)| (index, field.type_id, deepen_field_value(unsafe { (field.read_erased)(rec.ptr().add(field.offset)) })))
|
||||
.collect();
|
||||
OwnedRecord { bytes, element, fields }
|
||||
}
|
||||
|
||||
/// Replays the copy into a caller's claim, re-parking droppable payloads
|
||||
/// against `arena`; the claim's layout is the one the copy was taken at,
|
||||
/// and `None` reports arena exhaustion.
|
||||
/// against `arena`; `None` reports arena exhaustion. The claim's layout must
|
||||
/// be the one the copy was taken at, which the checks below establish rather
|
||||
/// than assume: the copy carries no layout of its own, so a mismatched claim
|
||||
/// would otherwise write past the frame or re-park a field through another
|
||||
/// field's glue.
|
||||
pub fn replay_into(&self, slot: &mut FrameClaim<'_, '_>, arena: &crate::arena::Arena) -> Option<()> {
|
||||
let layout = slot.layout;
|
||||
assert_eq!(self.bytes.len(), layout.size, "a replay lands in the layout the copy was taken at");
|
||||
assert_eq!(self.element.is_some(), layout.element.parked, "a replay lands in the layout the copy was taken at");
|
||||
for &(index, type_id, _) in &self.fields {
|
||||
let field = layout.fields.get(index).expect("a replay lands in the layout the copy was taken at");
|
||||
assert_eq!(field.type_id, type_id, "a replay lands in the layout the copy was taken at");
|
||||
}
|
||||
self.write_into(layout, slot.dst(), arena)
|
||||
}
|
||||
|
||||
/// `dst` is a claimed frame of `layout`, and `replay_into`'s asserts have
|
||||
/// established that `layout` is the one the copy was taken at.
|
||||
fn write_into(&self, layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
// SAFETY: the copy is `layout.size` bytes and the claim is a frame of it.
|
||||
unsafe { std::ptr::copy_nonoverlapping(self.bytes.as_ptr(), dst, self.bytes.len()) };
|
||||
if let Some(element) = &self.element {
|
||||
// SAFETY: the element was cloned out of this layout's own slot at offset 0.
|
||||
unsafe { (layout.element.repark)(&**element, dst, arena) }?;
|
||||
}
|
||||
for (index, value) in &self.fields {
|
||||
for (index, _, value) in &self.fields {
|
||||
let field = &layout.fields[*index];
|
||||
let repark = field.repark.expect("copied fields carry re-park glue");
|
||||
let resident = replay_field_value(&**value, arena)?;
|
||||
// SAFETY: the asserts matched this index's field type, so the glue and
|
||||
// the value agree; the write lands in that field's own region.
|
||||
unsafe { repark(resident.as_deref().unwrap_or(&**value), dst.add(field.offset), arena) }?;
|
||||
}
|
||||
Some(())
|
||||
@@ -142,6 +175,34 @@ mod tests {
|
||||
use crate::record::frames::FrameArena;
|
||||
use crate::record::layout::{FieldWrite, element_write};
|
||||
|
||||
#[test]
|
||||
fn a_padded_layout_copies_out_without_reading_its_seam() {
|
||||
// A 4-byte element before an 8-aligned field leaves [4, 8) unwritten.
|
||||
let layout = Layout::default().with_writes(0, element_write::<u32>(), &[FieldWrite::of::<crate::attribute::Opacity>(0)]);
|
||||
let offset = layout.offset_of("opacity", 0).unwrap();
|
||||
assert_eq!((layout.element.size, offset), (4, 8), "the fixture needs the element-to-field seam");
|
||||
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let scratch = arena.alloc_scratch::<u64>(layout.frame_bytes().div_ceil(8)).unwrap();
|
||||
let base: *mut u8 = scratch.as_mut_ptr().cast();
|
||||
unsafe { write_element(base, 7u32, &arena) }.unwrap();
|
||||
unsafe { write_field::<f64>(base, offset, 0.5) };
|
||||
|
||||
let copy = unsafe { OwnedRecord::copy_out(&layout, Rec::new(base.cast_const())) };
|
||||
|
||||
let replay_arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(layout.frame_bytes());
|
||||
let frames = frame_arena.frames();
|
||||
let mut slot = frames.claim(&layout);
|
||||
copy.replay_into(&mut slot, &replay_arena).unwrap();
|
||||
// SAFETY: the replay completes the record in the claimed frame.
|
||||
let value = unsafe { slot.finish() };
|
||||
let rec = layout.rec(&value);
|
||||
assert_eq!(unsafe { read_element::<u32>(rec) }, 7);
|
||||
assert_eq!(unsafe { rec.read::<f64>(offset) }, 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_records_replay_re_parked_payloads_after_the_source_dies() {
|
||||
let layout = Layout::default().with_writes(0, element_write::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
|
||||
|
||||
@@ -99,6 +99,7 @@ pub(in crate::record) unsafe fn promote_record(layout: &Layout, dst: *mut u8, pr
|
||||
None => {
|
||||
// SAFETY: as above, and the clone owns its content.
|
||||
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
|
||||
// SAFETY: the clone is this element's own type, back into its slot.
|
||||
unsafe { (layout.element.repark)(&*owned, dst, promotion.persistent) }?;
|
||||
}
|
||||
},
|
||||
@@ -243,6 +244,7 @@ impl MaterializedSpan {
|
||||
// SAFETY: the caller's contract on the lane, into the lane's own
|
||||
// region of the freshly reserved slab.
|
||||
let dst = unsafe { base.add(lane * stride) };
|
||||
// SAFETY: as above; `layout.size` bytes of a lane fit its own stride.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, layout.size) };
|
||||
// SAFETY: the copy images a record of this layout.
|
||||
unsafe { promote_record(layout, dst, promotion) }?;
|
||||
@@ -370,7 +372,7 @@ mod tests {
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
let length = "shared across lanes".len();
|
||||
unsafe { write_element_sized(base, String::from("shared across lanes"), &transient, length) }.unwrap();
|
||||
// A carried field byte-copies the reference, so both lanes name the one park.
|
||||
// A carried element byte-copies its park reference, so both lanes name the one park.
|
||||
let shared = unsafe { base.cast::<*const u8>().read() };
|
||||
unsafe { base.add(stride).cast::<*const u8>().write(shared) };
|
||||
|
||||
|
||||
@@ -48,9 +48,11 @@ impl SourcePlan {
|
||||
|
||||
/// # Safety
|
||||
/// `src` must be a record of this plan's source layout and `dst` a
|
||||
/// buffer of the plan's union layout. The returned view borrows `dst`, so
|
||||
/// `'d` must not outlive it.
|
||||
/// buffer of the plan's union layout that does not overlap `src`. The
|
||||
/// returned view borrows `dst`, so `'d` must not outlive it.
|
||||
pub unsafe fn translate<'d>(&self, src: Rec<'_>, dst: *mut u8) -> Rec<'d> {
|
||||
// SAFETY: the caller's contract; the plan's moves and fills name only
|
||||
// offsets of the layouts it was built from.
|
||||
unsafe {
|
||||
apply_plan(src, dst, &self.moves);
|
||||
for (offset, bytes) in &self.fills {
|
||||
@@ -97,7 +99,7 @@ where
|
||||
let Some(plan) = &self.plan else {
|
||||
return self.edge.serve(input, slot);
|
||||
};
|
||||
match serve_input(&self.edge, input, &mut slot.frames().reborrow()) {
|
||||
match serve_input(&self.edge, input, &slot.frames().reborrow()) {
|
||||
GPoll::Final(value) => {
|
||||
// SAFETY: the value came from this source, so it carries the
|
||||
// plan's source layout.
|
||||
|
||||
@@ -2,9 +2,53 @@
|
||||
|
||||
use super::access::write_element;
|
||||
use super::layout::{ElementWrite, FieldOffset, FieldWrite, Layout, element_write_hashed};
|
||||
use super::owned::deep_field_glue;
|
||||
use super::owned::{deep_field_glue, deepen_field_value, replay_field_value};
|
||||
use super::promote::{Promotion, promote_record};
|
||||
|
||||
/// A group's element is compared and hashed by content, so it needs glue: the
|
||||
/// byte fallback would read a padded element type's uninitialized padding.
|
||||
fn assert_element_glue(layout: &Layout) {
|
||||
assert!(
|
||||
layout.element.size == 0 || layout.element.content_hash.is_some(),
|
||||
"a run's element adopts only with content glue; declare it with `element_write_hashed`"
|
||||
);
|
||||
}
|
||||
|
||||
/// Whether a lane of `layout` names payloads a byte copy would leave parked in
|
||||
/// the source arena.
|
||||
fn holds_parked(layout: &Layout) -> bool {
|
||||
layout.element.parked || layout.fields.iter().any(|field| field.repark.is_some())
|
||||
}
|
||||
|
||||
/// Re-parks one copied lane's payloads into `arena`, so a lane copied across
|
||||
/// arenas owns what it names instead of pointing back at the source's parks.
|
||||
/// The counterpart of [`promote_record`] for a copy whose target is a serving
|
||||
/// arena rather than the persistent region, so every reference clones.
|
||||
/// `None` reports arena exhaustion.
|
||||
///
|
||||
/// # Safety
|
||||
/// `dst` must image a live record of `layout` whose parked references still
|
||||
/// resolve, which is the source lane's own image before this rewrites it.
|
||||
unsafe fn readopt_record(layout: &Layout, dst: *mut u8, arena: &crate::arena::Arena) -> Option<()> {
|
||||
if layout.element.parked {
|
||||
// SAFETY: the caller's contract; the clone owns all of its content.
|
||||
let owned = unsafe { (layout.element.clone_out)(dst.cast_const()) };
|
||||
// SAFETY: the clone is the element's own type, into its own slot.
|
||||
unsafe { (layout.element.repark)(&*owned, dst, arena) }?;
|
||||
}
|
||||
for field in &layout.fields {
|
||||
let Some(repark) = field.repark else { continue };
|
||||
// SAFETY: a parked field slot holds one reference at its offset.
|
||||
let slot = unsafe { dst.add(field.offset) };
|
||||
// SAFETY: the slot images a parked field of this descriptor.
|
||||
let value = deepen_field_value(unsafe { (field.read_erased)(slot.cast_const()) });
|
||||
let resident = replay_field_value(&*value, arena)?;
|
||||
// SAFETY: the replay produced this field's own value type.
|
||||
unsafe { repark(resident.as_deref().unwrap_or(&*value), slot, arena) }?;
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Builds a resident run lane by lane: fresh frames in the arena at a layout
|
||||
/// derived from the element glue and field writes, elements pushed in order
|
||||
/// and attributes written onto pushed lanes. The finished item's frames are
|
||||
@@ -22,7 +66,7 @@ impl<'e> RunBuilder<'e> {
|
||||
/// `None` reports arena exhaustion.
|
||||
pub fn new(arena: &'e crate::arena::Arena, element: ElementWrite, fields: &[FieldWrite], len: usize) -> Option<Self> {
|
||||
let layout = Layout::default().with_writes(0, element, fields);
|
||||
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
|
||||
assert_element_glue(&layout);
|
||||
for field in &layout.fields {
|
||||
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
|
||||
}
|
||||
@@ -52,6 +96,8 @@ impl<'e> RunBuilder<'e> {
|
||||
// `lane` is below `len`; the element slot and each field's region are
|
||||
// disjoint parts of this lane.
|
||||
let base = unsafe { self.frames.add(lane * stride) };
|
||||
// SAFETY: the element slot is fresh, and the assert above matched `T` to
|
||||
// the layout's element type.
|
||||
unsafe { write_element(base, element, self.arena) }?;
|
||||
for field in &self.layout.fields {
|
||||
// SAFETY: as above; the field region is within the lane.
|
||||
@@ -89,13 +135,23 @@ impl<'e> RunBuilder<'e> {
|
||||
|
||||
/// Writes a legacy stored value on an already pushed lane through the
|
||||
/// census glue, parking droppable payloads. A marker outside the layout's
|
||||
/// fields is dropped; a wrong-typed stored value leaves the field's
|
||||
/// fields is dropped, as is one whose row and field agree on the name but
|
||||
/// not on the value type; a wrong-typed stored value leaves the field's
|
||||
/// default. `None` reports arena exhaustion.
|
||||
pub fn attr_stored(&mut self, lane: usize, info: &crate::attribute::AttributeInfo, value: &dyn crate::list::AnyAttributeValue) -> Option<()> {
|
||||
assert!(lane < self.pushed, "attributes write onto pushed lanes");
|
||||
let Some(offset) = self.layout.offset_of(info.name, 0) else { return Some(()) };
|
||||
// SAFETY: the offset comes from the builder's own layout, and the
|
||||
// census writer verifies the stored type before touching the field.
|
||||
let Some(field) = self.layout.fields.iter().find(|field| field.name == info.name && field.level == 0) else {
|
||||
return Some(());
|
||||
};
|
||||
let (offset, size, type_id) = (field.offset, field.size, field.type_id);
|
||||
// The row reaches the field by name alone, so the writer's own value type
|
||||
// is checked against the field before its glue writes there, as `push`
|
||||
// checks the default writer's.
|
||||
if info.size != size || info.value_type != type_id {
|
||||
return Some(());
|
||||
}
|
||||
// SAFETY: the offset comes from the builder's own layout, and the field
|
||||
// was just checked to hold the writer's own value type at its size.
|
||||
unsafe { (info.write_stored)(value, self.frames.add(lane * self.layout.lane_stride() + offset), self.arena) }
|
||||
}
|
||||
|
||||
@@ -151,9 +207,7 @@ struct OwnedLanes {
|
||||
fields: Vec<(usize, Vec<Box<dyn crate::list::AnyAttributeValue>>)>,
|
||||
}
|
||||
|
||||
// SAFETY: the same argument as for `RecordValue`. The element bounds and the
|
||||
// parking discipline make the record bytes thread-safe, and their validity
|
||||
// is tied to the shared arena.
|
||||
// SAFETY: as for `RecordValue`.
|
||||
unsafe impl Send for GroupItem<'_> {}
|
||||
// SAFETY: as `Send`.
|
||||
unsafe impl Sync for GroupItem<'_> {}
|
||||
@@ -162,10 +216,11 @@ impl<'e> GroupItem<'e> {
|
||||
/// Copies the batch's lanes into the arena and clones its layout.
|
||||
/// Returns `None` when the arena is exhausted. Parked regions must carry
|
||||
/// the content glue, so equality and hashing never fall back to pointer
|
||||
/// bytes.
|
||||
/// bytes. A copied lane's parked payloads re-park into `arena`, so the
|
||||
/// adopted run names nothing the source arena's reset frees.
|
||||
pub fn adopt(batch: crate::node::RecordBatch<'_>, arena: &'e crate::arena::Arena) -> Option<Self> {
|
||||
let layout = batch.layout().clone();
|
||||
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
|
||||
assert_element_glue(&layout);
|
||||
for field in &layout.fields {
|
||||
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
|
||||
}
|
||||
@@ -173,7 +228,7 @@ impl<'e> GroupItem<'e> {
|
||||
// A run already living in the target region needs no copy: the arena is
|
||||
// insert-only within a generation, so the lanes cannot move or change
|
||||
// while the adopting item borrows them.
|
||||
if batch.len() > 0 && arena.contains(batch.frames_ptr()) {
|
||||
if !batch.is_empty() && arena.contains(batch.frames_ptr()) {
|
||||
return Some(Self {
|
||||
layout,
|
||||
storage: ItemStorage::Resident(batch.frames_ptr()),
|
||||
@@ -183,9 +238,16 @@ impl<'e> GroupItem<'e> {
|
||||
}
|
||||
let scratch = arena.alloc_scratch::<u64>((batch.len() * stride).div_ceil(8))?;
|
||||
let frames = scratch.as_mut_ptr().cast::<u8>();
|
||||
let parked = holds_parked(&layout);
|
||||
for lane in 0..batch.len() {
|
||||
// SAFETY: both sides hold `len` lanes at the shared layout's stride.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), frames.add(lane * stride), stride) };
|
||||
let dst = unsafe { frames.add(lane * stride) };
|
||||
// SAFETY: as above; the scratch was reserved for exactly these lanes.
|
||||
unsafe { std::ptr::copy_nonoverlapping(batch.get(lane).rec().ptr(), dst, stride) };
|
||||
if parked {
|
||||
// SAFETY: the copy images a live record of this layout.
|
||||
unsafe { readopt_record(&layout, dst, arena) }?;
|
||||
}
|
||||
}
|
||||
Some(Self {
|
||||
layout,
|
||||
@@ -241,11 +303,14 @@ impl<'e> GroupItem<'e> {
|
||||
/// A `GroupItem` over the batch's frames, without copying.
|
||||
///
|
||||
/// # Safety
|
||||
/// The frames must stay valid for the evaluation. Arena-resident batches
|
||||
/// qualify, caller stack scratch does not.
|
||||
/// The item borrows the batch's frames at `'e`, so the frames must stay
|
||||
/// valid for the whole of `'e` and nothing derived from the item may outlive
|
||||
/// it. Arena-resident batches span the evaluation; a caller's serve scratch
|
||||
/// spans only the window it lends the batch for, which is sound exactly when
|
||||
/// `'e` is bounded to that window.
|
||||
pub unsafe fn from_resident(batch: crate::node::RecordBatch<'e>) -> Self {
|
||||
let layout = batch.layout().clone();
|
||||
assert!(!layout.element.parked || layout.element.content_hash.is_some(), "a parked element adopts only with content glue");
|
||||
assert_element_glue(&layout);
|
||||
for field in &layout.fields {
|
||||
assert!(field.repark.is_none() || field.content_hash.is_some(), "a parked field adopts only with content glue");
|
||||
}
|
||||
@@ -281,11 +346,19 @@ impl<'e> GroupItem<'e> {
|
||||
let frames = self.frames();
|
||||
// SAFETY: the constructors store `len` lanes of `layout` at the
|
||||
// layout's stride, and the erased glue reads each lane's own region.
|
||||
let bytes: Box<[u8]> = unsafe { std::slice::from_raw_parts(frames, self.len * stride) }.into();
|
||||
// A lane's seam and stride tail are never written, so the copy stays
|
||||
// untyped: a `&[u8]` over the frames would read those bytes.
|
||||
let mut staged = Vec::<u8>::with_capacity(self.len * stride);
|
||||
let bytes = unsafe {
|
||||
std::ptr::copy_nonoverlapping(frames, staged.as_mut_ptr(), self.len * stride);
|
||||
staged.set_len(self.len * stride);
|
||||
staged.into_boxed_slice()
|
||||
};
|
||||
let elements = self
|
||||
.layout
|
||||
.element
|
||||
.parked
|
||||
// SAFETY: as above; a parked element sits at each lane's offset 0.
|
||||
.then(|| (0..self.len).map(|lane| unsafe { (self.layout.element.clone_out)(frames.add(lane * stride)) }).collect());
|
||||
let fields = self
|
||||
.layout
|
||||
@@ -294,6 +367,7 @@ impl<'e> GroupItem<'e> {
|
||||
.enumerate()
|
||||
.filter(|(_, field)| field.repark.is_some())
|
||||
.map(|(index, field)| {
|
||||
// SAFETY: as above; each lane reads this descriptor's own offset.
|
||||
let mut values: Vec<_> = (0..self.len).map(|lane| unsafe { (field.read_erased)(frames.add(lane * stride + field.offset)) }).collect();
|
||||
if let Some(glue) = values.first().and_then(|value| deep_field_glue(value.as_any().type_id())) {
|
||||
for value in &mut values {
|
||||
@@ -314,12 +388,13 @@ impl<'e> GroupItem<'e> {
|
||||
}
|
||||
|
||||
/// Re-parks an owned item's lanes into `arena`, restoring the resident
|
||||
/// form; `None` reports arena exhaustion. A resident item returns a plain
|
||||
/// clone.
|
||||
/// form; `None` reports arena exhaustion. A resident item re-adopts into
|
||||
/// `arena`, sharing only where its lanes already live there.
|
||||
pub fn replay<'a>(&self, arena: &'a crate::arena::Arena) -> Option<GroupItem<'a>> {
|
||||
let ItemStorage::Owned(owned) = &self.storage else {
|
||||
// A resident item re-serves at the target arena's own lifetime,
|
||||
// so its lanes copy rather than relabeling the borrow.
|
||||
// A resident item re-serves at the target arena's own lifetime, so
|
||||
// its lanes copy and their parked payloads re-park there rather
|
||||
// than relabeling the borrow.
|
||||
return GroupItem::adopt(self.lanes(), arena);
|
||||
};
|
||||
let stride = self.layout.lane_stride();
|
||||
@@ -330,6 +405,7 @@ impl<'e> GroupItem<'e> {
|
||||
unsafe { std::ptr::copy_nonoverlapping(owned.bytes.as_ptr(), frames, owned.bytes.len()) };
|
||||
if let Some(elements) = &owned.elements {
|
||||
for (lane, element) in elements.iter().enumerate() {
|
||||
// SAFETY: as above; the clone is this element's own type, into its lane's slot.
|
||||
unsafe { (self.layout.element.repark)(&**element, frames.add(lane * stride), arena) }?;
|
||||
}
|
||||
}
|
||||
@@ -338,6 +414,8 @@ impl<'e> GroupItem<'e> {
|
||||
let repark = field.repark.expect("copied fields carry re-park glue");
|
||||
let glue = values.first().and_then(|value| deep_field_glue(value.as_any().type_id()));
|
||||
for (lane, value) in values.iter().enumerate() {
|
||||
// SAFETY: the copy took these values through this field's own glue,
|
||||
// so each writes its own type into its lane's region of the field.
|
||||
match glue {
|
||||
Some(glue) => match (glue.replay)(&**value, arena)? {
|
||||
Some(resident) => unsafe { repark(&*resident, frames.add(lane * stride + field.offset), arena) }?,
|
||||
@@ -402,6 +480,25 @@ impl<'e> GroupItem<'e> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One typed run as an owned legacy list, elements cloned and every attribute
|
||||
/// copied through its erased read. The owned result outlives the evaluation the
|
||||
/// run was materialized in, so an async source can carry it across its await.
|
||||
pub fn run_to_owned_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &GroupItem) -> Option<crate::list::List<T>> {
|
||||
let lanes = item.typed_lanes::<T>()?;
|
||||
let mut list = crate::list::List::new();
|
||||
for lane in 0..lanes.len() {
|
||||
list.push(crate::list::Item::new_from_element(lanes.element_ref(lane).clone()));
|
||||
}
|
||||
for field in &item.layout().fields {
|
||||
for lane in 0..lanes.len() {
|
||||
// SAFETY: the offset comes from the item's own layout.
|
||||
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
|
||||
list.set_attribute_value_dyn(field.name, lane, crate::list::AttributeValueDyn(value));
|
||||
}
|
||||
}
|
||||
Some(list)
|
||||
}
|
||||
|
||||
/// A run read at its element type. Record fields hold each marker's value
|
||||
/// verbatim, so lane reads are plain typed reads at a hoisted offset.
|
||||
pub struct RunView<'a, T> {
|
||||
@@ -480,8 +577,7 @@ impl<T: crate::bounds::BoundingBox + dyn_any::StaticTypeSized> crate::bounds::Bo
|
||||
|
||||
/// Records nested inside one element: a single homogeneous run. The `row`
|
||||
/// holds the group's own attribute record. A group that sits on a lane leaves
|
||||
/// it `None`, because that lane's record carries the attributes. The typed
|
||||
/// segment stack returns when merge constructs segments.
|
||||
/// it `None`, because that lane's record carries the attributes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Group<'e> {
|
||||
pub row: Option<GroupItem<'e>>,
|
||||
@@ -525,15 +621,26 @@ impl<'e> Group<'e> {
|
||||
}
|
||||
|
||||
/// Compares one record region of `layout` by content. Regions without glue
|
||||
/// compare as bytes, which is the content for unparked values.
|
||||
/// compare as bytes, which is the content for unparked values. Only written
|
||||
/// spans are read: the element's own bytes and each field's own bytes, never
|
||||
/// the element-to-field seam or the lane's stride tail, which no writer
|
||||
/// touches. The element always carries glue (`assert_element_glue`) and
|
||||
/// `FieldWrite::of` always installs field glue, so a padded value's own
|
||||
/// padding never reaches the byte fallback either.
|
||||
///
|
||||
/// # Safety
|
||||
/// `a` and `b` must both be live records of `layout`.
|
||||
unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool {
|
||||
// SAFETY: the caller's contract; each call reads a written span of the layout.
|
||||
let bytes_eq = |offset: usize, size: usize| unsafe { std::slice::from_raw_parts(a.add(offset), size) == std::slice::from_raw_parts(b.add(offset), size) };
|
||||
let element = match layout.element.content_eq {
|
||||
// SAFETY: the caller's contract; the glue is the element's own.
|
||||
Some(eq) => unsafe { eq(a, b) },
|
||||
None => bytes_eq(0, layout.element.size),
|
||||
};
|
||||
element
|
||||
&& layout.fields.iter().all(|field| match field.content_eq {
|
||||
// SAFETY: as above, at this descriptor's own offset.
|
||||
Some(eq) => unsafe { eq(a.add(field.offset), b.add(field.offset)) },
|
||||
None => bytes_eq(field.offset, field.size),
|
||||
})
|
||||
@@ -541,14 +648,21 @@ unsafe fn record_content_eq(layout: &Layout, a: *const u8, b: *const u8) -> bool
|
||||
|
||||
/// Hashes one record region of `layout` by content, with the byte fallback
|
||||
/// of [`record_content_eq`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `ptr` must be a live record of `layout`.
|
||||
unsafe fn record_content_hash(layout: &Layout, ptr: *const u8, state: &mut dyn core::hash::Hasher) {
|
||||
match layout.element.content_hash {
|
||||
// SAFETY: the caller's contract; the glue is the element's own.
|
||||
Some(hash) => unsafe { hash(ptr, state) },
|
||||
// SAFETY: as above; the element's own bytes are written.
|
||||
None => state.write(unsafe { std::slice::from_raw_parts(ptr, layout.element.size) }),
|
||||
}
|
||||
for field in &layout.fields {
|
||||
match field.content_hash {
|
||||
// SAFETY: as above, at this descriptor's own offset.
|
||||
Some(hash) => unsafe { hash(ptr.add(field.offset), state) },
|
||||
// SAFETY: as above; the field's own bytes are written.
|
||||
None => state.write(unsafe { std::slice::from_raw_parts(ptr.add(field.offset), field.size) }),
|
||||
}
|
||||
}
|
||||
@@ -584,7 +698,7 @@ impl graphene_hash::CacheHash for GroupItem<'_> {
|
||||
let stride = self.layout.lane_stride();
|
||||
let frames = self.frames();
|
||||
for lane in 0..self.len {
|
||||
// SAFETY: `adopt` filled `len` lanes of `layout`.
|
||||
// SAFETY: the constructors store `len` lanes of `layout` at the layout's stride.
|
||||
unsafe { record_content_hash(&self.layout, frames.add(lane * stride), state) };
|
||||
}
|
||||
}
|
||||
@@ -610,7 +724,6 @@ impl graphene_hash::CacheHash for Group<'_> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::record::access::{read_element, write_field};
|
||||
use crate::record::layout::element_write;
|
||||
use crate::record::test_support::f64_field;
|
||||
|
||||
#[test]
|
||||
@@ -621,7 +734,7 @@ mod tests {
|
||||
|
||||
let arena = crate::arena::Arena::new(4096).unwrap();
|
||||
let transform = DAffine2::from_translation((5., 6.).into());
|
||||
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Transform>(0), FieldWrite::of::<Opacity>(0)], 2).unwrap();
|
||||
for lane in 0..2 {
|
||||
let lane = builder.push(lane as f64).unwrap();
|
||||
builder.attr::<Transform>(lane, transform);
|
||||
@@ -651,7 +764,7 @@ mod tests {
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write::<f64>(), &[], 1).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[], 1).unwrap();
|
||||
builder.push(0f64).unwrap();
|
||||
let item = builder.finish();
|
||||
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
|
||||
@@ -663,7 +776,7 @@ mod tests {
|
||||
fn an_interior_run_already_persistent_is_shared() {
|
||||
let transient = crate::arena::Arena::new(4096).unwrap();
|
||||
let persistent = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
|
||||
let stride = layout.lane_stride();
|
||||
|
||||
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
|
||||
@@ -685,7 +798,7 @@ mod tests {
|
||||
#[test]
|
||||
fn adopting_within_one_region_shares_the_run() {
|
||||
let arena = crate::arena::Arena::new(4096).unwrap();
|
||||
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
|
||||
let stride = layout.lane_stride();
|
||||
|
||||
let mut buffer = vec![0u64; (2 * stride).div_ceil(8)];
|
||||
@@ -705,7 +818,7 @@ mod tests {
|
||||
#[test]
|
||||
fn adopted_lanes_round_trip_through_the_group_item() {
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let layout = Layout::default().with_writes(1, element_write::<f64>(), &[f64_field("opacity")]);
|
||||
let layout = Layout::default().with_writes(1, element_write_hashed::<f64>(), &[f64_field("opacity")]);
|
||||
let stride = layout.lane_stride();
|
||||
let offset = layout.offset_of("opacity", 0).unwrap();
|
||||
|
||||
@@ -733,6 +846,34 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cross_arena_adopt_re_parks_what_the_lanes_name() {
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let mut source = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
let target = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let adopted = {
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)], 2).unwrap();
|
||||
for lane in 0..2 {
|
||||
let lane = builder.push(format!("element {lane}")).unwrap();
|
||||
let (name, _) = source.alloc(format!("field {lane}")).unwrap();
|
||||
builder.attr::<crate::attribute::Name>(lane, name.as_str());
|
||||
}
|
||||
let item = builder.finish();
|
||||
GroupItem::adopt(item.lanes(), &target).unwrap()
|
||||
};
|
||||
// The adopted run must own what it names: the source's flush frees every
|
||||
// payload the lanes were built over.
|
||||
source.reset();
|
||||
|
||||
let run = RunView::<String>::new(&adopted).expect("the run holds string elements");
|
||||
for lane in 0..2 {
|
||||
assert_eq!(run.element(lane).map(String::as_str), Some(format!("element {lane}").as_str()), "lane {lane}");
|
||||
assert_eq!(run.attr::<crate::attribute::Name>(lane), format!("field {lane}"), "lane {lane}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_content_equality_and_hashing_read_through_the_park() {
|
||||
use graphene_hash::CacheHash;
|
||||
@@ -771,20 +912,21 @@ mod tests {
|
||||
fn owned_items_replay_re_parked_payloads_after_the_source_dies() {
|
||||
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[FieldWrite::of::<crate::attribute::Name>(0)]);
|
||||
let stride = layout.lane_stride();
|
||||
let mut bytes = vec![0u8; stride * 2];
|
||||
// Word storage: the parked element and the `&str` field are 8-aligned.
|
||||
let mut bytes = vec![0u64; (stride * 2).div_ceil(8)];
|
||||
|
||||
let owned = {
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
for lane in 0..2 {
|
||||
let base = unsafe { bytes.as_mut_ptr().add(lane * stride) };
|
||||
let base = unsafe { bytes.as_mut_ptr().cast::<u8>().add(lane * stride) };
|
||||
unsafe { write_element(base, format!("element {lane}"), &arena) }.unwrap();
|
||||
let (name, _) = arena.alloc(format!("field {lane}")).unwrap();
|
||||
unsafe { write_field::<&str>(base, layout.offset_of("name", 0).unwrap(), name.as_str()) };
|
||||
}
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 2, &layout)) };
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 2, &layout)) };
|
||||
item.copy_out()
|
||||
};
|
||||
bytes.fill(u8::MAX);
|
||||
bytes.fill(u64::MAX);
|
||||
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let replayed = owned.replay(&arena).unwrap();
|
||||
@@ -846,6 +988,26 @@ mod tests {
|
||||
assert_eq!(run.attr::<crate::attribute::EditorLayerPath>(0), &[crate::uuid::NodeId(3)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_census_row_pointed_at_another_field_writes_nothing() {
|
||||
use crate::attribute::{Attribute, Opacity, Transform};
|
||||
use crate::lane::LaneSource;
|
||||
|
||||
let arena = crate::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<f64>(), &[FieldWrite::of::<Opacity>(0)], 1).unwrap();
|
||||
let lane = builder.push(0f64).unwrap();
|
||||
|
||||
// The transform writer renamed onto the 8-byte opacity field: a
|
||||
// 48-byte write past the lane if the name were the only check.
|
||||
let mut forged = crate::attribute::info(Transform::NAME).unwrap();
|
||||
forged.name = Opacity::NAME;
|
||||
builder.attr_stored(lane, &forged, &glam::DAffine2::from_translation((5., 6.).into())).unwrap();
|
||||
|
||||
let item = builder.finish();
|
||||
let run = RunView::<f64>::new(&item).expect("the run holds f64 elements");
|
||||
assert_eq!(run.attr::<Opacity>(0), 1., "the mistyped row leaves the census default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_typed_or_undeclared_column_leaves_the_default() {
|
||||
use crate::lane::LaneSource;
|
||||
@@ -865,10 +1027,11 @@ mod tests {
|
||||
#[should_panic(expected = "an owned item replays")]
|
||||
fn an_owned_item_refuses_reads() {
|
||||
let layout = Layout::default().with_writes(0, element_write_hashed::<String>(), &[]);
|
||||
let mut bytes = vec![0u8; layout.lane_stride()];
|
||||
// Word storage: the parked element slot holds an 8-aligned reference.
|
||||
let mut bytes = vec![0u64; layout.lane_stride().div_ceil(8)];
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
unsafe { write_element(bytes.as_mut_ptr(), String::from("parked"), &arena) }.unwrap();
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr(), 1, &layout)) };
|
||||
unsafe { write_element(bytes.as_mut_ptr().cast(), String::from("parked"), &arena) }.unwrap();
|
||||
let item = unsafe { GroupItem::from_resident(crate::node::RecordBatch::new(bytes.as_ptr().cast(), 1, &layout)) };
|
||||
item.copy_out().lanes();
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,13 @@ pub struct SlotRun<'a> {
|
||||
}
|
||||
|
||||
impl<'a> SlotRun<'a> {
|
||||
/// `None` where the scratch cannot hold `len` lanes. The products are
|
||||
/// checked: the stride is a multiple of 8, so a wrapped one would pass the
|
||||
/// capacity test vacuously.
|
||||
pub(in crate::record) fn new(scratch: &'a mut [std::mem::MaybeUninit<u64>], len: usize, layout: &'a Layout) -> Option<SlotRun<'a>> {
|
||||
(scratch.len() * 8 >= len * layout.lane_stride()).then_some(SlotRun { scratch, layout, len, filled: 0 })
|
||||
let need = len.checked_mul(layout.lane_stride())?;
|
||||
let capacity = scratch.len().checked_mul(8)?;
|
||||
(capacity >= need).then_some(SlotRun { scratch, layout, len, filled: 0 })
|
||||
}
|
||||
|
||||
pub fn layout(&self) -> &'a Layout {
|
||||
@@ -41,20 +46,24 @@ impl<'a> SlotRun<'a> {
|
||||
inline: RecordValue::zeroed(),
|
||||
frame: (self.layout.frame_bytes() != 0).then_some(frame),
|
||||
free: frames.reborrow(),
|
||||
filled_fields: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Records lane `lane` as served; the proof came from that lane's slot. An
|
||||
/// inline record rides the value's own storage, so it takes the one copy
|
||||
/// the run makes.
|
||||
/// the run makes. Lanes serve in ascending order with no gaps, so the
|
||||
/// filled count is an initialized prefix rather than a high-water mark.
|
||||
pub fn served(&mut self, lane: usize, proof: &Served<'_>) {
|
||||
assert!(lane < self.len, "lane {lane} out of bounds for a run of {}", self.len);
|
||||
assert_eq!(lane, self.filled, "lane {lane} serves out of order after {} filled lanes", self.filled);
|
||||
if self.layout.size == 0 {
|
||||
let stride = self.layout.lane_stride();
|
||||
// SAFETY: in-bounds by the capacity check `new` made, and the lane
|
||||
// takes the whole inline record.
|
||||
// SAFETY: in-bounds by the assert against the capacity check `new`
|
||||
// made, and the lane takes the whole inline record.
|
||||
unsafe { std::ptr::copy_nonoverlapping(self.layout.rec(proof.record()).ptr(), self.scratch.as_mut_ptr().cast::<u8>().add(lane * stride), stride) };
|
||||
}
|
||||
self.filled = self.filled.max(lane + 1);
|
||||
self.filled = lane + 1;
|
||||
}
|
||||
|
||||
/// The served lanes as the caller's exclusive batch.
|
||||
@@ -74,6 +83,9 @@ pub struct FrameClaim<'e, 'l> {
|
||||
pub(in crate::record) inline: RecordValue<'static>,
|
||||
pub(in crate::record) frame: Option<*mut u8>,
|
||||
pub(in crate::record) free: Frames<'e>,
|
||||
/// Set by the writes that fill the declared fields, so the safe closers can
|
||||
/// refuse a field-bearing frame that was never filled.
|
||||
pub(in crate::record) filled_fields: bool,
|
||||
}
|
||||
|
||||
impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
@@ -107,17 +119,27 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must be a live record of the plan's source layout, and the plan
|
||||
/// must be the wiring-resolved plan of this frame's layout.
|
||||
/// must be the wiring-resolved plan of this frame's layout. `src` must not
|
||||
/// overlap this frame; an input's frame is split off beyond the claim, so
|
||||
/// serving the source through [`Self::frames`] establishes it.
|
||||
pub unsafe fn carry(&mut self, src: Rec<'_>, plan: &[(usize, usize, usize)]) {
|
||||
unsafe { apply_plan(src, self.dst(), plan) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
|
||||
/// Writes a field at its wiring-resolved offset.
|
||||
///
|
||||
/// # Safety
|
||||
/// `offset` must be this layout's resolved offset for a field of `T`.
|
||||
/// `offset` must be this layout's resolved offset for a field of `T`. A
|
||||
/// generated write offset defaults to 0 until `set_layout` installs it, so
|
||||
/// the debug assertion catches a serve that ran before the install.
|
||||
pub unsafe fn attr_at<T>(&mut self, offset: usize, value: T) {
|
||||
debug_assert!(
|
||||
self.layout.fields.iter().any(|field| field.offset == offset),
|
||||
"attribute write at an offset this layout does not carry; the layout must install before serving"
|
||||
);
|
||||
unsafe { write_field(self.dst(), offset, value) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
|
||||
/// Writes the element; `None` reports arena exhaustion for a parked
|
||||
@@ -132,9 +154,17 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
/// Lifts a kernel's poll into the frame and closes it: the element
|
||||
/// writes on value polls, every poll keeps the frame claimed, and arena
|
||||
/// exhaustion of a parked element reports as an error poll. Panics where
|
||||
/// the element does not match the wired layout.
|
||||
/// the element does not match the wired layout, or where a field-bearing
|
||||
/// layout closes on a frame no carry or field write ever filled, since the
|
||||
/// [`Served`] proof certifies the whole record and the fields would be the
|
||||
/// prior frame's bytes.
|
||||
pub fn lift<T: Send + Sync + dyn_any::StaticTypeSized>(mut self, poll: GPoll<T>, arena: &'e crate::arena::Arena) -> GPoll<RecordValue<'e>> {
|
||||
self.check_element::<T>();
|
||||
assert!(
|
||||
self.layout.fields.is_empty() || self.filled_fields,
|
||||
"a layout with {} fields must carry or write them before lifting",
|
||||
self.layout.fields.len()
|
||||
);
|
||||
let frame_bytes = self.layout.frame_bytes();
|
||||
let dst = self.dst();
|
||||
// SAFETY: the frame is this layout's fresh claim, the element check
|
||||
@@ -150,6 +180,7 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
/// references outlive the serving evaluation.
|
||||
pub unsafe fn fill_copy(&mut self, src: *const u8) {
|
||||
unsafe { std::ptr::copy_nonoverlapping(src, self.dst(), self.layout.size) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
|
||||
/// The served record. The frame stays claimed for the consumer; the drop
|
||||
@@ -196,10 +227,12 @@ impl<'e, 'l> FrameClaim<'e, 'l> {
|
||||
/// Translates a source record into the frame through a wiring-resolved plan.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must be a live record of `plan`'s source layout, and `plan` must
|
||||
/// translate into this frame's layout.
|
||||
/// `src` must be a live record of `plan`'s source layout, `plan` must
|
||||
/// translate into this frame's layout, and `src` must not overlap this
|
||||
/// frame, as [`Self::carry`] requires.
|
||||
pub unsafe fn translate(&mut self, src: Rec<'_>, plan: &SourcePlan) {
|
||||
unsafe { plan.translate(src, self.dst()) };
|
||||
self.filled_fields = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -312,6 +345,35 @@ mod tests {
|
||||
frames.claim(&layout).element(1u32, &arena);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_refuses_a_lane_count_whose_stride_product_overflows() {
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
|
||||
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 4];
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(64);
|
||||
let frames = frame_arena.frames();
|
||||
let wrapping = usize::MAX / layout.lane_stride() + 1;
|
||||
assert!(frames.run(&mut scratch, wrapping, &layout).is_none(), "a wrapped capacity product must not pass the check");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "serves out of order")]
|
||||
fn a_run_refuses_a_gapped_serve() {
|
||||
let arena = crate::arena::Arena::new(1024).unwrap();
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[]);
|
||||
let mut scratch = [std::mem::MaybeUninit::<u64>::uninit(); 8];
|
||||
let mut frame_arena = FrameArena::new();
|
||||
frame_arena.reserve(1 << 10);
|
||||
let frames = frame_arena.frames();
|
||||
let mut run = frames.run(&mut scratch, 3, &layout).unwrap();
|
||||
let lane_frames = frames.scope();
|
||||
let slot = run.slot(2, &lane_frames);
|
||||
let GPoll::Final(proof) = slot.lift_served(GPoll::Final(1.0f64), &arena) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
run.served(2, &proof);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_claim_shortens_onto_a_derived_lifetime() {
|
||||
fn shorten<'long: 'short, 'short, 'l>(claim: FrameClaim<'long, 'l>) -> FrameClaim<'short, 'l> {
|
||||
|
||||
@@ -20,7 +20,7 @@ pub struct NodeMetadata {
|
||||
pub context_features: Vec<ContextFeature>,
|
||||
pub memoize: bool,
|
||||
pub inject_scope: bool,
|
||||
/// The macro appended its hidden `_runtime` and `_source` fields as the last two entries of `fields`.
|
||||
/// Set where `_runtime` and `_source` are the last two entries of `fields`.
|
||||
pub async_source_fields: bool,
|
||||
}
|
||||
|
||||
@@ -79,20 +79,20 @@ pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>> + Send + Sync;
|
||||
pub type ErasedRecordNode = dyn for<'c> Node<ContextImpl<'c>>;
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
type DynEdge = dyn std::any::Any + Send + Sync;
|
||||
type DynSource = dyn std::any::Any + Send + Sync;
|
||||
#[cfg(target_family = "wasm")]
|
||||
type DynEdge = dyn std::any::Any;
|
||||
type DynSource = dyn std::any::Any;
|
||||
|
||||
pub fn record_type<T: 'static>() -> Type {
|
||||
Type::Record(Box::new(concrete!(T)))
|
||||
}
|
||||
|
||||
pub fn record_edge_type<T: 'static>() -> Type {
|
||||
pub fn record_source_type<T: 'static>() -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(record_type::<T>()))
|
||||
}
|
||||
|
||||
/// The record edge type of a token row, generic over the element.
|
||||
pub fn generic_record_edge_type(name: &'static str) -> Type {
|
||||
/// The record source type of a token row, generic over the element.
|
||||
pub fn generic_record_source_type(name: &'static str) -> Type {
|
||||
Type::Fn(Box::new(concrete!(Context)), Box::new(Type::Record(Box::new(Type::Generic(std::borrow::Cow::Borrowed(name))))))
|
||||
}
|
||||
|
||||
@@ -127,12 +127,22 @@ impl<N: ?Sized> SharedSource<N> {
|
||||
|
||||
/// Re-derives the cached pointer from the owned payload. An exclusive
|
||||
/// re-borrow of the payload invalidates the pointer taken before it, so
|
||||
/// every mutation through `own` ends here.
|
||||
/// every mutation through `own` ends here, an unwinding one included.
|
||||
pub fn rederive(&mut self) {
|
||||
self.ptr = std::ptr::NonNull::from(&*self.own);
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-derives on the way out of an exclusive re-borrow, so a mutation that
|
||||
/// panics cannot leave the cached pointer retired for a caller that catches.
|
||||
struct Rederive<'a, N: ?Sized>(&'a mut SharedSource<N>);
|
||||
|
||||
impl<N: ?Sized> Drop for Rederive<'_, N> {
|
||||
fn drop(&mut self) {
|
||||
self.0.rederive();
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: `ptr` is derived from the owned Arc and never mutated through, so the source is exactly as
|
||||
// thread safe as the payload it shares.
|
||||
unsafe impl<N: ?Sized + Send + Sync> Send for SharedSource<N> {}
|
||||
@@ -143,9 +153,6 @@ impl<Input, N> Node<Input> for SharedSource<N>
|
||||
where
|
||||
N: Node<Input> + ?Sized,
|
||||
{
|
||||
/// A node takes exactly its own frame out of its caller's free space: the
|
||||
/// caller minted the claim and kept the cursor, so the frame accounting is
|
||||
/// structural here and asserted where a claim is split.
|
||||
fn serve<'e, 'l>(&self, input: &Input, slot: crate::record::FrameClaim<'e, 'l>) -> crate::gpoll::GPoll<crate::record::Served<'e>>
|
||||
where
|
||||
Input: crate::context::ExtractArena<ArenaRef = &'e crate::arena::Arena>,
|
||||
@@ -188,31 +195,34 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub struct EdgeHandle {
|
||||
node: Box<DynEdge>,
|
||||
share: fn(&DynEdge) -> Box<DynEdge>,
|
||||
serialize: fn(&DynEdge) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
||||
layout: fn(&DynEdge) -> &crate::record::Layout,
|
||||
set_layout: fn(&mut DynEdge, crate::record::RecordLayout),
|
||||
pub struct SourceHandle {
|
||||
node: Box<DynSource>,
|
||||
share: fn(&DynSource) -> Box<DynSource>,
|
||||
serialize: fn(&DynSource) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>>,
|
||||
layout: fn(&DynSource) -> &crate::record::Layout,
|
||||
set_layout: fn(&mut DynSource, crate::record::RecordLayout),
|
||||
ty: Type,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for EdgeHandle {
|
||||
impl std::fmt::Debug for SourceHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("EdgeHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||
f.debug_struct("SourceHandle").field("ty", &self.ty).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
// SAFETY: wasm is single threaded, so the marker-free payload never actually crosses a thread.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Send for EdgeHandle {}
|
||||
unsafe impl Send for SourceHandle {}
|
||||
// SAFETY: as in Send.
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for EdgeHandle {}
|
||||
unsafe impl Sync for SourceHandle {}
|
||||
|
||||
impl EdgeHandle {
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("SourceHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the stored node bounded instead");
|
||||
|
||||
impl SourceHandle {
|
||||
pub fn new_record<T: 'static>(node: std::sync::Arc<ErasedRecordNode>) -> Self {
|
||||
Self::new_erased(node, record_edge_type::<T>())
|
||||
Self::new_erased(node, record_source_type::<T>())
|
||||
}
|
||||
|
||||
pub fn new_erased<N>(node: std::sync::Arc<N>, ty: Type) -> Self
|
||||
@@ -227,9 +237,11 @@ impl EdgeHandle {
|
||||
layout: |edge| Node::<ContextImpl>::layout(edge.downcast_ref::<SharedSource<N>>().expect("layout hook matches the stored edge type")),
|
||||
set_layout: |edge, layout| {
|
||||
let shared = edge.downcast_mut::<SharedSource<N>>().expect("set_layout hook matches the stored edge type");
|
||||
let node = std::sync::Arc::get_mut(&mut shared.own).expect("layout is installed before the node is shared");
|
||||
// The re-borrow below retires the cached pointer, so the rederive
|
||||
// is a guard: a panicking `set_layout` must not leave it stale.
|
||||
let guard = Rederive(shared);
|
||||
let node = std::sync::Arc::get_mut(&mut guard.0.own).expect("layout is installed before the node is shared");
|
||||
Node::<ContextImpl>::set_layout(node, layout);
|
||||
shared.rederive();
|
||||
},
|
||||
ty,
|
||||
}
|
||||
@@ -263,12 +275,12 @@ impl EdgeHandle {
|
||||
}
|
||||
|
||||
pub fn downcast_record<T: 'static>(self) -> Result<SharedSource<ErasedRecordNode>, ConstructionError> {
|
||||
self.downcast_erased(record_edge_type::<T>())
|
||||
self.downcast_erased(record_source_type::<T>())
|
||||
}
|
||||
|
||||
/// The erased record edge, for callers that dispatch on the layout rather
|
||||
/// than a static element type. `None` for an edge erased to another node type.
|
||||
pub fn record_edge(self) -> Option<SharedSource<ErasedRecordNode>> {
|
||||
/// The erased record source, for callers that dispatch on the layout rather
|
||||
/// than a static element type. `None` for a source erased to another node type.
|
||||
pub fn record_source(self) -> Option<SharedSource<ErasedRecordNode>> {
|
||||
self.node.downcast::<SharedSource<ErasedRecordNode>>().ok().map(|edge| *edge)
|
||||
}
|
||||
|
||||
@@ -281,19 +293,19 @@ impl EdgeHandle {
|
||||
}
|
||||
}
|
||||
|
||||
pub type NodeConstructor = fn(Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError>;
|
||||
pub type NodeConstructor = fn(Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RegistryEntry {
|
||||
pub io: NodeIOTypes,
|
||||
pub constructor: NodeConstructor,
|
||||
/// Declarative record-io metadata for the compiler layout pass; `None` for
|
||||
/// nodes whose layout the pass does not yet fold (routing/opaque, hand-written
|
||||
/// nodes whose layout the pass does not fold (routing/opaque, hand-written
|
||||
/// rows), which keep the construction-time path.
|
||||
pub layout_meta: Option<crate::record::LayoutMeta>,
|
||||
}
|
||||
|
||||
pub fn construct(entry: &RegistryEntry, inputs: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
pub fn construct(entry: &RegistryEntry, inputs: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
|
||||
if inputs.len() != entry.io.inputs.len() {
|
||||
return Err(ConstructionError::Arity {
|
||||
expected: entry.io.inputs.len(),
|
||||
@@ -379,7 +391,7 @@ mod tests {
|
||||
|
||||
let node = LendNode::new("held");
|
||||
let layout = Node::<ContextImpl>::layout(&node).clone();
|
||||
let handle = EdgeHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
|
||||
let handle = SourceHandle::new_erased(Arc::new(node) as Arc<ErasedRecordNode>, concrete!(String));
|
||||
assert_eq!(*handle.ty(), concrete!(String));
|
||||
|
||||
let wired = handle.downcast_erased::<ErasedRecordNode>(concrete!(String)).unwrap();
|
||||
@@ -392,8 +404,8 @@ mod tests {
|
||||
assert_eq!(held.len(), 4);
|
||||
}
|
||||
|
||||
/// Evaluates its content at three promoted index levels and serves the
|
||||
/// collected elements.
|
||||
/// Evaluates its content at three indices of one promoted level and serves
|
||||
/// the collected elements.
|
||||
struct RepeatNode<Node0, T> {
|
||||
content: Node0,
|
||||
inner: Layout,
|
||||
@@ -554,29 +566,29 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn construct_checks_arity_and_types() {
|
||||
fn construct_strlen(args: Vec<EdgeHandle>) -> Result<EdgeHandle, ConstructionError> {
|
||||
fn construct_strlen(args: Vec<SourceHandle>) -> Result<SourceHandle, ConstructionError> {
|
||||
let mut args = args.into_iter();
|
||||
let value = args.next().ok_or(ConstructionError::Arity { expected: 1, got: 0 })?.downcast_record::<String>()?;
|
||||
drop(value);
|
||||
Ok(crate::value::record_value_edge(0u32))
|
||||
Ok(crate::value::record_value_source(0u32))
|
||||
}
|
||||
let entry = RegistryEntry {
|
||||
layout_meta: None,
|
||||
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_edge_type::<String>()]),
|
||||
io: NodeIOTypes::new(concrete!(Context), record_type::<u32>(), vec![record_source_type::<String>()]),
|
||||
constructor: construct_strlen,
|
||||
};
|
||||
|
||||
let owned = crate::value::record_value_edge("typed".to_string());
|
||||
let owned = crate::value::record_value_source("typed".to_string());
|
||||
assert!(construct(&entry, vec![owned]).is_ok());
|
||||
|
||||
assert_eq!(construct(&entry, vec![]).unwrap_err(), ConstructionError::Arity { expected: 1, got: 0 });
|
||||
|
||||
let mistyped = crate::value::record_value_edge(1.0f64);
|
||||
let mistyped = crate::value::record_value_source(1.0f64);
|
||||
assert_eq!(
|
||||
construct(&entry, vec![mistyped]).unwrap_err(),
|
||||
ConstructionError::Type {
|
||||
expected: Box::new(record_edge_type::<String>()),
|
||||
found: Box::new(record_edge_type::<f64>()),
|
||||
expected: Box::new(record_source_type::<String>()),
|
||||
found: Box::new(record_source_type::<f64>()),
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -590,9 +602,9 @@ mod tests {
|
||||
|
||||
let counting = counting();
|
||||
let layout = Node::<ContextImpl>::layout(&counting).clone();
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
||||
let handle = SourceHandle::new_record::<u32>(Arc::new(counting) as Arc<ErasedRecordNode>);
|
||||
let duplicate = handle.duplicate();
|
||||
assert_eq!(*duplicate.ty(), record_edge_type::<u32>());
|
||||
assert_eq!(*duplicate.ty(), record_source_type::<u32>());
|
||||
let frames = crate::record::test_frames(1 << 12);
|
||||
|
||||
let first = handle.downcast_record::<u32>().unwrap();
|
||||
|
||||
@@ -30,6 +30,9 @@ unsafe impl Send for RuntimeHandle {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl Sync for RuntimeHandle {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("RuntimeHandle's wasm Send/Sync rest on a single-threaded build; a +atomics target needs the payload bounded instead");
|
||||
|
||||
impl std::fmt::Debug for RuntimeHandle {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RuntimeHandle").finish_non_exhaustive()
|
||||
@@ -102,6 +105,9 @@ unsafe impl<S> Send for GraphRuntime<S> {}
|
||||
#[cfg(target_family = "wasm")]
|
||||
unsafe impl<S> Sync for GraphRuntime<S> {}
|
||||
|
||||
#[cfg(all(target_family = "wasm", target_feature = "atomics"))]
|
||||
compile_error!("GraphRuntime's wasm Send/Sync are unbounded in S and rest on a single-threaded build; a +atomics target needs S bounded instead");
|
||||
|
||||
impl<S> GraphRuntime<S> {
|
||||
pub fn new(spawner: S) -> Self {
|
||||
Self {
|
||||
@@ -272,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)
|
||||
}
|
||||
|
||||
@@ -33,12 +33,12 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// The native record edge of a constant.
|
||||
pub fn record_value_edge<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::EdgeHandle
|
||||
/// The native record source of a constant.
|
||||
pub fn record_value_source<T: Clone + Send + Sync + dyn_any::StaticTypeSized + 'static>(value: T) -> crate::registry::SourceHandle
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(ValueSource::new(value)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
}
|
||||
|
||||
/// The node behind a leveled value source: a constant list served as one level,
|
||||
@@ -90,10 +90,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
/// The native record edge of a constant level: the edge type is the element's.
|
||||
pub fn leveled_record_value_edge<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized + 'static>(values: Vec<T>) -> crate::registry::EdgeHandle
|
||||
/// The native record source of a constant level: the source type is the element's.
|
||||
pub fn leveled_record_value_source<T: Clone + Send + Sync + crate::CacheHash + PartialEq + dyn_any::StaticTypeSized + 'static>(values: Vec<T>) -> crate::registry::SourceHandle
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
crate::registry::EdgeHandle::new_record::<T>(std::sync::Arc::new(LeveledValueSource::new(values)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
crate::registry::SourceHandle::new_record::<T>(std::sync::Arc::new(LeveledValueSource::new(values)) as std::sync::Arc<crate::registry::ErasedRecordNode>)
|
||||
}
|
||||
@@ -238,8 +238,7 @@ impl_tuple!(A, B, C, D, E);
|
||||
impl_tuple!(A, B, C, D, E, F);
|
||||
|
||||
/// rustc-hash's polynomial hash with the state pinned to u64, so keys match across native and wasm targets.
|
||||
/// The state starts at a nonzero seed: zero-initialized fx absorbs leading zero words, which produced
|
||||
/// a real wrong-value memo hit in the prototype.
|
||||
/// The state starts at a nonzero seed, since zero-initialized fx absorbs leading zero words.
|
||||
#[derive(Clone)]
|
||||
pub struct FxHasher64 {
|
||||
hash: u64,
|
||||
|
||||
@@ -19,7 +19,7 @@ impl<'e> Artboard<'e> {
|
||||
Self(content)
|
||||
}
|
||||
|
||||
pub fn as_graphic_list(&self) -> &List<Graphic> {
|
||||
pub fn as_graphic_list(&self) -> &List<Graphic<'_>> {
|
||||
&self.0
|
||||
}
|
||||
|
||||
@@ -50,11 +50,13 @@ impl<'e> Artboard<'e> {
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live parked `Artboard` element field.
|
||||
unsafe fn deep_clone_artboard(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
// SAFETY: the caller's contract.
|
||||
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(ptr)) };
|
||||
let mut content = artboard.0.clone();
|
||||
for element in content.iter_element_values_mut() {
|
||||
*element = crate::graphic::map_groups_to_owned(element);
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_owned(&mut content);
|
||||
Box::new(Artboard(content))
|
||||
}
|
||||
|
||||
@@ -70,22 +72,27 @@ unsafe fn deep_repark_artboard(value: &(dyn std::any::Any + Send + Sync), dst: *
|
||||
for element in content.iter_element_values_mut() {
|
||||
*element = crate::graphic::map_groups_to_resident(element, arena)?;
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_resident(&mut content, arena)?;
|
||||
// SAFETY: the caller's contract on `dst`; the replayed content is an `Artboard`.
|
||||
unsafe { core_types::record::write_element(dst, Artboard(content), arena) }
|
||||
}
|
||||
|
||||
/// The promote for `Artboard` elements: as for `Graphic`, content groups the
|
||||
/// persistent region already holds are shared rather than copied, and
|
||||
/// group-free content moves its header instead of copying its heap.
|
||||
/// persistent region already holds are shared rather than copied, and content
|
||||
/// no group is reachable from moves its header instead of copying its heap.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked `Artboard` element field, and `dst` at
|
||||
/// the element field the promoted reference is written to.
|
||||
unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract on `src`.
|
||||
let artboard = unsafe { core_types::record::borrow_element::<Artboard>(core_types::record::Rec::new(src)) };
|
||||
if !crate::graphic::list_contains_groups(&artboard.0) {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0, and
|
||||
// group-free content owns all of itself.
|
||||
// content no group is reachable from, elements and item attribute values
|
||||
// alike, owns all of itself.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
// SAFETY: as above; the group-free check establishes the own-all-content half.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Artboard>(header, 0) } {
|
||||
// SAFETY: as above, into the promoted image's own element slot.
|
||||
unsafe { dst.cast::<*const Artboard>().write(moved) };
|
||||
@@ -97,6 +104,8 @@ unsafe fn promote_artboard(src: *const u8, dst: *mut u8, promotion: &core_types:
|
||||
let (element, attributes) = item.into_parts();
|
||||
content.push(core_types::list::Item::from_parts(crate::graphic::map_groups_to_persistent(&element, promotion)?, attributes));
|
||||
}
|
||||
crate::graphic::map_attribute_groups_to_persistent(&mut content, promotion)?;
|
||||
// SAFETY: the caller's contract on `dst`; the promoted content is an `Artboard`.
|
||||
unsafe { core_types::record::write_element(dst, Artboard(content), promotion.persistent()) }
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ use glam::{DAffine2, DVec2};
|
||||
use vector_types::GradientStops;
|
||||
|
||||
/// The outcome of materializing a leveled wire into a group.
|
||||
// The group is the render path's success payload; boxing it would add a heap allocation per materialized level.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum LevelGroup<'e> {
|
||||
Group(Group<'e>, Finality),
|
||||
Pending,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,675 @@
|
||||
//! The record-crossing glue: group interiors carried between the owned, resident, and persistent regions.
|
||||
|
||||
use super::Graphic;
|
||||
use core_types::Color;
|
||||
use core_types::list::{Item, List};
|
||||
use raster_types::{CPU, Raster};
|
||||
use vector_types::Vector;
|
||||
|
||||
/// The graphic with every `Group` deep-copied to its owned form, which
|
||||
/// survives the arena generation but cannot be read until
|
||||
/// [`map_groups_to_resident`] re-parks it into a serving arena.
|
||||
pub fn map_groups_to_owned<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
|
||||
match graphic {
|
||||
Graphic::Group(group) => Graphic::Group(group.copy_out()),
|
||||
Graphic::Graphic(children) => {
|
||||
let mut out = List::new();
|
||||
for item in children.clone().into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(map_groups_to_owned(&element), attributes));
|
||||
}
|
||||
map_attribute_groups_to_owned(&mut out);
|
||||
Graphic::Graphic(out)
|
||||
}
|
||||
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
|
||||
Graphic::RasterCPU(raster) => Graphic::RasterCPU(raster.clone()),
|
||||
Graphic::RasterGPU(raster) => Graphic::RasterGPU(raster.clone()),
|
||||
Graphic::Color(color) => Graphic::Color(*color),
|
||||
Graphic::Gradient(gradient) => Graphic::Gradient(gradient.clone()),
|
||||
Graphic::Text(text) => Graphic::Text(text.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The graphic with every owned `Group` re-parked into `arena`; `None`
|
||||
/// reports arena exhaustion.
|
||||
pub fn map_groups_to_resident<'a>(graphic: &Graphic<'a>, arena: &'a core_types::arena::Arena) -> Option<Graphic<'a>> {
|
||||
match graphic {
|
||||
Graphic::Group(group) => group.replay(arena).map(Graphic::Group),
|
||||
Graphic::Graphic(children) => {
|
||||
let mut children = children.clone();
|
||||
for child in children.iter_element_values_mut() {
|
||||
*child = map_groups_to_resident(child, arena)?;
|
||||
}
|
||||
map_attribute_groups_to_resident(&mut children, arena)?;
|
||||
Some(Graphic::Graphic(children))
|
||||
}
|
||||
other => Some(other.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The deep copy-out for `Graphic` elements: a plain clone of a group
|
||||
/// interior would carry frame pointers into the evaluation's arena, so memo
|
||||
/// and capture seams copy out the owned-group form.
|
||||
///
|
||||
/// # Safety
|
||||
/// `ptr` must point at a live parked `Graphic` element field.
|
||||
unsafe fn deep_clone_graphic(ptr: *const u8) -> Box<dyn std::any::Any + Send + Sync> {
|
||||
// SAFETY: the caller's contract.
|
||||
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(ptr)) };
|
||||
Box::new(map_groups_to_owned(graphic))
|
||||
}
|
||||
|
||||
/// The deep re-park for `Graphic` elements: owned groups replay into the
|
||||
/// serving arena before the graphic parks.
|
||||
///
|
||||
/// # Safety
|
||||
/// `value` must hold a `Graphic` and `dst` must be a live `Graphic` element
|
||||
/// field.
|
||||
unsafe fn deep_repark_graphic(value: &(dyn std::any::Any + Send + Sync), dst: *mut u8, arena: &core_types::arena::Arena) -> Option<()> {
|
||||
let graphic = value.downcast_ref::<Graphic>().expect("an element replays at its own type");
|
||||
let resident = map_groups_to_resident(graphic, arena)?;
|
||||
let retained = graphic_retained_heap(&resident);
|
||||
// SAFETY: the caller's contract; the resident form is a `Graphic` for `dst`.
|
||||
unsafe { core_types::record::write_element_sized(dst, resident, arena, retained) }
|
||||
}
|
||||
|
||||
/// The graphic with every `Group` promoted into the persistent region: an
|
||||
/// interior already living there is shared rather than copied, so the cost is
|
||||
/// what this level newly produced. `None` reports arena exhaustion.
|
||||
pub fn map_groups_to_persistent<'p>(graphic: &Graphic<'_>, promotion: &core_types::record::Promotion<'p>) -> Option<Graphic<'p>> {
|
||||
match graphic {
|
||||
Graphic::Group(group) => group.to_persistent(promotion).map(Graphic::Group),
|
||||
Graphic::Graphic(children) => {
|
||||
let mut out = List::new();
|
||||
for item in children.clone().into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(map_groups_to_persistent(&element, promotion)?, attributes));
|
||||
}
|
||||
map_attribute_groups_to_persistent(&mut out, promotion)?;
|
||||
Some(Graphic::Graphic(out))
|
||||
}
|
||||
Graphic::Vector(vector) => Some(Graphic::Vector(vector.clone())),
|
||||
Graphic::RasterCPU(raster) => Some(Graphic::RasterCPU(raster.clone())),
|
||||
Graphic::RasterGPU(raster) => Some(Graphic::RasterGPU(raster.clone())),
|
||||
Graphic::Color(color) => Some(Graphic::Color(*color)),
|
||||
Graphic::Gradient(gradient) => Some(Graphic::Gradient(gradient.clone())),
|
||||
Graphic::Text(text) => Some(Graphic::Text(text.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The list's attribute keys, owned so the columns can be walked mutably.
|
||||
fn attribute_keys(list: &List<Graphic>) -> Vec<String> {
|
||||
list.attribute_keys().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
/// Every group held in the list's item attribute values, deep-copied to its
|
||||
/// owned form. Element values are the caller's own pass; a value list's own
|
||||
/// item attributes recurse here.
|
||||
pub(crate) fn map_attribute_groups_to_owned(list: &mut List<Graphic<'_>>) {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
*element = map_groups_to_owned(element);
|
||||
}
|
||||
map_attribute_groups_to_owned(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every owned group held in the list's item attribute values, re-parked into
|
||||
/// `arena`. `None` reports arena exhaustion.
|
||||
pub(crate) fn map_attribute_groups_to_resident(list: &mut List<Graphic<'_>>, arena: &core_types::arena::Arena) -> Option<()> {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let resident = map_groups_to_resident(element, arena)?;
|
||||
// SAFETY: the attribute store is erased, and the replay serves as
|
||||
// long as `arena`, which the store's reader outlives.
|
||||
*element = unsafe { core_types::record::erase_static(resident) };
|
||||
}
|
||||
map_attribute_groups_to_resident(value, arena)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Every group held in the list's item attribute values, promoted into the
|
||||
/// persistent region on the same Cow dispatch the elements take. `None` reports
|
||||
/// arena exhaustion.
|
||||
pub(crate) fn map_attribute_groups_to_persistent(list: &mut List<Graphic<'_>>, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
for key in attribute_keys(list) {
|
||||
// A column of a type that cannot hold groups is skipped whole.
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(&key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
let promoted = map_groups_to_persistent(element, promotion)?;
|
||||
// SAFETY: the attribute store is erased, and persistent content
|
||||
// outlives the evaluation.
|
||||
*element = unsafe { core_types::record::erase_static(promoted) };
|
||||
}
|
||||
map_attribute_groups_to_persistent(value, promotion)?;
|
||||
}
|
||||
}
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// The promote for `Graphic` elements: the generic path would deep-copy every
|
||||
/// interior through an owned intermediate, while this shares the interiors the
|
||||
/// persistent region already holds. A graphic no group is reachable from
|
||||
/// references nothing the evaluation owns, so its header moves and its heap is
|
||||
/// never copied.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked `Graphic` element field, and `dst` at the
|
||||
/// element field the promoted reference is written to.
|
||||
unsafe fn promote_graphic(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract on `src`.
|
||||
let graphic = unsafe { core_types::record::borrow_element::<Graphic>(core_types::record::Rec::new(src)) };
|
||||
if !graphic_contains_groups(graphic) {
|
||||
// SAFETY: a parked element slot holds one reference at offset 0, and a
|
||||
// graphic no group is reachable from, elements and item attribute values
|
||||
// alike, owns all of its content.
|
||||
let header = unsafe { src.cast::<*const u8>().read() };
|
||||
// SAFETY: as above; the group-free check establishes the own-all-content half.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<Graphic<'static>>(header, graphic_retained_heap(graphic)) } {
|
||||
// SAFETY: as above, into the promoted image's own element slot.
|
||||
unsafe { dst.cast::<*const Graphic<'static>>().write(moved) };
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
let promoted = map_groups_to_persistent(graphic, promotion)?;
|
||||
let retained = graphic_retained_heap(&promoted);
|
||||
// SAFETY: the caller's contract on `dst`; the promoted form is a `Graphic`.
|
||||
unsafe { core_types::record::write_element_sized(dst, promoted, promotion.persistent(), retained) }
|
||||
}
|
||||
|
||||
/// The heap a graphic's own payload owns. Group interiors are excluded: their
|
||||
/// lanes park through this same glue and are counted as they land.
|
||||
fn graphic_retained_heap(graphic: &Graphic<'_>) -> usize {
|
||||
match graphic {
|
||||
Graphic::Vector(vector) => vector_retained_heap(vector),
|
||||
Graphic::RasterCPU(raster) => raster.data.len() * size_of::<Color>(),
|
||||
Graphic::Text(text) => text.len(),
|
||||
Graphic::Gradient(gradient) => gradient.len() * size_of::<(f64, Color)>(),
|
||||
Graphic::Graphic(children) => (0..children.len()).filter_map(|index| children.element(index)).map(graphic_retained_heap).sum(),
|
||||
Graphic::Group(_) | Graphic::RasterGPU(_) | Graphic::Color(_) => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The heap a vector's domain columns own, summed over the columns it
|
||||
/// exposes, so the segment domain's private parallel columns are undercounted.
|
||||
fn vector_retained_heap(vector: &Vector) -> usize {
|
||||
size_of_val(vector.point_domain.ids())
|
||||
+ size_of_val(vector.point_domain.positions())
|
||||
+ size_of_val(vector.segment_domain.ids())
|
||||
+ size_of_val(vector.region_domain.ids())
|
||||
+ size_of_val(vector.colinear_manipulators.as_slice())
|
||||
}
|
||||
|
||||
/// Whether any group is reachable from the graphic, so it does not own all of
|
||||
/// its content.
|
||||
fn graphic_contains_groups(graphic: &Graphic) -> bool {
|
||||
match graphic {
|
||||
Graphic::Group(_) => true,
|
||||
Graphic::Graphic(children) => list_contains_groups(children),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any group is reachable from the list, so it does not own all of its
|
||||
/// content. An item attribute value holds its groups exactly as an element
|
||||
/// does: a cloned group there keeps a resident interior borrowing the
|
||||
/// evaluation's arena, so the elements alone cannot decide ownership.
|
||||
pub(crate) fn list_contains_groups(list: &List<Graphic>) -> bool {
|
||||
(0..list.len()).any(|index| list.element(index).is_some_and(graphic_contains_groups)) || attribute_values_contain_groups(list)
|
||||
}
|
||||
|
||||
/// Whether any group hides in the list's item attribute values. Only the
|
||||
/// group-capable columns are scanned: those are the value types the deep field
|
||||
/// glue is registered for, today `Option<List<Graphic>>` alone. A list with no
|
||||
/// attribute columns costs nothing, and a column of any other type is decided
|
||||
/// by its one downcast rather than per value.
|
||||
fn attribute_values_contain_groups(list: &List<Graphic>) -> bool {
|
||||
list.attribute_keys().any(|key| {
|
||||
list.iter_attribute_values::<Option<List<Graphic>>>(key)
|
||||
.is_some_and(|mut values| values.any(|value| value.as_ref().is_some_and(list_contains_groups)))
|
||||
})
|
||||
}
|
||||
|
||||
/// The heap a graphic list's elements own, group interiors excluded as
|
||||
/// [`graphic_retained_heap`] excludes them.
|
||||
fn list_retained_heap(list: &List<Graphic>) -> usize {
|
||||
(0..list.len()).filter_map(|index| list.element(index)).map(graphic_retained_heap).sum()
|
||||
}
|
||||
|
||||
/// The deep copy-out for graphic-list field values (the paint markers' owned
|
||||
/// form): content groups leave in their owned form, whether an element or an
|
||||
/// item attribute value holds them. Declines (`None`) for group-free content,
|
||||
/// which already owns everything.
|
||||
fn deep_clone_graphic_list(value: &dyn core_types::list::AnyAttributeValue) -> Option<Box<dyn core_types::list::AnyAttributeValue>> {
|
||||
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field deep-copies at its own type");
|
||||
let list = list.as_ref().filter(|list| list_contains_groups(list))?;
|
||||
let mut list = list.clone();
|
||||
for element in list.iter_element_values_mut() {
|
||||
*element = map_groups_to_owned(element);
|
||||
}
|
||||
map_attribute_groups_to_owned(&mut list);
|
||||
Some(Box::new(Some(list)))
|
||||
}
|
||||
|
||||
/// The deep replay for graphic-list field values: owned content groups replay
|
||||
/// into the serving arena before the field re-parks, whether an element or an
|
||||
/// item attribute value holds them. `Some(None)` declines for group-free
|
||||
/// content; `None` reports arena exhaustion.
|
||||
fn deep_repark_graphic_list(value: &dyn core_types::list::AnyAttributeValue, arena: &core_types::arena::Arena) -> Option<Option<Box<dyn core_types::list::AnyAttributeValue>>> {
|
||||
let list = value.as_any().downcast_ref::<Option<List<Graphic>>>().expect("a graphic list field replays at its own type");
|
||||
let Some(list) = list.as_ref().filter(|list| list_contains_groups(list)) else {
|
||||
return Some(None);
|
||||
};
|
||||
let mut list = list.clone();
|
||||
for element in list.iter_element_values_mut() {
|
||||
*element = map_groups_to_resident(element, arena)?;
|
||||
}
|
||||
map_attribute_groups_to_resident(&mut list, arena)?;
|
||||
// SAFETY: every group the clone carried, in an element or an item attribute
|
||||
// value, now names `arena`, whose borrow the replayed field is read at.
|
||||
let list = unsafe { core_types::record::erase_static(list) };
|
||||
Some(Some(Box::new(Some(list))))
|
||||
}
|
||||
|
||||
/// The promote for graphic-list fields, the deep field glue's third half: the
|
||||
/// owned halves copy content groups out to the owned form and replay them back,
|
||||
/// while this maps the content transient-to-persistent in one pass.
|
||||
///
|
||||
/// THE TWO-LEVEL SHARING LAW: the field's own header is not provenance-shared.
|
||||
/// It moves where no group is reachable from the list, elements and item
|
||||
/// attribute values alike, since the payload then owns all of its content and
|
||||
/// the transient arena confirms the reference is its own park, and otherwise it
|
||||
/// clones into a fresh persistent park. One level inside, a content group's
|
||||
/// interior is arena-resident and its provenance is decidable, so it takes
|
||||
/// [`map_groups_to_persistent`]'s Cow dispatch: an interior the persistent
|
||||
/// region already holds is shared pointer for pointer.
|
||||
///
|
||||
/// # Safety
|
||||
/// `src` must point at a live parked graphic-list field, and `dst` at the field
|
||||
/// slot the promoted reference is written to.
|
||||
unsafe fn promote_graphic_list(src: *const u8, dst: *mut u8, promotion: &core_types::record::Promotion<'_>) -> Option<()> {
|
||||
// SAFETY: the caller's contract; the slot holds one optional reference.
|
||||
let Some(list) = (unsafe { src.cast::<Option<&List<Graphic<'static>>>>().read() }) else {
|
||||
// SAFETY: as above, into the promoted image's own field slot.
|
||||
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(None) };
|
||||
return Some(());
|
||||
};
|
||||
let retained = list_retained_heap(list);
|
||||
if !list_contains_groups(list) {
|
||||
// SAFETY: a list no group is reachable from, elements and item attribute
|
||||
// values alike, owns all of its content, and the arena declines a
|
||||
// reference that is not a park at the list's own address and size.
|
||||
if let Some(moved) = unsafe { promotion.move_park::<List<Graphic<'static>>>(std::ptr::from_ref(list).cast(), retained) } {
|
||||
// SAFETY: the move published a live list in the persistent region.
|
||||
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(Some(&*moved)) };
|
||||
return Some(());
|
||||
}
|
||||
}
|
||||
let mut promoted = list.clone();
|
||||
for element in promoted.iter_element_values_mut() {
|
||||
*element = map_groups_to_persistent(element, promotion)?;
|
||||
}
|
||||
map_attribute_groups_to_persistent(&mut promoted, promotion)?;
|
||||
// SAFETY: every borrow the clone carried, in an element or an item attribute
|
||||
// value, was replaced by persistent content above, so the erased form
|
||||
// outlives the evaluation.
|
||||
let promoted = unsafe { core_types::record::erase_static(promoted) };
|
||||
let (parked, _) = promotion.persistent().alloc_sized(promoted, retained)?;
|
||||
// SAFETY: the slot holds one optional reference.
|
||||
unsafe { dst.cast::<Option<&List<Graphic<'static>>>>().write(Some(parked)) };
|
||||
Some(())
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
fn register_all() {
|
||||
core_types::record::register_deep_element_clone::<Graphic>(deep_clone_graphic, deep_repark_graphic);
|
||||
core_types::record::register_deep_field_value::<Option<List<Graphic>>>(deep_clone_graphic_list, deep_repark_graphic_list);
|
||||
core_types::record::register_field_promote::<Option<&'static List<Graphic<'static>>>>(promote_graphic_list);
|
||||
core_types::record::register_element_promote::<Graphic>(promote_graphic);
|
||||
core_types::record::register_retained_heap::<Graphic>(|value| value.downcast_ref::<Graphic>().map_or(0, graphic_retained_heap));
|
||||
core_types::record::register_retained_heap::<Vector>(|value| value.downcast_ref::<Vector>().map_or(0, vector_retained_heap));
|
||||
core_types::record::register_retained_heap::<Raster<CPU>>(|value| value.downcast_ref::<Raster<CPU>>().map_or(0, |raster| raster.data.len() * size_of::<Color>()));
|
||||
core_types::record::register_retained_heap::<String>(|value| value.downcast_ref::<String>().map_or(0, String::len));
|
||||
}
|
||||
|
||||
#[cfg(not(target_family = "wasm"))]
|
||||
#[core_types::ctor::ctor]
|
||||
fn register() {
|
||||
register_all();
|
||||
}
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[unsafe(export_name = "__node_registry_deep_element_graphic")]
|
||||
extern "C" fn register() {
|
||||
register_all();
|
||||
}
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::test_support::{native_group_paint, unit_square_at};
|
||||
use crate::graphic::{group_to_legacy_list, map_groups_to_legacy};
|
||||
use crate::markers::{Fill, Stroke};
|
||||
use core_types::attribute::Attribute;
|
||||
use core_types::lane::LaneSource;
|
||||
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||
use glam::DVec2;
|
||||
|
||||
#[test]
|
||||
fn an_owned_group_replays_content_equal_after_the_source_dies() {
|
||||
let paint = List::new_from_element(Graphic::Color(Color::BLACK));
|
||||
let vector = unit_square_at(DVec2::ZERO);
|
||||
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
let group = core_types::record::Group { row: None, content: builder.finish() };
|
||||
let expected = group_to_legacy_list(&group);
|
||||
let owned = map_groups_to_owned(&Graphic::Group(group));
|
||||
drop(source);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let resident = map_groups_to_resident(&owned, &arena).expect("the arena holds the replay");
|
||||
let Graphic::Group(group) = &resident else { panic!("the replay keeps the group form") };
|
||||
assert_eq!(group_to_legacy_list(group), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_group_replays_nested_groups_through_the_element_glue() {
|
||||
let vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||
builder.push(vector.clone()).unwrap();
|
||||
let nested = Graphic::Group(core_types::record::Group { row: None, content: builder.finish() });
|
||||
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Graphic>(), &[], 1).unwrap();
|
||||
builder.push(nested).unwrap();
|
||||
let group = core_types::record::Group { row: None, content: builder.finish() };
|
||||
let expected = group_to_legacy_list(&group);
|
||||
let owned = map_groups_to_owned(&Graphic::Group(group));
|
||||
drop(source);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let resident = map_groups_to_resident(&owned, &arena).expect("the arena holds the replay");
|
||||
let Graphic::Group(group) = &resident else { panic!("the replay keeps the group form") };
|
||||
assert_eq!(group_to_legacy_list(group), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_run_deep_copies_graphic_list_fields() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
// SAFETY: the erased native list serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let owned = item.copy_out();
|
||||
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||
drop(item);
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let replayed = owned.replay(&arena).expect("the arena holds the replay");
|
||||
let run = RunView::<Vector>::new(&replayed).expect("the run holds vector elements");
|
||||
let served = run.attr::<Fill>(0).expect("the fill replays present");
|
||||
assert_eq!(map_groups_to_legacy(served.element(0).unwrap()), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_record_deep_copies_graphic_list_fields() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
// SAFETY: the erased native list serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let layout = item.layout().clone();
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
// SAFETY: the item's lane is a live record of `layout`.
|
||||
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
|
||||
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||
drop(item);
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||
let mut slot = frames.claim(&layout);
|
||||
owned.replay_into(&mut slot, &arena).expect("the arena holds the replay");
|
||||
// SAFETY: the replay completes the record in the claimed frame.
|
||||
let value = unsafe { slot.finish() };
|
||||
// SAFETY: the replay wrote a record of `layout`.
|
||||
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the fill replays present");
|
||||
assert_eq!(map_groups_to_legacy(served.element(0).unwrap()), expected);
|
||||
}
|
||||
|
||||
/// A `lanes`-long frame promoted out of `transient` into `persistent`, with
|
||||
/// `fill` written into the paint field of every lane. The frame buffer comes
|
||||
/// back so it outlives the promote's reads.
|
||||
fn promote_paint_field(
|
||||
fill: Option<&List<Graphic<'static>>>,
|
||||
lanes: usize,
|
||||
transient: &core_types::arena::Arena,
|
||||
persistent: &core_types::arena::Arena,
|
||||
) -> (core_types::record::Layout, core_types::record::MaterializedSpan, Vec<u64>) {
|
||||
use core_types::record::{Layout, MaterializedSpan, Promotion, element_write, write_field};
|
||||
|
||||
let layout = Layout::default().with_writes(0, element_write::<f64>(), &[FieldWrite::of::<Fill>(0)]);
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
let stride = layout.lane_stride();
|
||||
let mut buffer = vec![0u64; (lanes * stride).div_ceil(8)];
|
||||
let base = buffer.as_mut_ptr().cast::<u8>();
|
||||
let bounds = (base as usize, buffer.len() * 8);
|
||||
for lane in 0..lanes {
|
||||
// SAFETY: the frame is this layout's, written at the element slot and
|
||||
// at the paint field's own offset.
|
||||
unsafe {
|
||||
base.add(lane * stride).cast::<f64>().write(lane as f64);
|
||||
write_field::<Option<&List<Graphic<'static>>>>(base.add(lane * stride), offset, fill);
|
||||
}
|
||||
}
|
||||
// SAFETY: the frames hold `lanes` live records of `layout`.
|
||||
let batch = unsafe { core_types::node::RecordBatch::new(base.cast_const(), lanes, &layout) };
|
||||
let promotion = Promotion::new(transient, bounds, persistent);
|
||||
// SAFETY: as above.
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) }.expect("the region holds the promote");
|
||||
(layout, span, buffer)
|
||||
}
|
||||
|
||||
/// 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>> {
|
||||
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.
|
||||
unsafe { batch.get(lane).rec().read::<Option<&List<Graphic>>>(offset) }.expect("the paint promotes present")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_promoted_paint_field_shares_persistent_interiors() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
// The interior an upstream promote already published, named by a paint
|
||||
// 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")
|
||||
};
|
||||
group.content.lanes().get(0).rec().ptr()
|
||||
};
|
||||
// SAFETY: the list serves only while `persistent` is live, and the
|
||||
// promote under test replaces every borrow it carries.
|
||||
let (paint, _) = transient.alloc_sized_keyed(unsafe { core_types::record::erase_static(published) }, 0).unwrap();
|
||||
|
||||
let occupied = persistent.occupancy();
|
||||
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")
|
||||
};
|
||||
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>>(),
|
||||
"the promote allocated the lane slab and the field's own header, never the owned form of the shared interior"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_free_paint_field_moves_its_parked_header() {
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO)));
|
||||
let heap = {
|
||||
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
|
||||
vector.point_domain.positions().as_ptr()
|
||||
};
|
||||
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||
|
||||
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"
|
||||
);
|
||||
assert!(std::ptr::eq(served, promoted_paint(&span, &layout, 1, &persistent)), "a paint two lanes share moves once");
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
assert!(matches!(served.element(0), Some(Graphic::Vector(_))), "the moved paint survives the transient reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paint_field_whose_attributes_hold_groups_never_moves() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
// Group-free elements, with the resident group hidden in an item attribute.
|
||||
let native = native_group_paint(&inner_vector, &transient);
|
||||
let expected = map_groups_to_legacy(native.element(0).unwrap());
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(4., 4.))));
|
||||
// SAFETY: the erased native list serves only while `transient` is live; the
|
||||
// promote under test replaces its borrows.
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||
|
||||
let (layout, span, _frames) = promote_paint_field(Some(paint), 1, &transient, &persistent);
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
let moved = std::ptr::eq(std::ptr::from_ref(served).cast::<u8>(), std::ptr::from_ref(paint).cast::<u8>());
|
||||
assert!(!moved, "an attribute-held group denies the move, so the promote parks a header of its own");
|
||||
|
||||
transient.reset();
|
||||
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"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_free_paint_field_moves_past_its_attribute_columns() {
|
||||
let mut transient = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let persistent = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO)));
|
||||
// Columns of a type that cannot hold groups, and a group-capable column
|
||||
// whose value holds none: neither denies the move.
|
||||
paint.set_attribute::<f64>("opacity", 0, 0.5);
|
||||
paint.set_attribute::<Color>("probe:color", 0, Color::BLACK);
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(List::new_from_element(Graphic::Color(Color::WHITE))));
|
||||
let heap = {
|
||||
let Some(Graphic::Vector(vector)) = paint.element(0) else { panic!("the paint carries a vector") };
|
||||
vector.point_domain.positions().as_ptr()
|
||||
};
|
||||
let (paint, _) = transient.alloc_sized_keyed(paint, 0).unwrap();
|
||||
|
||||
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"
|
||||
);
|
||||
|
||||
transient.reset();
|
||||
let served = promoted_paint(&span, &layout, 0, &persistent);
|
||||
assert!(matches!(served.element(0), Some(Graphic::Vector(_))), "the moved paint survives the transient reset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_owned_record_deep_copies_attribute_held_groups() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let native = native_group_paint(&inner_vector, &source);
|
||||
let expected = map_groups_to_legacy(native.element(0).unwrap());
|
||||
|
||||
// The field's elements are group-free; the group rides an item attribute,
|
||||
// which the shallow read alone would leave borrowing `source`.
|
||||
let mut paint = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
|
||||
// SAFETY: the erased native list serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
paint.set_attribute::<Option<List<Graphic>>>(Stroke::NAME, 0, Some(unsafe { core_types::record::erase_static(native) }));
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let layout = item.layout().clone();
|
||||
let offset = layout.offset_of(Fill::NAME, 0).unwrap();
|
||||
// SAFETY: the item's lane is a live record of `layout`.
|
||||
let owned = unsafe { core_types::record::OwnedRecord::copy_out(&layout, item.lanes().get(0).rec()) };
|
||||
drop(item);
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let frames = core_types::record::test_frames(layout.frame_bytes());
|
||||
let mut slot = frames.claim(&layout);
|
||||
owned.replay_into(&mut slot, &arena).expect("the arena holds the replay");
|
||||
// SAFETY: the replay completes the record in the claimed frame.
|
||||
let value = unsafe { slot.finish() };
|
||||
// SAFETY: the replay wrote a record of `layout`.
|
||||
let served = unsafe { layout.rec(&value).read::<Option<&List<Graphic>>>(offset) }.expect("the fill replays present");
|
||||
let held = served.attribute::<Option<List<Graphic>>>(Stroke::NAME, 0).expect("the stroke attribute rides the replayed 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 replayed into the serving arena");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
//! The legacy bridge: record-backed groups rebuilt as owned legacy lists.
|
||||
|
||||
use super::walk::push_lane_paint_into_interiors;
|
||||
use super::{Graphic, detable_items};
|
||||
use crate::markers::{ATTR_FILL, ATTR_STROKE};
|
||||
use core_types::Color;
|
||||
use core_types::list::{Item, List};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::{GradientStops, Vector};
|
||||
|
||||
/// One typed run as an owned list, elements cloned and every attribute copied
|
||||
/// through its erased read. Content keeps its native form; the legacy
|
||||
/// conversions layer their mapping on top.
|
||||
pub fn run_to_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
|
||||
core_types::record::run_to_owned_list(item)
|
||||
}
|
||||
|
||||
/// Converts the group content of the list's paint attribute values to legacy
|
||||
/// form, so a legacy product owns everything its attributes reach.
|
||||
pub fn map_paint_attrs_to_legacy<T>(list: &mut List<T>) {
|
||||
for key in [ATTR_FILL, ATTR_STROKE, crate::markers::ATTR_EDITOR_MERGED_LAYERS] {
|
||||
let Some(values) = list.iter_attribute_values_mut::<Option<List<Graphic>>>(key) else { continue };
|
||||
for value in values.flatten() {
|
||||
for element in value.iter_element_values_mut() {
|
||||
*element = map_groups_to_legacy(element);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One typed run as a legacy list: [`run_to_list`] with the paint attribute
|
||||
/// contents converted to their legacy form.
|
||||
pub(crate) fn run_to_legacy_list<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(item: &core_types::record::GroupItem) -> Option<List<T>> {
|
||||
let mut list = run_to_list::<T>(item)?;
|
||||
map_paint_attrs_to_legacy(&mut list);
|
||||
Some(list)
|
||||
}
|
||||
|
||||
/// The graphic with every `Group` converted to its legacy form.
|
||||
pub fn map_groups_to_legacy<'out>(graphic: &Graphic<'_>) -> Graphic<'out> {
|
||||
match graphic {
|
||||
Graphic::Group(group) => group_to_legacy_graphic(group),
|
||||
Graphic::Graphic(children) => {
|
||||
let mut out = List::new();
|
||||
for item in children.clone().into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
|
||||
}
|
||||
map_paint_attrs_to_legacy(&mut out);
|
||||
Graphic::Graphic(out)
|
||||
}
|
||||
Graphic::Vector(vector) => Graphic::Vector(vector.clone()),
|
||||
Graphic::RasterCPU(raster) => Graphic::RasterCPU(raster.clone()),
|
||||
Graphic::RasterGPU(raster) => Graphic::RasterGPU(raster.clone()),
|
||||
Graphic::Color(color) => Graphic::Color(*color),
|
||||
Graphic::Gradient(gradient) => Graphic::Gradient(gradient.clone()),
|
||||
Graphic::Text(text) => Graphic::Text(text.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The group as one legacy graphic. A bare (row-less) wrap of a single typed
|
||||
/// run keeps the run's typed variant, matching the `Into<Graphic>` the
|
||||
/// pre-flip wrap applied; everything else becomes the legacy group list.
|
||||
pub fn group_to_legacy_graphic(group: &core_types::record::Group) -> Graphic<'static> {
|
||||
if group.row.is_none() {
|
||||
let item = &group.content;
|
||||
let typed = None
|
||||
.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
|
||||
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
|
||||
.or_else(|| run_to_legacy_list::<GradientStops>(item).map(|list| detable_items(list, Graphic::Gradient)))
|
||||
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)));
|
||||
if let Some(typed) = typed {
|
||||
return Graphic::Graphic(typed);
|
||||
}
|
||||
}
|
||||
Graphic::Graphic(group_to_legacy_list(group))
|
||||
}
|
||||
|
||||
/// The group as a legacy `List<Graphic>`: a `Graphic` run becomes the items,
|
||||
/// another typed run becomes one de-tabled leaf item per lane.
|
||||
pub fn group_to_legacy_list(group: &core_types::record::Group) -> List<Graphic<'static>> {
|
||||
let item = &group.content;
|
||||
if let Some(mut list) = run_to_legacy_list::<Graphic>(item) {
|
||||
for element in list.iter_element_values_mut() {
|
||||
*element = map_groups_to_legacy(element);
|
||||
}
|
||||
push_lane_paint_into_interiors(&mut list);
|
||||
return list;
|
||||
}
|
||||
None.or_else(|| run_to_legacy_list::<Vector>(item).map(|list| detable_items(list, Graphic::Vector)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<CPU>>(item).map(|list| detable_items(list, Graphic::RasterCPU)))
|
||||
.or_else(|| run_to_legacy_list::<Raster<GPU>>(item).map(|list| detable_items(list, Graphic::RasterGPU)))
|
||||
.or_else(|| run_to_legacy_list::<Color>(item).map(|list| detable_items(list, Graphic::Color)))
|
||||
.or_else(|| run_to_legacy_list::<GradientStops>(item).map(|list| detable_items(list, Graphic::Gradient)))
|
||||
.or_else(|| run_to_legacy_list::<String>(item).map(|list| detable_items(list, Graphic::Text)))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::test_support::{native_group_paint, unit_square_at};
|
||||
use crate::markers::Fill;
|
||||
use core_types::attribute::Attribute;
|
||||
use core_types::record::{FieldWrite, RunBuilder, element_write_hashed};
|
||||
use glam::DVec2;
|
||||
|
||||
#[test]
|
||||
fn a_legacy_list_owns_its_paint_attr_content() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let source = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
// SAFETY: the erased native list serves only while `source` is live; the
|
||||
// deep glue under test replaces its borrows at the copy-out seam.
|
||||
let paint = unsafe { core_types::record::erase_static(native_group_paint(&inner_vector, &source)) };
|
||||
|
||||
let vector = unit_square_at(DVec2::new(4., 4.));
|
||||
let mut builder = RunBuilder::new(&source, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||
let expected = map_groups_to_legacy(paint.element(0).unwrap());
|
||||
drop(item);
|
||||
drop(paint);
|
||||
drop(source);
|
||||
|
||||
let served = legacy.attribute::<Option<List<Graphic>>>(Fill::NAME, 0).expect("the fill attribute rides the list");
|
||||
let served = served.as_ref().expect("the fill is present");
|
||||
assert_eq!(served.element(0).unwrap(), &expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_list_keeps_native_group_elements() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let content = native_group_paint(&inner_vector, &arena);
|
||||
let element = content.element(0).unwrap();
|
||||
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Graphic>(), &[], 1).unwrap();
|
||||
builder.push(element.clone()).unwrap();
|
||||
let item = builder.finish();
|
||||
let list = run_to_list::<Graphic>(&item).expect("the run holds graphic lanes");
|
||||
assert!(matches!(list.element(0), Some(Graphic::Group(_))), "the list keeps the native group form");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,697 @@
|
||||
mod glue;
|
||||
mod legacy;
|
||||
mod paint;
|
||||
mod walk;
|
||||
|
||||
pub(crate) use glue::{list_contains_groups, map_attribute_groups_to_owned, map_attribute_groups_to_persistent, map_attribute_groups_to_resident};
|
||||
pub use glue::{map_groups_to_owned, map_groups_to_persistent, map_groups_to_resident};
|
||||
pub(crate) use legacy::run_to_legacy_list;
|
||||
pub use legacy::{group_to_legacy_graphic, group_to_legacy_list, map_groups_to_legacy, map_paint_attrs_to_legacy, run_to_list};
|
||||
pub use paint::{
|
||||
LanePaint, PaintColumns, PaintOverlay, PaintOverlayColumn, PaintReach, bake_paint_transforms, has_paint, is_paint_present, paint_graphics, set_paint_attribute, set_paint_attribute_at,
|
||||
vector_can_reduce_to_clip_path,
|
||||
};
|
||||
pub use walk::{GraphicLevel, GraphicLevelColumn, RowStep, VectorRow, direct_vector_len, flatten_vector_rows, group_is_empty, lane_attributes, run_lane_attributes, walk_vector_rows};
|
||||
use walk::{group_all_clipped, group_bounding_box, group_is_fully_transparent, group_is_opaque, group_render_complexity};
|
||||
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::ops::{FromAnchorPosition, ListConvert};
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::GradientStops;
|
||||
pub use vector_types::Vector;
|
||||
|
||||
/// The possible forms of graphical content that can be rendered by the Render node into either an image or SVG syntax.
|
||||
/// A leaf holds its element directly; its attributes ride the containing
|
||||
/// lane. Multi-element content is a [`core_types::record::Group`] run, or
|
||||
/// transitionally the legacy `Graphic` list.
|
||||
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||
pub enum Graphic<'e> {
|
||||
Graphic(List<Graphic<'e>>),
|
||||
Vector(Vector),
|
||||
RasterCPU(Raster<CPU>),
|
||||
RasterGPU(Raster<GPU>),
|
||||
Color(Color),
|
||||
Gradient(GradientStops),
|
||||
Text(String),
|
||||
Group(core_types::record::Group<'e>),
|
||||
}
|
||||
|
||||
impl Default for Graphic<'_> {
|
||||
fn default() -> Self {
|
||||
Self::Graphic(List::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// A typed legacy list as a legacy graphic list: each item de-tables to a
|
||||
/// leaf element, keeping its attributes on the containing lane.
|
||||
pub(in crate::graphic) fn detable_items<'e, T: Clone + Send + Sync + 'static>(list: List<T>, leaf: fn(T) -> Graphic<'e>) -> List<Graphic<'e>> {
|
||||
let mut out = List::new();
|
||||
for item in list.into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
out.push(Item::from_parts(leaf(element), attributes));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The element-space coercion into `Graphic`: a leaf converts in place and a
|
||||
/// legacy list becomes a native group built over the arena, so the coercion
|
||||
/// never constructs a legacy interior.
|
||||
pub trait IntoGraphicElement: Clone + Send + Sync + CacheHash + 'static {
|
||||
/// `None` reports arena exhaustion.
|
||||
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>;
|
||||
}
|
||||
|
||||
fn list_group<T: Clone + Send + Sync + CacheHash + PartialEq + dyn_any::StaticTypeSized>(list: List<T>, arena: &core_types::arena::Arena) -> Option<Graphic<'_>>
|
||||
where
|
||||
T::Static: Clone + Send + Sync,
|
||||
{
|
||||
Some(Graphic::Group(core_types::record::Group {
|
||||
row: None,
|
||||
content: core_types::record::GroupItem::from_list(list, arena)?,
|
||||
}))
|
||||
}
|
||||
|
||||
macro_rules! into_graphic_element {
|
||||
($($leaf:ident: $element:ty;)*) => {
|
||||
$(
|
||||
impl IntoGraphicElement for $element {
|
||||
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
Some(Graphic::$leaf(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicElement for List<$element> {
|
||||
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
list_group(self, arena)
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
into_graphic_element! {
|
||||
Vector: Vector;
|
||||
RasterCPU: Raster<CPU>;
|
||||
RasterGPU: Raster<GPU>;
|
||||
Color: Color;
|
||||
Gradient: GradientStops;
|
||||
Text: String;
|
||||
}
|
||||
|
||||
impl IntoGraphicElement for Graphic<'static> {
|
||||
fn into_graphic_element(self, _arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
Some(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicElement for List<Graphic<'static>> {
|
||||
fn into_graphic_element(self, arena: &core_types::arena::Arena) -> Option<Graphic<'_>> {
|
||||
list_group(self, arena)
|
||||
}
|
||||
}
|
||||
|
||||
// Vector
|
||||
impl From<Vector> for Graphic<'_> {
|
||||
fn from(vector: Vector) -> Self {
|
||||
Graphic::Vector(vector)
|
||||
}
|
||||
}
|
||||
|
||||
// Raster<CPU>
|
||||
impl From<Raster<CPU>> for Graphic<'_> {
|
||||
fn from(raster: Raster<CPU>) -> Self {
|
||||
Graphic::RasterCPU(raster)
|
||||
}
|
||||
}
|
||||
|
||||
// Raster<GPU>
|
||||
impl From<Raster<GPU>> for Graphic<'_> {
|
||||
fn from(raster: Raster<GPU>) -> Self {
|
||||
Graphic::RasterGPU(raster)
|
||||
}
|
||||
}
|
||||
|
||||
// Color
|
||||
impl From<Color> for Graphic<'_> {
|
||||
fn from(color: Color) -> Self {
|
||||
Graphic::Color(color)
|
||||
}
|
||||
}
|
||||
// Note: List<Color> -> Option<Color> is in gcore (Color is defined there)
|
||||
|
||||
// GradientStops
|
||||
impl From<GradientStops> for Graphic<'_> {
|
||||
fn from(gradient: GradientStops) -> Self {
|
||||
Graphic::Gradient(gradient)
|
||||
}
|
||||
}
|
||||
|
||||
// String
|
||||
impl From<String> for Graphic<'_> {
|
||||
fn from(text: String) -> Self {
|
||||
Graphic::Text(text)
|
||||
}
|
||||
}
|
||||
|
||||
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
|
||||
/// and discarding all other non-matching content. Recursion through `Graphic::Graphic` sub-`List`s composes transforms and opacity.
|
||||
fn flatten_graphic_list<T>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
|
||||
fn flatten_recursive<T>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>, parent_layer_path: Option<&[NodeId]>) {
|
||||
for current_graphic_item in current_graphic_list.into_iter() {
|
||||
// Whether the parent carries each attribute: a structural fact (column presence), never a value comparison.
|
||||
// Flattening composes a parent attribute onto its children only when the parent has it,
|
||||
// so an absent parent attribute never invents a column the children didn't already have.
|
||||
let parent_has_transform = current_graphic_item.attribute::<DAffine2>(ATTR_TRANSFORM).is_some();
|
||||
let parent_has_opacity = current_graphic_item.attribute::<f64>(ATTR_OPACITY).is_some();
|
||||
let parent_has_fill = current_graphic_item.attribute::<f64>(ATTR_OPACITY_FILL).is_some();
|
||||
|
||||
let current_transform: DAffine2 = current_graphic_item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let current_opacity: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY, 1.);
|
||||
let current_fill: f64 = current_graphic_item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
|
||||
let lane_layer_path: Option<Vec<NodeId>> = current_graphic_item.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH).cloned();
|
||||
|
||||
let (element, attributes) = current_graphic_item.into_parts();
|
||||
match element {
|
||||
// Compose the parent's transform/opacity/fill onto each child, but only for attributes the parent carries.
|
||||
// A child lacking one is padded with the composition identity (`1.` for opacity/fill, identity for transform), so composing through it is a no-op.
|
||||
Graphic::Graphic(mut sub_list) => {
|
||||
if parent_has_transform {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*v = current_transform * *v;
|
||||
}
|
||||
}
|
||||
if parent_has_opacity {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY) {
|
||||
*v *= current_opacity;
|
||||
}
|
||||
}
|
||||
if parent_has_fill {
|
||||
for v in sub_list.iter_attribute_values_mut_or_default::<f64>(ATTR_OPACITY_FILL) {
|
||||
*v *= current_fill;
|
||||
}
|
||||
}
|
||||
|
||||
flatten_recursive(output, sub_list, extract_variant, lane_layer_path.as_deref());
|
||||
}
|
||||
// A bridge row's native group flattens through its legacy lowering.
|
||||
Graphic::Group(group) => {
|
||||
let lowered = List::new_from_item(Item::from_parts(group_to_legacy_graphic(&group), attributes.clone()));
|
||||
flatten_recursive(output, lowered, extract_variant, parent_layer_path);
|
||||
}
|
||||
// A de-tabled leaf is one attr-less element; the extracted row rides with its containing lane's full attributes, paint included.
|
||||
// The enclosing group lane's own layer path overrides, one hop only, matching the native walk.
|
||||
other => {
|
||||
if let Some(typed_list) = extract_variant(other) {
|
||||
for item in typed_list.into_iter() {
|
||||
let mut row = Item::from_parts(item.into_element(), attributes.clone());
|
||||
if let Some(layer_path) = parent_layer_path {
|
||||
row.set_attribute(ATTR_EDITOR_LAYER_PATH, layer_path.to_vec());
|
||||
}
|
||||
output.push(row);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut output = List::new();
|
||||
flatten_recursive(&mut output, content, extract_variant, None);
|
||||
output
|
||||
}
|
||||
|
||||
/// Maps from a concrete element type to its corresponding `Graphic` enum variant,
|
||||
/// enabling type-directed casting of typed `List`s from a `Graphic` value.
|
||||
pub trait TryFromGraphic: Clone + Sized {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>>;
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Vector {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Vector(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Raster<CPU> {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::RasterCPU(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Color {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Color(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for GradientStops {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Gradient(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
if let Graphic::Text(t) = graphic { Some(List::new_from_element(t)) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
// Local trait to convert types to List<Graphic> (avoids orphan rule issues)
|
||||
pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + PartialEq + CacheHash + 'static {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>>;
|
||||
|
||||
/// Deeply flattens any content of type `T` within a `List<Graphic>`, discarding all other content, and returning a flat `List<T>`.
|
||||
fn into_flattened_list<T: TryFromGraphic>(self) -> List<T>
|
||||
where
|
||||
Self: std::marker::Sized,
|
||||
{
|
||||
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Graphic<'static>> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Vector> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Vector)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Raster<CPU>> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::RasterCPU)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Raster<GPU>> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::RasterGPU)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Color> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Color)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<GradientStops> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Gradient)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<String> {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
detable_items(self, Graphic::Text)
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for DAffine2 {
|
||||
fn into_graphic_list(self) -> List<Graphic<'static>> {
|
||||
List::new_from_element(Graphic::default())
|
||||
}
|
||||
}
|
||||
|
||||
// DAffine2
|
||||
impl From<DAffine2> for Graphic<'_> {
|
||||
fn from(_: DAffine2) -> Self {
|
||||
Graphic::default()
|
||||
}
|
||||
}
|
||||
|
||||
// DVec2
|
||||
impl From<DVec2> for Graphic<'_> {
|
||||
fn from(position: DVec2) -> Self {
|
||||
Graphic::Vector(Vector::from_anchor_position(position))
|
||||
}
|
||||
}
|
||||
// Note: List conversions handled by blanket impl in gcore
|
||||
|
||||
impl<'e> Graphic<'e> {
|
||||
pub fn as_graphic(&self) -> Option<&List<Graphic<'_>>> {
|
||||
match self {
|
||||
Graphic::Graphic(graphic) => Some(graphic),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_graphic_mut(&mut self) -> Option<&mut List<Graphic<'e>>> {
|
||||
match self {
|
||||
Graphic::Graphic(graphic) => Some(graphic),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_vector(&self) -> Option<&Vector> {
|
||||
match self {
|
||||
Graphic::Vector(vector) => Some(vector),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_raster(&self) -> Option<&Raster<CPU>> {
|
||||
match self {
|
||||
Graphic::RasterCPU(raster) => Some(raster),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_raster_mut(&mut self) -> Option<&mut Raster<CPU>> {
|
||||
match self {
|
||||
Graphic::RasterCPU(raster) => Some(raster),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A leaf carries no clipping attribute, which rides its containing lane.
|
||||
pub fn had_clip_enabled(&self) -> bool {
|
||||
fn all_clipped<T>(list: &List<T>) -> bool {
|
||||
list.iter_attribute_values_or_default::<bool>(ATTR_CLIPPING_MASK).all(|clip| clip)
|
||||
}
|
||||
|
||||
match self {
|
||||
Graphic::Graphic(list) => all_clipped(list),
|
||||
Graphic::Group(group) => group_all_clipped(group),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Vector(vector) => vector_can_reduce_to_clip_path(&core_types::lane::Single(vector)),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_opaque(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Graphic(list) => !list.is_empty() && list.iter_element_values().all(Graphic::is_opaque),
|
||||
// A bare leaf carries no paint attribute, which rides its lane, so
|
||||
// nothing here claims opacity.
|
||||
Graphic::Vector(_) => false,
|
||||
Graphic::Color(color) => color.is_opaque(),
|
||||
Graphic::Gradient(stops) => stops.iter().all(|stop| stop.color.is_opaque()),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||
Graphic::Group(group) => group_is_opaque(group),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_fully_transparent(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Graphic(list) => list.iter_element_values().all(Graphic::is_fully_transparent),
|
||||
// A bare leaf carries no paint attribute, so only an unstroked
|
||||
// vector is invisible on its own.
|
||||
Graphic::Vector(vector) => vector.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke()),
|
||||
Graphic::Color(color) => color.a() == 0.,
|
||||
Graphic::Gradient(stops) => stops.iter().all(|stop| stop.color.a() == 0.),
|
||||
Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Text(_) => false,
|
||||
Graphic::Group(group) => group_is_fully_transparent(group),
|
||||
}
|
||||
}
|
||||
|
||||
/// True if this paint opaquely covers the entire fill region.
|
||||
/// Vector, Raster, and a nested Graphic may leave gaps, so they return false.
|
||||
pub fn covers_opaquely(&self) -> bool {
|
||||
matches!(self, Graphic::Color(_) | Graphic::Gradient(_)) && self.is_opaque()
|
||||
}
|
||||
|
||||
/// Whether the graphic holds no content: a leaf always holds its element.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
match self {
|
||||
Graphic::Graphic(list) => list.is_empty(),
|
||||
Graphic::Group(group) => group_is_empty(group),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Graphic<'_> {
|
||||
fn bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::Vector(vector) => BoundingBox::bounding_box(vector, transform, include_stroke),
|
||||
Graphic::RasterCPU(raster) => raster.bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(raster) => raster.bounding_box(transform, include_stroke),
|
||||
Graphic::Graphic(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(color) => color.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(gradient) => gradient.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(text) => text.bounding_box(transform, include_stroke),
|
||||
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, false),
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
Graphic::Vector(vector) => vector.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterCPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::RasterGPU(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Graphic(graphic) => graphic.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Group(group) => group_bounding_box(group, transform, include_stroke, true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'e> ListConvert<Graphic<'e>> for Vector {
|
||||
fn convert_item(self) -> Graphic<'e> {
|
||||
Graphic::Vector(self)
|
||||
}
|
||||
}
|
||||
impl<'e> ListConvert<Graphic<'e>> for Raster<CPU> {
|
||||
fn convert_item(self) -> Graphic<'e> {
|
||||
Graphic::RasterCPU(self)
|
||||
}
|
||||
}
|
||||
impl<'e> ListConvert<Graphic<'e>> for Raster<GPU> {
|
||||
fn convert_item(self) -> Graphic<'e> {
|
||||
Graphic::RasterGPU(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderComplexity for Graphic<'_> {
|
||||
fn render_complexity(&self) -> usize {
|
||||
match self {
|
||||
Self::Graphic(list) => list.render_complexity(),
|
||||
Self::Vector(list) => list.render_complexity(),
|
||||
Self::RasterCPU(list) => list.render_complexity(),
|
||||
Self::RasterGPU(list) => list.render_complexity(),
|
||||
Self::Color(list) => list.render_complexity(),
|
||||
Self::Gradient(list) => list.render_complexity(),
|
||||
Self::Text(list) => list.render_complexity(),
|
||||
Self::Group(group) => group_render_complexity(group),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Node definitions moved to graphic-nodes crate
|
||||
|
||||
pub trait AtIndex {
|
||||
type Output;
|
||||
fn at_index(&self, index: usize) -> Option<Self::Output>;
|
||||
fn at_index_from_end(&self, index: usize) -> Option<Self::Output>;
|
||||
}
|
||||
impl<T: Clone> AtIndex for Vec<T> {
|
||||
type Output = T;
|
||||
|
||||
fn at_index(&self, index: usize) -> Option<Self::Output> {
|
||||
self.get(index).cloned()
|
||||
}
|
||||
|
||||
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
|
||||
if index == 0 || index > self.len() { None } else { self.get(self.len() - index).cloned() }
|
||||
}
|
||||
}
|
||||
impl<T: Clone> AtIndex for List<T> {
|
||||
type Output = List<T>;
|
||||
|
||||
fn at_index(&self, index: usize) -> Option<Self::Output> {
|
||||
self.clone_item(index).map(|item| {
|
||||
let mut result_list = Self::default();
|
||||
result_list.push(item);
|
||||
result_list
|
||||
})
|
||||
}
|
||||
|
||||
fn at_index_from_end(&self, index: usize) -> Option<Self::Output> {
|
||||
if index == 0 || index > self.len() { None } else { self.at_index(self.len() - index) }
|
||||
}
|
||||
}
|
||||
|
||||
pub trait OmitIndex {
|
||||
fn omit_index(&self, index: usize) -> Self;
|
||||
fn omit_index_from_end(&self, index: usize) -> Self;
|
||||
}
|
||||
impl<T: Clone> OmitIndex for Vec<T> {
|
||||
fn omit_index(&self, index: usize) -> Self {
|
||||
self.iter().enumerate().filter(|(i, _)| *i != index).map(|(_, v)| v.clone()).collect()
|
||||
}
|
||||
|
||||
fn omit_index_from_end(&self, index: usize) -> Self {
|
||||
if index == 0 || index > self.len() {
|
||||
return self.clone();
|
||||
}
|
||||
self.omit_index(self.len() - index)
|
||||
}
|
||||
}
|
||||
impl<T: Clone> OmitIndex for List<T> {
|
||||
fn omit_index(&self, index: usize) -> Self {
|
||||
let mut result = Self::default();
|
||||
for i in 0..self.len() {
|
||||
if i != index
|
||||
&& let Some(item) = self.clone_item(i)
|
||||
{
|
||||
result.push(item);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn omit_index_from_end(&self, index: usize) -> Self {
|
||||
if index == 0 || index > self.len() {
|
||||
return self.clone();
|
||||
}
|
||||
self.omit_index(self.len() - index)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::list::List;
|
||||
|
||||
fn vector_graphic() -> Graphic<'static> {
|
||||
Graphic::Vector(Vector::default())
|
||||
}
|
||||
|
||||
// Flattening must not invent attribute columns that neither the parent graphic nor the child carried
|
||||
#[test]
|
||||
fn flatten_does_not_invent_attributes() {
|
||||
let graphics = List::new_from_element(vector_graphic());
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
for key in [ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, ATTR_EDITOR_LAYER_PATH] {
|
||||
assert!(!flattened.attribute_keys().any(|k| k == key), "flatten invented the `{key}` attribute");
|
||||
}
|
||||
}
|
||||
|
||||
// A parent attribute that is present must compose onto the flattened children
|
||||
#[test]
|
||||
fn flatten_propagates_present_attributes() {
|
||||
let mut graphics = List::new_from_element(vector_graphic());
|
||||
graphics.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
let flattened: List<Vector> = graphics.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
|
||||
let mut group = List::new_from_element(Graphic::Graphic(List::new_from_element(vector_graphic())));
|
||||
group.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
|
||||
let flattened: List<Vector> = group.into_flattened_list();
|
||||
assert_eq!(flattened.attribute_cloned_or_default::<f64>(ATTR_OPACITY, 0), 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod graphic_is_opaque_tests {
|
||||
use vector_types::GradientStop;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn color_graphic(alpha: f64) -> Graphic<'static> {
|
||||
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
||||
Graphic::Color(color)
|
||||
}
|
||||
|
||||
fn gradient_graphic(gradient: GradientStops) -> Graphic<'static> {
|
||||
Graphic::Gradient(gradient)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opaque_color_is_opaque() {
|
||||
let g = color_graphic(1.);
|
||||
assert!(g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transparent_color_is_not_opaque() {
|
||||
let g = color_graphic(0.5);
|
||||
assert!(!g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_is_not_opaque() {
|
||||
let g = Graphic::Vector(Vector::default());
|
||||
assert!(!g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_with_all_opaque_stops_is_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: color_1,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: color_2,
|
||||
},
|
||||
]);
|
||||
let g = gradient_graphic(gradient);
|
||||
assert!(g.is_opaque());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_with_transparent_stop_is_not_opaque() {
|
||||
let color_1 = Color::from_rgbaf32(1., 0., 0., 0.5).unwrap();
|
||||
let color_2 = Color::from_rgbaf32(1., 0., 0., 1.).unwrap();
|
||||
let gradient = GradientStops::new(vec![
|
||||
GradientStop {
|
||||
position: 0.,
|
||||
midpoint: 0.5,
|
||||
color: color_1,
|
||||
},
|
||||
GradientStop {
|
||||
position: 1.,
|
||||
midpoint: 0.5,
|
||||
color: color_2,
|
||||
},
|
||||
]);
|
||||
let g = gradient_graphic(gradient);
|
||||
assert!(!g.is_opaque());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test_support {
|
||||
use super::Graphic;
|
||||
use core_types::list::List;
|
||||
use core_types::record::{RunBuilder, element_write_hashed};
|
||||
use glam::DVec2;
|
||||
use vector_types::Vector;
|
||||
use vector_types::subpath::Subpath;
|
||||
use vector_types::vector::PointId;
|
||||
|
||||
pub(in crate::graphic) fn unit_square_at(corner: DVec2) -> Vector {
|
||||
Vector::from_subpath(Subpath::<PointId>::new_rectangle(corner, corner + DVec2::ONE))
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn native_group_paint<'a>(vector: &Vector, arena: &'a core_types::arena::Arena) -> List<Graphic<'a>> {
|
||||
let mut builder = RunBuilder::new(arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||
builder.push(vector.clone()).unwrap();
|
||||
List::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: builder.finish() }))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! The paint column level: fill and stroke read as lane columns and threaded down to the elements they reach.
|
||||
|
||||
use super::{Graphic, IntoGraphicList};
|
||||
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill, Stroke};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::attribute::{Attribute, Opacity};
|
||||
use core_types::lane::{LaneColumn, LaneSource};
|
||||
use core_types::list::{ItemAttributeValues, List};
|
||||
use glam::DAffine2;
|
||||
use vector_types::Vector;
|
||||
|
||||
/// Whether a normalized paint graphic list actually carries renderable paint.
|
||||
/// A 0-item list, or a list whose first graphic is empty, is treated as no paint.
|
||||
pub fn is_paint_present(graphic_list: &List<Graphic>) -> bool {
|
||||
graphic_list.element(0).is_some_and(|graphic| !graphic.is_empty())
|
||||
}
|
||||
|
||||
/// Look up the paint graphics stored under the marker `A`, in the canonical `List<Graphic>` form.
|
||||
pub fn paint_graphics<'a, A, S>(source: &'a S, index: usize) -> Option<&'a List<Graphic<'static>>>
|
||||
where
|
||||
S: LaneSource,
|
||||
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
|
||||
{
|
||||
source
|
||||
.attr::<A>(index)
|
||||
// Treat a blank paint attribute as absent so an empty attribute doesn't count as painted
|
||||
.filter(|graphic_list| is_paint_present(graphic_list))
|
||||
}
|
||||
|
||||
/// Whether the item carries a non-blank canonical `List<Graphic>` paint under the marker `A`,
|
||||
/// checked by borrowing without cloning the renderable list.
|
||||
pub fn has_paint<'a, A, S>(source: &'a S, index: usize) -> bool
|
||||
where
|
||||
S: LaneSource,
|
||||
A: Attribute<Value<'a> = Option<&'a List<Graphic<'static>>>>,
|
||||
{
|
||||
paint_graphics::<A, S>(source, index).is_some()
|
||||
}
|
||||
|
||||
/// Whether every lane of a vector source draws as a plain clip path: fully
|
||||
/// opaque, fill absent or opaque, stroke invisible or fully transparent.
|
||||
pub fn vector_can_reduce_to_clip_path<S: LaneSource<Element = Vector>>(source: &S) -> bool {
|
||||
(0..source.lane_count()).all(|index| {
|
||||
let Some(element) = source.element(index) else { return false };
|
||||
let opacity: f64 = source.attr::<Opacity>(index);
|
||||
|
||||
let fill_opaque_or_absent = paint_graphics::<Fill, _>(source, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_opaque()));
|
||||
|
||||
let stroke_invisible_or_transparent = element.stroke.as_ref().is_none_or(|stroke| !stroke.has_renderable_stroke())
|
||||
|| paint_graphics::<Stroke, _>(source, index).is_none_or(|graphic_list| graphic_list.element(0).is_none_or(|graphic| graphic.is_fully_transparent()));
|
||||
|
||||
opacity > 1. - f64::EPSILON && fill_opaque_or_absent && stroke_invisible_or_transparent
|
||||
})
|
||||
}
|
||||
|
||||
/// The paint a lane carries for its interiors, in the reference form
|
||||
/// [`PaintOverlay`] threads down.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct LanePaint<'a> {
|
||||
pub fill: Option<&'a List<Graphic<'static>>>,
|
||||
pub stroke: Option<&'a List<Graphic<'static>>>,
|
||||
}
|
||||
|
||||
impl<'a> LanePaint<'a> {
|
||||
pub const NONE: Self = Self { fill: None, stroke: None };
|
||||
|
||||
pub fn is_present(&self) -> bool {
|
||||
self.fill.is_some() || self.stroke.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A source's fill and stroke columns, resolved once for per-lane reads.
|
||||
pub struct PaintColumns<'a, S: LaneSource + 'a> {
|
||||
fill: S::Column<'a, Fill>,
|
||||
stroke: S::Column<'a, Stroke>,
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource> PaintColumns<'a, S> {
|
||||
pub fn new(source: &'a S) -> Self {
|
||||
Self {
|
||||
fill: source.column::<Fill>(),
|
||||
stroke: source.column::<Stroke>(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane's present, non-blank paint.
|
||||
pub fn read(&self, lane: usize) -> LanePaint<'a> {
|
||||
let present = |value: Option<Option<&'a List<Graphic<'static>>>>| value.flatten().filter(|list| is_paint_present(list));
|
||||
LanePaint {
|
||||
fill: present(self.fill.try_get(lane)),
|
||||
stroke: present(self.stroke.try_get(lane)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a lane's paint reaches into the element beneath it, mirroring the
|
||||
/// legacy conversion's paint push: vector interiors directly and vector
|
||||
/// children of a nested graphic list, one level deep.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct PaintReach<'a> {
|
||||
pub paint: LanePaint<'a>,
|
||||
hops: u8,
|
||||
}
|
||||
|
||||
impl<'a> PaintReach<'a> {
|
||||
pub const NONE: Self = Self { paint: LanePaint::NONE, hops: 0 };
|
||||
|
||||
/// The lane's effective reach: an inherited paint stays authoritative
|
||||
/// (lane paint below a push's origin is inert in the legacy model), an
|
||||
/// absent one reads the lane's own paint.
|
||||
pub fn for_lane<S: LaneSource>(self, columns: &PaintColumns<'a, S>, index: usize) -> Self {
|
||||
match self.paint.is_present() {
|
||||
true => self,
|
||||
false => Self { paint: columns.read(index), hops: 2 },
|
||||
}
|
||||
}
|
||||
|
||||
pub fn applies(&self) -> bool {
|
||||
self.hops > 0 && self.paint.is_present()
|
||||
}
|
||||
|
||||
/// The reach one graphic nesting level further down.
|
||||
pub fn nested(self) -> Self {
|
||||
Self {
|
||||
paint: self.paint,
|
||||
hops: self.hops.saturating_sub(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// The reach entering a group's own graphic run: a spent or absent reach
|
||||
/// resets so the group's own lane paint applies at its own boundary.
|
||||
pub fn into_group_graphics(self) -> Self {
|
||||
match self.applies() {
|
||||
true => self.nested(),
|
||||
false => Self::NONE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A source with a lane's paint forced over its fill and stroke columns,
|
||||
/// reaching the interiors the legacy conversion's paint push reached.
|
||||
pub struct PaintOverlay<'a, S> {
|
||||
inner: &'a S,
|
||||
paint: LanePaint<'a>,
|
||||
}
|
||||
|
||||
impl<'a, S> PaintOverlay<'a, S> {
|
||||
pub fn new(inner: &'a S, paint: LanePaint<'a>) -> Self {
|
||||
Self { inner, paint }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct PaintOverlayColumn<'a, S: LaneSource + 'a, A: Attribute> {
|
||||
inner: S::Column<'a, A>,
|
||||
forced: Option<A::Value<'a>>,
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource, A: Attribute> LaneColumn<'a, A> for PaintOverlayColumn<'a, S, A> {
|
||||
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||
match self.forced {
|
||||
Some(forced) => Some(forced),
|
||||
None => self.inner.try_get(lane),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The forced value for the marker `A`: the lane paint where `A` is this
|
||||
/// crate's fill or stroke marker, absent otherwise.
|
||||
fn forced_paint<'a, A: Attribute>(paint: LanePaint<'a>) -> Option<A::Value<'a>> {
|
||||
let slot = match A::NAME {
|
||||
name if name == Fill::NAME => paint.fill,
|
||||
name if name == Stroke::NAME => paint.stroke,
|
||||
_ => None,
|
||||
}?;
|
||||
assert_eq!(
|
||||
std::any::TypeId::of::<A::Value<'static>>(),
|
||||
std::any::TypeId::of::<Option<&'static List<Graphic<'static>>>>(),
|
||||
"attribute `{}` is declared at another value type than this crate's paint form",
|
||||
A::NAME
|
||||
);
|
||||
assert_eq!(
|
||||
size_of::<A::Value<'a>>(),
|
||||
size_of::<Option<&'a List<Graphic<'a>>>>(),
|
||||
"the paint value form must span the marker's value"
|
||||
);
|
||||
// SAFETY: the census admits one value type per attribute name, so a `fill` or `stroke` marker carries this crate's `Option<&List<Graphic>>` at the asserted size.
|
||||
Some(unsafe { std::mem::transmute_copy::<Option<&'a List<Graphic>>, A::Value<'a>>(&Some(slot)) })
|
||||
}
|
||||
|
||||
impl<'a, S: LaneSource> LaneSource for PaintOverlay<'a, S> {
|
||||
type Element = S::Element;
|
||||
type Column<'b, A: Attribute>
|
||||
= PaintOverlayColumn<'b, S, A>
|
||||
where
|
||||
Self: 'b;
|
||||
|
||||
fn lane_count(&self) -> usize {
|
||||
self.inner.lane_count()
|
||||
}
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&S::Element> {
|
||||
self.inner.element(lane)
|
||||
}
|
||||
|
||||
fn column<A: Attribute>(&self) -> PaintOverlayColumn<'_, S, A> {
|
||||
PaintOverlayColumn {
|
||||
inner: self.inner.column::<A>(),
|
||||
forced: forced_paint::<A>(self.paint),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stores a paint attribute in the paint marker's owned form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute(attributes: &mut ItemAttributeValues, key: &str, paint: impl IntoGraphicList) {
|
||||
attributes.insert(key, Some(paint.into_graphic_list()));
|
||||
}
|
||||
|
||||
/// Stores a paint attribute at a list index in the paint marker's owned form, the only representation paint readers accept.
|
||||
pub fn set_paint_attribute_at<T>(list: &mut List<T>, index: usize, key: &str, paint: impl IntoGraphicList) {
|
||||
list.set_attribute(key, index, Some(paint.into_graphic_list()));
|
||||
}
|
||||
|
||||
/// Bake the provided transform into the per-item transforms of the paint graphics stored under the
|
||||
/// canonical `List<Graphic>` fill and stroke attributes.
|
||||
pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DAffine2) {
|
||||
fn bake_graphic_paint_transform(graphics: &mut List<Graphic>, transform: DAffine2) {
|
||||
for item_transform in graphics.iter_attribute_values_mut_or_default::<DAffine2>(ATTR_TRANSFORM) {
|
||||
*item_transform = transform * *item_transform;
|
||||
}
|
||||
for graphic in graphics.iter_element_values_mut() {
|
||||
if let Graphic::Graphic(list) = graphic {
|
||||
bake_graphic_paint_transform(list, transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for paint_key in [ATTR_FILL, ATTR_STROKE] {
|
||||
if let Some(Some(graphics)) = attributes.get_mut::<Option<List<Graphic>>>(paint_key) {
|
||||
bake_graphic_paint_transform(graphics, transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::run_to_legacy_list;
|
||||
use crate::graphic::test_support::unit_square_at;
|
||||
use core_types::Color;
|
||||
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||
use glam::DVec2;
|
||||
|
||||
#[test]
|
||||
fn a_run_serves_the_parked_paint_reference() {
|
||||
let paint = List::new_from_element(Graphic::Color(Color::BLACK));
|
||||
let vector = unit_square_at(DVec2::ZERO);
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<Fill>(0)], 1).unwrap();
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<Fill>(lane, Some(&paint));
|
||||
let item = builder.finish();
|
||||
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
|
||||
|
||||
assert_eq!(run.attr::<Fill>(0), Some(&paint));
|
||||
assert_eq!(paint_graphics::<Fill, _>(&run, 0), Some(&paint));
|
||||
assert_eq!(paint_graphics::<Stroke, _>(&run, 0), None);
|
||||
|
||||
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||
assert_eq!(paint_graphics::<Fill, _>(&legacy, 0), paint_graphics::<Fill, _>(&run, 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,572 @@
|
||||
//! The native-content walk: vector rows reached through a graphic's own storage, with no legacy conversion.
|
||||
|
||||
use super::Graphic;
|
||||
use super::paint::{LanePaint, PaintColumns, PaintReach, is_paint_present, paint_graphics, set_paint_attribute_at};
|
||||
use crate::markers::{ATTR_FILL, ATTR_STROKE, Fill};
|
||||
use core_types::attribute::{Attribute, ClippingMask, EditorLayerPath, Opacity, OpacityFill, Transform};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::lane::LaneSource;
|
||||
use core_types::list::{AttributeValueDyn, Item, ItemAttributeValues, List};
|
||||
use core_types::record::FieldOffset;
|
||||
use core_types::render_complexity::RenderComplexity;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{ATTR_EDITOR_LAYER_PATH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::{GradientStops, Vector};
|
||||
|
||||
/// One run's attribute tokens, minted once so the lane loops read at an offset.
|
||||
struct RunAttrs {
|
||||
transform: Option<FieldOffset<Transform>>,
|
||||
opacity: Option<FieldOffset<Opacity>>,
|
||||
opacity_fill: Option<FieldOffset<OpacityFill>>,
|
||||
clipping_mask: Option<FieldOffset<ClippingMask>>,
|
||||
}
|
||||
|
||||
impl RunAttrs {
|
||||
fn of(item: &core_types::record::GroupItem) -> Self {
|
||||
let layout = item.layout();
|
||||
Self {
|
||||
transform: FieldOffset::of(layout, 0),
|
||||
opacity: FieldOffset::of(layout, 0),
|
||||
opacity_fill: FieldOffset::of(layout, 0),
|
||||
clipping_mask: FieldOffset::of(layout, 0),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_or<'i, A: Attribute>(item: &'i core_types::record::GroupItem, field: Option<FieldOffset<A>>, lane: usize, default: A::Value<'i>) -> A::Value<'i> {
|
||||
match field.and_then(|field| item.lanes().get(lane).try_attr_at(field)) {
|
||||
Some(value) => value,
|
||||
None => default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn group_is_empty(group: &core_types::record::Group) -> bool {
|
||||
group.content.is_empty()
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_all_clipped(group: &core_types::record::Group) -> bool {
|
||||
let item = &group.content;
|
||||
let attrs = RunAttrs::of(item);
|
||||
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.clipping_mask, lane, false))
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_is_opaque(group: &core_types::record::Group) -> bool {
|
||||
let item = &group.content;
|
||||
let attrs = RunAttrs::of(item);
|
||||
let lanes = item.typed_lanes::<Graphic>();
|
||||
!item.is_empty()
|
||||
&& (0..item.len()).all(|lane| {
|
||||
RunAttrs::read_or(item, attrs.opacity, lane, 1.) >= 1.
|
||||
&& RunAttrs::read_or(item, attrs.opacity_fill, lane, 1.) >= 1.
|
||||
&& lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_opaque())
|
||||
})
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_is_fully_transparent(group: &core_types::record::Group) -> bool {
|
||||
let item = &group.content;
|
||||
let attrs = RunAttrs::of(item);
|
||||
let lanes = item.typed_lanes::<Graphic>();
|
||||
(0..item.len()).all(|lane| RunAttrs::read_or(item, attrs.opacity, lane, 1.) <= 0. || lanes.as_ref().is_some_and(|lanes| lanes.element_ref(lane).is_fully_transparent()))
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_bounding_box(group: &core_types::record::Group, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
|
||||
fn combine(combined: &mut Option<[DVec2; 2]>, any_infinite: &mut bool, bounds: RenderBoundingBox, thumbnail: bool) -> Option<RenderBoundingBox> {
|
||||
match bounds {
|
||||
RenderBoundingBox::None => None,
|
||||
RenderBoundingBox::Infinite if thumbnail => {
|
||||
*any_infinite = true;
|
||||
None
|
||||
}
|
||||
RenderBoundingBox::Infinite => Some(RenderBoundingBox::Infinite),
|
||||
RenderBoundingBox::Rectangle(bounds) => {
|
||||
*combined = Some(match *combined {
|
||||
Some(existing) => core_types::math::quad::Quad::combine_bounds(existing, bounds),
|
||||
None => bounds,
|
||||
});
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
fn typed_run<T: dyn_any::StaticTypeSized + BoundingBox>(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> Option<RenderBoundingBox> {
|
||||
let lanes = item.typed_lanes::<T>()?;
|
||||
let transform_offset = RunAttrs::of(item).transform;
|
||||
let mut combined = None;
|
||||
let mut any_infinite = false;
|
||||
for lane in 0..lanes.len() {
|
||||
let lane_transform = transform * RunAttrs::read_or(item, transform_offset, lane, DAffine2::IDENTITY);
|
||||
let element = lanes.element_ref(lane);
|
||||
let bounds = match thumbnail {
|
||||
true => element.thumbnail_bounding_box(lane_transform, include_stroke),
|
||||
false => element.bounding_box(lane_transform, include_stroke),
|
||||
};
|
||||
if let Some(short_circuit) = combine(&mut combined, &mut any_infinite, bounds, thumbnail) {
|
||||
return Some(short_circuit);
|
||||
}
|
||||
}
|
||||
Some(match (combined, any_infinite) {
|
||||
(Some(bounds), _) => RenderBoundingBox::Rectangle(bounds),
|
||||
(None, true) => RenderBoundingBox::Infinite,
|
||||
(None, false) => RenderBoundingBox::None,
|
||||
})
|
||||
}
|
||||
fn run_bounding_box(item: &core_types::record::GroupItem, transform: DAffine2, include_stroke: bool, thumbnail: bool) -> RenderBoundingBox {
|
||||
None.or_else(|| typed_run::<Graphic>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Vector>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Raster<CPU>>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Raster<GPU>>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<Color>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<GradientStops>(item, transform, include_stroke, thumbnail))
|
||||
.or_else(|| typed_run::<String>(item, transform, include_stroke, thumbnail))
|
||||
.unwrap_or(RenderBoundingBox::Infinite)
|
||||
}
|
||||
run_bounding_box(&group.content, transform, include_stroke, thumbnail)
|
||||
}
|
||||
|
||||
/// One step of the vector-row walk: continue to the next row or stop early.
|
||||
pub enum RowStep {
|
||||
Continue,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// The ancestor composition a flattened row inherits: transform, opacity and
|
||||
/// fill opacity multiply down, each composing only where some ancestor
|
||||
/// carries the attribute, matching the legacy flatten.
|
||||
#[derive(Clone, Copy)]
|
||||
struct FlattenScale {
|
||||
has_transform: bool,
|
||||
transform: DAffine2,
|
||||
has_opacity: bool,
|
||||
opacity: f64,
|
||||
has_fill_opacity: bool,
|
||||
fill_opacity: f64,
|
||||
}
|
||||
|
||||
impl FlattenScale {
|
||||
const ROOT: Self = Self {
|
||||
has_transform: false,
|
||||
transform: DAffine2::IDENTITY,
|
||||
has_opacity: false,
|
||||
opacity: 1.,
|
||||
has_fill_opacity: false,
|
||||
fill_opacity: 1.,
|
||||
};
|
||||
|
||||
fn composed<S: LaneSource>(self, source: &S, lane: usize) -> Self {
|
||||
let transform = source.try_attr::<Transform>(lane);
|
||||
let opacity = source.try_attr::<Opacity>(lane);
|
||||
let fill_opacity = source.try_attr::<OpacityFill>(lane);
|
||||
Self {
|
||||
has_transform: self.has_transform || transform.is_some(),
|
||||
transform: self.transform * transform.unwrap_or(DAffine2::IDENTITY),
|
||||
has_opacity: self.has_opacity || opacity.is_some(),
|
||||
opacity: self.opacity * opacity.unwrap_or(1.),
|
||||
has_fill_opacity: self.has_fill_opacity || fill_opacity.is_some(),
|
||||
fill_opacity: self.fill_opacity * fill_opacity.unwrap_or(1.),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A graphic level in either of its two storages, as one lane source.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum GraphicLevel<'a> {
|
||||
Legacy(&'a List<Graphic<'a>>),
|
||||
Run(&'a core_types::record::GroupItem<'a>),
|
||||
}
|
||||
|
||||
pub enum GraphicLevelColumn<'a, A: Attribute> {
|
||||
Legacy(core_types::list::ListColumn<'a, A>),
|
||||
Run(core_types::record::RunColumn<'a, A>),
|
||||
}
|
||||
|
||||
impl<'a, A: Attribute> core_types::lane::LaneColumn<'a, A> for GraphicLevelColumn<'a, A> {
|
||||
fn try_get(&self, lane: usize) -> Option<A::Value<'a>> {
|
||||
match self {
|
||||
GraphicLevelColumn::Legacy(column) => column.try_get(lane),
|
||||
GraphicLevelColumn::Run(column) => column.try_get(lane),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> LaneSource for GraphicLevel<'a> {
|
||||
type Element = Graphic<'a>;
|
||||
type Column<'b, A: Attribute>
|
||||
= GraphicLevelColumn<'b, A>
|
||||
where
|
||||
Self: 'b;
|
||||
|
||||
fn lane_count(&self) -> usize {
|
||||
match self {
|
||||
GraphicLevel::Legacy(list) => list.len(),
|
||||
GraphicLevel::Run(item) => item.len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn element(&self, lane: usize) -> Option<&Graphic<'a>> {
|
||||
match self {
|
||||
GraphicLevel::Legacy(list) => list.element(lane),
|
||||
GraphicLevel::Run(item) => {
|
||||
let lanes = item.typed_lanes::<Graphic>()?;
|
||||
if lane >= lanes.len() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: the layout records the element type, and a parked
|
||||
// element stores its reference at offset 0.
|
||||
Some(unsafe { core_types::record::borrow_element::<Graphic>(item.lanes().get(lane).rec()) })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn column<A: Attribute>(&self) -> GraphicLevelColumn<'_, A> {
|
||||
match self {
|
||||
GraphicLevel::Legacy(list) => GraphicLevelColumn::Legacy(list.column::<A>()),
|
||||
GraphicLevel::Run(item) => GraphicLevelColumn::Run(core_types::record::RunColumn::of(item)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The lane's attributes as an owned set, read through the erased glue.
|
||||
pub fn run_lane_attributes(item: &core_types::record::GroupItem, lane: usize) -> ItemAttributeValues {
|
||||
let mut scratch: List<Vector> = List::new_from_element(Vector::default());
|
||||
for field in &item.layout().fields {
|
||||
// SAFETY: the offset comes from the item's own layout.
|
||||
let value = unsafe { (field.read_erased)(item.lanes().get(lane).rec().ptr().add(field.offset)) };
|
||||
scratch.set_attribute_value_dyn(field.name, 0, AttributeValueDyn(value));
|
||||
}
|
||||
scratch.clone_item_attributes(0)
|
||||
}
|
||||
|
||||
/// The lane's attributes as an owned set, from either level storage.
|
||||
pub fn lane_attributes(level: GraphicLevel<'_>, lane: usize) -> ItemAttributeValues {
|
||||
match level {
|
||||
GraphicLevel::Legacy(list) => list.clone_item_attributes(lane),
|
||||
GraphicLevel::Run(item) => run_lane_attributes(item, lane),
|
||||
}
|
||||
}
|
||||
|
||||
/// One flattened vector row served by [`walk_vector_rows`]: cheap probes
|
||||
/// first, the full row built on demand.
|
||||
pub struct VectorRow<'w> {
|
||||
source: RowSourceRef<'w>,
|
||||
scale: FlattenScale,
|
||||
layer_path: Option<&'w [NodeId]>,
|
||||
paint: LanePaint<'w>,
|
||||
}
|
||||
|
||||
enum RowSourceRef<'w> {
|
||||
/// A de-tabled vector leaf on a graphic lane: the lane is the row.
|
||||
Lane(GraphicLevel<'w>, usize),
|
||||
/// A lane of a vector run.
|
||||
Run(&'w core_types::record::RunView<'w, Vector>, &'w core_types::record::GroupItem<'w>, usize),
|
||||
}
|
||||
|
||||
impl VectorRow<'_> {
|
||||
/// The row's vector, borrowed.
|
||||
pub fn element(&self) -> &Vector {
|
||||
match &self.source {
|
||||
RowSourceRef::Lane(level, index) => level.element(*index).and_then(Graphic::as_vector).expect("the walk visits vector lanes"),
|
||||
RowSourceRef::Run(run, _, index) => LaneSource::element(*run, *index).expect("the walk visits held lanes"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the built row will carry fill paint: the reaching lane paint,
|
||||
/// else the row's own.
|
||||
pub fn has_fill(&self) -> bool {
|
||||
if self.paint.fill.is_some() {
|
||||
return true;
|
||||
}
|
||||
match &self.source {
|
||||
RowSourceRef::Lane(level, index) => paint_graphics::<Fill, _>(level, *index).is_some(),
|
||||
RowSourceRef::Run(run, _, index) => paint_graphics::<Fill, _>(*run, *index).is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the row at the end of `out`, applying the reach paint and the
|
||||
/// inherited composition.
|
||||
pub fn build_into(&self, out: &mut List<Vector>) {
|
||||
let index = out.len();
|
||||
match &self.source {
|
||||
RowSourceRef::Lane(level, lane) => {
|
||||
let vector = self.element().clone();
|
||||
out.push(Item::from_parts(vector, lane_attributes(*level, *lane)));
|
||||
}
|
||||
RowSourceRef::Run(run, item, lane) => {
|
||||
let vector = LaneSource::element(*run, *lane).expect("the walk visits held lanes").clone();
|
||||
out.push(Item::from_parts(vector, run_lane_attributes(item, *lane)));
|
||||
}
|
||||
}
|
||||
for (key, slot) in [(ATTR_FILL, self.paint.fill), (ATTR_STROKE, self.paint.stroke)] {
|
||||
if let Some(paint) = slot {
|
||||
set_paint_attribute_at(out, index, key, paint.clone());
|
||||
}
|
||||
}
|
||||
if self.scale.has_transform || out.attribute::<DAffine2>(ATTR_TRANSFORM, index).is_some() {
|
||||
let row_transform: DAffine2 = out.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
out.set_attribute(ATTR_TRANSFORM, index, self.scale.transform * row_transform);
|
||||
}
|
||||
if self.scale.has_opacity || out.attribute::<f64>(ATTR_OPACITY, index).is_some() {
|
||||
let row_opacity: f64 = out.attribute_cloned_or(ATTR_OPACITY, index, 1.);
|
||||
out.set_attribute(ATTR_OPACITY, index, self.scale.opacity * row_opacity);
|
||||
}
|
||||
if self.scale.has_fill_opacity || out.attribute::<f64>(ATTR_OPACITY_FILL, index).is_some() {
|
||||
let row_fill: f64 = out.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.);
|
||||
out.set_attribute(ATTR_OPACITY_FILL, index, self.scale.fill_opacity * row_fill);
|
||||
}
|
||||
if let Some(layer_path) = self.layer_path {
|
||||
out.set_attribute(ATTR_EDITOR_LAYER_PATH, index, layer_path.to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk_rows_of_run(item: &core_types::record::GroupItem, scale: FlattenScale, layer_path: Option<&[NodeId]>, paint: LanePaint<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) -> RowStep {
|
||||
let Some(run) = core_types::record::RunView::<Vector>::new(item) else {
|
||||
return RowStep::Continue;
|
||||
};
|
||||
for lane in 0..item.len() {
|
||||
if let RowStep::Stop = visit(VectorRow {
|
||||
source: RowSourceRef::Run(&run, item, lane),
|
||||
scale,
|
||||
layer_path,
|
||||
paint,
|
||||
}) {
|
||||
return RowStep::Stop;
|
||||
}
|
||||
}
|
||||
RowStep::Continue
|
||||
}
|
||||
|
||||
/// Walks a graphic level into its flattened vector rows, matching the legacy
|
||||
/// push-then-flatten lowering: lane paint threads with [`PaintReach`],
|
||||
/// ancestor transform, opacity and fill opacity compose down, the containing
|
||||
/// level's parent layer path overwrites its rows, and non-vector content is
|
||||
/// discarded. A de-tabled leaf's row is its lane, attributes included.
|
||||
pub fn walk_vector_rows(level: GraphicLevel<'_>, visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep) {
|
||||
walk_vector_rows_impl(level, FlattenScale::ROOT, None, PaintReach::NONE, visit);
|
||||
}
|
||||
|
||||
fn walk_vector_rows_impl<'a>(
|
||||
level: GraphicLevel<'a>,
|
||||
scale: FlattenScale,
|
||||
parent_layer_path: Option<&'a [NodeId]>,
|
||||
inherited: PaintReach<'a>,
|
||||
visit: &mut dyn FnMut(VectorRow<'_>) -> RowStep,
|
||||
) -> RowStep {
|
||||
if let GraphicLevel::Run(item) = level {
|
||||
// A vector-typed run is already its rows.
|
||||
if item.typed_lanes::<Vector>().is_some() {
|
||||
let paint = match inherited.applies() {
|
||||
true => inherited.paint,
|
||||
false => LanePaint::NONE,
|
||||
};
|
||||
return walk_rows_of_run(item, scale, parent_layer_path, paint, visit);
|
||||
}
|
||||
}
|
||||
let columns = PaintColumns::new(&level);
|
||||
for index in 0..level.lane_count() {
|
||||
let Some(element) = level.element(index) else { continue };
|
||||
let reach = inherited.for_lane(&columns, index);
|
||||
let row_paint = match reach.applies() {
|
||||
true => reach.paint,
|
||||
false => LanePaint::NONE,
|
||||
};
|
||||
let step = match element {
|
||||
Graphic::Vector(_) => visit(VectorRow {
|
||||
source: RowSourceRef::Lane(level, index),
|
||||
scale,
|
||||
layer_path: parent_layer_path,
|
||||
paint: row_paint,
|
||||
}),
|
||||
Graphic::Graphic(children) => walk_vector_rows_impl(
|
||||
GraphicLevel::Legacy(children),
|
||||
scale.composed(&level, index),
|
||||
level.try_attr::<EditorLayerPath>(index),
|
||||
reach.nested(),
|
||||
visit,
|
||||
),
|
||||
Graphic::Group(group) => {
|
||||
let item = &group.content;
|
||||
if item.typed_lanes::<Vector>().is_some() {
|
||||
walk_rows_of_run(item, scale.composed(&level, index), level.try_attr::<EditorLayerPath>(index), row_paint, visit)
|
||||
} else if item.typed_lanes::<Graphic>().is_some() {
|
||||
walk_vector_rows_impl(
|
||||
GraphicLevel::Run(item),
|
||||
scale.composed(&level, index),
|
||||
level.try_attr::<EditorLayerPath>(index),
|
||||
reach.into_group_graphics(),
|
||||
visit,
|
||||
)
|
||||
} else {
|
||||
RowStep::Continue
|
||||
}
|
||||
}
|
||||
_ => RowStep::Continue,
|
||||
};
|
||||
if let RowStep::Stop = step {
|
||||
return RowStep::Stop;
|
||||
}
|
||||
}
|
||||
RowStep::Continue
|
||||
}
|
||||
|
||||
/// The level's flattened vector rows as one owned list, the walk's collect
|
||||
/// form.
|
||||
pub fn flatten_vector_rows(level: GraphicLevel<'_>) -> List<Vector> {
|
||||
let mut out = List::new();
|
||||
walk_vector_rows(level, &mut |row| {
|
||||
row.build_into(&mut out);
|
||||
RowStep::Continue
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// The transitional paint placement: a lane-level fill or stroke paint
|
||||
/// attribute moves onto the vector interiors the legacy paint readers
|
||||
/// inspect, reaching as far as the pre-flip broadcast did.
|
||||
pub(in crate::graphic) fn push_lane_paint_into_interiors(list: &mut List<Graphic>) {
|
||||
for index in 0..list.len() {
|
||||
for key in [ATTR_FILL, ATTR_STROKE] {
|
||||
let stored = list.attribute::<Option<List<Graphic>>>(key, index).and_then(|optional| optional.as_ref());
|
||||
let Some(paint) = stored.filter(|paint| is_paint_present(paint)).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let Some(Graphic::Graphic(children)) = list.element_mut(index) else { continue };
|
||||
for child in 0..children.len() {
|
||||
if matches!(children.element(child), Some(Graphic::Vector(_))) {
|
||||
set_paint_attribute_at(children, child, key, paint.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The count [`map_groups_to_legacy`] would expose through [`Graphic::as_vector`],
|
||||
/// read from the run's lanes instead of materializing the legacy list. Mirrors
|
||||
/// [`group_to_legacy_graphic`]'s typed-run path, where `Vector` is tried first.
|
||||
pub fn direct_vector_len(graphic: &Graphic) -> usize {
|
||||
match graphic {
|
||||
Graphic::Vector(_) => 1,
|
||||
Graphic::Group(group) => match &group.row {
|
||||
None => group.content.typed_lanes::<Vector>().map_or(0, |lanes| lanes.len()),
|
||||
_ => 0,
|
||||
},
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::graphic) fn group_render_complexity(group: &core_types::record::Group) -> usize {
|
||||
fn typed_run<T: dyn_any::StaticTypeSized + RenderComplexity>(item: &core_types::record::GroupItem) -> Option<usize> {
|
||||
let lanes = item.typed_lanes::<T>()?;
|
||||
Some((0..lanes.len()).map(|lane| lanes.element_ref(lane).render_complexity()).sum())
|
||||
}
|
||||
let item = &group.content;
|
||||
None.or_else(|| typed_run::<Graphic>(item))
|
||||
.or_else(|| typed_run::<Vector>(item))
|
||||
.or_else(|| typed_run::<Raster<CPU>>(item))
|
||||
.or_else(|| typed_run::<Raster<GPU>>(item))
|
||||
.or_else(|| typed_run::<Color>(item))
|
||||
.or_else(|| typed_run::<GradientStops>(item))
|
||||
.or_else(|| typed_run::<String>(item))
|
||||
.unwrap_or(item.len())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod run_tests {
|
||||
use super::*;
|
||||
use crate::graphic::test_support::unit_square_at;
|
||||
use crate::graphic::{IntoGraphicList, map_groups_to_legacy, run_to_legacy_list};
|
||||
use core_types::record::{FieldWrite, RunBuilder, RunView, element_write_hashed};
|
||||
|
||||
#[test]
|
||||
fn the_vector_row_walk_matches_the_legacy_flatten() {
|
||||
let inner_vector = unit_square_at(DVec2::ZERO);
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[], 1).unwrap();
|
||||
builder.push(inner_vector.clone()).unwrap();
|
||||
let inner_item = builder.finish();
|
||||
|
||||
let mut painted = List::new();
|
||||
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ZERO))));
|
||||
painted.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::ONE))));
|
||||
painted.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(1., 0.)));
|
||||
painted.set_attribute(core_types::ATTR_TRANSFORM, 1, DAffine2::from_translation(DVec2::new(0., 1.)));
|
||||
set_paint_attribute_at(&mut painted, 1, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
|
||||
|
||||
let mut nested = List::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(2., 2.))));
|
||||
nested.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_scale(DVec2::splat(2.)));
|
||||
|
||||
let mut top = List::new();
|
||||
top.push(Item::new_from_element(Graphic::Graphic(painted)));
|
||||
top.push(Item::new_from_element(Graphic::Graphic(nested)));
|
||||
top.push(Item::new_from_element(Graphic::Group(core_types::record::Group { row: None, content: inner_item })));
|
||||
top.push(Item::new_from_element(Graphic::Color(Color::BLACK)));
|
||||
top.push(Item::new_from_element(Graphic::Vector(unit_square_at(DVec2::new(6., 0.)))));
|
||||
top.set_attribute(core_types::ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(5., 5.)));
|
||||
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 0, vec![core_types::uuid::NodeId(7)]);
|
||||
set_paint_attribute_at(&mut top, 0, ATTR_FILL, List::new_from_element(Graphic::Color(Color::BLACK)));
|
||||
top.set_attribute(core_types::ATTR_OPACITY, 1, 0.5);
|
||||
top.set_attribute(core_types::ATTR_TRANSFORM, 2, DAffine2::from_scale(DVec2::splat(3.)));
|
||||
top.set_attribute(core_types::ATTR_TRANSFORM, 4, DAffine2::from_translation(DVec2::new(0., 7.)));
|
||||
top.set_attribute(core_types::ATTR_EDITOR_LAYER_PATH, 4, vec![core_types::uuid::NodeId(9)]);
|
||||
set_paint_attribute_at(&mut top, 4, ATTR_FILL, List::new_from_element(Graphic::Color(Color::WHITE)));
|
||||
|
||||
let legacy = {
|
||||
let mut list = List::new();
|
||||
for item in top.clone().into_iter() {
|
||||
let (element, attributes) = item.into_parts();
|
||||
list.push(Item::from_parts(map_groups_to_legacy(&element), attributes));
|
||||
}
|
||||
push_lane_paint_into_interiors(&mut list);
|
||||
list.into_flattened_list::<Vector>()
|
||||
};
|
||||
let native = flatten_vector_rows(GraphicLevel::Legacy(&top));
|
||||
assert_eq!(native.len(), legacy.len());
|
||||
for row in 0..native.len() {
|
||||
assert_eq!(
|
||||
native.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
|
||||
legacy.attribute::<DAffine2>(core_types::ATTR_TRANSFORM, row),
|
||||
"transform, row {row}"
|
||||
);
|
||||
assert_eq!(
|
||||
native.attribute::<f64>(core_types::ATTR_OPACITY, row),
|
||||
legacy.attribute::<f64>(core_types::ATTR_OPACITY, row),
|
||||
"opacity, row {row}"
|
||||
);
|
||||
assert_eq!(
|
||||
native.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
|
||||
legacy.attribute::<Vec<core_types::uuid::NodeId>>(core_types::ATTR_EDITOR_LAYER_PATH, row),
|
||||
"layer path, row {row}"
|
||||
);
|
||||
assert_eq!(
|
||||
native.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
|
||||
legacy.attribute::<Option<List<Graphic>>>(ATTR_FILL, row),
|
||||
"fill, row {row}"
|
||||
);
|
||||
}
|
||||
assert_eq!(native, legacy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_and_its_legacy_list_agree_on_bounding_boxes() {
|
||||
let vectors = [unit_square_at(DVec2::ZERO), unit_square_at(DVec2::new(4., 4.))];
|
||||
let transforms = [DAffine2::from_translation(DVec2::new(1., 2.)), DAffine2::from_scale(DVec2::splat(3.))];
|
||||
|
||||
let arena = core_types::arena::Arena::new(1 << 16).unwrap();
|
||||
let mut builder = RunBuilder::new(&arena, element_write_hashed::<Vector>(), &[FieldWrite::of::<core_types::attribute::Transform>(0)], 2).unwrap();
|
||||
for (vector, transform) in vectors.iter().zip(transforms) {
|
||||
let lane = builder.push(vector.clone()).unwrap();
|
||||
builder.attr::<core_types::attribute::Transform>(lane, transform);
|
||||
}
|
||||
let item = builder.finish();
|
||||
let run = RunView::<Vector>::new(&item).expect("the run holds vector elements");
|
||||
let legacy = run_to_legacy_list::<Vector>(&item).expect("the run lowers to a legacy vector list");
|
||||
|
||||
let outer = DAffine2::from_angle(0.3);
|
||||
for include_stroke in [false, true] {
|
||||
let bounds = run.bounding_box(outer, include_stroke);
|
||||
assert_eq!(bounds, legacy.bounding_box(outer, include_stroke));
|
||||
assert!(matches!(bounds, RenderBoundingBox::Rectangle(_)));
|
||||
assert_eq!(run.thumbnail_bounding_box(outer, include_stroke), legacy.thumbnail_bounding_box(outer, include_stroke));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -197,7 +197,7 @@ pub(crate) fn generate_node_code(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let field_pushed_levels: Vec<u8> = regular_fields
|
||||
.iter()
|
||||
.map(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0 => *list_levels as u8,
|
||||
ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0 => *list_levels,
|
||||
ParsedFieldType::Node(_) => pushed_levels,
|
||||
_ => 0,
|
||||
})
|
||||
@@ -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)
|
||||
@@ -728,7 +740,7 @@ pub(crate) struct NodePlan {
|
||||
|
||||
/// The field and generic derivation shared by the struct/metadata side and the
|
||||
/// impl side, computed once in [`generate_node_code`] and passed to
|
||||
/// [`generate_node_impl`]. `regular_fields` is the carrier-skipped slice both
|
||||
/// [`generate_node_impl`]. `regular_fields` is the non-data field slice both
|
||||
/// sides agree on.
|
||||
pub(crate) struct NodeFields<'a> {
|
||||
pub(crate) data_fields: Vec<&'a ParsedField>,
|
||||
@@ -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) };
|
||||
}
|
||||
@@ -1265,6 +1292,9 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
// A lazy input claims beyond every input frame this node holds, and its
|
||||
// cursor is shared, so the inputs a kernel drives claim past each other.
|
||||
// The snapshot copies the cursor where it stands, so every frame the node
|
||||
// still reads after the kernel runs (the carrier's included) must have been
|
||||
// claimed before it.
|
||||
let lazy_frames_entry = quote! {
|
||||
let __lazy_frames = __frame.frames().reborrow();
|
||||
};
|
||||
@@ -1399,8 +1429,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
}
|
||||
// A flip value or a routing non-source value rides a record input; the
|
||||
// element copies out into `name`. The mark/rewind that reclaims the
|
||||
// record's frame is applied by the step lowering (see `reads_out`).
|
||||
// element copies out into `name`.
|
||||
ValueBinding::RecordElement => {
|
||||
let slot = format_ident!("__in_{index}");
|
||||
quote! {
|
||||
@@ -1515,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
|
||||
@@ -1531,8 +1560,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
});
|
||||
|
||||
// The extent override is the leveled `extent_at`; consumers query the
|
||||
// composite `extent(ctx, Level)`, which the trait derives from it. A node
|
||||
// without `extent = fn` keeps the scalar default (one item at every level).
|
||||
// composite `extent(ctx, Level)`, which the trait derives from it.
|
||||
// The typed extent surface: the node's inputs in declaration order (values
|
||||
// readable without unsafe, inputs as per-level extent queries, derived
|
||||
// content promoted per copy), then the level paired with the node's depth.
|
||||
@@ -1716,12 +1744,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let fn_where = &parsed.where_clause;
|
||||
let body = if level_delta > 0 { rewrite_emit(&parsed.body) } else { parsed.body.clone() };
|
||||
let vis = &parsed.vis;
|
||||
let kernel_fields: Vec<&&ParsedField> = regular_fields.iter().filter(|field| !injected_name(&field.pat_ident.ident)).collect();
|
||||
// The input index rides along: an async kernel's param type depends on the
|
||||
// field's value binding, which is indexed off the node's inputs.
|
||||
let kernel_indexed: Vec<(usize, &&ParsedField)> = regular_fields.iter().enumerate().filter(|(_, field)| !kernel_omits(field)).collect();
|
||||
let kernel_fields: Vec<&&ParsedField> = kernel_indexed.iter().map(|(_, field)| *field).collect();
|
||||
// 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)))
|
||||
@@ -1756,12 +1789,18 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
};
|
||||
quote!(#pat: #ty)
|
||||
});
|
||||
let value_kernel_params = kernel_fields.iter().map(|field| {
|
||||
let value_kernel_params = kernel_indexed.iter().map(|(index, field)| {
|
||||
let pat = &field.pat_ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
unreachable!("async source fields are eager values");
|
||||
};
|
||||
quote!(#pat: #ty)
|
||||
// A materialized level is a borrowed arena view, which cannot cross
|
||||
// into a `'static` future; the prologue snapshots it to the owned
|
||||
// legacy list and the kernel takes that instead.
|
||||
match ir::materialized_levels(&node, *index) > 0 {
|
||||
true => quote!(#pat: #core_types::list::List<#ty>),
|
||||
false => quote!(#pat: #ty),
|
||||
}
|
||||
});
|
||||
let params = snapshot_param.chain(data_kernel_params).chain(value_kernel_params);
|
||||
quote! {
|
||||
@@ -1809,6 +1848,17 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.filter(|field| matches!(field.ty, ParsedFieldType::Regular(_)))
|
||||
.map(|field| &field.pat_ident.ident)
|
||||
.collect();
|
||||
let tail_form = if async_fn {
|
||||
Tail::SpawnAsyncFn
|
||||
} else if future_kernel {
|
||||
Tail::SpawnFuture
|
||||
} else {
|
||||
match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => Tail::Record,
|
||||
ir::NodeKind::Flip => Tail::Flip,
|
||||
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
|
||||
}
|
||||
};
|
||||
// A carried tail claims the node's frame first, evaluates the carrier
|
||||
// beyond it, and carries its fields; every exit closes the frame through
|
||||
// `lift_poll_into`.
|
||||
@@ -1852,6 +1902,37 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
})
|
||||
});
|
||||
// A record tail's carrier claim, the one the plan and the kernel read
|
||||
// `__src_rec` out of.
|
||||
let carrier_eval = (record_io && !skips_carrier && !lazy_carrier).then(|| {
|
||||
let name = ®ular_fields[0].pat_ident.ident;
|
||||
quote! {
|
||||
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into()
|
||||
};
|
||||
let __src_rec = self.__carrier.rec(&__src);
|
||||
}
|
||||
});
|
||||
// The carrier's record stays claimed and readable through the kernel call, so
|
||||
// its claim runs before the lazy snapshot and the lazy handles claim past it
|
||||
// rather than over it. With no lazy input there is no snapshot and the claim
|
||||
// stays in the tail.
|
||||
let has_lazy = regular_fields.iter().any(|field| matches!(field.ty, ParsedFieldType::Node(_)));
|
||||
let hoisted_carrier = match (has_lazy, tail_form) {
|
||||
(false, _) => TokenStream2::new(),
|
||||
(true, Tail::Record) => carrier_eval.clone().unwrap_or_default(),
|
||||
(true, _) => carried_prelude.clone().unwrap_or_default(),
|
||||
};
|
||||
let carried_prelude = match has_lazy {
|
||||
true => None,
|
||||
false => carried_prelude,
|
||||
};
|
||||
let carrier_eval = match has_lazy {
|
||||
true => None,
|
||||
false => carrier_eval,
|
||||
};
|
||||
let lazy_entry = quote!(#hoisted_carrier #lazy_frames_entry);
|
||||
// Async slots persist plain values across evaluations; the source lifts
|
||||
// the slot value onto its record input at every merge point, into the
|
||||
// carried frame when the node has a carrier.
|
||||
@@ -1958,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
|
||||
@@ -1968,16 +2049,6 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
}
|
||||
});
|
||||
let record_kernel_call = quote!(self::#fn_name(__input #(, &self.#data_names)* #(, #carrier_arg)* #(, #value_args)*));
|
||||
let carrier_eval = (!skips_carrier && !lazy_carrier).then(|| {
|
||||
let name = ®ular_fields[0].pat_ident.ident;
|
||||
quote! {
|
||||
let __src = match __cell.eval_input(0, &self.#name, __input, __frame.frames()) {
|
||||
Ok(value) => value,
|
||||
Err(interrupt) => return interrupt.into()
|
||||
};
|
||||
let __src_rec = self.__carrier.rec(&__src);
|
||||
}
|
||||
});
|
||||
let carry = (!skips_carrier && !lazy_carrier).then(|| quote!(unsafe { __frame.carry(__src_rec, &self.__plan) };));
|
||||
// A lazy carrier's source record is the token the kernel returned; its
|
||||
// content frames sit above the claim and stay readable until its drop.
|
||||
@@ -2099,28 +2170,37 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
__cell.merge(__frame.lift_served(#core_types::gpoll::GPoll::Final(__kernel_value), #core_types::context::ExtractArena::arena(__input)))
|
||||
}
|
||||
});
|
||||
let tail_form = if async_fn {
|
||||
Tail::SpawnAsyncFn
|
||||
} else if future_kernel {
|
||||
Tail::SpawnFuture
|
||||
} else {
|
||||
match ir::node_kind(&node) {
|
||||
ir::NodeKind::RecordIo => Tail::Record,
|
||||
ir::NodeKind::Flip => Tail::Flip,
|
||||
ir::NodeKind::Routing | ir::NodeKind::Opaque => Tail::Forward,
|
||||
}
|
||||
};
|
||||
let lower_tail = |form: Tail| match form {
|
||||
Tail::Forward => lift.clone(),
|
||||
Tail::Record => record_tail.clone().expect("a record-io node has a record tail"),
|
||||
Tail::Flip => flip_tail.clone().expect("a flip node has a flip tail"),
|
||||
Tail::SpawnAsyncFn => {
|
||||
let kernel_value_names: Vec<&Ident> = kernel_fields.iter().map(|field| &field.pat_ident.ident).collect();
|
||||
// The level is still live here (the prologue materialized it into the
|
||||
// evaluation's arena), so the owned copy is taken before the future
|
||||
// is built, as the owned-attr crossing does.
|
||||
let kernel_value_args: Vec<TokenStream2> = kernel_indexed
|
||||
.iter()
|
||||
.map(|(index, field)| {
|
||||
let name = &field.pat_ident.ident;
|
||||
let ParsedFieldType::Regular(RegularParsedField { ty, .. }) = &field.ty else {
|
||||
return quote!(#name.clone());
|
||||
};
|
||||
match ir::materialized_levels(&node, *index) > 0 {
|
||||
true => quote! {
|
||||
match #core_types::record::run_to_owned_list::<#ty>(&#name.as_group_item()) {
|
||||
::core::option::Option::Some(__owned) => __owned,
|
||||
::core::option::Option::None => return #core_types::gpoll::GPoll::Error(::std::boxed::Box::new(
|
||||
#core_types::gpoll::GraphError::new(::std::concat!("the materialized level of ", ::std::stringify!(#name), " holds another element type")),
|
||||
)),
|
||||
}
|
||||
},
|
||||
false => quote!(#name.clone()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let snapshot_binding = snapshot_ctx.then(|| quote!(let __snapshot = #core_types::context::CtxSnapshot::capture(__input);)).into_iter();
|
||||
let snapshot_arg = snapshot_ctx.then(|| quote!(__snapshot)).into_iter();
|
||||
let future_args = snapshot_arg
|
||||
.chain(data_names.iter().map(|name| quote!(self.#name.clone())))
|
||||
.chain(kernel_value_names.iter().map(|name| quote!(#name.clone())));
|
||||
let future_args = snapshot_arg.chain(data_names.iter().map(|name| quote!(self.#name.clone()))).chain(kernel_value_args);
|
||||
let completion = future_completion(&parsed.output_type);
|
||||
let tail = spawn_tail(completion, inflight.clone());
|
||||
let prelude = carried_prelude.iter();
|
||||
@@ -2227,7 +2307,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let clamp = clamp_tokens(field);
|
||||
(field, quote!(#body #clamp))
|
||||
}),
|
||||
&lazy_frames_entry,
|
||||
&lazy_entry,
|
||||
);
|
||||
// The rebind path with nothing hoisted: every non-carrier input binds
|
||||
// fresh per lane, so an index-dependent input reaches its own lane.
|
||||
@@ -2244,7 +2324,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
let clamp = clamp_tokens(field);
|
||||
(field, quote!(#body #clamp))
|
||||
}),
|
||||
&lazy_frames_entry,
|
||||
&lazy_entry,
|
||||
);
|
||||
// A hoisted value is moved into every lane's kernel call, so each
|
||||
// lane consumes a clone; view and borrow binds copy freely.
|
||||
@@ -2435,20 +2515,20 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, _)| ir::materialized_levels(&node, *index) == 0)
|
||||
.filter_map(|(_, field)| match &field.ty {
|
||||
.map(|(_, field)| match &field.ty {
|
||||
// The conditional arena-park moves a lend element once.
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => Some({
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend: Some(_), .. }) => {
|
||||
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
||||
quote!(#ty: ::core::marker::Send + ::core::marker::Sync + 'static)
|
||||
}),
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => Some({
|
||||
}
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => {
|
||||
let ty = &crate::codegen::classify::substitute_lifetimes(ty, "'static");
|
||||
quote!(#ty: ::core::clone::Clone)
|
||||
}),
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => Some({
|
||||
}
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => {
|
||||
let output_type = &crate::codegen::classify::substitute_lifetimes(output_type, "'static");
|
||||
quote!(#output_type: ::core::clone::Clone)
|
||||
}),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let out = crate::codegen::classify::substitute_lifetimes(&slot_value_type(&parsed.output_type), "'static");
|
||||
@@ -2466,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
|
||||
@@ -2514,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! {
|
||||
@@ -2530,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
|
||||
@@ -2568,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
|
||||
@@ -2595,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(),
|
||||
@@ -2613,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(®ular_fields, &node).into_iter().map(|index| {
|
||||
let slot = format_ident!("__mat_cache_{index}");
|
||||
@@ -2659,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)*
|
||||
@@ -2696,7 +2831,7 @@ pub(crate) fn generate_node_impl(crate_ident: &CrateIdent, parsed: &ParsedNodeFn
|
||||
EvalStep::Bind(index, field) => {
|
||||
let body = bind_body(*index, field, false, "e!(__frame.frames()));
|
||||
match matches!(field.ty, ParsedFieldType::Node(_)) && !std::mem::replace(&mut lazy_declared, true) {
|
||||
true => quote!(#lazy_frames_entry #body),
|
||||
true => quote!(#lazy_entry #body),
|
||||
false => body,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,7 +120,7 @@ pub(crate) fn routing_value_indices(regular_fields: &[&ParsedField], generic: &I
|
||||
}
|
||||
|
||||
/// The lazy inputs declaring attribute reads, with their indices into the
|
||||
/// unit-skipped regular fields.
|
||||
/// regular fields.
|
||||
pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(usize, &'a ParsedField)> {
|
||||
regular_fields
|
||||
.iter()
|
||||
@@ -130,7 +130,7 @@ pub(crate) fn lazy_read_fields<'a>(regular_fields: &[&'a ParsedField]) -> Vec<(u
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The indices (into the unit-skipped regular fields) of value inputs whose
|
||||
/// The indices (into the regular fields) of value inputs whose
|
||||
/// reads resolve against their own input rather than the carrier's.
|
||||
pub(crate) fn reading_secondary_indices(regular_fields: &[&ParsedField], skips_carrier: bool) -> Vec<usize> {
|
||||
regular_fields
|
||||
@@ -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());
|
||||
@@ -312,7 +342,7 @@ pub(crate) fn record_shape(parsed: &ParsedNodeFn) -> Option<RecordShape> {
|
||||
ParsedFieldType::Node(NodeParsedField { output_type, .. }) => is_served(output_type) || crate::codegen::ir::strip_ilist(output_type).1 > 0 || !field.attribute_reads.is_empty(),
|
||||
ParsedFieldType::Regular(_) => false,
|
||||
};
|
||||
if parsed.fields.iter().skip(lazy_carrier as usize).any(|field| unsupported_lazy_secondary(field)) {
|
||||
if parsed.fields.iter().skip(lazy_carrier as usize).any(unsupported_lazy_secondary) {
|
||||
return None;
|
||||
}
|
||||
let reads_well_placed = parsed.fields.iter().enumerate().all(|(index, field)| {
|
||||
@@ -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;
|
||||
@@ -423,10 +460,7 @@ pub(crate) fn flip_carrier(parsed: &ParsedNodeFn) -> bool {
|
||||
!(async_kernel && lend.is_some())
|
||||
}
|
||||
|
||||
/// Whether a plain node's lowering flips onto record inputs: sync,
|
||||
/// fully-concrete value-input nodes in this cut; batch, shader, async, lend,
|
||||
/// lazy, and generic nodes keep the plain lowering until their record forms
|
||||
/// land.
|
||||
/// Whether any value input declares `IList` nesting, so the node materializes a ranked input.
|
||||
pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
||||
parsed
|
||||
.fields
|
||||
@@ -434,6 +468,7 @@ pub(crate) fn has_materialized_input(parsed: &ParsedNodeFn) -> bool {
|
||||
.any(|field| matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0))
|
||||
}
|
||||
|
||||
/// Whether a plain node's lowering flips onto record inputs.
|
||||
pub(crate) fn record_flip(parsed: &ParsedNodeFn) -> bool {
|
||||
if record_shape(parsed).is_some() || has_record_io(parsed) || routing_io(parsed).is_some() || record_opaque(parsed) {
|
||||
return false;
|
||||
@@ -577,7 +612,7 @@ pub(crate) fn routing_io(parsed: &ParsedNodeFn) -> Option<RoutingIo> {
|
||||
}
|
||||
}
|
||||
}
|
||||
(sources > 0).then(|| RoutingIo { generic: ident })
|
||||
(sources > 0).then_some(RoutingIo { generic: ident })
|
||||
}
|
||||
|
||||
pub(crate) fn bare_ident(ty: &Type) -> Option<&Ident> {
|
||||
|
||||
@@ -6,13 +6,25 @@ use syn::spanned::Spanned;
|
||||
use syn::{GenericParam, Ident, Type};
|
||||
|
||||
pub(crate) fn entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, data_field_generic_idents: &[Ident], regular_fields: &[&ParsedField]) -> TokenStream2 {
|
||||
// A data-field generic is monomorphized by hand, so those nodes carry their own rows.
|
||||
if !data_field_generic_idents.is_empty() {
|
||||
return quote!();
|
||||
}
|
||||
match crate::codegen::ir::node_kind(&crate::codegen::ir::build(parsed)) {
|
||||
let entries = match crate::codegen::ir::node_kind(&crate::codegen::ir::build(parsed)) {
|
||||
crate::codegen::ir::NodeKind::Flip => flip_entries_tokens(parsed, struct_name, regular_fields),
|
||||
_ => single_row_entries(parsed, struct_name, regular_fields),
|
||||
};
|
||||
// Validation already rejects a generic input without implementations, so an
|
||||
// empty row set here is an emitter gap, not an unregistered shape.
|
||||
if entries.is_empty() && !parsed.attributes.skip_impl {
|
||||
emit_error!(
|
||||
parsed.fn_name.span(),
|
||||
"no registry rows were generated for `{}`, so a document cannot resolve it",
|
||||
parsed.fn_name;
|
||||
help = "give every generic input an #[implementations(...)] list, or mark the node skip_impl if it registers its rows by hand"
|
||||
);
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
/// The registry rows of a flipped plain node: every input is a record input,
|
||||
@@ -100,7 +112,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
}
|
||||
}
|
||||
let alias_params: Vec<&GenericParam> = candidate_params.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(param, _)| *param).collect();
|
||||
let alias_param_idents: Vec<Ident> = alias_params.iter().map(|param| param_ident(param)).collect();
|
||||
let alias_param_idents: Vec<Ident> = alias_params.iter().map(param_ident).collect();
|
||||
let alias_param_tokens: Vec<TokenStream2> = alias_params.iter().map(|param| quote!(#param)).collect();
|
||||
let output_alias = format_ident!("__{}_output", fn_name);
|
||||
let alias_def = match alias_param_tokens.is_empty() {
|
||||
@@ -130,7 +142,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
};
|
||||
let assignment_types = assignment_types.iter();
|
||||
let turbofish = quote!(::<#(#node_underscores,)* #(#assignment_types,)*>);
|
||||
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_edge_type::<#ty>()));
|
||||
let input_types = row.iter().map(|ty| quote!(gcore::registry::record_source_type::<#ty>()));
|
||||
let downcasts = names.iter().zip(row.iter()).enumerate().map(|(index, (name, ty))| {
|
||||
let handle = format_ident!("__handle_{index}");
|
||||
let layout = format_ident!("__layout_{index}");
|
||||
@@ -145,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),
|
||||
@@ -161,7 +173,7 @@ fn flip_entries_tokens(parsed: &ParsedNodeFn, struct_name: &Ident, regular_field
|
||||
let mut inputs = inputs.into_iter();
|
||||
#(#downcasts)*
|
||||
let __node = #struct_name #turbofish::new(#(#names,)* #(#layout_args)*);
|
||||
Ok(gcore::registry::EdgeHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
|
||||
Ok(gcore::registry::SourceHandle::new_record::<#row_output>(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>))
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -261,27 +273,34 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
// (erased routing generics included) is row-invariant. The carried list
|
||||
// mirrors the struct's carried generic parameters in declaration order.
|
||||
let ctx_ident = context_param(parsed).map(|ctx| ctx.ident.clone());
|
||||
let ranked_generic_idents: Vec<Ident> = parsed
|
||||
let ranked = |index: usize| matches!(®ular_fields[index].ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 0);
|
||||
// A record-io node's plain secondary reaches the constructor concrete, so its generic monomorphizes the row like a ranked element does.
|
||||
let record_secondary =
|
||||
|index: usize| matches!(ir::node_kind(&node), ir::NodeKind::RecordIo) && index > 0 && !node.inputs[index].subject && matches!(®ular_fields[index].ty, ParsedFieldType::Regular(_));
|
||||
let names_generic = |index: usize, generic: &Ident| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => crate::codegen::type_contains_ident(ty, generic),
|
||||
_ => false,
|
||||
};
|
||||
let solves_generic = |index: usize, generic: &Ident| match ®ular_fields[index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, implementations, .. }) => !implementations.is_empty() && generic_extractable(ty, generic),
|
||||
_ => false,
|
||||
};
|
||||
let carried_generic_idents: Vec<Ident> = parsed
|
||||
.fn_generics
|
||||
.iter()
|
||||
.filter_map(|param| match param {
|
||||
GenericParam::Type(type_param) if Some(&type_param.ident) != ctx_ident.as_ref() => Some(type_param.ident.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|ident| {
|
||||
regular_fields.iter().any(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, .. }) => *list_levels > 0 && crate::codegen::type_contains_ident(ty, ident),
|
||||
_ => false,
|
||||
})
|
||||
})
|
||||
.filter(|ident| (0..regular_fields.len()).any(|index| (ranked(index) || record_secondary(index)) && names_generic(index, ident)))
|
||||
.collect();
|
||||
let ranked_source = |generic: &Ident| {
|
||||
regular_fields.iter().position(|field| match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, list_levels, implementations, .. }) => *list_levels > 0 && !implementations.is_empty() && generic_extractable(ty, generic),
|
||||
_ => false,
|
||||
})
|
||||
// Ranked sources come first, so a generic a ranked input already carries keeps sourcing its rows from that input.
|
||||
let carried_source = |generic: &Ident| {
|
||||
(0..regular_fields.len())
|
||||
.find(|&index| ranked(index) && solves_generic(index, generic))
|
||||
.or_else(|| (0..regular_fields.len()).find(|&index| record_secondary(index) && solves_generic(index, generic)))
|
||||
};
|
||||
let carried: Option<Vec<(Ident, usize)>> = ranked_generic_idents.iter().map(|ident| ranked_source(ident).map(|index| (ident.clone(), index))).collect();
|
||||
let carried: Option<Vec<(Ident, usize)>> = carried_generic_idents.iter().map(|ident| carried_source(ident).map(|index| (ident.clone(), index))).collect();
|
||||
let Some(carried) = carried else {
|
||||
return quote!();
|
||||
};
|
||||
@@ -299,7 +318,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
let row_ty = ir::strip_ilist(&impls[row.min(impls.len() - 1)]).0;
|
||||
let field_ty = match ®ular_fields[*index].ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, .. }) => ty.clone(),
|
||||
_ => unreachable!("ranked sources are regular fields"),
|
||||
_ => unreachable!("carried sources are regular fields"),
|
||||
};
|
||||
generic_assignment(&field_ty, &row_ty, generic).map(|ty| (generic.clone(), ty))
|
||||
})
|
||||
@@ -339,8 +358,8 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
}
|
||||
|
||||
let input_types = slots.iter().map(|slot| match slot {
|
||||
SlotKind::BaseGeneric(name) => quote!(gcore::registry::generic_record_edge_type(#name)),
|
||||
SlotKind::BaseConcrete(ty) | SlotKind::Value(ty) | SlotKind::Extracted(ty) | SlotKind::Ranked(ty) => quote!(gcore::registry::record_edge_type::<#ty>()),
|
||||
SlotKind::BaseGeneric(name) => quote!(gcore::registry::generic_record_source_type(#name)),
|
||||
SlotKind::BaseConcrete(ty) | SlotKind::Value(ty) | SlotKind::Extracted(ty) | SlotKind::Ranked(ty) => quote!(gcore::registry::record_source_type::<#ty>()),
|
||||
});
|
||||
|
||||
let downcasts = names.iter().zip(&slots).enumerate().map(|(index, (name, slot))| {
|
||||
@@ -378,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))
|
||||
};
|
||||
|
||||
@@ -394,7 +413,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
let (io_output, wrap) = match &output_element {
|
||||
Some(element) => (
|
||||
quote!(gcore::registry::record_type::<#element>()),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
|
||||
quote!(Ok(gcore::registry::SourceHandle::new_record::<#element>(::std::sync::Arc::new(__node)))),
|
||||
),
|
||||
None => {
|
||||
let name = match &node.output.shape.element {
|
||||
@@ -404,7 +423,7 @@ fn single_row_entries(parsed: &ParsedNodeFn, struct_name: &Ident, regular_fields
|
||||
let base_ty = format_ident!("__ty_{}", base_indices[0]);
|
||||
(
|
||||
quote!(gcore::Type::Record(Box::new(gcore::Type::Generic(::std::borrow::Cow::Borrowed(#name))))),
|
||||
quote!(Ok(gcore::registry::EdgeHandle::new_erased(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>, #base_ty))),
|
||||
quote!(Ok(gcore::registry::SourceHandle::new_erased(::std::sync::Arc::new(__node) as ::std::sync::Arc<gcore::registry::ErasedRecordNode>, #base_ty))),
|
||||
)
|
||||
}
|
||||
};
|
||||
@@ -413,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}"));
|
||||
@@ -510,3 +547,122 @@ pub(crate) fn implementation_rows(parsed: &ParsedNodeFn, regular_fields: &[&Pars
|
||||
let row_count = candidates.iter().map(|types| types.len()).max().unwrap_or(1).max(1);
|
||||
Some((0..row_count).map(|row| candidates.iter().map(|types| types[row.min(types.len() - 1)].clone()).collect()).collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::parsing::parse_node_fn;
|
||||
|
||||
/// The macro's own pipeline up to the entries emitter, so a test node's rows
|
||||
/// match what `#[node]` would generate.
|
||||
fn entries_of(attr: TokenStream2, item: TokenStream2) -> String {
|
||||
let mut parsed = parse_node_fn(attr, item).unwrap();
|
||||
parsed.replace_impl_trait_in_input();
|
||||
if parsed.injects_async_source_fields() {
|
||||
parsed.inject_async_source_fields("e!(gcore));
|
||||
}
|
||||
let regular_fields: Vec<&ParsedField> = parsed.fields.iter().filter(|field| !field.is_data_field).collect();
|
||||
let data_field_generic_idents: Vec<Ident> = parsed
|
||||
.fn_generics
|
||||
.iter()
|
||||
.filter_map(|param| match param {
|
||||
GenericParam::Type(type_param) => Some(type_param.ident.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.filter(|ident| {
|
||||
parsed
|
||||
.fields
|
||||
.iter()
|
||||
.any(|field| field.is_data_field && matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { ty, .. }) if crate::codegen::type_contains_ident(ty, ident)))
|
||||
})
|
||||
.collect();
|
||||
entries_tokens(&parsed, &format_ident!("TestNode"), &data_field_generic_idents, ®ular_fields).to_string()
|
||||
}
|
||||
|
||||
/// A record-io async source whose only generic sits on a plain secondary:
|
||||
/// the shape the rasterize node has. One row per implementation, or the
|
||||
/// node never reaches the registry.
|
||||
#[test]
|
||||
fn record_io_source_rows_an_implementations_generic_secondary() {
|
||||
let entries = entries_of(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
async fn rasterize<T: Send + Clone>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(List<Vector>, List<Raster<CPU>>, List<Graphic>, List<Color>, List<GradientStops>)] data: List<T>,
|
||||
footprint: Footprint,
|
||||
canvas: CanvasHandle,
|
||||
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
);
|
||||
assert!(entries.contains("fn rasterize_entries"), "a registrable record-io source must emit its entries fn");
|
||||
for element in ["Vector", "Raster < CPU >", "Graphic", "Color", "GradientStops"] {
|
||||
let row = format!("record_source_type :: < List < {element} > > ()");
|
||||
assert!(entries.contains(&row), "the implementations row {element} is missing: {entries}");
|
||||
}
|
||||
assert_eq!(entries.matches("constructor :").count(), 5, "one row per implementation");
|
||||
assert!(!entries.contains("< T >"), "every row instantiates the carried generic");
|
||||
}
|
||||
|
||||
/// The same shape without implementations stays unregistered: nothing names
|
||||
/// the rows, so a silent empty emission is the intended answer.
|
||||
#[test]
|
||||
fn record_io_source_without_implementations_stays_unregistered() {
|
||||
let entries = entries_of(
|
||||
quote!(category(""), skip_impl),
|
||||
quote!(
|
||||
async fn rasterize_open<T: Send + Clone>(_: impl Ctx, _: (), data: List<T>) -> (Raster<CPU>, Attr<Transform>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
);
|
||||
assert!(entries.is_empty(), "an unsourced generic secondary registers nothing: {entries}");
|
||||
}
|
||||
|
||||
/// A ranked element generic keeps sourcing its rows from the ranked input.
|
||||
#[test]
|
||||
fn ranked_generic_still_rows_from_its_ranked_input() {
|
||||
let entries = entries_of(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
fn count<T: Send + Clone>(_: impl Ctx, _: (), #[implementations(IList<f64>, IList<u32>)] items: IList<T>) -> (u32, Attr<Opacity>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
);
|
||||
assert!(entries.contains("fn count_entries"), "a ranked record-io node still emits: {entries}");
|
||||
assert_eq!(entries.matches("constructor :").count(), 2, "one row per ranked implementation");
|
||||
}
|
||||
|
||||
/// An async source's materialized input crosses the future boundary as an
|
||||
/// owned snapshot: the prologue materializes the level while the evaluation
|
||||
/// is live, bridges it to the legacy list, and the kernel takes that.
|
||||
#[test]
|
||||
fn async_source_takes_a_materialized_input_as_an_owned_list() {
|
||||
let generated = crate::parsing::new_node_fn(
|
||||
quote!(category("")),
|
||||
quote!(
|
||||
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(Vector, Raster<CPU>, Graphic)] data: IList<T>,
|
||||
footprint: Footprint,
|
||||
) -> (Raster<CPU>, Attr<Transform>) {
|
||||
todo!()
|
||||
}
|
||||
),
|
||||
)
|
||||
.expect("the async materialized shape generates")
|
||||
.to_string();
|
||||
assert!(generated.contains("data : :: core_types :: list :: List < T >"), "the kernel takes the owned legacy list: {generated}");
|
||||
assert!(generated.contains("run_to_owned_list"), "the prologue snapshots the materialized level: {generated}");
|
||||
assert!(generated.contains("record :: materialize_batch"), "the level still materializes in the prologue: {generated}");
|
||||
for element in ["Vector", "Raster < CPU >", "Graphic"] {
|
||||
let row = format!("record_source_type :: < {element} > ()");
|
||||
assert!(generated.contains(&row), "the row carries the leveled element {element}: {generated}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,7 @@ fn generics(parsed: &ParsedNodeFn) -> Vec<Generic> {
|
||||
|
||||
fn inputs(parsed: &ParsedNodeFn, fields: &[&ParsedField], generics: &[Ident]) -> Vec<Input> {
|
||||
let routing = routing_io(parsed);
|
||||
let carrier_subject = flip_carrier(parsed) || record_shape(parsed).map_or(false, |shape| !shape.skips_carrier());
|
||||
let carrier_subject = flip_carrier(parsed) || record_shape(parsed).is_some_and(|shape| !shape.skips_carrier());
|
||||
fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -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,16 +265,24 @@ 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.iter().enumerate().filter_map(|(index, input)| {
|
||||
(matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty()).then(|| {
|
||||
let reads = node
|
||||
.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, input)| matches!(input.evaluation, Evaluation::Eager) && !input.shape.attrs.is_empty())
|
||||
.map(|(index, input)| {
|
||||
let descs = field_writes(&input.shape.attrs, core_types);
|
||||
let index = index as u8;
|
||||
quote!(#core_types::record::InputReads { input: #index, reads: ::std::vec![#(#descs),*] })
|
||||
})
|
||||
});
|
||||
});
|
||||
let writes = field_writes(&node.output.shape.attrs, core_types);
|
||||
let 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;
|
||||
@@ -287,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,
|
||||
@@ -351,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;
|
||||
@@ -359,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.
|
||||
@@ -524,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.
|
||||
@@ -547,6 +664,8 @@ pub(crate) struct ItemShape {
|
||||
pub(crate) attrs: Vec<LevelAttr>,
|
||||
}
|
||||
|
||||
// Macro IR built once per node at expansion time, so the variant spread costs nothing at runtime.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub(crate) enum Element {
|
||||
Concrete(Type),
|
||||
/// Indexes [`Node::generics`].
|
||||
@@ -734,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, "e!(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(
|
||||
@@ -857,9 +1097,7 @@ mod tests {
|
||||
let routing_source = |ty: &Type| generic.as_ref().is_some_and(|generic| crate::codegen::classify::routing_source_output(ty, generic));
|
||||
match &field.ty {
|
||||
ParsedFieldType::Regular(RegularParsedField { ty, lend, .. }) => {
|
||||
if record && !skips_carrier && index == 0 {
|
||||
"carrier"
|
||||
} else if carrier_flip && index == 0 {
|
||||
if index == 0 && ((record && !skips_carrier) || carrier_flip) {
|
||||
"carrier"
|
||||
} else if flip && lend.is_some() {
|
||||
"lend"
|
||||
|
||||
@@ -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()?;
|
||||
@@ -333,6 +369,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.
|
||||
@@ -619,10 +659,10 @@ impl Parse for NodeFnAttributes {
|
||||
let parsed_path: Path = meta.parse_args().map_err(|_| Error::new_spanned(meta, "Expected a valid path for 'batch', e.g., batch(my_batch)"))?;
|
||||
batch = Some(parsed_path);
|
||||
}
|
||||
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
|
||||
// Keeps the plain-input lowering for this node during the record transition.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
// #[node_macro::node(..., plain, ...)]
|
||||
"plain" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if plain {
|
||||
@@ -630,6 +670,10 @@ impl Parse for NodeFnAttributes {
|
||||
}
|
||||
plain = true;
|
||||
}
|
||||
// Instructs the generated eval to report `Pending` instead of passing partial upstream values into this node.
|
||||
//
|
||||
// Example usage:
|
||||
// #[node_macro::node(..., no_partial, ...)]
|
||||
"no_partial" => {
|
||||
let path = meta.require_path_only()?;
|
||||
if no_partial {
|
||||
@@ -1227,9 +1271,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,
|
||||
@@ -1352,6 +1405,7 @@ impl ParsedNodeFn {
|
||||
widget_override: ParsedWidgetOverride::Hidden,
|
||||
ty: ParsedFieldType::Regular(RegularParsedField {
|
||||
ty,
|
||||
name_source: None,
|
||||
list_levels: 0,
|
||||
lend: None,
|
||||
exposed: false,
|
||||
@@ -1529,6 +1583,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),
|
||||
@@ -1627,6 +1682,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),
|
||||
@@ -1706,6 +1762,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),
|
||||
@@ -1783,6 +1840,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),
|
||||
@@ -1872,6 +1930,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),
|
||||
@@ -1964,6 +2023,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,
|
||||
|
||||
@@ -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) {
|
||||
@@ -264,6 +277,14 @@ fn validate_async_source(parsed: &ParsedNodeFn) {
|
||||
"`async fn` source nodes cannot take `impl Node` inputs: the spawned future outlives any borrow of the graph, so it cannot evaluate other nodes; use the sync-prologue form (return `SourceFuture`) to evaluate lazy inputs before spawning"
|
||||
);
|
||||
}
|
||||
// One level snapshots to one owned legacy list; a deeper input has no
|
||||
// owned form to cross the future boundary with.
|
||||
if matches!(&field.ty, ParsedFieldType::Regular(RegularParsedField { list_levels, .. }) if *list_levels > 1) {
|
||||
emit_error!(
|
||||
field.pat_ident.span(),
|
||||
"`async fn` source nodes take a materialized input as an owned snapshot of one level, so nested `IList` is unsupported; flatten to a single `IList` or use the sync-prologue form (return `SourceFuture`)"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -416,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() {
|
||||
|
||||
@@ -83,10 +83,7 @@ fn brush_stamp_generator(_: impl Ctx, #[unit(" px")] diameter: f64, color: Color
|
||||
|
||||
/// Used to efficiently paint brush strokes. Applies the same texture repeatedly at different positions with proper blending and boundary handling.
|
||||
#[node_macro::node(category(""), skip_impl)]
|
||||
fn blit<BlendFn>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>>
|
||||
where
|
||||
BlendFn: Fn(Color, Color) -> Color,
|
||||
{
|
||||
fn blit<BlendFn: Fn(Color, Color) -> Color>(_: impl Ctx, mut target: List<Raster<CPU>>, texture: Raster<CPU>, positions: Vec<DVec2>, blend_mode: BlendFn) -> List<Raster<CPU>> {
|
||||
if positions.is_empty() {
|
||||
return target;
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ fn read_gradient(ctx: impl Ctx + ExtractVarArgs) -> List<GradientStops> {
|
||||
}
|
||||
|
||||
/// The mapped row riding as vararg 0, in the production single-item shape.
|
||||
fn vararg_list<'a, T: 'static>(ctx: &'a impl ExtractVarArgs) -> Option<&'a List<T>> {
|
||||
fn vararg_list<T: 'static>(ctx: &impl ExtractVarArgs) -> Option<&List<T>> {
|
||||
let arg = ctx.vararg(0).ok()?;
|
||||
(arg as &dyn std::any::Any).downcast_ref::<List<T>>()
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ fn memoize<'e, 'l>(
|
||||
return serve(entry, slot);
|
||||
}
|
||||
if leveled {
|
||||
return match content.materialize_level(&ctx, ctx.arena()) {
|
||||
return match content.materialize_level(ctx, ctx.arena()) {
|
||||
LevelStatus::Batch(batch, finality) => {
|
||||
let layout = content.layout();
|
||||
// SAFETY: the batch came from this input, so it carries the input's layout.
|
||||
@@ -107,7 +107,7 @@ fn memoize<'e, 'l>(
|
||||
};
|
||||
}
|
||||
// The output layout is the content's, so the claim is the content's frame.
|
||||
let result = content.serve(&ctx, slot);
|
||||
let result = content.serve(ctx, slot);
|
||||
let publishable = match &result {
|
||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||
@@ -185,7 +185,7 @@ fn frame_memo<'e, 'l>(
|
||||
};
|
||||
let past_end = || GPoll::Error(Box::new(core_types::gpoll::GraphError::past_end()));
|
||||
let entry = cache.lock().unwrap().as_ref().filter(|entry| entry.key == key).map(|entry| (entry.span, entry.finality));
|
||||
// A span that no longer resolves was flushed; the miss below re-publishes.
|
||||
// A span that no longer resolves was flushed.
|
||||
if let Some((span, finality)) = entry
|
||||
&& let Some(published) = span.batch(persistent, content.layout())
|
||||
{
|
||||
@@ -196,7 +196,7 @@ fn frame_memo<'e, 'l>(
|
||||
return serve(published.get(lane).rec().ptr(), finality, slot);
|
||||
}
|
||||
if leveled {
|
||||
return match content.materialize_level(&ctx, ctx.arena()) {
|
||||
return match content.materialize_level(ctx, ctx.arena()) {
|
||||
LevelStatus::Batch(batch, finality) => {
|
||||
// SAFETY: the batch came from this input, so it carries the input's layout.
|
||||
let span = unsafe { MaterializedSpan::to_persistent(&batch, &promotion) };
|
||||
@@ -212,7 +212,7 @@ fn frame_memo<'e, 'l>(
|
||||
};
|
||||
}
|
||||
// The output layout is the content's, so the claim is the content's frame.
|
||||
let result = content.serve(&ctx, slot);
|
||||
let result = content.serve(ctx, slot);
|
||||
let publishable = match &result {
|
||||
GPoll::Final(served) => Some((served.record(), Finality::AllFinal)),
|
||||
GPoll::Partial(served) => Some((served.record(), Finality::Partial)),
|
||||
@@ -246,7 +246,7 @@ fn monitor<'e, 'l>(
|
||||
if ctx.index() == 0 {
|
||||
*io.lock().unwrap() = Some(CtxSnapshot::capture(ctx));
|
||||
}
|
||||
content.serve(&ctx, slot)
|
||||
content.serve(ctx, slot)
|
||||
}
|
||||
|
||||
fn serialize_monitor(io: &MonitorValue) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
|
||||
@@ -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::{EdgeHandle, 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>>
|
||||
@@ -303,7 +303,7 @@ mod tests {
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let monitor = MonitorNode::new(lifted::<u32>(11u32), &layout);
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
let handle = SourceHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
assert!(handle.serialize().is_none(), "no snapshot before the first eval");
|
||||
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
@@ -331,7 +331,7 @@ mod tests {
|
||||
let source = core_types::value::LeveledValueSource::new(vec![10u32, 20, 30]);
|
||||
let layout = Node::<ContextImpl>::layout(&source).clone();
|
||||
let monitor = MonitorNode::new(source, &layout);
|
||||
let handle = EdgeHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
let handle = SourceHandle::new_record::<u32>(Arc::new(monitor) as Arc<ErasedRecordNode>);
|
||||
|
||||
let edge = handle.duplicate().downcast_record::<u32>().unwrap();
|
||||
let GPoll::Final(_) = core_types::record::serve_input(&edge, &ctx, &frames) else {
|
||||
@@ -475,8 +475,8 @@ mod tests {
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let layout = element_layout::<u32>();
|
||||
let edge = EdgeHandle::new_record::<u32>(Arc::new(counting()) as Arc<ErasedRecordNode>);
|
||||
let memoized = EdgeHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
|
||||
let edge = SourceHandle::new_record::<u32>(Arc::new(counting()) as Arc<ErasedRecordNode>);
|
||||
let memoized = SourceHandle::new_record::<u32>(Arc::new(MemoizeNode::new(edge.downcast_record::<u32>().unwrap(), &layout)) as Arc<ErasedRecordNode>);
|
||||
let stacked = MemoizeNode::new(memoized.downcast_record::<u32>().unwrap(), &layout);
|
||||
let stacked = core_types::record::RecordExtract::<u32, _>::new(stacked, &layout);
|
||||
|
||||
|
||||
@@ -171,8 +171,7 @@ fn extend_extent(base: ExtentIn<'_>, new: ExtentIn<'_>, level: LevelIn) -> GPoll
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer-path stamp: the flip-time replacement for the Merge
|
||||
/// subnetwork's named attribute write.
|
||||
/// The layer-path stamp: writes the owning layer's document node path on each lane.
|
||||
#[node_macro::node(category("Test"))]
|
||||
fn stamp_layer_path<'e, T>(ctx: impl Ctx + ExtractArena<'e>, element: T, path: Vec<NodeId>) -> Result<(T, Attr<'e, EditorLayerPath>), Interrupt> {
|
||||
let (parked, _) = ctx.arena().alloc(path).ok_or(GraphError {
|
||||
@@ -361,6 +360,15 @@ fn offset(_: impl Ctx, element: f64, by: &f64) -> f64 {
|
||||
element + *by
|
||||
}
|
||||
|
||||
/// Test-only flip node holding a borrow of its lent carrier across a lazy
|
||||
/// input's evaluation: the borrow points into the carrier's frame, so the lazy
|
||||
/// input's claim has to start beyond it.
|
||||
#[node_macro::node(category("Test"))]
|
||||
fn lend_across_lazy(ctx: impl Ctx, element: &f64, addend: impl Node<Context<'_>, Output = f64>) -> Result<f64, Interrupt> {
|
||||
let added = addend.eval(ctx)?;
|
||||
Ok(*element + added)
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Test"))]
|
||||
async fn double_async(_: impl Ctx, element: f64) -> f64 {
|
||||
element * 2.
|
||||
@@ -654,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)
|
||||
};
|
||||
@@ -663,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(),
|
||||
@@ -756,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,
|
||||
@@ -792,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,
|
||||
@@ -836,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,
|
||||
@@ -886,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,
|
||||
@@ -984,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,
|
||||
@@ -1052,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,
|
||||
@@ -1126,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,
|
||||
@@ -1170,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,
|
||||
@@ -1179,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,
|
||||
@@ -1254,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,
|
||||
@@ -1307,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,
|
||||
@@ -1523,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)])
|
||||
};
|
||||
@@ -1601,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,
|
||||
@@ -1654,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,
|
||||
@@ -1764,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,
|
||||
@@ -1890,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,
|
||||
@@ -2343,6 +2420,35 @@ mod tests {
|
||||
assert_eq!(served.attr::<Opacity>(), 0.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lent_carrier_borrow_survives_a_lazy_inputs_claim() {
|
||||
let arena = Arena::new(1024).unwrap();
|
||||
let generations = [];
|
||||
let scope = scope_fixture(&generations, &arena);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let carrier_layout = f64_layout(&["opacity"]);
|
||||
let addend_layout = f64_layout(&["opacity"]);
|
||||
assert!(carrier_layout.frame_bytes() != 0, "the lend must borrow into a spilled frame for the claims to overlap");
|
||||
let frames = frames_for(&[&carrier_layout, &addend_layout]);
|
||||
|
||||
let node = install(
|
||||
LendAcrossLazyNode::new(
|
||||
f64_record_source(&carrier_layout, 2., vec![("opacity", 0.25)]),
|
||||
f64_record_source(&addend_layout, 40., vec![("opacity", 0.5)]),
|
||||
&carrier_layout,
|
||||
&addend_layout,
|
||||
),
|
||||
lend_across_lazy_layout_meta(),
|
||||
&[Some(&carrier_layout), None],
|
||||
);
|
||||
let GPoll::Final(served) = core_types::record::capture(&node, &ctx, &frames) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
assert_eq!(served.element::<f64>(), 42., "the lazy input claims beyond the carrier's frame, so the borrow keeps its element");
|
||||
assert_eq!(served.attr::<Opacity>(), 0.25);
|
||||
}
|
||||
|
||||
struct InlineRuntime;
|
||||
|
||||
impl core_types::runtime::Runtime for InlineRuntime {
|
||||
@@ -2406,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)],
|
||||
);
|
||||
@@ -2445,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 {
|
||||
@@ -2860,8 +2956,14 @@ mod tests {
|
||||
let frames = frames_for(&[&layout]);
|
||||
let base = {
|
||||
let probe = frames.scope();
|
||||
// SAFETY: nothing reads the probe's record; only its address is taken.
|
||||
let value = unsafe { probe.claim(&layout).finish() };
|
||||
let mut claim = probe.claim(&layout);
|
||||
claim.element(0f64, &arena).expect("the arena holds the element");
|
||||
for name in ["opacity", "length"] {
|
||||
// SAFETY: the offset is this claim's own layout's, at the f64 the field was declared with.
|
||||
unsafe { claim.attr_at(layout.offset_of(name, 0).expect("the fixture declares the field"), 0f64) };
|
||||
}
|
||||
// SAFETY: the element and both fields complete the record.
|
||||
let value = unsafe { claim.finish() };
|
||||
layout.rec(&value).ptr()
|
||||
};
|
||||
|
||||
@@ -2984,8 +3086,8 @@ mod tests {
|
||||
{
|
||||
let scope = scope_fixture(&generations, &first_arena).with_persistent(&persistent);
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
let mut first = frames.reborrow();
|
||||
let GPoll::Final(_) = core_types::record::serve_input(&memo, &ctx, &mut first) else {
|
||||
let first = frames.reborrow();
|
||||
let GPoll::Final(_) = core_types::record::serve_input(&memo, &ctx, &first) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -226,7 +227,7 @@ where
|
||||
}
|
||||
let fill = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_FILL, source).cloned().flatten())?;
|
||||
let stroke = park_paint(legacy.attribute::<Option<List<Graphic>>>(graphic_types::ATTR_STROKE, source).cloned().flatten())?;
|
||||
let layer_path: Vec<NodeId> = legacy.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, source).map(|path| path.clone()).unwrap_or_default();
|
||||
let layer_path: Vec<NodeId> = legacy.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, source).cloned().unwrap_or_default();
|
||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||
|
||||
Ok((
|
||||
@@ -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<'e, T>(
|
||||
_: impl Ctx,
|
||||
/// The content whose lanes carry the attribute; its element is never read.
|
||||
(content, value): (T, Attr<'e, Named<Name0, $row>>),
|
||||
/// The attribute name, folded into an offset when the graph compiles.
|
||||
name: Named<Name0>,
|
||||
) -> $value {
|
||||
let _ = content;
|
||||
*value
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
attribute_reads! {
|
||||
/// Reads a named `f64` attribute, such as `opacity` or `font_size`.
|
||||
read_number_attribute: f64 => f64;
|
||||
/// Reads a named `u64` attribute, such as a regex match's `start` or `end`.
|
||||
read_integer_attribute: u64 => u64;
|
||||
/// Reads a named `bool` attribute, such as `clipping_mask` or `clip`.
|
||||
read_bool_attribute: bool => bool;
|
||||
/// Reads a named `DVec2` attribute, such as an artboard's `location` or `dimensions`.
|
||||
read_coordinate_attribute: DVec2 => DVec2;
|
||||
/// Reads a named `DAffine2` attribute, such as `transform`.
|
||||
read_transform_attribute: DAffine2 => DAffine2;
|
||||
/// Reads a named `Color` attribute, such as an artboard's `background`.
|
||||
read_color_attribute: Color => Color;
|
||||
/// Reads a named `BlendMode` attribute, such as `blend_mode`.
|
||||
read_blend_mode_attribute: core_types::blending::BlendMode => core_types::blending::BlendMode;
|
||||
/// Reads a named gradient-shape attribute, such as `gradient_type`.
|
||||
read_gradient_type_attribute: GradientTypeValue => GradientTypeValue;
|
||||
/// Reads a named gradient-spread attribute, such as `spread_method`.
|
||||
read_spread_method_attribute: GradientSpreadMethod => GradientSpreadMethod;
|
||||
}
|
||||
|
||||
/// Joins two levels of the same type, the base's lanes followed by the new's.
|
||||
#[node_macro::node(category("General"), extent(extend_extent))]
|
||||
pub fn extend<T>(
|
||||
@@ -540,7 +608,7 @@ fn to_graphic_unit_extent(_content: core_types::extent::ValueIn<'_, ()>, _level:
|
||||
/// The transitional level bridge: the input's records as the legacy list an
|
||||
/// unconverted consumer expects, attributes copied through their erased
|
||||
/// reads and content kept in its native form. Registered under the legacy
|
||||
/// convert identifiers; the rows die with the last legacy consumer.
|
||||
/// convert identifiers.
|
||||
#[node_macro::node(category(""))]
|
||||
pub fn level_to_list<T: Clone + Send + Sync + CacheHash + dyn_any::StaticTypeSized>(
|
||||
_: impl Ctx,
|
||||
|
||||
@@ -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,
|
||||
@@ -551,9 +561,9 @@ mod tests {
|
||||
let entries = _flat_map_mod::flat_map_entries();
|
||||
assert_eq!(entries.len(), 6, "one registry row per content implementation");
|
||||
let content_types: Vec<core_types::Type> = entries.iter().map(|entry| entry.io.inputs[0].clone()).collect();
|
||||
assert_eq!(content_types[0], core_types::registry::record_edge_type::<Graphic>());
|
||||
assert_eq!(content_types[1], core_types::registry::record_edge_type::<Vector>());
|
||||
assert_eq!(content_types[5], core_types::registry::record_edge_type::<String>());
|
||||
assert_eq!(content_types[0], core_types::registry::record_source_type::<Graphic>());
|
||||
assert_eq!(content_types[1], core_types::registry::record_source_type::<Vector>());
|
||||
assert_eq!(content_types[5], core_types::registry::record_source_type::<String>());
|
||||
// The subject and the output stay erased across rows.
|
||||
assert_eq!(entries[0].io.inputs[1], entries[5].io.inputs[1]);
|
||||
assert_eq!(entries[0].io.return_value, entries[5].io.return_value);
|
||||
@@ -750,10 +760,11 @@ mod tests {
|
||||
let copy = unsafe { (out.element.clone_out)(out.rec(&value).ptr()) };
|
||||
|
||||
let replay_arena = Arena::new(1 << 16).unwrap();
|
||||
let mut slot = [0u8; 8];
|
||||
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr(), &replay_arena) }.expect("the arena holds the replay");
|
||||
// Word storage: a parked element slot holds an 8-aligned reference.
|
||||
let mut slot = [0u64; 1];
|
||||
unsafe { (out.element.repark)(&*copy, slot.as_mut_ptr().cast(), &replay_arena) }.expect("the arena holds the replay");
|
||||
// SAFETY: the re-park wrote a parked `Graphic` element into `slot`.
|
||||
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr())) }) else {
|
||||
let Graphic::Group(group) = (unsafe { record::borrow_element::<Graphic>(record::Rec::new(slot.as_ptr().cast())) }) else {
|
||||
panic!("the replay restores the group element");
|
||||
};
|
||||
let item = &group.content;
|
||||
@@ -880,13 +891,16 @@ mod tests {
|
||||
let head = ctx.index_head();
|
||||
let group = {
|
||||
// SAFETY: the element is cloned out inside the scope, so no borrow
|
||||
// into the frame escapes it.
|
||||
// into the frame escapes it. The clone is shallow, so the `'static`
|
||||
// the `GraphicSource` rows infer launders a borrow of `arena`: it is
|
||||
// contained because `arena` outlives every use below and this test
|
||||
// never resets it, so the interior stays resident for the whole
|
||||
// generation the group is read in.
|
||||
let scope = frames.scope();
|
||||
let GPoll::Final(value) = record::serve_input(&wrapped, &ctx.promoted(&head, 0), &scope) else {
|
||||
panic!("expected a final record");
|
||||
};
|
||||
let group = unsafe { record::borrow_element::<Graphic>(wrap_out.rec(&value)) }.clone();
|
||||
group
|
||||
unsafe { record::borrow_element::<Graphic>(wrap_out.rec(&value)) }.clone()
|
||||
};
|
||||
|
||||
// One row holding the wrapped group flattens back to the lanes, the
|
||||
|
||||
@@ -9,13 +9,13 @@ use core_types::gpoll::GPoll;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::list::List;
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::math::bbox::Bbox;
|
||||
use core_types::runtime::SourceFuture;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::transform::Footprint;
|
||||
#[cfg(target_family = "wasm")]
|
||||
use core_types::{ATTR_TRANSFORM, WasmNotSend};
|
||||
use core_types::{Color, Ctx};
|
||||
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
|
||||
pub use graph_craft::application_io::*;
|
||||
@@ -204,17 +204,17 @@ fn create_canvas(_: impl Ctx) -> CanvasHandle {
|
||||
/// Renders a view of the input graphic within an area defined by the *Footprint*.
|
||||
#[cfg(target_family = "wasm")]
|
||||
#[node_macro::node(category(""))]
|
||||
async fn rasterize<T: WasmNotSend + Clone>(
|
||||
async fn rasterize<T: Clone + Send + Sync + dyn_any::StaticTypeSized>(
|
||||
_: impl Ctx,
|
||||
_: (),
|
||||
#[implementations(
|
||||
List<Vector>,
|
||||
List<Raster<CPU>>,
|
||||
List<Graphic>,
|
||||
List<Color>,
|
||||
List<GradientStops>,
|
||||
Vector,
|
||||
Raster<CPU>,
|
||||
Graphic,
|
||||
Color,
|
||||
GradientStops,
|
||||
)]
|
||||
mut data: List<T>,
|
||||
mut data: IList<T>,
|
||||
footprint: Footprint,
|
||||
mut canvas: CanvasHandle,
|
||||
) -> (Raster<CPU>, Attr<Transform>, OwnedAttr<EditorMergedLayers>)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1016,7 +1016,7 @@ mod graphene_test {
|
||||
use core_types::node::{BatchStatus, Node};
|
||||
use core_types::record::{Layout, LiftedSource, RecordValue, serve_input};
|
||||
use core_types::registry::{ErasedRecordNode, construct};
|
||||
use core_types::value::record_value_edge;
|
||||
use core_types::value::record_value_source;
|
||||
use std::mem::MaybeUninit;
|
||||
|
||||
fn scope_fixture(arena: &Arena) -> EvalScope<'_> {
|
||||
@@ -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(),
|
||||
@@ -1111,9 +1114,12 @@ mod graphene_test {
|
||||
let ctx = ContextImpl::root(&scope);
|
||||
|
||||
let entries = super::_logical_or_mod::logical_or_entries();
|
||||
let mut wired = construct(&entries[0], vec![record_value_edge(true), record_value_edge(false)]).unwrap();
|
||||
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(),
|
||||
@@ -1148,18 +1154,21 @@ mod graphene_test {
|
||||
assert_eq!(entries.len(), 6);
|
||||
assert_eq!(
|
||||
entries[0].io.inputs,
|
||||
vec![core_types::registry::record_edge_type::<f64>(), core_types::registry::record_edge_type::<f64>()]
|
||||
vec![core_types::registry::record_source_type::<f64>(), core_types::registry::record_source_type::<f64>()]
|
||||
);
|
||||
assert_eq!(entries[0].io.return_value, core_types::registry::record_type::<f64>());
|
||||
assert_eq!(
|
||||
entries[3].io.inputs,
|
||||
vec![core_types::registry::record_edge_type::<DVec2>(), core_types::registry::record_edge_type::<DVec2>()]
|
||||
vec![core_types::registry::record_source_type::<DVec2>(), core_types::registry::record_source_type::<DVec2>()]
|
||||
);
|
||||
assert_eq!(entries[3].io.return_value, core_types::registry::record_type::<DVec2>());
|
||||
|
||||
let mut wired = construct(&entries[0], vec![record_value_edge(1.5f64), record_value_edge(2.5f64)]).unwrap();
|
||||
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(),
|
||||
@@ -1179,7 +1188,7 @@ mod graphene_test {
|
||||
// Routing forwards the whole record, so the branch types need no rows.
|
||||
let entries = super::_switch_mod::switch_entries();
|
||||
assert_eq!(entries.len(), 1);
|
||||
assert_eq!(entries[0].io.inputs[0], core_types::registry::record_edge_type::<bool>());
|
||||
assert_eq!(entries[0].io.inputs[0], core_types::registry::record_source_type::<bool>());
|
||||
assert!(matches!(&entries[0].io.return_value, core_types::Type::Record(element) if matches!(**element, core_types::Type::Generic(_))));
|
||||
assert_eq!(entries[0].io.inputs.len(), 3);
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ fn boolean_core<'e>(
|
||||
use core_types::lane::LaneSource;
|
||||
let fill = park_paint(result_vector_list.attr::<Fill>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||
let stroke = park_paint(result_vector_list.attr::<Stroke>(0).filter(|paint| is_paint_present(paint)).cloned())?;
|
||||
let layer_path: Vec<NodeId> = result_vector_list.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, 0).map(|path| path.clone()).unwrap_or_default();
|
||||
let layer_path: Vec<NodeId> = result_vector_list.attribute::<Vec<NodeId>>(ATTR_EDITOR_LAYER_PATH, 0).cloned().unwrap_or_default();
|
||||
let layer_path = arena.alloc(layer_path).ok_or_else(exhausted)?.0;
|
||||
// Snapshot the input layers so the renderer can recurse into them for
|
||||
// editor click-target preservation.
|
||||
|
||||
@@ -433,7 +433,7 @@ mod tests {
|
||||
#[test]
|
||||
fn qr_code_test() {
|
||||
let qr = qr_code(&(), (), "https://graphite.art".to_string(), false, 1., QRCodeErrorCorrectionLevel::Low, true);
|
||||
assert!(qr.point_domain.ids().len() > 0);
|
||||
assert!(qr.segment_domain.ids().len() > 0);
|
||||
assert!(!qr.point_domain.ids().is_empty());
|
||||
assert!(!qr.segment_domain.ids().is_empty());
|
||||
}
|
||||
}
|
||||
@@ -327,7 +327,6 @@ fn paint_table(paint: core_types::node::List<'_, Graphic<'_>>) -> List<Graphic<'
|
||||
}
|
||||
|
||||
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
|
||||
/// The gradient transform fallback spans the lane's own bounds rather than the whole content's.
|
||||
#[node_macro::node(category("Vector: Style"), path(graphene_core::vector), properties("fill_properties"))]
|
||||
fn fill<'e>(
|
||||
ctx: impl Ctx + ExtractArena<'e> + ExtractIndex + InjectIndex + Copy,
|
||||
@@ -1578,7 +1577,7 @@ fn emit_legacy_lane<'e>(
|
||||
/// one group lane, lane 0's layer path stamped on the wrapper.
|
||||
fn wrap_vector_level(content: core_types::node::List<'_, Vector>) -> List<Graphic<'_>> {
|
||||
let item = content.as_group_item();
|
||||
let layer_path: Vec<NodeId> = match content.len() > 0 {
|
||||
let layer_path: Vec<NodeId> = match !content.is_empty() {
|
||||
true => content.lane(0).attr::<EditorLayerPath>().to_vec(),
|
||||
false => Vec::new(),
|
||||
};
|
||||
@@ -1767,8 +1766,6 @@ fn path_is_closed(
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
// Converts with the write-attribute family: the record form needs a lazy
|
||||
// value input on a record node, which the macro does not accept yet, and it
|
||||
/// Sets each anchor point's position to the value the mapped input produces, with the point's
|
||||
/// index and current position provided via context.
|
||||
#[node_macro::node(category("Vector"), path(graphene_core::vector), extent(map_points_extent))]
|
||||
|
||||
Reference in new issue
Block a user