开发者

Modifying generated code

开发者 https://www.devze.com 2023-01-11 19:00 出处:网络
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):

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 c开发者_如何学Pythonode 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?


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!


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...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消