Limit recursion depth for macro expansions, closes #17628

This is a patch for #17628, thanks to @kmcallister for your helpful hints!