1 /** 2 * Contains functions to mixin to simplify code reuse. For these to work, the parameters of a native function 3 * must be called context, thisObj, args, and nfe. 4 */ 5 module mildew.binder; 6 7 import std.format: format; 8 import std.conv: to; 9 10 /** 11 * Check for a minimum number of arguments. This must be used if using TO_ARG 12 */ 13 string CHECK_MINIMUM_ARGS(int num)() 14 { 15 return format(q{ 16 if(args.length < %1$s) 17 { 18 nfe = NativeFunctionError.WRONG_NUMBER_OF_ARGS; 19 return ScriptAny.UNDEFINED; 20 } 21 }, num.to!string); 22 } 23 24 /** 25 * Shorthand for validating a this object as a native type 26 */ 27 string CHECK_THIS_NATIVE_OBJECT(string varName, alias dclass)() 28 { 29 return format(q{ 30 auto %1$s = thisObj.toNativeObject!%2$s; 31 if(%1$s is null) 32 { 33 nfe = NativeFunctionError.WRONG_TYPE_OF_ARG; 34 return ScriptAny.UNDEFINED; 35 } 36 }, varName, dclass.stringof); 37 } 38 39 /** 40 * Uses .init value of a variable if argument doesn't exist. Arguments length MUST be checked first 41 */ 42 string TO_ARG(string varName, int index, alias type)() 43 { 44 return format(q{ 45 auto %1$s = args[%2$s].toValue!%3$s; 46 }, varName, index.to!string, type.stringof); 47 } 48 49 /** 50 * Get an optional argument and default value 51 */ 52 string TO_ARG_OPT(string varName, int index, alias defaultValue, alias type)() 53 { 54 return format(q{ 55 auto %1$s = %3$s; 56 if(%2$s < args.length) 57 { 58 %1$s = args[%2$s].toValue!%4$s; 59 } 60 }, varName, index.to!string, defaultValue.stringof, type.stringof); 61 } 62 63 /** 64 * Shorthand for extracting an argument without validating its type 65 */ 66 string TO_ARG_CHECK_INDEX(string varName, int index, alias type)() 67 { 68 return format(q{ 69 if(args.length < %2$s + 1) 70 { 71 nfe = NativeFunctionError.WRONG_NUMBER_OF_ARGS; 72 return ScriptAny.UNDEFINED; 73 } 74 auto %1$s = args[%2$s].toValue!%3$s; 75 }, varName, index.to!string, type.stringof); 76 } 77