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