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 {
579        mutable: bool,
580        inner: Box<TypeExpr>,
581    },
582    /// Pointer: `*const T`, `*mut T`
583    Pointer {
584        mutable: bool,
585        inner: Box<TypeExpr>,
586    },
587    /// Array: `[T; N]`
588    Array {
589        element: Box<TypeExpr>,
590        size: Box<Expr>,
591    },
592    /// Slice: `[T]`
593    Slice(Box<TypeExpr>),
594    /// Tuple: `(A, B, C)`
595    Tuple(Vec<TypeExpr>),
596    /// Function: `fn(A, B) -> C`
597    Function {
598        params: Vec<TypeExpr>,
599        return_type: Option<Box<TypeExpr>>,
600    },
601    /// With evidentiality: `T!`, `T?`, `T~`
602    Evidential {
603        inner: Box<TypeExpr>,
604        evidentiality: Evidentiality,
605    },
606    /// Cycle type: `Cycle<N>`
607    Cycle {
608        modulus: Box<Expr>,
609    },
610    /// SIMD vector type: `simd<f32, 4>`, `Vec4f`
611    Simd {
612        element: Box<TypeExpr>,
613        lanes: u8,
614    },
615    /// Atomic type: `atomic<T>`
616    Atomic(Box<TypeExpr>),
617    /// Never type: `!` or `never`
618    Never,
619    /// Inferred: `_`
620    Infer,
621}
622
623/// Type path with optional generics.
624#[derive(Debug, Clone, PartialEq)]
625pub struct TypePath {
626    pub segments: Vec<PathSegment>,
627}
628
629#[derive(Debug, Clone, PartialEq)]
630pub struct PathSegment {
631    pub ident: Ident,
632    pub generics: Option<Vec<TypeExpr>>,
633}
634
635/// Memory representation for structs.
636#[derive(Debug, Clone, PartialEq)]
637pub enum StructRepr {
638    /// C-compatible layout
639    C,
640    /// Transparent (single field struct)
641    Transparent,
642    /// Specific integer type
643    Int(String),
644}
645
646/// Struct definition.
647#[derive(Debug, Clone, PartialEq)]
648pub struct StructDef {
649    pub visibility: Visibility,
650    pub attrs: StructAttrs,
651    pub name: Ident,
652    pub generics: Option<Generics>,
653    pub fields: StructFields,
654}
655
656#[derive(Debug, Clone, PartialEq)]
657pub enum StructFields {
658    Named(Vec<FieldDef>),
659    Tuple(Vec<TypeExpr>),
660    Unit,
661}
662
663#[derive(Debug, Clone, PartialEq)]
664pub struct FieldDef {
665    pub visibility: Visibility,
666    pub name: Ident,
667    pub ty: TypeExpr,
668}
669
670/// Enum definition.
671#[derive(Debug, Clone, PartialEq)]
672pub struct EnumDef {
673    pub visibility: Visibility,
674    pub name: Ident,
675    pub generics: Option<Generics>,
676    pub variants: Vec<EnumVariant>,
677}
678
679#[derive(Debug, Clone, PartialEq)]
680pub struct EnumVariant {
681    pub name: Ident,
682    pub fields: StructFields,
683    pub discriminant: Option<Expr>,
684}
685
686/// Trait definition.
687#[derive(Debug, Clone, PartialEq)]
688pub struct TraitDef {
689    pub visibility: Visibility,
690    pub name: Ident,
691    pub generics: Option<Generics>,
692    pub supertraits: Vec<TypeExpr>,
693    pub items: Vec<TraitItem>,
694}
695
696#[derive(Debug, Clone, PartialEq)]
697pub enum TraitItem {
698    Function(Function),
699    Type {
700        name: Ident,
701        bounds: Vec<TypeExpr>,
702    },
703    Const {
704        name: Ident,
705        ty: TypeExpr,
706    },
707}
708
709/// Impl block.
710#[derive(Debug, Clone, PartialEq)]
711pub struct ImplBlock {
712    pub generics: Option<Generics>,
713    pub trait_: Option<TypePath>,
714    pub self_ty: TypeExpr,
715    pub items: Vec<ImplItem>,
716}
717
718#[derive(Debug, Clone, PartialEq)]
719pub enum ImplItem {
720    Function(Function),
721    Type(TypeAlias),
722    Const(ConstDef),
723}
724
725/// Type alias.
726#[derive(Debug, Clone, PartialEq)]
727pub struct TypeAlias {
728    pub visibility: Visibility,
729    pub name: Ident,
730    pub generics: Option<Generics>,
731    pub ty: TypeExpr,
732}
733
734/// Module.
735#[derive(Debug, Clone, PartialEq)]
736pub struct Module {
737    pub visibility: Visibility,
738    pub name: Ident,
739    pub items: Option<Vec<Spanned<Item>>>,
740}
741
742/// Use declaration.
743#[derive(Debug, Clone, PartialEq)]
744pub struct UseDecl {
745    pub visibility: Visibility,
746    pub tree: UseTree,
747}
748
749#[derive(Debug, Clone, PartialEq)]
750pub enum UseTree {
751    Path {
752        prefix: Ident,
753        suffix: Box<UseTree>,
754    },
755    Name(Ident),
756    Rename {
757        name: Ident,
758        alias: Ident,
759    },
760    Glob,
761    Group(Vec<UseTree>),
762}
763
764/// Const definition.
765#[derive(Debug, Clone, PartialEq)]
766pub struct ConstDef {
767    pub visibility: Visibility,
768    pub name: Ident,
769    pub ty: TypeExpr,
770    pub value: Expr,
771}
772
773/// Static definition.
774#[derive(Debug, Clone, PartialEq)]
775pub struct StaticDef {
776    pub visibility: Visibility,
777    pub mutable: bool,
778    pub name: Ident,
779    pub ty: TypeExpr,
780    pub value: Expr,
781}
782
783/// Actor definition (concurrency).
784#[derive(Debug, Clone, PartialEq)]
785pub struct ActorDef {
786    pub visibility: Visibility,
787    pub name: Ident,
788    pub generics: Option<Generics>,
789    pub state: Vec<FieldDef>,
790    pub handlers: Vec<MessageHandler>,
791}
792
793#[derive(Debug, Clone, PartialEq)]
794pub struct MessageHandler {
795    pub message: Ident,
796    pub params: Vec<Param>,
797    pub return_type: Option<TypeExpr>,
798    pub body: Block,
799}
800
801/// Code block.
802#[derive(Debug, Clone, PartialEq)]
803pub struct Block {
804    pub stmts: Vec<Stmt>,
805    pub expr: Option<Box<Expr>>,
806}
807
808/// Statements.
809#[derive(Debug, Clone, PartialEq)]
810pub enum Stmt {
811    Let {
812        pattern: Pattern,
813        ty: Option<TypeExpr>,
814        init: Option<Expr>,
815    },
816    Expr(Expr),
817    Semi(Expr),
818    Item(Box<Item>),
819}
820
821/// Patterns.
822#[derive(Debug, Clone, PartialEq)]
823pub enum Pattern {
824    Ident {
825        mutable: bool,
826        name: Ident,
827        evidentiality: Option<Evidentiality>,
828    },
829    Tuple(Vec<Pattern>),
830    Struct {
831        path: TypePath,
832        fields: Vec<FieldPattern>,
833        rest: bool,
834    },
835    TupleStruct {
836        path: TypePath,
837        fields: Vec<Pattern>,
838    },
839    Slice(Vec<Pattern>),
840    Or(Vec<Pattern>),
841    Literal(Literal),
842    Range {
843        start: Option<Box<Pattern>>,
844        end: Option<Box<Pattern>>,
845        inclusive: bool,
846    },
847    Wildcard,
848    Rest,
849}
850
851#[derive(Debug, Clone, PartialEq)]
852pub struct FieldPattern {
853    pub name: Ident,
854    pub pattern: Option<Pattern>,
855}
856
857/// Expressions.
858#[derive(Debug, Clone, PartialEq)]
859pub enum Expr {
860    /// Literal value
861    Literal(Literal),
862    /// Variable reference
863    Path(TypePath),
864    /// Binary operation
865    Binary {
866        left: Box<Expr>,
867        op: BinOp,
868        right: Box<Expr>,
869    },
870    /// Unary operation
871    Unary {
872        op: UnaryOp,
873        expr: Box<Expr>,
874    },
875    /// Pipe expression: `x|f|g`
876    Pipe {
877        expr: Box<Expr>,
878        operations: Vec<PipeOp>,
879    },
880    /// Incorporation: `file·open·read`
881    Incorporation {
882        segments: Vec<IncorporationSegment>,
883    },
884    /// Morpheme application: `τ{f}`
885    Morpheme {
886        kind: MorphemeKind,
887        body: Box<Expr>,
888    },
889    /// Function call
890    Call {
891        func: Box<Expr>,
892        args: Vec<Expr>,
893    },
894    /// Method call
895    MethodCall {
896        receiver: Box<Expr>,
897        method: Ident,
898        args: Vec<Expr>,
899    },
900    /// Field access
901    Field {
902        expr: Box<Expr>,
903        field: Ident,
904    },
905    /// Index: `arr[i]`
906    Index {
907        expr: Box<Expr>,
908        index: Box<Expr>,
909    },
910    /// Array literal
911    Array(Vec<Expr>),
912    /// Tuple literal
913    Tuple(Vec<Expr>),
914    /// Struct literal
915    Struct {
916        path: TypePath,
917        fields: Vec<FieldInit>,
918        rest: Option<Box<Expr>>,
919    },
920    /// Block expression
921    Block(Block),
922    /// If expression
923    If {
924        condition: Box<Expr>,
925        then_branch: Block,
926        else_branch: Option<Box<Expr>>,
927    },
928    /// Match expression
929    Match {
930        expr: Box<Expr>,
931        arms: Vec<MatchArm>,
932    },
933    /// Loop
934    Loop(Block),
935    /// While loop
936    While {
937        condition: Box<Expr>,
938        body: Block,
939    },
940    /// For loop
941    For {
942        pattern: Pattern,
943        iter: Box<Expr>,
944        body: Block,
945    },
946    /// Closure: `{x => x + 1}` or `|x| x + 1`
947    Closure {
948        params: Vec<ClosureParam>,
949        body: Box<Expr>,
950    },
951    /// Await: `expr|await` or `expr⌛`
952    Await(Box<Expr>),
953    /// Try: `expr?`
954    Try(Box<Expr>),
955    /// Return
956    Return(Option<Box<Expr>>),
957    /// Break
958    Break(Option<Box<Expr>>),
959    /// Continue
960    Continue,
961    /// Range: `a..b` or `a..=b`
962    Range {
963        start: Option<Box<Expr>>,
964        end: Option<Box<Expr>>,
965        inclusive: bool,
966    },
967    /// Macro invocation
968    Macro {
969        path: TypePath,
970        tokens: String,
971    },
972    /// With evidentiality marker
973    Evidential {
974        expr: Box<Expr>,
975        evidentiality: Evidentiality,
976    },
977    /// Assignment: `x = value`
978    Assign {
979        target: Box<Expr>,
980        value: Box<Expr>,
981    },
982    /// Unsafe block: `unsafe { ... }`
983    Unsafe(Block),
984    /// Raw pointer dereference: `*ptr`
985    Deref(Box<Expr>),
986    /// Address-of: `&expr` or `&mut expr`
987    AddrOf {
988        mutable: bool,
989        expr: Box<Expr>,
990    },
991    /// Cast: `expr as Type`
992    Cast {
993        expr: Box<Expr>,
994        ty: TypeExpr,
995    },
996
997    /// Inline assembly: `asm!("instruction", ...)`
998    InlineAsm(InlineAsm),
999
1000    /// Volatile read: `volatile read<T>(ptr)` or `volatile read(ptr)`
1001    VolatileRead {
1002        ptr: Box<Expr>,
1003        ty: Option<TypeExpr>,
1004    },
1005
1006    /// Volatile write: `volatile write<T>(ptr, value)` or `volatile write(ptr, value)`
1007    VolatileWrite {
1008        ptr: Box<Expr>,
1009        value: Box<Expr>,
1010        ty: Option<TypeExpr>,
1011    },
1012
1013    // ========================================
1014    // SIMD Operations
1015    // ========================================
1016
1017    /// SIMD vector literal: `simd[1.0, 2.0, 3.0, 4.0]`
1018    SimdLiteral {
1019        elements: Vec<Expr>,
1020        ty: Option<TypeExpr>,
1021    },
1022
1023    /// SIMD intrinsic operation: `simd::add(a, b)`
1024    SimdIntrinsic {
1025        op: SimdOp,
1026        args: Vec<Expr>,
1027    },
1028
1029    /// SIMD shuffle: `simd::shuffle(a, b, [0, 4, 1, 5])`
1030    SimdShuffle {
1031        a: Box<Expr>,
1032        b: Box<Expr>,
1033        indices: Vec<u8>,
1034    },
1035
1036    /// SIMD splat (broadcast scalar to all lanes): `simd::splat(x)`
1037    SimdSplat {
1038        value: Box<Expr>,
1039        lanes: u8,
1040    },
1041
1042    /// SIMD extract single lane: `simd::extract(v, 0)`
1043    SimdExtract {
1044        vector: Box<Expr>,
1045        index: u8,
1046    },
1047
1048    /// SIMD insert into lane: `simd::insert(v, 0, value)`
1049    SimdInsert {
1050        vector: Box<Expr>,
1051        index: u8,
1052        value: Box<Expr>,
1053    },
1054
1055    // ========================================
1056    // Atomic Operations
1057    // ========================================
1058
1059    /// Atomic operation: `atomic::load(&x, Ordering::SeqCst)`
1060    AtomicOp {
1061        op: AtomicOp,
1062        ptr: Box<Expr>,
1063        value: Option<Box<Expr>>,        // For store, swap, fetch_add, etc.
1064        expected: Option<Box<Expr>>,     // For compare_exchange
1065        ordering: MemoryOrdering,
1066        failure_ordering: Option<MemoryOrdering>,  // For compare_exchange
1067    },
1068
1069    /// Atomic fence: `atomic::fence(Ordering::SeqCst)`
1070    AtomicFence {
1071        ordering: MemoryOrdering,
1072    },
1073
1074    // ==========================================
1075    // Protocol Expressions - Sigil-native networking
1076    // All protocol expressions yield values with Reported evidentiality
1077    // ==========================================
1078
1079    /// HTTP request: `http·get(url)`, `http·post(url)`, etc.
1080    /// Incorporation pattern for building HTTP requests
1081    HttpRequest {
1082        method: HttpMethod,
1083        url: Box<Expr>,
1084        headers: Vec<(Expr, Expr)>,
1085        body: Option<Box<Expr>>,
1086        timeout: Option<Box<Expr>>,
1087    },
1088
1089    /// gRPC call: `grpc·call(service, method)`
1090    /// Incorporation pattern for gRPC operations
1091    GrpcCall {
1092        service: Box<Expr>,
1093        method: Box<Expr>,
1094        message: Option<Box<Expr>>,
1095        metadata: Vec<(Expr, Expr)>,
1096        timeout: Option<Box<Expr>>,
1097    },
1098
1099    /// WebSocket connection: `ws·connect(url)`
1100    /// Incorporation pattern for WebSocket operations
1101    WebSocketConnect {
1102        url: Box<Expr>,
1103        protocols: Vec<Expr>,
1104        headers: Vec<(Expr, Expr)>,
1105    },
1106
1107    /// WebSocket message: `ws·message(data)` or `ws·text(str)` / `ws·binary(bytes)`
1108    WebSocketMessage {
1109        kind: WebSocketMessageKind,
1110        data: Box<Expr>,
1111    },
1112
1113    /// Kafka operation: `kafka·produce(topic, message)`, `kafka·consume(topic)`
1114    KafkaOp {
1115        kind: KafkaOpKind,
1116        topic: Box<Expr>,
1117        payload: Option<Box<Expr>>,
1118        key: Option<Box<Expr>>,
1119        partition: Option<Box<Expr>>,
1120    },
1121
1122    /// GraphQL query: `graphql·query(document)` or `graphql·mutation(document)`
1123    GraphQLOp {
1124        kind: GraphQLOpKind,
1125        document: Box<Expr>,
1126        variables: Option<Box<Expr>>,
1127        operation_name: Option<Box<Expr>>,
1128    },
1129
1130    /// Protocol stream: iterable over network messages
1131    /// `http·stream(url)`, `ws·stream()`, `kafka·stream(topic)`
1132    ProtocolStream {
1133        protocol: ProtocolKind,
1134        source: Box<Expr>,
1135        config: Option<Box<Expr>>,
1136    },
1137}
1138
1139/// Inline assembly expression.
1140#[derive(Debug, Clone, PartialEq)]
1141pub struct InlineAsm {
1142    /// The assembly template string
1143    pub template: String,
1144    /// Output operands
1145    pub outputs: Vec<AsmOperand>,
1146    /// Input operands
1147    pub inputs: Vec<AsmOperand>,
1148    /// Clobbered registers
1149    pub clobbers: Vec<String>,
1150    /// Assembly options
1151    pub options: AsmOptions,
1152}
1153
1154/// An assembly operand (input or output).
1155#[derive(Debug, Clone, PartialEq)]
1156pub struct AsmOperand {
1157    /// Constraint string (e.g., "=r", "r", "m", or register name)
1158    pub constraint: String,
1159    /// The expression to bind
1160    pub expr: Expr,
1161    /// The kind of operand
1162    pub kind: AsmOperandKind,
1163    /// For inout operands, the output expression (if different from input)
1164    pub output: Option<Box<Expr>>,
1165}
1166
1167/// Assembly operand kind.
1168#[derive(Debug, Clone, PartialEq, Eq)]
1169pub enum AsmOperandKind {
1170    /// Input only
1171    Input,
1172    /// Output only
1173    Output,
1174    /// Input and output (same register)
1175    InOut,
1176}
1177
1178/// Assembly options/modifiers.
1179#[derive(Debug, Clone, PartialEq, Default)]
1180pub struct AsmOptions {
1181    /// Volatile (has side effects, cannot be optimized away)
1182    pub volatile: bool,
1183    /// Pure assembly (no side effects)
1184    pub pure_asm: bool,
1185    /// No memory clobber
1186    pub nomem: bool,
1187    /// No stack
1188    pub nostack: bool,
1189    /// Preserves flags
1190    pub preserves_flags: bool,
1191    /// Read-only (inputs only)
1192    pub readonly: bool,
1193    /// AT&T syntax (vs Intel)
1194    pub att_syntax: bool,
1195}
1196
1197/// Pipe operation in a chain.
1198#[derive(Debug, Clone, PartialEq)]
1199pub enum PipeOp {
1200    /// Transform morpheme: `τ{f}`
1201    Transform(Box<Expr>),
1202    /// Filter morpheme: `φ{p}`
1203    Filter(Box<Expr>),
1204    /// Sort morpheme: `σ` or `σ.field`
1205    Sort(Option<Ident>),
1206    /// Reduce morpheme: `ρ{f}`
1207    Reduce(Box<Expr>),
1208    /// Middle morpheme: `μ` - get middle/median element
1209    Middle,
1210    /// Choice morpheme: `χ` - random element selection
1211    Choice,
1212    /// Nth morpheme: `ν{n}` - get nth element
1213    Nth(Box<Expr>),
1214    /// Next morpheme: `ξ` - get next element (iterator)
1215    Next,
1216    /// First morpheme: `α` - get first element
1217    First,
1218    /// Last morpheme: `ω` - get last element
1219    Last,
1220    /// Parallel morpheme: `∥{op}` or `parallel{op}` - execute operation in parallel
1221    /// Wraps another operation to run it across multiple threads
1222    Parallel(Box<PipeOp>),
1223    /// GPU compute morpheme: `⊛{op}` or `gpu{op}` - execute operation on GPU
1224    /// Wraps another operation to run it as a compute shader
1225    Gpu(Box<PipeOp>),
1226    /// Method call
1227    Method {
1228        name: Ident,
1229        args: Vec<Expr>,
1230    },
1231    /// Await
1232    Await,
1233    /// Named morpheme: `·map{f}`, `·flow{f}`
1234    Named {
1235        prefix: Vec<Ident>,
1236        body: Option<Box<Expr>>,
1237    },
1238
1239    // ==========================================
1240    // Protocol Operations - Sigil-native networking
1241    // ==========================================
1242
1243    /// Send operation: `|send{data}` or `|⇒{data}` - send data over connection
1244    /// Results are automatically marked with Reported evidentiality
1245    Send(Box<Expr>),
1246
1247    /// Receive operation: `|recv` or `|⇐` - receive data from connection
1248    /// Results are automatically marked with Reported evidentiality
1249    Recv,
1250
1251    /// Stream operation: `|stream{handler}` or `|≋{handler}` - iterate over incoming data
1252    /// Each element is marked with Reported evidentiality
1253    Stream(Box<Expr>),
1254
1255    /// Connect operation: `|connect{config}` or `|⊸{config}` - establish connection
1256    Connect(Option<Box<Expr>>),
1257
1258    /// Close operation: `|close` or `|⊗` - close connection gracefully
1259    Close,
1260
1261    /// Protocol header: `|header{name, value}` - add/set header
1262    Header {
1263        name: Box<Expr>,
1264        value: Box<Expr>,
1265    },
1266
1267    /// Protocol body: `|body{data}` - set request body
1268    Body(Box<Expr>),
1269
1270    /// Timeout: `|timeout{ms}` or `|⏱{ms}` - set operation timeout
1271    Timeout(Box<Expr>),
1272
1273    /// Retry: `|retry{count}` or `|retry{count, strategy}` - retry on failure
1274    Retry {
1275        count: Box<Expr>,
1276        strategy: Option<Box<Expr>>,
1277    },
1278}
1279
1280/// Incorporation segment.
1281#[derive(Debug, Clone, PartialEq)]
1282pub struct IncorporationSegment {
1283    pub name: Ident,
1284    pub args: Option<Vec<Expr>>,
1285}
1286
1287/// Morpheme kinds.
1288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1289pub enum MorphemeKind {
1290    Transform,  // τ
1291    Filter,     // φ
1292    Sort,       // σ
1293    Reduce,     // ρ
1294    Lambda,     // λ
1295    Sum,        // Σ
1296    Product,    // Π
1297    Middle,     // μ
1298    Choice,     // χ
1299    Nth,        // ν
1300    Next,       // ξ
1301    First,      // α
1302    Last,       // ω
1303}
1304
1305// ==========================================
1306// Protocol Types - Sigil-native networking
1307// ==========================================
1308
1309/// HTTP methods for http· incorporation.
1310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1311pub enum HttpMethod {
1312    Get,
1313    Post,
1314    Put,
1315    Delete,
1316    Patch,
1317    Head,
1318    Options,
1319    Connect,
1320    Trace,
1321}
1322
1323impl std::fmt::Display for HttpMethod {
1324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1325        match self {
1326            HttpMethod::Get => write!(f, "GET"),
1327            HttpMethod::Post => write!(f, "POST"),
1328            HttpMethod::Put => write!(f, "PUT"),
1329            HttpMethod::Delete => write!(f, "DELETE"),
1330            HttpMethod::Patch => write!(f, "PATCH"),
1331            HttpMethod::Head => write!(f, "HEAD"),
1332            HttpMethod::Options => write!(f, "OPTIONS"),
1333            HttpMethod::Connect => write!(f, "CONNECT"),
1334            HttpMethod::Trace => write!(f, "TRACE"),
1335        }
1336    }
1337}
1338
1339/// WebSocket message kinds for ws· incorporation.
1340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1341pub enum WebSocketMessageKind {
1342    Text,
1343    Binary,
1344    Ping,
1345    Pong,
1346    Close,
1347}
1348
1349/// Kafka operation kinds for kafka· incorporation.
1350#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1351pub enum KafkaOpKind {
1352    Produce,
1353    Consume,
1354    Subscribe,
1355    Unsubscribe,
1356    Commit,
1357    Seek,
1358}
1359
1360/// GraphQL operation kinds for graphql· incorporation.
1361#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1362pub enum GraphQLOpKind {
1363    Query,
1364    Mutation,
1365    Subscription,
1366}
1367
1368/// Protocol kinds for stream expressions.
1369#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1370pub enum ProtocolKind {
1371    Http,
1372    Grpc,
1373    WebSocket,
1374    Kafka,
1375    Amqp,
1376    GraphQL,
1377}
1378
1379impl std::fmt::Display for ProtocolKind {
1380    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1381        match self {
1382            ProtocolKind::Http => write!(f, "http"),
1383            ProtocolKind::Grpc => write!(f, "grpc"),
1384            ProtocolKind::WebSocket => write!(f, "ws"),
1385            ProtocolKind::Kafka => write!(f, "kafka"),
1386            ProtocolKind::Amqp => write!(f, "amqp"),
1387            ProtocolKind::GraphQL => write!(f, "graphql"),
1388        }
1389    }
1390}
1391
1392/// Binary operators.
1393#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1394pub enum BinOp {
1395    Add,
1396    Sub,
1397    Mul,
1398    Div,
1399    Rem,
1400    Pow,
1401    And,
1402    Or,
1403    BitAnd,
1404    BitOr,
1405    BitXor,
1406    Shl,
1407    Shr,
1408    Eq,
1409    Ne,
1410    Lt,
1411    Le,
1412    Gt,
1413    Ge,
1414    Concat,
1415}
1416
1417/// Unary operators.
1418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1419pub enum UnaryOp {
1420    Neg,
1421    Not,
1422    Deref,
1423    Ref,
1424    RefMut,
1425}
1426
1427/// Literal values.
1428#[derive(Debug, Clone, PartialEq)]
1429pub enum Literal {
1430    Int {
1431        value: String,
1432        base: NumBase,
1433        suffix: Option<String>,
1434    },
1435    Float {
1436        value: String,
1437        suffix: Option<String>,
1438    },
1439    String(String),
1440    /// Multi-line string literal (""" ... """)
1441    MultiLineString(String),
1442    /// Raw string literal (no escape processing)
1443    RawString(String),
1444    /// Byte string literal (b"...")
1445    ByteString(Vec<u8>),
1446    /// Interpolated string literal (f"... {expr} ...")
1447    InterpolatedString {
1448        parts: Vec<InterpolationPart>,
1449    },
1450    /// SQL sigil string (σ"...")
1451    SigilStringSql(String),
1452    /// Route sigil string (ρ"...")
1453    SigilStringRoute(String),
1454    Char(char),
1455    Bool(bool),
1456    Null,      // null
1457    /// Special mathematical constants
1458    Empty,     // ∅
1459    Infinity,  // ∞
1460    Circle,    // ◯
1461}
1462
1463/// Part of an interpolated string
1464#[derive(Debug, Clone, PartialEq)]
1465pub enum InterpolationPart {
1466    /// Literal text segment
1467    Text(String),
1468    /// Expression to be evaluated and converted to string
1469    Expr(Box<Expr>),
1470}
1471
1472/// Number bases.
1473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1474pub enum NumBase {
1475    Binary,      // 0b
1476    Octal,       // 0o
1477    Decimal,     // default
1478    Hex,         // 0x
1479    Vigesimal,   // 0v (base 20)
1480    Sexagesimal, // 0s (base 60)
1481    Duodecimal,  // 0z (base 12)
1482    Explicit(u8),// N:₆₀ etc.
1483}
1484
1485#[derive(Debug, Clone, PartialEq)]
1486pub struct FieldInit {
1487    pub name: Ident,
1488    pub value: Option<Expr>,
1489}
1490
1491#[derive(Debug, Clone, PartialEq)]
1492pub struct MatchArm {
1493    pub pattern: Pattern,
1494    pub guard: Option<Expr>,
1495    pub body: Expr,
1496}
1497
1498#[derive(Debug, Clone, PartialEq)]
1499pub struct ClosureParam {
1500    pub pattern: Pattern,
1501    pub ty: Option<TypeExpr>,
1502}