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