1use crate::LisetteDiagnostic;
2use syntax::ast::{Annotation, BinaryOperator, Span};
3use syntax::types::{SimpleKind, Type};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum MismatchedTailKind {
7 Result,
8 Option,
9 Partial,
10 Value,
11}
12
13impl MismatchedTailKind {
14 pub fn allow_alias(&self) -> &'static str {
15 match self {
16 Self::Result => "unused_result",
17 Self::Option => "unused_option",
18 Self::Partial => "unused_partial",
19 Self::Value => "unused_value",
20 }
21 }
22}
23
24pub fn mismatched_tail_value(
25 actual_span: &Span,
26 actual_ty: &str,
27 expected_span: &Span,
28 expected_ty: &str,
29) -> LisetteDiagnostic {
30 LisetteDiagnostic::error("Mismatch between return type and return value")
31 .with_infer_code("mismatched_return_value")
32 .with_span_primary_label(actual_span, format!("returns `{}`", actual_ty))
33 .with_span_label(
34 expected_span,
35 format!("has `{}` as implicit return type", expected_ty),
36 )
37 .with_help(format!(
38 "If the `{}` return type is intended, discard the return value with `let _ = ...`. If the `{}` return value is intended, add `-> {}` to the function signature.",
39 expected_ty, actual_ty, actual_ty
40 ))
41}
42
43pub fn blank_import_non_go(blank_span: Span) -> LisetteDiagnostic {
44 LisetteDiagnostic::error("Invalid import")
45 .with_resolve_code("blank_import_non_go")
46 .with_span_label(&blank_span, "only allowed for Go modules")
47 .with_help(
48 "Remove the underscore. Blank imports are allowed only for Go imports, \
49 because Lisette modules have no `init()` side effects.",
50 )
51}
52
53pub fn import_conflict(
54 alias: &str,
55 path1: &str,
56 path2: &str,
57 name_span: Span,
58) -> LisetteDiagnostic {
59 LisetteDiagnostic::error("Import conflict")
60 .with_resolve_code("import_conflict")
61 .with_span_label(
62 &name_span,
63 format!("conflicts with prior import `{}`", alias),
64 )
65 .with_help(format!(
66 "`{}` and `{}` resolve to the same name. Add an alias to at least one of them: \
67 `import my_{} \"{}\"`",
68 path1, path2, alias, path2
69 ))
70}
71
72pub fn reserved_import_alias(alias: &str, alias_span: Span) -> LisetteDiagnostic {
73 LisetteDiagnostic::error("Reserved import alias")
74 .with_resolve_code("reserved_import_alias")
75 .with_span_label(&alias_span, "reserved name")
76 .with_help(format!(
77 "`{}` is a reserved name and cannot be used as an import alias. \
78 Choose a different alias, e.g. `import my_{} \"...\"`",
79 alias, alias
80 ))
81}
82
83pub fn duplicate_import_path(path: &str, name_span: Span) -> LisetteDiagnostic {
84 LisetteDiagnostic::error("Duplicate import")
85 .with_resolve_code("duplicate_import")
86 .with_span_label(&name_span, "already imported above")
87 .with_help(format!(
88 "Module `{}` is already imported. Remove the duplicate import.",
89 path
90 ))
91}
92
93pub fn definition_shadows_import(
94 name: &str,
95 import_path: &str,
96 name_span: Span,
97) -> LisetteDiagnostic {
98 LisetteDiagnostic::error("Definition shadows import")
99 .with_resolve_code("definition_shadows_import")
100 .with_span_label(
101 &name_span,
102 format!("conflicts with imported module `{}`", import_path),
103 )
104 .with_help(format!(
105 "`{}` is already used as a module alias for `{}`. \
106 Rename this definition or use a different import alias.",
107 name, import_path
108 ))
109}
110
111pub fn statement_as_tail(span: Span) -> LisetteDiagnostic {
112 LisetteDiagnostic::error("Statement used as value")
113 .with_infer_code("statement_as_tail")
114 .with_span_label(&span, "this is a statement, not an expression")
115 .with_help(
116 "The last item in this block must be an expression that produces a value. \
117 Statements like `let`, `=`, `task`, and `defer` do not produce values.",
118 )
119}
120
121pub fn invalid_map_initialization(key: &Type, value: &Type, span: Span) -> LisetteDiagnostic {
122 LisetteDiagnostic::error("Invalid `Map` initialization")
123 .with_infer_code("invalid_map_initialization")
124 .with_span_label(&span, "invalid syntax")
125 .with_help(format!(
126 "To initialize a `Map`, use `Map.new<{}, {}>()`",
127 key, value
128 ))
129}
130
131pub fn self_type_not_supported(span: Span, impl_receiver: Option<&str>) -> LisetteDiagnostic {
132 let name_span = Span::new(span.file_id, span.byte_offset, 4); let help = match impl_receiver {
134 Some(name) => format!("Replace `Self` with `{}`.", name),
135 None => "Use a type parameter instead, e.g. `interface Comparable<T> { fn compare(self, other: T) -> int }`".to_string(),
136 };
137 LisetteDiagnostic::error("Use of `Self` type")
138 .with_resolve_code("self_type_not_supported")
139 .with_span_label(&name_span, "invalid type")
140 .with_help(help)
141}
142
143pub fn type_not_found(type_name: &str, annotation_span: Span) -> LisetteDiagnostic {
144 let simple_name = type_name.rsplit('.').next().unwrap_or(type_name);
145 let qualifier_offset = (type_name.len() - simple_name.len()) as u32;
146 let name_span = Span::new(
147 annotation_span.file_id,
148 annotation_span.byte_offset + qualifier_offset,
149 simple_name.len() as u32,
150 );
151
152 let looks_like_type_param = simple_name.len() == 1
153 && simple_name.chars().next().is_some_and(|c| c.is_uppercase())
154 || ["Key", "Value", "Item", "Error", "Elem", "In", "Out"].contains(&simple_name);
155
156 if looks_like_type_param {
157 return LisetteDiagnostic::error("Undeclared type parameter")
158 .with_resolve_code("type_not_found")
159 .with_span_label(&name_span, "undeclared")
160 .with_help(format!(
161 "Declare the type parameter, e.g. `impl<{t}>` or `fn foo<{t}>`",
162 t = simple_name
163 ));
164 }
165
166 LisetteDiagnostic::error("Type not found")
167 .with_resolve_code("type_not_found")
168 .with_span_label(&name_span, "type not found in scope")
169 .with_help("Define or import this type")
170}
171
172pub fn undeclared_impl_type_param(
173 type_name: &str,
174 annotation_span: Span,
175 receiver_name: &str,
176) -> LisetteDiagnostic {
177 let name_span = Span::new(
178 annotation_span.file_id,
179 annotation_span.byte_offset,
180 type_name.len() as u32,
181 );
182
183 LisetteDiagnostic::error("Undeclared type parameter")
184 .with_resolve_code("type_not_found")
185 .with_span_label(&name_span, "undeclared")
186 .with_help(format!(
187 "Declare the type parameter: `impl<{t}> {r}<{t}>`",
188 t = type_name,
189 r = receiver_name
190 ))
191}
192
193pub fn type_param_with_args(type_arg_count: usize, span: Span) -> LisetteDiagnostic {
194 let noun = if type_arg_count == 1 {
195 "type argument"
196 } else {
197 "type arguments"
198 };
199
200 LisetteDiagnostic::error("Invalid type argument")
201 .with_infer_code("type_param_with_args")
202 .with_span_label(&span, "type is not parameterized")
203 .with_help(format!("Remove {}", noun))
204}
205
206pub fn type_args_on_non_generic(type_arg_count: usize, span: Span) -> LisetteDiagnostic {
207 let noun = if type_arg_count == 1 {
208 "type argument"
209 } else {
210 "type arguments"
211 };
212
213 LisetteDiagnostic::error("Unexpected type arguments")
214 .with_infer_code("type_arg_on_non_generic")
215 .with_span_label(&span, "accepts no type arguments")
216 .with_help(format!("Remove the {} from this call", noun))
217}
218
219pub fn circular_type_alias(type_name: &str, span: Span) -> LisetteDiagnostic {
220 LisetteDiagnostic::error("Circular type alias")
221 .with_resolve_code("circular_type_alias")
222 .with_span_label(&span, format!("`{}` references itself", type_name))
223 .with_help("Type aliases cannot be recursive")
224}
225
226pub fn const_disallows_composite(span: Span) -> LisetteDiagnostic {
227 LisetteDiagnostic::error("Composite value in `const`")
228 .with_infer_code("const_disallows_composite")
229 .with_span_label(&span, "not allowed")
230 .with_help("`const` only accepts primitive values: `bool`, `int`, `float`, and `string`")
231}
232
233pub fn const_cycle(cycle: &[String], span: Span) -> LisetteDiagnostic {
234 let mut diagnostic = LisetteDiagnostic::error("`const` init cycle")
235 .with_infer_code("const_cycle")
236 .with_help(
237 "`const` initializers cannot refer to themselves, either directly or transitively",
238 );
239 diagnostic = if cycle.len() == 1 {
240 diagnostic.with_span_label(&span, "self-reference")
241 } else {
242 let chain = cycle
243 .iter()
244 .map(|name| format!("`{}`", name))
245 .collect::<Vec<_>>()
246 .join(" → ");
247 diagnostic.with_span_label(&span, format!("cycle: {} → `{}`", chain, cycle[0]))
248 };
249 diagnostic
250}
251
252pub fn name_not_found(
253 variable_name: &str,
254 span: Span,
255 available_names: &[String],
256 expected_ty: Option<&Type>,
257) -> LisetteDiagnostic {
258 if matches!(variable_name, "nil" | "null" | "Nil" | "undefined") {
259 let help = nil_help_for(expected_ty);
260 return LisetteDiagnostic::error(format!("`{}` is not supported", variable_name))
261 .with_resolve_code("nil_not_supported")
262 .with_span_label(&span, "does not exist")
263 .with_help(help);
264 }
265
266 if let Some(hint) = go_builtin_hint(variable_name) {
267 return LisetteDiagnostic::error("Name not found")
268 .with_resolve_code("name_not_found")
269 .with_span_label(&span, "name not found in scope")
270 .with_help(hint);
271 }
272
273 let mut diagnostic = LisetteDiagnostic::error("Name not found")
274 .with_resolve_code("name_not_found")
275 .with_span_label(&span, "name not found in scope");
276
277 let suggestion = available_names
278 .iter()
279 .filter_map(|c| {
280 let d = levenshtein_distance(variable_name, c);
281 (d <= 2).then_some((c, d))
282 })
283 .min_by_key(|(_, d)| *d)
284 .map(|(c, _)| c.clone());
285
286 if let Some(suggestion) = suggestion {
287 diagnostic = diagnostic.with_help(format!("Did you mean `{}`?", suggestion));
288 } else {
289 diagnostic = diagnostic.with_help(format!("Define or import `{}`.", variable_name));
290 }
291
292 diagnostic
293}
294
295fn nil_help_for(expected_ty: Option<&Type>) -> String {
297 match expected_ty {
298 Some(ty) if ty.is_slice() => format!("For an empty `{}`, use `[]`.", ty),
299 Some(ty) if ty.is_map() => format!("For an empty `{}`, use `Map.new()`.", ty),
300 _ => {
301 "Absence is encoded with `Option<T>` in Lisette. Use `None` to represent absent values."
302 .to_string()
303 }
304 }
305}
306
307pub fn self_in_static_method(span: Span) -> LisetteDiagnostic {
308 LisetteDiagnostic::error("Invalid `self`")
309 .with_resolve_code("self_in_static_method")
310 .with_span_label(&span, "`self` is not available here")
311 .with_help("Add a `self` parameter to the method if you need an instance method")
312}
313
314pub fn static_method_called_on_instance(
315 method_name: &str,
316 type_name: &str,
317 span: Span,
318) -> LisetteDiagnostic {
319 LisetteDiagnostic::error("Static method called on instance")
320 .with_infer_code("static_method_on_instance")
321 .with_span_label(&span, format!("`{}` is a static method", method_name))
322 .with_help(format!(
323 "Call it as `{}.{}(...)` on the type, not on an instance",
324 type_name, method_name
325 ))
326}
327
328pub fn function_or_value_not_found_in_module(name: &str, span: Span) -> LisetteDiagnostic {
329 LisetteDiagnostic::error("Name not found")
330 .with_resolve_code("not_found_in_module")
331 .with_span_label(&span, format!("`{}` not found in module", name))
332 .with_help("Ensure the name is exported and spelled correctly")
333}
334
335pub fn receiver_type_mismatch(
336 impl_type: &str,
337 receiver_type: &str,
338 span: Span,
339) -> LisetteDiagnostic {
340 LisetteDiagnostic::error("Type mismatch")
341 .with_infer_code("receiver_type_mismatch")
342 .with_span_label(
343 &span,
344 format!(
345 "expected `{}` or `Ref<{}>`, found `{}`",
346 impl_type, impl_type, receiver_type
347 ),
348 )
349 .with_help(format!(
350 "Change the receiver type to `{}` or `Ref<{}>`",
351 impl_type, impl_type
352 ))
353}
354
355pub fn receiver_must_be_named_self(actual_name: &str, span: Span) -> LisetteDiagnostic {
356 LisetteDiagnostic::error("Invalid receiver name")
357 .with_infer_code("receiver_not_self")
358 .with_span_label(&span, "expected `self`")
359 .with_help(format!(
360 "Rename `{}` to `self`. In an instance method definition, Lisette expects the first parameter to be named `self`",
361 actual_name
362 ))
363}
364
365pub fn stringer_signature_mismatch(method_name: &str, span: Span) -> LisetteDiagnostic {
366 LisetteDiagnostic::error("Reserved method signature")
367 .with_infer_code("stringer_signature_mismatch")
368 .with_span_label(
369 &span,
370 format!("`{}` must have signature `(self) -> string`", method_name),
371 )
372 .with_help(format!(
373 "`{}` is reserved for the Go `fmt.Stringer` (or `fmt.GoStringer`) interface and is auto-emitted by Lisette. Either change the signature to `(self) -> string`, or rename the method",
374 method_name
375 ))
376}
377
378pub fn disallowed_mutation(
379 variable_name: &str,
380 span: Span,
381 self_type_name: Option<&str>,
382 is_match_arm_binding: bool,
383 is_const_binding: bool,
384) -> LisetteDiagnostic {
385 if variable_name == "self" {
386 if let Some(type_name) = self_type_name {
387 LisetteDiagnostic::error("Immutable receiver")
388 .with_infer_code("value_receiver_immutable")
389 .with_span_label(&span, "receiver is immutable")
390 .with_help(format!(
391 "Use `self: Ref<{type_name}>` to make the receiver mutable"
392 ))
393 } else {
394 LisetteDiagnostic::error("Immutable receiver")
395 .with_infer_code("value_receiver_immutable")
396 .with_span_label(&span, "receiver is immutable")
397 .with_help("Use `self: Ref<Self>` to make the receiver mutable")
398 }
399 } else if is_const_binding {
400 LisetteDiagnostic::error("Cannot mutate `const`")
401 .with_infer_code("immutable")
402 .with_span_label(&span, "cannot mutate a `const`")
403 .with_help(format!(
404 "`const` bindings are immutable. Rebind with `let mut {variable_name} = {variable_name}` to mutate a local copy"
405 ))
406 } else if is_match_arm_binding {
407 LisetteDiagnostic::error("Immutable variable")
408 .with_infer_code("immutable")
409 .with_span_label(&span, "cannot mutate an immutable variable")
410 .with_help(format!(
411 "Pattern bindings are immutable; rebind with `let mut {variable_name} = {variable_name}` to mutate"
412 ))
413 } else {
414 LisetteDiagnostic::error("Immutable variable")
415 .with_infer_code("immutable")
416 .with_span_label(&span, "cannot mutate an immutable variable")
417 .with_help(format!(
418 "Declare using `let mut {variable_name}` to make the variable mutable"
419 ))
420 }
421}
422
423pub fn self_reference_in_assignment(span: Span) -> LisetteDiagnostic {
424 LisetteDiagnostic::error("Cannot reassign variable while taking its reference")
425 .with_infer_code("self_reference_in_assignment")
426 .with_span_label(&span, "disallowed")
427 .with_help("Separate the reassignment from reference taking, or use a different variable")
428}
429
430pub fn uppercase_binding(span: Span, name: &str) -> LisetteDiagnostic {
431 LisetteDiagnostic::error("Invalid binding name")
432 .with_infer_code("uppercase_binding")
433 .with_span_label(&span, "binding names must start with a lowercase letter")
434 .with_help(format!("Use a lowercase name instead of `{}`", name))
435}
436
437pub fn enum_variant_constructor_not_found(
438 span: Span,
439 enum_info: Option<(&str, &[String])>,
440 variant_name: &str,
441) -> LisetteDiagnostic {
442 let help = if let Some((enum_name, variants)) = enum_info {
443 if variants.iter().any(|v| v == variant_name) {
444 format!("Use `{}.{}` to match this variant", enum_name, variant_name)
445 } else if let Some(closest) = variants
446 .iter()
447 .filter_map(|v| {
448 let d = levenshtein_distance(variant_name, v);
449 (d <= 2).then_some((v, d))
450 })
451 .min_by_key(|(_, d)| *d)
452 .map(|(v, _)| v)
453 {
454 format!("Did you mean `{}.{}`?", enum_name, closest)
455 } else {
456 let variants_fmt = format_list(variants, |v| format!("`{}.{}`", enum_name, v));
457 format!(
458 "Available variants for `{}` are {}",
459 enum_name, variants_fmt
460 )
461 }
462 } else {
463 "Check that the variant is defined in the enum and spelled correctly".to_string()
464 };
465
466 LisetteDiagnostic::error("Variant not found")
467 .with_resolve_code("variant_not_found")
468 .with_span_label(&span, "not found")
469 .with_help(help)
470}
471
472pub fn value_enum_in_source_file(enum_name: &str, span: Span) -> LisetteDiagnostic {
473 LisetteDiagnostic::error("Invalid value enum")
474 .with_infer_code("value_enum_outside_typedef")
475 .with_span_label(&span, "not allowed in .lis files")
476 .with_help(format!(
477 "Use a regular enum instead: `enum {} {{ A, B, C }}`. Value enums exist only to represent Go's enums in typedefs.",
478 enum_name
479 ))
480}
481
482pub fn arity_mismatch(
483 expected: &[Type],
484 actual: &[Type],
485 generic_params: &[String],
486 is_constructor: bool,
487 span: Span,
488) -> LisetteDiagnostic {
489 let expected_str = if !generic_params.is_empty() {
490 generic_params.join(", ")
491 } else {
492 expected
493 .iter()
494 .map(|t| t.to_string())
495 .collect::<Vec<_>>()
496 .join(", ")
497 };
498
499 let actual_str = actual
500 .iter()
501 .map(|t| t.to_string())
502 .collect::<Vec<_>>()
503 .join(", ");
504
505 let expected_count = expected.len();
506 let actual_count = actual.len();
507 let expected_word = if expected_count == 1 {
508 "argument"
509 } else {
510 "arguments"
511 };
512 let actual_word = if actual_count == 1 {
513 "argument"
514 } else {
515 "arguments"
516 };
517
518 LisetteDiagnostic::error("Wrong argument count")
519 .with_infer_code("arg_count_mismatch")
520 .with_span_label(
521 &span,
522 format!("expected `({})`, found `({})`", expected_str, actual_str),
523 )
524 .with_help(format!(
525 "This {} expects {} {} but received {} {}",
526 if is_constructor {
527 "constructor"
528 } else {
529 "function"
530 },
531 expected_count,
532 expected_word,
533 actual_count,
534 actual_word
535 ))
536}
537
538pub fn generics_arity_mismatch(
539 expected_generic_params: &[String],
540 actual_type_args: &[Annotation],
541 actual_types: &[Type],
542 span: Span,
543) -> LisetteDiagnostic {
544 let expected: Vec<Type> = expected_generic_params
545 .iter()
546 .map(|param| Type::Parameter(param.as_str().into()))
547 .collect();
548
549 let expected_str = expected
550 .iter()
551 .map(|t| t.to_string())
552 .collect::<Vec<_>>()
553 .join(", ");
554
555 let actual_str = actual_types
556 .iter()
557 .map(|t| t.to_string())
558 .collect::<Vec<_>>()
559 .join(", ");
560
561 let expected_count = expected.len();
562 let actual_count = actual_types.len();
563 let expected_word = if expected_count == 1 {
564 "type parameter"
565 } else {
566 "type parameters"
567 };
568 let actual_word = if actual_count == 1 {
569 "type parameter"
570 } else {
571 "type parameters"
572 };
573
574 let generics_span =
575 if let (Some(first), Some(last)) = (actual_type_args.first(), actual_type_args.last()) {
576 let first_span = first.get_span();
577 let last_span = last.get_span();
578 Span::new(
579 first_span.file_id,
580 first_span.byte_offset.saturating_sub(1),
581 (last_span.byte_offset + last_span.byte_length + 1)
582 .saturating_sub(first_span.byte_offset.saturating_sub(1)),
583 )
584 } else {
585 span
586 };
587
588 LisetteDiagnostic::error("Wrong type argument count")
589 .with_infer_code("type_arg_count_mismatch")
590 .with_span_label(
591 &generics_span,
592 format!("expected `<{}>`, found `<{}>`", expected_str, actual_str),
593 )
594 .with_help(format!(
595 "This type expects {} {} but received {} {}",
596 expected_count, expected_word, actual_count, actual_word
597 ))
598}
599
600pub fn tuple_arity_mismatch(
601 pattern_arity: usize,
602 expected_arity: usize,
603 span: Span,
604) -> LisetteDiagnostic {
605 let expected_word = if expected_arity == 1 {
606 "element"
607 } else {
608 "elements"
609 };
610 let actual_word = if pattern_arity == 1 {
611 "element"
612 } else {
613 "elements"
614 };
615 LisetteDiagnostic::error("Tuple arity mismatch")
616 .with_infer_code("tuple_element_count_mismatch")
617 .with_span_label(
618 &span,
619 format!(
620 "expected {} {}, found {} {}",
621 expected_arity, expected_word, pattern_arity, actual_word
622 ),
623 )
624 .with_help("Adjust the pattern to match the number of elements in the tuple.")
625}
626
627pub fn struct_not_found(identifier: &str, span: Span) -> LisetteDiagnostic {
628 let simple_name = identifier.rsplit('.').next().unwrap_or(identifier);
629 let qualifier_offset = (identifier.len() - simple_name.len()) as u32;
630 let name_span = Span::new(
631 span.file_id,
632 span.byte_offset + qualifier_offset,
633 simple_name.len() as u32,
634 );
635
636 LisetteDiagnostic::error("Struct not found")
637 .with_resolve_code("struct_not_found")
638 .with_span_label(&name_span, "struct not found in scope")
639 .with_help("Define or import this struct")
640}
641
642pub fn struct_missing_fields(
643 struct_name: &str,
644 missing: &[String],
645 span: Span,
646) -> LisetteDiagnostic {
647 let fields_list = missing.join(", ");
648
649 let simple_name = struct_name.rsplit('.').next().unwrap_or(struct_name);
650 let qualifier_offset = (struct_name.len() - simple_name.len()) as u32;
651 let name_span = Span::new(
652 span.file_id,
653 span.byte_offset + qualifier_offset,
654 simple_name.len() as u32,
655 );
656
657 LisetteDiagnostic::error(format!("Struct `{}` is missing fields", simple_name))
658 .with_infer_code("missing_struct_fields")
659 .with_span_label(&name_span, format!("missing fields: {}", fields_list))
660 .with_help("Initialize all fields, or add `..` to zero-fill the rest")
661}
662
663pub fn pattern_missing_fields(missing: &[String], span: Span) -> LisetteDiagnostic {
664 let (noun, fields_fmt) = if missing.len() == 1 {
665 ("field", format!("`{}`", missing[0]))
666 } else {
667 let formatted: Vec<String> = missing.iter().map(|f| format!("`{}`", f)).collect();
668 ("fields", formatted.join(", "))
669 };
670
671 let pronoun = if missing.len() == 1 { "it" } else { "them" };
672
673 LisetteDiagnostic::error("Missing pattern fields")
674 .with_infer_code("pattern_missing_fields")
675 .with_span_label(&span, format!("missing {}", fields_fmt))
676 .with_help(format!(
677 "Include the missing {}, or use `..` to ignore {}",
678 noun, pronoun
679 ))
680}
681
682pub fn private_field_access(field_name: &str, struct_name: &str, span: Span) -> LisetteDiagnostic {
683 LisetteDiagnostic::error("Private field")
684 .with_resolve_code("private_field_access")
685 .with_span_label(&span, "private")
686 .with_help(format!(
687 "Cannot access private field `{}` of struct `{}`. Mark the field as `pub`.",
688 field_name, struct_name
689 ))
690}
691
692pub fn private_method_access(method_name: &str, type_name: &str, span: Span) -> LisetteDiagnostic {
693 LisetteDiagnostic::error("Private method")
694 .with_resolve_code("private_method_access")
695 .with_span_label(&span, "private")
696 .with_help(format!(
697 "Cannot access private method `{}` of type `{}`. Mark the method as `pub`.",
698 method_name, type_name
699 ))
700}
701
702pub fn private_field_in_spread(
703 field_name: &str,
704 struct_name: &str,
705 span: Span,
706) -> LisetteDiagnostic {
707 LisetteDiagnostic::error("Private field")
708 .with_resolve_code("private_field_spread")
709 .with_span_label(&span, "private")
710 .with_help(format!(
711 "Cannot spread `{}` because field `{}` is private. Mark the field as `pub`.",
712 struct_name, field_name
713 ))
714}
715
716pub fn private_field_in_zero_fill(
717 field_name: &str,
718 struct_name: &str,
719 owning_module: &str,
720 span: Span,
721) -> LisetteDiagnostic {
722 LisetteDiagnostic::error("Private field")
723 .with_resolve_code("private_field_zero_fill")
724 .with_span_label(&span, "private")
725 .with_help(format!(
726 "`{}` of `{}` cannot be zero-filled because `{}` is private to module `{}`. \
727 Provide an explicit value, or have `{}` expose `{}` as `pub` or offer a \
728 constructor.",
729 field_name, struct_name, field_name, owning_module, owning_module, field_name
730 ))
731}
732
733pub fn field_no_zero(
734 struct_name: &str,
735 field_name: &str,
736 field_ty: &Type,
737 chain: &[&str],
738 private: Option<(&str, &str, &str)>,
739 span: Span,
740) -> LisetteDiagnostic {
741 let main = match private {
742 Some((priv_struct, priv_field, priv_module)) => format!(
743 "`{}` of `{}` cannot be zero-filled because `{}.{}` is private to module `{}`. \
744 Provide an explicit value for `{}`, or have `{}` expose `{}` as `pub`.",
745 field_name,
746 struct_name,
747 priv_struct,
748 priv_field,
749 priv_module,
750 field_name,
751 priv_module,
752 priv_field
753 ),
754 None if chain.is_empty() => format!(
755 "Field `{}` of type `{}` has no zero value. Provide an explicit value, \
756 or wrap the field type in `Option<T>`.",
757 field_name, field_ty
758 ),
759 None => format!(
760 "Field `{}.{}` of type `{}` has no zero value. Provide an explicit value for \
761 `{}`, or wrap the field type in `Option<T>`.",
762 field_name,
763 chain.join("."),
764 field_ty,
765 field_name
766 ),
767 };
768 LisetteDiagnostic::error("Field has no zero value")
769 .with_infer_code("field_no_zero")
770 .with_span_label(&span, "no zero available")
771 .with_help(main)
772}
773
774pub fn unresolved_receiver_type(member: &str, span: Span) -> LisetteDiagnostic {
775 LisetteDiagnostic::error("Cannot infer receiver type")
776 .with_infer_code("unresolved_receiver_type")
777 .with_span_label(
778 &span,
779 format!(
780 "cannot resolve `.{}` because the receiver type is unknown",
781 member
782 ),
783 )
784 .with_help(
785 "Annotate the receiver's binding, e.g. `let x: SomeType = ...` or \
786 `|param: SomeType| ...`.",
787 )
788}
789
790pub fn member_not_found(
791 ty: &Type,
792 field: &str,
793 span: Span,
794 available_fields: Option<&[String]>,
795 unwrap_hint: Option<UnwrapHint>,
796 is_call_target: bool,
797) -> LisetteDiagnostic {
798 let mut diagnostic = LisetteDiagnostic::error("Member not found")
799 .with_infer_code("member_not_found")
800 .with_span_label(&span, format!("no member `{}` on type `{}`", field, ty));
801
802 if matches!(field, "unwrap" | "expect") && (ty.is_option() || ty.is_result() || ty.is_partial())
803 {
804 let help = if ty.is_option() {
805 format!(
806 "Lisette does not provide `{}()`. Use `?` to propagate, `match` to handle both \
807 cases (e.g. `match <expr> {{ Some(x) => x, None => ... }}`), `let else` for \
808 early exit, or `unwrap_or(default)` for a fallback.",
809 field
810 )
811 } else if ty.is_result() {
812 format!(
813 "Lisette does not provide `{}()`. Use `?` to propagate, `match` to handle both \
814 cases (e.g. `match <expr> {{ Ok(x) => x, Err(e) => ... }}`), `let else` for \
815 early exit, or `unwrap_or(default)` for a fallback.",
816 field
817 )
818 } else {
819 format!(
820 "Lisette does not provide `{}()`. The `?` operator is not supported on \
821 `Partial`; use `match` to handle all three cases (e.g. `match <expr> \
822 {{ Ok(x) => ..., Err(e) => ..., Both(x, e) => ... }}`) or `unwrap_or(default)` \
823 for a fallback.",
824 field
825 )
826 };
827 diagnostic = diagnostic.with_help(help);
828 return diagnostic;
829 }
830
831 if let Some(hint) = unwrap_hint {
832 let (wrapper_name, pattern) = match hint.wrapper {
833 UnwrapWrapper::Option => (
834 "Option",
835 format!(
836 "match <expr> {{ Some(x) => x.{}(...), None => ... }}",
837 field
838 ),
839 ),
840 UnwrapWrapper::Result => (
841 "Result",
842 format!(
843 "match <expr> {{ Ok(x) => x.{}(...), Err(e) => ... }}",
844 field
845 ),
846 ),
847 };
848 diagnostic = diagnostic.with_help(format!(
849 "Unwrap the `{}` to extract the `{}` value, then call `{}` on it, e.g. `{}`",
850 wrapper_name, hint.inner_ty, field, pattern
851 ));
852 return diagnostic;
853 }
854
855 let suggestion = available_fields.and_then(|fields| find_similar_name(field, fields));
856
857 if let Some(suggestion) = suggestion {
858 let rendered = if is_call_target {
859 format!("{}()", suggestion)
860 } else {
861 suggestion
862 };
863 diagnostic = diagnostic.with_help(format!("Did you mean `{}`?", rendered));
864 } else {
865 diagnostic = diagnostic.with_help("Ensure the field or method is defined on this type");
866 }
867
868 diagnostic
869}
870
871#[derive(Debug, Clone, Copy)]
872pub enum UnwrapWrapper {
873 Option,
874 Result,
875}
876
877#[derive(Debug, Clone)]
878pub struct UnwrapHint {
879 pub wrapper: UnwrapWrapper,
880 pub inner_ty: Type,
881}
882
883pub fn not_numeric(ty: &Type, span: Span) -> LisetteDiagnostic {
884 LisetteDiagnostic::error("Type mismatch")
885 .with_infer_code("type_mismatch")
886 .with_span_label(&span, format!("expected `int` or `float`, found `{}`", ty))
887 .with_help("The negation operator `-` can only be used with `int` or `float`")
888}
889
890pub fn not_numeric_for_binary(
891 operator: &BinaryOperator,
892 ty: &Type,
893 span: Span,
894) -> LisetteDiagnostic {
895 LisetteDiagnostic::error("Type mismatch")
896 .with_infer_code("type_mismatch")
897 .with_span_label(&span, format!("expected `int` or `float`, found `{}`", ty))
898 .with_help(format!(
899 "The `{}` operator can only be used with `int` or `float`",
900 operator
901 ))
902}
903
904pub fn binary_operator_type_mismatch(
905 operator: &BinaryOperator,
906 left_ty: &Type,
907 right_ty: &Type,
908 span: Span,
909) -> LisetteDiagnostic {
910 let label_msg = format!(
911 "cannot {} `{}` and `{}`",
912 operator_verb(operator),
913 left_ty,
914 right_ty
915 );
916
917 LisetteDiagnostic::error("Type mismatch")
918 .with_infer_code("type_mismatch")
919 .with_span_label(&span, label_msg)
920 .with_help(format!(
921 "The `{}` operator {}",
922 operator,
923 operator_help(operator)
924 ))
925}
926
927pub fn not_orderable(ty: &Type, span: Span) -> LisetteDiagnostic {
928 LisetteDiagnostic::error("Type mismatch")
929 .with_infer_code("type_mismatch")
930 .with_span_label(&span, format!("expected orderable, found `{}`", ty))
931 .with_help("Use comparison operators only with numeric, string, or boolean types")
932}
933
934pub fn not_comparable(ty: &Type, reason: &str, span: Span) -> LisetteDiagnostic {
935 LisetteDiagnostic::error("Type mismatch")
936 .with_infer_code("type_mismatch")
937 .with_span_label(&span, format!("`{}` cannot be compared with `==`", ty))
938 .with_help(format!(
939 "The `==` and `!=` operators cannot be used on {} because they are not comparable in Go",
940 reason
941 ))
942}
943
944pub fn not_orderable_bound(span: Span) -> LisetteDiagnostic {
945 LisetteDiagnostic::error("Bound not satisfied")
946 .with_infer_code("not_orderable_bound")
947 .with_span_label(&span, "does not satisfy `cmp.Ordered`")
948 .with_help(
949 "The type parameter must be `cmp.Ordered` but the argument is not orderable. \
950 Relax the bound or pass an argument that satisfies it",
951 )
952}
953
954pub fn not_comparable_bound(span: Span) -> LisetteDiagnostic {
955 LisetteDiagnostic::error("Bound not satisfied")
956 .with_infer_code("not_comparable_bound")
957 .with_span_label(&span, "does not satisfy `Comparable`")
958 .with_help(
959 "The parameter must be `Comparable` but the argument is not comparable. \
960 Relax the bound or pass an argument that satisfies it",
961 )
962}
963
964pub fn bound_only_in_value_position(name: &str, span: Span) -> LisetteDiagnostic {
965 LisetteDiagnostic::error(format!("`{}` is a bound, not a value type", name))
966 .with_infer_code("bound_only_in_value_position")
967 .with_span_label(&span, "not allowed here")
968 .with_help(format!(
969 "Use `{}` only as a bound to constrain a generic parameter, e.g. `fn f<T: {}>(x: T)`",
970 name, name
971 ))
972}
973
974pub fn missing_bound_on_param(
975 param_name: &str,
976 required_bound: &str,
977 span: Span,
978) -> LisetteDiagnostic {
979 let short = required_bound.rsplit('.').next().unwrap_or(required_bound);
980 LisetteDiagnostic::error("Missing bound on type parameter")
981 .with_infer_code("missing_bound_on_param")
982 .with_span_label(&span, format!("does not satisfy `{}`", short))
983 .with_help(format!(
984 "The parameter must be `{}` but the argument is unbounded. \
985 Add this bound to the enclosing function: `<{}: {}>`",
986 required_bound, param_name, required_bound
987 ))
988}
989
990pub fn division_by_zero(span: Span) -> LisetteDiagnostic {
991 LisetteDiagnostic::error("Division by zero")
992 .with_infer_code("division_by_zero")
993 .with_span_label(&span, "cannot divide by zero")
994 .with_help("This operation will panic at runtime")
995}
996
997pub fn incompatible_named_numeric_types(underlying_ty: &Type, span: Span) -> LisetteDiagnostic {
998 LisetteDiagnostic::error("Type mismatch")
999 .with_infer_code("incompatible_named_numeric_types")
1000 .with_span_label(&span, "cannot compute")
1001 .with_help(format!(
1002 "Cast one to the other's type, or convert both to `{}`",
1003 underlying_ty
1004 ))
1005}
1006
1007pub fn invalid_division_order(
1008 operator: &BinaryOperator,
1009 left_ty: &Type,
1010 right_ty: &Type,
1011 span: Span,
1012) -> LisetteDiagnostic {
1013 let (op_symbol, help_msg) = match operator {
1014 BinaryOperator::Division => (
1015 "/",
1016 format!(
1017 "To divide by `{}`, the dividend (left operand) must also be `{}`",
1018 right_ty, right_ty
1019 ),
1020 ),
1021 BinaryOperator::Remainder => (
1022 "%",
1023 format!(
1024 "To take the remainder by `{}`, the dividend (left operand) must also be `{}`",
1025 right_ty, right_ty
1026 ),
1027 ),
1028 _ => unreachable!(),
1029 };
1030
1031 LisetteDiagnostic::error("Invalid operation")
1032 .with_infer_code("invalid_division_order")
1033 .with_span_label(
1034 &span,
1035 format!("cannot compute `{}` {} `{}`", left_ty, op_symbol, right_ty),
1036 )
1037 .with_help(help_msg)
1038}
1039
1040pub fn branch_type_mismatch(
1041 consequence_ty: &Type,
1042 consequence_span: Span,
1043 alternative_ty: &Type,
1044 alternative_span: Span,
1045) -> LisetteDiagnostic {
1046 LisetteDiagnostic::error("Type mismatch")
1047 .with_infer_code("type_mismatch")
1048 .with_span_label(
1049 &consequence_span,
1050 format!("this branch returns `{}`", consequence_ty),
1051 )
1052 .with_span_label(
1053 &alternative_span,
1054 format!("this branch returns `{}`", alternative_ty),
1055 )
1056 .with_help("All branches must return the same type")
1057}
1058
1059pub fn let_else_must_diverge(span: Span) -> LisetteDiagnostic {
1060 LisetteDiagnostic::error("Invalid `else` block")
1061 .with_infer_code("let_else_must_diverge")
1062 .with_span_primary_label(&span, "this branch does not diverge")
1063 .with_help("Add `return`, `break`, `continue`, or a diverging call in the `else` block")
1064}
1065
1066pub fn return_outside_function(span: Span) -> LisetteDiagnostic {
1067 LisetteDiagnostic::error("`return` outside function")
1068 .with_infer_code("return_outside_function")
1069 .with_span_label(&span, "`return` outside function")
1070 .with_help("Use `return` only inside a function body")
1071}
1072
1073pub fn disallowed_mut_use(span: Span) -> LisetteDiagnostic {
1074 LisetteDiagnostic::error("Invalid `mut`")
1075 .with_infer_code("mut_not_allowed")
1076 .with_span_label(&span, "not allowed here")
1077 .with_help("`mut` is not allowed with destructuring patterns")
1078}
1079
1080pub fn cannot_match_on_functions(span: Span) -> LisetteDiagnostic {
1081 LisetteDiagnostic::error("Invalid pattern")
1082 .with_infer_code("invalid_pattern")
1083 .with_span_label(&span, "cannot pattern match on functions")
1084 .with_help("Functions cannot be compared for equality")
1085}
1086
1087pub fn cannot_match_on_unknown(span: Span) -> LisetteDiagnostic {
1088 LisetteDiagnostic::error("Cannot match on Unknown")
1089 .with_infer_code("cannot_match_on_unknown")
1090 .with_span_label(&span, "is type `Unknown`")
1091 .with_help("Use `assert_type` to narrow this value into a concrete type before matching. Example: `let value = assert_type<MyType>(x)?`")
1092}
1093
1094pub fn cannot_match_on_unconstrained_type(span: Span) -> LisetteDiagnostic {
1095 LisetteDiagnostic::error("Uninferred type")
1096 .with_infer_code("cannot_match_on_unconstrained_type")
1097 .with_span_label(&span, "type cannot be inferred at this point")
1098 .with_help("Add a type annotation on the value before matching on it")
1099}
1100
1101pub fn duplicate_binding_in_pattern(
1102 name: &str,
1103 first_span: Span,
1104 second_span: Span,
1105) -> LisetteDiagnostic {
1106 LisetteDiagnostic::error("Duplicate binding")
1107 .with_infer_code("duplicate_binding_in_pattern")
1108 .with_span_label(&first_span, format!("first use of `{}`", name))
1109 .with_span_label(&second_span, "used again")
1110 .with_help("Remove the duplicate binding")
1111}
1112
1113pub fn literal_pattern_in_binding(span: Span) -> LisetteDiagnostic {
1114 LisetteDiagnostic::error("Pattern might not match")
1115 .with_infer_code("literal_in_binding")
1116 .with_span_label(&span, "value might not equal this literal")
1117 .with_help("Use `match` or `if` to compare values")
1118}
1119
1120pub fn as_binding_in_irrefutable_context(span: Span) -> LisetteDiagnostic {
1121 LisetteDiagnostic::error("Invalid `as` binding")
1122 .with_infer_code("as_binding_in_irrefutable_context")
1123 .with_span_label(&span, "`as` is disallowed here")
1124 .with_help("Use `as` only in `match`, `if let`, and `while let`")
1125}
1126
1127pub fn select_some_as_binding_not_supported(span: Span) -> LisetteDiagnostic {
1128 LisetteDiagnostic::error("Cannot alias `Some(...)` in select")
1129 .with_infer_code("select_some_as_not_supported")
1130 .with_span_label(&span, "`as` cannot be placed around `Some(...)`")
1131 .with_help(
1132 "Place `as` inside `Some(...)` to bind the received value: `Some(value as alias)`",
1133 )
1134}
1135
1136pub fn redundant_as_identifier(inner: &str, alias: &str, span: Span) -> LisetteDiagnostic {
1137 LisetteDiagnostic::error("Redundant `as` binding")
1138 .with_infer_code("redundant_as_binding")
1139 .with_span_label(&span, format!("`{}` already binds this value", inner))
1140 .with_help(format!(
1141 "Use `{}` directly, or rename `{}` to `{}`",
1142 alias, inner, alias
1143 ))
1144}
1145
1146pub fn redundant_as_wildcard(alias: &str, span: Span) -> LisetteDiagnostic {
1147 LisetteDiagnostic::error("Redundant `as` binding")
1148 .with_infer_code("redundant_as_binding")
1149 .with_span_label(&span, "`_` binds nothing")
1150 .with_help(format!("Replace `_ as {}` with just `{}`", alias, alias))
1151}
1152
1153pub fn redundant_as_literal(literal: &str, alias: &str, span: Span) -> LisetteDiagnostic {
1154 LisetteDiagnostic::error("Redundant `as` binding")
1155 .with_infer_code("redundant_as_binding")
1156 .with_span_label(&span, format!("`{}` is always `{}`", alias, literal))
1157 .with_help(format!(
1158 "Replace `{} as {}` with just `{}`",
1159 literal, alias, literal
1160 ))
1161}
1162
1163pub fn or_pattern_in_irrefutable_context(span: Span) -> LisetteDiagnostic {
1164 LisetteDiagnostic::error("Invalid or-pattern")
1165 .with_infer_code("or_pattern_in_irrefutable")
1166 .with_span_label(&span, "or-patterns are not allowed here")
1167 .with_help("Use a `match` expression instead.")
1168 .with_note("Or-patterns can only be used in `match`, `if let`, and `while let`.")
1169}
1170
1171pub fn or_pattern_binding_mismatch(
1172 span: Span,
1173 missing_in_later: &[&str],
1174 missing_in_first: &[&str],
1175) -> LisetteDiagnostic {
1176 let missing = if !missing_in_later.is_empty() {
1177 missing_in_later.join(", ")
1178 } else {
1179 missing_in_first.join(", ")
1180 };
1181
1182 LisetteDiagnostic::error("Invalid or-pattern")
1183 .with_infer_code("or_pattern_binding_mismatch")
1184 .with_span_label(&span, "only bound here")
1185 .with_help(format!(
1186 "Variable {} is not bound in all alternatives. Use a wildcard `_` instead of a binding, or ensure all alternatives bind the same variable",
1187 missing
1188 ))
1189}
1190
1191pub fn or_pattern_type_mismatch(span: Span, first_ty: &str, alt_ty: &str) -> LisetteDiagnostic {
1192 LisetteDiagnostic::error("Invalid or-pattern")
1193 .with_infer_code("or_pattern_type_mismatch")
1194 .with_span_label(
1195 &span,
1196 format!("expected `{}`, found `{}`", first_ty, alt_ty),
1197 )
1198 .with_help(
1199 "Use a wildcard `_` instead of a binding, or use separate match arms for each variant",
1200 )
1201}
1202
1203pub fn unknown_iterable_type(span: Span) -> LisetteDiagnostic {
1204 LisetteDiagnostic::error("Uninferrable type")
1205 .with_infer_code("type_not_inferred")
1206 .with_span_label(&span, "cannot be inferred")
1207 .with_help("Add a type annotation to the iterable expression")
1208}
1209
1210pub fn not_iterable(ty: &Type, span: Span) -> LisetteDiagnostic {
1211 LisetteDiagnostic::error("Not iterable")
1212 .with_infer_code("not_iterable")
1213 .with_span_label(&span, format!("`{}` is not iterable", ty))
1214 .with_help("Use `Slice`, `Map`, `Range`, `Channel`, or `string`")
1215}
1216
1217pub fn tuple_literal_required_in_loop(span: Span) -> LisetteDiagnostic {
1218 LisetteDiagnostic::error("Invalid loop pattern")
1219 .with_infer_code("invalid_pattern")
1220 .with_span_label(&span, "tuple literal required here")
1221 .with_help("Use `(key, value)` destructuring pattern for map or enumerated iteration")
1222}
1223
1224pub fn propagate_on_partial(span: Span) -> LisetteDiagnostic {
1225 LisetteDiagnostic::error("Cannot use `?` on `Partial`")
1226 .with_infer_code("propagate_on_partial")
1227 .with_span_label(&span, "`Partial` requires explicit `match`")
1228 .with_help(
1229 "The `?` operator is incompatible with `Partial` because it has \
1230 three variants. Use `match` to handle `Ok`, `Err`, and `Both` \
1231 explicitly.",
1232 )
1233}
1234
1235pub fn try_requires_result_or_option(span: Span) -> LisetteDiagnostic {
1236 LisetteDiagnostic::error("Type mismatch")
1237 .with_infer_code("try_requires_result_or_option")
1238 .with_span_label(&span, "expects `Result` or `Option`")
1239 .with_help("Use the `?` operator only on `Result` or `Option`")
1240}
1241
1242pub fn try_outside_function(span: Span) -> LisetteDiagnostic {
1243 LisetteDiagnostic::error("`?` outside function")
1244 .with_infer_code("try_outside_function")
1245 .with_span_label(&span, "`?` outside function")
1246 .with_help("Use `?` only inside a function that returns `Result` or `Option`")
1247}
1248
1249pub fn try_return_type_mismatch(expected: &str, actual_ty: &Type, span: Span) -> LisetteDiagnostic {
1250 LisetteDiagnostic::error("Type mismatch")
1251 .with_infer_code("try_return_type_mismatch")
1252 .with_span_label(
1253 &span,
1254 format!(
1255 "expects `{}`, but function returns `{}`",
1256 expected, actual_ty
1257 ),
1258 )
1259 .with_help(format!(
1260 "Change the function return type to `{}` or remove the `?` operator",
1261 expected
1262 ))
1263}
1264
1265pub fn try_block_empty(span: Span) -> LisetteDiagnostic {
1266 LisetteDiagnostic::error("Empty `try` block")
1267 .with_infer_code("try_block_empty")
1268 .with_span_label(&span, "empty")
1269 .with_help("Ensure the `try` block contains at least one expression")
1270}
1271
1272pub fn try_block_no_question_mark(try_keyword_span: Span) -> LisetteDiagnostic {
1273 LisetteDiagnostic::error("Useless `try` block")
1274 .with_infer_code("try_block_no_question_mark")
1275 .with_span_label(&try_keyword_span, "no `?` operator found")
1276 .with_help("A `try` block must contain at least one `?` for propagation")
1277}
1278
1279pub fn mixed_carriers_in_try_block(span: Span) -> LisetteDiagnostic {
1280 LisetteDiagnostic::error("Mixed `try` block")
1281 .with_infer_code("try_block_mixed_carriers")
1282 .with_span_label(&span, "mixing `Option` and `Result`")
1283 .with_help(
1284 "A `try` block must use either all `Option` operations or all `Result` operations",
1285 )
1286}
1287
1288pub fn break_outside_loop(span: Span) -> LisetteDiagnostic {
1289 LisetteDiagnostic::error("`break` outside loop")
1290 .with_infer_code("break_outside_loop")
1291 .with_span_label(&span, "not inside a loop")
1292 .with_help("`break` can only be used inside `loop`, `for`, or `while`")
1293}
1294
1295pub fn continue_outside_loop(span: Span) -> LisetteDiagnostic {
1296 LisetteDiagnostic::error("`continue` outside loop")
1297 .with_infer_code("continue_outside_loop")
1298 .with_span_label(&span, "not inside a loop")
1299 .with_help("`continue` can only be used inside `loop`, `for`, or `while`")
1300}
1301
1302pub fn nested_function(span: Span) -> LisetteDiagnostic {
1303 LisetteDiagnostic::error("Nested function declaration")
1304 .with_infer_code("nested_function")
1305 .with_span_label(&span, "functions can only be declared at top level")
1306 .with_help("Use a lambda instead: `|x| x + 1` or `|x| { ... }`")
1307}
1308
1309pub fn return_in_try_block(span: Span) -> LisetteDiagnostic {
1310 LisetteDiagnostic::error("`return` in `try` block")
1311 .with_infer_code("try_block_return")
1312 .with_span_label(&span, "not inside a function")
1313 .with_help(
1314 "Use `return` inside a function, or use `Err(...)?` to exit the `try` block early",
1315 )
1316}
1317
1318pub fn break_in_try_block(span: Span) -> LisetteDiagnostic {
1319 LisetteDiagnostic::error("`break` in `try` block")
1320 .with_infer_code("try_block_break")
1321 .with_span_label(&span, "not inside a loop")
1322 .with_help("Use `break` inside a loop, or use `Err(...)?` to exit the `try` block early")
1323}
1324
1325pub fn continue_in_try_block(span: Span) -> LisetteDiagnostic {
1326 LisetteDiagnostic::error("`continue` in `try` block")
1327 .with_infer_code("try_block_continue")
1328 .with_span_label(&span, "not inside a loop")
1329 .with_help("Use `continue` inside a loop, or use `Err(...)?` to exit the `try` block early")
1330}
1331
1332pub fn recover_block_empty(span: Span) -> LisetteDiagnostic {
1333 LisetteDiagnostic::warn("Empty `recover` block")
1334 .with_infer_code("recover_block_empty")
1335 .with_span_label(&span, "empty")
1336 .with_help("Ensure the `recover` block contains at least one expression that may panic")
1337}
1338
1339pub fn recover_cannot_use_question_mark(span: Span) -> LisetteDiagnostic {
1340 LisetteDiagnostic::error("`?` in `recover` block")
1341 .with_infer_code("recover_cannot_use_question_mark")
1342 .with_span_label(&span, "cannot propagate to `recover` block")
1343 .with_help(
1344 "Use a `try` block inside the `recover` block, or handle the `Result` explicitly",
1345 )
1346}
1347
1348pub fn return_in_recover_block(span: Span) -> LisetteDiagnostic {
1349 LisetteDiagnostic::error("`return` in `recover` block")
1350 .with_infer_code("recover_block_return")
1351 .with_span_label(&span, "not allowed inside `recover` block")
1352 .with_help("Remove the `return`, or move it inside a nested function")
1353}
1354
1355pub fn break_in_recover_block(span: Span) -> LisetteDiagnostic {
1356 LisetteDiagnostic::error("`break` in `recover` block")
1357 .with_infer_code("recover_block_break")
1358 .with_span_label(&span, "not allowed inside `recover` block")
1359 .with_help("Remove the `break`, or move it inside a loop within the `recover` block")
1360}
1361
1362pub fn continue_in_recover_block(span: Span) -> LisetteDiagnostic {
1363 LisetteDiagnostic::error("`continue` in `recover` block")
1364 .with_infer_code("recover_block_continue")
1365 .with_span_label(&span, "not allowed inside `recover` block")
1366 .with_help("Remove the `continue`, or move it inside a loop within the `recover` block")
1367}
1368
1369pub fn expected_channel_receive(ty: &Type, span: Span) -> LisetteDiagnostic {
1370 LisetteDiagnostic::error("Expected channel receive")
1371 .with_infer_code("expected_channel_receive")
1372 .with_span_label(&span, format!("`{}` is not a channel receive", ty))
1373 .with_help("Use `ch.receive()` to receive from a channel in select")
1374}
1375
1376pub fn empty_select(span: Span) -> LisetteDiagnostic {
1377 LisetteDiagnostic::error("Empty select")
1378 .with_infer_code("empty_select")
1379 .with_span_label(&span, "select has no arms")
1380 .with_help(
1381 "Add at least one channel operation arm, e.g. `select { ch.receive() => v { ... } }`",
1382 )
1383}
1384
1385pub fn expected_channel_send(span: Span) -> LisetteDiagnostic {
1386 LisetteDiagnostic::error("Expected channel operation")
1387 .with_infer_code("expected_channel_send")
1388 .with_span_label(&span, "not a channel operation")
1389 .with_help("Use `ch.send(value)` or `ch.receive()` in select arms")
1390}
1391
1392pub fn bare_identifier_in_select_receive(span: Span) -> LisetteDiagnostic {
1393 LisetteDiagnostic::error("Invalid select case")
1394 .with_infer_code("bare_identifier_in_select_receive")
1395 .with_span_label(&span, "expected destructuring")
1396 .with_help("`ch.receive()` returns an `Option`, so use `let Some(v) = ch.receive()` to bind the value")
1397}
1398
1399pub fn none_pattern_in_select_receive(span: Span) -> LisetteDiagnostic {
1400 LisetteDiagnostic::error("Invalid select case")
1401 .with_infer_code("none_pattern_in_select_receive")
1402 .with_span_label(&span, "expected match")
1403 .with_help(
1404 "To detect channel close, use `match ch.receive() { Some(v) => ..., None => ... }`",
1405 )
1406}
1407
1408pub fn select_match_missing_some_arm(span: Span) -> LisetteDiagnostic {
1409 LisetteDiagnostic::error("Invalid select match")
1410 .with_infer_code("select_match_missing_some_arm")
1411 .with_span_label(&span, "missing `Some` arm")
1412 .with_help("`None` only handles channel close. Add a `Some(v) => ...` arm to handle received values")
1413}
1414
1415pub fn select_match_missing_none_arm(span: Span) -> LisetteDiagnostic {
1416 LisetteDiagnostic::error("Invalid select match")
1417 .with_infer_code("select_match_missing_none_arm")
1418 .with_span_label(&span, "missing `None` arm")
1419 .with_help("Matching on `ch.receive()` requires handling channel close. Add a `None => ...` arm to handle channel close, or simplify to `let Some(v) = ch.receive() => ...`")
1420}
1421
1422pub fn select_match_duplicate_some_arm(span: Span) -> LisetteDiagnostic {
1423 LisetteDiagnostic::error("Invalid select match")
1424 .with_infer_code("select_match_duplicate_some_arm")
1425 .with_span_label(&span, "duplicate")
1426 .with_help(
1427 "Remove the duplicate `Some` arm. If you need to, use a `match` inside the arm body",
1428 )
1429}
1430
1431pub fn select_match_duplicate_none_arm(span: Span) -> LisetteDiagnostic {
1432 LisetteDiagnostic::error("Invalid select match")
1433 .with_infer_code("select_match_duplicate_none_arm")
1434 .with_span_label(&span, "duplicate")
1435 .with_help(
1436 "Remove the duplicate `None` arm. If you need to, use a `match` inside the arm body",
1437 )
1438}
1439
1440pub fn select_match_guard_not_allowed(span: Span) -> LisetteDiagnostic {
1441 LisetteDiagnostic::error("Invalid select match")
1442 .with_infer_code("select_match_guard_not_allowed")
1443 .with_span_label(&span, "not supported")
1444 .with_help("Match arms inside `select` do not support guards. Move the condition inside the arm body: `Some(v) => { if condition { ... } }`")
1445}
1446
1447pub fn select_match_invalid_pattern(span: Span) -> LisetteDiagnostic {
1448 LisetteDiagnostic::error("Invalid select match")
1449 .with_infer_code("select_match_invalid_pattern")
1450 .with_span_label(&span, "unsupported pattern")
1451 .with_help("Select match arms support only `Some(...)` and `None` patterns")
1452}
1453
1454pub fn select_receive_refutable_pattern(span: Span) -> LisetteDiagnostic {
1455 LisetteDiagnostic::error("Refutable pattern in select receive")
1456 .with_infer_code("select_receive_refutable_pattern")
1457 .with_span_label(&span, "may not match all received values")
1458 .with_help(
1459 "Select receive requires an irrefutable binding like `Some(v)` or `Some(_)`. \
1460 Use a regular `match` inside the arm body to filter values",
1461 )
1462}
1463
1464pub fn multiple_select_receives(first_span: Span, second_span: Span) -> LisetteDiagnostic {
1465 LisetteDiagnostic::error("Invalid select")
1466 .with_infer_code("multiple_select_receives")
1467 .with_span_label(&first_span, "first receive arm")
1468 .with_span_label(&second_span, "second receive arm")
1469 .with_help("Multiple shorthand receive arms can lead to unexpected behavior when a channel closes. Use `match ch.receive() { Some(v) => ..., None => ... }` to handle closes explicitly")
1470}
1471
1472pub fn duplicate_select_default(first_span: Span, second_span: Span) -> LisetteDiagnostic {
1473 LisetteDiagnostic::error("Invalid select")
1474 .with_infer_code("duplicate_select_default")
1475 .with_span_label(&first_span, "first default arm")
1476 .with_span_label(&second_span, "duplicate default arm")
1477 .with_help(
1478 "A select block can have at most one default arm (`_ => ...`). Remove the duplicate.",
1479 )
1480}
1481
1482pub fn non_exhaustive_select_expression(span: Span) -> LisetteDiagnostic {
1483 LisetteDiagnostic::error("Non-exhaustive select expression")
1484 .with_infer_code("non_exhaustive_select_expression")
1485 .with_span_label(&span, "may not produce a value")
1486 .with_help("Add a default arm `_ => ...` to handle closed channels")
1487}
1488
1489pub fn type_must_be_known(span: Span) -> LisetteDiagnostic {
1490 LisetteDiagnostic::error("Uninferrable type")
1491 .with_infer_code("type_not_inferred")
1492 .with_span_label(&span, "cannot be inferred")
1493 .with_help("Add a type annotation to help the compiler infer the type")
1494}
1495
1496pub fn uninferred_binding(name: &str, span: Span) -> LisetteDiagnostic {
1497 LisetteDiagnostic::error("Uninferrable type")
1498 .with_infer_code("type_not_inferred")
1499 .with_span_label(&span, "cannot be inferred")
1500 .with_help(format!(
1501 "Add a type annotation. For example: `let {}: Slice<int> = ...`",
1502 name
1503 ))
1504}
1505
1506pub fn unconstrained_type_param(param_name: &str, span: Span) -> LisetteDiagnostic {
1507 LisetteDiagnostic::error("Unconstrained type parameter")
1508 .with_infer_code("unconstrained_type_param")
1509 .with_span_label(
1510 &span,
1511 format!(
1512 "`{}` is not constrained by parameters or return type",
1513 param_name
1514 ),
1515 )
1516 .with_help(format!(
1517 "Use `{}` in a parameter or return type, or provide an explicit type argument: `func<SomeType>(...)`",
1518 param_name
1519 ))
1520}
1521
1522pub fn slice_index_type_mismatch(index_ty: &Type, span: Span) -> LisetteDiagnostic {
1523 LisetteDiagnostic::error("Type mismatch")
1524 .with_infer_code("slice_index_type_mismatch")
1525 .with_span_label(&span, format!("expected `int`, found `{}`", index_ty))
1526 .with_help(
1527 "Use an integer to index into a `Slice`. For key-value lookup, use a `Map<K, V>`",
1528 )
1529}
1530
1531pub fn only_slices_and_maps_indexable(ty: &Type, span: Span) -> LisetteDiagnostic {
1532 LisetteDiagnostic::error("Not indexable")
1533 .with_infer_code("not_indexable")
1534 .with_span_label(&span, format!("expected `Slice` or `Map`, found `{}`", ty))
1535 .with_help("Only `Slice` and `Map` can be indexed into")
1536}
1537
1538pub fn string_not_indexable(span: Span, receiver: &str) -> LisetteDiagnostic {
1539 LisetteDiagnostic::error("Cannot index into `string`")
1540 .with_infer_code("string_not_indexable")
1541 .with_span_label(&span, "not indexable")
1542 .with_help(format!(
1543 "Use `{receiver}.rune_at(i)` to get a `rune`, or `{receiver}.byte_at(i)` to get a `byte`"
1544 ))
1545}
1546
1547pub fn string_not_sliceable(span: Span, receiver: &str) -> LisetteDiagnostic {
1548 LisetteDiagnostic::error("Cannot slice into `string`")
1549 .with_infer_code("string_not_sliceable")
1550 .with_span_label(&span, "not sliceable")
1551 .with_help(format!(
1552 "Use `{receiver}.substring(a..b)` for a rune-indexed substring, or `{receiver}.bytes()[a..b]` for a range of bytes"
1553 ))
1554}
1555
1556pub fn string_not_iterable(span: Span, receiver: &str) -> LisetteDiagnostic {
1557 LisetteDiagnostic::error("Cannot iterate over `string`")
1558 .with_infer_code("string_not_iterable")
1559 .with_span_label(&span, "not iterable")
1560 .with_help(format!(
1561 "Use `for r in {receiver}.runes()` for code points, or `for b in {receiver}.bytes()` for bytes"
1562 ))
1563}
1564
1565pub fn colon_in_subscript(
1566 span: Span,
1567 receiver: &str,
1568 type_name: Option<&str>,
1569) -> LisetteDiagnostic {
1570 let (message, label, help) = match type_name {
1571 Some("string") => (
1572 "Invalid syntax for string slicing",
1573 "expected a method call",
1574 format!(
1575 "Use `{receiver}.substring(a..b)` for a string, or `{receiver}.bytes()[a..b]` for a range of bytes"
1576 ),
1577 ),
1578 _ => (
1579 "Invalid syntax for subslicing",
1580 "expected `..`",
1581 format!(
1582 "Use `{receiver}[a..b]` or `{receiver}[a..=b]` for an exclusive or inclusive slice, respectively"
1583 ),
1584 ),
1585 };
1586 LisetteDiagnostic::error(message)
1587 .with_parse_code("colon_in_subscript")
1588 .with_span_label(&span, label)
1589 .with_help(help)
1590}
1591
1592pub fn not_callable(
1593 ty: &Type,
1594 callee_name: Option<&str>,
1595 arg_name: Option<&str>,
1596 span: Span,
1597) -> LisetteDiagnostic {
1598 let type_name = ty.get_name();
1599 let is_type_call = matches!((callee_name, type_name), (Some(c), Some(t)) if c == t);
1600 let is_cast_target = ty.get_underlying().is_some()
1601 || type_name.is_some_and(|n| SimpleKind::from_name(n).is_some());
1602
1603 let help = if is_type_call && is_cast_target {
1604 let subject = arg_name.unwrap_or("value");
1605 format!(
1606 "Use `{} as {}` to cast between types",
1607 subject,
1608 type_name.unwrap()
1609 )
1610 } else {
1611 "Only functions can be called with `()`".to_string()
1612 };
1613
1614 LisetteDiagnostic::error("Not callable")
1615 .with_infer_code("not_callable")
1616 .with_span_label(&span, format!("expected function, found `{}`", ty))
1617 .with_help(help)
1618}
1619
1620pub fn type_conversion_arity(
1621 type_name: &str,
1622 actual_count: usize,
1623 span: Span,
1624) -> LisetteDiagnostic {
1625 LisetteDiagnostic::error("Wrong argument count")
1626 .with_infer_code("type_conversion_arity")
1627 .with_span_label(
1628 &span,
1629 format!("expected 1 argument, found {}", actual_count),
1630 )
1631 .with_help(format!(
1632 "Type conversion `{}(value)` takes exactly one argument — the value to convert",
1633 type_name
1634 ))
1635}
1636
1637#[derive(Debug, Clone)]
1638pub struct InterfaceViolation {
1639 pub interface_name: String,
1640 pub parent_of: Option<String>,
1641 pub missing: Vec<(String, Type)>,
1642 pub incompatible: Vec<(String, Type, Type)>,
1643}
1644
1645pub fn interface_not_implemented(
1646 interface_name: &str,
1647 type_name: &str,
1648 violations: &[InterfaceViolation],
1649 span: Span,
1650) -> LisetteDiagnostic {
1651 let mut help_lines = Vec::new();
1652
1653 let mut missing_sections: Vec<(String, Vec<String>)> = Vec::new();
1654 let mut incompatible_sections: Vec<(String, Vec<String>)> = Vec::new();
1655
1656 for violation in violations {
1657 let header = if let Some(ref parent) = violation.parent_of {
1658 format!(
1659 "From `{}` (required by `{}`)",
1660 violation.interface_name, parent
1661 )
1662 } else {
1663 format!("From `{}`", violation.interface_name)
1664 };
1665
1666 if !violation.missing.is_empty() {
1667 let methods: Vec<String> = violation
1668 .missing
1669 .iter()
1670 .map(|(name, sig)| format!(" - {}: {}", name, sig))
1671 .collect();
1672 missing_sections.push((header.clone(), methods));
1673 }
1674
1675 if !violation.incompatible.is_empty() {
1676 let methods: Vec<String> = violation
1677 .incompatible
1678 .iter()
1679 .map(|(name, expected, actual)| {
1680 format!(" - {}: expected `{}`, found `{}`", name, expected, actual)
1681 })
1682 .collect();
1683 incompatible_sections.push((header, methods));
1684 }
1685 }
1686
1687 if !missing_sections.is_empty() {
1688 help_lines.push("Missing methods:".to_string());
1689 for (header, methods) in &missing_sections {
1690 help_lines.push(format!(" {}", header));
1691 for method in methods {
1692 help_lines.push(format!(" {}", method));
1693 }
1694 }
1695 }
1696
1697 if !incompatible_sections.is_empty() {
1698 help_lines.push("Incompatible methods:".to_string());
1699 for (header, methods) in &incompatible_sections {
1700 help_lines.push(format!(" {}", header));
1701 for method in methods {
1702 help_lines.push(format!(" {}", method));
1703 }
1704 }
1705 }
1706
1707 LisetteDiagnostic::error("Interface not implemented")
1708 .with_infer_code("interface_not_implemented")
1709 .with_span_label(
1710 &span,
1711 format!("`{}` does not implement `{}`", type_name, interface_name),
1712 )
1713 .with_help(help_lines.join("\n"))
1714}
1715
1716pub fn pointer_receiver_interface_mismatch(
1717 interface_name: &str,
1718 type_name: &str,
1719 methods: &[String],
1720 span: Span,
1721) -> LisetteDiagnostic {
1722 let methods_str = methods
1723 .iter()
1724 .map(|m| format!("`{}.{}`", type_name, m))
1725 .collect::<Vec<_>>()
1726 .join(", ");
1727 let takes = if methods.len() == 1 {
1728 format!("{} takes `self: Ref<{}>`", methods_str, type_name)
1729 } else {
1730 format!("{} take `self: Ref<{}>`", methods_str, type_name)
1731 };
1732 LisetteDiagnostic::error("Interface not implemented")
1733 .with_infer_code("interface_not_implemented")
1734 .with_span_label(
1735 &span,
1736 format!("`{}` does not implement `{}`", type_name, interface_name),
1737 )
1738 .with_help(format!("{}, so pass a `Ref<{}>`.", takes, type_name))
1739}
1740
1741pub fn unknown_in_bound_position(span: Span) -> LisetteDiagnostic {
1742 LisetteDiagnostic::error("Invalid `Unknown` bound")
1743 .with_infer_code("unknown_in_bound_position")
1744 .with_span_label(&span, "invalid bound")
1745 .with_help("`Unknown` cannot constrain a generic")
1746}
1747
1748pub fn unknown_in_const_annotation(span: Span) -> LisetteDiagnostic {
1749 LisetteDiagnostic::error("Invalid `Unknown` in `const` annotation")
1750 .with_infer_code("unknown_in_const_annotation")
1751 .with_span_label(&span, "invalid annotation")
1752 .with_help("`Unknown` cannot be used to annotate a constant")
1753}
1754
1755pub fn unknown_as_map_key(span: Span) -> LisetteDiagnostic {
1756 LisetteDiagnostic::error("`Unknown` cannot be used as a map key")
1757 .with_infer_code("unknown_as_map_key")
1758 .with_span_label(&span, "key resolves to `any`")
1759 .with_help("Use a concrete comparable key type.")
1760 .with_note("Go's `map[any]V` admits non-comparable runtime values that panic on insertion.")
1761}
1762
1763pub fn opaque_type_outside_typedef(span: Span) -> LisetteDiagnostic {
1764 LisetteDiagnostic::error("Undefined type")
1765 .with_infer_code("undefined_type_outside_typedef")
1766 .with_span_label(&span, "needs a definition")
1767 .with_help("Use `type Point = ...` to define the type.")
1768 .with_note("Opaque declarations are only allowed in `.d.lis` files.")
1769}
1770
1771pub fn bodyless_function_outside_typedef(span: Span) -> LisetteDiagnostic {
1772 LisetteDiagnostic::error("Missing function body")
1773 .with_infer_code("bodyless_function_outside_typedef")
1774 .with_span_label(&span, "needs a body")
1775 .with_help("Add a body: `fn greet() { ... }`.")
1776 .with_note("Bodyless declarations are only allowed in `.d.lis` files.")
1777}
1778
1779pub fn valueless_const_outside_typedef(span: Span) -> LisetteDiagnostic {
1780 LisetteDiagnostic::error("Missing const value")
1781 .with_infer_code("valueless_const_outside_typedef")
1782 .with_span_label(&span, "needs a value")
1783 .with_help("Ensure the constant has a value: `const MAX_SIZE: int = 100`.")
1784 .with_note("Valueless const declarations are only allowed in `.d.lis` files.")
1785}
1786
1787pub fn valueless_const_missing_annotation(span: Span) -> LisetteDiagnostic {
1788 LisetteDiagnostic::error("Missing const annotation")
1789 .with_infer_code("valueless_const_missing_annotation")
1790 .with_span_label(&span, "needs a type annotation")
1791 .with_help("Valueless const declarations require a type annotation: `const MAX_SIZE: int`")
1792}
1793
1794pub fn variable_declaration_outside_typedef(span: Span) -> LisetteDiagnostic {
1795 LisetteDiagnostic::error("Invalid variable declaration")
1796 .with_infer_code("variable_declaration_outside_typedef")
1797 .with_span_label(&span, "`var` is not allowed here")
1798 .with_help("Use `let` to declare a variable: `let x: int = 0`.")
1799 .with_note("`var` declarations are only allowed in `.d.lis` files.")
1800}
1801
1802pub fn range_full_not_valid_expression(span: Span) -> LisetteDiagnostic {
1803 LisetteDiagnostic::error("Invalid expression")
1804 .with_infer_code("range_full_not_expression")
1805 .with_span_label(&span, "`..` can only be used in slice indexing")
1806 .with_help("Use `arr[..]` to get a full slice, or provide bounds like `0..10`")
1807}
1808
1809pub fn range_not_iterable(range_type: &str, span: Span) -> LisetteDiagnostic {
1810 LisetteDiagnostic::error("Not iterable")
1811 .with_infer_code("range_not_iterable")
1812 .with_span_label(&span, format!("`{}` has no start bound", range_type))
1813 .with_help("Use a range with a start bound, e.g. `0..10` instead of `..10`")
1814}
1815
1816pub fn taking_value_of_ufcs_method(span: Span) -> LisetteDiagnostic {
1817 LisetteDiagnostic::error("Invalid method value")
1818 .with_infer_code("taking_value_of_ufcs_method")
1819 .with_span_label(&span, "taking value not allowed")
1820 .with_help(
1821 "This method cannot be taken as a value. Call the method directly: `obj.method(...)`",
1822 )
1823}
1824
1825pub fn duplicate_definition(kind: &str, name: &str, span: Span) -> LisetteDiagnostic {
1826 LisetteDiagnostic::error(format!("Duplicate {}", kind))
1827 .with_infer_code("duplicate_definition")
1828 .with_span_label(&span, "already defined")
1829 .with_help(format!(
1830 "`{}` is already defined in this module. Rename or remove this definition.",
1831 name
1832 ))
1833}
1834
1835pub fn duplicate_impl_item(item_name: &str, type_name: &str, span: Span) -> LisetteDiagnostic {
1836 LisetteDiagnostic::error("Duplicate name in impl")
1837 .with_infer_code("duplicate_impl_item")
1838 .with_span_label(&span, "method name already taken")
1839 .with_help(format!(
1840 "Method `{}` is already defined for type `{}`. Rename one of the methods.",
1841 item_name, type_name
1842 ))
1843}
1844
1845pub fn duplicate_method_across_specialized_impls(
1846 method_name: &str,
1847 type_name: &str,
1848 generics: &[String],
1849 span: Span,
1850) -> LisetteDiagnostic {
1851 let params = generics.join(", ");
1852 LisetteDiagnostic::error("Duplicate method across specialized `impl` blocks")
1853 .with_infer_code("duplicate_method_across_specialized_impls")
1854 .with_span_label(&span, "already defined in another specialization")
1855 .with_help(format!(
1856 "Specialized `impl` blocks for `{type_name}` share a method namespace. \
1857 Use different method names, or move `{method_name}` to a generic `impl<{params}> {type_name}<{params}> {{}}` block."
1858 ))
1859}
1860
1861pub fn method_shadows_field(type_name: &str, field_name: &str, span: Span) -> LisetteDiagnostic {
1862 LisetteDiagnostic::error("Method shadows struct field")
1863 .with_infer_code("method_shadows_field")
1864 .with_span_label(&span, "same as field")
1865 .with_help(format!(
1866 "`{}` has a field `{}` and a method `{}`. Rename either the field or the method",
1867 type_name, field_name, field_name
1868 ))
1869}
1870
1871pub fn non_int_range_not_iterable(element_ty: &Type, span: Span) -> LisetteDiagnostic {
1872 LisetteDiagnostic::error("Not iterable")
1873 .with_infer_code("non_int_range_not_iterable")
1874 .with_span_label(
1875 &span,
1876 format!("cannot iterate over `Range<{}>`", element_ty),
1877 )
1878 .with_help("Range iteration requires integer bounds")
1879}
1880
1881pub fn only_slices_indexable_by_range(ty: &Type, span: Span) -> LisetteDiagnostic {
1882 LisetteDiagnostic::error("Type mismatch")
1883 .with_infer_code("range_index_not_slice")
1884 .with_span_label(
1885 &span,
1886 format!("expected `Slice` or `string`, found `{}`", ty),
1887 )
1888 .with_help("Range indexing only works on `Slice` and `string`")
1889}
1890
1891pub fn empty_body_return_mismatch(expected_ty: &Type, span: Span) -> LisetteDiagnostic {
1892 LisetteDiagnostic::error("Type mismatch")
1893 .with_infer_code("type_mismatch")
1894 .with_span_label(
1895 &span,
1896 format!("promises `{}`, but returns `()`", expected_ty),
1897 )
1898 .with_help("Return a value or change the return type annotation to `()`.")
1899 .with_note("An empty function body implicitly returns `()`.")
1900}
1901
1902fn operator_verb(operator: &BinaryOperator) -> &'static str {
1903 match operator {
1904 BinaryOperator::Addition => "add",
1905 BinaryOperator::Subtraction => "subtract",
1906 BinaryOperator::Multiplication => "multiply",
1907 BinaryOperator::Division => "divide",
1908 BinaryOperator::Remainder => "get remainder of",
1909 BinaryOperator::Equal | BinaryOperator::NotEqual => "compare",
1910 BinaryOperator::LessThan
1911 | BinaryOperator::LessThanOrEqual
1912 | BinaryOperator::GreaterThan
1913 | BinaryOperator::GreaterThanOrEqual => "compare",
1914 BinaryOperator::And | BinaryOperator::Or => "apply logical operator to",
1915 BinaryOperator::Pipeline => "pipe",
1916 }
1917}
1918
1919fn operator_help(op: &BinaryOperator) -> &'static str {
1920 match op {
1921 BinaryOperator::Addition => "requires both operands to have the same type",
1922 BinaryOperator::Subtraction
1923 | BinaryOperator::Multiplication
1924 | BinaryOperator::Division
1925 | BinaryOperator::Remainder => "requires both operands to have the same numeric type",
1926 BinaryOperator::Equal | BinaryOperator::NotEqual => {
1927 "requires both operands to have the same type"
1928 }
1929 BinaryOperator::LessThan
1930 | BinaryOperator::LessThanOrEqual
1931 | BinaryOperator::GreaterThan
1932 | BinaryOperator::GreaterThanOrEqual => "requires both operands to have the same type",
1933 BinaryOperator::And | BinaryOperator::Or => "requires both operands to be bool",
1934 BinaryOperator::Pipeline => "should have been desugared",
1935 }
1936}
1937
1938pub fn task_in_expression_position(span: Span) -> LisetteDiagnostic {
1939 LisetteDiagnostic::error("Invalid `task`")
1940 .with_infer_code("task_in_expression_position")
1941 .with_span_label(&span, "produces no value")
1942 .with_help("Move `task` to its own statement")
1943}
1944
1945pub fn defer_in_expression_position(span: Span) -> LisetteDiagnostic {
1946 LisetteDiagnostic::error("Invalid `defer`")
1947 .with_infer_code("defer_in_expression_position")
1948 .with_span_label(&span, "produces no value")
1949 .with_help("Move `defer` to its own statement")
1950}
1951
1952pub fn non_addressable_expression(expression_kind: &str, span: Span) -> LisetteDiagnostic {
1953 LisetteDiagnostic::error("Non-addressable expression")
1954 .with_infer_code("non_addressable_expression")
1955 .with_span_label(&span, format!("cannot take address of {}", expression_kind))
1956 .with_help("Assign the value to a variable first, then take its address")
1957}
1958
1959pub fn non_addressable_const(span: Span) -> LisetteDiagnostic {
1960 LisetteDiagnostic::error("Cannot take address of `const`")
1961 .with_infer_code("non_addressable_const")
1962 .with_span_label(&span, "not addressable")
1963 .with_help(
1964 "`const` bindings are not addressable. Copy the value into a local `let` first if you need a reference",
1965 )
1966}
1967
1968pub fn non_addressable_assignment(expression_kind: &str, span: Span) -> LisetteDiagnostic {
1969 LisetteDiagnostic::error("Cannot assign to non-addressable expression")
1970 .with_infer_code("non_addressable_assignment")
1971 .with_span_label(&span, format!("cannot assign to {}", expression_kind))
1972 .with_help("Assign the value to a variable first, then modify it")
1973}
1974
1975pub fn newtype_field_assignment(type_name: &str, span: Span) -> LisetteDiagnostic {
1976 LisetteDiagnostic::error("Cannot assign to newtype field")
1977 .with_infer_code("newtype_field_assignment")
1978 .with_span_label(&span, "newtype fields are read-only")
1979 .with_help(format!(
1980 "Reconstruct the newtype: `variable = {type_name}(new_value)`"
1981 ))
1982}
1983
1984pub fn complex_select_expression(span: Span) -> LisetteDiagnostic {
1985 LisetteDiagnostic::error("Complex expression in `select` arm")
1986 .with_infer_code("complex_select_expression")
1987 .with_span_label(&span, "expected simple expression")
1988 .with_help("Hoist to a `let` binding before the `select`")
1989}
1990
1991pub fn ref_slice_append(span: Span) -> LisetteDiagnostic {
1992 LisetteDiagnostic::error("Cannot call append/extend on `Ref<Slice>`")
1993 .with_infer_code("ref_slice_append")
1994 .with_span_label(&span, "dereference the ref first")
1995 .with_help("Use `r.*.append(x)` to deref, then append")
1996}
1997
1998pub fn map_field_chain_assignment(span: Span) -> LisetteDiagnostic {
1999 LisetteDiagnostic::error("Cannot assign to field of map entry")
2000 .with_infer_code("map_field_chain_assignment")
2001 .with_span_label(&span, "assignment not allowed here")
2002 .with_help(
2003 "Extract, modify, and reinsert: `let mut entry = m[key]; entry.field = value; m[key] = entry`",
2004 )
2005}
2006
2007pub fn enum_field_type_conflict(
2008 loc_a: &str,
2009 type_a: &str,
2010 loc_b: &str,
2011 type_b: &str,
2012 span: Span,
2013) -> LisetteDiagnostic {
2014 LisetteDiagnostic::error("Conflicting field types across enum variants")
2015 .with_infer_code("enum_field_type_conflict")
2016 .with_span_label(&span, "field type mismatch")
2017 .with_help(format!(
2018 "`{loc_a}` is `{type_a}` but `{loc_b}` is `{type_b}`. Rename one of the fields or align their types",
2019 ))
2020}
2021
2022pub fn cannot_auto_address_receiver(
2023 receiver_kind: &str,
2024 method_name: &str,
2025 expected_ty: &Type,
2026 actual_ty: &Type,
2027 span: Span,
2028) -> LisetteDiagnostic {
2029 let readable_kind = match receiver_kind {
2030 "map index expression" => "map lookup",
2031 "function call" => "function result",
2032 "literal" => "literal",
2033 "binary expression" => "expression result",
2034 "conditional expression" => "conditional result",
2035 "match expression" => "match result",
2036 "block expression" => "block result",
2037 "lambda" => "lambda",
2038 "tuple" => "tuple",
2039 "range expression" => "range expression",
2040 _ => "expression",
2041 };
2042
2043 LisetteDiagnostic::error("Expression not modifiable")
2044 .with_infer_code("cannot_auto_address_receiver")
2045 .with_span_label(&span, "modifies its receiver")
2046 .with_help(format!(
2047 "Assign the {} to a variable first, then call the method. The receiver of `{}` is `{}`, not `{}`",
2048 readable_kind, method_name, expected_ty, actual_ty
2049 ))
2050}
2051
2052pub fn break_value_in_non_loop(span: Span) -> LisetteDiagnostic {
2053 LisetteDiagnostic::error("`break` with value in non-`loop` loop")
2054 .with_infer_code("break_value_in_non_loop")
2055 .with_span_label(&span, "`break` with value only allowed in `loop`")
2056 .with_help("`break` with a value is only meaningful in `loop` expressions, which can return the value. In `for` and `while` loops, use `break` without a value.")
2057}
2058
2059pub fn defer_in_loop(span: Span) -> LisetteDiagnostic {
2060 LisetteDiagnostic::error("`defer` inside loop")
2061 .with_infer_code("defer_in_loop")
2062 .with_span_label(&span, "not allowed inside loop")
2063 .with_help("Wrap the loop body in a helper function, e.g. `fn process(file: File) { defer file.close(); ... }` and call it in the loop: `for f in files { process(f); }`")
2064}
2065
2066pub fn propagate_in_condition(span: Span) -> LisetteDiagnostic {
2067 LisetteDiagnostic::error("`?` cannot be used inside a condition")
2068 .with_infer_code("propagate_in_condition")
2069 .with_span_label(&span, "`?` inside condition")
2070 .with_help("Bind the result first: `let val = expression?; if val { ... }`")
2071}
2072
2073pub fn propagate_in_defer(span: Span) -> LisetteDiagnostic {
2074 LisetteDiagnostic::error("Invalid `?` in `defer`")
2075 .with_infer_code("propagate_in_defer")
2076 .with_span_label(&span, "`?` not allowed here")
2077 .with_help("`defer` in combination with `?` is not allowed due to confusing semantics. Handle the error inside a `defer` block: `defer { if let Err(e) = file.close() { log(e); } }`")
2078}
2079
2080pub fn return_in_defer_block(span: Span) -> LisetteDiagnostic {
2081 LisetteDiagnostic::error("`return` in `defer` block")
2082 .with_infer_code("return_in_defer_block")
2083 .with_span_label(&span, "not allowed inside `defer` block")
2084 .with_help("Remove the `return` as it only exits the `defer` block")
2085}
2086
2087pub fn break_in_defer_block(span: Span) -> LisetteDiagnostic {
2088 LisetteDiagnostic::error("`break` in `defer` block")
2089 .with_infer_code("break_in_defer_block")
2090 .with_span_label(&span, "not allowed inside `defer` block")
2091 .with_help("Remove the `break`, or move it inside a loop within the `defer` block")
2092}
2093
2094pub fn continue_in_defer_block(span: Span) -> LisetteDiagnostic {
2095 LisetteDiagnostic::error("`continue` in `defer` block")
2096 .with_infer_code("continue_in_defer_block")
2097 .with_span_label(&span, "not allowed inside `defer` block")
2098 .with_help("Remove the `continue`, or move it inside a loop within the `defer` block")
2099}
2100
2101pub fn invalid_cast(source_ty: &Type, target_ty: &Type, span: Span) -> LisetteDiagnostic {
2102 let same_constructor_with_unresolved = source_ty
2103 .get_qualified_id()
2104 .zip(target_ty.get_qualified_id())
2105 .is_some_and(|(s, t)| s == t)
2106 && source_ty.has_unbound_variables();
2107
2108 let help = if same_constructor_with_unresolved {
2109 format!(
2110 "Use a type annotation instead: `let x: {} = ...`",
2111 target_ty,
2112 )
2113 } else if source_ty.is_string() {
2114 "Strings cannot be cast to numbers and require explicit conversion. Use `strconv.Atoi()` to parse.".into()
2115 } else if source_ty.is_complex() || target_ty.is_complex() {
2116 "Complex numbers cannot be cast directly. Use `real(c)` or `imaginary(c)` to extract components.".into()
2117 } else if source_ty.has_underlying_rune() && target_ty.has_underlying_byte() {
2118 "rune (int32) is wider than byte (uint8) and may not fit. Use an intermediate variable to cast via int first: `let n = r as int; n as byte`".into()
2119 } else if source_ty.has_underlying_byte() && target_ty.is_string() {
2120 "A byte has two readings as a string. Use `[b] as string` to preserve the byte (may be invalid UTF-8), or cast through a rune to encode as a codepoint: `let r = b as rune; r as string`".into()
2121 } else {
2122 "Casts are supported between numeric types, between string and byte/rune slices, from rune to string, and from concrete types to interfaces.".into()
2123 };
2124
2125 LisetteDiagnostic::error("Invalid cast")
2126 .with_infer_code("invalid_cast")
2127 .with_span_label(
2128 &span,
2129 format!("cannot cast `{}` to `{}`", source_ty, target_ty),
2130 )
2131 .with_help(help)
2132}
2133
2134pub fn chained_cast(span: Span) -> LisetteDiagnostic {
2135 LisetteDiagnostic::error("Invalid cast")
2136 .with_infer_code("chained_cast")
2137 .with_span_label(&span, "chained cast not allowed")
2138 .with_help("Use an intermediate variable if you need to cast through multiple types")
2139}
2140
2141pub fn redundant_cast(ty: &Type, span: Span) -> LisetteDiagnostic {
2142 LisetteDiagnostic::warn("Redundant cast")
2143 .with_infer_code("redundant_cast")
2144 .with_span_label(&span, format!("casting `{}` to itself has no effect", ty))
2145 .with_help("Remove the unnecessary cast")
2146}
2147
2148pub fn integer_literal_overflow(
2149 target_ty: &str,
2150 min: i128,
2151 max: i128,
2152 span: Span,
2153) -> LisetteDiagnostic {
2154 LisetteDiagnostic::error("Integer literal overflow")
2155 .with_infer_code("integer_literal_overflow")
2156 .with_span_label(&span, format!("overflows `{}`", target_ty))
2157 .with_help(format!(
2158 "`{}` must be in range `{}` to `{}`",
2159 target_ty, min, max
2160 ))
2161}
2162
2163pub fn float_literal_overflow(target_ty: &str, span: Span) -> LisetteDiagnostic {
2164 LisetteDiagnostic::error("Float literal overflow")
2165 .with_infer_code("float_literal_overflow")
2166 .with_span_label(&span, format!("value overflows `{}`", target_ty))
2167 .with_help(format!(
2168 "Use `float64` for larger values, or ensure the value fits in `{}`",
2169 target_ty
2170 ))
2171}
2172
2173pub fn cannot_negate_unsigned(target_ty: &str, span: Span) -> LisetteDiagnostic {
2174 LisetteDiagnostic::error("Cannot negate unsigned type")
2175 .with_infer_code("cannot_negate_unsigned")
2176 .with_span_label(&span, format!("cannot negate `{}`", target_ty))
2177 .with_help("Unsigned types cannot represent negative values")
2178}
2179
2180fn go_builtin_hint(name: &str) -> Option<&'static str> {
2181 match name {
2182 "len" => Some(
2183 "Lisette has no `len` builtin. Use the `.length()` method instead, e.g. `items.length()`.",
2184 ),
2185 "cap" => Some(
2186 "Lisette has no `cap` builtin. Use the `.capacity()` method instead, e.g. `items.capacity()`.",
2187 ),
2188 "make" => Some(
2189 "Lisette has no `make` builtin. Use constructor methods instead, e.g. `Channel.new<int>()`, `Slice.new<int>()`, `Map.new<K, V>()`.",
2190 ),
2191 "append" => Some(
2192 "Lisette has no `append` builtin. Use the `.append()` method instead, e.g. `items.append(1)`.",
2193 ),
2194 "close" => Some(
2195 "Lisette has no `close` builtin. Use the `.close()` method instead, e.g. `ch.close()`.",
2196 ),
2197 "copy" => Some(
2198 "Lisette has no `copy` builtin. Use the `.copy_from()` method instead, e.g. `dst.copy_from(src)`.",
2199 ),
2200 "delete" => Some(
2201 "Lisette has no `delete` builtin. Use the `.delete()` method instead, e.g. `map.delete(key)`.",
2202 ),
2203 "new" => Some(
2204 "Lisette has no `new` builtin. Use constructor methods instead, e.g. `MyStruct { field: value }` or `MyType.new()`.",
2205 ),
2206 "print" | "println" | "printf" => Some(
2207 "Lisette has no `print` builtin. Use `fmt.Println`, `fmt.Printf`, etc. after `import \"go:fmt\"`.",
2208 ),
2209 _ => None,
2210 }
2211}
2212
2213pub fn levenshtein_distance(a: &str, b: &str) -> usize {
2214 let b_len = b.len();
2215
2216 if a.is_empty() {
2217 return b_len;
2218 }
2219 if b_len == 0 {
2220 return a.len();
2221 }
2222
2223 let mut prev: Vec<usize> = (0..=b_len).collect();
2224 let mut curr = vec![0; b_len + 1];
2225
2226 for (i, a_char) in a.chars().enumerate() {
2227 curr[0] = i + 1;
2228 for (j, b_char) in b.chars().enumerate() {
2229 let cost = if a_char == b_char { 0 } else { 1 };
2230 curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
2231 }
2232 std::mem::swap(&mut prev, &mut curr);
2233 }
2234
2235 prev[b_len]
2236}
2237
2238pub fn find_similar_name(name: &str, candidates: &[String]) -> Option<String> {
2241 let best_distance = candidates
2242 .iter()
2243 .filter_map(|c| {
2244 let d = levenshtein_distance(name, c);
2245 (d <= 2).then_some((c, d))
2246 })
2247 .min_by_key(|(_, d)| *d);
2248
2249 let by_prefix = if name.len() >= 2 {
2250 candidates
2251 .iter()
2252 .filter(|c| c.starts_with(name) || name.starts_with(c.as_str()))
2253 .min_by_key(|c| c.len().abs_diff(name.len()))
2254 } else {
2255 None
2256 };
2257
2258 match (best_distance, by_prefix) {
2259 (Some((d, dist)), Some(p)) => {
2260 if dist <= 1 {
2263 Some(d.clone())
2264 } else {
2265 Some(p.clone())
2266 }
2267 }
2268 (Some((d, _)), None) => Some(d.clone()),
2269 (None, Some(p)) => Some(p.clone()),
2270 (None, None) => None,
2271 }
2272}
2273
2274pub fn cannot_infer_type_argument(span: Span) -> LisetteDiagnostic {
2275 LisetteDiagnostic::error("Missing type argument")
2276 .with_infer_code("missing_type_argument")
2277 .with_span_label(&span, "expected type argument")
2278 .with_help("Supply a type argument for the call, e.g. `Channel.new<int>()`")
2279}
2280
2281fn format_list<T, F>(items: &[T], fmt: F) -> String
2282where
2283 F: Fn(&T) -> String,
2284{
2285 match items.len() {
2286 0 => String::new(),
2287 1 => fmt(&items[0]),
2288 2 => format!("{} and {}", fmt(&items[0]), fmt(&items[1])),
2289 _ => {
2290 let mut result = String::new();
2291 for (i, item) in items.iter().enumerate() {
2292 if i > 0 {
2293 result.push_str(", ");
2294 }
2295 if i == items.len() - 1 {
2296 result.push_str("and ");
2297 }
2298 result.push_str(&fmt(item));
2299 }
2300 result
2301 }
2302 }
2303}
2304
2305pub fn recursive_generic_instantiation(type_name: &str, span: Span) -> LisetteDiagnostic {
2306 LisetteDiagnostic::error("Recursive generic instantiation")
2307 .with_infer_code("recursive_instantiation")
2308 .with_span_label(&span, format!("`{}` is nested within itself", type_name))
2309 .with_help(format!(
2310 "Go does not allow recursive type instantiation (e.g., `{0}<{0}<T>>`). \
2311 Use a wrapper type or a different design.",
2312 type_name
2313 ))
2314}
2315
2316pub fn non_comparable_map_key(key_ty: &Type, reason: &str, span: Span) -> LisetteDiagnostic {
2317 LisetteDiagnostic::error("Invalid map key type")
2318 .with_infer_code("non_comparable_map_key")
2319 .with_span_label(&span, format!("`{}` is not comparable", key_ty))
2320 .with_help(format!(
2321 "Map keys must be comparable in Go. {} cannot be used as map keys.",
2322 reason
2323 ))
2324}
2325
2326pub fn ref_of_interface_type(inner_ty: &Type, span: Span) -> LisetteDiagnostic {
2327 LisetteDiagnostic::error("Invalid use of `Ref` with interface")
2328 .with_infer_code("ref_of_interface")
2329 .with_span_label(&span, "not allowed")
2330 .with_help(format!(
2331 "Use `{}` instead of `Ref<{}>`. Interfaces are already reference types in Go.",
2332 inner_ty, inner_ty
2333 ))
2334}
2335
2336pub fn float_modulo_not_supported(span: Span) -> LisetteDiagnostic {
2337 LisetteDiagnostic::error("Invalid operation")
2338 .with_infer_code("float_modulo")
2339 .with_span_label(&span, "`%` is not supported on floating-point types")
2340 .with_help("Use `math.Mod(x, y)` for floating-point modulo")
2341}
2342
2343pub fn recursive_type(type_name: &str, span: Span) -> LisetteDiagnostic {
2344 LisetteDiagnostic::error("Recursive type has infinite size")
2345 .with_infer_code("recursive_type")
2346 .with_span_label(
2347 &span,
2348 format!("`{}` contains itself without indirection", type_name),
2349 )
2350 .with_help(format!(
2351 "Use `Ref<{}>` for indirection. For example: `next: Option<Ref<{}>>`",
2352 type_name, type_name
2353 ))
2354}
2355
2356pub fn interface_self_embedding(interface_name: &str, span: Span) -> LisetteDiagnostic {
2357 LisetteDiagnostic::error("Recursive interface embedding")
2358 .with_infer_code("interface_cycle")
2359 .with_span_label(&span, format!("`{}` embeds itself", interface_name))
2360 .with_help("An interface cannot embed itself. Remove the self-referencing `impl`.")
2361}
2362
2363pub fn interface_embedding_cycle(cycle: &[String], span: Span) -> LisetteDiagnostic {
2364 let cycle_str = cycle.join(" → ");
2365 LisetteDiagnostic::error("Recursive interface embedding")
2366 .with_infer_code("interface_cycle")
2367 .with_span_label(&span, "creates a cycle")
2368 .with_help(format!(
2369 "Interface embedding cycle detected: {}. Break the cycle by removing one of the embeddings.",
2370 cycle_str
2371 ))
2372}
2373
2374pub fn interface_method_conflict(
2375 interface_name: &str,
2376 method_name: &str,
2377 parent1: &str,
2378 parent2: &str,
2379 span: Span,
2380) -> LisetteDiagnostic {
2381 LisetteDiagnostic::error("Conflicting method signatures")
2382 .with_infer_code("interface_method_conflict")
2383 .with_span_label(&span, format!("duplicate method `{}`", method_name))
2384 .with_help(format!(
2385 "Interface `{}` inherits conflicting definitions of `{}` from `{}` and `{}`. \
2386 Rename one of the methods or remove one of the embeddings.",
2387 interface_name, method_name, parent1, parent2
2388 ))
2389}
2390
2391pub fn impl_on_foreign_type(type_name: &str, module_name: &str, span: Span) -> LisetteDiagnostic {
2392 LisetteDiagnostic::error("Cannot implement methods on foreign type")
2393 .with_infer_code("impl_on_foreign_type")
2394 .with_span_label(
2395 &span,
2396 format!("`{}` is defined in module `{}`", type_name, module_name),
2397 )
2398 .with_help(format!(
2399 "Methods can only be defined on types in the same module. \
2400 Use a standalone function instead: `fn my_method(w: {}) {{ ... }}`",
2401 type_name
2402 ))
2403}
2404
2405pub fn impl_on_type_alias(_type_name: &str, span: Span) -> LisetteDiagnostic {
2406 LisetteDiagnostic::error("Cannot implement methods on type alias")
2407 .with_infer_code("impl_on_type_alias")
2408 .with_span_label(&span, "type alias")
2409 .with_help(
2410 "A type alias cannot carry its own methods. Either add methods to the underlying \
2411 type directly or define a tuple struct instead",
2412 )
2413}
2414
2415pub fn prelude_type_shadowed(name: &str, span: Span) -> LisetteDiagnostic {
2416 LisetteDiagnostic::error("Cannot shadow prelude type")
2417 .with_infer_code("prelude_type_shadowed")
2418 .with_span_label(&span, format!("`{}` is a prelude type", name))
2419 .with_help(format!(
2420 "Choose a different name — `{}` is defined in the prelude and cannot be redefined",
2421 name
2422 ))
2423}
2424
2425pub fn prelude_function_shadowed(name: &str, span: Span) -> LisetteDiagnostic {
2426 LisetteDiagnostic::error("Cannot shadow prelude function")
2427 .with_infer_code("prelude_function_shadowed")
2428 .with_span_label(&span, format!("`{}` is a prelude function", name))
2429 .with_help(format!(
2430 "Choose a different name — `{}` is defined in the prelude and cannot be redefined",
2431 name
2432 ))
2433}
2434
2435pub fn non_pub_interface_with_pub_impl(
2436 interface_name: &str,
2437 struct_name: &str,
2438 span: Span,
2439) -> LisetteDiagnostic {
2440 LisetteDiagnostic::error("Visibility mismatch in interface implementation")
2441 .with_infer_code("non_pub_interface_pub_impl")
2442 .with_span_label(
2443 &span,
2444 "has public methods, but interface is private",
2445 )
2446 .with_help(format!(
2447 "`{}` implements public methods for the private interface `{}`. Either make the interface `pub`, or remove `pub` from the struct methods",
2448 struct_name, interface_name
2449 ))
2450}
2451
2452pub fn missing_constraint_on_generic_return_type(
2453 fn_name: &str,
2454 param_name: &str,
2455 constraint: &Type,
2456 span: Span,
2457) -> LisetteDiagnostic {
2458 LisetteDiagnostic::error("Missing constraint on generic return type")
2459 .with_infer_code("missing_constraint_on_return_type")
2460 .with_span_label(
2461 &span,
2462 format!("expected `{}` to be constrained", param_name),
2463 )
2464 .with_help(
2465 format!(
2466 "Constrain the generic: `{}<{}: {}>()`",
2467 fn_name, param_name, constraint
2468 ) + ". The function returns a type whose methods depend on the constraint",
2469 )
2470}
2471
2472pub fn panic_in_expression_position(span: Span) -> LisetteDiagnostic {
2473 LisetteDiagnostic::error("`panic()` used as a value")
2474 .with_infer_code("panic_in_expression_position")
2475 .with_span_label(&span, "disallowed")
2476 .with_help("`panic()` can only be used in statement position, not assigned to a variable or passed as an argument")
2477}
2478
2479pub fn specialized_impl_cannot_satisfy_interface(
2480 struct_name: &str,
2481 interface_name: &str,
2482 method_name: &str,
2483 generics: &[String],
2484 span: Span,
2485) -> LisetteDiagnostic {
2486 let params = generics.join(", ");
2487 LisetteDiagnostic::error("Specialized impl cannot satisfy interface")
2488 .with_infer_code("specialized_impl_cannot_satisfy_interface")
2489 .with_span_label(
2490 &span,
2491 format!(
2492 "`{}` on `{}` cannot satisfy `{}`",
2493 method_name, struct_name, interface_name
2494 ),
2495 )
2496 .with_help(format!(
2497 "Methods in specialized `impl` blocks cannot satisfy interfaces. \
2498 Move `{}` to a generic `impl` block: `impl<{params}> {}<{params}> {{}}`",
2499 method_name, struct_name
2500 ))
2501}
2502
2503pub enum NativeMethodForm {
2504 Instance,
2505 Static,
2506}
2507
2508pub fn native_method_value(method: &str, form: NativeMethodForm, span: Span) -> LisetteDiagnostic {
2509 let help = match form {
2510 NativeMethodForm::Instance => format!(
2511 "Call it directly: `receiver.{method}()`. To use it as a value, wrap in a closure: `|args| receiver.{method}(args)`"
2512 ),
2513 NativeMethodForm::Static => {
2514 format!("Use a closure instead: `|args| receiver.{method}(args)`")
2515 }
2516 };
2517 LisetteDiagnostic::error("Cannot use native method as a value")
2518 .with_infer_code("native_method_value")
2519 .with_span_label(&span, "native methods must be called directly")
2520 .with_help(help)
2521}
2522
2523pub fn native_constructor_value(name: &str, span: Span) -> LisetteDiagnostic {
2524 LisetteDiagnostic::error("Cannot use native constructor as a value")
2525 .with_infer_code("native_constructor_value")
2526 .with_span_label(&span, "native constructors must be called directly")
2527 .with_help(format!("Use a closure instead: `|args| {name}(args)`"))
2528}
2529
2530pub fn enum_variant_constructor_value(name: &str, span: Span) -> LisetteDiagnostic {
2531 LisetteDiagnostic::error("Cannot use enum variant as value")
2532 .with_infer_code("enum_variant_constructor_value")
2533 .with_span_label(&span, "used as value")
2534 .with_help(format!(
2535 "Instantiate the variant: `{name} {{ field: value, ... }}`"
2536 ))
2537}
2538
2539pub fn record_struct_value(name: &str, span: Span) -> LisetteDiagnostic {
2540 LisetteDiagnostic::error("Cannot use struct type as a value")
2541 .with_infer_code("record_struct_value")
2542 .with_span_label(&span, "struct types cannot be used as expressions")
2543 .with_help(format!(
2544 "Use a struct literal instead: `{name} {{ field: value, ... }}`"
2545 ))
2546}
2547
2548pub fn private_method_expression(span: Span) -> LisetteDiagnostic {
2549 LisetteDiagnostic::error("Cannot use private method as a value")
2550 .with_infer_code("private_method_expression")
2551 .with_span_label(&span, "private methods must be called directly")
2552 .with_help("Use a closure instead: `|self_, args| self_.method(args)`")
2553}
2554
2555pub fn float_literal_int_cast(span: Span) -> LisetteDiagnostic {
2556 LisetteDiagnostic::error("Cannot cast float literal to integer directly")
2557 .with_infer_code("float_literal_int_cast")
2558 .with_span_label(&span, "unsupported cast")
2559 .with_help("Bind to a variable first: `let f = 1.0; f as int`")
2560}
2561
2562pub fn const_requires_simple_expression(span: Span) -> LisetteDiagnostic {
2563 LisetteDiagnostic::error("`const` requires a simple expression")
2564 .with_infer_code("const_requires_simple_expression")
2565 .with_span_label(&span, "expected literal or simple expression")
2566 .with_help("Use `let` for computed values")
2567}
2568
2569pub fn complex_sub_expression(span: Span) -> LisetteDiagnostic {
2570 LisetteDiagnostic::error("Complex expression used as sub-expression")
2571 .with_infer_code("complex_sub_expression")
2572 .with_span_label(&span, "expected simple expression")
2573 .with_help("Hoist to a `let` binding")
2574}
2575
2576pub fn reference_through_newtype(span: Span) -> LisetteDiagnostic {
2577 LisetteDiagnostic::error("Cannot take reference through newtype boundary")
2578 .with_infer_code("reference_through_newtype")
2579 .with_span_label(&span, "newtype `.0` inside `&`")
2580 .with_help("Bind the inner value first: `let inner = val.0; &inner`")
2581}
2582
2583pub fn immutable_argument_to_mut_param(
2584 var_name: &str,
2585 callee_label: &str,
2586 span: Span,
2587) -> LisetteDiagnostic {
2588 let help = format!(
2589 "{callee_label} may mutate `{var_name}`, so declare it mutable using `let mut {var_name} = ...`."
2590 );
2591 LisetteDiagnostic::error("Immutable argument passed to `mut` parameter")
2592 .with_infer_code("immutable_arg_to_mut_param")
2593 .with_span_label(&span, "expected mutable, found immutable")
2594 .with_help(help)
2595}
2596
2597pub fn failure_propagation_in_expression(span: Span) -> LisetteDiagnostic {
2598 LisetteDiagnostic::error("Failure propagation in expression position")
2599 .with_infer_code("failure_propagation_in_expression")
2600 .with_span_label(
2601 &span,
2602 "`Err(..)?` and `None?` always early-return and never produce a value",
2603 )
2604 .with_help("Use `return Err(..)` or `return None` instead")
2605}
2606
2607pub fn never_call_in_expression(span: Span) -> LisetteDiagnostic {
2608 LisetteDiagnostic::error("Never-returning call in expression position")
2609 .with_infer_code("never_call_in_expression")
2610 .with_span_label(&span, "`panic` never returns and cannot produce a value")
2611 .with_help("Use `panic(...)` as a statement instead")
2612}
2613
2614pub fn invalid_main_signature(span: Span) -> LisetteDiagnostic {
2615 LisetteDiagnostic::error("Invalid main signature")
2616 .with_infer_code("invalid_main_signature")
2617 .with_span_label(&span, "`main` must have no parameters and no return type")
2618 .with_help(
2619 "Use `fn main() { ... }`. To handle errors, use `match` or `if let` \
2620 inside main instead of returning `Result`.",
2621 )
2622}
2623
2624pub fn parenthesized_qualifier(path: &str, member: &str, span: Span) -> LisetteDiagnostic {
2625 LisetteDiagnostic::error("Unnecessary parentheses around qualifier")
2626 .with_infer_code("parenthesized_qualifier")
2627 .with_span_label(&span, "parenthesized qualifier")
2628 .with_help(format!("Remove the parentheses: `{}.{}`", path, member))
2629}
2630
2631pub fn type_alias_as_qualifier(
2632 alias: &str,
2633 underlying: &str,
2634 member: &str,
2635 span: Span,
2636) -> LisetteDiagnostic {
2637 LisetteDiagnostic::error("Cannot use generic type alias as qualifier")
2638 .with_infer_code("type_alias_as_qualifier")
2639 .with_span_label(
2640 &span,
2641 format!("`{}` aliases `{}`", alias, underlying),
2642 )
2643 .with_help(format!(
2644 "Aliases for types with generic parameters are not supported as qualifiers. Use the original type directly: `{}.{}`",
2645 underlying, member
2646 ))
2647}
2648
2649pub fn ref_qualifier(member: &str, span: Span) -> LisetteDiagnostic {
2650 LisetteDiagnostic::error("Invalid `Ref` construction")
2651 .with_infer_code("ref_qualifier")
2652 .with_span_label(&span, format!("`Ref` has no `{}`", member))
2653 .with_help("To take a reference, use `&value`")
2654}
2655
2656pub fn control_flow_in_expression(keyword: &str, span: Span) -> LisetteDiagnostic {
2657 LisetteDiagnostic::error(format!(
2658 "`{}` cannot be used in expression position",
2659 keyword
2660 ))
2661 .with_infer_code("control_flow_in_expression")
2662 .with_span_label(
2663 &span,
2664 format!("`{}` is a statement and cannot produce a value", keyword),
2665 )
2666 .with_help(format!(
2667 "Use `{}` as a standalone statement instead",
2668 keyword
2669 ))
2670}
2671
2672pub fn spread_on_non_variadic(span: Span) -> LisetteDiagnostic {
2673 LisetteDiagnostic::error("Invalid spread argument")
2674 .with_infer_code("spread_on_non_variadic")
2675 .with_span_label(&span, "this function does not accept variadic arguments")
2676 .with_help("Only functions with a `VarArgs<T>` parameter accept a `xs...` spread")
2677}
2678
2679pub fn range_to_for_variadic(span: Span, var_name: Option<&str>) -> LisetteDiagnostic {
2680 let suggestion = match var_name {
2681 Some(name) => format!("Use postfix: `{}...`", name),
2682 None => "Use postfix `...` for variadic spread".to_string(),
2683 };
2684 LisetteDiagnostic::error("Invalid range argument")
2685 .with_infer_code("range_to_for_variadic")
2686 .with_span_label(&span, "this is a range, not a spread")
2687 .with_help(suggestion)
2688}
2689
2690pub fn reference_aliases_sibling(ref_span: Span, var_name: &str) -> LisetteDiagnostic {
2691 LisetteDiagnostic::error("Reference aliases sibling expression")
2692 .with_infer_code("reference_aliases_sibling")
2693 .with_span_label(
2694 &ref_span,
2695 format!(
2696 "`&{}` could mutate `{}` used by a sibling",
2697 var_name, var_name
2698 ),
2699 )
2700 .with_help(format!(
2701 "Bind `{}` to a `let` before this expression to make evaluation order explicit",
2702 var_name
2703 ))
2704}