Macro to replace all return statements in a method

Hi, I need to create a macro that takes a method definition and replaces all return statements in this method? Is this possible in Crystal? Can I use a macro to visit the AST and replace certain parts?

Any help would be greatly appreciated.

This should theoretically be possible, but I fear it would be quite a hassle.

You can stringify AST nodes via macro expansion. But it’s not possible to mutate them. So you couldn’t just traverse through the tree, swap all Return for something else, and then stringify.

Instead you could stringify manually, i.e. breaking down each node into its constituents and stringify them as well. All would do the same as normal stringification, except for Return, where you could do something else. This would obviously require a huge effort (depending on how much syntax you need to support), which I guess makes it prohibitively impractical.

Can we have a small example of where you want to use this? There might be some other way to solve what you want.

I have written a “trace” macro that wraps a method body in begin/rescue/end and logs incoming and outgoing calls as well as exceptions.

Currently I use a trace_return macro instead of plain “return” to catch early returns. However, the macro would be a lot nicer if one would not have to do that, and “return” would automatically be replaced by “log & return”

1 Like