[m-rev.] diff: Fix abort while typechecking X = coerce(X).

Peter Wang novalazy at gmail.com
Fri Jul 5 16:35:53 AEST 2024


compiler/typecheck_clauses.m:
    When typechecking coerce expressions, don't call
    type_assign_fresh_type_var a second time for the same variable.

tests/invalid/Mmakefile:
tests/invalid/coerce_same_var.err_exp:
tests/invalid/coerce_same_var.m:
    Add test case.

diff --git a/compiler/typecheck_clauses.m b/compiler/typecheck_clauses.m
index 47da3eb5a..3021fbe3d 100644
--- a/compiler/typecheck_clauses.m
+++ b/compiler/typecheck_clauses.m
@@ -1819,8 +1819,14 @@ typecheck_coerce_2(Context, FromVar, ToVar, TypeAssign0,
             TypeAssign2 = TypeAssign1
         ;
             MaybeToType = no,
-            type_assign_fresh_type_var(ToVar, ToType,
-                TypeAssign1, TypeAssign2)
+            % Handle X = coerce(X).
+            ( if ToVar = FromVar then
+                ToType = FromType,
+                TypeAssign2 = TypeAssign1
+            else
+                type_assign_fresh_type_var(ToVar, ToType,
+                    TypeAssign1, TypeAssign2)
+            )
         ),
         Coercion = coerce_constraint(FromType, ToType, Context, FromVar,
             need_to_check),
diff --git a/tests/invalid/Mmakefile b/tests/invalid/Mmakefile
index 9c8bf0de2..3ee003d5b 100644
--- a/tests/invalid/Mmakefile
+++ b/tests/invalid/Mmakefile
@@ -128,6 +128,7 @@ BORING_SINGLEMODULE_PROGS = \
 	coerce_non_du \
 	coerce_recursive_inst \
 	coerce_recursive_type \
+	coerce_same_var \
 	coerce_syntax \
 	coerce_type_error \
 	coerce_unify_tvars \
diff --git a/tests/invalid/coerce_same_var.err_exp b/tests/invalid/coerce_same_var.err_exp
new file mode 100644
index 000000000..3fb73abfb
--- /dev/null
+++ b/tests/invalid/coerce_same_var.err_exp
@@ -0,0 +1,3 @@
+coerce_same_var.m:017: In clause for predicate `main'/2:
+coerce_same_var.m:017:   error: the type of `X' is unresolved; cannot coerce
+coerce_same_var.m:017:   from `V_2' to `V_2'.
diff --git a/tests/invalid/coerce_same_var.m b/tests/invalid/coerce_same_var.m
new file mode 100644
index 000000000..8b2651861
--- /dev/null
+++ b/tests/invalid/coerce_same_var.m
@@ -0,0 +1,18 @@
+%---------------------------------------------------------------------------%
+% vim: ts=4 sw=4 et ft=mercury
+%---------------------------------------------------------------------------%
+
+:- module coerce_same_var.
+:- interface.
+
+:- import_module io.
+
+:- pred main(io::di, io::uo) is det.
+
+%---------------------------------------------------------------------------%
+
+:- implementation.
+
+main(!IO) :-
+    X = coerce(X),
+    io.print_line(X, !IO).
-- 
2.44.0



More information about the reviews mailing list