Browse Source

[typer] support @:const constraints

closes #6878
Simon Krajewski 7 years ago
parent
commit
0b12c33faa

+ 12 - 2
src/typing/typeload.ml

@@ -409,7 +409,17 @@ let check_param_constraints ctx types t pl c p =
 			try
 				unify_raise ctx t ti p
 			with Error(Unify l,p) ->
-				if not ctx.untyped then display_error ctx (error_msg (Unify (Constraint_failure (s_type_path c.cl_path) :: l))) p;
+				let fail() =
+					if not ctx.untyped then display_error ctx (error_msg (Unify (Constraint_failure (s_type_path c.cl_path) :: l))) p;
+				in
+				match follow t with
+				| TInst({cl_kind = KExpr e},_) ->
+					let e = type_expr {ctx with locals = PMap.empty} e (WithType ti) in
+					begin try unify_raise ctx e.etype ti p
+					with Error (Unify _,_) -> fail() end
+				| _ ->
+					fail()
+
 		) ctl
 
 let requires_value_meta com co =
@@ -3776,7 +3786,7 @@ type generic_context = {
 let generic_check_const_expr ctx t =
 	match follow t with
 	| TInst({cl_kind = KExpr e},_) ->
-		let e = type_expr ctx e Value in
+		let e = type_expr {ctx with locals = PMap.empty} e Value in
 		e.etype,Some e
 	| _ -> t,None
 

+ 13 - 0
tests/misc/projects/Issue6878/Main.hx

@@ -0,0 +1,13 @@
+@:generic
+class Foo<@:const T:Int> {
+   public function new() {
+       trace(T);
+   }
+}
+
+class Main {
+    public static function main() {
+    	new Foo<10>();
+		new Foo<"10">();
+    }
+}

+ 8 - 0
tests/misc/projects/Issue6878/Main1.hx

@@ -0,0 +1,8 @@
+class Main {
+    public static function main() {
+		test("10");
+		test(10);
+    }
+
+	@:generic static function test<T:String>(t:T) { }
+}

+ 2 - 0
tests/misc/projects/Issue6878/compile-fail.hxml

@@ -0,0 +1,2 @@
+-main Main
+--interp

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

@@ -0,0 +1,2 @@
+Main.hx:11: characters 7-16 : Constraint check failure for Foo.T
+Main.hx:11: characters 7-16 : "10" should be Int

+ 2 - 0
tests/misc/projects/Issue6878/compile1-fail.hxml

@@ -0,0 +1,2 @@
+-main Main1
+--interp

+ 2 - 0
tests/misc/projects/Issue6878/compile1-fail.hxml.stderr

@@ -0,0 +1,2 @@
+Main1.hx:4: characters 3-11 : Constraint check failure for test.T
+Main1.hx:4: characters 3-11 : Int should be String