From 19a96acac862fc7abac60a573d0201193709d01d Mon Sep 17 00:00:00 2001 From: Christoffer Lerno Date: Mon, 7 Oct 2024 21:00:17 +0200 Subject: [PATCH] Improve error message in the case of `MyInterface x = foo;` #1522 --- releasenotes.md | 1 + src/compiler/sema_casts.c | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/releasenotes.md b/releasenotes.md index bff06e365..70176abb5 100644 --- a/releasenotes.md +++ b/releasenotes.md @@ -7,6 +7,7 @@ - Slicing arrays, slices and bytes at compile time #1466. - Better error for `int a[4] = ...`. #1518 - Better error for `int Foo(int a)` declarations #1516 +- Improve error message in the case of `MyInterface x = foo;` #1522 ### Fixes - `Unsupported int[*] $x = { 1, 2, 3, 4 }` #1489. diff --git a/src/compiler/sema_casts.c b/src/compiler/sema_casts.c index 601acb752..d451fdc3a 100644 --- a/src/compiler/sema_casts.c +++ b/src/compiler/sema_casts.c @@ -695,6 +695,21 @@ static bool report_cast_error(CastContext *cc, bool may_cast_explicit) } else { + if (to->type_kind == TYPE_INTERFACE) + { + if (expr->type->canonical->type_kind != TYPE_POINTER) + { + RETURN_CAST_ERROR(expr, + "You can only convert pointers to an interface like %s. " + "Try passing the address of the expression instead.", + type_quoted_error_string(to)); + } + } + else if (to->type_kind == TYPE_ANY && expr->type->canonical->type_kind != TYPE_POINTER) + { + RETURN_CAST_ERROR(expr, "You can only convert pointers to 'any'. " + "Try passing the address of the expression instead."); + } RETURN_CAST_ERROR(expr, "It is not possible to cast %s to %s.", type_quoted_error_string(type_no_optional(expr->type)), type_quoted_error_string(to));