Browse Source

prohibit @:structInit on interfaces (closes #9017)

Aleksandr Kuzmenko 5 năm trước cách đây
mục cha
commit
322f9cdcae

+ 11 - 2
src/typing/typeloadFields.ml

@@ -1563,9 +1563,18 @@ let init_class ctx c p context_init herits fields =
 	(*
 		make sure a default contructor with same access as super one will be added to the class structure at some point.
 	*)
-	let has_struct_init = Meta.has Meta.StructInit c.cl_meta in
+	let has_struct_init, struct_init_pos =
+		try
+			let _,_,p = Meta.get Meta.StructInit c.cl_meta in
+			true, p
+		with Not_found ->
+			false, null_pos
+	in
 	if has_struct_init then
-		ensure_struct_init_constructor ctx c fields p;
+		if c.cl_interface then
+			display_error ctx "@:structInit is not allowed on interfaces" struct_init_pos
+		else
+			ensure_struct_init_constructor ctx c fields p;
 	begin match cctx.uninitialized_final with
 		| Some pf when c.cl_constructor = None ->
 			display_error ctx "This class has uninitialized final vars, which requires a constructor" p;

+ 11 - 0
tests/misc/projects/Issue9017/Main.hx

@@ -0,0 +1,11 @@
+class Main {
+	static function main() {
+		var f:Foo = { field:1 };
+		trace(f.field);
+	}
+}
+
+@:structInit
+interface Foo {
+	var field:Int;
+}

+ 1 - 0
tests/misc/projects/Issue9017/compile-fail.hxml

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

+ 3 - 0
tests/misc/projects/Issue9017/compile-fail.hxml.stderr

@@ -0,0 +1,3 @@
+Main.hx:8: characters 1-13 : @:structInit is not allowed on interfaces
+Main.hx:9: lines 9-11 : Defined in this class
+Main.hx:3: characters 15-26 : Foo does not have a constructor