Skip to main content

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