D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 6638 - Suggestions/error messages for misuses of for/foreach
Summary: Suggestions/error messages for misuses of for/foreach
Status: RESOLVED LATER
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords: diagnostic
Depends on:
Blocks:
 
Reported: 2011-09-09 11:24 UTC by bearophile_hugs
Modified: 2021-01-24 05:51 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2011-09-09 11:24:56 UTC
Languages and compilers copy each other all the time. This is a low-priority diagnostic enhancement request inspired by Rust compiler:

https://github.com/graydon/rust/wiki/Error-reporting

> Use of for where for each was meant.
> 
> for (v in foo.iter()) // suggest "for each"


This is wrong D code (in my code the mistakes #5 and #7 are common enough):


void main() {
    for (i; 0 .. 10) {} // #1
    int[5] a;
    for (x; a) {} // #2
    foreach (int = 0; i < 10; i++) {} // #3
    foreach (i, 0 .. 10) {} // #4
    foreach (i, x, a) {} // #5
    foreach (i; x, a) {} // #6
    foreach (i; x; a) {} // #7
}


DMD 2.055 gives:

test.d(2): found '..' when expecting ';' following for condition
test.d(4): found ')' when expecting ';' following for condition
test.d(5): found 'foreach' when expecting ')'
test.d(5): found '=' when expecting '.' following int
test.d(5): found '0' when expecting identifier following 'int.'
test.d(5): found ';' when expecting ')'
test.d(5): found 'i' when expecting ';' following statement
test.d(5): found '<' instead of statement
test.d(5): found ')' when expecting ';' following statement
test.d(6): basic type expected, not 0
test.d(6): no identifier for declarator int
test.d(6): found '0' when expecting ';'
test.d(6): expression expected, not '..'
test.d(6): found '10' when expecting ')'
test.d(6): found ')' instead of statement
test.d(7): Declaration expected, not 'foreach'
test.d(8): no identifier for declarator x
test.d(8): semicolon expected, not ')'
test.d(8): Declaration expected, not ')'
test.d(9): no identifier for declarator x
test.d(9): no identifier for declarator a


In some (or all) such 7 situations the D compiler can generate specific better error messages, with a suggestion.
Comment 1 mhh 2021-01-24 05:51:14 UTC
The Error message is still bad in 2020 but ultimately this would mean adding a bunch of new logic to the parser to fix something pretty obvious (to be blunt)