Skip to content

Commit 4ee2d7c

Browse files
author
Sebastian Harko
committed
Add error message regarding yield and do keywords in for comprehensions
1 parent 56731e4 commit 4ee2d7c

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

src/dotty/tools/dotc/parsing/Parsers.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1326,7 +1326,7 @@ object Parsers {
13261326
if (in.token == YIELD) { in.nextToken(); ForYield(enums, expr()) }
13271327
else if (in.token == DO) { in.nextToken(); ForDo(enums, expr()) }
13281328
else {
1329-
if (!wrappedEnums) syntaxErrorOrIncomplete("`yield' or `do' expected")
1329+
if (!wrappedEnums) syntaxError(YieldOrDoExpectedInForComprehension())
13301330
ForDo(enums, expr())
13311331
}
13321332
}

src/dotty/tools/dotc/reporting/diagnostic/messages.scala

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,4 +512,39 @@ object messages {
512512
|}""".stripMargin
513513
}
514514

515+
case class YieldOrDoExpectedInForComprehension()(implicit ctx: Context) extends Message(19) {
516+
val kind = "Syntax"
517+
val msg = hl"${"yield"} or ${"do"} expected"
518+
519+
val code1 = "val numbers = for i <- 1 to 3 yield i"
520+
val code2 = "val numbers = for (i <- 1 to 3) yield i"
521+
val code3 = "for (i <- 1 to 3) println(i)"
522+
val code4 = "for i <- 1 to 3 do println(i) // notice the 'do' keyword"
523+
524+
val explanation =
525+
hl"""When the enumerators in a for comprehension are not placed in parentheses or braces, a ${"do"} or ${"yield"} statement
526+
|is required after the enumerators section of the comprehension.
527+
|
528+
|You can save some keystrokes by omitting the parentheses and writing
529+
|
530+
|$code1
531+
|
532+
| instead of
533+
|
534+
|$code2
535+
|
536+
|but the ${"yield"} keyword is still required.
537+
|
538+
|For comprehensions that simply perform a side effect without yielding anything can also be written without parentheses
539+
|but a ${"do"} keyword has to be included. For example,
540+
|
541+
|$code3
542+
|
543+
| can be written as
544+
|
545+
|$code4
546+
|
547+
|""".stripMargin
548+
}
549+
515550
}

0 commit comments

Comments
 (0)