Using core.reflect to check for unused paramters

Stefan Koch uplink.coder at googlemail.com
Mon Aug 30 18:13:59 UTC 2021


Hi,

I've just extended core.reflect's reflection to function bodies.

Which means you can now do fun things such as checking for unused 
parameters at compile-time.

If you checkout the core.reflect branch from my forks of druntime 
and dmd you can run the example code below and convince yourself 
that it works

```d
import core.reflect.reflect;
import core.reflect.transitiveVisitor;
// import core.reflect.nodeToString();

int func(int a, int b)
{
     return a + b;
}
static assert(!hasUnusedParameters(nodeFromName("func")));

int func2(int a, int b, int c)
{
     return func(a, b);
}
static assert(hasUnusedParameters(nodeFromName("func2")));


bool hasUnusedParameters(const Node n)
{
     bool result = false;
     if (auto fd = cast(FunctionDeclaration) n)
     {
         result = hasUnusedParameters(fd);
     }
     return result;
}

bool hasUnusedParameters(const FunctionDeclaration fd)
{
     bool[const(VariableDeclaration)] parameterUsageList;
     foreach(p;fd.parameters)
     {
         parameterUsageList[p] = false;
     }

     class Marker : TransitiveVisitor
     {
         bool[const(VariableDeclaration)]* parameterUsageList;

         this(bool[const(VariableDeclaration)] *parameterUsageList)
         {
             this.parameterUsageList = parameterUsageList;
         }

         alias visit = TransitiveVisitor.visit;
         override void visit(VariableDeclaration vd)
         {
             if (auto b = vd in *parameterUsageList)
             {
                 *b = true;
             }
         }
     }

     scope marker = new Marker(&parameterUsageList);
     (cast()fd.fbody).accept(marker);

     foreach(v, unused; parameterUsageList)
     {
         if (!unused) return true;
     }
     return false;
}
```

I am aware that these block of code posts of mine are not the 
most appealing.
Please wait a little I will have more high-levels descriptions as 
the core.reflect prototype gets closer to a stable state.


More information about the Digitalmars-d mailing list