Skip to content

Commit 2a3c984

Browse files
cknittclaude
andauthored
Make char an alias of int
`char` was a private abbreviation of `int`: a char could be coerced to an int with `:>`, but an int could not be used as a char. It is now a plain alias, so char literals and ints mix freely, including in one `switch`. Pattern matching treats a char constant and an int constant with the same value as the same constant, for exhaustiveness, unused cases and switch compilation. Char literals keep their spelling in generated JavaScript comments and in warning examples. First step of #7028. Example (rescript): let f = x => switch x { | '\000' .. '\255' => 0 | 'ō' => 2 | _ => 3 } Before (js): function f(x) { if (x !== 333) { if (x >= 256) { return 3; } else { return 0; } } else { return 2; } } After (js): function f(x) { if (x >= 256) { if (x !== 333) { return 3; } else { return 2; } } else if (x >= 0) { return 0; } else { return 3; } } Source: tests/tests/src/string_unicode_test.mjs in the diff (the range starts at code point 0, written as a literal NUL character in the test). Review: Why keep `Const_char` instead of typing char literals as ints? It keeps the `/* 'a' */97` comments in the JavaScript and the char spelling in warnings such as "for example: | '\x00'". Review: Why do char switches now use int32 bounds instead of 0..max_int? A char can now hold any int, including negative ones, so a switch can no longer assume `x >= 0`. Two committed snapshots change for that reason. Review: Do integer range patterns such as `1 .. 5` work now? No, they still report `Invalid_interval`. Char ranges expand to one case per value, which does not scale to arbitrary ints; that needs interval patterns of their own. Area: typechecker lambda analysis tests Output: changed tests/tests/src/adt_optimize_test.mjs and string_unicode_test.mjs, char switches whose range starts at '\000' now send negative values to the default case Formatting: unchanged Formats: none PPX: unchanged Editor: pipe completion on a `char` value offers `Int` functions; it offered none before (tests/analysis_tests/tests/src/CompletionChar.res) Errors: ERROR_VARIANTS.md warnings section lists the two new warning 8 and 11 fixtures Tests: +tests/tests/src/char_int_alias_test.res +tests/analysis_tests/tests/src/CompletionChar.res +tests/build_tests/super_errors/fixtures/warning_8_char_int_patterns.res +tests/build_tests/super_errors/fixtures/warning_11_equivalent_char_int_patterns.res ~tests/tests/src/adt_optimize_test.mjs ~tests/tests/src/string_unicode_test.mjs Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01JALXUyHhkDqzcB3WuW9Svo Signed-off-by: Christoph Knittel <ck@cca.io>
1 parent 4252552 commit 2a3c984

17 files changed

Lines changed: 346 additions & 51 deletions

‎analysis/src/type_utils.ml‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1330,7 +1330,9 @@ let rec find_root_type_id ~full ~env ~state (t : Types.type_expr) =
13301330
then
13311331
Some
13321332
(if debug then Printf.printf "[find_root_type_id] returning builtin\n";
1333-
Path.name path)
1333+
(* [char] is an alias of [int] *)
1334+
if Path.same path Predef.path_char then Path.name Predef.path_int
1335+
else Path.name path)
13341336
else None)
13351337
| _ -> None
13361338

@@ -1396,7 +1398,7 @@ let completion_path_from_maybe_builtin path =
13961398
| Some ("list", _) -> Some ["Stdlib"; "List"]
13971399
| Some ("result", _) -> Some ["Stdlib"; "Result"]
13981400
| Some ("dict", _) -> Some ["Stdlib"; "Dict"]
1399-
| Some ("char", _) -> Some ["Stdlib"; "Char"]
1401+
| Some ("char", _) -> Some ["Stdlib"; "Int"]
14001402
| _ -> (
14011403
match path |> Utils.expand_path |> List.rev with
14021404
| [main_module; "t"] when String.starts_with ~prefix:"Stdlib_" main_module

‎changes/char-int-alias.feature.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
- `char` is now an alias of `int`, so char literals and ints mix freely, including in `switch` patterns.

‎compiler/ml/matching.ml‎

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1147,28 +1147,30 @@ let add make_matching_fun division eq_key key patl_action args =
11471147
cell.pm.cases <- [patl_action];
11481148
(key, cell) :: division
11491149

1150-
(* Cells whose key is [hashable] are also found by hashing, which must agree
1151-
with [eq_key]. This keeps a column of many distinct keys linear. *)
1152-
let divide ?(hashable = fun _ -> false) make eq_key get_key get_args ctx pm =
1150+
(* Cells whose key has a [hash_key] are also found by hashing on it, which
1151+
must agree with [eq_key]. This keeps a column of many distinct keys
1152+
linear. *)
1153+
let divide ?(hash_key = fun _ -> None) make eq_key get_key get_args ctx pm =
11531154
let cells = lazy (Hashtbl.create 16) in
11541155
let rec divide_rec = function
11551156
| (p :: patl, action) :: rem -> (
11561157
let this_match = divide_rec rem in
11571158
let key = get_key p in
11581159
let patl_action = (get_args p patl, action) in
1159-
if not (hashable key) then
1160+
match hash_key key with
1161+
| None ->
11601162
add (make p pm.default ctx) this_match eq_key key patl_action pm.args
1161-
else
1163+
| Some hkey -> (
11621164
let cells = Lazy.force cells in
1163-
match Hashtbl.find_opt cells key with
1165+
match Hashtbl.find_opt cells hkey with
11641166
| Some cell ->
11651167
cell.pm.cases <- patl_action :: cell.pm.cases;
11661168
this_match
11671169
| None ->
11681170
let cell = make p pm.default ctx pm.args in
11691171
cell.pm.cases <- [patl_action];
1170-
Hashtbl.add cells key cell;
1171-
(key, cell) :: this_match)
1172+
Hashtbl.add cells hkey cell;
1173+
(key, cell) :: this_match))
11721174
| _ -> []
11731175
in
11741176
@@ -1226,9 +1228,10 @@ let make_constant_matching p def ctx = function
12261228
12271229
let divide_constant ctx m =
12281230
divide
1229-
~hashable:(function
1230-
| Asttypes.Const_int _ | Const_char _ | Const_string _ -> true
1231-
| Const_float _ | Const_bigint _ -> false)
1231+
~hash_key:(function
1232+
| (Asttypes.Const_int _ | Const_char _ | Const_string _) as c ->
1233+
Some (Parmatch.const_key c)
1234+
| Const_float _ | Const_bigint _ -> None)
12321235
make_constant_matching
12331236
(fun c d -> const_compare c d = 0)
12341237
(get_key_constant "divide")
@@ -1999,27 +2002,19 @@ let combine_constant loc arg cst partial ctx def
19992002
let fail, local_jumps = mk_failaction_neg partial ctx def in
20002003
let lambda1 =
20012004
match (cst : Asttypes.constant) with
2002-
| Const_int _ ->
2005+
| Const_int _ | Const_char _ ->
2006+
(* [char] is an alias of [int], so a column can mix both. *)
20032007
let int_lambda_list =
20042008
List.map
20052009
(function
2006-
| Asttypes.Const_int n, l -> (n, l)
2010+
| (Asttypes.Const_int n | Const_char n), l -> (n, l)
20072011
| _ -> assert false)
20082012
const_lambda_list
20092013
in
20102014
(* Match intervals must use ReScript's int32 bounds, not the host's.
20112015
Otherwise the upper fail interval starts at 2147483648, which wraps
20122016
when converted to a Lambda integer constant. *)
20132017
call_switcher fail arg int32_low int32_high int_lambda_list
2014-
| Const_char _ ->
2015-
let int_lambda_list =
2016-
List.map
2017-
(function
2018-
| Asttypes.Const_char c, l -> (c, l)
2019-
| _ -> assert false)
2020-
const_lambda_list
2021-
in
2022-
call_switcher fail arg 0 max_int int_lambda_list
20232018
| Const_string _ ->
20242019
(* Note as the bytecode compiler may resort to dichotomic search,
20252020
the clauses of stringswitch are sorted with duplicates removed.

‎compiler/ml/parmatch.ml‎

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,7 @@ let all_coherent column =
155155
| _ -> false)
156156
| Tpat_constant c1, Tpat_constant c2 -> (
157157
match (c1, c2) with
158-
| Const_char _, Const_char _
159-
| Const_int _, Const_int _
158+
| (Const_char _ | Const_int _), (Const_char _ | Const_int _)
160159
| Const_bigint _, Const_bigint _
161160
| Const_float _, Const_float _
162161
| Const_string _, Const_string _ ->
@@ -270,8 +269,16 @@ let const_compare x y =
270269
| Const_bigint (s1, b1), Const_bigint (s2, b2) ->
271270
Bigint_utils.compare (s1, b1) (s2, b2)
272271
| Const_string s1, Const_string s2 -> String.compare s1 s2
272+
| (Const_char i1 | Const_int i1), (Const_char i2 | Const_int i2) ->
273+
compare i1 i2
273274
| _, _ -> compare x y
274275

276+
(* [char] is an alias of [int], so a char constant and an int constant with the
277+
same value match the same values. Hash tables of constants use this key. *)
278+
let const_key = function
279+
| Const_char i -> Const_int i
280+
| c -> c
281+
275282
let records_args l1 l2 =
276283
(* Invariant: fields are already sorted by Typecore.type_record_elem_list *)
277284
let rec combine r1 r2 l1 l2 =
@@ -765,7 +772,7 @@ let filter_all pat0 pss =
765772
let insert q qs =
766773
match q.pat_desc with
767774
| Tpat_constant ((Const_int _ | Const_char _ | Const_string _) as c) ->
768-
find_or_add const_groups c q qs
775+
find_or_add const_groups (const_key c) q qs
769776
| Tpat_variant (l, _, _) -> find_or_add variant_groups l q qs
770777
| _ -> (
771778
match List.find_opt (fun (q0, _) -> simple_match q0 q) !groups with
@@ -1058,21 +1065,18 @@ let build_other ext env : Typedtree.pattern =
10581065
(fun p_res pat ->
10591066
make_pat (Tpat_or (pat, p_res, None)) p.pat_type p.pat_env)
10601067
pat other_pats)
1061-
| (({pat_desc = Tpat_constant (Const_int _)} as p), _) :: _ ->
1062-
build_other_constant
1063-
(function
1064-
| Tpat_constant (Const_int i) -> i
1065-
| _ -> assert false)
1066-
(function
1067-
| i -> Tpat_constant (Const_int i))
1068-
0 succ p env
1069-
| (({pat_desc = Tpat_constant (Const_char _)} as p), _) :: _ ->
1068+
| (({pat_desc = Tpat_constant ((Const_int _ | Const_char _) as c)} as p), _)
1069+
:: _ ->
1070+
(* Int and char constants can share a column; the example takes the kind
1071+
of the first one. *)
10701072
build_other_constant
10711073
(function
1072-
| Tpat_constant (Const_char i) -> i
1074+
| Tpat_constant (Const_int i | Const_char i) -> i
10731075
| _ -> assert false)
1074-
(function
1075-
| i -> Tpat_constant (Const_char i))
1076+
(fun i ->
1077+
match c with
1078+
| Const_char _ -> Tpat_constant (Const_char i)
1079+
| _ -> Tpat_constant (Const_int i))
10761080
0 succ p env
10771081
| (({pat_desc = Tpat_constant (Const_bigint _)} as p), _) :: _ ->
10781082
build_other_constant
@@ -1713,7 +1717,7 @@ let get_mins_pats pss =
17131717
Tpat_constant ((Const_int _ | Const_char _ | Const_string _) as c);
17141718
}
17151719
:: _ ->
1716-
Some c
1720+
Some (const_key c)
17171721
| _ -> None
17181722
in
17191723
(* [select_rec [] pss] of [get_mins le_pats]: drops each row covered by a

‎compiler/ml/parmatch.mli‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ val all_record_args :
3434
(Longident.t loc * label_description * pattern * bool) list
3535
val const_compare : constant -> constant -> int
3636

37+
(* A hash key agreeing with [const_compare]: char constants map to ints. *)
38+
val const_key : constant -> constant
39+
3740
val le_pat : pattern -> pattern -> bool
3841
val le_pats : pattern list -> pattern list -> bool
3942

‎compiler/ml/predef.ml‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -434,9 +434,8 @@ let common_initial_env add_type add_extension empty_env =
434434

435435
let build_initial_env add_type add_exception empty_env =
436436
let common = common_initial_env add_type add_exception empty_env in
437-
let decl_type_char =
438-
{decl_abstr with type_manifest = Some (type_int ()); type_private = Private}
439-
in
437+
(* [char] is an alias of [int]: a char literal is its code point. *)
438+
let decl_type_char = {decl_abstr with type_manifest = Some (type_int ())} in
440439
add_type ident_char decl_type_char common
441440

442441
let () =

‎tests/ERROR_VARIANTS.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -559,7 +559,10 @@ warnings still fire.
559559

560560
Fixtures follow the naming convention `warning_<NN>_<description>.res`
561561
so coverage gaps stay greppable. Warning 11 (`Unused_match`) is covered by
562-
`warning_11_equivalent_string_patterns.res`, and warning 111
562+
`warning_11_equivalent_string_patterns.res` and
563+
`warning_11_equivalent_char_int_patterns.res`, warning 8
564+
(`Partial_match`) on mixed char and int patterns by
565+
`warning_8_char_int_patterns.res`, and warning 111
563566
(`Bs_private_record_mutation`, a write to a private record field) by
564567
`private_label.res`.
565568

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// `char` is an alias of `int`, so a char completes `Int` functions.
2+
let c = 'a'
3+
// let _ = c->toS
4+
// ^com
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
Complete src/CompletionChar.res 2:17
2+
pos_cursor:[2:17] pos_no_white:[2:16] Found expr:[2:11->2:17]
3+
Completable: Cpath Value[c]->toS
4+
Package opens Stdlib.place holder Pervasives.JsxModules.place holder
5+
Resolved opens 1 Stdlib
6+
ContextPath Value[c]->toS
7+
ContextPath Value[c]
8+
Path c
9+
Path Stdlib.Int.toS
10+
Path toS
11+
[
12+
{
13+
"deprecated": true,
14+
"detail": "(int, ~radix: int) => string",
15+
"documentation": {
16+
"kind": "markdown",
17+
"value": "Deprecated: Use `toString` instead\n\n\n`toStringWithRadix(n, ~radix)` return a `string` representing the given value.\n`~radix` specifies the radix base to use for the formatted number.\nSee [`Number.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString)\non MDN.\n\n## Examples\n\n```rescript\nInt.toStringWithRadix(6, ~radix=2) // \"110\"\nInt.toStringWithRadix(373592855, ~radix=16) // \"16449317\"\nInt.toStringWithRadix(123456, ~radix=36) // \"2n9c\"\n```\n\n## Exceptions\n\n`RangeError`: if `radix` is less than 2 or greater than 36.\n"
18+
},
19+
"kind": 12,
20+
"label": "Int.toStringWithRadix",
21+
"tags": [ 1 ]
22+
},
23+
{
24+
"detail": "(int, ~radix: int=?) => string",
25+
"documentation": {
26+
"kind": "markdown",
27+
"value": "\n`toString(n, ~radix=?)` return a `string` representing the given value.\n`~radix` specifies the radix base to use for the formatted number.\nSee [`Number.toString`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toString)\non MDN.\n\n## Examples\n\n```rescript\nInt.toString(1000) // \"1000\"\nInt.toString(-1000) // \"-1000\"\nInt.toString(6, ~radix=2) // \"110\"\nInt.toString(373592855, ~radix=16) // \"16449317\"\nInt.toString(123456, ~radix=36) // \"2n9c\"\n```\n\n## Exceptions\n\n`RangeError`: if `radix` is less than 2 or greater than 36.\n"
28+
},
29+
"kind": 12,
30+
"label": "Int.toString",
31+
"tags": []
32+
}
33+
]
34+
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
2+
Warning number 11
3+
/.../fixtures/warning_11_equivalent_char_int_patterns.res:5:5-6
4+
5+
3 ┆ switch x {
6+
4 ┆ | 'a' => 1
7+
5 ┆ | 97 => 2
8+
6 ┆ | _ => 3
9+
7 ┆ }
10+
11+
this match case is unused.

0 commit comments

Comments
 (0)