Compare commits

..
Author SHA1 Message Date
Dennis Kobert 54b308efc6 Export the compiler spike's workloads from .gdd saves with their definitions table, share entries across instances, and drop the Inline input 2026-11-09 19:19:14 +01:00
Dennis Kobert 90adad8c89 Fix the compiler spike's profiling examples after rebasing onto master 2026-11-09 19:19:12 +01:00
Dennis Kobert 8619ae05fe Unify adapter selection into one cost-tiered resolver and add typed named varargs to the compiler spike 2026-11-09 19:19:10 +01:00
Dennis Kobert f976f95cdc Insert promotion adapters as IR nodes, read converters from scope, and add a Rust codegen spike 2026-11-09 19:19:07 +01:00
Dennis Kobert 7c0f7bc29f Add a standalone compiler performance spike with incremental compilation and purity-based coercion 2026-11-09 19:19:05 +01:00
Dennis Kobert 58c35aa475 Remove the legacy undo/redo snapshot stacks and undo through the gdd storage alone (#4938)
* Remove the legacy undo/redo snapshot stacks and undo through the gdd storage alone

* Tidy comments and naming in the storage undo and abort paths

* Forget a discarded cursor step so neither redo nor the History panel brings it back

* Fix bugs caused by redoing past the end
2026-11-09 19:14:20 +01:00
Dennis Kobert 932da8abb0 Transition editor to save documents with the new format, but still with .graphite extension (#4937)
* Save as gdd by default

* Always save documents as zipped gdd archives with the .graphite extension and remove the storage round-trip validation

* Tidy comments and grouping in the gdd save and CLI open paths

* Keep .gdd-named CLI inputs on the archive path so a damaged file reports the archive error
2026-11-09 15:57:57 +00:00
Keavon Chambers c6cdc7fe92 New nodes: 'L-System' and 'Turtle Path' (#4920)
* New node: 'L-System'

* New node: 'Turtle Path'

* Give 'L-System' arrow rules, computed chances, cuts, and a Max Symbols input

* Add half steps, scaling, tropism, randomness, polygons, and UV counters to 'Turtle Path'

* Make 'L-System' chances probabilities out of 1

* Give 'Turtle Path' fixed command letters and make `!` and `?` scale the width

* Extend `.` in 'Turtle Path' to place free points with a `kind`
2026-11-09 12:08:49 +00:00
Keavon Chambers a7ac19fd6b Make 'Read Index' return 0 outside of any loop 2026-11-08 14:52:40 -08:00
Keavon Chambers 717103866e Fix undo leaving a document unable to render 2026-11-08 14:21:03 -08:00
Keavon Chambers d3f51f1522 Rename the Session panel to Collaboration and hide it by default 2026-11-08 14:21:03 -08:00
131 changed files with 11163 additions and 1324 deletions

No files matched your search

Generated
+4 -2
View File
@@ -4826,9 +4826,9 @@ dependencies = [
[[package]]
name = "ollev"
version = "0.2.0"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e858a872f7e5f74992f283fe52d9c184234e8505f316e6aa7822fa394b39d0a"
checksum = "d77164e6c8fb386ee064104ab480578451b0fd106ca4c0a6988eb7ca4ed9ec4b"
dependencies = [
"glam",
]
@@ -5408,6 +5408,7 @@ dependencies = [
"interpreted-executor",
"log",
"node-macro",
"serde_json",
]
[[package]]
@@ -7265,6 +7266,7 @@ dependencies = [
"graphene-hash",
"graphene-resource",
"ipsum",
"math-parser",
"node-macro",
"parley",
"rand",
+1 -1
View File
@@ -268,7 +268,7 @@ tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.8", features = ["html_reports"] }
gungraun = { version = "0.20" }
ndarray = "0.17"
ollev = "0.2.0"
ollev = "0.1.2"
dirs = "7.0"
cef = "156"
cef-dll-sys = "156"
+16 -2
View File
@@ -53,21 +53,35 @@ impl<L: Layout> Gdd<L> {
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
/// the undone `Rev`. The working registry is rewound in place by the reverse delta, so re-snapshot it
/// (alongside `head`) or a reopen would read a `registry.bin` inconsistent with the persisted cursor.
/// Records what the step named for [`take_remote_changes`](Self::take_remote_changes).
pub fn undo(&mut self) -> Result<Rev, Error> {
let rev = self.session.undo()?;
self.remote_changes.touched.extend(self.session.touched_between(self.session.head_rev(), rev));
self.persist_registry_snapshot()?;
self.persist_session_state()?;
Ok(rev)
}
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry.
/// Re-apply the most-recently-undone commit and persist the new cursor and re-snapshotted registry. Records what
/// the step named like [`undo`](Self::undo).
pub fn redo(&mut self) -> Result<Rev, Error> {
let from = self.session.head_rev();
let rev = self.session.redo()?;
self.remote_changes.touched.extend(self.session.touched_between(from, rev));
self.persist_registry_snapshot()?;
self.persist_session_state()?;
Ok(rev)
}
/// Forget the latest undone commit, so redo can't bring it back, and persist the cursor.
pub fn forget_latest_undo(&mut self) -> Result<Option<Rev>, Error> {
let forgotten = self.session.forget_latest_undo();
if forgotten.is_some() {
self.persist_session_state()?;
}
Ok(forgotten)
}
/// Set the person using this device. `peer` must be unused, so the previous user keeps their steps. Refused while connected.
pub fn set_user(&mut self, user: UserId, peer: PeerId) -> Result<(), Error> {
if self.session.user() == user {
@@ -562,7 +576,7 @@ impl<L: Layout> Gdd<L> {
self.remote_changes.touched.record(op);
}
self.stage_ops(ops)?;
Ok(())
self.end_interaction()
}
/// Retire what is due at `now_ms`. Open interactions never retire. `idle` means the editor is between steps.
+1 -2
View File
@@ -142,8 +142,7 @@ mod tests {
assert_eq!(tagged, graph_craft::document::value::TaggedValue::None);
}
/// A `SetExport(None)` truncation leaves a trailing empty slot. Such a network is value-equal to
/// the same network without that slot, so the soak oracle doesn't false-report drift.
/// A `SetExport(None)` truncation leaves a trailing empty slot, which doesn't change the network's value.
#[test]
fn trailing_empty_export_slot_is_value_equal() {
let compact = Network {
+1 -115
View File
@@ -1,4 +1,4 @@
use crate::{Attributes, Implementation, NetworkId, NodeId, PeerId, ROOT_NETWORK, Registry, ResourceId, ResourceStore, SourceKey, TimeStamp, Tombstone};
use crate::{Attributes, Implementation, NetworkId, NodeId, ROOT_NETWORK, Registry, ResourceStore, Tombstone};
use std::collections::{HashMap, HashSet};
impl Registry {
@@ -97,36 +97,6 @@ impl Registry {
true
}
/// True if the relative timestamp order on every shared timestamped slot agrees across
/// the two registries. Catches LWW-bookkeeping bugs that `value_equal` deliberately ignores.
///
/// For every pair of shared keys (a, b), checks that `self[a].cmp(self[b])` and
/// `other[a].cmp(other[b])` are compatible: `Equal` on either side is always compatible;
/// otherwise both sides must agree on direction. Equality on one side imposes no order, so
/// a registry with all-equal timestamps trivially passes against any other.
///
/// Slots present in only one registry are skipped. O(N²) in the number of shared timestamped
/// slots; intended for debug-only use.
pub fn order_consistent(&self, other: &Self) -> bool {
let self_stamps = collect_timestamps(self);
let other_stamps = collect_timestamps(other);
let shared: Vec<(TimestampKey, TimeStamp, TimeStamp)> = self_stamps.into_iter().filter_map(|(key, ts)| other_stamps.get(&key).map(|other_ts| (key, ts, *other_ts))).collect();
for i in 0..shared.len() {
for j in (i + 1)..shared.len() {
let self_order = shared[i].1.cmp(&shared[j].1);
let other_order = shared[i].2.cmp(&shared[j].2);
use std::cmp::Ordering::*;
let compatible = matches!((self_order, other_order), (Equal, _) | (_, Equal) | (Less, Less) | (Greater, Greater));
if !compatible {
return false;
}
}
}
true
}
}
pub(crate) fn attributes_value_equal(a: &Attributes, b: &Attributes) -> bool {
@@ -150,87 +120,3 @@ pub(crate) fn resources_value_equal(a: &ResourceStore, b: &ResourceStore) -> boo
})
})
}
/// Stable identity for any timestamp in a `Registry`, tombstoned content and existence stamps included. Used by
/// `order_consistent`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum TimestampKey {
/// A whole-entity stamp under its field name: presence, a shape or floor, a removal.
Node(NodeId, &'static str),
NodeInput(NodeId, usize),
NodeInputFloor(NodeId, usize),
NodeInputAttribute(NodeId, usize, String),
NodeAttribute(NodeId, String),
Network(NetworkId, &'static str),
NetworkExport(NetworkId, usize),
NetworkAttribute(NetworkId, String),
DocumentAttribute(String),
Resource(ResourceId, &'static str),
ResourceSource(ResourceId, SourceKey),
Document(&'static str),
PeerRegistration(PeerId),
}
fn collect_timestamps(registry: &Registry) -> HashMap<TimestampKey, TimeStamp> {
let mut out = HashMap::new();
let nodes = registry.node_instances.iter().chain(registry.removed_nodes.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, node) in nodes {
for (field, timestamp) in [
("presence", node.presence),
("network", node.network_timestamp),
("inputs", node.inputs_timestamp),
("implementation", node.implementation_timestamp),
("attributes", node.attributes.floor()),
] {
out.insert(TimestampKey::Node(id, field), timestamp);
}
for (i, slot) in node.inputs.iter().enumerate() {
out.insert(TimestampKey::NodeInput(id, i), slot.timestamp);
out.insert(TimestampKey::NodeInputFloor(id, i), slot.attributes.floor());
for (key, value) in &slot.attributes {
out.insert(TimestampKey::NodeInputAttribute(id, i, key.clone()), value.timestamp);
}
}
for (key, value) in &node.attributes {
out.insert(TimestampKey::NodeAttribute(id, key.clone()), value.timestamp);
}
}
let networks = registry.networks.iter().chain(registry.removed_networks.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, network) in networks {
for (field, timestamp) in [("presence", network.presence), ("exports", network.exports_timestamp), ("attributes", network.attributes.floor())] {
out.insert(TimestampKey::Network(id, field), timestamp);
}
for (i, slot) in network.exports.iter().enumerate() {
out.insert(TimestampKey::NetworkExport(id, i), slot.timestamp);
}
for (key, value) in &network.attributes {
out.insert(TimestampKey::NetworkAttribute(id, key.clone()), value.timestamp);
}
}
out.insert(TimestampKey::Document("attributes"), registry.attributes.floor());
for (key, value) in &registry.attributes {
out.insert(TimestampKey::DocumentAttribute(key.clone()), value.timestamp);
}
let resources = registry.resources.iter().chain(registry.removed_resources.iter().map(|(id, mark)| (id, &mark.content)));
for (&id, entry) in resources {
for (field, timestamp) in [("presence", entry.presence), ("hash", entry.hash_timestamp), ("sources", entry.sources_timestamp)] {
out.insert(TimestampKey::Resource(id, field), timestamp);
}
for (source_key, source_value) in &entry.sources {
out.insert(TimestampKey::ResourceSource(id, *source_key), source_value.timestamp);
}
}
for (&id, mark) in &registry.removed_nodes {
out.insert(TimestampKey::Node(id, "removed"), mark.timestamp);
}
for (&id, mark) in &registry.removed_networks {
out.insert(TimestampKey::Network(id, "removed"), mark.timestamp);
}
for (&id, mark) in &registry.removed_resources {
out.insert(TimestampKey::Resource(id, "removed"), mark.timestamp);
}
for (&peer, registration) in &registry.peer_users {
out.insert(TimestampKey::PeerRegistration(peer), registration.timestamp);
}
out
}
+17
View File
@@ -547,6 +547,18 @@ impl Session {
Ok(touched)
}
/// What the deltas from `tip` back along its parents to `base` named, without `base` itself.
pub fn touched_between(&self, base: Option<Rev>, tip: Rev) -> Touched {
let mut touched = Touched::default();
let mut cursor = Some(tip);
while cursor != base {
let Some(delta) = cursor.and_then(|rev| self.document.history.get(rev)) else { break };
touched.record(&delta.kind);
cursor = delta.parent;
}
touched
}
/// What the deltas on the head's line but not on `base`'s named, merged branches included. Fails unless `base` is
/// on the head's line.
fn touched_since(&self, base: Option<Rev>) -> Result<Touched, CrdtError> {
@@ -948,6 +960,11 @@ impl Session {
}
}
/// Forget the latest undone interaction, so redo can't bring it back.
pub fn forget_latest_undo(&mut self) -> Option<Rev> {
self.document.redo_stack.pop()
}
pub fn can_redo(&self) -> bool {
!self.document.redo_stack.is_empty()
}
-17
View File
@@ -1406,23 +1406,6 @@ fn a_network_re_added_shorter_keeps_only_its_own_exports() {
}
}
/// Two registries ordering a removal differently against a write are not order-consistent, though their values agree.
#[test]
fn order_consistency_covers_removal_stamps() {
let with_removal_at = |counter: u64| {
let mut document = fresh_document(PeerId(1));
let node = Node::new(NetworkId(1), crate::Implementation::ProtoNode(graphene_resource::ResourceId::from(7)), 0);
document.apply_op_idempotent(RegistryDelta::AddNode { id: NodeId(2), node: node.clone() }, ts(3, 1)).expect("add");
document
.apply_op_idempotent(RegistryDelta::RemoveNode { id: NodeId(1), snapshot: node }, ts(counter, 1))
.expect("remove");
document.working_registry
};
let (earlier, later) = (with_removal_at(2), with_removal_at(4));
assert!(earlier.value_equal(&later));
assert!(!earlier.order_consistent(&later));
}
/// An input naming a node whose addition has not arrived renders as a dangling input, as one naming a removed node does,
/// rather than failing the conversion: the placeholder knows nothing of the node's network.
#[test]
@@ -1249,3 +1249,32 @@ fn a_removed_network_counts_as_rendered_only_when_the_root_reaches_it() {
assert!(rendered.networks.contains_key(&run_by_root) && rendered.networks.contains_key(&nested));
assert!(!rendered.networks.contains_key(&run_by_stray) && rendered.removed_networks.contains_key(&run_by_stray));
}
#[test]
fn the_span_an_undo_walks_names_only_the_undone_step() {
let mut session = Session::with_peer(PeerId(1));
let base = step(&mut session, add_network(1));
let tip = step(&mut session, add_network(2));
let undone = session.undo().expect("undo");
assert_eq!(undone, tip);
let touched = session.touched_between(session.head_rev(), undone);
assert_eq!(touched.networks, [NetworkId(2)].into_iter().collect());
assert_eq!(session.head_rev(), Some(base));
let from = session.head_rev();
let redone = session.redo().expect("redo");
assert_eq!(session.touched_between(from, redone).networks, [NetworkId(2)].into_iter().collect());
}
#[test]
fn a_forgotten_undo_cannot_be_redone() {
let mut session = Session::with_peer(PeerId(1));
step(&mut session, add_network(1));
let tip = step(&mut session, add_network(2));
session.undo().expect("undo");
assert_eq!(session.forget_latest_undo(), Some(tip));
assert!(!session.can_redo());
assert!(session.redo_stack().is_empty());
}
+1 -2
View File
@@ -208,8 +208,7 @@ pub const COLOR_OVERLAY_BLACK_75: &str = "#000000bf";
// DOCUMENT
pub const FILE_EXTENSION: &str = "graphite";
/// New document container format. Save writes a `.gdd` with the legacy `.graphite` embedded as a fallback
/// during the dual-write soak; `.graphite` stays a supported open/import input.
/// Extension of documents saved before the `.gdd` container took the `.graphite` extension. Still opened and imported.
pub const GDD_FILE_EXTENSION: &str = "gdd";
pub const DEFAULT_DOCUMENT_NAME: &str = "Untitled Document";
pub const MAX_UNDO_HISTORY_LEN: usize = 100; // TODO: Add this to user preferences
+1 -2
View File
@@ -306,13 +306,12 @@ impl Dispatcher {
menu_bar_message_handler.focus_document = self.message_handlers.portfolio_message_handler.workspace.panel_layout.focus_document;
let layout = &self.message_handlers.portfolio_message_handler.workspace.panel_layout;
menu_bar_message_handler.data_panel_open = layout.is_panel_present(PanelType::Data);
menu_bar_message_handler.session_panel_open = layout.is_panel_present(PanelType::Session);
menu_bar_message_handler.collaboration_panel_open = layout.is_panel_present(PanelType::Collaboration);
menu_bar_message_handler.history_panel_open = layout.is_panel_present(PanelType::History);
menu_bar_message_handler.layers_panel_open = layout.is_panel_present(PanelType::Layers);
menu_bar_message_handler.inspector_open = layout.is_panel_present(PanelType::Inspector);
menu_bar_message_handler.message_logging_verbosity = self.message_handlers.debug_message_handler.message_logging_verbosity;
menu_bar_message_handler.reset_node_definitions_on_open = self.message_handlers.portfolio_message_handler.reset_node_definitions_on_open;
menu_bar_message_handler.show_storage_preferences = self.message_handlers.preferences_message_handler.show_storage_preferences;
if let Some(document) = self
.message_handlers
@@ -303,35 +303,11 @@ impl PreferencesDialogMessageHandler {
// =========
// DOCUMENTS
// =========
// Soak-only `.gdd` storage options, hidden unless enabled from the developer debug menu.
if preferences.show_storage_preferences {
{
let header = vec![TextLabel::new("Documents").italic(true).widget_instance()];
let save_as_gdd_description = "
Save documents in the new .gdd container format (with the legacy .graphite file embedded as a recovery fallback) instead of a plain .graphite file. The .gdd format is still being validated, so this is opt-in for now.\n\
\n\
*Default: Off.*
"
.trim();
let save_as_gdd_checkbox_id = CheckboxId::new();
let save_as_gdd = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.save_as_gdd)
.tooltip_label("Save as .gdd")
.tooltip_description(save_as_gdd_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::SaveAsGdd { enabled: checkbox_input.checked }.into())
.for_label(save_as_gdd_checkbox_id)
.widget_instance(),
TextLabel::new("Save as .gdd")
.tooltip_label("Save as .gdd")
.tooltip_description(save_as_gdd_description)
.for_checkbox(save_as_gdd_checkbox_id)
.widget_instance(),
];
let save_with_history_description = "
Include the document's edit history in saved files. Only applies with \"Save as .gdd\" enabled.\n\
Include the document's edit history in saved files.\n\
\n\
*Default: Off.*
"
@@ -353,30 +329,7 @@ impl PreferencesDialogMessageHandler {
.widget_instance(),
];
let validate_description = "
Validate every document save, open, and undo by round-tripping it through the .gdd storage format and comparing against the legacy path, logging any mismatch. Useful for debugging the .gdd format during its soak, but the per-edit round-trip has a performance cost.\n\
\n\
*Default: Off.*
"
.trim();
let validate_checkbox_id = CheckboxId::new();
let validate_storage_round_trip = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
CheckboxInput::new(preferences.validate_storage_round_trip)
.tooltip_label("Validate Storage Round-Trip")
.tooltip_description(validate_description)
.on_update(|checkbox_input: &CheckboxInput| PreferencesMessage::ValidateStorageRoundTrip { enabled: checkbox_input.checked }.into())
.for_label(validate_checkbox_id)
.widget_instance(),
TextLabel::new("Validate Storage Round-Trip")
.tooltip_label("Validate Storage Round-Trip")
.tooltip_description(validate_description)
.for_checkbox(validate_checkbox_id)
.widget_instance(),
];
rows.extend_from_slice(&[header, save_as_gdd, save_with_history, validate_storage_round_trip]);
rows.extend_from_slice(&[header, save_with_history]);
}
// =============
@@ -6,8 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::node_graph::utility_types::{
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeProgress, FrontendNodeType, FrontendRemoteCursor,
NodeGraphErrorDiagnostic,
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
};
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
@@ -273,10 +272,6 @@ pub enum FrontendMessage {
UpdateDocumentArtwork {
svg: String,
},
/// How far the work in progress of the active document has come from 0 to 1 (none when it has no work in progress).
UpdateDocumentProgress {
progress: Option<f64>,
},
UpdateRenderStatus {
status: RenderStatus,
},
@@ -331,9 +326,6 @@ pub enum FrontendMessage {
UpdateNodeGraphErrorDiagnostics {
errors: Vec<NodeGraphErrorDiagnostic>,
},
UpdateNodeGraphProgress {
progress: Vec<FrontendNodeProgress>,
},
UpdateVisibleNodes {
nodes: Vec<NodeId>,
},
@@ -58,10 +58,6 @@ pub enum MouseCursorIcon {
pub enum RenderStatus {
#[default]
Rendering,
/// Rendering a frame computed from provisional data, while async work is in progress.
Partial,
/// Rendering a frame computed from substitute data, because part of the graph failed.
Fallback,
Error,
Panic,
}
@@ -76,7 +76,7 @@ define_layout_target!(
NodeGraphControlBar,
/// The body of the Inspector containing many collapsable sections.
Inspector,
SessionPanel,
CollaborationPanel,
/// The contextual input key/mouse combination shortcuts shown in the status bar at the bottom of the window.
StatusBarHints,
/// The version information shown in the status bar at the bottom right of the window.
@@ -437,8 +437,6 @@ pub struct NodeSection {
/// Whether the content wire also continues up past its turn, to the section above that takes it from the bottom.
#[serde(rename = "contentWireContinues")]
pub content_wire_continues: bool,
/// How far the work in progress of the node has come from 0 to 1, shown in the section header with a button to cancel it (none when it has no work in progress).
pub progress: Option<f64>,
/// Whether this section is expanded to show its contents, as opposed to being collapsed down to just its header.
pub expanded: bool,
/// The ID of the node whose Inspector section this is.
@@ -492,7 +490,6 @@ impl LayoutGroup {
node_reference: false,
content_wire: None,
content_wire_continues: false,
progress: None,
expanded,
id,
layout,
@@ -600,7 +597,6 @@ impl Diffable for LayoutGroup {
node_reference: current_node_reference,
content_wire: current_content_wire,
content_wire_continues: current_content_wire_continues,
progress: current_progress,
expanded: current_expanded,
id: current_id,
layout: current_layout,
@@ -617,7 +613,6 @@ impl Diffable for LayoutGroup {
node_reference: new_node_reference,
content_wire: new_content_wire,
content_wire_continues: new_content_wire_continues,
progress: new_progress,
expanded: new_expanded,
id: new_id,
layout: new_layout,
@@ -637,7 +632,6 @@ impl Diffable for LayoutGroup {
|| *current_node_reference != new_node_reference
|| *current_content_wire != new_content_wire
|| *current_content_wire_continues != new_content_wire_continues
|| *current_progress != new_progress
|| *current_expanded != new_expanded
|| *current_id != new_id
{
@@ -653,7 +647,6 @@ impl Diffable for LayoutGroup {
*current_node_reference = new_node_reference;
*current_content_wire = new_content_wire;
*current_content_wire_continues = new_content_wire_continues;
*current_progress = new_progress;
*current_expanded = new_expanded;
*current_id = new_id;
current_layout.clone_from(&new_layout);
@@ -671,7 +664,6 @@ impl Diffable for LayoutGroup {
node_reference: new_node_reference,
content_wire: new_content_wire,
content_wire_continues: new_content_wire_continues,
progress: new_progress,
expanded: new_expanded,
id: new_id,
layout: new_layout,
@@ -21,10 +21,9 @@ pub struct MenuBarMessageHandler {
pub has_selection_history: (bool, bool),
pub message_logging_verbosity: MessageLoggingVerbosity,
pub reset_node_definitions_on_open: bool,
pub show_storage_preferences: bool,
pub make_path_editable_is_allowed: bool,
pub data_panel_open: bool,
pub session_panel_open: bool,
pub collaboration_panel_open: bool,
pub history_panel_open: bool,
pub layers_panel_open: bool,
pub inspector_open: bool,
@@ -61,7 +60,6 @@ impl LayoutHolder for MenuBarMessageHandler {
let message_logging_verbosity_names = self.message_logging_verbosity == MessageLoggingVerbosity::Names;
let message_logging_verbosity_contents = self.message_logging_verbosity == MessageLoggingVerbosity::Contents;
let reset_node_definitions_on_open = self.reset_node_definitions_on_open;
let show_storage_preferences = self.show_storage_preferences;
let make_path_editable_is_allowed = self.make_path_editable_is_allowed;
let about = MenuListEntry::new("About Graphite…")
@@ -689,10 +687,10 @@ impl LayoutHolder for MenuBarMessageHandler {
.tooltip_shortcut(action_shortcut!(WorkspaceMessageDiscriminant::ToggleDataPanelOpen))
.on_commit(|_| WorkspaceMessage::ToggleDataPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("Session")
.label("Session")
.icon(if self.session_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleSessionPanelOpen.into())
MenuListEntry::new("Collaboration")
.label("Collaboration")
.icon(if self.collaboration_panel_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| WorkspaceMessage::ToggleCollaborationPanelOpen.into())
.disabled(self.focus_document),
MenuListEntry::new("History")
.label("History")
@@ -740,10 +738,6 @@ impl LayoutHolder for MenuBarMessageHandler {
.label("Reset Nodes to Definitions on Open")
.icon(if reset_node_definitions_on_open { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen.into()),
MenuListEntry::new("Show Storage Preferences")
.label("Show Storage Preferences")
.icon(if show_storage_preferences { "CheckboxChecked" } else { "CheckboxUnchecked" })
.on_commit(|_| PreferencesMessage::ToggleShowStoragePreferences.into()),
],
vec![
MenuListEntry::new("Print Trace Logs")
@@ -1,6 +1,5 @@
//! Human-readable pretty-printers for the dual-write soak's validation checks: registry-vs-registry and
//! runtime-network-vs-runtime-network diffs. The callers are gated behind the `validate_storage_round_trip`
//! preference, so these ship in release but only run when the soak is turned on.
//! Human-readable pretty-printers for storage test failures: registry-vs-registry and
//! runtime-network-vs-runtime-network diffs.
use std::fmt::Write;
@@ -1,7 +1,7 @@
use std::collections::VecDeque;
use std::collections::{BTreeMap, HashSet};
use document_graph_storage::{Declarations, Registry, Value};
use document_graph_storage::{Declarations, Value};
use graph_craft::application_io::resource::{ResourceHash, ResourceId, ResourceRegistry, ResourceStorage};
use super::utility_types::network_interface::NodeNetworkInterface;
@@ -9,19 +9,12 @@ use super::utility_types::network_interface::editor_delta::{EditorDelta, Staging
use super::utility_types::network_interface::storage_metadata::{StorageMetadataView, build_interface_from_storage, collect_network_view_settings};
use crate::messages::portfolio::history::utility_types::LineChange;
/// Per-document undo/redo state: the legacy snapshot stacks plus the `Gdd` working-copy cursor that is
/// becoming the authoritative history. Owns the dual-stack bookkeeping push/pop/clear and the cursor's stage/retire/move/verify
/// lifecycle, so the handler drives history through one surface rather than three loose fields.
/// Per-document undo/redo state, kept in the `Gdd` working copy.
///
/// Not serialized: the legacy stacks are runtime-only, and a clone shares the working-copy container by
/// `Arc`, so it keeps reading the live working copy.
/// Not serialized: a clone shares the working-copy container by `Arc`, so it keeps reading the live working copy.
#[derive(derivative::Derivative)]
#[derivative(Clone, Debug, Default)]
pub struct DocumentHistory {
/// Stack of document network snapshots for previous history states.
legacy_undo_stack: VecDeque<NodeNetworkInterface>,
/// Stack of document network snapshots for future history states.
legacy_redo_stack: VecDeque<NodeNetworkInterface>,
/// The `Gdd` working copy: owns the CRDT `Session` and mirrors edits to disk. `None` until the mount
/// future built by `load_document` resolves.
#[derivative(Debug = "ignore")]
@@ -36,8 +29,8 @@ pub struct DocumentHistory {
/// moved without recording it (an upgrade on open), since the recorded batch would then describe only
/// part of the distance between the two.
needs_whole_document_stage: bool,
/// How storage undid each step on the legacy redo stack, aligned with its top.
undo_notes: Vec<UndoNote>,
/// How storage undid each step that redo can bring back, latest last.
undo_notes: VecDeque<UndoNote>,
}
#[derive(Clone, Debug)]
@@ -50,57 +43,12 @@ enum UndoNote {
Cursor,
}
/// Why [`DocumentHistory::move_cursor`] produced no interface.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CursorMoveError {
/// Nothing to move to, unmounted, or the move itself failed. The cursor did not move.
NotMoved,
/// The cursor moved but the rebuild from it failed. It stays moved unless the caller reverts it.
RebuildFailed,
}
impl DocumentHistory {
// ===== Legacy snapshot stacks =====
/// Push a snapshot onto the undo stack, evicting the oldest entry past the history cap.
pub fn push_undo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.legacy_undo_stack, snapshot);
}
/// Push a snapshot onto the redo stack, evicting the oldest entry past the history cap.
pub fn push_redo(&mut self, snapshot: NodeNetworkInterface) {
Self::push_capped(&mut self.legacy_redo_stack, snapshot);
}
/// Pop the most recent undo snapshot, or `None` when the stack is empty.
pub fn pop_undo(&mut self) -> Option<NodeNetworkInterface> {
self.legacy_undo_stack.pop_back()
}
/// Pop the most recent redo snapshot, or `None` when the stack is empty.
pub fn pop_redo(&mut self) -> Option<NodeNetworkInterface> {
self.legacy_redo_stack.pop_back()
}
/// Drop the most recently pushed undo snapshot (used to cancel a transaction that ended up unmodified).
pub fn discard_last_undo(&mut self) {
self.legacy_undo_stack.pop_back();
}
/// Clear the redo stack, called when a fresh edit invalidates the redo future.
/// Forget the steps redo could bring back.
pub fn clear_redo(&mut self) {
self.legacy_redo_stack.clear();
self.undo_notes.clear();
}
/// Add the resources referenced by every snapshot in both history stacks into `resources`, so
/// history-only resources stay alive for legacy undo/redo.
pub fn collect_used_resources(&self, resources: &mut HashSet<ResourceId>) {
for interface in self.legacy_undo_stack.iter().chain(&self.legacy_redo_stack) {
interface.collect_used_resources(resources);
}
}
// ===== Gdd working-copy cursor =====
/// The `Gdd` working copy, `None` until the mount future resolves.
@@ -137,75 +85,84 @@ impl DocumentHistory {
}
}
/// Undoes the latest step in storage alone. Returns whether storage undid it.
pub fn undo_in_storage(&mut self, in_session: bool) -> bool {
if self.legacy_undo_stack.is_empty() {
return false;
/// Undoes the latest step in storage, so it can be redone. Returns whether a step was undone.
pub fn undo(&mut self, in_session: bool) -> bool {
let Some(note) = self.undo_step(in_session) else { return false };
self.undo_notes.push_back(note);
if self.undo_notes.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
self.undo_notes.pop_front();
}
true
}
/// Undoes the latest step in storage without a way to redo it. Returns whether a step was undone.
pub fn discard_step(&mut self, in_session: bool) -> bool {
let Some(note) = self.undo_step(in_session) else { return false };
if matches!(note, UndoNote::Cursor)
&& let Some(storage) = self.storage.as_mut()
&& let Err(error) = storage.forget_latest_undo()
{
log::error!("Forgetting the discarded step failed: {error}");
}
true
}
/// Takes the latest step back. A hot step is retracted, a retired one is dropped from a session's shared line,
/// and otherwise the cursor moves back over it.
fn undo_step(&mut self, in_session: bool) -> Option<UndoNote> {
// A failed retract may already have taken the step back, so no older step is undone after it
let retracted = match self.retract_storage_interaction() {
Ok(retracted) => retracted,
Err(error) => {
log::error!("Taking the storage interaction back failed: {error}");
return false;
return None;
}
};
let note = if let Some(ops) = retracted {
UndoNote::Retracted(ops)
} else if in_session && let Some(rev) = self.undo_retired_step() {
UndoNote::Dropped(rev)
} else {
return false;
};
if let Some(snapshot) = self.pop_undo() {
self.push_redo(snapshot);
if let Some(ops) = retracted {
return Some(UndoNote::Retracted(ops));
}
self.note_undo(note);
true
// A session's history is shared, so its cursor never moves
if in_session {
return self.undo_retired_step().map(UndoNote::Dropped);
}
self.move_cursor(true).then_some(UndoNote::Cursor)
}
/// Reverses [`undo_in_storage`](Self::undo_in_storage). Returns whether the next redo step was undone there.
pub fn redo_in_storage(&mut self) -> bool {
if self.legacy_redo_stack.is_empty() {
return false;
}
let reachable = self.storage.as_ref().is_some_and(|storage| storage.can_change_line());
let Some(note) = self
.undo_notes
.pop_if(|note| matches!(note, UndoNote::Retracted(_)) || (reachable && matches!(note, UndoNote::Dropped(_))))
else {
return false;
};
/// Brings back the latest undone step. Returns whether it was redone.
pub fn redo(&mut self) -> bool {
let Some(note) = self.undo_notes.pop_back() else { return false };
let line_reachable = self.storage.as_ref().is_some_and(|storage| storage.can_change_line());
let redone = match &note {
UndoNote::Retracted(ops) => self.restage_ops(ops.clone()),
UndoNote::Dropped(rev) => self.redo_retired_step(*rev),
UndoNote::Cursor => true,
UndoNote::Dropped(rev) => line_reachable && self.redo_retired_step(*rev),
UndoNote::Cursor => self.move_cursor(false),
};
if !redone {
// The note stays paired with its redo snapshot
self.undo_notes.push(note);
return false;
self.undo_notes.push_back(note);
}
if let Some(snapshot) = self.pop_redo() {
self.push_undo(snapshot);
}
true
redone
}
pub fn note_cursor_undo(&mut self) {
self.note_undo(UndoNote::Cursor);
}
/// Move the cursor along the retired interaction chain, flushing any open interaction first. Returns whether it moved.
fn move_cursor(&mut self, undo: bool) -> bool {
self.retire_storage_interaction();
let Some(storage) = self.storage.as_mut() else { return false };
pub fn forget_undo_note(&mut self) {
self.undo_notes.pop();
}
fn note_undo(&mut self, note: UndoNote) {
self.undo_notes.push(note);
let evicted = self.undo_notes.len().saturating_sub(self.legacy_redo_stack.len());
self.undo_notes.drain(..evicted);
let moved = if undo {
if !storage.can_undo() {
return false;
}
storage.undo()
} else {
if !storage.can_redo() {
return false;
}
storage.redo()
};
moved.inspect_err(|error| log::error!("Storage undo/redo cursor move failed: {error}")).is_ok()
}
fn retract_storage_interaction(&mut self) -> Result<Option<Vec<document_graph_storage::RegistryDelta>>, document_format::Error> {
@@ -249,13 +206,6 @@ impl DocumentHistory {
result.inspect_err(|error| log::error!("Changing the history line with {change:?} failed: {error}")).is_ok()
}
/// Forgets the legacy snapshots once the head has moved off their line.
pub fn clear_legacy(&mut self) {
self.legacy_undo_stack.clear();
self.legacy_redo_stack.clear();
self.undo_notes.clear();
}
pub fn retire_storage_interaction(&mut self) {
let Some(storage) = self.storage.as_mut() else { return };
if let Err(error) = storage.retire_pending_interaction() {
@@ -320,8 +270,7 @@ impl DocumentHistory {
/// Stages what the store recorded since the last drain.
///
/// This and the whole-document conversion produce the same registry for the same edit, which
/// `verify_round_trip` checks when the `validate_storage_round_trip` preference is on. They differ in
/// This and the whole-document conversion produce the same registry for the same edit. They differ in
/// what they cost and in what they can miss: a conversion sees every change however it was made,
/// while this sees only what went through the store, so a write that bypasses it is not persisted.
fn stage_recorded(
@@ -361,32 +310,6 @@ impl DocumentHistory {
}
}
/// Move the `Gdd` undo/redo cursor along the retired interaction chain, flushing any open interaction
/// first, and rebuild the interface from the rewound registry using the declaration cache.
pub fn move_cursor(&mut self, undo: bool) -> Result<NodeNetworkInterface, CursorMoveError> {
self.retire_storage_interaction();
let storage = self.storage.as_mut().ok_or(CursorMoveError::NotMoved)?;
let moved = if undo {
if !storage.can_undo() {
return Err(CursorMoveError::NotMoved);
}
storage.undo().map(|_| ())
} else {
if !storage.can_redo() {
return Err(CursorMoveError::NotMoved);
}
storage.redo().map(|_| ())
};
if let Err(error) = moved {
log::error!("Storage undo/redo cursor move failed: {error}");
return Err(CursorMoveError::NotMoved);
}
self.rebuild_interface().ok_or(CursorMoveError::RebuildFailed)
}
/// Build a new interface from the working registry and cached declarations. `None` when it doesn't convert.
pub fn rebuild_interface(&self) -> Option<NodeNetworkInterface> {
let storage = self.storage.as_ref()?;
@@ -439,105 +362,4 @@ impl DocumentHistory {
}
}
}
/// Step the cursor back the other way, undoing a [`move_cursor`](Self::move_cursor) in the `undo`
/// direction whose rebuild failed.
pub fn revert_cursor(&mut self, undo: bool) {
let Some(storage) = self.storage.as_mut() else { return };
let reverted = if undo { storage.redo() } else { storage.undo() };
if let Err(error) = reverted {
log::error!("Storage undo/redo cursor revert failed: {error}");
}
}
// Soak round-trip verification (runtime-gated by `validate_storage_round_trip`)
// These log drift rather than panicking, since the soak can run in release where a crash is
// unacceptable; tests still fail loud via the `#[cfg(test)]` panics.
/// Soak check: the stored registry should equal a fresh `from_runtime`, and a `to_runtime` of it should
/// equal the original network.
pub fn verify_round_trip(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry) {
use super::diff_networks;
use super::document_diff::diff_registries;
let Some(storage) = &self.storage else { return };
let peer = storage.session().peer();
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let conversion = match Registry::convert_from_runtime(network, &metadata_view, registry, peer) {
Ok(conversion) => conversion,
Err(error) => {
log::error!("storage round-trip: from_runtime failed: {error}");
return;
}
};
let target = &conversion.registry;
let declarations = &conversion.declarations;
let stored = storage.registry();
if !stored.value_equal(target) {
log::error!("storage round-trip: registry value drift after commit\n{}", diff_registries(stored, target));
#[cfg(test)]
panic!("storage round-trip: registry value drift after commit");
}
if !stored.order_consistent(target) {
log::error!("storage round-trip: timestamp order inconsistent between stored and target");
#[cfg(test)]
panic!("storage round-trip: timestamp order inconsistent between stored and target");
}
let (round_tripped, _entries) = match stored.to_runtime_with_metadata(declarations, storage.blobs()) {
Ok(result) => result,
Err(error) => {
log::error!("storage round-trip: to_runtime failed: {error}");
return;
}
};
if &round_tripped != network {
log::error!("storage round-trip: network drift after to_runtime\n{}", diff_networks(network, &round_tripped));
#[cfg(test)]
panic!("storage round-trip: network drift after to_runtime");
}
}
/// Soak check: after a cursor move, the cursor's registry should equal a fresh `from_runtime` of the
/// current (legacy-restored) interface. `current_resources` are the resources the live network
/// references; history-only resources the cursor dropped are expected, not drift.
pub fn verify_cursor_matches_runtime(&self, interface: &NodeNetworkInterface, registry: &ResourceRegistry, current_resources: &HashSet<ResourceId>) {
use super::document_diff::diff_registries;
let Some(storage) = &self.storage else { return };
let peer = storage.session().peer();
let network = interface.document_network();
let metadata_view = StorageMetadataView::new(interface);
let Ok(mut conversion) = Registry::convert_from_runtime(network, &metadata_view, registry, peer) else {
log::error!("undo/redo shadow: from_runtime failed");
return;
};
let stored = storage.registry();
// The cursor reverts the interaction's `AddResource` while the runtime keeps the resource alive for
// legacy redo, so a history-only resource the cursor dropped is expected. Drop those before comparing.
conversion.registry.resources.retain(|id, _| stored.resources.contains_key(id) || current_resources.contains(id));
if !stored.value_equal(&conversion.registry) {
log::error!(
"undo/redo shadow: cursor registry diverged from the restored interface\n{}",
diff_registries(stored, &conversion.registry)
);
}
}
fn push_capped(stack: &mut VecDeque<NodeNetworkInterface>, snapshot: NodeNetworkInterface) {
stack.push_back(snapshot);
if stack.len() > crate::consts::MAX_UNDO_HISTORY_LEN {
stack.pop_front();
}
}
}
@@ -217,9 +217,6 @@ pub enum DocumentMessage {
layers: Vec<NodeId>,
layers_missing_details: Vec<NodeId>,
},
CancelNodeWork {
node_id: NodeId,
},
SetNodePinned {
node_id: NodeId,
pinned: bool,
@@ -1,11 +1,10 @@
use super::document_diff::diff_networks;
use super::DocumentHistory;
use super::node_graph::{document_node_definitions, node_inspector};
use super::utility_types::error::EditorError;
use super::utility_types::layers_in_view::LayersInView;
use super::utility_types::misc::{ANGLE_STEP_MAX, ANGLE_STEP_MIN, GroupFolderType, SNAPPING_OPTION_GROUPS, SnappingState};
use super::utility_types::network_interface::{self, NodeNetworkInterface, TransactionStatus};
use super::utility_types::nodes::{CollapsedLayers, LayerStructureEntry, SelectedNodes};
use super::{CursorMoveError, DocumentHistory};
use crate::application::{Environment, GRAPHITE_GIT_COMMIT_HASH, generate_uuid};
use crate::consts::{
ASYMPTOTIC_EFFECT, BLEND_COUNT_PER_LAYER, COLOR_OVERLAY_GRAY, CURVATURE_COMB_DEFAULT_SCALE, CURVATURE_COMB_MAX_SCALE, CURVATURE_COMB_MIN_SCALE, DEFAULT_DOCUMENT_NAME, FILE_EXTENSION,
@@ -470,12 +469,17 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.chain_node_range_selection_reference = None;
}
DocumentMessage::DocumentHistoryBackward => {
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
self.undo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses)
self.stage_edits_outside_transaction(&resource_storage.resources_mut());
self.undo_with_history(document_id, responses);
self.resolve_unresolved_resources(document_id, responses);
}
DocumentMessage::DocumentHistoryForward => {
self.redo_with_history(document_id, responses);
self.resolve_unresolved_resources(document_id, responses);
}
DocumentMessage::DocumentHistoryForward => self.redo_with_history(document_id, viewport, preferences.validate_storage_round_trip, responses),
DocumentMessage::ChangeHistoryLine { rev, change } => {
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), preferences.validate_storage_round_trip, responses)
self.change_history_line(document_id, rev, change, &resource_storage.resources_mut(), responses);
self.resolve_unresolved_resources(document_id, responses);
}
DocumentMessage::DocumentStructureChanged => {
if layers_panel_open {
@@ -1256,16 +1260,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
DocumentMessage::SaveDocument | DocumentMessage::SaveDocumentAs => {
responses.add(PortfolioMessage::AutoSaveActiveDocument);
// Save as a `.gdd` container or a plain legacy `.graphite`, per the editor preference.
let save_as_gdd = preferences.save_as_gdd;
let include_history = preferences.save_with_history;
let extension = if save_as_gdd { GDD_FILE_EXTENSION } else { FILE_EXTENSION };
let name = format!("{}.{}", self.name.clone(), extension);
// Keep the path's extension in sync with the chosen format so bytes and filename agree.
// Saved as a `.gdd` container under the `.graphite` extension
let name = format!("{}.{FILE_EXTENSION}", self.name.clone());
// A document opened from a `.gdd` file is saved back under the `.graphite` extension
let path = match message {
DocumentMessage::SaveDocumentAs => None,
_ => self.path.clone().map(|path| path.with_extension(extension)),
_ => self.path.clone().map(|path| path.with_extension(FILE_EXTENSION)),
};
if path.is_some() || environment.is_web() {
responses.add(DocumentMessage::MarkAsSaved);
@@ -1279,20 +1282,19 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
let export_load_handle = resource_storage.resources();
responses.add(async move {
document.resources.collect_garbage(document.used_resources(false).as_ref());
document.resources.collect_garbage(document.used_resources().as_ref());
document.resources.embed_resources(resources_load_handle).await;
// Legacy .graphite blob with resources embedded inline, so it is self-contained and also
// serves as the .gdd recovery fallback.
let legacy_document = document.serialize_document().into_bytes();
// A .gdd exports the working copy with the legacy blob embedded, falling back to the bare
// Export the working copy with the legacy blob embedded, falling back to the bare
// blob when there is no working copy or the export fails.
let content = match (save_as_gdd, document.history.storage()) {
(false, _) => legacy_document,
(true, Some(storage)) => storage
let content = match document.history.storage() {
Some(storage) => storage
.export_to_bytes(
document_format::ExportFormat::Xz,
document_format::ExportFormat::Zip,
document_format::ExportOptions {
include_history,
..Default::default()
@@ -1305,7 +1307,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
log::error!("Save: building .gdd export failed, falling back to legacy .graphite: {error}");
legacy_document
}),
(true, None) => {
None => {
log::warn!("Save: working copy not mounted yet, saving legacy .graphite only");
legacy_document
}
@@ -1318,7 +1320,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
folder,
filters: vec![FileFilter {
name: "Graphite Document".into(),
extensions: vec![extension.into()],
extensions: vec![FILE_EXTENSION.into()],
mime_types: Vec::new(),
}],
content: content.into(),
@@ -1550,10 +1552,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
responses.add(NodeGraphMessage::SendLayerPanelDetails { layers: layers_missing_details });
}
}
DocumentMessage::CancelNodeWork { node_id } => {
let node_path = [self.selection_network_path.as_slice(), &[node_id]].concat();
responses.add(PortfolioMessage::CancelNodeWork { node_path });
}
DocumentMessage::SetNodePinned { node_id, pinned } => {
responses.add(DocumentMessage::AddTransaction);
responses.add(NodeGraphMessage::SetPinned { node_id, pinned });
@@ -1676,11 +1674,10 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
}
// Note: A transaction should never be started in a scope that mutates the network interface, since it will only be run after that scope ends.
DocumentMessage::StartTransaction => {
self.stage_edits_outside_transaction(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
self.stage_edits_outside_transaction(&resource_storage.resources_mut());
self.end_storage_interaction();
self.network_interface.start_transaction();
self.history.push_undo(self.network_interface.clone());
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
@@ -1696,7 +1693,6 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
},
DocumentMessage::CancelTransaction => {
self.network_interface.finish_transaction();
self.history.discard_last_undo();
}
DocumentMessage::CommitTransaction => {
if self.network_interface.transaction_status() == TransactionStatus::Finished {
@@ -1705,7 +1701,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
self.network_interface.finish_transaction();
self.history.clear_redo();
self.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
self.commit_storage_snapshot(&resource_storage.resources_mut());
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
}
@@ -1723,9 +1719,7 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
return;
}
for _ in 0..undo_count {
self.undo(viewport, responses);
}
self.abort_steps(document_id, undo_count, &resource_storage.resources_mut(), responses);
self.network_interface.finish_transaction();
responses.add(OverlaysMessage::Draw);
@@ -2471,7 +2465,7 @@ impl DocumentMessageHandler {
/// The batch boundary: everything the interface recorded since the last one is this commit's batch.
/// Draining happens whether or not a working copy is mounted, so the buffer cannot grow across a
/// session that never mounts one.
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
pub fn commit_storage_snapshot(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
self.network_interface.settle_definitions();
let deltas = self.network_interface.take_deltas();
if self.history.storage().is_none() {
@@ -2480,18 +2474,13 @@ impl DocumentMessageHandler {
let view_settings = self.storage_view_settings();
self.history.stage_snapshot(&deltas, &self.network_interface, &self.resources.registry, view_settings, byte_store);
// The interface lags the registry until peer changes are applied
if validate && self.pending_remote.is_empty() {
self.history.verify_round_trip(&self.network_interface, &self.resources.registry);
}
}
/// Stages edits made after a transaction finished, such as those queued behind an `AddTransaction`, whose commit runs
/// first. They belong to the undo step that just ended, so they must reach storage before it closes.
fn stage_edits_outside_transaction(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage, validate: bool) {
fn stage_edits_outside_transaction(&mut self, byte_store: &dyn graph_craft::application_io::resource::ResourceStorage) {
if self.network_interface.transaction_status() == TransactionStatus::Finished && self.network_interface.has_deltas() {
self.commit_storage_snapshot(byte_store, validate);
self.commit_storage_snapshot(byte_store);
}
}
@@ -2538,32 +2527,42 @@ impl DocumentMessageHandler {
}
}
/// Move the `Gdd` undo/redo cursor, swap in the interface rebuilt from it, and autosave so the legacy
/// document matches the cursor. `had_oracle` records whether the legacy snapshot already applied, so the
/// rebuild can be compared against it.
fn drive_storage_undo_redo(&mut self, document_id: DocumentId, had_oracle: bool, undo: bool, validate: bool, responses: &mut VecDeque<Message>) {
match self.history.move_cursor(undo) {
Ok(rebuilt) => {
self.apply_gdd_cursor_rebuild(rebuilt, had_oracle, validate, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
Err(CursorMoveError::NotMoved) => {}
// Without the legacy snapshot the interface stayed put, so the cursor has to follow it back.
Err(CursorMoveError::RebuildFailed) => {
if !had_oracle {
self.history.revert_cursor(undo);
}
}
}
}
/// Rebuild the resource registry from storage, or keep it on failure. `Resource` inputs resolve through it.
fn refresh_resource_registry(&mut self) {
let Some(storage) = self.history.storage() else { return };
match storage.registry().to_resource_registry() {
Ok(resource_registry) => self.resources.registry = resource_registry,
Err(error) => log::error!("Failed to rebuild the resource registry from storage: {error}"),
let mut resource_registry = match storage.registry().to_resource_registry() {
Ok(resource_registry) => resource_registry,
Err(error) => {
log::error!("Failed to rebuild the resource registry from storage: {error}");
return;
}
};
// Preserve completed resolutions across undo and redo
let stored_resources = &storage.registry().resources;
for resolved in self.resources.registry.resolved() {
let Some(&hash) = resolved.hash else { continue };
match resource_registry.info(&resolved.id) {
// Storage has its own hash, or a peer changed where the resource comes from
Some(stored) if stored.hash.is_some() || stored.sources != resolved.sources => continue,
Some(_) => {}
// Kept for a redo of the undone step that added it
None if !stored_resources.contains_key(&resolved.id) => resolved.sources.iter().for_each(|source| resource_registry.push_source_back(&resolved.id, source.clone())),
// Storage holds it with neither a hash nor sources
None => continue,
}
resource_registry.resolve(&resolved.id, hash);
}
self.resources.registry = resource_registry;
}
/// Queues resolving the resources that history left without a hash, as applying a peer's changes does.
fn resolve_unresolved_resources(&self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
if self.resources.registry.unresolved().next().is_some() {
responses.add(PortfolioMessage::ResolveDocumentResources { document_id });
}
}
@@ -2605,7 +2604,7 @@ impl DocumentMessageHandler {
match self.history.rebuild_interface() {
Some(rebuilt) => {
self.apply_gdd_cursor_rebuild(rebuilt, false, false, responses);
self.apply_gdd_cursor_rebuild(rebuilt, responses);
true
}
None => {
@@ -2648,15 +2647,11 @@ impl DocumentMessageHandler {
}
/// Swap in the interface rebuilt from the `Gdd` cursor. Always overwrites the interface.
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, had_oracle: bool, validate: bool, responses: &mut VecDeque<Message>) {
fn apply_gdd_cursor_rebuild(&mut self, mut rebuilt: NodeNetworkInterface, responses: &mut VecDeque<Message>) {
rebuilt.copy_all_transient_view_state(&self.network_interface);
std::mem::swap(&mut rebuilt.resolved_types, &mut self.network_interface.resolved_types);
rebuilt.load_structure();
if validate && had_oracle {
self.compare_rebuild_against_legacy(&rebuilt);
}
self.network_interface = rebuilt;
self.pending_remote = Default::default();
if let Some(gdd) = self.history.storage_mut() {
@@ -2664,11 +2659,6 @@ impl DocumentMessageHandler {
}
self.refresh_resource_registry();
if validate {
let current_resources: std::collections::HashSet<_> = self.used_resources(false).iter().copied().collect();
self.history.verify_cursor_matches_runtime(&self.network_interface, &self.resources.registry, &current_resources);
}
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
@@ -2676,17 +2666,6 @@ impl DocumentMessageHandler {
responses.add(NodeGraphMessage::SendWires);
}
/// Check if the rebuilt network equals the legacy-restored one. Logs drift (panics in tests).
fn compare_rebuild_against_legacy(&self, rebuilt: &NodeNetworkInterface) {
let legacy = self.network_interface.document_network();
let candidate = rebuilt.document_network();
if candidate != legacy {
log::error!("undo/redo rebuild diverged from the legacy snapshot\n{}", diff_networks(legacy, candidate));
#[cfg(test)]
panic!("undo/redo rebuild diverged from the legacy snapshot")
}
}
pub fn serialize_document(&self) -> String {
let val = serde_json::to_string(self);
// We fully expect the serialization to succeed
@@ -2983,46 +2962,67 @@ impl DocumentMessageHandler {
paths
}
pub fn undo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
// The storage path skips `undo`, which settles a glide before the snapshot moves
pub fn undo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
// Settled before storage moves, so the glide's offsets don't outlive the step
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
// The legacy snapshot predates peers' writes, so follow only what storage changed
let stored_name = self.stored_name().map(str::to_string);
if self.history.undo_in_storage(self.is_in_session()) {
if self.history.undo(self.is_in_session()) {
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
return;
}
// A session's history is shared, so no legacy snapshot may be installed
if self.is_in_session() {
return;
}
let legacy_applied = if let Some(previous_network) = self.undo(viewport, responses) {
self.history.push_redo(previous_network);
self.history.note_cursor_undo();
true
} else {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, true, validate, responses);
}
/// Makes a History panel change in storage and drops the legacy snapshots, which are off the head's line.
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, validate: bool, responses: &mut VecDeque<Message>) {
pub fn redo_with_history(&mut self, document_id: DocumentId, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let stored_name = self.stored_name().map(str::to_string);
if self.history.redo() {
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
}
/// Takes back the open transaction along with the `undo_count - 1` steps before it, leaving nothing to redo.
fn abort_steps(&mut self, document_id: DocumentId, undo_count: usize, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let open_transaction_has_edits = self.network_interface.transaction_status() == TransactionStatus::Modified;
if open_transaction_has_edits {
// Staged so they are taken back with the steps before them
self.commit_storage_snapshot(byte_store);
}
let steps = if open_transaction_has_edits { undo_count } else { undo_count.saturating_sub(1) };
let stored_name = self.stored_name().map(str::to_string);
let in_session = self.is_in_session();
let discarded = (0..steps).take_while(|_| self.history.discard_step(in_session)).count();
if discarded == 0 {
return;
}
// Staging the open transaction's edits made storage's own redo unreachable
if open_transaction_has_edits {
self.history.clear_redo();
}
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
}
/// Makes a History panel change in storage and drops the steps redo could bring back, which are off the head's line.
fn change_history_line(&mut self, document_id: DocumentId, rev: Rev, change: LineChange, byte_store: &dyn ResourceStorage, responses: &mut VecDeque<Message>) {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
}
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
responses.add(EventMessage::ToolAbort);
self.stage_edits_outside_transaction(byte_store, validate);
self.stage_edits_outside_transaction(byte_store);
self.history.retire_storage_interaction();
let stored_name = self.stored_name().map(str::to_string);
if !self.history.change_line(rev, change) {
return;
}
self.history.clear_legacy();
self.history.clear_redo();
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
responses.add(OverlaysMessage::Draw);
@@ -3045,78 +3045,6 @@ impl DocumentMessageHandler {
self.storage().is_some_and(|gdd| gdd.role().is_some())
}
/// Installs a history snapshot as the active network interface, carrying over the current view state and structure load, and returns the replaced interface.
fn install_history_snapshot(&mut self, mut network_interface: NodeNetworkInterface, viewport: &ViewportMessageHandler) -> NodeNetworkInterface {
// Set the previous network navigation metadata to the current navigation metadata
network_interface.copy_all_navigation_metadata(&self.network_interface);
std::mem::swap(&mut network_interface.resolved_types, &mut self.network_interface.resolved_types);
// Update the metadata transform based on document PTZ
let transform = self.navigation_handler.calculate_offset_transform(viewport.center_in_viewport_space().into(), &self.document_ptz);
network_interface.set_document_to_viewport_transform(transform);
// Ensure document structure is loaded so that updating the selected nodes has the correct metadata
network_interface.load_structure();
std::mem::replace(&mut self.network_interface, network_interface)
}
pub fn undo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
// If there is no history return and don't broadcast SelectionChanged
let network_interface = self.history.pop_undo()?;
// Settled first, so the interface stored for redo keeps none of the offsets of a glide underway
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let previous_network = self.install_history_snapshot(network_interface, viewport);
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
// TODO: Remove once the footprint is used to load the imports/export distances from the edge
responses.add(NodeGraphMessage::UnloadWires);
Some(previous_network)
}
pub fn redo_with_history(&mut self, document_id: DocumentId, viewport: &ViewportMessageHandler, validate: bool, responses: &mut VecDeque<Message>) {
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let stored_name = self.stored_name().map(str::to_string);
if self.history.redo_in_storage() {
self.follow_storage_changes(stored_name, responses);
responses.add(PortfolioMessage::AutoSaveDocument { document_id });
return;
}
if self.is_in_session() {
return;
}
let legacy_applied = if let Some(previous_network) = self.redo(viewport, responses) {
self.history.push_undo(previous_network);
self.history.forget_undo_note();
true
} else {
false
};
self.drive_storage_undo_redo(document_id, legacy_applied, false, validate, responses);
}
pub fn redo(&mut self, viewport: &ViewportMessageHandler, responses: &mut VecDeque<Message>) -> Option<NodeNetworkInterface> {
// If there is no history return and don't broadcast SelectionChanged
let network_interface = self.history.pop_redo()?;
// Settled first, as when undoing
self.node_graph_handler.stop_gliding(&self.network_interface, responses);
let previous_network = self.install_history_snapshot(network_interface, viewport);
// Push the UpdateOpenDocumentsList message to the bus in order to update the save status of the open documents
responses.add(PortfolioMessage::UpdateOpenDocumentsList);
responses.add(NodeGraphMessage::SelectedNodesUpdated);
responses.add(NodeGraphMessage::ForceRunDocumentGraph);
responses.add(NodeGraphMessage::UnloadWires);
responses.add(NodeGraphMessage::SendWires);
Some(previous_network)
}
pub fn current_hash(&self) -> u64 {
self.network_interface.document_network().current_hash()
}
@@ -4327,7 +4255,7 @@ impl DocumentMessageHandler {
}
pub fn garbage_collect_resources(&mut self) {
let used_resources = self.used_resources(true);
let used_resources = self.used_resources();
self.resources.collect_garbage(&used_resources);
}
@@ -4335,12 +4263,10 @@ impl DocumentMessageHandler {
self.history.resource_gc_roots()
}
pub fn used_resources(&self, include_history: bool) -> Box<[ResourceId]> {
/// The resources the current network references.
pub fn used_resources(&self) -> Box<[ResourceId]> {
let mut resources = HashSet::new();
self.network_interface.collect_used_resources(&mut resources);
if include_history {
self.history.collect_used_resources(&mut resources);
}
resources.into_iter().collect::<Vec<_>>().into_boxed_slice()
}
}
@@ -1,3 +1,4 @@
#[cfg(test)]
pub(crate) mod document_diff;
mod document_history;
mod document_message;
@@ -14,8 +15,7 @@ pub mod overlays;
pub mod resource;
pub mod utility_types;
pub(crate) use document_diff::diff_networks;
pub(crate) use document_history::{CursorMoveError, DocumentHistory};
pub(crate) use document_history::DocumentHistory;
#[doc(inline)]
pub use document_message::{DocumentMessage, DocumentMessageDiscriminant};
#[doc(inline)]
@@ -1448,6 +1448,13 @@ fn static_input_inspector() -> InputInspector {
Ok(vec![choices])
}),
);
map.insert(
"vec2_uv".to_string(),
Box::new(|node_id, index, context| {
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false)])
}),
);
map
}
@@ -345,10 +345,6 @@ pub enum NodeGraphMessage {
UpdateEvaluationErrors {
errors: Vec<NodeEvaluationError>,
},
/// The progress of the nodes with work in progress, by their full path from the root network.
UpdateNodeProgress {
progress: Vec<(Vec<NodeId>, f64)>,
},
UpdateActionButtons,
UpdateGraphBarRight,
UpdateInSelectedNetwork,
@@ -6,7 +6,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, FrontendNodeProgress, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
@@ -136,8 +136,6 @@ pub struct NodeGraphMessageHandler {
/// Used to keep track of what wires are sent to the frontend so the old ones can be removed
frontend_wires: HashSet<(NodeId, usize)>,
evaluation_errors: Vec<NodeEvaluationError>,
/// The progress of the nodes with work in progress, by their full path from the root network.
node_progress: Vec<(Vec<NodeId>, f64)>,
}
/// NodeGraphMessageHandler always modifies the network which the selected nodes are in. No GraphOperationMessages should be added here, since those messages will always affect the document network.
@@ -2060,8 +2058,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
let errors = self.node_graph_errors(network_interface, breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphErrorDiagnostics { errors });
let progress = self.node_graph_progress(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
let (layer_widths, chain_widths, has_left_input_wire) = network_interface.collect_layer_widths(breadcrumb_network_path);
responses.add(NodeGraphMessage::UpdateImportsExports);
@@ -2668,15 +2664,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
}
}
}
NodeGraphMessage::UpdateNodeProgress { progress } => {
if self.node_progress != progress {
self.node_progress = progress;
if breadcrumb_network_path == selection_network_path && graph_view_overlay_open {
let progress = self.node_graph_progress(breadcrumb_network_path);
responses.add(FrontendMessage::UpdateNodeGraphProgress { progress });
}
}
}
NodeGraphMessage::UpdateActionButtons => {
if selection_network_path == breadcrumb_network_path {
self.update_graph_bar_left(network_interface, breadcrumb_network_path, responses);
@@ -3884,22 +3871,6 @@ impl NodeGraphMessageHandler {
.collect()
}
/// The progress of the nodes in the network at `breadcrumb_network_path`, where a node shows the first work in progress within it.
fn node_graph_progress(&self, breadcrumb_network_path: &[NodeId]) -> Vec<FrontendNodeProgress> {
let depth = breadcrumb_network_path.len();
let mut shown = HashSet::new();
self.node_progress
.iter()
.filter(|(path, _)| path.starts_with(breadcrumb_network_path) && path.len() > depth)
.filter(|(path, _)| shown.insert(path[depth]))
.map(|(path, progress)| FrontendNodeProgress {
node_id: path[depth],
progress: *progress,
})
.collect()
}
/// Sends the Layers panel the details of the given layers, which it needs only for the rows it has in view.
// O(given layers × nesting depth), apart from what the active tool would edit in the selected layers
fn update_layer_panel(
@@ -4109,7 +4080,6 @@ impl Default for NodeGraphMessageHandler {
frontend_nodes: Vec::new(),
frontend_wires: HashSet::new(),
evaluation_errors: Vec::new(),
node_progress: Vec::new(),
}
}
}
@@ -3284,7 +3284,6 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
let mut section = LayoutGroup::section(name, icon, description, visible, pinned, expanded, node_id.0, Layout(layout));
if let LayoutGroup::NodeSection(node_section) = &mut section {
node_section.chain_wire = chain_wire;
node_section.progress = context.executor.node_progress(&[network_path, &[node_id]].concat());
}
section
}
@@ -202,15 +202,6 @@ pub struct NodeGraphErrorDiagnostic {
pub error: String,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct FrontendNodeProgress {
#[serde(rename = "nodeId")]
pub node_id: NodeId,
/// How much of the work within the node is done, from 0 to 1.
pub progress: f64,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct NodeEvaluationError {
pub node_path: Vec<NodeId>,
@@ -0,0 +1,19 @@
use crate::test_utils::test_prelude::*;
const TEMPLATE_DIRECTORY: &str = "../node-graph/compiler-spike/workloads/templates";
/// Draws three rectangle layers with the Rectangle tool and saves the document as the compiler spike's layer template.
/// Run with `cargo test -p graphite-editor export_compiler_spike_templates -- --ignored`, then rerun the spike's workload export.
#[tokio::test]
#[ignore]
async fn export_compiler_spike_templates() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
for i in 0..3 {
let offset = i as f64 * 20.;
editor.draw_rect(offset, offset, offset + 10., offset + 10.).await;
}
std::fs::create_dir_all(TEMPLATE_DIRECTORY).unwrap();
std::fs::write(format!("{TEMPLATE_DIRECTORY}/rectangle-layers.graphite"), editor.active_document().serialize_document()).unwrap();
}
@@ -4,6 +4,7 @@ use crate::messages::frontend::utility_types::PersistedState;
use crate::messages::portfolio::document_storage_io::document_key;
use crate::messages::prelude::*;
use crate::test_utils::EditorTestUtils;
use document_container::archive::ArchiveFormat;
use document_container::{AnyContainer, AsyncContainer};
fn dispatch(editor: &mut EditorTestUtils, message: impl Into<Message>) -> Vec<FrontendMessage> {
@@ -118,20 +119,22 @@ async fn legacy_only_container_gets_storage() {
}
#[tokio::test]
async fn legacy_save_format_still_keeps_a_working_copy() {
async fn saving_writes_a_zip_archive_with_the_graphite_extension() {
let mut editor = EditorTestUtils::create();
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled: false });
let id = new_document(&mut editor, "Legacy");
let id = new_document(&mut editor, "Saved");
let container = container(&editor, id).await;
assert!(editor.active_document().storage().is_some(), "every document gets a working copy, whatever the save format");
assert!(container.exists("manifest.json").await);
let saved = dispatch(&mut editor, DocumentMessage::SaveDocumentAs);
let name = saved.iter().find_map(|message| match message {
FrontendMessage::TriggerSaveDocument { name, .. } => Some(name.clone()),
_ => None,
});
assert_eq!(name.as_deref(), Some("Legacy.graphite"));
let (name, content) = saved
.iter()
.find_map(|message| match message {
FrontendMessage::TriggerSaveDocument { name, content, .. } => Some((name.clone(), content.clone())),
_ => None,
})
.expect("the save is sent to the frontend");
assert_eq!(name, "Saved.graphite");
assert_eq!(ArchiveFormat::detect(&content), Some(ArchiveFormat::Zip));
}
#[tokio::test]
@@ -202,20 +205,6 @@ async fn closing_removes_the_stored_document() {
assert!(portfolio(&editor).persisted_state_snapshot().documents.is_empty());
}
#[tokio::test]
async fn storage_preference_keeps_the_working_copy() {
let mut editor = EditorTestUtils::create();
let id = new_document(&mut editor, "Toggle");
let container = container(&editor, id).await;
assert!(editor.active_document().storage().is_some());
assert!(container.exists("legacy.graphite").await);
for enabled in [false, true] {
dispatch(&mut editor, PreferencesMessage::SaveAsGdd { enabled });
assert!(editor.active_document().storage().is_some(), "the preference only picks the save format");
}
}
#[tokio::test]
async fn unreadable_document_is_reported_and_kept_until_discarded() {
let mut editor = EditorTestUtils::create();
@@ -4,6 +4,7 @@
//!
//! Shared fixtures live in [`test_support`].
mod compiler_spike_templates;
mod lifecycle_tests;
mod metadata_tests;
mod round_trip_tests;
@@ -1,15 +1,14 @@
//! End-to-end storage round-trip tests: drive real edits through the editor, push the document
//! through a fresh in-memory `Gdd` (stage → retire → persist), reopen from the same container, and
//! assert the reopened document matches. Exercises the full persistence pipeline (conversion,
//! postcard codecs, hot-op retirement, file layout, replay-on-open) that the debug-only
//! `verify_storage_round_trip` only checks in-process without an actual save/reopen.
//! postcard codecs, hot-op retirement, file layout, replay-on-open).
use crate::messages::resource_storage::ResourcesHandle;
use document_container::AnyContainer;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use document_graph_storage::{NodeMetadataSource, PeerId, UserId, to_value};
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::application_io::resource::{DataSource, HashMapResourceStorage, ResourceHash, ResourceId};
use std::sync::Arc;
use super::test_support::{RoundTrip, node_locations, node_paths, round_trip_through_gdd};
@@ -185,7 +184,7 @@ async fn edit_after_open_commits_cleanly() {
// Mirror the live sequence via the real `commit_storage_snapshot`: initial commit after open, then a
// deletion, then commit again. Deletion (not addition) is the trigger, since it emits a `RemoveNode`
// whose retire/reverse is where "Target node does not exist" surfaced live.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let layer = editor.active_document().metadata().all_layers().next().expect("at least one layer");
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
@@ -334,7 +333,7 @@ async fn live_undo_shadows_storage_cursor() {
let byte_store = mount_in_memory_storage(&mut editor);
// Capture the loaded state as the base interaction, then make a real edit (fires CommitTransaction).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_ellipse(50., 50., 150., 150.).await;
let after_edit = editor.active_document().network_interface.document_network().clone();
@@ -475,7 +474,7 @@ async fn live_undo_new_document_draw_rect() {
let byte_store = mount_in_memory_storage(&mut editor);
// Mount-time snapshot: capture the new-document graph as the base interaction.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let before_rect = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
@@ -562,7 +561,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.handle_message(paste_named_image()).await;
@@ -573,7 +572,7 @@ async fn undo_image_paste_resources_subset_of_runtime() {
let stored: std::collections::BTreeSet<_> = storage.registry().resources.keys().copied().collect();
// Every resource the restored network still references must be in the cursor.
let current: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
let current: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
assert!(
current.is_subset(&stored),
"cursor is missing a resource the restored network references: current={current:?} stored={stored:?}"
@@ -594,7 +593,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let base = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(0., 0., 100., 100.).await;
@@ -615,7 +614,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
// cached for redo though its node is gone, so a naive snapshot would re-detect it as a new `AddResource`
// and retire a phantom interaction, knocking the cursor out of lockstep. Scoping the snapshot to
// network-referenced resources must keep this a no-op.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
// Second undo: removes the rectangle, back to the loaded base. The cursor must step a second interaction
// and land on the base, not one short.
@@ -634,7 +633,7 @@ async fn undo_twice_steps_cursor_two_interactions() {
}
/// Assert the `Gdd` cursor's stored registry matches a fresh `from_runtime` of the current interface (node
/// set, network set, per-network export wiring), mirroring the live `verify_cursor_matches_runtime` check.
/// set, network set, per-network export wiring).
/// The runtime's resource set may be a superset (it keeps undone resources alive for redo), but every
/// resource the current network references must be present.
fn assert_cursor_matches_runtime(document: &DocumentMessageHandler, at: &str) {
@@ -670,15 +669,15 @@ async fn pasted_image_resource_survives_inserting_a_node() {
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.handle_message(paste_named_image()).await;
editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER)).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let document = editor.active_document();
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
}
@@ -689,14 +688,117 @@ async fn pasted_image_resource_survives_storage_mounting_after_the_paste() {
editor.handle_message(paste_named_image()).await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let document = editor.active_document();
let stored: std::collections::BTreeSet<_> = document.storage().expect("storage mounted").registry().resources.keys().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources(false).iter().copied().collect();
let used: std::collections::BTreeSet<_> = document.used_resources().iter().copied().collect();
assert!(used.is_subset(&stored), "storage lost a resource the network references: used={used:?} stored={stored:?}");
}
/// Pastes an image and points it at a resource from `source` that is staged before it resolves, then resolves it, giving the resource and its hash.
async fn image_resource_resolved_after_staging(editor: &mut EditorTestUtils, source: DataSource) -> (ResourceId, ResourceHash) {
use graph_craft::document::DocumentNodeImplementation;
use graph_craft::document::value::TaggedValue;
use graphene_std::raster_nodes::std_nodes::image;
editor.new_document().await;
let byte_store = mount_in_memory_storage(editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.handle_message(paste_named_image()).await;
// Point the image at a resource that is still being fetched, so its entry is staged without a hash
let image_node_id = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == image::IDENTIFIER))
.map(|(id, _)| *id)
.expect("the pasted image should be an Image node");
let resource_id = ResourceId::new();
editor.active_document_mut().resources.registry.push_source_back(&resource_id, source.clone());
editor.dispatch(DocumentMessage::StartTransaction);
editor.dispatch(NodeGraphMessage::SetInputValue {
node_id: image_node_id,
input_index: image::ResourceInput::INDEX,
value: TaggedValue::Resource(resource_id).into(),
});
editor.dispatch(DocumentMessage::CommitTransaction);
let stored = editor
.active_document()
.storage()
.expect("storage mounted")
.registry()
.resources
.get(&resource_id)
.map(|entry| entry.hash);
assert_eq!(stored, Some(None), "storage should hold the resource without its hash");
// The fetch finishes, which caches a font's hash for a later resolve
let data: Arc<[u8]> = Image::new(2, 2, Color::BLACK).to_png().into();
let hash = ResourceHash::from(data.as_ref());
let document_id = editor.portfolio_message_handler().active_document_id.expect("a document is open");
editor.dispatch(ResourceStorageMessage::Store { data });
editor.dispatch(PortfolioMessage::DocumentPassMessage {
document_id,
message: ResourceMessage::Resolved { resource_id, source, hash }.into(),
});
(resource_id, hash)
}
/// Undo and redo keep the hash of a resource resolved after its entry was staged.
#[tokio::test]
async fn resource_resolved_after_staging_stays_resolved_through_undo_and_redo() {
let mut editor = EditorTestUtils::create();
// An embedded source can't be fetched again, so only the runtime's resolution keeps it resolved
let (resource_id, hash) = image_resource_resolved_after_staging(&mut editor, DataSource::Embedded).await;
editor.draw_rect(0., 0., 100., 100.).await;
// Undo and redo the rectangle, then the step that set the resource
for (message, step) in [
(DocumentMessage::Undo, "undoing the rectangle"),
(DocumentMessage::Redo, "redoing the rectangle"),
(DocumentMessage::Undo, "undoing the rectangle again"),
(DocumentMessage::Undo, "undoing the resource change"),
(DocumentMessage::Redo, "redoing the resource change"),
] {
editor.dispatch(message);
let document = editor.active_document();
let registry = &document.resources.registry;
assert!(registry.unresolved().next().is_none(), "{step} left a resource unresolved, which stops rendering");
assert!(document.used_resources().iter().all(|id| registry.hash(id).is_some()), "{step} left a used resource without its hash");
}
assert_eq!(editor.active_document().resources.registry.hash(&resource_id), Some(hash));
}
/// A resource that history leaves without its hash is resolved again.
#[tokio::test]
async fn resource_left_unresolved_by_history_is_resolved_again() {
let mut editor = EditorTestUtils::create();
// A font resolves again from its cached hash, without a download
let font = DataSource::Font {
family: "Test Family".into(),
style: Some("Regular (400)".into()),
};
let (resource_id, hash) = image_resource_resolved_after_staging(&mut editor, font).await;
// No snapshot uses the resource once its step is undone, so collection drops the runtime's resolution
editor.dispatch(DocumentMessage::Undo);
editor.active_document_mut().garbage_collect_resources();
assert!(
editor.active_document().resources.registry.info(&resource_id).is_none(),
"garbage collection should drop the undone step's resource"
);
editor.dispatch(DocumentMessage::Redo);
let registry = &editor.active_document().resources.registry;
assert_eq!(registry.hash(&resource_id), Some(hash), "redoing the step should resolve its resource again");
assert!(registry.unresolved().next().is_none(), "redoing the step left a resource unresolved, which stops rendering");
}
/// Mount a fresh in-memory `Gdd` onto the active document so `commit_storage_snapshot` (the real
/// autosave path) runs against it. Returns the byte store the document's resources resolve through.
fn mount_in_memory_storage(editor: &mut EditorTestUtils) -> ResourcesHandle {
@@ -728,7 +830,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
let byte_store = mount_in_memory_storage(&mut editor);
// First autosave: captures the loaded document. `verify_storage_round_trip` panics on drift.
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let history_after_open = editor.active_document().storage().unwrap().session().history().count();
// Snapshot the network, then make a real modification.
@@ -737,7 +839,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(before_edit, after_edit, "drawing a rectangle should change the document network");
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.active_document_mut().retire_storage_interaction();
let history_after_edit = editor.active_document().storage().unwrap().session().history().count();
assert!(
@@ -751,7 +853,7 @@ async fn demo_artwork_edit_autosaves_and_round_trips() {
assert_eq!(after_undo, before_edit, "undo should restore the pre-edit network");
// Autosaving the undone state still round-trips cleanly (no drift panic).
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
}
/// Manual edits ride a saved document as a folded `VectorModification`, so opening the artworks carrying the most
@@ -978,13 +1080,13 @@ async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
editor.active_document_mut().retire_storage_interaction();
let history_base = editor.active_document().storage().unwrap().session().history().count();
let before_edit = editor.active_document().network_interface.document_network().clone();
editor.draw_rect(64., 64., 192., 192.).await;
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
let after_edit = editor.active_document().network_interface.document_network().clone();
assert_ne!(after_edit, before_edit);
assert!(!editor.active_document().storage().unwrap().session().hot_log().is_empty(), "the step is hot");
@@ -994,7 +1096,7 @@ async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
let storage = editor.active_document().storage().unwrap();
assert!(storage.session().hot_log().is_empty(), "the step was taken back, not retired: {:?}", storage.session().hot_log());
assert_eq!(storage.session().history().count(), history_base, "nothing entered history");
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
// The step held for redo keeps its declaration bytes from collection
let storage = editor.active_document().storage().unwrap();
assert!(
@@ -1007,5 +1109,46 @@ async fn undoing_a_hot_step_takes_it_back_and_redo_stages_it_again() {
let storage = editor.active_document().storage().unwrap();
assert!(!storage.session().hot_log().is_empty(), "the redone step is staged afresh");
assert_eq!(storage.session().history().count(), history_base);
editor.active_document_mut().commit_storage_snapshot(&byte_store, true);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
}
/// Draws three ellipses, undoes all of them, redoes them and one more, then undoes once. `retire` retires each
/// drawing first, so the steps undo through the cursor rather than by retraction.
async fn redone_steps_undo_one_at_a_time(retire: bool) {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let byte_store = mount_in_memory_storage(&mut editor);
editor.active_document_mut().commit_storage_snapshot(&byte_store);
for offset in [0., 200., 400.] {
editor.draw_ellipse(offset, 0., offset + 100., 100.).await;
if retire {
editor.active_document_mut().retire_storage_interaction();
}
}
let layer_count = |editor: &EditorTestUtils| editor.active_document().metadata().all_layers().count();
assert_eq!(layer_count(&editor), 3);
for expected in [2, 1, 0] {
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(layer_count(&editor), expected, "undoing down to {expected} ellipses");
}
for expected in [1, 2, 3, 3] {
editor.handle_message(DocumentMessage::Redo).await;
assert_eq!(layer_count(&editor), expected, "redoing up to {expected} ellipses");
}
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(layer_count(&editor), 2, "undo takes back only the last redone ellipse");
assert_cursor_matches_runtime(editor.active_document(), "after undoing a redone step");
}
#[tokio::test]
async fn redone_hot_steps_undo_one_at_a_time() {
redone_steps_undo_one_at_a_time(false).await;
}
#[tokio::test]
async fn redone_retired_steps_undo_one_at_a_time() {
redone_steps_undo_one_at_a_time(true).await;
}
@@ -43,9 +43,6 @@ fn new_artboard_message(id: NodeId) -> GraphOperationMessage {
async fn invariants_hold_through_basic_editing_flow() {
let mut editor = EditorTestUtils::create();
// This test covers the interface's structural invariants. The storage dual-write is out of its scope and asserted by the storage round-trip tests.
editor.editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false });
editor.new_document().await;
assert_invariants(&editor, "after opening a new document");
@@ -1179,8 +1176,6 @@ fn fed_inputs(editor: &EditorTestUtils, output_connector: &OutputConnector, netw
async fn dragging_a_dot_out_of_an_import_takes_over_the_wires_the_import_fed() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
// TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it
editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await;
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
let path = vec![merge];
@@ -2997,9 +2992,6 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
// TODO: Remove once staging the recorded edits stores a node wired to an import inside a subgraph as it is, instead of drifting from it
editor.handle_message(PreferencesMessage::ValidateStorageRoundTrip { enabled: false }).await;
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
editor.handle_message(NodeGraphMessage::AddImport).await;
@@ -40,10 +40,6 @@ pub enum PortfolioMessage {
AutoSaveDocument {
document_id: DocumentId,
},
/// Cancels the work in progress of the active document's node at this full path from the root network.
CancelNodeWork {
node_path: Vec<graphene_std::uuid::NodeId>,
},
CloseActiveDocumentWithConfirmation,
CloseAllDocuments,
CloseAllDocumentsWithConfirmation,
@@ -269,7 +269,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
match container.write_non_blocking(legacy_path(), document.serialize_document().as_bytes()) {
Ok(()) => {
document.commit_storage_snapshot(&resource_storage.resources_mut(), preferences.validate_storage_round_trip);
document.commit_storage_snapshot(&resource_storage.resources_mut());
document.set_auto_save_state(true);
}
Err(error) => {
@@ -283,9 +283,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
}
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::CancelNodeWork { node_path } => {
self.executor.cancel_node_work(node_path);
}
PortfolioMessage::CloseActiveDocumentWithConfirmation => {
if let Some(document_id) = self.active_document_id {
responses.add(PortfolioMessage::CloseDocumentWithConfirmation { document_id });
@@ -1347,7 +1344,7 @@ impl PortfolioMessageHandler {
let resources = resource_storage.resources_mut();
document.set_storage(*gdd, declarations, resources.storage());
document.require_whole_document_stage();
document.commit_storage_snapshot(&resources, preferences.validate_storage_round_trip);
document.commit_storage_snapshot(&resources);
document.retire_storage_interaction();
}
None => {
@@ -13,7 +13,7 @@ pub enum SyncMessage {
Leave,
/// Host the active document as a new session with its own link. The others stay in the old room.
Fork,
/// Send the Session panel's layout.
/// Send the Collaboration panel's layout.
RefreshPanel,
/// Apply what peers sent, once per frame.
Poll,
@@ -171,10 +171,10 @@ impl MessageHandler<SyncMessage, SyncMessageContext<'_>> for SyncMessageHandler
refresh_session_views(responses);
}
SyncMessage::RefreshPanel => {
let layout = session_panel_layout(documents, active_document_id, preferences);
let layout = collaboration_panel_layout(documents, active_document_id, preferences);
responses.add(LayoutMessage::SendLayout {
layout,
layout_target: LayoutTarget::SessionPanel,
layout_target: LayoutTarget::CollaborationPanel,
});
}
SyncMessage::Poll => {
@@ -226,7 +226,7 @@ impl SyncMessageHandler {
fn host(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) {
let Some(token) = self.connect_document(document_id, gdd, preferences, responses) else { return };
responses.add(FrontendMessage::TriggerSessionLinkCopy { token: token.to_string() });
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Session });
responses.add(WorkspaceMessage::FocusPanel { panel_type: PanelType::Collaboration });
}
fn connect_document(&mut self, document_id: DocumentId, gdd: &mut GddV1, preferences: &PreferencesMessageHandler, responses: &mut VecDeque<Message>) -> Option<SessionToken> {
@@ -534,7 +534,7 @@ fn refresh_session_views(responses: &mut VecDeque<Message>) {
responses.add(SyncMessage::RefreshPanel);
}
fn session_panel_layout(documents: &HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, preferences: &PreferencesMessageHandler) -> Layout {
fn collaboration_panel_layout(documents: &HashMap<DocumentId, DocumentMessageHandler>, active_document_id: Option<DocumentId>, preferences: &PreferencesMessageHandler) -> Layout {
let heading = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).bold(true).widget_instance()]);
let note = |text: &str| LayoutGroup::row(vec![TextLabel::new(text).multiline(true).widget_instance()]);
let user_name = preferences.user_name.as_str();
@@ -12,7 +12,7 @@ pub enum PanelType {
#[serde(alias = "Properties")]
Inspector,
Data,
Session,
Collaboration,
History,
}
@@ -24,7 +24,7 @@ impl From<String> for PanelType {
"Layers" => PanelType::Layers,
"Inspector" | "Properties" => PanelType::Inspector,
"Data" => PanelType::Data,
"Session" => PanelType::Session,
"Collaboration" => PanelType::Collaboration,
"History" => PanelType::History,
_ => panic!("Unknown panel type: {value}"),
}
@@ -33,7 +33,7 @@ impl From<String> for PanelType {
impl PanelType {
pub fn non_document_panels() -> &'static [PanelType] {
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Session, PanelType::History]
&[PanelType::Layers, PanelType::Inspector, PanelType::Data, PanelType::Collaboration, PanelType::History]
}
}
@@ -305,10 +305,10 @@ impl WorkspacePanelLayout {
/// - Data: below the document in the left column (root child 0)
/// - Inspector: top of the right column (root child 1)
/// - Layers: bottom of the right column (root child 1)
/// - Session, History: a tab beside the Inspector or Layers, otherwise placed like that panel
/// - Collaboration, History: a tab beside the Inspector or Layers, otherwise placed like that panel
fn restore_panel_to_default_position(&mut self, panel_type: PanelType) {
let beside = match panel_type {
PanelType::Session => Some(PanelType::Inspector),
PanelType::Collaboration => Some(PanelType::Inspector),
PanelType::History => Some(PanelType::Layers),
_ => None,
};
@@ -334,9 +334,9 @@ impl WorkspacePanelLayout {
// Determine which root child column to insert into and at which position
let (root_child_index, insert_at_end) = match panel_type {
PanelType::Data => (0, true), // Left column, after document
PanelType::Inspector | PanelType::Session => (1, false), // Right column, at top
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
PanelType::Data => (0, true), // Left column, after document
PanelType::Inspector | PanelType::Collaboration => (1, false), // Right column, at top
PanelType::Layers | PanelType::History => (1, true), // Right column, at bottom
_ => (1, true),
};
@@ -421,7 +421,7 @@ impl Default for WorkspacePanelLayout {
subdivision: PanelLayoutSubdivision::PanelGroup {
id: PanelGroupId(1),
state: PanelGroupState {
tabs: vec![PanelType::Inspector, PanelType::Session],
tabs: vec![PanelType::Inspector],
active_tab_index: 0,
},
},
@@ -34,7 +34,7 @@ pub enum WorkspaceMessage {
panel_type: PanelType,
},
ToggleDataPanelOpen,
ToggleSessionPanelOpen,
ToggleCollaborationPanelOpen,
ToggleHistoryPanelOpen,
ToggleInspectorOpen,
ToggleLayersPanelOpen,
@@ -288,12 +288,12 @@ impl MessageHandler<WorkspaceMessage, WorkspaceMessageContext> for WorkspaceMess
let panel_type = PanelType::Data;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::ToggleSessionPanelOpen => {
WorkspaceMessage::ToggleCollaborationPanelOpen => {
if self.panel_layout.focus_document {
return;
}
let panel_type = PanelType::Session;
let panel_type = PanelType::Collaboration;
self.toggle_dockable_panel(panel_type, has_active_document, has_no_documents, responses);
}
WorkspaceMessage::ToggleHistoryPanelOpen => {
@@ -419,7 +419,7 @@ impl WorkspaceMessageHandler {
PanelType::Inspector => &[LayoutTarget::Inspector],
PanelType::Layers => &[LayoutTarget::LayersPanelControlLeftBar, LayoutTarget::LayersPanelBottomLeftBar, LayoutTarget::LayersPanelBottomRightBar],
PanelType::Data => &[LayoutTarget::DataPanel, LayoutTarget::DataPanelContext, LayoutTarget::DataPanelPath],
PanelType::Session => &[LayoutTarget::SessionPanel],
PanelType::Collaboration => &[LayoutTarget::CollaborationPanel],
PanelType::Document | PanelType::Welcome | PanelType::History => return,
};
@@ -446,7 +446,7 @@ impl WorkspaceMessageHandler {
PanelType::Data => {
// The Data panel's content is populated automatically as a side effect of the graph run completing, so there's nothing to do here
}
PanelType::Session => {
PanelType::Collaboration => {
responses.add(SyncMessage::RefreshPanel);
}
PanelType::History => {
@@ -33,16 +33,9 @@ pub enum PreferencesMessage {
DisableUIAcceleration {
disable_ui_acceleration: bool,
},
ValidateStorageRoundTrip {
enabled: bool,
},
SaveAsGdd {
enabled: bool,
},
SaveWithHistory {
enabled: bool,
},
ToggleShowStoragePreferences,
UserName {
name: String,
},
@@ -21,10 +21,7 @@ pub struct PreferencesMessageHandler {
pub viewport_zoom_wheel_rate: f64,
pub ui_scale: f64,
pub disable_ui_acceleration: bool,
pub validate_storage_round_trip: bool,
pub save_as_gdd: bool,
pub save_with_history: bool,
pub show_storage_preferences: bool,
/// This person's id across documents. A decimal string, since the browser's JSON loses 64-bit precision.
#[serde(with = "u64_as_string")]
#[cfg_attr(feature = "wasm", tsify(type = "string"))]
@@ -58,10 +55,7 @@ impl Default for PreferencesMessageHandler {
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
ui_scale: UI_SCALE_DEFAULT,
disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably
validate_storage_round_trip: false,
save_as_gdd: false,
save_with_history: false,
show_storage_preferences: false,
user_id: crate::application::generate_uuid(),
user_name: String::new(),
show_remote_cursors: true,
@@ -145,19 +139,9 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
PreferencesMessage::DisableUIAcceleration { disable_ui_acceleration } => {
self.disable_ui_acceleration = disable_ui_acceleration;
}
PreferencesMessage::ValidateStorageRoundTrip { enabled } => {
self.validate_storage_round_trip = enabled;
}
PreferencesMessage::SaveAsGdd { enabled } => {
self.save_as_gdd = enabled;
}
PreferencesMessage::SaveWithHistory { enabled } => {
self.save_with_history = enabled;
}
PreferencesMessage::ToggleShowStoragePreferences => {
self.show_storage_preferences = !self.show_storage_preferences;
responses.add(MenuBarMessage::SendLayout);
}
PreferencesMessage::UserName { name } => {
self.user_name = name.trim().to_string();
responses.add(SyncMessage::RefreshPanel);
@@ -1180,6 +1180,32 @@ mod test_transform_layer {
);
}
#[tokio::test]
async fn a_cancelled_grab_is_taken_back_for_good_and_leaves_the_drawing_as_the_step_to_undo() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.drag_tool(ToolType::Rectangle, 0., 0., 100., 100., ModifierKeys::empty()).await;
let layer = editor.active_document().metadata().all_layers().next().unwrap();
let original_transform = get_layer_transform(&mut editor, layer).await.unwrap();
editor.handle_message(TransformLayerMessage::BeginGrab).await;
editor.move_mouse(50., 50., ModifierKeys::empty(), MouseKeys::NONE).await;
editor
.handle_message(TransformLayerMessage::PointerMove {
slow_key: Key::Shift,
increments_key: Key::Control,
})
.await;
editor.handle_message(TransformLayerMessage::CancelTransformOperation).await;
assert_eq!(get_layer_transform(&mut editor, layer).await.unwrap(), original_transform);
editor.handle_message(DocumentMessage::DocumentHistoryForward).await;
assert_eq!(get_layer_transform(&mut editor, layer).await.unwrap(), original_transform, "the cancelled grab can't be redone");
editor.handle_message(DocumentMessage::DocumentHistoryBackward).await;
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "undo takes back the drawing, not the grab");
}
#[tokio::test]
async fn test_rotate_apply() {
let mut editor = EditorTestUtils::create();
+9 -57
View File
@@ -41,16 +41,12 @@ pub struct ExecutionResponse {
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The resulting value from the temporary inspected during execution
inspect_result: Option<InspectResult>,
/// The progress of each source with work in progress, by the path of the value node injecting the source.
progress: Vec<(Vec<NodeId>, f64)>,
}
#[derive(Debug)]
pub enum ExecutionResult {
Pending,
Value(TaggedValue),
/// A value computed from provisional data, which is evaluated again once that data is final.
Partial(TaggedValue),
Fallback(TaggedValue, EvaluationErrors),
Error(EvaluationErrors),
Panic(Box<dyn Any + Send>),
@@ -103,8 +99,6 @@ pub struct NodeGraphExecutor {
previous_node_to_inspect: Vec<NodeId>,
/// The canvas images the frontend holds, so a render sends only those it lacks.
canvas_images_sent: HashSet<u64>,
/// The progress of the active document's nodes with work in progress, by their full path from the root network.
node_progress: Vec<(Vec<NodeId>, f64)>,
/// Evaluation errors of the last evaluation, used in tests
#[cfg(test)]
evaluation_errors: Option<EvaluationErrors>,
@@ -158,7 +152,6 @@ impl NodeGraphExecutor {
node_graph_document: None,
previous_node_to_inspect: Vec::new(),
canvas_images_sent: HashSet::new(),
node_progress: Vec::new(),
#[cfg(test)]
evaluation_errors: None,
gradient_migration: None,
@@ -194,16 +187,6 @@ impl NodeGraphExecutor {
execution_id
}
/// The progress of the work of the node at this full path from the root network, if it has work in progress.
pub fn node_progress(&self, node_path: &[NodeId]) -> Option<f64> {
self.node_progress.iter().find(|(path, _)| path == node_path).map(|(_, progress)| *progress)
}
/// Cancels the work in progress of the node at this full path from the root network.
pub fn cancel_node_work(&self, node_path: Vec<NodeId>) {
self.sender.send(GraphRuntimeRequest::Cancel(node_path)).expect("Failed to send the cancellation");
}
pub fn submit_inspect_context_overrides(&self, overrides: graphene_std::ContextOverrides) {
self.sender.send(GraphRuntimeRequest::InspectContextOverrides(overrides)).expect("Failed to send the context overrides");
}
@@ -475,7 +458,6 @@ impl NodeGraphExecutor {
dropped_thumbnails,
vector_modify,
inspect_result,
progress,
} = *execution_response;
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
@@ -519,33 +501,14 @@ impl NodeGraphExecutor {
responses.add(OverlaysMessage::Draw);
// The deepest document node containing each source shows its progress
if execution_context.document_id == document_id {
let node_progress: Vec<_> = progress
.into_iter()
.filter_map(|(path, progress)| {
let node_path = (1..=path.len()).rev().map(|length| &path[..length]).find(|path| is_document_node(document, path))?;
Some((node_path.to_vec(), progress))
})
.collect();
if self.node_progress != node_progress {
responses.add(NodeGraphMessage::UpdateNodeProgress { progress: node_progress.clone() });
// The document as a whole shows the mean progress of its nodes with work in progress
let document_progress = (!node_progress.is_empty()).then(|| node_progress.iter().map(|(_, progress)| progress).sum::<f64>() / node_progress.len() as f64);
responses.add(FrontendMessage::UpdateDocumentProgress { progress: document_progress });
self.node_progress = node_progress;
responses.add(InspectorMessage::Refresh);
}
}
// A pending graph keeps the last frame, and the errors shown with it
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| is_document_node(document, path);
let in_document = |path: &&[NodeId]| {
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
};
errors
.iter()
.flat_map(|(error, trace)| {
@@ -562,7 +525,7 @@ impl NodeGraphExecutor {
})
.collect()
}
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Partial(_) | ExecutionResult::Panic(_) => Vec::new(),
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Panic(_) => Vec::new(),
};
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
}
@@ -571,14 +534,9 @@ impl NodeGraphExecutor {
{
self.evaluation_errors = None;
}
let render_status = match result {
ExecutionResult::Partial(_) => RenderStatus::Partial,
ExecutionResult::Fallback(..) => RenderStatus::Fallback,
ExecutionResult::Pending | ExecutionResult::Value(_) | ExecutionResult::Error(_) | ExecutionResult::Panic(_) => RenderStatus::Rendering,
};
let node_graph_output = match result {
ExecutionResult::Pending => Ok(None),
ExecutionResult::Value(value) | ExecutionResult::Partial(value) => Ok(Some(value)),
ExecutionResult::Value(value) => Ok(Some(value)),
ExecutionResult::Fallback(value, _errors) => {
#[cfg(test)]
{
@@ -628,7 +586,7 @@ impl NodeGraphExecutor {
match (node_graph_output, execution_context.export_config) {
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, responses),
(None, _) => {}
}
responses.add(DeferMessage::TriggerGraphRun {
@@ -941,7 +899,7 @@ impl NodeGraphExecutor {
self.node_graph_hash = 0;
}
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, render_status: RenderStatus, responses: &mut VecDeque<Message>) {
fn process_node_graph_output(&mut self, node_graph_output: TaggedValue, document_to_viewport: DAffine2, responses: &mut VecDeque<Message>) {
let TaggedValue::RenderOutput(render_output) = node_graph_output else {
log::error!("Invalid node graph output type: {node_graph_output:#?}");
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
@@ -1021,7 +979,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw);
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Rendering });
}
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
@@ -1083,12 +1041,6 @@ impl NodeGraphExecutor {
// TODO: Eventually remove this document upgrade code
/// Whether the fill node's `_has_transform` is still `false`, meaning its gradient placement has not yet been baked
/// (or set by the user), so a measured bake may safely be written.
/// Whether the node at this full path from the root network exists in the document.
fn is_document_node(document: &DocumentMessageHandler, path: &[NodeId]) -> bool {
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
}
fn fill_transform_unbaked(document: &DocumentMessageHandler, network_path: &[NodeId], fill_node_id: NodeId) -> bool {
let Some(network) = document.network_interface.document_network().nested_network(network_path) else {
return false;
+5 -76
View File
@@ -10,7 +10,6 @@ use graph_craft::document::{NodeId, NodeNetwork};
use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
use graph_craft::proto::GraphErrors;
use graphene_hash::CacheHash;
use graphene_std::SourceId;
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
use graphene_std::list::{Item, List};
use graphene_std::memo::IORecord;
@@ -56,8 +55,6 @@ pub struct NodeRuntime {
node_graph_errors: GraphErrors,
node_graph_warnings: GraphErrors,
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
/// Each source of the compiled network, with the path of the value node injecting it.
source_paths: Vec<(SourceId, Vec<NodeId>)>,
thumbnails: Thumbnails,
/// The node the Data panel inspects.
@@ -88,8 +85,6 @@ pub enum GraphRuntimeRequest {
/// The full path from the root network to the node the Data panel inspects, or empty for none.
Inspect(Vec<NodeId>),
InspectContextOverrides(ContextOverrides),
/// Cancels the work in progress of the sources within the node at this full path from the root network.
Cancel(Vec<NodeId>),
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
@@ -152,7 +147,6 @@ impl NodeRuntime {
node_graph_errors: Vec::new(),
node_graph_warnings: Vec::new(),
monitor_nodes: Vec::new(),
source_paths: Vec::new(),
thumbnails: Thumbnails::new(),
preprocessor: preprocessor::Preprocessor::new(),
@@ -201,15 +195,6 @@ impl NodeRuntime {
inspect_state.overrides_changed = true;
}
}
GraphRuntimeRequest::Cancel(node_path) => {
let mut canceled = false;
for (source, _) in self.source_paths.iter().filter(|(_, path)| path.starts_with(&node_path)) {
canceled |= self.async_runtime().cancel(*source);
}
if canceled {
self.dirty.store(true, Ordering::Release);
}
}
}
}
@@ -374,8 +359,7 @@ impl NodeRuntime {
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.executor.output(), &context))) {
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Final(value) | Poll::Partial(value))) => ExecutionResult::Value(value),
Ok(Ok(Poll::Fallback(boxed))) => {
let (value, error) = *boxed;
ExecutionResult::Fallback(value, self.resolve_errors(&error))
@@ -390,7 +374,6 @@ impl NodeRuntime {
dropped_thumbnails: Vec::new(),
vector_modify: HashMap::new(),
inspect_result: None,
progress: Vec::new(),
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
return None;
@@ -404,16 +387,6 @@ impl NodeRuntime {
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let progress = self
.async_runtime()
.progress()
.into_iter()
.filter_map(|(source, progress)| {
let (_, path) = self.source_paths.iter().find(|(candidate, _)| *candidate == source)?;
Some((path.clone(), progress))
})
.collect();
let response = ExecutionResponse {
execution_id,
result,
@@ -421,7 +394,6 @@ impl NodeRuntime {
dropped_thumbnails,
vector_modify: self.vector_modify.clone(),
inspect_result,
progress,
};
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
}
@@ -459,7 +431,6 @@ impl NodeRuntime {
.filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER)
.map(|(id, node)| (node.original_location.path.clone().unwrap_or_default(), *id))
.collect();
self.source_paths = proto_network.source_paths().map(|(source, path)| (*source, path.to_vec())).collect();
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
@@ -533,9 +504,7 @@ impl NodeRuntime {
impl ExecutionResult {
fn render_output(&mut self) -> Option<&mut RenderOutputType> {
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
return None;
};
let (Self::Value(value) | Self::Fallback(value, _)) = self else { return None };
let TaggedValue::RenderOutput(RenderOutput { data, .. }) = value else { return None };
Some(data)
}
@@ -729,7 +698,6 @@ impl InspectState {
#[cfg(test)]
mod tests {
use super::*;
use crate::messages::frontend::utility_types::RenderStatus;
use crate::test_utils::EditorTestUtils;
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
@@ -749,17 +717,12 @@ mod tests {
/// Sends a network update and a request to evaluate it, as the editor does for a change to the graph.
fn send_update(editor: &mut EditorTestUtils) {
send_update_at(editor, UVec2::ONE);
}
/// Sends a network update and a request to evaluate it at a viewport of `resolution` pixels.
fn send_update_at(editor: &mut EditorTestUtils, resolution: UVec2) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
executor
.submit_node_graph_evaluation(document, document_id, resolution, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
.unwrap();
}
@@ -789,8 +752,8 @@ mod tests {
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
}
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations. Returns the Vectorize node.
fn vectorize_layer(editor: &mut EditorTestUtils) -> NodeId {
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
fn vectorize_layer(editor: &mut EditorTestUtils) {
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
@@ -815,7 +778,6 @@ mod tests {
output_connector: OutputConnector::primary_output(vectorize),
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
});
vectorize
}
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
@@ -926,39 +888,6 @@ mod tests {
assert!(!evaluated(&mut editor), "the requests of the older network updates evaluated again");
}
/// A trace renders partial frames and shows its progress on its node until it is canceled, which keeps the shapes traced so far.
#[tokio::test]
async fn a_trace_shows_its_progress_until_it_is_canceled() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 512., 512.).await;
let vectorize = vectorize_layer(&mut editor);
send_update_at(&mut editor, UVec2::splat(512));
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
assert!(
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Partial }),
"the trace's frame isn't partial"
);
assert!(editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_some(), "the trace shows no progress");
editor.dispatch(PortfolioMessage::CancelNodeWork { node_path: vec![vectorize] });
editor.runtime.update();
editor.runtime.run().await;
let messages = editor.dispatch(Message::Wake);
assert!(
messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Fallback }),
"the canceled trace's frame isn't a fallback"
);
assert!(
editor.portfolio_message_handler_mut().executor.node_progress(&[vectorize]).is_none(),
"the canceled trace still shows progress"
);
}
#[test]
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
let previewed_node = NodeId(1);
-4
View File
@@ -50,10 +50,6 @@ impl EditorTestUtils {
editor.dispatch(PortfolioMessage::Init);
// Tests run with `.gdd` storage on and the dual-write soak validation enabled, so storage round-trip drift fails loud.
editor.dispatch(PreferencesMessage::SaveAsGdd { enabled: true });
editor.dispatch(PreferencesMessage::ValidateStorageRoundTrip { enabled: true });
editor
}
@@ -1,17 +1,17 @@
<script lang="ts">
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
import { sessionPanelLayout } from "/src/stores/portfolio";
import { collaborationPanelLayout } from "/src/stores/portfolio";
</script>
<LayoutCol class="session-panel">
<LayoutCol class="collaboration-panel">
<LayoutCol class="body" scrollableY={true}>
<WidgetLayout layout={sessionPanelLayout} layoutTarget="SessionPanel" />
<WidgetLayout layout={collaborationPanelLayout} layoutTarget="CollaborationPanel" />
</LayoutCol>
</LayoutCol>
<style lang="scss">
.session-panel {
.collaboration-panel {
flex-grow: 1;
padding: 4px 8px;
+1 -16
View File
@@ -739,12 +739,9 @@
>
</canvas>
{/if}
{#if isWeb && !["Error", "Panic"].includes($document.renderStatus)}
{#if isWeb && $document.renderStatus === "Rendering"}
<TextLabel class="shader-compiling-overlay" italic={true} classes={{ show: !firstArtworkReceived }}>Initializing Renderer…</TextLabel>
{/if}
{#if typeof $document.progress === "number"}
<div class="render-progress" style:width={`${Math.min(Math.max($document.progress, 0), 1) * 100}%`}></div>
{/if}
{#if $document.renderStatus === "Error"}
<LayoutCol class="render-status-overlay">
<TextLabel>
@@ -1008,18 +1005,6 @@
}
}
.render-progress {
position: absolute;
left: 0;
bottom: 0;
// Above the error overlays
z-index: 1;
height: 2px;
background: var(--color-warning-yellow);
pointer-events: none;
transition: width 0.1s linear;
}
.render-status-overlay {
position: absolute;
inset: 0;
@@ -965,12 +965,10 @@
{@const clipPathId = String(Math.random()).substring(2)}
{@const description = node.reference ? $nodeGraph.nodeDescriptions.get(node.reference) : undefined}
{@const icon = (node.reference && $nodeGraph.nodeIcons.get(node.reference)) || "NodeCustomNode"}
{@const progress = $nodeGraph.progress.get(node.id)}
<div
class="node"
class:selected={$nodeGraph.selected.includes(node.id)}
class:previewed={node.previewed}
class:in-progress={progress !== undefined}
class:disabled={!node.visible}
style:--offset-left={(node.position?.[0] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 0)}
style:--offset-top={(node.position?.[1] || 0) + glideCells($nodeGlideOffsets.nodes.get(node.id), 1)}
@@ -986,9 +984,6 @@
<IconLabel {icon} />
<!-- TODO: Allow the user to edit the name, just like in the Layers panel -->
<TextLabel>{node.displayName}</TextLabel>
{#if progress !== undefined}
<div class="progress" style:width={`${Math.min(Math.max(progress, 0), 1) * 100}%`}></div>
{/if}
</div>
<!-- Secondary rows -->
{#if exposedInputsOutputs.length > 0}
@@ -1497,10 +1492,6 @@
border: 1px dashed var(--color-e-nearwhite);
}
&.in-progress::after {
border-color: var(--color-warning-yellow);
}
.connectors {
position: absolute;
// Keeps the connectors above the wires
@@ -1886,15 +1877,6 @@
margin-left: 0;
margin-right: 4px;
}
.progress {
position: absolute;
left: 0;
bottom: 0;
height: 3px;
background: var(--color-e-nearwhite);
transition: width 0.1s linear;
}
}
.secondary {
@@ -3,7 +3,6 @@
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import IconLabel from "/src/components/widgets/labels/IconLabel.svelte";
import ProgressBar from "/src/components/widgets/labels/ProgressBar.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
import NodeSection from "/src/components/widgets/NodeSection.svelte";
import WidgetSpan from "/src/components/widgets/WidgetSpan.svelte";
@@ -94,18 +93,6 @@
<div class="expand-arrow"></div>
</div>
<TextLabel tooltipLabel={widgetData.name} tooltipDescription={widgetData.description}>{widgetData.name}</TextLabel>
{#if typeof widgetData.progress === "number"}
<ProgressBar fraction={widgetData.progress} label={`${Math.floor(Math.min(Math.max(widgetData.progress, 0), 1) * 100)}%`} />
<IconButton
icon="CloseX"
tooltipDescription="Stop the work in progress, keeping its result so far."
size={24}
action={(e) => {
editor.cancelNodeWork(widgetData.id);
e?.stopPropagation();
}}
/>
{/if}
<IconButton
icon={widgetData.visible ? "EyeVisible" : "EyeHidden"}
hoverIcon={widgetData.visible ? "EyeHide" : "EyeShow"}
@@ -474,12 +461,6 @@
overflow: hidden;
text-overflow: ellipsis;
}
.progress-bar {
flex: 1 1 auto;
min-width: 0;
margin-left: 8px;
}
}
// Hovering the chain sections within doesn't count
@@ -1,71 +0,0 @@
<script lang="ts">
import type { ActionShortcut } from "/wrapper/pkg/graphite_wasm_wrapper";
let className = "";
export { className as class };
export let classes: Record<string, boolean> = {};
// Content
export let fraction: number;
export let label = "";
// Tooltips
export let tooltipLabel: string | undefined = undefined;
export let tooltipDescription: string | undefined = undefined;
export let tooltipShortcut: ActionShortcut | undefined = undefined;
$: extraClasses = Object.entries(classes)
.flatMap(([className, stateName]) => (stateName ? [className] : []))
.join(" ");
$: percent = `${Math.min(Math.max(fraction, 0), 1) * 100}%`;
</script>
<div
class={`progress-bar ${className} ${extraClasses}`.trim()}
role="progressbar"
aria-valuemin={0}
aria-valuemax={1}
aria-valuenow={fraction}
data-tooltip-label={tooltipLabel}
data-tooltip-description={tooltipDescription}
data-tooltip-shortcut={tooltipShortcut?.shortcut ? JSON.stringify(tooltipShortcut.shortcut) : undefined}
>
<div class="track">
<div class="fill" style:width={percent}></div>
</div>
{#if label}
<span class="label">{label}</span>
{/if}
</div>
<style lang="scss">
.progress-bar {
display: flex;
align-items: center;
gap: 8px;
flex: 1 1 100%;
height: 24px;
.track {
position: relative;
flex: 1 1 100%;
height: 4px;
border-radius: 2px;
overflow: hidden;
background: var(--color-1-nearblack);
}
.fill {
position: absolute;
inset: 0 auto 0 0;
background: var(--color-e-nearwhite);
transition: width 0.1s linear;
}
.label {
flex: 0 0 auto;
font-size: 12px;
white-space: nowrap;
color: var(--color-a-softgray);
}
}
</style>
+3 -3
View File
@@ -2,12 +2,12 @@
import { getContext, onDestroy, tick } from "svelte";
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
import LayoutRow from "/src/components/layout/LayoutRow.svelte";
import Collaboration from "/src/components/panels/Collaboration.svelte";
import Data from "/src/components/panels/Data.svelte";
import Document from "/src/components/panels/Document.svelte";
import History from "/src/components/panels/History.svelte";
import Inspector from "/src/components/panels/Inspector.svelte";
import Layers from "/src/components/panels/Layers.svelte";
import Session from "/src/components/panels/Session.svelte";
import Welcome from "/src/components/panels/Welcome.svelte";
import IconButton from "/src/components/widgets/buttons/IconButton.svelte";
import TextLabel from "/src/components/widgets/labels/TextLabel.svelte";
@@ -22,7 +22,7 @@
History,
Inspector,
Data,
Session,
Collaboration,
};
const BUTTON_LEFT = 0;
const BUTTON_MIDDLE = 1;
@@ -461,7 +461,7 @@
class="session"
class:disconnected={tabLabel.session === "Disconnected"}
data-tooltip-label={tabLabel.session === "Connected" ? "Live session" : "Disconnected from the session"}
data-tooltip-description={tabLabel.session === "Connected" ? "Click to open the Session panel." : "Reconnecting. Click to open the Session panel."}
data-tooltip-description={tabLabel.session === "Connected" ? "Click to open the Collaboration panel." : "Reconnecting. Click to open the Collaboration panel."}
data-session-button
on:pointerdown|stopPropagation
on:click|stopPropagation={() => sessionAction?.(tabIndex)}
@@ -207,9 +207,9 @@
editor.renameDocument(newName);
}}
sessionAction={(tabIndex) => {
// The Session panel shows the active document
// The Collaboration panel shows the active document
editor.selectDocument($portfolio.documents[tabIndex].id);
editor.focusPanel("Session");
editor.focusPanel("Collaboration");
}}
tabActiveIndex={$portfolio.activeDocumentIndex}
groupDropAction={groupDrop}
+4
View File
@@ -230,6 +230,7 @@ import NodeIsNonzero from "/../branding/assets/16x16-nodes/node-is-nonzero.svg";
import NodeItemAtIndex from "/../branding/assets/16x16-nodes/node-item-at-index.svg";
import NodeIterate from "/../branding/assets/16x16-nodes/node-iterate.svg";
import NodeJitterPoints from "/../branding/assets/16x16-nodes/node-jitter-points.svg";
import NodeLSystem from "/../branding/assets/16x16-nodes/node-l-system.svg";
import NodeLeastCommonMultiple from "/../branding/assets/16x16-nodes/node-least-common-multiple.svg";
import NodeLerp from "/../branding/assets/16x16-nodes/node-lerp.svg";
import NodeLessThan from "/../branding/assets/16x16-nodes/node-less-than.svg";
@@ -375,6 +376,7 @@ import NodeText from "/../branding/assets/16x16-nodes/node-text.svg";
import NodeThreshold from "/../branding/assets/16x16-nodes/node-threshold.svg";
import NodeTransform from "/../branding/assets/16x16-nodes/node-transform.svg";
import NodeTriangulate from "/../branding/assets/16x16-nodes/node-triangulate.svg";
import NodeTurtlePath from "/../branding/assets/16x16-nodes/node-turtle-path.svg";
import NodeUngroup from "/../branding/assets/16x16-nodes/node-ungroup.svg";
import NodeUnweld from "/../branding/assets/16x16-nodes/node-unweld.svg";
import NodeVaryFillColors from "/../branding/assets/16x16-nodes/node-vary-fill-colors.svg";
@@ -524,6 +526,7 @@ export const ICON_16X16_NODES = {
NodeLogicalNot: { svg: NodeLogicalNot, size: 16 },
NodeLogicalOr: { svg: NodeLogicalOr, size: 16 },
NodeLoremIpsum: { svg: NodeLoremIpsum, size: 16 },
NodeLSystem: { svg: NodeLSystem, size: 16 },
NodeMagnitude: { svg: NodeMagnitude, size: 16 },
NodeMakeOpaque: { svg: NodeMakeOpaque, size: 16 },
NodeMandelbrot: { svg: NodeMandelbrot, size: 16 },
@@ -657,6 +660,7 @@ export const ICON_16X16_NODES = {
NodeThreshold: { svg: NodeThreshold, size: 16 },
NodeTransform: { svg: NodeTransform, size: 16 },
NodeTriangulate: { svg: NodeTriangulate, size: 16 },
NodeTurtlePath: { svg: NodeTurtlePath, size: 16 },
NodeUngroup: { svg: NodeUngroup, size: 16 },
NodeUnweld: { svg: NodeUnweld, size: 16 },
NodeVaryFillColors: { svg: NodeVaryFillColors, size: 16 },
-11
View File
@@ -16,8 +16,6 @@ type DocumentStoreState = {
graphViewOverlayOpen: boolean;
fadeArtwork: number;
renderStatus: RenderStatus;
// How far the work in progress of the document has come from 0 to 1, if it has any
progress: number | undefined;
};
const initialState: DocumentStoreState = {
toolOptionsLayout: createLayout(),
@@ -28,7 +26,6 @@ const initialState: DocumentStoreState = {
graphViewOverlayOpen: false,
fadeArtwork: 100,
renderStatus: "Rendering",
progress: undefined,
};
let subscriptionsRouter: SubscriptionsRouter | undefined = undefined;
@@ -95,13 +92,6 @@ export function createDocumentStore(subscriptions: SubscriptionsRouter) {
});
});
subscriptions.subscribeFrontendMessage("UpdateDocumentProgress", (data) => {
update((state) => {
state.progress = data.progress;
return state;
});
});
return { subscribe, remoteCursorsStore };
}
@@ -112,7 +102,6 @@ export function destroyDocumentStore() {
subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork");
subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay");
subscriptions.unsubscribeFrontendMessage("UpdateRenderStatus");
subscriptions.unsubscribeFrontendMessage("UpdateDocumentProgress");
subscriptions.unsubscribeFrontendMessage("UpdateDocumentCursors");
subscriptions.unsubscribeLayoutUpdate("ToolOptions");
subscriptions.unsubscribeLayoutUpdate("DocumentBar");
-10
View File
@@ -25,7 +25,6 @@ type NodeGraphStoreState = {
clickTargets: FrontendClickTargets | undefined;
contextMenuInformation: ContextMenuInformation | undefined;
errors: NodeGraphErrorDiagnostic[];
progress: Map<bigint, number>;
layerWidths: Map<bigint, number>;
chainWidths: Map<bigint, number>;
hasLeftInputWire: Map<bigint, boolean>;
@@ -48,7 +47,6 @@ const initialState: NodeGraphStoreState = {
clickTargets: undefined,
contextMenuInformation: undefined,
errors: [],
progress: new Map(),
layerWidths: new Map(),
chainWidths: new Map(),
hasLeftInputWire: new Map(),
@@ -229,13 +227,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
});
});
subscriptions.subscribeFrontendMessage("UpdateNodeGraphProgress", (data) => {
update((state) => {
state.progress = new Map(data.progress.map(({ nodeId, progress }) => [nodeId, progress]));
return state;
});
});
subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
const newNodes = new Set<bigint>(data.nodes);
@@ -359,7 +350,6 @@ export function destroyNodeGraphStore() {
subscriptions.unsubscribeFrontendMessage("UpdateLayerWidths");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphNodes");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphErrorDiagnostics");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphProgress");
subscriptions.unsubscribeFrontendMessage("UpdateVisibleNodes");
subscriptions.unsubscribeFrontendMessage("UpdateGlideOffsets");
subscriptions.unsubscribeFrontendMessage("UpdateNodeGraphWires");
+4 -4
View File
@@ -42,7 +42,7 @@ export const inspectorLayout = persistedLayout("inspectorLayout");
export const dataPanelLayout = persistedLayout("dataPanelLayout");
export const dataPanelContextLayout = persistedLayout("dataPanelContextLayout");
export const dataPanelPathLayout = persistedLayout("dataPanelPathLayout");
export const sessionPanelLayout = persistedLayout("sessionPanelLayout");
export const collaborationPanelLayout = persistedLayout("collaborationPanelLayout");
export const layersPanelControlBarLeftLayout = persistedLayout("layersPanelControlBarLeftLayout");
export const layersPanelBottomBarLeftLayout = persistedLayout("layersPanelBottomBarLeftLayout");
export const layersPanelBottomBarRightLayout = persistedLayout("layersPanelBottomBarRightLayout");
@@ -147,8 +147,8 @@ export function createPortfolioStore(subscriptions: SubscriptionsRouter, editor:
patchLayout(dataPanelPathLayout, data);
});
subscriptions.subscribeLayoutUpdate("SessionPanel", (data) => {
patchLayout(sessionPanelLayout, data);
subscriptions.subscribeLayoutUpdate("CollaborationPanel", (data) => {
patchLayout(collaborationPanelLayout, data);
});
subscriptions.subscribeLayoutUpdate("LayersPanelControlLeftBar", (data) => {
@@ -214,7 +214,7 @@ export function destroyPortfolioStore() {
subscriptions.unsubscribeLayoutUpdate("DataPanel");
subscriptions.unsubscribeLayoutUpdate("DataPanelContext");
subscriptions.unsubscribeLayoutUpdate("DataPanelPath");
subscriptions.unsubscribeLayoutUpdate("SessionPanel");
subscriptions.unsubscribeLayoutUpdate("CollaborationPanel");
subscriptions.unsubscribeLayoutUpdate("LayersPanelControlLeftBar");
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomLeftBar");
subscriptions.unsubscribeLayoutUpdate("LayersPanelBottomRightBar");
-5
View File
@@ -761,11 +761,6 @@ mod editor_commands {
DocumentMessage::ToggleNodeVisibility { node_id: NodeId(id) }.into()
}
/// Stop the work in progress of a node shown in the Inspector, which may be in a subgraph
fn cancel_node_work(id: u64) -> Message {
DocumentMessage::CancelNodeWork { node_id: NodeId(id) }.into()
}
/// Pin or unpin a node given its node ID
fn set_node_pinned(id: u64, pinned: bool) -> Message {
DocumentMessage::SetNodePinned { node_id: NodeId(id), pinned }.into()
+592
View File
@@ -0,0 +1,592 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anes"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "bumpalo"
version = "3.20.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "ciborium"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e"
dependencies = [
"ciborium-io",
"ciborium-ll",
"serde",
]
[[package]]
name = "ciborium-io"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757"
[[package]]
name = "ciborium-ll"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9"
dependencies = [
"ciborium-io",
"half",
]
[[package]]
name = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstyle",
"clap_lex",
]
[[package]]
name = "clap_lex"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "compiler-spike"
version = "0.0.0"
dependencies = [
"criterion",
"rustc-hash",
"serde",
"serde_json",
]
[[package]]
name = "criterion"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1c047a62b0cc3e145fa84415a3191f628e980b194c2755aa12300a4e6cbd928"
dependencies = [
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
"itertools",
"num-traits",
"oorandom",
"plotters",
"rayon",
"regex",
"serde",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b1bcc0dc7dfae599d84ad0b1a55f80cde8af3725da8313b528da95ef783e338"
dependencies = [
"cast",
"itertools",
]
[[package]]
name = "crossbeam-deque"
version = "0.8.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
dependencies = [
"crossbeam-epoch",
"crossbeam-utils",
]
[[package]]
name = "crossbeam-epoch"
version = "0.9.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
dependencies = [
"crossbeam-utils",
]
[[package]]
name = "crossbeam-utils"
version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
[[package]]
name = "crunchy"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "either"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be"
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "half"
version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
"zerocopy",
]
[[package]]
name = "itertools"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "js-sys"
version = "0.3.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
dependencies = [
"cfg-if",
"futures-util",
"wasm-bindgen",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "oorandom"
version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
[[package]]
name = "plotters"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aeb6f403d7a4911efb1e33402027fc44f29b5bf6def3effcc22d7bb75f2b747"
dependencies = [
"num-traits",
"plotters-backend",
"plotters-svg",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "plotters-backend"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df42e13c12958a16b3f7f4386b9ab1f3e7933914ecea48da7139435263a4172a"
[[package]]
name = "plotters-svg"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "51bae2ac328883f7acdfea3d66a7c35751187f870bc81f94563733a154d7a670"
dependencies = [
"plotters-backend",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rayon"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
dependencies = [
"either",
"rayon-core",
]
[[package]]
name = "rayon-core"
version = "1.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
dependencies = [
"crossbeam-deque",
"crossbeam-utils",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]]
name = "rustversion"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tinytemplate"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4d6b5f19ff7664e8c98d03e2139cb510db9b0a60b55f8e8709b689d939b6bc"
dependencies = [
"serde",
"serde_json",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasm-bindgen"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
dependencies = [
"cfg-if",
"once_cell",
"rustversion",
"wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn 3.0.9",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.129"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
dependencies = [
"unicode-ident",
]
[[package]]
name = "web-sys"
version = "0.3.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "zerocopy"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "compiler-spike"
version = "0.0.0"
edition = "2024"
publish = false
# Standalone workspace so the spike builds without Graphite's dependency tree
[workspace]
[dependencies]
rustc-hash = "2.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
[dev-dependencies]
criterion = "0.7"
[[bench]]
name = "pipeline"
harness = false
[profile.release]
debug = true
codegen-units = 1
[profile.bench]
debug = true
codegen-units = 1
@@ -0,0 +1,106 @@
use compiler_spike::baseline::Baseline;
use compiler_spike::workload::DEMO_ART;
use criterion::{BatchSize, Criterion, criterion_group, criterion_main};
use std::hint::black_box;
fn baseline(c: &mut Criterion) {
let mut baseline = Baseline::load();
let demos: Vec<_> = DEMO_ART
.iter()
.map(|name| {
let network = baseline.load_network(name);
let preprocessed = baseline.preprocess(network.clone());
let proto_network = baseline.compile(preprocessed.clone()).unwrap();
(name, network, preprocessed, proto_network)
})
.collect();
let mut group = c.benchmark_group("Baseline preprocess");
for (name, network, _, _) in &demos {
group.bench_function(**name, |b| b.iter_batched(|| network.clone(), |network| baseline.preprocess(black_box(network)), BatchSize::SmallInput));
}
group.finish();
let mut group = c.benchmark_group("Baseline compile");
for (name, _, preprocessed, _) in &demos {
group.bench_function(**name, |b| {
b.iter_batched(|| preprocessed.clone(), |network| baseline.compile(black_box(network)).unwrap(), BatchSize::SmallInput)
});
}
group.finish();
let mut group = c.benchmark_group("Baseline executor construction");
for (name, _, _, proto_network) in &demos {
group.bench_function(**name, |b| {
b.iter_batched(
|| proto_network.clone(),
|network| baseline.build_executor(black_box(network)).unwrap().tree.len(),
BatchSize::SmallInput,
)
});
}
group.finish();
let mut group = c.benchmark_group("Baseline full pipeline");
for (name, network, _, _) in &demos {
group.bench_function(**name, |b| {
b.iter_batched(|| network.clone(), |network| baseline.run(black_box(network)).unwrap().tree.len(), BatchSize::SmallInput)
});
}
group.finish();
}
fn lean(c: &mut Criterion) {
use compiler_spike::lean::Lean;
use compiler_spike::lean::executor::Executor;
use compiler_spike::workload::load_network;
let mut lean = Lean::load();
let demos: Vec<_> = DEMO_ART
.iter()
.map(|name| {
let network = load_network(name);
let document = lean.convert_document(&network);
(name, network, document)
})
.collect();
let mut group = c.benchmark_group("Lean document conversion");
for (name, network, _) in &demos {
group.bench_function(**name, |b| b.iter(|| lean.convert_document(black_box(network)).definitions.len()));
}
group.finish();
let mut group = c.benchmark_group("Lean compile");
for (name, _, document) in &demos {
group.bench_function(**name, |b| b.iter(|| lean.compile(black_box(document)).unwrap().output));
}
group.finish();
let mut group = c.benchmark_group("Lean executor construction");
for (name, _, document) in &demos {
let compiled = lean.compile(document).unwrap();
group.bench_function(**name, |b| b.iter(|| Executor::new(black_box(&compiled)).nodes.len()));
}
group.finish();
let mut group = c.benchmark_group("Lean full pipeline");
for (name, _, document) in &demos {
group.bench_function(**name, |b| b.iter(|| Executor::new(&lean.compile(black_box(document)).unwrap()).nodes.len()));
}
group.finish();
let mut group = c.benchmark_group("Lean full pipeline cold selections");
for (name, _, document) in &demos {
group.bench_function(**name, |b| {
b.iter(|| {
lean.typing.registry.clear_selections();
Executor::new(&lean.compile(black_box(document)).unwrap()).nodes.len()
})
});
}
group.finish();
}
criterion_group!(benches, baseline, lean);
criterion_main!(benches);
@@ -0,0 +1,122 @@
//! Usage: `cargo run --release --example codegen_timings [--iterations=N] [--async] [--modes=Everywhere,Bounded,Monomorphic,Functions,FunctionPointers] [demo...]`
use compiler_spike::lean::Lean;
use compiler_spike::lean::codegen::{self, Erasure, Evaluation};
use compiler_spike::workload::{DEMO_ART, load_network};
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};
const RUSTC_TIMEOUT_SECONDS: &str = "600";
fn build(path: &Path) -> Option<Duration> {
let start = Instant::now();
let status = Command::new("timeout")
.args([RUSTC_TIMEOUT_SECONDS, "rustc", "--edition", "2024", "-C", "opt-level=3", "-C", "codegen-units=1", "-o"])
.arg(path.with_extension(""))
.arg(path)
.output()
.ok()?
.status;
status.success().then(|| start.elapsed())
}
/// Returns the nanoseconds per evaluation and the checksum.
fn run(path: &Path, iterations: u64) -> Option<(u64, String)> {
let output = Command::new(path.with_extension("")).arg(iterations.to_string()).output().ok()?;
let stdout = String::from_utf8(output.stdout).ok()?;
let (nanoseconds, checksum) = stdout.trim().split_once(' ')?;
Some((nanoseconds.parse().ok()?, checksum.to_string()))
}
#[derive(Clone, Copy, Debug)]
enum Variant {
Structs(Erasure, Evaluation),
Functions,
FunctionPointers,
}
impl Variant {
fn label(self) -> String {
match self {
Variant::Structs(erasure, evaluation) => format!("{erasure:?} {evaluation:?}"),
Variant::Functions => "Functions".to_string(),
Variant::FunctionPointers => "FunctionPointers".to_string(),
}
}
fn parse(label: &str, asynchronous: bool) -> Vec<Variant> {
let evaluations = if asynchronous { vec![Evaluation::Sync, Evaluation::Async] } else { vec![Evaluation::Sync] };
let structs = |erasure| evaluations.iter().map(|&evaluation| Variant::Structs(erasure, evaluation)).collect();
match label {
"Everywhere" => structs(Erasure::Everywhere),
"Bounded" => structs(Erasure::Bounded),
"Monomorphic" => structs(Erasure::Monomorphic),
"Functions" => vec![Variant::Functions],
"FunctionPointers" => vec![Variant::FunctionPointers],
_ => panic!("Unknown variant {label}"),
}
}
}
fn main() {
let mut iterations = 10_000;
let mut labels = "Everywhere,Bounded,Monomorphic,Functions,FunctionPointers".to_string();
let mut asynchronous = false;
let mut selected = Vec::new();
for argument in std::env::args().skip(1) {
if let Some(value) = argument.strip_prefix("--iterations=") {
iterations = value.parse().expect("--iterations should be a number");
} else if let Some(value) = argument.strip_prefix("--modes=") {
labels = value.to_string();
} else if argument == "--async" {
asynchronous = true;
} else {
selected.push(argument);
}
}
let variants: Vec<Variant> = labels.split(',').flat_map(|label| Variant::parse(label, asynchronous)).collect();
let names: Vec<&str> = DEMO_ART
.into_iter()
.chain(["rectangle-layers"])
.filter(|name| selected.is_empty() || selected.iter().any(|selected| selected == name))
.collect();
let directory = std::env::temp_dir().join("compiler-spike-codegen");
std::fs::create_dir_all(&directory).unwrap();
let mut lean = Lean::load();
println!(
"{:<26} {:<18} {:>6} {:>10} {:>9} {:>10} {:>12} {:>9}",
"document", "variant", "nodes", "node evals", "emit", "build", "ns per run", "checksum"
);
for name in names {
let document = lean.convert_document(&load_network(name));
let output = lean.compile(&document).unwrap().output;
for &variant in &variants {
let start = Instant::now();
let emitted = match variant {
Variant::Structs(erasure, evaluation) => codegen::emit(&lean, output, erasure, evaluation),
Variant::Functions => codegen::emit_functions(&lean, output, false),
Variant::FunctionPointers => codegen::emit_functions(&lean, output, true),
};
let emit_time = start.elapsed();
let path = directory.join(format!("{name}-{}.rs", variant.label().replace(' ', "-")));
std::fs::write(&path, &emitted.source).unwrap();
let build_time = build(&path);
let result = build_time.and_then(|_| run(&path, iterations));
println!(
"{name:<26} {:<18} {:>6} {:>10.0} {:>9.2?} {:>10} {:>12} {:>9}",
variant.label(),
emitted.statements,
emitted.evaluations_per_run,
emit_time,
build_time.map_or("failed".to_string(), |time| format!("{:.2}s", time.as_secs_f64())),
result.as_ref().map_or("failed".to_string(), |(nanoseconds, _)| nanoseconds.to_string()),
result.as_ref().map_or("-".to_string(), |(_, checksum)| checksum.chars().take(8).collect()),
);
}
}
}
@@ -0,0 +1,37 @@
use compiler_spike::lean::Lean;
use compiler_spike::lean::document::{Implementation, Input};
use compiler_spike::synthetic::rectangle_layers;
fn main() {
let mut lean = Lean::load();
let mut document = lean.convert_document(&rectangle_layers(1600));
lean.compile_incremental(&mut document).unwrap();
let transform = lean.strings.get("transform_nodes::transform_nodes::TransformNode").unwrap();
let root = &document.definitions[document.root.index()];
let mut bottom = None;
'search: for (index, definition) in document.definitions.iter().enumerate() {
for (local, node) in definition.nodes.iter().enumerate() {
if matches!(node.implementation, Implementation::Proto(identifier) if identifier.0 == transform)
&& let Some(input) = definition.node_inputs(node).iter().position(|input| matches!(input, Input::Value(_)))
{
bottom = Some((index as u32, local as u32, input));
break 'search;
}
}
}
let _ = root;
let (definition, local, input) = bottom.expect("a transform value should exist");
let mut timings = Vec::new();
for edit in 0..300_u64 {
document.set_value(definition, local, input, 0xED17 + edit);
let start = std::time::Instant::now();
std::hint::black_box(lean.compile_incremental(&mut document).unwrap().output);
timings.push((start.elapsed(), lean.ir.len()));
}
for range in [0..10, 100..110, 290..300] {
let average = timings[range.clone()].iter().map(|(time, _)| *time).sum::<std::time::Duration>() / 10;
println!("edits {range:?}: {average:.3?} per edit, store {} nodes", timings[range.end - 1].1);
}
}
@@ -0,0 +1,13 @@
use compiler_spike::lean::Lean;
use compiler_spike::lean::executor::Executor;
use compiler_spike::workload::load_network;
fn main() {
let name = std::env::args().nth(1).unwrap_or_else(|| "red-dress".to_string());
let mut lean = Lean::load();
let document = lean.convert_document(&load_network(&name));
for _ in 0..3000 {
let compiled = lean.compile(&document).unwrap();
std::hint::black_box(Executor::new(&compiled).nodes.len());
}
}
@@ -0,0 +1,77 @@
{
"purity": [
["core_types::color::color_types::Color", "vector_types::gradient::Gradient"],
["vector_types::gradient::Gradient", "vector_types::vector::vector_types::Vector"],
["vector_types::vector::vector_types::Vector", "raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>"],
["core_types::color::color_types::Color", "alloc::string::String"]
],
"equivalent": [
["raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>", "raster_types::raster_types::Raster<raster_types::raster_types::gpu::GPU>"]
],
"conversions": [
{ "from": "core_types::color::color_types::Color", "to": "vector_types::vector::vector_types::Vector" },
{ "from": "core_types::color::color_types::Color", "to": "vector_types::gradient::Gradient" },
{ "from": "vector_types::gradient::Gradient", "to": "vector_types::vector::vector_types::Vector" },
{ "from": "vector_types::vector::vector_types::Vector", "to": "raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>", "reads_footprint": true },
{ "from": "raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>", "to": "vector_types::vector::vector_types::Vector" },
{ "from": "core_types::color::color_types::Color", "to": "alloc::string::String" },
{ "from": "f64", "to": "core_types::color::color_types::Color" },
{
"from": "raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>",
"to": "raster_types::raster_types::Raster<raster_types::raster_types::gpu::GPU>",
"converter": { "type": "wgpu_executor::WgpuExecutor", "scope": "graphene_std::platform_application_io::WgpuExecutorNode" }
},
{
"from": "raster_types::raster_types::Raster<raster_types::raster_types::gpu::GPU>",
"to": "raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>",
"converter": { "type": "wgpu_executor::WgpuExecutor", "scope": "graphene_std::platform_application_io::WgpuExecutorNode" },
"asynchronous": true
}
],
"nodes": [
{
"identifier": "spike::Blur",
"element_types": ["vector_types::vector::vector_types::Vector", "raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>"]
},
{
"identifier": "spike::Shade",
"element_types": ["vector_types::vector::vector_types::Vector", "vector_types::gradient::Gradient"]
},
{
"identifier": "spike::VectorOnly",
"element_types": ["vector_types::vector::vector_types::Vector"]
},
{
"identifier": "spike::RasterOnly",
"element_types": ["raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>"]
},
{
"identifier": "spike::GpuOnly",
"element_types": ["raster_types::raster_types::Raster<raster_types::raster_types::gpu::GPU>"]
},
{
"identifier": "spike::NumberList",
"element_types": ["f64"],
"ranks": ["List"]
},
{
"identifier": "spike::Integer",
"element_types": ["i64"],
"ranks": ["Item"]
},
{
"identifier": "spike::NumberOrText",
"element_types": ["f64", "alloc::string::String"],
"ranks": ["Item"]
},
{
"identifier": "spike::GenericList",
"element_types": ["generic:T"],
"ranks": ["List"]
},
{
"identifier": "spike::Ambiguous",
"element_types": ["vector_types::vector::vector_types::Vector", "alloc::string::String"]
}
]
}
@@ -0,0 +1,584 @@
//! A port of `graph_craft::document`: document nodes and the flattening passes of `Compiler::compile`.
use super::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
use super::types::Type;
use super::{Builtins, CompileMetadata, ContextModification, NodeId, PASSTHROUGH, VALUE_NODE};
use crate::workload::Reflection;
use rustc_hash::FxHashMap;
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
fn merge_ids(a: NodeId, b: NodeId) -> NodeId {
let mut hasher = DefaultHasher::new();
a.hash(&mut hasher);
b.hash(&mut hasher);
NodeId(hasher.finish())
}
/// Stands in for `generate_uuid`, which draws from a random source.
fn generate_node_id() -> NodeId {
thread_local! {
static STATE: std::cell::Cell<u64> = const { std::cell::Cell::new(0x9E37_79B9_7F4A_7C15) };
}
STATE.with(|state| {
let mut x = state.get();
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
state.set(x);
NodeId(x)
})
}
#[derive(Debug, PartialEq)]
pub enum ValueKind {
/// A document value, represented by its exported cache hash and serialized size.
Document {
size: usize,
},
None,
NodeIdPath(Vec<NodeId>),
SourceId(u64),
ContextModification(ContextModification),
}
#[derive(Debug, PartialEq)]
pub struct ValueData {
pub ty: Type,
pub kind: ValueKind,
}
/// A port of `MemoHash<TaggedValue>`: the value behind an `Arc` with its cache hash computed once.
#[derive(Clone, Debug)]
pub struct MemoValue {
pub hash: u64,
pub value: Arc<ValueData>,
}
impl PartialEq for MemoValue {
fn eq(&self, other: &Self) -> bool {
self.value == other.value
}
}
impl MemoValue {
pub fn new(data: ValueData) -> Self {
let mut hasher = DefaultHasher::new();
std::mem::discriminant(&data.kind).hash(&mut hasher);
match &data.kind {
ValueKind::Document { size } => size.hash(&mut hasher),
ValueKind::None => {}
ValueKind::NodeIdPath(path) => path.hash(&mut hasher),
ValueKind::SourceId(source) => source.hash(&mut hasher),
ValueKind::ContextModification(modification) => modification.hash(&mut hasher),
}
Self {
hash: hasher.finish(),
value: Arc::new(data),
}
}
pub fn with_hash(data: ValueData, hash: u64) -> Self {
Self { hash, value: Arc::new(data) }
}
pub fn ty(&self) -> Type {
self.value.ty.clone()
}
pub fn source_id(&self) -> Option<u64> {
match self.value.kind {
ValueKind::SourceId(source) => Some(source),
_ => None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum NodeInput {
Node { node_id: NodeId, output_index: usize },
Value { value: MemoValue, exposed: bool },
Import { import_type: Type, import_index: usize },
Scope(Cow<'static, str>),
Reflection(Reflection),
}
impl NodeInput {
pub fn node(node_id: NodeId, output_index: usize) -> Self {
Self::Node { node_id, output_index }
}
fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId) {
if let NodeInput::Node { node_id, .. } = self {
*node_id = f(*node_id)
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct OriginalLocation {
pub path: Option<Vec<NodeId>>,
pub dependants: Vec<Vec<NodeId>>,
pub auto_convert_index: Option<usize>,
}
#[derive(Clone, Debug, PartialEq)]
pub enum DocumentNodeImplementation {
Network(NodeNetwork),
ProtoNode(Cow<'static, str>),
Extract,
}
impl DocumentNodeImplementation {
fn output_count(&self) -> usize {
match self {
DocumentNodeImplementation::Network(network) => network.exports.len(),
_ => 1,
}
}
fn is_proto_node(&self, identifier: &str) -> bool {
matches!(self, DocumentNodeImplementation::ProtoNode(proto) if proto == identifier)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct DocumentNode {
pub inputs: Vec<NodeInput>,
pub call_argument: Type,
pub implementation: DocumentNodeImplementation,
pub visible: bool,
pub skip_deduplication: bool,
pub compile_metadata: Option<CompileMetadata>,
pub original_location: OriginalLocation,
}
impl Default for DocumentNode {
fn default() -> Self {
Self {
inputs: Vec::new(),
call_argument: Type::context(),
implementation: DocumentNodeImplementation::ProtoNode(Cow::Borrowed(PASSTHROUGH)),
visible: true,
skip_deduplication: false,
compile_metadata: None,
original_location: OriginalLocation::default(),
}
}
}
impl DocumentNode {
fn populate_first_network_input(&mut self, node_id: NodeId, output_index: usize, offset: usize) {
let (index, _) = self.inputs.iter().enumerate().nth(offset).expect("network input should exist at the offset");
self.inputs[index] = NodeInput::Node { node_id, output_index };
}
fn resolve_proto_node(self) -> ProtoNode {
let DocumentNodeImplementation::ProtoNode(identifier) = self.implementation else {
unreachable!("tried to resolve a node that was not flattened");
};
assert!(!self.inputs.iter().any(|input| matches!(input, NodeInput::Import { .. })), "received non-resolved input");
let mut construction_args = ConstructionArgs::Nodes(vec![]);
if let &[NodeInput::Value { ref value, .. }] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Value(value.clone());
}
if let ConstructionArgs::Nodes(nodes) = &mut construction_args {
nodes.extend(self.inputs.iter().map(|input| match input {
NodeInput::Node { node_id, .. } => *node_id,
_ => unreachable!(),
}));
}
ProtoNode {
identifier,
call_argument: self.call_argument,
construction_args,
original_location: self.original_location,
skip_deduplication: self.skip_deduplication,
compile_metadata: self.compile_metadata.unwrap_or_default(),
upstream_context_features: 0,
}
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NodeNetwork {
pub exports: Vec<NodeInput>,
pub nodes: FxHashMap<NodeId, DocumentNode>,
pub scope_injections: FxHashMap<String, (NodeId, Type)>,
pub generated: bool,
}
struct ScopeChain<'a> {
scopes: &'a FxHashMap<String, (NodeId, Type)>,
parent: Option<&'a ScopeChain<'a>>,
}
enum ScopeChainLookup<'a> {
Current(&'a NodeId, &'a Type),
Parent(&'a NodeId, &'a Type),
None,
}
impl ScopeChain<'_> {
fn lookup(&self, key: &str) -> ScopeChainLookup<'_> {
self.scopes
.get(key)
.map(|(id, ty)| ScopeChainLookup::Current(id, ty))
.or_else(|| {
self.parent.and_then(|parent| match parent.lookup(key) {
ScopeChainLookup::Current(id, ty) | ScopeChainLookup::Parent(id, ty) => Some(ScopeChainLookup::Parent(id, ty)),
ScopeChainLookup::None => None,
})
})
.unwrap_or(ScopeChainLookup::None)
}
}
impl NodeNetwork {
pub fn resolve_scope_inputs(&mut self) {
let mut leftover = Vec::new();
self.resolve_scope_inputs_impl(None, &mut leftover);
assert!(leftover.is_empty(), "Unresolved scope keys at top level: {leftover:?}");
}
fn resolve_scope_inputs_impl(&mut self, parent: Option<&ScopeChain<'_>>, network_inputs: &mut Vec<NodeInput>) {
let scope_chain = ScopeChain {
scopes: &self.scope_injections,
parent,
};
for node in self.nodes.values_mut() {
let DocumentNodeImplementation::Network(network) = &mut node.implementation else { continue };
network.resolve_scope_inputs_impl(Some(&scope_chain), &mut node.inputs);
}
let mut key_to_index: FxHashMap<Cow<'static, str>, usize> = FxHashMap::default();
for node in self.nodes.values_mut() {
for input in node.inputs.iter_mut() {
let NodeInput::Scope(key) = input else { continue };
*input = match scope_chain.lookup(key) {
ScopeChainLookup::Current(node_id, _) => NodeInput::node(*node_id, 0),
ScopeChainLookup::Parent(_, ty) => {
let import_index = *key_to_index.entry(key.clone()).or_insert_with(|| {
let index = network_inputs.len();
network_inputs.push(NodeInput::Scope(key.clone()));
index
});
NodeInput::Import {
import_type: ty.clone(),
import_index,
}
}
ScopeChainLookup::None => panic!("Scope key `{key}` not found in any ancestor scope_injections"),
};
}
}
}
fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId + Copy) {
self.exports.iter_mut().for_each(|output| output.map_ids(f));
self.scope_injections.values_mut().for_each(|(id, _)| *id = f(*id));
let nodes = std::mem::take(&mut self.nodes);
self.nodes = nodes
.into_iter()
.map(|(id, mut node)| {
node.inputs.iter_mut().for_each(|input| input.map_ids(f));
node.original_location.dependants.iter_mut().for_each(|dependants| dependants.iter_mut().for_each(|id| *id = f(*id)));
(f(id), node)
})
.collect();
}
pub fn generate_node_paths(&mut self, prefix: &[NodeId]) {
for (node_id, node) in &mut self.nodes {
let mut new_path = prefix.to_vec();
if !self.generated {
new_path.push(*node_id);
}
if let DocumentNodeImplementation::Network(network) = &mut node.implementation {
network.generate_node_paths(new_path.as_slice());
}
if node.original_location.path.is_none() {
node.original_location.path = Some(new_path);
node.original_location.dependants = (0..node.implementation.output_count()).map(|_| Vec::new()).collect();
}
}
}
pub fn populate_dependants(&mut self) {
let mut dependency_changes = Vec::new();
for (node_id, node) in &mut self.nodes {
let len = node.original_location.dependants.len();
node.original_location.dependants.extend(vec![vec![]; node.implementation.output_count().max(len) - len]);
for input in &node.inputs {
if let NodeInput::Node { node_id: dependency_id, output_index } = input {
dependency_changes.push((*dependency_id, *output_index, *node_id));
}
}
}
for (dependency_id, output_index, node_id) in dependency_changes {
let node = self.nodes.get_mut(&dependency_id).expect("Encountered invalid node id");
let len = node.original_location.dependants.len();
node.original_location.dependants.extend(vec![vec![]; (output_index + 1).max(len) - len]);
node.original_location.dependants[output_index].push(node_id);
}
}
fn replace_node_inputs(&mut self, node_id: NodeId, old_input: (NodeId, usize), new_input: (NodeId, usize)) {
let Some(node) = self.nodes.get_mut(&node_id) else { return };
for input in node.inputs.iter_mut() {
if let NodeInput::Node { node_id: input_id, output_index } = input
&& (*input_id, *output_index) == old_input
{
(*input_id, *output_index) = new_input;
}
}
}
fn replace_network_outputs(&mut self, old_output: &NodeInput, new_output: &NodeInput) {
for output in self.exports.iter_mut() {
if *output == *old_output {
*output = new_output.clone();
}
}
}
pub fn flatten(&mut self, node_id: NodeId, builtins: &Builtins) {
let Some((id, mut node)) = self.nodes.remove_entry(&node_id) else { return };
if !node.visible && !node.implementation.is_proto_node(PASSTHROUGH) {
node.implementation = DocumentNodeImplementation::ProtoNode(Cow::Borrowed(PASSTHROUGH));
if node.inputs.is_empty() {
node.inputs.push(NodeInput::Value {
value: MemoValue::new(ValueData {
ty: Type::unit(),
kind: ValueKind::None,
}),
exposed: false,
});
}
let removed_inputs = node.inputs.split_off(1);
for removed_input in removed_inputs {
if let NodeInput::Node { node_id, output_index } = removed_input
&& let Some(former_dependency) = self.nodes.get_mut(&node_id)
&& !node.inputs.iter().any(|input| matches!(input, NodeInput::Node { node_id: other, .. } if *other == node_id))
{
former_dependency.original_location.dependants[output_index].retain(|&dependant| dependant != id);
}
}
let path = node.original_location.path.clone().unwrap_or_default();
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, id, builtins);
node.call_argument = Type::unit();
self.nodes.insert(id, node);
return;
}
let path = node.original_location.path.clone().unwrap_or_default();
if !node.implementation.is_proto_node(VALUE_NODE) {
Self::replace_value_inputs_with_nodes(&mut node.inputs, &mut self.nodes, &path, id, builtins);
}
let DocumentNodeImplementation::Network(mut inner_network) = node.implementation else {
assert!(!self.nodes.contains_key(&id), "Trying to insert a node into the network caused an id conflict");
self.nodes.insert(id, node);
return;
};
Self::replace_value_inputs_with_nodes(
&mut inner_network.exports,
&mut inner_network.nodes,
node.original_location.path.as_ref().unwrap_or(&vec![]),
id,
builtins,
);
inner_network.map_ids(|inner_id| merge_ids(id, inner_id));
inner_network.populate_dependants();
let new_nodes = inner_network.nodes.keys().cloned().collect::<Vec<_>>();
for (key, value) in inner_network.scope_injections.into_iter() {
self.scope_injections.entry(key).or_insert(value);
}
for (nested_node_id, mut nested_node) in inner_network.nodes.into_iter() {
for (nested_input_index, nested_input) in nested_node.clone().inputs.iter().enumerate() {
let NodeInput::Import { import_index, .. } = nested_input else { continue };
let parent_input = node.inputs.get(*import_index).expect("Import index of network node implementation should always exist");
match *parent_input {
NodeInput::Node { node_id, output_index } => {
nested_node.populate_first_network_input(node_id, output_index, nested_input_index);
let input_node = self.nodes.get_mut(&node_id).expect("Unable to find input node");
input_node.original_location.dependants[output_index].push(nested_node_id);
}
NodeInput::Import { import_index, .. } => {
let parent_input_index = import_index;
let Some(NodeInput::Import { import_index, .. }) = nested_node.inputs.get_mut(nested_input_index) else {
continue;
};
*import_index = parent_input_index;
}
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => unreachable!("Should have been resolved before flattening"),
}
}
self.nodes.insert(nested_node_id, nested_node);
}
for parent_input in &node.inputs {
if let NodeInput::Node { node_id, output_index } = *parent_input
&& let Some(input_node) = self.nodes.get_mut(&node_id)
{
input_node.original_location.dependants[output_index].retain(|&dependant| dependant != id);
}
}
self.replace_node_with_its_exports(id, &node.original_location, &inner_network.exports);
for node_id in new_nodes {
self.flatten(node_id, builtins);
}
}
fn replace_node_with_its_exports(&mut self, id: NodeId, original_location: &OriginalLocation, exports: &[NodeInput]) {
for (i, export) in exports.iter().enumerate() {
if let NodeInput::Node { node_id, output_index } = &export {
for dependants in &original_location.dependants {
for dependant in dependants {
self.replace_node_inputs(*dependant, (id, i), (*node_id, *output_index));
}
}
if let Some(new_output_node) = self.nodes.get_mut(node_id) {
for dependant in &original_location.dependants[i] {
new_output_node.original_location.dependants[*output_index].push(*dependant);
}
new_output_node.original_location.dependants[*output_index].retain(|&dependant| dependant != id);
}
}
self.replace_network_outputs(&NodeInput::node(id, i), export);
}
}
#[inline(never)]
fn replace_value_inputs_with_nodes(inputs: &mut [NodeInput], collection: &mut FxHashMap<NodeId, DocumentNode>, path: &[NodeId], id: NodeId, builtins: &Builtins) {
for export in inputs {
let previous_export = std::mem::replace(
export,
NodeInput::Import {
import_type: Type::unit(),
import_index: 0,
},
);
let (value, exposed) = match previous_export {
NodeInput::Value { value, exposed } => (value, exposed),
NodeInput::Reflection(Reflection::DocumentNodePath) => (
MemoValue::new(ValueData {
ty: builtins.node_id_path.clone(),
kind: ValueKind::NodeIdPath(path.to_vec()),
}),
false,
),
NodeInput::Reflection(Reflection::SourceId) => {
let mut hasher = rustc_hash::FxHasher::default();
path.hash(&mut hasher);
let data = ValueData {
ty: builtins.source_id.clone(),
kind: ValueKind::SourceId(hasher.finish()),
};
(MemoValue::new(data), false)
}
previous_export => {
*export = previous_export;
continue;
}
};
let value_node_id = generate_node_id();
let merged_node_id = merge_ids(id, value_node_id);
let mut original_location = OriginalLocation {
path: Some(path.to_vec()),
dependants: vec![vec![id]],
..Default::default()
};
if let Some(path) = &mut original_location.path {
path.push(value_node_id);
}
collection.insert(
merged_node_id,
DocumentNode {
inputs: vec![NodeInput::Value { value, exposed }],
implementation: DocumentNodeImplementation::ProtoNode(Cow::Borrowed(VALUE_NODE)),
original_location,
..Default::default()
},
);
*export = NodeInput::node(merged_node_id, 0);
}
}
fn remove_passthrough_node(&mut self, passthrough_id: NodeId) {
let node = self.nodes.remove(&passthrough_id).expect("Passthrough node should exist");
assert_eq!(node.inputs.len(), 1, "Passthrough node has more than one input");
if let NodeInput::Node {
node_id: upstream_node_id,
output_index: upstream_output_index,
} = node.inputs[0]
&& let Some(upstream_node) = self.nodes.get_mut(&upstream_node_id)
{
let dependants_of_upstream = &mut upstream_node.original_location.dependants[upstream_output_index];
dependants_of_upstream.extend(node.original_location.dependants[0].iter().copied());
dependants_of_upstream.retain(|&dependant| dependant != passthrough_id);
}
for node_input in self.exports.iter_mut() {
if matches!(node_input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) {
*node_input = node.inputs[0].clone();
}
}
for &dependant_id in &node.original_location.dependants[0] {
let Some(dependant_node) = self.nodes.get_mut(&dependant_id) else { continue };
for input in dependant_node.inputs.iter_mut() {
if matches!(input, NodeInput::Node { node_id, .. } if *node_id == passthrough_id) {
*input = node.inputs[0].clone();
}
}
}
}
pub fn remove_all_passthrough_nodes(&mut self) {
let passthrough_nodes = self
.nodes
.iter()
.filter(|(_, node)| node.implementation.is_proto_node(PASSTHROUGH))
.map(|(id, _)| *id)
.collect::<Vec<_>>();
for id in passthrough_nodes {
self.remove_passthrough_node(id);
}
}
pub fn into_proto_network(self) -> ProtoNetwork {
let nodes: Vec<_> = self.nodes.into_iter().map(|(id, node)| (id, node.resolve_proto_node())).collect();
let [NodeInput::Node { node_id, .. }] = self.exports.as_slice() else {
panic!("The spike only handles networks with a single node export");
};
ProtoNetwork {
inputs: Vec::new(),
output: *node_id,
nodes,
}
}
}
@@ -0,0 +1,175 @@
//! A port of `interpreted_executor::dynamic_executor` with mock nodes standing in for the real node constructors.
use super::NodeId;
use super::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
use super::types::Type;
use super::typing::{Registry, TypingContext};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub trait MockNode: Send + Sync {
fn input_count(&self) -> usize;
}
pub type SharedNode = Arc<dyn MockNode>;
/// Stands in for the boxed downcast wrapper each registry constructor puts around an input.
struct DowncastInput(#[expect(dead_code, reason = "the mock only models the allocation, it never evaluates")] SharedNode);
struct ConstructedNode {
inputs: Vec<Box<DowncastInput>>,
}
impl MockNode for ConstructedNode {
fn input_count(&self) -> usize {
self.inputs.len()
}
}
struct ValueNode(#[expect(dead_code, reason = "the mock only models the allocation, it never evaluates")] super::document::MemoValue);
impl MockNode for ValueNode {
fn input_count(&self) -> usize {
0
}
}
/// Stands in for `ObservedNode`, which wraps every node with a slot for the last evaluated context.
struct ObservedNode {
node: Box<dyn MockNode>,
_last_context: Mutex<Option<Arc<()>>>,
}
impl MockNode for ObservedNode {
fn input_count(&self) -> usize {
self.node.input_count()
}
}
pub type NodeConstructor = fn(Vec<SharedNode>) -> Box<dyn MockNode>;
pub fn construct(inputs: Vec<SharedNode>) -> Box<dyn MockNode> {
Box::new(ConstructedNode {
inputs: inputs.into_iter().map(|input| Box::new(DowncastInput(input))).collect(),
})
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NodeTypes {
pub inputs: Vec<Type>,
pub output: Type,
}
type Path = Box<[NodeId]>;
#[derive(Default)]
pub struct BorrowTree {
nodes: HashMap<NodeId, (SharedNode, Path, Box<[NodeId]>)>,
source_map: HashMap<Path, (NodeId, NodeTypes)>,
context_features: HashMap<NodeId, u32>,
}
impl BorrowTree {
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<Self, String> {
let mut tree = BorrowTree::default();
for (id, node) in proto_network.nodes {
tree.push_node(id, node, typing_context)?
}
Ok(tree)
}
pub fn len(&self) -> usize {
self.nodes.len()
}
fn update_source_map(&mut self, id: NodeId, typing_context: &TypingContext, proto_node: &ProtoNode) -> bool {
let Some(node_io) = typing_context.type_of(id) else { return false };
let inputs = [&node_io.call_argument].into_iter().chain(&node_io.inputs).cloned().collect();
let node_path = proto_node.original_location.path.as_ref().unwrap_or(const { &vec![] });
let entry = self.source_map.entry(node_path.to_vec().into()).or_default();
let update = (
id,
NodeTypes {
inputs,
output: node_io.return_value.clone(),
},
);
let modified = *entry != update;
*entry = update;
modified
}
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), String> {
self.update_source_map(id, typing_context, &proto_node);
self.context_features.insert(id, proto_node.upstream_context_features);
let path: Path = proto_node.original_location.path.clone().unwrap_or_default().into();
let observe = |node: Box<dyn MockNode>| -> SharedNode {
Arc::new(ObservedNode {
node,
_last_context: Mutex::new(None),
})
};
match &proto_node.construction_args {
ConstructionArgs::Value(value) => {
let node = observe(Box::new(ValueNode(value.clone())));
self.nodes.insert(id, (node, path, Box::default()));
}
ConstructionArgs::Nodes(ids) => {
let ids = ids.to_vec();
let mut construction_nodes: Vec<SharedNode> = ids.iter().map(|node| self.nodes.get(node).unwrap().0.clone()).collect();
if let Some(promotions) = typing_context.promotions(id) {
for (argument_index, promotion) in promotions {
let adapter_constructor = typing_context.adapter_constructor(&promotion.adapter_identifier()).ok_or("No promotion adapter constructor")?;
let adapter = adapter_constructor(vec![construction_nodes[*argument_index].clone()]);
construction_nodes[*argument_index] = Arc::from(adapter);
}
}
let constructor = typing_context.constructor(id).ok_or("No constructor")?;
let node = observe(constructor(construction_nodes));
self.nodes.insert(id, (node, path, ids.into()));
}
}
Ok(())
}
}
pub struct DynamicExecutor<'a> {
pub tree: BorrowTree,
pub output: NodeId,
pub typing_context: TypingContext<'a>,
pub sources: Vec<u64>,
}
impl<'a> DynamicExecutor<'a> {
pub fn new(proto_network: ProtoNetwork, registry: &'a Registry) -> Result<Self, String> {
let mut typing_context = TypingContext::new(registry);
typing_context.update(&proto_network)?;
let output = proto_network.output;
let sources = proto_network
.nodes
.iter()
.filter_map(|(_, node)| match &node.construction_args {
ConstructionArgs::Value(value) => value.source_id(),
_ => None,
})
.collect();
let tree = BorrowTree::new(proto_network, &typing_context)?;
Ok(Self {
tree,
output,
typing_context,
sources,
})
}
pub fn output_type(&self) -> Option<Type> {
self.typing_context.type_of(self.output).map(|node_io| node_io.return_value.clone())
}
}
@@ -0,0 +1,246 @@
//! A faithful port of Graphite's current compilation pipeline: preprocessing, `Compiler::compile`, and `DynamicExecutor::new`.
pub mod document;
pub mod executor;
pub mod preprocess;
pub mod proto;
pub mod types;
pub mod typing;
use crate::workload;
use document::{DocumentNode, DocumentNodeImplementation, MemoValue, NodeInput, NodeNetwork, OriginalLocation, ValueData, ValueKind};
use executor::DynamicExecutor;
use preprocess::{Preprocessor, Substitution};
use proto::ProtoNetwork;
use std::borrow::Cow;
use std::collections::BTreeSet;
use types::{NodeIOTypes, Type, TypeNames};
use typing::Registry;
pub const PASSTHROUGH: &str = "graphene_core::ops::PassthroughNode";
pub const VALUE_NODE: &str = "core_types::value::ClonedNode";
pub const MEMOIZE: &str = "graphene_core::memo::MemoizeNode";
pub const CONTEXT_MODIFICATION: &str = "graphene_core::context_modification::ContextModificationNode";
pub const FOOTPRINT: u32 = 1 << 0;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(pub u64);
pub type CompileMetadata = workload::CompileMetadata;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct ContextModification {
pub features: u32,
pub sources: BTreeSet<u64>,
}
/// Types of the values the compiler synthesizes itself.
pub struct Builtins {
pub node_id_path: Type,
pub source_id: Type,
pub context_modification: Type,
}
pub struct Baseline {
pub registry: Registry,
pub preprocessor: Preprocessor,
pub builtins: Builtins,
/// Analyzes each node's context dependencies once rather than once per path reaching it, as Graphite does since #4834.
pub memoize_context_analysis: bool,
names: TypeNames,
}
impl Baseline {
pub fn load() -> Self {
let mut names = TypeNames::default();
let mut item = |name: &str| Type::Item(Box::new(names.convert(&workload::Type::Concrete(name.to_string()))));
let builtins = Builtins {
node_id_path: item("core_types::list::NodeIdPath"),
source_id: item("core_types::runtime::SourceId"),
context_modification: item("core_types::context::ContextModification"),
};
let registry = workload::load_registry()
.into_iter()
.map(|entry| {
let implementations = entry
.implementations
.iter()
.map(|signature| {
let node_io = NodeIOTypes::new(
names.convert(&signature.call_argument),
names.convert(&signature.output),
signature.inputs.iter().map(|input| names.convert(input)).collect(),
);
(node_io, executor::construct as executor::NodeConstructor)
})
.collect();
(Cow::Borrowed(names.leak(&entry.identifier)), implementations)
})
.collect();
let tables = workload::load_preprocessor_tables();
let mut converter = Converter {
names: &mut names,
from_code: true,
entries: Default::default(),
};
let substitutions = tables
.substitutions
.iter()
.map(|substitution| {
let node = converter.node(&substitution.node);
(
converter.identifier(&substitution.identifier),
Substitution {
node,
wrapped_node_id: NodeId(substitution.wrapped_node_id),
},
)
})
.collect();
let inject_scopes = tables
.inject_scopes
.iter()
.map(|scope| (converter.identifier(&scope.identifier), (converter.node(&scope.template), converter.ty(&scope.ty))))
.collect();
let compile_metadata = tables.compile_metadata.iter().map(|entry| (converter.identifier(&entry.identifier), entry.metadata)).collect();
Self {
registry,
preprocessor: Preprocessor {
substitutions,
inject_scopes,
compile_metadata,
},
builtins,
memoize_context_analysis: true,
names,
}
}
/// The demo's scoped network as Graphite deserializes it from the document.
pub fn load_network(&mut self, name: &str) -> NodeNetwork {
self.convert_network(&workload::load_network(name))
}
pub fn convert_network(&mut self, network: &workload::Network) -> NodeNetwork {
Converter {
names: &mut self.names,
from_code: false,
entries: Default::default(),
}
.network(network)
}
pub fn preprocess(&self, mut network: NodeNetwork) -> NodeNetwork {
self.preprocessor.preprocess(&mut network);
network
}
pub fn compile(&self, mut network: NodeNetwork) -> Result<ProtoNetwork, String> {
network.resolve_scope_inputs();
network.generate_node_paths(&[]);
let node_ids = network.nodes.keys().copied().collect::<Vec<_>>();
network.populate_dependants();
for id in node_ids {
network.flatten(id, &self.builtins);
}
network.remove_all_passthrough_nodes();
let mut proto_network = network.into_proto_network();
proto_network.insert_context_nullification_nodes(&self.builtins, self.memoize_context_analysis)?;
if proto_network.non_constant_inputs() != 0 {
return Err("An input requiring a constant is not fed by a value".to_string());
}
std::hint::black_box(proto_network.footprint_invariance_violations());
proto_network.generate_stable_node_ids();
Ok(proto_network)
}
pub fn build_executor(&self, proto_network: ProtoNetwork) -> Result<DynamicExecutor<'_>, String> {
DynamicExecutor::new(proto_network, &self.registry)
}
pub fn run(&self, network: NodeNetwork) -> Result<DynamicExecutor<'_>, String> {
self.build_executor(self.compile(self.preprocess(network))?)
}
}
/// Converts the exported workload schema into the baseline's runtime structures.
struct Converter<'a> {
names: &'a mut TypeNames,
/// Whether the structures were built in Graphite's code (borrowed names, `TypeId`s) rather than deserialized from a document.
from_code: bool,
/// The definitions table entries, which this port of the inline compiler inlines wherever a node names one.
entries: std::collections::HashMap<u64, workload::Network>,
}
impl Converter<'_> {
fn identifier(&mut self, identifier: &str) -> Cow<'static, str> {
match self.from_code {
true => Cow::Borrowed(self.names.leak(identifier)),
false => Cow::Owned(identifier.to_string()),
}
}
fn ty(&mut self, ty: &workload::Type) -> Type {
match self.from_code {
true => self.names.convert(ty),
false => TypeNames::convert_deserialized(ty),
}
}
fn input(&mut self, input: &workload::Input) -> NodeInput {
match input {
workload::Input::Node(reference) => NodeInput::node(NodeId(reference.node), reference.output),
workload::Input::Value(value) => {
let data = ValueData {
ty: self.names.convert(&value.ty),
kind: ValueKind::Document { size: value.size },
};
NodeInput::Value {
value: MemoValue::with_hash(data, value.hash),
exposed: value.exposed,
}
}
workload::Input::Import(import) => NodeInput::Import {
import_type: self.ty(&import.ty),
import_index: import.index,
},
workload::Input::Scope(key) => NodeInput::Scope(self.identifier(key)),
workload::Input::Reflection(reflection) => NodeInput::Reflection(*reflection),
}
}
fn node(&mut self, node: &workload::Node) -> DocumentNode {
let implementation = match &node.implementation {
workload::Implementation::Network(network) => DocumentNodeImplementation::Network(self.network(network)),
workload::Implementation::Definition(id) => {
let entry = self.entries.get(id).unwrap_or_else(|| panic!("Definition {id} is missing from the definitions table")).clone();
DocumentNodeImplementation::Network(self.network(&entry))
}
workload::Implementation::Proto(identifier) => DocumentNodeImplementation::ProtoNode(self.identifier(identifier)),
workload::Implementation::Extract => DocumentNodeImplementation::Extract,
};
DocumentNode {
inputs: node.inputs.iter().map(|input| self.input(input)).collect(),
call_argument: self.ty(&node.call_argument),
implementation,
visible: node.visible,
skip_deduplication: node.skip_deduplication,
compile_metadata: node.compile_metadata,
original_location: OriginalLocation::default(),
}
}
fn network(&mut self, network: &workload::Network) -> NodeNetwork {
self.entries.extend(network.definitions.iter().cloned());
NodeNetwork {
exports: network.exports.iter().map(|input| self.input(input)).collect(),
nodes: network.nodes.iter().map(|(id, node)| (NodeId(*id), self.node(node))).collect(),
scope_injections: network.scope_injections.iter().map(|(key, id, ty)| (key.clone(), (NodeId(*id), self.ty(ty)))).collect(),
generated: network.generated,
}
}
}
@@ -0,0 +1,82 @@
//! A port of the `preprocessor` crate's `Preprocessor::preprocess`, driven by the exported substitution tables.
use super::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork, ValueKind};
use super::types::Type;
use super::{CompileMetadata, NodeId};
use std::borrow::Cow;
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
pub struct Substitution {
pub node: DocumentNode,
pub wrapped_node_id: NodeId,
}
#[derive(Default)]
pub struct Preprocessor {
pub substitutions: HashMap<Cow<'static, str>, Substitution>,
pub inject_scopes: HashMap<Cow<'static, str>, (DocumentNode, Type)>,
pub compile_metadata: HashMap<Cow<'static, str>, CompileMetadata>,
}
impl Preprocessor {
pub fn preprocess(&self, network: &mut NodeNetwork) {
self.insert_inject_scopes(network);
Self::check_for_producer_inputs(network);
self.expand_network(network);
}
fn insert_inject_scopes(&self, network: &mut NodeNetwork) {
for (identifier, (template, ty)) in self.inject_scopes.iter() {
let mut hasher = DefaultHasher::new();
identifier.as_ref().hash(&mut hasher);
let producer_id = NodeId(hasher.finish());
network.nodes.insert(producer_id, template.clone());
network.scope_injections.insert(identifier.to_string(), (producer_id, ty.clone()));
}
}
/// Walks the network like `replace_inputs_with_producer_nodes`. The exported documents contain no resource or curve values to replace.
fn check_for_producer_inputs(network: &mut NodeNetwork) {
for node in network.nodes.values_mut() {
if let DocumentNodeImplementation::Network(nested) = &mut node.implementation {
Self::check_for_producer_inputs(nested);
continue;
}
for input in node.inputs.iter_mut() {
let NodeInput::Value { value, .. } = input else { continue };
assert!(matches!(value.value.kind, ValueKind::Document { .. }), "Producer values are not supported by the spike");
}
}
}
fn expand_network(&self, network: &mut NodeNetwork) {
for node in network.nodes.values_mut() {
match &mut node.implementation {
DocumentNodeImplementation::Network(node_network) => self.expand_network(node_network),
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
let compile_metadata = node.compile_metadata.take().or_else(|| self.compile_metadata.get(proto_node_identifier).copied());
if let Some(Substitution { node: new_node, wrapped_node_id }) = self.substitutions.get(proto_node_identifier) {
while node.inputs.len() < new_node.inputs.len() {
node.inputs.push(new_node.inputs[node.inputs.len()].clone());
}
node.inputs.truncate(new_node.inputs.len());
node.implementation = new_node.implementation.clone();
if let DocumentNodeImplementation::Network(network) = &mut node.implementation
&& let Some(wrapped_node) = network.nodes.get_mut(wrapped_node_id)
{
wrapped_node.compile_metadata = compile_metadata;
}
} else {
node.compile_metadata = compile_metadata;
}
}
DocumentNodeImplementation::Extract => (),
}
}
}
}
@@ -0,0 +1,398 @@
//! A port of `graph_craft::proto`: proto networks, context nullification, and stable node IDs.
use super::document::{MemoValue, OriginalLocation, ValueData, ValueKind};
use super::types::Type;
use super::{Builtins, CompileMetadata, ContextModification, FOOTPRINT, MEMOIZE, NodeId, PASSTHROUGH, VALUE_NODE};
use rustc_hash::FxHashMap;
use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap};
use std::hash::{Hash, Hasher};
#[derive(Clone, Debug, PartialEq)]
pub enum ConstructionArgs {
Value(MemoValue),
Nodes(Vec<NodeId>),
}
impl ConstructionArgs {
fn cache_hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
Self::Nodes(nodes) => {
for node in nodes {
node.hash(state);
}
}
Self::Value(value) => value.hash.hash(state),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ProtoNode {
pub construction_args: ConstructionArgs,
pub call_argument: Type,
pub identifier: Cow<'static, str>,
pub original_location: OriginalLocation,
pub skip_deduplication: bool,
pub compile_metadata: CompileMetadata,
pub upstream_context_features: u32,
}
impl Default for ProtoNode {
fn default() -> Self {
Self {
identifier: Cow::Borrowed(PASSTHROUGH),
construction_args: ConstructionArgs::Nodes(Vec::new()),
call_argument: Type::unit(),
original_location: OriginalLocation::default(),
skip_deduplication: false,
compile_metadata: CompileMetadata::default(),
upstream_context_features: 0,
}
}
}
impl ProtoNode {
fn stable_node_id(&self) -> NodeId {
let mut hasher = rustc_hash::FxHasher::default();
self.identifier.as_ref().hash(&mut hasher);
self.construction_args.cache_hash(&mut hasher);
if self.skip_deduplication {
self.original_location.path.hash(&mut hasher);
}
std::mem::discriminant(&self.call_argument).hash(&mut hasher);
self.call_argument.hash(&mut hasher);
NodeId(hasher.finish())
}
fn map_ids(&mut self, f: impl Fn(NodeId) -> NodeId) {
if let ConstructionArgs::Nodes(ids) = &mut self.construction_args {
ids.iter_mut().for_each(|id| *id = f(*id));
}
}
}
#[derive(Clone, Copy, PartialEq)]
enum NodeState {
Unvisited,
Visiting,
Visited,
}
#[derive(Clone, Debug, Default)]
pub struct ProtoNetwork {
pub inputs: Vec<NodeId>,
pub output: NodeId,
pub nodes: Vec<(NodeId, ProtoNode)>,
}
impl ProtoNetwork {
fn collect_outwards_edges(&self) -> HashMap<NodeId, Vec<NodeId>> {
let mut edges: HashMap<NodeId, Vec<NodeId>> = self.nodes.iter().map(|(id, _)| (*id, Vec::new())).collect();
for (id, node) in &self.nodes {
if let ConstructionArgs::Nodes(ref_nodes) = &node.construction_args {
for ref_id in ref_nodes {
edges.entry(*ref_id).or_default().push(*id)
}
}
}
edges
}
pub fn generate_stable_node_ids(&mut self) {
let outwards_edges = self.collect_outwards_edges();
for index in 0..self.nodes.len() {
let stable_id = self.nodes[index].1.stable_node_id();
self.replace_node_id(&outwards_edges, NodeId(index as u64), stable_id);
self.nodes[index].0 = stable_id;
}
}
fn collect_inwards_edges_with_mapping(&self) -> (Vec<Vec<usize>>, FxHashMap<NodeId, usize>) {
let id_map: FxHashMap<_, _> = self.nodes.iter().enumerate().map(|(index, (id, _))| (*id, index)).collect();
let mut inwards_edges = vec![Vec::new(); self.nodes.len()];
for (node_id, node) in &self.nodes {
let node_index = id_map[node_id];
if let ConstructionArgs::Nodes(ref_nodes) = &node.construction_args {
for ref_id in ref_nodes {
inwards_edges[node_index].push(id_map[ref_id]);
}
}
}
(inwards_edges, id_map)
}
/// With `memoize`, each node's context analysis runs once instead of once per path reaching it, which Graphite currently does.
pub fn insert_context_nullification_nodes(&mut self, builtins: &Builtins, memoize: bool) -> Result<(), String> {
self.reorder_ids()?;
let mut analyzed = memoize.then(FxHashMap::default);
let (output_dependencies, _) = self.find_context_dependencies(self.output, builtins, &mut analyzed);
self.nodes[self.output.0 as usize].1.upstream_context_features = output_dependencies.features;
self.reorder_ids()?;
Ok(())
}
pub fn non_constant_inputs(&self) -> usize {
self.nodes
.iter()
.filter(|(_, node)| node.compile_metadata.constant_inputs != 0)
.map(|(_, node)| {
let inputs = match &node.construction_args {
ConstructionArgs::Nodes(inputs) => inputs.as_slice(),
_ => &[],
};
inputs
.iter()
.enumerate()
.filter(|&(index, &input)| index < 64 && node.compile_metadata.constant_inputs & (1 << index) != 0 && !self.resolves_to_value(input))
.count()
})
.sum()
}
fn resolves_to_value(&self, mut id: NodeId) -> bool {
loop {
let Some((_, node)) = self.nodes.get(id.0 as usize) else { return false };
match &node.construction_args {
ConstructionArgs::Value(_) => return true,
ConstructionArgs::Nodes(inputs) if node.compile_metadata.forwards_input => match inputs.first() {
Some(&input) => id = input,
None => return false,
},
_ => return false,
}
}
}
pub fn footprint_invariance_violations(&self) -> usize {
self.nodes
.iter()
.filter(|(_, node)| node.compile_metadata.footprint_invariant && node.upstream_context_features & FOOTPRINT != 0)
.count()
}
fn insert_context_nullification_node(&mut self, node_id: NodeId, context_dependencies: ContextModification, builtins: &Builtins) -> NodeId {
let (_, node) = &self.nodes[node_id.0 as usize];
let mut path = node.original_location.path.clone();
if let Some(path) = path.as_mut() {
path.push(NodeId(10))
}
let features = context_dependencies.features;
let forwarding = CompileMetadata {
forwards_input: true,
..Default::default()
};
let memoize_node_id = NodeId(self.nodes.len() as u64);
self.nodes.push((
memoize_node_id,
ProtoNode {
construction_args: ConstructionArgs::Nodes(vec![node_id]),
call_argument: Type::context(),
identifier: Cow::Borrowed(MEMOIZE),
original_location: OriginalLocation {
path: path.clone(),
..Default::default()
},
compile_metadata: forwarding,
upstream_context_features: features,
..Default::default()
},
));
let nullification_value_node_id = NodeId(self.nodes.len() as u64);
let value = ValueData {
ty: builtins.context_modification.clone(),
kind: ValueKind::ContextModification(context_dependencies),
};
self.nodes.push((
nullification_value_node_id,
ProtoNode {
construction_args: ConstructionArgs::Value(MemoValue::new(value)),
call_argument: Type::context(),
identifier: Cow::Borrowed(VALUE_NODE),
original_location: OriginalLocation {
path: path.clone(),
..Default::default()
},
..Default::default()
},
));
let nullification_node_id = NodeId(self.nodes.len() as u64);
self.nodes.push((
nullification_node_id,
ProtoNode {
construction_args: ConstructionArgs::Nodes(vec![memoize_node_id, nullification_value_node_id]),
call_argument: Type::context(),
identifier: Cow::Borrowed(super::CONTEXT_MODIFICATION),
original_location: OriginalLocation { path, ..Default::default() },
compile_metadata: forwarding,
upstream_context_features: features,
..Default::default()
},
));
nullification_node_id
}
fn find_context_dependencies(&mut self, id: NodeId, builtins: &Builtins, analyzed: &mut Option<FxHashMap<NodeId, (ContextModification, Option<NodeId>)>>) -> (ContextModification, Option<NodeId>) {
if let Some(analyzed) = analyzed
&& let Some(result) = analyzed.get(&id)
{
return result.clone();
}
let result = self.analyze_context_dependencies(id, builtins, analyzed);
if let Some(analyzed) = analyzed {
analyzed.insert(id, result.clone());
}
result
}
fn analyze_context_dependencies(
&mut self,
id: NodeId,
builtins: &Builtins,
analyzed: &mut Option<FxHashMap<NodeId, (ContextModification, Option<NodeId>)>>,
) -> (ContextModification, Option<NodeId>) {
let mut branch_dependencies = Vec::new();
let mut combined = ContextModification::default();
let node_index = id.0 as usize;
let dependencies = self.nodes[node_index].1.compile_metadata;
let mut inputs = match &self.nodes[node_index].1.construction_args {
ConstructionArgs::Nodes(items) => items.clone(),
ConstructionArgs::Value(value) if let Some(source) = value.source_id() => {
return (
ContextModification {
features: dependencies.extract,
sources: BTreeSet::from([source]),
},
Some(id),
);
}
ConstructionArgs::Value(_) => {
return (
ContextModification {
features: dependencies.extract,
sources: BTreeSet::new(),
},
Some(id),
);
}
};
for &node in &inputs {
let branch = self.find_context_dependencies(node, builtins, analyzed);
self.nodes[node.0 as usize].1.upstream_context_features = branch.0.features;
combined.features |= branch.0.features;
combined.sources.extend(&branch.0.sources);
branch_dependencies.push(branch);
}
let features = (combined.features & !dependencies.inject) | dependencies.extract;
let introduces_new_dependencies = combined.features & features != features;
for (child_node, (child_dependencies, new_id)) in inputs.iter_mut().zip(branch_dependencies) {
if let Some(new_id) = new_id {
*child_node = new_id;
} else if introduces_new_dependencies || child_dependencies != combined {
*child_node = self.insert_context_nullification_node(*child_node, child_dependencies, builtins);
}
}
self.nodes[node_index].1.construction_args = ConstructionArgs::Nodes(inputs);
let net_injections = dependencies.inject & !dependencies.extract;
let remaining_from_children = combined.features & !net_injections;
let supplies_existing_dependencies = combined.features & !remaining_from_children != 0;
let new_dependencies = ContextModification { features, sources: combined.sources };
let mut new_id = None;
if supplies_existing_dependencies {
new_id = Some(self.insert_context_nullification_node(id, new_dependencies.clone(), builtins));
}
(new_dependencies, new_id)
}
fn replace_node_id(&mut self, outwards_edges: &HashMap<NodeId, Vec<NodeId>>, node_id: NodeId, replacement_node_id: NodeId) {
if let Some(referring_nodes) = outwards_edges.get(&node_id) {
for &referring_node_id in referring_nodes {
let (_, referring_node) = &mut self.nodes[referring_node_id.0 as usize];
referring_node.map_ids(|id| if id == node_id { replacement_node_id } else { id })
}
}
if self.output == node_id {
self.output = replacement_node_id;
}
self.inputs.iter_mut().for_each(|id| {
if *id == node_id {
*id = replacement_node_id;
}
});
}
fn topological_sort(&self) -> Result<Vec<NodeId>, String> {
let (inwards_edges, id_map) = self.collect_inwards_edges_with_mapping();
let mut sorted = Vec::with_capacity(self.nodes.len());
let mut stack = vec![id_map[&self.output]];
let mut state = vec![NodeState::Unvisited; self.nodes.len()];
while let Some(&node_index) = stack.last() {
match state[node_index] {
NodeState::Unvisited => {
state[node_index] = NodeState::Visiting;
for &dependency_index in inwards_edges[node_index].iter().rev() {
match state[dependency_index] {
NodeState::Visiting => return Err(format!("Cycle detected involving node {:?}", self.nodes[dependency_index].0)),
NodeState::Unvisited => stack.push(dependency_index),
NodeState::Visited => {}
}
}
}
NodeState::Visiting => {
stack.pop();
state[node_index] = NodeState::Visited;
sorted.push(NodeId(node_index as u64));
}
NodeState::Visited => {
stack.pop();
}
}
}
Ok(sorted)
}
fn reorder_ids(&mut self) -> Result<(), String> {
let order = self.topological_sort()?;
let new_positions: FxHashMap<_, _> = order.iter().enumerate().map(|(position, id)| (self.nodes[id.0 as usize].0, position)).collect();
let mut new_nodes = Vec::with_capacity(order.len());
for (index, &id) in order.iter().enumerate() {
let mut node = std::mem::take(&mut self.nodes[id.0 as usize].1);
node.map_ids(|id| NodeId(*new_positions.get(&id).expect("node not found in lookup table") as u64));
new_nodes.push((NodeId(index as u64), node));
}
self.nodes = new_nodes;
self.inputs = self.inputs.iter().filter_map(|id| new_positions.get(id).map(|x| NodeId(*x as u64))).collect();
self.output = NodeId(*new_positions.get(&self.output).unwrap() as u64);
Ok(())
}
}
@@ -0,0 +1,206 @@
//! A port of `core_types::Type` with the same layout and clone behavior, so type movement costs what it does in Graphite.
use crate::workload;
use rustc_hash::FxHashMap;
use std::borrow::Cow;
use std::hash::{Hash, Hasher};
pub const UNIT_NAME: &str = "()";
pub const CONTEXT_NAME: &str = "core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>";
const UNIT_ID: u128 = 0;
const CONTEXT_ID: u128 = 1;
#[derive(Clone, Debug)]
pub struct TypeDescriptor {
pub id: Option<u128>,
pub name: Cow<'static, str>,
pub size: usize,
pub align: usize,
}
impl Hash for TypeDescriptor {
fn hash<H: Hasher>(&self, state: &mut H) {
self.name.hash(state);
}
}
impl PartialEq for TypeDescriptor {
fn eq(&self, other: &Self) -> bool {
match (self.id, other.id) {
(Some(id), Some(other_id)) => id == other_id,
_ => self.name == other.name,
}
}
}
impl Eq for TypeDescriptor {}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Type {
Generic(Cow<'static, str>),
Concrete(TypeDescriptor),
Fn(Box<Type>, Box<Type>),
Item(Box<Type>),
List(Box<Type>),
}
impl Default for Type {
fn default() -> Self {
Type::unit()
}
}
impl Type {
fn concrete(id: u128, name: &'static str) -> Self {
Type::Concrete(TypeDescriptor {
id: Some(id),
name: Cow::Borrowed(name),
size: 0,
align: 0,
})
}
pub fn unit() -> Self {
Type::concrete(UNIT_ID, UNIT_NAME)
}
pub fn context() -> Self {
Type::concrete(CONTEXT_ID, CONTEXT_NAME)
}
pub fn function(input: &Type, output: &Type) -> Type {
Type::Fn(Box::new(input.clone()), Box::new(output.clone()))
}
pub fn nested_type(&self) -> &Type {
match self {
Self::Fn(_, output) => output.nested_type(),
_ => self,
}
}
pub fn replace_nested(&mut self, f: impl Fn(&Type) -> Option<Type>) -> Option<Type> {
if let Some(replacement) = f(self) {
return Some(std::mem::replace(self, replacement));
}
match self {
Self::Fn(_, output) => output.replace_nested(f),
_ => None,
}
}
pub fn fn_input(&self) -> Option<&Type> {
match self {
Type::Fn(input, _) => Some(input),
_ => None,
}
}
pub fn fn_output(&self) -> Option<&Type> {
match self {
Type::Fn(_, output) => Some(output),
_ => None,
}
}
pub fn bundle_element_name(&self) -> Option<&str> {
let Type::Item(element) = self else { return None };
let Type::Concrete(descriptor) = element.as_ref() else { return None };
descriptor.name.strip_prefix("core_types::list::Bundle<")?.strip_suffix('>')
}
pub fn identifier_name(&self) -> String {
match self {
Type::Generic(name) => name.to_string(),
Type::Concrete(descriptor) => simplify_identifier_name(&descriptor.name),
Type::Fn(call_argument, return_value) => format!("{} called with {}", return_value.identifier_name(), call_argument.identifier_name()),
Type::Item(element) => element.identifier_name(),
Type::List(element) => format!("{}[]", element.identifier_name()),
}
}
}
fn simplify_identifier_name(name: &str) -> String {
name.split('<')
.map(|path| path.split(',').map(|path| path.split("::").last().unwrap_or(path)).collect::<Vec<_>>().join(","))
.collect::<Vec<_>>()
.join("<")
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct NodeIOTypes {
pub call_argument: Type,
pub return_value: Type,
pub inputs: Vec<Type>,
}
impl NodeIOTypes {
pub fn new(call_argument: Type, return_value: Type, inputs: Vec<Type>) -> Self {
Self { call_argument, return_value, inputs }
}
pub fn ty(&self) -> Type {
Type::Fn(Box::new(self.call_argument.clone()), Box::new(self.return_value.clone()))
}
}
/// Interns concrete type names into `'static` strings with stable IDs, standing in for Rust's `TypeId`.
pub struct TypeNames {
names: FxHashMap<String, (&'static str, u128)>,
}
impl Default for TypeNames {
fn default() -> Self {
let names = [(UNIT_NAME, UNIT_ID), (CONTEXT_NAME, CONTEXT_ID)]
.into_iter()
.map(|(name, id)| (name.to_string(), (name, id)))
.collect();
Self { names }
}
}
impl TypeNames {
/// Converts a type the way Graphite builds it in code: a `TypeId` and a borrowed name.
pub fn convert(&mut self, ty: &workload::Type) -> Type {
match ty {
workload::Type::Generic(name) => Type::Generic(Cow::Borrowed(self.leak(name))),
workload::Type::Concrete(name) => {
let (name, id) = self.intern(name);
Type::concrete(id, name)
}
workload::Type::Fn(input, output) => Type::Fn(Box::new(self.convert(input)), Box::new(self.convert(output))),
workload::Type::Item(element) => Type::Item(Box::new(self.convert(element))),
workload::Type::List(element) => Type::List(Box::new(self.convert(element))),
}
}
/// Converts a type the way Graphite deserializes it from a document: no `TypeId` and an owned name.
pub fn convert_deserialized(ty: &workload::Type) -> Type {
match ty {
workload::Type::Generic(name) => Type::Generic(Cow::Owned(name.clone())),
workload::Type::Concrete(name) => Type::Concrete(TypeDescriptor {
id: None,
name: Cow::Owned(name.clone()),
size: 0,
align: 0,
}),
workload::Type::Fn(input, output) => Type::Fn(Box::new(Self::convert_deserialized(input)), Box::new(Self::convert_deserialized(output))),
workload::Type::Item(element) => Type::Item(Box::new(Self::convert_deserialized(element))),
workload::Type::List(element) => Type::List(Box::new(Self::convert_deserialized(element))),
}
}
fn intern(&mut self, name: &str) -> (&'static str, u128) {
if let Some(&entry) = self.names.get(name) {
return entry;
}
let entry = (self.leak(name), self.names.len() as u128);
self.names.insert(name.to_string(), entry);
entry
}
/// Leaks the string so types hold `Cow::Borrowed` names like Graphite's `TypeId`-derived descriptors.
pub fn leak(&mut self, name: &str) -> &'static str {
Box::leak(name.to_string().into_boxed_str())
}
}
@@ -0,0 +1,267 @@
//! A port of `graph_craft::proto::TypingContext`.
use super::NodeId;
use super::executor::NodeConstructor;
use super::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
use super::types::{NodeIOTypes, Type};
use std::borrow::Cow;
use std::collections::HashMap;
pub type Registry = HashMap<Cow<'static, str>, HashMap<NodeIOTypes, NodeConstructor>>;
fn valid_type(from: &Type, to: &Type) -> bool {
match (from, to) {
(Type::Concrete(type1), Type::Concrete(type2)) => type1 == type2,
(Type::Fn(in1, out1), Type::Fn(in2, out2)) => valid_type(out2, out1) && valid_type(in1, in2),
(Type::Item(element1), Type::Item(element2)) => valid_type(element1, element2),
(Type::List(element1), Type::List(element2)) => valid_type(element1, element2),
(Type::Generic(_), _) | (_, Type::Generic(_)) => true,
_ => false,
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Promotion {
ItemToList(Type),
Bundle(Type),
Unbundle(Type),
}
type PromotionVariant = fn(Type) -> Promotion;
impl Promotion {
fn between(from: &Type, to: &Type) -> Option<Self> {
Self::variant_between(from, to).map(|(variant, element)| variant(element.clone()))
}
fn variant_between<'a>(from: &'a Type, to: &'a Type) -> Option<(PromotionVariant, &'a Type)> {
fn concrete_name(ty: &Type) -> Option<&str> {
match ty {
Type::Concrete(descriptor) => Some(&descriptor.name),
_ => None,
}
}
match (from, to) {
(Type::Item(from_element), Type::List(element)) if valid_type(from_element, element) => Some((Self::ItemToList, element)),
(Type::List(element), Type::Item(_)) if to.bundle_element_name().is_some_and(|name| Some(name) == concrete_name(element)) => Some((Self::Bundle, element)),
(Type::Item(_), Type::List(element)) if from.bundle_element_name().is_some_and(|name| Some(name) == concrete_name(element)) => Some((Self::Unbundle, element)),
_ => None,
}
}
pub fn adapter_identifier(&self) -> String {
let (adapter_name, element) = match self {
Self::ItemToList(element) => ("graphene_core::ops::ItemToListNode", element),
Self::Bundle(element) => ("graphene_core::ops::BundleNode", element),
Self::Unbundle(element) => ("graphene_core::ops::UnbundleNode", element),
};
format!("{adapter_name}<{}>", element.identifier_name())
}
}
pub struct TypingContext<'a> {
lookup: &'a Registry,
inferred: HashMap<NodeId, NodeIOTypes>,
constructor: HashMap<NodeId, NodeConstructor>,
promotions: HashMap<NodeId, Vec<(usize, Promotion)>>,
}
impl<'a> TypingContext<'a> {
pub fn new(lookup: &'a Registry) -> Self {
Self {
lookup,
inferred: HashMap::new(),
constructor: HashMap::new(),
promotions: HashMap::new(),
}
}
pub fn update(&mut self, network: &ProtoNetwork) -> Result<(), String> {
for (id, node) in network.nodes.iter() {
self.infer(*id, node)?;
}
Ok(())
}
pub fn promotions(&self, node_id: NodeId) -> Option<&Vec<(usize, Promotion)>> {
self.promotions.get(&node_id)
}
pub fn adapter_constructor(&self, identifier: &str) -> Option<NodeConstructor> {
self.lookup.get(identifier).and_then(|implementations| implementations.values().next().copied())
}
pub fn constructor(&self, node_id: NodeId) -> Option<NodeConstructor> {
self.constructor.get(&node_id).copied()
}
pub fn type_of(&self, node_id: NodeId) -> Option<&NodeIOTypes> {
self.inferred.get(&node_id)
}
pub fn infer(&mut self, node_id: NodeId, node: &ProtoNode) -> Result<NodeIOTypes, String> {
if let Some(inferred) = self.inferred.get(&node_id) {
return Ok(inferred.clone());
}
let inputs = match node.construction_args {
ConstructionArgs::Value(ref value) => {
let types = NodeIOTypes::new(Type::context(), value.ty(), vec![]);
self.inferred.insert(node_id, types.clone());
return Ok(types);
}
ConstructionArgs::Nodes(ref nodes) => nodes
.iter()
.map(|id| {
self.inferred
.get(id)
.ok_or_else(|| format!("Input node {id:?} is not present in the typing context"))
.map(|node| node.ty())
})
.collect::<Result<Vec<Type>, String>>()?,
};
let call_argument = &node.call_argument;
let implementations = self.lookup.get(&node.identifier).ok_or_else(|| format!("No implementations found for {}", node.identifier))?;
if let Some(index) = inputs.iter().position(|p| matches!(p, Type::Fn(_, b) if matches!(b.as_ref(), Type::Generic(_)))) {
return Err(format!("Generic inputs should not exist but found at {index}"));
}
let valid_output_types = implementations
.keys()
.filter(|node_io| valid_type(&node_io.call_argument, call_argument) && inputs.iter().zip(node_io.inputs.iter()).all(|(p1, p2)| valid_type(p1, p2)))
.collect::<Vec<_>>();
let substitution_results = valid_output_types
.iter()
.map(|node_io| {
let generics_lookup: Result<HashMap<_, _>, _> = collect_generics(node_io)
.iter()
.map(|generic| check_generic(node_io, call_argument, &inputs, generic).map(|x| (generic.to_string(), x)))
.collect();
generics_lookup.map(|generics_lookup| {
let original_node_io = (*node_io).clone();
let mut new_node_io = original_node_io.clone();
replace_generics(&mut new_node_io, &generics_lookup);
(new_node_io, original_node_io)
})
})
.collect::<Vec<_>>();
let valid_implementations = substitution_results.iter().filter_map(|result| result.as_ref().ok()).collect::<Vec<_>>();
match valid_implementations.as_slice() {
[] => {
fn promotable_adapter(from: &Type, to: &Type) -> Option<Promotion> {
let (Type::Fn(from_input, from_output), Type::Fn(to_input, to_output)) = (from, to) else {
return None;
};
if !valid_type(from_input, to_input) {
return None;
}
Promotion::between(from_output.nested_type(), to_output.nested_type())
}
let mut promotable_matches = implementations
.keys()
.filter(|node_io| collect_generics(node_io).is_empty() && valid_type(&node_io.call_argument, call_argument) && inputs.len() == node_io.inputs.len())
.filter_map(|node_io| {
let mut required_promotions = Vec::new();
for (index, (provided, expected)) in inputs.iter().zip(node_io.inputs.iter()).enumerate() {
if valid_type(provided, expected) {
continue;
}
required_promotions.push((index, promotable_adapter(provided, expected)?));
}
Some((node_io, required_promotions))
})
.collect::<Vec<_>>();
promotable_matches.sort_by_key(|(_, required_promotions)| required_promotions.len());
let minimum_promotions = promotable_matches.first().map(|(_, required_promotions)| required_promotions.len());
let tied_at_minimum = promotable_matches
.iter()
.take_while(|(_, required_promotions)| Some(required_promotions.len()) == minimum_promotions)
.count();
if tied_at_minimum == 1 {
let (node_io, required_promotions) = promotable_matches.remove(0);
let node_io = node_io.clone();
self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, implementations[&node_io]);
self.promotions.insert(node_id, required_promotions);
return Ok(node_io);
}
Err(format!("Invalid implementations for {} with inputs {inputs:?}", node.identifier))
}
[(node_io, original_node_io)] => {
let node_io = node_io.clone();
self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, implementations[original_node_io]);
Ok(node_io)
}
[first, second] => {
if first.0.call_argument != second.0.call_argument {
for (node_io, original_node_io) in [first, second] {
if node_io.call_argument != Type::unit() {
continue;
}
self.inferred.insert(node_id, node_io.clone());
self.constructor.insert(node_id, implementations[original_node_io]);
return Ok(node_io.clone());
}
}
Err(format!("Multiple implementations found for {}", node.identifier))
}
_ => Err(format!("Multiple implementations found for {}", node.identifier)),
}
}
}
fn collect_generics(types: &NodeIOTypes) -> Vec<Cow<'static, str>> {
let inputs = [&types.call_argument].into_iter().chain(types.inputs.iter().map(|x| x.nested_type()));
let mut generics = inputs
.filter_map(|t| match t {
Type::Generic(out) => Some(out.clone()),
_ => None,
})
.collect::<Vec<_>>();
if let Type::Generic(out) = &types.return_value {
generics.push(out.clone());
}
generics.dedup();
generics
}
fn check_generic(types: &NodeIOTypes, input: &Type, parameters: &[Type], generic: &str) -> Result<Type, String> {
let inputs = [(Some(&types.call_argument), Some(input))]
.into_iter()
.chain(types.inputs.iter().map(|x| x.fn_input()).zip(parameters.iter().map(|x| x.fn_input())))
.chain(types.inputs.iter().map(|x| x.fn_output()).zip(parameters.iter().map(|x| x.fn_output())));
let concrete_inputs = inputs.filter(|(node_input, _)| matches!(node_input, Some(Type::Generic(input)) if generic == input));
let mut outputs = concrete_inputs.flat_map(|(_, out)| out);
let out_ty = outputs
.next()
.ok_or_else(|| format!("Generic output type {generic} is not dependent on input {input:?} or parameters {parameters:?}"))?;
if outputs.any(|ty| ty != out_ty) {
return Err(format!("Generic output type {generic} is dependent on multiple inputs or parameters"));
}
Ok(out_ty.clone())
}
fn replace_generics(types: &mut NodeIOTypes, lookup: &HashMap<String, Type>) {
let replace = |ty: &Type| {
let Type::Generic(ident) = ty else { return None };
lookup.get(ident.as_ref()).cloned()
};
types.call_argument.replace_nested(replace);
types.return_value.replace_nested(replace);
for input in &mut types.inputs {
input.replace_nested(replace);
}
}
@@ -0,0 +1,90 @@
//! Times incremental compiles after typical edits against cold compiles. Run with `cargo run --release --bin incremental`.
use compiler_spike::lean::document::{Implementation, Input};
use compiler_spike::lean::{Document, Lean};
use compiler_spike::synthetic::rectangle_layers;
use compiler_spike::workload::{Network, load_network};
use std::time::{Duration, Instant};
const TRANSFORM: &str = "transform_nodes::transform_nodes::TransformNode";
const RUNS: usize = 30;
fn transform_values(lean: &Lean, document: &Document) -> Vec<(u32, u32, usize)> {
let mut values = Vec::new();
for (definition_index, definition) in document.definitions.iter().enumerate() {
for (local, node) in definition.nodes.iter().enumerate() {
let Implementation::Proto(identifier) = node.implementation else { continue };
if lean.identifier_name(identifier) != TRANSFORM {
continue;
}
for (input, value) in definition.node_inputs(node).iter().enumerate() {
if matches!(value, Input::Value(_)) {
values.push((definition_index as u32, local as u32, input));
}
}
}
}
values
}
fn median(mut samples: Vec<Duration>) -> Duration {
samples.sort();
samples[samples.len() / 2]
}
fn report(name: &str, network: &Network) {
let mut lean = Lean::load();
let mut document = lean.convert_document(network);
let cold = median((0..RUNS).map(|_| time(|| lean.compile(&document).map(|compiled| compiled.output))).collect());
let warmup = time(|| lean.compile_incremental(&mut document).map(|compiled| compiled.output));
let unchanged = median((0..RUNS).map(|_| time(|| lean.compile_incremental(&mut document).map(|compiled| compiled.output))).collect());
let unchanged_statistics = lean.instance_statistics();
println!(
"\n{name}: cold {cold:.3?}, first incremental {warmup:.3?}, unchanged recompile {unchanged:.3?} ({} instances reused)",
unchanged_statistics.instance_hits
);
println!(
"{:>14} {:>12} {:>9} {:>9} {:>12} {:>9}",
"edited value", "incremental", "reused", "rebuilt", "store nodes", "recomputed"
);
let values = transform_values(&lean, &document);
if values.is_empty() {
return;
}
let mut next_value = 0xED17_u64;
for (label, index) in [("bottom layer", 0), ("middle layer", values.len() / 2), ("top layer", values.len() - 1)] {
let (definition, local, input) = values[index];
let samples: Vec<_> = (0..RUNS)
.map(|_| {
next_value += 1;
document.set_value(definition, local, input, next_value);
time(|| lean.compile_incremental(&mut document).map(|compiled| compiled.output))
})
.collect();
let statistics = lean.instance_statistics();
println!(
"{label:>14} {:>12.3?} {:>9} {:>9} {:>12} {:>9}",
median(samples),
statistics.instance_hits,
statistics.instance_misses,
lean.ir.len(),
statistics.nodes_invalidated
);
}
}
fn time<T>(compile: impl FnOnce() -> Result<T, String>) -> Duration {
let start = Instant::now();
std::hint::black_box(compile().expect("the workload should compile"));
start.elapsed()
}
fn main() {
report("red-dress", &load_network("red-dress"));
for layers in [200, 1600] {
report(&format!("rectangles({layers})"), &rectangle_layers(layers));
}
}
@@ -0,0 +1,171 @@
//! Sweeps the synthetic workloads over growing sizes and prints per-stage timings, exposing superlinear stages.
//! Run with `cargo run --release --bin scaling [--memoize | --lean] [shape] [--sizes=a,b,c]`.
//! For `--lean`, the stages are document conversion, lowering, and executor construction, and nodes are unique IR nodes.
use compiler_spike::baseline::Baseline;
use compiler_spike::lean::Lean;
use compiler_spike::lean::executor::Executor;
use compiler_spike::synthetic;
use compiler_spike::workload::Network;
use std::hint::black_box;
use std::time::{Duration, Instant};
/// Sizes stop growing once a single pipeline run exceeds this.
const RUN_LIMIT: Duration = Duration::from_secs(2);
const MEASUREMENT_BUDGET: Duration = Duration::from_millis(300);
enum Pipeline {
Baseline(Baseline),
Lean(Lean),
}
struct Timings {
nodes: usize,
stages: [Duration; 3],
}
fn median(mut samples: Vec<Duration>) -> Duration {
samples.sort();
samples[samples.len() / 2]
}
/// Times one run of the pipeline's three stages, returning the stage durations and the node count.
fn run(pipeline: &mut Pipeline, workload: &Network) -> ([Duration; 3], usize) {
match pipeline {
Pipeline::Baseline(baseline) => {
let network = baseline.convert_network(workload);
let start = Instant::now();
let preprocessed = baseline.preprocess(network);
let preprocess = start.elapsed();
let start = Instant::now();
let proto_network = baseline.compile(preprocessed).expect("synthetic workloads should compile");
let compile = start.elapsed();
let nodes = proto_network.nodes.len();
let start = Instant::now();
let executor = baseline.build_executor(proto_network).expect("synthetic workloads should type check");
black_box(executor.tree.len());
([preprocess, compile, start.elapsed()], nodes)
}
Pipeline::Lean(lean) => {
let start = Instant::now();
let document = lean.convert_document(workload);
let conversion = start.elapsed();
let start = Instant::now();
let compiled = lean.compile(&document).expect("synthetic workloads should compile");
let lowering = start.elapsed();
let start = Instant::now();
black_box(Executor::new(&compiled).nodes.len());
([conversion, lowering, start.elapsed()], compiled.ir.len())
}
}
}
fn measure(pipeline: &mut Pipeline, workload: &Network) -> Timings {
let mut samples: [Vec<Duration>; 3] = Default::default();
let mut nodes = 0;
let started = Instant::now();
while samples[0].is_empty() || (started.elapsed() < MEASUREMENT_BUDGET && samples[0].len() < 50) {
let (stages, node_count) = run(pipeline, workload);
for (stage_samples, stage) in samples.iter_mut().zip(stages) {
stage_samples.push(stage);
}
nodes = node_count;
}
Timings { nodes, stages: samples.map(median) }
}
fn sweep(pipeline: &mut Pipeline, shape: &str, sizes: &[usize], generate: impl Fn(usize) -> Network) {
let stage_names = match pipeline {
Pipeline::Baseline(_) => ["preprocess", "compile", "executor"],
Pipeline::Lean(_) => ["conversion", "lowering", "executor"],
};
println!("\n{shape}");
println!(
"{:>8} {:>8} {:>8} {:>11} {:>11} {:>11} {:>11} {:>10} {:>9}",
"size", "document", "nodes", stage_names[0], stage_names[1], stage_names[2], "total", "ns/node", "ns/doc"
);
for &size in sizes {
let workload = generate(size);
let document_nodes = count_nodes(&workload);
let timings = measure(pipeline, &workload);
let [first, second, third] = timings.stages;
// Lean's document conversion stands in for a representation the editor would already hold, so it is excluded from the total
let total = match pipeline {
Pipeline::Baseline(_) => first + second + third,
Pipeline::Lean(_) => second + third,
};
println!(
"{size:>8} {document_nodes:>8} {:>8} {first:>11.3?} {second:>11.3?} {third:>11.3?} {total:>11.3?} {:>10.0} {:>9.0}",
timings.nodes,
total.as_nanos() as f64 / timings.nodes.max(1) as f64,
total.as_nanos() as f64 / document_nodes.max(1) as f64
);
if total > RUN_LIMIT {
println!("{:>8} (stopping: a run exceeded {RUN_LIMIT:?})", "");
break;
}
}
}
fn count_nodes(network: &Network) -> usize {
network
.nodes
.iter()
.map(|(_, node)| match &node.implementation {
compiler_spike::workload::Implementation::Network(inner) => 1 + count_nodes(inner),
_ => 1,
})
.sum()
}
fn main() {
let arguments: Vec<String> = std::env::args().skip(1).collect();
let memoize = arguments.iter().any(|argument| argument == "--memoize");
let filter = arguments.iter().find(|argument| !argument.starts_with("--"));
let selected = |shape: &str| filter.is_none_or(|filter| shape.starts_with(filter.as_str()));
let size_override: Option<Vec<usize>> = arguments
.iter()
.find_map(|argument| argument.strip_prefix("--sizes="))
.map(|sizes| sizes.split(',').map(|size| size.parse().expect("--sizes takes comma-separated numbers")).collect());
let sizes = |default: &'static [usize]| size_override.clone().unwrap_or_else(|| default.to_vec());
let mut baseline = match arguments.iter().any(|argument| argument == "--lean") {
true => Pipeline::Lean(Lean::load()),
false => {
let mut baseline = Baseline::load();
baseline.memoize_context_analysis = memoize;
Pipeline::Baseline(baseline)
}
};
if selected("rectangles") {
sweep(&mut baseline, "rectangles(layers)", &sizes(&[1, 10, 50, 100, 200, 400, 800, 1600]), synthetic::rectangle_layers);
}
if selected("chain") {
sweep(&mut baseline, "chain(length)", &sizes(&[100, 200, 400, 800, 1600, 3200, 6400]), synthetic::chain);
}
if selected("fan_out") {
sweep(&mut baseline, "fan_out(width)", &sizes(&[100, 200, 400, 800, 1600, 3200, 6400]), synthetic::fan_out);
}
if selected("lattice") {
sweep(&mut baseline, "lattice(width 8, depth)", &sizes(&[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]), |depth| {
synthetic::lattice(8, depth)
});
sweep(&mut baseline, "lattice(width, depth 4)", &sizes(&[8, 16, 32, 64, 128, 256, 512]), |width| synthetic::lattice(width, 4));
}
if selected("nesting") {
sweep(&mut baseline, "nesting(depth, chain 10)", &sizes(&[1, 2, 4, 8, 16, 32, 64, 128]), |depth| synthetic::nesting(depth, 10));
}
if selected("instances") {
sweep(&mut baseline, "instances(count, chain 20)", &sizes(&[10, 20, 40, 80, 160, 320]), |count| {
synthetic::instances(count, 20)
});
}
}
@@ -0,0 +1,38 @@
//! Node-local compile-time checks: inputs required to be constant, and footprint invariance.
use super::ir::NewNode;
const FOOTPRINT: u32 = 1 << 0;
#[derive(Default)]
pub struct Checks {
/// Indexed by IR node ID: whether the node's output is a value known at compile time.
pub resolves_to_value: Vec<bool>,
pub footprint_warnings: Vec<u32>,
}
impl Checks {
pub fn clear(&mut self) {
self.resolves_to_value.clear();
self.footprint_warnings.clear();
}
/// Checks a node about to be built and returns whether its output resolves to a compile-time value.
pub fn check(&self, node: &NewNode, inputs: &[u32]) -> Result<bool, String> {
let metadata = node.compile_metadata;
for (index, &input) in inputs.iter().enumerate() {
let constant = index < 64 && metadata.constant_inputs & (1 << index) != 0;
if constant && !self.resolves_to_value[input as usize] {
return Err("An input requiring a constant is not fed by a value".to_string());
}
}
Ok(node.value.is_some() || metadata.forwards_input && inputs.first().is_some_and(|&first| self.resolves_to_value[first as usize]))
}
/// Records a footprint warning for a footprint-invariant node whose upstream reads the footprint.
pub fn check_footprint(&mut self, id: u32, node: &NewNode, upstream_features: u32) {
if node.compile_metadata.footprint_invariant && upstream_features & FOOTPRINT != 0 {
self.footprint_warnings.push(id);
}
}
}
@@ -0,0 +1,475 @@
//! A structural Rust codegen backend: one `let` per reachable IR node in IR order, against stub node and type definitions
//! whose trait bounds make rustc check that every node's inputs have the types its selected implementation expects.
//!
//! Each stub node hashes its inputs' payloads with the context, so the emitted program also measures evaluation overhead.
use super::Lean;
use super::document::IdentifierId;
use super::types::{TypeData, TypeId};
use rustc_hash::FxHashMap;
use std::fmt::Write;
const MONOMORPHIC_RECURSION_LIMIT: u32 = 4096;
const PRELUDE: &str = "#![allow(dead_code, non_camel_case_types, unused_mut, unused_variables, clippy::all)]
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
pub type EvalContext = u64;
pub trait Payload {
fn payload(&self) -> u64;
fn from_payload(payload: u64) -> Self;
}
pub struct Item<T>(T);
pub struct List<T>(T);
pub struct Function<I, O>(O, PhantomData<I>);
impl<T: Payload> Payload for Item<T> {
fn payload(&self) -> u64 {
self.0.payload()
}
fn from_payload(payload: u64) -> Self {
Self(T::from_payload(payload))
}
}
impl<T: Payload> Payload for List<T> {
fn payload(&self) -> u64 {
self.0.payload()
}
fn from_payload(payload: u64) -> Self {
Self(T::from_payload(payload))
}
}
impl<I, O: Payload> Payload for Function<I, O> {
fn payload(&self) -> u64 {
self.0.payload()
}
fn from_payload(payload: u64) -> Self {
Self(O::from_payload(payload), PhantomData)
}
}
pub fn mix(hash: u64, value: u64) -> u64 {
(hash ^ value).wrapping_mul(0x9E37_79B9_7F4A_7C15).rotate_left(29)
}
pub struct Value<T>(u64, PhantomData<T>);
impl<T> Value<T> {
pub fn new(hash: u64) -> Self {
Self(hash, PhantomData)
}
}
";
const SYNC_PRELUDE: &str = "
pub trait Node {
type Output;
fn eval(&self, context: EvalContext) -> Self::Output;
}
impl<N: Node + ?Sized> Node for &N {
type Output = N::Output;
fn eval(&self, context: EvalContext) -> Self::Output {
(**self).eval(context)
}
}
impl<T: Payload> Node for Value<T> {
type Output = T;
fn eval(&self, _: EvalContext) -> T {
T::from_payload(self.0)
}
}
pub struct Erased<'a, O>(pub &'a dyn Node<Output = O>);
impl<O> Node for Erased<'_, O> {
type Output = O;
fn eval(&self, context: EvalContext) -> O {
self.0.eval(context)
}
}
pub fn evaluate<N: Node>(node: &N, context: EvalContext) -> u64
where
N::Output: Payload,
{
node.eval(context).payload()
}
pub fn assert_output<T, N: Node<Output = T>>(_: &N) {}
";
const ASYNC_PRELUDE: &str = "
pub trait Node {
type Output;
fn eval(&self, context: EvalContext) -> impl Future<Output = Self::Output>;
}
impl<N: Node + ?Sized> Node for &N {
type Output = N::Output;
fn eval(&self, context: EvalContext) -> impl Future<Output = Self::Output> {
(**self).eval(context)
}
}
impl<T: Payload> Node for Value<T> {
type Output = T;
fn eval(&self, _: EvalContext) -> impl Future<Output = T> {
std::future::ready(T::from_payload(self.0))
}
}
pub trait DynNode {
type Output;
fn eval_dyn(&self, context: EvalContext) -> Pin<Box<dyn Future<Output = Self::Output> + '_>>;
}
impl<N: Node> DynNode for N {
type Output = N::Output;
fn eval_dyn(&self, context: EvalContext) -> Pin<Box<dyn Future<Output = Self::Output> + '_>> {
Box::pin(self.eval(context))
}
}
pub struct Erased<'a, O>(pub &'a dyn DynNode<Output = O>);
impl<O> Node for Erased<'_, O> {
type Output = O;
fn eval(&self, context: EvalContext) -> impl Future<Output = O> {
self.0.eval_dyn(context)
}
}
pub fn block_on<F: Future>(future: F) -> F::Output {
let mut future = std::pin::pin!(future);
let mut task_context = std::task::Context::from_waker(std::task::Waker::noop());
loop {
if let std::task::Poll::Ready(output) = future.as_mut().poll(&mut task_context) {
return output;
}
}
}
pub fn evaluate<N: Node>(node: &N, context: EvalContext) -> u64
where
N::Output: Payload,
{
block_on(node.eval(context)).payload()
}
pub fn assert_output<T, N: Node<Output = T>>(_: &N) {}
";
const MAIN: &str = "
fn main() {
let iterations: u64 = std::env::args().nth(1).and_then(|argument| argument.parse().ok()).unwrap_or(1000);
run(iterations / 10 + 1);
let start = std::time::Instant::now();
let checksum = run(iterations);
let elapsed = start.elapsed();
println!(\"{} {checksum}\", elapsed.as_nanos() / iterations as u128);
}
";
/// Where node types are erased behind `&dyn Node<Output = T>`, which bounds how deeply node types nest.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Erasure {
Monomorphic,
/// At nodes with several consumers, and where a node type would nest deeper than `MAX_NESTING`.
Bounded,
Everywhere,
}
const MAX_NESTING: u32 = 32;
/// Graphite's nodes return futures, which erased nodes box like `DynFuture`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Evaluation {
Sync,
Async,
}
pub struct Emitted {
pub source: String,
pub statements: usize,
pub node_types: usize,
pub concrete_types: usize,
/// How many node evaluations one evaluation of the output performs, since nothing caches shared nodes.
pub evaluations_per_run: f64,
}
/// Generic implementations get one stub per specialization, since their input and output types vary between uses.
#[derive(PartialEq, Eq, Hash)]
struct Monomorphization {
identifier: IdentifierId,
implementation: u32,
specialization: Option<(TypeId, Box<[TypeId]>)>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Style {
Structs(Evaluation),
/// Generic over `impl Fn` inputs, so every IR node instantiates its implementation with flat function item types.
Functions,
/// Over `fn` pointer inputs, so every implementation is instantiated once and called indirectly.
FunctionPointers,
}
struct Emitter<'a> {
lean: &'a Lean,
style: Style,
rendered_types: FxHashMap<TypeId, String>,
type_definitions: String,
concrete_types: usize,
node_types: FxHashMap<Monomorphization, String>,
node_definitions: String,
}
fn evaluations_per_run(lean: &Lean, reachable: &[u32], output: u32) -> f64 {
let mut evaluations = vec![0_f64; lean.ir.len()];
evaluations[output as usize] = 1.;
for &id in reachable.iter().rev() {
for &input in lean.ir.inputs(id) {
evaluations[input as usize] += evaluations[id as usize];
}
}
reachable.iter().map(|&id| evaluations[id as usize]).sum()
}
/// Emits each IR node as a function calling its node implementation with its inputs' functions, evaluating synchronously.
pub fn emit_functions(lean: &Lean, output: u32, pointers: bool) -> Emitted {
let mut emitter = Emitter::new(lean, if pointers { Style::FunctionPointers } else { Style::Functions });
let reachable = lean.ir.reachable(output);
let mut functions = String::new();
for &id in &reachable {
let node = &lean.ir.nodes[id as usize];
let return_type = emitter.render(lean.typing.info[id as usize].return_type);
let body = match node.value {
Some(value) => format!("<{return_type}>::from_payload({:#x})", value.hash),
None => {
let node_type = emitter.node_type(id);
let arguments: Vec<String> = lean.ir.inputs(id).iter().map(|input| format!("n{input}")).collect();
format!("nodes::{node_type}(context, {})", arguments.join(", "))
}
};
writeln!(functions, "pub fn n{id}(context: EvalContext) -> {return_type} {{\n\t{body}\n}}\n").unwrap();
}
let mut source = String::with_capacity(PRELUDE.len() + emitter.type_definitions.len() + emitter.node_definitions.len() + functions.len() + 4096);
if !pointers {
writeln!(source, "#![recursion_limit = \"{MONOMORPHIC_RECURSION_LIMIT}\"]").unwrap();
}
source.push_str(PRELUDE);
write!(source, "\npub mod types {{\n\tuse super::Payload;\n\n{}}}\n", emitter.type_definitions).unwrap();
write!(source, "\npub mod nodes {{\n\tuse super::*;\n\n{}}}\n", emitter.node_definitions).unwrap();
write!(source, "\n{functions}").unwrap();
write!(
source,
"pub fn run(iterations: u64) -> u64 {{\n\tlet mut checksum = 0;\n\tfor iteration in 0..iterations {{\n\t\tchecksum ^= n{output}(std::hint::black_box(iteration)).payload();\n\t}}\n\tchecksum\n}}\n"
)
.unwrap();
source.push_str(MAIN);
Emitted {
source,
statements: reachable.len(),
node_types: emitter.node_types.len(),
concrete_types: emitter.concrete_types,
evaluations_per_run: evaluations_per_run(lean, &reachable, output),
}
}
pub fn emit(lean: &Lean, output: u32, erasure: Erasure, evaluation: Evaluation) -> Emitted {
let mut emitter = Emitter::new(lean, Style::Structs(evaluation));
let reachable = lean.ir.reachable(output);
let mut consumers = vec![0_u32; lean.ir.len()];
for &id in &reachable {
for &input in lean.ir.inputs(id) {
consumers[input as usize] += 1;
}
}
let mut nesting = vec![0_u32; lean.ir.len()];
let mut body = String::new();
for &id in &reachable {
let node = &lean.ir.nodes[id as usize];
nesting[id as usize] = 1 + lean.ir.inputs(id).iter().map(|&input| nesting[input as usize]).max().unwrap_or(0);
let expression = match node.value {
Some(value) => format!("Value::<{}>::new({:#x})", emitter.render(value.ty), value.hash),
None => {
let node_type = emitter.node_type(id);
let arguments: Vec<String> = lean.ir.inputs(id).iter().map(|input| format!("&n{input}")).collect();
format!("nodes::{node_type}::new({})", arguments.join(", "))
}
};
let erased = match erasure {
Erasure::Monomorphic => false,
Erasure::Bounded => consumers[id as usize] > 1 || nesting[id as usize] >= MAX_NESTING,
Erasure::Everywhere => true,
};
if erased {
nesting[id as usize] = 1;
let output = emitter.render(lean.typing.info[id as usize].return_type);
writeln!(body, "\tlet n{id}_node = {expression};\n\tlet n{id} = Erased::<{output}>(&n{id}_node);").unwrap();
} else {
writeln!(body, "\tlet n{id} = {expression};").unwrap();
}
}
let output_type = emitter.render(lean.typing.info[output as usize].return_type);
writeln!(body, "\tassert_output::<{output_type}, _>(&n{output});\n").unwrap();
writeln!(body, "\tlet mut checksum = 0;\n\tfor iteration in 0..iterations {{").unwrap();
writeln!(body, "\t\tchecksum ^= evaluate(&n{output}, std::hint::black_box(iteration));\n\t}}\n\tchecksum").unwrap();
let mut source = String::with_capacity(PRELUDE.len() + emitter.type_definitions.len() + emitter.node_definitions.len() + body.len() + 4096);
if erasure != Erasure::Everywhere {
writeln!(source, "#![recursion_limit = \"{MONOMORPHIC_RECURSION_LIMIT}\"]").unwrap();
}
source.push_str(PRELUDE);
source.push_str(match evaluation {
Evaluation::Sync => SYNC_PRELUDE,
Evaluation::Async => ASYNC_PRELUDE,
});
write!(source, "\npub mod types {{\n\tuse super::Payload;\n\n{}}}\n", emitter.type_definitions).unwrap();
write!(source, "\npub mod nodes {{\n\tuse super::*;\n\n{}}}\n", emitter.node_definitions).unwrap();
write!(source, "\npub fn run(iterations: u64) -> u64 {{\n{body}}}\n").unwrap();
source.push_str(MAIN);
Emitted {
source,
statements: reachable.len(),
node_types: emitter.node_types.len(),
concrete_types: emitter.concrete_types,
evaluations_per_run: evaluations_per_run(lean, &reachable, output),
}
}
impl<'a> Emitter<'a> {
fn new(lean: &'a Lean, style: Style) -> Self {
Self {
lean,
style,
rendered_types: FxHashMap::default(),
type_definitions: String::new(),
concrete_types: 0,
node_types: FxHashMap::default(),
node_definitions: String::new(),
}
}
fn render(&mut self, ty: TypeId) -> String {
if let Some(rendered) = self.rendered_types.get(&ty) {
return rendered.clone();
}
let rendered = match self.lean.typing.types.get(ty) {
TypeData::Concrete(_) | TypeData::Generic(_) => {
let name = self.lean.typing.types.concrete_name(ty).unwrap_or("unresolved generic");
let stub = format!("T{}", self.concrete_types);
writeln!(
self.type_definitions,
"\t#[doc = {name:?}]\n\tpub struct {stub}(u64);\n\timpl Payload for {stub} {{\n\t\tfn payload(&self) -> u64 {{\n\t\t\tself.0\n\t\t}}\n\t\tfn from_payload(payload: u64) -> Self {{\n\t\t\tSelf(payload)\n\t\t}}\n\t}}\n"
)
.unwrap();
self.concrete_types += 1;
format!("types::{stub}")
}
TypeData::Item(element) => format!("Item<{}>", self.render(element)),
TypeData::List(element) => format!("List<{}>", self.render(element)),
TypeData::Fn(input, output) => format!("Function<{}, {}>", self.render(input), self.render(output)),
};
self.rendered_types.insert(ty, rendered.clone());
rendered
}
fn node_type(&mut self, id: u32) -> String {
let (ir, typing) = (&self.lean.ir, &self.lean.typing);
let node = &ir.nodes[id as usize];
let info = typing.info[id as usize];
let signature = &typing.registry.implementations[&node.identifier][info.implementation as usize];
let generic = !signature.generics.is_empty();
let input_types: Box<[TypeId]> = if generic {
ir.inputs(id).iter().map(|&input| typing.info[input as usize].return_type).collect()
} else {
signature.inputs.iter().map(|&input| typing.types.nested(input)).collect()
};
let key = Monomorphization {
identifier: node.identifier,
implementation: info.implementation,
specialization: generic.then(|| (info.return_type, input_types.clone())),
};
if let Some(name) = self.node_types.get(&key) {
return name.clone();
}
let seed = self.node_types.len();
let sanitized: String = self.lean.identifier_name(node.identifier).chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }).collect();
let name = format!("{sanitized}_{seed}");
let output = self.render(info.return_type);
let bounds: Vec<String> = input_types.iter().enumerate().map(|(index, &ty)| format!("I{index}: Node<Output = {}>", self.render(ty))).collect();
let parameters: Vec<String> = (0..input_types.len()).map(|index| format!("I{index}")).collect();
let arguments: Vec<String> = (0..input_types.len()).map(|index| format!("i{index}: I{index}")).collect();
let fields: Vec<String> = (0..input_types.len()).map(|index| format!("i{index}")).collect();
let mut evaluation = format!("let mut hash = mix(context, {seed});");
for index in 0..input_types.len() {
match self.style {
Style::Structs(Evaluation::Sync) => write!(evaluation, " hash = mix(hash, self.{index}.eval(context).payload());").unwrap(),
Style::Structs(Evaluation::Async) => write!(evaluation, " hash = mix(hash, self.{index}.eval(context).await.payload());").unwrap(),
Style::Functions | Style::FunctionPointers => write!(evaluation, " hash = mix(hash, i{index}(context).payload());").unwrap(),
}
}
write!(evaluation, " <{output}>::from_payload(std::hint::black_box(hash))").unwrap();
let documentation = format!("\t#[doc = {:?}]", self.lean.identifier_name(node.identifier));
if matches!(self.style, Style::Functions | Style::FunctionPointers) {
let input_types: Vec<String> = input_types.iter().map(|&ty| self.render(ty)).collect();
let parameters: Vec<String> = input_types
.iter()
.enumerate()
.map(|(index, ty)| match self.style {
Style::FunctionPointers => format!("i{index}: fn(EvalContext) -> {ty}"),
_ => format!("i{index}: impl Fn(EvalContext) -> {ty}"),
})
.collect();
let parameters = std::iter::once("context: EvalContext".to_string()).chain(parameters).collect::<Vec<_>>().join(", ");
writeln!(self.node_definitions, "{documentation}\n\tpub fn {name}({parameters}) -> {output} {{\n\t\t{evaluation}\n\t}}\n").unwrap();
self.node_types.insert(key, name.clone());
return name;
}
let eval = match self.style {
Style::Structs(Evaluation::Async) => format!("fn eval(&self, context: EvalContext) -> impl Future<Output = Self::Output> {{ async move {{ {evaluation} }} }}"),
_ => format!("fn eval(&self, context: EvalContext) -> Self::Output {{ {evaluation} }}"),
};
let (bounds, parameters) = (bounds.join(", "), parameters.join(", "));
let definitions = &mut self.node_definitions;
writeln!(definitions, "{documentation}").unwrap();
writeln!(definitions, "\tpub struct {name}<{parameters}>({parameters});").unwrap();
writeln!(definitions, "\timpl<{bounds}> Node for {name}<{parameters}> {{\n\t\ttype Output = {output};\n\t\t{eval}\n\t}}").unwrap();
writeln!(
definitions,
"\timpl<{bounds}> {name}<{parameters}> {{\n\t\tpub fn new({}) -> Self {{\n\t\t\tSelf({})\n\t\t}}\n\t}}\n",
arguments.join(", "),
fields.join(", ")
)
.unwrap();
self.node_types.insert(key, name.clone());
name
}
}
@@ -0,0 +1,275 @@
//! Automatic conversions between data types through `Convert` and `ConvertAsync` implementations, chosen by a purity relation
//! instead of hardcoded in the compiler.
//!
//! A conversion from `A` to `B` is applied automatically when `A` is purer than `B` (data loses purity but never regains it by
//! discarding information, which needs an explicit node) or when both are representations of the same data, like CPU and GPU
//! rasters. At most one conversion is applied per input. Among the implementations a node could use after converting, the one
//! needing the fewest purity-losing conversions, then the fewest representation changes, then receiving the purest data wins.
use super::document::{IdentifierId, Strings};
use super::registry::Registry;
use super::types::{TypeData, TypeId, TypeInterner};
use crate::workload::CompileMetadata;
use rustc_hash::{FxHashMap, FxHashSet};
use serde::Deserialize;
use std::path::Path;
const FOOTPRINT: u32 = 1 << 0;
/// A `Convert<To, Converter>` (or `ConvertAsync`) implementation for `From`.
#[derive(Deserialize)]
struct ConvertImplementation {
from: String,
to: String,
converter: Option<ConverterDeclaration>,
#[serde(default)]
asynchronous: bool,
#[serde(default)]
reads_footprint: bool,
}
#[derive(Deserialize)]
struct ConverterDeclaration {
#[serde(rename = "type")]
ty: String,
scope: String,
}
#[derive(Deserialize)]
struct NodeDeclaration {
identifier: String,
/// Concrete type names, or `generic:T` for a generic parameter.
element_types: Vec<String>,
#[serde(default = "both_ranks")]
ranks: Vec<Rank>,
}
fn both_ranks() -> Vec<Rank> {
vec![Rank::Item, Rank::List]
}
/// The spike's stand-in for purity declarations on Graphite's types, the `Convert` implementations, and test nodes.
#[derive(Deserialize)]
struct CoercionData {
purity: Vec<(String, String)>,
equivalent: Vec<(String, String)>,
conversions: Vec<ConvertImplementation>,
nodes: Vec<NodeDeclaration>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize)]
pub enum Rank {
Item,
List,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum ConversionKind {
/// Between representations of the same data, which is semantically invisible.
Representation,
/// From purer data to less pure data.
PurityLosing,
/// A registered conversion on a cycle of registered conversions, like `f64` and `i64`, so neither side is purer.
Lossy,
}
/// The conversion node turning one element type into another at a rank, like `convert_item` over `Convert<To, Converter>`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ConversionNode {
pub identifier: IdentifierId,
/// The scope key providing the `Converter` the implementation needs as a second input, like the `WgpuExecutor`.
pub converter_scope: Option<u32>,
pub kind: ConversionKind,
pub reads_footprint: bool,
pub forwards_input: bool,
}
impl ConversionNode {
pub fn compile_metadata(&self) -> CompileMetadata {
CompileMetadata {
extract: if self.reads_footprint { FOOTPRINT } else { 0 },
forwards_input: self.forwards_input,
..Default::default()
}
}
}
#[derive(Default)]
pub struct Coercions {
/// Pairs `(purer, less pure)`, transitively closed.
purer: FxHashSet<(TypeId, TypeId)>,
equivalent: FxHashSet<(TypeId, TypeId)>,
conversions: FxHashMap<(TypeId, TypeId, Rank), ConversionNode>,
/// Registered conversions that change a wire's whole type rather than its element, like `List<T>` into `ListDyn`.
wire_conversions: FxHashMap<(TypeId, TypeId), ConversionNode>,
}
impl Coercions {
pub fn wire_conversion(&self, from: TypeId, to: TypeId) -> Option<ConversionNode> {
self.wire_conversions.get(&(from, to)).copied()
}
pub fn is_purer(&self, a: TypeId, b: TypeId) -> bool {
self.purer.contains(&(a, b))
}
/// The automatic conversion from one element type to another, if `Convert` implements it and purity allows applying it.
pub fn automatic_conversion(&self, from: TypeId, to: TypeId, rank: Rank) -> Option<ConversionNode> {
let conversion = self.conversions.get(&(from, to, rank))?;
let allowed = match conversion.kind {
ConversionKind::Representation => true,
ConversionKind::PurityLosing => self.is_purer(from, to),
ConversionKind::Lossy => true,
};
allowed.then_some(*conversion)
}
/// The rank and element of a wire type `Fn(_, Item<T>)` or `Fn(_, List<T>)`.
pub fn ranked_element(types: &TypeInterner, wire: TypeId) -> Option<(Rank, TypeId)> {
match types.get(types.nested(wire)) {
TypeData::Item(element) => Some((Rank::Item, element)),
TypeData::List(element) => Some((Rank::List, element)),
_ => None,
}
}
}
/// Loads the spike's coercion data, registering the conversion nodes' implementations and the test nodes.
pub fn load(types: &mut TypeInterner, strings: &mut Strings, registry: &mut Registry, context: TypeId) {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("spike-data/coercions.json");
let content = std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("Failed to read {}: {error}", path.display()));
let data: CoercionData = serde_json::from_str(&content).unwrap_or_else(|error| panic!("Failed to parse {}: {error}", path.display()));
let equivalent = data
.equivalent
.iter()
.flat_map(|(a, b)| {
let (a, b) = (types.concrete(a), types.concrete(b));
[(a, b), (b, a)]
})
.collect();
let mut coercions = Coercions { equivalent, ..Default::default() };
for conversion in &data.conversions {
let (from, to) = (types.concrete(&conversion.from), types.concrete(&conversion.to));
let converter = conversion.converter.as_ref().map(|converter| (types.concrete(&converter.ty), strings.intern(&converter.scope)));
let kind = if coercions.equivalent.contains(&(from, to)) {
ConversionKind::Representation
} else {
ConversionKind::PurityLosing
};
for (rank, wrap) in [(Rank::Item, TypeData::Item as fn(TypeId) -> TypeData), (Rank::List, TypeData::List)] {
// Monomorphized over the target like `convert_item`'s `PhantomData<E>`, so typing the inserted node is unambiguous
let node = match (rank, conversion.asynchronous) {
(Rank::Item, false) => "graphene_core::ops::ConvertItemNode",
(Rank::List, false) => "graphene_core::ops::ConvertListNode",
(Rank::Item, true) => "graphene_core::ops::ConvertAsyncItemNode",
(Rank::List, true) => "graphene_core::ops::ConvertAsyncListNode",
};
let identifier = IdentifierId(strings.intern(&format!("{node}<{}>", conversion.to)));
let (from_wire, to_wire) = (types.intern(wrap(from)), types.intern(wrap(to)));
let mut inputs = vec![types.function(context, from_wire)];
if let Some((converter, _)) = converter {
let converter_wire = types.intern(TypeData::Item(converter));
inputs.push(types.function(context, converter_wire));
}
registry.add(types, identifier, context, inputs, to_wire);
coercions.conversions.insert(
(from, to, rank),
ConversionNode {
identifier,
converter_scope: converter.map(|(_, scope)| scope),
kind,
reads_footprint: conversion.reads_footprint,
forwards_input: false,
},
);
}
}
// Graphite's input adapter rows are the conversions node authors registered, each into the adapter's element type
let mut registered = Vec::new();
for (&identifier, signatures) in &registry.implementations {
if !strings.name(identifier.0).starts_with("input_adapter<") {
continue;
}
for signature in signatures {
let [input] = signature.inputs.as_slice() else { continue };
match (Coercions::ranked_element(types, *input), Coercions::ranked_element(types, signature.output)) {
(Some((from_rank, from)), Some((to_rank, to))) if from_rank == to_rank => {
if from != to {
registered.push((from, to, from_rank, identifier));
}
}
_ => {
let wire_conversion = ConversionNode {
identifier,
converter_scope: None,
kind: ConversionKind::PurityLosing,
reads_footprint: false,
forwards_input: true,
};
coercions.wire_conversions.insert((types.nested(*input), signature.output), wire_conversion);
}
}
}
}
let reachable = transitive_closure(registered.iter().map(|&(from, to, _, _)| (from, to)).collect());
let mut registered_purity = Vec::new();
for (from, to, rank, identifier) in registered {
let lossy = reachable.contains(&(to, from));
if !lossy {
registered_purity.push((from, to));
}
coercions.conversions.entry((from, to, rank)).or_insert(ConversionNode {
identifier,
converter_scope: None,
kind: if lossy { ConversionKind::Lossy } else { ConversionKind::PurityLosing },
reads_footprint: false,
forwards_input: true,
});
}
for node in &data.nodes {
let identifier = IdentifierId(strings.intern(&node.identifier));
for element in &node.element_types {
let element = match element.strip_prefix("generic:") {
Some(name) => types.convert(&crate::workload::Type::Generic(name.to_string())),
None => types.concrete(element),
};
for &rank in &node.ranks {
let wire = types.intern(match rank {
Rank::Item => TypeData::Item(element),
Rank::List => TypeData::List(element),
});
let input = types.function(context, wire);
registry.add(types, identifier, context, vec![input], wire);
}
}
}
let declared = data.purity.iter().map(|(a, b)| (types.concrete(a), types.concrete(b)));
let purer = transitive_closure(declared.chain(registered_purity).collect());
if let Some(&(cycle, _)) = purer.iter().find(|&&(a, b)| a == b) {
panic!("The purity relation has a cycle through {}", types.concrete_name(cycle).unwrap_or("a type"));
}
coercions.purer = purer;
registry.coercions = coercions;
}
/// O(n³) in the worst case over the few dozen convertible types.
fn transitive_closure(mut pairs: FxHashSet<(TypeId, TypeId)>) -> FxHashSet<(TypeId, TypeId)> {
loop {
let derived: Vec<_> = pairs
.iter()
.flat_map(|&(a, b)| pairs.iter().filter(move |&&(c, _)| c == b).map(move |&(_, d)| (a, d)))
.filter(|pair| !pairs.contains(pair))
.collect();
if derived.is_empty() {
return pairs;
}
pairs.extend(derived);
}
}
@@ -0,0 +1,264 @@
//! The context analysis pass: tracks which context features each node depends on and reads inputs through nullification
//! nodes where their dependencies differ, like `find_context_dependencies` with memoization.
use super::Builtins;
use super::checks::Checks;
use super::document::IdentifierId;
use super::ir::{Ir, IrValue, NewNode};
use super::registry::{Conversion, Promotion};
use super::typing::{Inferred, Typing};
use crate::workload::CompileMetadata;
use rustc_hash::{FxHashMap, FxHasher};
use std::hash::{Hash, Hasher};
/// Builds nodes through the store, typing, and checks, which every pass inserting nodes goes through.
pub struct Builder<'a> {
pub ir: &'a mut Ir,
pub typing: &'a mut Typing,
pub checks: &'a mut Checks,
}
/// What building a node produced: the node, or the conversions its inputs need before it can be built.
pub enum Built {
Node { id: u32, new: bool },
NeedsConversions(Box<[Conversion]>),
}
impl Builder<'_> {
/// Returns the existing node with this content, or types, checks, and appends it. `selected` is typing's selection
/// for inputs of the same types, when already made.
pub fn build(&mut self, node: NewNode, inputs: &[u32], selected: Option<u32>) -> Result<Built, String> {
let (hash, existing) = self.ir.find(&node, inputs);
if let Some(id) = existing {
return Ok(Built::Node { id, new: false });
}
let info = match self.typing.infer(self.ir, &node, inputs, selected)? {
Inferred::Typed(info) => info,
Inferred::NeedsConversions(conversions) => return Ok(Built::NeedsConversions(conversions)),
};
let resolves_to_value = self.checks.check(&node, inputs)?;
let id = self.ir.push(hash, node, inputs);
self.typing.info.push(info);
self.checks.resolves_to_value.push(resolves_to_value);
Ok(Built::Node { id, new: true })
}
/// Builds a node that never needs conversions, such as values and compiler-inserted nodes over any type.
fn build_direct(&mut self, node: NewNode, inputs: &[u32]) -> Result<(u32, bool), String> {
match self.build(node, inputs, None)? {
Built::Node { id, new } => Ok((id, new)),
Built::NeedsConversions(_) => Err("A compiler-inserted node should not need conversions".to_string()),
}
}
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Analysis {
pub features: u32,
pub sources: u32,
/// Whether the node supplies context features its inputs need, so consumers read it through a nullification.
pub supplies: bool,
}
pub struct ContextAnalysis {
/// Indexed by IR node ID.
pub analysis: Vec<Analysis>,
source_sets: Vec<Vec<u64>>,
source_set_ids: FxHashMap<Vec<u64>, u32>,
builtins: Builtins,
}
impl ContextAnalysis {
pub fn new(builtins: Builtins) -> Self {
let mut analysis = Self {
analysis: Vec::new(),
source_sets: Vec::new(),
source_set_ids: FxHashMap::default(),
builtins,
};
analysis.clear();
analysis
}
pub fn clear(&mut self) {
self.analysis.clear();
self.source_sets.clear();
self.source_sets.push(Vec::new());
self.source_set_ids.clear();
self.source_set_ids.insert(Vec::new(), 0);
}
fn source_set(&mut self, sources: Vec<u64>) -> u32 {
if let Some(&id) = self.source_set_ids.get(&sources) {
return id;
}
let id = self.source_sets.len() as u32;
self.source_sets.push(sources.clone());
self.source_set_ids.insert(sources, id);
id
}
fn union_sources(&mut self, a: u32, b: u32) -> u32 {
if a == b || b == 0 {
return a;
}
if a == 0 {
return b;
}
let mut union: Vec<u64> = self.source_sets[a as usize].iter().chain(&self.source_sets[b as usize]).copied().collect();
union.sort_unstable();
union.dedup();
self.source_set(union)
}
fn record(&mut self, id: u32, analysis: Analysis) {
match (id as usize).cmp(&self.analysis.len()) {
std::cmp::Ordering::Less => self.analysis[id as usize] = analysis,
std::cmp::Ordering::Equal => self.analysis.push(analysis),
std::cmp::Ordering::Greater => unreachable!("nodes are analyzed in the order they are built"),
}
}
/// Builds a value or compiler-inserted node, whose analysis does not depend on its inputs' dependencies.
fn build_unanalyzed(&mut self, builder: &mut Builder, node: NewNode, inputs: &[u32]) -> Result<u32, String> {
let (id, new) = builder.build_direct(node, inputs)?;
if new {
let sources = match node.value {
Some(IrValue { source: Some(source), .. }) => self.source_set(vec![source]),
_ => 0,
};
self.record(
id,
Analysis {
features: node.compile_metadata.extract,
sources,
supplies: false,
},
);
}
Ok(id)
}
pub fn build_value(&mut self, builder: &mut Builder, node: NewNode) -> Result<u32, String> {
self.build_unanalyzed(builder, node, &[])
}
/// The node a consumer reads in place of `child` when it needs `features` and `sources` stripped from the context.
fn nullification(&mut self, builder: &mut Builder, child: u32, analysis: Analysis) -> Result<u32, String> {
let builtins = self.builtins;
let origin = builder.ir.nodes[child as usize].origin;
let forwarding = CompileMetadata {
forwards_input: true,
..Default::default()
};
let compiler_node = |identifier| NewNode {
identifier,
call_argument: builtins.context,
value: None,
skip_deduplication: None,
compile_metadata: forwarding,
origin,
};
let memoize = self.build_unanalyzed(builder, compiler_node(builtins.memoize), &[child])?;
let mut hasher = FxHasher::default();
analysis.features.hash(&mut hasher);
self.source_sets[analysis.sources as usize].hash(&mut hasher);
let modification = NewNode {
identifier: builtins.value_node,
call_argument: builtins.context,
value: Some(IrValue {
ty: builtins.context_modification,
hash: hasher.finish(),
source: None,
}),
skip_deduplication: None,
compile_metadata: CompileMetadata::default(),
origin,
};
let modification = self.build_unanalyzed(builder, modification, &[])?;
let nullification = self.build_unanalyzed(builder, compiler_node(builtins.context_modification_node), &[memoize, modification])?;
self.record(nullification, Analysis { supplies: false, ..analysis });
Ok(nullification)
}
/// Adapters only change an input's rank, so they share its analysis.
fn promotion_adapter(&mut self, builder: &mut Builder, input: u32, adapter: IdentifierId) -> Result<u32, String> {
let node = NewNode {
identifier: adapter,
call_argument: self.builtins.context,
value: None,
skip_deduplication: None,
compile_metadata: CompileMetadata::default(),
origin: builder.ir.nodes[input as usize].origin,
};
let (id, _) = builder.build_direct(node, &[input])?;
self.record(id, self.analysis[input as usize]);
Ok(id)
}
/// Replaces `inputs` with what the node reads after nullification, builds the node, and records its own analysis.
/// Returns the conversions instead, with `inputs` untouched, when typing finds the inputs need some first.
pub fn build(&mut self, builder: &mut Builder, node: NewNode, inputs: &mut [u32]) -> Result<Result<u32, Box<[Conversion]>>, String> {
// Nullification keeps every input's type, so selecting before it gives the same implementation
let selected = node.value.is_none().then(|| builder.typing.select(&node, inputs));
if let Some(selection) = selected {
let conversions = builder.typing.conversions(selection)?;
if !conversions.is_empty() {
return Ok(Err(conversions.into()));
}
}
let (mut combined_features, mut combined_sources) = (0, 0);
for &input in inputs.iter() {
let child = self.analysis[input as usize];
combined_features |= child.features;
combined_sources = self.union_sources(combined_sources, child.sources);
}
let metadata = node.compile_metadata;
let features = (combined_features & !metadata.inject) | metadata.extract;
let introduces_new_dependencies = combined_features & features != features;
for input in inputs.iter_mut() {
let child = self.analysis[*input as usize];
let is_value = builder.ir.nodes[*input as usize].value.is_some();
let differs = introduces_new_dependencies || child.features != combined_features || child.sources != combined_sources;
if !is_value && (child.supplies || differs) {
*input = self.nullification(builder, *input, child)?;
}
}
if let Some(selection) = selected {
let promotions = builder.typing.promotions(selection)?;
if !promotions.is_empty() {
let promotions: Box<[Promotion]> = promotions.into();
for promotion in promotions.iter() {
let input = &mut inputs[promotion.input as usize];
*input = self.promotion_adapter(builder, *input, promotion.adapter)?;
}
}
}
let Built::Node { id, new } = builder.build(node, inputs, selected)? else {
return Err("Conversions are inserted before context analysis".to_string());
};
let net_injections = metadata.inject & !metadata.extract;
let remaining = combined_features & !net_injections;
self.record(
id,
Analysis {
features,
sources: combined_sources,
supplies: combined_features & !remaining != 0,
},
);
if new {
builder.checks.check_footprint(id, &node, features);
}
Ok(Ok(id))
}
}
@@ -0,0 +1,281 @@
//! Documents as tables of shared definitions with index-based references, built once at load time.
use super::types::{TypeId, TypeInterner};
use crate::workload::{self, CompileMetadata, Reflection};
use rustc_hash::FxHashMap;
use std::hash::{Hash, Hasher};
use std::ops::Range;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IdentifierId(pub u32);
/// A definition owned by the registry (substitution templates) or by one document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DefinitionId {
Template(u32),
Document(u32),
}
impl DefinitionId {
/// The index within its owner's definition list, the registry's templates or the document's definitions.
pub fn index(self) -> usize {
match self {
DefinitionId::Template(index) | DefinitionId::Document(index) => index as usize,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct Value {
pub ty: TypeId,
pub hash: u64,
}
#[derive(Clone, Copy, Debug)]
pub enum Input {
Node { local: u32, output: u32 },
Value(Value),
Import(u32),
Scope(u32),
Reflection(Reflection),
}
#[derive(Clone, Copy, Debug)]
pub enum Implementation {
Proto(IdentifierId),
Network(DefinitionId),
Extract,
}
#[derive(Clone, Debug)]
pub struct Node {
pub id: u64,
pub implementation: Implementation,
pub inputs: Range<u32>,
pub call_argument: TypeId,
pub visible: bool,
pub skip_deduplication: bool,
pub compile_metadata: Option<CompileMetadata>,
}
#[derive(Clone, Debug, Default)]
pub struct Definition {
pub nodes: Vec<Node>,
pub inputs: Vec<Input>,
pub exports: Vec<Input>,
/// Scope keys this network injects, with the local node providing each.
pub scopes: Vec<(u32, u32)>,
pub generated: bool,
/// Whether this network is part of the document tree, where the preprocessor substitutes nodes and fills in their compile metadata.
pub in_document: bool,
/// A Merkle hash of everything elaboration reads, including nested definitions, which keys cached instances.
pub deep_hash: u64,
/// Every document definition and node implemented by this definition, so edits can rehash up to the root.
pub owners: Vec<(u32, u32)>,
/// For each node, how many exports its instance has, or `SINGLE_OUTPUT` when it lowers to one IR node.
pub export_counts: Vec<u32>,
}
pub const SINGLE_OUTPUT: u32 = u32::MAX;
impl Definition {
pub fn node_inputs(&self, node: &Node) -> &[Input] {
&self.inputs[node.inputs.start as usize..node.inputs.end as usize]
}
/// Hashes the definition's content, with nested definitions contributing their own deep hashes.
pub fn compute_deep_hash(&self, nested_hash: impl Fn(DefinitionId) -> u64) -> u64 {
let mut hasher = rustc_hash::FxHasher::default();
(self.generated, self.in_document).hash(&mut hasher);
for node in &self.nodes {
node.id.hash(&mut hasher);
match node.implementation {
Implementation::Proto(identifier) => (0_u8, identifier.0 as u64).hash(&mut hasher),
Implementation::Network(definition) => (1_u8, nested_hash(definition)).hash(&mut hasher),
Implementation::Extract => (2_u8, 0_u64).hash(&mut hasher),
}
(node.call_argument, node.visible, node.skip_deduplication, node.compile_metadata).hash(&mut hasher);
hash_inputs(self.node_inputs(node), &mut hasher);
}
hash_inputs(&self.exports, &mut hasher);
self.scopes.hash(&mut hasher);
hasher.finish()
}
}
fn hash_inputs(inputs: &[Input], hasher: &mut impl Hasher) {
for input in inputs {
match *input {
Input::Node { local, output } => (0_u8, local, output).hash(hasher),
Input::Value(value) => (1_u8, value.ty, value.hash).hash(hasher),
Input::Import(index) => (2_u8, index).hash(hasher),
Input::Scope(key) => (3_u8, key).hash(hasher),
Input::Reflection(reflection) => (4_u8, reflection as u32).hash(hasher),
}
}
}
pub struct Substitution {
pub definition: DefinitionId,
pub wrapped_local: u32,
/// The template's inputs, which fill in inputs a document node lacks.
pub defaults: Vec<Input>,
}
/// Interns identifiers and scope keys, shared by the registry and every document.
#[derive(Default)]
pub struct Strings {
ids: FxHashMap<String, u32>,
names: Vec<String>,
}
impl Strings {
pub fn intern(&mut self, name: &str) -> u32 {
if let Some(&id) = self.ids.get(name) {
return id;
}
let id = self.names.len() as u32;
self.names.push(name.to_string());
self.ids.insert(name.to_string(), id);
id
}
pub fn get(&self, name: &str) -> Option<u32> {
self.ids.get(name).copied()
}
pub fn name(&self, id: u32) -> &str {
&self.names[id as usize]
}
}
/// Converts workload networks into definitions appended to `definitions`.
pub struct Converter<'a> {
pub types: &'a mut TypeInterner,
pub strings: &'a mut Strings,
pub definitions: &'a mut Vec<Definition>,
pub template: bool,
pub in_document: bool,
/// The converted entries of the definitions table, by their document network ID.
pub entries: FxHashMap<u64, DefinitionId>,
}
impl Converter<'_> {
fn id(&self, index: usize) -> DefinitionId {
match self.template {
true => DefinitionId::Template(index as u32),
false => DefinitionId::Document(index as u32),
}
}
pub fn input(&mut self, input: &workload::Input, locals: &FxHashMap<u64, u32>) -> Input {
match input {
workload::Input::Node(reference) => Input::Node {
local: locals[&reference.node],
output: reference.output as u32,
},
workload::Input::Value(value) => Input::Value(Value {
ty: self.types.convert(&value.ty),
hash: value.hash,
}),
workload::Input::Import(import) => Input::Import(import.index as u32),
workload::Input::Scope(key) => Input::Scope(self.strings.intern(key)),
workload::Input::Reflection(reflection) => Input::Reflection(*reflection),
}
}
pub fn node(&mut self, id: u64, node: &workload::Node, definition: &mut Definition, locals: &FxHashMap<u64, u32>) -> Node {
let implementation = match &node.implementation {
workload::Implementation::Proto(identifier) => Implementation::Proto(IdentifierId(self.strings.intern(identifier))),
workload::Implementation::Network(network) => Implementation::Network(self.network(network)),
workload::Implementation::Definition(id) => Implementation::Network(*self.entries.get(id).unwrap_or_else(|| panic!("Definition {id} is missing from the definitions table"))),
workload::Implementation::Extract => Implementation::Extract,
};
let start = definition.inputs.len() as u32;
for input in &node.inputs {
let input = self.input(input, locals);
definition.inputs.push(input);
}
Node {
id,
implementation,
inputs: start..definition.inputs.len() as u32,
call_argument: self.types.convert(&node.call_argument),
visible: node.visible,
skip_deduplication: node.skip_deduplication,
compile_metadata: node.compile_metadata,
}
}
/// Converts a network with additional root nodes, such as the preprocessor's inject scope templates.
pub fn network_with(&mut self, network: &workload::Network, extra_nodes: &[(u64, workload::Node)], extra_scopes: &[(String, u64)]) -> DefinitionId {
let table: FxHashMap<u64, &workload::Network> = network.definitions.iter().map(|(id, entry)| (*id, entry)).collect();
for (id, _) in &network.definitions {
self.entry(*id, &table);
}
let all_nodes: Vec<&(u64, workload::Node)> = network.nodes.iter().chain(extra_nodes).collect();
let locals: FxHashMap<u64, u32> = all_nodes.iter().enumerate().map(|(index, (id, _))| (*id, index as u32)).collect();
let mut definition = Definition {
generated: network.generated,
in_document: self.in_document,
..Default::default()
};
for (id, node) in all_nodes {
let node = self.node(*id, node, &mut definition, &locals);
definition.nodes.push(node);
}
definition.exports = network.exports.iter().map(|input| self.input(input, &locals)).collect();
definition.scopes = network
.scope_injections
.iter()
.map(|(key, id, _)| (key.as_str(), *id))
.chain(extra_scopes.iter().map(|(key, id)| (key.as_str(), *id)))
.map(|(key, id)| (self.strings.intern(key), locals[&id]))
.collect();
let index = self.definitions.len() as u32;
definition.deep_hash = definition.compute_deep_hash(|nested| self.definitions[nested.index()].deep_hash);
for (local, node) in definition.nodes.iter().enumerate() {
if let Implementation::Network(nested) = node.implementation {
self.definitions[nested.index()].owners.push((index, local as u32));
}
}
self.definitions.push(definition);
self.id(index as usize)
}
pub fn network(&mut self, network: &workload::Network) -> DefinitionId {
self.network_with(network, &[], &[])
}
/// Converts a definitions table entry once, after the entries it names, so every node naming it shares the definition.
fn entry(&mut self, id: u64, table: &FxHashMap<u64, &workload::Network>) -> DefinitionId {
if let Some(&converted) = self.entries.get(&id) {
return converted;
}
let network = *table.get(&id).unwrap_or_else(|| panic!("Definition {id} is missing from the definitions table"));
let mut named = Vec::new();
named_entries(network, &mut named);
for nested in named {
self.entry(nested, table);
}
let converted = self.network(network);
self.entries.insert(id, converted);
converted
}
}
/// The definitions table entries that nodes in `network` and its inline networks name.
fn named_entries(network: &workload::Network, named: &mut Vec<u64>) {
for (_, node) in &network.nodes {
match &node.implementation {
workload::Implementation::Definition(id) => named.push(*id),
workload::Implementation::Network(nested) => named_entries(nested, named),
workload::Implementation::Proto(_) | workload::Implementation::Extract => {}
}
}
}
@@ -0,0 +1,800 @@
//! The elaboration pass: walks definition instances post-order, resolving imports, scopes, reflection, passthroughs,
//! hidden nodes, and substitutions, and hands each resulting node to the node-local passes.
//!
//! With instance memoization, each instance's exports are cached under its definition's deep hash, its arguments, its
//! path, and its metadata override, together with the outer scope bindings it read, so unchanged instances are skipped.
use super::checks::Checks;
use super::context::{Builder, ContextAnalysis};
use super::document::{Definition, DefinitionId, IdentifierId, Implementation, Input, Node, Strings, Substitution};
use super::ir::{Ir, IrValue, NewNode};
use super::registry::Conversion;
use super::typing::Typing;
use super::varargs::{self, Environments};
use super::{Builtins, Document};
use crate::workload::{CompileMetadata, Reflection};
use rustc_hash::{FxHashMap, FxHasher};
use std::hash::{Hash, Hasher};
const UNLOWERED: u32 = u32::MAX;
/// Marks a slot whose lowering read no vararg binding from outside itself, so every environment can share it.
const ENVIRONMENT_INDEPENDENT: u32 = u32::MAX;
const ROOT_PATH: u32 = 0;
/// Marks a slot pointing into its instance's slot cache's export lists rather than this compile's export stack.
const PERSISTED: u32 = 1 << 31;
/// A document instance's slots from its previous lowering, reused when its outer scope bindings are unchanged: the edited
/// nodes, the nodes reading changed arguments, and their dependents are recomputed, and the rest keep their results.
struct SlotCache {
arguments: Box<[u32]>,
scope_reads: Box<[(u32, u32)]>,
slots: Vec<u32>,
exports: Vec<u32>,
/// For each node, the nodes of the same definition reading it through an input or a scope binding.
dependents: Vec<Vec<u32>>,
/// For each import, the nodes reading it directly.
import_readers: Vec<Vec<u32>>,
}
impl SlotCache {
fn new(definition: &Definition) -> Self {
let mut dependents = vec![Vec::new(); definition.nodes.len()];
let mut import_readers: Vec<Vec<u32>> = Vec::new();
for (local, node) in definition.nodes.iter().enumerate() {
for input in definition.node_inputs(node) {
let dependency = match *input {
Input::Node { local, .. } => Some(local),
Input::Scope(key) => definition.scopes.iter().find(|(scope_key, _)| *scope_key == key).map(|(_, provider)| *provider),
Input::Import(index) => {
if import_readers.len() <= index as usize {
import_readers.resize(index as usize + 1, Vec::new());
}
import_readers[index as usize].push(local as u32);
None
}
_ => None,
};
if let Some(dependency) = dependency {
dependents[dependency as usize].push(local as u32);
}
}
}
Self {
arguments: Box::default(),
scope_reads: Box::default(),
slots: Vec::new(),
exports: Vec::new(),
dependents,
import_readers,
}
}
}
/// The node-local passes, run in order on every node elaboration produces.
pub struct Passes<'a> {
pub ir: &'a mut Ir,
pub typing: &'a mut Typing,
pub checks: &'a mut Checks,
pub context: &'a mut ContextAnalysis,
/// For naming nodes monomorphized during elaboration, like vararg readers.
pub strings: &'a mut Strings,
}
impl Passes<'_> {
fn builder(&mut self) -> (Builder<'_>, &mut ContextAnalysis) {
let Passes { ir, typing, checks, context, .. } = self;
(Builder { ir, typing, checks }, context)
}
/// Builds a node through the passes, or returns the conversions its inputs need first.
fn build(&mut self, node: NewNode, inputs: &mut [u32]) -> Result<Result<u32, Box<[Conversion]>>, String> {
let (mut builder, context) = self.builder();
context.build(&mut builder, node, inputs)
}
fn build_value(&mut self, node: NewNode) -> Result<u32, String> {
let (mut builder, context) = self.builder();
context.build_value(&mut builder, node)
}
}
/// The registry-level tables elaboration reads.
#[derive(Clone, Copy)]
pub struct Tables<'a> {
pub templates: &'a [Definition],
pub substitutions: &'a [Option<Substitution>],
pub compile_metadata: &'a [Option<CompileMetadata>],
pub builtins: Builtins,
}
struct Frame<'a> {
definition: DefinitionId,
slots: usize,
arguments: (usize, usize),
path: u32,
depth: u32,
parent: Option<&'a Frame<'a>>,
/// Compile metadata the preprocessor moves onto a substitution's wrapped node.
wrapped_metadata: Option<(u32, CompileMetadata)>,
slot_cache: Option<u32>,
}
enum Lowered {
Single(u32),
Exports(u32),
}
struct InstanceEntry {
deep_hash: u64,
path_hash: u64,
wrapped_metadata: Option<(u32, CompileMetadata)>,
arguments: Box<[u32]>,
exports: Box<[u32]>,
/// Scope bindings resolved outside the instance while lowering it, as (key, IR node).
scope_reads: Box<[(u32, u32)]>,
}
/// An instance being lowered, collecting the outer scope bindings it reads.
struct ActiveInstance {
depth: u32,
scope_reads: Vec<(u32, u32)>,
}
/// Elaboration's stacks, kept between compiles to reuse their capacity, and the instance cache.
#[derive(Default)]
pub struct Elaboration {
slots: Vec<u32>,
/// Parallel to `slots`: the vararg environment a slot's lowering depends on.
slot_environments: Vec<u32>,
environments: Environments,
environment: u32,
/// The deepest outer vararg binding the node being lowered has read so far, or 0 for none.
vararg_read_depth: u32,
exports: Vec<u32>,
arguments: Vec<u32>,
/// Parent and hash of each path.
paths: Vec<(u32, u64)>,
scratch: Vec<u32>,
pub memoize_instances: bool,
instances: FxHashMap<u64, Vec<InstanceEntry>>,
active: Vec<ActiveInstance>,
slot_caches: Vec<SlotCache>,
/// Slot caches by (document definition, path hash), valid for `slot_cache_document`.
slot_cache_index: FxHashMap<(u32, u64), u32>,
slot_cache_document: u64,
/// This compile's edited nodes by definition.
dirty: FxHashMap<u32, Vec<u32>>,
pub statistics: Statistics,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct Statistics {
pub instance_hits: usize,
pub instance_misses: usize,
/// Nodes of reused slot caches recomputed because an edit reached them.
pub nodes_invalidated: usize,
pub slot_caches_reused: usize,
}
struct Walk<'a, 'p> {
tables: Tables<'a>,
document: &'a Document,
state: &'a mut Elaboration,
passes: Passes<'p>,
}
impl Elaboration {
pub fn clear_instances(&mut self) {
self.instances.clear();
self.slot_caches.clear();
self.slot_cache_index.clear();
}
/// Elaborates the document's root export and returns the IR node it lowers to.
/// When memoizing, instances containing `dirty` edits recompute those nodes with their dependents and reuse the rest.
pub fn run(&mut self, tables: Tables, document: &Document, dirty: &[(u32, u32)], passes: Passes) -> Result<u32, String> {
self.slots.clear();
self.slot_environments.clear();
self.environment = varargs::ROOT;
self.vararg_read_depth = 0;
self.exports.clear();
self.arguments.clear();
self.paths.clear();
self.paths.push((ROOT_PATH, 0));
self.scratch.clear();
self.active.clear();
self.statistics = Statistics::default();
if self.memoize_instances {
if self.slot_cache_document != document.id {
self.slot_caches.clear();
self.slot_cache_index.clear();
self.slot_cache_document = document.id;
}
self.dirty.clear();
for &(definition, local) in dirty {
self.dirty.entry(definition).or_default().push(local);
}
}
let mut walk = Walk {
tables,
document,
state: self,
passes,
};
let definition = walk.definition(document.root);
let slot_cache = walk.prepare_slots(document.root, ROOT_PATH, (0, 0), None)?;
let root = Frame {
definition: document.root,
slots: 0,
arguments: (0, 0),
path: ROOT_PATH,
depth: 0,
parent: None,
wrapped_metadata: None,
slot_cache,
};
let [export] = definition.exports.as_slice() else {
return Err("Only networks with a single export are supported".to_string());
};
let output = walk.lower_input(&root, export, ROOT_PATH)?;
walk.persist_slots(&root, Box::default());
Ok(output)
}
}
impl<'a> Walk<'a, '_> {
fn definition(&self, id: DefinitionId) -> &'a Definition {
match id {
DefinitionId::Template(index) => &self.tables.templates[index as usize],
DefinitionId::Document(index) => &self.document.definitions[index as usize],
}
}
fn substitution(&self, identifier: IdentifierId) -> Option<&'a Substitution> {
self.tables.substitutions.get(identifier.0 as usize).and_then(Option::as_ref)
}
fn registered_metadata(&self, identifier: IdentifierId) -> Option<CompileMetadata> {
self.tables.compile_metadata.get(identifier.0 as usize).copied().flatten()
}
fn path(&mut self, parent: u32, id: u64) -> u32 {
let mut hasher = FxHasher::default();
self.state.paths[parent as usize].1.hash(&mut hasher);
id.hash(&mut hasher);
self.state.paths.push((parent, hasher.finish()));
(self.state.paths.len() - 1) as u32
}
fn path_hash(&self, path: u32) -> u64 {
self.state.paths[path as usize].1
}
fn origin(&self, path: u32, id: u64) -> (u64, u64) {
(self.path_hash(path), id)
}
fn node_path(&mut self, frame: &Frame, id: u64) -> u32 {
match self.definition(frame.definition).generated {
true => frame.path,
false => self.path(frame.path, id),
}
}
fn is_substituted(&self, definition: &Definition, node: &Node) -> bool {
node.visible && definition.in_document && matches!(node.implementation, Implementation::Proto(identifier) if self.substitution(identifier).is_some())
}
/// How many exports a node lowering to an instance has, or `None` for a node lowering to a single IR node.
/// Document definitions carry these counts precomputed; templates contain no instances.
fn export_count(&self, definition: &Definition, local: usize, node: &Node) -> Option<usize> {
if let Some(&count) = definition.export_counts.get(local) {
return (count != super::document::SINGLE_OUTPUT).then_some(count as usize);
}
match node.implementation {
Implementation::Network(network) if node.visible => Some(self.definition(network).exports.len()),
Implementation::Proto(identifier) if self.is_substituted(definition, node) => {
let substitution = self.substitution(identifier).expect("checked by `is_substituted`");
Some(self.definition(substitution.definition).exports.len())
}
_ => None,
}
}
/// Allocates an instance's slots on the slot stack, starting from its slot cache when memoizing a document instance whose
/// arguments and outer scope bindings are unchanged, with its edited nodes and their dependents cleared.
fn prepare_slots(&mut self, definition_id: DefinitionId, path: u32, arguments: (usize, usize), parent: Option<&Frame>) -> Result<Option<u32>, String> {
let definition = self.definition(definition_id);
let base = self.state.slots.len();
self.state.slots.resize(base + definition.nodes.len(), UNLOWERED);
self.state.slot_environments.resize(base + definition.nodes.len(), ENVIRONMENT_INDEPENDENT);
let DefinitionId::Document(index) = definition_id else { return Ok(None) };
if !self.state.memoize_instances {
return Ok(None);
}
let key = (index, self.path_hash(path));
let cache_index = match self.state.slot_cache_index.get(&key) {
Some(&cache_index) => cache_index,
None => {
self.state.slot_caches.push(SlotCache::new(definition));
let cache_index = (self.state.slot_caches.len() - 1) as u32;
self.state.slot_cache_index.insert(key, cache_index);
cache_index
}
};
let cache = &self.state.slot_caches[cache_index as usize];
let same_argument_count = cache.arguments.len() == arguments.1 - arguments.0;
let mut reusable = same_argument_count && cache.slots.len() == definition.nodes.len();
if reusable && let Some(parent) = parent {
for (scope_key, expected) in cache.scope_reads.clone() {
if !matches!(self.resolve_scope(parent, scope_key), Some(Ok((_, id))) if id == expected) {
reusable = false;
break;
}
}
}
let cache = &mut self.state.slot_caches[cache_index as usize];
if reusable {
self.state.slots[base..].copy_from_slice(&cache.slots);
let mut stack = self.state.dirty.get(&index).cloned().unwrap_or_default();
let current_arguments = &self.state.arguments[arguments.0..arguments.1];
for (import, (previous, current)) in cache.arguments.iter().zip(current_arguments).enumerate() {
if previous != current
&& let Some(readers) = cache.import_readers.get(import)
{
stack.extend_from_slice(readers);
}
}
cache.arguments = current_arguments.into();
while let Some(local) = stack.pop() {
if std::mem::replace(&mut self.state.slots[base + local as usize], UNLOWERED) != UNLOWERED {
self.state.statistics.nodes_invalidated += 1;
stack.extend_from_slice(&cache.dependents[local as usize]);
}
}
self.state.statistics.slot_caches_reused += 1;
} else {
cache.arguments = self.state.arguments[arguments.0..arguments.1].into();
}
Ok(Some(cache_index))
}
/// Stores an instance's slots in its slot cache, moving export lists lowered this compile out of the export stack.
fn persist_slots(&mut self, frame: &Frame, scope_reads: Box<[(u32, u32)]>) {
let Some(cache_index) = frame.slot_cache else { return };
let definition = self.definition(frame.definition);
let mut slots = Vec::with_capacity(definition.nodes.len());
for (local, node) in definition.nodes.iter().enumerate() {
let mut slot = self.state.slots[frame.slots + local];
if self.state.slot_environments[frame.slots + local] != ENVIRONMENT_INDEPENDENT {
slot = UNLOWERED;
}
if slot != UNLOWERED
&& slot & PERSISTED == 0
&& let Some(count) = self.export_count(definition, local, node)
{
let cache = &mut self.state.slot_caches[cache_index as usize];
let start = cache.exports.len() as u32;
cache.exports.extend_from_slice(&self.state.exports[slot as usize..slot as usize + count]);
slot = PERSISTED | start;
}
slots.push(slot);
}
let cache = &mut self.state.slot_caches[cache_index as usize];
cache.slots = slots;
cache.scope_reads = scope_reads;
}
fn value_node(&mut self, ty: super::types::TypeId, hash: u64, source: Option<u64>, call_argument: super::types::TypeId, origin: (u64, u64)) -> Result<u32, String> {
self.passes.build_value(NewNode {
identifier: self.tables.builtins.value_node,
call_argument,
value: Some(IrValue { ty, hash, source }),
skip_deduplication: None,
compile_metadata: CompileMetadata::default(),
origin,
})
}
/// Builds the node reading the inputs in `scratch[start..]`, first inserting the conversions typing asks for.
fn build_converting(&mut self, frame: &Frame, node: NewNode, start: usize) -> Result<u32, String> {
let conversions = match self.passes.build(node, &mut self.state.scratch[start..])? {
Ok(id) => return Ok(id),
Err(conversions) => conversions,
};
for conversion in conversions.iter() {
let slot = start + conversion.input as usize;
let mut conversion_inputs = vec![self.state.scratch[slot]];
if let Some(scope) = conversion.node.converter_scope {
conversion_inputs.push(self.lower_input(frame, &Input::Scope(scope), ROOT_PATH)?);
}
let conversion_node = NewNode {
identifier: conversion.node.identifier,
call_argument: self.tables.builtins.context,
value: None,
skip_deduplication: None,
compile_metadata: conversion.node.compile_metadata(),
origin: node.origin,
};
let converted = self.passes.build(conversion_node, &mut conversion_inputs)?;
self.state.scratch[slot] = converted.map_err(|_| "Conversions do not chain".to_string())?;
}
self.passes
.build(node, &mut self.state.scratch[start..])?
.map_err(|_| "Converted inputs still need conversions".to_string())
}
/// Resolves a scope key from `frame` outward, returning the frame depth providing it and the node it lowers to.
fn resolve_scope(&mut self, frame: &Frame, key: u32) -> Option<Result<(u32, u32), String>> {
let mut scope = Some(frame);
while let Some(current) = scope {
if let Some(&(_, local)) = self.definition(current.definition).scopes.iter().find(|(scope_key, _)| *scope_key == key) {
return Some(self.lower_output(current, local, 0).map(|id| (current.depth, id)));
}
scope = current.parent;
}
None
}
fn lower_input(&mut self, frame: &Frame, input: &Input, owner_path: u32) -> Result<u32, String> {
let builtins = self.tables.builtins;
match *input {
Input::Node { local, output } => self.lower_output(frame, local, output),
Input::Value(value) => {
let origin = self.origin(frame.path, 0);
self.value_node(value.ty, value.hash, None, builtins.context, origin)
}
Input::Import(index) => Ok(self.state.arguments[frame.arguments.0 + index as usize]),
Input::Scope(key) => {
let (provider_depth, id) = self.resolve_scope(frame, key).ok_or_else(|| format!("Scope key {key} not found"))??;
// Instances below the providing frame depend on this binding
for active in self.state.active.iter_mut().rev().take_while(|active| active.depth > provider_depth) {
active.scope_reads.push((key, id));
}
Ok(id)
}
Input::Reflection(reflection) => {
let path_hash = self.path_hash(owner_path);
let (ty, source) = match reflection {
Reflection::DocumentNodePath => (builtins.node_id_path, None),
Reflection::SourceId => (builtins.source_id, Some(path_hash)),
};
let hash = path_hash ^ (reflection as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15);
self.value_node(ty, hash, source, builtins.context, (path_hash, 0))
}
}
}
fn lower_output(&mut self, frame: &Frame, local: u32, output: u32) -> Result<u32, String> {
let index = frame.slots + local as usize;
let slot = self.state.slots[index];
let definition = self.definition(frame.definition);
let node = &definition.nodes[local as usize];
let multiple_outputs = self.export_count(definition, local as usize, node).is_some();
let slot_environment = self.state.slot_environments[index];
let reusable = slot_environment == ENVIRONMENT_INDEPENDENT || slot_environment == self.state.environment;
if slot != UNLOWERED && reusable {
if slot_environment != ENVIRONMENT_INDEPENDENT {
let depth = self.state.environments.depth(slot_environment);
self.state.vararg_read_depth = self.state.vararg_read_depth.max(depth);
}
return Ok(match (multiple_outputs, slot & PERSISTED != 0) {
(false, _) => slot,
(true, true) => {
let cache = frame.slot_cache.expect("persisted slots come from the frame's slot cache");
self.state.slot_caches[cache as usize].exports[((slot & !PERSISTED) + output) as usize]
}
(true, false) => self.state.exports[(slot + output) as usize],
});
}
let outer_read_depth = std::mem::replace(&mut self.state.vararg_read_depth, 0);
let lowered = self.lower_node(frame, local);
let read_depth = self.state.vararg_read_depth;
self.state.vararg_read_depth = outer_read_depth.max(read_depth);
let (slot, result) = match lowered? {
Lowered::Single(id) => (id, id),
Lowered::Exports(start) => (start, self.state.exports[(start + output) as usize]),
};
self.state.slots[index] = slot;
self.state.slot_environments[index] = if read_depth > 0 { self.state.environment } else { ENVIRONMENT_INDEPENDENT };
Ok(result)
}
/// Lowers a network node's inputs as its instance's arguments. A substitution takes exactly its template's inputs,
/// filling in the ones the document node lacks and dropping extra ones.
fn lower_arguments(&mut self, frame: &Frame, inputs: &[Input], template_defaults: Option<&[Input]>, path: u32) -> Result<(usize, usize), String> {
let start = self.state.arguments.len();
let count = template_defaults.map_or(inputs.len(), <[Input]>::len);
for index in 0..count {
let input = inputs
.get(index)
.or_else(|| template_defaults.map(|defaults| &defaults[index]))
.expect("the index is within the inputs or the defaults");
let argument = self.lower_input(frame, input, path)?;
self.state.arguments.push(argument);
}
Ok((start, self.state.arguments.len()))
}
fn lower_node(&mut self, frame: &Frame, local: u32) -> Result<Lowered, String> {
let definition = self.definition(frame.definition);
let node = &definition.nodes[local as usize];
let inputs = definition.node_inputs(node);
let builtins = self.tables.builtins;
// A hidden node passes its primary input through, or the unit value when it has none
if !node.visible {
let path = self.node_path(frame, node.id);
return Ok(Lowered::Single(match inputs.first() {
Some(input) => self.lower_input(frame, input, path)?,
None => {
let origin = self.origin(path, node.id);
self.value_node(builtins.unit, builtins.none_hash, None, builtins.context, origin)?
}
}));
}
match node.implementation {
Implementation::Proto(identifier) if identifier == builtins.passthrough => {
let path = self.node_path(frame, node.id);
Ok(Lowered::Single(self.lower_input(frame, &inputs[0], path)?))
}
Implementation::Proto(identifier) if identifier == builtins.inject_vararg => Ok(Lowered::Single(self.lower_vararg_injection(frame, node, inputs)?)),
Implementation::Proto(identifier) if identifier == builtins.read_vararg => Ok(Lowered::Single(self.lower_vararg_read(frame, node, inputs)?)),
Implementation::Proto(identifier) if self.is_substituted(definition, node) => {
let substitution = self.substitution(identifier).expect("checked by `is_substituted`");
let metadata = node.compile_metadata.or_else(|| self.registered_metadata(identifier)).unwrap_or_default();
let path = self.node_path(frame, node.id);
let arguments = self.lower_arguments(frame, inputs, Some(&substitution.defaults), path)?;
let exports = self.instantiate(frame, substitution.definition, arguments, path, Some((substitution.wrapped_local, metadata)))?;
self.state.arguments.truncate(arguments.0);
Ok(Lowered::Exports(exports))
}
Implementation::Proto(identifier)
if identifier == builtins.value_node
&& let [Input::Value(value)] = inputs =>
{
let origin = self.origin(frame.path, node.id);
Ok(Lowered::Single(self.value_node(value.ty, value.hash, None, node.call_argument, origin)?))
}
Implementation::Proto(identifier) => {
let path = self.node_path(frame, node.id);
let start = self.state.scratch.len();
for input in inputs {
let lowered = self.lower_input(frame, input, path)?;
self.state.scratch.push(lowered);
}
let compile_metadata = match frame.wrapped_metadata {
Some((wrapped_local, metadata)) if wrapped_local == local => metadata,
_ if definition.in_document => node.compile_metadata.or_else(|| self.registered_metadata(identifier)).unwrap_or_default(),
_ => node.compile_metadata.unwrap_or_default(),
};
let new_node = NewNode {
identifier,
call_argument: node.call_argument,
value: None,
skip_deduplication: node.skip_deduplication.then(|| self.path_hash(path)),
compile_metadata,
origin: self.origin(frame.path, node.id),
};
let id = self.build_converting(frame, new_node, start);
self.state.scratch.truncate(start);
Ok(Lowered::Single(id?))
}
Implementation::Network(network) => {
let path = self.node_path(frame, node.id);
let arguments = self.lower_arguments(frame, inputs, None, path)?;
let exports = self.instantiate(frame, network, arguments, path, None)?;
self.state.arguments.truncate(arguments.0);
Ok(Lowered::Exports(exports))
}
Implementation::Extract => Err("Extract nodes are not supported".to_string()),
}
}
fn constant_hash(&self, id: u32) -> Result<u64, String> {
let value = self.passes.ir.nodes[id as usize].value;
value.map(|value| value.hash).ok_or_else(|| "Vararg names must be compile-time constants".to_string())
}
/// Lowers the name and value in the current environment and the body with the name bound to the value's type.
fn lower_vararg_injection(&mut self, frame: &Frame, node: &Node, inputs: &[Input]) -> Result<u32, String> {
let [name, value, body] = inputs else {
return Err("Injecting a vararg takes a name, a value, and a body".to_string());
};
let path = self.node_path(frame, node.id);
let name = self.lower_input(frame, name, path)?;
let name_hash = self.constant_hash(name)?;
let value = self.lower_input(frame, value, path)?;
let outer = self.state.environment;
let value_type = self.passes.typing.info[value as usize].return_type;
self.state.environment = self.state.environments.bind(outer, name_hash, value_type);
let body = self.lower_input(frame, body, path);
self.state.environment = outer;
// Reads of this binding do not reach outside the injector
let outer_depth = self.state.environments.depth(outer);
self.state.vararg_read_depth = self.state.vararg_read_depth.min(outer_depth);
let body = body?;
let start = self.state.scratch.len();
self.state.scratch.extend_from_slice(&[name, value, body]);
let injection = NewNode {
identifier: self.tables.builtins.inject_vararg,
call_argument: node.call_argument,
value: None,
skip_deduplication: None,
compile_metadata: varargs::INJECTION_METADATA,
origin: self.origin(frame.path, node.id),
};
let id = self.build_converting(frame, injection, start);
self.state.scratch.truncate(start);
id
}
/// Lowers a reader to the reader monomorphized for the type its name is bound to.
fn lower_vararg_read(&mut self, frame: &Frame, node: &Node, inputs: &[Input]) -> Result<u32, String> {
let [name] = inputs else {
return Err("Reading a vararg takes a name".to_string());
};
let path = self.node_path(frame, node.id);
let name = self.lower_input(frame, name, path)?;
let name_hash = self.constant_hash(name)?;
let (depth, ty) = self.state.environments.resolve(self.state.environment, name_hash).ok_or_else(|| "Unbound vararg".to_string())?;
self.state.vararg_read_depth = self.state.vararg_read_depth.max(depth);
let name_type = self.passes.typing.info[name as usize].return_type;
let context = self.tables.builtins.context;
let typing = &mut *self.passes.typing;
let identifier = varargs::monomorphized_reader(&mut typing.types, self.passes.strings, &mut typing.registry, context, name_type, ty);
let read = NewNode {
identifier,
call_argument: node.call_argument,
value: None,
skip_deduplication: None,
compile_metadata: varargs::READ_METADATA,
origin: self.origin(frame.path, node.id),
};
let start = self.state.scratch.len();
self.state.scratch.push(name);
let id = self.build_converting(frame, read, start);
self.state.scratch.truncate(start);
id
}
fn instance_key(&self, deep_hash: u64, path_hash: u64, wrapped_metadata: Option<(u32, CompileMetadata)>, arguments: &[u32]) -> u64 {
let mut hasher = FxHasher::default();
(deep_hash, path_hash, wrapped_metadata, arguments).hash(&mut hasher);
hasher.finish()
}
/// Finds a cached instance with the same key whose outer scope bindings still resolve to the same nodes.
fn cached_instance(
&mut self,
parent: &Frame,
key: u64,
deep_hash: u64,
path_hash: u64,
wrapped_metadata: Option<(u32, CompileMetadata)>,
arguments: (usize, usize),
) -> Result<Option<u32>, String> {
let candidates = self.state.instances.get(&key).map_or(0, Vec::len);
for candidate in 0..candidates {
let entry = &self.state.instances[&key][candidate];
let same_key =
entry.deep_hash == deep_hash && entry.path_hash == path_hash && entry.wrapped_metadata == wrapped_metadata && *entry.arguments == self.state.arguments[arguments.0..arguments.1];
if !same_key {
continue;
}
let scope_reads = entry.scope_reads.clone();
let mut resolved_reads = Vec::with_capacity(scope_reads.len());
for &(scope_key, expected) in &scope_reads {
match self.resolve_scope(parent, scope_key) {
Some(resolved) => {
let (provider_depth, id) = resolved?;
if id != expected {
break;
}
resolved_reads.push((scope_key, provider_depth, id));
}
None => break,
}
}
if resolved_reads.len() == scope_reads.len() {
// The enclosing instances being recorded depend on the reused instance's outer bindings too
for (scope_key, provider_depth, id) in resolved_reads {
for active in self.state.active.iter_mut().rev().take_while(|active| active.depth > provider_depth) {
active.scope_reads.push((scope_key, id));
}
}
let start = self.state.exports.len();
let entry = &self.state.instances[&key][candidate];
self.state.exports.extend_from_slice(&entry.exports);
return Ok(Some(start as u32));
}
}
Ok(None)
}
fn instantiate(&mut self, parent: &Frame, definition_id: DefinitionId, arguments: (usize, usize), path: u32, wrapped_metadata: Option<(u32, CompileMetadata)>) -> Result<u32, String> {
let definition = self.definition(definition_id);
let path_hash = self.path_hash(path);
let key = self.instance_key(definition.deep_hash, path_hash, wrapped_metadata, &self.state.arguments[arguments.0..arguments.1]);
// Substitution templates are a handful of nodes, cheaper to elaborate again than to look up. Inside a vararg binding the
// instance's results can depend on the binding, so only instances outside every binding are cached.
let memoize = self.state.memoize_instances && matches!(definition_id, DefinitionId::Document(_)) && self.state.environment == varargs::ROOT;
if memoize {
if let Some(start) = self.cached_instance(parent, key, definition.deep_hash, path_hash, wrapped_metadata, arguments)? {
self.state.statistics.instance_hits += 1;
return Ok(start);
}
self.state.statistics.instance_misses += 1;
}
let depth = parent.depth + 1;
let slots = self.state.slots.len();
let slot_cache = match memoize {
true => self.prepare_slots(definition_id, path, arguments, Some(parent))?,
false => {
self.state.slots.resize(slots + definition.nodes.len(), UNLOWERED);
self.state.slot_environments.resize(slots + definition.nodes.len(), ENVIRONMENT_INDEPENDENT);
None
}
};
let frame = Frame {
definition: definition_id,
slots,
arguments,
path,
depth,
parent: Some(parent),
wrapped_metadata,
slot_cache,
};
if memoize {
self.state.active.push(ActiveInstance { depth, scope_reads: Vec::new() });
}
// Reserving the range first keeps it contiguous while nested instances push their own exports after it
let start = self.state.exports.len();
self.state.exports.resize(start + definition.exports.len(), UNLOWERED);
for (index, export) in definition.exports.iter().enumerate() {
if matches!(export, Input::Import(_)) {
return Err("Network exports of imports are not supported by flattening".to_string());
}
self.state.exports[start + index] = self.lower_input(&frame, export, path)?;
}
if memoize {
let active = self.state.active.pop().expect("this instance's record was pushed above");
self.persist_slots(&frame, active.scope_reads.clone().into());
let entry = InstanceEntry {
deep_hash: definition.deep_hash,
path_hash,
wrapped_metadata,
arguments: self.state.arguments[arguments.0..arguments.1].into(),
exports: self.state.exports[start..start + definition.exports.len()].into(),
scope_reads: active.scope_reads.into(),
};
self.state.instances.entry(key).or_default().push(entry);
}
self.state.slots.truncate(slots);
self.state.slot_environments.truncate(slots);
Ok(start as u32)
}
}
@@ -0,0 +1,52 @@
//! Executor construction over the IR: one boxed node per IR node, wired to its inputs by index.
use super::Compiled;
use super::ir::IrValue;
pub trait MockNode: Send + Sync {
fn input_count(&self) -> usize;
}
struct ConstructedNode {
inputs: (u32, u32),
_implementation: u32,
}
impl MockNode for ConstructedNode {
fn input_count(&self) -> usize {
(self.inputs.1 - self.inputs.0) as usize
}
}
struct ValueNode(#[expect(dead_code, reason = "the mock only models the allocation, it never evaluates")] IrValue);
impl MockNode for ValueNode {
fn input_count(&self) -> usize {
0
}
}
pub struct Executor {
pub nodes: Vec<Box<dyn MockNode>>,
pub output: u32,
}
impl Executor {
pub fn new(compiled: &Compiled) -> Self {
let (ir, typing) = (compiled.ir, compiled.typing);
let mut nodes: Vec<Box<dyn MockNode>> = Vec::with_capacity(ir.len());
for (id, node) in ir.nodes.iter().enumerate() {
if let Some(value) = node.value {
nodes.push(Box::new(ValueNode(value)));
continue;
}
nodes.push(Box::new(ConstructedNode {
inputs: node.inputs,
_implementation: typing.info[id].implementation,
}));
}
Self { nodes, output: compiled.output }
}
}
+135
View File
@@ -0,0 +1,135 @@
//! The IR store: hash-consed nodes in topological order. Pass results live in side tables indexed by node ID.
use super::document::IdentifierId;
use super::types::TypeId;
use crate::workload::CompileMetadata;
use rustc_hash::{FxHashMap, FxHasher};
use std::hash::{Hash, Hasher};
const NONE: u32 = u32::MAX;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct IrValue {
pub ty: TypeId,
pub hash: u64,
pub source: Option<u64>,
}
/// A node about to be built, before its inputs are stored.
#[derive(Clone, Copy, Debug)]
pub struct NewNode {
pub identifier: IdentifierId,
pub call_argument: TypeId,
pub value: Option<IrValue>,
/// Path hash of nodes exempt from deduplication, which keeps each instance distinct.
pub skip_deduplication: Option<u64>,
pub compile_metadata: CompileMetadata,
/// The hash of the containing instance's path and the document node's ID.
pub origin: (u64, u64),
}
#[derive(Clone, Debug)]
pub struct IrNode {
pub identifier: IdentifierId,
pub call_argument: TypeId,
pub inputs: (u32, u32),
pub value: Option<IrValue>,
pub skip_deduplication: Option<u64>,
pub compile_metadata: CompileMetadata,
pub origin: (u64, u64),
}
/// Compares element by element, since inputs are a handful of IDs and an out-of-line `memcmp` call costs more than the loop.
#[inline]
fn same_inputs(a: &[u32], b: &[u32]) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(a, b)| a == b)
}
#[derive(Default)]
pub struct Ir {
pub nodes: Vec<IrNode>,
pub inputs: Vec<u32>,
consed: FxHashMap<u64, u32>,
collisions: Vec<u32>,
}
impl Ir {
pub fn clear(&mut self) {
self.nodes.clear();
self.inputs.clear();
self.consed.clear();
self.collisions.clear();
}
pub fn len(&self) -> usize {
self.nodes.len()
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
pub fn inputs(&self, id: u32) -> &[u32] {
let (start, end) = self.nodes[id as usize].inputs;
&self.inputs[start as usize..end as usize]
}
fn hash(node: &NewNode, inputs: &[u32]) -> u64 {
let mut hasher = FxHasher::default();
node.identifier.hash(&mut hasher);
node.call_argument.hash(&mut hasher);
node.value.map(|value| (value.ty, value.hash)).hash(&mut hasher);
node.skip_deduplication.hash(&mut hasher);
inputs.hash(&mut hasher);
hasher.finish()
}
/// The existing node with this content, if any, and the content hash for inserting it otherwise.
pub fn find(&self, node: &NewNode, inputs: &[u32]) -> (u64, Option<u32>) {
let hash = Self::hash(node, inputs);
let mut candidate = self.consed.get(&hash).copied().unwrap_or(NONE);
while candidate != NONE {
let existing = &self.nodes[candidate as usize];
let same = existing.identifier == node.identifier
&& existing.call_argument == node.call_argument
&& existing.value.map(|value| (value.ty, value.hash)) == node.value.map(|value| (value.ty, value.hash))
&& existing.skip_deduplication == node.skip_deduplication
&& same_inputs(self.inputs(candidate), inputs);
if same {
return (hash, Some(candidate));
}
candidate = self.collisions[candidate as usize];
}
(hash, None)
}
pub fn push(&mut self, hash: u64, node: NewNode, inputs: &[u32]) -> u32 {
let start = self.inputs.len() as u32;
self.inputs.extend_from_slice(inputs);
let id = self.nodes.len() as u32;
self.nodes.push(IrNode {
identifier: node.identifier,
call_argument: node.call_argument,
inputs: (start, self.inputs.len() as u32),
value: node.value,
skip_deduplication: node.skip_deduplication,
compile_metadata: node.compile_metadata,
origin: node.origin,
});
self.collisions.push(self.consed.insert(hash, id).unwrap_or(NONE));
id
}
/// The nodes reachable from `output`, which is the compiled graph once earlier compiles have left unreferenced nodes behind.
pub fn reachable(&self, output: u32) -> Vec<u32> {
let mut reached = vec![false; self.nodes.len()];
let mut stack = vec![output];
while let Some(id) = stack.pop() {
if std::mem::replace(&mut reached[id as usize], true) {
continue;
}
stack.extend_from_slice(self.inputs(id));
}
(0..self.nodes.len() as u32).filter(|&id| reached[id as usize]).collect()
}
}
+353
View File
@@ -0,0 +1,353 @@
//! An exploratory from-scratch compiler aiming at the performance target, producing the same graph as the memoized baseline.
//!
//! Load time builds the shared tables: interned types and identifiers, the registry, and the preprocessor's substitutions as
//! shared template definitions. A document is a table of definitions referencing nodes by index.
//!
//! Compilation is a set of passes with their own state, fused per node by elaboration's post-order walk:
//! - `elaborate`: instances, imports, scopes, reflection, passthroughs, hidden nodes, substitutions.
//! - `context`: context feature analysis and nullification insertion.
//! - `typing`: implementation selection.
//! - `checks`: constant inputs and footprint invariance.
//!
//! Every pass stores its per-node results in a table indexed by the IR node ID, and the IR store hash-conses nodes as they are built.
pub mod checks;
pub mod codegen;
pub mod coercion;
pub mod context;
pub mod document;
pub mod elaborate;
pub mod executor;
pub mod ir;
pub mod registry;
pub mod types;
pub mod typing;
pub mod varargs;
use crate::baseline::{CONTEXT_MODIFICATION, MEMOIZE, PASSTHROUGH, VALUE_NODE};
use crate::workload::{self, CompileMetadata};
use checks::Checks;
use context::ContextAnalysis;
use document::{Converter, Definition, DefinitionId, IdentifierId, Strings, Substitution};
use elaborate::{Elaboration, Passes, Tables};
use ir::Ir;
use registry::Registry;
use rustc_hash::FxHashMap;
use types::{TypeId, TypeInterner};
use typing::Typing;
#[derive(Clone, Copy)]
pub struct Builtins {
pub context: TypeId,
pub unit: TypeId,
pub node_id_path: TypeId,
pub source_id: TypeId,
pub context_modification: TypeId,
pub none_hash: u64,
pub passthrough: IdentifierId,
pub value_node: IdentifierId,
pub memoize: IdentifierId,
pub context_modification_node: IdentifierId,
pub inject_vararg: IdentifierId,
pub read_vararg: IdentifierId,
}
pub struct Document {
pub definitions: Vec<Definition>,
pub root: DefinitionId,
/// Identifies this document's structure, so incremental compiles know when the root's cached slots still apply.
pub id: u64,
/// Nodes edited since the last compile as (definition, node), including the node implementing each edited definition up
/// to the root, whose results and dependents must be recomputed.
pub dirty_nodes: Vec<(u32, u32)>,
}
impl Document {
/// Replaces a value input, as dragging a slider does, and rehashes the edited definition and its ancestors.
pub fn set_value(&mut self, definition: u32, local: u32, input: usize, hash: u64) {
let edited = &mut self.definitions[definition as usize];
let index = edited.nodes[local as usize].inputs.start as usize + input;
let document::Input::Value(value) = &mut edited.inputs[index] else {
panic!("The edited input should be a value")
};
value.hash = hash;
self.rehash(definition, local);
}
fn rehash(&mut self, definition: u32, local: u32) {
let mut dirty = rustc_hash::FxHashSet::default();
let mut pending = vec![(definition, local)];
while let Some(node) = pending.pop() {
if dirty.insert(node) {
pending.extend(self.definitions[node.0 as usize].owners.iter().copied());
}
}
// Definitions follow the ones they name, so ascending order rehashes every nested definition before its owners
let mut affected: Vec<u32> = dirty.iter().map(|(definition, _)| *definition).collect();
affected.sort_unstable();
affected.dedup();
for definition in affected {
let definitions = &self.definitions;
let deep_hash = definitions[definition as usize].compute_deep_hash(|nested| definitions[nested.index()].deep_hash);
self.definitions[definition as usize].deep_hash = deep_hash;
}
self.dirty_nodes.extend(dirty);
}
}
/// The result of a compile: the IR store with its pass results, and the node computing the document's output.
pub struct Compiled<'a> {
pub ir: &'a Ir,
pub typing: &'a Typing,
pub context: &'a ContextAnalysis,
pub checks: &'a Checks,
pub output: u32,
}
pub struct Lean {
pub strings: Strings,
pub templates: Vec<Definition>,
/// Indexed by identifier ID, which is dense since identifiers are interned.
pub substitutions: Vec<Option<Substitution>>,
pub compile_metadata: Vec<Option<CompileMetadata>>,
/// The preprocessor's inject scope templates, added to each document's root.
inject_scopes: Vec<(String, workload::Node)>,
pub builtins: Builtins,
pub ir: Ir,
pub typing: Typing,
pub checks: Checks,
pub context: ContextAnalysis,
elaboration: Elaboration,
}
/// Where inputs get converted to the types their connectors accept.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InputAdapters {
/// The preprocessor's `input_adapter<T>` wrapper on every input of a substituted node, as Graphite does today.
Preprocessed,
/// Typing inserts conversion nodes only on the inputs that need them, selecting among all of the node's implementations.
Resolved,
}
fn strip_input_adapters(network: &mut workload::Network) {
for (_, node) in &mut network.nodes {
match &mut node.implementation {
workload::Implementation::Proto(identifier) if identifier.starts_with("input_adapter<") => *identifier = PASSTHROUGH.to_string(),
workload::Implementation::Network(nested) => strip_input_adapters(nested),
_ => {}
}
}
}
impl Lean {
pub fn load() -> Self {
Self::load_with(InputAdapters::Resolved)
}
pub fn load_with(input_adapters: InputAdapters) -> Self {
let mut types = TypeInterner::default();
let mut strings = Strings::default();
let item = |types: &mut TypeInterner, name: &str| {
let element = types.concrete(name);
types.intern(types::TypeData::Item(element))
};
let builtins = Builtins {
context: types.concrete(crate::baseline::types::CONTEXT_NAME),
unit: types.concrete(crate::baseline::types::UNIT_NAME),
node_id_path: item(&mut types, "core_types::list::NodeIdPath"),
source_id: item(&mut types, "core_types::runtime::SourceId"),
context_modification: item(&mut types, "core_types::context::ContextModification"),
none_hash: 0x4E4F_4E45,
passthrough: IdentifierId(strings.intern(PASSTHROUGH)),
value_node: IdentifierId(strings.intern(VALUE_NODE)),
memoize: IdentifierId(strings.intern(MEMOIZE)),
context_modification_node: IdentifierId(strings.intern(CONTEXT_MODIFICATION)),
inject_vararg: IdentifierId(strings.intern(varargs::INJECT_VARARG)),
read_vararg: IdentifierId(strings.intern(varargs::READ_VARARG)),
};
let mut registry = Registry::default();
for entry in workload::load_registry() {
let identifier = IdentifierId(strings.intern(&entry.identifier));
for signature in &entry.implementations {
let call_argument = types.convert(&signature.call_argument);
let inputs = signature.inputs.iter().map(|input| types.convert(input)).collect();
let output = types.convert(&signature.output);
registry.add(&types, identifier, call_argument, inputs, output);
}
}
registry.index_promotion_adapters(&types, &strings);
coercion::load(&mut types, &mut strings, &mut registry, builtins.context);
varargs::load(&mut types, &mut registry, builtins.inject_vararg, builtins.context);
let tables = workload::load_preprocessor_tables();
let mut templates = Vec::new();
let mut substitutions = Vec::new();
for substitution in &tables.substitutions {
let workload::Implementation::Network(network) = &substitution.node.implementation else {
continue;
};
let stripped;
let network = match input_adapters {
InputAdapters::Preprocessed => network,
InputAdapters::Resolved => {
let mut copy = network.clone();
strip_input_adapters(&mut copy);
stripped = copy;
&stripped
}
};
let mut converter = Converter {
types: &mut types,
strings: &mut strings,
definitions: &mut templates,
template: true,
in_document: false,
entries: Default::default(),
};
let definition = converter.network(network);
let empty = FxHashMap::default();
let defaults = substitution.node.inputs.iter().map(|input| converter.input(input, &empty)).collect();
let wrapped_local = network.nodes.iter().position(|(id, _)| *id == substitution.wrapped_node_id).expect("the wrapped node should exist") as u32;
let identifier = strings.intern(&substitution.identifier) as usize;
if substitutions.len() <= identifier {
substitutions.resize_with(identifier + 1, || None);
}
substitutions[identifier] = Some(Substitution { definition, wrapped_local, defaults });
}
let mut compile_metadata = Vec::new();
for entry in &tables.compile_metadata {
let identifier = strings.intern(&entry.identifier) as usize;
if compile_metadata.len() <= identifier {
compile_metadata.resize(identifier + 1, None);
}
compile_metadata[identifier] = Some(entry.metadata);
}
let inject_scopes = tables.inject_scopes.into_iter().map(|scope| (scope.identifier, scope.template)).collect();
Self {
strings,
templates,
substitutions,
compile_metadata,
inject_scopes,
builtins,
ir: Ir::default(),
typing: Typing::new(types, registry, builtins.context),
checks: Checks::default(),
context: ContextAnalysis::new(builtins),
elaboration: Elaboration::default(),
}
}
/// Converts a scoped document, adding the inject scope templates to its root like `Preprocessor::insert_inject_scopes`.
pub fn convert_document(&mut self, network: &workload::Network) -> Document {
use std::hash::{Hash, Hasher};
let producer_id = |identifier: &str| {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
identifier.hash(&mut hasher);
hasher.finish()
};
let extra_nodes: Vec<(u64, workload::Node)> = self.inject_scopes.iter().map(|(identifier, template)| (producer_id(identifier), template.clone())).collect();
let extra_scopes: Vec<(String, u64)> = self.inject_scopes.iter().map(|(identifier, _)| (identifier.clone(), producer_id(identifier))).collect();
let mut definitions = Vec::new();
let mut converter = Converter {
types: &mut self.typing.types,
strings: &mut self.strings,
definitions: &mut definitions,
template: false,
in_document: true,
entries: Default::default(),
};
let root = converter.network_with(network, &extra_nodes, &extra_scopes);
self.annotate_export_counts(&mut definitions);
static NEXT_DOCUMENT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
Document {
definitions,
root,
id: NEXT_DOCUMENT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
dirty_nodes: Vec::new(),
}
}
/// Records how many exports each node's instance has: networks and substituted nodes lower to instances.
fn annotate_export_counts(&self, definitions: &mut [Definition]) {
for index in 0..definitions.len() {
let definition = &definitions[index];
let counts = definition
.nodes
.iter()
.map(|node| match node.implementation {
document::Implementation::Network(network) if node.visible => definitions[network.index()].exports.len() as u32,
document::Implementation::Proto(identifier) if node.visible && definition.in_document => match self.substitutions.get(identifier.0 as usize) {
Some(Some(substitution)) => self.templates[substitution.definition.index()].exports.len() as u32,
_ => document::SINGLE_OUTPUT,
},
_ => document::SINGLE_OUTPUT,
})
.collect();
definitions[index].export_counts = counts;
}
}
/// Compiles the document from scratch, keeping only the pass buffers' capacity from earlier compiles.
pub fn compile(&mut self, document: &Document) -> Result<Compiled<'_>, String> {
self.ir.clear();
self.typing.clear();
self.checks.clear();
self.context.clear();
self.elaboration.clear_instances();
self.elaboration.memoize_instances = false;
self.run(document, &[])
}
/// Compiles the document reusing everything earlier incremental compiles built: hash-consed nodes with their pass
/// results, the root nodes untouched by edits since the last compile, and cached instances whose definition content,
/// arguments, path, and outer scope bindings are unchanged. Consumes the document's record of edits.
/// Nodes no longer reachable stay in the store; `Compiled::output` reaches only the current graph.
pub fn compile_incremental(&mut self, document: &mut Document) -> Result<Compiled<'_>, String> {
self.elaboration.memoize_instances = true;
let dirty = std::mem::take(&mut document.dirty_nodes);
self.run(document, &dirty)
}
pub fn instance_statistics(&self) -> elaborate::Statistics {
self.elaboration.statistics
}
fn run(&mut self, document: &Document, dirty: &[(u32, u32)]) -> Result<Compiled<'_>, String> {
let tables = Tables {
templates: &self.templates,
substitutions: &self.substitutions,
compile_metadata: &self.compile_metadata,
builtins: self.builtins,
};
let passes = Passes {
ir: &mut self.ir,
typing: &mut self.typing,
checks: &mut self.checks,
context: &mut self.context,
strings: &mut self.strings,
};
let output = self.elaboration.run(tables, document, dirty, passes)?;
Ok(Compiled {
ir: &self.ir,
typing: &self.typing,
context: &self.context,
checks: &self.checks,
output,
})
}
pub fn identifier_name(&self, identifier: IdentifierId) -> &str {
self.strings.name(identifier.0)
}
}
@@ -0,0 +1,415 @@
//! Implementation selection over interned types, memoized per identifier and input types.
use super::coercion::{Coercions, ConversionKind, ConversionNode, Rank};
use super::document::{IdentifierId, Strings};
use super::types::{TypeData, TypeId, TypeInterner};
use rustc_hash::FxHashMap;
pub struct Signature {
pub call_argument: TypeId,
pub inputs: Vec<TypeId>,
pub output: TypeId,
/// The generic names, collected like `collect_generics`.
pub generics: Vec<u32>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PromotionKind {
ItemToList,
Bundle,
Unbundle,
}
impl PromotionKind {
const ADAPTER_PREFIXES: [(&str, PromotionKind); 3] = [
("graphene_core::ops::ItemToListNode<", PromotionKind::ItemToList),
("graphene_core::ops::BundleNode<", PromotionKind::Bundle),
("graphene_core::ops::UnbundleNode<", PromotionKind::Unbundle),
];
}
/// An adapter node to insert on an input after context analysis nullified it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Promotion {
pub input: u32,
pub adapter: IdentifierId,
}
/// A conversion node to insert on an input before the node can be built.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Conversion {
pub input: u32,
pub node: ConversionNode,
}
#[derive(Clone, Debug)]
pub struct Selection {
pub implementation: u32,
pub return_type: TypeId,
pub fn_type: TypeId,
pub promotions: Vec<Promotion>,
/// When not empty, the node is only buildable after inserting these conversions, which changes its input types and so
/// its selection.
pub conversions: Vec<Conversion>,
}
#[derive(Default)]
pub struct Registry {
pub implementations: FxHashMap<IdentifierId, Vec<Signature>>,
pub coercions: Coercions,
/// Keyed by the element of the adapter's `List` side.
promotion_adapters: FxHashMap<(PromotionKind, TypeId), IdentifierId>,
selection_indices: FxHashMap<Box<[u32]>, u32>,
selections: Vec<Result<Selection, String>>,
key: Vec<u32>,
}
fn collect_generics(types: &TypeInterner, call_argument: TypeId, inputs: &[TypeId], output: TypeId) -> Vec<u32> {
let mut generics = Vec::new();
for ty in [call_argument].into_iter().chain(inputs.iter().copied()).chain([output]) {
types.collect_generics(ty, &mut generics);
}
generics
}
/// Binds the generics in `expected` to the matching parts of `provided`, failing when one generic would bind two types.
/// Concrete parts are not compared, since `TypeInterner::valid` checks them.
fn bind_generics(types: &TypeInterner, expected: TypeId, provided: TypeId, bindings: &mut Vec<(u32, TypeId)>) -> bool {
match (types.get(expected), types.get(provided)) {
(TypeData::Generic(name), _) => match bindings.iter().find(|(generic, _)| *generic == name) {
Some(&(_, bound)) => bound == provided,
None => {
bindings.push((name, provided));
true
}
},
(TypeData::Fn(expected_input, expected_output), TypeData::Fn(provided_input, provided_output)) => {
bind_generics(types, expected_input, provided_input, bindings) && bind_generics(types, expected_output, provided_output, bindings)
}
(TypeData::Item(expected), TypeData::Item(provided)) | (TypeData::List(expected), TypeData::List(provided)) => bind_generics(types, expected, provided, bindings),
_ => true,
}
}
impl Registry {
pub fn add(&mut self, types: &TypeInterner, identifier: IdentifierId, call_argument: TypeId, inputs: Vec<TypeId>, output: TypeId) {
let generics = collect_generics(types, call_argument, &inputs, output);
self.implementations.entry(identifier).or_default().push(Signature {
call_argument,
inputs,
output,
generics,
});
}
pub fn index_promotion_adapters(&mut self, types: &TypeInterner, strings: &Strings) {
for (&identifier, signatures) in &self.implementations {
let name = strings.name(identifier.0);
let Some(&(_, kind)) = PromotionKind::ADAPTER_PREFIXES.iter().find(|(prefix, _)| name.starts_with(prefix)) else {
continue;
};
let [signature] = signatures.as_slice() else { continue };
let [input] = signature.inputs.as_slice() else { continue };
let list_side = if kind == PromotionKind::Bundle { types.nested(*input) } else { signature.output };
if let TypeData::List(element) = types.get(list_side) {
self.promotion_adapters.insert((kind, element), identifier);
}
}
}
pub fn clear_selections(&mut self) {
self.selection_indices.clear();
self.selections.clear();
}
pub fn select(&mut self, types: &mut TypeInterner, identifier: IdentifierId, call_argument: TypeId, inputs: &[TypeId]) -> Result<&Selection, String> {
let index = self.select_index(types, identifier, call_argument, inputs);
self.selection(index)
}
pub fn selection(&self, index: u32) -> Result<&Selection, String> {
self.selections[index as usize].as_ref().map_err(Clone::clone)
}
/// Selects the implementation and returns the memoized result's index, which stays valid until selections are cleared.
pub fn select_index(&mut self, types: &mut TypeInterner, identifier: IdentifierId, call_argument: TypeId, inputs: &[TypeId]) -> u32 {
self.key.clear();
self.key.push(identifier.0);
self.key.push(call_argument.0);
self.key.extend(inputs.iter().map(|input| input.0));
match self.selection_indices.get(self.key.as_slice()) {
Some(&index) => index,
None => {
let selection = self.resolve(types, identifier, call_argument, inputs);
let index = self.selections.len() as u32;
self.selections.push(selection);
self.selection_indices.insert(self.key.clone().into_boxed_slice(), index);
index
}
}
}
fn resolve(&self, types: &mut TypeInterner, identifier: IdentifierId, call_argument: TypeId, inputs: &[TypeId]) -> Result<Selection, String> {
let implementations = self.implementations.get(&identifier).ok_or("No implementations found")?;
if inputs.iter().any(|&input| matches!(types.get(input), TypeData::Fn(_, output) if types.generic_name(output).is_some())) {
return Err("Generic inputs should not exist".to_string());
}
let mut valid = Vec::new();
for (index, signature) in implementations.iter().enumerate() {
let matches = types.valid(signature.call_argument, call_argument) && inputs.iter().zip(&signature.inputs).all(|(&provided, &expected)| types.valid(provided, expected));
if !matches {
continue;
}
if let Some((substituted_call, substituted_output)) = substitute_generics(types, signature, call_argument, inputs) {
valid.push((index, substituted_call, substituted_output));
}
}
let selected = match valid.as_slice() {
[] => return self.resolve_adapted(types, implementations, call_argument, inputs),
[single] => *single,
[first, second] => {
let unit = types.concrete(crate::baseline::types::UNIT_NAME);
match [first, second].into_iter().find(|candidate| first.1 != second.1 && candidate.1 == unit) {
Some(candidate) => *candidate,
None => return Err("Multiple implementations found".to_string()),
}
}
_ => return Err("Multiple implementations found".to_string()),
};
let (implementation, call, output) = selected;
Ok(Selection {
implementation: implementation as u32,
return_type: output,
fn_type: types.function(call, output),
promotions: Vec::new(),
conversions: Vec::new(),
})
}
/// Plans how one input reaches its connector: unchanged, promoted, converted, or converted at its own rank and then
/// promoted. Conversions need a concrete connector element, since the target must be known to pick one.
fn plan_edge(&self, types: &mut TypeInterner, provided: TypeId, expected: TypeId) -> Option<EdgePlan> {
if types.valid(provided, expected) {
return Some(EdgePlan::unchanged(provided));
}
let call_argument = types.fn_input(provided)?;
if !types.valid(call_argument, types.fn_input(expected)?) {
return None;
}
let concrete_connector = !contains_generic(types, expected);
if let Some((kind, element)) = promotion_between(types, provided, expected) {
let element = match (kind, types.get(types.nested(provided))) {
(PromotionKind::ItemToList, TypeData::Item(provided_element)) if !concrete_connector => provided_element,
_ if concrete_connector => element,
_ => return None,
};
let adapter = *self.promotion_adapters.get(&(kind, element))?;
let adapted = match concrete_connector {
true => expected,
false => {
let list = types.intern(TypeData::List(element));
types.function(call_argument, list)
}
};
return Some(EdgePlan {
adapted,
conversion: None,
promotion: Some(adapter),
target: None,
});
}
if !concrete_connector {
return None;
}
let (provided_wire, expected_wire) = (types.nested(provided), types.nested(expected));
if let Some(conversion) = self.coercions.wire_conversion(provided_wire, expected_wire) {
return Some(EdgePlan {
adapted: expected,
conversion: Some(conversion),
promotion: None,
target: Some(expected_wire),
});
}
let (from_rank, from) = Coercions::ranked_element(types, provided)?;
let (to_rank, to) = Coercions::ranked_element(types, expected)?;
let conversion = self.coercions.automatic_conversion(from, to, from_rank)?;
let promotion = match (from_rank, to_rank) {
(from_rank, to_rank) if from_rank == to_rank => None,
(Rank::Item, Rank::List) => Some(*self.promotion_adapters.get(&(PromotionKind::ItemToList, to))?),
_ => return None,
};
Some(EdgePlan {
adapted: expected,
conversion: Some(conversion),
promotion,
target: Some(to),
})
}
/// Selects among all implementations reachable by adapting inputs, each input taking at most one conversion followed by at
/// most one promotion. Candidates rank by fewest lossy conversions, then purity-losing ones, then representation changes,
/// then promotions. Remaining ties go to the candidate whose converted inputs receive the purest data, or are ambiguous.
fn resolve_adapted(&self, types: &mut TypeInterner, implementations: &[Signature], call_argument: TypeId, inputs: &[TypeId]) -> Result<Selection, String> {
let mut candidates: Vec<Candidate> = Vec::new();
'implementations: for (index, signature) in implementations.iter().enumerate() {
if !types.valid(signature.call_argument, call_argument) || inputs.len() != signature.inputs.len() {
continue;
}
let mut candidate = Candidate {
implementation: index,
..Default::default()
};
for (input, (&provided, &expected)) in inputs.iter().zip(&signature.inputs).enumerate() {
let Some(plan) = self.plan_edge(types, provided, expected) else { continue 'implementations };
candidate.adapted.push(plan.adapted);
candidate.targets.push(plan.target);
if let Some(node) = plan.conversion {
candidate.conversions.push(Conversion { input: input as u32, node });
}
if let Some(adapter) = plan.promotion {
candidate.promotions.push(Promotion { input: input as u32, adapter });
}
}
let Some((call, output)) = substitute_generics(types, signature, call_argument, &candidate.adapted) else {
continue;
};
candidate.substituted = (call, output);
candidates.push(candidate);
}
let Some(cheapest) = candidates.iter().map(Candidate::cost).min() else {
let provided: Vec<_> = inputs.iter().map(|&input| types.to_workload(types.nested(input))).collect();
return Err(format!("No implementation is reachable through automatic adaptation from {provided:?}"));
};
candidates.retain(|candidate| candidate.cost() == cheapest);
let at_least_as_pure = |a: &Candidate, b: &Candidate| {
a.targets.iter().zip(&b.targets).all(|pair| match pair {
(Some(a), Some(b)) => a == b || self.coercions.is_purer(*a, *b),
_ => true,
})
};
let best: Vec<_> = candidates.iter().filter(|candidate| candidates.iter().all(|other| at_least_as_pure(candidate, other))).collect();
let [best] = best.as_slice() else {
return Err(if cheapest.0 + cheapest.1 + cheapest.2 > 0 {
"Ambiguous automatic conversions"
} else {
"Invalid implementations"
}
.to_string());
};
let (call, output) = best.substituted;
Ok(Selection {
implementation: best.implementation as u32,
return_type: output,
fn_type: types.function(call, output),
promotions: best.promotions.clone(),
conversions: best.conversions.clone(),
})
}
}
struct EdgePlan {
adapted: TypeId,
conversion: Option<ConversionNode>,
promotion: Option<IdentifierId>,
/// The element a conversion produces, which ranks candidates by purity.
target: Option<TypeId>,
}
impl EdgePlan {
fn unchanged(provided: TypeId) -> Self {
Self {
adapted: provided,
conversion: None,
promotion: None,
target: None,
}
}
}
#[derive(Default)]
struct Candidate {
implementation: usize,
adapted: Vec<TypeId>,
targets: Vec<Option<TypeId>>,
conversions: Vec<Conversion>,
promotions: Vec<Promotion>,
substituted: (TypeId, TypeId),
}
impl Candidate {
fn cost(&self) -> (usize, usize, usize, usize) {
let count = |kind| self.conversions.iter().filter(|conversion| conversion.node.kind == kind).count();
(
count(ConversionKind::Lossy),
count(ConversionKind::PurityLosing),
count(ConversionKind::Representation),
self.promotions.len(),
)
}
}
fn contains_generic(types: &TypeInterner, ty: TypeId) -> bool {
match types.get(ty) {
TypeData::Generic(_) => true,
TypeData::Concrete(_) => false,
TypeData::Item(element) | TypeData::List(element) => contains_generic(types, element),
TypeData::Fn(input, output) => contains_generic(types, input) || contains_generic(types, output),
}
}
/// Resolves the signature's generics against the provided types like `check_generic` and `replace_generics`, returning the substituted call argument and output.
fn substitute_generics(types: &mut TypeInterner, signature: &Signature, call_argument: TypeId, inputs: &[TypeId]) -> Option<(TypeId, TypeId)> {
if signature.generics.is_empty() {
return Some((signature.call_argument, signature.output));
}
let mut bindings: Vec<(u32, TypeId)> = Vec::with_capacity(signature.generics.len());
let pairs = [(signature.call_argument, call_argument)]
.into_iter()
.chain(signature.inputs.iter().copied().zip(inputs.iter().copied()));
for (expected, provided) in pairs {
if !bind_generics(types, expected, provided, &mut bindings) {
return None;
}
}
if signature.generics.iter().any(|generic| !bindings.iter().any(|(bound, _)| bound == generic)) {
return None;
}
let replace = |name: u32| bindings.iter().find(|(generic, _)| *generic == name).map(|(_, ty)| *ty);
Some((types.substitute(signature.call_argument, &replace), types.substitute(signature.output, &replace)))
}
fn promotion_between(types: &TypeInterner, provided: TypeId, expected: TypeId) -> Option<(PromotionKind, TypeId)> {
let (TypeData::Fn(provided_input, provided_output), TypeData::Fn(expected_input, expected_output)) = (types.get(provided), types.get(expected)) else {
return None;
};
if !types.valid(provided_input, expected_input) {
return None;
}
let (from, to) = (types.nested(provided_output), types.nested(expected_output));
match (types.get(from), types.get(to)) {
(TypeData::Item(from_element), TypeData::List(element)) if types.valid(from_element, element) => Some((PromotionKind::ItemToList, element)),
(TypeData::List(element), TypeData::Item(_)) if types.bundle_element_name(to).is_some() && types.bundle_element_name(to) == types.concrete_name(element) => {
Some((PromotionKind::Bundle, element))
}
(TypeData::Item(_), TypeData::List(element)) if types.bundle_element_name(from).is_some() && types.bundle_element_name(from) == types.concrete_name(element) => {
Some((PromotionKind::Unbundle, element))
}
_ => None,
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Interned types: every structurally distinct type is a `TypeId`, so equality is an integer compare and nothing is cloned.
use crate::workload;
use rustc_hash::FxHashMap;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TypeId(pub u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum TypeData {
Generic(u32),
Concrete(u32),
Fn(TypeId, TypeId),
Item(TypeId),
List(TypeId),
}
#[derive(Default)]
pub struct TypeInterner {
data: Vec<TypeData>,
ids: FxHashMap<TypeData, TypeId>,
names: Vec<String>,
name_ids: FxHashMap<String, u32>,
}
impl TypeInterner {
pub fn intern(&mut self, data: TypeData) -> TypeId {
if let Some(&id) = self.ids.get(&data) {
return id;
}
let id = TypeId(self.data.len() as u32);
self.data.push(data);
self.ids.insert(data, id);
id
}
pub fn get(&self, id: TypeId) -> TypeData {
self.data[id.0 as usize]
}
pub fn name_id(&mut self, name: &str) -> u32 {
if let Some(&id) = self.name_ids.get(name) {
return id;
}
let id = self.names.len() as u32;
self.names.push(name.to_string());
self.name_ids.insert(name.to_string(), id);
id
}
pub fn name(&self, id: u32) -> &str {
&self.names[id as usize]
}
pub fn concrete(&mut self, name: &str) -> TypeId {
let name = self.name_id(name);
self.intern(TypeData::Concrete(name))
}
pub fn function(&mut self, input: TypeId, output: TypeId) -> TypeId {
self.intern(TypeData::Fn(input, output))
}
pub fn convert(&mut self, ty: &workload::Type) -> TypeId {
let data = match ty {
workload::Type::Generic(name) => TypeData::Generic(self.name_id(name)),
workload::Type::Concrete(name) => TypeData::Concrete(self.name_id(name)),
workload::Type::Fn(input, output) => TypeData::Fn(self.convert(input), self.convert(output)),
workload::Type::Item(element) => TypeData::Item(self.convert(element)),
workload::Type::List(element) => TypeData::List(self.convert(element)),
};
self.intern(data)
}
pub fn to_workload(&self, id: TypeId) -> workload::Type {
match self.get(id) {
TypeData::Generic(name) => workload::Type::Generic(self.name(name).to_string()),
TypeData::Concrete(name) => workload::Type::Concrete(self.name(name).to_string()),
TypeData::Fn(input, output) => workload::Type::Fn(Box::new(self.to_workload(input)), Box::new(self.to_workload(output))),
TypeData::Item(element) => workload::Type::Item(Box::new(self.to_workload(element))),
TypeData::List(element) => workload::Type::List(Box::new(self.to_workload(element))),
}
}
/// Whether a value of type `from` may feed a connector of type `to`, as `valid_type` in Graphite.
pub fn valid(&self, from: TypeId, to: TypeId) -> bool {
if from == to {
return true;
}
match (self.get(from), self.get(to)) {
(TypeData::Generic(_), _) | (_, TypeData::Generic(_)) => true,
(TypeData::Fn(in1, out1), TypeData::Fn(in2, out2)) => self.valid(out2, out1) && self.valid(in1, in2),
(TypeData::Item(element1), TypeData::Item(element2)) | (TypeData::List(element1), TypeData::List(element2)) => self.valid(element1, element2),
_ => false,
}
}
pub fn nested(&self, id: TypeId) -> TypeId {
match self.get(id) {
TypeData::Fn(_, output) => self.nested(output),
_ => id,
}
}
pub fn fn_input(&self, id: TypeId) -> Option<TypeId> {
match self.get(id) {
TypeData::Fn(input, _) => Some(input),
_ => None,
}
}
pub fn fn_output(&self, id: TypeId) -> Option<TypeId> {
match self.get(id) {
TypeData::Fn(_, output) => Some(output),
_ => None,
}
}
pub fn generic_name(&self, id: TypeId) -> Option<u32> {
match self.get(id) {
TypeData::Generic(name) => Some(name),
_ => None,
}
}
/// Replaces every generic anywhere in `id`, such as the `T` in `Fn(Context, List<T>)`.
pub fn substitute(&mut self, id: TypeId, replace: &impl Fn(u32) -> Option<TypeId>) -> TypeId {
let data = match self.get(id) {
TypeData::Generic(name) => return replace(name).unwrap_or(id),
TypeData::Concrete(_) => return id,
TypeData::Fn(input, output) => TypeData::Fn(self.substitute(input, replace), self.substitute(output, replace)),
TypeData::Item(element) => TypeData::Item(self.substitute(element, replace)),
TypeData::List(element) => TypeData::List(self.substitute(element, replace)),
};
self.intern(data)
}
/// Collects every generic name anywhere in `id`.
pub fn collect_generics(&self, id: TypeId, generics: &mut Vec<u32>) {
match self.get(id) {
TypeData::Generic(name) if !generics.contains(&name) => generics.push(name),
TypeData::Generic(_) | TypeData::Concrete(_) => {}
TypeData::Fn(input, output) => {
self.collect_generics(input, generics);
self.collect_generics(output, generics);
}
TypeData::Item(element) | TypeData::List(element) => self.collect_generics(element, generics),
}
}
pub fn bundle_element_name(&self, id: TypeId) -> Option<&str> {
let TypeData::Item(element) = self.get(id) else { return None };
let TypeData::Concrete(name) = self.get(element) else { return None };
self.name(name).strip_prefix("core_types::list::Bundle<")?.strip_suffix('>')
}
pub fn concrete_name(&self, id: TypeId) -> Option<&str> {
match self.get(id) {
TypeData::Concrete(name) => Some(self.name(name)),
_ => None,
}
}
}
@@ -0,0 +1,85 @@
//! The typing pass: selects each node's implementation from its input types and records the result per node.
use super::ir::{Ir, NewNode};
use super::registry::{Conversion, Promotion, Registry};
use super::types::{TypeId, TypeInterner};
/// The typing of a node about to be built, or the conversions its inputs need first.
pub enum Inferred {
Typed(TypeInfo),
NeedsConversions(Box<[Conversion]>),
}
#[derive(Clone, Copy, Debug)]
pub struct TypeInfo {
pub return_type: TypeId,
pub fn_type: TypeId,
pub implementation: u32,
}
pub struct Typing {
pub types: TypeInterner,
pub registry: Registry,
/// Indexed by IR node ID.
pub info: Vec<TypeInfo>,
context: TypeId,
scratch: Vec<TypeId>,
}
impl Typing {
pub fn new(types: TypeInterner, registry: Registry, context: TypeId) -> Self {
Self {
types,
registry,
info: Vec::new(),
context,
scratch: Vec::new(),
}
}
pub fn clear(&mut self) {
self.info.clear();
}
/// Selects the implementation for a node with these inputs, returning the selection's index for `infer`.
pub fn select(&mut self, node: &NewNode, inputs: &[u32]) -> u32 {
self.scratch.clear();
self.scratch.extend(inputs.iter().map(|&input| self.info[input as usize].fn_type));
self.registry.select_index(&mut self.types, node.identifier, node.call_argument, &self.scratch)
}
/// The conversions a selection needs inserted on its inputs before the node can be built.
pub fn conversions(&self, selection: u32) -> Result<&[Conversion], String> {
self.registry.selection(selection).map(|selection| selection.conversions.as_slice())
}
/// The promotion adapters a selection needs inserted on its inputs after context analysis.
pub fn promotions(&self, selection: u32) -> Result<&[Promotion], String> {
self.registry.selection(selection).map(|selection| selection.promotions.as_slice())
}
/// Types a node, using `selected` when typing already selected its implementation for inputs of the same types.
pub fn infer(&mut self, ir: &Ir, node: &NewNode, inputs: &[u32], selected: Option<u32>) -> Result<Inferred, String> {
if let Some(value) = node.value {
let fn_type = self.types.function(self.context, value.ty);
return Ok(Inferred::Typed(TypeInfo {
return_type: value.ty,
fn_type,
implementation: 0,
}));
}
debug_assert!(inputs.iter().all(|&input| (input as usize) < ir.len()));
let selection = selected.unwrap_or_else(|| self.select(node, inputs));
let selection = self.registry.selection(selection)?;
if !selection.conversions.is_empty() {
return Ok(Inferred::NeedsConversions(selection.conversions.as_slice().into()));
}
Ok(Inferred::Typed(TypeInfo {
return_type: selection.return_type,
fn_type: selection.fn_type,
implementation: selection.implementation,
}))
}
}
@@ -0,0 +1,115 @@
//! Named context varargs: an injector binds a name to its value's type for its body, and readers inside the body take their
//! output type from the innermost binding of their name. A shared subgraph is lowered once per binding environment it reads.
use super::document::{IdentifierId, Strings};
use super::registry::Registry;
use super::types::{TypeData, TypeId, TypeInterner};
use crate::workload::{self, CompileMetadata};
use rustc_hash::FxHashMap;
pub const INJECT_VARARG: &str = "spike::InjectVarArg";
pub const READ_VARARG: &str = "spike::ReadVarArg";
const VARARGS: u32 = 1 << 6;
pub const INJECTION_METADATA: CompileMetadata = CompileMetadata {
extract: 0,
inject: VARARGS,
footprint_invariant: false,
forwards_input: false,
constant_inputs: 0,
};
pub const READ_METADATA: CompileMetadata = CompileMetadata {
extract: VARARGS,
inject: 0,
footprint_invariant: false,
forwards_input: false,
constant_inputs: 0,
};
/// The environment without bindings.
pub const ROOT: u32 = 0;
struct Binding {
parent: u32,
name: u64,
ty: TypeId,
depth: u32,
}
/// Binding chains interned so equal environments share an ID, which slots and readers key on.
pub struct Environments {
bindings: Vec<Binding>,
index: FxHashMap<(u32, u64, TypeId), u32>,
}
impl Default for Environments {
fn default() -> Self {
let root = Binding {
parent: ROOT,
name: 0,
ty: TypeId::default(),
depth: 0,
};
Self {
bindings: vec![root],
index: FxHashMap::default(),
}
}
}
impl Environments {
pub fn bind(&mut self, parent: u32, name: u64, ty: TypeId) -> u32 {
if let Some(&environment) = self.index.get(&(parent, name, ty)) {
return environment;
}
let depth = self.depth(parent) + 1;
self.bindings.push(Binding { parent, name, ty, depth });
let environment = (self.bindings.len() - 1) as u32;
self.index.insert((parent, name, ty), environment);
environment
}
pub fn depth(&self, environment: u32) -> u32 {
self.bindings[environment as usize].depth
}
/// The depth and type of the innermost binding of `name`.
pub fn resolve(&self, mut environment: u32, name: u64) -> Option<(u32, TypeId)> {
while environment != ROOT {
let binding = &self.bindings[environment as usize];
if binding.name == name {
return Some((binding.depth, binding.ty));
}
environment = binding.parent;
}
None
}
}
/// Registers the injector, generic over its name, value, and body types.
pub fn load(types: &mut TypeInterner, registry: &mut Registry, inject: IdentifierId, context: TypeId) {
let [name, value, body] = ["N", "V", "U"].map(|generic| types.convert(&workload::Type::Generic(generic.to_string())));
let inputs = [name, value, body].map(|ty| types.function(context, ty)).to_vec();
registry.add(types, inject, context, inputs, body);
}
/// The reader monomorphized for one bound type, registered on first use like the adapters' `ItemToListNode<T>`.
pub fn monomorphized_reader(types: &mut TypeInterner, strings: &mut Strings, registry: &mut Registry, context: TypeId, name_type: TypeId, ty: TypeId) -> IdentifierId {
let identifier = IdentifierId(strings.intern(&format!("{READ_VARARG}<{}>", display(types, ty))));
if !registry.implementations.contains_key(&identifier) {
let input = types.function(context, name_type);
registry.add(types, identifier, context, vec![input], ty);
}
identifier
}
fn display(types: &TypeInterner, ty: TypeId) -> String {
match types.get(ty) {
TypeData::Concrete(_) | TypeData::Generic(_) => types.concrete_name(ty).unwrap_or("?").to_string(),
TypeData::Item(element) => format!("Item<{}>", display(types, element)),
TypeData::List(element) => format!("List<{}>", display(types, element)),
TypeData::Fn(input, output) => format!("Fn({}) -> {}", display(types, input), display(types, output)),
}
}
+6
View File
@@ -0,0 +1,6 @@
//! Standalone performance spike for Graphite's graph compiler, built on workloads exported from Graphite.
pub mod baseline;
pub mod lean;
pub mod synthetic;
pub mod workload;
+291
View File
@@ -0,0 +1,291 @@
//! Synthetic workloads in the exported schema, built from real registry nodes so the baseline type checks them.
use crate::workload::{Implementation, Import, Input, Network, Node, NodeReference, Type, Value, load_network};
/// The ID `wrap_network_in_scope` gives the document network inside the editor's scope wrapper, followed by the render network.
const DOCUMENT_NODE: u64 = 0;
const RENDER_NODE: u64 = 1;
/// Places a document in the editor's scope wrapper, taken from an exported demo, as `wrap_network_in_scope` does.
/// Without `render`, the document is exported directly, for documents whose output is not a graphic.
pub fn wrap_in_scope(mut document: Network, render: bool) -> Network {
let mut scoped = load_network("procedural-string-lights");
scoped.definitions = std::mem::take(&mut document.definitions);
let (_, document_node) = scoped
.nodes
.iter_mut()
.find(|(id, _)| *id == DOCUMENT_NODE)
.expect("the scope wrapper should contain the document node");
document_node.implementation = Implementation::Network(document);
if !render {
scoped.nodes.retain(|(id, _)| *id != RENDER_NODE);
scoped.exports = vec![Input::Node(NodeReference { node: DOCUMENT_NODE, output: 0 })];
}
scoped
}
const ADD: &str = "math_nodes::AddNode";
const ANIMATION_TIME: &str = "graphene_core::animation::AnimationTimeNode";
const CONTEXT: &str = "core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>";
fn number() -> Type {
Type::Item(Box::new(Type::Concrete("f64".to_string())))
}
fn context() -> Type {
Type::Concrete(CONTEXT.to_string())
}
/// Accumulates the nodes of one network, handing out sequential IDs.
#[derive(Default)]
struct Builder {
nodes: Vec<(u64, Node)>,
next_value_hash: u64,
}
impl Builder {
fn push(&mut self, identifier: &str, inputs: Vec<Input>) -> Input {
self.push_implementation(Implementation::Proto(identifier.to_string()), inputs)
}
fn push_implementation(&mut self, implementation: Implementation, inputs: Vec<Input>) -> Input {
let id = self.nodes.len() as u64 + 1;
self.nodes.push((
id,
Node {
inputs,
call_argument: context(),
implementation,
visible: true,
skip_deduplication: false,
compile_metadata: None,
},
));
Input::Node(NodeReference { node: id, output: 0 })
}
/// A distinct constant, so deduplication by stable ID does not collapse the workload.
fn value(&mut self) -> Input {
self.next_value_hash += 1;
Input::Value(Value {
ty: number(),
hash: self.next_value_hash.wrapping_mul(0x9E37_79B9_7F4A_7C15),
size: 8,
exposed: false,
producer: None,
})
}
/// A leaf reading the animation time, which gives the nullification pass context features to track.
fn time(&mut self) -> Input {
self.push(ANIMATION_TIME, Vec::new())
}
fn add(&mut self, a: Input, b: Input) -> Input {
self.push(ADD, vec![a, b])
}
/// Sums the inputs with a balanced tree of adds.
fn reduce(&mut self, mut layer: Vec<Input>) -> Input {
while layer.len() > 1 {
let mut next = Vec::with_capacity(layer.len().div_ceil(2));
let mut pairs = layer.into_iter();
while let Some(a) = pairs.next() {
next.push(match pairs.next() {
Some(b) => self.add(a, b),
None => a,
});
}
layer = next;
}
layer.pop().expect("reduce needs at least one input")
}
fn finish(self, export: Input) -> Network {
Network {
exports: vec![export],
nodes: self.nodes,
scope_injections: Vec::new(),
definitions: Vec::new(),
generated: false,
}
}
/// Finishes the document network and places it in the editor's scope wrapper.
fn finish_document(self, export: Input) -> Network {
wrap_in_scope(self.finish(export), false)
}
}
/// A linear chain of `length` adds, alternating time and constant operands.
pub fn chain(length: usize) -> Network {
let mut builder = Builder::default();
let mut current = builder.time();
for i in 0..length {
let operand = if i % 2 == 0 { builder.value() } else { builder.time() };
current = builder.add(current, operand);
}
builder.finish_document(current)
}
/// `depth` layers of `width` adds where each node sums two neighbors of the layer below, so paths reconverge.
pub fn lattice(width: usize, depth: usize) -> Network {
let mut builder = Builder::default();
let mut layer: Vec<Input> = (0..width).map(|i| if i % 2 == 0 { builder.time() } else { builder.value() }).collect();
for _ in 0..depth {
layer = (0..width).map(|i| builder.add(layer[i].clone(), layer[(i + 1) % width].clone())).collect();
}
let export = builder.reduce(layer);
builder.finish_document(export)
}
/// One time leaf feeding `width` adds, summed by a balanced tree.
pub fn fan_out(width: usize) -> Network {
let mut builder = Builder::default();
let source = builder.time();
let consumers = (0..width)
.map(|_| {
let operand = builder.value();
builder.add(source.clone(), operand)
})
.collect();
let export = builder.reduce(consumers);
builder.finish_document(export)
}
/// A chain of `length` adds over a network import, used as the body of nested or instanced subnetworks.
fn import_chain(length: usize) -> Network {
let mut builder = Builder::default();
let mut current = Input::Import(Import { ty: number(), index: 0 });
for i in 0..length {
let operand = if i % 2 == 0 { builder.value() } else { builder.time() };
current = builder.add(current, operand);
}
builder.finish(current)
}
/// Subnetworks nested `depth` levels deep, each adding to the result of the level inside it.
pub fn nesting(depth: usize, chain_length: usize) -> Network {
let mut inner = import_chain(chain_length);
for _ in 0..depth {
let mut builder = Builder::default();
let nested = builder.push_implementation(Implementation::Network(inner), vec![Input::Import(Import { ty: number(), index: 0 })]);
let operand = builder.time();
let export = builder.add(nested, operand);
inner = builder.finish(export);
}
let mut builder = Builder::default();
let source = builder.time();
let export = builder.push_implementation(Implementation::Network(inner), vec![source]);
builder.finish_document(export)
}
fn node_inputs(node: &Node) -> impl Iterator<Item = u64> + '_ {
node.inputs.iter().filter_map(|input| match input {
Input::Node(reference) => Some(reference.node),
_ => None,
})
}
/// The layer node and the content chain feeding its second input, as copied from a document the editor drew.
fn layer_group(document: &Network, layer: u64) -> Vec<u64> {
let nodes: std::collections::HashMap<u64, &Node> = document.nodes.iter().map(|(id, node)| (*id, node)).collect();
let Input::Node(content) = &nodes[&layer].inputs[1] else {
panic!("A layer's second input should be its content")
};
let mut group = vec![layer];
let mut stack = vec![content.node];
while let Some(id) = stack.pop() {
if group.contains(&id) {
continue;
}
group.push(id);
stack.extend(node_inputs(nodes[&id]));
}
group
}
/// `count` rectangle layers stacked on each other, replicating the top layer of the editor-drawn `rectangle-layers` template.
/// Every layer keeps the real node chain the Rectangle tool creates and the document keeps the editor's render pipeline.
pub fn rectangle_layers(count: usize) -> Network {
let mut scoped = load_network("rectangle-layers");
let (_, document_node) = scoped
.nodes
.iter_mut()
.find(|(id, _)| *id == DOCUMENT_NODE)
.expect("the scope wrapper should contain the document node");
let Implementation::Network(document) = &mut document_node.implementation else {
panic!("The document node should be a network")
};
let [Input::Node(top)] = document.exports.as_slice() else {
panic!("The template should export its top layer")
};
let top_layer = top.node;
let template: std::collections::HashMap<u64, Node> = document.nodes.iter().cloned().collect();
// Walk down the layer stack to the bottom layer, whose stack input is a value
let mut bottom_layer = top_layer;
while let Input::Node(below) = &template[&bottom_layer].inputs[0] {
bottom_layer = below.node;
}
let mut nodes: Vec<(u64, Node)> = layer_group(document, bottom_layer).into_iter().map(|id| (id, template[&id].clone())).collect();
let top_group = layer_group(document, top_layer);
// Values that differ between the top layer and the one below it (like a rectangle's position) are made distinct per copy
let Input::Node(below_top) = &template[&top_layer].inputs[0] else {
panic!("The template should stack at least two layers")
};
let below_group = layer_group(document, below_top.node);
let varying_value = |id: u64, below_id: u64, input_index: usize| match (&template[&id].inputs[input_index], &template[&below_id].inputs[input_index]) {
(Input::Value(top), Input::Value(below)) => top.hash != below.hash,
_ => false,
};
let mut previous_layer = bottom_layer;
for copy in 1..count as u64 {
let remap = |id: u64| id.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(copy);
for (&id, &below_id) in top_group.iter().zip(&below_group) {
let mut node = template[&id].clone();
for (input_index, input) in node.inputs.iter_mut().enumerate() {
match input {
Input::Node(reference) => reference.node = remap(reference.node),
Input::Value(value) if varying_value(id, below_id, input_index) => value.hash = value.hash.wrapping_add(copy),
_ => {}
}
}
if id == top_layer {
node.inputs[0] = Input::Node(NodeReference { node: previous_layer, output: 0 });
}
nodes.push((remap(id), node));
}
previous_layer = remap(top_layer);
}
document.nodes = nodes;
document.exports = vec![Input::Node(NodeReference { node: previous_layer, output: 0 })];
scoped
}
/// `count` instances of one subnetwork definition, each fed by its own time leaf and summed by a balanced tree.
/// The instances name one shared definitions table entry, as nodes inserted from the catalog do.
pub fn instances(count: usize, chain_length: usize) -> Network {
const SHARED_DEFINITION: u64 = 1;
let mut builder = Builder::default();
let outputs = (0..count)
.map(|_| {
let source = builder.time();
builder.push_implementation(Implementation::Definition(SHARED_DEFINITION), vec![source])
})
.collect();
let export = builder.reduce(outputs);
let mut document = builder.finish(export);
document.definitions = vec![(SHARED_DEFINITION, import_chain(chain_length))];
wrap_in_scope(document, false)
}
+176
View File
@@ -0,0 +1,176 @@
//! The exported workload schema, mirroring `preprocessor/src/spike_export.rs` in Graphite.
use serde::Deserialize;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Hash)]
pub enum Type {
Generic(String),
Concrete(String),
Fn(Box<Type>, Box<Type>),
Item(Box<Type>),
List(Box<Type>),
}
#[derive(Clone, Debug, Deserialize)]
pub struct NodeReference {
pub node: u64,
pub output: usize,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Value {
pub ty: Type,
pub hash: u64,
pub size: usize,
pub exposed: bool,
pub producer: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Import {
pub ty: Type,
pub index: usize,
}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
pub enum Reflection {
DocumentNodePath,
SourceId,
}
#[derive(Clone, Debug, Deserialize)]
pub enum Input {
Node(NodeReference),
Value(Value),
Import(Import),
Scope(String),
Reflection(Reflection),
}
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash)]
pub struct CompileMetadata {
pub extract: u32,
pub inject: u32,
pub footprint_invariant: bool,
pub forwards_input: bool,
pub constant_inputs: u64,
}
#[derive(Clone, Debug, Deserialize)]
pub enum Implementation {
Network(Network),
/// An entry of the root network's definitions table.
Definition(u64),
Proto(String),
Extract,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Node {
pub inputs: Vec<Input>,
pub call_argument: Type,
pub implementation: Implementation,
pub visible: bool,
pub skip_deduplication: bool,
pub compile_metadata: Option<CompileMetadata>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Network {
pub exports: Vec<Input>,
pub nodes: Vec<(u64, Node)>,
pub scope_injections: Vec<(String, u64, Type)>,
/// The networks shared by the nodes naming them, which only the root network holds.
#[serde(default)]
pub definitions: Vec<(u64, Network)>,
pub generated: bool,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Signature {
pub call_argument: Type,
pub inputs: Vec<Type>,
pub output: Type,
}
#[derive(Clone, Debug, Deserialize)]
pub struct RegistryEntry {
pub identifier: String,
pub implementations: Vec<Signature>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Substitution {
pub identifier: String,
pub node: Node,
pub wrapped_node_id: u64,
}
#[derive(Clone, Debug, Deserialize)]
pub struct InjectScope {
pub identifier: String,
pub template: Node,
pub ty: Type,
}
#[derive(Clone, Debug, Deserialize)]
pub struct CompileMetadataEntry {
pub identifier: String,
pub metadata: CompileMetadata,
}
#[derive(Clone, Debug, Deserialize)]
pub struct PreprocessorTables {
pub substitutions: Vec<Substitution>,
pub inject_scopes: Vec<InjectScope>,
pub compile_metadata: Vec<CompileMetadataEntry>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct Expected {
pub proto_nodes: usize,
pub unique_stable_ids: usize,
pub distinct_identifiers: usize,
/// How many proto nodes have each identifier.
#[serde(default)]
pub identifier_counts: std::collections::BTreeMap<String, usize>,
pub output_type: Option<Type>,
}
pub const DEMO_ART: [&str; 7] = [
"changing-seasons",
"painted-dreams",
"red-dress",
"valley-of-spires",
"isometric-fountain",
"procedural-string-lights",
"parametric-dunescape",
];
pub fn workload_directory() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("workloads")
}
fn load<T: for<'de> Deserialize<'de>>(name: &str) -> T {
let path = workload_directory().join(format!("{name}.json"));
let content = std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("Failed to read {}: {error}", path.display()));
serde_json::from_str(&content).unwrap_or_else(|error| panic!("Failed to parse {}: {error}", path.display()))
}
pub fn load_network(name: &str) -> Network {
load(name)
}
pub fn load_registry() -> Vec<RegistryEntry> {
load("registry")
}
pub fn load_preprocessor_tables() -> PreprocessorTables {
load("preprocessor")
}
pub fn load_expected() -> HashMap<String, Expected> {
load("expected")
}
@@ -0,0 +1,98 @@
use compiler_spike::baseline::proto::{ConstructionArgs, ProtoNetwork};
use compiler_spike::baseline::types::TypeNames;
use compiler_spike::baseline::{Baseline, CONTEXT_MODIFICATION, MEMOIZE};
use compiler_spike::workload::{DEMO_ART, load_expected};
use std::collections::{HashMap, HashSet};
#[test]
fn baseline_matches_graphite() {
let mut baseline = Baseline::load();
let expected = load_expected();
for name in DEMO_ART.into_iter().chain(["rectangle-layers"]) {
let network = baseline.load_network(name);
let proto_network = baseline.compile(baseline.preprocess(network)).unwrap_or_else(|error| panic!("{name} failed to compile: {error}"));
let unique_stable_ids: HashSet<_> = proto_network.nodes.iter().map(|(id, _)| *id).collect();
let distinct_identifiers: HashSet<_> = proto_network.nodes.iter().map(|(_, node)| node.identifier.clone()).collect();
let expected = &expected[name];
let mut identifier_counts = std::collections::BTreeMap::<String, usize>::new();
for (_, node) in &proto_network.nodes {
*identifier_counts.entry(node.identifier.to_string()).or_default() += 1;
}
let differing: Vec<_> = identifier_counts
.keys()
.chain(expected.identifier_counts.keys())
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.filter_map(|identifier| {
let (actual, graphite) = (
identifier_counts.get(identifier).copied().unwrap_or(0),
expected.identifier_counts.get(identifier).copied().unwrap_or(0),
);
(actual != graphite).then(|| format!("{identifier}: {actual} instead of {graphite}"))
})
.collect();
assert!(differing.is_empty(), "{name}: proto nodes per identifier differ:\n{}", differing.join("\n"));
assert_eq!(proto_network.nodes.len(), expected.proto_nodes, "{name}: proto node count");
assert_eq!(unique_stable_ids.len(), expected.unique_stable_ids, "{name}: unique stable ID count");
assert_eq!(distinct_identifiers.len(), expected.distinct_identifiers, "{name}: distinct identifier count");
let executor = baseline.build_executor(proto_network).unwrap_or_else(|error| panic!("{name} failed to type check: {error}"));
let expected_output = expected.output_type.as_ref().map(TypeNames::convert_deserialized);
assert_eq!(executor.output_type(), expected_output, "{name}: output type");
}
}
/// Replicating the template's top layer back up to three layers rebuilds a graph equivalent to the template the editor drew.
#[test]
fn rectangle_layers_generator_matches_the_editor_template() {
let mut baseline = Baseline::load();
let expected = &load_expected()["rectangle-layers"];
let network = baseline.convert_network(&compiler_spike::synthetic::rectangle_layers(3));
let proto_network = baseline.compile(baseline.preprocess(network)).unwrap();
let unique_stable_ids: HashSet<_> = proto_network.nodes.iter().map(|(id, _)| *id).collect();
assert_eq!(proto_network.nodes.len(), expected.proto_nodes);
assert_eq!(unique_stable_ids.len(), expected.unique_stable_ids);
baseline.build_executor(proto_network).unwrap();
}
/// Unique nodes of the compiled network, and how many nullification nodes directly wrap another nullification node.
fn unique_nodes_and_nested_nullifications(proto_network: &ProtoNetwork) -> (usize, usize) {
let nodes: HashMap<_, _> = proto_network.nodes.iter().map(|(id, node)| (*id, node)).collect();
let first_input = |id| match &nodes[&id].construction_args {
ConstructionArgs::Nodes(inputs) => inputs.first().copied(),
_ => None,
};
let nullifications: HashSet<_> = proto_network.nodes.iter().filter(|(_, node)| node.identifier == CONTEXT_MODIFICATION).map(|(id, _)| *id).collect();
let nested = nullifications
.iter()
.filter(|&&id| first_input(id).is_some_and(|memoize| nodes[&memoize].identifier == MEMOIZE && first_input(memoize).is_some_and(|inner| nullifications.contains(&inner))))
.count();
(nodes.len(), nested)
}
/// Graphite reanalyzed a shared node once per path reaching it before #4834, and each revisit wrapped its existing nullification in
/// another one stripping the same features. Memoizing the analysis removes exactly those redundant memoize and nullification pairs.
#[test]
fn memoized_context_analysis_only_removes_nested_nullifications() {
let mut baseline = Baseline::load();
for name in DEMO_ART {
let network = baseline.load_network(name);
let mut compile = |memoize| {
baseline.memoize_context_analysis = memoize;
unique_nodes_and_nested_nullifications(&baseline.compile(baseline.preprocess(network.clone())).unwrap())
};
let (faithful_nodes, faithful_nested) = compile(false);
let (memoized_nodes, memoized_nested) = compile(true);
assert_eq!(memoized_nested, 0, "{name}: memoized analysis left nested nullifications");
assert_eq!(
faithful_nodes - memoized_nodes,
2 * faithful_nested,
"{name}: memoizing removed more than the nested nullification pairs"
);
}
}
@@ -0,0 +1,40 @@
use compiler_spike::lean::Lean;
use compiler_spike::lean::codegen::{self, Erasure, Evaluation};
use compiler_spike::workload::{DEMO_ART, load_network};
use std::path::PathBuf;
use std::process::Command;
fn type_check(name: &str, source: &str) -> Result<(), String> {
let directory = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("codegen");
std::fs::create_dir_all(&directory).map_err(|error| error.to_string())?;
let path = directory.join(format!("{name}.rs"));
std::fs::write(&path, source).map_err(|error| error.to_string())?;
let result = Command::new("rustc")
.args(["--edition", "2024", "--crate-type", "lib", "--emit", "metadata", "--out-dir"])
.arg(&directory)
.arg(&path)
.output()
.map_err(|error| error.to_string())?;
if result.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&result.stderr).lines().take(40).collect::<Vec<_>>().join("\n"))
}
}
#[test]
fn erased_emitted_demos_type_check() {
let mut lean = Lean::load();
for name in DEMO_ART.into_iter().chain(["rectangle-layers"]) {
let document = lean.convert_document(&load_network(name));
let output = lean.compile(&document).unwrap_or_else(|error| panic!("{name} failed to compile: {error}")).output;
for (erasure, evaluation) in [(Erasure::Bounded, Evaluation::Sync), (Erasure::Everywhere, Evaluation::Async)] {
let emitted = codegen::emit(&lean, output, erasure, evaluation);
if let Err(error) = type_check(&format!("{name}-{erasure:?}-{evaluation:?}"), &emitted.source) {
panic!("{name} ({erasure:?}, {evaluation:?}): emitted source does not type check:\n{error}");
}
}
}
}
+158
View File
@@ -0,0 +1,158 @@
use compiler_spike::baseline::types::CONTEXT_NAME;
use compiler_spike::lean::Lean;
use compiler_spike::synthetic::wrap_in_scope;
use compiler_spike::workload::{Implementation, Input, Network, Node, NodeReference, Type, Value};
const COLOR: &str = "core_types::color::color_types::Color";
const VECTOR: &str = "vector_types::vector::vector_types::Vector";
const GRADIENT: &str = "vector_types::gradient::Gradient";
const RASTER_CPU: &str = "raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>";
const RASTER_GPU: &str = "raster_types::raster_types::Raster<raster_types::raster_types::gpu::GPU>";
/// What compiling a value of `element` fed into `node` produced: the output's element type, and the identifier and input
/// count of the node feeding it.
struct Coerced {
output: Type,
feeding: String,
feeding_inputs: Vec<String>,
feeding_reads_footprint: bool,
/// The identifiers from the consumer's input down to the value, following first inputs.
chain: Vec<String>,
}
fn feed(element: &str, node: &str) -> Result<Coerced, String> {
let value = Input::Value(Value {
ty: Type::Item(Box::new(Type::Concrete(element.to_string()))),
hash: 7,
size: 8,
exposed: false,
producer: None,
});
let consumer = Node {
inputs: vec![value],
call_argument: Type::Concrete(CONTEXT_NAME.to_string()),
implementation: Implementation::Proto(node.to_string()),
visible: true,
skip_deduplication: false,
compile_metadata: None,
};
let document = Network {
exports: vec![Input::Node(NodeReference { node: 1, output: 0 })],
nodes: vec![(1, consumer)],
scope_injections: Vec::new(),
definitions: Vec::new(),
generated: false,
};
let mut lean = Lean::load();
let document = lean.convert_document(&wrap_in_scope(document, false));
let output = lean.compile(&document)?.output;
let [feeding] = lean.ir.inputs(output) else {
return Err("The consumer should have one input".to_string());
};
let feeding = *feeding;
let mut chain = Vec::new();
let mut current = Some(feeding);
while let Some(id) = current {
chain.push(lean.identifier_name(lean.ir.nodes[id as usize].identifier).to_string());
current = lean.ir.inputs(id).first().copied();
}
Ok(Coerced {
chain,
output: lean.typing.types.to_workload(lean.typing.info[output as usize].return_type),
feeding: lean.identifier_name(lean.ir.nodes[feeding as usize].identifier).to_string(),
feeding_inputs: lean
.ir
.inputs(feeding)
.iter()
.map(|&input| lean.identifier_name(lean.ir.nodes[input as usize].identifier).to_string())
.collect(),
feeding_reads_footprint: lean.ir.nodes[feeding as usize].compile_metadata.extract != 0,
})
}
fn item(element: &str) -> Type {
Type::Item(Box::new(Type::Concrete(element.to_string())))
}
#[test]
fn matching_inputs_need_no_conversion() {
let coerced = feed(VECTOR, "spike::Blur").unwrap();
assert_eq!(coerced.output, item(VECTOR));
assert_eq!(coerced.feeding, "core_types::value::ClonedNode");
}
#[test]
fn a_purer_input_converts_to_the_implementation_it_can_reach() {
// Color converts to Vector, while no conversion reaches Raster directly and chains are not followed
let coerced = feed(COLOR, "spike::Blur").unwrap();
assert_eq!(coerced.output, item(VECTOR));
assert_eq!(coerced.feeding, format!("graphene_core::ops::ConvertItemNode<{VECTOR}>"));
}
#[test]
fn the_purest_reachable_target_wins() {
// Color reaches both Vector and Gradient, and Gradient is purer
let coerced = feed(COLOR, "spike::Shade").unwrap();
assert_eq!(coerced.output, item(GRADIENT));
}
#[test]
fn conversions_regaining_purity_are_not_automatic() {
// Vectorizing exists as a conversion, but it would discard information to regain purity
assert!(feed(RASTER_CPU, "spike::VectorOnly").is_err());
}
#[test]
fn incomparable_targets_are_ambiguous() {
let error = feed(COLOR, "spike::Ambiguous").err().expect("Vector and String are incomparable");
assert!(error.contains("Ambiguous"), "{error}");
}
#[test]
fn representation_changes_convert_with_their_converter() {
let coerced = feed(RASTER_CPU, "spike::GpuOnly").unwrap();
assert_eq!(coerced.output, item(RASTER_GPU));
assert_eq!(coerced.feeding, format!("graphene_core::ops::ConvertItemNode<{RASTER_GPU}>"));
assert_eq!(coerced.feeding_inputs, ["core_types::value::ClonedNode", "graphene_std::platform_application_io::WgpuExecutorNode"]);
}
#[test]
fn only_rasterizing_conversions_read_the_footprint() {
assert!(!feed(COLOR, "spike::Blur").unwrap().feeding_reads_footprint);
assert!(feed(VECTOR, "spike::RasterOnly").unwrap().feeding_reads_footprint);
}
#[test]
fn conversions_apply_before_promotion() {
let coerced = feed("i64", "spike::NumberList").unwrap();
assert_eq!(coerced.output, Type::List(Box::new(Type::Concrete("f64".to_string()))));
assert_eq!(coerced.chain, ["graphene_core::ops::ItemToListNode<f64>", "input_adapter<f64>", "core_types::value::ClonedNode"]);
}
#[test]
fn registered_conversions_on_a_cycle_are_lossy_but_automatic() {
let coerced = feed("f64", "spike::Integer").unwrap();
assert_eq!(coerced.output, item("i64"));
assert_eq!(coerced.feeding, "input_adapter<i64>");
}
#[test]
fn lossy_conversions_rank_below_purity_losing_ones() {
// Integers convert to numbers only lossily but to text without loss, so the text implementation wins
let coerced = feed("i64", "spike::NumberOrText").unwrap();
assert_eq!(coerced.output, item("alloc::string::String"));
}
#[test]
fn promotion_reaches_generic_implementations() {
let coerced = feed(COLOR, "spike::GenericList").unwrap();
assert_eq!(coerced.output, Type::List(Box::new(Type::Concrete(COLOR.to_string()))));
assert_eq!(coerced.feeding, "graphene_core::ops::ItemToListNode<Color>");
}
#[test]
fn types_without_a_purity_relation_do_not_convert() {
assert!(feed("f64", "spike::VectorOnly").is_err());
}
@@ -0,0 +1,132 @@
use compiler_spike::lean::document::{Implementation, Input};
use compiler_spike::lean::{Document, Lean};
use compiler_spike::synthetic::{instances, rectangle_layers};
use compiler_spike::workload::load_network;
use std::collections::BTreeMap;
const TRANSFORM: &str = "transform_nodes::transform_nodes::TransformNode";
/// Unique nodes per identifier among the nodes reachable from the output, plus the output type.
fn summary(lean: &Lean, output: u32) -> (BTreeMap<String, usize>, compiler_spike::workload::Type) {
let mut counts = BTreeMap::new();
for id in lean.ir.reachable(output) {
let identifier = lean.identifier_name(lean.ir.nodes[id as usize].identifier).to_string();
*counts.entry(identifier).or_default() += 1;
}
(counts, lean.typing.types.to_workload(lean.typing.info[output as usize].return_type))
}
/// Every value input of a Transform node, in document order, as (definition, node, input).
fn transform_values(lean: &Lean, document: &Document) -> Vec<(u32, u32, usize)> {
let mut values = Vec::new();
for (definition_index, definition) in document.definitions.iter().enumerate() {
for (local, node) in definition.nodes.iter().enumerate() {
let Implementation::Proto(identifier) = node.implementation else { continue };
if lean.identifier_name(identifier) != TRANSFORM {
continue;
}
for (input, value) in definition.node_inputs(node).iter().enumerate() {
if matches!(value, Input::Value(_)) {
values.push((definition_index as u32, local as u32, input));
}
}
}
}
values
}
fn assert_incremental_matches_cold(incremental: &mut Lean, cold: &mut Lean, document: &mut Document, context: &str) {
let output = incremental.compile_incremental(document).unwrap().output;
let incremental_summary = summary(incremental, output);
let output = cold.compile(document).unwrap().output;
let cold_summary = summary(cold, output);
assert_eq!(incremental_summary, cold_summary, "{context}: the incremental compile differs from a cold compile");
}
#[test]
fn incremental_compiles_match_cold_compiles_after_value_edits() {
let mut incremental = Lean::load();
let mut cold = Lean::load();
let mut document = incremental.convert_document(&rectangle_layers(20));
let _ = cold.convert_document(&rectangle_layers(20));
assert_incremental_matches_cold(&mut incremental, &mut cold, &mut document, "initial compile");
assert_incremental_matches_cold(&mut incremental, &mut cold, &mut document, "unchanged recompile");
assert!(incremental.instance_statistics().instance_misses == 0, "An unchanged recompile should hit every instance");
let values = transform_values(&incremental, &document);
for (edit, &(definition, local, input)) in [values[0], values[values.len() / 2], values[values.len() - 1]].iter().enumerate() {
document.set_value(definition, local, input, 0xED17 + edit as u64);
assert_incremental_matches_cold(&mut incremental, &mut cold, &mut document, &format!("edit {edit}"));
}
}
#[test]
fn incremental_compiles_match_cold_compiles_on_the_demos() {
for name in ["red-dress", "changing-seasons"] {
let mut incremental = Lean::load();
let mut cold = Lean::load();
let network = load_network(name);
let mut document = incremental.convert_document(&network);
let _ = cold.convert_document(&network);
assert_incremental_matches_cold(&mut incremental, &mut cold, &mut document, name);
if let Some(&(definition, local, input)) = transform_values(&incremental, &document).first() {
document.set_value(definition, local, input, 0xED17);
assert_incremental_matches_cold(&mut incremental, &mut cold, &mut document, &format!("{name} after an edit"));
}
}
}
/// The value hashes reachable from the output, which an incremental compile that missed an edited instance would leave stale.
fn reachable_values(lean: &Lean, output: u32) -> Vec<u64> {
let mut values: Vec<u64> = lean
.ir
.reachable(output)
.into_iter()
.filter_map(|id| lean.ir.nodes[id as usize].value.map(|value| value.hash))
.collect();
values.sort_unstable();
values
}
#[test]
fn an_edit_inside_a_shared_definition_reaches_every_instance() {
const INSTANCES: usize = 8;
let mut incremental = Lean::load();
let mut cold = Lean::load();
let network = instances(INSTANCES, 4);
let mut document = incremental.convert_document(&network);
let _ = cold.convert_document(&network);
incremental.compile_incremental(&mut document).unwrap();
let (shared, definition) = document
.definitions
.iter()
.enumerate()
.find(|(_, definition)| definition.owners.len() == INSTANCES)
.expect("the instances should share one definition");
let (local, input) = definition
.nodes
.iter()
.enumerate()
.find_map(|(local, node)| {
definition
.node_inputs(node)
.iter()
.position(|input| matches!(input, Input::Value(_)))
.map(|input| (local as u32, input))
})
.expect("the shared definition should hold a value input");
let owners = definition.owners.clone();
document.set_value(shared as u32, local, input, 0xED17);
assert!(owners.iter().all(|owner| document.dirty_nodes.contains(owner)), "Every instance should be marked dirty");
let output = incremental.compile_incremental(&mut document).unwrap().output;
let incremental_values = reachable_values(&incremental, output);
let output = cold.compile(&document).unwrap().output;
assert_eq!(incremental_values, reachable_values(&cold, output));
assert!(incremental_values.contains(&0xED17), "The edited value should reach the output");
}
@@ -0,0 +1,107 @@
use compiler_spike::baseline::proto::ConstructionArgs;
use compiler_spike::baseline::types::Type;
use compiler_spike::baseline::{Baseline, CONTEXT_MODIFICATION, MEMOIZE, VALUE_NODE};
use compiler_spike::lean::executor::Executor;
use compiler_spike::lean::{InputAdapters, Lean};
use compiler_spike::workload::{DEMO_ART, load_expected, load_network};
use std::collections::{BTreeMap, BTreeSet, HashSet};
type Counts = BTreeMap<String, usize>;
fn nested(ty: &Type) -> &Type {
match ty {
Type::Fn(_, output) => nested(output),
_ => ty,
}
}
/// Unique nodes per identifier after stable ID deduplication, with promotions counted as the adapter node per promoted
/// input that lean builds, and optionally without input adapters that leave their input's type unchanged.
fn baseline_counts(baseline: &mut Baseline, name: &str, skip_identity_adapters: bool) -> Counts {
let network = baseline.load_network(name);
let proto_network = baseline.compile(baseline.preprocess(network)).unwrap();
let executor = baseline.build_executor(proto_network.clone()).unwrap_or_else(|error| panic!("{name} failed to type: {error}"));
let typing = &executor.typing_context;
let is_identity_adapter =
|id, identifier: &str| identifier.starts_with("input_adapter<") && typing.type_of(id).is_some_and(|types| types.inputs.first().is_some_and(|input| nested(input) == &types.return_value));
let unique: HashSet<_> = proto_network
.nodes
.iter()
.filter(|(id, node)| !(skip_identity_adapters && is_identity_adapter(*id, &node.identifier)))
.map(|(id, node)| (*id, node.identifier.to_string()))
.collect();
let mut adapters = HashSet::new();
for (id, node) in &proto_network.nodes {
let (Some(promotions), ConstructionArgs::Nodes(inputs)) = (typing.promotions(*id), &node.construction_args) else {
continue;
};
for (index, promotion) in promotions {
adapters.insert((inputs[*index], promotion.adapter_identifier()));
}
}
let mut counts = Counts::new();
for identifier in unique.into_iter().map(|(_, identifier)| identifier).chain(adapters.into_iter().map(|(_, identifier)| identifier)) {
*counts.entry(identifier).or_default() += 1;
}
counts
}
fn lean_counts(lean: &mut Lean, name: &str) -> Counts {
let expected = load_expected();
let document = lean.convert_document(&load_network(name));
let compiled = lean.compile(&document).unwrap_or_else(|error| panic!("{name} failed to compile: {error}"));
let (output, output_type) = (compiled.output, compiled.typing.info[compiled.output as usize].return_type);
assert_eq!(Executor::new(&compiled).nodes.len(), compiled.ir.len());
let identifiers: Vec<_> = compiled.ir.nodes.iter().map(|node| node.identifier).collect();
let mut counts = Counts::new();
for identifier in identifiers {
*counts.entry(lean.identifier_name(identifier).to_string()).or_default() += 1;
}
let output_type = lean.typing.types.to_workload(output_type);
assert_eq!(Some(output_type), expected[name].output_type, "{name}: output type");
assert!(output < lean.ir.len() as u32);
counts
}
fn assert_counts_match(name: &str, baseline: &Counts, lean: &Counts, ignored: &[&str]) {
let differing: Vec<_> = baseline
.keys()
.chain(lean.keys())
.collect::<BTreeSet<_>>()
.into_iter()
.filter(|identifier| !ignored.contains(&identifier.as_str()) && baseline.get(*identifier) != lean.get(*identifier))
.map(|identifier| (identifier.clone(), baseline.get(identifier).copied().unwrap_or(0), lean.get(identifier).copied().unwrap_or(0)))
.collect();
assert!(differing.is_empty(), "{name}: unique nodes per identifier differ (identifier, baseline, lean): {differing:#?}");
}
/// The lean pass hash-conses as it builds, so its IR should equal the memoized baseline's graph after stable ID deduplication.
#[test]
fn lean_matches_the_memoized_baseline() {
let mut baseline = Baseline::load();
baseline.memoize_context_analysis = true;
let mut lean = Lean::load_with(InputAdapters::Preprocessed);
for name in DEMO_ART.into_iter().chain(["rectangle-layers"]) {
assert_counts_match(name, &baseline_counts(&mut baseline, name, false), &lean_counts(&mut lean, name), &[]);
}
}
/// Without the preprocessor's wrappers, typing inserts exactly the input adapters that change a type. Values then feed
/// connectors directly instead of through a wrapper, which needs fewer nullifications, so those are not compared.
#[test]
fn resolved_adapters_match_the_converting_preprocessed_ones() {
let mut baseline = Baseline::load();
baseline.memoize_context_analysis = true;
let mut lean = Lean::load_with(InputAdapters::Resolved);
for name in DEMO_ART.into_iter().chain(["rectangle-layers"]) {
let ignored = [MEMOIZE, CONTEXT_MODIFICATION, VALUE_NODE];
assert_counts_match(name, &baseline_counts(&mut baseline, name, true), &lean_counts(&mut lean, name), &ignored);
}
}
+204
View File
@@ -0,0 +1,204 @@
use compiler_spike::baseline::types::CONTEXT_NAME;
use compiler_spike::lean::Lean;
use compiler_spike::synthetic::wrap_in_scope;
use compiler_spike::workload::{Implementation, Input, Network, Node, NodeReference, Type, Value};
use std::hash::{DefaultHasher, Hash, Hasher};
const COLOR: &str = "core_types::color::color_types::Color";
const VECTOR: &str = "vector_types::vector::vector_types::Vector";
const STRING: &str = "alloc::string::String";
const VARARGS: u32 = 1 << 6;
fn item(element: &str) -> Type {
Type::Item(Box::new(Type::Concrete(element.to_string())))
}
fn value(element: &str, hash: u64) -> Input {
Input::Value(Value {
ty: item(element),
hash,
size: 8,
exposed: false,
producer: None,
})
}
fn name(name: &str) -> Input {
let mut hasher = DefaultHasher::new();
name.hash(&mut hasher);
value(STRING, hasher.finish())
}
fn node(id: u64) -> Input {
Input::Node(NodeReference { node: id, output: 0 })
}
fn proto(identifier: &str, inputs: Vec<Input>) -> Node {
Node {
inputs,
call_argument: Type::Concrete(CONTEXT_NAME.to_string()),
implementation: Implementation::Proto(identifier.to_string()),
visible: true,
skip_deduplication: false,
compile_metadata: None,
}
}
fn read(variable: &str) -> Node {
proto("spike::ReadVarArg", vec![name(variable)])
}
fn inject(variable: &str, value: Input, body: Input) -> Node {
proto("spike::InjectVarArg", vec![name(variable), value, body])
}
fn network(nodes: Vec<(u64, Node)>, output: u64) -> Network {
Network {
exports: vec![node(output)],
nodes,
scope_injections: Vec::new(),
definitions: Vec::new(),
generated: false,
}
}
struct Compiled {
lean: Lean,
output: u32,
}
impl Compiled {
fn output_type(&self) -> Type {
self.lean.typing.types.to_workload(self.lean.typing.info[self.output as usize].return_type)
}
fn identifiers(&self) -> Vec<String> {
self.lean
.ir
.reachable(self.output)
.into_iter()
.map(|id| self.lean.identifier_name(self.lean.ir.nodes[id as usize].identifier).to_string())
.collect()
}
fn readers(&self) -> Vec<String> {
let mut readers: Vec<_> = self.identifiers().into_iter().filter(|identifier| identifier.starts_with("spike::ReadVarArg<")).collect();
readers.sort();
readers
}
fn node_with(&self, prefix: &str) -> u32 {
self.lean
.ir
.reachable(self.output)
.into_iter()
.find(|&id| self.lean.identifier_name(self.lean.ir.nodes[id as usize].identifier).starts_with(prefix))
.unwrap_or_else(|| panic!("No {prefix} node"))
}
}
fn compile(nodes: Vec<(u64, Node)>, output: u64) -> Result<Compiled, String> {
let mut lean = Lean::load();
let document = lean.convert_document(&wrap_in_scope(network(nodes, output), false));
let output = lean.compile(&document)?.output;
Ok(Compiled { lean, output })
}
#[test]
fn readers_take_the_type_of_their_binding() {
let compiled = compile(vec![(1, read("x")), (2, inject("x", value(COLOR, 1), node(1)))], 2).unwrap();
assert_eq!(compiled.output_type(), item(COLOR));
assert_eq!(compiled.readers(), [format!("spike::ReadVarArg<Item<{COLOR}>>")]);
}
#[test]
fn read_types_flow_into_selection_and_coercion() {
let compiled = compile(vec![(1, read("x")), (2, proto("spike::Blur", vec![node(1)])), (3, inject("x", value(COLOR, 1), node(2)))], 3).unwrap();
assert_eq!(compiled.output_type(), item(VECTOR));
assert!(compiled.identifiers().contains(&format!("graphene_core::ops::ConvertItemNode<{VECTOR}>")));
}
#[test]
fn shared_subgraphs_instantiate_once_per_binding_type() {
let nodes = vec![
(1, read("x")),
(2, proto("spike::Blur", vec![node(1)])),
(3, inject("x", value(COLOR, 1), node(2))),
(4, inject("x", value(VECTOR, 2), node(2))),
(5, inject("y", node(3), node(4))),
];
let compiled = compile(nodes, 5).unwrap();
assert_eq!(compiled.output_type(), item(VECTOR));
assert_eq!(compiled.readers(), [format!("spike::ReadVarArg<Item<{COLOR}>>"), format!("spike::ReadVarArg<Item<{VECTOR}>>")]);
let blurs = compiled.identifiers().into_iter().filter(|identifier| identifier == "spike::Blur").count();
assert_eq!(blurs, 2, "The Blur reading each binding is instantiated for it");
}
#[test]
fn bindings_of_the_same_type_share_their_readers() {
let nodes = vec![
(1, read("x")),
(2, inject("x", value(COLOR, 1), node(1))),
(3, inject("x", value(COLOR, 2), node(1))),
(4, inject("y", node(2), node(3))),
];
let compiled = compile(nodes, 4).unwrap();
assert_eq!(compiled.readers(), [format!("spike::ReadVarArg<Item<{COLOR}>>")]);
}
#[test]
fn inner_bindings_shadow_outer_ones() {
let nodes = vec![(1, read("x")), (2, inject("x", value(COLOR, 1), node(1))), (3, inject("x", value(VECTOR, 2), node(2)))];
assert_eq!(compile(nodes, 3).unwrap().output_type(), item(COLOR));
}
#[test]
fn readers_inside_nested_networks_see_outer_bindings() {
let inner = network(vec![(1, read("x"))], 1);
let mut instance = proto("unused", Vec::new());
instance.implementation = Implementation::Network(inner);
let compiled = compile(vec![(1, instance), (2, inject("x", value(COLOR, 1), node(1)))], 2).unwrap();
assert_eq!(compiled.output_type(), item(COLOR));
}
#[test]
fn unbound_readers_are_errors() {
let error = compile(vec![(1, read("x")), (2, inject("y", value(COLOR, 1), node(1)))], 2).err().expect("x is unbound");
assert!(error.contains("Unbound vararg"), "{error}");
}
#[test]
fn vararg_names_must_be_constants() {
let nodes = vec![(1, proto("spike::Blur", vec![value(VECTOR, 1)])), (2, proto("spike::ReadVarArg", vec![node(1)]))];
let error = compile(nodes, 2).err().expect("the name is computed");
assert!(error.contains("compile-time constants"), "{error}");
}
#[test]
fn injectors_supply_the_feature_their_readers_extract() {
let compiled = compile(vec![(1, read("x")), (2, inject("x", value(COLOR, 1), node(1)))], 2).unwrap();
let analysis = &compiled.lean.context.analysis;
assert_ne!(analysis[compiled.node_with("spike::ReadVarArg<") as usize].features & VARARGS, 0);
assert_eq!(analysis[compiled.node_with("spike::InjectVarArg") as usize].features & VARARGS, 0);
}
#[test]
fn incremental_compiles_match_cold_compiles_with_bindings() {
let nodes = vec![
(1, read("x")),
(2, proto("spike::Blur", vec![node(1)])),
(3, inject("x", value(COLOR, 1), node(2))),
(4, inject("x", value(VECTOR, 2), node(2))),
(5, inject("y", node(3), node(4))),
];
let mut lean = Lean::load();
let mut document = lean.convert_document(&wrap_in_scope(network(nodes, 5), false));
let cold = lean.compile(&document).unwrap().output;
let cold_nodes = lean.ir.reachable(cold).len();
let mut incremental = Lean::load();
for _ in 0..2 {
let output = incremental.compile_incremental(&mut document).unwrap().output;
assert_eq!(incremental.ir.reachable(output).len(), cold_nodes);
}
}
@@ -0,0 +1 @@
{"definitions":[[3075940105410955250,{"definitions":[],"exports":[{"Node":{"node":4,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete":"alloc::string::String"}}}},{"Node":{"node":2,"output":0}}],"skip_deduplication":false,"visible":true}],[4,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::ExtendNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Node":{"node":3,"output":0}}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[3373839479157045031,{"definitions":[],"exports":[{"Node":{"node":4,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete":"alloc::string::String"}}}},{"Node":{"node":2,"output":0}}],"skip_deduplication":false,"visible":true}],[4,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::ExtendNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Node":{"node":3,"output":0}}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[3515936097443090512,{"definitions":[],"exports":[{"Node":{"node":4,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete":"alloc::string::String"}}}},{"Node":{"node":2,"output":0}}],"skip_deduplication":false,"visible":true}],[4,{"call_argument":{"Generic":"T"},"compLine truncated
@@ -0,0 +1 @@
{"changing-seasons":{"distinct_identifiers":67,"identifier_counts":{"core_types::value::ClonedNode":203,"core_types::vector::MorphNode":1,"core_types::vector::ReadIndexNode":1,"core_types::vector::ScatterPointsNode":1,"graphene_core::context_modification::ContextModificationNode":51,"graphene_core::memo::MemoizeNode":69,"graphene_core::memo::MonitorNode":3,"graphene_core::vector::CountNode":1,"graphene_core::vector::FillNode":7,"graphene_core::vector::VaryFillColorsNode":1,"graphene_std::platform_application_io::ApplicationIoNode":1,"graphene_std::platform_application_io::EditorApiNode":1,"graphene_std::platform_application_io::WgpuExecutorNode":1,"graphene_std::render_background::CompositeBackgroundPipelineNode":1,"graphene_std::render_background::RenderBackgroundNode":1,"graphene_std::render_cache::RenderOutputCacheNode":1,"graphene_std::render_node::CreateContextNode":1,"graphene_std::render_node::RenderIntermediateNode":1,"graphene_std::render_node::RenderNode":1,"graphene_std::render_pixel_preview::PixelPreviewPipelineNode":1,"graphene_std::render_pixel_preview::RenderPixelPreviewNode":1,"graphic_nodes::artboard::CreateArtboardNode":1,"graphic_nodes::graphic::AsGraphicNode":10,"graphic_nodes::graphic::ColorsToGradientNode":1,"graphic_nodes::graphic::ExtendNode":11,"graphic_nodes::graphic::FlattenVectorNode":1,"graphic_nodes::graphic::GradientToColorsNode":2,"graphic_nodes::graphic::IntoGroupNode":11,"graphic_nodes::graphic::MirrorNode":2,"graphic_nodes::graphic::PathOfSubgraphNode":11,"graphic_nodes::graphic::WriteAttributeNode":11,"input_adapter<AttributeValueDyn>":11,"input_adapter<BlendMode>":1,"input_adapter<BooleanOperation>":2,"input_adapter<Box<VectorModification>>":3,"input_adapter<BoxCorners>":3,"input_adapter<Color>":10,"input_adapter<DAffine2>":7,"input_adapter<DVec2>":5,"input_adapter<Gradient>":12,"input_adapter<GradientForm>":7,"input_adapter<Graphic>":22,"input_adapter<InterpolationDistribution>":1,"input_adapter<ListDyn>":1,"input_adapter<NodeIdPath>":14,"input_adapter<ReferencePoint>":2,"input_adapter<String>":12,"input_adapter<Vector>":5,"input_adapter<bool>":25,"input_adapter<f64>":21,"input_adapter<i64>":10,"math_nodes::AsIntegerNode":1,"math_nodes::DivideNode":2,"math_nodes::GradientValueNode":2,"math_nodes::MathFxNode":1,"math_nodes::MaxNode":1,"math_nodes::PercentageValueNode":1,"math_nodes::SubtractNode":2,"path_bool_nodes::BooleanOperationNode":2,"raster_nodes::blending_nodes::MixColorsNode":1,"repeat_nodes::repeat_nodes::RepeatNode":1,"repeat_nodes::repeat_nodes::RepeatOnPointsNode":1,"transform_nodes::transform_nodes::TransformNode":1,"transform_nodes::transform_nodes::VaryRotationsNode":1,"transform_nodes::transform_nodes::VaryScalesNode":1,"vector_nodes::generator_nodes::RectangleNode":3,"vector_nodes::vector_modification_nodes::PathModifyNode":3},"output_type":{"Item":{"Concrete":"graph_craft::document::value::RenderOutput"}},"proto_nodes":608,"unique_stable_ids":366},"isometric-fountain":{"distinct_identifiers":47,"identifier_counts":{"blending_nodes::BlendModeNode":3,"blending_nodes::OpacityNode":4,"core_types::value::ClonedNode":1075,"graphene_core::context_modification::ContextModificationNode":7,"graphene_core::memo::MemoizeNode":172,"graphene_core::memo::MonitorNode":164,"graphene_core::vector::FillNode":63,"graphene_core::vector::StrokeNode":1,"graphene_std::platform_application_io::ApplicationIoNode":1,"graphene_std::platform_application_io::EditorApiNode":1,"graphene_std::platform_application_io::WgpuExecutorNode":1,"graphene_std::render_background::CompositeBackgroundPipelineNode":1,"graphene_std::render_background::RenderBackgroundNode":1,"graphene_std::render_cache::RenderOutputCacheNode":1,"graphene_std::render_node::CreateContextNode":1,"graphene_std::render_node::RenderIntermediateNode":1,"graphene_std::render_node::RenderNode":1,"graphene_std::render_pixel_preview::PixelPreviewPipelineNode":1,"graphene_std::render_pixel_preview::RenderPixelPreviewNode":1,"graphic_nodes::artboard::CreateArtboardNode":1,"graphic_nodes::graphic::AsGraphicNode":87,"graphic_nodes::graphic::ExtendNode":88,"graphic_nodes::graphic::IntoGroupNode":87,"graphic_nodes::graphic::PathOfSubgraphNode":88,"graphic_nodes::graphic::WriteAttributeNode":88,"input_adapter<AttributeValueDyn>":88,"input_adapter<BlendMode>":3,"input_adapter<BooleanOperation>":1,"input_adapter<Box<VectorModification>>":76,"input_adapter<Color>":64,"input_adapter<DAffine2>":63,"input_adapter<DVec2>":182,"input_adapter<DashPattern>":1,"input_adapter<Gradient>":63,"input_adapter<GradientForm>":63,"input_adapter<Graphic>":152,"input_adapter<NodeIdPath>":164,"input_adapter<String>":88,"input_adapter<StrokeAlign>":1,"input_adapter<StrokeCap>":1,"input_adapter<StrokeJoin>":1,"input_adapter<Vector>":76,"input_adapter<bool>":72,"input_adapter<f64>":71,"path_bool_nodes::BooleanOperationNode":1,"transform_nodes::transform_nodes::TransformNode":60,"vector_nodes::vector_modification_nodes::PathModifyNode":76},"output_type":{"ItLine truncated
@@ -0,0 +1 @@
{"definitions":[[129468748241612805,{"definitions":[],"exports":[{"Node":{"node":5,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete":"alloc::string::String"}}}},{"Node":{"node":2,"output":0}}],"skip_deduplication":false,"visible":true}],[4,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Node":{"node":3,"output":0}}],"skip_deduplication":true,"visible":true}],[5,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::ExtendNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Node":{"node":4,"output":0}}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[217427177650093194,{"definitions":[],"exports":[{"Node":{"node":1,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":true,"visible":true}],[1,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"vector_nodes::vector_modification_nodes::PathModifyNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Import":{"index":1,"ty":{"Concrete":"vector_types::vector::vector_modification::VectorModification"}}},{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[266487329061412220,{"definitions":[],"exports":[{"Node":{"node":1,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":true,"visible":true}],[1,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"vector_nodes::vector_modification_nodes::PathModifyNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Import":{"index":1,"ty":{"Concrete":"vector_types::vector::vector_modification::VectorModification"}}},{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[351578486738532771,{"definitions":[],"exports":[{"Node":{"node":5,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete"Line truncated
@@ -0,0 +1 @@
{"definitions":[[186911567179288130,{"definitions":[],"exports":[{"Node":{"node":5,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete":"alloc::string::String"}}}},{"Node":{"node":2,"output":0}}],"skip_deduplication":false,"visible":true}],[4,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Node":{"node":3,"output":0}}],"skip_deduplication":true,"visible":true}],[5,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::ExtendNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Node":{"node":4,"output":0}}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[338046885365909145,{"definitions":[],"exports":[{"Node":{"node":1,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":true,"visible":true}],[1,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"vector_nodes::vector_modification_nodes::PathModifyNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Import":{"index":1,"ty":{"Concrete":"vector_types::vector::vector_modification::VectorModification"}}},{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[615223746930215117,{"definitions":[],"exports":[{"Node":{"node":5,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete":"alloc::string::String"}}}},{"Node":{"node":2,"output":0}}],"skip_deduplication":false,"visible":true}],[4,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Node":{"node":3,"output":0}}],"skip_deduplication":true,"visible":true}],[5,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::ExtendNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Node":{"node":4,"output":0}}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[904202400024055805,{"definitions":[],"exports":[{"Node":{"node":1,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"coreLine truncated
@@ -0,0 +1 @@
{"definitions":[[41622474613176235,{"definitions":[],"exports":[{"Node":{"node":2288754089236120499,"output":0}}],"generated":false,"nodes":[[640915213983348287,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"vector_nodes::generator_nodes::RectangleNode"},"inputs":[{"Value":{"exposed":false,"hash":13646096770106105413,"producer":null,"size":6,"ty":{"Concrete":"()"}}},{"Value":{"exposed":false,"hash":5892469572511108693,"producer":null,"size":17,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":8086743829696919657,"producer":null,"size":16,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":15866446205965306736,"producer":null,"size":20,"ty":{"Item":{"Concrete":"vector_types::vector::misc::BoxCorners"}}}},{"Value":{"exposed":false,"hash":833760312133278981,"producer":null,"size":13,"ty":{"Item":{"Concrete":"bool"}}}},{"Value":{"exposed":false,"hash":16673275165411230030,"producer":null,"size":14,"ty":{"Item":{"Concrete":"bool"}}}}],"skip_deduplication":false,"visible":true}],[757876048866560520,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"core_types::vector::SamplePolylineNode"},"inputs":[{"Node":{"node":1791308547102433540,"output":0}},{"Value":{"exposed":false,"hash":14474755563581931724,"producer":null,"size":33,"ty":{"Item":{"Concrete":"vector_types::vector::misc::PointSpacingType"}}}},{"Value":{"exposed":false,"hash":18231466058637960781,"producer":null,"size":16,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":6015567135588644561,"producer":null,"size":15,"ty":{"Item":{"Concrete":"i64"}}}},{"Value":{"exposed":false,"hash":4199625609901051029,"producer":null,"size":14,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":4199625609901051029,"producer":null,"size":14,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":16673275165411230030,"producer":null,"size":14,"ty":{"Item":{"Concrete":"bool"}}}}],"skip_deduplication":false,"visible":true}],[1357621220363171879,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"core_types::vector::SamplePolylineNode"},"inputs":[{"Node":{"node":11731553664207576737,"output":0}},{"Value":{"exposed":false,"hash":14474755563581931724,"producer":null,"size":33,"ty":{"Item":{"Concrete":"vector_types::vector::misc::PointSpacingType"}}}},{"Value":{"exposed":false,"hash":5771056047690537652,"producer":null,"size":16,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":6015567135588644561,"producer":null,"size":15,"ty":{"Item":{"Concrete":"i64"}}}},{"Value":{"exposed":false,"hash":4199625609901051029,"producer":null,"size":14,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":4199625609901051029,"producer":null,"size":14,"ty":{"Item":{"Concrete":"f64"}}}},{"Value":{"exposed":false,"hash":16673275165411230030,"producer":null,"size":14,"ty":{"Item":{"Concrete":"bool"}}}}],"skip_deduplication":false,"visible":true}],[1791308547102433540,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::vector::FillNode"},"inputs":[{"Node":{"node":640915213983348287,"output":0}},{"Import":{"index":1,"ty":{"Generic":"T"}}},{"Value":{"exposed":false,"hash":12525535966144496710,"producer":null,"size":89,"ty":{"Item":{"Concrete":"core_types::color::color_types::Color"}}}},{"Value":{"exposed":false,"hash":10647031114719576416,"producer":null,"size":230,"ty":{"Item":{"Concrete":"vector_types::gradient::Gradient"}}}},{"Value":{"exposed":false,"hash":16470438148677102229,"producer":null,"size":25,"ty":{"Item":{"Concrete":"vector_types::gradient::GradientForm"}}}},{"Value":{"exposed":false,"hash":16673275165411230030,"producer":null,"size":14,"ty":{"Item":{"Concrete":"bool"}}}},{"Value":{"exposed":false,"hash":16091040744797387128,"producer":null,"size":38,"ty":{"Item":{"Concrete":"glam::f64::daffine2::DAffine2"}}}}],"skip_deduplication":false,"visible":true}],[2288754089236120499,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"core_types::vector::SplineNode"},"inputs":[{"Node":{"node":14158287945315818946,"output":0}}],"skip_deduplication":false,"visible":true}],[7828034197076821310,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"math_nodes::AsIntegerNode"},"inputs":[{"Import":{"index":3,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[11731553664207576737,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"core_types::vector::JitterPointsLine truncated
@@ -0,0 +1 @@
{"compile_metadata":[{"identifier":"blending_nodes::BlendModeNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"blending_nodes::ClippingMaskNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"blending_nodes::OpacityNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"brush_nodes::BrushStrokesNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"brush_nodes::basic_brush::BasicBrushNode","metadata":{"constant_inputs":0,"extract":1,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"brush_nodes::basic_brush::BasicBrushPipelineNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::AreaNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::AsVectorNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::BevelNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::BoundingBoxNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::BoxWarpNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::CentroidNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::ClosePathsNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::ConvexHullNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::DecimateNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::DimensionsNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::ExtractTransformNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::ExtrudeNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::JitterPointsNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::MorphNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::OffsetPathNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::OffsetPointsNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::PathIsClosedNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::PathLengthNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::PointInsideNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::PointsToPolylineNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::PointsToVectorNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::ReadIndexNode","metadata":{"constant_inputs":0,"extract":32,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::ReadPositionNode","metadata":{"constant_inputs":0,"extract":16,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::RelaxPointsNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::ReversePathsNode","metadata":{"constant_inputs":0,"extract":0,"footprint_invariant":false,"forwards_input":false,"inject":0}},{"identifier":"core_types::vector::RoundCornerLine truncated
@@ -0,0 +1 @@
{"definitions":[[3072219632412308961,{"definitions":[],"exports":[{"Node":{"node":1,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":true,"visible":true}],[1,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"vector_nodes::vector_modification_nodes::PathModifyNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Import":{"index":1,"ty":{"Concrete":"vector_types::vector::vector_modification::VectorModification"}}},{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[3795720623001749183,{"definitions":[],"exports":[{"Node":{"node":1,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":true,"visible":true}],[1,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"vector_nodes::vector_modification_nodes::PathModifyNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Import":{"index":1,"ty":{"Concrete":"vector_types::vector::vector_modification::VectorModification"}}},{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[6070787654632259716,{"definitions":[],"exports":[{"Node":{"node":5,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"Concrete":"alloc::string::String"}}}},{"Node":{"node":2,"output":0}}],"skip_deduplication":false,"visible":true}],[4,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphene_core::memo::MonitorNode"},"inputs":[{"Node":{"node":3,"output":0}}],"skip_deduplication":true,"visible":true}],[5,{"call_argument":{"Generic":"T"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::ExtendNode"},"inputs":[{"Node":{"node":0,"output":0}},{"Node":{"node":4,"output":0}}],"skip_deduplication":false,"visible":true}]],"scope_injections":[]}],[8690720052317786587,{"definitions":[],"exports":[{"Node":{"node":5,"output":0}}],"generated":false,"nodes":[[0,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::AsGraphicNode"},"inputs":[{"Import":{"index":0,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[1,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::IntoGroupNode"},"inputs":[{"Import":{"index":1,"ty":{"Generic":"T"}}}],"skip_deduplication":false,"visible":true}],[2,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::PathOfSubgraphNode"},"inputs":[{"Reflection":"DocumentNodePath"}],"skip_deduplication":false,"visible":true}],[3,{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"compile_metadata":null,"implementation":{"Proto":"graphic_nodes::graphic::WriteAttributeNode"},"inputs":[{"Node":{"node":1,"output":0}},{"Value":{"exposed":false,"hash":538378114103286041,"producer":null,"size":30,"ty":{"Item":{"ConcrLine truncated
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more