Browse Source

warn about uninitialized vars usage in closures (closes #7447)

Aleksandr Kuzmenko 5 years ago
parent
commit
abbc1b66bf

+ 9 - 5
src/filters/filters.ml

@@ -69,7 +69,7 @@ let rec add_final_return e =
 (* -------------------------------------------------------------------------- *)
 (* CHECK LOCAL VARS INIT *)
 
-let check_local_vars_init e =
+let check_local_vars_init com e =
 	let intersect vl1 vl2 =
 		PMap.mapi (fun v t -> t && PMap.find v vl2) vl1
 	in
@@ -88,9 +88,13 @@ let check_local_vars_init e =
 		match e.eexpr with
 		| TLocal v ->
 			let init = (try PMap.find v.v_id !vars with Not_found -> true) in
-			if not init && not (IntMap.mem v.v_id !outside_vars) then begin
-				if v.v_name = "this" then error "Missing this = value" e.epos
-				else error ("Local variable " ^ v.v_name ^ " used without being initialized") e.epos
+			if not init then begin
+				if IntMap.mem v.v_id !outside_vars then
+					if v.v_name = "this" then com.warning "this might be used before assigning a value to it" e.epos
+					else com.warning ("Local variable " ^ v.v_name ^ " might be used before being initialized") e.epos
+				else
+					if v.v_name = "this" then error "Missing this = value" e.epos
+					else error ("Local variable " ^ v.v_name ^ " used without being initialized") e.epos
 			end
 		| TVar (v,eo) ->
 			begin
@@ -818,7 +822,7 @@ let run com tctx main =
 	t();
 	let filters = [
 		fix_return_dynamic_from_void_function tctx true;
-		check_local_vars_init;
+		check_local_vars_init tctx.com;
 		check_abstract_as_value;
 		if defined com Define.AnalyzerOptimize then Tre.run tctx else (fun e -> e);
 		Optimizer.reduce_expression tctx;

+ 12 - 0
tests/misc/projects/Issue7447/Main.hx

@@ -0,0 +1,12 @@
+class Main {
+	static function main() {
+		var v;
+		trace(() -> v);
+	}
+}
+
+abstract Abstr(Int) {
+	public inline function new() {
+		trace(() -> this);
+	}
+}

+ 1 - 0
tests/misc/projects/Issue7447/compile.hxml

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

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

@@ -0,0 +1,2 @@
+Main.hx:4: characters 15-16 : Warning : Local variable v might be used before being initialized
+Main.hx:10: characters 15-19 : Warning : this might be used before assigning a value to it