Fix #20330 - Make subtracting pointers of different types an error

This commit is contained in:
Nicholas Wilson 2024-12-19 05:51:39 +08:00
parent b7a3a1942c
commit 8d2fe40f4b
3 changed files with 21 additions and 10 deletions

View file

@ -0,0 +1,11 @@
An error is now given for subtracting pointers of different types
The following code now gives errors:
```
static assert(cast(void*)8 - cast(int*) 0 == 2L);
static assert(cast(int*) 8 - cast(void*)0 == 8L);
void test()
{
auto foo = (ushort*).init - (ubyte*).init;
}
```

View file

@ -12403,12 +12403,10 @@ private extern (C++) final class ExpressionSemanticVisitor : Visitor
if (!p1.equivalent(p2))
{
// Deprecation to remain for at least a year, after which this should be
// changed to an error
// See https://github.com/dlang/dmd/pull/7332
deprecation(exp.loc,
"cannot subtract pointers to different types: `%s` and `%s`.",
error(exp.loc, "cannot subtract pointers to different types: `%s` and `%s`.",
t1.toChars(), t2.toChars());
return setError();
}
// Need to divide the result by the stride

View file

@ -1,11 +1,13 @@
/* REQUIRED_ARGS: -main -de
* TEST_OUTPUT:
/* TEST_OUTPUT:
---
fail_compilation/test11006.d(10): Deprecation: cannot subtract pointers to different types: `void*` and `int*`.
fail_compilation/test11006.d(10): while evaluating: `static assert(2L == 2L)`
fail_compilation/test11006.d(11): Deprecation: cannot subtract pointers to different types: `int*` and `void*`.
fail_compilation/test11006.d(11): while evaluating: `static assert(8L == 8L)`
fail_compilation/test11006.d(11): Error: cannot subtract pointers to different types: `void*` and `int*`.
fail_compilation/test11006.d(11): while evaluating: `static assert(cast(void*)8 - cast(int*)0 == 2L)`
fail_compilation/test11006.d(12): Error: cannot subtract pointers to different types: `int*` and `void*`.
fail_compilation/test11006.d(12): while evaluating: `static assert(cast(int*)8 - cast(void*)0 == 8L)`
fail_compilation/test11006.d(13): Error: cannot subtract pointers to different types: `ushort*` and `ubyte*`.
fail_compilation/test11006.d(13): while evaluating: `static assert(null - null == 0)`
---
*/
static assert(cast(void*)8 - cast(int*) 0 == 2L);
static assert(cast(int*) 8 - cast(void*)0 == 8L);
static assert((ushort*).init - (ubyte*).init == 0);