Skip to main content

xmachines_build/
lib.rs

1#![doc = include_str!("../README.md")]
2
3mod names;
4mod types;
5
6use std::collections::HashSet;
7use std::fmt;
8use std::path::{Path, PathBuf};
9
10use serde_json::{Map, Value};
11use xmachines_runtime::{Machine, Reference};
12
13use names::{pascal, raw_lit, snake_after, snake_word, string_lit};
14use types::{validate, variant_text, Root, Types, VALUE};
15
16/// A problem with a bundle, at a JSON path (`$...` for the definition,
17/// `schemas...` for the schemas).
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Error {
20    pub file: Option<PathBuf>,
21    pub path: String,
22    pub message: String,
23}
24
25impl Error {
26    pub(crate) fn new(path: &str, message: impl Into<String>) -> Self {
27        Self { file: None, path: path.to_owned(), message: message.into() }
28    }
29}
30
31impl fmt::Display for Error {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        if let Some(file) = &self.file {
34            write!(f, "{}: ", file.display())?;
35        }
36        write!(f, "{}: {}", self.path, self.message)
37    }
38}
39
40impl std::error::Error for Error {}
41
42/// The generated module and any warnings (unused schema entries).
43#[derive(Debug, Clone)]
44pub struct Generated {
45    pub code: String,
46    pub warnings: Vec<String>,
47}
48
49const SCHEMA_KEYS: &[&str] = &[
50    "context",
51    "input",
52    "output",
53    "events",
54    "internalEvents",
55    "emitted",
56    "rejections",
57    "actions",
58    "guards",
59    "children",
60    "actors",
61];
62
63fn obj(v: Option<&Value>) -> Option<&Map<String, Value>> {
64    v.and_then(Value::as_object)
65}
66
67/// Every transition of a state, with its path: `on`, `always`, `after`,
68/// `onDone`, `onTimeout` and invoke completion transitions.
69fn transitions<'a>(state: &'a Map<String, Value>, path: &str) -> Vec<(String, &'a Value)> {
70    let mut out = Vec::new();
71    let mut add = |p: String, v: &'a Value| match v {
72        Value::Array(items) => {
73            for (i, t) in items.iter().enumerate() {
74                out.push((format!("{p}[{i}]"), t));
75            }
76        }
77        t => out.push((p, t)),
78    };
79    for key in ["on", "after"] {
80        for (k, v) in obj(state.get(key)).into_iter().flatten() {
81            add(format!("{path}.{key}.{k}"), v);
82        }
83    }
84    for key in ["always", "onDone", "onTimeout"] {
85        if let Some(v) = state.get(key) {
86            add(format!("{path}.{key}"), v);
87        }
88    }
89    let invokes: Vec<(String, &Value)> = match state.get("invoke") {
90        Some(Value::Array(items)) => {
91            items.iter().enumerate().map(|(i, v)| (format!("{path}.invoke[{i}]"), v)).collect()
92        }
93        Some(v) => vec![(format!("{path}.invoke"), v)],
94        None => vec![],
95    };
96    for (ipath, invoke) in invokes {
97        for key in ["onDone", "onError", "onSnapshot", "onTimeout"] {
98            if let Some(v) = invoke.get(key) {
99                add(format!("{ipath}.{key}"), v);
100            }
101        }
102    }
103    out
104}
105
106/// Calls `f` for every state node, depth first.
107fn each_state<'a>(state: &'a Map<String, Value>, path: &str, f: &mut dyn FnMut(&'a Map<String, Value>, &str)) {
108    f(state, path);
109    for (k, child) in obj(state.get("states")).into_iter().flatten() {
110        if let Some(child) = child.as_object() {
111            each_state(child, &format!("{path}.states.{k}"), f);
112        }
113    }
114}
115
116/// Every action object with a built-in `type` in the definition.
117fn builtin_actions<'a>(value: &'a Value, path: &str, out: &mut Vec<(String, &'a Map<String, Value>)>) {
118    match value {
119        Value::Array(items) => {
120            for (i, v) in items.iter().enumerate() {
121                builtin_actions(v, &format!("{path}[{i}]"), out);
122            }
123        }
124        Value::Object(o) => {
125            if o.get("type").and_then(Value::as_str).is_some_and(|t| t.starts_with("@xstate."))
126                && o.contains_key("event")
127                || o.get("type").and_then(Value::as_str) == Some("@xstate.assign")
128            {
129                out.push((path.to_owned(), o));
130            }
131            for (k, v) in o {
132                if !matches!(k.as_str(), "meta" | "context" | "output" | "description" | "params" | "event") {
133                    builtin_actions(v, &format!("{path}.{k}"), out);
134                }
135            }
136        }
137        _ => {}
138    }
139}
140
141/// Whether a value is an expression (`{"@code": ...}` or `{"@expr": ...}`).
142fn is_code(value: &Value) -> bool {
143    value.as_object().is_some_and(|o| o.contains_key("@code") || o.contains_key("@expr"))
144}
145
146/// Whether a value is or holds an expression.
147fn has_code(value: &Value) -> bool {
148    match value {
149        Value::Object(o) => is_code(value) || o.values().any(has_code),
150        Value::Array(items) => items.iter().any(has_code),
151        _ => false,
152    }
153}
154
155/// Checks the static part of a value: all of it without expressions,
156/// nothing of an expression, else each property of an object on its own
157/// (computed ones are known only at run time, so `required` is not checked).
158fn check_static(value: &Value, schema: &Value, root: &Value, path: &str) -> Result<(), Error> {
159    if !has_code(value) {
160        return validate(value, schema, root, path).map_err(|m| match m.split_once(": ") {
161            Some((p, m)) => Error::new(p, m),
162            None => Error::new(path, m),
163        });
164    }
165    if is_code(value) {
166        return Ok(());
167    }
168    check_properties(value, schema, root, path)
169}
170
171/// Checks each property of an object against its schema, if it has one.
172fn check_properties(value: &Value, schema: &Value, root: &Value, path: &str) -> Result<(), Error> {
173    let (Some(object), Some(props)) = (value.as_object(), schema.get("properties").and_then(Value::as_object)) else {
174        return Ok(());
175    };
176    if is_code(value) {
177        return Ok(());
178    }
179    for (k, v) in object {
180        match props.get(k) {
181            Some(s) => check_static(v, s, root, &format!("{path}.{k}"))?,
182            None if schema.get("additionalProperties") == Some(&Value::Bool(false)) => {
183                return Err(Error::new(&format!("{path}.{k}"), format!("unknown property `{k}`")))
184            }
185            None => {}
186        }
187    }
188    Ok(())
189}
190
191struct Checker<'a> {
192    schemas: &'a Map<String, Value>,
193    declared_events: Option<HashSet<&'a str>>,
194}
195
196impl Checker<'_> {
197    fn check(value: &Value, schema: &Value, path: &str) -> Result<(), Error> {
198        validate(value, schema, schema, path).map_err(|m| match m.split_once(": ") {
199            Some((p, m)) => Error::new(p, m),
200            None => Error::new(path, m),
201        })
202    }
203
204    fn event_schema(&self, ty: &str) -> Option<&Value> {
205        ["events", "internalEvents"].iter().find_map(|k| self.schemas.get(*k)?.get(ty))
206    }
207
208    /// Checks a rejecting branch's reasons against `schemas.rejections`, as
209    /// XState checks a rejection against its rejection schemas: when there
210    /// are any, a reason's `type` must be one of them and its static payload
211    /// must fit. A computed reason or type is known only at run time.
212    fn rejections(&self, reasons: &[Value], path: &str) -> Result<(), Error> {
213        let Some(schemas) = obj(self.schemas.get("rejections")) else { return Ok(()) };
214        for (i, reason) in reasons.iter().enumerate() {
215            let rpath = format!("{path}[{i}]");
216            let Some(reason) = reason.as_object() else { continue };
217            let Some(ty) = reason.get("type").and_then(Value::as_str) else { continue };
218            let schema = schemas
219                .get(ty)
220                .ok_or_else(|| Error::new(&rpath, format!("rejection `{ty}` is not declared in schemas.rejections")))?;
221            if has_code(&Value::Object(reason.clone())) {
222                check_properties(&Value::Object(reason.clone()), schema, schema, &rpath)?;
223            } else {
224                Self::payload(reason, schema, &rpath)?;
225            }
226        }
227        Ok(())
228    }
229
230    /// Checks an event object's payload (everything but `type`).
231    fn payload(event: &Map<String, Value>, schema: &Value, path: &str) -> Result<(), Error> {
232        let mut payload = event.clone();
233        payload.remove("type");
234        let mut schema = schema.clone();
235        if let Some(props) = schema.get_mut("properties").and_then(Value::as_object_mut) {
236            props.remove("type");
237        }
238        if let Some(req) = schema.get_mut("required").and_then(Value::as_array_mut) {
239            req.retain(|r| r != "type");
240        }
241        Self::check(&Value::Object(payload), &schema, path)
242    }
243
244    fn references(&self, kind: &str, refs: &[Reference], warnings: &mut Vec<String>) -> Result<(), Error> {
245        let empty = Map::new();
246        let declared = obj(self.schemas.get(kind)).unwrap_or(&empty);
247        for r in refs {
248            let def = declared.get(&r.name).ok_or_else(|| {
249                Error::new(&r.path, format!("`{}` has no entry in schemas.{kind}; declare its params there", r.name))
250            })?;
251            let params = r.params.clone().unwrap_or(Value::Null);
252            match def.get("params") {
253                Some(schema) => check_static(&params, schema, schema, &format!("{}.params", r.path))?,
254                None if !params.is_null() => {
255                    return Err(Error::new(
256                        &format!("{}.params", r.path),
257                        format!("`{}` takes no params (schemas.{kind}.{} declares none)", r.name, r.name),
258                    ))
259                }
260                None => {}
261            }
262        }
263        for name in declared.keys() {
264            if !refs.iter().any(|r| r.name == *name) {
265                warnings.push(format!("schemas.{kind}.{name} is declared but never referenced"));
266            }
267        }
268        Ok(())
269    }
270
271    fn definition(&self, machine: &Map<String, Value>) -> Result<(), Error> {
272        let context_schema = self.schemas.get("context");
273        let initial = machine.get("context").cloned();
274        // A computed initial context: patches are checked property by property.
275        let initial_computed = initial.as_ref().is_some_and(has_code);
276        match (&initial, context_schema) {
277            (Some(ctx), Some(schema)) => check_static(ctx, schema, schema, "$.context")?,
278            (Some(_), None) => {
279                return Err(Error::new("schemas.context", "the machine has context but no context schema"))
280            }
281            _ => {}
282        }
283        let patch = |path: &str, patch: &Value, initial: &Option<Value>| -> Result<(), Error> {
284            let (Some(schema), Some(patch_object)) = (context_schema, patch.as_object()) else { return Ok(()) };
285            if initial_computed || has_code(patch) {
286                return check_properties(patch, schema, schema, path);
287            }
288            let patch = patch_object;
289            let mut merged = initial.clone().and_then(|v| v.as_object().cloned()).unwrap_or_default();
290            for (k, v) in patch {
291                merged.insert(k.clone(), v.clone());
292            }
293            Self::check(&Value::Object(merged), schema, path)
294        };
295
296        let mut result = Ok(());
297        each_state(machine, "$", &mut |state, path| {
298            if result.is_err() {
299                return;
300            }
301            result = (|| {
302                if let Some(declared) = &self.declared_events {
303                    for key in obj(state.get("on")).into_iter().flatten().map(|(k, _)| k) {
304                        if !key.contains('*') && !key.starts_with("xstate.") && !declared.contains(key.as_str()) {
305                            return Err(Error::new(
306                                &format!("{path}.on.{key}"),
307                                format!("event `{key}` is not declared in schemas.events or schemas.internalEvents"),
308                            ));
309                        }
310                    }
311                }
312                for (tpath, t) in transitions(state, path) {
313                    if let Some(ctx) = t.get("context") {
314                        patch(&format!("{tpath}.context"), ctx, &initial)?;
315                    }
316                    if let Some(reasons) = t.get("reject").and_then(Value::as_array) {
317                        self.rejections(reasons, &format!("{tpath}.reject"))?;
318                    }
319                }
320                Ok(())
321            })();
322        });
323        result?;
324
325        let mut actions = Vec::new();
326        let whole = Value::Object(machine.clone());
327        builtin_actions(&whole, "$", &mut actions);
328        for (path, action) in actions {
329            let ty = action.get("type").and_then(Value::as_str).unwrap_or_default();
330            if ty == "@xstate.assign" {
331                if let Some(ctx) = action.get("context") {
332                    patch(&format!("{path}.context"), ctx, &initial)?;
333                }
334                continue;
335            }
336            let Some(event) = action.get("event").and_then(Value::as_object) else { continue };
337            // A computed event or event type is known only at run time.
338            let Some(event_type) = event.get("type").and_then(Value::as_str) else { continue };
339            let epath = format!("{path}.event");
340            let payload = |event: &Map<String, Value>, schema: &Value| {
341                if has_code(&Value::Object(event.clone())) {
342                    check_properties(&Value::Object(event.clone()), schema, schema, &epath)
343                } else {
344                    Self::payload(event, schema, &epath)
345                }
346            };
347            match ty {
348                "@xstate.raise" if !event_type.starts_with("xstate.") => {
349                    if let Some(declared) = &self.declared_events {
350                        if !declared.contains(event_type) {
351                            return Err(Error::new(&epath, format!("raised event `{event_type}` is not declared in schemas.events or schemas.internalEvents")));
352                        }
353                        payload(event, self.event_schema(event_type).unwrap())?;
354                    }
355                }
356                "@xstate.emit" => {
357                    let schema = self.schemas.get("emitted").and_then(|e| e.get(event_type)).ok_or_else(|| {
358                        Error::new(&epath, format!("emitted event `{event_type}` is not declared in schemas.emitted"))
359                    })?;
360                    payload(event, schema)?;
361                }
362                _ => {}
363            }
364        }
365
366        if let Some(schema) = self.schemas.get("output") {
367            if let Some(output) = machine.get("output") {
368                check_static(output, schema, schema, "$.output")?;
369            } else {
370                for (k, child) in obj(machine.get("states")).into_iter().flatten() {
371                    if child.get("type").and_then(Value::as_str) == Some("final") {
372                        if let Some(output) = child.get("output") {
373                            check_static(output, schema, schema, &format!("$.states.{k}.output"))?;
374                        }
375                    }
376                }
377            }
378        }
379        Ok(())
380    }
381}
382
383/// The `id`s of every invoke in the definition, with their paths.
384fn invoke_ids(machine: &Map<String, Value>) -> Vec<(String, String)> {
385    let mut ids = Vec::new();
386    each_state(machine, "$", &mut |state, path| {
387        let invokes: Vec<(String, &Value)> = match state.get("invoke") {
388            Some(Value::Array(items)) => {
389                items.iter().enumerate().map(|(i, v)| (format!("{path}.invoke[{i}]"), v)).collect()
390            }
391            Some(v) => vec![(format!("{path}.invoke"), v)],
392            None => vec![],
393        };
394        for (ipath, invoke) in invokes {
395            if let Some(id) = invoke.get("id").and_then(Value::as_str) {
396                ids.push((id.to_owned(), ipath));
397            }
398        }
399    });
400    ids
401}
402
403/// Types, a handle and an output reader for each declared child.
404fn children(types: &mut Types, machine: &Map<String, Value>, schemas: &Map<String, Value>) -> Result<String, Error> {
405    let Some(declared) = schemas.get("children") else { return Ok(String::new()) };
406    let declared = declared.as_object().ok_or_else(|| Error::new("schemas.children", "expected an object"))?;
407    let ids = invoke_ids(machine);
408    let mut code = String::new();
409    for (id, def) in declared {
410        let path = format!("schemas.children.{id}");
411        let def = def.as_object().ok_or_else(|| Error::new(&path, "expected `{ events?, output? }`"))?;
412        if let Some(k) = def.keys().find(|k| !matches!(k.as_str(), "events" | "output")) {
413            return Err(Error::new(&format!("{path}.{k}"), "unknown key (expected `events` or `output`)"));
414        }
415        let Some((_, invoke_path)) = ids.iter().find(|(i, _)| i == id) else {
416            return Err(Error::new(&path, format!("no invoke in the machine has `id: \"{id}\"`")));
417        };
418        let p = pascal(id);
419        let (handle, event, output) = (format!("{p}Child"), format!("{p}ChildEvent"), format!("{p}ChildOutput"));
420        types.claim(&handle, &path)?;
421        match def.get("events") {
422            Some(Value::Object(events)) => {
423                event_enum(types, &event, &event, &[(&format!("children.{id}.events"), events)])?
424            }
425            Some(_) => return Err(Error::new(&format!("{path}.events"), "expected an object of event schemas")),
426            None => {
427                types.claim(&event, &path)?;
428                types.out.push(format!("pub type {event} = {VALUE};\n"));
429            }
430        }
431        match def.get("output") {
432            Some(schema) => types.named(schema, &output, &format!("{path}.output"))?,
433            None => {
434                types.claim(&output, &path)?;
435                types.out.push(format!("pub type {output} = {VALUE};\n"));
436            }
437        }
438        let snake_id = snake_word(id);
439        let lit = string_lit(id);
440        code.push_str(&format!(
441            r#"/// The running child invoked with `id: {lit}` (at `{invoke_path}`).
442pub struct {handle}<'a> {{
443    actor: &'a mut Actor,
444    address: String,
445}}
446
447impl {handle}<'_> {{
448    /// The invoke `id`.
449    pub const ID: &'static str = {lit};
450
451    /// The child's address in the actor's system.
452    pub fn address(&self) -> &str {{
453        &self.address
454    }}
455
456    /// The child's status.
457    pub fn status(&self) -> __rt::Status {{
458        self.actor.system().snapshot(&self.address).map_or(__rt::Status::Stopped, |s| s.status())
459    }}
460
461    /// Sends an event to the child at `now_ms` (see `Actor::send_to`).
462    pub fn send(&mut self, event: {event}, now_ms: u64) -> Result<(), __rt::SystemError> {{
463        let event = __rt::EventType::to_json(&event);
464        self.actor.send_to(&self.address, event, now_ms)
465    }}
466}}
467
468/// The child invoked with `id: {lit}`, while the machine's active states invoke it.
469pub fn child_{snake_id}(actor: &mut Actor) -> Option<{handle}<'_>> {{
470    let address = actor.children().into_iter().find(|(id, _)| *id == {lit})?.1.to_owned();
471    Some({handle} {{ actor, address }})
472}}
473
474/// The output of the child invoked with `id: {lit}`, when `event` is its
475/// `xstate.done.actor` event (`None` for other events, or an output that
476/// does not fit `{output}`).
477pub fn child_{snake_id}_output(event: &__rt::Ev<Event>) -> Option<{output}> {{
478    if event.event_type() != "xstate.done.actor" || event.field("actorId")?.as_str() != Some({lit}) {{
479        return None;
480    }}
481    __rt::serde_json::from_value(event.field("output").unwrap_or(__rt::serde_json::Value::Null)).ok()
482}}
483
484"#
485        ));
486    }
487    Ok(code)
488}
489
490/// Distinct names in reference order.
491fn distinct(refs: &[Reference]) -> Vec<&Reference> {
492    let mut seen = HashSet::new();
493    refs.iter().filter(|r| seen.insert(r.name.as_str())).collect()
494}
495
496/// An event enum (`Event`, `Emitted` or `Rejection`) from `type -> schema` maps.
497fn event_enum(
498    types: &mut Types,
499    name: &str,
500    nested_prefix: &str,
501    maps: &[(&str, &Map<String, Value>)],
502) -> Result<(), Error> {
503    types.claim(name, &format!("schemas.{}", maps[0].0))?;
504    let mut item = format!(
505        "{}\n#[serde(crate = \"__rt::serde\", tag = \"type\")]\npub enum {name} {{\n",
506        "#[derive(Debug, Clone, PartialEq, __rt::serde::Serialize, __rt::serde::Deserialize)]"
507    );
508    let mut arms = String::new();
509    let mut seen = HashSet::new();
510    for (key, map) in maps {
511        for (ty, schema) in *map {
512            let path = format!("schemas.{key}.{ty}");
513            let variant = pascal(ty);
514            if !seen.insert(variant.clone()) {
515                return Err(Error::new(&path, format!("event types map to the same variant `{variant}`")));
516            }
517            let hint = format!("{nested_prefix}{variant}");
518            let root = Root { schema, name: &hint };
519            let resolved = match schema.get("$ref").and_then(Value::as_str) {
520                Some(r) => r.strip_prefix("#/$defs/").and_then(|n| schema.get("$defs")?.get(n)).unwrap_or(schema),
521                None => schema,
522            };
523            let o = resolved
524                .as_object()
525                .filter(|o| o.get("type").and_then(Value::as_str) == Some("object"))
526                .ok_or_else(|| Error::new(&path, "an event schema must be an object (z.object)"))?;
527            let fields = types.fields(o, &hint, &path, root, &["type"], "")?;
528            item.push_str(&variant_text(&variant, ty, &fields, o));
529            arms.push_str(&format!("            Self::{variant} {{ .. }} => {},\n", string_lit(ty)));
530        }
531    }
532    item.push_str("}\n\n");
533    item.push_str(&format!(
534        "impl __rt::EventType for {name} {{\n    fn event_type(&self) -> &str {{\n        match self {{\n{arms}        }}\n    }}\n}}\n"
535    ));
536    types.out.push(item);
537    Ok(())
538}
539
540/// The bundle's `hostActions`: the custom actions the host does, each one the
541/// definition references. None of a bundle that names none.
542fn host_actions(bundle: &Value, refs: &xmachines_runtime::References) -> Result<Vec<String>, Error> {
543    let Some(names) = bundle.get("hostActions") else { return Ok(Vec::new()) };
544    let names = names.as_array().ok_or_else(|| Error::new("hostActions", "expected an array of action names"))?;
545    let mut out = Vec::new();
546    for (i, name) in names.iter().enumerate() {
547        let path = format!("hostActions[{i}]");
548        let name = name.as_str().ok_or_else(|| Error::new(&path, "expected an action name"))?;
549        if !refs.actions.iter().any(|r| r.name == name) {
550            return Err(Error::new(&path, format!("the definition references no custom action `{name}`")));
551        }
552        if out.iter().any(|n| n == name) {
553            return Err(Error::new(&path, format!("`{name}` is named twice")));
554        }
555        out.push(name.to_owned());
556    }
557    Ok(out)
558}
559
560/// The bundle's `schemas.actors`: by `src`, what the invoked logic takes,
561/// gives and fails with, `{ input?, output?, error? }`, each `src` one the
562/// definition invokes.
563fn actors<'a>(
564    schemas: &'a Map<String, Value>,
565    refs: &xmachines_runtime::References,
566) -> Result<Option<&'a Map<String, Value>>, Error> {
567    let Some(actors) = schemas.get("actors") else { return Ok(None) };
568    let actors = actors.as_object().ok_or_else(|| Error::new("schemas.actors", "expected an object by `src`"))?;
569    for (src, def) in actors {
570        let path = format!("schemas.actors.{src}");
571        let def = def.as_object().ok_or_else(|| Error::new(&path, "expected `{ input?, output?, error? }`"))?;
572        if let Some(k) = def.keys().find(|k| !matches!(k.as_str(), "input" | "output" | "error")) {
573            return Err(Error::new(&format!("{path}.{k}"), "unknown key (expected `input`, `output` or `error`)"));
574        }
575        if !refs.actors.iter().any(|r| r.name == *src) {
576            return Err(Error::new(&path, format!("no invoke in the machine has `src: \"{src}\"`")));
577        }
578    }
579    Ok(Some(actors))
580}
581
582/// The types of the work of the record protocol (`xmachines-workflow`), of
583/// `schemas.actors` and `hostActions`: `Invoke`, by `src`, with the types of
584/// each one's input, output and error; `HostAction`, by `type`, with its
585/// params; and the protocol's types of this machine, `Work`,
586/// `WorkflowInput`, `Snapshot` and `Record`. A child the machine runs itself
587/// is a variant of `Invoke` too: nothing in the bundle tells it apart from
588/// the host's work, and a run never asks the host for it.
589fn workflow_types(
590    types: &mut Types,
591    schemas: &Map<String, Value>,
592    actors: Option<&Map<String, Value>>,
593    sources: &[&Reference],
594    host_actions: &[String],
595) -> Result<(), Error> {
596    let derive = "#[derive(Debug, Clone, PartialEq, __rt::serde::Serialize, __rt::serde::Deserialize)]";
597    // An optional value keeps `null` apart from none, as the record protocol's own types do.
598    let optional = "#[serde(default, skip_serializing_if = \"Option::is_none\", deserialize_with = \"::xmachines_workflow::present\")]";
599    let empty = Map::new();
600    let mut invoke = format!("/// Invoked work, by `src`: what the host does.\n{derive}\n#[serde(crate = \"__rt::serde\", tag = \"src\")]\npub enum Invoke {{\n");
601    let mut invoke_ids = String::new();
602    types.claim("Invoke", "schemas.actors")?;
603    // One variant for each `src` the definition invokes: one of no schema takes and gives JSON, as
604    // a child the trait's implementation runs may be invoked work of the host's all the same.
605    for src in sources.iter().map(|r| r.name.as_str()) {
606        let def = actors.unwrap_or(&empty).get(src).and_then(Value::as_object).unwrap_or(&empty);
607        let path = format!("schemas.actors.{src}");
608        let p = pascal(src);
609        let mut input = VALUE.to_owned();
610        for (key, suffix) in [("input", "Input"), ("output", "Output"), ("error", "Error")] {
611            let name = format!("{p}{suffix}");
612            match def.get(key) {
613                Some(schema) => types.named(schema, &name, &format!("{path}.{key}"))?,
614                None => {
615                    types.claim(&name, &path)?;
616                    types.out.push(format!("pub type {name} = {VALUE};\n"));
617                }
618            }
619            if key == "input" {
620                input = name;
621            }
622        }
623        invoke.push_str(&format!(
624            "    /// The invoked logic `{src}`.\n    #[serde(rename = {lit})]\n    {p} {{\n        id: String,\n        actor: String,\n        {optional}\n        input: Option<{input}>,\n    }},\n",
625            lit = string_lit(src)
626        ));
627        invoke_ids.push_str(&format!("            Self::{p} {{ id, .. }} => id,\n"));
628    }
629    invoke.push_str("}\n\n");
630    let body = if invoke_ids.is_empty() {
631        "        match *self {}\n".to_owned()
632    } else {
633        format!("        match self {{\n{invoke_ids}        }}\n")
634    };
635    invoke.push_str(&format!(
636        "impl ::xmachines_workflow::WorkId for Invoke {{\n    fn id(&self) -> &str {{\n{body}    }}\n}}\n"
637    ));
638    types.out.push(invoke);
639
640    let mut action = format!("/// A host action, by `type`: what the host does, then settles `done`.\n{derive}\n#[serde(crate = \"__rt::serde\", tag = \"type\")]\npub enum HostAction {{\n");
641    let mut action_ids = String::new();
642    types.claim("HostAction", "hostActions")?;
643    for name in host_actions {
644        let p = pascal(name);
645        let params = match schemas.get("actions").and_then(|a| a.get(name)).and_then(|d| d.get("params")) {
646            Some(schema) => {
647                let params = format!("{p}Params");
648                types.named(schema, &params, &format!("schemas.actions.{name}.params"))?;
649                params
650            }
651            None => VALUE.to_owned(),
652        };
653        action.push_str(&format!(
654            "    /// The host action `{name}`.\n    #[serde(rename = {lit})]\n    {p} {{\n        id: String,\n        actor: String,\n        {optional}\n        params: Option<{params}>,\n    }},\n",
655            lit = string_lit(name)
656        ));
657        action_ids.push_str(&format!("            Self::{p} {{ id, .. }} => id,\n"));
658    }
659    action.push_str("}\n\n");
660    let body = if action_ids.is_empty() {
661        "        match *self {}\n".to_owned()
662    } else {
663        format!("        match self {{\n{action_ids}        }}\n")
664    };
665    action.push_str(&format!(
666        "impl ::xmachines_workflow::WorkId for HostAction {{\n    fn id(&self) -> &str {{\n{body}    }}\n}}\n"
667    ));
668    types.out.push(action);
669
670    for name in ["Work", "WorkflowInput", "Snapshot", "Record"] {
671        types.claim(name, "schemas")?;
672    }
673    let output = if schemas.contains_key("output") { "Output" } else { VALUE };
674    let emitted = if schemas.contains_key("emitted") { "Emitted" } else { VALUE };
675    types.out.push(format!(
676        "/// The work a run of the machine waits for (the record protocol's).\npub type Work = ::xmachines_workflow::Work<Invoke, HostAction>;\n\n/// An input of a run of the machine: an event of it, or a control input.\npub type WorkflowInput = ::xmachines_workflow::Input<Event>;\n\n/// A snapshot of a run of the machine.\npub type Snapshot = ::xmachines_workflow::Snapshot<Context, {VALUE}, Work, {output}>;\n\n/// A record of a run of the machine.\npub type Record = ::xmachines_workflow::Record<{emitted}, Snapshot, WorkflowInput>;\n"
677    ));
678    Ok(())
679}
680
681/// Generates the module for a bundle. `module` names it in comments and is
682/// the trait's name when the machine has no `id`.
683pub fn generate(bundle: &Value, module: &str) -> Result<Generated, Error> {
684    if let Some(key) =
685        obj(Some(bundle)).and_then(|b| b.keys().find(|k| !matches!(k.as_str(), "machine" | "schemas" | "hostActions")))
686    {
687        return Err(Error::new(key, "unknown bundle key (a bundle has `machine`, `schemas` and `hostActions`)"));
688    }
689    let machine =
690        obj(bundle.get("machine")).ok_or_else(|| Error::new("machine", "the bundle has no `machine` object"))?;
691    let empty = Map::new();
692    let schemas = match bundle.get("schemas") {
693        None => &empty,
694        Some(Value::Object(s)) => s,
695        Some(_) => return Err(Error::new("schemas", "expected an object")),
696    };
697    for k in schemas.keys() {
698        if !SCHEMA_KEYS.contains(&k.as_str()) {
699            return Err(Error::new(&format!("schemas.{k}"), "unknown schema key"));
700        }
701    }
702    let machine_value = Value::Object(machine.clone());
703    let refs = Machine::<Value, Value>::references(&machine_value).map_err(|e| Error::new(&e.path, e.message))?;
704
705    let host_actions = host_actions(bundle, &refs)?;
706    let actors = actors(schemas, &refs)?;
707
708    let events = obj(schemas.get("events"));
709    let internal = obj(schemas.get("internalEvents"));
710    let declared_events = (events.is_some() || internal.is_some())
711        .then(|| events.into_iter().chain(internal).flat_map(|m| m.keys().map(String::as_str)).collect::<HashSet<_>>());
712    let checker = Checker { schemas, declared_events };
713    let mut warnings = Vec::new();
714    checker.references("guards", &refs.guards, &mut warnings)?;
715    checker.references("actions", &refs.actions, &mut warnings)?;
716    checker.definition(machine)?;
717
718    let id = machine.get("id").and_then(Value::as_str).unwrap_or("");
719    let trait_name = format!("{}Impl", pascal(if id.is_empty() { module } else { id }));
720    let mut types = Types::default();
721    for name in ["Actor", "ID", "DEFINITION", trait_name.as_str()] {
722        types.claim(name, "$")?;
723    }
724
725    match schemas.get("context") {
726        Some(schema) => types.named(schema, "Context", "schemas.context")?,
727        None => {
728            types.named(&serde_json::json!({ "type": "object", "properties": {} }), "Context", "schemas.context")?
729        }
730    }
731    let mut maps = Vec::new();
732    if let Some(e) = events {
733        maps.push(("events", e));
734    }
735    if let Some(e) = internal {
736        maps.push(("internalEvents", e));
737    }
738    if maps.is_empty() {
739        types.claim("Event", "schemas.events")?;
740        types.out.push(format!("pub type Event = {VALUE};\n"));
741    } else {
742        event_enum(&mut types, "Event", "", &maps)?;
743    }
744    if let Some(e) = obj(schemas.get("emitted")) {
745        event_enum(&mut types, "Emitted", "Emitted", &[("emitted", e)])?;
746    }
747    if let Some(e) = obj(schemas.get("rejections")) {
748        event_enum(&mut types, "Rejection", "Rejection", &[("rejections", e)])?;
749    }
750    for (key, name) in [("input", "Input"), ("output", "Output")] {
751        if let Some(schema) = schemas.get(key) {
752            types.named(schema, name, &format!("schemas.{key}"))?;
753        }
754    }
755
756    let children_code = children(&mut types, machine, schemas)?;
757
758    // The implementation trait and the registry wiring.
759    let mut methods = Vec::new();
760    let mut wiring = Vec::new();
761    let mut method_names = HashSet::new();
762    let mut method = |name: String, path: &str| -> Result<String, Error> {
763        if !method_names.insert(name.clone()) {
764            return Err(Error::new(path, format!("two sources map to the method `{name}`; rename one")));
765        }
766        Ok(name)
767    };
768    let params_type = |types: &mut Types, kind: &str, r: &Reference| -> Result<Option<String>, Error> {
769        let Some(schema) = schemas.get(kind).and_then(|d| d.get(&r.name)).and_then(|d| d.get("params")) else {
770            return Ok(None);
771        };
772        let name = format!("{}Params", pascal(&r.name));
773        types.named(schema, &name, &format!("schemas.{kind}.{}.params", r.name))?;
774        Ok(Some(name))
775    };
776    for r in distinct(&refs.guards) {
777        let m = method(snake_after("guard", &r.name), &r.path)?;
778        let doc = format!("    /// Guard `{}` (referenced at `{}`).\n", r.name, r.path);
779        let lit = string_lit(&r.name);
780        match params_type(&mut types, "guards", r)? {
781            Some(p) => {
782                methods.push(format!(
783                    "{doc}    fn {m}(&self, args: &__rt::GuardArgs<'_, Context, Event>, params: &{p}) -> bool;\n"
784                ));
785                wiring.push(format!(
786                    "    let i = imp.clone();\n    r.guard_with({lit}, move |args, p: &{p}| i.{m}(args, p));\n"
787                ));
788            }
789            None => {
790                methods.push(format!("{doc}    fn {m}(&self, args: &__rt::GuardArgs<'_, Context, Event>) -> bool;\n"));
791                wiring.push(format!("    let i = imp.clone();\n    r.guard({lit}, move |args| i.{m}(args));\n"));
792            }
793        }
794    }
795    if !host_actions.is_empty() {
796        let names: Vec<String> = host_actions.iter().map(|n| format!("{}.to_owned()", string_lit(n))).collect();
797        wiring.push(format!("    r.host_actions(__rt::HostActions::Named(::std::vec![{}]));\n", names.join(", ")));
798    }
799    for r in distinct(&refs.actions).into_iter().filter(|r| !host_actions.contains(&r.name)) {
800        let m = method(snake_after("action", &r.name), &r.path)?;
801        let doc = format!(
802            "    /// Action `{}` (referenced at `{}`). Runs as an effect after the step that enqueued it.\n",
803            r.name, r.path
804        );
805        let lit = string_lit(&r.name);
806        match params_type(&mut types, "actions", r)? {
807            Some(p) => {
808                methods.push(format!("{doc}    fn {m}(&self, params: &{p});\n"));
809                wiring.push(format!("    let i = imp.clone();\n    r.action_with({lit}, move |p: &{p}| i.{m}(p));\n"));
810            }
811            None => {
812                methods.push(format!("{doc}    fn {m}(&self);\n"));
813                wiring.push(format!("    let i = imp.clone();\n    r.action({lit}, move || i.{m}());\n"));
814            }
815        }
816    }
817    for r in distinct(&refs.delays) {
818        let m = method(snake_after("delay", &r.name), &r.path)?;
819        methods.push(format!(
820            "    /// Delay `{}` in milliseconds (referenced at `{}`), computed when the timer is scheduled.\n    fn {m}(&self, context: &Context, event: &__rt::Ev<Event>) -> u64;\n",
821            r.name, r.path
822        ));
823        wiring.push(format!(
824            "    let i = imp.clone();\n    r.delay({}, move |c, e| i.{m}(c, e));\n",
825            string_lit(&r.name)
826        ));
827    }
828    for r in distinct(&refs.actors) {
829        let m = method(snake_after("actor", &r.name), &r.path)?;
830        methods.push(format!(
831            "    /// Actor logic for `src: {}` (referenced at `{}`).\n    fn {m}(&self) -> ::std::sync::Arc<dyn __rt::Logic>;\n",
832            r.name, r.path
833        ));
834        wiring.push(format!("    r.actor({}, imp.{m}());\n", string_lit(&r.name)));
835    }
836
837    for r in distinct(&refs.exprs) {
838        let m = method(snake_after("expr", &r.name), &r.path)?;
839        methods.push(format!(
840            "    /// Expression `{}` (first used at `{}`): the value of each `{{\"@code\": {}, \"@lang\": \"rust\"}}`.\n    fn {m}(&self, args: &__rt::ExprArgs<'_, Context, Event>) -> __rt::serde_json::Value;\n",
841            r.name,
842            r.path,
843            string_lit(&r.name)
844        ));
845        wiring.push(format!("    let i = imp.clone();\n    r.expr({}, move |a| i.{m}(a));\n", string_lit(&r.name)));
846    }
847    for r in distinct(&refs.contexts) {
848        let m = method(snake_after("context", &r.name), &r.path)?;
849        // The whole root context is typed; a part of it is JSON.
850        let (ty, wrap) = if r.path == "$.context" {
851            ("Context", "__rt::serde_json::to_value(i.{m}(input)).expect(\"the context serializes\")")
852        } else {
853            ("__rt::serde_json::Value", "i.{m}(input)")
854        };
855        methods.push(format!(
856            "    /// The root context expression `{}` (at `{}`), computed from the actor's input when it starts.\n    fn {m}(&self, input: Option<&__rt::serde_json::Value>) -> {ty};\n",
857            r.name, r.path
858        ));
859        wiring.push(format!(
860            "    let i = imp.clone();\n    r.context({}, move |input| {});\n",
861            string_lit(&r.name),
862            wrap.replace("{m}", &m)
863        ));
864    }
865
866    for r in &refs.languages {
867        let m = method(snake_after("evaluator", &r.name), &r.path)?;
868        methods.push(format!(
869            "    /// The evaluator of the code nodes in language `{}` (first used at `{}`).\n    fn {m}(&self) -> ::std::sync::Arc<dyn __rt::Evaluator<Context, Event>>;\n",
870            r.name, r.path
871        ));
872        wiring.push(format!("    r.evaluator({}, imp.{m}());\n", string_lit(&r.name)));
873    }
874
875    if actors.is_some() || bundle.get("hostActions").is_some() {
876        workflow_types(&mut types, schemas, actors, &distinct(&refs.actors), &host_actions)?;
877    }
878
879    let mut code = String::new();
880    code.push_str(&format!("// @generated by xmachines-build from `{module}`. Do not edit.\n\n"));
881    code.push_str("#[allow(unused_imports)]\nuse ::xmachines_runtime::__codegen as __rt;\n\n");
882    code.push_str(&format!("/// The machine's `id`.\npub const ID: &str = {};\n\n", string_lit(id)));
883    code.push_str(&format!(
884        "/// The `MachineJSON` definition.\npub const DEFINITION: &str = {};\n\n",
885        raw_lit(&serde_json::to_string(&machine_value).expect("JSON"))
886    ));
887    code.push_str(&format!(
888        "/// The bundle's JSON Schemas (`schemas`: context, events, emitted, ...).\npub const SCHEMAS: &str = {};\n\n",
889        raw_lit(&serde_json::to_string(schemas).expect("JSON"))
890    ));
891    for item in &types.out {
892        code.push_str(item);
893        code.push('\n');
894    }
895    code.push_str(&format!(
896        "/// The guards, actions, delays, actors and expressions `{module}` needs from Rust.\npub trait {trait_name}: Send + Sync + 'static {{\n{}}}\n\n",
897        methods.join("\n")
898    ));
899    code.push_str(&format!(
900        "/// A registry that calls `imp`.\npub fn registry<I: {trait_name}>(imp: ::std::sync::Arc<I>) -> __rt::Registry<Context, Event> {{\n    #[allow(unused_mut)]\n    let mut r = __rt::Registry::new();\n{}    let _ = imp;\n    r\n}}\n\n",
901        wiring.concat()
902    ));
903    code.push_str(&format!(
904        "/// Compiles the definition with `imp`.\npub fn machine<I: {trait_name}>(imp: ::std::sync::Arc<I>) -> Result<__rt::Machine<Context, Event>, __rt::LoadError> {{\n    __rt::Machine::from_json_str(DEFINITION, &registry(imp))\n}}\n\n"
905    ));
906    code.push_str("/// An actor running this machine.\npub type Actor = __rt::Actor<Context, Event>;\n");
907    if !children_code.is_empty() {
908        code.push('\n');
909        code.push_str(&children_code);
910    }
911    Ok(Generated { code, warnings })
912}
913
914/// Generates modules for bundles from `build.rs`.
915#[derive(Debug, Default)]
916pub struct Builder {
917    machines: Vec<PathBuf>,
918    out_dir: Option<PathBuf>,
919}
920
921impl Builder {
922    pub fn new() -> Self {
923        Self::default()
924    }
925
926    /// Adds a bundle (`<name>.machine.json`). The module is named `<name>`.
927    pub fn machine(mut self, path: impl AsRef<Path>) -> Self {
928        self.machines.push(path.as_ref().to_owned());
929        self
930    }
931
932    /// Where to write the modules. Defaults to `$OUT_DIR/xstate`, where
933    /// `include_machine!` looks.
934    pub fn out_dir(mut self, dir: impl AsRef<Path>) -> Self {
935        self.out_dir = Some(dir.as_ref().to_owned());
936        self
937    }
938
939    /// Writes one module per bundle, prints `cargo:rerun-if-changed` for each
940    /// bundle and `cargo:warning` for each warning, and returns the files.
941    pub fn build(self) -> Result<Vec<PathBuf>, Error> {
942        let io = |file: &Path, e: std::io::Error| Error {
943            file: Some(file.to_owned()),
944            path: String::new(),
945            message: e.to_string(),
946        };
947        let out_dir = match self.out_dir {
948            Some(d) => d,
949            None => PathBuf::from(
950                std::env::var_os("OUT_DIR")
951                    .ok_or_else(|| Error::new("", "OUT_DIR is not set; call build() from build.rs or set out_dir"))?,
952            )
953            .join("xstate"),
954        };
955        std::fs::create_dir_all(&out_dir).map_err(|e| io(&out_dir, e))?;
956        let mut written = Vec::new();
957        for path in self.machines {
958            println!("cargo:rerun-if-changed={}", path.display());
959            let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();
960            let module = file_name
961                .strip_suffix(".machine.json")
962                .or_else(|| file_name.strip_suffix(".json"))
963                .unwrap_or(file_name);
964            let text = std::fs::read_to_string(&path).map_err(|e| io(&path, e))?;
965            let bundle: Value = serde_json::from_str(&text).map_err(|e| Error {
966                file: Some(path.clone()),
967                path: String::new(),
968                message: e.to_string(),
969            })?;
970            let generated = generate(&bundle, module).map_err(|e| Error { file: Some(path.clone()), ..e })?;
971            for w in generated.warnings {
972                println!("cargo:warning={}: {w}", path.display());
973            }
974            let out = out_dir.join(format!("{module}.rs"));
975            std::fs::write(&out, generated.code).map_err(|e| io(&out, e))?;
976            written.push(out);
977        }
978        Ok(written)
979    }
980}