sigil_parser/
ast.rs

1//! Abstract Syntax Tree for Sigil.
2//!
3//! Represents the polysynthetic structure with evidentiality markers.
4
5use crate::span::{Span, Spanned};
6
7// ============================================
8// Attributes (for no_std, entry points, etc.)
9// ============================================
10
11/// An attribute applied to an item or crate.
12/// Outer: `#[name]` or `#[name(args)]`
13/// Inner: `#![name]` or `#![name(args)]`
14#[derive(Debug, Clone, PartialEq)]
15pub struct Attribute {
16    pub name: Ident,
17    pub args: Option<AttrArgs>,
18    pub is_inner: bool, // true for #![...], false for #[...]
19}
20
21/// Arguments to an attribute.
22#[derive(Debug, Clone, PartialEq)]
23pub enum AttrArgs {
24    /// Parenthesized arguments: `#[attr(a, b, c)]`
25    Paren(Vec<AttrArg>),
26    /// Key-value: `#[attr = "value"]`
27    Eq(Box<Expr>),
28}
29
30/// A single argument in an attribute.
31#[derive(Debug, Clone, PartialEq)]
32pub enum AttrArg {
33    /// Simple identifier: `no_std`
34    Ident(Ident),
35    /// Literal value: `"entry"`
36    Literal(Literal),
37    /// Nested attribute: `cfg(target_os = "none")`
38    Nested(Attribute),
39    /// Key-value pair: `target = "x86_64"`
40    KeyValue { key: Ident, value: Box<Expr> },
41}
42
43/// Crate-level configuration derived from inner attributes.
44#[derive(Debug, Clone, PartialEq, Default)]
45pub struct CrateConfig {
46    /// `#![no_std]` - disable standard library
47    pub no_std: bool,
48    /// `#![no_main]` - custom entry point, no main function required
49    pub no_main: bool,
50    /// `#![feature(...)]` - enabled features
51    pub features: Vec<String>,
52    /// Target architecture (from `#![target(...)]`)
53    pub target: Option<TargetConfig>,
54    /// Linker configuration
55    pub linker: Option<LinkerConfig>,
56}
57
58/// Target-specific configuration.
59#[derive(Debug, Clone, PartialEq, Default)]
60pub struct TargetConfig {
61    pub arch: Option<String>,  // "x86_64", "aarch64", "riscv64"
62    pub os: Option<String>,    // "none", "linux", "windows"
63    pub abi: Option<String>,   // "gnu", "musl", "msvc"
64    pub features: Vec<String>, // CPU features
65}
66
67/// Linker configuration for bare-metal/OS development.
68#[derive(Debug, Clone, PartialEq, Default)]
69pub struct LinkerConfig {
70    /// Path to linker script: `#![linker_script = "link.ld"]`
71    pub script: Option<String>,
72    /// Entry point symbol: `#![entry_point = "_start"]`
73    pub entry_point: Option<String>,
74    /// Base address for code: `#![base_address = 0x100000]`
75    pub base_address: Option<u64>,
76    /// Stack size: `#![stack_size = 0x4000]`
77    pub stack_size: Option<u64>,
78    /// Additional linker flags
79    pub flags: Vec<String>,
80    /// Memory regions for embedded targets
81    pub memory_regions: Vec<MemoryRegion>,
82    /// Output sections configuration
83    pub sections: Vec<SectionConfig>,
84}
85
86/// Memory region for linker scripts.
87#[derive(Debug, Clone, PartialEq)]
88pub struct MemoryRegion {
89    pub name: String,
90    pub origin: u64,
91    pub length: u64,
92    pub attributes: MemoryAttributes,
93}
94
95/// Memory region attributes.
96#[derive(Debug, Clone, PartialEq, Default)]
97pub struct MemoryAttributes {
98    pub readable: bool,
99    pub writable: bool,
100    pub executable: bool,
101}
102
103/// Output section configuration.
104#[derive(Debug, Clone, PartialEq)]
105pub struct SectionConfig {
106    pub name: String,
107    pub address: Option<u64>,
108    pub align: Option<u64>,
109    pub region: Option<String>,
110}
111
112// ============================================
113// SIMD Types for Game Engine / High-Performance
114// ============================================
115
116/// SIMD vector type.
117#[derive(Debug, Clone, PartialEq)]
118pub struct SimdType {
119    /// Element type (f32, f64, i32, etc.)
120    pub element_type: Box<TypeExpr>,
121    /// Number of lanes (2, 4, 8, 16)
122    pub lanes: u8,
123}
124
125/// SIMD intrinsic operations.
126#[derive(Debug, Clone, PartialEq, Copy)]
127pub enum SimdOp {
128    // Arithmetic
129    Add,
130    Sub,
131    Mul,
132    Div,
133    Neg,
134    Abs,
135    Min,
136    Max,
137
138    // Comparison (returns mask)
139    Eq,
140    Ne,
141    Lt,
142    Le,
143    Gt,
144    Ge,
145
146    // Horizontal operations
147    HAdd, // Horizontal add (sum all lanes)
148    Dot,  // Dot product
149
150    // Shuffle/permute
151    Shuffle,
152    Blend,
153
154    // Load/store
155    Load,
156    Store,
157    LoadAligned,
158    StoreAligned,
159
160    // Conversions
161    Cast,
162    Widen,
163    Narrow,
164
165    // Math functions
166    Sqrt,
167    Rsqrt, // Reciprocal square root
168    Rcp,   // Reciprocal
169    Floor,
170    Ceil,
171    Round,
172
173    // Bitwise
174    And,
175    Or,
176    Xor,
177    Not,
178    Shl,
179    Shr,
180}
181
182// ============================================
183// Atomic Types for Concurrency
184// ============================================
185
186/// Atomic memory ordering.
187#[derive(Debug, Clone, PartialEq, Copy, Default)]
188pub enum MemoryOrdering {
189    /// No ordering constraints
190    Relaxed,
191    /// Acquire semantics (for loads)
192    Acquire,
193    /// Release semantics (for stores)
194    Release,
195    /// Acquire + Release
196    AcqRel,
197    /// Sequential consistency
198    #[default]
199    SeqCst,
200}
201
202/// Atomic operations.
203#[derive(Debug, Clone, PartialEq, Copy)]
204pub enum AtomicOp {
205    Load,
206    Store,
207    Swap,
208    CompareExchange,
209    CompareExchangeWeak,
210    FetchAdd,
211    FetchSub,
212    FetchAnd,
213    FetchOr,
214    FetchXor,
215    FetchMin,
216    FetchMax,
217}
218
219// ============================================
220// Derive Macros
221// ============================================
222
223/// Built-in derivable traits.
224#[derive(Debug, Clone, PartialEq)]
225pub enum DeriveTrait {
226    // Standard traits
227    Debug,
228    Clone,
229    Copy,
230    Default,
231    PartialEq,
232    Eq,
233    PartialOrd,
234    Ord,
235    Hash,
236
237    // Game engine specific
238    Component, // ECS component marker
239    Resource,  // ECS resource marker
240    Bundle,    // ECS component bundle
241
242    // Serialization
243    Serialize,
244    Deserialize,
245
246    // Custom derive (name of the derive macro)
247    Custom(String),
248}
249
250/// Struct attributes including derive.
251#[derive(Debug, Clone, PartialEq, Default)]
252pub struct StructAttrs {
253    /// Memory representation
254    pub repr: Option<StructRepr>,
255    /// Packed layout (no padding)
256    pub packed: bool,
257    /// Alignment override
258    pub align: Option<usize>,
259    /// SIMD alignment/vectorization hints
260    pub simd: bool,
261    /// Derived traits
262    pub derives: Vec<DeriveTrait>,
263    /// Outer attributes
264    pub outer_attrs: Vec<Attribute>,
265}
266
267// ============================================
268// Allocator Trait Support
269// ============================================
270
271/// Built-in trait definitions for game engines.
272#[derive(Debug, Clone, PartialEq)]
273pub enum BuiltinTrait {
274    /// Memory allocator trait
275    Allocator,
276    /// Iterator trait
277    Iterator,
278    /// Into iterator
279    IntoIterator,
280    /// Drop/destructor
281    Drop,
282    /// Default construction
283    Default,
284    /// Deref coercion
285    Deref,
286    /// DerefMut coercion
287    DerefMut,
288    /// Index access
289    Index,
290    /// IndexMut access
291    IndexMut,
292}
293
294/// A complete Sigil source file.
295#[derive(Debug, Clone, PartialEq)]
296pub struct SourceFile {
297    /// Inner attributes: `#![no_std]`, `#![feature(...)]`
298    pub attrs: Vec<Attribute>,
299    /// Crate configuration derived from attributes
300    pub config: CrateConfig,
301    /// Top-level items
302    pub items: Vec<Spanned<Item>>,
303}
304
305/// Top-level items.
306#[derive(Debug, Clone, PartialEq)]
307pub enum Item {
308    Function(Function),
309    Struct(StructDef),
310    Enum(EnumDef),
311    Trait(TraitDef),
312    Impl(ImplBlock),
313    TypeAlias(TypeAlias),
314    Module(Module),
315    Use(UseDecl),
316    Const(ConstDef),
317    Static(StaticDef),
318    Actor(ActorDef),
319    ExternBlock(ExternBlock),
320}
321
322/// Foreign function interface block.
323/// `extern "C" { fn foo(x: c_int) -> c_int; }`
324#[derive(Debug, Clone, PartialEq)]
325pub struct ExternBlock {
326    pub abi: String, // "C", "Rust", "system", etc.
327    pub items: Vec<ExternItem>,
328}
329
330/// Items that can appear in an extern block.
331#[derive(Debug, Clone, PartialEq)]
332pub enum ExternItem {
333    Function(ExternFunction),
334    Static(ExternStatic),
335}
336
337/// Foreign function declaration (no body).
338#[derive(Debug, Clone, PartialEq)]
339pub struct ExternFunction {
340    pub visibility: Visibility,
341    pub name: Ident,
342    pub params: Vec<Param>,
343    pub return_type: Option<TypeExpr>,
344    pub variadic: bool, // For C varargs: fn printf(fmt: *const c_char, ...)
345}
346
347/// Foreign static variable.
348#[derive(Debug, Clone, PartialEq)]
349pub struct ExternStatic {
350    pub visibility: Visibility,
351    pub mutable: bool,
352    pub name: Ident,
353    pub ty: TypeExpr,
354}
355
356/// Function attributes for low-level control.
357#[derive(Debug, Clone, PartialEq, Default)]
358pub struct FunctionAttrs {
359    /// Naked function (no prologue/epilogue)
360    pub naked: bool,
361    /// Inline hint
362    pub inline: Option<InlineHint>,
363    /// Calling convention override
364    pub calling_convention: Option<String>,
365    /// No mangle (preserve symbol name)
366    pub no_mangle: bool,
367    /// Link section (e.g., ".text.boot", ".init")
368    pub link_section: Option<String>,
369    /// Export as C function
370    pub export: bool,
371    /// Panic handler function
372    pub panic_handler: bool,
373    /// Entry point function
374    pub entry: bool,
375    /// Interrupt handler with interrupt number
376    pub interrupt: Option<u32>,
377    /// Align function to boundary
378    pub align: Option<usize>,
379    /// Cold function (unlikely to be called)
380    pub cold: bool,
381    /// Hot function (likely to be called)
382    pub hot: bool,
383    /// Test function
384    pub test: bool,
385    /// Outer attributes (raw, for any we don't recognize)
386    pub outer_attrs: Vec<Attribute>,
387}
388
389/// Inline hints for functions.
390#[derive(Debug, Clone, PartialEq)]
391pub enum InlineHint {
392    /// #[inline]
393    Hint,
394    /// #[inline(always)]
395    Always,
396    /// #[inline(never)]
397    Never,
398}
399
400/// Verb aspect for function semantics.
401#[derive(Debug, Clone, Copy, PartialEq, Eq)]
402pub enum Aspect {
403    /// ·ing - Progressive aspect: ongoing/streaming operation
404    Progressive,
405    /// ·ed - Perfective aspect: completed operation
406    Perfective,
407    /// ·able - Potential aspect: capability check (returns bool)
408    Potential,
409    /// ·ive - Resultative aspect: produces a result
410    Resultative,
411}
412
413/// Function definition.
414#[derive(Debug, Clone, PartialEq)]
415pub struct Function {
416    pub visibility: Visibility,
417    pub is_async: bool,
418    pub attrs: FunctionAttrs,
419    pub name: Ident,
420    pub aspect: Option<Aspect>, // Verb aspect: ·ing, ·ed, ·able, ·ive
421    pub generics: Option<Generics>,
422    pub params: Vec<Param>,
423    pub return_type: Option<TypeExpr>,
424    pub where_clause: Option<WhereClause>,
425    pub body: Option<Block>,
426}
427
428/// Visibility modifier.
429#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
430pub enum Visibility {
431    #[default]
432    Private,
433    Public,
434    Crate,
435    Super,
436}
437
438/// Identifier with optional evidentiality and affect markers.
439#[derive(Debug, Clone, PartialEq)]
440pub struct Ident {
441    pub name: String,
442    pub evidentiality: Option<Evidentiality>,
443    pub affect: Option<Affect>,
444    pub span: Span,
445}
446
447/// Evidentiality markers from the type system.
448#[derive(Debug, Clone, Copy, PartialEq, Eq)]
449pub enum Evidentiality {
450    Known,     // !
451    Uncertain, // ?
452    Reported,  // ~
453    Paradox,   // ‽
454}
455
456/// Affective markers for sentiment and emotion tracking.
457#[derive(Debug, Clone, PartialEq)]
458pub struct Affect {
459    pub sentiment: Option<Sentiment>,
460    pub sarcasm: bool, // ⸮
461    pub intensity: Option<Intensity>,
462    pub formality: Option<Formality>,
463    pub emotion: Option<Emotion>,
464    pub confidence: Option<Confidence>,
465}
466
467impl Default for Affect {
468    fn default() -> Self {
469        Affect {
470            sentiment: None,
471            sarcasm: false,
472            intensity: None,
473            formality: None,
474            emotion: None,
475            confidence: None,
476        }
477    }
478}
479
480impl Affect {
481    pub fn is_empty(&self) -> bool {
482        self.sentiment.is_none()
483            && !self.sarcasm
484            && self.intensity.is_none()
485            && self.formality.is_none()
486            && self.emotion.is_none()
487            && self.confidence.is_none()
488    }
489}
490
491/// Sentiment polarity markers.
492#[derive(Debug, Clone, Copy, PartialEq, Eq)]
493pub enum Sentiment {
494    Positive, // ⊕
495    Negative, // ⊖
496    Neutral,  // ⊜
497}
498
499/// Intensity modifiers.
500#[derive(Debug, Clone, Copy, PartialEq, Eq)]
501pub enum Intensity {
502    Up,   // ↑ (intensifier)
503    Down, // ↓ (dampener)
504    Max,  // ⇈ (maximum)
505}
506
507/// Formality register.
508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
509pub enum Formality {
510    Formal,   // ♔
511    Informal, // ♟
512}
513
514/// Emotion categories (Plutchik's wheel).
515#[derive(Debug, Clone, Copy, PartialEq, Eq)]
516pub enum Emotion {
517    Joy,      // ☺
518    Sadness,  // ☹
519    Anger,    // ⚡
520    Fear,     // ❄
521    Surprise, // ✦
522    Love,     // ♡
523}
524
525/// Confidence level markers.
526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527pub enum Confidence {
528    High,   // ◉
529    Medium, // ◎
530    Low,    // ○
531}
532
533/// Function parameter.
534#[derive(Debug, Clone, PartialEq)]
535pub struct Param {
536    pub pattern: Pattern,
537    pub ty: TypeExpr,
538}
539
540/// Generic parameters.
541#[derive(Debug, Clone, PartialEq)]
542pub struct Generics {
543    pub params: Vec<GenericParam>,
544}
545
546#[derive(Debug, Clone, PartialEq)]
547pub enum GenericParam {
548    Type {
549        name: Ident,
550        bounds: Vec<TypeExpr>,
551        evidentiality: Option<Evidentiality>,
552    },
553    Const {
554        name: Ident,
555        ty: TypeExpr,
556    },
557    Lifetime(String),
558}
559
560/// Where clause for bounds.
561#[derive(Debug, Clone, PartialEq)]
562pub struct WhereClause {
563    pub predicates: Vec<WherePredicate>,
564}
565
566#[derive(Debug, Clone, PartialEq)]
567pub struct WherePredicate {
568    pub ty: TypeExpr,
569    pub bounds: Vec<TypeExpr>,
570}
571
572/// Type expressions.
573#[derive(Debug, Clone, PartialEq)]
574pub enum TypeExpr {
575    /// Simple named type: `i32`, `String`
576    Path(TypePath),
577    /// Reference: `&T`, `&mut T`
578    Reference { mutable: bool, inner: Box<TypeExpr> },
579    /// Pointer: `*const T`, `*mut T`
580    Pointer { mutable: bool, inner: Box<TypeExpr> },
581    /// Array: `[T; N]`
582    Array {
583        element: Box<TypeExpr>,
584        size: Box<Expr>,
585    },
586    /// Slice: `[T]`
587    Slice(Box<TypeExpr>),
588    /// Tuple: `(A, B, C)`
589    Tuple(Vec<TypeExpr>),
590    /// Function: `fn(A, B) -> C`
591    Function {
592        params: Vec<TypeExpr>,
593        return_type: Option<Box<TypeExpr>>,
594    },
595    /// With evidentiality: `T!`, `T?`, `T~`, or with error type: `T?[Error]`, `T![Error]`
596    /// The error type syntax is sugar for Result<T, Error> with evidentiality tracking:
597    /// - `T?[E]` means Result<T, E> with uncertain evidentiality
598    /// - `T![E]` means Result<T, E> with known/infallible path
599    /// - `T~[E]` means Result<T, E> from external/reported source
600    Evidential {
601        inner: Box<TypeExpr>,
602        evidentiality: Evidentiality,
603        /// Optional error type for Result sugar: `T?[ErrorType]`
604        error_type: Option<Box<TypeExpr>>,
605    },
606    /// Cycle type: `Cycle<N>`
607    Cycle { modulus: Box<Expr> },
608    /// SIMD vector type: `simd<f32, 4>`, `Vec4f`
609    Simd { element: Box<TypeExpr>, lanes: u8 },
610    /// Atomic type: `atomic<T>`
611    Atomic(Box<TypeExpr>),
612    /// Never type: `!` or `never`
613    Never,
614    /// Inferred: `_`
615    Infer,
616}
617
618/// Type path with optional generics.
619#[derive(Debug, Clone, PartialEq)]
620pub struct TypePath {
621    pub segments: Vec<PathSegment>,
622}
623
624#[derive(Debug, Clone, PartialEq)]
625pub struct PathSegment {
626    pub ident: Ident,
627    pub generics: Option<Vec<TypeExpr>>,
628}
629
630/// Memory representation for structs.
631#[derive(Debug, Clone, PartialEq)]
632pub enum StructRepr {
633    /// C-compatible layout
634    C,
635    /// Transparent (single field struct)
636    Transparent,
637    /// Specific integer type
638    Int(String),
639}
640
641/// Struct definition.
642#[derive(Debug, Clone, PartialEq)]
643pub struct StructDef {
644    pub visibility: Visibility,
645    pub attrs: StructAttrs,
646    pub name: Ident,
647    pub generics: Option<Generics>,
648    pub fields: StructFields,
649}
650
651#[derive(Debug, Clone, PartialEq)]
652pub enum StructFields {
653    Named(Vec<FieldDef>),
654    Tuple(Vec<TypeExpr>),
655    Unit,
656}
657
658#[derive(Debug, Clone, PartialEq)]
659pub struct FieldDef {
660    pub visibility: Visibility,
661    pub name: Ident,
662    pub ty: TypeExpr,
663    /// Default value for the field (e.g., `field: Type = default_expr`)
664    pub default: Option<Expr>,
665}
666
667/// Enum definition.
668#[derive(Debug, Clone, PartialEq)]
669pub struct EnumDef {
670    pub visibility: Visibility,
671    pub name: Ident,
672    pub generics: Option<Generics>,
673    pub variants: Vec<EnumVariant>,
674}
675
676#[derive(Debug, Clone, PartialEq)]
677pub struct EnumVariant {
678    pub name: Ident,
679    pub fields: StructFields,
680    pub discriminant: Option<Expr>,
681}
682
683/// Trait definition.
684#[derive(Debug, Clone, PartialEq)]
685pub struct TraitDef {
686    pub visibility: Visibility,
687    pub name: Ident,
688    pub generics: Option<Generics>,
689    pub supertraits: Vec<TypeExpr>,
690    pub items: Vec<TraitItem>,
691}
692
693#[derive(Debug, Clone, PartialEq)]
694pub enum TraitItem {
695    Function(Function),
696    Type { name: Ident, bounds: Vec<TypeExpr> },
697    Const { name: Ident, ty: TypeExpr },
698}
699
700/// Impl block.
701#[derive(Debug, Clone, PartialEq)]
702pub struct ImplBlock {
703    pub generics: Option<Generics>,
704    pub trait_: Option<TypePath>,
705    pub self_ty: TypeExpr,
706    pub items: Vec<ImplItem>,
707}
708
709#[derive(Debug, Clone, PartialEq)]
710pub enum ImplItem {
711    Function(Function),
712    Type(TypeAlias),
713    Const(ConstDef),
714}
715
716/// Type alias.
717#[derive(Debug, Clone, PartialEq)]
718pub struct TypeAlias {
719    pub visibility: Visibility,
720    pub name: Ident,
721    pub generics: Option<Generics>,
722    pub ty: TypeExpr,
723}
724
725/// Module.
726#[derive(Debug, Clone, PartialEq)]
727pub struct Module {
728    pub visibility: Visibility,
729    pub name: Ident,
730    pub items: Option<Vec<Spanned<Item>>>,
731}
732
733/// Use declaration.
734#[derive(Debug, Clone, PartialEq)]
735pub struct UseDecl {
736    pub visibility: Visibility,
737    pub tree: UseTree,
738}
739
740#[derive(Debug, Clone, PartialEq)]
741pub enum UseTree {
742    Path { prefix: Ident, suffix: Box<UseTree> },
743    Name(Ident),
744    Rename { name: Ident, alias: Ident },
745    Glob,
746    Group(Vec<UseTree>),
747}
748
749/// Const definition.
750#[derive(Debug, Clone, PartialEq)]
751pub struct ConstDef {
752    pub visibility: Visibility,
753    pub name: Ident,
754    pub ty: TypeExpr,
755    pub value: Expr,
756}
757
758/// Static definition.
759#[derive(Debug, Clone, PartialEq)]
760pub struct StaticDef {
761    pub visibility: Visibility,
762    pub mutable: bool,
763    pub name: Ident,
764    pub ty: TypeExpr,
765    pub value: Expr,
766}
767
768/// Actor definition (concurrency).
769#[derive(Debug, Clone, PartialEq)]
770pub struct ActorDef {
771    pub visibility: Visibility,
772    pub name: Ident,
773    pub generics: Option<Generics>,
774    pub state: Vec<FieldDef>,
775    pub handlers: Vec<MessageHandler>,
776}
777
778#[derive(Debug, Clone, PartialEq)]
779pub struct MessageHandler {
780    pub message: Ident,
781    pub params: Vec<Param>,
782    pub return_type: Option<TypeExpr>,
783    pub body: Block,
784}
785
786/// Code block.
787#[derive(Debug, Clone, PartialEq)]
788pub struct Block {
789    pub stmts: Vec<Stmt>,
790    pub expr: Option<Box<Expr>>,
791}
792
793/// Statements.
794#[derive(Debug, Clone, PartialEq)]
795pub enum Stmt {
796    Let {
797        pattern: Pattern,
798        ty: Option<TypeExpr>,
799        init: Option<Expr>,
800    },
801    Expr(Expr),
802    Semi(Expr),
803    Item(Box<Item>),
804}
805
806/// Patterns.
807#[derive(Debug, Clone, PartialEq)]
808pub enum Pattern {
809    Ident {
810        mutable: bool,
811        name: Ident,
812        evidentiality: Option<Evidentiality>,
813    },
814    Tuple(Vec<Pattern>),
815    Struct {
816        path: TypePath,
817        fields: Vec<FieldPattern>,
818        rest: bool,
819    },
820    TupleStruct {
821        path: TypePath,
822        fields: Vec<Pattern>,
823    },
824    Slice(Vec<Pattern>),
825    Or(Vec<Pattern>),
826    Literal(Literal),
827    Range {
828        start: Option<Box<Pattern>>,
829        end: Option<Box<Pattern>>,
830        inclusive: bool,
831    },
832    Wildcard,
833    Rest,
834}
835
836#[derive(Debug, Clone, PartialEq)]
837pub struct FieldPattern {
838    pub name: Ident,
839    pub pattern: Option<Pattern>,
840}
841
842/// Expressions.
843#[derive(Debug, Clone, PartialEq)]
844pub enum Expr {
845    /// Literal value
846    Literal(Literal),
847    /// Variable reference
848    Path(TypePath),
849    /// Binary operation
850    Binary {
851        left: Box<Expr>,
852        op: BinOp,
853        right: Box<Expr>,
854    },
855    /// Unary operation
856    Unary { op: UnaryOp, expr: Box<Expr> },
857    /// Pipe expression: `x|f|g`
858    Pipe {
859        expr: Box<Expr>,
860        operations: Vec<PipeOp>,
861    },
862    /// Incorporation: `file·open·read`
863    Incorporation { segments: Vec<IncorporationSegment> },
864    /// Morpheme application: `τ{f}`
865    Morpheme { kind: MorphemeKind, body: Box<Expr> },
866    /// Function call
867    Call { func: Box<Expr>, args: Vec<Expr> },
868    /// Method call
869    MethodCall {
870        receiver: Box<Expr>,
871        method: Ident,
872        args: Vec<Expr>,
873    },
874    /// Field access
875    Field { expr: Box<Expr>, field: Ident },
876    /// Index: `arr[i]`
877    Index { expr: Box<Expr>, index: Box<Expr> },
878    /// Array literal
879    Array(Vec<Expr>),
880    /// Tuple literal
881    Tuple(Vec<Expr>),
882    /// Struct literal
883    Struct {
884        path: TypePath,
885        fields: Vec<FieldInit>,
886        rest: Option<Box<Expr>>,
887    },
888    /// Block expression
889    Block(Block),
890    /// If expression
891    If {
892        condition: Box<Expr>,
893        then_branch: Block,
894        else_branch: Option<Box<Expr>>,
895    },
896    /// Match expression
897    Match {
898        expr: Box<Expr>,
899        arms: Vec<MatchArm>,
900    },
901    /// Loop
902    Loop(Block),
903    /// While loop
904    While { condition: Box<Expr>, body: Block },
905    /// For loop
906    For {
907        pattern: Pattern,
908        iter: Box<Expr>,
909        body: Block,
910    },
911    /// Closure: `{x => x + 1}` or `|x| x + 1`
912    Closure {
913        params: Vec<ClosureParam>,
914        body: Box<Expr>,
915    },
916    /// Await with optional evidentiality: `expr⌛` or `expr⌛?` or `expr⌛!` or `expr⌛~`
917    /// The evidentiality marker specifies how to handle the awaited result:
918    /// - `⌛?` - await and propagate error (uncertain)
919    /// - `⌛!` - await, expect success (known/infallible)
920    /// - `⌛~` - await external/reported source
921    /// - `⌛‽` - await with trust boundary crossing
922    Await {
923        expr: Box<Expr>,
924        evidentiality: Option<Evidentiality>,
925    },
926    /// Try: `expr?`
927    Try(Box<Expr>),
928    /// Return
929    Return(Option<Box<Expr>>),
930    /// Break
931    Break(Option<Box<Expr>>),
932    /// Continue
933    Continue,
934    /// Range: `a..b` or `a..=b`
935    Range {
936        start: Option<Box<Expr>>,
937        end: Option<Box<Expr>>,
938        inclusive: bool,
939    },
940    /// Macro invocation
941    Macro { path: TypePath, tokens: String },
942    /// With evidentiality marker
943    Evidential {
944        expr: Box<Expr>,
945        evidentiality: Evidentiality,
946    },
947    /// Assignment: `x = value`
948    Assign { target: Box<Expr>, value: Box<Expr> },
949    /// Unsafe block: `unsafe { ... }`
950    Unsafe(Block),
951    /// Raw pointer dereference: `*ptr`
952    Deref(Box<Expr>),
953    /// Address-of: `&expr` or `&mut expr`
954    AddrOf { mutable: bool, expr: Box<Expr> },
955    /// Cast: `expr as Type`
956    Cast { expr: Box<Expr>, ty: TypeExpr },
957
958    /// Inline assembly: `asm!("instruction", ...)`
959    InlineAsm(InlineAsm),
960
961    /// Volatile read: `volatile read<T>(ptr)` or `volatile read(ptr)`
962    VolatileRead {
963        ptr: Box<Expr>,
964        ty: Option<TypeExpr>,
965    },
966
967    /// Volatile write: `volatile write<T>(ptr, value)` or `volatile write(ptr, value)`
968    VolatileWrite {
969        ptr: Box<Expr>,
970        value: Box<Expr>,
971        ty: Option<TypeExpr>,
972    },
973
974    // ========================================
975    // SIMD Operations
976    // ========================================
977    /// SIMD vector literal: `simd[1.0, 2.0, 3.0, 4.0]`
978    SimdLiteral {
979        elements: Vec<Expr>,
980        ty: Option<TypeExpr>,
981    },
982
983    /// SIMD intrinsic operation: `simd::add(a, b)`
984    SimdIntrinsic { op: SimdOp, args: Vec<Expr> },
985
986    /// SIMD shuffle: `simd::shuffle(a, b, [0, 4, 1, 5])`
987    SimdShuffle {
988        a: Box<Expr>,
989        b: Box<Expr>,
990        indices: Vec<u8>,
991    },
992
993    /// SIMD splat (broadcast scalar to all lanes): `simd::splat(x)`
994    SimdSplat { value: Box<Expr>, lanes: u8 },
995
996    /// SIMD extract single lane: `simd::extract(v, 0)`
997    SimdExtract { vector: Box<Expr>, index: u8 },
998
999    /// SIMD insert into lane: `simd::insert(v, 0, value)`
1000    SimdInsert {
1001        vector: Box<Expr>,
1002        index: u8,
1003        value: Box<Expr>,
1004    },
1005
1006    // ========================================
1007    // Atomic Operations
1008    // ========================================
1009    /// Atomic operation: `atomic::load(&x, Ordering::SeqCst)`
1010    AtomicOp {
1011        op: AtomicOp,
1012        ptr: Box<Expr>,
1013        value: Option<Box<Expr>>,    // For store, swap, fetch_add, etc.
1014        expected: Option<Box<Expr>>, // For compare_exchange
1015        ordering: MemoryOrdering,
1016        failure_ordering: Option<MemoryOrdering>, // For compare_exchange
1017    },
1018
1019    /// Atomic fence: `atomic::fence(Ordering::SeqCst)`
1020    AtomicFence { ordering: MemoryOrdering },
1021
1022    // ==========================================
1023    // Protocol Expressions - Sigil-native networking
1024    // All protocol expressions yield values with Reported evidentiality
1025    // ==========================================
1026    /// HTTP request: `http·get(url)`, `http·post(url)`, etc.
1027    /// Incorporation pattern for building HTTP requests
1028    HttpRequest {
1029        method: HttpMethod,
1030        url: Box<Expr>,
1031        headers: Vec<(Expr, Expr)>,
1032        body: Option<Box<Expr>>,
1033        timeout: Option<Box<Expr>>,
1034    },
1035
1036    /// gRPC call: `grpc·call(service, method)`
1037    /// Incorporation pattern for gRPC operations
1038    GrpcCall {
1039        service: Box<Expr>,
1040        method: Box<Expr>,
1041        message: Option<Box<Expr>>,
1042        metadata: Vec<(Expr, Expr)>,
1043        timeout: Option<Box<Expr>>,
1044    },
1045
1046    /// WebSocket connection: `ws·connect(url)`
1047    /// Incorporation pattern for WebSocket operations
1048    WebSocketConnect {
1049        url: Box<Expr>,
1050        protocols: Vec<Expr>,
1051        headers: Vec<(Expr, Expr)>,
1052    },
1053
1054    /// WebSocket message: `ws·message(data)` or `ws·text(str)` / `ws·binary(bytes)`
1055    WebSocketMessage {
1056        kind: WebSocketMessageKind,
1057        data: Box<Expr>,
1058    },
1059
1060    /// Kafka operation: `kafka·produce(topic, message)`, `kafka·consume(topic)`
1061    KafkaOp {
1062        kind: KafkaOpKind,
1063        topic: Box<Expr>,
1064        payload: Option<Box<Expr>>,
1065        key: Option<Box<Expr>>,
1066        partition: Option<Box<Expr>>,
1067    },
1068
1069    /// GraphQL query: `graphql·query(document)` or `graphql·mutation(document)`
1070    GraphQLOp {
1071        kind: GraphQLOpKind,
1072        document: Box<Expr>,
1073        variables: Option<Box<Expr>>,
1074        operation_name: Option<Box<Expr>>,
1075    },
1076
1077    /// Protocol stream: iterable over network messages
1078    /// `http·stream(url)`, `ws·stream()`, `kafka·stream(topic)`
1079    ProtocolStream {
1080        protocol: ProtocolKind,
1081        source: Box<Expr>,
1082        config: Option<Box<Expr>>,
1083    },
1084}
1085
1086/// Inline assembly expression.
1087#[derive(Debug, Clone, PartialEq)]
1088pub struct InlineAsm {
1089    /// The assembly template string
1090    pub template: String,
1091    /// Output operands
1092    pub outputs: Vec<AsmOperand>,
1093    /// Input operands
1094    pub inputs: Vec<AsmOperand>,
1095    /// Clobbered registers
1096    pub clobbers: Vec<String>,
1097    /// Assembly options
1098    pub options: AsmOptions,
1099}
1100
1101/// An assembly operand (input or output).
1102#[derive(Debug, Clone, PartialEq)]
1103pub struct AsmOperand {
1104    /// Constraint string (e.g., "=r", "r", "m", or register name)
1105    pub constraint: String,
1106    /// The expression to bind
1107    pub expr: Expr,
1108    /// The kind of operand
1109    pub kind: AsmOperandKind,
1110    /// For inout operands, the output expression (if different from input)
1111    pub output: Option<Box<Expr>>,
1112}
1113
1114/// Assembly operand kind.
1115#[derive(Debug, Clone, PartialEq, Eq)]
1116pub enum AsmOperandKind {
1117    /// Input only
1118    Input,
1119    /// Output only
1120    Output,
1121    /// Input and output (same register)
1122    InOut,
1123}
1124
1125/// Assembly options/modifiers.
1126#[derive(Debug, Clone, PartialEq, Default)]
1127pub struct AsmOptions {
1128    /// Volatile (has side effects, cannot be optimized away)
1129    pub volatile: bool,
1130    /// Pure assembly (no side effects)
1131    pub pure_asm: bool,
1132    /// No memory clobber
1133    pub nomem: bool,
1134    /// No stack
1135    pub nostack: bool,
1136    /// Preserves flags
1137    pub preserves_flags: bool,
1138    /// Read-only (inputs only)
1139    pub readonly: bool,
1140    /// AT&T syntax (vs Intel)
1141    pub att_syntax: bool,
1142}
1143
1144/// Pipe operation in a chain.
1145#[derive(Debug, Clone, PartialEq)]
1146pub enum PipeOp {
1147    /// Transform morpheme: `τ{f}`
1148    Transform(Box<Expr>),
1149    /// Filter morpheme: `φ{p}`
1150    Filter(Box<Expr>),
1151    /// Sort morpheme: `σ` or `σ.field`
1152    Sort(Option<Ident>),
1153    /// Reduce morpheme: `ρ{f}`
1154    Reduce(Box<Expr>),
1155    /// Sum reduction: `ρ+` or `ρ_sum` - sum all elements
1156    ReduceSum,
1157    /// Product reduction: `ρ*` or `ρ_prod` - multiply all elements
1158    ReduceProd,
1159    /// Min reduction: `ρ_min` - find minimum element
1160    ReduceMin,
1161    /// Max reduction: `ρ_max` - find maximum element
1162    ReduceMax,
1163    /// Concat reduction: `ρ++` or `ρ_cat` - concatenate strings/arrays
1164    ReduceConcat,
1165    /// All reduction: `ρ&` or `ρ_all` - logical AND (all true)
1166    ReduceAll,
1167    /// Any reduction: `ρ|` or `ρ_any` - logical OR (any true)
1168    ReduceAny,
1169    /// Middle morpheme: `μ` - get middle/median element
1170    Middle,
1171    /// Choice morpheme: `χ` - random element selection
1172    Choice,
1173    /// Nth morpheme: `ν{n}` - get nth element
1174    Nth(Box<Expr>),
1175    /// Next morpheme: `ξ` - get next element (iterator)
1176    Next,
1177    /// First morpheme: `α` - get first element
1178    First,
1179    /// Last morpheme: `ω` - get last element
1180    Last,
1181    /// Parallel morpheme: `∥{op}` or `parallel{op}` - execute operation in parallel
1182    /// Wraps another operation to run it across multiple threads
1183    Parallel(Box<PipeOp>),
1184    /// GPU compute morpheme: `⊛{op}` or `gpu{op}` - execute operation on GPU
1185    /// Wraps another operation to run it as a compute shader
1186    Gpu(Box<PipeOp>),
1187    /// Method call
1188    Method { name: Ident, args: Vec<Expr> },
1189    /// Await
1190    Await,
1191    /// Match morpheme: `|match{ Pattern => expr, ... }`
1192    /// Applies pattern matching to the piped value
1193    Match(Vec<MatchArm>),
1194    /// Trust boundary morpheme: `|‽` or `|‽{mapper}`
1195    /// Uses interrobang (‽) to signal crossing a trust/certainty boundary.
1196    /// Unwraps Result/Option or propagates errors, with optional error transformation.
1197    TryMap(Option<Box<Expr>>),
1198    /// Named morpheme: `·map{f}`, `·flow{f}`
1199    Named {
1200        prefix: Vec<Ident>,
1201        body: Option<Box<Expr>>,
1202    },
1203
1204    // ==========================================
1205    // Protocol Operations - Sigil-native networking
1206    // ==========================================
1207    /// Send operation: `|send{data}` or `|⇒{data}` - send data over connection
1208    /// Results are automatically marked with Reported evidentiality
1209    Send(Box<Expr>),
1210
1211    /// Receive operation: `|recv` or `|⇐` - receive data from connection
1212    /// Results are automatically marked with Reported evidentiality
1213    Recv,
1214
1215    /// Stream operation: `|stream{handler}` or `|≋{handler}` - iterate over incoming data
1216    /// Each element is marked with Reported evidentiality
1217    Stream(Box<Expr>),
1218
1219    /// Connect operation: `|connect{config}` or `|⊸{config}` - establish connection
1220    Connect(Option<Box<Expr>>),
1221
1222    /// Close operation: `|close` or `|⊗` - close connection gracefully
1223    Close,
1224
1225    /// Protocol header: `|header{name, value}` - add/set header
1226    Header { name: Box<Expr>, value: Box<Expr> },
1227
1228    /// Protocol body: `|body{data}` - set request body
1229    Body(Box<Expr>),
1230
1231    /// Timeout: `|timeout{ms}` or `|⏱{ms}` - set operation timeout
1232    Timeout(Box<Expr>),
1233
1234    /// Retry: `|retry{count}` or `|retry{count, strategy}` - retry on failure
1235    Retry {
1236        count: Box<Expr>,
1237        strategy: Option<Box<Expr>>,
1238    },
1239
1240    // ==========================================
1241    // Evidence Promotion Operations
1242    // ==========================================
1243    /// Validate operation: `|validate!{predicate}` - promote evidence with validation
1244    /// Takes a predicate function that validates the data.
1245    /// If validation passes: ~ → ! (reported → known)
1246    /// If validation fails: returns an error
1247    /// Example: `data~|validate!{x => x.id > 0 && x.name.len > 0}`
1248    Validate {
1249        predicate: Box<Expr>,
1250        target_evidence: Evidentiality,
1251    },
1252
1253    /// Assume operation: `|assume!` or `|assume!("reason")` - explicit trust promotion
1254    /// Escape hatch that promotes evidence with an audit trail.
1255    /// Always logs the assumption for security review.
1256    /// Example: `external_data~|assume!("trusted legacy system")`
1257    Assume {
1258        reason: Option<Box<Expr>>,
1259        target_evidence: Evidentiality,
1260    },
1261
1262    /// Assert evidence: `|assert_evidence!{expected}` - verify evidence level at compile time
1263    /// Fails compilation if actual evidence doesn't match expected.
1264    /// Example: `data|assert_evidence!{!}` - assert data is known
1265    AssertEvidence(Evidentiality),
1266
1267    // ==========================================
1268    // Scope Functions (Kotlin-inspired)
1269    // ==========================================
1270    /// Also: `|also{f}` - execute side effect, return original value unchanged
1271    /// Like Kotlin's `also` - useful for logging/debugging in pipelines
1272    /// Example: `data|also{println}|process` - logs data, then processes it
1273    Also(Box<Expr>),
1274
1275    /// Apply: `|apply{block}` - mutate value in place, return modified value
1276    /// Like Kotlin's `apply` - useful for configuration/setup
1277    /// Example: `config|apply{.timeout = 5000; .retries = 3}`
1278    Apply(Box<Expr>),
1279
1280    /// TakeIf: `|take_if{predicate}` - return Some(value) if predicate true, None otherwise
1281    /// Like Kotlin's `takeIf` - useful for conditional pipelines
1282    /// Example: `user|take_if{.age >= 18}` - returns Option<User>
1283    TakeIf(Box<Expr>),
1284
1285    /// TakeUnless: `|take_unless{predicate}` - return Some(value) if predicate false
1286    /// Like Kotlin's `takeUnless` - inverse of take_if
1287    /// Example: `item|take_unless{.is_deleted}` - returns Option<Item>
1288    TakeUnless(Box<Expr>),
1289
1290    /// Let: `|let{f}` - transform value, like map but reads better for single values
1291    /// Like Kotlin's `let` - essentially an alias for transform
1292    /// Example: `name|let{.to_uppercase}` - transforms the name
1293    Let(Box<Expr>),
1294
1295    // ==========================================
1296    // Mathematical & APL-Inspired Operations
1297    // ==========================================
1298    /// All/ForAll: `|∀{p}` or `|all{p}` - check if ALL elements satisfy predicate
1299    /// Returns bool. Short-circuits on first false.
1300    /// Example: `numbers|∀{x => x > 0}` - are all positive?
1301    All(Box<Expr>),
1302
1303    /// Any/Exists: `|∃{p}` or `|any{p}` - check if ANY element satisfies predicate
1304    /// Returns bool. Short-circuits on first true.
1305    /// Example: `items|∃{.is_valid}` - is any valid?
1306    Any(Box<Expr>),
1307
1308    /// Compose: `|∘{f}` or `|compose{f}` - function composition
1309    /// Creates a new function that applies f after the current transformation.
1310    /// Example: `parse|∘{validate}|∘{save}` - compose three functions
1311    Compose(Box<Expr>),
1312
1313    /// Zip/Join: `|⋈{other}` or `|zip{other}` - combine with another collection
1314    /// Pairs elements from two collections into tuples.
1315    /// Example: `names|⋈{ages}` -> [(name1, age1), (name2, age2), ...]
1316    Zip(Box<Expr>),
1317
1318    /// Scan/Integral: `|∫{f}` or `|scan{f}` - cumulative fold (like Haskell's scanl)
1319    /// Returns all intermediate accumulator values.
1320    /// Example: `[1,2,3]|∫{+}` -> [1, 3, 6] (running sum)
1321    Scan(Box<Expr>),
1322
1323    /// Diff/Derivative: `|∂` or `|diff` - differences between adjacent elements
1324    /// Returns a collection of deltas.
1325    /// Example: `[1, 4, 6, 10]|∂` -> [3, 2, 4]
1326    Diff,
1327
1328    /// Gradient: `|∇{var}` or `|grad{var}` - automatic differentiation
1329    /// Computes gradient of expression with respect to variable.
1330    /// Example: `loss|∇{weights}` - gradient for backprop
1331    Gradient(Box<Expr>),
1332
1333    /// Sort Ascending: `|⍋` or `|sort_asc` - APL grade-up
1334    /// Sorts in ascending order (same as σ but more explicit)
1335    SortAsc,
1336
1337    /// Sort Descending: `|⍒` or `|sort_desc` - APL grade-down
1338    /// Sorts in descending order
1339    SortDesc,
1340
1341    /// Reverse: `|⌽` or `|rev` - APL rotate/reverse
1342    /// Reverses the collection
1343    Reverse,
1344
1345    /// Cycle: `|↻{n}` or `|cycle{n}` - repeat collection n times
1346    /// Example: `[1,2]|↻{3}` -> [1,2,1,2,1,2]
1347    Cycle(Box<Expr>),
1348
1349    /// Windows: `|⌺{n}` or `|windows{n}` - sliding window
1350    /// Example: `[1,2,3,4]|⌺{2}` -> [[1,2], [2,3], [3,4]]
1351    Windows(Box<Expr>),
1352
1353    /// Chunks: `|⊞{n}` or `|chunks{n}` - split into chunks
1354    /// Example: `[1,2,3,4]|⊞{2}` -> [[1,2], [3,4]]
1355    Chunks(Box<Expr>),
1356
1357    /// Flatten: `|⋳` or `|flatten` - flatten nested collection
1358    /// Example: `[[1,2], [3,4]]|⋳` -> [1,2,3,4]
1359    Flatten,
1360
1361    /// Unique: `|∪` or `|unique` - remove duplicates (set union with self)
1362    /// Example: `[1,2,2,3,3,3]|∪` -> [1,2,3]
1363    Unique,
1364
1365    /// Enumerate: `|⍳` or `|enumerate` - APL iota, pair with indices
1366    /// Example: `["a","b","c"]|⍳` -> [(0,"a"), (1,"b"), (2,"c")]
1367    Enumerate,
1368}
1369
1370/// Incorporation segment.
1371#[derive(Debug, Clone, PartialEq)]
1372pub struct IncorporationSegment {
1373    pub name: Ident,
1374    pub args: Option<Vec<Expr>>,
1375}
1376
1377/// Morpheme kinds.
1378#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1379pub enum MorphemeKind {
1380    Transform, // τ
1381    Filter,    // φ
1382    Sort,      // σ
1383    Reduce,    // ρ
1384    Lambda,    // λ
1385    Sum,       // Σ
1386    Product,   // Π
1387    Middle,    // μ
1388    Choice,    // χ
1389    Nth,       // ν
1390    Next,      // ξ
1391    First,     // α
1392    Last,      // ω
1393}
1394
1395// ==========================================
1396// Protocol Types - Sigil-native networking
1397// ==========================================
1398
1399/// HTTP methods for http· incorporation.
1400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1401pub enum HttpMethod {
1402    Get,
1403    Post,
1404    Put,
1405    Delete,
1406    Patch,
1407    Head,
1408    Options,
1409    Connect,
1410    Trace,
1411}
1412
1413impl std::fmt::Display for HttpMethod {
1414    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1415        match self {
1416            HttpMethod::Get => write!(f, "GET"),
1417            HttpMethod::Post => write!(f, "POST"),
1418            HttpMethod::Put => write!(f, "PUT"),
1419            HttpMethod::Delete => write!(f, "DELETE"),
1420            HttpMethod::Patch => write!(f, "PATCH"),
1421            HttpMethod::Head => write!(f, "HEAD"),
1422            HttpMethod::Options => write!(f, "OPTIONS"),
1423            HttpMethod::Connect => write!(f, "CONNECT"),
1424            HttpMethod::Trace => write!(f, "TRACE"),
1425        }
1426    }
1427}
1428
1429/// WebSocket message kinds for ws· incorporation.
1430#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1431pub enum WebSocketMessageKind {
1432    Text,
1433    Binary,
1434    Ping,
1435    Pong,
1436    Close,
1437}
1438
1439/// Kafka operation kinds for kafka· incorporation.
1440#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1441pub enum KafkaOpKind {
1442    Produce,
1443    Consume,
1444    Subscribe,
1445    Unsubscribe,
1446    Commit,
1447    Seek,
1448}
1449
1450/// GraphQL operation kinds for graphql· incorporation.
1451#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1452pub enum GraphQLOpKind {
1453    Query,
1454    Mutation,
1455    Subscription,
1456}
1457
1458/// Protocol kinds for stream expressions.
1459#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1460pub enum ProtocolKind {
1461    Http,
1462    Grpc,
1463    WebSocket,
1464    Kafka,
1465    Amqp,
1466    GraphQL,
1467}
1468
1469impl std::fmt::Display for ProtocolKind {
1470    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1471        match self {
1472            ProtocolKind::Http => write!(f, "http"),
1473            ProtocolKind::Grpc => write!(f, "grpc"),
1474            ProtocolKind::WebSocket => write!(f, "ws"),
1475            ProtocolKind::Kafka => write!(f, "kafka"),
1476            ProtocolKind::Amqp => write!(f, "amqp"),
1477            ProtocolKind::GraphQL => write!(f, "graphql"),
1478        }
1479    }
1480}
1481
1482/// Binary operators.
1483#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1484pub enum BinOp {
1485    Add,
1486    Sub,
1487    Mul,
1488    Div,
1489    Rem,
1490    Pow,
1491    And,
1492    Or,
1493    BitAnd,
1494    BitOr,
1495    BitXor,
1496    Shl,
1497    Shr,
1498    Eq,
1499    Ne,
1500    Lt,
1501    Le,
1502    Gt,
1503    Ge,
1504    Concat,
1505}
1506
1507/// Unary operators.
1508#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1509pub enum UnaryOp {
1510    Neg,
1511    Not,
1512    Deref,
1513    Ref,
1514    RefMut,
1515}
1516
1517/// Literal values.
1518#[derive(Debug, Clone, PartialEq)]
1519pub enum Literal {
1520    Int {
1521        value: String,
1522        base: NumBase,
1523        suffix: Option<String>,
1524    },
1525    Float {
1526        value: String,
1527        suffix: Option<String>,
1528    },
1529    String(String),
1530    /// Multi-line string literal (""" ... """)
1531    MultiLineString(String),
1532    /// Raw string literal (no escape processing)
1533    RawString(String),
1534    /// Byte string literal (b"...")
1535    ByteString(Vec<u8>),
1536    /// Interpolated string literal (f"... {expr} ...")
1537    InterpolatedString {
1538        parts: Vec<InterpolationPart>,
1539    },
1540    /// SQL sigil string (σ"...")
1541    SigilStringSql(String),
1542    /// Route sigil string (ρ"...")
1543    SigilStringRoute(String),
1544    Char(char),
1545    Bool(bool),
1546    Null, // null
1547    /// Special mathematical constants
1548    Empty, // ∅
1549    Infinity, // ∞
1550    Circle, // ◯
1551}
1552
1553/// Part of an interpolated string
1554#[derive(Debug, Clone, PartialEq)]
1555pub enum InterpolationPart {
1556    /// Literal text segment
1557    Text(String),
1558    /// Expression to be evaluated and converted to string
1559    Expr(Box<Expr>),
1560}
1561
1562/// Number bases.
1563#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1564pub enum NumBase {
1565    Binary,       // 0b
1566    Octal,        // 0o
1567    Decimal,      // default
1568    Hex,          // 0x
1569    Vigesimal,    // 0v (base 20)
1570    Sexagesimal,  // 0s (base 60)
1571    Duodecimal,   // 0z (base 12)
1572    Explicit(u8), // N:₆₀ etc.
1573}
1574
1575#[derive(Debug, Clone, PartialEq)]
1576pub struct FieldInit {
1577    pub name: Ident,
1578    pub value: Option<Expr>,
1579}
1580
1581#[derive(Debug, Clone, PartialEq)]
1582pub struct MatchArm {
1583    pub pattern: Pattern,
1584    pub guard: Option<Expr>,
1585    pub body: Expr,
1586}
1587
1588#[derive(Debug, Clone, PartialEq)]
1589pub struct ClosureParam {
1590    pub pattern: Pattern,
1591    pub ty: Option<TypeExpr>,
1592}