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
109 changed files with 11119 additions and 762 deletions

No files matched your search

Generated
+2
View File
@@ -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",
+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]);
}
// =============
@@ -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.
@@ -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();
}
}
}
@@ -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(),
@@ -1672,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);
}
@@ -1692,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 {
@@ -1701,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);
}
@@ -1719,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);
@@ -2467,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() {
@@ -2476,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);
}
}
@@ -2534,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 });
}
}
@@ -2601,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 => {
@@ -2644,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() {
@@ -2660,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);
@@ -2672,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
@@ -2979,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);
@@ -3041,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()
}
@@ -4323,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);
}
@@ -4331,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
}
@@ -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;
@@ -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) => {
@@ -1344,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();
-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;
+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 },
+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");
+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
@@ -0,0 +1 @@
{"definitions":[[1046848046610815255,{"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":[]}],[2679765217266705463,{"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":[]}],[7417426838449345270,{"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":[{"ReflectLine truncated
@@ -0,0 +1 @@
{"definitions":[[61667981330104086,{"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":[]}],[108681930996513462,{"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":[]}],[204450373054997983,{"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":[]}],[321339454244260504,{"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":[]}],[324216590873272998,{"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":[{"NodLine truncated
@@ -0,0 +1 @@
[{"identifier":"blending_nodes::BlendModeNode","implementations":[{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"alloc::string::String"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"Item":{"Concrete":"alloc::string::String"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::color::color_types::Color"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"Item":{"Concrete":"core_types::color::color_types::Color"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"graphic_types::graphic::Graphic"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"Item":{"Concrete":"graphic_types::graphic::Graphic"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"Item":{"Concrete":"raster_types::raster_types::Raster<raster_types::raster_types::cpu::CPU>"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"raster_types::raster_types::Raster<raster_types::raster_types::gpu::GPU>"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"Item":{"Concrete":"raster_types::raster_types::Raster<raster_types::raster_types::gpu::GPU>"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"vector_types::gradient::Gradient"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"Item":{"Concrete":"vector_types::gradient::Gradient"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"vector_types::vector::vector_types::Vector"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"Item":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"Item":{"Concrete":"vector_types::vector::vector_types::Vector"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"List":{"Concrete":"alloc::string::String"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"List":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"List":{"Concrete":"alloc::string::String"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"List":{"Concrete":"core_types::color::color_types::Color"}}]},{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"List":{"Concrete":"core_types::blending::BlendMode"}}]}],"output":{"List":{"Concrete":"core_types::color::color_types::Color"}}},{"call_argument":{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},"inputs":[{"Fn":[{"Concrete":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"},{"List":{"ConcLine truncated
@@ -0,0 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":17738733215159701439,"output_index":0}}],"nodes":[[280753769593512207,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":10.0},"exposed":false}},{"Value":{"tagged_value":{"Number":10.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false}],[443602663222444460,{"inputs":[{"Node":{"node_id":1917884629397383709,"output_index":0}},{"Node":{"node_id":2963509085978140338,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[449265030557790020,{"inputs":[{"Node":{"node_id":280753769593512207,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[25.0,25.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[1917884629397383709,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":14839750353685974326,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inpLine truncated
@@ -0,0 +1 @@
{"definitions":[[76756043877552268,{"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":[]}],[489369270929916135,{"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":[]}],[491682712509119664,{"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":[]}],[701608061008519615,{"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
+2 -2
View File
@@ -629,8 +629,8 @@ impl TaggedValue {
pub fn from_primitive_string(string: &str, ty: &Type) -> Option<Self> {
fn to_number<T: FromStr>(input: &str) -> Option<T> {
// Stringified tokens separate a negative number's minus sign from its digits (e.g. "- 180.")
input.split_whitespace().collect::<String>().parse().ok()
// Ignores stringified tokens' spacing (e.g. "- 180.") and digit separators (e.g. "1_000_000")
input.chars().filter(|character| !character.is_whitespace() && *character != '_').collect::<String>().parse().ok()
}
fn to_dvec2(input: &str) -> Option<DVec2> {
@@ -0,0 +1,56 @@
//! Exports the compiler spike's workloads from documents opened the way the editor opens them.
//!
//! Usage: `cargo run -p graphene-cli --example spike_export -- <output directory> <documents or directories>...`
use graph_craft::application_io::resource::ResourceId;
use graphene_cli::open_document;
use preprocessor::spike_export::{WorkloadDocument, export_compiler_spike_workloads};
use std::path::PathBuf;
fn documents_in(paths: &[PathBuf]) -> Vec<PathBuf> {
let mut documents = Vec::new();
for path in paths {
if !path.is_dir() {
documents.push(path.clone());
continue;
}
let mut found: Vec<PathBuf> = std::fs::read_dir(path)
.into_iter()
.flatten()
.filter_map(Result::ok)
.map(|entry| entry.path())
.filter(|path| path.extension().is_some_and(|extension| extension == "gdd" || extension == "graphite"))
.collect();
found.sort();
documents.extend(found);
}
documents
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut arguments = std::env::args_os().skip(1).map(PathBuf::from);
let output_directory = arguments.next().ok_or("expected an output directory")?;
let inputs: Vec<PathBuf> = arguments.collect();
let mut opened = Vec::new();
for path in documents_in(&inputs) {
let name = path.file_stem().and_then(|stem| stem.to_str()).ok_or("document names must be UTF-8")?.to_string();
let mut document = open_document(&path, false).await.map_err(|error| format!("{}: {error}", path.display()))?;
// The editor lifts nested networks into the definitions table on load, which a legacy document still nests inline
document.network.lift_nested_networks();
opened.push((name, document));
}
let documents = opened.iter().map(|(name, document)| WorkloadDocument {
name: name.clone(),
network: document.network.clone(),
resolve_resource: Box::new(move |resource_id: ResourceId| document.gdd.as_ref()?.registry().resources.get(&resource_id).and_then(|resource| resource.hash)),
});
export_compiler_spike_workloads(&output_directory, documents)?;
println!("Exported {} documents to {}", opened.len(), output_directory.display());
Ok(())
}
+8 -6
View File
@@ -5,6 +5,7 @@ pub mod dump;
pub mod export;
use document_container::AnyContainer;
use document_container::archive::ArchiveFormat;
use document_container::backends::memory::MemoryBackend;
use document_format::{GddV1, GddV1Layout};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
@@ -45,12 +46,14 @@ pub async fn open_gdd(archive: &[u8]) -> Result<GddV1, Box<dyn Error>> {
Ok(gdd)
}
/// Open `path` by extension: `.gdd` as an archive, anything else as a legacy `.graphite` document. `with_names` also collects its display names.
/// Open `path` as a `.gdd` if it is named `.gdd` or starts with archive magic bytes, otherwise as a legacy JSON document. `with_names` also collects its display names.
pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocument, Box<dyn Error>> {
let is_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
let bytes = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
if !is_gdd {
let document_string = std::fs::read_to_string(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
// A file named `.gdd` stays on the archive path, so a damaged one reports the archive error
let named_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
if !named_gdd && ArchiveFormat::detect(&bytes).is_none() {
let document_string = String::from_utf8(bytes).map_err(|error| format!("Document {} is neither a .gdd archive nor text: {error}", path.display()))?;
return Ok(OpenedDocument {
gdd: None,
network: load_network(&document_string),
@@ -58,8 +61,7 @@ pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocume
});
}
let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
let gdd = open_gdd(&archive).await?;
let gdd = open_gdd(&bytes).await?;
let declarations = gdd.declarations(&gdd).await;
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations, gdd.blobs())?;
let names = with_names.then(|| {
+7 -3
View File
@@ -3,6 +3,7 @@ mod repl;
mod watch;
use clap::{Args, Parser, Subcommand};
use document_container::archive::ArchiveFormat;
use document_live::{DEFAULT_SIGNALING_SERVER, SessionToken};
use fern::colors::{Color, ColoredLevelConfig};
use graphene_cli::{compile_document, dump, export, open_document, open_gdd};
@@ -135,15 +136,18 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Before the document converts to a network, so a registry that can't convert doesn't block recovering the legacy file
if let Command::ExtractLegacyDoc { document: path } = &app.command {
if !path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd")) {
let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
if ArchiveFormat::detect(&archive).is_none() {
return Err("ExtractLegacyDoc requires a .gdd document".into());
}
let archive = std::fs::read(path).map_err(|error| format!("Failed to read document {}: {error}", path.display()))?;
let gdd = open_gdd(&archive).await?;
let Some(legacy_doc) = gdd.read_legacy_document().await else {
return Err("gdd file did not contain a legacy .graphite document".into());
};
let new_path = path.with_extension("graphite");
// Saved documents carry the `.graphite` extension too, so the extracted file is named apart from its source
let new_path = path.with_extension("legacy.graphite");
std::fs::write(&new_path, legacy_doc).map_err(|error| format!("Failed to write .graphite file: {error}"))?;
eprintln!("Saved file to {}", new_path.to_string_lossy());
return Ok(());
@@ -43,6 +43,10 @@ gungraun = { workspace = true }
preprocessor = { workspace = true }
# Benchmarks
[[bench]]
name = "compile_pipeline"
harness = false
[[bench]]
name = "update_executor"
harness = false
@@ -1,5 +1,6 @@
use criterion::BenchmarkGroup;
use criterion::measurement::Measurement;
use graph_craft::document::NodeNetwork;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi;
@@ -7,10 +8,16 @@ use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
/// The demo's document network, wrapped in the editor's scope like the editor runtime does before preprocessing.
pub fn scoped_network(name: &str) -> NodeNetwork {
let network = load_from_name(name);
let editor_api = std::sync::Arc::new(EditorApi::default());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle())
}
#[allow(dead_code, reason = "shared by the bench targets, only some of which call it, and each compiles this module separately")]
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let mut network = scoped_network(name);
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
@@ -0,0 +1,61 @@
mod benchmark_util;
use benchmark_util::scoped_network;
use criterion::{BatchSize, Criterion, criterion_group, criterion_main};
use graph_craft::util::{DEMO_ART, compile};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use preprocessor::Preprocessor;
use std::hint::black_box;
fn compile_pipeline(c: &mut Criterion) {
let preprocessor = Preprocessor::new();
let preprocess = |mut network| {
preprocessor.preprocess(&mut network, &|_| None).unwrap();
network
};
let demos: Vec<_> = DEMO_ART
.iter()
.map(|name| {
let scoped = scoped_network(name);
let preprocessed = preprocess(scoped.clone());
let proto_network = compile(preprocessed.clone());
(name, scoped, preprocessed, proto_network)
})
.collect();
let mut group = c.benchmark_group("Preprocess");
for (name, scoped, _, _) in &demos {
group.bench_function(**name, |b| b.iter_batched(|| scoped.clone(), |network| preprocess(black_box(network)), BatchSize::SmallInput));
}
group.finish();
let mut group = c.benchmark_group("Compile");
for (name, _, preprocessed, _) in &demos {
group.bench_function(**name, |b| b.iter_batched(|| preprocessed.clone(), |network| compile(black_box(network)), BatchSize::SmallInput));
}
group.finish();
let mut group = c.benchmark_group("Executor construction");
for (name, _, _, proto_network) in &demos {
group.bench_function(**name, |b| {
b.iter_batched(|| proto_network.clone(), |network| DynamicExecutor::new(black_box(network)).unwrap(), BatchSize::SmallInput)
});
}
group.finish();
let mut group = c.benchmark_group("Full pipeline");
for (name, scoped, _, _) in &demos {
group.bench_function(**name, |b| {
b.iter_batched(
|| scoped.clone(),
|network| DynamicExecutor::new(compile(preprocess(black_box(network)))).unwrap(),
BatchSize::SmallInput,
)
});
}
group.finish();
}
criterion_group!(benches, compile_pipeline);
criterion_main!(benches);
@@ -0,0 +1,77 @@
//! Temporary, uncommitted: prints the compiled proto paths from the output down to nodes matching a name.
//!
//! Usage: `cargo run --release -p interpreted-executor --example memo_census -- <document name> <identifier substring>`
use core_types::uuid::NodeId;
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::NodeNetwork;
use graph_craft::proto::{ConstructionArgs, ProtoNetwork};
use graph_craft::util::load_network;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::util::wrap_network_in_scope;
use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
struct DummySpawner;
impl Spawn for DummySpawner {
fn spawn(&self, _task: Task) {}
}
fn compile(network: NodeNetwork, editor_api: &Arc<PlatformEditorApi>) -> ProtoNetwork {
let mut network = wrap_network_in_scope(network, editor_api.clone(), AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
preprocessor::Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
graph_craft::util::compile(network)
}
fn short_identifier(identifier: &str) -> &str {
identifier.rsplit("::").next().unwrap_or(identifier)
}
fn main() {
let mut arguments = std::env::args().skip(1);
let name = arguments.next().unwrap_or("changing-seasons".into());
let target = arguments.next().unwrap_or("ScatterPoints".into());
let editor_api = Arc::new(PlatformEditorApi::default());
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../demo-artwork").join(format!("{name}.graphite"));
let network = load_network(&std::fs::read_to_string(&path).expect("Failed to read the document"));
let proto = compile(network, &editor_api);
let nodes: HashMap<NodeId, _> = proto.nodes.iter().map(|(id, node)| (*id, node)).collect();
let mut counts: HashMap<&str, usize> = HashMap::new();
for (_, node) in &proto.nodes {
*counts.entry(short_identifier(node.identifier.as_str())).or_default() += 1;
}
println!("{} proto nodes, {} memoize", proto.nodes.len(), counts.get("MemoizeNode").copied().unwrap_or_default());
// Depth-first search for every path from the output to a matching node, printing the first few
let mut printed = 0;
let mut stack = vec![(proto.output, vec![proto.output])];
while let Some((id, path)) = stack.pop() {
let node = nodes[&id];
if short_identifier(node.identifier.as_str()).contains(&target) {
printed += 1;
println!("--- path {printed}");
for step in &path {
let node = nodes[step];
let arguments = match &node.construction_args {
ConstructionArgs::Nodes(inputs) => format!("{} inputs", inputs.len()),
ConstructionArgs::Value(value) => format!("value {:?}", value.ty()),
};
println!("{:40} ({arguments})", short_identifier(node.identifier.as_str()));
}
if printed >= 3 {
break;
}
continue;
}
if let ConstructionArgs::Nodes(inputs) = &node.construction_args {
for input in inputs {
let mut path = path.clone();
path.push(*input);
stack.push((*input, path));
}
}
}
}
@@ -0,0 +1,440 @@
//! Temporary, uncommitted: times edit loops (nudge a Transform node, recompile, update the executor, evaluate) on demo artwork.
//!
//! Usage: `[VELLO=1] cargo run --release -p interpreted-executor --example profile_edits -- <iterations> [document names...]`
//! With `VELLO=1` it renders through Vello on a GPU context instead of to SVG.
use core_types::uuid::NodeId;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::load_network;
use graphene_std::application_io::{ExportFormat, RenderConfig};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use graphene_std::transform::Footprint;
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
struct DummySpawner;
impl Spawn for DummySpawner {
fn spawn(&self, _task: Task) {}
}
fn compile(network: NodeNetwork, editor_api: &Arc<PlatformEditorApi>) -> ProtoNetwork {
let mut network = wrap_network_in_scope(network, editor_api.clone(), AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
preprocessor::Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
let mut proto = graph_craft::util::compile(network);
match std::env::var("MEMO_EXTEND").as_deref() {
Ok("1") => memoize_extend_outputs(&mut proto),
Ok("base") => memoize_extend_bases(&mut proto),
_ => {}
}
proto
}
/// Puts a Memoize node on the base (lower stack) input of every Extend node, leaving the Extend's other consumers of that input alone.
fn memoize_extend_bases(proto: &mut ProtoNetwork) {
let Some(template) = proto.nodes.iter().find(|(_, node)| node.identifier.as_str().ends_with("MemoizeNode")).map(|(_, node)| node.clone()) else {
return;
};
let memo_of = |id: NodeId| NodeId(id.0.rotate_left(23) ^ 0x6a09_e667_f3bc_c908);
// Rewire each Extend's base to the memo of that base
let mut bases = std::collections::HashSet::new();
for (_, node) in &mut proto.nodes {
if node.identifier.as_str().ends_with("ExtendNode")
&& let graph_craft::proto::ConstructionArgs::Nodes(inputs) = &mut node.construction_args
&& let Some(base) = inputs.first_mut()
{
bases.insert(*base);
*base = memo_of(*base);
}
}
// Insert each memo right after its base to keep the list topologically sorted
let mut nodes = Vec::with_capacity(proto.nodes.len() + bases.len());
for (id, node) in std::mem::take(&mut proto.nodes) {
let original_location = node.original_location.clone();
nodes.push((id, node));
if bases.contains(&id) {
let mut memo = template.clone();
memo.construction_args = graph_craft::proto::ConstructionArgs::Nodes(vec![id]);
memo.original_location = original_location;
nodes.push((memo_of(id), memo));
}
}
proto.nodes = nodes;
eprintln!("memoized {} extend bases", bases.len());
}
/// Puts a Memoize node after every Extend node, with an ID derived from the Extend's so it stays stable across recompiles.
fn memoize_extend_outputs(proto: &mut ProtoNetwork) {
let Some(template) = proto.nodes.iter().find(|(_, node)| node.identifier.as_str().ends_with("MemoizeNode")).map(|(_, node)| node.clone()) else {
return;
};
let extends: Vec<NodeId> = proto.nodes.iter().filter(|(_, node)| node.identifier.as_str().ends_with("ExtendNode")).map(|(id, _)| *id).collect();
let memo_of = |id: NodeId| NodeId(id.0.rotate_left(17) ^ 0x9e37_79b9_7f4a_7c15);
// Point every consumer of an Extend at its memo
let extend_set: std::collections::HashSet<NodeId> = extends.iter().copied().collect();
for (_, node) in &mut proto.nodes {
node.map_ids(|id| if extend_set.contains(&id) { memo_of(id) } else { id });
}
if extend_set.contains(&proto.output) {
proto.output = memo_of(proto.output);
}
// Insert each memo right after its Extend to keep the list topologically sorted
let mut nodes = Vec::with_capacity(proto.nodes.len() + extends.len());
for (id, node) in std::mem::take(&mut proto.nodes) {
let is_extend = extend_set.contains(&id);
let original_location = node.original_location.clone();
nodes.push((id, node));
if is_extend {
let mut memo = template.clone();
memo.construction_args = graph_craft::proto::ConstructionArgs::Nodes(vec![id]);
memo.original_location = original_location;
nodes.push((memo_of(id), memo));
}
}
proto.nodes = nodes;
eprintln!("memoized {} extend outputs", extends.len());
}
fn for_each_translation(network: &mut NodeNetwork, visit: &mut impl FnMut(&mut DVec2)) {
let mut node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
node_ids.sort();
for node_id in node_ids {
let Some(node) = network.nodes.get_mut(&node_id) else { continue };
match &mut node.implementation {
DocumentNodeImplementation::Network(nested) => for_each_translation(nested, visit),
DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("TransformNode") => {
if let Some(NodeInput::Value { tagged_value, .. }) = node.inputs.get_mut(1)
&& let TaggedValue::DVec2(translation) = &mut *tagged_value.inner_mut()
{
visit(translation);
}
}
_ => {}
}
}
}
fn node_input_id(input: Option<&NodeInput>) -> Option<NodeId> {
match input {
Some(NodeInput::Node { node_id, .. }) => Some(*node_id),
_ => None,
}
}
fn is_fill(node: &graph_craft::document::DocumentNode) -> bool {
matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("FillNode"))
}
/// Copies the node and everything it reads from in the same network under fresh IDs, returning the copy's ID.
fn copy_subtree(network: &mut NodeNetwork, root: NodeId, next_id: &mut u64) -> NodeId {
let mut copied = std::collections::HashMap::new();
let mut pending = vec![root];
while let Some(node_id) = pending.pop() {
if copied.contains_key(&node_id) {
continue;
}
*next_id += 1;
copied.insert(node_id, NodeId(*next_id));
pending.extend(network.nodes[&node_id].inputs.iter().filter_map(|input| node_input_id(Some(input))));
}
for (original, copy) in &copied {
let mut node = network.nodes[original].clone();
for input in &mut node.inputs {
if let NodeInput::Node { node_id, .. } = input {
*node_id = copied[node_id];
}
}
network.nodes.insert(*copy, node);
}
copied[&root]
}
/// Draws a shape layer on top of (or with `at_bottom`, beneath) the first artboard's content, as dragging a newly drawn shape needs, and returns its Transform node's ID.
/// The layer is a copy of the artboard's top layer, its shape a copy of the bottom-most layer's Fill chain, placed by a copy of `transform_template`.
fn insert_shape(network: &mut NodeNetwork, transform_template: &graph_craft::document::DocumentNode, at_bottom: bool) -> Option<NodeId> {
let artboard = node_input_id(network.exports.first())?;
let old_top = node_input_id(network.nodes[&artboard].inputs.get(1))?;
// The first layer down the stack is the template for the new one, and the last one with a Fill content gives its shape
let mut layer_template = None;
let mut bottom_layer = None;
let mut shape = None;
let mut current = Some(old_top);
while let Some(node_id) = current {
let node = &network.nodes[&node_id];
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) && node.inputs.len() == 2 {
layer_template.get_or_insert(node_id);
bottom_layer = Some(node_id);
if let Some(content) = node_input_id(node.inputs.get(1))
&& is_fill(&network.nodes[&content])
{
shape = Some(content);
}
}
current = node_input_id(node.inputs.first());
}
let (layer_template, shape) = (layer_template?, shape?);
let mut next_id = 0x5ade_0000_0000;
let shape_copy = copy_subtree(network, shape, &mut next_id);
let transform_id = NodeId(next_id + 1);
let mut transform = transform_template.clone();
transform.inputs[0] = NodeInput::node(shape_copy, 0);
network.nodes.insert(transform_id, transform);
let layer_id = NodeId(next_id + 2);
let mut layer = network.nodes[&layer_template].clone();
layer.inputs[1] = NodeInput::node(transform_id, 0);
// Beneath the stack, the new layer takes over the bottom layer's stack input, so every layer above it is downstream of the drag
if at_bottom {
let bottom_layer = bottom_layer?;
layer.inputs[0] = network.nodes[&bottom_layer].inputs[0].clone();
network.nodes.insert(layer_id, layer);
network.nodes.get_mut(&bottom_layer)?.inputs[0] = NodeInput::node(layer_id, 0);
} else {
layer.inputs[0] = NodeInput::node(old_top, 0);
network.nodes.insert(layer_id, layer);
network.nodes.get_mut(&artboard)?.inputs[1] = NodeInput::node(layer_id, 0);
}
Some(transform_id)
}
/// Moves the Transform node with the given ID in the root network by 10 units.
fn nudge_transform(network: &mut NodeNetwork, transform_id: NodeId) {
if let Some(NodeInput::Value { tagged_value, .. }) = network.nodes.get_mut(&transform_id).and_then(|node| node.inputs.get_mut(1))
&& let TaggedValue::DVec2(translation) = &mut *tagged_value.inner_mut()
{
*translation += DVec2::new(10., 0.);
}
}
/// The only Transform node with a translation value among the demo artwork, used as the template for inserted shapes.
fn transform_template() -> graph_craft::document::DocumentNode {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../demo-artwork/changing-seasons.graphite");
let network = load_network(&std::fs::read_to_string(&path).expect("Failed to read the document"));
let artboard = node_input_id(network.exports.first()).expect("The document has an artboard");
let transform = node_input_id(network.nodes[&artboard].inputs.get(1)).expect("The artboard has content");
network.nodes[&transform].clone()
}
/// Prints the chain of nodes from the network's export down its primary inputs, with each node's inputs.
fn dump_stack(network: &NodeNetwork, depth: usize) {
let describe = |node: &graph_craft::document::DocumentNode| match &node.implementation {
DocumentNodeImplementation::ProtoNode(identifier) => identifier.as_str().rsplit("::").next().unwrap_or_default().to_string(),
DocumentNodeImplementation::Network(nested) => format!("Network({} nodes)", nested.nodes.len()),
_ => "other".into(),
};
let indent = " ".repeat(depth);
let mut current = network
.exports
.first()
.and_then(|export| if let NodeInput::Node { node_id, .. } = export { Some(*node_id) } else { None });
let mut steps = 0;
while let Some(node_id) = current
&& steps < 40
{
let Some(node) = network.nodes.get(&node_id) else { break };
let inputs: Vec<String> = node
.inputs
.iter()
.map(|input| match input {
NodeInput::Node { node_id, .. } => network.nodes.get(node_id).map(describe).unwrap_or_default(),
NodeInput::Value { tagged_value, .. } => format!("value {}", tagged_value.ty()),
NodeInput::Import { import_index, .. } => format!("import {import_index}"),
_ => "other".into(),
})
.collect();
println!("{indent}{node_id} {} [{}]", describe(node), inputs.join(", "));
// The artboard's content is its second input, so descend into it rather than to the artboards below
let next_index = if steps == 0 { 1 } else { 0 };
current = node
.inputs
.get(next_index)
.and_then(|input| if let NodeInput::Node { node_id, .. } = input { Some(*node_id) } else { None });
steps += 1;
}
}
/// Places `factor` times as many points along every Sample Polyline node's path, by dividing its separation and multiplying its quantity.
fn densify_sampling(network: &mut NodeNetwork, factor: f64) {
for node in network.nodes.values_mut() {
match &mut node.implementation {
DocumentNodeImplementation::Network(nested) => densify_sampling(nested, factor),
DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("SamplePolylineNode") => {
if let Some(NodeInput::Value { tagged_value, .. }) = node.inputs.get_mut(2)
&& let TaggedValue::Number(separation) = &mut *tagged_value.inner_mut()
{
*separation /= factor;
}
if let Some(NodeInput::Value { tagged_value, .. }) = node.inputs.get_mut(3)
&& let TaggedValue::Integer(quantity) = &mut *tagged_value.inner_mut()
{
*quantity = (*quantity as f64 * factor) as i64;
}
}
_ => {}
}
}
}
/// Nudges the middle Transform node by traversal order, as the trace driver's `edit_middle` frame does.
fn nudge_middle_transform(network: &mut NodeNetwork) -> bool {
let mut count = 0;
for_each_translation(network, &mut |_| count += 1);
if count == 0 {
return false;
}
let target = std::env::var("NUDGE_INDEX").ok().and_then(|value| value.parse().ok()).unwrap_or((count - 1) / 2);
let mut index = 0;
for_each_translation(network, &mut |translation| {
if index == target {
*translation += DVec2::new(10., 0.);
}
index += 1;
});
true
}
fn main() {
let mut arguments = std::env::args().skip(1);
let iterations: usize = arguments.next().and_then(|value| value.parse().ok()).unwrap_or(60);
let names: Vec<String> = arguments.collect();
let vello = std::env::var("VELLO").is_ok_and(|value| value == "1");
// Vello renders on a GPU context, which the render node takes from the editor API's application IO
let editor_api = Arc::new(match vello {
true => PlatformEditorApi {
application_io: Some(Arc::new(futures::executor::block_on(PlatformApplicationIo::new()))),
},
false => PlatformEditorApi::default(),
});
let context = RenderConfig {
viewport: Footprint {
transform: DAffine2::IDENTITY,
resolution: UVec2::new(1920, 1080),
..Default::default()
},
scale: 1.,
export_format: if vello { ExportFormat::Raster } else { ExportFormat::Svg },
..Default::default()
}
.into_context();
for name in names {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../demo-artwork").join(format!("{name}.graphite"));
let mut network = load_network(&std::fs::read_to_string(&path).expect("Failed to read the document"));
if std::env::var("DUMP").is_ok_and(|value| value == "1") {
dump_stack(&network, 0);
continue;
}
if let Ok(position) = std::env::var("NUDGE_CHECK")
&& (position == "top" || position == "bottom")
{
let render = |network: &NodeNetwork| {
let executor = DynamicExecutor::new(compile(network.clone(), &editor_api)).expect("The document compiles");
format!("{:?}", executor.tree().eval_tagged_value(executor.output(), &context)).len()
};
let without_shape = render(&network);
let transform_id = insert_shape(&mut network, &transform_template(), position == "bottom").expect("The document has a shape layer to copy");
let with_shape = render(&network);
let baseline: std::collections::HashSet<NodeId> = compile(network.clone(), &editor_api).nodes.iter().map(|(id, _)| *id).collect();
nudge_transform(&mut network, transform_id);
let changed = compile(network.clone(), &editor_api).nodes.iter().filter(|(id, _)| !baseline.contains(id)).count();
println!("{name}: output length {without_shape} without the shape, {with_shape} with it; a nudge makes {changed} new proto nodes");
continue;
}
if std::env::var("NUDGE_CHECK").is_ok_and(|value| value == "1") {
let baseline: std::collections::HashSet<NodeId> = compile(network.clone(), &editor_api).nodes.iter().map(|(id, _)| *id).collect();
let mut count = 0;
for_each_translation(&mut network, &mut |_| count += 1);
for target in 0..count {
let mut nudged = network.clone();
let mut index = 0;
for_each_translation(&mut nudged, &mut |translation| {
if index == target {
*translation += DVec2::new(10., 0.);
}
index += 1;
});
let changed = compile(nudged, &editor_api).nodes.iter().filter(|(id, _)| !baseline.contains(id)).count();
println!("{name} transform {target}: {changed} new proto nodes");
}
continue;
}
if let Some(factor) = std::env::var("DENSIFY").ok().and_then(|value| value.parse::<f64>().ok()) {
densify_sampling(&mut network, factor);
}
// With `NUDGE=top`, a shape drawn on top of the artwork is dragged, as when moving a new shape over it in the editor.
// With `NUDGE=bottom`, the shape is beneath every layer instead, so everything above it is recomputed each edit.
let top_shape_transform = match std::env::var("NUDGE").as_deref() {
Ok("top") => Some(insert_shape(&mut network, &transform_template(), false).expect("The document has a shape layer to copy")),
Ok("bottom") => Some(insert_shape(&mut network, &transform_template(), true).expect("The document has a shape layer to copy")),
_ => None,
};
let mut executor = DynamicExecutor::new(compile(network.clone(), &editor_api)).expect("The document compiles");
let _ = executor.tree().eval_tagged_value(executor.output(), &context);
let (mut update_time, mut eval_time) = (Duration::ZERO, Duration::ZERO);
for _ in 0..iterations {
match top_shape_transform {
Some(transform_id) => nudge_transform(&mut network, transform_id),
None if !nudge_middle_transform(&mut network) => break,
None => {}
}
let start = Instant::now();
if executor.update(compile(network.clone(), &editor_api)).is_err() {
break;
}
update_time += start.elapsed();
let start = Instant::now();
let _ = executor.tree().eval_tagged_value(executor.output(), &context);
eval_time += start.elapsed();
}
// The process's resident memory now and at its peak, which run one document per process to attribute
let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default();
let status_megabytes = |field: &str| {
let kilobytes: f64 = status
.lines()
.find(|line| line.starts_with(field))
.and_then(|line| line.split_whitespace().nth(1)?.parse().ok())
.unwrap_or_default();
kilobytes / 1024.
};
let per_edit = |duration: Duration| duration.as_secs_f64() * 1e3 / iterations as f64;
println!(
"{name:24} compile+update {:7.2} ms/edit evaluate {:7.2} ms/edit resident {:6.1} MB (peak {:6.1} MB)",
per_edit(update_time),
per_edit(eval_time),
status_megabytes("VmRSS:"),
status_megabytes("VmHWM:")
);
}
}
@@ -124,6 +124,21 @@ pub const ATTR_SMOOTH: &str = "smooth";
/// the internal addressing: a `PointId` on a `Vector`'s point pool, or a `SegmentId` on the `List<i64>`
/// inside a `Path` at the anchor reference the segment departs from.
pub const ATTR_ID: &str = "id";
/// Point's `i64` count of the `[` branches the turtle was nested in when drawing it, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_DEPTH: &str = "depth";
/// Point's `f64` distance the turtle traveled from its start to reach it, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_DISTANCE: &str = "distance";
/// Point's `f64` direction in degrees the turtle faced arriving at it (`0.` along +X, clockwise on screen), on a `Vector`'s
/// point pool from Turtle Path.
pub const ATTR_HEADING: &str = "heading";
/// Point's `f64` width the turtle drew with there, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_WIDTH: &str = "width";
/// Point's `DVec2` U and V numbers, counted up by `'` and `#`, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_UV: &str = "uv";
/// Point's `f64` turtle step length, scaled by `"` and `_`, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_STEP: &str = "step";
/// Point's `i64` kind set by a `.` outside a shape (default `1`), or `0` for a drawn point, on a `Vector`'s point pool from Turtle Path.
pub const ATTR_KIND: &str = "kind";
/// Text item's font size in document-space units (`f64`, implicit default `24.`).
pub const ATTR_FONT_SIZE: &str = "font_size";
/// Text item's font, as a `Resource` of the loaded font file.
+12 -5
View File
@@ -10,8 +10,6 @@ use raster_types::{CPU, Raster};
pub enum ReadContextError {
#[error("No {0} to read: this node only works inside a loop over {0} items, like in a Map node")]
NoLoopItem(&'static str),
#[error("No loop index to read: this node only works inside a loop, like in a Repeat or Map node")]
NoLoopIndex,
#[error("No position to read: this node only works inside a loop over points, like in a Repeat on Points node")]
NoLoopPosition,
#[error("Loop Level {level} is too high: the outermost loop around this node is level {outermost}")]
@@ -80,6 +78,8 @@ fn read_position(
/// Produces the index of the current iteration of a loop by reading from the evaluation context, which is supplied by downstream nodes such as *Repeat*.
///
/// Nested loops can enable 2D or higher-dimensional iteration by using the *Loop Level* parameter to read the index from outer levels of loops.
///
/// Outside of any loop, the index is 0.
#[node_macro::node(category("Data: Context"), icon("NodeReadIndex"), path(core_types::vector))]
fn read_index(
ctx: impl Ctx + ExtractIndex,
@@ -90,7 +90,9 @@ fn read_index(
#[hard(0..)]
loop_level: Item<i64>,
) -> Result<Item<f64>, ReadContextError> {
let indices = ctx.try_index().ok_or(ReadContextError::NoLoopIndex)?;
// The graph outside any loop runs once, as index 0
let Some(indices) = ctx.try_index() else { return Ok(Item::new_from_element(0.)) };
Ok(Item::new_from_element(at_loop_level(indices, *loop_level.element())? as f64))
}
@@ -119,9 +121,14 @@ mod tests {
assert_eq!(level(1).unwrap(), 4.);
assert_eq!(level(2).unwrap_err().to_string(), "Loop Level 2 is too high: the outermost loop around this node is level 1");
assert!(matches!(level(i64::MAX), Err(ReadContextError::LoopLevelTooHigh { .. })));
}
let outside = read_index(OwnedContextImpl::default().into_context(), (), Item::new_from_element(0));
assert!(matches!(outside, Err(ReadContextError::NoLoopIndex)));
#[test]
fn read_index_outside_a_loop_is_zero() {
let outside = |level: i64| read_index(OwnedContextImpl::default().into_context(), (), Item::new_from_element(level)).map(|index| *index.element());
assert_eq!(outside(0).unwrap(), 0.);
assert_eq!(outside(3).unwrap(), 0.);
}
#[test]
+1
View File
@@ -26,6 +26,7 @@ graphene-hash = { workspace = true }
graphene-resource = { workspace = true }
vector-types = { workspace = true }
node-macro = { workspace = true }
math-parser = { workspace = true }
# Workspace dependencies
dyn-any = { workspace = true }
+820
View File
@@ -0,0 +1,820 @@
use core_types::Ctx;
use core_types::list::Item;
use core_types::math::float_noise::round_away_float_noise;
use core_types::misc::{format_f64, parse_f64};
use math_parser::ast;
use math_parser::context::{EvalContext, NothingMap, ValueProvider};
use math_parser::value::Value;
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use std::collections::HashMap;
use std::ops::Range;
/// Why the "L-System" node's string stops short of what its inputs describe.
#[derive(Debug, thiserror::Error)]
pub enum LSystemError {
#[error("Line {line} of the rules isn't a valid rule: {reason}")]
InvalidRule { line: usize, reason: String },
#[error("The axiom isn't valid: {0}")]
InvalidAxiom(String),
#[error("A rule's math gives no number: {0}")]
Evaluation(String),
#[error("A rule's chance came out as {0}, which isn't from 0 to 1")]
InvalidChance(f64),
#[error("The chances of the rules for `{symbol}` add up to {total}, which is more than 1")]
ChancesOverOne { symbol: char, total: f64 },
#[error("Stopped after {completed} generations, since the next would grow past the Max Symbols limit of {limit}")]
TooLong { completed: i64, limit: usize },
#[error("Stopped after {limit} generations, since Max Symbols also limits how many generations run")]
TooManyGenerations { limit: usize },
}
/// Grows a string by rewriting all of its symbols at once with the rules, once per generation, for drawing with the **Turtle Path** node.
///
/// Since every symbol with a rule is replaced in each generation, patterns repeat inside themselves at ever finer scales, like the branching of plants or the folds of fractal curves.
#[node_macro::node(name("L-System"), category("String"), icon("NodeLSystem"))]
fn l_system(
_: impl Ctx,
/// The string to start growing from.
axiom: Item<String>,
/// One rule per line, like `F = F+F-F-F+F` (or `F -> F+F-F-F+F`), which replaces every `F` with `F+F-F-F+F` in each generation. Symbols without a rule stay as they are.
///
/// A rule can also check the symbols around one, as in `A < B > C = D`, which rewrites a `B` only between an `A` and a `C`. A rule ending with a chance from 0 to 1, like `F = F[+F]F : 0.6`, applies only that often and otherwise leaves the symbol as it is. The chances of a symbol's rules can add up to 1 at most.
///
/// Symbols can carry numbers, like `F(10)`. A rule names them to work out new numbers with math, and to apply only when the condition after `:` holds, as in `F(x) : x > 2 = F(x/2)[+F(x/2)]`. A chance can be worked out from them too.
///
/// A `%` cuts off the rest of its branch, up to the `]` that ends it.
///
/// Lines starting with `//` are skipped.
#[default("F = F+F-F-F+F")]
#[widget(ParsedWidgetOverride::Custom = "text_area")]
rules: Item<String>,
/// Symbols to look past when a rule checks the symbols around one, usually the turns between them.
///
/// Listing `[` and `]` reads the string straight through its branches, as if it had no brackets.
#[default("+-")]
ignored_symbols: Item<String>,
/// How many times the rules rewrite the whole string. Each generation can multiply its length.
#[default(3)]
#[hard(0..)]
generations: Item<i64>,
/// Seed to determine unique variations on where the rules with chances apply.
#[hard(0..)]
seed: Item<i64>,
/// The longest the string may grow, in symbols, and the most generations that run. A generation past either is left out, guarding against a number of generations that would freeze the editor.
#[default(1_000_000)]
#[hard(1..)]
max_symbols: Item<i64>,
) -> Result<Item<String>, (Item<String>, LSystemError)> {
// The grown string takes the axiom's place in its item, keeping the attributes it carries
let mut string = axiom;
let mut axiom = match parse_axiom(string.element()) {
Ok(axiom) => axiom,
Err(reason) => {
string.element_mut().clear();
return Err((string, LSystemError::InvalidAxiom(reason)));
}
};
cut_branches(&mut axiom);
let (rule_set, rule_error) = RuleSet::parse(rules.element());
let ignored_symbols: Vec<char> = ignored_symbols.element().chars().filter(|symbol| !symbol.is_whitespace()).collect();
let max_symbols = (*max_symbols.element()).max(1) as usize;
let (modules, rewrite_error) = rewrite(axiom, &rule_set, *generations.element(), max_symbols, &ignored_symbols, *seed.element() as u64);
*string.element_mut() = modules_to_string(&modules);
// An invalid rule is reported first, since it is usually being typed and explains any other surprise
match rule_error.or(rewrite_error) {
Some(error) => Err((string, error)),
None => Ok(string),
}
}
/// One symbol of an L-system string, with the numbers in parentheses after it, like `F(10, 2)`.
#[derive(Clone, Debug, PartialEq)]
struct Module {
symbol: char,
parameters: Vec<f64>,
}
/// A symbol a rule matches, with names for the numbers it carries, like `F(x, y)`.
struct Pattern {
symbol: char,
parameter_names: Vec<String>,
}
/// A symbol a rule writes, with the math that works out each of its numbers.
struct WrittenSymbol {
symbol: char,
parameters: Vec<ast::Node>,
}
/// One line of the rules: `left < symbol > right : condition = successor : chance`, where all but the symbol and successor are optional.
struct Rule {
/// The symbols that must come before the rewritten one, in reading order.
left_context: Vec<Pattern>,
predecessor: Pattern,
/// The symbols that must come after the rewritten one, in reading order.
right_context: Vec<Pattern>,
condition: Option<ast::Node>,
successor: Vec<WrittenSymbol>,
/// How often this rule applies, from 0 to 1, where it matches.
chance: Option<Chance>,
}
/// A rule's chance, as a written number or as math to work out from the numbers it names.
enum Chance {
Fixed(f64),
Computed(ast::Node),
}
/// The rules, looked up by the symbol each one rewrites.
struct RuleSet {
rules: Vec<Rule>,
by_symbol: HashMap<char, Vec<usize>>,
uses_context: bool,
}
impl RuleSet {
/// Parses one rule per line, keeping the valid rules and the error of the first invalid one.
fn parse(text: &str) -> (Self, Option<LSystemError>) {
let mut rules = Vec::new();
let mut first_error = None;
for (index, line) in text.lines().enumerate() {
let line = line.trim();
if line.is_empty() || line.starts_with("//") {
continue;
}
match parse_rule(line) {
Ok(rule) => rules.push(rule),
Err(reason) if first_error.is_none() => first_error = Some(LSystemError::InvalidRule { line: index + 1, reason }),
Err(_) => {}
}
}
let mut by_symbol: HashMap<char, Vec<usize>> = HashMap::new();
for (index, rule) in rules.iter().enumerate() {
by_symbol.entry(rule.predecessor.symbol).or_default().push(index);
}
let uses_context = rules.iter().any(|rule| !rule.left_context.is_empty() || !rule.right_context.is_empty());
(Self { rules, by_symbol, uses_context }, first_error)
}
}
/// The numbers a matched rule's names stand for.
#[derive(Default)]
struct Bindings<'a>(Vec<(&'a str, f64)>);
impl ValueProvider for Bindings<'_> {
fn get_value(&self, name: &str) -> Option<Value> {
self.0.iter().find(|(bound_name, _)| *bound_name == name).map(|&(_, value)| Value::from_f64(value))
}
}
impl<'a> Bindings<'a> {
/// Names the numbers of a module that matches the pattern, or gives `false` when the symbol or count of numbers differs.
fn bind(&mut self, pattern: &'a Pattern, module: &Module) -> bool {
if pattern.symbol != module.symbol || pattern.parameter_names.len() != module.parameters.len() {
return false;
}
self.0.extend(pattern.parameter_names.iter().map(String::as_str).zip(module.parameters.iter().copied()));
true
}
}
/// Rewrites every module once per generation, giving the last complete generation and why it stopped early, if it did.
fn rewrite(axiom: Vec<Module>, rule_set: &RuleSet, generations: i64, max_symbols: usize, ignored_symbols: &[char], seed: u64) -> (Vec<Module>, Option<LSystemError>) {
let mut rng = StdRng::seed_from_u64(seed);
let mut modules = axiom;
for generation in 0..generations {
// Running more generations than Max Symbols without passing it takes a string that stopped growing, which could otherwise run long enough to freeze the editor
if generation >= max_symbols as i64 {
return (modules, Some(LSystemError::TooManyGenerations { limit: max_symbols }));
}
let partners = if rule_set.uses_context { bracket_partners(&modules) } else { Vec::new() };
let neighbors = Neighbors {
modules: &modules,
partners: &partners,
ignored_symbols,
};
let mut next = Vec::with_capacity(modules.len());
let mut rolled = false;
for (index, module) in modules.iter().enumerate() {
let chosen = match choose_rule(rule_set, &neighbors, index, &mut rng, &mut rolled) {
Ok(chosen) => chosen,
Err(error) => return (modules, Some(error)),
};
let Some((rule, bindings)) = chosen else {
next.push(module.clone());
continue;
};
for written in &rule.successor {
let parameters = match written.parameters.iter().map(|expression| evaluate_number(expression, &bindings)).collect() {
Ok(parameters) => parameters,
Err(reason) => return (modules, Some(LSystemError::Evaluation(reason))),
};
next.push(Module { symbol: written.symbol, parameters });
}
if next.len() > max_symbols {
return (
modules,
Some(LSystemError::TooLong {
completed: generation,
limit: max_symbols,
}),
);
}
}
cut_branches(&mut next);
// A generation that changed nothing without rolling any chances would repeat forever, so growth has settled
let settled = !rolled && next == modules;
modules = next;
if settled {
break;
}
}
(modules, None)
}
/// Erases each `%` along with the rest of its branch, up to the `]` that ends it, or to the end of the string outside any branch. O(n).
fn cut_branches(modules: &mut Vec<Module>) {
if !modules.iter().any(|module| module.symbol == '%') {
return;
}
// While cutting, the count of branches opened since the `%`, so the `]` ending the cut branch is kept
let mut cut_depth: Option<usize> = None;
modules.retain(|module| match (cut_depth, module.symbol) {
(None, '%') => {
cut_depth = Some(0);
false
}
(None, _) => true,
(Some(0), ']') => {
cut_depth = None;
true
}
(Some(depth), '[') => {
cut_depth = Some(depth + 1);
false
}
(Some(depth), ']') => {
cut_depth = Some(depth - 1);
false
}
(Some(_), _) => false,
});
}
/// The rule that rewrites the module at `index` with its names bound. The first matching rule applies, unless it gives a chance, in which case one roll picks among the matching rules that give chances, or none with the chance left over.
/// Making that roll sets `rolled`.
fn choose_rule<'a>(rule_set: &'a RuleSet, neighbors: &Neighbors, index: usize, rng: &mut StdRng, rolled: &mut bool) -> Result<Option<(&'a Rule, Bindings<'a>)>, LSystemError> {
let module = &neighbors.modules[index];
let Some(candidates) = rule_set.by_symbol.get(&module.symbol) else { return Ok(None) };
let mut chance_matches = Vec::new();
for &rule_index in candidates {
let rule = &rule_set.rules[rule_index];
let Some(bindings) = matching_bindings(rule, neighbors, index).map_err(LSystemError::Evaluation)? else {
continue;
};
let chance = match &rule.chance {
Some(Chance::Fixed(chance)) => *chance,
Some(Chance::Computed(expression)) => evaluate_number(expression, &bindings).map_err(LSystemError::Evaluation)?,
None if chance_matches.is_empty() => return Ok(Some((rule, bindings))),
None => continue,
};
if !(0. ..=1.).contains(&chance) {
return Err(LSystemError::InvalidChance(chance));
}
chance_matches.push((rule, bindings, chance));
}
// Rounding lets chances like 0.7 and 0.2 and 0.1 add up to exactly 1
let total = round_away_float_noise(chance_matches.iter().map(|(_, _, chance)| chance).sum());
if total > 1. {
return Err(LSystemError::ChancesOverOne { symbol: module.symbol, total });
}
if total == 0. {
return Ok(None);
}
// When the chances add up to 1, the last rule also takes any sliver that float rounding leaves past it
*rolled = true;
let mut roll = rng.random::<f64>();
let last = chance_matches.len() - 1;
for (position, (rule, bindings, chance)) in chance_matches.into_iter().enumerate() {
if roll < chance || (position == last && total == 1.) {
return Ok(Some((rule, bindings)));
}
roll -= chance;
}
Ok(None)
}
/// The rule's names bound to the numbers of the module at `index` and its context, or `None` when the rule doesn't match there.
fn matching_bindings<'a>(rule: &'a Rule, neighbors: &Neighbors, index: usize) -> Result<Option<Bindings<'a>>, String> {
let mut bindings = Bindings::default();
if !bindings.bind(&rule.predecessor, &neighbors.modules[index]) {
return Ok(None);
}
// The left context is checked from the nearest symbol outward, so in reverse reading order
let mut position = index;
for pattern in rule.left_context.iter().rev() {
let Some(previous) = neighbors.previous(position) else { return Ok(None) };
if !bindings.bind(pattern, &neighbors.modules[previous]) {
return Ok(None);
}
position = previous;
}
let mut position = index;
for pattern in &rule.right_context {
let Some(next) = neighbors.next(position) else { return Ok(None) };
if !bindings.bind(pattern, &neighbors.modules[next]) {
return Ok(None);
}
position = next;
}
if let Some(condition) = &rule.condition
&& evaluate_number(condition, &bindings)? == 0.
{
return Ok(None);
}
Ok(Some(bindings))
}
/// A generation's modules, read the way context sees them: along the turtle's path, past side branches and ignored symbols.
struct Neighbors<'a> {
modules: &'a [Module],
/// The index of each bracket's partner, from [`bracket_partners`].
partners: &'a [Option<usize>],
ignored_symbols: &'a [char],
}
impl Neighbors<'_> {
/// The nearest module before `index` on the way back toward the start, stepping over whole branches and out of the one `index` sits in.
fn previous(&self, index: usize) -> Option<usize> {
let mut current = index;
while current > 0 {
current -= 1;
match self.modules[current].symbol {
symbol if self.ignored_symbols.contains(&symbol) => {}
']' => current = self.partners[current]?,
'[' => {}
_ => return Some(current),
}
}
None
}
/// The nearest module after `index` along the same branch, stepping over side branches, or `None` where the branch ends.
fn next(&self, index: usize) -> Option<usize> {
let mut current = index + 1;
while current < self.modules.len() {
match self.modules[current].symbol {
symbol if self.ignored_symbols.contains(&symbol) => current += 1,
'[' => current = self.partners[current]? + 1,
']' => return None,
_ => return Some(current),
}
}
None
}
}
/// The index of each `[` and `]` module's partner, so context matching can step over whole branches in O(1).
fn bracket_partners(modules: &[Module]) -> Vec<Option<usize>> {
let mut partners = vec![None; modules.len()];
let mut open = Vec::new();
for (index, module) in modules.iter().enumerate() {
match module.symbol {
'[' => open.push(index),
']' => {
if let Some(opening) = open.pop() {
partners[index] = Some(opening);
partners[opening] = Some(index);
}
}
_ => {}
}
}
partners
}
/// Writes modules back out as a string, with each one's numbers in parentheses after it.
fn modules_to_string(modules: &[Module]) -> String {
let mut text = String::with_capacity(modules.len());
for module in modules {
text.push(module.symbol);
if !module.parameters.is_empty() {
let numbers: Vec<String> = module.parameters.iter().map(|&number| format_f64(number)).collect();
text.push('(');
text.push_str(&numbers.join(","));
text.push(')');
}
}
text
}
/// Reads the axiom's modules, whose numbers may be written as math like `F(10*2)`.
fn parse_axiom(text: &str) -> Result<Vec<Module>, String> {
split_symbols(text)?
.into_iter()
.map(|(symbol, parameters)| {
let parameters = arguments(parameters).into_iter().map(evaluate_constant).collect::<Result<_, _>>()?;
Ok(Module { symbol, parameters })
})
.collect()
}
/// Parses one line of the rules.
fn parse_rule(line: &str) -> Result<Rule, String> {
let Some(separator) = rule_separator(line) else {
return Err("it needs an `=` between the symbol and what it becomes".to_string());
};
let (left_side, right_side) = (&line[..separator.start], &line[separator.end..]);
if rule_separator(right_side).is_some() {
return Err("it has a second `=`, but a condition checks equality with `==`".to_string());
}
// The left side reads `left < symbol > right : condition`, where all but the symbol are optional
let (pattern_text, condition_text) = split_at_first(left_side, ':');
let (left_context_text, rest) = match split_at_first(pattern_text, '<') {
(left_context, Some(rest)) => (Some(left_context), rest),
(rest, None) => (None, rest),
};
let (predecessor_text, right_context_text) = split_at_first(rest, '>');
let mut predecessor = parse_patterns(predecessor_text)?;
if predecessor.len() != 1 {
return Err("the left side must name exactly one symbol to rewrite".to_string());
}
let predecessor = predecessor.remove(0);
let left_context = left_context_text.map(parse_patterns).transpose()?.unwrap_or_default();
let right_context = right_context_text.map(parse_patterns).transpose()?.unwrap_or_default();
let condition = condition_text.map(parse_expression).transpose()?;
// The right side reads `successor : chance`, where the chance is optional
let (successor_text, chance_text) = match right_side.rfind(':') {
Some(colon) => (&right_side[..colon], Some(right_side[colon + 1..].trim())),
None => (right_side, None),
};
let chance = chance_text
.map(|text| match parse_f64(text) {
Some(chance) if (0. ..=1.).contains(&chance) => Ok(Chance::Fixed(chance)),
Some(_) => Err(format!("the chance `{text}` isn't a number from 0 to 1")),
None => parse_expression(text).map(Chance::Computed),
})
.transpose()?;
let successor = split_symbols(successor_text)?
.into_iter()
.map(|(symbol, parameters)| {
let parameters = arguments(parameters).into_iter().map(parse_expression).collect::<Result<_, _>>()?;
Ok(WrittenSymbol { symbol, parameters })
})
.collect::<Result<_, String>>()?;
Ok(Rule {
left_context,
predecessor,
right_context,
condition,
successor,
chance,
})
}
/// Reads symbols with names for their numbers, like `A(x)B`, as a rule's predecessor or context.
fn parse_patterns(text: &str) -> Result<Vec<Pattern>, String> {
split_symbols(text)?
.into_iter()
.map(|(symbol, parameters)| {
let parameter_names = arguments(parameters)
.into_iter()
.map(|name| {
let name = name.trim();
let mut characters = name.chars();
let valid = characters.next().is_some_and(|first| first.is_ascii_lowercase()) && characters.all(|character| character.is_ascii_alphanumeric() || character == '_');
if valid {
Ok(name.to_string())
} else {
Err(format!("`{name}` can't name a number, since names start with a lowercase letter, like `x`"))
}
})
.collect::<Result<_, _>>()?;
Ok(Pattern { symbol, parameter_names })
})
.collect()
}
/// The bytes of the first `=` or `->` outside parentheses, which separates a rule's two sides, passing over comparisons like `==`, `<=`, `>=` and `!=`.
fn rule_separator(text: &str) -> Option<Range<usize>> {
let bytes = text.as_bytes();
let mut depth = 0;
for (index, &byte) in bytes.iter().enumerate() {
let previous = index.checked_sub(1).map(|previous| bytes[previous]);
let next = bytes.get(index + 1).copied();
match byte {
b'(' => depth += 1,
b')' => depth -= 1,
b'-' if depth == 0 && next == Some(b'>') => return Some(index..index + 2),
b'=' if depth == 0 && !matches!(previous, Some(b'=' | b'<' | b'>' | b'!')) && next != Some(b'=') => return Some(index..index + 1),
_ => {}
}
}
None
}
/// Splits the text at the first `delimiter` outside parentheses, giving the text before it and, if found, the text after it.
fn split_at_first(text: &str, delimiter: char) -> (&str, Option<&str>) {
let mut depth = 0;
for (index, character) in text.char_indices() {
match character {
'(' => depth += 1,
')' => depth -= 1,
_ if character == delimiter && depth == 0 => return (&text[..index], Some(&text[index + character.len_utf8()..])),
_ => {}
}
}
(text, None)
}
/// Reads a string as symbols, each with the text inside any parentheses right after it. Whitespace between symbols is skipped.
fn split_symbols(text: &str) -> Result<Vec<(char, Option<&str>)>, String> {
let mut symbols = Vec::new();
let mut characters = text.char_indices().peekable();
while let Some((index, character)) = characters.next() {
if character.is_whitespace() {
continue;
}
if matches!(character, '(' | ')') {
return Err(format!("`{character}` must come right after a symbol, like `F(10)`"));
}
let after = index + character.len_utf8();
if !text[after..].starts_with('(') {
symbols.push((character, None));
continue;
}
let Some(close) = closing_parenthesis(text, after) else {
return Err(format!("the `(` after `{character}` is never closed"));
};
symbols.push((character, Some(&text[after + 1..close])));
while characters.next_if(|&(index, _)| index <= close).is_some() {}
}
Ok(symbols)
}
/// The byte index of the `)` that closes the `(` at `open`.
fn closing_parenthesis(text: &str, open: usize) -> Option<usize> {
let mut depth = 0;
for (index, character) in text[open..].char_indices() {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(open + index);
}
}
_ => {}
}
}
None
}
/// Splits the text inside a symbol's parentheses at its top-level commas, keeping the commas of nested calls like `max(a, b)`.
fn arguments(parameters: Option<&str>) -> Vec<&str> {
let Some(text) = parameters.filter(|text| !text.trim().is_empty()) else { return Vec::new() };
let mut pieces = Vec::new();
let mut depth = 0;
let mut start = 0;
for (index, character) in text.char_indices() {
match character {
'(' => depth += 1,
')' => depth -= 1,
',' if depth == 0 => {
pieces.push(&text[start..index]);
start = index + 1;
}
_ => {}
}
}
pieces.push(&text[start..]);
pieces
}
fn parse_expression(text: &str) -> Result<ast::Node, String> {
ast::Node::try_parse_from_str(text.trim()).map_err(|error| error.to_string())
}
/// Reads a written number, or works out the math of an expression like `10*2`.
fn evaluate_constant(text: &str) -> Result<f64, String> {
if let Some(number) = parse_f64(text.trim()) {
return Ok(number);
}
evaluate_number(&parse_expression(text)?, &Bindings::default())
}
/// Works out the math of an expression as a number, rounding away float noise so the string stays readable.
fn evaluate_number(expression: &ast::Node, bindings: &Bindings) -> Result<f64, String> {
let result = expression.eval(&EvalContext::new(bindings, NothingMap)).map_err(|error| error.to_string())?;
let number = result.as_value().and_then(|value| value.as_real()).ok_or_else(|| format!("`{result}` isn't a number"))?;
Ok(round_away_float_noise(number))
}
#[cfg(test)]
mod tests {
use super::*;
fn grow(axiom: &str, rules: &str, generations: i64) -> Result<String, (String, String)> {
grow_with(axiom, rules, generations, "+-", 0)
}
fn grow_with(axiom: &str, rules: &str, generations: i64, ignored_symbols: &str, seed: i64) -> Result<String, (String, String)> {
grow_up_to(axiom, rules, generations, ignored_symbols, seed, 1_000_000)
}
fn grow_up_to(axiom: &str, rules: &str, generations: i64, ignored_symbols: &str, seed: i64, max_symbols: i64) -> Result<String, (String, String)> {
let item = |text: &str| Item::new_from_element(text.to_string());
let number = Item::new_from_element;
l_system((), item(axiom), item(rules), item(ignored_symbols), number(generations), number(seed), number(max_symbols))
.map(Item::into_element)
.map_err(|(result, error)| (result.into_element(), error.to_string()))
}
#[test]
fn accepts_an_arrow_between_a_rules_sides() {
assert_eq!(grow("F", "F -> F+F", 1).unwrap(), "F+F");
assert_eq!(grow("F(3)", "F(x) : x > 2 -> F(x-1)", 1).unwrap(), "F(2)");
}
#[test]
fn rejects_a_single_equals_comparing_in_a_condition() {
let (_, error) = grow("F(0)", "F(m) : m=0 = X", 1).unwrap_err();
assert_eq!(error, "Line 1 of the rules isn't a valid rule: it has a second `=`, but a condition checks equality with `==`");
// Neither comparisons nor a `where` inside a symbol's parentheses separate the sides
assert_eq!(grow("F(0)", "F(m) : m == 0 = F(n where n = m + 1)", 1).unwrap(), "F(1)");
}
#[test]
fn rewrites_every_symbol_at_once() {
assert_eq!(grow("F", "F = F+F-F-F+F", 1).unwrap(), "F+F-F-F+F");
assert_eq!(grow("FX", "X = X+YF+\nY = -FX-Y", 2).unwrap(), "FX+YF++-FX-YF+");
assert_eq!(grow("FX", "X = X+YF+", 0).unwrap(), "FX");
}
#[test]
fn skips_whitespace_and_comment_lines() {
assert_eq!(grow("F G", "// F = G\n\nF = F + F", 1).unwrap(), "F+FG");
}
#[test]
fn matches_context_past_ignored_symbols_and_branches() {
assert_eq!(grow("ABC", "A < B > C = X", 1).unwrap(), "AXC");
assert_eq!(grow("ABD", "A < B > C = X", 1).unwrap(), "ABD");
assert_eq!(grow("A+BC", "A < B > C = X", 1).unwrap(), "A+XC");
// Left context steps out of the branch a symbol starts and over whole branches before it
assert_eq!(grow("A[B]", "A < B = X", 1).unwrap(), "A[X]");
assert_eq!(grow("A[C]B", "A < B = X", 1).unwrap(), "A[C]X");
// Right context ends with the branch
assert_eq!(grow("[AB]", "A > B = X", 1).unwrap(), "[XB]");
assert_eq!(grow("[A]B", "A > B = X", 1).unwrap(), "[A]B");
// Ignoring the brackets reads straight through branches
assert_eq!(grow_with("A[B]", "A > B = X", 1, "[]", 0).unwrap(), "X[B]");
assert_eq!(grow_with("A[Q]B", "A > B = X", 1, "[]", 0).unwrap(), "A[Q]B");
assert_eq!(grow_with("A[Q]B", "Q < B = X", 1, "[]", 0).unwrap(), "A[Q]X");
}
#[test]
fn cuts_the_rest_of_a_branch_after_a_percent_sign() {
assert_eq!(grow("[AB[C]D]E", "A = F%", 1).unwrap(), "[F]E");
assert_eq!(grow("AB[C]D", "A = F%", 1).unwrap(), "F");
assert_eq!(grow("F[%G]%H", "", 0).unwrap(), "F[]");
}
#[test]
fn the_first_matching_rule_applies() {
assert_eq!(grow("ABB", "A < B = X\nB = Y", 1).unwrap(), "AXY");
}
#[test]
fn works_out_parameters_and_conditions() {
let rules = "F(x) : x > 2 = F(x/2)[+F(x/2)]";
assert_eq!(grow("F(10)", rules, 1).unwrap(), "F(5)[+F(5)]");
assert_eq!(grow("F(5*2)", rules, 2).unwrap(), "F(2.5)[+F(2.5)][+F(2.5)[+F(2.5)]]");
// Below the condition's threshold, nothing changes
assert_eq!(grow("F(1)", rules, 3).unwrap(), "F(1)");
// A symbol carrying a different count of numbers doesn't match
assert_eq!(grow("F(1,2)F", rules, 1).unwrap(), "F(1,2)F");
// Context binds its own names
assert_eq!(grow("A(3)B(4)", "A(x) < B(y) = B(x+y)", 1).unwrap(), "A(3)B(7)");
}
#[test]
fn picks_among_chances_the_same_way_for_a_seed() {
let rules = "F = A : 0.5\nF = B : 0.5";
let first = grow_with("FFFFFFFFFFFFFFFFFFFF", rules, 1, "", 7).unwrap();
assert_eq!(first, grow_with("FFFFFFFFFFFFFFFFFFFF", rules, 1, "", 7).unwrap());
assert!(first.contains('A') && first.contains('B') && !first.contains('F'));
// A chance of zero is never picked
assert_eq!(grow_with("FFFF", "F = A : 0\nF = B : 1", 1, "", 3).unwrap(), "BBBB");
// A chance can be worked out from the symbol's numbers
assert_eq!(grow_with("F(1)F(0)", "F(x) = A : x\nF(x) = B : 1 - x", 1, "", 0).unwrap(), "AB");
let (_, error) = grow_with("F(2)", "F(x) = A : 1 - x", 1, "", 0).unwrap_err();
assert_eq!(error, "A rule's chance came out as -1, which isn't from 0 to 1");
}
#[test]
fn leaves_a_symbol_unchanged_with_the_chance_left_over() {
let grown = grow_with("FFFFFFFFFFFFFFFFFFFF", "F = A : 0.5", 1, "", 7).unwrap();
assert!(grown.contains('A') && grown.contains('F'));
// Chances adding up to exactly 1 always apply one of the rules
let grown = grow_with("FFFFFFFFFFFFFFFFFFFF", "F = A : 0.7\nF = B : 0.2\nF = C : 0.1", 1, "", 7).unwrap();
assert!(!grown.contains('F'));
let (_, error) = grow_with("F", "F = A : 0.6\nF = B : 0.6", 1, "", 0).unwrap_err();
assert_eq!(error, "The chances of the rules for `F` add up to 1.2, which is more than 1");
let (_, error) = grow("F", "F = A : 2", 1).unwrap_err();
assert_eq!(error, "Line 1 of the rules isn't a valid rule: the chance `2` isn't a number from 0 to 1");
}
#[test]
fn reports_the_first_invalid_line_and_keeps_the_valid_rules() {
let (result, error) = grow("F", "F = FF\nnonsense\nG(X) = G", 1).unwrap_err();
assert_eq!(result, "FF");
assert_eq!(error, "Line 2 of the rules isn't a valid rule: it needs an `=` between the symbol and what it becomes");
let (_, error) = grow("F", "G(X) = G", 1).unwrap_err();
assert!(error.starts_with("Line 1 of the rules isn't a valid rule: `X` can't name a number"));
let (result, error) = grow("F(", "", 1).unwrap_err();
assert_eq!(result, "");
assert_eq!(error, "The axiom isn't valid: the `(` after `F` is never closed");
}
#[test]
fn stops_before_a_generation_grows_past_max_symbols() {
let (result, error) = grow_up_to("F", "F = FFFFFFFFFF", 7, "", 0, 1000).unwrap_err();
assert_eq!(result.len(), 1000);
assert_eq!(error, "Stopped after 3 generations, since the next would grow past the Max Symbols limit of 1000");
}
#[test]
fn settled_growth_ends_early_and_max_symbols_caps_generations() {
// Once nothing changes, any number of generations finishes at once
assert_eq!(grow("F", "F = F", i64::MAX), Ok("F".to_string()));
assert_eq!(grow("A(1)", "A(n) : n < 3 = A(n+1)", i64::MAX), Ok("A(3)".to_string()));
// A string that keeps changing without growing stops at as many generations as Max Symbols
let (result, error) = grow_up_to("A(0)", "A(n) = A(n+1)", i64::MAX, "", 0, 100).unwrap_err();
assert_eq!(result, "A(100)");
assert_eq!(error, "Stopped after 100 generations, since Max Symbols also limits how many generations run");
// A generation left unchanged by a chance can still change in a later one
assert_eq!(grow("F", "F = F : 0.99\nF = G : 0.01", 2000), Ok("G".to_string()));
}
}
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more