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    /// Macro definition (declarative macro)
321    Macro(MacroDef),
322    /// Macro invocation at item level
323    MacroInvocation(MacroInvocation),
324    /// Plurality items (DAEMONIORUM extensions)
325    Plurality(crate::plurality::PluralityItem),
326}
327
328/// Declarative macro definition.
329/// `macro name($pattern) { $expansion }`
330#[derive(Debug, Clone, PartialEq)]
331pub struct MacroDef {
332    pub visibility: Visibility,
333    pub name: Ident,
334    pub rules: String, // Raw token body for now
335}
336
337/// Macro invocation at item level.
338/// `thread_local! { ... }` or `vec![1, 2, 3]`
339#[derive(Debug, Clone, PartialEq)]
340pub struct MacroInvocation {
341    pub path: TypePath,
342    pub delimiter: MacroDelimiter,
343    pub tokens: String, // Raw token body
344}
345
346/// Delimiter used in macro invocation
347#[derive(Debug, Clone, PartialEq)]
348pub enum MacroDelimiter {
349    Paren,   // ()
350    Bracket, // []
351    Brace,   // {}
352}
353
354/// Foreign function interface block.
355/// `extern "C" { fn foo(x: c_int) -> c_int; }`
356#[derive(Debug, Clone, PartialEq)]
357pub struct ExternBlock {
358    pub abi: String, // "C", "Rust", "system", etc.
359    pub items: Vec<ExternItem>,
360}
361
362/// Items that can appear in an extern block.
363#[derive(Debug, Clone, PartialEq)]
364pub enum ExternItem {
365    Function(ExternFunction),
366    Static(ExternStatic),
367}
368
369/// Foreign function declaration (no body).
370#[derive(Debug, Clone, PartialEq)]
371pub struct ExternFunction {
372    pub visibility: Visibility,
373    pub name: Ident,
374    pub params: Vec<Param>,
375    pub return_type: Option<TypeExpr>,
376    pub variadic: bool, // For C varargs: fn printf(fmt: *const c_char, ...)
377}
378
379/// Foreign static variable.
380#[derive(Debug, Clone, PartialEq)]
381pub struct ExternStatic {
382    pub visibility: Visibility,
383    pub mutable: bool,
384    pub name: Ident,
385    pub ty: TypeExpr,
386}
387
388/// Function attributes for low-level control.
389#[derive(Debug, Clone, PartialEq, Default)]
390pub struct FunctionAttrs {
391    /// Naked function (no prologue/epilogue)
392    pub naked: bool,
393    /// Inline hint
394    pub inline: Option<InlineHint>,
395    /// Calling convention override
396    pub calling_convention: Option<String>,
397    /// No mangle (preserve symbol name)
398    pub no_mangle: bool,
399    /// Link section (e.g., ".text.boot", ".init")
400    pub link_section: Option<String>,
401    /// Export as C function
402    pub export: bool,
403    /// Panic handler function
404    pub panic_handler: bool,
405    /// Entry point function
406    pub entry: bool,
407    /// Interrupt handler with interrupt number
408    pub interrupt: Option<u32>,
409    /// Align function to boundary
410    pub align: Option<usize>,
411    /// Cold function (unlikely to be called)
412    pub cold: bool,
413    /// Hot function (likely to be called)
414    pub hot: bool,
415    /// Test function
416    pub test: bool,
417    /// Outer attributes (raw, for any we don't recognize)
418    pub outer_attrs: Vec<Attribute>,
419}
420
421/// Inline hints for functions.
422#[derive(Debug, Clone, PartialEq)]
423pub enum InlineHint {
424    /// #[inline]
425    Hint,
426    /// #[inline(always)]
427    Always,
428    /// #[inline(never)]
429    Never,
430}
431
432/// Verb aspect for function semantics.
433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
434pub enum Aspect {
435    /// ·ing - Progressive aspect: ongoing/streaming operation
436    Progressive,
437    /// ·ed - Perfective aspect: completed operation
438    Perfective,
439    /// ·able - Potential aspect: capability check (returns bool)
440    Potential,
441    /// ·ive - Resultative aspect: produces a result
442    Resultative,
443}
444
445/// Function definition.
446#[derive(Debug, Clone, PartialEq)]
447pub struct Function {
448    pub visibility: Visibility,
449    pub is_async: bool,
450    pub is_const: bool,
451    pub is_unsafe: bool,
452    pub attrs: FunctionAttrs,
453    pub name: Ident,
454    pub aspect: Option<Aspect>, // Verb aspect: ·ing, ·ed, ·able, ·ive
455    pub generics: Option<Generics>,
456    pub params: Vec<Param>,
457    pub return_type: Option<TypeExpr>,
458    pub where_clause: Option<WhereClause>,
459    pub body: Option<Block>,
460}
461
462/// Visibility modifier.
463#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
464pub enum Visibility {
465    #[default]
466    Private,
467    Public,
468    Crate,
469    Super,
470}
471
472/// Identifier with optional evidentiality and affect markers.
473#[derive(Debug, Clone, PartialEq)]
474pub struct Ident {
475    pub name: String,
476    pub evidentiality: Option<Evidentiality>,
477    pub affect: Option<Affect>,
478    pub span: Span,
479}
480
481/// Evidentiality markers from the type system.
482#[derive(Debug, Clone, Copy, PartialEq, Eq)]
483pub enum Evidentiality {
484    Known,     // ! - verified ground truth
485    Uncertain, // ? - unverified input
486    Reported,  // ~ - EMA, eventually consistent
487    Predicted, // ◊ - model output, speculative
488    Paradox,   // ‽ - contradiction detected
489}
490
491// ============================================
492// Legion Morphemes (Holographic Agent Collective)
493// ============================================
494
495/// Legion collective operations for distributed memory.
496#[derive(Debug, Clone, PartialEq)]
497pub enum LegionOp {
498    /// Superposition: pattern joins the collective
499    /// `field∿ ⊕= pattern`
500    Superposition,
501
502    /// Interference: query the collective
503    /// `query ⫰ field∿`
504    Interference,
505
506    /// Resonance: extract agreement peaks
507    /// `resonance~ |◉`
508    Resonance,
509
510    /// Distribute: fragment holographically
511    /// `task ⟁ agent_count`
512    Distribute,
513
514    /// Gather: unify via interference
515    /// `fragments ⟀`
516    Gather,
517
518    /// Broadcast: one to many
519    /// `signal ↠ legion`
520    Broadcast,
521
522    /// Consensus: many become one
523    /// `contributions ⇢`
524    Consensus,
525
526    /// Decay: graceful fading
527    /// `field∿ ∂= 0.95`
528    Decay,
529}
530
531/// Suffix marker for Legion field types.
532/// `memory∿` indicates a LegionField collective memory.
533#[derive(Debug, Clone, PartialEq)]
534pub struct LegionFieldMarker {
535    pub base_name: Ident,
536}
537
538/// Affective markers for sentiment and emotion tracking.
539#[derive(Debug, Clone, PartialEq)]
540pub struct Affect {
541    pub sentiment: Option<Sentiment>,
542    pub sarcasm: bool, // ⸮
543    pub intensity: Option<Intensity>,
544    pub formality: Option<Formality>,
545    pub emotion: Option<Emotion>,
546    pub confidence: Option<Confidence>,
547}
548
549impl Default for Affect {
550    fn default() -> Self {
551        Affect {
552            sentiment: None,
553            sarcasm: false,
554            intensity: None,
555            formality: None,
556            emotion: None,
557            confidence: None,
558        }
559    }
560}
561
562impl Affect {
563    pub fn is_empty(&self) -> bool {
564        self.sentiment.is_none()
565            && !self.sarcasm
566            && self.intensity.is_none()
567            && self.formality.is_none()
568            && self.emotion.is_none()
569            && self.confidence.is_none()
570    }
571}
572
573/// Sentiment polarity markers.
574#[derive(Debug, Clone, Copy, PartialEq, Eq)]
575pub enum Sentiment {
576    Positive, // ⊕
577    Negative, // ⊖
578    Neutral,  // ⊜
579}
580
581/// Intensity modifiers.
582#[derive(Debug, Clone, Copy, PartialEq, Eq)]
583pub enum Intensity {
584    Up,   // ↑ (intensifier)
585    Down, // ↓ (dampener)
586    Max,  // ⇈ (maximum)
587}
588
589/// Formality register.
590#[derive(Debug, Clone, Copy, PartialEq, Eq)]
591pub enum Formality {
592    Formal,   // ♔
593    Informal, // ♟
594}
595
596/// Emotion categories (Plutchik's wheel).
597#[derive(Debug, Clone, Copy, PartialEq, Eq)]
598pub enum Emotion {
599    Joy,      // ☺
600    Sadness,  // ☹
601    Anger,    // ⚡
602    Fear,     // ❄
603    Surprise, // ✦
604    Love,     // ♡
605}
606
607/// Confidence level markers.
608#[derive(Debug, Clone, Copy, PartialEq, Eq)]
609pub enum Confidence {
610    High,   // ◉
611    Medium, // ◎
612    Low,    // ○
613}
614
615/// Function parameter.
616#[derive(Debug, Clone, PartialEq)]
617pub struct Param {
618    pub pattern: Pattern,
619    pub ty: TypeExpr,
620}
621
622/// Generic parameters.
623#[derive(Debug, Clone, PartialEq)]
624pub struct Generics {
625    pub params: Vec<GenericParam>,
626}
627
628#[derive(Debug, Clone, PartialEq)]
629pub enum GenericParam {
630    Type {
631        name: Ident,
632        bounds: Vec<TypeExpr>,
633        evidentiality: Option<Evidentiality>,
634        /// Default type: `T = DefaultType`
635        default: Option<TypeExpr>,
636    },
637    Const {
638        name: Ident,
639        ty: TypeExpr,
640        /// Default value for const generics
641        default: Option<Box<Expr>>,
642    },
643    Lifetime(String),
644}
645
646/// Where clause for bounds.
647#[derive(Debug, Clone, PartialEq)]
648pub struct WhereClause {
649    pub predicates: Vec<WherePredicate>,
650}
651
652#[derive(Debug, Clone, PartialEq)]
653pub struct WherePredicate {
654    pub ty: TypeExpr,
655    pub bounds: Vec<TypeExpr>,
656}
657
658/// Type expressions.
659#[derive(Debug, Clone, PartialEq)]
660pub enum TypeExpr {
661    /// Simple named type: `i32`, `String`
662    Path(TypePath),
663    /// Reference: `&T`, `&mut T`, `&'a T`, `&'static mut T`
664    Reference {
665        lifetime: Option<String>,
666        mutable: bool,
667        inner: Box<TypeExpr>,
668    },
669    /// Pointer: `*const T`, `*mut T`
670    Pointer { mutable: bool, inner: Box<TypeExpr> },
671    /// Array: `[T; N]`
672    Array {
673        element: Box<TypeExpr>,
674        size: Box<Expr>,
675    },
676    /// Slice: `[T]`
677    Slice(Box<TypeExpr>),
678    /// Tuple: `(A, B, C)`
679    Tuple(Vec<TypeExpr>),
680    /// Function: `fn(A, B) -> C`
681    Function {
682        params: Vec<TypeExpr>,
683        return_type: Option<Box<TypeExpr>>,
684    },
685    /// With evidentiality: `T!`, `T?`, `T~`, or with error type: `T?[Error]`, `T![Error]`
686    /// The error type syntax is sugar for Result<T, Error> with evidentiality tracking:
687    /// - `T?[E]` means Result<T, E> with uncertain evidentiality
688    /// - `T![E]` means Result<T, E> with known/infallible path
689    /// - `T~[E]` means Result<T, E> from external/reported source
690    Evidential {
691        inner: Box<TypeExpr>,
692        evidentiality: Evidentiality,
693        /// Optional error type for Result sugar: `T?[ErrorType]`
694        error_type: Option<Box<TypeExpr>>,
695    },
696    /// Cycle type: `Cycle<N>`
697    Cycle { modulus: Box<Expr> },
698    /// SIMD vector type: `simd<f32, 4>`, `Vec4f`
699    Simd { element: Box<TypeExpr>, lanes: u8 },
700    /// Atomic type: `atomic<T>`
701    Atomic(Box<TypeExpr>),
702    /// Linear type: `linear T` - value can only be used once (no-cloning)
703    Linear(Box<TypeExpr>),
704    /// Never type: `!` or `never`
705    Never,
706    /// Inferred: `_`
707    Infer,
708    /// Lifetime bound: `'static`, `'a`
709    Lifetime(String),
710    /// Trait object: `dyn Trait` or `dyn Trait + Send + 'static`
711    TraitObject(Vec<TypeExpr>),
712    /// Higher-ranked trait bound: `for<'a> Trait<'a>`
713    Hrtb {
714        lifetimes: Vec<String>,
715        bound: Box<TypeExpr>,
716    },
717    /// Inline struct type: `struct { field: Type, ... }`
718    InlineStruct { fields: Vec<FieldDef> },
719    /// Inline enum type: `enum { Variant1, Variant2(Type), ... }`
720    InlineEnum { variants: Vec<EnumVariant> },
721    /// Impl trait: `impl Trait`, `impl Fn() -> R`
722    ImplTrait(Vec<TypeExpr>),
723    /// Associated type binding: `Output = Type` used in trait bounds
724    AssocTypeBinding { name: Ident, ty: Box<TypeExpr> },
725    /// Const expression in type position (for const generics): `<32>`, `<{N + 1}>`
726    ConstExpr(Box<Expr>),
727    /// Qualified path type: `<Type as Trait>::AssociatedType`
728    /// Also supports `<Type>::Associated` for inherent associated types
729    QualifiedPath {
730        /// The base type: `Type` in `<Type as Trait>::...`
731        self_type: Box<TypeExpr>,
732        /// Optional trait bound: `Trait` in `<Type as Trait>::...`
733        trait_path: Option<TypePath>,
734        /// The associated item path: `AssociatedType` or `Associated::Nested`
735        item_path: TypePath,
736    },
737}
738
739/// Type path with optional generics.
740#[derive(Debug, Clone, PartialEq)]
741pub struct TypePath {
742    pub segments: Vec<PathSegment>,
743}
744
745#[derive(Debug, Clone, PartialEq)]
746pub struct PathSegment {
747    pub ident: Ident,
748    pub generics: Option<Vec<TypeExpr>>,
749}
750
751/// Memory representation for structs.
752#[derive(Debug, Clone, PartialEq)]
753pub enum StructRepr {
754    /// C-compatible layout
755    C,
756    /// Transparent (single field struct)
757    Transparent,
758    /// Specific integer type
759    Int(String),
760}
761
762/// Struct definition.
763#[derive(Debug, Clone, PartialEq)]
764pub struct StructDef {
765    pub visibility: Visibility,
766    pub attrs: StructAttrs,
767    pub name: Ident,
768    pub generics: Option<Generics>,
769    pub fields: StructFields,
770}
771
772#[derive(Debug, Clone, PartialEq)]
773pub enum StructFields {
774    Named(Vec<FieldDef>),
775    Tuple(Vec<TypeExpr>),
776    Unit,
777}
778
779#[derive(Debug, Clone, PartialEq)]
780pub struct FieldDef {
781    pub visibility: Visibility,
782    pub name: Ident,
783    pub ty: TypeExpr,
784    /// Default value for the field (e.g., `field: Type = default_expr`)
785    pub default: Option<Expr>,
786}
787
788/// Enum definition.
789#[derive(Debug, Clone, PartialEq)]
790pub struct EnumDef {
791    pub visibility: Visibility,
792    pub name: Ident,
793    pub generics: Option<Generics>,
794    pub variants: Vec<EnumVariant>,
795}
796
797#[derive(Debug, Clone, PartialEq)]
798pub struct EnumVariant {
799    pub name: Ident,
800    pub fields: StructFields,
801    pub discriminant: Option<Expr>,
802}
803
804/// Trait definition.
805#[derive(Debug, Clone, PartialEq)]
806pub struct TraitDef {
807    pub visibility: Visibility,
808    pub name: Ident,
809    pub generics: Option<Generics>,
810    pub supertraits: Vec<TypeExpr>,
811    pub items: Vec<TraitItem>,
812}
813
814#[derive(Debug, Clone, PartialEq)]
815pub enum TraitItem {
816    Function(Function),
817    Type { name: Ident, bounds: Vec<TypeExpr> },
818    Const { name: Ident, ty: TypeExpr },
819}
820
821/// Impl block.
822#[derive(Debug, Clone, PartialEq)]
823pub struct ImplBlock {
824    pub generics: Option<Generics>,
825    pub trait_: Option<TypePath>,
826    pub self_ty: TypeExpr,
827    pub items: Vec<ImplItem>,
828}
829
830#[derive(Debug, Clone, PartialEq)]
831pub enum ImplItem {
832    Function(Function),
833    Type(TypeAlias),
834    Const(ConstDef),
835}
836
837/// Type alias.
838#[derive(Debug, Clone, PartialEq)]
839pub struct TypeAlias {
840    pub visibility: Visibility,
841    pub name: Ident,
842    pub generics: Option<Generics>,
843    pub ty: TypeExpr,
844}
845
846/// Module.
847#[derive(Debug, Clone, PartialEq)]
848pub struct Module {
849    pub visibility: Visibility,
850    pub name: Ident,
851    pub items: Option<Vec<Spanned<Item>>>,
852}
853
854/// Use declaration.
855#[derive(Debug, Clone, PartialEq)]
856pub struct UseDecl {
857    pub visibility: Visibility,
858    pub tree: UseTree,
859}
860
861#[derive(Debug, Clone, PartialEq)]
862pub enum UseTree {
863    Path { prefix: Ident, suffix: Box<UseTree> },
864    Name(Ident),
865    Rename { name: Ident, alias: Ident },
866    Glob,
867    Group(Vec<UseTree>),
868}
869
870/// Const definition.
871#[derive(Debug, Clone, PartialEq)]
872pub struct ConstDef {
873    pub visibility: Visibility,
874    pub name: Ident,
875    pub ty: TypeExpr,
876    pub value: Expr,
877}
878
879/// Static definition.
880#[derive(Debug, Clone, PartialEq)]
881pub struct StaticDef {
882    pub visibility: Visibility,
883    pub mutable: bool,
884    pub name: Ident,
885    pub ty: TypeExpr,
886    pub value: Expr,
887}
888
889/// Actor definition (concurrency).
890#[derive(Debug, Clone, PartialEq)]
891pub struct ActorDef {
892    pub visibility: Visibility,
893    pub name: Ident,
894    pub generics: Option<Generics>,
895    pub state: Vec<FieldDef>,
896    pub handlers: Vec<MessageHandler>,
897}
898
899#[derive(Debug, Clone, PartialEq)]
900pub struct MessageHandler {
901    pub message: Ident,
902    pub params: Vec<Param>,
903    pub return_type: Option<TypeExpr>,
904    pub body: Block,
905}
906
907/// Code block.
908#[derive(Debug, Clone, PartialEq)]
909pub struct Block {
910    pub stmts: Vec<Stmt>,
911    pub expr: Option<Box<Expr>>,
912}
913
914/// Statements.
915#[derive(Debug, Clone, PartialEq)]
916pub enum Stmt {
917    Let {
918        pattern: Pattern,
919        ty: Option<TypeExpr>,
920        init: Option<Expr>,
921    },
922    /// Let-else statement: `let PATTERN = EXPR else { ... }`
923    LetElse {
924        pattern: Pattern,
925        ty: Option<TypeExpr>,
926        init: Expr,
927        else_branch: Box<Expr>,
928    },
929    Expr(Expr),
930    Semi(Expr),
931    Item(Box<Item>),
932}
933
934/// Patterns.
935#[derive(Debug, Clone, PartialEq)]
936pub enum Pattern {
937    Ident {
938        mutable: bool,
939        name: Ident,
940        evidentiality: Option<Evidentiality>,
941    },
942    /// Path pattern for matching unit enum variants: Token::Fn
943    Path(TypePath),
944    Tuple(Vec<Pattern>),
945    Struct {
946        path: TypePath,
947        fields: Vec<FieldPattern>,
948        rest: bool,
949    },
950    TupleStruct {
951        path: TypePath,
952        fields: Vec<Pattern>,
953    },
954    Slice(Vec<Pattern>),
955    Or(Vec<Pattern>),
956    Literal(Literal),
957    Range {
958        start: Option<Box<Pattern>>,
959        end: Option<Box<Pattern>>,
960        inclusive: bool,
961    },
962    /// Reference pattern: `&pattern` or `&mut pattern`
963    Ref {
964        mutable: bool,
965        pattern: Box<Pattern>,
966    },
967    /// Ref binding pattern: `ref ident` or `ref mut ident`
968    RefBinding {
969        mutable: bool,
970        name: Ident,
971        evidentiality: Option<Evidentiality>,
972    },
973    Wildcard,
974    Rest,
975}
976
977#[derive(Debug, Clone, PartialEq)]
978pub struct FieldPattern {
979    pub name: Ident,
980    pub pattern: Option<Pattern>,
981}
982
983/// Expressions.
984#[derive(Debug, Clone, PartialEq)]
985pub enum Expr {
986    /// Literal value
987    Literal(Literal),
988    /// Variable reference
989    Path(TypePath),
990    /// Binary operation
991    Binary {
992        left: Box<Expr>,
993        op: BinOp,
994        right: Box<Expr>,
995    },
996    /// Unary operation
997    Unary { op: UnaryOp, expr: Box<Expr> },
998    /// Pipe expression: `x|f|g`
999    Pipe {
1000        expr: Box<Expr>,
1001        operations: Vec<PipeOp>,
1002    },
1003    /// Incorporation: `file·open·read`
1004    Incorporation { segments: Vec<IncorporationSegment> },
1005    /// Morpheme application: `τ{f}`
1006    Morpheme { kind: MorphemeKind, body: Box<Expr> },
1007    /// Function call
1008    Call { func: Box<Expr>, args: Vec<Expr> },
1009    /// Method call
1010    MethodCall {
1011        receiver: Box<Expr>,
1012        method: Ident,
1013        /// Turbofish type arguments: `method::<T, U>(args)`
1014        type_args: Option<Vec<TypeExpr>>,
1015        args: Vec<Expr>,
1016    },
1017    /// Field access
1018    Field { expr: Box<Expr>, field: Ident },
1019    /// Index: `arr[i]`
1020    Index { expr: Box<Expr>, index: Box<Expr> },
1021    /// Array literal
1022    Array(Vec<Expr>),
1023    /// Array repeat literal: `[value; count]`
1024    ArrayRepeat { value: Box<Expr>, count: Box<Expr> },
1025    /// Tuple literal
1026    Tuple(Vec<Expr>),
1027    /// Struct literal
1028    Struct {
1029        path: TypePath,
1030        fields: Vec<FieldInit>,
1031        rest: Option<Box<Expr>>,
1032    },
1033    /// Block expression
1034    Block(Block),
1035    /// If expression
1036    If {
1037        condition: Box<Expr>,
1038        then_branch: Block,
1039        else_branch: Option<Box<Expr>>,
1040    },
1041    /// Match expression
1042    Match {
1043        expr: Box<Expr>,
1044        arms: Vec<MatchArm>,
1045    },
1046    /// Loop with optional label: `'label: loop { ... }`
1047    Loop { label: Option<Ident>, body: Block },
1048    /// While loop with optional label: `'label: while cond { ... }`
1049    While {
1050        label: Option<Ident>,
1051        condition: Box<Expr>,
1052        body: Block,
1053    },
1054    /// For loop with optional label: `'label: for x in iter { ... }`
1055    For {
1056        label: Option<Ident>,
1057        pattern: Pattern,
1058        iter: Box<Expr>,
1059        body: Block,
1060    },
1061    /// Closure: `{x => x + 1}` or `|x| x + 1` or `move |x| x + 1` or `|x| -> T { ... }`
1062    Closure {
1063        params: Vec<ClosureParam>,
1064        /// Optional explicit return type annotation: `|x| -> i32 { x + 1 }`
1065        return_type: Option<TypeExpr>,
1066        body: Box<Expr>,
1067        /// Whether this is a move closure that takes ownership of captured variables
1068        is_move: bool,
1069    },
1070    /// Await with optional evidentiality: `expr⌛` or `expr⌛?` or `expr⌛!` or `expr⌛~`
1071    /// The evidentiality marker specifies how to handle the awaited result:
1072    /// - `⌛?` - await and propagate error (uncertain)
1073    /// - `⌛!` - await, expect success (known/infallible)
1074    /// - `⌛~` - await external/reported source
1075    /// - `⌛‽` - await with trust boundary crossing
1076    Await {
1077        expr: Box<Expr>,
1078        evidentiality: Option<Evidentiality>,
1079    },
1080    /// Try: `expr?`
1081    Try(Box<Expr>),
1082    /// Return
1083    Return(Option<Box<Expr>>),
1084    /// Break with optional label and value: `break 'label value`
1085    Break {
1086        label: Option<Ident>,
1087        value: Option<Box<Expr>>,
1088    },
1089    /// Continue with optional label: `continue 'label`
1090    Continue { label: Option<Ident> },
1091    /// Range: `a..b` or `a..=b`
1092    Range {
1093        start: Option<Box<Expr>>,
1094        end: Option<Box<Expr>>,
1095        inclusive: bool,
1096    },
1097    /// Macro invocation
1098    Macro { path: TypePath, tokens: String },
1099    /// With evidentiality marker
1100    Evidential {
1101        expr: Box<Expr>,
1102        evidentiality: Evidentiality,
1103    },
1104    /// Assignment: `x = value`
1105    Assign { target: Box<Expr>, value: Box<Expr> },
1106    /// Let expression (for if-let, while-let patterns): `let pattern = expr`
1107    Let { pattern: Pattern, value: Box<Expr> },
1108    /// Unsafe block: `unsafe { ... }`
1109    Unsafe(Block),
1110    /// Async block: `async { ... }` or `async move { ... }`
1111    Async { block: Block, is_move: bool },
1112    /// Raw pointer dereference: `*ptr`
1113    Deref(Box<Expr>),
1114    /// Address-of: `&expr` or `&mut expr`
1115    AddrOf { mutable: bool, expr: Box<Expr> },
1116    /// Cast: `expr as Type`
1117    Cast { expr: Box<Expr>, ty: TypeExpr },
1118
1119    /// Inline assembly: `asm!("instruction", ...)`
1120    InlineAsm(InlineAsm),
1121
1122    /// Volatile read: `volatile read<T>(ptr)` or `volatile read(ptr)`
1123    VolatileRead {
1124        ptr: Box<Expr>,
1125        ty: Option<TypeExpr>,
1126    },
1127
1128    /// Volatile write: `volatile write<T>(ptr, value)` or `volatile write(ptr, value)`
1129    VolatileWrite {
1130        ptr: Box<Expr>,
1131        value: Box<Expr>,
1132        ty: Option<TypeExpr>,
1133    },
1134
1135    // ========================================
1136    // SIMD Operations
1137    // ========================================
1138    /// SIMD vector literal: `simd[1.0, 2.0, 3.0, 4.0]`
1139    SimdLiteral {
1140        elements: Vec<Expr>,
1141        ty: Option<TypeExpr>,
1142    },
1143
1144    /// SIMD intrinsic operation: `simd::add(a, b)`
1145    SimdIntrinsic { op: SimdOp, args: Vec<Expr> },
1146
1147    /// SIMD shuffle: `simd::shuffle(a, b, [0, 4, 1, 5])`
1148    SimdShuffle {
1149        a: Box<Expr>,
1150        b: Box<Expr>,
1151        indices: Vec<u8>,
1152    },
1153
1154    /// SIMD splat (broadcast scalar to all lanes): `simd::splat(x)`
1155    SimdSplat { value: Box<Expr>, lanes: u8 },
1156
1157    /// SIMD extract single lane: `simd::extract(v, 0)`
1158    SimdExtract { vector: Box<Expr>, index: u8 },
1159
1160    /// SIMD insert into lane: `simd::insert(v, 0, value)`
1161    SimdInsert {
1162        vector: Box<Expr>,
1163        index: u8,
1164        value: Box<Expr>,
1165    },
1166
1167    // ========================================
1168    // Atomic Operations
1169    // ========================================
1170    /// Atomic operation: `atomic::load(&x, Ordering::SeqCst)`
1171    AtomicOp {
1172        op: AtomicOp,
1173        ptr: Box<Expr>,
1174        value: Option<Box<Expr>>,    // For store, swap, fetch_add, etc.
1175        expected: Option<Box<Expr>>, // For compare_exchange
1176        ordering: MemoryOrdering,
1177        failure_ordering: Option<MemoryOrdering>, // For compare_exchange
1178    },
1179
1180    /// Atomic fence: `atomic::fence(Ordering::SeqCst)`
1181    AtomicFence { ordering: MemoryOrdering },
1182
1183    // ==========================================
1184    // Protocol Expressions - Sigil-native networking
1185    // All protocol expressions yield values with Reported evidentiality
1186    // ==========================================
1187    /// HTTP request: `http·get(url)`, `http·post(url)`, etc.
1188    /// Incorporation pattern for building HTTP requests
1189    HttpRequest {
1190        method: HttpMethod,
1191        url: Box<Expr>,
1192        headers: Vec<(Expr, Expr)>,
1193        body: Option<Box<Expr>>,
1194        timeout: Option<Box<Expr>>,
1195    },
1196
1197    /// gRPC call: `grpc·call(service, method)`
1198    /// Incorporation pattern for gRPC operations
1199    GrpcCall {
1200        service: Box<Expr>,
1201        method: Box<Expr>,
1202        message: Option<Box<Expr>>,
1203        metadata: Vec<(Expr, Expr)>,
1204        timeout: Option<Box<Expr>>,
1205    },
1206
1207    /// WebSocket connection: `ws·connect(url)`
1208    /// Incorporation pattern for WebSocket operations
1209    WebSocketConnect {
1210        url: Box<Expr>,
1211        protocols: Vec<Expr>,
1212        headers: Vec<(Expr, Expr)>,
1213    },
1214
1215    /// WebSocket message: `ws·message(data)` or `ws·text(str)` / `ws·binary(bytes)`
1216    WebSocketMessage {
1217        kind: WebSocketMessageKind,
1218        data: Box<Expr>,
1219    },
1220
1221    /// Kafka operation: `kafka·produce(topic, message)`, `kafka·consume(topic)`
1222    KafkaOp {
1223        kind: KafkaOpKind,
1224        topic: Box<Expr>,
1225        payload: Option<Box<Expr>>,
1226        key: Option<Box<Expr>>,
1227        partition: Option<Box<Expr>>,
1228    },
1229
1230    /// GraphQL query: `graphql·query(document)` or `graphql·mutation(document)`
1231    GraphQLOp {
1232        kind: GraphQLOpKind,
1233        document: Box<Expr>,
1234        variables: Option<Box<Expr>>,
1235        operation_name: Option<Box<Expr>>,
1236    },
1237
1238    /// Protocol stream: iterable over network messages
1239    /// `http·stream(url)`, `ws·stream()`, `kafka·stream(topic)`
1240    ProtocolStream {
1241        protocol: ProtocolKind,
1242        source: Box<Expr>,
1243        config: Option<Box<Expr>>,
1244    },
1245
1246    // ==========================================
1247    // Legion Expressions - Holographic Agent Collective
1248    // All Legion expressions work with collective memory and multi-agent coordination
1249    // ==========================================
1250    /// Legion field variable: `memory∿`
1251    /// The ∿ suffix indicates a LegionField collective memory type
1252    LegionFieldVar { name: Ident },
1253
1254    /// Superposition: `field∿ ⊕= pattern`
1255    /// Pattern joins the collective memory
1256    LegionSuperposition {
1257        field: Box<Expr>,
1258        pattern: Box<Expr>,
1259    },
1260
1261    /// Interference query: `query ⫰ field∿`
1262    /// Query the collective memory via interference
1263    LegionInterference { query: Box<Expr>, field: Box<Expr> },
1264
1265    /// Resonance extraction: `resonance~ |◉`
1266    /// Extract agreement peaks from interference pattern
1267    LegionResonance { expr: Box<Expr> },
1268
1269    /// Distribute: `task ⟁ agent_count`
1270    /// Fragment task holographically across agents
1271    LegionDistribute { task: Box<Expr>, count: Box<Expr> },
1272
1273    /// Gather: `fragments ⟀`
1274    /// Unify fragments via interference
1275    LegionGather { fragments: Box<Expr> },
1276
1277    /// Broadcast: `signal ↠ legion`
1278    /// Send signal to all agents
1279    LegionBroadcast {
1280        signal: Box<Expr>,
1281        target: Box<Expr>,
1282    },
1283
1284    /// Consensus: `contributions ⇢`
1285    /// Achieve consensus from multiple contributions
1286    LegionConsensus { contributions: Box<Expr> },
1287
1288    /// Decay: `field∿ ∂= rate`
1289    /// Apply decay to collective memory
1290    LegionDecay { field: Box<Expr>, rate: Box<Expr> },
1291
1292    /// Named argument in function call: `name: value`
1293    /// Used in calls like `stack(axis: 0)` or `func(x: 1, y: 2)`
1294    NamedArg { name: Ident, value: Box<Expr> },
1295}
1296
1297/// Inline assembly expression.
1298#[derive(Debug, Clone, PartialEq)]
1299pub struct InlineAsm {
1300    /// The assembly template string
1301    pub template: String,
1302    /// Output operands
1303    pub outputs: Vec<AsmOperand>,
1304    /// Input operands
1305    pub inputs: Vec<AsmOperand>,
1306    /// Clobbered registers
1307    pub clobbers: Vec<String>,
1308    /// Assembly options
1309    pub options: AsmOptions,
1310}
1311
1312/// An assembly operand (input or output).
1313#[derive(Debug, Clone, PartialEq)]
1314pub struct AsmOperand {
1315    /// Constraint string (e.g., "=r", "r", "m", or register name)
1316    pub constraint: String,
1317    /// The expression to bind
1318    pub expr: Expr,
1319    /// The kind of operand
1320    pub kind: AsmOperandKind,
1321    /// For inout operands, the output expression (if different from input)
1322    pub output: Option<Box<Expr>>,
1323}
1324
1325/// Assembly operand kind.
1326#[derive(Debug, Clone, PartialEq, Eq)]
1327pub enum AsmOperandKind {
1328    /// Input only
1329    Input,
1330    /// Output only
1331    Output,
1332    /// Input and output (same register)
1333    InOut,
1334}
1335
1336/// Assembly options/modifiers.
1337#[derive(Debug, Clone, PartialEq, Default)]
1338pub struct AsmOptions {
1339    /// Volatile (has side effects, cannot be optimized away)
1340    pub volatile: bool,
1341    /// Pure assembly (no side effects)
1342    pub pure_asm: bool,
1343    /// No memory clobber
1344    pub nomem: bool,
1345    /// No stack
1346    pub nostack: bool,
1347    /// Preserves flags
1348    pub preserves_flags: bool,
1349    /// Read-only (inputs only)
1350    pub readonly: bool,
1351    /// AT&T syntax (vs Intel)
1352    pub att_syntax: bool,
1353}
1354
1355/// Pipe operation in a chain.
1356#[derive(Debug, Clone, PartialEq)]
1357pub enum PipeOp {
1358    /// Transform morpheme: `τ{f}`
1359    Transform(Box<Expr>),
1360    /// Filter morpheme: `φ{p}`
1361    Filter(Box<Expr>),
1362    /// Sort morpheme: `σ` or `σ.field`
1363    Sort(Option<Ident>),
1364    /// Reduce morpheme: `ρ{f}`
1365    Reduce(Box<Expr>),
1366    /// Sum reduction: `ρ+` or `ρ_sum` - sum all elements
1367    ReduceSum,
1368    /// Product reduction: `ρ*` or `ρ_prod` - multiply all elements
1369    ReduceProd,
1370    /// Min reduction: `ρ_min` - find minimum element
1371    ReduceMin,
1372    /// Max reduction: `ρ_max` - find maximum element
1373    ReduceMax,
1374    /// Concat reduction: `ρ++` or `ρ_cat` - concatenate strings/arrays
1375    ReduceConcat,
1376    /// All reduction: `ρ&` or `ρ_all` - logical AND (all true)
1377    ReduceAll,
1378    /// Any reduction: `ρ|` or `ρ_any` - logical OR (any true)
1379    ReduceAny,
1380    /// Middle morpheme: `μ` - get middle/median element
1381    Middle,
1382    /// Choice morpheme: `χ` - random element selection
1383    Choice,
1384    /// Nth morpheme: `ν{n}` - get nth element
1385    Nth(Box<Expr>),
1386    /// Next morpheme: `ξ` - get next element (iterator)
1387    Next,
1388    /// First morpheme: `α` - get first element
1389    First,
1390    /// Last morpheme: `ω` - get last element
1391    Last,
1392    /// Parallel morpheme: `∥{op}` or `parallel{op}` - execute operation in parallel
1393    /// Wraps another operation to run it across multiple threads
1394    Parallel(Box<PipeOp>),
1395    /// GPU compute morpheme: `⊛{op}` or `gpu{op}` - execute operation on GPU
1396    /// Wraps another operation to run it as a compute shader
1397    Gpu(Box<PipeOp>),
1398    /// Method call with optional turbofish type arguments: `|collect::<String>()`
1399    Method {
1400        name: Ident,
1401        type_args: Option<Vec<TypeExpr>>,
1402        args: Vec<Expr>,
1403    },
1404    /// Call an arbitrary expression (e.g., `|self.layer` where layer is a callable)
1405    Call(Box<Expr>),
1406    /// Await
1407    Await,
1408    /// Match morpheme: `|match{ Pattern => expr, ... }`
1409    /// Applies pattern matching to the piped value
1410    Match(Vec<MatchArm>),
1411    /// Trust boundary morpheme: `|‽` or `|‽{mapper}`
1412    /// Uses interrobang (‽) to signal crossing a trust/certainty boundary.
1413    /// Unwraps Result/Option or propagates errors, with optional error transformation.
1414    TryMap(Option<Box<Expr>>),
1415    /// Named morpheme: `·map{f}`, `·flow{f}`
1416    Named {
1417        prefix: Vec<Ident>,
1418        body: Option<Box<Expr>>,
1419    },
1420
1421    // ==========================================
1422    // Protocol Operations - Sigil-native networking
1423    // ==========================================
1424    /// Send operation: `|send{data}` or `|⇒{data}` - send data over connection
1425    /// Results are automatically marked with Reported evidentiality
1426    Send(Box<Expr>),
1427
1428    /// Receive operation: `|recv` or `|⇐` - receive data from connection
1429    /// Results are automatically marked with Reported evidentiality
1430    Recv,
1431
1432    /// Stream operation: `|stream{handler}` or `|≋{handler}` - iterate over incoming data
1433    /// Each element is marked with Reported evidentiality
1434    Stream(Box<Expr>),
1435
1436    /// Connect operation: `|connect{config}` or `|⊸{config}` - establish connection
1437    Connect(Option<Box<Expr>>),
1438
1439    /// Close operation: `|close` or `|⊗` - close connection gracefully
1440    Close,
1441
1442    /// Protocol header: `|header{name, value}` - add/set header
1443    Header { name: Box<Expr>, value: Box<Expr> },
1444
1445    /// Protocol body: `|body{data}` - set request body
1446    Body(Box<Expr>),
1447
1448    /// Timeout: `|timeout{ms}` or `|⏱{ms}` - set operation timeout
1449    Timeout(Box<Expr>),
1450
1451    /// Retry: `|retry{count}` or `|retry{count, strategy}` - retry on failure
1452    Retry {
1453        count: Box<Expr>,
1454        strategy: Option<Box<Expr>>,
1455    },
1456
1457    // ==========================================
1458    // Evidence Promotion Operations
1459    // ==========================================
1460    /// Validate operation: `|validate!{predicate}` - promote evidence with validation
1461    /// Takes a predicate function that validates the data.
1462    /// If validation passes: ~ → ! (reported → known)
1463    /// If validation fails: returns an error
1464    /// Example: `data~|validate!{x => x.id > 0 && x.name.len > 0}`
1465    Validate {
1466        predicate: Box<Expr>,
1467        target_evidence: Evidentiality,
1468    },
1469
1470    /// Assume operation: `|assume!` or `|assume!("reason")` - explicit trust promotion
1471    /// Escape hatch that promotes evidence with an audit trail.
1472    /// Always logs the assumption for security review.
1473    /// Example: `external_data~|assume!("trusted legacy system")`
1474    Assume {
1475        reason: Option<Box<Expr>>,
1476        target_evidence: Evidentiality,
1477    },
1478
1479    /// Assert evidence: `|assert_evidence!{expected}` - verify evidence level at compile time
1480    /// Fails compilation if actual evidence doesn't match expected.
1481    /// Example: `data|assert_evidence!{!}` - assert data is known
1482    AssertEvidence(Evidentiality),
1483
1484    // ==========================================
1485    // Scope Functions (Kotlin-inspired)
1486    // ==========================================
1487    /// Also: `|also{f}` - execute side effect, return original value unchanged
1488    /// Like Kotlin's `also` - useful for logging/debugging in pipelines
1489    /// Example: `data|also{println}|process` - logs data, then processes it
1490    Also(Box<Expr>),
1491
1492    /// Apply: `|apply{block}` - mutate value in place, return modified value
1493    /// Like Kotlin's `apply` - useful for configuration/setup
1494    /// Example: `config|apply{.timeout = 5000; .retries = 3}`
1495    Apply(Box<Expr>),
1496
1497    /// TakeIf: `|take_if{predicate}` - return Some(value) if predicate true, None otherwise
1498    /// Like Kotlin's `takeIf` - useful for conditional pipelines
1499    /// Example: `user|take_if{.age >= 18}` - returns Option<User>
1500    TakeIf(Box<Expr>),
1501
1502    /// TakeUnless: `|take_unless{predicate}` - return Some(value) if predicate false
1503    /// Like Kotlin's `takeUnless` - inverse of take_if
1504    /// Example: `item|take_unless{.is_deleted}` - returns Option<Item>
1505    TakeUnless(Box<Expr>),
1506
1507    /// Let: `|let{f}` - transform value, like map but reads better for single values
1508    /// Like Kotlin's `let` - essentially an alias for transform
1509    /// Example: `name|let{.to_uppercase}` - transforms the name
1510    Let(Box<Expr>),
1511
1512    // ==========================================
1513    // Mathematical & APL-Inspired Operations
1514    // ==========================================
1515    /// All/ForAll: `|∀{p}` or `|all{p}` - check if ALL elements satisfy predicate
1516    /// Returns bool. Short-circuits on first false.
1517    /// Example: `numbers|∀{x => x > 0}` - are all positive?
1518    All(Box<Expr>),
1519
1520    /// Any/Exists: `|∃{p}` or `|any{p}` - check if ANY element satisfies predicate
1521    /// Returns bool. Short-circuits on first true.
1522    /// Example: `items|∃{.is_valid}` - is any valid?
1523    Any(Box<Expr>),
1524
1525    /// Compose: `|∘{f}` or `|compose{f}` - function composition
1526    /// Creates a new function that applies f after the current transformation.
1527    /// Example: `parse|∘{validate}|∘{save}` - compose three functions
1528    Compose(Box<Expr>),
1529
1530    /// Zip/Join: `|⋈{other}` or `|zip{other}` - combine with another collection
1531    /// Pairs elements from two collections into tuples.
1532    /// Example: `names|⋈{ages}` -> [(name1, age1), (name2, age2), ...]
1533    Zip(Box<Expr>),
1534
1535    /// Scan/Integral: `|∫{f}` or `|scan{f}` - cumulative fold (like Haskell's scanl)
1536    /// Returns all intermediate accumulator values.
1537    /// Example: `[1,2,3]|∫{+}` -> [1, 3, 6] (running sum)
1538    Scan(Box<Expr>),
1539
1540    /// Diff/Derivative: `|∂` or `|diff` - differences between adjacent elements
1541    /// Returns a collection of deltas.
1542    /// Example: `[1, 4, 6, 10]|∂` -> [3, 2, 4]
1543    Diff,
1544
1545    /// Gradient: `|∇{var}` or `|grad{var}` - automatic differentiation
1546    /// Computes gradient of expression with respect to variable.
1547    /// Example: `loss|∇{weights}` - gradient for backprop
1548    Gradient(Box<Expr>),
1549
1550    /// Sort Ascending: `|⍋` or `|sort_asc` - APL grade-up
1551    /// Sorts in ascending order (same as σ but more explicit)
1552    SortAsc,
1553
1554    /// Sort Descending: `|⍒` or `|sort_desc` - APL grade-down
1555    /// Sorts in descending order
1556    SortDesc,
1557
1558    /// Reverse: `|⌽` or `|rev` - APL rotate/reverse
1559    /// Reverses the collection
1560    Reverse,
1561
1562    /// Cycle: `|↻{n}` or `|cycle{n}` - repeat collection n times
1563    /// Example: `[1,2]|↻{3}` -> [1,2,1,2,1,2]
1564    Cycle(Box<Expr>),
1565
1566    /// Windows: `|⌺{n}` or `|windows{n}` - sliding window
1567    /// Example: `[1,2,3,4]|⌺{2}` -> [[1,2], [2,3], [3,4]]
1568    Windows(Box<Expr>),
1569
1570    /// Chunks: `|⊞{n}` or `|chunks{n}` - split into chunks
1571    /// Example: `[1,2,3,4]|⊞{2}` -> [[1,2], [3,4]]
1572    Chunks(Box<Expr>),
1573
1574    /// Flatten: `|⋳` or `|flatten` - flatten nested collection
1575    /// Example: `[[1,2], [3,4]]|⋳` -> [1,2,3,4]
1576    Flatten,
1577
1578    /// Unique: `|∪` or `|unique` - remove duplicates (set union with self)
1579    /// Example: `[1,2,2,3,3,3]|∪` -> [1,2,3]
1580    Unique,
1581
1582    /// Enumerate: `|⍳` or `|enumerate` - APL iota, pair with indices
1583    /// Example: `["a","b","c"]|⍳` -> [(0,"a"), (1,"b"), (2,"c")]
1584    Enumerate,
1585
1586    // ==========================================
1587    // Holographic Operations - Sigil-native distributed computing
1588    // ==========================================
1589    /// Universal reconstruction: `|∀` - reconstruct whole from shards
1590    /// For Vec<T>: sums all elements (numeric reconstruction)
1591    /// For distributed data: merges fragments into coherent whole
1592    /// Example: `vec![1, 2, 3, 4]|∀` -> 10
1593    Universal,
1594
1595    /// Possibility extraction: `|◊` - extract approximate/speculative answer
1596    /// For uncertain data: returns best-effort approximation
1597    /// Preserves uncertainty markers in output
1598    /// Example: `uncertain_data|◊` -> approximate value
1599    Possibility,
1600
1601    /// Possibility method call: `|◊method` or `|◊method(args)`
1602    /// Calls method with possibility semantics (returns approximate result)
1603    /// Example: `hll|◊count` -> approximate cardinality
1604    PossibilityMethod {
1605        name: Ident,
1606        args: Vec<Expr>,
1607    },
1608
1609    /// Necessity verification: `|□` - verify and promote to certain
1610    /// Validates data meets requirements, promotes evidence level
1611    /// Fails if verification cannot be established
1612    /// Example: `data|□` -> verified data with ! evidentiality
1613    Necessity,
1614
1615    /// Necessity method call: `|□method` or `|□method(args)`
1616    /// Calls method with necessity semantics (verifies and promotes evidence)
1617    /// Example: `node~|□verify` -> verified with ! evidentiality
1618    NecessityMethod {
1619        name: Ident,
1620        args: Vec<Expr>,
1621    },
1622}
1623
1624/// Incorporation segment.
1625#[derive(Debug, Clone, PartialEq)]
1626pub struct IncorporationSegment {
1627    pub name: Ident,
1628    pub args: Option<Vec<Expr>>,
1629}
1630
1631/// Morpheme kinds.
1632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1633pub enum MorphemeKind {
1634    Transform, // τ
1635    Filter,    // φ
1636    Sort,      // σ
1637    Reduce,    // ρ
1638    Lambda,    // λ
1639    Sum,       // Σ
1640    Product,   // Π
1641    Middle,    // μ
1642    Choice,    // χ
1643    Nth,       // ν
1644    Next,      // ξ
1645    First,     // α
1646    Last,      // ω
1647}
1648
1649// ==========================================
1650// Protocol Types - Sigil-native networking
1651// ==========================================
1652
1653/// HTTP methods for http· incorporation.
1654#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1655pub enum HttpMethod {
1656    Get,
1657    Post,
1658    Put,
1659    Delete,
1660    Patch,
1661    Head,
1662    Options,
1663    Connect,
1664    Trace,
1665}
1666
1667impl std::fmt::Display for HttpMethod {
1668    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1669        match self {
1670            HttpMethod::Get => write!(f, "GET"),
1671            HttpMethod::Post => write!(f, "POST"),
1672            HttpMethod::Put => write!(f, "PUT"),
1673            HttpMethod::Delete => write!(f, "DELETE"),
1674            HttpMethod::Patch => write!(f, "PATCH"),
1675            HttpMethod::Head => write!(f, "HEAD"),
1676            HttpMethod::Options => write!(f, "OPTIONS"),
1677            HttpMethod::Connect => write!(f, "CONNECT"),
1678            HttpMethod::Trace => write!(f, "TRACE"),
1679        }
1680    }
1681}
1682
1683/// WebSocket message kinds for ws· incorporation.
1684#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1685pub enum WebSocketMessageKind {
1686    Text,
1687    Binary,
1688    Ping,
1689    Pong,
1690    Close,
1691}
1692
1693/// Kafka operation kinds for kafka· incorporation.
1694#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1695pub enum KafkaOpKind {
1696    Produce,
1697    Consume,
1698    Subscribe,
1699    Unsubscribe,
1700    Commit,
1701    Seek,
1702}
1703
1704/// GraphQL operation kinds for graphql· incorporation.
1705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1706pub enum GraphQLOpKind {
1707    Query,
1708    Mutation,
1709    Subscription,
1710}
1711
1712/// Protocol kinds for stream expressions.
1713#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1714pub enum ProtocolKind {
1715    Http,
1716    Grpc,
1717    WebSocket,
1718    Kafka,
1719    Amqp,
1720    GraphQL,
1721}
1722
1723impl std::fmt::Display for ProtocolKind {
1724    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1725        match self {
1726            ProtocolKind::Http => write!(f, "http"),
1727            ProtocolKind::Grpc => write!(f, "grpc"),
1728            ProtocolKind::WebSocket => write!(f, "ws"),
1729            ProtocolKind::Kafka => write!(f, "kafka"),
1730            ProtocolKind::Amqp => write!(f, "amqp"),
1731            ProtocolKind::GraphQL => write!(f, "graphql"),
1732        }
1733    }
1734}
1735
1736/// Binary operators.
1737#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1738pub enum BinOp {
1739    Add,
1740    Sub,
1741    Mul,
1742    Div,
1743    Rem,
1744    Pow,
1745    And,
1746    Or,
1747    BitAnd,
1748    BitOr,
1749    BitXor,
1750    Shl,
1751    Shr,
1752    Eq,
1753    Ne,
1754    Lt,
1755    Le,
1756    Gt,
1757    Ge,
1758    Concat,
1759    /// Matrix multiplication (@)
1760    MatMul,
1761    /// Hadamard/element-wise product (⊙)
1762    Hadamard,
1763    /// Tensor/outer product (⊗)
1764    TensorProd,
1765    /// Convolution/merge (⊛) - holographic shard merging
1766    Convolve,
1767}
1768
1769/// Unary operators.
1770#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1771pub enum UnaryOp {
1772    Neg,
1773    Not,
1774    Deref,
1775    Ref,
1776    RefMut,
1777}
1778
1779/// Literal values.
1780#[derive(Debug, Clone, PartialEq)]
1781pub enum Literal {
1782    Int {
1783        value: String,
1784        base: NumBase,
1785        suffix: Option<String>,
1786    },
1787    Float {
1788        value: String,
1789        suffix: Option<String>,
1790    },
1791    String(String),
1792    /// Multi-line string literal (""" ... """)
1793    MultiLineString(String),
1794    /// Raw string literal (no escape processing)
1795    RawString(String),
1796    /// Byte string literal (b"...")
1797    ByteString(Vec<u8>),
1798    /// Interpolated string literal (f"... {expr} ...")
1799    InterpolatedString {
1800        parts: Vec<InterpolationPart>,
1801    },
1802    /// SQL sigil string (σ"...")
1803    SigilStringSql(String),
1804    /// Route sigil string (ρ"...")
1805    SigilStringRoute(String),
1806    Char(char),
1807    /// Byte character literal (b'x')
1808    ByteChar(u8),
1809    Bool(bool),
1810    Null, // null
1811    /// Special mathematical constants
1812    Empty, // ∅
1813    Infinity, // ∞
1814    Circle, // ◯
1815}
1816
1817/// Part of an interpolated string
1818#[derive(Debug, Clone, PartialEq)]
1819pub enum InterpolationPart {
1820    /// Literal text segment
1821    Text(String),
1822    /// Expression to be evaluated and converted to string
1823    Expr(Box<Expr>),
1824}
1825
1826/// Number bases.
1827#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1828pub enum NumBase {
1829    Binary,       // 0b
1830    Octal,        // 0o
1831    Decimal,      // default
1832    Hex,          // 0x
1833    Vigesimal,    // 0v (base 20)
1834    Sexagesimal,  // 0s (base 60)
1835    Duodecimal,   // 0z (base 12)
1836    Explicit(u8), // N:₆₀ etc.
1837}
1838
1839#[derive(Debug, Clone, PartialEq)]
1840pub struct FieldInit {
1841    pub name: Ident,
1842    pub value: Option<Expr>,
1843}
1844
1845#[derive(Debug, Clone, PartialEq)]
1846pub struct MatchArm {
1847    pub pattern: Pattern,
1848    pub guard: Option<Expr>,
1849    pub body: Expr,
1850}
1851
1852#[derive(Debug, Clone, PartialEq)]
1853pub struct ClosureParam {
1854    pub pattern: Pattern,
1855    pub ty: Option<TypeExpr>,
1856}