swamp_semantic/
err.rs

1/*
2 * Copyright (c) Peter Bjorklund. All rights reserved. https://github.com/swamp/semantic
3 * Licensed under the MIT License. See LICENSE in the project root for license information.
4 */
5use crate::SemanticError;
6use source_map_node::Node;
7use std::fmt;
8use std::num::{ParseFloatError, ParseIntError};
9use swamp_types::prelude::*;
10
11#[derive(Clone, Debug)]
12pub struct Error {
13    pub node: Node,
14    pub kind: ErrorKind,
15}
16#[derive(Clone, Debug)]
17pub enum ErrorKind {
18    NoAssociatedFunction(TypeRef, String),
19    MissingSubscriptMember,
20    UnusedVariablesCanNotBeMut,
21    VariableTypeMustBeAtLeastTransient(TypeRef),
22    GuardCanNotHaveMultipleWildcards,
23    WildcardMustBeLastInGuard,
24    GuardMustHaveWildcard,
25    GuardHasNoType,
26    TooManyDestructureVariables,
27    CanNotDestructure,
28    UnknownStructTypeReference,
29    DuplicateFieldName,
30    MissingFieldInStructInstantiation(Vec<String>, AnonymousStructType),
31    UnknownVariable,
32    ArrayIndexMustBeInt(TypeRef),
33    OverwriteVariableWithAnotherType,
34    NoneNeedsExpectedTypeHint,
35    ExpectedMutableLocation,
36    WrongNumberOfArguments(usize, usize),
37    CanOnlyOverwriteVariableWithMut,
38    OverwriteVariableNotAllowedHere,
39    UnknownEnumVariantType,
40    UnknownStructField,
41    UnknownEnumVariantTypeInPattern,
42    ExpectedEnumInPattern,
43    WrongEnumVariantContainer(EnumVariantType),
44    VariableIsNotMutable,
45    ArgumentIsNotMutable,
46    UnknownTypeReference,
47    SemanticError(SemanticError),
48    ExpectedOptional,
49    MapKeyTypeMismatch {
50        expected: TypeRef,
51        found: TypeRef,
52    },
53    MapValueTypeMismatch {
54        expected: TypeRef,
55        found: TypeRef,
56    },
57    IncompatibleTypes {
58        expected: TypeRef,
59        found: TypeRef,
60    },
61    UnknownMemberFunction(TypeRef),
62    ExpressionsNotAllowedInLetPattern,
63    UnknownField,
64    EnumVariantHasNoFields,
65    ExpectedTupleType,
66    TooManyTupleFields {
67        max: usize,
68        got: usize,
69    },
70    ExpectedBooleanExpression,
71    NotAnIterator,
72    IntConversionError(ParseIntError),
73    ByteConversionError(String),
74    FloatConversionError(ParseFloatError),
75    BoolConversionError,
76    DuplicateFieldInStructInstantiation(String),
77    UnknownIdentifier(String),
78    NoDefaultImplemented(TypeRef),
79    UnknownConstant,
80    NotValidLocationStartingPoint,
81    CallsCanNotBePartOfChain,
82    UnwrapCanNotBePartOfChain,
83    NoneCoalesceCanNotBePartOfChain,
84    InvalidOperatorAfterOptionalChaining,
85    SelfNotCorrectType,
86    CanNotNoneCoalesce,
87    UnknownSymbol,
88    UnknownEnumType,
89    UnknownModule,
90    BreakOutsideLoop,
91    ReturnOutsideCompare,
92    EmptyMatch,
93    MatchArmsMustHaveTypes,
94    ContinueOutsideLoop,
95    ParameterIsNotMutable,
96    CouldNotCoerceTo(TypeRef),
97    UnexpectedType,
98    CanNotAttachFunctionsToType,
99    MissingMemberFunction(String, TypeRef),
100    ExpectedLambda,
101    ExpectedSlice,
102    MissingToString(TypeRef),
103    IncompatibleTypesForAssignment {
104        expected: TypeRef,
105        found: TypeRef,
106    },
107    CapacityNotEnough {
108        size_requested: usize,
109        capacity: usize,
110    },
111    ExpectedInitializerTarget {
112        destination_type: TypeRef,
113    },
114    NoInferredTypeForEmptyInitializer,
115    TooManyInitializerListElementsForStorage {
116        capacity: usize,
117    },
118    KeyVariableNotAllowedToBeMutable,
119    SelfNotCorrectMutableState,
120    NotAllowedAsReturnType(TypeRef),
121    ParameterTypeCanNotBeStorage(TypeRef),
122    OperatorProblem,
123    MatchMustHaveAtLeastOneArm,
124    NeedStorage,
125    TooManyParameters {
126        encountered: usize,
127        allowed: usize,
128    },
129    CanOnlyHaveFunctionCallAtStartOfPostfixChain,
130    CanNotSubscriptWithThatType,
131    EnumTypeWasntExpectedHere,
132    CanNotInferEnumType,
133    CanNotHaveSeparateMemberFuncRef,
134    OutOfVirtualRegisters,
135    CanNotCreateTemporaryStorage,
136    CloseToMaxVirtualRegister,
137    CanNotBeBorrowed,
138    FunctionReferenceMustBeCall,
139}
140
141impl fmt::Display for ErrorKind {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        let error_message = match self {
144            Self::FunctionReferenceMustBeCall => "function reference must be call",
145            Self::CanNotBeBorrowed => "can not be borrowed",
146            Self::CloseToMaxVirtualRegister => "close to max virtual register",
147            Self::CanNotCreateTemporaryStorage => "can not create temporary storage",
148            Self::OutOfVirtualRegisters => "out of virtual registers",
149            Self::CanNotHaveSeparateMemberFuncRef => "can not have separate member func reference",
150            Self::EnumTypeWasntExpectedHere => "enum type was not expected here",
151            Self::CanNotInferEnumType => "can not infer enum type",
152            Self::ExpectedTupleType => "expected tuple type",
153            Self::CanOnlyHaveFunctionCallAtStartOfPostfixChain => {
154                "function calls only allowed at start of chain"
155            }
156            Self::CanNotSubscriptWithThatType => "subscript not possible with that type",
157            // Function and Method Errors
158            Self::NoAssociatedFunction(_, _) => "no associated function",
159            Self::UnknownMemberFunction(_) => "unknown member function",
160            Self::MissingMemberFunction(_, _) => "missing member function",
161            Self::WrongNumberOfArguments(_, _) => "wrong number of arguments",
162            Self::TooManyParameters { .. } => "too many parameters",
163            Self::CallsCanNotBePartOfChain => "calls cannot be part of a chain",
164            Self::ExpectedLambda => "expected a lambda",
165
166            // Variable and Type Errors
167            Self::UnknownVariable => "unknown variable",
168            Self::UnknownIdentifier(_) => "unknown identifier",
169            Self::UnknownTypeReference => "unknown type",
170            Self::UnusedVariablesCanNotBeMut => "unused variable cannot be mutable",
171            Self::VariableTypeMustBeAtLeastTransient(_) => {
172                "variable type must be at least ephemeral"
173            }
174            Self::OverwriteVariableWithAnotherType => {
175                "cannot overwrite variable with a different type"
176            }
177            Self::IncompatibleTypes { .. } => "incompatible types",
178            Self::IncompatibleTypesForAssignment { .. } => "incompatible types for assignment",
179            Self::CouldNotCoerceTo(_) => "could not coerce to type",
180            Self::UnexpectedType => "unexpected type",
181            Self::SelfNotCorrectType => "'self' is not the correct type",
182            Self::SelfNotCorrectMutableState => "'self' has incorrect mutable state",
183            Self::NotAllowedAsReturnType(_) => "not an allowed return type",
184            Self::ParameterTypeCanNotBeStorage(_) => "parameter cannot be of storage type",
185
186            // Mutability Errors
187            Self::ExpectedMutableLocation => "expected a mutable location",
188            Self::CanOnlyOverwriteVariableWithMut => "can only overwrite mutable variables",
189            Self::OverwriteVariableNotAllowedHere => "overwriting variables is not allowed here",
190            Self::VariableIsNotMutable => "variable is not mutable",
191            Self::ArgumentIsNotMutable => "argument is not mutable",
192            Self::ParameterIsNotMutable => "parameter is not mutable",
193            Self::KeyVariableNotAllowedToBeMutable => "key variable cannot be mutable",
194
195            // Struct and Enum Errors
196            Self::UnknownStructTypeReference => "unknown struct type",
197            Self::DuplicateFieldName => "duplicate field name",
198            Self::MissingFieldInStructInstantiation(_, _) => {
199                "missing field in struct instantiation"
200            }
201            Self::UnknownStructField => "unknown struct field",
202            Self::UnknownField => "unknown field",
203            Self::DuplicateFieldInStructInstantiation(_) => {
204                "duplicate field in struct instantiation"
205            }
206            Self::UnknownEnumVariantType => "unknown enum variant",
207            Self::UnknownEnumVariantTypeInPattern => "unknown enum variant in pattern",
208            Self::ExpectedEnumInPattern => "expected an enum in pattern",
209            Self::WrongEnumVariantContainer(_) => "wrong enum variant container",
210            Self::EnumVariantHasNoFields => "enum variant has no fields",
211            Self::UnknownEnumType => "unknown enum type",
212
213            // Optional and Chaining Errors
214            Self::ExpectedOptional => "expected optional",
215            Self::NoneNeedsExpectedTypeHint => "none requires a type hint",
216            Self::UnwrapCanNotBePartOfChain => "unwrap cannot be part of a chain",
217            Self::NoneCoalesceCanNotBePartOfChain => "none coalesce cannot be part of a chain",
218            Self::InvalidOperatorAfterOptionalChaining => {
219                "invalid operator after optional chaining (?)"
220            }
221            Self::CanNotNoneCoalesce => "cannot none-coalesce",
222
223            // Pattern Matching and Destructuring Errors
224            Self::GuardCanNotHaveMultipleWildcards => "guard cannot have multiple wildcards",
225            Self::WildcardMustBeLastInGuard => "wildcard must be last in guard",
226            Self::GuardMustHaveWildcard => "guard must have a wildcard",
227            Self::GuardHasNoType => "guard has no type",
228            Self::TooManyDestructureVariables => "too many destructure variables",
229            Self::CanNotDestructure => "cannot destructure",
230            Self::ExpressionsNotAllowedInLetPattern => "expressions not allowed in let patterns",
231            Self::EmptyMatch => "match statement is empty",
232            Self::MatchArmsMustHaveTypes => "match arms must have types",
233            Self::MatchMustHaveAtLeastOneArm => "match must have at least one arm",
234
235            // Collection and Data Structure Errors
236            Self::MissingSubscriptMember => "missing subscript member",
237            Self::ArrayIndexMustBeInt(_) => "array index must be an integer",
238            Self::MapKeyTypeMismatch { .. } => "map key type mismatch",
239            Self::MapValueTypeMismatch { .. } => "map value type mismatch",
240            Self::TooManyTupleFields { .. } => "too many tuple fields",
241            Self::ExpectedSlice => "expected a slice",
242            Self::CapacityNotEnough { .. } => "capacity not enough",
243            Self::ExpectedInitializerTarget { .. } => "expected initializer target",
244            Self::NoInferredTypeForEmptyInitializer => "cannot infer type for empty initializer",
245            Self::TooManyInitializerListElementsForStorage { .. } => {
246                "too many elements for storage"
247            }
248
249            // Control Flow Errors
250            Self::BreakOutsideLoop => "break outside of a loop",
251            Self::ContinueOutsideLoop => "continue outside of a loop",
252            Self::ReturnOutsideCompare => "return outside of a compare",
253
254            // Conversion and Operator Errors
255            Self::IntConversionError(_) => "integer conversion error",
256            Self::FloatConversionError(_) => "float conversion error",
257            Self::BoolConversionError => "boolean conversion error",
258            Self::ExpectedBooleanExpression => "expected a boolean expression",
259            Self::OperatorProblem => "operator problem",
260            Self::MissingToString(_) => "missing to_string implementation",
261
262            // Miscellaneous Errors
263            Self::SemanticError(e) => return write!(f, "{e:?}"),
264            Self::NotAnIterator => "not an iterator",
265            Self::NoDefaultImplemented(_) => "no default implementation",
266            Self::UnknownConstant => "unknown constant",
267            Self::NotValidLocationStartingPoint => "not a valid location starting point",
268            Self::UnknownSymbol => "unknown symbol",
269            Self::UnknownModule => "unknown module",
270            Self::CanNotAttachFunctionsToType => "cannot attach functions to this type",
271            Self::NeedStorage => "storage needed",
272            Self::ByteConversionError(_) => "byte conversion error",
273        };
274        f.write_str(error_message)
275    }
276}
277
278impl ErrorKind {
279    #[must_use]
280    pub const fn code(&self) -> usize {
281        match self {
282            Self::NoAssociatedFunction(_, _) => 1,
283            Self::MissingSubscriptMember => 2,
284            Self::UnusedVariablesCanNotBeMut => 3,
285            Self::VariableTypeMustBeAtLeastTransient(_) => 4,
286            Self::GuardCanNotHaveMultipleWildcards => 5,
287            Self::WildcardMustBeLastInGuard => 6,
288            Self::GuardMustHaveWildcard => 7,
289            Self::GuardHasNoType => 8,
290            Self::TooManyDestructureVariables => 9,
291            Self::CanNotDestructure => 10,
292            Self::UnknownStructTypeReference => 11,
293            Self::DuplicateFieldName => 12,
294            Self::MissingFieldInStructInstantiation(_, _) => 13,
295            Self::UnknownVariable => 14,
296            Self::ArrayIndexMustBeInt(_) => 15,
297            Self::OverwriteVariableWithAnotherType => 16,
298            Self::NoneNeedsExpectedTypeHint => 17,
299            Self::ExpectedMutableLocation => 18,
300            Self::WrongNumberOfArguments(_, _) => 19,
301            Self::CanOnlyOverwriteVariableWithMut => 20,
302            Self::OverwriteVariableNotAllowedHere => 21,
303            Self::UnknownEnumVariantType => 22,
304            Self::UnknownStructField => 23,
305            Self::UnknownEnumVariantTypeInPattern => 24,
306            Self::ExpectedEnumInPattern => 25,
307            Self::WrongEnumVariantContainer(_) => 26,
308            Self::VariableIsNotMutable => 27,
309            Self::ArgumentIsNotMutable => 28,
310            Self::UnknownTypeReference => 29,
311            Self::SemanticError(_) => 30,
312            Self::ExpectedOptional => 31,
313            Self::MapKeyTypeMismatch { .. } => 32,
314            Self::MapValueTypeMismatch { .. } => 33,
315            Self::IncompatibleTypes { .. } => 34,
316            Self::UnknownMemberFunction(_) => 35,
317            Self::ExpressionsNotAllowedInLetPattern => 36,
318            Self::UnknownField => 37,
319            Self::EnumVariantHasNoFields => 38,
320            Self::ExpectedTupleType => 39,
321            Self::TooManyTupleFields { .. } => 40,
322            Self::ExpectedBooleanExpression => 41,
323            Self::NotAnIterator => 42,
324            Self::IntConversionError(_) => 43,
325            Self::FloatConversionError(_) => 44,
326            Self::BoolConversionError => 45,
327            Self::DuplicateFieldInStructInstantiation(_) => 46,
328            Self::UnknownIdentifier(_) => 47,
329            Self::NoDefaultImplemented(_) => 48,
330            Self::UnknownConstant => 49,
331            Self::NotValidLocationStartingPoint => 50,
332            Self::CallsCanNotBePartOfChain => 51,
333            Self::UnwrapCanNotBePartOfChain => 52,
334            Self::NoneCoalesceCanNotBePartOfChain => 53,
335            Self::InvalidOperatorAfterOptionalChaining => 54,
336            Self::SelfNotCorrectType => 55,
337            Self::CanNotNoneCoalesce => 56,
338            Self::UnknownSymbol => 57,
339            Self::UnknownEnumType => 58,
340            Self::UnknownModule => 59,
341            Self::BreakOutsideLoop => 60,
342            Self::ReturnOutsideCompare => 61,
343            Self::EmptyMatch => 62,
344            Self::MatchArmsMustHaveTypes => 63,
345            Self::ContinueOutsideLoop => 64,
346            Self::ParameterIsNotMutable => 65,
347            Self::CouldNotCoerceTo(_) => 66,
348            Self::UnexpectedType => 67,
349            Self::CanNotAttachFunctionsToType => 68,
350            Self::MissingMemberFunction(_, _) => 69,
351            Self::ExpectedLambda => 70,
352            Self::ExpectedSlice => 71,
353            Self::MissingToString(_) => 72,
354            Self::IncompatibleTypesForAssignment { .. } => 73,
355            Self::CapacityNotEnough { .. } => 74,
356            Self::ExpectedInitializerTarget { .. } => 75,
357            Self::NoInferredTypeForEmptyInitializer => 76,
358            Self::TooManyInitializerListElementsForStorage { .. } => 77,
359            Self::KeyVariableNotAllowedToBeMutable => 78,
360            Self::SelfNotCorrectMutableState => 79,
361            Self::NotAllowedAsReturnType(_) => 80,
362            Self::ParameterTypeCanNotBeStorage(_) => 81,
363            Self::OperatorProblem => 82,
364            Self::MatchMustHaveAtLeastOneArm => 83,
365            Self::NeedStorage => 84,
366            Self::TooManyParameters { .. } => 85,
367            Self::CanOnlyHaveFunctionCallAtStartOfPostfixChain => 86,
368            Self::CanNotSubscriptWithThatType => 87,
369            Self::EnumTypeWasntExpectedHere => 88,
370            Self::CanNotInferEnumType => 89,
371            Self::CanNotHaveSeparateMemberFuncRef => 90,
372            Self::ByteConversionError(_) => 91,
373            Self::OutOfVirtualRegisters => 92,
374            Self::CanNotCreateTemporaryStorage => 93,
375            Self::CloseToMaxVirtualRegister => 94,
376            Self::CanNotBeBorrowed => 95,
377            Self::FunctionReferenceMustBeCall => 96,
378        }
379    }
380}
381
382impl From<SemanticError> for Error {
383    fn from(value: SemanticError) -> Self {
384        Self {
385            node: Node::default(),
386            kind: ErrorKind::SemanticError(value),
387        }
388    }
389}