1use 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    TooManyTupleFields {
66        max: usize,
67        got: usize,
68    },
69    ExpectedBooleanExpression,
70    NotAnIterator,
71    IntConversionError(ParseIntError),
72    FloatConversionError(ParseFloatError),
73    BoolConversionError,
74    DuplicateFieldInStructInstantiation(String),
75    UnknownIdentifier(String),
76    NoDefaultImplemented(TypeRef),
77    UnknownConstant,
78    NotValidLocationStartingPoint,
79    CallsCanNotBePartOfChain,
80    UnwrapCanNotBePartOfChain,
81    NoneCoalesceCanNotBePartOfChain,
82    OptionalChainingOperatorCanNotBePartOfChain,
83    SelfNotCorrectType,
84    CanNotNoneCoalesce,
85    UnknownSymbol,
86    UnknownEnumType,
87    UnknownModule,
88    BreakOutsideLoop,
89    ReturnOutsideCompare,
90    EmptyMatch,
91    MatchArmsMustHaveTypes,
92    ContinueOutsideLoop,
93    ParameterIsNotMutable,
94    CouldNotCoerceTo(TypeRef),
95    UnexpectedType,
96    CanNotAttachFunctionsToType,
97    MissingMemberFunction(String, TypeRef),
98    ExpectedLambda,
99    ExpectedSlice,
100    MissingToString(TypeRef),
101    IncompatibleTypesForAssignment {
102        expected: TypeRef,
103        found: TypeRef,
104    },
105    CapacityNotEnough {
106        size_requested: usize,
107        capacity: usize,
108    },
109    ExpectedInitializerTarget {
110        destination_type: TypeRef,
111    },
112    NoInferredTypeForEmptyInitializer,
113    TooManyInitializerListElementsForStorage {
114        capacity: usize,
115    },
116    KeyVariableNotAllowedToBeMutable,
117    SelfNotCorrectMutableState,
118    NotAllowedAsReturnType(TypeRef),
119    ParameterTypeCanNotBeStorage(TypeRef),
120    OperatorProblem,
121    MatchMustHaveAtLeastOneArm,
122    NeedStorage,
123    TooManyParameters {
124        encountered: usize,
125        allowed: usize,
126    },
127}
128
129impl fmt::Display for ErrorKind {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        let error_message = match self {
132            Self::NoAssociatedFunction(_, _) => "no associated function",
134            Self::UnknownMemberFunction(_) => "unknown member function",
135            Self::MissingMemberFunction(_, _) => "missing member function",
136            Self::WrongNumberOfArguments(_, _) => "wrong number of arguments",
137            Self::TooManyParameters { .. } => "too many parameters",
138            Self::CallsCanNotBePartOfChain => "calls cannot be part of a chain",
139            Self::ExpectedLambda => "expected a lambda",
140
141            Self::UnknownVariable => "unknown variable",
143            Self::UnknownIdentifier(_) => "unknown identifier",
144            Self::UnknownTypeReference => "unknown type",
145            Self::UnusedVariablesCanNotBeMut => "unused variable cannot be mutable",
146            Self::VariableTypeMustBeBlittable(_) => "variable type must be blittable",
147            Self::OverwriteVariableWithAnotherType => {
148                "cannot overwrite variable with a different type"
149            }
150            Self::IncompatibleTypes { .. } => "incompatible types",
151            Self::IncompatibleTypesForAssignment { .. } => "incompatible types for assignment",
152            Self::CouldNotCoerceTo(_) => "could not coerce to type",
153            Self::UnexpectedType => "unexpected type",
154            Self::SelfNotCorrectType => "'self' is not the correct type",
155            Self::SelfNotCorrectMutableState => "'self' has incorrect mutable state",
156            Self::NotAllowedAsReturnType(_) => "not an allowed return type",
157            Self::ParameterTypeCanNotBeStorage(_) => "parameter cannot be of storage type",
158
159            Self::ExpectedMutableLocation => "expected a mutable location",
161            Self::CanOnlyOverwriteVariableWithMut => "can only overwrite mutable variables",
162            Self::OverwriteVariableNotAllowedHere => "overwriting variables is not allowed here",
163            Self::VariableIsNotMutable => "variable is not mutable",
164            Self::ArgumentIsNotMutable => "argument is not mutable",
165            Self::ParameterIsNotMutable => "parameter is not mutable",
166            Self::KeyVariableNotAllowedToBeMutable => "key variable cannot be mutable",
167
168            Self::UnknownStructTypeReference => "unknown struct type",
170            Self::DuplicateFieldName => "duplicate field name",
171            Self::MissingFieldInStructInstantiation(_, _) => {
172                "missing field in struct instantiation"
173            }
174            Self::UnknownStructField => "unknown struct field",
175            Self::UnknownField => "unknown field",
176            Self::DuplicateFieldInStructInstantiation(_) => {
177                "duplicate field in struct instantiation"
178            }
179            Self::UnknownEnumVariantType => "unknown enum variant",
180            Self::UnknownEnumVariantTypeInPattern => "unknown enum variant in pattern",
181            Self::ExpectedEnumInPattern => "expected an enum in pattern",
182            Self::WrongEnumVariantContainer(_) => "wrong enum variant container",
183            Self::EnumVariantHasNoFields => "enum variant has no fields",
184            Self::UnknownEnumType => "unknown enum type",
185
186            Self::ExpectedOptional => "expected optional",
188            Self::NoneNeedsExpectedTypeHint => "none requires a type hint",
189            Self::UnwrapCanNotBePartOfChain => "unwrap cannot be part of a chain",
190            Self::NoneCoalesceCanNotBePartOfChain => "none coalesce cannot be part of a chain",
191            Self::OptionalChainingOperatorCanNotBePartOfChain => {
192                "optional chaining cannot be part of a chain"
193            }
194            Self::CanNotNoneCoalesce => "cannot none-coalesce",
195
196            Self::GuardCanNotHaveMultipleWildcards => "guard cannot have multiple wildcards",
198            Self::WildcardMustBeLastInGuard => "wildcard must be last in guard",
199            Self::GuardMustHaveWildcard => "guard must have a wildcard",
200            Self::GuardHasNoType => "guard has no type",
201            Self::TooManyDestructureVariables => "too many destructure variables",
202            Self::CanNotDestructure => "cannot destructure",
203            Self::ExpressionsNotAllowedInLetPattern => "expressions not allowed in let patterns",
204            Self::EmptyMatch => "match statement is empty",
205            Self::MatchArmsMustHaveTypes => "match arms must have types",
206            Self::MatchMustHaveAtLeastOneArm => "match must have at least one arm",
207
208            Self::MissingSubscriptMember => "missing subscript member",
210            Self::ArrayIndexMustBeInt(_) => "array index must be an integer",
211            Self::MapKeyTypeMismatch { .. } => "map key type mismatch",
212            Self::MapValueTypeMismatch { .. } => "map value type mismatch",
213            Self::TooManyTupleFields { .. } => "too many tuple fields",
214            Self::ExpectedSlice => "expected a slice",
215            Self::CapacityNotEnough { .. } => "capacity not enough",
216            Self::ExpectedInitializerTarget { .. } => "expected initializer target",
217            Self::NoInferredTypeForEmptyInitializer => "cannot infer type for empty initializer",
218            Self::TooManyInitializerListElementsForStorage { .. } => {
219                "too many elements for storage"
220            }
221
222            Self::BreakOutsideLoop => "break outside of a loop",
224            Self::ContinueOutsideLoop => "continue outside of a loop",
225            Self::ReturnOutsideCompare => "return outside of a compare",
226
227            Self::IntConversionError(_) => "integer conversion error",
229            Self::FloatConversionError(_) => "float conversion error",
230            Self::BoolConversionError => "boolean conversion error",
231            Self::ExpectedBooleanExpression => "expected a boolean expression",
232            Self::OperatorProblem => "operator problem",
233            Self::MissingToString(_) => "missing to_string implementation",
234
235            Self::SemanticError(e) => return write!(f, "{e:?}"),
237            Self::NotAnIterator => "not an iterator",
238            Self::NoDefaultImplemented(_) => "no default implementation",
239            Self::UnknownConstant => "unknown constant",
240            Self::NotValidLocationStartingPoint => "not a valid location starting point",
241            Self::UnknownSymbol => "unknown symbol",
242            Self::UnknownModule => "unknown module",
243            Self::CanNotAttachFunctionsToType => "cannot attach functions to this type",
244            Self::NeedStorage => "storage needed",
245        };
246        f.write_str(error_message)
247    }
248}
249
250impl From<SemanticError> for Error {
251    fn from(value: SemanticError) -> Self {
252        Self {
253            node: Node::default(),
254            kind: ErrorKind::SemanticError(value),
255        }
256    }
257}