@@ -372,21 +372,89 @@ def acceptAssert(self, node, memo):
372372 assertStat = self .factory .statement ('assert' , fs = FS .lsr , parent = self )
373373 assertStat .expr .walk (node .firstChild (), memo )
374374
375+ # Java statements that become a loop in the generated Python; a bare
376+ # break or continue binds to the innermost of these. A switch is
377+ # absent on purpose: it becomes an if/elif chain, not a loop.
378+ loopTypes = (tokens .WHILE , tokens .DO , tokens .FOR , tokens .FOR_EACH )
379+
380+ def labelJump (self , node ):
381+ """ Returns (target, name) for a break or continue node.
382+
383+ `target` is the labeled statement the jump leaves or restarts and
384+ `name` is the exception class the jump has to raise to get there.
385+ Both are None when the jump carries no label. `name` alone is
386+ None when a bare keyword already jumps to the right place, which
387+ is the case when the labeled statement is also the innermost loop
388+ around the jump.
389+ """
390+ ident = node .firstChildOfType (tokens .IDENT )
391+ if ident is None :
392+ return None , None
393+ def isLabel (item ):
394+ if item .type != tokens .LABELED_STATEMENT :
395+ return False
396+ name = item .firstChildOfType (tokens .IDENT )
397+ return name is not None and name .text == ident .text
398+ labeled = next (node .parents (isLabel ), None )
399+ if labeled is None :
400+ return None , None
401+ target = labeled .children [1 ]
402+ inner = next ((p for p in node .parents () if p .type in self .loopTypes ), None )
403+ if inner is target :
404+ return target , None
405+ keyword = tokens .map .get (node .type , '' ).title ()
406+ return target , f'_Label{ keyword } _{ ident .text } '
407+
408+ def addLabelClass (self , name , keyword , label ):
409+ """ Records an exception class for the module prologue to define. """
410+ module = next (self .parents (lambda x :x .isModule ))
411+ classes = getattr (module , 'needsLabelClasses' , None )
412+ if classes is None :
413+ classes = module .needsLabelClasses = []
414+ entry = (name , keyword , label )
415+ if entry not in classes :
416+ classes .append (entry )
417+
418+ def labelRaise (self , name ):
419+ """ Adds a raise statement that emulates a labeled jump. """
420+ raiseStat = self .factory .statement ('raise' , fs = FS .lsr , parent = self )
421+ raiseStat .expr .right = f'{ name } ()'
422+
423+ def openLabelContinue (self , node , loop ):
424+ """ Returns the block that should hold the body of the given loop.
425+
426+ A loop targeted by a labeled continue runs its body inside a try,
427+ so that the exception resumes the loop instead of leaving it.
428+ """
429+ if getattr (node , 'labelContinueClass' , None ):
430+ return self .factory .statement ('try' , fs = FS .lc , parent = loop )
431+ return loop
432+
433+ def closeLabelContinue (self , node , loop ):
434+ """ Adds the handler that catches a labeled continue, if needed. """
435+ name = getattr (node , 'labelContinueClass' , None )
436+ if name :
437+ exStat = self .factory .statement ('except' , fs = FS .lsrc , parent = loop )
438+ exStat .expr .right = name
439+ self .factory .expr (left = 'pass' , parent = exStat )
440+
375441 def acceptBreak (self , node , memo ):
376442 """ Accept and process a break statement. """
377- # possible parents of a break statement: switch, while, do, for
378- # we want to skip inserting a break statement if we're inside a switch.
379- insert , ok_types = True , [tokens .WHILE , tokens .DO , tokens .FOR ]
380- for parent in node .parents ():
381- if parent .type == tokens .SWITCH :
382- insert = False
383- break
384- if parent .type in ok_types :
385- break
386- if insert :
387- if len (node .children ):
388- warning ('Detected unhandled break statement with label; generated code incorrect.' )
389- breakStat = self .factory .statement ('break' , parent = self )
443+ target , name = self .labelJump (node )
444+ if name :
445+ self .labelRaise (name )
446+ return
447+ # An unlabeled break inside a switch ends the case rather than a
448+ # loop, and the generated if/elif chain needs no statement for it.
449+ # A labeled break is always emitted: it reached this point only
450+ # because a bare break lands where the label points.
451+ if target is None :
452+ for parent in node .parents ():
453+ if parent .type == tokens .SWITCH :
454+ return
455+ if parent .type in self .loopTypes :
456+ break
457+ self .factory .statement ('break' , parent = self )
390458
391459 def acceptCatch (self , node , memo ):
392460 """ Accept and process a catch statement. """
@@ -405,21 +473,24 @@ def acceptCatch(self, node, memo):
405473
406474 def acceptContinue (self , node , memo ):
407475 """ Accept and process a continue statement. """
408- parent = next (node .parents (lambda x : x .type in {tokens .FOR , tokens .FOR_EACH , tokens .DO , tokens .WHILE }))
476+ name = self .labelJump (node )[1 ]
477+ if name :
478+ self .labelRaise (name )
479+ return
480+ parent = next (node .parents (lambda x : x .type in self .loopTypes ))
409481 if parent .type == tokens .FOR :
410482 updateStat = self .factory .expr (parent = self )
411483 updateStat .walk (parent .firstChildOfType (tokens .FOR_UPDATE ), memo )
412484 contStat = self .factory .statement ('continue' , fs = FS .lsr , parent = self )
413- if len (node .children ):
414- warning ('Detected unhandled continue statement with label; generated code incorrect.' )
415485
416486 def acceptDo (self , node , memo ):
417487 """ Accept and process a do-while block. """
418488 # DO - BLOCK_SCOPE - PARENTESIZED_EXPR
419489 blkNode , parNode = node .children
420490 whileStat = self .factory .statement ('while' , fs = FS .lsrc , parent = self )
421491 whileStat .expr .right = 'True'
422- whileStat .walk (blkNode , memo )
492+ self .openLabelContinue (node , whileStat ).walk (blkNode , memo )
493+ self .closeLabelContinue (node , whileStat )
423494 fs = FS .l + ' ' + 'not ({right}):'
424495 ifStat = self .factory .statement ('if' , fs = fs , parent = whileStat )
425496 ifStat .expr .walk (parNode , memo )
@@ -450,10 +521,12 @@ def acceptFor(self, node, memo):
450521 else :
451522 whileStat .expr .walk (cond , memo )
452523 whileBlock = self .factory .methodContent (parent = self )
524+ forBody = self .openLabelContinue (node , whileBlock )
453525 if not node .firstChildOfType (tokens .BLOCK_SCOPE ).children :
454- self .factory .expr (left = 'pass' , parent = whileBlock )
526+ self .factory .expr (left = 'pass' , parent = forBody )
455527 else :
456- whileBlock .walk (node .firstChildOfType (tokens .BLOCK_SCOPE ), memo )
528+ forBody .walk (node .firstChildOfType (tokens .BLOCK_SCOPE ), memo )
529+ self .closeLabelContinue (node , whileBlock )
457530 updateStat = self .factory .expr (parent = whileBlock )
458531 updateStat .walk (node .firstChildOfType (tokens .FOR_UPDATE ), memo )
459532
@@ -465,7 +538,8 @@ def acceptForEach(self, node, memo):
465538 inExpr = identExpr .right = self .factory .expr ()
466539 inExpr .walk (node .firstChildOfType (tokens .EXPR ), memo )
467540 forBlock = self .factory .methodContent (parent = self )
468- forBlock .walk (node .children [4 ], memo )
541+ self .openLabelContinue (node , forBlock ).walk (node .children [4 ], memo )
542+ self .closeLabelContinue (node , forBlock )
469543
470544 def acceptIf (self , node , memo ):
471545 """ Accept and process an if statement. """
@@ -512,6 +586,35 @@ def acceptIf(self, node, memo):
512586 self .factory .expr (left = 'pass' , parent = elseStat )
513587
514588
589+ def acceptLabeledStatement (self , node , memo ):
590+ """ Accept and process a labeled statement.
591+
592+ Python has no labeled break or continue, so a jump that a bare
593+ keyword cannot express becomes a raise, and the labeled statement
594+ is wrapped in the handlers that catch it.
595+ """
596+ # LABELED_STATEMENT - IDENT - statement
597+ label , stmtNode = node .children [0 ].text , node .children [1 ]
598+ jumpTypes = (tokens .BREAK , tokens .CONTINUE )
599+ names = {}
600+ for jump in node .findChildren (lambda c :c .type in jumpTypes ):
601+ jumpTarget , name = self .labelJump (jump )
602+ if jumpTarget is stmtNode and name :
603+ names [jump .type ] = name
604+ breakName , continueName = names .get (tokens .BREAK ), names .get (tokens .CONTINUE )
605+ if continueName :
606+ self .addLabelClass (continueName , 'continue' , label )
607+ stmtNode .labelContinueClass = continueName
608+ target = self
609+ if breakName :
610+ self .addLabelClass (breakName , 'break' , label )
611+ target = self .factory .statement ('try' , fs = FS .lc , parent = self )
612+ target .walk (stmtNode , memo )
613+ if breakName :
614+ exStat = self .factory .statement ('except' , fs = FS .lsrc , parent = self )
615+ exStat .expr .right = breakName
616+ self .factory .expr (left = 'pass' , parent = exStat )
617+
515618 def acceptSwitch (self , node , memo ):
516619 """ Accept and process a switch block. """
517620 # This implementation needs a lot of work to handle case
@@ -617,10 +720,12 @@ def acceptWhile(self, node, memo):
617720 parNode , blkNode = node .children
618721 whileStat = self .factory .statement ('while' , fs = FS .lsrc , parent = self )
619722 whileStat .expr .walk (parNode , memo )
723+ whileBody = self .openLabelContinue (node , whileStat )
620724 if not blkNode .children :
621- self .factory .expr (left = 'pass' , parent = whileStat )
725+ self .factory .expr (left = 'pass' , parent = whileBody )
622726 else :
623- whileStat .walk (blkNode , memo )
727+ whileBody .walk (blkNode , memo )
728+ self .closeLabelContinue (node , whileStat )
624729
625730
626731class Method (ModifiersAcceptor , MethodContent ):
0 commit comments