Skip to content

Commit 6461fe7

Browse files
committed
[GR-18927] Python parser doesn't throw syntax error if yield is used outside a function.
1 parent 38f7fac commit 6461fe7

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

graalpython/com.oracle.graal.python.test/src/com/oracle/graal/python/test/parser/YieldStatementTests.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,4 +338,29 @@ public void try03() throws Exception {
338338
" except ValueError:\n" +
339339
" pass");
340340
}
341+
342+
@Test
343+
public void syntaxEror01() throws Exception {
344+
checkSyntaxErrorMessageContains("yield", "'yield' outside function");
345+
}
346+
347+
@Test
348+
public void syntaxEror02() throws Exception {
349+
checkSyntaxErrorMessageContains("yield from", "invalid syntax");
350+
}
351+
352+
@Test
353+
public void syntaxEror03() throws Exception {
354+
checkSyntaxErrorMessageContains("class foo:yield 1", "'yield' outside function");
355+
}
356+
357+
@Test
358+
public void syntaxEror04() throws Exception {
359+
checkSyntaxErrorMessageContains("class foo:yield from ()", "'yield' outside function");
360+
}
361+
362+
@Test
363+
public void syntaxEror05() throws Exception {
364+
checkSyntaxErrorMessageContains("def g(a:(yield)): pass", "'yield' outside function");
365+
}
341366
}

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/parser/PythonNodeFactory.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,6 +211,9 @@ private void createLocalVariable(SSTNode var) {
211211
}
212212

213213
public YieldExpressionSSTNode createYieldExpressionSSTNode(SSTNode value, boolean isFrom, int startOffset, int endOffset) {
214+
if (!scopeEnvironment.isInFunctionScope()) {
215+
throw errors.raiseInvalidSyntax(source, createSourceSection(startOffset, endOffset), "'yield' outside function");
216+
}
214217
scopeEnvironment.setToGeneratorScope();
215218
return new YieldExpressionSSTNode(value, isFrom, startOffset, endOffset);
216219
}

0 commit comments

Comments
 (0)