LOG_EXPR(x) is a macro that prints out x, no matter what type x is, without having to worry about format-strings (and related crashes from eg. printing a C-string the same way as an NSString). It works on Mac OS X and iOS. Here are some examples,

Pretty straightforward, really. The biggest convenience so far is having the expression printed out, so you don’t have to write out a name redundantly in the format string (eg. NSLog(@"actionURL = %@", actionURL)). But LOG_EXPR really shows it’s worth when you start using scalar or struct expressions:

LOG_EXPR(self.window.windowLevel);

self.window.windowLevel = 0.000000

LOG_EXPR(self.window.frame.size);

self.window.frame.size = {320, 480}

Yes, there are expressions that won’t work, but they’re pretty rare for me. I use LOG_EXPR every day. Several times. It’s not quite as good as having a REPL for Cocoa, but it’s handy.

How It Works

The problem is how to pick a function or format string to print x, based on the type of x. C++’s type-based dispatch would be a good fit here, but it’s verbose (a full function-definition per type) and I wanted to use pure Objective-C if possible. Fortunately, Objective-C has an @encode() compiler directive that returns a string describing any type it’s given. Unfortunately it works on types, not variables, but with C99 the typeof() compiler directive lets us get the type of any variable, which we can pass to @encode(). The final bit of compiler magic is using stringification (#) to print out the literal string inside LOG_EXPR()‘s parenthesis.

The first and last lines are a way to put {}‘s around the macro to prevent unintended effects. The do{}while(0); “loop” does nothing else.

First evaluate the expression, _X_, given to LOG_EXPRonce, and store the result in a _Y_. We need to use typeof() (which had to be written __typeof__() to appease some versions of GCC) to figure out the type of _Y_.

Now we have enough information to call a function, VTPG_DDToStringFromTypeAndValue() to convert the expression’s value to a string. We pass it the _TYPE_CODE_ string, and the address of _Y_, which is a pointer, and has a known size. We can’t pass _Y_ directly, because depending on what _X_ is, it will have different types and could be of any size.

VTPG_DDToStringFromTypeAndValue() returns nil if it can’t figure out how to convert a value to a string.

The VTPG_DDToStringFromTypeAndValue() Function

It’s derived from Dave Dribin‘s function DDToStringFromTypeAndValue(), and is pretty straightforward: strcmp() the type-string, and if it matches a known type call a function, or use +[NSString stringWithFormat]:, to turn the value into a string.

The First Step Twords Fixing Your Macro Problem is Admitting it…

So yeah, maybe I went a little wild with macros here…

But it took out some WET-ness of the original code, and prevents me from accidentally mixing up types in a long wall of ifs, eg.

If I were cool, I’d use NSDictionarys to map from the @encode-string to an appropriate format string or function pointer. This is conceptually cleaner; less error-prone than using macros; and almost certainly faster. Unfortunately, it gets a little tricky with functions, since I need to deference value into the proper type.

One final note from my testing, I could do away with the strcmp()s, because directly comparing @encode string pointers (eg if(typeCode == @encode(NSString*)) works. I don’t know if it will always work though, so relying on it strikes me as a profoundly Bad Idea. But maybe that bad idea will give someone a good idea.

Limitations

Arrays

C arrays generally muck things up. Casting to a pointer works around this:

__func__

Because it is a static const char [], __func__ (and __FUNCTION__ or __PRETTY_FUNCTION__) need casting to char* to work with LOG_EXPR. Because logging out a function/method call is something I do frequently, I use the macro:

#define LOG_FUNCTION() NSLog(@"%s", __func__)

long double (Leopard and older)

On older systems, LOG_EXPR won’t work with a long double value, because @encode(long double) gives the same result as @encode(double). This is a known issue with the runtime. The top-level LOG_EXPR macro could detect a long double with if((sizeof(_X_) == sizeof(long double)) && (_TYPE_CODE_ == @encode(double))). But I doubt this will ever be necessary.

I haven’t actually written any code that uses long double, because I use NSDecimal, or another base-10 number format, for situations that require more precision than a double.

Scaling and Frameworks

Growing LOG_EXPR to handle every type is a lot of work. I’ve only added types that I’ve actually needed to print. This has kept the code manageable, and seems to be working so far.

The biggest problem I have is how to deal with types that are in frameworks that not every project includes. Projects that use CoreLocation.framework need to be able to use LOG_EXPR to print out CoreLocation specific structs, like CLLocationCoordinate2D. But projects that don’t use CoreLocation.framework don’t have a definition of the CLLocationCoordinate2D type, so code to convert it to a string won’t compile. There are two ways I’ve tried to solve the problem

Comment-out framework-specific code

This is pretty self-explanatory, I’ll fork VTPG_Common.m and un-comment-out code for types that my project needs to print. It works, but it’s drudgery. Programmers hate that.

Hardcode type info

The idea is to hard-code the string that @encode(SomeType) would evaluate to, and then (since we know how SomeType is laid out in memory) use casting and pointer-arithmetic to get at the fields.

For example:

//This is a hack to print out CLLocationCoordinate2D, without needing to #import <CoreLocation/CoreLocation.h>
//A CLLocationCoordinate2D is a struct made up of 2 doubles.
//We detect it by hard-coding the result of @encode(CLLocationCoordinate2D).
//We get at the fields by treating it like an array of doubles, which it is identical to in memory.
if(strcmp(typeCode, "{?=dd}")==0)//@encode(CLLocationCoordinate2D)
return [NSString stringWithFormat:@"{latitude=%g,longitude=%g}",((double*)value)[0],((double*)value)[1]];

This Just Works in a project that includes CoreLocation, and doesn’t mess up projects that don’t. Unfortunately it’s horribly brittle. Any Xcode or system update could break it. It’s not a tenable fix.

Areas for Improvement

When I have time, I plan to write a general parser for @encode()-strings. This will let me print out anystruct, which mostly solves the type-defined-in-missing-framework problem, and would let LOG_EXPR Just Work with types from all kinds of POSIX/C libraries.

Here’s the complete struct handler from a similar (but incomplete) hack:http://gist.github.com/539041
It’s a basic recursive descent parser design. DecodeValue() (not included) has the same signature as DecodeStruct(), looks at encoding[*cursor] and dispatches to other functions with the same signature – much like VTPG_DDToStringFromTypeAndValue(), except a full parser only needs to look at one character for dispatch, so it uses a switch statement.

Oh yeah, maybe I should point out why it’s incomplete. ;-) Apart from problematic types like bit fields, it doesn’t deal with padding – for instance, in struct { char a; void *b; } b is pointer-aligned. My intended fix was to use a flag to DecodeValue() to indicate it was needed, plus a bunch of nasty ABI-specific rules to handle the details.

Thanks for the pointer to the code, and especially for explaining what problems you ran into :-). Keeping up with the ABI specifics of every iOS device is sounds scary. If there’s a simple way to detect probable padding then demanding struct-specific ToString() functions for those cases might end up being simpler over all.

It’s not as hard as it sounds. Each architecture has a padding requirement for each primitive type, and generally it’s “round up to a multiple of the size of the type” except in some cases for types bigger than a pointer.

The easiest way would probably be to stick the type handler in a struct { handler function pointer, unsigned alignment, char signature }, put those in an array, and bsearch them; the alignments would be declared as a list of constants in #ifs for each architecture. You might need a special case for nested structs, though; I’m not sure offhand whether all architectures align structs based on the first member.

Well, I’ve fished mine out of the experiment pile, made it actually work and given it a simple interface like yours. There are several limitations listed in the header, but I think it handles everything that can currently be encoded by @encode(). (There are several things that can’t be.) There are probably interesting failure cases with complex aggregates.

It doesn’t work on PPC-64 or ARM, but this should be a simple matter of finding the alignment enums using the FindAlignment.c tool in the repo.

Thanks Monsieur for the update, I pulled the old VTPG_Commons from an old Xcode project and it wasn’t compiling under the version of Xcode I have installed (4.3.2). This fixed it, and its also just the code I needed for LOG_EXPR.

Has anyone figured out a way to do something like LOG_EXPR while debugging in the LLDB command line interface? LLDB isn’t very smart about printing types, and in some cases just garbles it completely. Look at this case: