Difference between revisions of "Finding all Functions in a Module"

From D Wiki
Jump to: navigation, search
(Created page with "{{Cookbook |category=Meta Programming |level=Novice |type=Recipe |status=Draft |time=15 min |dversion=D2 |display=none }} This recipe show how to list all functions in a modu...")
 
m
Line 9: Line 9:
 
}}
 
}}
  
This recipe show how to list all functions in a module. More generally, it can be used to list all symbols in a module and filter them according to a specific predicate.
+
This recipe shows how to list all functions in a module. More generally, it can be used to list all symbols in a module and filter them according to a specific predicate.
  
 
First, we need a tuple of all symbol names in a module:
 
First, we need a tuple of all symbol names in a module:

Revision as of 13:30, 23 March 2014

Level: Novice
Cookbook Type: Recipe
Cookbook Status: Draft
Approximate reading time: 15 min
0.249 hr
D Version: D2


This recipe shows how to list all functions in a module. More generally, it can be used to list all symbols in a module and filter them according to a specific predicate.

First, we need a tuple of all symbol names in a module:

__traits(allMembers, mymodule)

Note that __traits(allMembers, XXX) returns a tuple of strings, not a tuple of symbols.

To iterate on this tuple, a simple foreach works very well:

foreach(m; __traits(allMembers, mymodule)) 
    {
       //
    }

Inside the foreach loop, we can use __traits(getMember, parentSymbol, name) to transform name (a string) into a real symbol. Then static if will test each symbol in turn. Here the predicate is__traits(isStaticFunction, XXX):

Program Code

module mymodule;
import std.stdio : writeln;

void main() {

    foreach(m; __traits(allMembers, mymodule)) 
    {
        static if (__traits(isStaticFunction, __traits(getMember, mymodule, m))) 
            writeln(m);     
    }
}

void myfunc() {}

int myOtherFunc(int i) { return i+1; }

Compilation Output

main
myfunc
myOtherFunc