@@ -47,7 +47,7 @@ public class ScopeTranslator<T> extends Python3BaseVisitor<T> {
4747 private final PythonCore core ;
4848 private final boolean interactive ;
4949 private final boolean trackCells ;
50- private int comprehensionOrTestDepth = 0 ;
50+ private ScopeInfo currentGeneratorScope = null ;
5151
5252 public ScopeTranslator (PythonCore core , TranslationEnvironment environment , boolean interactive , boolean trackCells ) {
5353 this .core = core ;
@@ -360,33 +360,37 @@ public T visitComp_for(Python3Parser.Comp_forContext ctx) {
360360
361361 @ Override
362362 public T visitOr_test (Python3Parser .Or_testContext ctx ) {
363- ScopeInfo generatorScope = null ;
363+ boolean pushedCurrentGeneratorScope = false ;
364364 if (ctx .getParent () instanceof Python3Parser .Comp_forContext ) {
365- if (comprehensionOrTestDepth == 0 && environment .getCurrentScopeLoopCount () == 1 ) {
365+ if (currentGeneratorScope == null && environment .getCurrentScopeLoopCount () == 1 ) {
366366 // the generator iterator needs to be early evaluated in the parent scope
367- generatorScope = environment .pushCurentScope ();
367+ currentGeneratorScope = environment .pushCurentScope ();
368+ pushedCurrentGeneratorScope = true ;
368369 }
369- comprehensionOrTestDepth ++;
370370 }
371371 try {
372372 return super .visitOr_test (ctx );
373373 } finally {
374374 if (ctx .getParent () instanceof Python3Parser .Comp_forContext ) {
375- comprehensionOrTestDepth --;
376- if (comprehensionOrTestDepth == 0 && generatorScope != null && generatorScope .getLoopCount () == 1 ) {
375+ if (pushedCurrentGeneratorScope && currentGeneratorScope .getLoopCount () == 1 ) {
377376 // restore the current scope
378377 environment .popCurrentScope ();
378+ currentGeneratorScope = null ;
379379 }
380380 }
381381 }
382382 }
383383
384384 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+ }
386388 try {
387389 return block .apply (ctx );
388390 } finally {
389- environment .endScope (ctx );
391+ if (currentGeneratorScope == null ) {
392+ environment .endScope (ctx );
393+ }
390394 }
391395 }
392396
0 commit comments