diff --git a/changes/empty-record-mutable-generalize.fix.md b/changes/empty-record-mutable-generalize.fix.md new file mode 100644 index 0000000000..49375a765b --- /dev/null +++ b/changes/empty-record-mutable-generalize.fix.md @@ -0,0 +1 @@ +- Stop generalizing the type of an empty record literal `{}` whose record has a mutable field, which let a value be stored at one type and read at another. diff --git a/compiler/ml/typecore.ml b/compiler/ml/typecore.ml index ddb271dfa5..85b3a05ee7 100644 --- a/compiler/ml/typecore.ml +++ b/compiler/ml/typecore.ml @@ -2095,7 +2095,14 @@ let rec is_nonexpansive exp = | None -> ( (* The optional fields the literal leaves out are allocated too *) match fields with - | [||] -> true + | [||] -> ( + (* [{}] has no field to find the record's labels through *) + match extract_concrete_record exp.exp_env exp.exp_type with + | _, _, decls, _ -> + List.for_all + (fun (ld : Types.label_declaration) -> ld.ld_mutable = Immutable) + decls + | exception Not_found -> false) | _ -> let lbl, _, _ = fields.(0) in Array.for_all (fun lbl -> lbl.lbl_mut = Immutable) lbl.lbl_all)) diff --git a/tests/build_tests/super_errors/expected/record_empty_mutable_does_not_generalize.res.expected b/tests/build_tests/super_errors/expected/record_empty_mutable_does_not_generalize.res.expected new file mode 100644 index 0000000000..02aa28f54a --- /dev/null +++ b/tests/build_tests/super_errors/expected/record_empty_mutable_does_not_generalize.res.expected @@ -0,0 +1,16 @@ + + We've found a bug for you! + /.../fixtures/record_empty_mutable_does_not_generalize.res:10:25-34 + + 8 │ let cell: cell<_> = {} + 9 │ cell.value = Some(1) + 10 │ let s: option = cell.value + 11 │ + + This has type: option + But it's expected to have type: option + + The incompatible parts: + int vs string + + You can convert int to string with Int.toString. \ No newline at end of file diff --git a/tests/build_tests/super_errors/fixtures/record_empty_mutable_does_not_generalize.res b/tests/build_tests/super_errors/fixtures/record_empty_mutable_does_not_generalize.res new file mode 100644 index 0000000000..2d0c6674c5 --- /dev/null +++ b/tests/build_tests/super_errors/fixtures/record_empty_mutable_does_not_generalize.res @@ -0,0 +1,10 @@ +// An immutable record still generalizes. +type options<'a> = {value?: 'a} +let defaults: options<_> = {} +let ints: options = defaults +let strings: options = defaults + +type cell<'a> = {tag?: int, mutable value?: 'a} +let cell: cell<_> = {} +cell.value = Some(1) +let s: option = cell.value