Compare commits

...
63 changed files with 8977 additions and 2 deletions

No files matched your search

Generated
+1
View File
@@ -5408,6 +5408,7 @@ dependencies = [
"interpreted-executor", "interpreted-executor",
"log", "log",
"node-macro", "node-macro",
"serde_json",
] ]
[[package]] [[package]]
@@ -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 @@
//! //!
//! Shared fixtures live in [`test_support`]. //! Shared fixtures live in [`test_support`].
mod compiler_spike_templates;
mod lifecycle_tests; mod lifecycle_tests;
mod metadata_tests; mod metadata_tests;
mod round_trip_tests; mod round_trip_tests;
+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
@@ -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(())
}
@@ -43,6 +43,10 @@ gungraun = { workspace = true }
preprocessor = { workspace = true } preprocessor = { workspace = true }
# Benchmarks # Benchmarks
[[bench]]
name = "compile_pipeline"
harness = false
[[bench]] [[bench]]
name = "update_executor" name = "update_executor"
harness = false harness = false
@@ -1,5 +1,6 @@
use criterion::BenchmarkGroup; use criterion::BenchmarkGroup;
use criterion::measurement::Measurement; use criterion::measurement::Measurement;
use graph_craft::document::NodeNetwork;
use graph_craft::proto::ProtoNetwork; use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name}; use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi; 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::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope; 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 network = load_from_name(name);
let editor_api = std::sync::Arc::new(EditorApi::default()); 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(); let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap(); preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network); 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:")
);
}
}
+2
View File
@@ -22,6 +22,7 @@ log = { workspace = true }
graphene-std = { workspace = true, features = ["gpu"] } graphene-std = { workspace = true, features = ["gpu"] }
graph-craft = { workspace = true } graph-craft = { workspace = true }
interpreted-executor = { workspace = true } interpreted-executor = { workspace = true }
serde_json = { workspace = true }
[dev-dependencies] [dev-dependencies]
# Workspace dependencies # Workspace dependencies
@@ -29,4 +30,5 @@ core-types = { workspace = true }
dyn-any = { workspace = true } dyn-any = { workspace = true }
futures = { workspace = true } futures = { workspace = true }
glam = { workspace = true } glam = { workspace = true }
graph-craft = { workspace = true, features = ["loading"] }
node-macro = { workspace = true } node-macro = { workspace = true }
+2
View File
@@ -450,6 +450,8 @@ pub enum PreprocessorError {
Definition(DefinitionError), Definition(DefinitionError),
} }
pub mod spike_export;
#[cfg(test)] #[cfg(test)]
mod destructure_tests { mod destructure_tests {
use super::*; use super::*;
+193
View File
@@ -0,0 +1,193 @@
use crate::{Preprocessor, Substitution};
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::*;
use graph_craft::graphene_compiler::Compiler;
use graph_craft::{ProtoNodeIdentifier, Type};
use graphene_std::NodeCompileMetadata;
use graphene_std::application_io::EditorApi;
use graphene_std::platform_application_io::ResourceHash;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::util::wrap_network_in_scope;
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::Arc;
struct DummySpawner;
impl Spawn for DummySpawner {
fn spawn(&self, _task: Task) {}
}
fn export_type(ty: &Type) -> Value {
match ty {
Type::Generic(name) => json!({ "Generic": name }),
Type::Concrete(descriptor) => json!({ "Concrete": descriptor.name }),
Type::Fn(input, output) => json!({ "Fn": [export_type(input), export_type(output)] }),
Type::Item(element) => json!({ "Item": export_type(element) }),
Type::List(element) => json!({ "List": export_type(element) }),
}
}
fn export_input(input: &NodeInput) -> Value {
match input {
NodeInput::Node { node_id, output_index } => json!({ "Node": { "node": node_id.0, "output": output_index } }),
NodeInput::Value { tagged_value, exposed } => {
let producer = match &**tagged_value {
TaggedValue::Resource(_) => Some("resource"),
TaggedValue::AnimationCurve(_) => Some("curve"),
_ => None,
};
json!({ "Value": {
"ty": export_type(&tagged_value.ty()),
"hash": tagged_value.hash_code(),
"size": serde_json::to_string(&**tagged_value).map_or(0, |serialized| serialized.len()),
"exposed": exposed,
"producer": producer,
} })
}
NodeInput::Import { import_type, import_index } => json!({ "Import": { "ty": export_type(import_type), "index": import_index } }),
NodeInput::Scope(key) => json!({ "Scope": key }),
NodeInput::Reflection(metadata) => json!({ "Reflection": format!("{metadata:?}") }),
}
}
fn export_compile_metadata(metadata: &NodeCompileMetadata) -> Value {
json!({
"extract": metadata.extract.bits(),
"inject": metadata.inject.bits(),
"footprint_invariant": metadata.footprint_invariant,
"forwards_input": metadata.forwards_input,
"constant_inputs": metadata.constant_inputs,
})
}
fn export_node(node: &DocumentNode) -> Value {
let implementation = match &node.implementation {
DocumentNodeImplementation::Network(network) => json!({ "Network": export_network(network) }),
DocumentNodeImplementation::Definition(id) => json!({ "Definition": id.0 }),
DocumentNodeImplementation::ProtoNode(identifier) => json!({ "Proto": identifier.as_str() }),
DocumentNodeImplementation::Extract => json!("Extract"),
};
json!({
"inputs": node.inputs.iter().map(export_input).collect::<Vec<_>>(),
"call_argument": export_type(&node.call_argument),
"implementation": implementation,
"visible": node.visible,
"skip_deduplication": node.skip_deduplication,
"compile_metadata": node.compile_metadata.as_ref().map(export_compile_metadata),
})
}
fn export_network(network: &NodeNetwork) -> Value {
let mut nodes: Vec<_> = network.nodes.iter().collect();
nodes.sort_by_key(|(id, _)| id.0);
let mut scope_injections: Vec<_> = network.scope_injections.iter().collect();
scope_injections.sort_by_key(|(key, _)| key.as_str());
let mut definitions: Vec<_> = network.definitions.iter().collect();
definitions.sort_by_key(|(id, _)| id.0);
json!({
"exports": network.exports.iter().map(export_input).collect::<Vec<_>>(),
"nodes": nodes.into_iter().map(|(id, node)| json!([id.0, export_node(node)])).collect::<Vec<_>>(),
"scope_injections": scope_injections.into_iter().map(|(key, (id, ty))| json!([key, id.0, export_type(ty)])).collect::<Vec<_>>(),
"definitions": definitions.into_iter().map(|(id, definition)| json!([id.0, export_network(definition)])).collect::<Vec<_>>(),
"generated": network.generated,
})
}
fn export_registry() -> Value {
let registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
let mut identifiers: Vec<&ProtoNodeIdentifier> = registry.keys().collect();
identifiers.sort_by_key(|identifier| identifier.as_str());
let entries: Vec<_> = identifiers
.into_iter()
.map(|identifier| {
let mut implementations: Vec<_> = registry[identifier]
.keys()
.map(|io| json!({ "call_argument": export_type(&io.call_argument), "inputs": io.inputs.iter().map(export_type).collect::<Vec<_>>(), "output": export_type(&io.return_value) }))
.collect();
implementations.sort_by_key(|implementation| implementation.to_string());
json!({ "identifier": identifier.as_str(), "implementations": implementations })
})
.collect();
json!(entries)
}
fn sorted<T>(map: &HashMap<ProtoNodeIdentifier, T>) -> Vec<&ProtoNodeIdentifier> {
let mut identifiers: Vec<_> = map.keys().collect();
identifiers.sort_by_key(|identifier| identifier.as_str());
identifiers
}
fn export_preprocessor(preprocessor: &Preprocessor) -> Value {
let substitutions: Vec<_> = sorted(&preprocessor.substitutions)
.into_iter()
.map(|identifier| {
let Substitution { node, wrapped_node_id } = &preprocessor.substitutions[identifier];
json!({ "identifier": identifier.as_str(), "node": export_node(node), "wrapped_node_id": wrapped_node_id.0 })
})
.collect();
let inject_scopes: Vec<_> = sorted(&preprocessor.inject_scopes)
.into_iter()
.map(|identifier| {
let (template, ty) = &preprocessor.inject_scopes[identifier];
json!({ "identifier": identifier.as_str(), "template": export_node(template), "ty": export_type(ty) })
})
.collect();
let compile_metadata: Vec<_> = sorted(&preprocessor.compile_metadata)
.into_iter()
.map(|identifier| json!({ "identifier": identifier.as_str(), "metadata": export_compile_metadata(&preprocessor.compile_metadata[identifier]) }))
.collect();
json!({ "substitutions": substitutions, "inject_scopes": inject_scopes, "compile_metadata": compile_metadata })
}
/// A document to export, with the resource store its value inputs resolve against.
pub struct WorkloadDocument<'a> {
pub name: String,
pub network: NodeNetwork,
pub resolve_resource: Box<dyn Fn(ResourceId) -> Option<ResourceHash> + 'a>,
}
/// Writes the compiler spike's workloads into `output_directory`: each document's scoped network before preprocessing,
/// the node registry, the preprocessor's tables, and the real compiler's results for validating the spike's baseline port.
pub fn export_compiler_spike_workloads<'a>(output_directory: &Path, documents: impl IntoIterator<Item = WorkloadDocument<'a>>) -> Result<(), String> {
std::fs::create_dir_all(output_directory).map_err(|error| error.to_string())?;
let write = |name: &str, value: &Value| std::fs::write(output_directory.join(format!("{name}.json")), value.to_string()).map_err(|error| error.to_string());
let preprocessor = Preprocessor::new();
write("registry", &export_registry())?;
write("preprocessor", &export_preprocessor(&preprocessor))?;
let runtime = AsyncRuntime::new(Arc::new(DummySpawner));
let mut expected = serde_json::Map::new();
for WorkloadDocument { name, network, resolve_resource } in documents {
let scoped = wrap_network_in_scope(network, Arc::new(EditorApi::default()), runtime.handle());
write(&name, &export_network(&scoped))?;
let mut preprocessed = scoped;
preprocessor.preprocess(&mut preprocessed, &*resolve_resource).map_err(|error| format!("{name}: {error:?}"))?;
let proto_network = Compiler {}.compile_single(preprocessed).map_err(|error| format!("{name}: {error:?}"))?.network;
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 mut identifier_counts = std::collections::BTreeMap::<&str, usize>::new();
for (_, node) in &proto_network.nodes {
*identifier_counts.entry(node.identifier.as_str()).or_default() += 1;
}
let executor = interpreted_executor::dynamic_executor::DynamicExecutor::new(proto_network.clone()).map_err(|error| format!("{name}: {error:?}"))?;
expected.insert(
name,
json!({
"proto_nodes": proto_network.nodes.len(),
"unique_stable_ids": unique_stable_ids.len(),
"distinct_identifiers": distinct_identifiers.len(),
"identifier_counts": identifier_counts,
"output_type": executor.output_type().as_ref().map(export_type),
}),
);
}
write("expected", &Value::Object(expected))
}
+243
View File
@@ -0,0 +1,243 @@
# Summary
Replace the graph compilation pipeline (preprocess, flatten, nullification, stable IDs, typing, borrow tree construction) with a pipeline built on shared definitions, interned types, and a single post-order lowering pass that emits a topologically ordered IR without ever sorting.
Shared definitions are also a user-facing feature: a subgraph defined once and instantiated many times, where editing the definition changes every instance.
# Motivation
## Performance
Cold compilation of the demo artwork, measured on migrated documents through the editor's own load path (median of 20, release build):
| document | proto nodes | preprocess | compile | executor construction | total |
|---|---|---|---|---|---|
| red-dress | 4172 | 0.34 ms | 6.74 ms | 5.64 ms | 12.7 ms |
| isometric-fountain | 3232 | 0.27 ms | 4.48 ms | 4.58 ms | 9.3 ms |
| valley-of-spires | 2890 | 0.25 ms | 3.91 ms | 4.06 ms | 8.2 ms |
| painted-dreams | 1857 | 0.17 ms | 2.59 ms | 2.72 ms | 5.5 ms |
| changing-seasons | 632 | 0.05 ms | 0.77 ms | 1.05 ms | 1.9 ms |
That is roughly 3 µs per proto node, and every edit pays it because there is no incremental compilation.
A perf profile (DWARF call graphs, 300 iterations over all demos) attributes the time as follows, as shares of the whole run:
- `DynamicExecutor::new`: 43%, of which `TypingContext::infer` 27% (scanning registry impls per node, collecting `NodeIOTypes`, cloning and dropping `Type`, `valid_type`) and `BorrowTree::push_node` 15% (of which `update_source_map` 8.6%, a `HashMap<Box<[NodeId]>, _>` of document paths).
- `Compiler::compile`: 40%, of which `flatten_with_fns` 19% (cloning `DocumentNode`s and their input `Vec`s, `HashMap` inserts and rehashes), `reorder_ids` 11% (two full topological sorts with ID remapping), `generate_stable_node_ids` 3.7% (SipHash over value contents, including vector segment data), `into_proto_networks` 3.4%.
- Preprocessing: 3%.
- Across all phases, malloc/free and memmove account for about 40% of self time.
The dominant cost is copying and allocating, not computation.
Incremental fixes to the current pipeline (FxHash, one topological sort, fewer clones) are expected to give a small constant factor; reaching the target below needs a different representation.
## Duplication
| document | document nodes | after preprocessing | proto nodes | unique stable IDs | distinct identifiers |
|---|---|---|---|---|---|
| red-dress | 1228 | 4173 | 4172 | 2413 | 42 |
| isometric-fountain | 985 | 3278 | 3232 | 2099 | 46 |
| painted-dreams | 602 | 1990 | 1857 | 1205 | 53 |
The preprocessor wraps every node macro node in a generated network (one input adapter per field), which flattening then clones per use: a 3.4x expansion.
42% of the resulting proto nodes are duplicates that are only removed after being built, and the whole document uses about 45 distinct node identifiers.
Most typing and construction work repeats a small set of signatures.
## Semantics
Users need reusable subgraphs: edit a definition once and have every instance follow.
The `.gdd` storage format already supports this structurally (`Implementation::Network(NetworkId)` can be referenced by several nodes), but the runtime inlines every nested network, so `from_runtime` mints a fresh network per traversal and the sharing is lost.
# Goals
- Cold compile of red-dress, through executor construction, in under 0.5 ms (about 100 ns per proto node).
- Compile work proportional to distinct definitions and signatures, not to instances.
- No topological sort and no ID remapping pass.
- Type checking that supports context-injected types and integrates coercion and rank promotion, replacing post hoc promotions.
- A structure that admits incremental compilation later without redesign.
- A backend-neutral compiled IR, the successor of `ProtoNetwork`, consumed either by the interpreted executor or by a Rust codegen backend that emits a compilable source file.
# Guide-level explanation
## Definitions and instances
A *definition* is either a network (nodes, exports, typed imports) or a proto node identifier.
A *node* in a network is an *instance*: a definition reference plus input bindings.
```rs
pub struct DefinitionId(u32);
pub enum Definition {
Network(NetworkDefinition),
Proto(ProtoNodeIdentifier),
}
pub struct Instance {
pub definition: DefinitionId,
pub inputs: Vec<NodeInput>,
// visible, call_argument, ...
}
```
The document owns a definitions table; the root network is one definition.
`DocumentNodeImplementation::Network(NodeNetwork)` becomes `Network(DefinitionId)`, mirroring `.gdd`'s `Implementation::Network(NetworkId)` so the storage conversion is one to one.
Editing a node inside a shared definition changes every instance.
Editing only one instance requires an explicit *make unique* operation, which copies the definition and repoints that instance.
## What compilation does
Compilation is two deterministic passes over the instance tree, with no backtracking:
1. **Context pass (top-down, from the output toward sources).**
Computes each node's *context signature*: which context features are injected above it and with which types (for example the vararg item type injected by Write Attribute's `value` lambda).
This is what lets a generic "read" node resolve its output type from an injection performed by a node called earlier in the call chain.
2. **Lowering pass (bottom-up, post-order).**
For each node, with its inputs already lowered: select the implementation and any input coercions, compute its context features and nullification, hash-cons it, and append it to the IR.
Lowering is memoized per `(definition, input signatures, context signature)`, so a definition instantiated a hundred times with the same types is lowered once and referenced a hundred times.
# Reference-level explanation
## Type interning
`Type` is a recursive enum of boxes; cloning and comparing it is the largest single typing cost.
All types are interned into a process-wide `TypeInterner`:
```rs
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct TypeId(u32);
```
Structural equality becomes integer equality, and node signatures (`call_argument`, inputs, output) are interned slices of `TypeId`.
The registry is indexed per identifier by input signature, so implementation lookup is a hash of a few integers instead of a scan over all impls with `valid_type` per candidate.
Generic resolution (`Generic("T")`) substitutes over interned types and caches the substitution result.
## Implementation selection and coercion
The compiler names no data types.
Coercion is driven by two inputs registered next to the types themselves, the same way nodes register today:
- **Conversions** are ordinary conversion node implementations (`from → to`); registering one makes the edge available.
- **A purity relation** is a partial order on data types, declared as "`A` is purer than `B`" edges (for example `Color` purer than `Vector`, `Vector` purer than `Raster<CPU>`).
The registry takes the transitive closure once at startup and stores it as a bit matrix over interned `TypeId`s.
The cost of a conversion `A → B` is derived from the relation, never declared per conversion:
| relation of `A` to `B` | conversion kind |
|---|---|
| `A` = `B` | identity, no conversion |
| `A` purer than `B` | purity-losing, applied automatically |
| `B` purer than `A` | purity-gaining (lossy), governed by policy |
| incomparable | not applied automatically |
For one input:
1. If an implementation accepts the incoming type, no conversion is applied.
2. Otherwise at most one registered conversion is applied per edge (no transitive chains).
3. Among the reachable accepted types, the maximal element under the purity order wins (for example `Color` into `{Vector, Raster}` becomes `Vector`); incomparable maxima are an ambiguity error.
Whether purity-gaining conversions may be applied automatically is a policy deliberately left open; initially they are not registered as automatic.
For nodes with several generic inputs, the implementation is chosen jointly by the lexicographic sum of per-input conversion kinds.
Adding a data type means registering its conversions and its purity edges; the compiler does not change.
Rank promotion (`Item<T>` to `List<T>`) is a structural coercion over the `Item`/`List` type constructors, ranked as identity-preserving, which replaces the `promotions` map and the retry path in `TypingContext`.
Selection results are memoized by `(identifier, input TypeIds, context signature)`; with about 45 distinct identifiers per document the table stays tiny.
Adapters are emitted as ordinary IR nodes only on edges that need them, which replaces the preprocessor's blanket per-field wrapping.
## The IR
```rs
pub struct CompiledGraph {
/// Topologically ordered: every node's inputs have lower indices.
pub nodes: Vec<IrNode>,
/// Flat input index storage, sliced by `IrNode::inputs`.
pub inputs: Vec<u32>,
pub values: Vec<MemoHash<TaggedValue>>,
}
pub struct IrNode {
/// The selected implementation: the proto node identifier plus its resolved monomorphic signature.
pub implementation: ImplementationId,
pub inputs: Range<u32>,
pub signature: SignatureId,
pub features: ContextFeatures,
pub content_hash: u64,
pub origin: OriginId,
}
```
The IR names implementations by identifier and monomorphic signature, never by an executor's constructor function, so it stays backend-neutral.
The interpreted executor maps each `ImplementationId` to a registry constructor; a Rust codegen backend maps it to the node's Rust path with its type arguments and emits the graph as a source file, using the IR's order as the statement order.
Topological order is a property of construction: a node is appended only after all of its inputs (post-order), so no sort or remap is needed.
Cycles are detected by the same DFS's visiting state.
Hash-consing uses `content_hash = hash(implementation, input content hashes, value hash)`, which replaces `generate_stable_node_ids` and removes duplicates before they are built.
Value hashes come from `MemoHash`'s cached hash instead of rehashing value contents.
`origin` indexes a table of document locations that is materialized only when something asks for it (errors, the Data panel, monitor lookup), replacing the per-node `Box<[NodeId]>` path map that executor construction currently maintains.
## Context features and nullification
Context features are already a bottom-up union, and the current algorithm (`find_context_dependencies`) decides where to insert nullification at the parent from its branches' feature sets.
Both therefore fold into the lowering pass, together with the footprint invariance and other compile-time checks.
## Executor construction
The borrow tree becomes a `Vec` of node containers indexed by IR index, with inputs resolved by index instead of `HashMap<NodeId, _>` lookups.
Across recompiles, containers are reused by content hash, as stable node IDs allow today.
## Allocation budget
- One flat buffer per IR table, reused across compiles; no per-node `Vec`.
- No cloning of document nodes: lowering reads the definitions table by reference.
- FxHash wherever hashing remains.
- The source map is materialized on demand only.
## Incremental compilation (future)
The lowering memo key, `(definition content hash, input signatures, context signature)`, is also a cache key across compiles: a definition untouched by an edit, used under the same signatures, keeps its lowered fragment.
`NodeNetworkInterface` change events mark the edited definitions dirty.
This works because both passes are deterministic and each node's result depends only on its upstream cone plus its context signature.
## Storage
`.gdd` already stores a networks table, so the runtime/storage conversion becomes structural and `from_runtime` stops duplicating networks.
Legacy documents contain inlined copies of nested networks.
These must not be merged into shared definitions automatically, since that would silently change edit semantics.
Only compiler-generated structure (former preprocessor wrappers, adapters) is shared implicitly.
# Migration plan
1. Benchmark harness: the editor-hosted timing harness over migrated demos becomes a committed benchmark, and the interpreted-executor benchmarks (currently broken on raw legacy files) load migrated fixtures.
2. Type interner, usable by both the old and new pipelines.
3. Definitions table in the runtime `NodeNetwork`, `NodeNetworkInterface`, and the storage conversion.
4. New pipeline next to the old one, with a differential test that evaluates every demo through both and compares outputs.
5. Coercion and rank promotion in the lowering pass; remove the preprocessor's wrapper generation.
6. Switch over and delete the old pipeline.
# Drawbacks
- A large change touching the editor, storage conversion, compiler, and executor at once.
- Shared definitions add user-facing concepts (shared vs unique, make unique) that need UX work.
- Two pipelines coexist during the transition.
# Rationale and alternatives
- **Quick wins in the current pipeline** (FxHash, a single topological sort, interned types only): lower risk, but the representation still clones every instance and builds duplicates before removing them, which caps the speedup at a small constant factor.
- **A query system (Salsa-style)**: more general incrementality, but it adds a framework before the basic pipeline is fast; the memo key above can migrate to queries later.
- **Set-of-types propagation with backward commitment**: more expressive resolution, but the chosen implementation would no longer be a function of a node's upstream cone, which conflicts with cone-local incremental compilation. The context pass covers the motivating case (types injected by callers) deterministically.
# Unresolved questions
- **Per-instance inputs under sharing**: `NodeInput::Reflection` (a node's own location), monitor nodes for layer thumbnails, and `skip_deduplication` are inherently per instance. Proposal: lift them into implicit definition parameters supplied by each instance, so the definition body stays shared.
- **Typed imports**: definitions need declared import types to be lowered once per signature; today import types live on each `NodeInput::Import`.
- **Context signature representation**: which injected facts it carries (feature set, vararg item types, later attribute schemas) and how it is interned.
- **Lossy automatic conversions**: policy deferred; initially not applied automatically.
- **Purity declarations**: where the edges are declared (on the type, with a derive or attribute, or as standalone registrations in the crate defining the conversion) and how an inconsistent declaration (a cycle) is reported.
- **`Extract` implementations and scope injections** under shared definitions.
- **Make unique** semantics and UX in `NodeNetworkInterface`, including undo and collaboration deltas.
# Future possibilities
- Attribute schemas carried in list types, so reads downstream of a write on the same list are typed forward (requires constant attribute names).
- Persistent cross-compile fragment cache, keyed by the lowering memo key.
- JIT or precompiled emission of hot subgraphs from the IR.