Skip to content

Commit dbecb97

Browse files
committed
Auto-fix: Add support for 'use_while_loops'
1 parent 0d83860 commit dbecb97

File tree

3 files changed

+51
-1
lines changed

3 files changed

+51
-1
lines changed

lkql_checker/share/lkql/use_while_loops.lkql

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,27 @@
1+
import stdlib
2+
3+
fun replace_by_while_loop(simple_loop, ctx) =
4+
|" Replace the given ``simple_loop`` with an exit condition as first
5+
|" statement with a while loop.
6+
{
7+
val negated_exit_cond = match simple_loop.f_stmts[1].f_cond_expr
8+
| null => new Identifier("False")
9+
| op@(RelationOp | UnOp(f_op: OpNot)) => stdlib.negate_op(op)
10+
| e => new UnOp(new OpNot(), e);
11+
ctx.remove(simple_loop.f_stmts[1])
12+
.replace(
13+
simple_loop,
14+
new WhileLoopStmt(
15+
f_spec=new WhileLoopSpec(negated_exit_cond),
16+
f_stmts=simple_loop.f_stmts,
17+
f_end_name=simple_loop.f_end_name
18+
)
19+
)
20+
}
21+
122
@check(message="simple LOOP may be replaced by a WHILE loop",
2-
category="Style", subcategory="Programming Practice")
23+
category="Style", subcategory="Programming Practice",
24+
auto_fix=replace_by_while_loop)
325
fun use_while_loops(node) =
426
|" Flag simple loop statements that have the exit statement completing
527
|" execution of such a loop as the first statement in their sequence of

testsuite/tests/checks/use_while_loops/test.out

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,30 @@ loop1.adb:28:4: rule violation: simple LOOP may be replaced by a WHILE loop
1616
30 || end loop Local_Loop;
1717
||_______________________^
1818

19+
Patched "loop1.adb":
20+
====================
21+
22+
procedure Loop1 (Str : in out String) is
23+
J : Integer;
24+
begin
25+
J := 0;
26+
while J <=10 loop if Str (J) = ' ' then
27+
Str (J) := 'a';
28+
return;
29+
end if;
30+
31+
J := J + 1;
32+
end loop;loop -- NOFLAG
33+
null;
34+
end loop;
35+
36+
Outer_Loop:
37+
loop -- NOFLAG
38+
loop -- NOFLAG
39+
exit Outer_Loop when True;
40+
end loop;
41+
end loop Outer_Loop;
42+
43+
Local_Loop:
44+
while False loop end loop Local_Loop;end Loop1;
45+
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
driver: 'checker'
22
rule_name: use_while_loops
33
project: 'prj.gpr'
4+
auto_fix: True

0 commit comments

Comments
 (0)