Skip to content

Commit a5f1d7c

Browse files
committed
explicit for loop condition
1 parent e26b1bf commit a5f1d7c

File tree

4 files changed

+24
-3
lines changed

4 files changed

+24
-3
lines changed

compiler/ml/error_message_utils.ml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ type type_clash_context =
8888
}
8989
| FunctionArgument
9090
| Statement of type_clash_statement
91+
| ForLoopCondition
9192
9293
let fprintf = Format.fprintf
9394
@@ -113,6 +114,8 @@ let error_expected_type_text ppf type_clash_context =
113114
| Some TryReturn -> fprintf ppf "But this try/catch is expected to return:"
114115
| Some WhileCondition ->
115116
fprintf ppf "But a @{<info>while@} loop condition must always be of type:"
117+
| Some ForLoopCondition ->
118+
fprintf ppf "But a @{<info>for@} loop bounds must always be of type:"
116119
| Some IfCondition ->
117120
fprintf ppf "But @{<info>if@} conditions must always be of type:"
118121
| Some IfReturn ->

compiler/ml/typecore.ml

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2858,9 +2858,12 @@ and type_expect_ ~context ?in_function ?(recarg = Rejected) env sexp ty_expected
28582858
exp_env = env;
28592859
}
28602860
| Pexp_for (param, slow, shigh, dir, sbody) ->
2861-
(* TODO: Add explicit ForCondition *)
2862-
let low = type_expect ~context:None env slow Predef.type_int in
2863-
let high = type_expect ~context:None env shigh Predef.type_int in
2861+
let low =
2862+
type_expect ~context:(Some ForLoopCondition) env slow Predef.type_int
2863+
in
2864+
let high =
2865+
type_expect ~context:(Some ForLoopCondition) env shigh Predef.type_int
2866+
in
28642867
let id, new_env =
28652868
match param.ppat_desc with
28662869
| Ppat_any -> (Ident.create "_for", env)
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
2+
We've found a bug for you!
3+
/.../fixtures/for_loop_condition.res:1:16-19
4+
5+
1 │ for (x in 0 to "10") {
6+
2 │ Console.log(x)
7+
3 │ }
8+
9+
This has type: string
10+
But a for loop bounds must always be of type: int
11+
12+
You can convert string to int with Int.fromString.
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
for x in 0 to "10" {
2+
Console.log(x)
3+
}

0 commit comments

Comments
 (0)