@@ -47,7 +47,7 @@ public class ScopeTranslator<T> extends Python3BaseVisitor<T> {
47
47
private final PythonCore core ;
48
48
private final boolean interactive ;
49
49
private final boolean trackCells ;
50
- private int comprehensionOrTestDepth = 0 ;
50
+ private ScopeInfo currentGeneratorScope = null ;
51
51
52
52
public ScopeTranslator (PythonCore core , TranslationEnvironment environment , boolean interactive , boolean trackCells ) {
53
53
this .core = core ;
@@ -360,33 +360,37 @@ public T visitComp_for(Python3Parser.Comp_forContext ctx) {
360
360
361
361
@ Override
362
362
public T visitOr_test (Python3Parser .Or_testContext ctx ) {
363
- ScopeInfo generatorScope = null ;
363
+ boolean pushedCurrentGeneratorScope = false ;
364
364
if (ctx .getParent () instanceof Python3Parser .Comp_forContext ) {
365
- if (comprehensionOrTestDepth == 0 && environment .getCurrentScopeLoopCount () == 1 ) {
365
+ if (currentGeneratorScope == null && environment .getCurrentScopeLoopCount () == 1 ) {
366
366
// the generator iterator needs to be early evaluated in the parent scope
367
- generatorScope = environment .pushCurentScope ();
367
+ currentGeneratorScope = environment .pushCurentScope ();
368
+ pushedCurrentGeneratorScope = true ;
368
369
}
369
- comprehensionOrTestDepth ++;
370
370
}
371
371
try {
372
372
return super .visitOr_test (ctx );
373
373
} finally {
374
374
if (ctx .getParent () instanceof Python3Parser .Comp_forContext ) {
375
- comprehensionOrTestDepth --;
376
- if (comprehensionOrTestDepth == 0 && generatorScope != null && generatorScope .getLoopCount () == 1 ) {
375
+ if (pushedCurrentGeneratorScope && currentGeneratorScope .getLoopCount () == 1 ) {
377
376
// restore the current scope
378
377
environment .popCurrentScope ();
378
+ currentGeneratorScope = null ;
379
379
}
380
380
}
381
381
}
382
382
}
383
383
384
384
private T visitGenerator (ParserRuleContext ctx , Function <ParserRuleContext , T > block ) {
385
- environment .beginScope (ctx , ScopeKind .Generator );
385
+ if (currentGeneratorScope == null ) {
386
+ environment .beginScope (ctx , ScopeKind .Generator );
387
+ }
386
388
try {
387
389
return block .apply (ctx );
388
390
} finally {
389
- environment .endScope (ctx );
391
+ if (currentGeneratorScope == null ) {
392
+ environment .endScope (ctx );
393
+ }
390
394
}
391
395
}
392
396
0 commit comments