Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module straw.core_test.a;
- import std.stdio;
- import straw.core.hooks;
- @callOnAppInit()
- void moduleInit() {
- writeln( "Called" );
- }
- // --------------------------------------------------------------------------------
- module straw.core.hooks;
- import std.array;
- import std.conv;
- import std.typetuple;
- /**
- * !!! USE callOnAppInit() NOT ONLY callOnAppInit, OTHERWISE IT WON'T WORK !!!
- * .
- * Use this as an attribute to mark a function that will be automatically called on app init (shared static this time).
- * The desired function has to be in the root of the module and has to be public. The function must be of type 'void function()';
- * This is a workaround for using shared static this, which isn't allowed in any two modules that are imported in each another.
- * The call order between modules in unspecified, it is expected that you only register hooks in marked routine.
- * */
- auto callOnAppInit( string module_ = __MODULE__, string function_ = __FUNCTION__, size_t line_ = __LINE__ )() {
- static assert( !function_.length, "@callOnAppInit has to be used in root!" );
- return Attr_CallOnAppInit!( module_, line_ )();
- }
- private struct Attr_CallOnAppInit( string module_, size_t line_ ) {
- private:
- enum IS_ATTR_CallOnAppInit = true;
- enum ATTR_LINE = line_;
- private:
- shared static this() {
- mixin( "static import " ~ module_ ~ ";" );
- alias moduleAlias = TypeTuple!( mixin( module_ ) );
- mixin( {
- size_t numFound;
- string result;
- foreach( memName; __traits( derivedMembers, moduleAlias ) ) {
- static if( __traits( compiles, __traits( getMember, moduleAlias, memName ) ) ) {
- foreach( attribute; __traits( getAttributes, __traits( getMember, moduleAlias, memName ) ) ) {
- static if( __traits( compiles, attribute.IS_ATTR_CallOnAppInit ) && attribute.ATTR_LINE == line_ ) {
- static assert( is( typeof( &__traits( getMember, moduleAlias, memName ) ) == void function() ), "The function '" ~ memName ~ "' in module '" ~ module_ ~ "' is of type '" ~ ( typeof( __traits( getMember, moduleAlias, memName ) ) ).stringof ~ "' not of type 'void function()'!" );
- result ~= "__traits( getMember, moduleAlias, \"" ~ memName ~ "\" )();\n";
- numFound ++;
- }
- }
- }
- }
- assert( numFound, "Could not find any relevant @callOnAppInit rutines in module '" ~ module_ ~ "' (#" ~ line_.to!string ~ "). Perhaps you marked it private?" );
- return result;
- } () );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment