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