Improve error message on pointer diff #2239.

This commit is contained in:
Christoffer Lerno
2025-06-23 23:47:19 +02:00
parent adabae2a24
commit 605a7c4091
3 changed files with 23 additions and 1 deletions

View File

@@ -25,7 +25,8 @@
- Support distrinct types as the base type of bitstructs. #2218
- Add hash::sha512 module to stdlib. #2227
- Compile time type assignment (eg `$Foo = int`) is no longer an expression.
- Add `@allow_deprecated` attribute to functions to selectively allow deprecated declarations #2223
- Add `@allow_deprecated` attribute to functions to selectively allow deprecated declarations #2223.
- Improve error message on pointer diff #2239.
### Fixes
- `-2147483648`, MIN literals work correctly.

View File

@@ -1275,6 +1275,14 @@ static bool rule_int_to_float(CastContext *cc, bool is_explicit, bool is_silent)
return true;
}
INLINE bool expr_is_pointer_diff(Expr *expr)
{
if (expr->type != type_isz) return false;
if (expr->expr_kind != EXPR_BINARY) return false;
if (expr->binary_expr.operator != BINARYOP_SUB) return false;
return type_is_pointer(exprptr(expr->binary_expr.left)->type) && type_is_pointer(exprptr(expr->binary_expr.right)->type);
}
static bool rule_widen_narrow(CastContext *cc, bool is_explicit, bool is_silent)
{
if (is_explicit) return true;
@@ -1327,6 +1335,11 @@ static bool rule_widen_narrow(CastContext *cc, bool is_explicit, bool is_silent)
expr_const_to_error_string(&expr->const_expr),
type_quoted_error_string(cc->to_type));
}
if (expr_is_pointer_diff(expr))
{
RETURN_CAST_ERROR(expr, "A pointer diff has the type %s which cannot implicitly be converted to %s. You can use an explicit cast if you know the conversion is safe.",
type_quoted_error_string(expr->type), type_quoted_error_string(cc->to_type));
}
RETURN_CAST_ERROR(expr, "%s cannot implicitly be converted to %s, but you may use a cast.",
type_quoted_error_string(expr->type), type_quoted_error_string(cc->to_type));
}

View File

@@ -0,0 +1,8 @@
import std;
fn int main()
{
void* a;
void* b;
int z = a - b; // #error: A pointer diff has the type
return 0;
}