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