Implement alternative to FUNCNAME

#!/bin/bash

crab() {
  echo "$FUNCNAME" # Returns 'crab'
}

Proposing similar implementation in rustlang

Rationale

  1. Better debugging: This would allow custom debugging channels to implement messages such as: Function 'crab' failed to do A B C, because of 1 2 3

  2. Use function names in a logic

fn thing() {
  match functionName == "thing" {
    true => println!("Called from function called 'thing'"), 
    _ => println!("This function is not called 'thing' it's called {:1:}", functionName)
  }
}

NOTE: There are a ways in rustlang to get this result, but that makes the code look ugly as it requires mentioning the function name within the function.

Some past discussion of this: https://github.com/rust-lang/rfcs/issues/1743

stdext has a macro that does this: stdext::function_name. It's a bit of a hack but possibly good enough for println debugging. It uses std::any::type_name.

Also tools can map file!, line! and column! to function names.

That said, it would be good to have a macro for this to compliment module_path!.

2 Likes

I would love to see this in the standard library. The consensus of the lang team last time it came up was that we all want this.

It seems to have stalled out the last time it was started, but there's an RFC from that effort that could be revived and updated.

8 Likes

When you say 'tools', do you mean some kind of macro that wraps them? If so, what macro is it?

Also, IIRC the discussion that @mbrubeck linked to stalled out over what to do about closures (and maybe anything else that is like an anonymous function; do futures count here too? Or the unstable call() method?). Maybe instead of just a plain func!(), we have func!(file!(), line!(), column!()) fallback option so that if the inner most function-like scope is anonymous we fall back to something involving file! , line! and column! instead. Not great, but since this is just for println!() debugging, probably not too horrible either.

Alternatively, once std::backtrace is stabilized, we could use that as an alternative in those cases where it's unclear what func!() should really print out by printing out the full backtrace. Again, not great, but maybe not too horrible either.

I don't think closures were at issue; closures already have a generated name for other purposes.

The discussion stalled out before transitioning from names to full paths (e.g. crate::module::func).

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.