NSStringinfying enums
29 December 2012
Making sense of enum values in C is too difficult. Usually sooner rather than later while debugging you need to see what's inside an enum value, but C provides no introspection tools. You just get an integer value, no mapping to the original symbolic name. That's why every enum should be accompanied by a stringifying function, but that requires manual labor. Few programmers are happy to write those functions and fewer are going to update them. Automation to the rescue.
I'm working in the context of Objective-C, and so is Wolf Rentzsch, who recently blogged his script for generating NSStringFromEnumName functions. I have used a very similar solution for a long time, and I expect so have many others.
But you don't have to be jwz to doubt the wisdom of parsing C with a bunch of ad hoc regexps. I was always unhappy with it and knew there were various not-so-corner cases I wasn't handling properly. Using a real C parser seemed like the right thing to do, but it hasn't really been feasible until pretty recently, after the advent of libclang.
So, here it is, using Python and clang, my most recent take on NSStringFromEnum. It might not be any better for being based on libclang, but it's different.