-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen_elixir.rs
More file actions
2519 lines (2281 loc) · 83.1 KB
/
Copy pathcodegen_elixir.rs
File metadata and controls
2519 lines (2281 loc) · 83.1 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2026 Jonathan D.A. Jewell (hyperpolymath) <j.d.a.jewell@open.ac.uk>
//
// 007 Agent Meta-Language — Elixir/OTP Code Generator
//
// Compiles the 007 AST into a runnable Elixir/OTP project:
// - Agents become GenServer modules
// - Supervisors become Supervisor modules
// - Functions, DataBindings, TypeDecls become library modules
// - Protocols become Behaviour modules
// - An Application module boots the OTP tree
// - A mix.exs and config/config.exs are generated
//
// The Harvard Architecture invariant (Data vs Control) is preserved
// in the generated code: DataExpr maps to pure Elixir expressions,
// ControlExpr maps to effectful GenServer interactions.
use serde::{Deserialize, Serialize};
use crate::ast::*;
// ============================================================
// Output types
// ============================================================
/// A complete generated Elixir project.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElixirProject {
/// All generated .ex source files.
pub files: Vec<ElixirFile>,
/// The contents of mix.exs.
pub mix_exs: String,
/// The contents of config/config.exs.
pub config: String,
}
/// A single generated Elixir source file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElixirFile {
/// Relative path from project root (e.g. "lib/my_app/agents/reviewer.{}", "ex").
pub path: String,
/// The full Elixir source text.
pub content: String,
}
/// Errors that can occur during code generation.
#[derive(Debug)]
pub enum CodegenError {
/// A 007 construct that has no direct Elixir representation.
UnsupportedConstruct(String),
}
impl std::fmt::Display for CodegenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CodegenError::UnsupportedConstruct(s) => write!(f, "Unsupported: {}", s),
}
}
}
impl std::error::Error for CodegenError {}
// ============================================================
// Generation context
// ============================================================
/// Internal context threaded through code generation.
pub struct GenContext {
/// Snake-case project name (e.g. "my_app").
project_name: String,
/// PascalCase project module prefix (e.g. "MyApp").
project_module: String,
/// Fully-qualified Functions module (e.g. "MyApp.Functions").
functions_module: String,
/// Fully-qualified Data module (e.g. "MyApp.Data").
#[allow(dead_code)]
data_module: String,
}
impl GenContext {
fn new(project_name: &str) -> Self {
let snake = to_snake_case(project_name);
let pascal = to_pascal_case(project_name);
Self {
project_name: snake.clone(),
project_module: pascal.clone(),
functions_module: format!("{}.Functions", pascal),
data_module: format!("{}.Data", pascal),
}
}
}
// ============================================================
// Main entry point
// ============================================================
/// Generate a complete Elixir/OTP project from a 007 AST.
///
/// Walks every `TopLevelDecl` in `program` and produces:
/// - One GenServer file per Agent
/// - One Supervisor file per Supervisor
/// - Collected Functions, DataBindings, TypeDecls modules
/// - Protocol/Behaviour modules
/// - Application module
/// - mix.exs and config/config.exs
pub fn generate_elixir(
program: &Program,
project_name: &str,
) -> Result<ElixirProject, CodegenError> {
let ctx = GenContext::new(project_name);
let mut files: Vec<ElixirFile> = Vec::new();
let mut functions: Vec<&FunctionDecl> = Vec::new();
let mut data_bindings: Vec<&DataBinding> = Vec::new();
let mut type_decls: Vec<&TypeDeclNode> = Vec::new();
let mut supervisors: Vec<&SupervisorDecl> = Vec::new();
let mut supervisor_names: Vec<String> = Vec::new();
let mut locales: Vec<&LocaleDecl> = Vec::new();
for decl in &program.declarations {
match decl {
TopLevelDecl::Agent(agent) => {
files.push(gen_agent(agent, &ctx));
}
TopLevelDecl::Supervisor(sup) => {
supervisors.push(sup);
supervisor_names.push(sup.name.clone());
files.push(gen_supervisor(sup, &ctx));
}
TopLevelDecl::Function(func) => {
functions.push(func);
}
TopLevelDecl::DataBinding(db) => {
data_bindings.push(db);
}
TopLevelDecl::Sentinel(_) => {
// Sentinels are compile-time only; no Elixir output
}
TopLevelDecl::TypeDecl(td) => {
type_decls.push(td);
}
TopLevelDecl::Protocol(proto) => {
files.push(gen_protocol(proto, &ctx));
}
TopLevelDecl::Behaviour(beh) => {
files.push(gen_behaviour(beh, &ctx));
}
TopLevelDecl::Choreography(choreo) => {
// Choreographies are global coordination protocols.
// They don't have a direct Elixir equivalent; emit a
// documentation module describing the protocol.
files.push(gen_choreography_doc(choreo, &ctx));
}
TopLevelDecl::Locale(locale) => {
locales.push(locale);
}
TopLevelDecl::Import(_) => {
// Imports are resolved at 007 compile time.
// No Elixir artifact needed.
}
TopLevelDecl::Discourse(_) => {
// Discourse blocks are type-checker directives; no Elixir output.
}
TopLevelDecl::Macro(_) => {
// Macros are expanded at compile time.
}
TopLevelDecl::DslBlock(_) => {
// DSL blocks are handled by external toolchains.
}
}
}
// Collected modules
if !functions.is_empty() {
files.push(gen_functions_module(&functions, &ctx));
}
if !data_bindings.is_empty() {
files.push(gen_data_module(&data_bindings, &ctx));
}
if !type_decls.is_empty() {
files.push(gen_types_module(&type_decls, &ctx));
}
// Locale routing module (BEAM distribution)
if !locales.is_empty() {
files.push(gen_locale_module(&locales, &ctx));
}
// Application module
files.push(gen_application_module(&supervisor_names, &ctx));
// Standard library modules
files.extend(gen_stdlib_modules(&ctx));
let mix_exs = gen_mix_exs(&ctx);
let config = gen_config_exs();
// Validate all generated files before handing the project off.
if let Err(e) = validate_generated_files(&ctx, &files) {
log::error!("Generated Elixir project failed validation: {}", e);
}
Ok(ElixirProject {
files,
mix_exs,
config,
})
}
/// Validate the generated Elixir files before returning the project.
///
/// Checks that every file has a non-empty path and non-empty content. This
/// catches codegen bugs (empty module bodies, missing stdlib files) before
/// the project is handed to `mix compile`. The real compilation step belongs
/// to the BEAM toolchain — see `beam_roundtrip.rs` for that.
fn validate_generated_files(
_ctx: &GenContext,
files: &[ElixirFile],
) -> Result<(), Box<dyn std::error::Error>> {
for file in files {
if file.path.is_empty() {
return Err("Generated file has empty path".into());
}
if file.content.is_empty() {
return Err(format!("Generated file '{}' has empty content", file.path).into());
}
// Sanity-check that every file carries the SPDX header injected by the
// individual generators. If it's missing, something went wrong upstream.
if !file.content.contains("SPDX-License-Identifier") {
log::warn!(
"Generated file '{}' is missing SPDX header — codegen bug?",
file.path
);
}
}
log::debug!("validate_generated_files: {} files OK", files.len());
Ok(())
}
// ============================================================
// Locale Routing — BEAM Distribution
// ============================================================
/// Generate Elixir code for a LocaleExpr reference.
fn gen_locale_expr(expr: &LocaleExpr) -> String {
match expr {
LocaleExpr::Named(name) => format!(":{}", to_snake_case(name)),
LocaleExpr::Constructor(ctor) => gen_locale_constructor(ctor),
}
}
/// Generate Elixir code for a LocaleConstructor.
fn gen_locale_constructor(ctor: &LocaleConstructor) -> String {
match ctor {
LocaleConstructor::Local => ":local".to_string(),
LocaleConstructor::Gpu { device } => format!("{{:gpu, {}}}", device),
LocaleConstructor::Remote { url, model } => {
let url_str = url.as_deref().unwrap_or("localhost");
let model_str = model.as_deref().unwrap_or("default");
format!("{{:remote, \"{}\", \"{}\"}}", url_str, model_str)
}
LocaleConstructor::Edge { region, model } => {
let region_str = region.as_deref().unwrap_or("default");
let model_str = model.as_deref().unwrap_or("default");
format!("{{:edge, \"{}\", \"{}\"}}", region_str, model_str)
}
LocaleConstructor::Cluster { nodes, models: _ } => {
let node_list: Vec<String> = nodes.iter().map(|n| format!("\"{}\"", n)).collect();
format!("{{:cluster, [{}]}}", node_list.join(", "))
}
}
}
/// Generate the Oo7.Locale module — locale registry and migration dispatch.
///
/// This module maps locale names to BEAM distribution targets and provides
/// the `migrate/3` function that routes computation to the correct node.
fn gen_locale_module(locales: &[&LocaleDecl], ctx: &GenContext) -> ElixirFile {
let mut locale_entries = String::new();
for locale in locales {
let ctor = gen_locale_constructor(&locale.constructor);
locale_entries.push_str(&format!(
" def resolve(:{}), do: {}\n",
to_snake_case(&locale.name),
ctor
));
}
let content = format!(
r#"defmodule {prefix}.Locale do
@moduledoc """
Locale registry and migration dispatch for 007 agents.
Maps locale names to BEAM distribution targets (nodes, GPU devices,
remote endpoints) and provides migrate/3 for transparent locale routing.
Generated by the 007 MK2 compiler.
"""
# ---- Locale Registry ----
# Each locale declaration maps to a resolve/1 clause.
{entries} def resolve(locale), do: {{:error, :unknown_locale, locale}}
# ---- Migration Dispatch ----
@doc """
Migrate a computation to a target locale.
`expr_fn` is a zero-arity function capturing the expression to evaluate.
`from` and `to` are locale atoms or tuples resolved by resolve/1.
Returns the result of evaluating `expr_fn` at the target locale.
"""
def migrate(expr_fn, from, to) when is_function(expr_fn, 0) do
from_locale = resolve_locale(from)
to_locale = resolve_locale(to)
do_migrate(expr_fn, from_locale, to_locale)
end
defp resolve_locale(locale) when is_atom(locale), do: resolve(locale)
defp resolve_locale(locale) when is_tuple(locale), do: locale
# Local → Local: just execute in place.
defp do_migrate(expr_fn, _from, :local), do: expr_fn.()
# Any → GPU: execute locally with GPU device hint.
# In production, this would dispatch to Nx/EXLA with device placement.
defp do_migrate(expr_fn, _from, {{:gpu, device}}) do
# GPU dispatch — placeholder for Nx device placement.
# In production: Nx.default_backend({{EXLA.Backend, device_id: device}})
_device = device
expr_fn.()
end
# Any → Remote: dispatch via :rpc.call to the remote node.
defp do_migrate(expr_fn, _from, {{:remote, url, _model}}) do
node = url_to_node(url)
case Node.connect(node) do
true ->
:rpc.call(node, Kernel, :apply, [expr_fn, []])
false ->
{{:error, :node_unreachable, node}}
end
end
# Any → Edge: same as Remote but with region-based node selection.
defp do_migrate(expr_fn, _from, {{:edge, region, _model}}) do
node = region_to_node(region)
case Node.connect(node) do
true ->
:rpc.call(node, Kernel, :apply, [expr_fn, []])
false ->
{{:error, :node_unreachable, node}}
end
end
# Any → Cluster: load-balanced dispatch across cluster nodes.
defp do_migrate(expr_fn, _from, {{:cluster, nodes}}) do
# Round-robin node selection via :erlang.phash2.
index = :erlang.phash2(make_ref(), length(nodes))
node_url = Enum.at(nodes, index)
node = url_to_node(node_url)
case Node.connect(node) do
true ->
:rpc.call(node, Kernel, :apply, [expr_fn, []])
false ->
# Fallback: try next node.
fallback_node = url_to_node(Enum.at(nodes, rem(index + 1, length(nodes))))
case Node.connect(fallback_node) do
true -> :rpc.call(fallback_node, Kernel, :apply, [expr_fn, []])
false -> {{:error, :cluster_unreachable, nodes}}
end
end
end
# Unknown locale type — execute locally with warning.
defp do_migrate(expr_fn, _from, _to) do
IO.warn("Unknown locale type — executing locally")
expr_fn.()
end
# ---- Helpers ----
defp url_to_node(url) when is_binary(url) do
# Convert URL to Erlang node name.
# "https://host.example.com" → :"oo7@host.example.com"
# "host.local" → :"oo7@host.local"
host = url
|> String.replace(~r/^https?:\/\//, "")
|> String.split("/")
|> List.first()
|> String.split(":")
|> List.first()
:"oo7@#{{host}}"
end
defp region_to_node(region) when is_binary(region) do
# Map region to a well-known edge node name.
:"oo7_edge@#{{region}}.edge.local"
end
end
"#,
prefix = ctx.project_module,
entries = locale_entries
);
ElixirFile {
path: format!("lib/{}/locale.ex", to_snake_case(&ctx.project_name)),
content,
}
}
/// Generate standard library modules.
fn gen_stdlib_modules(ctx: &GenContext) -> Vec<ElixirFile> {
vec![
gen_result_module(ctx),
gen_collections_module(ctx),
gen_stream_module(ctx),
gen_time_module(ctx),
]
}
// ============================================================
// Data expression codegen (Harvard: pure, total)
// ============================================================
/// Generate an Elixir expression from a 007 DataExpr.
///
/// DataExprs are total and pure — they map to simple Elixir literals
/// and pure function calls.
fn gen_data_expr(expr: &DataExpr) -> String {
match expr {
DataExpr::Int(n) => format!("{}", n),
DataExpr::Float(f) => {
if f.is_nan() {
":nan".to_string()
} else if f.is_infinite() {
if *f > 0.0 {
":infinity".to_string()
} else {
":neg_infinity".to_string()
}
} else {
// Ensure there's always a decimal point for Elixir
let s = format!("{}", f);
if s.contains('.') {
s
} else {
format!("{}.0", s)
}
}
}
DataExpr::String(s) => format!("\"{}\"", escape_elixir_string(s)),
DataExpr::Bool(b) => {
if *b {
"true".to_string()
} else {
"false".to_string()
}
}
DataExpr::Add(l, r) => {
format!("({} + {})", gen_data_expr(l), gen_data_expr(r))
}
DataExpr::Sub(l, r) => {
format!("({} - {})", gen_data_expr(l), gen_data_expr(r))
}
DataExpr::Mul(l, r) => {
format!("({} * {})", gen_data_expr(l), gen_data_expr(r))
}
DataExpr::Div(l, r) => {
// Elixir: use safe_div helper for totality (div by zero → nil)
format!("safe_div({}, {})", gen_data_expr(l), gen_data_expr(r))
}
DataExpr::Mod(l, r) => {
format!("safe_rem({}, {})", gen_data_expr(l), gen_data_expr(r))
}
DataExpr::Record(fields) => {
let inner: Vec<String> = fields
.iter()
.map(|(k, v)| format!("{}: {}", to_snake_case(k), gen_data_expr(v)))
.collect();
format!("%{{{}}}", inner.join(", "))
}
DataExpr::List(items) => {
let inner: Vec<String> = items.iter().map(gen_data_expr).collect();
format!("[{}]", inner.join(", "))
}
DataExpr::Rational(n, d) => format!("{{:rational, {}, {}}}", n, d),
DataExpr::Complex(r, i) => format!("{{:complex, {}, {}}}", r, i),
DataExpr::Symbolic(s) => format!("\"{}\"", escape_elixir_string(s)),
DataExpr::Min(l, r) => format!("min({}, {})", gen_data_expr(l), gen_data_expr(r)),
DataExpr::Max(l, r) => format!("max({}, {})", gen_data_expr(l), gen_data_expr(r)),
DataExpr::Or(l, r) => format!("({} or {})", gen_data_expr(l), gen_data_expr(r)),
DataExpr::Xor(l, r) => {
// Elixir XOR via Bitwise.bxor or boolean negation
format!("bxor({}, {})", gen_data_expr(l), gen_data_expr(r))
}
DataExpr::Var(name) => to_snake_case(name),
DataExpr::FieldAccess(expr, field) => {
format!(
"Map.get({}, :{})",
gen_data_expr(expr),
to_snake_case(field)
)
}
DataExpr::PureCall(name, args) => {
let arg_strs: Vec<String> = args.iter().map(gen_data_expr).collect();
format!(
"{}.{}({})",
"Functions",
to_snake_case(name),
arg_strs.join(", ")
)
}
}
}
// ============================================================
// Control expression codegen (Harvard: effectful)
// ============================================================
/// Generate an Elixir expression from a 007 ControlExpr.
///
/// ControlExprs may invoke side effects — sends, spawns, exchanges.
/// They map to GenServer calls and Elixir control flow.
pub fn gen_control_expr(expr: &ControlExpr, ctx: &GenContext) -> String {
match expr {
ControlExpr::DataLit(d) => gen_data_expr(d),
ControlExpr::Var(x) => to_snake_case(x),
ControlExpr::BinOp(l, op, r) => {
let left = gen_control_expr(l, ctx);
let right = gen_control_expr(r, ctx);
match op {
BinOp::Div => format!("div({}, {})", left, right),
BinOp::Mod => format!("rem({}, {})", left, right),
_ => format!("({} {} {})", left, elixir_binop(op), right),
}
}
ControlExpr::Call(name, args) => {
let arg_strs: Vec<String> = args.iter().map(|a| gen_control_expr(a, ctx)).collect();
format!(
"{}.{}({})",
ctx.functions_module,
to_snake_case(name),
arg_strs.join(", ")
)
}
ControlExpr::Constructor(name, args) => {
if args.is_empty() {
format!("{{:{}}}", to_snake_case(name))
} else {
let arg_strs: Vec<String> = args.iter().map(|a| gen_control_expr(a, ctx)).collect();
format!("{{:{}, {}}}", to_snake_case(name), arg_strs.join(", "))
}
}
ControlExpr::MethodCall(recv, method, args) => gen_method_call(recv, method, args, ctx),
ControlExpr::FieldAccess(expr, field) => {
format!(
"Map.get({}, :{})",
gen_control_expr(expr, ctx),
to_snake_case(field)
)
}
ControlExpr::Exchange(handle, message) => {
format!(
"GenServer.call({}, {{:exchange, {}}})",
gen_control_expr(handle, ctx),
gen_control_expr(message, ctx)
)
}
ControlExpr::Receive => {
"receive do\n msg -> msg\n after\n 0 -> nil\n end".to_string()
}
ControlExpr::Migrate { expr, from, to } => {
// Locale routing via BEAM distribution.
// Dispatches to Oo7.Locale.migrate/3 which uses :rpc.call
// for Remote/Edge/Cluster locales, local eval for Local/GPU.
let inner = gen_control_expr(expr, ctx);
let from_str = gen_locale_expr(from);
let to_str = gen_locale_expr(to);
format!(
"{}.Locale.migrate(fn -> {} end, {}, {})",
ctx.project_module, inner, from_str, to_str
)
}
ControlExpr::VerifyIntegrity(name) => {
format!("Oo7.Sentinel.verify({})", to_snake_case(name))
}
ControlExpr::QueryTrace { label, .. } => {
format!(
":ets.lookup(:oo7_traces, \"{}\") |> List.first()",
escape_elixir_string(label)
)
}
// Agent self-introspection — Harvard-safe (Control → Data)
ControlExpr::QueryCapabilities => "Process.get(:oo7_capabilities) || []".to_string(),
ControlExpr::QueryDiscourse => "Process.get(:oo7_discourse) || nil".to_string(),
ControlExpr::QueryBudget => "Process.get(:oo7_budget) || nil".to_string(),
ControlExpr::QueryStrategy => {
"Process.get(:oo7_strategy) || \"predicate_first\"".to_string()
}
ControlExpr::Record(fields) => {
let inner: Vec<String> = fields
.iter()
.map(|(k, v)| format!("{}: {}", to_snake_case(k), gen_control_expr(v, ctx)))
.collect();
format!("%{{{}}}", inner.join(", "))
}
ControlExpr::List(items) => {
let inner: Vec<String> = items.iter().map(|i| gen_control_expr(i, ctx)).collect();
format!("[{}]", inner.join(", "))
}
ControlExpr::Bridge { expr, from, to } => {
// Bridge passes a value across discourse boundaries.
// In Elixir, this is a no-op on the value — discourse semantics
// are handled at the type level. Emit a tagged tuple for tracing.
format!(
"{{:bridge, {}, :{}, :{}}}",
gen_control_expr(expr, ctx),
to_snake_case(from),
to_snake_case(to)
)
}
}
}
/// Map a 007 BinOp to its Elixir infix operator string.
///
/// Div and Mod are handled specially (function call form) in the caller.
fn elixir_binop(op: &BinOp) -> &'static str {
match op {
BinOp::Add => "+",
BinOp::Sub => "-",
BinOp::Mul => "*",
BinOp::Div => "div", // caller uses function form
BinOp::Mod => "rem", // caller uses function form
BinOp::Eq => "==",
BinOp::Neq => "!=",
BinOp::Lt => "<",
BinOp::Gt => ">",
BinOp::Lte => "<=",
BinOp::Gte => ">=",
BinOp::And => "and",
BinOp::Or => "or",
BinOp::Concat => "<>",
}
}
/// Generate Elixir for a method call, dispatching common methods
/// to appropriate Elixir standard library functions.
fn gen_method_call(
recv: &ControlExpr,
method: &str,
args: &[ControlExpr],
ctx: &GenContext,
) -> String {
let recv_str = gen_control_expr(recv, ctx);
match method {
"length" => format!(
"(if is_binary({}), do: String.length({}), else: length({}))",
recv_str, recv_str, recv_str
),
"to_upper" => format!("String.upcase({})", recv_str),
"to_lower" => format!("String.downcase({})", recv_str),
"get" => {
let idx = if args.is_empty() {
"0".to_string()
} else {
gen_control_expr(&args[0], ctx)
};
format!("Enum.at({}, {})", recv_str, idx)
}
"push" => {
let val = if args.is_empty() {
"nil".to_string()
} else {
gen_control_expr(&args[0], ctx)
};
format!("{} ++ [{}]", recv_str, val)
}
"keys" => format!("Map.keys({})", recv_str),
"id" => format!("inspect({})", recv_str),
_ => {
let arg_strs: Vec<String> = args.iter().map(|a| gen_control_expr(a, ctx)).collect();
format!("{}.{}({})", recv_str, method, arg_strs.join(", "))
}
}
}
// ============================================================
// Control statement codegen
// ============================================================
/// Generate Elixir source for a single ControlStmt.
///
/// Returns one or more lines of Elixir code at the given indentation level.
pub fn gen_control_stmt(stmt: &ControlStmt, ctx: &GenContext, indent: usize) -> String {
let ind = make_indent(indent);
match stmt {
ControlStmt::Let { pattern, value, .. } => {
format!(
"{}{} = {}",
ind,
gen_pattern(pattern),
gen_control_expr(value, ctx)
)
}
ControlStmt::Send { target, message } => {
format!(
"{}GenServer.cast({}, {{:receive, {}}})",
ind,
gen_control_expr(target, ctx),
gen_control_expr(message, ctx)
)
}
ControlStmt::SendFinal { target, message } => {
let target_str = gen_control_expr(target, ctx);
let msg_str = gen_control_expr(message, ctx);
format!(
"{}GenServer.cast({}, {{:receive, {}}})\n{}GenServer.stop({})",
ind, target_str, msg_str, ind, target_str
)
}
ControlStmt::Spawn {
binding,
agent_name,
..
} => {
format!(
"{}{{:ok, {}}} = {}.Agents.{}.start_link([])",
ind,
to_snake_case(binding),
ctx.project_module,
agent_name
)
}
ControlStmt::If {
condition,
then_body,
else_body,
} => {
let mut out = format!("{}if {} do\n", ind, gen_control_expr(condition, ctx));
out.push_str(&gen_stmts(then_body, ctx, indent + 1));
if !else_body.is_empty() {
out.push_str(&format!("\n{}else\n", ind));
out.push_str(&gen_stmts(else_body, ctx, indent + 1));
}
out.push_str(&format!("\n{}end", ind));
out
}
ControlStmt::Match { scrutinee, arms } => {
let mut out = format!("{}case {} do\n", ind, gen_control_expr(scrutinee, ctx));
for (pattern, body) in arms {
let pat_str = match pattern {
Pattern::Var(name) => to_snake_case(name),
_ => gen_pattern(pattern),
};
out.push_str(&format!("{} {} ->\n", ind, pat_str));
match body {
ControlExprOrBlock::Expr(e) => {
out.push_str(&format!("{} {}\n", ind, gen_control_expr(e, ctx)));
}
ControlExprOrBlock::Block(stmts, _trace) => {
out.push_str(&gen_stmts(stmts, ctx, indent + 2));
out.push('\n');
}
}
}
out.push_str(&format!("{}end", ind));
out
}
ControlStmt::Branch {
modifier,
traced,
arms,
} => gen_branch(modifier, traced, arms, ctx, indent),
ControlStmt::Loop { body, .. } => {
let mut out = format!(
"{}Stream.iterate(0, &(&1 + 1))\n\
{}|> Enum.reduce_while(nil, fn _, _acc ->\n\
{} try do\n",
ind, ind, ind
);
out.push_str(&gen_stmts(body, ctx, indent + 2));
out.push_str(&format!(
"\n{} {{:cont, nil}}\n\
{} catch\n\
{} {{:break, val}} -> {{:halt, val}}\n\
{} :continue -> {{:cont, nil}}\n\
{} end\n\
{}end)",
ind, ind, ind, ind, ind, ind
));
out
}
ControlStmt::Return(Some(expr)) => format!("{}{}", ind, gen_control_expr(expr, ctx)),
ControlStmt::Return(None) => format!("{}nil", ind),
ControlStmt::Break(Some(expr)) => {
format!("{}throw({{:break, {}}})", ind, gen_control_expr(expr, ctx))
}
ControlStmt::Break(None) => format!("{}throw({{:break, nil}})", ind),
ControlStmt::Continue => format!("{}throw(:continue)", ind),
ControlStmt::Reversible(body) => {
let mut out = format!("{}try do\n", ind);
out.push_str(&gen_stmts(body, ctx, indent + 1));
out.push_str(&format!(
"\n{}rescue\n{} e -> {{:error, e}}\n{}end",
ind, ind, ind
));
out
}
ControlStmt::Irreversible(body) => {
let mut out = format!("{}# irreversible block\n", ind);
out.push_str(&gen_stmts(body, ctx, indent));
out
}
ControlStmt::Reverse(body) => {
let mut out = format!("{}# reverse block\n", ind);
out.push_str(&gen_stmts(body, ctx, indent));
out
}
ControlStmt::ReversibleAs { binding, body } => {
let mut out = format!("{}# reversible as {}\n{}try do\n", ind, binding, ind);
out.push_str(&gen_stmts(body, ctx, indent + 1));
out.push_str(&format!(
"\n{}rescue\n{} e -> {{:error, e}}\n{}end",
ind, ind, ind
));
out
}
ControlStmt::ReverseNamed { target } => {
format!("{}# reverse {}", ind, target)
}
ControlStmt::EnterDiscourse { discourse, body } => {
// Discourse context — emit a comment and execute the body.
// Runtime discourse semantics are a future extension.
let mut out = format!("{}# enter discourse: {}\n", ind, discourse);
out.push_str(&gen_stmts(body, ctx, indent));
out
}
ControlStmt::Expr(e) => {
format!("{}{}", ind, gen_control_expr(e, ctx))
}
}
}
/// Generate a `branch` construct — the hermeneutic moment.
///
/// Maps to a cond block in Elixir. If `traced`, records the decision
/// in the ETS trace table. If `cached`, wraps with an ETS lookup.
/// If `speculative`, wraps arms in Task.async for parallel eval.
fn gen_branch(
modifier: &Option<BranchModifier>,
traced: &Option<String>,
arms: &[BranchArm],
ctx: &GenContext,
indent: usize,
) -> String {
let ind = make_indent(indent);
let mut out = String::new();
// For cached branches, check ETS first
if *modifier == Some(BranchModifier::Cached)
&& let Some(label) = traced
{
out.push_str(&format!(
"{}case :ets.lookup(:oo7_traces, \"{}\") do\n\
{} [{{_, cached_result}} | _] -> cached_result\n\
{} [] ->\n",
ind,
escape_elixir_string(label),
ind,
ind
));
}
let branch_indent = if *modifier == Some(BranchModifier::Cached) && traced.is_some() {
indent + 2
} else {
indent
};
let bi = make_indent(branch_indent);
if *modifier == Some(BranchModifier::Speculative) {
// Speculative: spawn Task.async for each arm, await first success
out.push_str(&format!("{}tasks = [\n", bi));
for arm in arms {
out.push_str(&format!(
"{} Task.async(fn ->\n\
{} # arm: {}\n",
bi, bi, arm.label
));
out.push_str(&gen_stmts(&arm.body, ctx, branch_indent + 2));
out.push_str(&format!("\n{} end),\n", bi));
}
out.push_str(&format!(
"{}]\n{}Task.await_many(tasks) |> List.first()",
bi, bi
));
} else {
// Standard or cached: cond block
out.push_str(&format!("{}cond do\n", bi));
for arm in arms {
let guard = gen_given_guard(&arm.given);
out.push_str(&format!("{} {} ->\n", bi, guard));
if let Some(label) = traced {
// Record trace
out.push_str(&format!(
"{} :ets.insert(:oo7_traces, {{\"{}\", \"{}\"}})\n",
bi,
escape_elixir_string(label),
escape_elixir_string(&arm.label)
));
}
out.push_str(&gen_stmts(&arm.body, ctx, branch_indent + 2));
out.push('\n');
}
out.push_str(&format!("{}end", bi));
}
// Close cached wrapper
if *modifier == Some(BranchModifier::Cached) && traced.is_some() {
out.push_str(&format!("\n{}end", ind));
}
out
}
/// Generate a guard expression from a GivenClause for use in cond arms.
///
/// If there is no given clause, returns "true" (unconditional arm).
fn gen_given_guard(given: &Option<GivenClause>) -> String {
match given {
None => "true".to_string(),
Some(clause) => {
let predicates: Vec<String> = clause
.items
.iter()
.filter_map(|item| match item {
GivenItem::Predicate { left, op, right } => {
let op_str = match op {
PredOp::Gt => ">",
PredOp::Lt => "<",
PredOp::Gte => ">=",
PredOp::Lte => "<=",
PredOp::Eq => "==",
PredOp::Neq => "!=",
};
Some(format!(
"{} {} {}",
gen_data_expr(left),
op_str,
gen_data_expr(right)
))
}
_ => None, // Named/Bare items are evidence, not guards
})
.collect();
if predicates.is_empty() {
"true".to_string()
} else {
predicates.join(" and ")
}
}
}
}
// ============================================================
// Pattern codegen
// ============================================================
/// Generate an Elixir pattern from a 007 Pattern.
fn gen_pattern(pattern: &Pattern) -> String {
match pattern {
Pattern::Var(name) => to_snake_case(name),
Pattern::Wildcard => "_".to_string(),
Pattern::Constructor(name, pats) => {
if pats.is_empty() {
format!("{{:{}}}", to_snake_case(name))
} else {
let inner: Vec<String> = pats.iter().map(gen_pattern).collect();
format!("{{:{}, {}}}", to_snake_case(name), inner.join(", "))
}
}
Pattern::Tuple(pats) => {
let inner: Vec<String> = pats.iter().map(gen_pattern).collect();
format!("{{{}}}", inner.join(", "))
}
Pattern::Literal(DataExpr::Int(n)) => format!("{}", n),
Pattern::Literal(DataExpr::String(s)) => {
format!("\"{}\"", escape_elixir_string(s))
}
Pattern::Literal(DataExpr::Bool(b)) => {
if *b {
"true".to_string()
} else {
"false".to_string()
}
}
Pattern::Literal(DataExpr::Float(f)) => format!("{}", f),