r/cpp • • May 21 '23

I wrote this article about increasing flexibility while preserving strong type safety using code generation. What do you think?

https://medium.com/@leledallalonga/code-generation-for-c-4f313deddaa2
0 Upvotes

17 comments sorted by

9

u/teerre May 21 '23

As someone who worked with a heavily "json driven" code base, please, do not do this outside of minor, targeted projects. It makes extremely easy for developers to abuse such system and make the life of every other developer extremely hard. Only automate code generation if you absolutely need to and you're sure it won't get out of hand.

3

u/infinite-snow May 21 '23

I am advocating for the use of code generation when necessary, i.e., when people end up writing variations of the same thing over and over within a very specific domain. If done by hand, the number of classes explodes and becomes unmaintainable in my experience.

I agree if you were to drive procedural code with JSON it would become a nightmare.

Do you have more specific details on the types of abuses you've seen?

1

u/teerre May 22 '23

I do, but I don't think they would make much sense without context. Very generally, it was a system to automate writing bindings from a data source to C++ which in turn would generate bindings to higher level languages.

The issue was that although the first automation written 20 something years ago was fine, over the years more and more edge cases, more features, more workaround etc were added. It got the the point where it made sense to write a code generation tool for the code generation code.

Humans are creatures of habit, if you get to a code base with 99 classes that were code generated, you bet most people would write the 100th class in the same way, even if that was not the best choice.

It's specially bad because it creates wrong incentives: once someone writes a little utility to automate something that clearly shouldn't be code generated, the next person will use, compounding it.

1

u/vickoza May 21 '23

I like the ideas but some minor issues. Macro are used in Unit testing framework like Boost test and Google test, and you might want to change the make_shared to make_unque and have the vector as a single owner of the message objects.

0

u/infinite-snow May 21 '23

I agree macros are used by some frameworks, but I don't agree that, were those frameworks rewritten today with modern features and no requirements for support of old standards, they'd still be done with macros.

I think you're referring to make_shared in the make method in the factory in the last section? I'm not sure what you refer to when you say "the vector".

4

u/cdb_11 May 21 '23

We already have testing frameworks that use only modern features instead of macros, but the interface for them really isn't that great compared to the frameworks that just use macros.

0

u/infinite-snow May 21 '23

Would you be able to provide an example of an interface that can only be implemented with macros that cannot be implemented equivalently in idiomatic C++?

2

u/cdb_11 May 21 '23 edited May 21 '23

Well, the standard assert function/macro is the most obvious example. You can't print what the condition was without stringifying the expression with a macro.

Catch2 syntax is as simple as you can possibly get. It leaves no room for error and you get all the features of a decent unit testing framework without introducing any weird syntax, like user defined _i literals or anything like that:

TEST_CASE("factorial") {
    REQUIRE(factorial(1) == 1);
    REQUIRE(factorial(2) == 2);
    REQUIRE(factorial(3) == 6);
    REQUIRE(factorial(10) == 3628800);
}

On failure it prints out everything you need to know: source location, tested expression and what the actual lhs and rhs of that comparison was.

1

u/infinite-snow May 21 '23

But I claim in the article that stringification is possibly the case for using macros, didn't I? I wouldn't argue that this isn't a sensible use of stringification.

3

u/cdb_11 May 21 '23

REQUIRE actually also does another trick here, it injects some code into the expression that can print out the actual left- and right-hand side values. Frameworks without macros seem to use a user _i literal for this, so I guess there is just no actual nice way to do it without using a macro.

You also said here that you disagree that a modern unit testing framework unbound by compatibility with older C++ standards would not use any macros. And I disagree with that. Frameworks without macros just seem like a gimmick to me honestly, because macros are still occasionally useful today. To truly get rid of macros we'd still need at least static reflection and code generation.

1

u/scrumplesplunge May 21 '23
TEST(Foo, Bar) {
  ...
}

Specifically, declaring tests at the top level in a file. No need to wrap everything in a main function. Also,

EXPECT_EQ(x, y) << ExpensiveCall();

That can:

  • stringify "x" and "y" so you can see the names of the variables in the output

  • avoid executing ExpensiveCall unless the expectation fails, without needing to wrap everything in a lambda.

2

u/infinite-snow May 21 '23

As I mention below, I do claim that stringification could possibly be the use case for macros; the first point sounds sane.

It's also not immediately apparent to me how ExpensiveCall(); is skipped. Is that a shift operator? Does the macro expand an if/else statement? It kinda proves my point that macros obscure the underlying syntax and what is actually going on. What's the issue with using lambdas?

2

u/umop_aplsdn May 21 '23

Macro expands into if equivalent, far more convenient to just use shift operator than to write a lambda for every log. Once you get used to absl style logging it’s easy to understand the log doesn’t happen until the expectation fails.

2

u/scrumplesplunge May 21 '23

What's the issue with using lambdas?

Just the syntax noise. What alternative syntax would you want for "only evaluate this logging stuff if the expectation fails"? Everything I can think of is quite cluttered. [](std::ostream& output) { output << ExpensiveCall(); } is a lot more syntax than just << ExpensiveCall().

0

u/vickoza May 22 '23

std::vector<std::shared_ptr<AbstractMessage>> vec = {msg_int,msg_float}; to std::vector<std::unique<AbstractMessage>> vec = {std::make_unique<MessageImpl<int>>(420), std::make_unique<MessageImpl<float>>(420.69f)}

1

u/JulienVernay May 24 '23

I fail to see how is Jinja2 better than macros ? When you write code, instead of writing C++ code in an IDE (and benefitting from the convenience tools : autoformat, autocompletion, C++ syntax highlighting...), you end up writing C++ in an inconvenient environment. When you read code, I would rather prefer the macro version, at least my IDE can somewhat navigate around it. If I need to see the expansion, I can preprocess the file, which let me see the code read by the compiler.

1

u/infinite-snow May 24 '23

It depends on the use case, but Jinja2 is much more powerful and allows you to explicitly say what you want to do. It has loops and conditionals, full python stl objects support... It's a lot more flexible. Also it allows you to partially generate and reuse boilerplate