forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathast.rs
More file actions
1132 lines (1064 loc) · 35.3 KB
/
Copy pathast.rs
File metadata and controls
1132 lines (1064 loc) · 35.3 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
//! Abstract Syntax Tree definitions for Nulang.
use crate::types::{Capability, EffectRow, Span, Type, TypeVar};
use serde::{Deserialize, Serialize};
// ---------------------------------------------------------------------------
// Literals
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub enum Literal {
Int(i64),
Float(f64),
String(String),
Bool(bool),
Nil,
Unit,
}
// ---------------------------------------------------------------------------
// Patterns
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub enum Pattern {
Wild, // _
Var(String), // x
Lit(Literal), // 42, "hello"
Tuple(Vec<Pattern>), // (p1, p2)
Record(Vec<(String, Pattern)>), // { a: p1, b: p2 }
Variant(String, Option<Box<Pattern>>), // Some(x), None
Alias(String, Box<Pattern>), // x @ Pattern
}
// ---------------------------------------------------------------------------
// Expressions
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
/// Literal value
Literal(Literal, Span),
/// Variable reference
Var(String, Span),
/// Lambda: fn(x: T) -> e
Lambda {
params: Vec<(String, Option<Type>)>,
ret_type: Option<Type>,
body: Box<Expr>,
effect: Option<EffectRow>,
span: Span,
},
/// Function application: f(x, y)
App {
func: Box<Expr>,
args: Vec<Expr>,
span: Span,
},
/// Let binding: let x [: T] = e1 in e2.
/// `let_in` is true when the body is an explicit `in`-expression
/// (scoped to just the body); false for statement-let where the parser
/// folds subsequent block expressions into the body.
Let {
name: String,
ty: Option<Type>,
value: Box<Expr>,
body: Box<Expr>,
mutable: bool,
let_in: bool,
span: Span,
},
/// Let-rec: let rec f = e1 in e2
LetRec {
name: String,
params: Vec<(String, Option<Type>)>,
value: Box<Expr>,
body: Box<Expr>,
span: Span,
},
/// If/else (expression, not statement)
If {
cond: Box<Expr>,
then_branch: Box<Expr>,
else_branch: Option<Box<Expr>>,
span: Span,
},
/// Pattern match. Each arm is `(pattern, optional guard, body)`; the
/// guard is a boolean expression evaluated with the pattern's bindings
/// in scope after the pattern matches (`| pat if cond => body`).
Match {
scrutinee: Box<Expr>,
arms: Vec<(Pattern, Option<Expr>, Expr)>,
span: Span,
},
/// Block expression: { e1; e2 }
Block {
exprs: Vec<Expr>,
span: Span,
},
/// Tuple: (e1, e2)
Tuple(Vec<Expr>, Span),
/// Record literal: { a: e1, b: e2 }
Record(Vec<(String, Expr)>, Span),
/// Record field access: rec.field
FieldAccess {
expr: Box<Expr>,
field: String,
span: Span,
},
/// Record update: { base .. field = val, ... }
/// Creates a new record by shallow-copying `base` and overriding the
/// listed fields.
RecordUpdate {
base: Box<Expr>,
fields: Vec<(String, Expr)>,
span: Span,
},
Array(Vec<Expr>, Span),
/// Array index: arr[i]
Index {
arr: Box<Expr>,
idx: Box<Expr>,
span: Span,
},
/// Binary operator
Binary {
op: BinOp,
left: Box<Expr>,
right: Box<Expr>,
span: Span,
},
/// Unary operator
Unary {
op: UnOp,
expr: Box<Expr>,
span: Span,
},
/// Assignment: x = e
Assign {
target: Box<Expr>,
value: Box<Expr>,
span: Span,
},
/// Actor spawn: spawn ActorName { init } or spawn ActorName(args)
Spawn {
actor_type: Box<Expr>,
init: Vec<(String, Expr)>,
/// Positional constructor args: `spawn Foo(a, b)`.
positional_args: Option<Vec<Expr>>,
/// Named registration: `spawn Foo() as "name"`.
register_as: Option<String>,
span: Span,
},
/// Message send: actor ! behavior(args)
Send {
actor: Box<Expr>,
behavior: String,
args: Vec<Expr>,
remote: bool,
span: Span,
},
/// Request/response: ask actor behavior(args)
Ask {
actor: Box<Expr>,
behavior: String,
args: Vec<Expr>,
remote: bool,
timeout_ms: Option<u64>,
span: Span,
},
/// Receive: receive { | Behavior(params) => expr } [after ms => timeout_expr]
///
/// Each arm carries the behavior name, a list of payload patterns
/// (one per payload slot; `Pattern::Var(name)` for a simple binding,
/// `Pattern::Wild` for `_`, `Pattern::Lit(_)` for a literal test, etc.),
/// an optional guard expression (`if cond`), and the arm body.
Receive {
arms: Vec<(String, Vec<Pattern>, Option<Box<Expr>>, Expr)>,
/// Optional timeout clause: `(timeout_ms, timeout_body)`. `timeout_ms`
/// is an Int expression; on no matching message the actor waits up to
/// that many milliseconds, then evaluates `timeout_body`.
after: Option<(Box<Expr>, Box<Expr>)>,
span: Span,
},
/// Self reference within actor
SelfRef(Span),
/// Emit event: emit EventName(args)
Emit {
event: String,
args: Vec<Expr>,
span: Span,
},
/// Perform effect: perform Effect.op(arg)
Perform {
effect: String,
op: String,
args: Vec<Expr>,
span: Span,
},
/// Handle effect: handle expr { | op(x) => ... | return(x) => ... }
Handle {
body: Box<Expr>,
handlers: Vec<EffectHandler>,
span: Span,
},
/// Actor migration: migrate actor to node
Migrate {
actor: Box<Expr>,
node: Box<Expr>,
span: Span,
},
/// Capability annotation: actor :cap iso
CapAnnotate {
expr: Box<Expr>,
cap: Capability,
span: Span,
},
/// Type annotation: expr : Type
TypeAnnotate {
expr: Box<Expr>,
ty: Type,
span: Span,
},
/// Pipe: x |> f
Pipe {
left: Box<Expr>,
right: Box<Expr>,
span: Span,
},
/// For comprehension
For {
var: String,
iterable: Box<Expr>,
body: Box<Expr>,
span: Span,
},
/// While loop: while cond { body }
While {
cond: Box<Expr>,
body: Box<Expr>,
span: Span,
},
/// Return from function
Return(Option<Box<Expr>>, Span),
/// Break from loop
Break(Option<Box<Expr>>, Span),
/// Consume variable: consume x — moves ownership, marks source unavailable
Consume {
expr: Box<Expr>,
span: Span,
},
/// Recovery block: recover { body } — isolated scope for capability upgrade
Recover {
body: Box<Expr>,
span: Span,
},
/// Deferred expression: `defer expr` — runs when enclosing scope exits.
/// `errdefer expr` runs only on error exit paths.
Defer {
expr: Box<Expr>,
/// true for `errdefer` (only on error), false for `defer` (always).
error_only: bool,
span: Span,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
Add,
Sub,
Mul,
Div,
Mod,
Eq,
Ne,
Lt,
Le,
Gt,
Ge,
And,
Or,
BitAnd,
BitOr,
BitXor,
Shl,
Shr,
Pow,
Assign,
Range,
Pipe,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
Neg,
Not,
Deref,
Ref(Capability),
}
#[derive(Debug, Clone, PartialEq)]
pub struct EffectHandler {
pub effect_name: String,
pub op_name: String,
pub params: Vec<String>,
pub body: Expr,
pub resume: bool,
}
// ---------------------------------------------------------------------------
// Behaviors (actor message handlers)
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub struct Behavior {
pub name: String,
pub params: Vec<(String, Option<Type>)>,
pub body: Expr,
pub effect: Option<EffectRow>,
pub cap: Capability,
pub span: Span,
}
// ---------------------------------------------------------------------------
// State models for actor fields
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StateModel {
Local,
Durable,
EventSourced,
Crdt,
}
impl Default for StateModel {
fn default() -> Self {
StateModel::Local
}
}
// ---------------------------------------------------------------------------
// State machine events (state_machine declaration transitions)
// ---------------------------------------------------------------------------
/// A single event transition inside a `state_machine` declaration:
/// `event name(params): Target`.
#[derive(Debug, Clone, PartialEq)]
pub struct StateMachineEvent {
pub name: String,
pub params: Vec<(String, Option<Type>)>,
/// Target state name. Must be one of the states declared via `state`
/// lines (enforced by the parser); handler-function targets like
/// gen_statem's are not supported.
pub target: String,
pub span: Span,
}
// ---------------------------------------------------------------------------
// Actor backend kind
// ---------------------------------------------------------------------------
/// Actor execution backend kind, selected at compile time.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ActorBackendKind {
#[default]
Native,
WasmComponent,
}
// ---------------------------------------------------------------------------
// Function annotations
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub enum FunctionAnnotation {
/// `@tool(description: "...")` marks a function as an LLM-callable tool.
Tool { description: String },
/// `@backend(native | wasm)` selects the actor execution backend.
Backend { kind: ActorBackendKind },
}
// ---------------------------------------------------------------------------
// Agent memory configuration
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub struct AgentMemoryConfig {
pub max_turns: usize,
}
/// Per-token pricing configuration for an agent declaration.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AgentPricing {
pub input: f64,
pub output: f64,
}
/// Semantic-memory configuration for an agent declaration.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AgentSemanticMemoryConfig {
pub dimensions: usize,
}
/// Procedural-memory configuration for an agent declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct AgentProceduralMemoryConfig {
pub namespace: String,
}
// ---------------------------------------------------------------------------
// Agent fallback & retry configuration
// ---------------------------------------------------------------------------
/// One entry in an agent's fallback pipeline.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AgentFallbackEntry {
pub model: String,
pub on: Vec<String>,
pub max_tokens: Option<usize>,
}
/// Backoff strategy for agent LLM retries.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum AgentBackoff {
Exponential {
initial_ms: u64,
factor: f64,
max_ms: u64,
},
Fixed {
delay_ms: u64,
},
}
/// Retry configuration for an agent declaration.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AgentRetryConfig {
pub max_attempts: u32,
pub backoff: AgentBackoff,
}
/// A method signature in a typeclass declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct ClassMethod {
pub name: String,
pub params: Vec<(String, Type)>,
pub return_type: Type,
pub default_body: Option<Expr>,
}
/// A method implementation in an `impl` block.
#[derive(Debug, Clone, PartialEq)]
pub struct ImplMethod {
pub name: String,
pub params: Vec<(String, Type)>,
pub return_type: Type,
pub body: Expr,
}
// Declarations
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub enum Decl {
Function {
name: String,
type_params: Vec<String>,
/// Typeclass constraints on type parameters. Each entry is
/// (param_name, type_var, [class_names]). e.g. `[T: Eq + Ord]` →
/// [("T", tv, ["Eq", "Ord"])]. Empty when no constraints.
type_param_constraints: Vec<(String, TypeVar, Vec<String>)>,
params: Vec<(String, Option<Type>)>,
/// Default values for parameters. Same length as `params`;
/// `Some(expr)` when a default is declared (`name: Type = expr`),
/// `None` when the parameter is required.
default_values: Vec<Option<Expr>>,
/// `using` parameters: filled from `given` bindings in the caller's scope.
using_params: Vec<(String, Option<Type>)>,
ret_type: Option<Type>,
error_type: Option<Type>,
effect: Option<EffectRow>,
cap: Option<Capability>,
body: Expr,
annotations: Vec<FunctionAnnotation>,
public: bool,
span: Span,
},
/// Actor declaration: [persistent] actor Name { state [model] name: Type = expr, behavior ... }
Actor {
name: String,
type_params: Vec<String>,
persistent: bool,
state_fields: Vec<(String, StateModel, Type, Expr)>, // name, model, type, default
behaviors: Vec<Behavior>,
init: Vec<(String, Expr)>,
/// Compile-time backend selection. `None` means use the CLI default.
backend: Option<ActorBackendKind>,
/// Optional initializer block: `initial name(params) { body }`.
initializer: Option<(String, Vec<(String, Option<Type>)>, Expr)>,
/// Entity schema version (defaults to 1). Used by migration contracts
/// (RFC 0008) to track schema evolution.
version: u32,
/// Typed event declarations from an `events` block (entity only).
events: Vec<EventDecl>,
/// Apply handlers from an `apply` block (entity only).
apply_handlers: Vec<ApplyHandler>,
/// Migration contracts from a `migration` block (entity only, RFC 0008).
migrations: Vec<MigrationDecl>,
is_organization: bool,
implements: Option<String>,
span: Span,
},
/// State machine declaration (BEAM_PRIMITIVES §4.2 gen_statem adaptation):
/// `state_machine Name { state S, event e(p): T, on_entry S { .. }, on_exit S { .. } }`.
/// Kept as a real declaration so the typechecker, effect checker, and LSP
/// see the source-level structure; desugared to an ordinary `Decl::Actor`
/// by [`desugar_state_machine`].
StateMachine {
name: String,
/// Declared states in source order; `states[0]` is the initial state.
states: Vec<String>,
events: Vec<StateMachineEvent>,
/// `(state, body)` hooks run on transitions entering `state`.
entry_hooks: Vec<(String, Expr)>,
/// `(state, body)` hooks run on transitions leaving `state`.
exit_hooks: Vec<(String, Expr)>,
span: Span,
},
/// Type alias: type MyInt = Int
TypeAlias {
name: String,
type_params: Vec<String>,
body: Type,
/// true for `opaque type Name = Type` — distinct type at compile time,
/// erases to underlying type at runtime.
opaque: bool,
public: bool,
span: Span,
},
/// Record type: type Point = { x: Int, y: Int }
RecordType {
name: String,
type_params: Vec<String>,
fields: Vec<(String, Type)>,
public: bool,
span: Span,
},
/// Variant type: type Option[T] = Some(T) | None
VariantType {
name: String,
type_params: Vec<String>,
variants: Vec<(String, Option<Type>)>,
public: bool,
span: Span,
},
/// Effect declaration: effect MyEffect { op1: A -> B }
EffectDecl {
name: String,
ops: Vec<(String, Vec<Type>, Type)>, // name, arg types, ret type
span: Span,
},
/// Module declaration: module Name { ... }
Module {
name: String,
exports: Vec<String>,
decls: Vec<Decl>,
span: Span,
},
/// Import: import "path" or import Module.{name1, name2}
Import {
path: String,
items: Vec<String>,
span: Span,
},
/// Foreign function interface block: extern "lib" { fn f(x: T) -> R }
Extern {
library: String,
funcs: Vec<ExternFunc>,
span: Span,
},
/// Workflow declaration (v0.8): workflow Name { step name { body } ... }
Workflow {
name: String,
input: Option<(String, Type)>,
items: Vec<WorkflowItem>,
compensate: Option<Expr>,
span: Span,
},
/// Agent declaration (v0.9): agent Name = { model: "...", system_prompt: "...", tools: [...], memory: { max_turns: N }, semantic_memory: { dimensions: D }, procedural_memory: { namespace: "..." }, fallback: [{ model: "...", on: [Timeout, RateLimit], max_tokens: 8192 }], retry: { max_attempts: 3, backoff: Exponential { initial_ms: 200, factor: 2.0, max_ms: 3000 } } }
Agent {
name: String,
model: String,
system_prompt: Option<String>,
tools: Vec<String>,
memory: Option<AgentMemoryConfig>,
semantic_memory: Option<AgentSemanticMemoryConfig>,
procedural_memory: Option<AgentProceduralMemoryConfig>,
pricing: Option<AgentPricing>,
fallback: Vec<AgentFallbackEntry>,
retry: Option<AgentRetryConfig>,
span: Span,
},
/// Database declaration: database Name { table Name { col: Type, ... } }
Database {
name: String,
tables: Vec<DatabaseTable>,
span: Span,
},
/// Named handler declaration: `handler name = { | Effect.op(params) resume => body, ... }`
NamedHandler {
name: String,
handlers: Vec<EffectHandler>,
span: Span,
},
/// Typeclass declaration: `class Eq[T] { fn eq(self: T, other: T) -> Bool }`
Class {
name: String,
type_params: Vec<String>,
/// Typeclass constraints on type parameters.
type_param_constraints: Vec<(String, TypeVar, Vec<String>)>,
super_classes: Vec<String>,
methods: Vec<ClassMethod>,
span: Span,
},
/// Typeclass instance: `impl Eq[Int] { fn eq(self, other) = self == other }`
Impl {
class_name: String,
type_params: Vec<String>,
for_type: Type,
methods: Vec<ImplMethod>,
span: Span,
},
/// Module-level let binding: `let name [: Type] = value`
LetBinding {
name: String,
type_ann: Option<Type>,
value: Expr,
mutable: bool,
span: Span,
},
/// Contextual value declaration: `given name: Type = expr`
Given {
name: String,
ty: Option<Type>,
value: Expr,
span: Span,
},
}
// ---------------------------------------------------------------------------
// Entity event and apply declarations
// ---------------------------------------------------------------------------
/// A typed event declaration inside an `entity`'s `events` block.
///
/// ```nulang
/// events
/// | Deposited(amount: Int)
/// | Withdrawn(amount: Int)
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct EventDecl {
pub name: String,
pub params: Vec<(String, Type)>,
pub span: Span,
}
/// An apply handler inside an `entity`'s `apply` block.
///
/// ```nulang
/// apply
/// | Deposited(amount) => self.balance = self.balance + amount
/// | Withdrawn(amount) => self.balance = self.balance - amount
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct ApplyHandler {
pub event: String,
pub params: Vec<String>,
pub body: Expr,
pub span: Span,
}
/// A migration contract inside an `entity`'s `migration` block.
///
/// ```nulang
/// migration from 1 to 2 {
/// state => { self.currency = "USD" }
/// events {
/// | Deposited(amount) => emit Deposited(amount)
/// | other => other
/// }
/// }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct MigrationDecl {
pub from_version: u32,
pub to_version: u32,
/// State migration: an expression that updates `self`.
pub state_body: Option<Expr>,
/// Event migrations: `(event_name, params, body)` — if `event_name` is
/// `"other"`, it's a catch-all for unlisted events.
pub event_migrations: Vec<(String, Vec<String>, Expr)>,
pub span: Span,
}
// ---------------------------------------------------------------------------
// Database declaration (Turso/libSQL first-class integration)
// ---------------------------------------------------------------------------
/// A column definition inside a `database` table.
#[derive(Debug, Clone, PartialEq)]
pub struct DatabaseColumn {
pub name: String,
pub col_type: Type,
pub modifiers: Vec<String>, // "primary_key", "unique", "not_null", etc.
pub span: Span,
}
/// A table definition inside a `database` declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct DatabaseTable {
pub name: String,
pub columns: Vec<DatabaseColumn>,
pub span: Span,
}
/// A single item inside a `workflow` declaration, preserving the original
/// source order of sequential steps and parallel blocks.
#[derive(Debug, Clone, PartialEq)]
pub enum WorkflowItem {
Step(WorkflowStep),
Parallel(Vec<WorkflowStep>),
}
/// A single step inside a `workflow` declaration.
#[derive(Debug, Clone, PartialEq)]
pub struct WorkflowStep {
pub name: String,
pub body: Expr,
/// Optional saga compensation expression run when a later step fails.
pub compensate: Option<Expr>,
pub span: Span,
}
/// Foreign function declaration inside an `extern` block.
#[derive(Debug, Clone, PartialEq)]
pub struct ExternFunc {
pub name: String,
pub params: Vec<(String, Type)>,
pub ret: Type,
pub span: Span,
}
// ---------------------------------------------------------------------------
// State machine desugar (state_machine -> actor)
// ---------------------------------------------------------------------------
/// Desugar a `state_machine` declaration into an ordinary actor. The
/// typechecker, effect checker, and HIR lowering all run the result through
/// exactly the same paths as a hand-written `Decl::Actor`, so the feature
/// needs no IR, bytecode, or runtime support (BEAM_PRIMITIVES §15 Phase 2).
///
/// The generated actor has:
/// - a `Local` string state field `_sm_state` initialized to the first
/// declared state (`states` must be non-empty; enforced by the parser),
/// holding the current state tag;
/// - one behavior per `event name(params): Target`, whose body
/// 1. runs the `on_exit` hook of the *current* state, if one is declared —
/// an if-chain comparing `_sm_state` against each hooked state tag;
/// 2. assigns `_sm_state = "Target"`;
/// 3. runs the `on_entry Target` hook inline, if one is declared (the
/// target is statically known, so no dispatch is needed);
/// 4. evaluates to `nil`.
///
/// Hooks run on every matching transition, including self-transitions
/// (e.g. `disconnect: Closed` taken while already `Closed` runs both the
/// `Closed` exit and entry hooks). Because events do not name source states,
/// every event is allowed in every state — gen_statem's "event ignored in a
/// state where it is not allowed" case cannot arise, so no message is ever
/// dropped for state reasons. `send`/`ask` against the machine behave
/// exactly as against any actor.
pub fn desugar_state_machine(
name: &str,
states: &[String],
events: &[StateMachineEvent],
entry_hooks: &[(String, Expr)],
exit_hooks: &[(String, Expr)],
span: Span,
) -> Decl {
let initial = states.first().cloned().unwrap_or_default();
let state_field = (
"_sm_state".to_string(),
StateModel::Local,
Type::string(),
Expr::Literal(Literal::String(initial), span),
);
let sm_state = || Expr::FieldAccess {
expr: Box::new(Expr::SelfRef(span)),
field: "_sm_state".to_string(),
span,
};
let behaviors = events
.iter()
.map(|event| {
let mut body_exprs: Vec<Expr> = Vec::new();
// on_exit: dispatch on the current state tag over the states
// that declare an exit hook. The hook value is discarded into a
// trailing `unit` because an `if` without `else` unifies its
// then-branch with Unit — a non-Unit hook body (e.g. one ending
// in `nil`) would otherwise fail type checking.
for (state, hook) in exit_hooks {
body_exprs.push(Expr::If {
cond: Box::new(Expr::Binary {
op: BinOp::Eq,
left: Box::new(sm_state()),
right: Box::new(Expr::Literal(Literal::String(state.clone()), span)),
span,
}),
then_branch: Box::new(Expr::Block {
exprs: vec![hook.clone(), Expr::Literal(Literal::Unit, span)],
span,
}),
else_branch: None,
span,
});
}
// Transition to the target state.
body_exprs.push(Expr::Assign {
target: Box::new(sm_state()),
value: Box::new(Expr::Literal(Literal::String(event.target.clone()), span)),
span,
});
// on_entry of the (statically known) target state, if declared.
if let Some((_, hook)) = entry_hooks.iter().find(|(s, _)| s == &event.target) {
body_exprs.push(hook.clone());
}
body_exprs.push(Expr::Literal(Literal::Nil, span));
Behavior {
name: event.name.clone(),
params: event.params.clone(),
body: Expr::Block {
exprs: body_exprs,
span,
},
effect: None,
cap: Capability::Ref,
span: event.span,
}
})
.collect();
Decl::Actor {
name: name.to_string(),
type_params: vec![],
persistent: false,
state_fields: vec![state_field],
behaviors,
init: vec![],
backend: None,
initializer: None,
events: vec![],
apply_handlers: vec![],
version: 1,
migrations: vec![],
is_organization: false,
implements: None,
span,
}
}
// ---------------------------------------------------------------------------
// Top-level AST
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub struct AstModule {
pub name: String,
pub decls: Vec<Decl>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_literal_variants() {
// Construct each Literal variant and verify Debug output
let i = Literal::Int(42);
assert_eq!(format!("{:?}", i), "Int(42)");
let f = Literal::Float(1.5);
assert_eq!(format!("{:?}", f), "Float(1.5)");
let s = Literal::String("hello".to_string());
assert_eq!(format!("{:?}", s), "String(\"hello\")");
let b = Literal::Bool(true);
assert_eq!(format!("{:?}", b), "Bool(true)");
let n = Literal::Nil;
assert_eq!(format!("{:?}", n), "Nil");
let u = Literal::Unit;
assert_eq!(format!("{:?}", u), "Unit");
}
#[test]
fn test_binop_variants() {
// Construct each BinOp variant
let ops = vec![
(BinOp::Add, "Add"),
(BinOp::Sub, "Sub"),
(BinOp::Mul, "Mul"),
(BinOp::Div, "Div"),
(BinOp::Mod, "Mod"),
(BinOp::Eq, "Eq"),
(BinOp::Ne, "Ne"),
(BinOp::Lt, "Lt"),
(BinOp::Le, "Le"),
(BinOp::Gt, "Gt"),
(BinOp::Ge, "Ge"),
(BinOp::And, "And"),
(BinOp::Or, "Or"),
(BinOp::BitAnd, "BitAnd"),
(BinOp::BitOr, "BitOr"),
(BinOp::BitXor, "BitXor"),
(BinOp::Shl, "Shl"),
(BinOp::Shr, "Shr"),
(BinOp::Assign, "Assign"),
(BinOp::Pipe, "Pipe"),
];
for (op, name) in ops {
assert_eq!(format!("{:?}", op), name);
}
}
#[test]
fn test_unop_variants() {
assert_eq!(format!("{:?}", UnOp::Neg), "Neg");
assert_eq!(format!("{:?}", UnOp::Not), "Not");
assert_eq!(format!("{:?}", UnOp::Deref), "Deref");
assert_eq!(format!("{:?}", UnOp::Ref(Capability::Val)), "Ref(Val)");
}
#[test]
fn test_state_model_default() {
assert_eq!(StateModel::default(), StateModel::Local);
}
#[test]
fn test_span_default() {
let s = Span::default();
assert_eq!(s.start, 0);
assert_eq!(s.end, 0);
// line()/column() return 0 when no SourceMap is set (no lexer ran).
assert_eq!(s.line(), 0);
assert_eq!(s.column(), 0);
}
#[test]
fn test_ast_module_new() {
let m = AstModule {
name: "test".to_string(),
decls: vec![],
};
assert_eq!(m.name, "test");
assert!(m.decls.is_empty());
}
#[test]
fn test_effect_handler_new() {
// Without resume offset
let h = EffectHandler {
effect_name: "IO".to_string(),
op_name: "print".to_string(),
params: vec!["msg".to_string()],
body: Expr::Literal(Literal::Unit, Span::default()),
resume: false,
};
assert_eq!(h.effect_name, "IO");
assert_eq!(h.op_name, "print");
assert_eq!(h.params, vec!["msg"]);
assert!(matches!(h.body, Expr::Literal(Literal::Unit, _)));
assert!(!h.resume);
// With resume offset
let h2 = EffectHandler {
effect_name: "Net".to_string(),
op_name: "fetch".to_string(),
params: vec!["url".to_string()],
body: Expr::Literal(Literal::Int(0), Span::default()),
resume: true,
};
assert_eq!(h2.effect_name, "Net");
assert!(h2.resume);
}
#[test]
fn test_behavior_new() {