Skip to content

Commit f8d18cb

Browse files
jbretteclaude
andcommitted
Translate labeled break and continue
Both were silently wrong: the label was dropped and a bare break or continue emitted in its place, with only a warning to say so. That is correct just when the labeled statement happens to be the innermost loop, which is why test/Break0.java passed anyway. Classify each labeled jump instead. One a bare keyword can express still emits one -- so Break0's output is unchanged, and a `break label` inside a switch keeps emitting a bare break, since the switch becomes an if/elif chain rather than a loop. The rest raise a generated per-label exception that the labeled statement catches: the break handler wraps the whole statement, the continue handler wraps the loop body, placed before a for-update or a do-while condition so those still run, matching Java. maybeLabelClasses defines one documented Exception subclass per label actually used, following the existing needsBsrFunc pattern. Also add FOR_EACH to the loop types acceptBreak scans. Without it a plain break inside a for-each nested in a switch was dropped entirely. Seven tests cover each changed loop path: Break2 (nested for), Break3 (labeled block), Break4 (from inside a switch), Continue3 (for), Continue4 (while), Continue5 (do-while), ForEach1 (for-each, both jumps on one label). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FfdD42ztfjZth9nXpRduKE
1 parent 8b79650 commit f8d18cb

10 files changed

Lines changed: 249 additions & 22 deletions

File tree

‎java2python/compiler/visitor.py‎

Lines changed: 127 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -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

626731
class Method(ModifiersAcceptor, MethodContent):

‎java2python/config/default.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
basic.maybeJavaDiv,
2828
basic.maybeAbstractHelpers,
2929
basic.maybeSyncHelpers,
30+
basic.maybeLabelClasses,
3031
]
3132

3233

‎java2python/mod/basic.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,14 @@ def maybeSyncHelpers(module):
177177
yield from getSyncHelpersSrc().split('\n')
178178

179179

180+
def maybeLabelClasses(module):
181+
""" Yields the exception classes that emulate Java labeled jumps. """
182+
for name, keyword, label in getattr(module, 'needsLabelClasses', ()):
183+
yield f'class {name}(Exception):'
184+
yield f' """ Raised to emulate the Java statement `{keyword} {label};`. """'
185+
yield ''
186+
187+
180188
def classContentSort(obj):
181189
isMethod = lambda x:x and x.isMethod
182190

‎test/Break2.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Break2 {
2+
public static void main(String[] args) {
3+
outer:
4+
for (int i = 0; i < 4; i++) {
5+
for (int j = 0; j < 4; j++) {
6+
if (i * j > 3) {
7+
break outer;
8+
}
9+
System.out.println(i * 10 + j);
10+
}
11+
System.out.println(-1);
12+
}
13+
System.out.println("done");
14+
}
15+
}

‎test/Break3.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
class Break3 {
2+
public static void main(String[] args) {
3+
int x = 7;
4+
block: {
5+
System.out.println("in block");
6+
if (x == 7) {
7+
break block;
8+
}
9+
System.out.println("not reached");
10+
}
11+
System.out.println("after block");
12+
}
13+
}

‎test/Break4.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Break4 {
2+
public static void main(String[] args) {
3+
loop:
4+
while (true) {
5+
switch (3) {
6+
case 3:
7+
System.out.println("in case");
8+
break loop;
9+
default:
10+
System.out.println("not reached");
11+
}
12+
}
13+
System.out.println("after loop");
14+
}
15+
}

‎test/Continue3.java‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Continue3 {
2+
public static void main(String[] args) {
3+
outer:
4+
for (int i = 0; i < 4; i++) {
5+
for (int j = 0; j < 4; j++) {
6+
if (j == 2) {
7+
continue outer;
8+
}
9+
System.out.println(i * 10 + j);
10+
}
11+
System.out.println(-1);
12+
}
13+
System.out.println("done");
14+
}
15+
}

‎test/Continue4.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Continue4 {
2+
public static void main(String[] args) {
3+
int i = 0;
4+
outer:
5+
while (i < 4) {
6+
i++;
7+
int j = 0;
8+
while (j < 4) {
9+
j++;
10+
if (j == 2) {
11+
continue outer;
12+
}
13+
System.out.println(i * 10 + j);
14+
}
15+
System.out.println(-1);
16+
}
17+
System.out.println("done");
18+
}
19+
}

‎test/Continue5.java‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Continue5 {
2+
public static void main(String[] args) {
3+
int i = 0;
4+
outer:
5+
do {
6+
i++;
7+
for (int j = 0; j < 4; j++) {
8+
if (j == 2) {
9+
continue outer;
10+
}
11+
System.out.println(i * 10 + j);
12+
}
13+
System.out.println(-1);
14+
} while (i < 4);
15+
System.out.println("done");
16+
}
17+
}

‎test/ForEach1.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class ForEach1 {
2+
public static void main(String[] args) {
3+
int ints[] = {1, 2, 3, 4};
4+
outer:
5+
for (int i: ints) {
6+
for (int j: ints) {
7+
if (j == 3) {
8+
continue outer;
9+
}
10+
if (i == 4) {
11+
break outer;
12+
}
13+
System.out.println(i * 10 + j);
14+
}
15+
System.out.println(-1);
16+
}
17+
System.out.println("done");
18+
}
19+
}

0 commit comments

Comments
 (0)