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 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}
130
131impl fmt::Display for ErrorKind {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 let error_message = match self {
134 Self::ExpectedTupleType => "expected tuple type",
135 Self::CanOnlyHaveFunctionCallAtStartOfPostfixChain => "function calls only allowed at start of chain",
136 Self::NoAssociatedFunction(_, _) => "no associated function",
138 Self::UnknownMemberFunction(_) => "unknown member function",
139 Self::MissingMemberFunction(_, _) => "missing member function",
140 Self::WrongNumberOfArguments(_, _) => "wrong number of arguments",
141 Self::TooManyParameters { .. } => "too many parameters",
142 Self::CallsCanNotBePartOfChain => "calls cannot be part of a chain",
143 Self::ExpectedLambda => "expected a lambda",
144
145 Self::UnknownVariable => "unknown variable",
147 Self::UnknownIdentifier(_) => "unknown identifier",
148 Self::UnknownTypeReference => "unknown type",
149 Self::UnusedVariablesCanNotBeMut => "unused variable cannot be mutable",
150 Self::VariableTypeMustBeBlittable(_) => "variable type must be blittable",
151 Self::OverwriteVariableWithAnotherType => {
152 "cannot overwrite variable with a different type"
153 }
154 Self::IncompatibleTypes { .. } => "incompatible types",
155 Self::IncompatibleTypesForAssignment { .. } => "incompatible types for assignment",
156 Self::CouldNotCoerceTo(_) => "could not coerce to type",
157 Self::UnexpectedType => "unexpected type",
158 Self::SelfNotCorrectType => "'self' is not the correct type",
159 Self::SelfNotCorrectMutableState => "'self' has incorrect mutable state",
160 Self::NotAllowedAsReturnType(_) => "not an allowed return type",
161 Self::ParameterTypeCanNotBeStorage(_) => "parameter cannot be of storage type",
162
163 Self::ExpectedMutableLocation => "expected a mutable location",
165 Self::CanOnlyOverwriteVariableWithMut => "can only overwrite mutable variables",
166 Self::OverwriteVariableNotAllowedHere => "overwriting variables is not allowed here",
167 Self::VariableIsNotMutable => "variable is not mutable",
168 Self::ArgumentIsNotMutable => "argument is not mutable",
169 Self::ParameterIsNotMutable => "parameter is not mutable",
170 Self::KeyVariableNotAllowedToBeMutable => "key variable cannot be mutable",
171
172 Self::UnknownStructTypeReference => "unknown struct type",
174 Self::DuplicateFieldName => "duplicate field name",
175 Self::MissingFieldInStructInstantiation(_, _) => {
176 "missing field in struct instantiation"
177 }
178 Self::UnknownStructField => "unknown struct field",
179 Self::UnknownField => "unknown field",
180 Self::DuplicateFieldInStructInstantiation(_) => {
181 "duplicate field in struct instantiation"
182 }
183 Self::UnknownEnumVariantType => "unknown enum variant",
184 Self::UnknownEnumVariantTypeInPattern => "unknown enum variant in pattern",
185 Self::ExpectedEnumInPattern => "expected an enum in pattern",
186 Self::WrongEnumVariantContainer(_) => "wrong enum variant container",
187 Self::EnumVariantHasNoFields => "enum variant has no fields",
188 Self::UnknownEnumType => "unknown enum type",
189
190 Self::ExpectedOptional => "expected optional",
192 Self::NoneNeedsExpectedTypeHint => "none requires a type hint",
193 Self::UnwrapCanNotBePartOfChain => "unwrap cannot be part of a chain",
194 Self::NoneCoalesceCanNotBePartOfChain => "none coalesce cannot be part of a chain",
195 Self::InvalidOperatorAfterOptionalChaining => {
196 "invalid operator after optional chaining (?)"
197 }
198 Self::CanNotNoneCoalesce => "cannot none-coalesce",
199
200 Self::GuardCanNotHaveMultipleWildcards => "guard cannot have multiple wildcards",
202 Self::WildcardMustBeLastInGuard => "wildcard must be last in guard",
203 Self::GuardMustHaveWildcard => "guard must have a wildcard",
204 Self::GuardHasNoType => "guard has no type",
205 Self::TooManyDestructureVariables => "too many destructure variables",
206 Self::CanNotDestructure => "cannot destructure",
207 Self::ExpressionsNotAllowedInLetPattern => "expressions not allowed in let patterns",
208 Self::EmptyMatch => "match statement is empty",
209 Self::MatchArmsMustHaveTypes => "match arms must have types",
210 Self::MatchMustHaveAtLeastOneArm => "match must have at least one arm",
211
212 Self::MissingSubscriptMember => "missing subscript member",
214 Self::ArrayIndexMustBeInt(_) => "array index must be an integer",
215 Self::MapKeyTypeMismatch { .. } => "map key type mismatch",
216 Self::MapValueTypeMismatch { .. } => "map value type mismatch",
217 Self::TooManyTupleFields { .. } => "too many tuple fields",
218 Self::ExpectedSlice => "expected a slice",
219 Self::CapacityNotEnough { .. } => "capacity not enough",
220 Self::ExpectedInitializerTarget { .. } => "expected initializer target",
221 Self::NoInferredTypeForEmptyInitializer => "cannot infer type for empty initializer",
222 Self::TooManyInitializerListElementsForStorage { .. } => {
223 "too many elements for storage"
224 }
225
226 Self::BreakOutsideLoop => "break outside of a loop",
228 Self::ContinueOutsideLoop => "continue outside of a loop",
229 Self::ReturnOutsideCompare => "return outside of a compare",
230
231 Self::IntConversionError(_) => "integer conversion error",
233 Self::FloatConversionError(_) => "float conversion error",
234 Self::BoolConversionError => "boolean conversion error",
235 Self::ExpectedBooleanExpression => "expected a boolean expression",
236 Self::OperatorProblem => "operator problem",
237 Self::MissingToString(_) => "missing to_string implementation",
238
239 Self::SemanticError(e) => return write!(f, "{e:?}"),
241 Self::NotAnIterator => "not an iterator",
242 Self::NoDefaultImplemented(_) => "no default implementation",
243 Self::UnknownConstant => "unknown constant",
244 Self::NotValidLocationStartingPoint => "not a valid location starting point",
245 Self::UnknownSymbol => "unknown symbol",
246 Self::UnknownModule => "unknown module",
247 Self::CanNotAttachFunctionsToType => "cannot attach functions to this type",
248 Self::NeedStorage => "storage needed",
249 };
250 f.write_str(error_message)
251 }
252}
253
254impl From<SemanticError> for Error {
255 fn from(value: SemanticError) -> Self {
256 Self {
257 node: Node::default(),
258 kind: ErrorKind::SemanticError(value),
259 }
260 }
261}