vexil-lang 0.5.0

Compiler library for the Vexil schema definition language — lexer, parser, IR, and type checker
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
//! # Stability: Tier 1
//!
//! Intermediate representation for compiled Vexil schemas.
//!
//! The IR is produced by the lowering pass and refined by the type checker.
//! All type references are resolved to [`TypeId`] handles into a [`TypeRegistry`],
//! and wire sizes are computed for fixed-layout types.

pub mod types;

pub use types::{
    CustomAnnotation, CustomAnnotationArg, CustomAnnotationValue, DeprecatedInfo, Encoding,
    FieldEncoding, ResolvedAnnotations, ResolvedType, TombstoneDef, TypeId, TypeRegistry, WireSize,
    POISON_TYPE_ID,
};

use crate::ast::{DefaultValue, EnumBacking};
use crate::span::Span;
use smol_str::SmolStr;
use std::collections::HashMap;

/// Constraint expression for field validation.
#[derive(Debug, Clone, PartialEq)]
pub enum FieldConstraint {
    /// Binary logical AND
    And(Box<FieldConstraint>, Box<FieldConstraint>),
    /// Binary logical OR
    Or(Box<FieldConstraint>, Box<FieldConstraint>),
    /// Logical NOT
    Not(Box<FieldConstraint>),
    /// Comparison: value op operand
    Cmp {
        op: CmpOp,
        operand: ConstraintOperand,
    },
    /// Range check: value in [low, high) or [low, high]
    Range {
        low: ConstraintOperand,
        high: ConstraintOperand,
        exclusive_high: bool,
    },
    /// Length comparison: len(value) op operand
    LenCmp {
        op: CmpOp,
        operand: ConstraintOperand,
    },
    /// Length range: len(value) in range
    LenRange {
        low: ConstraintOperand,
        high: ConstraintOperand,
        exclusive_high: bool,
    },
}

/// Comparison operators in IR constraint expressions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CmpOp {
    /// `==` — equality.
    Eq,
    /// `!=` — inequality.
    Ne,
    /// `<` — less than.
    Lt,
    /// `>` — greater than.
    Gt,
    /// `<=` — less than or equal.
    Le,
    /// `>=` — greater than or equal.
    Ge,
}

/// Operands in constraint expressions.
#[derive(Debug, Clone, PartialEq)]
pub enum ConstraintOperand {
    Int(i64),
    Float(f64),
    String(String),
    Bool(bool),
    ConstRef(SmolStr),
}

/// A single-file compilation result.
///
/// Contains the type registry, the list of types declared in this file,
/// and the schema-level namespace and annotations. Imported types live in
/// the registry but are **not** listed in `declarations`.
#[derive(Debug, Clone)]
pub struct CompiledSchema {
    /// Namespace segments, e.g. `["net", "example", "types"]`.
    pub namespace: Vec<SmolStr>,
    /// Schema-level annotations (version, doc, etc.).
    pub annotations: ResolvedAnnotations,
    /// All type definitions reachable from this schema (declared + imported).
    pub registry: TypeRegistry,
    /// Type IDs of declarations **defined** in this file (excludes imports).
    pub declarations: Vec<TypeId>,
    /// Evaluated constant values (const name -> value).
    pub constants: HashMap<SmolStr, ConstValue>,
}

// Compile-time assertion: CompiledSchema must be Send + Sync for
// potential future parallel compilation and cross-thread sharing.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<CompiledSchema>();
};

impl CompiledSchema {
    /// Iterates implementation declarations defined in this schema.
    ///
    /// Impls are registry-only records: they have no exportable name and do
    /// not participate in `declarations` or canonical schema ordering.
    pub fn impls(&self) -> impl Iterator<Item = (TypeId, &ImplDef)> {
        self.registry.iter().filter_map(|(id, def)| match def {
            TypeDef::Impl(impl_def) => Some((id, impl_def)),
            _ => None,
        })
    }

    /// Returns all type names declared in this schema (not imports).
    pub fn type_names(&self) -> Vec<&str> {
        self.declarations
            .iter()
            .filter_map(|&id| self.registry.get(id))
            .map(|def| match def {
                TypeDef::Message(m) => m.name.as_str(),
                TypeDef::Enum(e) => e.name.as_str(),
                TypeDef::Flags(f) => f.name.as_str(),
                TypeDef::Union(u) => u.name.as_str(),
                TypeDef::Newtype(n) => n.name.as_str(),
                TypeDef::Config(c) => c.name.as_str(),
                TypeDef::GenericAlias(g) => g.name.as_str(),
                TypeDef::Trait(t) => t.name.as_str(),
                TypeDef::Impl(_) => "", // Impls don't have a simple name
            })
            .filter(|s| !s.is_empty())
            .collect()
    }

    /// Look up a type by name. Returns the TypeId and TypeDef if found.
    pub fn find_type(&self, name: &str) -> Option<(TypeId, &TypeDef)> {
        for &id in &self.declarations {
            if let Some(def) = self.registry.get(id) {
                let def_name = match def {
                    TypeDef::Message(m) => m.name.as_str(),
                    TypeDef::Enum(e) => e.name.as_str(),
                    TypeDef::Flags(f) => f.name.as_str(),
                    TypeDef::Union(u) => u.name.as_str(),
                    TypeDef::Newtype(n) => n.name.as_str(),
                    TypeDef::Config(c) => c.name.as_str(),
                    TypeDef::GenericAlias(g) => g.name.as_str(),
                    TypeDef::Trait(t) => t.name.as_str(),
                    TypeDef::Impl(_) => continue, // Skip impls in name lookup
                };
                if def_name == name {
                    return Some((id, def));
                }
            }
        }
        None
    }

    /// Returns the fully-qualified namespace as a dot-separated string.
    pub fn namespace_str(&self) -> String {
        self.namespace
            .iter()
            .map(|s| s.as_str())
            .collect::<Vec<_>>()
            .join(".")
    }

    /// Returns the BLAKE3 schema hash as a hex string.
    pub fn hash_hex(&self) -> String {
        let hash = crate::canonical::schema_hash(self);
        hash.iter().map(|b| format!("{b:02x}")).collect()
    }
}

/// A compiled constant value.
#[derive(Debug, Clone, PartialEq)]
pub struct ConstValue {
    /// The constant's resolved type.
    pub ty: ResolvedType,
    /// The evaluated value (stored as i64 for all integral types).
    pub value: i64,
    /// Source span for error reporting.
    pub span: Span,
}

/// A type definition in the Vexil IR.
///
/// Each variant corresponds to one of the declaration forms in the
/// Vexil language. Marked `#[non_exhaustive]` to allow future expansion.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum TypeDef {
    /// A message with ordered, typed fields.
    Message(MessageDef),
    /// A closed or open enumeration.
    Enum(EnumDef),
    /// A bitmask / flag set.
    Flags(FlagsDef),
    /// A tagged union (sum type).
    Union(UnionDef),
    /// A newtype wrapper around another type.
    Newtype(NewtypeDef),
    /// A compile-time configuration record (not encoded on the wire).
    Config(ConfigDef),
    /// A generic type alias with type parameters.
    /// Stores the alias definition with type parameters and target type expression.
    GenericAlias(GenericAliasDef),
    /// A trait definition (compile-time contract, no wire encoding).
    Trait(TraitDef),
    /// An implementation of a trait for a type (compile-time only).
    Impl(ImplDef),
}

/// A message type definition with ordered, typed fields.
#[derive(Debug, Clone)]
pub struct MessageDef {
    pub name: SmolStr,
    pub span: Span,
    pub fields: Vec<FieldDef>,
    pub tombstones: Vec<TombstoneDef>,
    pub annotations: ResolvedAnnotations,
    pub wire_size: Option<WireSize>,
}

/// A single field within a message or union variant.
#[derive(Debug, Clone)]
pub struct FieldDef {
    pub name: SmolStr,
    pub span: Span,
    pub ordinal: u32,
    pub resolved_type: ResolvedType,
    pub encoding: FieldEncoding,
    pub annotations: ResolvedAnnotations,
    pub constraint: Option<FieldConstraint>,
}

#[derive(Debug, Clone)]
pub struct EnumDef {
    pub name: SmolStr,
    pub span: Span,
    /// Explicit backing type specified by the user (`: u8`, `: u16`, etc.).
    /// `None` means no explicit backing — `wire_bits` is auto-computed by typeck.
    pub backing: Option<EnumBacking>,
    pub variants: Vec<EnumVariantDef>,
    pub tombstones: Vec<TombstoneDef>,
    pub annotations: ResolvedAnnotations,
    /// Computed by typeck: number of bits used on the wire.
    /// For explicit backing this equals the backing type width;
    /// for auto-sized enums this is the minimal bit width for the variant count.
    pub wire_bits: u8,
}

/// A single variant within an enum type.
#[derive(Debug, Clone)]
pub struct EnumVariantDef {
    pub name: SmolStr,
    pub span: Span,
    pub ordinal: u32,
    pub annotations: ResolvedAnnotations,
}

#[derive(Debug, Clone)]
pub struct FlagsDef {
    pub name: SmolStr,
    pub span: Span,
    pub bits: Vec<FlagsBitDef>,
    pub tombstones: Vec<TombstoneDef>,
    pub annotations: ResolvedAnnotations,
    /// Computed by typeck: number of bytes used on the wire (1, 2, 4, or 8).
    pub wire_bytes: u8,
}

/// A single bit definition within a flags type.
#[derive(Debug, Clone)]
pub struct FlagsBitDef {
    pub name: SmolStr,
    pub span: Span,
    pub bit: u32,
    pub annotations: ResolvedAnnotations,
}

/// A tagged union (sum type) definition.
#[derive(Debug, Clone)]
pub struct UnionDef {
    pub name: SmolStr,
    pub span: Span,
    pub variants: Vec<UnionVariantDef>,
    pub tombstones: Vec<TombstoneDef>,
    pub annotations: ResolvedAnnotations,
    pub wire_size: Option<WireSize>,
}

/// A single variant within a union type.
#[derive(Debug, Clone)]
pub struct UnionVariantDef {
    pub name: SmolStr,
    pub span: Span,
    pub ordinal: u32,
    pub fields: Vec<FieldDef>,
    pub tombstones: Vec<TombstoneDef>,
    pub annotations: ResolvedAnnotations,
}

/// A newtype wrapper around another type.
#[derive(Debug, Clone)]
pub struct NewtypeDef {
    pub name: SmolStr,
    pub span: Span,
    pub inner_type: ResolvedType,
    pub terminal_type: ResolvedType,
    pub annotations: ResolvedAnnotations,
}

/// A compile-time configuration record (not wire-encoded).
#[derive(Debug, Clone)]
pub struct ConfigDef {
    pub name: SmolStr,
    pub span: Span,
    pub fields: Vec<ConfigFieldDef>,
    pub annotations: ResolvedAnnotations,
}

/// A single field within a config record.
#[derive(Debug, Clone)]
pub struct ConfigFieldDef {
    pub name: SmolStr,
    pub span: Span,
    pub resolved_type: ResolvedType,
    pub default_value: DefaultValue,
    pub annotations: ResolvedAnnotations,
}

/// A generic type alias definition.
///
/// Generic aliases are stored with their type parameters and target type.
/// When a generic alias is used with type arguments (e.g., `Vec3<fixed64>`),
/// the type arguments are substituted into the target type to produce the
/// final resolved type.
#[derive(Debug, Clone)]
pub struct GenericAliasDef {
    pub name: SmolStr,
    pub span: Span,
    /// Type parameter names (e.g., `["T"]` for `type Vec3<T> = ...`).
    pub type_params: Vec<SmolStr>,
    /// The target type expression with unresolved type parameters.
    /// Type arguments are substituted into this to produce the resolved type.
    pub target_type: crate::ast::TypeExpr,
    pub annotations: ResolvedAnnotations,
}

/// A trait definition defining required fields and functions.
#[derive(Debug, Clone)]
pub struct TraitDef {
    pub name: SmolStr,
    pub type_params: Vec<crate::ast::TypeParam>,
    pub fields: Vec<TraitFieldDef>,
    pub functions: Vec<TraitFnDef>,
    pub annotations: ResolvedAnnotations,
    pub span: Span,
}

/// Required field in a trait.
#[derive(Debug, Clone)]
pub struct TraitFieldDef {
    pub name: SmolStr,
    pub ty: ResolvedType,
    pub unresolved_ty: crate::ast::TypeExpr,
    pub ordinal: u32,
    pub annotations: ResolvedAnnotations,
}

/// Function signature in a trait.
#[derive(Debug, Clone)]
pub struct TraitFnDef {
    pub name: SmolStr,
    pub params: Vec<FnParamDef>,
    pub return_type: Option<ResolvedType>,
}

/// Function parameter definition.
#[derive(Debug, Clone)]
pub struct FnParamDef {
    pub name: SmolStr,
    pub ty: ResolvedType,
    /// Original AST type expression, preserved for generic trait substitution
    /// and target signature projection.
    pub unresolved_ty: crate::ast::TypeExpr,
}

/// An implementation of a trait for a specific type.
#[derive(Debug, Clone)]
pub struct ImplDef {
    pub trait_name: SmolStr,
    pub target_type: ResolvedType,
    pub type_args: Vec<ResolvedType>, // Concrete types for trait generics
    pub functions: Vec<ImplFnDef>,
    pub annotations: ResolvedAnnotations,
    pub span: Span,
}

/// Function implementation in an impl block.
#[derive(Debug, Clone)]
pub struct ImplFnDef {
    pub name: SmolStr,
    pub params: Vec<FnParamDef>,
    pub return_type: Option<ResolvedType>,
    pub body: FnBody,
}

/// Binary operators in IR expressions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Eq,
    Ne,
    Lt,
    Le,
    Gt,
    Ge,
}

/// Unary operators in IR expressions.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnaryOp {
    Neg,
    Not,
}

/// IR expression.
#[derive(Debug, Clone)]
pub enum Expr {
    Int(i64),
    UInt(u64),
    Float(f64),
    Bool(bool),
    String(String),
    /// Local variable or parameter reference.
    Local(SmolStr),
    /// Field access on self or another expression.
    FieldAccess(Box<Expr>, SmolStr),
    /// Function call (resolved to specific function).
    Call(SmolStr, Vec<Expr>),
    /// Trait method call - will be resolved to specific impl.
    TraitMethodCall {
        trait_name: SmolStr,
        method_name: SmolStr,
        receiver: Box<Expr>,
        args: Vec<Expr>,
    },
    Binary(BinOp, Box<Expr>, Box<Expr>),
    Unary(UnaryOp, Box<Expr>),
    /// Self reference.
    SelfRef,
}

/// IR statement.
#[derive(Debug, Clone)]
pub enum Statement {
    Expr(Expr),
    Let {
        name: SmolStr,
        ty: Option<ResolvedType>,
        value: Expr,
    },
    Return(Option<Expr>),
    Assign {
        target: Expr,
        value: Expr,
    },
}

/// Function body.
#[derive(Debug, Clone)]
pub enum FnBody {
    /// Implemented via FFI or native code (no Vexil source body).
    External,
    /// Block body with statements.
    Block(Vec<Statement>),
}