varpulis-core 0.11.0

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

use serde::{Deserialize, Serialize};

use crate::span::Spanned;
use crate::types::Type;

/// A complete VPL program
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Program {
    /// The top-level statements that make up the program.
    pub statements: Vec<Spanned<Stmt>>,
}

/// Top-level statement
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Stmt {
    /// Connector declaration: `connector MyMqtt = mqtt (host: "localhost", port: 1883)`
    ConnectorDecl {
        /// Connector name.
        name: String,
        /// Connector protocol type (e.g., `"mqtt"`, `"kafka"`).
        connector_type: String,
        /// Connection parameters.
        params: Vec<ConnectorParam>,
    },
    /// Stream declaration: `stream X = Y` or `stream X = Y.where(...)`
    StreamDecl {
        /// Stream name.
        name: String,
        /// Optional type annotation for the stream.
        type_annotation: Option<Type>,
        /// Event source for this stream.
        source: StreamSource,
        /// Chained stream operations.
        ops: Vec<StreamOp>,
        /// Per-operation source spans (parallel to `ops`). Empty when spans unavailable.
        #[serde(default)]
        op_spans: Vec<crate::span::Span>,
    },
    /// Event declaration: `event X: ...`
    EventDecl {
        /// Event type name.
        name: String,
        /// Parent event type if this event extends another.
        extends: Option<String>,
        /// Fields declared on this event type.
        fields: Vec<Field>,
    },
    /// Type declaration: alias (`type X = Y`) or struct (`type X: field: T`).
    TypeDecl {
        /// Type name.
        name: String,
        /// The aliased type (alias form only).
        ty: Option<Type>,
        /// Struct fields (struct form only).
        fields: Vec<Field>,
    },
    /// Variable declaration: `let x = ...` or `var x = ...`
    VarDecl {
        /// Whether the variable can be reassigned.
        mutable: bool,
        /// Variable name.
        name: String,
        /// Optional type annotation.
        ty: Option<Type>,
        /// Initial value expression.
        value: Expr,
    },
    /// Constant declaration: `const X = ...`
    ConstDecl {
        /// Constant name.
        name: String,
        /// Optional type annotation.
        ty: Option<Type>,
        /// Constant value expression.
        value: Expr,
    },
    /// Function declaration: `fn x(...) -> T: ...`
    FnDecl {
        /// Function name.
        name: String,
        /// Function parameters.
        params: Vec<Param>,
        /// Optional return type.
        ret: Option<Type>,
        /// Function body statements.
        body: Vec<Spanned<Self>>,
    },
    /// Configuration block with name (e.g., `config mqtt { ... }`)
    ///
    /// **Deprecated:** Use `connector` declarations instead.
    /// ```vpl
    /// connector MyMqtt = mqtt (
    ///     broker: "localhost",
    ///     port: 1883,
    ///     topic: "events/#"
    /// )
    /// ```
    Config {
        /// Configuration block name.
        name: String,
        /// Configuration key-value items.
        items: Vec<ConfigItem>,
    },
    /// Import statement
    Import {
        /// Module path to import.
        path: String,
        /// Optional import alias.
        alias: Option<String>,
    },
    /// Import a WASM function as a UDF.
    /// Syntax: `import fn name(param: type, ...) -> return_type from "path.wasm"`
    ImportWasmFn {
        /// Function name (registered in UdfRegistry).
        name: String,
        /// Typed parameters.
        params: Vec<Param>,
        /// Return type (None defaults to Any).
        ret: Option<Type>,
        /// Path to the WASM module file.
        wasm_path: String,
    },
    /// Expression statement
    Expr(Expr),
    /// If statement
    If {
        /// Condition expression.
        cond: Expr,
        /// Statements to execute when the condition is true.
        then_branch: Vec<Spanned<Self>>,
        /// Optional else-if branches (condition, body pairs).
        elif_branches: Vec<(Expr, Vec<Spanned<Self>>)>,
        /// Optional else branch.
        else_branch: Option<Vec<Spanned<Self>>>,
    },
    /// For loop
    For {
        /// Loop variable name.
        var: String,
        /// Iterable expression.
        iter: Expr,
        /// Loop body statements.
        body: Vec<Spanned<Self>>,
    },
    /// While loop
    While {
        /// Loop condition.
        cond: Expr,
        /// Loop body statements.
        body: Vec<Spanned<Self>>,
    },
    /// Return statement
    Return(Option<Expr>),
    /// Break statement
    Break,
    /// Continue statement
    Continue,
    /// Emit event statement: `emit EventType(field1: expr1, field2: expr2)`
    Emit {
        /// Event type to emit.
        event_type: String,
        /// Named field values for the emitted event.
        fields: Vec<NamedArg>,
    },
    /// Variable assignment: `name := value`
    Assignment {
        /// Variable name to assign.
        name: String,
        /// New value expression.
        value: Expr,
    },
    /// SASE+ Pattern declaration: `pattern Name = SEQ(A, B+) within 1h partition by user_id`
    PatternDecl {
        /// Pattern name.
        name: String,
        /// SASE+ pattern expression.
        expr: SasePatternExpr,
        /// Optional time window constraint.
        within: Option<Expr>,
        /// Optional partition key expression.
        partition_by: Option<Expr>,
    },
    /// Context declaration: `context name (cores: [0, 1])`
    ContextDecl {
        /// Context name.
        name: String,
        /// Optional CPU core affinity list.
        cores: Option<Vec<usize>>,
    },
}

/// Connector parameter: `host: "localhost"` or `port: 1883`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConnectorParam {
    /// Parameter name.
    pub name: String,
    /// Parameter value.
    pub value: ConfigValue,
}

/// SASE+ Pattern Expression for complex event processing.
///
/// Patterns are produced by the arrow syntax (`A -> all B as bs -> C`).
/// The legacy `SEQ()` form and AND/OR/NOT/Group combinators have been
/// removed in favor of the unified arrow syntax.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SasePatternExpr {
    /// Sequence: A -> B -> C (or a single item, degenerate sequence)
    Seq(Vec<SasePatternItem>),
}

/// Item in a SASE+ sequence with optional Kleene operator
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SasePatternItem {
    /// Event type name
    pub event_type: String,
    /// Optional alias for the event
    pub alias: Option<String>,
    /// Kleene operator: None, Plus (+), Star (*), Optional (?)
    pub kleene: Option<KleeneOp>,
    /// Optional filter condition
    pub filter: Option<Expr>,
    /// Monotonic operator: .increasing(field) / .decreasing(field)
    pub monotonic: Option<MonotonicOp>,
}

/// Kleene operators for SASE+ patterns
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum KleeneOp {
    /// One or more (+)
    Plus,
    /// Zero or more (*)
    Star,
    /// Zero or one (?)
    Optional,
}

/// Monotonic operators: syntactic sugar for self-referencing Kleene predicates
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MonotonicOp {
    /// .increasing(field) — each value > previous
    Increasing(String),
    /// .decreasing(field) — each value < previous
    Decreasing(String),
}

/// Stream source
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum StreamSource {
    /// Reference to existing stream with optional alias
    Ident(String),
    /// Event type with optional alias: `EventType as alias`
    IdentWithAlias {
        /// Event type or stream name.
        name: String,
        /// Alias for the source.
        alias: String,
    },
    /// Source event type with inline filter and optional alias.
    /// Example: `EventType where status == "failed" as f1`
    IdentWithFilterAndAlias {
        /// Event type or stream name.
        name: String,
        /// Inline filter expression.
        filter: Expr,
        /// Optional alias for the source.
        alias: Option<String>,
    },
    /// Event type with all quantifier and optional alias: `all EventType as alias`
    AllWithAlias {
        /// Event type name.
        name: String,
        /// Optional alias for the source.
        alias: Option<String>,
    },
    /// From connector: `EventType.from(Connector, topic: "...", qos: 1)`
    FromConnector {
        /// Event type to receive from the connector.
        event_type: String,
        /// Connector name to read from.
        connector_name: String,
        /// Additional connector parameters.
        params: Vec<ConnectorParam>,
    },
    /// Merge multiple streams
    Merge(Vec<InlineStreamDecl>),
    /// Join multiple streams
    Join(Vec<JoinClause>),
    /// Sequence construct: `sequence(step1: Event1, step2: Event2 where cond, ...)`
    Sequence(SequenceDecl),
    /// Periodic timer source: `timer(5s)` or `timer(5s, initial_delay: 1s)`
    Timer(TimerDecl),
}

/// Timer declaration for periodic event generation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TimerDecl {
    /// Interval between timer fires (duration expression)
    pub interval: Expr,
    /// Optional initial delay before first fire
    pub initial_delay: Option<Box<Expr>>,
}

/// Sequence declaration for temporal event correlation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SequenceDecl {
    /// Whether to match all first events or just one
    pub match_all: bool,
    /// Global timeout for the sequence
    pub timeout: Option<Box<Expr>>,
    /// Named steps in the sequence
    pub steps: Vec<SequenceStepDecl>,
}

/// A single step in a sequence declaration
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SequenceStepDecl {
    /// Alias for the captured event
    pub alias: String,
    /// Event type to match
    pub event_type: String,
    /// Optional filter condition
    pub filter: Option<Expr>,
    /// Optional timeout for this step
    pub timeout: Option<Box<Expr>>,
}

/// Inline stream declaration used in merge/join
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct InlineStreamDecl {
    /// Name alias for this inline stream.
    pub name: String,
    /// Source event type or stream name.
    pub source: String,
    /// Optional filter condition for this source.
    pub filter: Option<Expr>,
}

/// Join type for stream correlation
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum JoinType {
    /// Inner join (default) — emit only when all sources match
    #[default]
    Inner,
    /// Left join — emit when left source has an event, fill nulls for missing right
    Left,
    /// Right join — emit when right source has an event, fill nulls for missing left
    Right,
    /// Full outer join — emit for either side, fill nulls for missing sources
    Full,
}

/// Join clause
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JoinClause {
    /// Name alias for this join source.
    pub name: String,
    /// Source event type or stream name.
    pub source: String,
    /// Optional join condition expression.
    pub on: Option<Expr>,
    /// Type of join (inner, left, right, full).
    #[serde(default)]
    pub join_type: JoinType,
}

/// Stream operation (method call on stream)
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum StreamOp {
    /// Filter: `.where(cond)`
    Where(Expr),
    /// Projection: `.select(fields)`
    Select(Vec<SelectItem>),
    /// Window: `.window(duration, ...)`
    Window(WindowArgs),
    /// Aggregation: `.aggregate(...)`
    Aggregate(Vec<AggItem>),
    /// Having: `.having(cond)` - filter after aggregation
    Having(Expr),
    /// Partitioning: `.partition_by(key)`
    PartitionBy(Expr),
    /// Ordering: `.order_by(...)`
    OrderBy(Vec<OrderItem>),
    /// Limit: `.limit(n)`
    Limit(Expr),
    /// Distinct: `.distinct(expr?)`
    Distinct(Option<Expr>),
    /// Map: `.map(fn)`
    Map(Expr),
    /// Filter with lambda: `.filter(fn)`
    Filter(Expr),
    /// Tap for observability: `.tap(...)`
    Tap(Vec<NamedArg>),
    /// Print to console: `.print(...)` or `.print("message", expr)`
    Print(Vec<Expr>),
    /// Log with level: `.log(level: "info", message: "...", data: expr)`
    Log(Vec<NamedArg>),
    /// Emit output: `.emit(fields...)` or `.emit as Type (fields...)`
    Emit {
        /// Optional type cast: `.emit as Alert (...)`
        output_type: Option<String>,
        /// Field mappings
        fields: Vec<NamedArg>,
        /// Optional target context for cross-context emit: `.emit(context: ctx_name, ...)`
        target_context: Option<String>,
    },
    /// Send to connector: `.to(Connector, topic: "...", method: "POST")`
    To {
        /// Target connector name.
        connector_name: String,
        /// Sink parameters (topic, method, etc.).
        params: Vec<ConnectorParam>,
    },
    /// Send to destination (legacy): `.to(target)`
    ToExpr(Expr),
    /// Pattern matching: `.pattern(...)`
    Pattern(PatternDef),
    /// Concurrent processing: `.concurrent(...)`
    Concurrent(Vec<NamedArg>),
    /// Process with function: `.process(fn)`
    Process(Expr),
    /// Error handler: `.on_error(fn)`
    OnError(Expr),
    /// Collect results: `.collect()`
    Collect,
    /// Join condition: `.on(expr)`
    On(Expr),
    /// Followed-by sequence: `-> EventType where condition as alias`
    FollowedBy(FollowedByClause),
    /// Timeout constraint: `.within(duration)`
    Within(Expr),
    /// Negation: `.not(EventType where condition)`
    Not(FollowedByClause),
    /// Fork into multiple parallel paths: `.fork(path1: ..., path2: ...)`
    Fork(Vec<ForkPath>),
    /// Wait for any path to complete: `.any()` or `.any(n)` for at least n
    Any(Option<usize>),
    /// Wait for all paths to complete: `.all()`
    All,
    /// Wait for first path to complete: `.first()`
    First,
    /// Assign stream to a context: `.context(name)`
    Context(String),
    /// Watermark configuration: `.watermark(out_of_order: 10s)`
    Watermark(Vec<NamedArg>),
    /// Allowed lateness for late data: `.allowed_lateness(30s)`
    AllowedLateness(Expr),
    /// Trend aggregation over Kleene patterns (Hamlet engine):
    /// `.trend_aggregate(count: count_trends(), events: count_events(rising))`
    TrendAggregate(Vec<TrendAggItem>),
    /// ONNX model scoring: `.score(model: "path.onnx", inputs: [...], outputs: [...])`
    Score(ScoreSpec),
    /// PST-based pattern forecasting: `.forecast(confidence: 0.7, horizon: 2m, warmup: 500, max_depth: 5)`
    Forecast(ForecastSpec),
    /// External connector enrichment: `.enrich(WeatherAPI, key: t.city, fields: [forecast, humidity], cache_ttl: 5m)`
    Enrich(EnrichSpec),
    /// Alert notification: `.alert(webhook: "https://...", message: "Alert: {field}")`
    Alert(Vec<NamedArg>),
    /// SASE+ selection mode: `.strict()`, `.stnm()`, or `.stam()`.
    /// Controls how runs are spawned and which events extend them.
    SelectionMode(SelectionMode),
    /// SASE+ emission mode: `.each()`, `.longest()`, or `.subsets()`.
    /// Controls how many MatchResults each completed run produces.
    EmissionMode(EmissionMode),
}

/// SASE+ selection strategy. See `crates/varpulis-sase/src/types.rs::SelectionStrategy`
/// for the runtime equivalent. Mirrored here so the parser/AST don't depend on sase.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SelectionMode {
    /// Strict contiguity — events must be adjacent in the stream
    Strict,
    /// Skip-till-next-match — one maximal non-overlapping match per anchor
    Stnm,
    /// Skip-till-any-match — overlapping runs from every anchor (paper-correct)
    Stam,
}

/// SASE+ emission mode. See `crates/varpulis-sase/src/types.rs::EmissionMode`
/// for the runtime equivalent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EmissionMode {
    /// Emit on every Kleene event extension (default for non-monotonic)
    Each,
    /// Emit once with the longest captured sequence (default for `.increasing()`/`.decreasing()`)
    Longest,
    /// Emit one match per non-empty subset of the Kleene capture (paper-correct STAM verbose)
    Subsets,
}

/// A path in a fork construct
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ForkPath {
    /// Name of the path
    pub name: String,
    /// Sequence of operations for this path
    pub ops: Vec<StreamOp>,
}

/// Item in a trend_aggregate operation
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TrendAggItem {
    /// Output alias for the aggregation result
    pub alias: String,
    /// Aggregation function name: "count_trends", "count_events", "sum_trends", etc.
    pub func: String,
    /// Optional argument (field reference for sum/avg/min/max, alias for count_events)
    pub arg: Option<Expr>,
}

/// Specification for ONNX model scoring
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ScoreSpec {
    /// Path to the ONNX model file.
    pub model_path: String,
    /// Input tensor names to feed from event fields.
    pub inputs: Vec<String>,
    /// Output tensor names to extract as event fields.
    pub outputs: Vec<String>,
    /// Enable GPU acceleration (default: false)
    #[serde(default)]
    pub gpu: bool,
    /// Batch size for inference (default: 1, >1 enables batch mode)
    #[serde(default = "default_batch_size")]
    pub batch_size: usize,
    /// GPU device ID (default: 0)
    #[serde(default)]
    pub device_id: i32,
}

const fn default_batch_size() -> usize {
    1
}

/// Specification for PST-based pattern forecasting
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ForecastSpec {
    /// Minimum probability to emit forecast (default 0.5)
    pub confidence: Option<Expr>,
    /// Forecast time horizon (default = within duration)
    pub horizon: Option<Expr>,
    /// Events before forecasting starts (default 100)
    pub warmup: Option<Expr>,
    /// Maximum PST context depth (default 5)
    pub max_depth: Option<Expr>,
    /// Enable Hawkes intensity modulation (default true)
    pub hawkes: Option<Expr>,
    /// Enable conformal prediction intervals (default true)
    pub conformal: Option<Expr>,
    /// Preset mode: "fast", "accurate", or "balanced" (default "balanced")
    pub mode: Option<Expr>,
}

/// Specification for external connector enrichment
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnrichSpec {
    /// Name of the connector to use for lookups
    pub connector_name: String,
    /// Expression to evaluate as the lookup key
    pub key_expr: Box<Expr>,
    /// Fields to extract from the enrichment response
    pub fields: Vec<String>,
    /// Cache TTL (optional, duration expression)
    pub cache_ttl: Option<Expr>,
    /// Timeout for the enrichment request (optional, duration expression)
    pub timeout: Option<Expr>,
    /// Fallback value when lookup fails (optional)
    pub fallback: Option<Expr>,
}

/// Followed-by clause for temporal sequences
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FollowedByClause {
    /// Event type to match
    pub event_type: String,
    /// Optional filter condition
    pub filter: Option<Expr>,
    /// Optional alias for captured event
    pub alias: Option<String>,
    /// Whether to match all events (true) or just one (false)
    pub match_all: bool,
    /// Monotonic operator: .increasing(field) / .decreasing(field)
    pub monotonic: Option<MonotonicOp>,
}

/// Select item in projection
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SelectItem {
    /// Simple field reference
    Field(String),
    /// Aliased expression: `alias: expr`
    Alias(String, Expr),
}

/// Aggregation item
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AggItem {
    /// Output field name for the aggregation result.
    pub alias: String,
    /// Aggregation expression (e.g., `avg(temperature)`).
    pub expr: Expr,
}

/// Order item
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OrderItem {
    /// Expression to sort by.
    pub expr: Expr,
    /// Whether to sort in descending order.
    pub descending: bool,
}

/// Window arguments
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WindowArgs {
    /// Window duration (tumbling window size).
    pub duration: Expr,
    /// Optional slide interval for sliding windows.
    pub sliding: Option<Expr>,
    /// Optional eviction policy expression.
    pub policy: Option<Expr>,
    /// Session window gap duration (syntax: `.window(session: 5m)`)
    pub session_gap: Option<Expr>,
}

/// Pattern definition
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PatternDef {
    /// Pattern name.
    pub name: String,
    /// Matcher expression for the pattern.
    pub matcher: Expr,
}

/// Named argument: `name: value`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NamedArg {
    /// Argument name.
    pub name: String,
    /// Argument value expression.
    pub value: Expr,
}

/// Field in event declaration
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Field {
    /// Field name.
    pub name: String,
    /// Field type.
    pub ty: Type,
    /// Whether the field is optional.
    pub optional: bool,
}

/// Function parameter
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Param {
    /// Parameter name.
    pub name: String,
    /// Parameter type.
    pub ty: Type,
}

/// Expression
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Expr {
    /// Null literal.
    Null,
    /// Boolean literal.
    Bool(bool),
    /// Integer literal.
    Int(i64),
    /// Floating-point literal.
    Float(f64),
    /// String literal.
    Str(String),
    /// Duration literal in nanoseconds.
    Duration(u64),
    /// Timestamp literal in nanoseconds since epoch.
    Timestamp(i64),

    /// Array literal: `[1, 2, 3]`.
    Array(Vec<Self>),
    /// Map literal: `{key: value, ...}`.
    Map(Vec<(String, Self)>),

    /// Identifier reference.
    Ident(String),

    /// Binary operation: `left op right`.
    Binary {
        /// The binary operator.
        op: BinOp,
        /// Left operand.
        left: Box<Self>,
        /// Right operand.
        right: Box<Self>,
    },

    /// Unary operation: `op expr`.
    Unary {
        /// The unary operator.
        op: UnaryOp,
        /// Operand expression.
        expr: Box<Self>,
    },

    /// Member access: `expr.member`.
    Member {
        /// Object expression.
        expr: Box<Self>,
        /// Member name to access.
        member: String,
    },

    /// Optional member access: `expr?.member`.
    OptionalMember {
        /// Object expression (may be null).
        expr: Box<Self>,
        /// Member name to access.
        member: String,
    },

    /// Index access: `expr[index]`.
    Index {
        /// Collection expression.
        expr: Box<Self>,
        /// Index expression.
        index: Box<Self>,
    },

    /// Slice: `expr[start:end]`.
    Slice {
        /// Collection expression.
        expr: Box<Self>,
        /// Optional start index.
        start: Option<Box<Self>>,
        /// Optional end index.
        end: Option<Box<Self>>,
    },

    /// Function call: `func(args)`.
    Call {
        /// Function expression to call.
        func: Box<Self>,
        /// Arguments to the function.
        args: Vec<Arg>,
    },

    /// Lambda: `x => expr` or `(x, y) => expr`.
    Lambda {
        /// Lambda parameter names.
        params: Vec<String>,
        /// Lambda body expression.
        body: Box<Self>,
    },

    /// Conditional expression: `if cond then a else b`.
    If {
        /// Condition expression.
        cond: Box<Self>,
        /// Value when true.
        then_branch: Box<Self>,
        /// Value when false.
        else_branch: Box<Self>,
    },

    /// Null coalescing: `expr ?? default`.
    Coalesce {
        /// Expression that may be null.
        expr: Box<Self>,
        /// Fallback value when expr is null.
        default: Box<Self>,
    },

    /// Range: `start..end` or `start..=end`.
    Range {
        /// Range start.
        start: Box<Self>,
        /// Range end.
        end: Box<Self>,
        /// Whether the end is inclusive (`..=`).
        inclusive: bool,
    },

    /// Block expression: `{ let a = 1; let b = 2; a + b }`.
    Block {
        /// Local bindings: (name, optional type, value, is_mutable).
        stmts: Vec<(String, Option<Type>, Self, bool)>,
        /// Final expression that produces the block's value.
        result: Box<Self>,
    },
}

/// Function argument
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Arg {
    /// Positional argument.
    Positional(Expr),
    /// Named argument: `name: value`.
    Named(String, Expr),
}

/// Binary operator
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum BinOp {
    /// Addition (`+`).
    Add,
    /// Subtraction (`-`).
    Sub,
    /// Multiplication (`*`).
    Mul,
    /// Division (`/`).
    Div,
    /// Modulo (`%`).
    Mod,
    /// Exponentiation (`**`).
    Pow,

    /// Equality (`==`).
    Eq,
    /// Inequality (`!=`).
    NotEq,
    /// Less than (`<`).
    Lt,
    /// Less than or equal (`<=`).
    Le,
    /// Greater than (`>`).
    Gt,
    /// Greater than or equal (`>=`).
    Ge,
    /// Membership test (`in`).
    In,
    /// Negated membership test (`not in`).
    NotIn,
    /// Type identity test (`is`).
    Is,

    /// Logical AND (`and`).
    And,
    /// Logical OR (`or`).
    Or,
    /// Logical XOR (`xor`).
    Xor,

    /// Temporal followed-by operator (`->`).
    FollowedBy,

    /// Bitwise AND (`&`).
    BitAnd,
    /// Bitwise OR (`|`).
    BitOr,
    /// Bitwise XOR (`^`).
    BitXor,
    /// Left shift (`<<`).
    Shl,
    /// Right shift (`>>`).
    Shr,
}

impl BinOp {
    /// Returns the operator's source-level string representation.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Add => "+",
            Self::Sub => "-",
            Self::Mul => "*",
            Self::Div => "/",
            Self::Mod => "%",
            Self::Pow => "**",
            Self::Eq => "==",
            Self::NotEq => "!=",
            Self::Lt => "<",
            Self::Le => "<=",
            Self::Gt => ">",
            Self::Ge => ">=",
            Self::In => "in",
            Self::NotIn => "not in",
            Self::Is => "is",
            Self::And => "and",
            Self::Or => "or",
            Self::Xor => "xor",
            Self::FollowedBy => "->",
            Self::BitAnd => "&",
            Self::BitOr => "|",
            Self::BitXor => "^",
            Self::Shl => "<<",
            Self::Shr => ">>",
        }
    }
}

/// Unary operator
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum UnaryOp {
    /// Arithmetic negation (`-`).
    Neg,
    /// Logical negation (`not`).
    Not,
    /// Bitwise complement (`~`).
    BitNot,
}

impl UnaryOp {
    /// Returns the operator's source-level string representation.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Neg => "-",
            Self::Not => "not",
            Self::BitNot => "~",
        }
    }
}

/// Configuration item
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ConfigItem {
    /// Simple key-value pair.
    Value(String, ConfigValue),
    /// Nested configuration block.
    Nested(String, Vec<Self>),
}

/// Configuration value
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ConfigValue {
    /// Boolean value.
    Bool(bool),
    /// Integer value.
    Int(i64),
    /// Floating-point value.
    Float(f64),
    /// String value.
    Str(String),
    /// Duration value in nanoseconds.
    Duration(u64),
    /// Identifier reference.
    Ident(String),
    /// Array of configuration values.
    Array(Vec<Self>),
    /// Map of key-value pairs.
    Map(Vec<(String, Self)>),
    /// String concatenation: `"prefix-" + field_name + "-suffix"`
    /// Elements are `Str` or `Ident` only.
    Concat(Vec<Self>),
}

impl ConfigValue {
    /// Get value as string (works for Str and Ident)
    pub fn as_string(&self) -> Option<&str> {
        match self {
            Self::Str(s) => Some(s),
            Self::Ident(s) => Some(s),
            _ => None,
        }
    }

    /// Get value as i64
    pub const fn as_int(&self) -> Option<i64> {
        match self {
            Self::Int(i) => Some(*i),
            Self::Float(f) => Some(*f as i64),
            _ => None,
        }
    }

    /// Get value as f64
    pub const fn as_float(&self) -> Option<f64> {
        match self {
            Self::Float(f) => Some(*f),
            Self::Int(i) => Some(*i as f64),
            _ => None,
        }
    }

    /// Get value as bool
    pub const fn as_bool(&self) -> Option<bool> {
        match self {
            Self::Bool(b) => Some(*b),
            _ => None,
        }
    }
}