Skip to content

Commit cbbca2b

Browse files
authored
Improve foreach AA error messages & add tests (dlang#21472)
Show parameter name and `ref`-ness.
1 parent 0c05e38 commit cbbca2b

2 files changed

Lines changed: 12 additions & 5 deletions

File tree

compiler/src/dmd/statementsem.d

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3903,8 +3903,8 @@ private extern(D) Expression applyAssocArray(ForeachStatement fs, Expression fld
39033903
Type ti = (isRef ? taa.index.addMod(MODFlags.const_) : taa.index);
39043904
if (isRef ? !ti.constConv(ta) : !ti.implicitConvTo(ta))
39053905
{
3906-
error(fs.loc, "`foreach`: index must be type `%s`, not `%s`",
3907-
ti.toChars(), ta.toChars());
3906+
error(fs.loc, "`foreach`: index parameter `%s%s` must be type `%s`, not `%s`",
3907+
isRef ? "ref ".ptr : "".ptr, p.toChars(), ti.toChars(), ta.toChars());
39083908
return null;
39093909
}
39103910
p = (*fs.parameters)[1];
@@ -3914,8 +3914,8 @@ private extern(D) Expression applyAssocArray(ForeachStatement fs, Expression fld
39143914
Type taav = taa.nextOf();
39153915
if (isRef ? !taav.constConv(ta) : !taav.implicitConvTo(ta))
39163916
{
3917-
error(fs.loc, "`foreach`: value must be type `%s`, not `%s`",
3918-
taav.toChars(), ta.toChars());
3917+
error(fs.loc, "`foreach`: value parameter `%s%s` must be type `%s`, not `%s`",
3918+
isRef ? "ref ".ptr : "".ptr, p.toChars(), taav.toChars(), ta.toChars());
39193919
return null;
39203920
}
39213921

compiler/test/fail_compilation/fail13756.d

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
/*
22
TEST_OUTPUT:
33
---
4-
fail_compilation/fail13756.d(11): Error: `foreach`: index must be type `const(int)`, not `int`
4+
fail_compilation/fail13756.d(14): Error: `foreach`: index parameter `ref k` must be type `const(int)`, not `int`
5+
fail_compilation/fail13756.d(17): Error: cannot implicitly convert expression `__applyArg0` of type `int` to `string`
6+
fail_compilation/fail13756.d(19): Error: cannot implicitly convert expression `__applyArg1` of type `int` to `char`
7+
fail_compilation/fail13756.d(20): Error: `foreach`: value parameter `ref val` must be type `int`, not `dchar`
58
---
69
*/
710

@@ -11,4 +14,8 @@ void maiin()
1114
foreach (ref int k, v; aa)
1215
{
1316
}
17+
foreach (string key, val; aa) {}
18+
19+
foreach (key, char val; aa) {}
20+
foreach (key, ref dchar val; aa) {}
1421
}

0 commit comments

Comments
 (0)