Hacker News new | past | comments | ask | show | jobs | submit login

Cog is great. I use it all the time in my personal projects. It really shines in C++.

Some uses I've found for it:

* Generate long literal lists, with less tedium and fewer bugs:

  snprintf(buf, sizeof buf,
      "%f %f %f %f\n"
      "%f %f %f %f\n"
      "%f %f %f %f\n"
      "%f %f %f %f\n"
      "%f %f %f %f\n",
      /* [[[cog
      for i in range(20):
          cog.outl(f"matrix[{i}]" + (',' if i != 19 else ''))
      ]]] */
      matrix[0],
      matrix[1],
      (...)
* Automatically instantiate classes from a set of files:

  /* [[[cog
    for path in glob('src/editor/Panel*.cc'):
      name = stem(path)
      instance = name[0].lower() + name[1:]
      outl(f'{name} {instance};')
  ]]] */
      PanelInspector inspector;
      PanelGame game;
      PanelTextures textures;
      PanelModules modules;
      PanelProject project;
      PanelInput input;
      PanelPerformance performance;
  // [[[end]]]
* Given a list of Python strings, generate a C++ enum, and functions to convert it to and from a string.

* Parse a C++ source file for struct definitions, and generate code to debug-dump them, inspect them in a GUI, save/load them... alright, Clang might be a better tool for this, but Cog will do in a pinch.

All this is stuff that a more expressive language could do without external tools, but even in such a language, you won't usually see what a macro is being expanded to without some sort of tooling. Cog puts it right there in the file for you, which I often appreciate.




Great examples.

Is source generation becoming "trendy"? Microsoft have recently added more of it to C#, in order to support their AOT efforts. It's a bit infrastructure-heavy as it seems to be intended for point support for specific things, rather than a general purpose "write code to generate code" tool. But I wonder if there would be a market for such a thing. The architecture currently does not allow you to edit user source code, just add more code. I.e. it's not a preprocessor, it just has readonly access to the AST.

e.g. the regex generator https://learn.microsoft.com/en-us/dotnet/standard/base-types...

(Reference blog post https://andrewlock.net/creating-a-source-generator-part-1-cr... )


I expect wider convergence on better build tools like CMake has made it relatively easier to perform custom build time logic like code generation without disrupting consumers of projects by changing or otherwise adding complexity to the build process.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: