Skip to content

Commit

Permalink
Merge pull request #20577 from thewilsonator/pointer-subtract
Browse files Browse the repository at this point in the history
Make subtracting pointers of different types an error
  • Loading branch information
dkorpel authored Jan 9, 2025
2 parents ec5cc17 + 8d2fe40 commit 69664b9
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 10 deletions.
11 changes: 11 additions & 0 deletions changelog/dmd.deprecation-pointer-subtract.dd
Original file line number Diff line number Diff line change
@@ -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;
}
```
6 changes: 2 additions & 4 deletions compiler/src/dmd/expressionsem.d
Original file line number Diff line number Diff line change
Expand Up @@ -12241,12 +12241,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
Expand Down
14 changes: 8 additions & 6 deletions compiler/test/fail_compilation/test11006.d
Original file line number Diff line number Diff line change
@@ -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);

0 comments on commit 69664b9

Please sign in to comment.