Last active
December 14, 2015 06:58
-
-
Save jasononeil/5046390 to your computer and use it in GitHub Desktop.
Very simple proof of concept for a macro which checks that all member variables and static variables have been initialised. Currently it checks for every single type... so it finds a bunch of errors in the standard library too. Someone may want to fork it and make it a little bit more clever... UPDATE: modified it to only check Int, Float, Strin…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Only tested on Neko, Haxe3RC | |
// Compile and run with: | |
// haxe -x InitialisationChecker.hx | |
// Created by Jason O'Neil, 2013. Release public domain. | |
#if macro | |
import haxe.macro.Context; | |
using Lambda; | |
#end | |
class InitialisationChecker | |
{ | |
static function main() | |
{ | |
checkAllFieldsInitialised(); | |
new TestA(); | |
} | |
macro static function checkAllFieldsInitialised() | |
{ | |
Context.onGenerate(function (types:Array<haxe.macro.Type>) { | |
for (type in types) | |
{ | |
// We're only interested in classes, type=TInst() | |
switch (type) | |
{ | |
case TInst(t, _): | |
// Check all instance fields are initialised | |
var members = t.get().fields.get(); | |
var statics = t.get().statics.get(); | |
var allFields = members.concat(statics); | |
for (field in allFields) | |
{ | |
// We want kind=FVar(), type=TAbstract(Int,Bool,Float) or TInst(String) | |
var typesToCheck = ["Int", "Float", "Bool", "String"]; | |
var matching = switch [field.kind, field.type] | |
{ | |
case [ FVar(_,_), TInst(fType,_) ] if (typesToCheck.has(fType.toString())): true; | |
case [ FVar(_,_), TAbstract(fType,_) ] if (typesToCheck.has(fType.toString())): true; | |
default: false; | |
} | |
if (matching && field.expr() == null) | |
{ | |
Context.warning('In class $t field ${field.name} was not initialised', field.pos); | |
} | |
} | |
default: | |
// pass | |
} | |
} | |
}); | |
return macro 0; | |
} | |
} | |
class TestA | |
{ | |
public function new() {} | |
var s1:String; | |
var s2:String = "Hello"; | |
var i1:Int; | |
var i2:Int = 10; | |
var f1:Float; | |
var f2:Float = 1.333; | |
var d1:Date; | |
var d2:Date = null; | |
var b1:Bool; | |
var b2:Bool = true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment