Browse Source

[typer] type `null` against expected type if available

see #7736
Simon Krajewski 3 years ago
parent
commit
02a7f9834b
2 changed files with 21 additions and 5 deletions
  1. 19 3
      src/typing/typer.ml
  2. 2 2
      tests/misc/projects/Issue10504/compile-fail.hxml.stderr

+ 19 - 3
src/typing/typer.ml

@@ -311,9 +311,25 @@ let rec type_ident_raise ctx i p mode with_type =
 		| FunMemberClassLocal | FunMemberAbstractLocal -> typing_error "Cannot access super inside a local function" p);
 		| FunMemberClassLocal | FunMemberAbstractLocal -> typing_error "Cannot access super inside a local function" p);
 		AKExpr (mk (TConst TSuper) t p)
 		AKExpr (mk (TConst TSuper) t p)
 	| "null" ->
 	| "null" ->
-		if mode = MGet then
-			AKExpr (null (ctx.t.tnull (spawn_monomorph ctx p)) p)
-		else
+		if mode = MGet then begin
+			let tnull () = ctx.t.tnull (spawn_monomorph ctx p) in
+			let t = match with_type with
+				| WithType.WithType(t,_) ->
+					begin match follow t with
+					| TMono r ->
+						(* If our expected type is a monomorph, bind it to Null<?>. *)
+						Monomorph.do_bind r (tnull())
+					| _ ->
+						(* Otherwise there's no need to create a monomorph, we can just type the null literal
+						   the way we expect it. *)
+						()
+					end;
+					t
+				| _ ->
+					tnull()
+			in
+			AKExpr (null t p)
+		end else
 			AKNo i
 			AKNo i
 	| _ ->
 	| _ ->
 	try
 	try

+ 2 - 2
tests/misc/projects/Issue10504/compile-fail.hxml.stderr

@@ -1,5 +1,5 @@
-Main.hx:4: characters 9-10 : Warning : { foo : Unknown<0>, a : Int }
-Main.hx:6: characters 9-10 : Warning : { foo : Unknown<0>, ?b : Null<Int>, a : Int }
+Main.hx:4: characters 9-10 : Warning : { foo : Null<Unknown<0>>, a : Int }
+Main.hx:6: characters 9-10 : Warning : { foo : Null<Unknown<0>>, ?b : Null<Int>, a : Int }
 Main.hx:7: characters 10-11 : error: Int should be String
 Main.hx:7: characters 10-11 : error: Int should be String
 Main.hx:7: characters 10-11 : ... have: { b: Int }
 Main.hx:7: characters 10-11 : ... have: { b: Int }
 Main.hx:7: characters 10-11 : ... want: { b: String }
 Main.hx:7: characters 10-11 : ... want: { b: String }