shape-ast 0.1.8

AST types and Pest grammar for the Shape programming language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Type system definitions for Shape AST

use super::DocComment;
use super::functions::Annotation;
use super::span::Span;
use super::type_path::TypePath;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TypeAnnotation {
    /// Basic types: number, string, bool, row, pattern, etc.
    Basic(String),
    /// Vector type: T[] or Vec<T>
    Array(Box<TypeAnnotation>),
    /// Tuple type: [T1, T2, T3]
    Tuple(Vec<TypeAnnotation>),
    /// Object type: { field1: T1, field2?: T2 }
    Object(Vec<ObjectTypeField>),
    /// Function type: (T1, T2) => T3
    Function {
        params: Vec<FunctionParam>,
        returns: Box<TypeAnnotation>,
    },
    /// Union type: T1 | T2 | T3 (discriminated union - value is ONE of the types)
    Union(Vec<TypeAnnotation>),
    /// Intersection type: T1 + T2 (structural merge - value has ALL fields from both types)
    /// Only valid for object/interface types. Field collisions are compile-time errors.
    Intersection(Vec<TypeAnnotation>),
    /// Generic type: Map<K, V>
    Generic {
        name: TypePath,
        args: Vec<TypeAnnotation>,
    },
    /// Type reference (custom type or type alias)
    Reference(TypePath),
    /// Void type
    Void,
    /// Never type
    Never,
    /// Null type
    Null,
    /// Undefined type
    Undefined,
    /// Trait object type: dyn Trait1 + Trait2
    /// Represents a type-erased value that implements the given traits
    Dyn(Vec<TypePath>),
}

impl TypeAnnotation {
    pub fn option(inner: TypeAnnotation) -> Self {
        TypeAnnotation::Generic {
            name: TypePath::simple("Option"),
            args: vec![inner],
        }
    }

    pub fn option_inner(&self) -> Option<&TypeAnnotation> {
        match self {
            TypeAnnotation::Generic { name, args }
                if name.as_str() == "Option" && args.len() == 1 =>
            {
                args.first()
            }
            _ => None,
        }
    }

    pub fn into_option_inner(self) -> Option<TypeAnnotation> {
        match self {
            TypeAnnotation::Generic { name, mut args }
                if name.as_str() == "Option" && args.len() == 1 =>
            {
                Some(args.remove(0))
            }
            _ => None,
        }
    }

    pub fn is_option(&self) -> bool {
        self.option_inner().is_some()
    }

    /// Extract a simple type name if this is a Reference or Basic type
    ///
    /// Returns `Some(type_name)` for:
    /// - `TypeAnnotation::Reference(path)` - e.g., `Currency`, `foo::MyType`
    /// - `TypeAnnotation::Basic(name)` - e.g., `number`, `string`
    ///
    /// Returns `None` for complex types like arrays, tuples, functions, etc.
    pub fn as_simple_name(&self) -> Option<&str> {
        match self {
            TypeAnnotation::Reference(path) => Some(path.as_str()),
            TypeAnnotation::Basic(name) => Some(name.as_str()),
            _ => None,
        }
    }

    /// Extract the type name string for Basic or Reference variants.
    /// Handles the `Basic(name) | Reference(path)` pattern uniformly.
    pub fn as_type_name_str(&self) -> Option<&str> {
        match self {
            TypeAnnotation::Basic(name) => Some(name.as_str()),
            TypeAnnotation::Reference(path) => Some(path.as_str()),
            _ => None,
        }
    }

    /// Convert a type annotation to its full string representation.
    pub fn to_type_string(&self) -> String {
        match self {
            TypeAnnotation::Basic(name) => name.clone(),
            TypeAnnotation::Reference(path) => path.to_string(),
            TypeAnnotation::Array(inner) => format!("Array<{}>", inner.to_type_string()),
            TypeAnnotation::Generic { name, args }
                if name.as_str() == "Option" && args.len() == 1 =>
            {
                format!("{}?", args[0].to_type_string())
            }
            TypeAnnotation::Generic { name, args } => {
                let args_str: Vec<String> = args.iter().map(|a| a.to_type_string()).collect();
                format!("{}<{}>", name, args_str.join(", "))
            }
            TypeAnnotation::Tuple(items) => {
                let items_str: Vec<String> = items.iter().map(|t| t.to_type_string()).collect();
                format!("[{}]", items_str.join(", "))
            }
            TypeAnnotation::Union(items) => {
                let items_str: Vec<String> = items.iter().map(|t| t.to_type_string()).collect();
                items_str.join(" | ")
            }
            TypeAnnotation::Void => "void".to_string(),
            TypeAnnotation::Never => "never".to_string(),
            TypeAnnotation::Null => "null".to_string(),
            TypeAnnotation::Undefined => "undefined".to_string(),
            TypeAnnotation::Object(fields) => {
                let fields_str: Vec<String> = fields
                    .iter()
                    .map(|f| {
                        let opt = if f.optional { "?" } else { "" };
                        // Include @alias in the type string so the Python extension
                        // can use the wire name when looking up dict keys.
                        let alias = f
                            .annotations
                            .iter()
                            .find(|a| a.name == "alias")
                            .and_then(|a| a.args.first())
                            .and_then(|arg| match arg {
                                super::expressions::Expr::Literal(
                                    super::literals::Literal::String(s),
                                    _,
                                ) => Some(s.as_str()),
                                _ => None,
                            });
                        let alias_str = alias.map(|a| format!("@\"{}\" ", a)).unwrap_or_default();
                        format!(
                            "{}{}{}: {}",
                            alias_str,
                            f.name,
                            opt,
                            f.type_annotation.to_type_string()
                        )
                    })
                    .collect();
                format!("{{{}}}", fields_str.join(", "))
            }
            _ => "any".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ObjectTypeField {
    pub name: String,
    pub optional: bool,
    pub type_annotation: TypeAnnotation,
    /// Field annotations (e.g. `@alias("wire name")`)
    #[serde(default)]
    pub annotations: Vec<Annotation>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FunctionParam {
    pub name: Option<String>,
    pub optional: bool,
    pub type_annotation: TypeAnnotation,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeParam {
    pub name: String,
    #[serde(default)]
    pub span: Span,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    /// Default type argument: `T = int`
    pub default_type: Option<TypeAnnotation>,
    /// Trait bounds: `T: Comparable + Displayable`
    #[serde(default)]
    pub trait_bounds: Vec<TypePath>,
}

/// A predicate in a where clause: `T: Comparable + Display`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct WherePredicate {
    pub type_name: String,
    pub bounds: Vec<TypePath>,
}

impl PartialEq for TypeParam {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.doc_comment == other.doc_comment
            && self.default_type == other.default_type
            && self.trait_bounds == other.trait_bounds
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeAliasDef {
    pub name: String,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    pub type_params: Option<Vec<TypeParam>>,
    pub type_annotation: TypeAnnotation,
    /// Meta parameter overrides: type Percent4 = Percent { decimals: 4 }
    pub meta_param_overrides: Option<std::collections::HashMap<String, super::expressions::Expr>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InterfaceDef {
    pub name: String,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    pub type_params: Option<Vec<TypeParam>>,
    pub members: Vec<InterfaceMember>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum InterfaceMember {
    /// Property signature
    Property {
        name: String,
        optional: bool,
        type_annotation: TypeAnnotation,
        #[serde(default)]
        span: Span,
        #[serde(default)]
        doc_comment: Option<DocComment>,
    },
    /// Method signature
    Method {
        name: String,
        optional: bool,
        params: Vec<FunctionParam>,
        return_type: TypeAnnotation,
        /// Whether this is an async method
        is_async: bool,
        #[serde(default)]
        span: Span,
        #[serde(default)]
        doc_comment: Option<DocComment>,
    },
    /// Index signature
    IndexSignature {
        param_name: String,
        param_type: String, // "string" or "number"
        return_type: TypeAnnotation,
        #[serde(default)]
        span: Span,
        #[serde(default)]
        doc_comment: Option<DocComment>,
    },
}

impl InterfaceMember {
    pub fn span(&self) -> Span {
        match self {
            InterfaceMember::Property { span, .. }
            | InterfaceMember::Method { span, .. }
            | InterfaceMember::IndexSignature { span, .. } => *span,
        }
    }

    pub fn doc_comment(&self) -> Option<&DocComment> {
        match self {
            InterfaceMember::Property { doc_comment, .. }
            | InterfaceMember::Method { doc_comment, .. }
            | InterfaceMember::IndexSignature { doc_comment, .. } => doc_comment.as_ref(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnumDef {
    pub name: String,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    pub type_params: Option<Vec<TypeParam>>,
    pub members: Vec<EnumMember>,
    /// Annotations applied to the enum (e.g., `@with_label() enum Color { ... }`)
    #[serde(default)]
    pub annotations: Vec<super::Annotation>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnumMember {
    pub name: String,
    pub kind: EnumMemberKind,
    #[serde(default)]
    pub span: Span,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EnumMemberKind {
    /// Unit variant: Variant or Variant = 1
    Unit { value: Option<EnumValue> },
    /// Tuple variant: Variant(Type, Type)
    Tuple(Vec<TypeAnnotation>),
    /// Struct variant: Variant { field: Type, ... }
    Struct(Vec<ObjectTypeField>),
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EnumValue {
    String(String),
    Number(f64),
}

/// A member of a trait definition: either required (signature only) or default (with body)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TraitMember {
    /// Required method — implementors must provide this
    Required(InterfaceMember),
    /// Default method — used if implementor does not override
    Default(MethodDef),
    /// Associated type declaration: `type Item;` or `type Item: Comparable;`
    AssociatedType {
        name: String,
        bounds: Vec<TypeAnnotation>,
        #[serde(default)]
        span: Span,
        #[serde(default)]
        doc_comment: Option<DocComment>,
    },
}

impl TraitMember {
    pub fn span(&self) -> Span {
        match self {
            TraitMember::Required(member) => member.span(),
            TraitMember::Default(method) => method.span,
            TraitMember::AssociatedType { span, .. } => *span,
        }
    }

    pub fn doc_comment(&self) -> Option<&DocComment> {
        match self {
            TraitMember::Required(member) => member.doc_comment(),
            TraitMember::Default(method) => method.doc_comment.as_ref(),
            TraitMember::AssociatedType { doc_comment, .. } => doc_comment.as_ref(),
        }
    }
}

/// A concrete binding for an associated type inside an `impl` block:
/// `type Item = number;`
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssociatedTypeBinding {
    pub name: String,
    pub concrete_type: TypeAnnotation,
}

/// Trait definition — like interface but with `trait` keyword, supporting default methods
///
/// ```shape
/// trait Queryable<T> {
///     filter(predicate: (T) => bool): Self    // required
///     method execute() -> Result<Table<T>> {   // default
///         return Ok(self.filter(|_| true))
///     }
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraitDef {
    pub name: String,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    pub type_params: Option<Vec<TypeParam>>,
    /// Supertrait bounds: `trait Foo: Bar + Baz { ... }`
    #[serde(default)]
    pub super_traits: Vec<TypeAnnotation>,
    pub members: Vec<TraitMember>,
    /// Annotations applied to the trait (e.g., `@documented("...") trait Foo { ... }`)
    #[serde(default)]
    pub annotations: Vec<super::Annotation>,
}

/// Impl block — implements a trait for a type
///
/// ```shape
/// impl Queryable<T> for Table<T> {
///     method filter(predicate) { /* ... */ }
///     method execute() { Ok(self) }
/// }
/// ```
///
/// Under the hood, compiles identically to an extend block (UFCS desugaring)
/// plus trait validation (all required methods present with correct arities).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImplBlock {
    /// The trait being implemented (e.g., Queryable<T>)
    pub trait_name: TypeName,
    /// The type implementing the trait (e.g., Table<T>)
    pub target_type: TypeName,
    /// Optional named implementation selector:
    /// `impl Display for User as JsonDisplay { ... }`
    pub impl_name: Option<String>,
    /// Method implementations
    pub methods: Vec<MethodDef>,
    /// Associated type bindings: `type Item = number;`
    pub associated_type_bindings: Vec<AssociatedTypeBinding>,
    /// Where clause: `where T: Display + Comparable`
    pub where_clause: Option<Vec<WherePredicate>>,
}

/// Type extension for adding methods to existing types
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtendStatement {
    /// The type being extended (e.g., "Vec")
    pub type_name: TypeName,
    /// Methods being added to the type
    pub methods: Vec<MethodDef>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MethodDef {
    /// Method name
    pub name: String,
    #[serde(default)]
    pub span: Span,
    /// Declaring module path for compiler/runtime provenance checks.
    ///
    /// This is injected by the module loader for loaded modules and is not part
    /// of user-authored source syntax.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub declaring_module_path: Option<String>,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    /// Annotations applied to this method (e.g., `@traced`)
    #[serde(default)]
    pub annotations: Vec<super::functions::Annotation>,
    /// Type parameters for generic methods (e.g., `method map<U>(...)`)
    #[serde(default)]
    pub type_params: Option<Vec<TypeParam>>,
    /// Method parameters
    pub params: Vec<super::functions::FunctionParameter>,
    /// Optional when clause for conditional method definitions
    pub when_clause: Option<Box<super::expressions::Expr>>,
    /// Optional return type annotation
    pub return_type: Option<TypeAnnotation>,
    /// Method body
    pub body: Vec<super::statements::Statement>,
    /// Whether this is an async method
    pub is_async: bool,
}

impl PartialEq for MethodDef {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
            && self.doc_comment == other.doc_comment
            && self.annotations == other.annotations
            && self.type_params == other.type_params
            && self.params == other.params
            && self.when_clause == other.when_clause
            && self.return_type == other.return_type
            && self.body == other.body
            && self.is_async == other.is_async
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TypeName {
    /// Simple type name (e.g., "Vec", "Table", "foo::Bar")
    Simple(TypePath),
    /// Generic type name (e.g., "Table<Row>")
    Generic {
        name: TypePath,
        type_args: Vec<TypeAnnotation>,
    },
}

// ============================================================================
// Struct Type Definitions
// ============================================================================

/// Struct type definition — pure data with named fields
///
/// ```shape
/// type Point { x: number, y: number }
/// type DataVec<V, K = Timestamp> { index: Vec<K>, data: Vec<V> }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StructTypeDef {
    pub name: String,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    pub type_params: Option<Vec<TypeParam>>,
    pub fields: Vec<StructField>,
    /// Inline method definitions inside the type body
    #[serde(default)]
    pub methods: Vec<MethodDef>,
    /// Annotations applied to the struct (e.g., `@derive_debug type Foo { ... }`)
    pub annotations: Vec<Annotation>,
    /// Optional native layout metadata for `type C`.
    #[serde(default)]
    pub native_layout: Option<NativeLayoutBinding>,
}

/// Native layout binding metadata for `type C` declarations.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NativeLayoutBinding {
    /// ABI name (currently `"C"`).
    pub abi: String,
}

/// A field in a struct type definition
///
/// Comptime fields are type-level constants baked at compile time.
/// They occupy zero runtime slots (no ValueSlot in TypedObject).
/// Access resolves to a constant push at compile time.
///
/// ```shape
/// type Currency {
///     comptime symbol: string = "$",
///     comptime decimals: number = 2,
///     amount: number,
/// }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StructField {
    pub annotations: Vec<Annotation>,
    pub is_comptime: bool,
    pub name: String,
    #[serde(default)]
    pub span: Span,
    #[serde(default)]
    pub doc_comment: Option<DocComment>,
    pub type_annotation: TypeAnnotation,
    pub default_value: Option<super::expressions::Expr>,
}

impl PartialEq for StructField {
    fn eq(&self, other: &Self) -> bool {
        self.annotations == other.annotations
            && self.is_comptime == other.is_comptime
            && self.name == other.name
            && self.doc_comment == other.doc_comment
            && self.type_annotation == other.type_annotation
            && self.default_value == other.default_value
    }
}