Skip to content

Commit 049c802

Browse files
committed
Added support for try-else
1 parent 44023a3 commit 049c802

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

src/control-flow/cfg-python.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,7 @@ export class CFGBuilder {
209209

210210
const bodySyntax = this.getSyntax(match, "try-body");
211211
const exceptSyntaxMany = this.getSyntaxMany(match, "except-body");
212+
const elseSyntax = this.getSyntax(match, "else-body");
212213
const finallySyntax = this.getSyntax(match, "finally-body");
213214
return this.withCluster("try-complex", (tryComplexCluster) => {
214215
const bodyBlock = this.withCluster("try", () =>
@@ -231,6 +232,9 @@ export class CFGBuilder {
231232
});
232233
}
233234

235+
// Create the `else` block before `finally` to handle returns correctly.
236+
const elseBlock = getBlock(elseSyntax);
237+
234238
const finallyBlock = this.withCluster("finally", () => {
235239
// Handle all the return statements from the try block
236240
if (finallySyntax) {
@@ -264,10 +268,19 @@ export class CFGBuilder {
264268
return finallyBlock;
265269
});
266270

271+
let complexExit: string | null = bodyBlock.exit;
272+
273+
// Connect the body to the `else` block
274+
if (bodyBlock.exit && elseBlock?.entry) {
275+
this.addEdge(bodyBlock.exit, elseBlock.entry);
276+
complexExit = elseBlock.exit;
277+
}
278+
267279
if (finallyBlock?.entry) {
268280
// Connect `try` to `finally`
269-
if (bodyBlock.exit) this.addEdge(bodyBlock.exit, finallyBlock.entry);
270-
281+
const toFinally = elseBlock?.exit ?? bodyBlock.exit;
282+
if (toFinally) this.addEdge(toFinally, finallyBlock.entry);
283+
complexExit = finallyBlock.exit;
271284
// Connect `except` to `finally`
272285
exceptBlocks.forEach((exceptBlock) => {
273286
if (exceptBlock.exit)
@@ -277,7 +290,7 @@ export class CFGBuilder {
277290

278291
return blockHandler.update({
279292
entry: bodyBlock.entry,
280-
exit: finallyBlock?.exit ?? bodyBlock.exit,
293+
exit: complexExit,
281294
});
282295
});
283296
}

src/test/commentTestSamples/sample.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,40 @@ def try_many_except_finally():
192192
return
193193

194194

195+
# exits: 0,
196+
# render: true
197+
def try_except_else_finally():
198+
try: pass
199+
except: pass
200+
else: pass
201+
finally: pass
202+
203+
# exits: 0,
204+
# render: true
205+
def massive_try_except_else_finally():
206+
try:
207+
try: pass
208+
except: pass
209+
else: pass
210+
finally: pass
211+
except:
212+
try: pass
213+
except: pass
214+
else: pass
215+
finally: pass
216+
else:
217+
if x:
218+
pass
219+
else:
220+
pass
221+
try:
222+
pass
223+
finally: pass
224+
finally:
225+
with x:
226+
for y in a:
227+
pass
228+
195229
# exits: 5,
196230
# render: true
197231
def try_finally():

0 commit comments

Comments
 (0)