cloacina-macros 0.9.0

Procedural macros for the cloacina workflow orchestration library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
/*
 *  Copyright 2025-2026 Colliery Software
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

//! Topology parser for `#[computation_graph]`.
//!
//! Parses the macro attribute syntax. Two top-level field shapes:
//!
//! Split form — graph subscribes to a standalone `#[reactor]`:
//! ```text
//! #[computation_graph(
//!     trigger = reactor(MyReactor),
//!     graph = {
//!         decision_engine(alpha, beta, gamma) => {
//!             Signal -> risk_check,
//!             NoAction -> audit_logger,
//!         },
//!         risk_check(gamma) => {
//!             Approved -> output_handler,
//!             Blocked -> alert_handler,
//!         },
//!     }
//! )]
//! ```
//!
//! Trigger-less form — graph is registered by name and invoked directly:
//! ```text
//! #[computation_graph(graph = { entry(alpha) -> output })]
//! ```
//!
//! The bundled `react = when_any(...)` form was removed in CLOACI-I-0101.
//! The parser still recognizes `react` as a key so it can emit a migration
//! diagnostic; it does not parse a value.

use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{braced, Ident, LitStr, Token};

/// The full parsed topology from the macro attribute.
///
/// Supports two shapes:
/// - `trigger = reactor(TypePath)` + `graph = { ... }` — split form; the graph
///   binds at runtime to the already-declared reactor whose struct is
///   `TypePath`, and the graph macro emits a compile-time subset check
///   between entry accumulators and `<TypePath as Reactor>::ACCUMULATORS`.
/// - `graph = { ... }` only — trigger-less form; the graph is registered by
///   name only and is invoked directly (T-02 workflow tasks, T-03 Python).
pub struct ParsedTopology {
    pub trigger: TriggerSpec,
    pub edges: Vec<ParsedEdge>,
}

impl std::fmt::Debug for ParsedTopology {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ParsedTopology")
            .field("trigger", &self.trigger)
            .field("edges", &self.edges)
            .finish()
    }
}

/// Which form of trigger the user declared.
#[derive(Debug)]
pub enum TriggerSpec {
    /// `trigger = reactor("name")` — split form referencing a standalone
    /// reactor declaration by name. The compile-time accumulator-subset
    /// check that the type-path form enabled is gone — runtime contract
    /// validation at load time (T-B) is the replacement.
    ByReactor(String),
    /// No `trigger` — the graph is trigger-less.
    None,
}

/// A parsed edge in the topology.
#[derive(Debug)]
pub enum ParsedEdge {
    /// `node_a(inputs) -> node_b`
    Linear {
        from: Ident,
        from_inputs: Vec<Ident>,
        to: Ident,
    },
    /// `node_a(inputs) => { Variant -> node_b, Variant2 -> node_c }`
    Routing {
        from: Ident,
        from_inputs: Vec<Ident>,
        variants: Vec<RoutingVariant>,
    },
}

/// A single variant -> downstream mapping in a routing edge.
#[derive(Debug)]
pub struct RoutingVariant {
    pub variant_name: Ident,
    pub target: Ident,
}

// `from_name` and `from_inputs` are accessor methods that return the
// `from` / `from_inputs` field of the parsed edge — they are not factory
// methods, so the `from_*` lint about taking `self` doesn't apply.
#[allow(clippy::wrong_self_convention)]
impl ParsedEdge {
    pub fn from_name(&self) -> &Ident {
        match self {
            ParsedEdge::Linear { from, .. } => from,
            ParsedEdge::Routing { from, .. } => from,
        }
    }

    pub fn from_inputs(&self) -> &[Ident] {
        match self {
            ParsedEdge::Linear { from_inputs, .. } => from_inputs,
            ParsedEdge::Routing { from_inputs, .. } => from_inputs,
        }
    }
}

// --- Parsing implementation ---

impl Parse for ParsedTopology {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut trigger_reactor: Option<String> = None;
        let mut edges: Option<Vec<ParsedEdge>> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;

            match key.to_string().as_str() {
                "react" => {
                    return Err(syn::Error::new(
                        key.span(),
                        "the bundled `#[computation_graph(react = ...)]` form has been \
                         removed. Declare a standalone `#[reactor]` and reference it via \
                         `#[computation_graph(trigger = reactor(\"name\"), ...)]` — see \
                         initiative CLOACI-I-0101 for migration guidance.",
                    ));
                }
                "trigger" => {
                    input.parse::<Token![=]>()?;
                    if trigger_reactor.is_some() {
                        return Err(syn::Error::new(key.span(), "duplicate 'trigger' field"));
                    }
                    // Expect: reactor("name")
                    let kind: Ident = input.parse()?;
                    if kind != "reactor" {
                        return Err(syn::Error::new(
                            kind.span(),
                            format!(
                                "unknown trigger kind '{}', expected 'reactor' \
                                 (e.g. trigger = reactor(\"risk_signals\"))",
                                kind
                            ),
                        ));
                    }
                    let paren;
                    syn::parenthesized!(paren in input);
                    let name: LitStr = paren.parse().map_err(|_| {
                        syn::Error::new(
                            paren.span(),
                            "reactor(...) expects a string literal name \
                             (e.g. reactor(\"risk_signals\")). The type-path form was \
                             removed in CLOACI-I-0102 — cross-reference is now by name \
                             with runtime contract validation.",
                        )
                    })?;
                    if !paren.is_empty() {
                        return Err(syn::Error::new(
                            paren.span(),
                            "reactor(...) takes exactly one string-literal argument",
                        ));
                    }
                    trigger_reactor = Some(name.value());
                }
                "graph" => {
                    input.parse::<Token![=]>()?;
                    if edges.is_some() {
                        return Err(syn::Error::new(key.span(), "duplicate 'graph' field"));
                    }
                    edges = Some(parse_graph_block(input)?);
                }
                other => {
                    return Err(syn::Error::new(
                        key.span(),
                        format!("unknown field '{}', expected 'trigger' or 'graph'", other),
                    ));
                }
            }

            // Optional trailing comma between top-level fields
            let _ = input.parse::<Token![,]>();
        }

        let edges = edges.ok_or_else(|| {
            syn::Error::new(proc_macro2::Span::call_site(), "missing 'graph' field")
        })?;

        let trigger = match trigger_reactor {
            Some(name) => TriggerSpec::ByReactor(name),
            None => TriggerSpec::None,
        };

        Ok(ParsedTopology { trigger, edges })
    }
}

/// Parse the `graph = { ... }` block containing edge declarations.
fn parse_graph_block(input: ParseStream) -> syn::Result<Vec<ParsedEdge>> {
    let content;
    braced!(content in input);

    let mut edges = Vec::new();

    while !content.is_empty() {
        edges.push(parse_edge(&content)?);
        // Optional trailing comma between edges
        let _ = content.parse::<Token![,]>();
    }

    Ok(edges)
}

/// Parse a single edge declaration.
///
/// Either:
/// - `node_name(inputs) -> target` (linear)
/// - `node_name(inputs) => { Variant -> target, ... }` (routing)
/// - `node_name -> target` (linear, no inputs)
/// - `node_name` (terminal node, no edges — just declares it exists)
fn parse_edge(input: ParseStream) -> syn::Result<ParsedEdge> {
    let from: Ident = input.parse()?;

    // Parse optional parenthesized cache inputs
    let from_inputs = if input.peek(syn::token::Paren) {
        let content;
        syn::parenthesized!(content in input);
        let inputs: Punctuated<Ident, Token![,]> =
            content.parse_terminated(Ident::parse, Token![,])?;
        inputs.into_iter().collect()
    } else {
        Vec::new()
    };

    // Determine edge type by lookahead
    if input.peek(Token![=>]) {
        // Routing edge: node => { Variant -> target, ... }
        input.parse::<Token![=>]>()?;
        let variants_content;
        braced!(variants_content in input);

        let mut variants = Vec::new();
        while !variants_content.is_empty() {
            let variant_name: Ident = variants_content.parse()?;
            variants_content.parse::<Token![->]>()?;
            let target: Ident = variants_content.parse()?;
            variants.push(RoutingVariant {
                variant_name,
                target,
            });
            // Optional trailing comma
            let _ = variants_content.parse::<Token![,]>();
        }

        if variants.is_empty() {
            return Err(syn::Error::new(
                from.span(),
                "routing edge must have at least one variant",
            ));
        }

        Ok(ParsedEdge::Routing {
            from,
            from_inputs,
            variants,
        })
    } else if input.peek(Token![->]) {
        // Linear edge: node -> target
        input.parse::<Token![->]>()?;
        let to: Ident = input.parse()?;
        Ok(ParsedEdge::Linear {
            from,
            from_inputs,
            to,
        })
    } else {
        // Terminal node with no downstream — this is valid but we represent it
        // as a linear edge to nowhere. The graph IR will handle terminal detection.
        // For now, error — we require explicit edges.
        Err(syn::Error::new(
            from.span(),
            format!(
                "expected '->' or '=>' after node '{}'. Terminal nodes are detected automatically \
                 from the graph — they don't need explicit declaration.",
                from
            ),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use quote::quote;

    fn parse_topology(tokens: proc_macro2::TokenStream) -> syn::Result<ParsedTopology> {
        syn::parse2::<ParsedTopology>(tokens)
    }

    #[test]
    fn test_error_react_form_removed() {
        let tokens = quote! {
            react = when_any(alpha),
            graph = {
                entry(alpha) -> output,
            }
        };
        let result = parse_topology(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("bundled") && err.contains("CLOACI-I-0101"),
            "expected migration diagnostic pointing at CLOACI-I-0101, got: {}",
            err
        );
    }

    #[test]
    fn test_parse_split_form_trigger_reactor() {
        let tokens = quote! {
            trigger = reactor("risk_signals"),
            graph = {
                entry(alpha) -> output,
            }
        };
        let topology = parse_topology(tokens).unwrap();
        match topology.trigger {
            TriggerSpec::ByReactor(name) => {
                assert_eq!(name, "risk_signals");
            }
            other => panic!("expected ByReactor, got {:?}", other),
        }
    }

    #[test]
    fn test_error_trigger_reactor_type_path_rejected() {
        // The type-path form was removed in CLOACI-I-0102. A bare ident
        // inside reactor(...) should now produce a friendly migration error.
        let tokens = quote! {
            trigger = reactor(MyReactor),
            graph = { a -> b },
        };
        let result = parse_topology(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("string literal"),
            "expected migration diagnostic, got: {}",
            err
        );
    }

    #[test]
    fn test_parse_triggerless_form() {
        let tokens = quote! {
            graph = {
                entry(alpha) -> output,
            }
        };
        let topology = parse_topology(tokens).unwrap();
        assert!(matches!(topology.trigger, TriggerSpec::None));
    }

    #[test]
    fn test_error_trigger_unknown_kind() {
        let tokens = quote! {
            trigger = schedule("0 * * * *"),
            graph = { a -> b },
        };
        let result = parse_topology(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("unknown trigger kind"), "got: {}", err);
    }

    #[test]
    fn test_parse_linear_edge() {
        let tokens = quote! {
            trigger = reactor("r"),
            graph = {
                entry(alpha) -> middle,
                middle -> output,
            }
        };
        let topology = parse_topology(tokens).unwrap();
        assert_eq!(topology.edges.len(), 2);

        match &topology.edges[0] {
            ParsedEdge::Linear {
                from,
                from_inputs,
                to,
            } => {
                assert_eq!(from.to_string(), "entry");
                assert_eq!(from_inputs.len(), 1);
                assert_eq!(from_inputs[0].to_string(), "alpha");
                assert_eq!(to.to_string(), "middle");
            }
            _ => panic!("expected linear edge"),
        }

        match &topology.edges[1] {
            ParsedEdge::Linear {
                from,
                from_inputs,
                to,
            } => {
                assert_eq!(from.to_string(), "middle");
                assert!(from_inputs.is_empty());
                assert_eq!(to.to_string(), "output");
            }
            _ => panic!("expected linear edge"),
        }
    }

    #[test]
    fn test_parse_routing_edge() {
        let tokens = quote! {
            trigger = reactor("r"),
            graph = {
                decision(alpha) => {
                    Signal -> handler_a,
                    NoAction -> handler_b,
                },
            }
        };
        let topology = parse_topology(tokens).unwrap();
        assert_eq!(topology.edges.len(), 1);

        match &topology.edges[0] {
            ParsedEdge::Routing {
                from,
                from_inputs,
                variants,
            } => {
                assert_eq!(from.to_string(), "decision");
                assert_eq!(from_inputs.len(), 1);
                assert_eq!(variants.len(), 2);
                assert_eq!(variants[0].variant_name.to_string(), "Signal");
                assert_eq!(variants[0].target.to_string(), "handler_a");
                assert_eq!(variants[1].variant_name.to_string(), "NoAction");
                assert_eq!(variants[1].target.to_string(), "handler_b");
            }
            _ => panic!("expected routing edge"),
        }
    }

    #[test]
    fn test_parse_mixed_edges() {
        let tokens = quote! {
            trigger = reactor("r"),
            graph = {
                decision_engine(alpha, beta, gamma) => {
                    Signal -> risk_check,
                    NoAction -> audit_logger,
                },
                risk_check(gamma) => {
                    Approved -> output_handler,
                    Blocked -> alert_handler,
                },
            }
        };
        let topology = parse_topology(tokens).unwrap();
        assert_eq!(topology.edges.len(), 2);

        // First edge: routing with 3 cache inputs
        match &topology.edges[0] {
            ParsedEdge::Routing {
                from, from_inputs, ..
            } => {
                assert_eq!(from.to_string(), "decision_engine");
                assert_eq!(from_inputs.len(), 3);
            }
            _ => panic!("expected routing edge"),
        }

        // Second edge: routing with 1 cache input
        match &topology.edges[1] {
            ParsedEdge::Routing {
                from,
                from_inputs,
                variants,
            } => {
                assert_eq!(from.to_string(), "risk_check");
                assert_eq!(from_inputs.len(), 1);
                assert_eq!(from_inputs[0].to_string(), "gamma");
                assert_eq!(variants.len(), 2);
            }
            _ => panic!("expected routing edge"),
        }
    }

    #[test]
    fn test_parse_fan_in() {
        let tokens = quote! {
            trigger = reactor("r"),
            graph = {
                validate_a(a) -> merge,
                validate_b(b) -> merge,
            }
        };
        let topology = parse_topology(tokens).unwrap();
        assert_eq!(topology.edges.len(), 2);

        // Both edges point to "merge"
        match &topology.edges[0] {
            ParsedEdge::Linear { to, .. } => assert_eq!(to.to_string(), "merge"),
            _ => panic!("expected linear edge"),
        }
        match &topology.edges[1] {
            ParsedEdge::Linear { to, .. } => assert_eq!(to.to_string(), "merge"),
            _ => panic!("expected linear edge"),
        }
    }

    #[test]
    fn test_parse_fan_out() {
        let tokens = quote! {
            trigger = reactor("r"),
            graph = {
                compute(a) -> output_handler,
                compute(a) -> audit_logger,
            }
        };
        let topology = parse_topology(tokens).unwrap();
        assert_eq!(topology.edges.len(), 2);

        match &topology.edges[0] {
            ParsedEdge::Linear { from, to, .. } => {
                assert_eq!(from.to_string(), "compute");
                assert_eq!(to.to_string(), "output_handler");
            }
            _ => panic!("expected linear edge"),
        }
        match &topology.edges[1] {
            ParsedEdge::Linear { from, to, .. } => {
                assert_eq!(from.to_string(), "compute");
                assert_eq!(to.to_string(), "audit_logger");
            }
            _ => panic!("expected linear edge"),
        }
    }

    #[test]
    fn test_error_missing_graph() {
        let tokens = quote! {
            trigger = reactor("r")
        };
        let result = parse_topology(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("missing 'graph' field"), "got: {}", err);
    }

    #[test]
    fn test_error_unknown_field() {
        let tokens = quote! {
            trigger = reactor("r"),
            graph = { a -> b },
            bogus = something,
        };
        let result = parse_topology(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("unknown field 'bogus'"), "got: {}", err);
    }

    #[test]
    fn test_error_empty_routing() {
        let tokens = quote! {
            trigger = reactor("r"),
            graph = {
                a(a) => {},
            }
        };
        let result = parse_topology(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("at least one variant"), "got: {}", err);
    }

    #[test]
    fn test_error_duplicate_trigger() {
        let tokens = quote! {
            trigger = reactor("r1"),
            trigger = reactor("r2"),
            graph = { a -> b },
        };
        let result = parse_topology(tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("duplicate 'trigger'"), "got: {}", err);
    }
}