Implementing cdecl with pycparser

October 18th, 2008 at 11:22 am

cdecl is a tool for decoding C type declarations. It was first first described in K&R2 and since then is part of most Unix/Linux distributions.

Well, since my pycparser project is nearing completion, I’ve decided to implement cdecl on top of it. As pycparser is a complete parser and produces ASTs from ANSI C, I figured this shouldn’t be too complicated.

Indeed, it turned out to be quite simple. The core of the implementation (which you can see here) is a 30-line function that traverses the AST recursively and spits out the explanation.

Here are a couple of sample results:

char *(*(**foo [][8])())[];

=> foo is a array of array[8] of pointer to pointer to function() returning pointer to array of pointer to char

static const char* const cptr[2];

=> cptr is a static array[2] of const pointer to const char

The cdecl is a simple and fun way to experiment with pycparser. It teaches how to explore the AST created by pycparser an traverse it correctly.

Related posts:

  1. Reading C type declarations
  2. From C to AST and back to C with pycparser
  3. pycparser v1.0 is out!
  4. pycparser now supports C99
  5. pycparser v1.06 released

Comments are closed.