Skip to content

Commit d39dfc0

Browse files
authored
Merge pull request #2804 from dotty-staging/add-pure-warning
Emit "pure expression does nothing in statement position" warning
2 parents 1a959c3 + 70eaa36 commit d39dfc0

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

compiler/src/dotty/tools/dotc/typer/Typer.scala

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1707,7 +1707,10 @@ class Typer extends Namer with TypeAssigner with Applications with Implicits wit
17071707
case Thicket(stats) :: rest =>
17081708
traverse(stats ++ rest)
17091709
case stat :: rest =>
1710-
buf += typed(stat)(ctx.exprContext(stat, exprOwner))
1710+
val stat1 = typed(stat)(ctx.exprContext(stat, exprOwner))
1711+
if (!ctx.isAfterTyper && isPureExpr(stat1))
1712+
ctx.warning(em"a pure expression does nothing in statement position", stat.pos)
1713+
buf += stat1
17111714
traverse(rest)
17121715
case nil =>
17131716
buf.toList

compiler/test/dotty/tools/dotc/CompilationTests.scala

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,7 @@ class CompilationTests extends ParallelTesting {
163163
compileFile("../tests/neg/customArgs/noimports2.scala", defaultOptions.and("-Yno-imports")) +
164164
compileFile("../tests/neg/customArgs/overloadsOnAbstractTypes.scala", allowDoubleBindings) +
165165
compileFile("../tests/neg/customArgs/xfatalWarnings.scala", defaultOptions.and("-Xfatal-warnings")) +
166+
compileFile("../tests/neg/customArgs/pureStatement.scala", defaultOptions.and("-Xfatal-warnings")) +
166167
compileFile("../tests/neg/customArgs/phantom-overload.scala", allowDoubleBindings) +
167168
compileFile("../tests/neg/tailcall/t1672b.scala", defaultOptions) +
168169
compileFile("../tests/neg/tailcall/t3275.scala", defaultOptions) +
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class IOCapability
2+
3+
object Test {
4+
"" // error: pure expression does nothing in statement position
5+
6+
locally {
7+
"" // error: pure expression does nothing in statement position
8+
9+
println("")
10+
11+
42 // error: pure expression does nothing in statement position
12+
13+
((x: Int) => println("hi")) // error: pure expression does nothing in statement position
14+
15+
()
16+
}
17+
18+
// Forgot to mark `ev` implicit!
19+
def doSideEffects(x: Int)(ev: IOCapability) = {
20+
println("x: " + x)
21+
}
22+
23+
implicit val cap: IOCapability = new IOCapability
24+
25+
2 // error: pure expression does nothing in statement position
26+
27+
doSideEffects(1) // error: pure expression does nothing in statement position
28+
}

0 commit comments

Comments
 (0)