Selaa lähdekoodia

Allow `return;` from abstract constructor, and error on `return value;` (#9278)

* allow `return;` from abstract ctor
error on `return value;`

* generate texpr directly instead of generating and typing Ast.expr

* use get_this
Aleksandr Kuzmenko 5 vuotta sitten
vanhempi
commit
4450dfbb6e

+ 9 - 0
src/typing/typer.ml

@@ -2200,7 +2200,11 @@ and type_array_comprehension ctx e with_type p =
 	]) v.v_type p
 
 and type_return ?(implicit=false) ctx e with_type p =
+	let is_abstract_ctor = ctx.curfun = FunMemberAbstract && ctx.curfield.cf_name = "_new" in
 	match e with
+	| None when is_abstract_ctor ->
+		let e_cast = mk (TCast(get_this ctx p,None)) ctx.ret p in
+		mk (TReturn (Some e_cast)) t_dynamic p
 	| None ->
 		let v = ctx.t.tvoid in
 		unify ctx v ctx.ret p;
@@ -2211,6 +2215,11 @@ and type_return ?(implicit=false) ctx e with_type p =
 		in
 		mk (TReturn None) (if expect_void then v else t_dynamic) p
 	| Some e ->
+		if is_abstract_ctor then begin
+			match fst e with
+			| ECast((EConst(Ident "this"),_),None) -> ()
+			| _ -> display_error ctx "Cannot return a value from constructor" p
+		end;
 		try
 			let with_expected_type =
 				if implicit then WithType.of_implicit_return ctx.ret

+ 6 - 0
tests/misc/projects/Issue7809/ReturnEarly.hx

@@ -0,0 +1,6 @@
+abstract ReturnEarly(Int) from Int {
+	public function new(i:Int):Void {
+		return;
+		this = i;
+	}
+}

+ 6 - 0
tests/misc/projects/Issue7809/ReturnValue.hx

@@ -0,0 +1,6 @@
+abstract ReturnValue(Int) from Int {
+	public function new(i:Int):Void {
+		this = i;
+		return 123;
+	}
+}

+ 6 - 0
tests/misc/projects/Issue7809/ReturnVoid.hx

@@ -0,0 +1,6 @@
+abstract ReturnVoid(Int) from Int {
+	public function new(i:Int):Void {
+		this = i;
+		return;
+	}
+}

+ 1 - 0
tests/misc/projects/Issue7809/returnEarly-fail.hxml

@@ -0,0 +1 @@
+ReturnEarly

+ 1 - 0
tests/misc/projects/Issue7809/returnEarly-fail.hxml.stderr

@@ -0,0 +1 @@
+ReturnEarly.hx:3: characters 3-9 : Missing this = value

+ 1 - 0
tests/misc/projects/Issue7809/returnValue-fail.hxml

@@ -0,0 +1 @@
+ReturnValue

+ 1 - 0
tests/misc/projects/Issue7809/returnValue-fail.hxml.stderr

@@ -0,0 +1 @@
+ReturnValue.hx:4: characters 3-13 : Cannot return a value from constructor

+ 1 - 0
tests/misc/projects/Issue7809/returnVoid.hxml

@@ -0,0 +1 @@
+ReturnVoid