-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathrust.rs
More file actions
2244 lines (2004 loc) · 75.5 KB
/
rust.rs
File metadata and controls
2244 lines (2004 loc) · 75.5 KB
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Rust source code generator
//!
//! Converts an [`ArchitectureState`] into compilable Rust source that uses the
//! actual AimDB 0.5.x API: `#[derive(RecordKey)]`, `BufferCfg`, and
//! `AimDbBuilder::configure()`.
//!
//! Uses [`quote`] for quasi-quoting token streams and [`prettyplease`] for
//! formatting the output into idiomatic Rust.
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use crate::state::{
ArchitectureState, ConnectorDef, ConnectorDirection, RecordDef, SerializationType, TaskDef,
TaskType,
};
// ── Public API ────────────────────────────────────────────────────────────────
/// Generate a complete Rust source file from architecture state.
///
/// The returned string can be written to `src/generated_schema.rs`.
/// It contains:
/// - One `<Name>Value` struct per record (with `Serialize` / `Deserialize`)
/// - One `<Name>Key` enum per record (with `#[derive(RecordKey)]`)
/// - A `configure_schema<R>()` function wiring all records into `AimDbBuilder`
pub fn generate_rust(state: &ArchitectureState) -> String {
let formatted = generate_rust_inner(state);
let header = "\
// @generated — do not edit manually.\n\
// Source: .aimdb/state.toml — edit via `aimdb generate` or the architecture agent.\n\
// Regenerate: `aimdb generate` or confirm a proposal in the architecture agent.\n\n";
format!("{header}{formatted}")
}
/// Generate `schema.rs` for a common crate (no `@generated` header).
///
/// Emits only the portable data-contract layer: value structs, key enums,
/// `SchemaType` and `Linkable` impls. No `configure_schema`, no runtime deps.
/// This keeps the common crate platform-agnostic (`no_std`-compatible).
pub fn generate_schema_rs(state: &ArchitectureState) -> String {
generate_types_inner(state)
}
/// Types-only inner — value structs + key enums + trait impls, no `configure_schema`.
fn generate_types_inner(state: &ArchitectureState) -> String {
let imports = emit_imports_types_only(state);
let record_items: Vec<TokenStream> = state
.records
.iter()
.flat_map(|rec| {
let mut items = vec![emit_value_struct(rec), emit_key_enum(rec)];
items.push(emit_schema_type_impl(rec));
let linkable = emit_linkable_impl(rec);
if !linkable.is_empty() {
items.push(linkable);
}
if let Some(obs) = emit_observable_impl(rec) {
items.push(obs);
}
if let Some(set) = emit_settable_impl(rec) {
items.push(set);
}
items
})
.collect();
let file_tokens = quote! {
#imports
#(#record_items)*
};
let syntax_tree = syn::parse2(file_tokens).expect("generated tokens should be valid Rust");
prettyplease::unparse(&syntax_tree)
}
fn generate_rust_inner(state: &ArchitectureState) -> String {
let imports = emit_imports(state);
let record_items: Vec<TokenStream> = state
.records
.iter()
.flat_map(|rec| {
let mut items = vec![emit_value_struct(rec), emit_key_enum(rec)];
items.push(emit_schema_type_impl(rec));
let linkable = emit_linkable_impl(rec);
if !linkable.is_empty() {
items.push(linkable);
}
if let Some(obs) = emit_observable_impl(rec) {
items.push(obs);
}
if let Some(set) = emit_settable_impl(rec) {
items.push(set);
}
items
})
.collect();
let configure_fn = emit_configure_schema(state);
let file_tokens = quote! {
#imports
#(#record_items)*
#configure_fn
};
let syntax_tree = syn::parse2(file_tokens).expect("generated tokens should be valid Rust");
prettyplease::unparse(&syntax_tree)
}
/// Generate `Cargo.toml` content for a common crate.
///
/// Requires `state.project` to be `Some`. The caller should validate this
/// before calling.
pub fn generate_cargo_toml(state: &ArchitectureState) -> String {
let project = state
.project
.as_ref()
.expect("generate_cargo_toml requires [project] block in state.toml");
let crate_name = format!("{}-common", project.name);
let edition = project.edition.as_deref().unwrap_or("2024");
let has_non_custom_ser = state.records.iter().any(|r| {
r.serialization.as_ref().unwrap_or(&SerializationType::Json) != &SerializationType::Custom
});
let has_postcard = state
.records
.iter()
.any(|r| r.serialization.as_ref() == Some(&SerializationType::Postcard));
let has_observable = state.records.iter().any(|r| r.observable.is_some());
let mut data_contracts_features = Vec::new();
if has_non_custom_ser {
data_contracts_features.push("\"linkable\"");
}
let dc_features_str = if data_contracts_features.is_empty() {
String::new()
} else {
format!(", features = [{}]", data_contracts_features.join(", "))
};
// Build std feature deps
let mut std_deps = vec!["\"aimdb-data-contracts/std\"".to_string()];
if has_non_custom_ser && !has_postcard {
std_deps.push("\"serde_json\"".to_string());
}
if has_observable {
std_deps.push("\"aimdb-data-contracts/observable\"".to_string());
}
let std_features = std_deps.join(", ");
let mut optional_deps = String::new();
if has_non_custom_ser && !has_postcard {
optional_deps.push_str("serde_json = { version = \"1.0\", optional = true }\n");
}
if has_postcard {
optional_deps.push_str(
"postcard = { version = \"1.0\", default-features = false, features = [\"alloc\"] }\n",
);
}
format!(
r#"# Regenerate with `aimdb generate --common-crate`
[package]
name = "{crate_name}"
version = "0.1.0"
edition = "{edition}"
[features]
default = ["std"]
std = [{std_features}]
alloc = []
[dependencies]
aimdb-core = {{ version = "0.5", default-features = false, features = ["derive", "alloc"] }}
aimdb-data-contracts = {{ version = "0.5", default-features = false{dc_features_str} }}
serde = {{ version = "1.0", default-features = false, features = ["derive", "alloc"] }}
{optional_deps}"#
)
}
/// Generate `lib.rs` content for a common crate.
pub fn generate_lib_rs() -> String {
"\
// Regenerate with `aimdb generate --common-crate`
#![cfg_attr(not(feature = \"std\"), no_std)]
extern crate alloc;
mod schema;
// Re-export all public types for downstream crates
pub use schema::*;
"
.to_string()
}
// ── Binary crate generators ───────────────────────────────────────────────────
/// Generate `src/main.rs` for the named binary crate.
///
/// Uses `quote!` + `prettyplease` for guaranteed idiomatic formatting.
/// Requires the binary to exist in `state.binaries`. Returns `None` if not found.
pub fn generate_main_rs(state: &ArchitectureState, binary_name: &str) -> Option<String> {
let bin = state.binaries.iter().find(|b| b.name == binary_name)?;
let project_name = state
.project
.as_ref()
.map(|p| p.name.as_str())
.unwrap_or("project");
let common_crate = format_ident!("{}", format!("{}_common", project_name.replace('-', "_")));
// Collect tasks belonging to this binary
let tasks: Vec<&TaskDef> = bin
.tasks
.iter()
.filter_map(|tname| state.tasks.iter().find(|t| &t.name == tname))
.collect();
let task_use_idents: Vec<syn::Ident> = bin
.tasks
.iter()
.map(|name| format_ident!("{}", name))
.collect();
// ── Connector use statements ─────────────────────────────────────────
let connector_use_stmts: Vec<TokenStream> = bin
.external_connectors
.iter()
.filter_map(|c| match c.protocol.as_str() {
"mqtt" => Some(quote! { use aimdb_mqtt_connector::MqttConnector; }),
"knx" => Some(quote! { use aimdb_knx_connector::KnxConnector; }),
"ws" => Some(quote! { use aimdb_websocket_connector::WebSocketConnector; }),
_ => None,
})
.collect();
// ── Connector env-var bindings + construction ────────────────────────
let connector_let_stmts: Vec<TokenStream> = bin
.external_connectors
.iter()
.map(|c| {
let var_ident = format_ident!("{}", c.env_var.to_lowercase());
let var_name = &c.env_var;
let default = &c.default;
let ctor: TokenStream = match c.protocol.as_str() {
"mqtt" => quote! { MqttConnector::new(&#var_ident) },
"knx" => quote! { KnxConnector::new(&#var_ident) },
"ws" => quote! {
WebSocketConnector::new()
.bind(#var_ident.parse::<std::net::SocketAddr>()
.expect("invalid WebSocket bind address"))
.path("/ws")
},
_ => {
let msg = format!("build connector for protocol '{}'", c.protocol);
quote! { todo!(#msg) }
}
};
let connector_ident = format_ident!("{}_connector", c.protocol);
quote! {
let #var_ident = std::env::var(#var_name)
.unwrap_or_else(|_| #default.to_string());
let #connector_ident = #ctor;
}
})
.collect();
// ── .with_connector(...) chain calls ─────────────────────────────────
let with_connector_calls: Vec<TokenStream> = bin
.external_connectors
.iter()
.map(|c| {
let connector_ident = format_ident!("{}_connector", c.protocol);
quote! { .with_connector(#connector_ident) }
})
.collect();
// ── Task source registrations ────────────────────────────────────────
let task_registrations: Vec<TokenStream> = tasks
.iter()
.flat_map(|task| {
task.outputs.iter().flat_map(move |output| {
let variants: Vec<String> = if output.variants.is_empty() {
state
.records
.iter()
.find(|r| r.name == output.record)
.map(|r| r.key_variants.clone())
.unwrap_or_default()
} else {
output.variants.clone()
};
let value_type = format_ident!("{}Value", output.record);
let key_type = format_ident!("{}Key", output.record);
let task_fn = format_ident!("{}", task.name);
variants.into_iter().map(move |variant| {
let variant_ident = format_ident!("{}", to_pascal_case(&variant));
quote! {
builder.configure::<#value_type>(#key_type::#variant_ident, |reg| {
reg.source(#task_fn);
});
}
})
})
})
.collect();
// ── Assemble via quote! ──────────────────────────────────────────────
let file_tokens = quote! {
use aimdb_core::{AimDbBuilder, DbResult};
use aimdb_tokio_adapter::TokioAdapter;
#(#connector_use_stmts)*
use std::sync::Arc;
use #common_crate::configure_schema;
mod tasks;
use tasks::{#(#task_use_idents),*};
#[tokio::main]
async fn main() -> DbResult<()> {
tracing_subscriber::fmt::init();
#(#connector_let_stmts)*
let runtime = Arc::new(TokioAdapter::new());
let mut builder = AimDbBuilder::new()
.runtime(runtime)
#(#with_connector_calls)*
;
configure_schema(&mut builder);
#(#task_registrations)*
builder.run().await
}
};
let header = format!(
"// @generated — do not edit manually.\n\
// Source: .aimdb/state.toml\n\
// Regenerate: `aimdb generate --binary {binary_name}`\n\n"
);
let syntax_tree =
syn::parse2(file_tokens).expect("generate_main_rs: tokens should be valid Rust");
Some(format!("{header}{}", prettyplease::unparse(&syntax_tree)))
}
/// Generate `src/tasks.rs` scaffold for the named binary crate.
///
/// Uses `quote!` + `prettyplease` for guaranteed idiomatic formatting.
/// This file is generated **once** — it has no `@generated` header and is
/// then owned by the developer. Signatures must not be changed.
/// Returns `None` if the binary is not found.
pub fn generate_tasks_rs(state: &ArchitectureState, binary_name: &str) -> Option<String> {
let bin = state.binaries.iter().find(|b| b.name == binary_name)?;
let project_name = state
.project
.as_ref()
.map(|p| p.name.as_str())
.unwrap_or("project");
let common_crate = format_ident!("{}", format!("{}_common", project_name.replace('-', "_")));
// Collect tasks belonging to this binary
let tasks: Vec<&TaskDef> = bin
.tasks
.iter()
.filter_map(|tname| state.tasks.iter().find(|t| &t.name == tname))
.collect();
let task_fns: Vec<TokenStream> = tasks
.iter()
.map(|task| {
let fn_name = format_ident!("{}", task.name);
// Build parameter list
let mut params: Vec<TokenStream> = vec![quote! { ctx: RuntimeContext<TokioAdapter> }];
for input in &task.inputs {
let arg_name = format_ident!("{}", to_snake_case(&input.record));
let value_type = format_ident!("{}Value", input.record);
params.push(quote! { #arg_name: Consumer<#value_type> });
}
for output in &task.outputs {
let arg_name = format_ident!("{}", to_snake_case(&output.record));
let value_type = format_ident!("{}Value", output.record);
params.push(quote! { #arg_name: Producer<#value_type> });
}
let todo_msg = match &task.task_type {
TaskType::Agent => "LLM agent stub — implement reasoning loop".to_string(),
_ => format!("implement: {}", task.description),
};
let doc_attr = if task.description.is_empty() {
quote! {}
} else {
let desc = &task.description;
quote! { #[doc = #desc] }
};
quote! {
#doc_attr
pub async fn #fn_name(#(#params),*) -> DbResult<()> {
todo!(#todo_msg)
}
}
})
.collect();
let file_tokens = quote! {
use aimdb_core::{Consumer, DbResult, Producer, RuntimeContext};
use aimdb_tokio_adapter::TokioAdapter;
use #common_crate::*;
#(#task_fns)*
};
let header = format!(
"// Implement the task bodies; signatures must not change.\n\
// Regenerate with `aimdb generate --binary {binary_name} --tasks-scaffold`\n\
// (only writes this file if it does not already exist)\n\n"
);
let syntax_tree =
syn::parse2(file_tokens).expect("generate_tasks_rs: tokens should be valid Rust");
Some(format!("{header}{}", prettyplease::unparse(&syntax_tree)))
}
/// Generate `Cargo.toml` content for a binary crate.
///
/// Derives dependencies from the binary's tasks and external connectors.
/// Returns `None` if the binary is not found.
pub fn generate_binary_cargo_toml(state: &ArchitectureState, binary_name: &str) -> Option<String> {
let bin = state.binaries.iter().find(|b| b.name == binary_name)?;
let project_name = state
.project
.as_ref()
.map(|p| p.name.as_str())
.unwrap_or("project");
let common_crate_name = format!("{project_name}-common");
let common_crate_dep = common_crate_name.replace('-', "_");
let edition = state
.project
.as_ref()
.and_then(|p| p.edition.as_deref())
.unwrap_or("2024");
let has_mqtt = bin.external_connectors.iter().any(|c| c.protocol == "mqtt");
let has_knx = bin.external_connectors.iter().any(|c| c.protocol == "knx");
let has_ws = bin.external_connectors.iter().any(|c| c.protocol == "ws");
let mut optional_connector_deps = String::new();
if has_mqtt {
optional_connector_deps.push_str(
"aimdb-mqtt-connector = { version = \"0.5\", features = [\"tokio-runtime\"] }\n",
);
}
if has_knx {
optional_connector_deps.push_str(
"aimdb-knx-connector = { version = \"0.5\", features = [\"tokio-runtime\"] }\n",
);
}
if has_ws {
optional_connector_deps.push_str(
"aimdb-websocket-connector = { version = \"0.5\", features = [\"tokio-runtime\"] }\n",
);
}
let out = format!(
"# @generated — do not edit manually.\n\
# Source: .aimdb/state.toml — regenerate with `aimdb generate --binary {binary_name}`\n\
[package]\n\
name = \"{binary_name}\"\n\
version = \"0.1.0\"\n\
edition = \"{edition}\"\n\
\n\
[[bin]]\n\
name = \"{binary_name}\"\n\
path = \"src/main.rs\"\n\
\n\
[dependencies]\n\
{common_crate_dep} = {{ path = \"../{common_crate_name}\" }}\n\
aimdb-core = {{ version = \"0.5\" }}\n\
aimdb-tokio-adapter = {{ version = \"0.5\", features = [\"tokio-runtime\"] }}\n\
{optional_connector_deps}\
tokio = {{ version = \"1\", features = [\"full\"] }}\n\
tracing = \"0.1\"\n\
tracing-subscriber = {{ version = \"0.3\", features = [\"env-filter\"] }}\n"
);
Some(out)
}
/// Imports for the types-only common crate schema — no runtime deps.
fn emit_imports_types_only(state: &ArchitectureState) -> TokenStream {
let has_non_custom_ser = state.records.iter().any(|r| {
r.serialization.as_ref().unwrap_or(&SerializationType::Json) != &SerializationType::Custom
});
let has_observable = state.records.iter().any(|r| r.observable.is_some());
let has_settable = state
.records
.iter()
.any(|r| r.fields.iter().any(|f| f.settable));
let mut contract_traits: Vec<TokenStream> = vec![quote! { SchemaType }];
if has_non_custom_ser {
contract_traits.push(quote! { Linkable });
}
if has_observable {
contract_traits.push(quote! { Observable });
}
if has_settable {
contract_traits.push(quote! { Settable });
}
quote! {
use aimdb_core::RecordKey;
use aimdb_data_contracts::{#(#contract_traits),*};
use serde::{Deserialize, Serialize};
}
}
/// Imports for the full flat schema — includes runtime registration deps.
fn emit_imports(state: &ArchitectureState) -> TokenStream {
let has_non_custom_ser = state.records.iter().any(|r| {
r.serialization.as_ref().unwrap_or(&SerializationType::Json) != &SerializationType::Custom
});
let has_observable = state.records.iter().any(|r| r.observable.is_some());
let has_settable = state
.records
.iter()
.any(|r| r.fields.iter().any(|f| f.settable));
// Build aimdb_data_contracts trait imports
let mut contract_traits: Vec<TokenStream> = vec![quote! { SchemaType }];
if has_non_custom_ser {
contract_traits.push(quote! { Linkable });
}
if has_observable {
contract_traits.push(quote! { Observable });
}
if has_settable {
contract_traits.push(quote! { Settable });
}
quote! {
use aimdb_core::buffer::BufferCfg;
use aimdb_core::builder::AimDbBuilder;
use aimdb_core::RecordKey;
use aimdb_data_contracts::{#(#contract_traits),*};
use aimdb_executor::RuntimeAdapter;
use serde::{Deserialize, Serialize};
}
}
// ── Value struct ──────────────────────────────────────────────────────────────
fn emit_value_struct(rec: &RecordDef) -> TokenStream {
let struct_name = format_ident!("{}Value", rec.name);
let doc = format!("Value type for `{}`.", rec.name);
let fields: Vec<TokenStream> = if rec.fields.is_empty() {
vec![emit_todo_field(
"add fields — use `propose_record` to define them via the architecture agent",
)]
} else {
rec.fields
.iter()
.map(|f| {
let fname = format_ident!("{}", f.name);
let ftype: syn::Type = syn::parse_str(&f.field_type).unwrap_or_else(|_| {
panic!("invalid type `{}` for field `{}`", f.field_type, f.name)
});
if f.description.is_empty() {
quote! { pub #fname: #ftype, }
} else {
let desc = &f.description;
quote! {
#[doc = #desc]
pub #fname: #ftype,
}
}
})
.collect()
};
quote! {
#[doc = #doc]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct #struct_name {
#(#fields)*
}
}
}
/// Emit a dummy field with a TODO doc comment (for records with no fields yet).
fn emit_todo_field(msg: &str) -> TokenStream {
let doc = format!("TODO: {msg}");
quote! {
#[doc = #doc]
pub _placeholder: (),
}
}
// ── Key enum ──────────────────────────────────────────────────────────────────
fn emit_key_enum(rec: &RecordDef) -> TokenStream {
let enum_name = format_ident!("{}Key", rec.name);
// The RecordKey derive macro supports a single #[link_address] attribute.
// We use the first connector for that; additional connectors are resolved
// via standalone helper functions emitted by `emit_connector_address_fns`.
let connector = rec.connectors.first();
let key_prefix_attr = if !rec.key_prefix.is_empty() {
let prefix = &rec.key_prefix;
quote! { #[key_prefix = #prefix] }
} else {
quote! {}
};
let variants: Vec<TokenStream> = if rec.key_variants.is_empty() {
let doc = "TODO: add key variants — use the architecture agent to resolve them";
vec![quote! {
#[doc = #doc]
_Placeholder,
}]
} else {
rec.key_variants
.iter()
.map(|variant_str| {
let variant_name = format_ident!("{}", to_pascal_case(variant_str));
let link_attr = connector.map(|conn| {
let addr = conn.url.replace("{variant}", variant_str);
quote! { #[link_address = #addr] }
});
quote! {
#[key = #variant_str]
#link_attr
#variant_name,
}
})
.collect()
};
let address_fns = emit_connector_address_fns(rec);
quote! {
#[derive(Debug, RecordKey, Clone, Copy, PartialEq, Eq)]
#key_prefix_attr
pub enum #enum_name {
#(#variants)*
}
#address_fns
}
}
/// Emit standalone address-resolver functions for connectors beyond the first.
///
/// The first connector's addresses are baked into `#[link_address]` on the key
/// enum and exposed via the `RecordKey::link_address()` trait method. Additional
/// connectors get a `fn {record_snake}_{protocol}_address(key: &{Record}Key) -> Option<&'static str>`
/// function that the configure block can call.
fn emit_connector_address_fns(rec: &RecordDef) -> TokenStream {
if rec.connectors.len() <= 1 || rec.key_variants.is_empty() {
return quote! {};
}
let key_type = format_ident!("{}Key", rec.name);
let record_snake = to_snake_case(&rec.name);
let fns: Vec<TokenStream> = rec
.connectors
.iter()
.skip(1) // first connector uses link_address()
.map(|conn| {
let fn_name = format_ident!("{}_{}_address", record_snake, conn.protocol);
let doc = format!(
"Link address for `{}` — {} connector (`{}`).",
rec.name,
conn.protocol,
conn.direction_label(),
);
let arms: Vec<TokenStream> = rec
.key_variants
.iter()
.map(|variant_str| {
let variant_ident = format_ident!("{}", to_pascal_case(variant_str));
let addr = conn.url.replace("{variant}", variant_str);
quote! { #key_type::#variant_ident => Some(#addr), }
})
.collect();
quote! {
#[doc = #doc]
pub fn #fn_name(key: &#key_type) -> Option<&'static str> {
match key {
#(#arms)*
}
}
}
})
.collect();
quote! { #(#fns)* }
}
// ── configure_schema ──────────────────────────────────────────────────────────
fn emit_configure_schema(state: &ArchitectureState) -> TokenStream {
let record_blocks: Vec<TokenStream> = state
.records
.iter()
.map(emit_record_configure_block)
.collect();
quote! {
/// Register all architecture-agent-defined records on the builder.
///
/// Generated from `.aimdb/state.toml`. Configures buffer types and connector
/// addresses. Producers, consumers, serializers, and deserializers contain
/// business logic and must be provided by application code — they are not
/// generated here.
pub fn configure_schema<R: RuntimeAdapter + 'static>(builder: &mut AimDbBuilder<R>) {
#(#record_blocks)*
}
}
}
fn emit_record_configure_block(rec: &RecordDef) -> TokenStream {
if rec.key_variants.is_empty() {
let msg = format!("TODO: {}: no key variants defined yet", rec.name);
return quote! {
// #msg — placeholder
let _ = (#msg,);
};
}
let value_type = format_ident!("{}Value", rec.name);
let key_type = format_ident!("{}Key", rec.name);
let buffer_tokens = rec.buffer.to_tokens(rec.capacity);
let variant_idents: Vec<syn::Ident> = rec
.key_variants
.iter()
.map(|v| format_ident!("{}", to_pascal_case(v)))
.collect();
let is_custom = rec
.serialization
.as_ref()
.map(|s| s == &SerializationType::Custom)
.unwrap_or(false);
if rec.connectors.is_empty() {
// No connectors: just buffer
return quote! {
for key in [
#(#key_type::#variant_idents,)*
] {
builder.configure::<#value_type>(key, |reg| {
reg.buffer(#buffer_tokens);
});
}
};
}
// ── Pre-extract addresses ────────────────────────────────────────────
// First connector uses `key.link_address()` (from RecordKey derive).
// Additional connectors use generated helper functions.
let record_snake = to_snake_case(&rec.name);
let addr_extractions: Vec<TokenStream> = rec
.connectors
.iter()
.enumerate()
.map(|(i, conn)| {
let addr_var = format_ident!("addr_{}", i);
if i == 0 {
quote! {
let #addr_var = key.link_address().map(|s| s.to_string());
}
} else {
let resolver_fn = format_ident!("{}_{}_address", record_snake, conn.protocol);
quote! {
let #addr_var = #resolver_fn(&key).map(|s| s.to_string());
}
}
})
.collect();
// ── Build the configure closure body ─────────────────────────────────
//
// `reg.buffer()` consumes the `&mut` borrow and returns a builder, so
// everything must be a single fluent chain starting from `reg.buffer(...)`.
// We build two branches: one with connectors wired (when all addresses
// resolve), one plain buffer fallback.
let linked_chain =
emit_connector_chain(&rec.connectors, &value_type, &buffer_tokens, is_custom);
let addr_conditions: Vec<TokenStream> = (0..rec.connectors.len())
.map(|i| {
let addr_var = format_ident!("addr_{}", i);
quote! { #addr_var.as_deref() }
})
.collect();
// For a single connector: `if let Some(addr) = addr_0.as_deref() { chain } else { buffer }`
// For multiple connectors: nest or tuple-match the conditions.
let body = if rec.connectors.len() == 1 {
let cond = &addr_conditions[0];
quote! {
if let Some(addr_0) = #cond {
#linked_chain
} else {
reg.buffer(#buffer_tokens);
}
}
} else {
// Multiple connectors: match a tuple of Options.
// When ALL addresses are present, wire the full chain.
// Otherwise fall back to buffer-only.
let some_bindings: Vec<TokenStream> = (0..rec.connectors.len())
.map(|i| {
let binding = format_ident!("addr_{}", i);
quote! { Some(#binding) }
})
.collect();
quote! {
match (#(#addr_conditions),*) {
(#(#some_bindings),*) => {
#linked_chain
}
_ => {
reg.buffer(#buffer_tokens);
}
}
}
};
quote! {
for key in [
#(#key_type::#variant_idents,)*
] {
#(#addr_extractions)*
builder.configure::<#value_type>(key, |reg| {
#body
});
}
}
}
/// Build the full fluent chain: `reg.buffer(...).link_X(addr_0)...link_Y(addr_1)...`
///
/// All connector links are chained off a single `reg.buffer()` call so there
/// is only one mutable borrow of `reg`. Address variables `addr_0`, `addr_1`,
/// etc. are assumed to be in scope as `&str`.
fn emit_connector_chain(
connectors: &[ConnectorDef],
value_type: &syn::Ident,
buffer_tokens: &TokenStream,
is_custom: bool,
) -> TokenStream {
// Start the chain with reg.buffer(...)
let mut chain = quote! { reg.buffer(#buffer_tokens) };
for (i, conn) in connectors.iter().enumerate() {
let addr_var = format_ident!("addr_{}", i);
if is_custom {
let todo_comment = match conn.direction {
ConnectorDirection::Outbound => {
"TODO: chain .link_to(...).with_serializer(...) — serialization = \"custom\""
}
ConnectorDirection::Inbound => {
"TODO: chain .link_from(...).with_deserializer(...) — serialization = \"custom\""
}
};
// Can't chain a TODO into the builder, so just emit a let-binding comment
// after the chain. We'll terminate the chain with `;` below.
chain = quote! {
#chain;
let _ = (#todo_comment, #addr_var)
};
} else {
match conn.direction {
ConnectorDirection::Inbound => {
chain = quote! {
#chain
.link_from(#addr_var)
.with_deserializer(#value_type::from_bytes)
.finish()
};
}
ConnectorDirection::Outbound => {
chain = quote! {
#chain
.link_to(#addr_var)
.with_serializer_raw(|v: &#value_type| {
v.to_bytes()
.map_err(|_| aimdb_core::connector::SerializeError::InvalidData)
})
.finish()
};
}
}
}
}
// Terminate the chain
quote! { #chain; }
}
// ── Trait implementations ────────────────────────────────────────────────────
fn emit_schema_type_impl(rec: &RecordDef) -> TokenStream {
let struct_name = format_ident!("{}Value", rec.name);
let schema_name = to_snake_case(&rec.name);
let version = proc_macro2::Literal::u32_unsuffixed(rec.schema_version.unwrap_or(1));
quote! {
impl SchemaType for #struct_name {
const NAME: &'static str = #schema_name;
const VERSION: u32 = #version;
}
}
}
fn emit_linkable_impl(rec: &RecordDef) -> TokenStream {
let ser = rec
.serialization
.as_ref()
.unwrap_or(&SerializationType::Json);
match ser {
SerializationType::Custom => quote! {},
SerializationType::Json => emit_linkable_json(rec),
SerializationType::Postcard => emit_linkable_postcard(rec),
}
}
fn emit_linkable_json(rec: &RecordDef) -> TokenStream {
let struct_name = format_ident!("{}Value", rec.name);
quote! {
impl Linkable for #struct_name {
fn to_bytes(&self) -> Result<alloc::vec::Vec<u8>, alloc::string::String> {
#[cfg(feature = "std")]
{
serde_json::to_vec(self)
.map_err(|e| alloc::format!("serialize {}: {e}", Self::NAME))
}
#[cfg(not(feature = "std"))]
{
Err(alloc::string::String::from(
"no_std serialization not available — enable the std feature or use postcard",
))
}
}
fn from_bytes(data: &[u8]) -> Result<Self, alloc::string::String> {
#[cfg(feature = "std")]
{
serde_json::from_slice(data)
.map_err(|e| alloc::format!("deserialize {}: {e}", Self::NAME))
}
#[cfg(not(feature = "std"))]
{
let _ = data;
Err(alloc::string::String::from(
"no_std deserialization not available — enable the std feature or use postcard",
))
}
}
}
}
}
fn emit_linkable_postcard(rec: &RecordDef) -> TokenStream {
let struct_name = format_ident!("{}Value", rec.name);
quote! {
impl Linkable for #struct_name {
fn to_bytes(&self) -> Result<alloc::vec::Vec<u8>, alloc::string::String> {
postcard::to_allocvec(self)
.map_err(|e| alloc::format!("serialize {}: {e}", Self::NAME))
}
fn from_bytes(data: &[u8]) -> Result<Self, alloc::string::String> {
postcard::from_bytes(data)
.map_err(|e| alloc::format!("deserialize {}: {e}", Self::NAME))
}
}