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    /// Never type: `!` or `never`
703    Never,
704    /// Inferred: `_`
705    Infer,
706    /// Lifetime bound: `'static`, `'a`
707    Lifetime(String),
708    /// Trait object: `dyn Trait` or `dyn Trait + Send + 'static`
709    TraitObject(Vec<TypeExpr>),
710    /// Higher-ranked trait bound: `for<'a> Trait<'a>`
711    Hrtb {
712        lifetimes: Vec<String>,
713        bound: Box<TypeExpr>,
714    },
715    /// Inline struct type: `struct { field: Type, ... }`
716    InlineStruct { fields: Vec<FieldDef> },
717    /// Inline enum type: `enum { Variant1, Variant2(Type), ... }`
718    InlineEnum { variants: Vec<EnumVariant> },
719    /// Impl trait: `impl Trait`, `impl Fn() -> R`
720    ImplTrait(Vec<TypeExpr>),
721    /// Associated type binding: `Output = Type` used in trait bounds
722    AssocTypeBinding { name: Ident, ty: Box<TypeExpr> },
723    /// Const expression in type position (for const generics): `<32>`, `<{N + 1}>`
724    ConstExpr(Box<Expr>),
725    /// Qualified path type: `<Type as Trait>::AssociatedType`
726    /// Also supports `<Type>::Associated` for inherent associated types
727    QualifiedPath {
728        /// The base type: `Type` in `<Type as Trait>::...`
729        self_type: Box<TypeExpr>,
730        /// Optional trait bound: `Trait` in `<Type as Trait>::...`
731        trait_path: Option<TypePath>,
732        /// The associated item path: `AssociatedType` or `Associated::Nested`
733        item_path: TypePath,
734    },
735}
736
737/// Type path with optional generics.
738#[derive(Debug, Clone, PartialEq)]
739pub struct TypePath {
740    pub segments: Vec<PathSegment>,
741}
742
743#[derive(Debug, Clone, PartialEq)]
744pub struct PathSegment {
745    pub ident: Ident,
746    pub generics: Option<Vec<TypeExpr>>,
747}
748
749/// Memory representation for structs.
750#[derive(Debug, Clone, PartialEq)]
751pub enum StructRepr {
752    /// C-compatible layout
753    C,
754    /// Transparent (single field struct)
755    Transparent,
756    /// Specific integer type
757    Int(String),
758}
759
760/// Struct definition.
761#[derive(Debug, Clone, PartialEq)]
762pub struct StructDef {
763    pub visibility: Visibility,
764    pub attrs: StructAttrs,
765    pub name: Ident,
766    pub generics: Option<Generics>,
767    pub fields: StructFields,
768}
769
770#[derive(Debug, Clone, PartialEq)]
771pub enum StructFields {
772    Named(Vec<FieldDef>),
773    Tuple(Vec<TypeExpr>),
774    Unit,
775}
776
777#[derive(Debug, Clone, PartialEq)]
778pub struct FieldDef {
779    pub visibility: Visibility,
780    pub name: Ident,
781    pub ty: TypeExpr,
782    /// Default value for the field (e.g., `field: Type = default_expr`)
783    pub default: Option<Expr>,
784}
785
786/// Enum definition.
787#[derive(Debug, Clone, PartialEq)]
788pub struct EnumDef {
789    pub visibility: Visibility,
790    pub name: Ident,
791    pub generics: Option<Generics>,
792    pub variants: Vec<EnumVariant>,
793}
794
795#[derive(Debug, Clone, PartialEq)]
796pub struct EnumVariant {
797    pub name: Ident,
798    pub fields: StructFields,
799    pub discriminant: Option<Expr>,
800}
801
802/// Trait definition.
803#[derive(Debug, Clone, PartialEq)]
804pub struct TraitDef {
805    pub visibility: Visibility,
806    pub name: Ident,
807    pub generics: Option<Generics>,
808    pub supertraits: Vec<TypeExpr>,
809    pub items: Vec<TraitItem>,
810}
811
812#[derive(Debug, Clone, PartialEq)]
813pub enum TraitItem {
814    Function(Function),
815    Type { name: Ident, bounds: Vec<TypeExpr> },
816    Const { name: Ident, ty: TypeExpr },
817}
818
819/// Impl block.
820#[derive(Debug, Clone, PartialEq)]
821pub struct ImplBlock {
822    pub generics: Option<Generics>,
823    pub trait_: Option<TypePath>,
824    pub self_ty: TypeExpr,
825    pub items: Vec<ImplItem>,
826}
827
828#[derive(Debug, Clone, PartialEq)]
829pub enum ImplItem {
830    Function(Function),
831    Type(TypeAlias),
832    Const(ConstDef),
833}
834
835/// Type alias.
836#[derive(Debug, Clone, PartialEq)]
837pub struct TypeAlias {
838    pub visibility: Visibility,
839    pub name: Ident,
840    pub generics: Option<Generics>,
841    pub ty: TypeExpr,
842}
843
844/// Module.
845#[derive(Debug, Clone, PartialEq)]
846pub struct Module {
847    pub visibility: Visibility,
848    pub name: Ident,
849    pub items: Option<Vec<Spanned<Item>>>,
850}
851
852/// Use declaration.
853#[derive(Debug, Clone, PartialEq)]
854pub struct UseDecl {
855    pub visibility: Visibility,
856    pub tree: UseTree,
857}
858
859#[derive(Debug, Clone, PartialEq)]
860pub enum UseTree {
861    Path { prefix: Ident, suffix: Box<UseTree> },
862    Name(Ident),
863    Rename { name: Ident, alias: Ident },
864    Glob,
865    Group(Vec<UseTree>),
866}
867
868/// Const definition.
869#[derive(Debug, Clone, PartialEq)]
870pub struct ConstDef {
871    pub visibility: Visibility,
872    pub name: Ident,
873    pub ty: TypeExpr,
874    pub value: Expr,
875}
876
877/// Static definition.
878#[derive(Debug, Clone, PartialEq)]
879pub struct StaticDef {
880    pub visibility: Visibility,
881    pub mutable: bool,
882    pub name: Ident,
883    pub ty: TypeExpr,
884    pub value: Expr,
885}
886
887/// Actor definition (concurrency).
888#[derive(Debug, Clone, PartialEq)]
889pub struct ActorDef {
890    pub visibility: Visibility,
891    pub name: Ident,
892    pub generics: Option<Generics>,
893    pub state: Vec<FieldDef>,
894    pub handlers: Vec<MessageHandler>,
895}
896
897#[derive(Debug, Clone, PartialEq)]
898pub struct MessageHandler {
899    pub message: Ident,
900    pub params: Vec<Param>,
901    pub return_type: Option<TypeExpr>,
902    pub body: Block,
903}
904
905/// Code block.
906#[derive(Debug, Clone, PartialEq)]
907pub struct Block {
908    pub stmts: Vec<Stmt>,
909    pub expr: Option<Box<Expr>>,
910}
911
912/// Statements.
913#[derive(Debug, Clone, PartialEq)]
914pub enum Stmt {
915    Let {
916        pattern: Pattern,
917        ty: Option<TypeExpr>,
918        init: Option<Expr>,
919    },
920    /// Let-else statement: `let PATTERN = EXPR else { ... }`
921    LetElse {
922        pattern: Pattern,
923        ty: Option<TypeExpr>,
924        init: Expr,
925        else_branch: Box<Expr>,
926    },
927    Expr(Expr),
928    Semi(Expr),
929    Item(Box<Item>),
930}
931
932/// Patterns.
933#[derive(Debug, Clone, PartialEq)]
934pub enum Pattern {
935    Ident {
936        mutable: bool,
937        name: Ident,
938        evidentiality: Option<Evidentiality>,
939    },
940    /// Path pattern for matching unit enum variants: Token::Fn
941    Path(TypePath),
942    Tuple(Vec<Pattern>),
943    Struct {
944        path: TypePath,
945        fields: Vec<FieldPattern>,
946        rest: bool,
947    },
948    TupleStruct {
949        path: TypePath,
950        fields: Vec<Pattern>,
951    },
952    Slice(Vec<Pattern>),
953    Or(Vec<Pattern>),
954    Literal(Literal),
955    Range {
956        start: Option<Box<Pattern>>,
957        end: Option<Box<Pattern>>,
958        inclusive: bool,
959    },
960    /// Reference pattern: `&pattern` or `&mut pattern`
961    Ref {
962        mutable: bool,
963        pattern: Box<Pattern>,
964    },
965    /// Ref binding pattern: `ref ident` or `ref mut ident`
966    RefBinding {
967        mutable: bool,
968        name: Ident,
969        evidentiality: Option<Evidentiality>,
970    },
971    Wildcard,
972    Rest,
973}
974
975#[derive(Debug, Clone, PartialEq)]
976pub struct FieldPattern {
977    pub name: Ident,
978    pub pattern: Option<Pattern>,
979}
980
981/// Expressions.
982#[derive(Debug, Clone, PartialEq)]
983pub enum Expr {
984    /// Literal value
985    Literal(Literal),
986    /// Variable reference
987    Path(TypePath),
988    /// Binary operation
989    Binary {
990        left: Box<Expr>,
991        op: BinOp,
992        right: Box<Expr>,
993    },
994    /// Unary operation
995    Unary { op: UnaryOp, expr: Box<Expr> },
996    /// Pipe expression: `x|f|g`
997    Pipe {
998        expr: Box<Expr>,
999        operations: Vec<PipeOp>,
1000    },
1001    /// Incorporation: `file·open·read`
1002    Incorporation { segments: Vec<IncorporationSegment> },
1003    /// Morpheme application: `τ{f}`
1004    Morpheme { kind: MorphemeKind, body: Box<Expr> },
1005    /// Function call
1006    Call { func: Box<Expr>, args: Vec<Expr> },
1007    /// Method call
1008    MethodCall {
1009        receiver: Box<Expr>,
1010        method: Ident,
1011        /// Turbofish type arguments: `method::<T, U>(args)`
1012        type_args: Option<Vec<TypeExpr>>,
1013        args: Vec<Expr>,
1014    },
1015    /// Field access
1016    Field { expr: Box<Expr>, field: Ident },
1017    /// Index: `arr[i]`
1018    Index { expr: Box<Expr>, index: Box<Expr> },
1019    /// Array literal
1020    Array(Vec<Expr>),
1021    /// Array repeat literal: `[value; count]`
1022    ArrayRepeat { value: Box<Expr>, count: Box<Expr> },
1023    /// Tuple literal
1024    Tuple(Vec<Expr>),
1025    /// Struct literal
1026    Struct {
1027        path: TypePath,
1028        fields: Vec<FieldInit>,
1029        rest: Option<Box<Expr>>,
1030    },
1031    /// Block expression
1032    Block(Block),
1033    /// If expression
1034    If {
1035        condition: Box<Expr>,
1036        then_branch: Block,
1037        else_branch: Option<Box<Expr>>,
1038    },
1039    /// Match expression
1040    Match {
1041        expr: Box<Expr>,
1042        arms: Vec<MatchArm>,
1043    },
1044    /// Loop with optional label: `'label: loop { ... }`
1045    Loop { label: Option<Ident>, body: Block },
1046    /// While loop with optional label: `'label: while cond { ... }`
1047    While {
1048        label: Option<Ident>,
1049        condition: Box<Expr>,
1050        body: Block,
1051    },
1052    /// For loop with optional label: `'label: for x in iter { ... }`
1053    For {
1054        label: Option<Ident>,
1055        pattern: Pattern,
1056        iter: Box<Expr>,
1057        body: Block,
1058    },
1059    /// Closure: `{x => x + 1}` or `|x| x + 1` or `move |x| x + 1` or `|x| -> T { ... }`
1060    Closure {
1061        params: Vec<ClosureParam>,
1062        /// Optional explicit return type annotation: `|x| -> i32 { x + 1 }`
1063        return_type: Option<TypeExpr>,
1064        body: Box<Expr>,
1065        /// Whether this is a move closure that takes ownership of captured variables
1066        is_move: bool,
1067    },
1068    /// Await with optional evidentiality: `expr⌛` or `expr⌛?` or `expr⌛!` or `expr⌛~`
1069    /// The evidentiality marker specifies how to handle the awaited result:
1070    /// - `⌛?` - await and propagate error (uncertain)
1071    /// - `⌛!` - await, expect success (known/infallible)
1072    /// - `⌛~` - await external/reported source
1073    /// - `⌛‽` - await with trust boundary crossing
1074    Await {
1075        expr: Box<Expr>,
1076        evidentiality: Option<Evidentiality>,
1077    },
1078    /// Try: `expr?`
1079    Try(Box<Expr>),
1080    /// Return
1081    Return(Option<Box<Expr>>),
1082    /// Break with optional label and value: `break 'label value`
1083    Break {
1084        label: Option<Ident>,
1085        value: Option<Box<Expr>>,
1086    },
1087    /// Continue with optional label: `continue 'label`
1088    Continue { label: Option<Ident> },
1089    /// Range: `a..b` or `a..=b`
1090    Range {
1091        start: Option<Box<Expr>>,
1092        end: Option<Box<Expr>>,
1093        inclusive: bool,
1094    },
1095    /// Macro invocation
1096    Macro { path: TypePath, tokens: String },
1097    /// With evidentiality marker
1098    Evidential {
1099        expr: Box<Expr>,
1100        evidentiality: Evidentiality,
1101    },
1102    /// Assignment: `x = value`
1103    Assign { target: Box<Expr>, value: Box<Expr> },
1104    /// Let expression (for if-let, while-let patterns): `let pattern = expr`
1105    Let { pattern: Pattern, value: Box<Expr> },
1106    /// Unsafe block: `unsafe { ... }`
1107    Unsafe(Block),
1108    /// Async block: `async { ... }` or `async move { ... }`
1109    Async { block: Block, is_move: bool },
1110    /// Raw pointer dereference: `*ptr`
1111    Deref(Box<Expr>),
1112    /// Address-of: `&expr` or `&mut expr`
1113    AddrOf { mutable: bool, expr: Box<Expr> },
1114    /// Cast: `expr as Type`
1115    Cast { expr: Box<Expr>, ty: TypeExpr },
1116
1117    /// Inline assembly: `asm!("instruction", ...)`
1118    InlineAsm(InlineAsm),
1119
1120    /// Volatile read: `volatile read<T>(ptr)` or `volatile read(ptr)`
1121    VolatileRead {
1122        ptr: Box<Expr>,
1123        ty: Option<TypeExpr>,
1124    },
1125
1126    /// Volatile write: `volatile write<T>(ptr, value)` or `volatile write(ptr, value)`
1127    VolatileWrite {
1128        ptr: Box<Expr>,
1129        value: Box<Expr>,
1130        ty: Option<TypeExpr>,
1131    },
1132
1133    // ========================================
1134    // SIMD Operations
1135    // ========================================
1136    /// SIMD vector literal: `simd[1.0, 2.0, 3.0, 4.0]`
1137    SimdLiteral {
1138        elements: Vec<Expr>,
1139        ty: Option<TypeExpr>,
1140    },
1141
1142    /// SIMD intrinsic operation: `simd::add(a, b)`
1143    SimdIntrinsic { op: SimdOp, args: Vec<Expr> },
1144
1145    /// SIMD shuffle: `simd::shuffle(a, b, [0, 4, 1, 5])`
1146    SimdShuffle {
1147        a: Box<Expr>,
1148        b: Box<Expr>,
1149        indices: Vec<u8>,
1150    },
1151
1152    /// SIMD splat (broadcast scalar to all lanes): `simd::splat(x)`
1153    SimdSplat { value: Box<Expr>, lanes: u8 },
1154
1155    /// SIMD extract single lane: `simd::extract(v, 0)`
1156    SimdExtract { vector: Box<Expr>, index: u8 },
1157
1158    /// SIMD insert into lane: `simd::insert(v, 0, value)`
1159    SimdInsert {
1160        vector: Box<Expr>,
1161        index: u8,
1162        value: Box<Expr>,
1163    },
1164
1165    // ========================================
1166    // Atomic Operations
1167    // ========================================
1168    /// Atomic operation: `atomic::load(&x, Ordering::SeqCst)`
1169    AtomicOp {
1170        op: AtomicOp,
1171        ptr: Box<Expr>,
1172        value: Option<Box<Expr>>,    // For store, swap, fetch_add, etc.
1173        expected: Option<Box<Expr>>, // For compare_exchange
1174        ordering: MemoryOrdering,
1175        failure_ordering: Option<MemoryOrdering>, // For compare_exchange
1176    },
1177
1178    /// Atomic fence: `atomic::fence(Ordering::SeqCst)`
1179    AtomicFence { ordering: MemoryOrdering },
1180
1181    // ==========================================
1182    // Protocol Expressions - Sigil-native networking
1183    // All protocol expressions yield values with Reported evidentiality
1184    // ==========================================
1185    /// HTTP request: `http·get(url)`, `http·post(url)`, etc.
1186    /// Incorporation pattern for building HTTP requests
1187    HttpRequest {
1188        method: HttpMethod,
1189        url: Box<Expr>,
1190        headers: Vec<(Expr, Expr)>,
1191        body: Option<Box<Expr>>,
1192        timeout: Option<Box<Expr>>,
1193    },
1194
1195    /// gRPC call: `grpc·call(service, method)`
1196    /// Incorporation pattern for gRPC operations
1197    GrpcCall {
1198        service: Box<Expr>,
1199        method: Box<Expr>,
1200        message: Option<Box<Expr>>,
1201        metadata: Vec<(Expr, Expr)>,
1202        timeout: Option<Box<Expr>>,
1203    },
1204
1205    /// WebSocket connection: `ws·connect(url)`
1206    /// Incorporation pattern for WebSocket operations
1207    WebSocketConnect {
1208        url: Box<Expr>,
1209        protocols: Vec<Expr>,
1210        headers: Vec<(Expr, Expr)>,
1211    },
1212
1213    /// WebSocket message: `ws·message(data)` or `ws·text(str)` / `ws·binary(bytes)`
1214    WebSocketMessage {
1215        kind: WebSocketMessageKind,
1216        data: Box<Expr>,
1217    },
1218
1219    /// Kafka operation: `kafka·produce(topic, message)`, `kafka·consume(topic)`
1220    KafkaOp {
1221        kind: KafkaOpKind,
1222        topic: Box<Expr>,
1223        payload: Option<Box<Expr>>,
1224        key: Option<Box<Expr>>,
1225        partition: Option<Box<Expr>>,
1226    },
1227
1228    /// GraphQL query: `graphql·query(document)` or `graphql·mutation(document)`
1229    GraphQLOp {
1230        kind: GraphQLOpKind,
1231        document: Box<Expr>,
1232        variables: Option<Box<Expr>>,
1233        operation_name: Option<Box<Expr>>,
1234    },
1235
1236    /// Protocol stream: iterable over network messages
1237    /// `http·stream(url)`, `ws·stream()`, `kafka·stream(topic)`
1238    ProtocolStream {
1239        protocol: ProtocolKind,
1240        source: Box<Expr>,
1241        config: Option<Box<Expr>>,
1242    },
1243
1244    // ==========================================
1245    // Legion Expressions - Holographic Agent Collective
1246    // All Legion expressions work with collective memory and multi-agent coordination
1247    // ==========================================
1248    /// Legion field variable: `memory∿`
1249    /// The ∿ suffix indicates a LegionField collective memory type
1250    LegionFieldVar { name: Ident },
1251
1252    /// Superposition: `field∿ ⊕= pattern`
1253    /// Pattern joins the collective memory
1254    LegionSuperposition {
1255        field: Box<Expr>,
1256        pattern: Box<Expr>,
1257    },
1258
1259    /// Interference query: `query ⫰ field∿`
1260    /// Query the collective memory via interference
1261    LegionInterference { query: Box<Expr>, field: Box<Expr> },
1262
1263    /// Resonance extraction: `resonance~ |◉`
1264    /// Extract agreement peaks from interference pattern
1265    LegionResonance { expr: Box<Expr> },
1266
1267    /// Distribute: `task ⟁ agent_count`
1268    /// Fragment task holographically across agents
1269    LegionDistribute { task: Box<Expr>, count: Box<Expr> },
1270
1271    /// Gather: `fragments ⟀`
1272    /// Unify fragments via interference
1273    LegionGather { fragments: Box<Expr> },
1274
1275    /// Broadcast: `signal ↠ legion`
1276    /// Send signal to all agents
1277    LegionBroadcast {
1278        signal: Box<Expr>,
1279        target: Box<Expr>,
1280    },
1281
1282    /// Consensus: `contributions ⇢`
1283    /// Achieve consensus from multiple contributions
1284    LegionConsensus { contributions: Box<Expr> },
1285
1286    /// Decay: `field∿ ∂= rate`
1287    /// Apply decay to collective memory
1288    LegionDecay { field: Box<Expr>, rate: Box<Expr> },
1289
1290    /// Named argument in function call: `name: value`
1291    /// Used in calls like `stack(axis: 0)` or `func(x: 1, y: 2)`
1292    NamedArg { name: Ident, value: Box<Expr> },
1293}
1294
1295/// Inline assembly expression.
1296#[derive(Debug, Clone, PartialEq)]
1297pub struct InlineAsm {
1298    /// The assembly template string
1299    pub template: String,
1300    /// Output operands
1301    pub outputs: Vec<AsmOperand>,
1302    /// Input operands
1303    pub inputs: Vec<AsmOperand>,
1304    /// Clobbered registers
1305    pub clobbers: Vec<String>,
1306    /// Assembly options
1307    pub options: AsmOptions,
1308}
1309
1310/// An assembly operand (input or output).
1311#[derive(Debug, Clone, PartialEq)]
1312pub struct AsmOperand {
1313    /// Constraint string (e.g., "=r", "r", "m", or register name)
1314    pub constraint: String,
1315    /// The expression to bind
1316    pub expr: Expr,
1317    /// The kind of operand
1318    pub kind: AsmOperandKind,
1319    /// For inout operands, the output expression (if different from input)
1320    pub output: Option<Box<Expr>>,
1321}
1322
1323/// Assembly operand kind.
1324#[derive(Debug, Clone, PartialEq, Eq)]
1325pub enum AsmOperandKind {
1326    /// Input only
1327    Input,
1328    /// Output only
1329    Output,
1330    /// Input and output (same register)
1331    InOut,
1332}
1333
1334/// Assembly options/modifiers.
1335#[derive(Debug, Clone, PartialEq, Default)]
1336pub struct AsmOptions {
1337    /// Volatile (has side effects, cannot be optimized away)
1338    pub volatile: bool,
1339    /// Pure assembly (no side effects)
1340    pub pure_asm: bool,
1341    /// No memory clobber
1342    pub nomem: bool,
1343    /// No stack
1344    pub nostack: bool,
1345    /// Preserves flags
1346    pub preserves_flags: bool,
1347    /// Read-only (inputs only)
1348    pub readonly: bool,
1349    /// AT&T syntax (vs Intel)
1350    pub att_syntax: bool,
1351}
1352
1353/// Pipe operation in a chain.
1354#[derive(Debug, Clone, PartialEq)]
1355pub enum PipeOp {
1356    /// Transform morpheme: `τ{f}`
1357    Transform(Box<Expr>),
1358    /// Filter morpheme: `φ{p}`
1359    Filter(Box<Expr>),
1360    /// Sort morpheme: `σ` or `σ.field`
1361    Sort(Option<Ident>),
1362    /// Reduce morpheme: `ρ{f}`
1363    Reduce(Box<Expr>),
1364    /// Sum reduction: `ρ+` or `ρ_sum` - sum all elements
1365    ReduceSum,
1366    /// Product reduction: `ρ*` or `ρ_prod` - multiply all elements
1367    ReduceProd,
1368    /// Min reduction: `ρ_min` - find minimum element
1369    ReduceMin,
1370    /// Max reduction: `ρ_max` - find maximum element
1371    ReduceMax,
1372    /// Concat reduction: `ρ++` or `ρ_cat` - concatenate strings/arrays
1373    ReduceConcat,
1374    /// All reduction: `ρ&` or `ρ_all` - logical AND (all true)
1375    ReduceAll,
1376    /// Any reduction: `ρ|` or `ρ_any` - logical OR (any true)
1377    ReduceAny,
1378    /// Middle morpheme: `μ` - get middle/median element
1379    Middle,
1380    /// Choice morpheme: `χ` - random element selection
1381    Choice,
1382    /// Nth morpheme: `ν{n}` - get nth element
1383    Nth(Box<Expr>),
1384    /// Next morpheme: `ξ` - get next element (iterator)
1385    Next,
1386    /// First morpheme: `α` - get first element
1387    First,
1388    /// Last morpheme: `ω` - get last element
1389    Last,
1390    /// Parallel morpheme: `∥{op}` or `parallel{op}` - execute operation in parallel
1391    /// Wraps another operation to run it across multiple threads
1392    Parallel(Box<PipeOp>),
1393    /// GPU compute morpheme: `⊛{op}` or `gpu{op}` - execute operation on GPU
1394    /// Wraps another operation to run it as a compute shader
1395    Gpu(Box<PipeOp>),
1396    /// Method call with optional turbofish type arguments: `|collect::<String>()`
1397    Method {
1398        name: Ident,
1399        type_args: Option<Vec<TypeExpr>>,
1400        args: Vec<Expr>,
1401    },
1402    /// Call an arbitrary expression (e.g., `|self.layer` where layer is a callable)
1403    Call(Box<Expr>),
1404    /// Await
1405    Await,
1406    /// Match morpheme: `|match{ Pattern => expr, ... }`
1407    /// Applies pattern matching to the piped value
1408    Match(Vec<MatchArm>),
1409    /// Trust boundary morpheme: `|‽` or `|‽{mapper}`
1410    /// Uses interrobang (‽) to signal crossing a trust/certainty boundary.
1411    /// Unwraps Result/Option or propagates errors, with optional error transformation.
1412    TryMap(Option<Box<Expr>>),
1413    /// Named morpheme: `·map{f}`, `·flow{f}`
1414    Named {
1415        prefix: Vec<Ident>,
1416        body: Option<Box<Expr>>,
1417    },
1418
1419    // ==========================================
1420    // Protocol Operations - Sigil-native networking
1421    // ==========================================
1422    /// Send operation: `|send{data}` or `|⇒{data}` - send data over connection
1423    /// Results are automatically marked with Reported evidentiality
1424    Send(Box<Expr>),
1425
1426    /// Receive operation: `|recv` or `|⇐` - receive data from connection
1427    /// Results are automatically marked with Reported evidentiality
1428    Recv,
1429
1430    /// Stream operation: `|stream{handler}` or `|≋{handler}` - iterate over incoming data
1431    /// Each element is marked with Reported evidentiality
1432    Stream(Box<Expr>),
1433
1434    /// Connect operation: `|connect{config}` or `|⊸{config}` - establish connection
1435    Connect(Option<Box<Expr>>),
1436
1437    /// Close operation: `|close` or `|⊗` - close connection gracefully
1438    Close,
1439
1440    /// Protocol header: `|header{name, value}` - add/set header
1441    Header { name: Box<Expr>, value: Box<Expr> },
1442
1443    /// Protocol body: `|body{data}` - set request body
1444    Body(Box<Expr>),
1445
1446    /// Timeout: `|timeout{ms}` or `|⏱{ms}` - set operation timeout
1447    Timeout(Box<Expr>),
1448
1449    /// Retry: `|retry{count}` or `|retry{count, strategy}` - retry on failure
1450    Retry {
1451        count: Box<Expr>,
1452        strategy: Option<Box<Expr>>,
1453    },
1454
1455    // ==========================================
1456    // Evidence Promotion Operations
1457    // ==========================================
1458    /// Validate operation: `|validate!{predicate}` - promote evidence with validation
1459    /// Takes a predicate function that validates the data.
1460    /// If validation passes: ~ → ! (reported → known)
1461    /// If validation fails: returns an error
1462    /// Example: `data~|validate!{x => x.id > 0 && x.name.len > 0}`
1463    Validate {
1464        predicate: Box<Expr>,
1465        target_evidence: Evidentiality,
1466    },
1467
1468    /// Assume operation: `|assume!` or `|assume!("reason")` - explicit trust promotion
1469    /// Escape hatch that promotes evidence with an audit trail.
1470    /// Always logs the assumption for security review.
1471    /// Example: `external_data~|assume!("trusted legacy system")`
1472    Assume {
1473        reason: Option<Box<Expr>>,
1474        target_evidence: Evidentiality,
1475    },
1476
1477    /// Assert evidence: `|assert_evidence!{expected}` - verify evidence level at compile time
1478    /// Fails compilation if actual evidence doesn't match expected.
1479    /// Example: `data|assert_evidence!{!}` - assert data is known
1480    AssertEvidence(Evidentiality),
1481
1482    // ==========================================
1483    // Scope Functions (Kotlin-inspired)
1484    // ==========================================
1485    /// Also: `|also{f}` - execute side effect, return original value unchanged
1486    /// Like Kotlin's `also` - useful for logging/debugging in pipelines
1487    /// Example: `data|also{println}|process` - logs data, then processes it
1488    Also(Box<Expr>),
1489
1490    /// Apply: `|apply{block}` - mutate value in place, return modified value
1491    /// Like Kotlin's `apply` - useful for configuration/setup
1492    /// Example: `config|apply{.timeout = 5000; .retries = 3}`
1493    Apply(Box<Expr>),
1494
1495    /// TakeIf: `|take_if{predicate}` - return Some(value) if predicate true, None otherwise
1496    /// Like Kotlin's `takeIf` - useful for conditional pipelines
1497    /// Example: `user|take_if{.age >= 18}` - returns Option<User>
1498    TakeIf(Box<Expr>),
1499
1500    /// TakeUnless: `|take_unless{predicate}` - return Some(value) if predicate false
1501    /// Like Kotlin's `takeUnless` - inverse of take_if
1502    /// Example: `item|take_unless{.is_deleted}` - returns Option<Item>
1503    TakeUnless(Box<Expr>),
1504
1505    /// Let: `|let{f}` - transform value, like map but reads better for single values
1506    /// Like Kotlin's `let` - essentially an alias for transform
1507    /// Example: `name|let{.to_uppercase}` - transforms the name
1508    Let(Box<Expr>),
1509
1510    // ==========================================
1511    // Mathematical & APL-Inspired Operations
1512    // ==========================================
1513    /// All/ForAll: `|∀{p}` or `|all{p}` - check if ALL elements satisfy predicate
1514    /// Returns bool. Short-circuits on first false.
1515    /// Example: `numbers|∀{x => x > 0}` - are all positive?
1516    All(Box<Expr>),
1517
1518    /// Any/Exists: `|∃{p}` or `|any{p}` - check if ANY element satisfies predicate
1519    /// Returns bool. Short-circuits on first true.
1520    /// Example: `items|∃{.is_valid}` - is any valid?
1521    Any(Box<Expr>),
1522
1523    /// Compose: `|∘{f}` or `|compose{f}` - function composition
1524    /// Creates a new function that applies f after the current transformation.
1525    /// Example: `parse|∘{validate}|∘{save}` - compose three functions
1526    Compose(Box<Expr>),
1527
1528    /// Zip/Join: `|⋈{other}` or `|zip{other}` - combine with another collection
1529    /// Pairs elements from two collections into tuples.
1530    /// Example: `names|⋈{ages}` -> [(name1, age1), (name2, age2), ...]
1531    Zip(Box<Expr>),
1532
1533    /// Scan/Integral: `|∫{f}` or `|scan{f}` - cumulative fold (like Haskell's scanl)
1534    /// Returns all intermediate accumulator values.
1535    /// Example: `[1,2,3]|∫{+}` -> [1, 3, 6] (running sum)
1536    Scan(Box<Expr>),
1537
1538    /// Diff/Derivative: `|∂` or `|diff` - differences between adjacent elements
1539    /// Returns a collection of deltas.
1540    /// Example: `[1, 4, 6, 10]|∂` -> [3, 2, 4]
1541    Diff,
1542
1543    /// Gradient: `|∇{var}` or `|grad{var}` - automatic differentiation
1544    /// Computes gradient of expression with respect to variable.
1545    /// Example: `loss|∇{weights}` - gradient for backprop
1546    Gradient(Box<Expr>),
1547
1548    /// Sort Ascending: `|⍋` or `|sort_asc` - APL grade-up
1549    /// Sorts in ascending order (same as σ but more explicit)
1550    SortAsc,
1551
1552    /// Sort Descending: `|⍒` or `|sort_desc` - APL grade-down
1553    /// Sorts in descending order
1554    SortDesc,
1555
1556    /// Reverse: `|⌽` or `|rev` - APL rotate/reverse
1557    /// Reverses the collection
1558    Reverse,
1559
1560    /// Cycle: `|↻{n}` or `|cycle{n}` - repeat collection n times
1561    /// Example: `[1,2]|↻{3}` -> [1,2,1,2,1,2]
1562    Cycle(Box<Expr>),
1563
1564    /// Windows: `|⌺{n}` or `|windows{n}` - sliding window
1565    /// Example: `[1,2,3,4]|⌺{2}` -> [[1,2], [2,3], [3,4]]
1566    Windows(Box<Expr>),
1567
1568    /// Chunks: `|⊞{n}` or `|chunks{n}` - split into chunks
1569    /// Example: `[1,2,3,4]|⊞{2}` -> [[1,2], [3,4]]
1570    Chunks(Box<Expr>),
1571
1572    /// Flatten: `|⋳` or `|flatten` - flatten nested collection
1573    /// Example: `[[1,2], [3,4]]|⋳` -> [1,2,3,4]
1574    Flatten,
1575
1576    /// Unique: `|∪` or `|unique` - remove duplicates (set union with self)
1577    /// Example: `[1,2,2,3,3,3]|∪` -> [1,2,3]
1578    Unique,
1579
1580    /// Enumerate: `|⍳` or `|enumerate` - APL iota, pair with indices
1581    /// Example: `["a","b","c"]|⍳` -> [(0,"a"), (1,"b"), (2,"c")]
1582    Enumerate,
1583}
1584
1585/// Incorporation segment.
1586#[derive(Debug, Clone, PartialEq)]
1587pub struct IncorporationSegment {
1588    pub name: Ident,
1589    pub args: Option<Vec<Expr>>,
1590}
1591
1592/// Morpheme kinds.
1593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1594pub enum MorphemeKind {
1595    Transform, // τ
1596    Filter,    // φ
1597    Sort,      // σ
1598    Reduce,    // ρ
1599    Lambda,    // λ
1600    Sum,       // Σ
1601    Product,   // Π
1602    Middle,    // μ
1603    Choice,    // χ
1604    Nth,       // ν
1605    Next,      // ξ
1606    First,     // α
1607    Last,      // ω
1608}
1609
1610// ==========================================
1611// Protocol Types - Sigil-native networking
1612// ==========================================
1613
1614/// HTTP methods for http· incorporation.
1615#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1616pub enum HttpMethod {
1617    Get,
1618    Post,
1619    Put,
1620    Delete,
1621    Patch,
1622    Head,
1623    Options,
1624    Connect,
1625    Trace,
1626}
1627
1628impl std::fmt::Display for HttpMethod {
1629    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1630        match self {
1631            HttpMethod::Get => write!(f, "GET"),
1632            HttpMethod::Post => write!(f, "POST"),
1633            HttpMethod::Put => write!(f, "PUT"),
1634            HttpMethod::Delete => write!(f, "DELETE"),
1635            HttpMethod::Patch => write!(f, "PATCH"),
1636            HttpMethod::Head => write!(f, "HEAD"),
1637            HttpMethod::Options => write!(f, "OPTIONS"),
1638            HttpMethod::Connect => write!(f, "CONNECT"),
1639            HttpMethod::Trace => write!(f, "TRACE"),
1640        }
1641    }
1642}
1643
1644/// WebSocket message kinds for ws· incorporation.
1645#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1646pub enum WebSocketMessageKind {
1647    Text,
1648    Binary,
1649    Ping,
1650    Pong,
1651    Close,
1652}
1653
1654/// Kafka operation kinds for kafka· incorporation.
1655#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1656pub enum KafkaOpKind {
1657    Produce,
1658    Consume,
1659    Subscribe,
1660    Unsubscribe,
1661    Commit,
1662    Seek,
1663}
1664
1665/// GraphQL operation kinds for graphql· incorporation.
1666#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1667pub enum GraphQLOpKind {
1668    Query,
1669    Mutation,
1670    Subscription,
1671}
1672
1673/// Protocol kinds for stream expressions.
1674#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1675pub enum ProtocolKind {
1676    Http,
1677    Grpc,
1678    WebSocket,
1679    Kafka,
1680    Amqp,
1681    GraphQL,
1682}
1683
1684impl std::fmt::Display for ProtocolKind {
1685    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1686        match self {
1687            ProtocolKind::Http => write!(f, "http"),
1688            ProtocolKind::Grpc => write!(f, "grpc"),
1689            ProtocolKind::WebSocket => write!(f, "ws"),
1690            ProtocolKind::Kafka => write!(f, "kafka"),
1691            ProtocolKind::Amqp => write!(f, "amqp"),
1692            ProtocolKind::GraphQL => write!(f, "graphql"),
1693        }
1694    }
1695}
1696
1697/// Binary operators.
1698#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1699pub enum BinOp {
1700    Add,
1701    Sub,
1702    Mul,
1703    Div,
1704    Rem,
1705    Pow,
1706    And,
1707    Or,
1708    BitAnd,
1709    BitOr,
1710    BitXor,
1711    Shl,
1712    Shr,
1713    Eq,
1714    Ne,
1715    Lt,
1716    Le,
1717    Gt,
1718    Ge,
1719    Concat,
1720    /// Matrix multiplication (@)
1721    MatMul,
1722    /// Hadamard/element-wise product (⊙)
1723    Hadamard,
1724    /// Tensor/outer product (⊗)
1725    TensorProd,
1726}
1727
1728/// Unary operators.
1729#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1730pub enum UnaryOp {
1731    Neg,
1732    Not,
1733    Deref,
1734    Ref,
1735    RefMut,
1736}
1737
1738/// Literal values.
1739#[derive(Debug, Clone, PartialEq)]
1740pub enum Literal {
1741    Int {
1742        value: String,
1743        base: NumBase,
1744        suffix: Option<String>,
1745    },
1746    Float {
1747        value: String,
1748        suffix: Option<String>,
1749    },
1750    String(String),
1751    /// Multi-line string literal (""" ... """)
1752    MultiLineString(String),
1753    /// Raw string literal (no escape processing)
1754    RawString(String),
1755    /// Byte string literal (b"...")
1756    ByteString(Vec<u8>),
1757    /// Interpolated string literal (f"... {expr} ...")
1758    InterpolatedString {
1759        parts: Vec<InterpolationPart>,
1760    },
1761    /// SQL sigil string (σ"...")
1762    SigilStringSql(String),
1763    /// Route sigil string (ρ"...")
1764    SigilStringRoute(String),
1765    Char(char),
1766    /// Byte character literal (b'x')
1767    ByteChar(u8),
1768    Bool(bool),
1769    Null, // null
1770    /// Special mathematical constants
1771    Empty, // ∅
1772    Infinity, // ∞
1773    Circle, // ◯
1774}
1775
1776/// Part of an interpolated string
1777#[derive(Debug, Clone, PartialEq)]
1778pub enum InterpolationPart {
1779    /// Literal text segment
1780    Text(String),
1781    /// Expression to be evaluated and converted to string
1782    Expr(Box<Expr>),
1783}
1784
1785/// Number bases.
1786#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1787pub enum NumBase {
1788    Binary,       // 0b
1789    Octal,        // 0o
1790    Decimal,      // default
1791    Hex,          // 0x
1792    Vigesimal,    // 0v (base 20)
1793    Sexagesimal,  // 0s (base 60)
1794    Duodecimal,   // 0z (base 12)
1795    Explicit(u8), // N:₆₀ etc.
1796}
1797
1798#[derive(Debug, Clone, PartialEq)]
1799pub struct FieldInit {
1800    pub name: Ident,
1801    pub value: Option<Expr>,
1802}
1803
1804#[derive(Debug, Clone, PartialEq)]
1805pub struct MatchArm {
1806    pub pattern: Pattern,
1807    pub guard: Option<Expr>,
1808    pub body: Expr,
1809}
1810
1811#[derive(Debug, Clone, PartialEq)]
1812pub struct ClosureParam {
1813    pub pattern: Pattern,
1814    pub ty: Option<TypeExpr>,
1815}