formalang 0.0.5-beta

FormaLang compiler frontend: lexer, parser, semantic analyzer, and IR lowering.
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
use crate::ast::PrimitiveType;
use crate::location::Span;
use thiserror::Error;

/// Compiler error types
#[expect(
    clippy::exhaustive_enums,
    reason = "matched exhaustively by consumer code"
)]
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum CompilerError {
    // Lexical errors
    #[error("Invalid character: {character}")]
    InvalidCharacter { character: char, span: Span },

    #[error("Unterminated string literal")]
    UnterminatedString { span: Span },

    #[error("Unterminated block comment")]
    UnterminatedBlockComment { span: Span },

    #[error("Invalid unicode escape '\\u{value}'")]
    InvalidUnicodeEscape { value: String, span: Span },

    #[error("Invalid number format: {value}")]
    InvalidNumber { value: String, span: Span },

    // Syntax errors
    #[error("Expected {expected}, found {found}")]
    UnexpectedToken {
        expected: String,
        found: String,
        span: Span,
    },

    #[error("Unexpected end of file")]
    UnexpectedEof { span: Span },

    // Semantic errors
    #[error("Undefined reference: {name}")]
    UndefinedReference { name: String, span: Span },

    #[error("Type mismatch: expected {expected}, found {found}")]
    TypeMismatch {
        expected: String,
        found: String,
        span: Span,
    },

    #[error("Duplicate definition: {name}")]
    DuplicateDefinition { name: String, span: Span },

    // Module resolution errors
    #[error("Module not found: '{name}'")]
    ModuleNotFound { name: String, span: Span },

    #[error("Failed to read module '{path}': {error}")]
    ModuleReadError {
        path: String,
        error: String,
        span: Span,
    },

    #[error("Circular import detected: {cycle}")]
    CircularImport { cycle: String, span: Span },

    #[error("Cannot import private item '{name}'")]
    PrivateImport { name: String, span: Span },

    #[error("Item '{item}' not found in module '{module}'. Available items: {available}")]
    ImportItemNotFound {
        item: String,
        module: String,
        available: String,
        span: Span,
    },

    // Parser errors
    #[error("Parse error: {message}")]
    ParseError { message: String, span: Span },

    // Type resolution errors
    #[error("Undefined type: '{name}'")]
    UndefinedType { name: String, span: Span },

    #[error("Cannot redefine primitive type '{name}'")]
    PrimitiveRedefinition { name: String, span: Span },

    /// A trait name appeared in a type position that produces a value
    /// (parameter, return, let annotation, struct/enum field, closure
    /// param/return). `FormaLang` has no dynamic dispatch — trait values
    /// must be passed via a generic-bounded parameter
    /// (`fn foo<T: SomeTrait>(x: T)`) so the concrete type is known
    /// after monomorphisation.
    #[error(
        "trait '{trait_name}' cannot be used as a value type — use a generic bound \
         like `<T: {trait_name}>` instead"
    )]
    TraitUsedAsValueType { trait_name: String, span: Span },

    // Trait validation errors
    #[error("Undefined trait: '{name}'")]
    UndefinedTrait { name: String, span: Span },

    #[error("'{name}' is a {actual_kind}, not a trait (cannot be used in trait composition)")]
    NotATrait {
        name: String,
        actual_kind: String,
        span: Span,
    },

    #[error("Missing required field '{field}' from trait '{trait_name}'")]
    MissingTraitField {
        field: String,
        trait_name: String,
        span: Span,
    },

    #[error("Field '{field}' has type {actual} but trait '{trait_name}' requires {expected}")]
    TraitFieldTypeMismatch {
        field: String,
        trait_name: String,
        expected: String,
        actual: String,
        span: Span,
    },

    // Circular dependency errors
    #[error("Circular dependency detected: {cycle}")]
    CircularDependency { cycle: String, span: Span },

    // Expression validation errors
    #[error("Binary operator {op} cannot be applied to {left_type} and {right_type}")]
    InvalidBinaryOp {
        op: String,
        left_type: String,
        right_type: String,
        span: Span,
    },

    #[error("For loop requires an array, found {actual}")]
    ForLoopNotArray { actual: String, span: Span },

    #[error("Array destructuring requires an array, found {actual}")]
    ArrayDestructuringNotArray { actual: String, span: Span },

    #[error("Struct destructuring requires a struct, found {actual}")]
    StructDestructuringNotStruct { actual: String, span: Span },

    #[error("If condition must be boolean or optional, found {actual}")]
    InvalidIfCondition { actual: String, span: Span },

    #[error("Match scrutinee must be an enum, found {actual}")]
    MatchNotEnum { actual: String, span: Span },

    #[error("Match is not exhaustive, missing variant(s): {missing}")]
    NonExhaustiveMatch { missing: String, span: Span },

    #[error("Duplicate match arm for variant '{variant}'")]
    DuplicateMatchArm { variant: String, span: Span },

    #[error("Unknown enum variant '{variant}' for enum '{enum_name}'")]
    UnknownEnumVariant {
        variant: String,
        enum_name: String,
        span: Span,
    },

    #[error("Variant '{variant}' has {expected} associated values, found {actual}")]
    VariantArityMismatch {
        variant: String,
        expected: usize,
        actual: usize,
        span: Span,
    },

    #[error("Missing field '{field}' for {type_name}")]
    MissingField {
        field: String,
        type_name: String,
        span: Span,
    },

    #[error("Unknown field '{field}' for {type_name}")]
    UnknownField {
        field: String,
        type_name: String,
        span: Span,
    },

    #[error("Cannot assign to immutable binding")]
    AssignmentToImmutable { span: Span },

    #[error(
        "Struct '{struct_name}' requires named arguments (field: value), but argument {position} is positional"
    )]
    PositionalArgInStruct {
        struct_name: String,
        position: usize,
        span: Span,
    },

    #[error("Enum variant '{variant}' has no data, cannot instantiate with parentheses")]
    EnumVariantWithoutData {
        variant: String,
        enum_name: String,
        span: Span,
    },

    #[error(
        "Enum variant '{variant}' requires data, use {enum_name}.{variant}(field: value, ...)"
    )]
    EnumVariantRequiresData {
        variant: String,
        enum_name: String,
        span: Span,
    },

    // Mutability errors
    #[error("Parameter '{param}' requires a mutable value, but received an immutable value")]
    MutabilityMismatch { param: String, span: Span },

    #[error("Cannot use '{name}' after it was moved into a sink parameter")]
    UseAfterSink { name: String, span: Span },

    // Generic type errors
    #[error("Type '{name}' expected {expected} generic argument(s), found {actual}")]
    GenericArityMismatch {
        name: String,
        expected: usize,
        actual: usize,
        span: Span,
    },

    #[error("Type argument '{arg}' does not satisfy constraint '{constraint}'")]
    GenericConstraintViolation {
        arg: String,
        constraint: String,
        span: Span,
    },

    #[error("Type parameter '{param}' is out of scope")]
    OutOfScopeTypeParameter { param: String, span: Span },

    #[error("Generic type '{name}' requires type arguments")]
    MissingGenericArguments { name: String, span: Span },

    #[error("Duplicate generic parameter '{param}'")]
    DuplicateGenericParam { param: String, span: Span },

    // Extern validation errors
    /// An `extern fn` declaration includes a body, which is not allowed.
    #[error("Extern function '{function}' must not have a body")]
    ExternFnWithBody { function: String, span: Span },

    /// A non-extern function is missing its body expression.
    #[error("Non-extern function '{function}' must have a body")]
    RegularFnWithoutBody { function: String, span: Span },

    /// An `extern impl` block contains at least one function with a body.
    #[error("Extern impl block for '{name}' must not contain function bodies")]
    ExternImplWithBody { name: String, span: Span },

    /// A parameter without a default value appears after one with a
    /// default value. Default values must be positional from the
    /// right (no required parameter may follow a defaulted one,
    /// excluding `self`).
    #[error(
        "Parameter '{param}' on '{function}' has no default value but follows a parameter that does — defaults must be positional from the right"
    )]
    RequiredParamAfterDefault {
        function: String,
        param: String,
        span: Span,
    },

    /// nil literal assigned to a non-optional type.
    #[error("Cannot assign nil to non-optional type '{expected}'")]
    NilAssignedToNonOptional { expected: String, span: Span },

    /// Optional type used where a non-optional is required.
    #[error("Cannot use optional type '{actual}' where non-optional '{expected}' is required")]
    OptionalUsedAsNonOptional {
        actual: String,
        expected: String,
        span: Span,
    },

    /// A trait implementation is missing a method required by the trait.
    #[error("Missing method '{method}' required by trait '{trait_name}'")]
    MissingTraitMethod {
        method: String,
        trait_name: String,
        span: Span,
    },

    /// A method's signature in an impl block does not match the trait's declaration.
    #[error(
        "Method '{method}' signature does not match trait '{trait_name}': expected {expected}, found {actual}"
    )]
    TraitMethodSignatureMismatch {
        method: String,
        trait_name: String,
        expected: String,
        actual: String,
        span: Span,
    },

    // Function overload errors
    /// More than one overload of a function matches the call arguments.
    #[error("Ambiguous call to '{function}': multiple overloads match")]
    AmbiguousCall { function: String, span: Span },

    /// No overload of a function matches the call arguments.
    #[error("No matching overload for '{function}' with the given arguments")]
    NoMatchingOverload { function: String, span: Span },

    // Enum type inference errors
    #[error("Cannot infer enum type for variant '.{variant}' from context")]
    CannotInferEnumType { variant: String, span: Span },

    // Function validation errors
    #[error("Function '{function}' has return type {expected} but body has type {actual}")]
    FunctionReturnTypeMismatch {
        function: String,
        expected: String,
        actual: String,
        span: Span,
    },

    /// Expression nesting exceeded the compiler recursion limit.
    #[error("Expression nesting exceeded the compiler recursion limit")]
    ExpressionDepthExceeded { span: Span },

    /// Module contains more definitions than the ID space allows (> `u32::MAX`).
    #[error("Module contains too many {kind} definitions")]
    TooManyDefinitions { kind: &'static str, span: Span },

    /// Attempted to access a private item from outside its defining module.
    #[error("'{name}' is private and cannot be accessed from outside its module")]
    VisibilityViolation { name: String, span: Span },

    /// A closure returned from a function captures a binding that does not
    /// outlive the function. Only `sink` parameters and outer-scope bindings
    /// may be captured by an escaping closure.
    #[error("Returned closure captures '{binding}' which does not outlive the function")]
    ClosureCaptureEscapesLocalBinding { binding: String, span: Span },

    /// A compiler invariant was violated during lowering or analysis. This is
    /// always a bug in the compiler itself — the `detail` field documents
    /// which invariant failed so it can be reported and fixed.
    #[error("Internal compiler error: {detail}")]
    InternalError { detail: String, span: Span },

    /// An integer literal does not fit in its declared (or default) target
    /// primitive — e.g. `2147483648I32` exceeds `i32::MAX`, or an unsuffixed
    /// `9_999_999_999` exceeds the `I32` default.
    #[error("Integer literal {written} does not fit in {target:?}")]
    NumericOverflow {
        written: String,
        target: PrimitiveType,
        span: Span,
    },

    /// A `pub` struct or `pub` enum variant declares a field whose type is
    /// a closure. Closures are an internal abstraction; they cannot be part
    /// of a publicly exposed type because they have no stable representation
    /// across the module / backend boundary.
    #[error("'{owner}' is public and cannot have closure-typed field '{field}'")]
    PublicClosureField {
        /// Human-readable identity of the offending item, e.g.
        /// `"struct Form"` or `"enum Event variant submitted"`.
        owner: String,
        /// Name of the closure-typed field.
        field: String,
        span: Span,
    },
}

impl CompilerError {
    #[must_use]
    pub const fn span(&self) -> Span {
        match self {
            Self::InvalidCharacter { span, .. }
            | Self::UnterminatedString { span }
            | Self::UnterminatedBlockComment { span }
            | Self::InvalidUnicodeEscape { span, .. }
            | Self::InvalidNumber { span, .. }
            | Self::UnexpectedToken { span, .. }
            | Self::UnexpectedEof { span }
            | Self::UndefinedReference { span, .. }
            | Self::TypeMismatch { span, .. }
            | Self::DuplicateDefinition { span, .. }
            | Self::ModuleNotFound { span, .. }
            | Self::ModuleReadError { span, .. }
            | Self::CircularImport { span, .. }
            | Self::PrivateImport { span, .. }
            | Self::ImportItemNotFound { span, .. }
            | Self::ParseError { span, .. }
            | Self::UndefinedType { span, .. }
            | Self::PrimitiveRedefinition { span, .. }
            | Self::TraitUsedAsValueType { span, .. }
            | Self::UndefinedTrait { span, .. }
            | Self::NotATrait { span, .. }
            | Self::MissingTraitField { span, .. }
            | Self::TraitFieldTypeMismatch { span, .. }
            | Self::CircularDependency { span, .. }
            | Self::InvalidBinaryOp { span, .. }
            | Self::ForLoopNotArray { span, .. }
            | Self::ArrayDestructuringNotArray { span, .. }
            | Self::StructDestructuringNotStruct { span, .. }
            | Self::InvalidIfCondition { span, .. }
            | Self::MatchNotEnum { span, .. }
            | Self::NonExhaustiveMatch { span, .. }
            | Self::DuplicateMatchArm { span, .. }
            | Self::UnknownEnumVariant { span, .. }
            | Self::VariantArityMismatch { span, .. }
            | Self::MissingField { span, .. }
            | Self::UnknownField { span, .. }
            | Self::PositionalArgInStruct { span, .. }
            | Self::EnumVariantWithoutData { span, .. }
            | Self::EnumVariantRequiresData { span, .. }
            | Self::MutabilityMismatch { span, .. }
            | Self::GenericArityMismatch { span, .. }
            | Self::GenericConstraintViolation { span, .. }
            | Self::OutOfScopeTypeParameter { span, .. }
            | Self::MissingGenericArguments { span, .. }
            | Self::DuplicateGenericParam { span, .. }
            | Self::ExternFnWithBody { span, .. }
            | Self::RegularFnWithoutBody { span, .. }
            | Self::ExternImplWithBody { span, .. }
            | Self::RequiredParamAfterDefault { span, .. }
            | Self::NilAssignedToNonOptional { span, .. }
            | Self::OptionalUsedAsNonOptional { span, .. }
            | Self::MissingTraitMethod { span, .. }
            | Self::TraitMethodSignatureMismatch { span, .. }
            | Self::AmbiguousCall { span, .. }
            | Self::NoMatchingOverload { span, .. }
            | Self::CannotInferEnumType { span, .. }
            | Self::FunctionReturnTypeMismatch { span, .. }
            | Self::AssignmentToImmutable { span, .. }
            | Self::UseAfterSink { span, .. }
            | Self::ExpressionDepthExceeded { span }
            | Self::TooManyDefinitions { span, .. }
            | Self::VisibilityViolation { span, .. }
            | Self::ClosureCaptureEscapesLocalBinding { span, .. }
            | Self::InternalError { span, .. }
            | Self::NumericOverflow { span, .. }
            | Self::PublicClosureField { span, .. } => *span,
        }
    }
}

/// Result type for compiler operations
pub type CompilerResult<T> = Result<T, Vec<CompilerError>>;