use super::documents::{declare_document, js_string, tree_of_element, DocTree, TagRule, Vocabulary};
use super::element::{attributes, elements, rust_name};
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};
elements! {
world: children;
space: leaf;
group: leaf;
unit: leaf;
view: leaf;
scene: children;
body: leaf;
device: children;
channel: leaf;
bound: leaf;
interlock: leaf;
dashboard: children;
param: leaf;
split: children;
pane: leaf;
region: leaf;
geoproject: children;
date_range = "dateRange": leaf;
camera: leaf;
reference: leaf;
shock: children;
scenario: children;
geomodel: children;
parameter: leaf;
geoparams: children;
geolayer: children;
geoformula: children;
geoview: children;
georeport: children;
geograph: children;
opgraph: children;
node: leaf;
wire: leaf;
}
attributes! {
pub trait OntologyAttrs {
name; kind; description; from; model; uid; device; serial; revision; domain; support; channels; manual_url; position; rotation;
origin_mm = "origin_mm"; size_mm = "size_mm"; dimensions_mm = "dimensions_mm";
hz; at; rot; vel; shape; mass; friction; restitution; angular_damping = "angular_damping"; gravity; scale;
backdrop; walls; grids; bodies; forces; particles; entities; relations; systems; robots; joints; links; kinematics;
dynamics; constraints; fidelity; motion; color; blend; balance; coupled; seals; release; calibration; optics; root; policies;
id; type_; label; dir; medium; format; transport; interface; manufacturer; model_number = "model_number";
product_url = "product_url"; price_usd = "price_usd"; record_hz = "record_hz"; spec_check = "spec_check";
limits; min_interval_ms; verbs; units; unit; rate; baud; dialect; encoding; conversion; parameters; params; editor;
rapid_mm_per_min;
firmware;
notes; status; suggest; speed; source; title; value; rank;
channel; field; min; max; max_rate; max_speed; requires; when; why;
focus; accept; default; required; axis; ratio; side; tab; open; collapsed; selected; path; view; world; param;
file; group; pad;
created_at; updated_at; default_workspace; metadata; start; end; center_lat; center_lng; zoom; pitch; bearing;
role; hash;
event_type; targets; duration_months; magnitude; probability; implementation_lag_months; enabled; affected_variables;
transmission_channels; baseline_date; time_horizon; parent_scenario; events; models; parameter_sets; tags; runtime;
version; compatible_events; assumptions; limitations; citations; validation; for_model; values;
renderer; category; source_dataset; source_formula; opacity; visible; filter; normalize_by; zoom_range; expression;
output_unit; missing_value; camera; enabled_layers; layer_overrides; selection; timeline; comparison; blocks; nodes;
edges;
meta; inputs; output; disabled; x; y; to; shade_a; shade_b; angle; seed; density; radius; freq; octave;
}
}
pub(crate) const FAMILY: Family =
Family { module: "ontology", roots: &["world", "device", "dashboard", "geoproject", "shock", "scenario", "geomodel", "geoparams", "geolayer", "geoformula", "geoview", "georeport", "geograph", "opgraph"], declare };
pub const NODE_GRAPH_ID: &str = "nodegraph";
pub const UNIT_FIELDS: &[&str] = &["uid", "name", "device", "serial", "revision", "domain", "group", "size_mm", "support", "channels", "manualUrl", "position", "rotation", "tilt_deg", "release", "calibration", "inputs", "equipment_id"];
pub const GROUP_FIELDS: &[&str] = &["uid", "name", "description", "group", "size_mm", "position", "rotation"];
const WORLD_FIELDS: &[&str] = &["name", "description", "from", "model", "links", "policies"];
const WORLD_READ: &[&str] = &["name", "description", "from", "model", "links", "policies", "kind"];
const WORLD_KIND: &str = "a world names real things: it has no kind; a simulation is a run of a .3d.tsx";
const WORLD_SCENE: &str = "a world declares no scene: its twin steps its model's scene (model=\"model.3d.tsx\"), and a simulation's scene is a .3d.tsx's";
const BOUND_FIELDS: &[&str] = &["channel", "field", "min", "max", "maxRate", "maxSpeed", "why"];
const INTERLOCK_FIELDS: &[&str] = &["name", "unit", "channel", "verbs", "when", "requires", "why"];
const DEVICE_INTERLOCK_FIELDS: &[&str] = &["name", "channel", "verbs", "when", "requires", "why"];
const GEO_FIELDS: &[&str] = &["id", "name", "createdAt", "updatedAt", "description", "defaultWorkspace", "metadata"];
const NODE_ATTRS: &[&str] = &["id", "type", "label", "x", "y", "disabled", "output", "meta", "inputs"];
const DASHBOARD_STRUCTURE: &[&str] = &["format", "layout", "panes", "params", "regions"];
const WORLD: Vocabulary = Vocabulary {
format: "world",
noun: "a world",
root: "world",
tags: &[
TagRule::new("world", &[]).required(&["name"]).attrs(WORLD_READ),
TagRule::new("space", &["world"]).single().required(&["origin_mm", "size_mm"]).attrs(&["origin_mm", "size_mm"]),
TagRule::new("group", &["world"]).key("uid").required(&["uid", "name"]).attrs(GROUP_FIELDS),
TagRule::new("unit", &["world"]).key("uid").required(&["uid", "name", "device"]).attrs(UNIT_FIELDS),
TagRule::new("view", &["world"]).single(),
TagRule::new("scene", &["world"]),
TagRule::new("body", &["scene"]),
TagRule::new("interlock", &["world"]).key("name").required(&["name", "unit", "channel", "requires", "why"]).attrs(INTERLOCK_FIELDS),
],
from_tree: world_of,
};
const DEVICE: Vocabulary = Vocabulary {
format: "device",
noun: "a device definition",
root: "device",
tags: &[
TagRule::new("device", &[]).required(&["name"]),
TagRule::new("channel", &["device"]).key("id").required(&["id"]),
TagRule::new("bound", &["device"]).required(&["channel", "field"]).attrs(BOUND_FIELDS),
TagRule::new("interlock", &["device"]).key("name").required(&["name", "channel", "requires", "why"]).attrs(DEVICE_INTERLOCK_FIELDS),
],
from_tree: device_of,
};
const DASHBOARD: Vocabulary = Vocabulary {
format: "dashboard",
noun: "a dashboard",
root: "dashboard",
tags: &[
TagRule::new("dashboard", &[]).required(&["name"]),
TagRule::new("param", &["dashboard"]).key("id").required(&["id", "type"]),
TagRule::new("split", &["dashboard", "split"]).required(&["axis", "ratio"]).attrs(&["axis", "ratio"]),
TagRule::new("pane", &["dashboard", "split"]).key("id").required(&["id"]),
TagRule::new("region", &["dashboard"]).key("side").required(&["side"]),
],
from_tree: dashboard_of,
};
const GEO: Vocabulary = Vocabulary {
format: "geo",
noun: "a geo project",
root: "geoproject",
tags: &[
TagRule::new("geoproject", &[]).required(&["id", "name"]).attrs(GEO_FIELDS),
TagRule::new("dateRange", &["geoproject"]).single().required(&["start", "end"]),
TagRule::new("camera", &["geoproject"]).single(),
TagRule::new("reference", &["geoproject"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
],
from_tree: geo_of,
};
const GEO_OWN: &[&str] = &["id", "name", "metadata"];
const SHOCK_DATA: &[&str] = &["eventType", "targets", "start", "durationMonths", "magnitude", "probability", "implementationLagMonths", "enabled", "affectedVariables", "transmissionChannels", "notes"];
const SCENARIO_DATA: &[&str] = &["baselineDate", "timeHorizon", "parentScenario", "events", "models", "parameterSets", "tags"];
const GEOMODEL_DATA: &[&str] = &["runtime", "version", "compatibleEvents", "assumptions", "limitations", "citations", "validation"];
const GEOPARAMS_DATA: &[&str] = &["forModel", "values"];
const GEOLAYER_DATA: &[&str] = &["renderer", "category", "sourceDataset", "sourceFormula", "scale", "opacity", "visible", "units", "filter", "normalizeBy", "zoomRange"];
const GEOFORMULA_DATA: &[&str] = &["inputs", "expression", "outputUnit", "missingValue"];
const GEOVIEW_DATA: &[&str] = &["camera", "enabledLayers", "layerOverrides", "selection", "timeline", "comparison"];
const GEOREPORT_DATA: &[&str] = &["blocks"];
const GEOGRAPH_DATA: &[&str] = &["nodes", "edges"];
macro_rules! geo_document {
($name:ident, $format:literal, $noun:literal, $attrs:expr, $of:ident, $type_:literal, $data:ident) => {
const $name: Vocabulary = Vocabulary {
format: $format,
noun: $noun,
root: $format,
tags: &[
TagRule::new($format, &[]).required(&["id", "name"]).attrs($attrs),
TagRule::new("reference", &[$format]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
],
from_tree: $of,
};
fn $of(t: &DocTree) -> Result<Json, String> {
geo_file_of(t, $type_, $data, None)
}
};
}
geo_document!(GEOLAYER, "geolayer", "a geo layer", &["id", "name", "metadata", "renderer", "category", "sourceDataset", "sourceFormula", "scale", "opacity", "visible", "units", "filter", "normalizeBy", "zoomRange"], geolayer_of, "geoeconomics/layer", GEOLAYER_DATA);
geo_document!(GEOFORMULA, "geoformula", "a geo formula", &["id", "name", "metadata", "inputs", "expression", "outputUnit", "missingValue"], geoformula_of, "geoeconomics/formula", GEOFORMULA_DATA);
geo_document!(GEOVIEW, "geoview", "a geo view", &["id", "name", "metadata", "camera", "enabledLayers", "layerOverrides", "selection", "timeline", "comparison"], geoview_of, "geoeconomics/view", GEOVIEW_DATA);
geo_document!(GEOREPORT, "georeport", "a geo report", &["id", "name", "metadata", "blocks"], georeport_of, "geoeconomics/report", GEOREPORT_DATA);
geo_document!(GEOGRAPH, "geograph", "a geo graph", &["id", "name", "metadata", "nodes", "edges"], geograph_of, "geoeconomics/graph", GEOGRAPH_DATA);
const SHOCK: Vocabulary = Vocabulary {
format: "shock",
noun: "a shock",
root: "shock",
tags: &[
TagRule::new("shock", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "eventType", "targets", "start", "durationMonths", "magnitude", "probability", "implementationLagMonths", "enabled", "affectedVariables", "transmissionChannels", "notes"]),
TagRule::new("reference", &["shock"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
],
from_tree: shock_of,
};
const SCENARIO: Vocabulary = Vocabulary {
format: "scenario",
noun: "a scenario",
root: "scenario",
tags: &[
TagRule::new("scenario", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "baselineDate", "timeHorizon", "parentScenario", "events", "models", "parameterSets", "tags"]),
TagRule::new("reference", &["scenario"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
],
from_tree: scenario_of,
};
const GEOMODEL: Vocabulary = Vocabulary {
format: "geomodel",
noun: "a geo model",
root: "geomodel",
tags: &[
TagRule::new("geomodel", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "runtime", "version", "compatibleEvents", "assumptions", "limitations", "citations", "validation"]),
TagRule::new("parameter", &["geomodel"]).key("name").required(&["name", "default", "min", "max"]).attrs(&["name", "label", "default", "min", "max"]),
TagRule::new("reference", &["geomodel"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
],
from_tree: geomodel_of,
};
const GEOPARAMS: Vocabulary = Vocabulary {
format: "geoparams",
noun: "a geo parameter set",
root: "geoparams",
tags: &[
TagRule::new("geoparams", &[]).required(&["id", "name"]).attrs(&["id", "name", "metadata", "forModel", "values"]),
TagRule::new("reference", &["geoparams"]).key("path").required(&["role", "path"]).attrs(&["role", "path", "hash"]),
],
from_tree: geoparams_of,
};
const OPGRAPH: Vocabulary = Vocabulary {
format: "opgraph",
noun: "a node graph",
root: "opgraph",
tags: &[
TagRule::new("opgraph", &[]).attrs(&["id", "name", "domain", "meta"]),
TagRule::new("node", &["opgraph"]).key("id").required(&["id", "type"]),
TagRule::new("wire", &["opgraph"]).key("to").required(&["from", "to"]).attrs(&["from", "to"]),
],
from_tree: opgraph_of,
};
pub const ONTOLOGY: &[&Vocabulary] = &[&WORLD, &DEVICE, &DASHBOARD, &GEO, &SHOCK, &SCENARIO, &GEOMODEL, &GEOPARAMS, &GEOLAYER, &GEOFORMULA, &GEOVIEW, &GEOREPORT, &GEOGRAPH, &OPGRAPH];
fn declare(root: El) -> Result<Declared, String> {
if root.tag == "opgraph" {
return Ok(Declared::Graph(opgraph_of(&tree_of_element(&root, &OPGRAPH)?)?));
}
let v = ONTOLOGY.iter().find(|v| v.root == root.tag).expect("a root of this family");
declare_document(&root, v)
}
fn own(o: &[(String, Json)], keys: &[&str]) -> Vec<(String, Json)> {
keys.iter().filter_map(|k| o.iter().find(|(n, _)| n == k).cloned()).collect()
}
fn omit(o: &[(String, Json)], keys: &[&str]) -> Vec<(String, Json)> {
o.iter().filter(|(k, _)| !keys.contains(&k.as_str())).cloned().collect()
}
fn kids<'a>(t: &'a DocTree, tag: &'a str) -> impl Iterator<Item = &'a DocTree> {
t.children.iter().filter(move |c| c.tag == tag)
}
fn text(v: Option<&Json>) -> String {
v.map(Json::text).unwrap_or_else(|| "undefined".into())
}
fn is_record(v: Option<&Json>) -> bool {
matches!(v, Some(Json::Obj(_)))
}
fn call(t: &DocTree, key: &str) -> String {
let f = super::element::fn_name(t.tag);
match t.attr_of(key) {
Some(v @ Json::Str(_)) => format!("{f}().{}({})", rust_name(key), v.text()),
_ => format!("{f}()"),
}
}
fn world_of(t: &DocTree) -> Result<Json, String> {
if t.attr_of("kind").is_some() {
return Err(format!("world().kind: {WORLD_KIND}"));
}
if kids(t, "scene").next().is_some() {
return Err(format!("scene() in a world(): {WORLD_SCENE}"));
}
let mut out = Json::Obj(own(&t.attrs, WORLD_FIELDS));
if let Some(space) = t.single("space") {
out.set("space", space.record());
}
let groups: Vec<Json> = kids(t, "group").map(DocTree::record).collect();
if !groups.is_empty() {
out.set("groups", Json::Arr(groups));
}
out.set("units", Json::Arr(kids(t, "unit").map(DocTree::record).collect()));
if let Some(view) = t.single("view") {
out.set("view", view.record());
}
let interlocks: Vec<Json> = kids(t, "interlock").map(DocTree::record).collect();
if !interlocks.is_empty() {
out.set("interlocks", Json::Arr(interlocks));
}
Ok(out)
}
fn device_of(t: &DocTree) -> Result<Json, String> {
if t.attr_of("channels").is_some() {
return Err("device(): write each channel as a channel() element, not a channels attribute".into());
}
if t.attr_of("interlocks").is_some() {
return Err("device(): write each interlock as an interlock() element, not an interlocks attribute".into());
}
let mut channels: Vec<Json> = kids(t, "channel").map(DocTree::record).collect();
if let Some(c) = channels.iter().find(|c| c.get("bounds").is_some()) {
let id = text(c.get("id"));
return Err(format!("channel().id({id}): write each bound as a bound().channel({id}) element, not a bounds attribute"));
}
for b in kids(t, "bound") {
let Some(c) = channels.iter_mut().find(|c| c.get("id") == b.attr_of("channel")) else {
return Err(format!("bound().field({}): channel {} is not a channel() of this device", text(b.attr_of("field")), text(b.attr_of("channel"))));
};
let bound = Json::Obj(omit(&b.attrs, &["channel"]));
match c.get("bounds") {
Some(Json::Arr(list)) => {
let mut list = list.clone();
list.push(bound);
c.set("bounds", Json::Arr(list));
}
_ => {
c.set("bounds", Json::Arr(vec![bound]));
}
}
}
let interlocks: Vec<Json> = kids(t, "interlock").map(DocTree::record).collect();
let mut out = t.record();
if !channels.is_empty() {
out.set("channels", Json::Arr(channels));
}
if !interlocks.is_empty() {
out.set("interlocks", Json::Arr(interlocks));
}
Ok(out)
}
fn dashboard_of(t: &DocTree) -> Result<Json, String> {
if let Some(k) = DASHBOARD_STRUCTURE.iter().find(|k| t.attr_of(k).is_some()) {
return Err(format!("dashboard(): {k} is written as elements (param(), split(), pane(), region()), not an attribute"));
}
let is_layout = |c: &&DocTree| c.tag == "split" || c.tag == "pane";
let layouts: Vec<&DocTree> = t.children.iter().filter(is_layout).collect();
if layouts.len() != 1 {
return Err(format!("dashboard() has one layout: a split() or one pane() (it has {})", layouts.len()));
}
fn layout(n: &DocTree, panes: &mut Vec<(String, Json)>) -> Result<Json, String> {
if n.tag == "pane" {
let id = js_string(n.attr_of("id"));
if panes.iter().any(|(k, _)| *k == id) {
return Err(format!("two pane() have id {:?}", id));
}
let pane = omit(&n.attrs, &["id"]);
let repeated = pane.iter().find(|(k, _)| k == "repeat").map(|(_, v)| v.clone());
if let Some(what) = repeated {
let files = pane.iter().any(|(k, v)| k == "kind" && *v == Json::Str("files".into()));
let names = pane.iter().any(|(k, _)| k == "selected" || k == "path");
if what != Json::Str("live-stream".into()) || !files || names {
return Err(format!("pane().id({:?}): repeat is \"live-stream\", and a repeating pane shows files and names no file of its own (it is filled from what is live)", id));
}
}
panes.push((id.clone(), Json::Obj(pane)));
return Ok(Json::obj().with("kind", "leaf").with("paneId", id));
}
let sides: Vec<&DocTree> = n.children.iter().filter(|c| c.tag == "split" || c.tag == "pane").collect();
if sides.len() != 2 {
return Err(format!("a split() has two sides (this one has {})", sides.len()));
}
let children = sides.into_iter().map(|c| layout(c, panes)).collect::<Result<Vec<_>, _>>()?;
let attr = |k: &str| n.attr_of(k).cloned().unwrap_or(Json::Null);
Ok(Json::obj().with("kind", "split").with("axis", attr("axis")).with("ratio", attr("ratio")).with("children", children))
}
let mut panes = Vec::new();
let root = layout(layouts[0], &mut panes)?;
let params: Vec<Json> = kids(t, "param").map(DocTree::record).collect();
let mut regions = Json::obj();
for r in kids(t, "region") {
regions.set(&js_string(r.attr_of("side")), Json::Obj(omit(&r.attrs, &["side"])));
}
let mut out = Json::obj().with("format", "commandagi-dashboard");
for (k, v) in &t.attrs {
out.set(k, v.clone());
}
if !params.is_empty() {
out.set("params", Json::Arr(params));
}
out.set("layout", root);
out.set("panes", Json::Obj(panes));
if regions != Json::obj() {
out.set("regions", regions);
}
Ok(out)
}
fn geo_of(t: &DocTree) -> Result<Json, String> {
let mut top = Json::Obj(own(&t.attrs, GEO_FIELDS));
let description = top.remove("description");
let workspace = top.remove("defaultWorkspace");
let mut data = Json::obj();
if let Some(w) = workspace {
data.set("defaultWorkspace", w);
}
if let Some(range) = t.single("dateRange") {
data.set("defaultDateRange", range.record());
}
if let Some(camera) = t.single("camera") {
data.set("defaultCamera", camera.record());
}
if let Some(d) = description {
data.set("description", d);
}
let mut out = Json::obj().with("type", "geoeconomics/project").with("schemaVersion", "1.0");
if let Json::Obj(fields) = top {
for (k, v) in fields {
out.set(&k, v);
}
}
let refs: Vec<Json> = kids(t, "reference").map(DocTree::record).collect();
if !refs.is_empty() {
out.set("references", Json::Arr(refs));
}
Ok(out.with("data", data))
}
fn geo_file_of(t: &DocTree, type_: &str, fields: &[&str], record: Option<(&str, &str, &str)>) -> Result<Json, String> {
let mut out = Json::obj().with("type", type_).with("schemaVersion", "1.0");
for (k, v) in own(&t.attrs, GEO_OWN) {
out.set(&k, v);
}
let refs: Vec<Json> = kids(t, "reference").map(DocTree::record).collect();
if !refs.is_empty() {
out.set("references", Json::Arr(refs));
}
let mut data = Json::Obj(own(&t.attrs, fields));
if let Some((tag, field, key)) = record {
let mut entries = Json::obj();
let mut any = false;
for e in kids(t, tag) {
let mut r = e.record();
if let Some(Json::Str(k)) = r.remove(key) {
entries.set(&k, r);
any = true;
}
}
if any {
data.set(field, entries);
}
}
Ok(out.with("data", data))
}
fn shock_of(t: &DocTree) -> Result<Json, String> {
geo_file_of(t, "geoeconomics/event", SHOCK_DATA, None)
}
fn scenario_of(t: &DocTree) -> Result<Json, String> {
geo_file_of(t, "geoeconomics/scenario", SCENARIO_DATA, None)
}
fn geomodel_of(t: &DocTree) -> Result<Json, String> {
geo_file_of(t, "geoeconomics/model", GEOMODEL_DATA, Some(("parameter", "parameterSchema", "name")))
}
fn geoparams_of(t: &DocTree) -> Result<Json, String> {
geo_file_of(t, "geoeconomics/params", GEOPARAMS_DATA, None)
}
pub fn port_is_attribute(port: &str) -> bool {
let mut chars = port.chars();
let first = chars.next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$');
first && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '$' | '-')) && !NODE_ATTRS.contains(&port) && port != "key" && port != "children"
}
fn is_wire(v: Option<&Json>) -> bool {
match v.and_then(|v| v.get("wire")) {
Some(w @ Json::Obj(_)) => matches!(w.get("node"), Some(Json::Str(_))) && matches!(w.get("port"), Some(Json::Str(_))),
_ => false,
}
}
fn end_of(text: Option<&Json>, what: &str) -> Result<(String, String), String> {
let split = match text {
Some(Json::Str(s)) => s.split_once(':').filter(|(n, p)| !n.is_empty() && !p.is_empty() && !p.contains(['\n', '\r', '\u{2028}', '\u{2029}'])),
_ => None,
};
match split {
Some((node, port)) => Ok((node.to_string(), port.to_string())),
None => Err(format!("wire(): {what} is \"node:port\", not {}", self::text(text))),
}
}
fn opgraph_of(t: &DocTree) -> Result<Json, String> {
let mut nodes: Vec<(String, Json)> = Vec::new();
let mut outputs: Vec<Json> = Vec::new();
for n in kids(t, "node") {
let id = js_string(n.attr_of("id"));
let at = call(n, "id");
if !matches!(n.attr_of("type"), Some(Json::Str(s)) if !s.is_empty()) {
return Err(format!("{at} needs a type_"));
}
if id.contains(':') {
return Err(format!("{at}: an id has no colon (a wire names \"node:port\")"));
}
let mut inputs = Json::Obj(n.attrs.iter().filter(|(k, _)| !NODE_ATTRS.contains(&k.as_str())).cloned().collect());
if let Some(given) = n.attr_of("inputs") {
let Json::Obj(ports) = given else { return Err(format!("{at} inputs is an object of ports")) };
for (k, v) in ports {
if port_is_attribute(k) {
return Err(format!("{at}: write {k} as a method (.{}(…)), not in inputs", rust_name(k)));
}
inputs.set(k, v.clone());
}
}
let mut meta = match n.attr_of("meta") {
None => Json::obj(),
Some(m @ Json::Obj(_)) => m.clone(),
Some(_) => return Err(format!("{at} meta is an object")),
};
for k in ["x", "y"] {
if let Some(v) = n.attr_of(k) {
meta.set(k, v.clone());
}
}
if let Some(s) = &n.source {
meta.set("source", s.clone());
}
let mut node = Json::obj().with("id", id.as_str()).with("type", n.attr_of("type").cloned().unwrap_or(Json::Null));
if let Some(label @ Json::Str(_)) = n.attr_of("label") {
node.set("label", label.clone());
}
node.set("inputs", inputs);
if n.attr_of("disabled") == Some(&Json::Bool(true)) {
node.set("disabled", true);
}
if meta != Json::obj() {
node.set("meta", meta);
}
if n.attr_of("output") == Some(&Json::Bool(true)) {
outputs.push(Json::from(id.as_str()));
}
nodes.push((id, node));
}
for w in kids(t, "wire") {
let (from_node, from_port) = end_of(w.attr_of("from"), "from")?;
let (to_node, to_port) = end_of(w.attr_of("to"), "to")?;
if !nodes.iter().any(|(k, _)| *k == to_node) {
return Err(format!("wire().to({}): no node().id({})", text(w.attr_of("to")), Json::from(to_node).text()));
}
if !nodes.iter().any(|(k, _)| *k == from_node) {
return Err(format!("wire().from({}): no node().id({})", text(w.attr_of("from")), Json::from(from_node).text()));
}
let target = &mut nodes.iter_mut().find(|(k, _)| *k == to_node).expect("checked").1;
let literal = target.get("inputs").and_then(|i| i.get(&to_port)).cloned();
if is_wire(literal.as_ref()) {
return Err(format!("two wire() go into {to_node}:{to_port} (a port takes one wire)"));
}
let mut bound = Json::obj().with("wire", Json::obj().with("node", from_node).with("port", from_port));
if let Some(v) = literal.filter(|v| *v != Json::Null) {
bound.set("value", v);
}
if let Json::Obj(fields) = target {
if let Some((_, inputs)) = fields.iter_mut().find(|(k, _)| k == "inputs") {
inputs.set(&to_port, bound);
}
}
if let Some(s) = &w.source {
let mut meta = target.get("meta").cloned().unwrap_or_else(Json::obj);
let mut sources = match meta.get("sources") {
Some(o @ Json::Obj(_)) => o.clone(),
_ => Json::obj(),
};
sources.set(&format!("wire:{to_port}"), s.clone());
meta.set("sources", sources);
target.set("meta", meta);
}
}
let mut meta = if is_record(t.attr_of("meta")) { t.attr_of("meta").cloned().unwrap_or_else(Json::obj) } else { Json::obj() };
if let Some(name) = t.attr_of("name") {
meta.set("name", name.clone());
}
meta.set("domain", t.attr_of("domain").filter(|d| **d != Json::Null).cloned().unwrap_or_else(|| NODE_GRAPH_ID.into()));
let id = match t.attr_of("id") {
Some(Json::Str(s)) => s.clone(),
_ => NODE_GRAPH_ID.to_string(),
};
Ok(Json::obj().with("id", id).with("nodes", Json::Obj(nodes)).with("outputs", outputs).with("meta", meta))
}