[cfe-dev] Hacking Clang to generate mock objects

Dave Elcock dave.elcock at gmail.com
Fri Sep 2 00:49:00 PDT 2011


> I'm not quite sure why you're approaching this problem from the direction
> you are. Why not generate *source code* for the mocks instead of trying to
> synthesize generated code for them based on the original code?
>
Yep, that would do it for sure, I just wondered if it was possible to
do it without the intermediate step of generating code, and going
straight to inserting extra AST or whatever mid-compile. I'm keen to
make it feel more like .net or java reflection at play than the
"inconvenience" of having to generate more source code (how very 20th
century). Basically, I miss the likes of RhinoMocks for .net and want
a similar level of simplicity and neat tests for C++.

> For reference, GoogleMock (which you should look at if you haven't) creates
> mock interfaces very easily. The complexity is exactly bounded by the size
> of the mocked interface, without regard for the complexity of
> implementation. There is even a (somewhat hacky) python script to generate
> the mock source code from an existing class.
>
I'm sure GoogleMock could handle it too, but I've never been that keen
on it. It's a bit too verbose, and it gets tiring mocking every method
explicitly (is that what the python script takes care of?). I'm also
not a big fan of the macro approach, but I guess there's not much of
an alternative with C++, so I'm just exploring other possibilities. If
nothing else, GoogleMock tests look ugly to me, aggressive even!
That's petty, I know.

> I could imagine writing a Clang-based tool that examined an AST to generate
> the mock instead of using Python. It would be less hacky and handle horrible
> corner cases of the language better. I'm fairly confident that the existing
> libraries etc in Clang are sufficient to do this.
>
Yes, I can see it's probably going to fall back to this if I ever
actually write any code, but I'm exploring my "dream" solution first.

> Anyways, if you want to talk more about the Clang tool for this, by all
> means carry on. =D Happy to help there.
>
Great, thanks. You could start by pointing me towards some
documentation! Having perused clang.llvm.org, I can't help feeling
there's some missing general architecture docs. There's a good deal of
info in Doxygen and the code itself, but something less detailed to
get me started would be helpful. Is Doxygen my best bet?

As for the "dream" option, where would I go about injecting this
imaginary "pass" to generate the mocks. Is there something similar to
LLVM's transform passes I can hook into?

Cheers,
Dave.



More information about the cfe-dev mailing list