Get the name of the current running function

Hi guys, I would like to know if there is a way to get the name of the a current running function. Like at the beginning of the function bloc, get it name

Maybe Macros - Crystal would do what you’re wanting?

Oh nice, so now I have another question related to your answer. Is it possible to make a behavior that everytime a function is running in a class, by default it run first a command that record the function name and class name.

def mainKernelVersion : String
            Ism.recordSystemCall(command: "#{{% @def.receiver %}}.#{{% @def.name %}}")
            
            return Ism.selectedKernel.version
        end

I would like basically to avoid to call for each function by copy paste always Ism.recordSystemCall. I would like as default behavior that when a function start, it execute Ism.recordSystemCall

Can you try this?

module Foo
  def mainKernelVersion : String
    Ism.recordSystemCall(command: {{ "#{@def.receiver.id}.#{@def.name.id}" }})
    
    Ism.selectedKernel.version
  end  
end

# It will expand to method like this:

                                
module Foo
  def mainKernelVersion : String
    Ism.recordSystemCall(command: "Foo.mainKernelVersion")
    
    Ism.selectedKernel.version
  end
end                           

I don’t think there’s a real great way to automatically do this to all methods. You’re best bet would be one of the following:

  1. Abstract the .recordSystemCall call to a macro itself, so just have to write Ism.record_system_call and thats it.
  2. Create a macro that accepts a method definition, rebuild the method definition with the extra line. Something like:
macro instrument(a_def)
  def {{a_def.name.id}}({{a_def.args.splat}}) {% unless a_def.return_type.is_a?(Nop) %}: {{a_def.return_type}}{% end %}
    Ism.record_system_call(command: \{{ "#{@def.receiver.id}.#{@def.name.id}" }})

    {{a_def.body}}
  end
end

instrument def test
  pp "foo"
end

Would need to be sure you handle blocks as well.

  1. Make use of some TBD feature like [RFC] Annotations metadata declaration/DSL - #9 by HertzDevil to make the second option a bit simpler/declarative.
2 Likes

Hmm okay, so I will do in another way. Thank you for your help all