swamp_semantic/
err.rs

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