Search code examples
overloadingnim-lang

In nim is there a way to get a list of all procedures with a given name?


In Nim is there a way to get a list of the declarations of all procedures with a given name which are defined at a given point in the code? For example I am looking for a function TYPE where following code

proc Sum(self: seq[int]):int =
    do something

echo $TYPE(Sum)

proc Sum(self: seq[float]):float =
    do something

echo $TYPE(Sum)

would print

@[proc Sum(self: seq[int]):int]
@[proc Sum(self: seq[int]):int, proc Sum(self: seq[float]):float]

Solution

  • Given a symbol you can do it with a macro and getImpl, you just need to make sure to iterate over all the sym choices:

    import macros, strutils
    
    macro TYPE(x: typed): untyped =
      result = quote do:
        seq[string](@[])
        
      template addSignature(x: untyped) =
        let impl = x.getImpl
        assert impl.kind == nnkProcDef, "Symbol not a procedure!"
        result[1][1].add newLit(impl.repr.splitLines[0][0..^3]) # Bit of a hack
        
      if x.kind == nnkSym:
        addSignature(x)
      else:
        for y in x:
          addSignature(y)
          
      echo result.treeRepr
    
    
    proc Sum(self: seq[int]):int =
      echo self
    
    echo $TYPE(Sum)
    
    proc Sum(self: seq[float]):float =
      echo self
    
    echo $TYPE(Sum)