views:

65

answers:

3

I'm wrapping a C++ library in PHP using SWIG and there have been some occasions where I want to modify the generated code (both generated C++ and PHP):

  • Fix code-generation errors
  • Add code that makes sense in PHP, but not in C++ (e.g. type checking)
  • Add documentation tags (e.g. phpDoc)

I'm currently automating these modifications with patch. This approach works, but it seems high-maintenance and fragile. Is there a better way of doing this?

+1  A: 

You may end up having a maintenance nightmare later on. Instead of SWIG you might consider using another generative approach that:

  • Let you add your custom code directly on the model (so that you won't need to add it post-generation)
  • Let you define your own generator. This feature alone could take out the need to add custom code all along.

The problem of using third-party generators is that they never really generate what you want. The problem of writing your own code generators is that it's much more work. You choose.

But correcting an automation with another automation...

Rui Curado
+1  A: 

Code generation is quite a wide topic and there are definitely many other approaches, which might be more interresting to you as mentioned above. But if you do not want to use other tool, depending on what code is generated and on the PHP OO capabilities, you might use the Generation Gap pattern.

Gabriel Ščerbák
+1  A: 

The best bet is to have your code generator generate correct code for your needs. Hand-tweaking generated output is unsustainable. You'll have to tweak it again any time the input changes.

If a tool is producing flatly erroneous output, it's ideal to repair it and submit patches back to the maintainer. If the output is correct for some circumstances but wrong for yours, I'd suggest to add an option that changes the behavior to what you need.

Sometimes, you can use a short program that automatically does an intelligent job of patching your generated code, so that you don't need a manual process to make patches.

Alternatively, you could write your own code generator, but I suspect that's much more work than you want. It also depends on what you're doing. Sometimes code-generation is really just macro-expansion, and there are plenty of good tools for that in the wild.

Good luck!

Ian
Try AtomWeaver. It lets you easily build a code generator. It is based on ABSE, a pragmatic model-driven approach (hence not UML/MDA). Because it's a template-based system and is quite simple, it might fit the needs of the OP.
Rui Curado