Skip to content

Commit d7ae9f1

Browse files
committed
Docs for infinite loops
1 parent 813c413 commit d7ae9f1

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

doc/keywords.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ do
77
else export
88
f32 f64 fail false float fn for
99
i16 i32 i64 i8 if import in int
10-
let log
10+
let log loop
1111
mod mutable
1212
native note
1313
obj

doc/rust.md

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ do
216216
else enum export
217217
fail false fn for
218218
if iface impl import
219-
let log
219+
let log loop
220220
mod mutable
221221
native
222222
pure
@@ -1901,6 +1901,38 @@ do {
19011901
} while i < 10;
19021902
~~~~
19031903

1904+
### Infinite loops
1905+
1906+
A `loop` expression denotes an infinite loop:
1907+
1908+
~~~~~~~~{.ebnf .gram}
1909+
loop_expr : "loop" '{' block '}';
1910+
~~~~~~~~
1911+
1912+
For a block `b`, the expression `loop b` is semantically equivalent to
1913+
`while true b`. However, `loop`s differ from `while` loops in that the
1914+
typestate analysis pass takes into account that `loop`s are infinite.
1915+
1916+
For example, the following (contrived) function uses a `loop` with a
1917+
`ret` expression:
1918+
1919+
~~~~
1920+
fn count() -> bool {
1921+
let i = 0;
1922+
loop {
1923+
i += 1;
1924+
if i == 20 { ret true; }
1925+
}
1926+
}
1927+
~~~~
1928+
1929+
This function compiles, because typestate recognizes that the `loop`
1930+
never terminates (except non-locally, with `ret`), thus there is no
1931+
need to insert a spurious `fail` or `ret` after the `loop`. If `loop`
1932+
were replaced with `while true`, the function would be rejected
1933+
because from the compiler's perspective, there would be a control path
1934+
along which `count` does not return a value (that is, if the loop
1935+
condition is always false).
19041936

19051937
### Break expressions
19061938

0 commit comments

Comments
 (0)