1use tpt_telos_parser::ast::{Arg, Attribute};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Target {
34 Rust,
35 Go,
36 Python,
40}
41
42impl Target {
43 pub fn as_str(&self) -> &'static str {
55 match self {
56 Target::Rust => "rust",
57 Target::Go => "go",
58 Target::Python => "python",
59 }
60 }
61}
62
63#[derive(Debug, Clone)]
66pub struct RoutingDiagnostic {
67 pub kind: DiagnosticKind,
68 pub module: String,
69 pub message: String,
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum DiagnosticKind {
75 RealTimeGoConflict,
78 ZeroAllocGoConflict,
80 RealTimePythonConflict,
82 ZeroAllocPythonConflict,
84 UnrecognizedStateValue,
86 UnrecognizedBoundaryFlag,
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
94pub enum StorageClass {
95 Persistent,
98 #[default]
100 Ephemeral,
101}
102
103#[derive(Debug, Clone)]
108pub struct Route {
109 pub target: Target,
110 pub storage: StorageClass,
112 pub reason: String,
114}
115
116impl Route {
117 pub fn is_rust(&self) -> bool {
134 self.target == Target::Rust
135 }
136}
137
138const RUST_FLAGS: &[&str] = &["cpu_bound", "zero_allocation", "crypto", "real_time"];
140
141const GO_FLAGS: &[&str] = &[
143 "network_io",
144 "high_concurrency",
145 "distributed",
146 "high_latency",
147];
148
149const PYTHON_FLAGS: &[&str] = &["ml_training", "python", "jax"];
151
152fn boundary_flags(attrs: &[Attribute]) -> Vec<String> {
153 let mut flags = Vec::new();
154 for attr in attrs {
155 if attr.name != "boundary" {
156 continue;
157 }
158 for arg in &attr.args {
159 if let Arg::Flag(f) = arg {
160 flags.push(f.clone());
161 }
162 }
163 }
164 flags
165}
166
167fn parse_storage_class(attrs: &[Attribute]) -> (StorageClass, Option<String>) {
172 for attr in attrs {
173 if attr.name != "state" {
174 continue;
175 }
176 for arg in &attr.args {
177 if let Arg::Flag(f) = arg {
178 match f.as_str() {
179 "persistent" => return (StorageClass::Persistent, None),
180 "ephemeral" => return (StorageClass::Ephemeral, None),
181 other => return (StorageClass::default(), Some(other.to_string())),
182 }
183 }
184 if let Arg::Kv(k, tpt_telos_parser::ast::Literal::Ident(v)) = arg {
185 if k == "class" {
186 match v.as_str() {
187 "persistent" => return (StorageClass::Persistent, None),
188 "ephemeral" => return (StorageClass::Ephemeral, None),
189 other => return (StorageClass::default(), Some(other.to_string())),
190 }
191 }
192 }
193 }
194 }
195 (StorageClass::default(), None)
196}
197
198pub fn route_checked(attrs: &[Attribute], module_name: &str) -> (Route, Vec<RoutingDiagnostic>) {
222 let flags = boundary_flags(attrs);
223
224 let (storage, unrecognized_state) = parse_storage_class(attrs);
226
227 let mut go_hits = Vec::new();
228 let mut rust_hits = Vec::new();
229 let mut python_hits = Vec::new();
230 let mut unrecognized_flags = Vec::new();
231 for f in &flags {
232 if PYTHON_FLAGS.contains(&f.as_str()) {
233 python_hits.push(f.clone());
234 } else if GO_FLAGS.contains(&f.as_str()) {
235 go_hits.push(f.clone());
236 } else if RUST_FLAGS.contains(&f.as_str()) {
237 rust_hits.push(f.clone());
238 } else {
239 unrecognized_flags.push(f.clone());
240 }
241 }
242
243 let route = if !python_hits.is_empty() {
245 Route {
246 target: Target::Python,
247 storage,
248 reason: format!("boundary flags {:?} routed to Python backend", python_hits),
249 }
250 } else if !go_hits.is_empty() {
251 Route {
252 target: Target::Go,
253 storage,
254 reason: format!("boundary flags {:?} routed to Go backend", go_hits),
255 }
256 } else if !rust_hits.is_empty() {
257 Route {
258 target: Target::Rust,
259 storage,
260 reason: format!("boundary flags {:?} routed to Rust backend", rust_hits),
261 }
262 } else {
263 Route {
264 target: Target::Rust,
265 storage,
266 reason: "no explicit boundary flags; defaulting to Rust compute backend".to_string(),
267 }
268 };
269
270 let mut diagnostics = Vec::new();
271
272 if let Some(ref bad_val) = unrecognized_state {
273 diagnostics.push(RoutingDiagnostic {
274 kind: DiagnosticKind::UnrecognizedStateValue,
275 module: module_name.to_string(),
276 message: format!(
277 "module `{}` has unrecognized `@state({})` value; \
278 valid values are `persistent` and `ephemeral` (defaulting to ephemeral)",
279 module_name, bad_val
280 ),
281 });
282 }
283
284 for bad_flag in &unrecognized_flags {
285 diagnostics.push(RoutingDiagnostic {
286 kind: DiagnosticKind::UnrecognizedBoundaryFlag,
287 module: module_name.to_string(),
288 message: format!(
289 "module `{}` has unrecognized `@boundary({})` flag; \
290 valid flags are cpu_bound, zero_allocation, crypto, real_time, \
291 network_io, high_concurrency, distributed, high_latency, \
292 ml_training, python, jax (ignored; defaulting to Rust backend)",
293 module_name, bad_flag
294 ),
295 });
296 }
297
298 if route.target == Target::Go {
299 if rust_hits.iter().any(|f| f == "real_time") {
300 diagnostics.push(RoutingDiagnostic {
301 kind: DiagnosticKind::RealTimeGoConflict,
302 module: module_name.to_string(),
303 message: format!(
304 "module `{}` has `real_time` flag but is routed to Go (GC is \
305 non-deterministic; FADEC/PREEMPT_RT targets must use Rust; \
306 see ARCHITECTURE.md § Go GC Determinism)",
307 module_name
308 ),
309 });
310 }
311 if rust_hits.iter().any(|f| f == "zero_allocation") {
312 diagnostics.push(RoutingDiagnostic {
313 kind: DiagnosticKind::ZeroAllocGoConflict,
314 module: module_name.to_string(),
315 message: format!(
316 "module `{}` has `zero_allocation` flag but is routed to Go \
317 (Go allocates via GC; zero-allocation guarantees cannot be upheld; \
318 see ARCHITECTURE.md § Go GC Determinism)",
319 module_name
320 ),
321 });
322 }
323 }
324
325 if route.target == Target::Python {
326 if rust_hits.iter().any(|f| f == "real_time") {
327 diagnostics.push(RoutingDiagnostic {
328 kind: DiagnosticKind::RealTimePythonConflict,
329 module: module_name.to_string(),
330 message: format!(
331 "module `{}` has `real_time` flag but is routed to Python \
332 (Python is GC-based with non-deterministic latency; \
333 hard real-time targets must use Rust)",
334 module_name
335 ),
336 });
337 }
338 if rust_hits.iter().any(|f| f == "zero_allocation") {
339 diagnostics.push(RoutingDiagnostic {
340 kind: DiagnosticKind::ZeroAllocPythonConflict,
341 module: module_name.to_string(),
342 message: format!(
343 "module `{}` has `zero_allocation` flag but is routed to Python \
344 (Python allocates via GC; zero-allocation guarantees cannot be upheld)",
345 module_name
346 ),
347 });
348 }
349 }
350
351 (route, diagnostics)
352}
353
354pub fn route(attrs: &[Attribute]) -> Route {
393 route_checked(attrs, "").0
394}
395
396#[cfg(test)]
397mod tests {
398 use super::*;
399 use tpt_telos_parser::ast::{Arg, Attribute};
400
401 fn attr(flags: &[&str]) -> Attribute {
402 Attribute {
403 name: "boundary".to_string(),
404 args: flags.iter().map(|f| Arg::Flag(f.to_string())).collect(),
405 }
406 }
407
408 #[test]
409 fn network_io_routes_to_go() {
410 let r = route(&[attr(&["network_io"])]);
411 assert_eq!(r.target, Target::Go);
412 }
413
414 #[test]
415 fn cpu_bound_routes_to_rust() {
416 let r = route(&[attr(&["cpu_bound"])]);
417 assert_eq!(r.target, Target::Rust);
418 }
419
420 #[test]
421 fn no_flags_default_rust() {
422 let r = route(&[]);
423 assert_eq!(r.target, Target::Rust);
424 }
425
426 #[test]
429 fn zero_allocation_routes_to_rust() {
430 let r = route(&[attr(&["zero_allocation"])]);
431 assert_eq!(r.target, Target::Rust);
432 }
433
434 #[test]
435 fn crypto_routes_to_rust() {
436 let r = route(&[attr(&["crypto"])]);
437 assert_eq!(r.target, Target::Rust);
438 }
439
440 #[test]
441 fn real_time_routes_to_rust() {
442 let r = route(&[attr(&["real_time"])]);
443 assert_eq!(r.target, Target::Rust);
444 }
445
446 #[test]
449 fn high_concurrency_routes_to_go() {
450 let r = route(&[attr(&["high_concurrency"])]);
451 assert_eq!(r.target, Target::Go);
452 }
453
454 #[test]
455 fn distributed_routes_to_go() {
456 let r = route(&[attr(&["distributed"])]);
457 assert_eq!(r.target, Target::Go);
458 }
459
460 #[test]
461 fn high_latency_routes_to_go() {
462 let r = route(&[attr(&["high_latency"])]);
463 assert_eq!(r.target, Target::Go);
464 }
465
466 #[test]
469 fn multiple_rust_flags_still_rust() {
470 let r = route(&[attr(&["cpu_bound", "zero_allocation", "crypto"])]);
471 assert_eq!(r.target, Target::Rust);
472 }
473
474 #[test]
475 fn multiple_go_flags_still_go() {
476 let r = route(&[attr(&["network_io", "high_concurrency"])]);
477 assert_eq!(r.target, Target::Go);
478 }
479
480 #[test]
481 fn go_flag_wins_over_rust_flag() {
482 let r = route(&[attr(&["cpu_bound", "network_io"])]);
484 assert_eq!(r.target, Target::Go);
485 }
486
487 #[test]
488 fn unrecognised_flag_defaults_to_rust() {
489 let r = route(&[attr(&["some_future_flag"])]);
491 assert_eq!(r.target, Target::Rust);
492 }
493
494 #[test]
495 fn unrecognised_boundary_flag_emits_diagnostic() {
496 let (r, diags) = route_checked(&[attr(&["some_future_flag"])], "MyModule");
497 assert_eq!(r.target, Target::Rust);
498 assert!(diags
499 .iter()
500 .any(|d| d.kind == DiagnosticKind::UnrecognizedBoundaryFlag));
501 }
502
503 #[test]
504 fn route_records_justification() {
505 let r = route(&[attr(&["network_io"])]);
506 assert!(r.reason.contains("network_io"));
507 assert!(r.is_rust() == (r.target == Target::Rust));
508 }
509
510 #[test]
513 fn ml_training_routes_to_python() {
514 let r = route(&[attr(&["ml_training"])]);
515 assert_eq!(r.target, Target::Python);
516 }
517
518 #[test]
519 fn python_flag_routes_to_python() {
520 let r = route(&[attr(&["python"])]);
521 assert_eq!(r.target, Target::Python);
522 }
523
524 #[test]
525 fn jax_flag_routes_to_python() {
526 let r = route(&[attr(&["jax"])]);
527 assert_eq!(r.target, Target::Python);
528 }
529
530 #[test]
531 fn python_beats_go_flag() {
532 let r = route(&[attr(&["ml_training", "network_io"])]);
534 assert_eq!(r.target, Target::Python);
535 }
536
537 #[test]
540 fn real_time_go_conflict_emits_diagnostic() {
541 let (r, diags) = route_checked(&[attr(&["real_time", "network_io"])], "ControlLoop");
542 assert_eq!(r.target, Target::Go);
543 assert!(diags
544 .iter()
545 .any(|d| d.kind == DiagnosticKind::RealTimeGoConflict));
546 }
547
548 #[test]
549 fn zero_alloc_go_conflict_emits_diagnostic() {
550 let (r, diags) = route_checked(&[attr(&["zero_allocation", "high_concurrency"])], "Buffer");
551 assert_eq!(r.target, Target::Go);
552 assert!(diags
553 .iter()
554 .any(|d| d.kind == DiagnosticKind::ZeroAllocGoConflict));
555 }
556
557 #[test]
558 fn real_time_alone_has_no_diagnostics() {
559 let (r, diags) = route_checked(&[attr(&["real_time"])], "FADEC");
560 assert_eq!(r.target, Target::Rust);
561 assert!(diags.is_empty());
562 }
563
564 #[test]
565 fn python_target_has_no_diagnostics() {
566 let (r, diags) = route_checked(&[attr(&["ml_training"])], "TrainLayer");
567 assert_eq!(r.target, Target::Python);
568 assert!(diags.is_empty());
569 }
570
571 fn state_attr(class: &str) -> Attribute {
574 Attribute {
575 name: "state".to_string(),
576 args: vec![Arg::Flag(class.to_string())],
577 }
578 }
579
580 #[test]
581 fn state_persistent_sets_storage_class() {
582 let r = route(&[state_attr("persistent")]);
583 assert_eq!(r.storage, StorageClass::Persistent);
584 }
585
586 #[test]
587 fn state_ephemeral_sets_storage_class() {
588 let r = route(&[state_attr("ephemeral")]);
589 assert_eq!(r.storage, StorageClass::Ephemeral);
590 }
591
592 #[test]
593 fn no_state_defaults_to_ephemeral() {
594 let r = route(&[]);
595 assert_eq!(r.storage, StorageClass::Ephemeral);
596 }
597
598 #[test]
599 fn state_with_boundary_combines() {
600 let boundary = attr(&["network_io"]);
601 let state = state_attr("persistent");
602 let r = route(&[boundary, state]);
603 assert_eq!(r.target, Target::Go);
604 assert_eq!(r.storage, StorageClass::Persistent);
605 }
606}