lpython icon indicating copy to clipboard operation
lpython copied to clipboard

Add support for for-else

Open thebesttv opened this issue 2 years ago • 2 comments

This is my attempt at adding support for for-else (issue #1442, according to czgdp1807's comment).

A new ASR node ForElse is added. In visit_For() at python_ast_to_asr.cpp, loops with non-zero n_orelse are converted to ForElse.

An ASR pass "for_else", &pass_replace_forelse} is added, which consists of two steps:

  1. ForElseVisitor: ForElse is visited and converted to DoLoop with an initial assignment to a boolean flag variable (_no_break_N), and an If block at the end that executes orelse as long as the flag remains true. The flag variable corresponding to the DoLoop is recorded in doLoopFlagMap.
  2. ExitVisitor: Exit is visited, and its enclosing DoLoop is recorded in a stack. If an Exit is found, and the enclosing DoLoop is originally a ForElse, the corresponding flag is set to false.

Some tests are added, under tests/for_else.

thebesttv avatar Apr 14 '23 10:04 thebesttv

@thebesttv I am really sorry, we somehow totally missed this PR. Next time please don't hesitate to ping us if we forget. We usually are pretty good about that. Also when the PR is ready, as this one seems, go ahead and mark it "Ready for review". I think what you implemented one approach --- a separate node that gets transformed via ASR->ASR pass.

Why not adding a new member to DoLoop: https://github.com/lcompilers/lpython/issues/2353#issuecomment-1742743488?

certik avatar Oct 03 '23 15:10 certik

@certik I think this PR can be closed as #2555 was merged.

kmr-srbh avatar Apr 20 '24 03:04 kmr-srbh