@@ -56,8 +56,6 @@ public final class ScopeTranslator<T> extends Python3BaseVisitor<T> {
5656 private final ArrayList <String > possibleCellIdentifiers = new ArrayList <>();
5757 private final ArrayList <ScopeInfo > possibleCellScopes = new ArrayList <>();
5858
59- private Stack <ScopeInfo > currentGeneratorScope = new Stack <>();
60-
6159 public ScopeTranslator (ParserErrorCallback errors , TranslationEnvironment environment , boolean interactive , FrameDescriptor curInlineLocals ) {
6260 this .errors = errors ;
6361 this .environment = environment ;
@@ -347,46 +345,31 @@ public T visitArgument(Python3Parser.ArgumentContext ctx) {
347345 @ Override
348346 public T visitComp_for (Python3Parser .Comp_forContext ctx ) {
349347 declareNames (ctx .exprlist ());
350- environment .incCurrentScopeLoopCount ();
351- return super .visitComp_for (ctx );
352- }
353-
354- @ Override
355- public T visitOr_test (Python3Parser .Or_testContext ctx ) {
356- boolean pushedCurrentGeneratorScope = false ;
357- if (ctx .getParent () instanceof Python3Parser .Comp_forContext ) {
358- if (currentGeneratorScope .peek () == null && environment .getCurrentScopeLoopCount () == 1 ) {
359- // the generator iterator needs to be early evaluated in the parent scope
360- currentGeneratorScope .pop ();
361- currentGeneratorScope .push (environment .pushCurentScope ());
362- pushedCurrentGeneratorScope = true ;
363- }
348+ visitExprlist (ctx .exprlist ());
349+
350+ ScopeInfo currentGeneratorScope = environment .getCurrentScope ();
351+ currentGeneratorScope .incLoopCount ();
352+ if (currentGeneratorScope .getLoopCount () == 1 ) {
353+ // the first iterator is eagerly evaluated in the outside scope
354+ environment .pushCurentScope ();
355+ visitOr_test (ctx .or_test ());
356+ environment .popCurrentScope (currentGeneratorScope );
357+ } else {
358+ visitOr_test (ctx .or_test ());
364359 }
365- try {
366- return super .visitOr_test (ctx );
367- } finally {
368- if (ctx .getParent () instanceof Python3Parser .Comp_forContext ) {
369- if (pushedCurrentGeneratorScope ) {
370- ScopeInfo scopeInfo = currentGeneratorScope .pop ();
371- // restore the current scope
372- environment .popCurrentScope (scopeInfo );
373- currentGeneratorScope .push (null );
374- }
375- }
360+
361+ if (ctx .comp_iter () != null ) {
362+ visitComp_iter (ctx .comp_iter ());
376363 }
364+ return null ;
377365 }
378366
379367 private T visitGenerator (ParserRuleContext ctx , Python3Parser .Comp_forContext compctx , Function <ParserRuleContext , T > block ) {
380368 compctx .scope = environment .createScope (ctx , ScopeKind .Generator );
381- currentGeneratorScope .push (null );
382369 try {
383370 return block .apply (ctx );
384371 } finally {
385- if (currentGeneratorScope .pop () == null ) {
386- environment .leaveScope ();
387- } else {
388- throw new IllegalStateException ("why did the currentGeneratorScope leak?" );
389- }
372+ environment .leaveScope ();
390373 }
391374 }
392375
0 commit comments