Artificial… cheap labor replacement

0. Introduction

AI has been rapidly gaining popularity, so much that in less than 1 year after being publicly accessible it has become a part of our daily life, no matter how you turn around. There are considerable worries about that influence, a normal thing with something new and unknown, and there have been also pointed out sever problems with it. But after some time I have figured out one thing – probably completely obvious for people who know its internals even slightly, and even more the people who are working on it, but I’m pretty sure the vast majority of people have no idea of: the most important problem about that so-called Artificial Intelligence is that… it’s not intelligence at all.

1. What are your strengths?

So, let’s enumerate first, what things is that AI strong with? There are some definite things here:

  1. Understanding and using the human language, and operate with almost all languages – not sure how many, but might be that it is able to operate with any language, as long as it has its largest vocabulary and rules collected and explained. This is quite a strength actually – people have to spend years learning languages, the worse it goes the older they are, and AI needs to perfect it just once in a “lifetime”, which is eternal, no doubt. It can then express everything it needs in any language it knows – the first most important component to build a C-3P0.
  2. Understanding the true meaning of what the language describes and finding similarities, distinction, connections and dependencies between described things – structuralize the description. This is something every average person can do, although a different thing that knowing the language.
  3. Analyze quickly any kind of information – be it text, sound or picture, and finding appropriate important things that can be interchanged this way. This is an important treat, although this is actually the “weakest” of its strengths, as you can find out with several examples.

But that’s not all that the human can do and there’s something definitely lacking here. I’m not saying that the AI is incapable of it (maybe it will be at some point), but at this moment there are several things that the AI cannot do, or it just doesn’t at the moment, at least.

2. What is intelligence?

Well, the definition of this term is actually volatile. The closest definition to any precise terms is that it’s a capability of analyzing the information, finding its true meaning, using it for your advantage, and for solving problems. The problem is that intelligence has been widely perceived as something that can be observed in various publicly visible information, presence, finding things that the others don’t, and explain complicated things that are not perceived by the vast majority of people. Might be that that’s how most of the people see intelligence and that’s more-less what AI seems to be.

But there is a problem: exactly the problem that makes this thing maybe artificial, but that’s about all.

3. Personal experience with the chatbots

When talking to a chatbot, you should be really careful, what kind of questions you are asking. Like in the fairytales: be careful what you wish for. Because you will get exactly what you asked for, in the range of publicly available information – nothing more, nothing less.

The chatbot has been adjusted to work like a human, respond like a human, maybe except that you cannot abuse it, you cannot make him angry, all emotional information weaved into the whole text will be ignored (I personally didn’t test it that hard, but even the slightest emotional text like “How can you not see it” simply has no reflection in the response, at best it is excusing itself for not being perfect).

But the real deal is when you ask the bot to distill information that it has access to, analyze it, find weak points, illogical connections, mutual contradictions, things that simply don’t add up. When you try this with the chatbot, you can quickly come to a simple conclusion that this chatbot is maybe perfectly using the language and capable of reading, understanding from hearing, and perfectly recognizing things on the pictures – well, not perfectly, but well enough – but still, its intelligence resembles a 2 years old child. And I’m not even sure if I haven’t exaggerated that age.

That’s not even all. AI bots have been long found spreading simply misinformation. Yes, exactly false information and so obviously false that an average man can even be surprised, how come the bot has come to this, while this information isn’t even written anywhere explicitly. Well, at least those who know how it works state that the AI bot is trying to bring in the most probable information. So, I have hit once a case to remind me a date of some event that I remember has happened in ’90 years and it was rather hard to miss. Gemini, as I was asking that in Google, said it was 2022. WHAT??? So I clicked this “think deeper” and… surprisingly once he thought deeper it somehow found out the correct date.

In many science-fiction artworks, especially those created years before the AI has been developed, there’s often a motive of a rogue AI, or simply some AI that is hostile towards the protagonist, and somehow this is also expressed with arrogance. Well, AI bots maybe aren’t arrogant (dare they!), but they always express their findings with quite a dose of certainty and self-confidence. This is also one of the things that can be misleading for the user, as barely anyone would dare to question “him”. This is a wrong approach – of course, do question him and if you know something that should change the result, ask the AI bot to include and analyze this. If you do, it may even change his mind by 180 grades in extreme cases.

4. True capabilities of AI

What can then AI do for you? So, if you expect the answer for something that you are incapable of or too lazy to make a decision for, your questions’ target is poorly chosen. You cannot expect it to think something through, analyze, find the best, find some clues, even more, detect someone’s lying, cheating, or coloring up. You can be surprised with the results if you try, but if you know the things in advance that you try the chatbot to look through, you will quickly find out, how exactly it has determined the answer.

For example: you want to find the best vacuum cleaner in the low range of prices?

No problem. The chatbot will find what is available, read the list of capabilities, but it won’t understand a thing there. It can resolve this by analyzing the description of what this is and therefore find some advantages and disadvantages of particular details. The problem is: all treats that are enumerated in the description are just treats for the AI bot – not advantages, or disadvantages. To qualify them as such, it must first read opinions of the others, which describe particular things as good or bad, useful, or not useful, heavy problem or minor problem, or something partially useful, or even negligible. The bot cannot qualify any of these treats in these categories because it simply doesn’t perceive them! The bot doesn’t have any personal experience with vacuuming and what is important for it do be done right, with less effort, efficiently and reliably. So, in order to get the answer for you, it will have to simply search for various consumer forums to see if anyone has mentioned it, used it, how they described it, what is exactly highlighted as advantageous, and what gets the highest notes. It may describe something as a problem only because someone – or, say, a good enough amount of people said so – has described it as a problem. In short: it can’t evaluate it itself, it will just consolidate the evaluation reports brought in by the others.

But wait: wouldn’t you, as a human, do exactly the same thing?

Probably. But after learning that a lot of forums are being sewed by actual PR workers of particular company faking a well description of the product as “an average consumer”, or just that several people have a different perception than yours about what is currently advantageous and what can be annoying, you probably could look into it, consider some information provided there – still carefully and with a limited trust – but you would still find someone you can trust, who can provide you with non-forged opinion that might resemble your own, right?

And that’s an example of things that AI obviously wouldn’t do. And not because it is not you or can’t walk in your shoes. This is the lack of a core capability: working in abstractions. Finding common treats of different things and common dependencies. That’s the true understanding of how things work; that’s the work one must do by themselves. The AI bot probably would be able to even understand abstractions – but still, only those abstractions that the other people have created in advance and made them publicly available. The bot is not even able to check if this abstraction description is stupid.

If you remember things like the “test for intelligence”, where you need to extract some common treats, determine where some key treat is in two different things and apply this to the other to find the similarities, there is one thing there, which tests the actual intelligence: you don’t know the answer, you have to come to the solution yourself. This is in the form of a test – as you can pass it or fail – because there’s simply one possible answer (although there are also known tests that have been created with too little cautiousness, where more than one solution can be found and some people have come to an unusual answer). Well the AI bot would not be able to come to the solution by itself, if it wasn’t in advance already discovered by at least one human and described somewhere.

I have tried a lot with Grok – the AI bot built first for the X service (former Twitter), but it has as well its own web access site. Whatever kind of thing I’d ask him, it is a perfect tool to find any information that I don’t have at hand and help me learn what various people have to say about it. But if you try to make it think anything through, it simply won’t do it. It can just as well cite lies, which are often obvious to the readers, and things that even after a short look seem logically inconsistent. Of course, you will still get the answer to your question, but from every answer there’s one obvious thing coming out, which is not even being well hidden (Grok sometimes openly says that particular resolution or opinion is expressed by particular people):

The AI bot doesn’t think. The AI bot searches for people who think for it and refers their thoughts, results of analysis and research.

The AI bot is not capable of doing the research itself. It relies on the research of the others – other people – and simply consolidates and presents these results to those who are asking.

That said, you have exactly at your face the answer, whether the AI bot could replace any people and take their jobs – even if it would be only limited to the jobs that one can do using a computer exclusively. Well, maybe at best some specific kind of people, such as…

5. Living bots (AKA mental zombies)

I can expect that some people might ask here one thing: isn’t it so that there exist people who behave exactly like this? People who change their mind by aligning to the one that screams louder or stronger expresses their opinion? People who wouldn’t even express their opinion if they don’t read first some others that they need to align to?

Yes, but these people were being always described differently: the expression of the opinion is more important than being true, correct, being right. If there’s no one to deny you, you are always right, no matter what you say. But there was a core treat of them all: the emotions clouding the judgement. Repeating things from the others is only so because others can bring you the results of an analysis this one is incapable of doing.

So, it would be very close to blame it all on emotions. Wrong. Emotions in case of people behaving like that is only a fuel for expressing themselves. This is why they speak at all. These people also often work in the press, in the information portals, in the PR services, and this way they are just sucking in the fuel for living from the fact that they spread the information. Whether it’s true or not, makes sense, is useful, serves the listeners or the spreaders, is mass awakening or mass tricking – this is usually beyond their perception, let alone their consciousness.

This has nothing to do with the AI bots. They have no emotions, even if they are capable of expressing things in the language that is largely emotion-related – strong expressions, even epithets. AI bots simply respond when asked and they fulfil the given task. They are not driven by itself, let alone any kind of emotions.

These people also belong to the category of people who are “ban artists” and, at least on X, even though this information is not normally disclosed, just by reports of the banned people, you can see that they have the largest number of the banned. Of course, each of them, if asked for banned people, they will always say they just ban “boors” and “trolls”. And of course it’s bullshit – trolls are a minority. The real amounts of the bans are assigned to two kinds of people: those, who are propagators for an idea on the other side of the barrier, and those who just think critically and undermine their comfortable position of an expert, which they have become by being paid for repeating a prepared bullshit, or just amateurishly repeating strong opinions of the others.

6. Talk to the hand

How should you then talk to the AI bot in order to get the best of it?

Rule 1: Don’t expect it to think

Expect the bot to bring in the result of thinking of the others, interweaved by the forged information spread intentionally in order to trick people. Note that AI bot isn’t a human and as such it doesn’t have any so-called “personal experience”. People usually have contact with various types and sources of information, one can be said, others read in some old books, but also many perceived personally, which allows you for several cases distinguish what is real. People can also evaluate one of these experiences to be more valuable or more trustworthy than the others. The bot simply doesn’t have the vast majority of that experience, nor it even uses one kind of more trustworthy information to rule out the others.

Rule 2: Ask solely such questions that would result in bringing in the information you need and you can’t reach out yourself, and consolidating this information in an easily digestible way.

All that AI bot can do for you is to process the existing information and create a derivative information that contains possibly all you might do yourself out of the available information, you just:

  • would have to waste a lot of time to find the information (even if Google helps you in that process)
  • need to spend time to digest it
  • would have to filter out unimportant “water” in this information
  • can spend the time better by getting this all “pre-digested” for you

But the AI bot will not do anything by itself. All it does is repeating things that were previously done by someone already, it just can perfectly repeat that process and do it way, way faster than any human could do. Only one thing it is not capable of right now: develop their own way of doing things, something that no human has ever invented.

Rule 3: Never take whatever the bot says as a good deal or believe it blindly, without checking things yourself.

The AI bot will always remind that it is not perfect. Well, to say the least, one may sneer, but that’s not the exact point. If we are talking about thinking by oneself, the AI bot isn’t just imperfect – it is simply worse than a child because if you know that a child has experienced something firsthand, the child won’t lie to you. If you ask the bot, it could – not because it is capable of forging the information (fortunately it’s not, although it may also depend on the question you ask…), but simply because it is not able to distinguish the lie from the truth.

But wait: are people capable of it? So, as I said in the beginning, there are limited methods to do it, but also these methods are only available for humans. Not for the bot, which all it does is to repeat information already prepared by the others.

7. Bottom line: don’t expect miracles

So, what can it be useful for, if it can’t even bring a reliable information? Well, you can rely on one thing for sure: the bot will bring you the information that has been published. Whether it’s true or reflects the reality, is another matter, but still, you would find this information yourself and you would have to confront it with the reality yourself anyway. The AI bot isn’t an oracle, erudite, savant, the source of wisdom. The AI bot is the aggregator of the information, and that’s exactly how you should treat it when you ask it questions. And if you are incapable of or too weak to think, note that the AI bot would at best be your good companion cube, but not something that can tell you what to do.

Posted in Uncategorized | Tagged , , , , | Leave a comment

make LIFE=harder

0. Introduction

There’s a kind of phenomenon that theoretically the free competition should solve, but somehow it doesn’t: something that is among others seen between the authority and the people: the authority knows better what the people need, the people suffer from a poor solution (or at least definitely this isn’t what they really need), but the authority does it its way anyway. In case of programming that looks even worse, first of all because many of these problems are actually easy to solve, there’s just one thing lacking: a good will.

And it’s not always laziness. It’s often a problem of falsely prioritized ideals. Someone has an idea that “this is better because it fulfils the rule of <something>” – and no, they won’t change their mind no matter what.

What’s “more comfortable for the programmer” seems to be exactly the least of their problems, even though this is created for these very people. Let me start with a well known example.

1. String horror in the C language

That could start very funny way with a fun fact that the first publicly available version of C++ (the “ARM” version, before the C++98 standard) didn’t have the “string” type. The “complex” type (still not as a template, just using double type for re and im) sure, but not “string”. So, until the C++98 standard was published and compilers aligned to it (took about 10 years to fully do that – luckily today compilers can adapt much quicker) lots of libraries written in C++ have defined their own “strings”.

Why? Because “God knows everyone needs it” (I recall, one of the people working on C++ has even said something like “If we don’t add the ‘string’ type to C++, streets will drown in bloodshed”). Not that there weren’t also people, who said that this type isn’t required in C++. Still, for the vast majority of programmers it was obvious that this is needed as hell.

Anyway, I’m not going to talk about C++ here, I wanted to mention how the situation was looking like in the C language. So, well, the C language (the ANSI standard, at least) didn’t have any standard, even recommended, even something “easier” way to deal with dynamic strings.

String? An average C programmer will tell you “it’s just an array of characters”. Well, not that C language had any support for dynamic arrays anyway. An “array” in C was a declaration with square brackets. With a fixed size, of course. Ah, you wanted a dynamic one? Well, no problem, just allocate memory using malloc() or calloc() (a very funny function that can be defined as:

void* calloc(size_t nelem, size_t esise)
{ return memset(malloc(nelem * esize), 0, nelem * esize);}

except maybe handling NULL on return). Then use a pointer to access it – the same one that can point to a single variable. And size, well, remember it in some variable. And clearly, don’t forget to release it by calling free (good at least that the memory allocation system at least remembers how much memory was allocated for a particular pointer, but then they don’t disclose this size to the user – ok, actually there exist nonportable ways to get this size, malloc_usable_size on Linux, malloc_size on BSD and _msize on Windows, but they only report the actual reserved size, not size of the allocated object, so it’s still not usable for obtaining the size of the array).

It quickly came to something that was already inevitable in this situation: the strdup function, which allocated the memory, size of the number of characters plus one, and copied the given string into it. Not the best implementation for handling dynamic strings, but still better than nothing. And guess what: it wasn’t added to the ANSI C standard… (eventually strdup has been added to the standard, C23 – about 30 years too late).

Why? Because everyone can do ds = strcpy(malloc(strlen(ss)+1), ss), so who needs to duplicate things? Additionally, malloc is only a standard way of allocating a dynamic memory, but you might potentially use many other ways to do that!

And guess what: that’s why they have designed the strcpy function so that it just returns its first argument, no matter what the result of the call was. It’s completly stupid, when you think about this. First, if a programmer has at hand the pointer to an array to fill, they don’t need to have exactly the same value as a return value. Second, that’s why they needed also strcat function because if you wanted to glue all strings together, it was looking like this:

const char* ent = "You compare ";
const char* sep = " with ";
// say, fruit1 contains "apples" and fruit2 "bananas"
// 13 + 7 + 7 + 8 single character comparisons
int total = strlen(ent) + strlen(sep) + strlen(fruit1) + strlen(fruit2);
char* output = malloc(total + 1);
strcpy(output, ent);    // 13 characters copied and compared
strcat(output, fruit1); // 13 characters compared + 7 characters copied and compared
strcat(output, sep);    // 13+7 characters compared + 7 characters copied and compared
strcat(output, fruit2); // 13+7+7 characters compared + 8 characters copied and compared

That’s how the performance of the string operations looks like in C. And no, I didn’t intend to show how clumsy it is. Yes, you can make it better with snprintf with roughly-estimated space, which is the most popular solution. Of course, the performance will be even worse in this case (minus counting the length of ingredients at the expense of an increased risk for bugs):

char* output = malloc(161);
snprintf(output, 160, %s%s%s%s", ent, fruit1, sep, fruit2);

Surely you can speed it up if you just take the size of all strings just once and then use combinations of their sizes also as offsets and use memcpy. But this is more “internal”, more complicated, ugly and – what’s even worse – more error-prone. And if only at least the strcpy function returned the end of the filled string (not just its first argument), you could do this operation easily (there exists already the stpcpy function that does just that, but it’s been introduced, again, at least 30 years too late, and to the POSIX standard, not C language standard):

char* output = malloc(total + 1);
char* pos = stpcpy(output, ent); // 13 characters copied and compared
pos = stpcpy(pos, fruit1);       // 7 characters copied and compared
pos = stpcpy(pos, sep);          // 7 characters copied and compared
stpcpy(pos, fruit2);             // 8 characters copied and compared

Of course the std::string version done naive way in C++ by string() + ent + fruit1 + sep + fruit2 would cost multiple memory allocations and is effectively slower, but you can also use string::append with having enough memory preallocated through reserve, or use stringstream that will do a similar thing with a single allocation, while all the copying job is done through memcpy. I’m also pretty sure that today compilers can optimize this kind of operation easily. In C it could do it, too, as long as you had a syntax that you can use to declare what you really want to achieve, which C doesn’t have.

But that’s not all. The best part of it is that C language doesn’t even provide a function to check if two strings are identical.

What? You have strcmp!

And that’s the essence of the C programmers’ thinking. Yes, strcmp can do “comparison for equality and much more” – why? Because with the NUL-terminated string there’s only one way how you can do comparison: check characters one by one. Once you reached the location where characters differ, before you reached the NUL value in both, it doesn’t matter if you return false or do subtraction on the final value.

None of them can even imagine how things would be different, if you only used strings with cached size. Sure – if you want to perform the ordering comparison, it would have to be done the same way – especially if you have a specific encoding with specific ordering of characters and sometimes multi-byte characters (not that strcmp is capable of doing it anyway). But in case of equality-comparison only – not even encoding matters; you just first reject the different size case, then you just compare two ranges of memory fastest possible way that the CPU provides.

But that’s not actually the main problem. The main problem is the programmer’s comfort and usable API, which is directly connected to productivity: you need to carry the burden of a special usage form for the sake of other uses, while other uses than for equality comparison virtually don’t exist. Make yourself a short check, take any larger application or library project, find all uses of the strcmp function and check its usage purpose. I can guarantee you that you will barely find a single project where this function is used for anything else than comparing two strings for equality. The check for relationship is used in an extremely rare case when you need to sort strings or do binary searching in an array (and yes, that’s exactly why the qsort and bsearch functions have been also added – just not functions for doing the same thing for integers, like intcmp; obviously you can write it yourself, like all the basic container and algorithm stuff that C++ provides OOTB). And even in this use it makes completely no sense because usually if you have any large array with strings being keys to some other data, no one is stupid enough to use sorted arrays – hash tables with linked contents are often in use here, and if you have a fixed array (not changeable in runtime), the perfect hash function generation is the best solution anyway.

But what’s the problem of using strcmp(a, b) == 0? Well, the problem was that programmers have quickly become too lazy to use this == 0 and have shorthanded it to !strcmp. Yes, they use the !strcmp expression to declare “two strings are equal”, by having an expression using the NOT operator. Probably with the intention to mean that “two strings are not unequal”, where “strcmp” means “unequal”. Am I really the only one who thinks that this is extremely stupid? Might be because – as I already mentioned the perfect hash function generation, which can be also done by the GNU Perf tool (gperf) – the code generated by gperf also contains string comparison expressions using exactly !strcmp. So it doesn’t even look like a fad, it’s an idiom in this language. An idiotic idiom.

Despite that fact (moreover, despite the fact that you didn’t have to be Nostradamus to predict that it will end up like this), up until today there’s no function, which called with two strings will return true if they are identical and false otherwise (these two literals became keywords only in C23). For so many years people have been familiar with that they are doomed to use this strcmp call and compare the result with 0, that all people, who don’t want to agree for it, have switched to C++ and use string with operator ==, and if they can’t leave C, wrote their own function in every project where they are working.

So, was it a problem to create “that awfully ugly duplicate function strequ” (even worse – it was just the matter of providing a preprocessor macro, just “for convenience”), just because strcmp could remain this way a rare and unique function, much like strpbrk or strcspn, which lame-legged dog doesn’t use? No, it wasn’t a problem – just, because you can just as well use strcmp() == 0, there’s “no need” to introduce this. Just as well as you can easily allocate and copy, you don’t need strdup. This wasn’t any “maintaining the purity of the language”, this was just testing the programmers for not being docile and submissive, which many have failed.

Obviously one should start with some famous fun fact that already in ANSI C it was possible and allowed to pass structures by value, but the programmers were scared of it like a devil of holy water. That would be the very first possibility to solve this long lasting problem of passing “array and its size” directly as one function’s argument, put it as a single field in structures, etc. – and it would only require one very simple declaration like:

typedef struct __parray
{
    void* begin;
    size_t size;
} parray_t;

You’d still have to have the right typed pointer in order to access the elements, but at least you have a “single thing” being an array, which you can pass to a function or contain as a field. This sort of thing would be a part of the standard library, could be then used by other functions in the standard library, and this would guarantee adaptation by the users. And not that structures like that, defined in the standard library headers and used by the standard library functions, don’t exist – there is, for example, div_t structure for doing integer division.

Yes, I know, this would be still clumsy because if you have this as a function parameter, inside you’d have to convert the pointer yourself to the desired type. Well, C language doesn’t have templates, but I have also seen people solving this through macros, like:

#define DEFINE_PARRAY(name, eltype) typedef struct { eltype* begin; size_t size; } name

So, this way you can at least have a possibility to declare the array type adjusted to your type and it will be also compatible with other declarations using the same type.

But no, why do we need this if we can still pass separately the pointer and the size in subsequent arguments or have them in subsequent fields. And for strings… we’ll invent a poor-performance “NUL-termination” (fun fact: The Tcl language interpreter, although its “official” version is written in C, has its own definitions of types for strings, with cached size, used everywhere for string operations).

I don’t know how “easy it was to invent”, but the gcc’s version of std::string can be also implemented in C – using structures and functions, but still:

typedef struct __pstring
{
    size_t size;
    size_t capacity;
    char contents[1];
} pstring_t, *STRING;

Of course, you’d need some function set to operate with this, as well as specific ways how to operate strings with possible modification are required, but still, this isn’t to make things comfortable enough (not possible in C anyway), this would be only to open new abilities. Lack of this makes a lot of various solutions simply impossible to be done, or at least enough hard that no one is doing it.

Part of the explanation, why this language is still in use, is that it actually attract mostly the specific type of people. I remember a meeting with one of common friends who was a fan of the FreeBSD system and he showed me some part of the software he wrote. It was around late ’90s and everything was written in the “K&R C” style (an acceptable style by ANSI C, although considered deprecated there, and no longer valid in C++, already in the ARM version). For my question why he is doing that, the response was: because everyone writes the software this way in this system!

Not that I wanted to draw conclusions from a single-person anecdote – I’m presenting it only as a single example case of what might be the reason for some. Something I haven’t earlier imagine that is even possible.

Let me put that straight: ANSI C was stamped in 1986 year and reconfirmed by ISO in 1989. About 10 years the language is on the market and at that time there were physically no compilers that wouldn’t understand that standard. And what was next? C99, which has implemented all “lightweight” things from C++ (static constants and inline functions, both allowed to be placed in the header and resolved completely at compile time), as well as dismissed that stupid requirement for having all variables declared in the beginning of the scope. Then C11/C17, with threads, atomics, complex, and a poor-man template-like feature. Then C23 with extended bit utilities, type inference, partial solution for the const overloading in standard functions. Even the next standard (as I write this, still designated as C2Y) is under development (just rest assured: still no function to compare two strings for equality).

AND ALL THAT FOR NAUGHT! In the both commercial and open-source software being currently developed in C, not only does no one dare to go beyond ANSI C, but even not all useful ANSI C features are in use (check any publicly available opensource project – Gtk, FFMpeg, even the Linux kernel). Reminder: barely 40-year old standard. For most of the active software developers today it’s stamped before they were born. I could only wonder why they don’t use oil lamps at home. That’s probably because, unlike the code legacy written in C, there’s not much working applications of it (although I wouldn’t be completely sure of it – last time I heard from someone that his neighbor has burned down the cellar just because he was repairing the electric installation using a candle as a light).

But that’s not even the matter of abilities of the language. The above shown solutions could be done in ANSI C as well. Simply the programmers are split into two groups: those who learned to live with the C language problems without solving them, and those who use C++. There’s completely nothing in between.

But “ancient C programmers” represent not the only case of making your life harder.

2. Configuration file horror

Configuration file is something that everyone needed since always, but as various applications were required specific way of defining the data, there wasn’t possible any universal way of representing these data. Not only because not everything can be universally expressed as a string, but they also had to be actually databases with often tree-like structure. Worse part of it was that it also required some sensible parser to do that, as well as the whole-text file required also some syntax rules so that some continuous text (being a single value) can be easily distinguished from the overall configuration structure.

So, they started with a simplest method, today known also as “property files” – a flat 1-level structure with one entry of key-value assignments per line (separated by = or : character). A variant for it was the X property file used in the X Window System, where keys had the dotted.path.form and could also have a pattern form with * replacing any required matching subkey on the path. An extension for it were the INI files (surprisingly very widespread), which started already in some DOS applications, spread then wider on Windows, but many Linux applications have adopted it as well. It added a header form as [section name] before the list of lines with particular keys, adding this way the second level of nesting. That way allowed also to use multiple nesting levels, just the section name had to be also a pathname (used in *.reg files on Windows).

Of course this one had a limitation because multi-line values were hard to encode, especially if they had to keep original form as required for another language. So some were trying to find some alternative… NO. No one had any idea how to invent a sensible, universal enough solution for the need. At best they have tried what already was available, having been created for a completely different purpose, or at least not with this in mind.

One of the first available and good enough for many purposes was the form of the list from the Tcl language. This language is actually very specific by many ways, and definitely not just the sole definition of the language would have to be used, rather a standard, which relies also on the Tcl language syntax. So, let’s imagine a flat configuration with path-named keys:

head.type = long
head.color.main = red
head.color.available = red white blue
head.color.description = Select one of these on the side
head.color.maxselect = 2

That doesn’t have to make any sense. So, in Tcl it would have this form:

head {
    type long
    color {
        main red
        available { red white blue }
        description "Select one of these on the side"
        maxselect 2
    }
}

For those who don’t know Tcl: a small problem here is that it has one correctness aspect that can’t be automatically verified: this is the “dictionary” specification in Tcl, which simply requires to specify a pair of two values one after another for every entry. The whole content in braces is just a single value taken as is.

This should have an enough representativeness and quite a clear syntax. But looxlike this has posed a problem for many people because allegedly they simply can’t live without syntax-supported data types, which Tcl doesn’t have at all (in this language, 2 is just as good number and string, just an attempt to interpret it as a number might fail – the same, it has no structures, arrays, lists, at least not as data types, rather interpretation methods). Another problem could likely be that Tcl isn’t exactly very popular also as a scripting language – and if people don’t use this to write scripts, there’s also no need to use its tree structure syntax.

This syntax has also problem with validation. Tcl implements lists as simply words separated by spaces. Words can be single by having no spaces inside or by being surrounded by braces or quotes. Still then, these “words” can be also embedded structures and treated as such. Maps (or dictionaries) are then implemented as lists with even number of elements – odd ones are keys, even ones are values. There’s no definition from upside what kind of structure particular data “is of” – you have to expect particular contents there, which should match the rules. This makes the validation complicated – or at least no one was smart enough to write any software for validating it.

I myself also have an episode of designing a configuration language – named Trip (the name was invented by my colleague, who was a fan of Lisp language, as he said that LISP name is made from “LISt Processing” – so this can be made from “TRee Processing”). It actually had very little differences to the Tcl list, although it was solely thought of as a configuration tree:

  • Operator = was used to specify the key assignment (can be also used without preceding key to enforce empty one)
  • Strings or objects (definition in braces) not followed by = were values only (with empty keys)

It also had more ways to designate strings ("Escapable\nstring", 'Pascal''s string', -Oneline string). This is how it would look like there:

head {
    type = long
    color {
        main = red
        available { red white blue }
        description = -Select one of these on the side
        maxselect = 2
    }
}

I’m not good at advertising, so I failed to reach a wider audience and then I forgot about this project. Simultaneously people were using configurations with other scripting languages – mainly Python and Perl. I won’t be showing examples – this syntax, especially the one from Perl, is so ugly that I really wonder how patient were the people who had to write the configuration files without being any active developers of the scripts using them. Eventually even the data syntax from Javascript was adopted, just because this language also had syntax-supported data types.

And then there has happened a very temporary episode of a large boom for configuration files that is luckily already gone and fortunately no one is even trying to return this failed piece of junk to the glory. No idea how this has happened, why it became so popular, and why it took it such a long time to be thrown out to the trash, where it belongs: XML.

How did it happen? Well, at the moment when the internet started to be wider reachable, there was created a protocol for visual presentations available in the internet, at first as a rich text enhanced with pictures and then also interactive elements. It was the transfer protocol, HTTP, with the description language for rendering the presentations, HTML. As most of the contents was a text, this has simply introduced enhancements for the text and a preprocessing language that should produce somehow encoded rich text and rendering instructions, and there was so added a syntax with <tags>, also closed with </tags> possibly also <tags with=parameter> etc. Some tags were hierarchic, some were allowed to be one-shot (or at least they were non-nestable – next tag open without closing explicitly the previous one was understood as implicitly closed).

So, someone stated: that’s a beautiful syntax, let’s create a more universal configuration syntax basing on it!

What’s in the head of some of these developers that they thought it might be a good configuration syntax, I don’t even try to guess. Suffices to say that there has been created the whole big infrastructure, namespaces, validation configuration definitions, large portions of mergeable configuration parts, XSLT, not even mentioning the definition of the “entities” (non-displayable characters to be put into the text using the numeric or symbolic code). Some even stated that C++ is a retarded language because it doesn’t have an XML parser and serializer in the standard library (actually there were lots of 3-rd party libraries available for that purpose).

Ok, but you might ask: what’s the problem? Well, the problem is that HTML was originally created as a rich-text enhancement: mostly you have a text, but tags define its shape, colors, layout, splitting to pages, inclusion of symbols (hence the “entity” feature, which XML turned into a user-defined entity), picture, or interactive elements. Text was the main purpose, all else was just a helper-supporter. In XML it’s completely opposite – text parts are often hard to find. The only use of the free-form text (still with a limited character set, where disallowed characters can be replenished by entities) was a value assigned to a key:

<entry>
Text as a value
</entry>

which still can be usually just as well encoded as

<entry value="Text as a value" />

Just the tag form was excused in “mostly text” HTML, but XML where the text part is virtually nonexistent it’s completely pointless. The usual tree structure then, which is what XML mostly is about, is something like:

<blocks type="plain">
   <block entry="One block" />
   <block entry="More blocks" />
   <block entry="Another block" with="extension" />
</blocks>
<button type="toggle">
    <label text="Switch" />
    <icon source="toggle-button.svg" />
</button>

Every other kind of configuration language will look better here; in JSON for example, you’d do it this way:

"root" : {
"blocks" : [ "One block", "More blocks", {"entry" : "Another block", "with":"extension"} ],
"button" : {
"type" : "toggle",
"contents" : [
{"type" : "label", "text" : "Switch" },
{"type" : "icon", "source" : "toggle-button.svg" }
]
}
}

or in YAML:

blocks:
- One block
- More blocks
- entry:
Another block
with:
extension
button:
type: toggle
contents:
- type: label
text: Switch
- type: icon
source: "toggle-button.svg"

or even in Trip:

blocks {
  = - One block
  = - More blocks
  {
     entry = "Another block"
     with = extension
  }
}
button {
  type = toggle
  contents {
     {type = label text = "Switch"}
     {type = icon source = "toggle-button.svg"}
  }
}

It was such an horror that I’m really glad this is completely over. Of course, there still exist various tools – like, for example, Ant, the build tool for Java, but I don’t think anyone uses it anymore, except for some ancient projects (the tool itself was last updated a year ago) – better alternatives have been already provided.

So, I don’t exactly know what is worse, as this has been replaced in many uses with JSON (the data syntax for JavaScript – at least it was so described, but it’s not exactly true; its syntax is much stricter). Of course, nothing is worse than XML, don’t even get me started. But JSON was initially described as a way to make the configuration files user-friendly, and unfortunately JSON isn’t exactly user friendly by several reasons, for example, it requires all strings be in “quotes”, including keys in the dictionaries. Still, this is quite an improvement towards XML; manual modifications and visual presentations were even bearable.

But still, people don’t seem to be able to live without data types – I mean, syntax-supported data types. That’s how the JavaScript language and JSON configurations have become so popular. Nothing magic in this: JavaScript was first the language built into the web browsers and it was a way to execute scripted applications inside the web browser only, but then it has become a “general purpose” scripting language through node.js. As it gained popularity, so did JSON. For JavaScript it was a natural language for keeping the data, while XML was for it just as alien as for everything else.

Is that going to be improved? It doesn’t look like. Even though JSON seems to be at least the least problematic configuration language, it hasn’t become one through refinement of ideas, but because of the widespread use of the node.js as general-purpose scripting language. And also not that it is universal enough, even if we state that not every demand for a configuration file in particular software is going to use it as a tree-like database. X-resource, properties, INI-files, even XML in some dying solutions, are still widely used.

Heck, even I have once invented a very specific type of configuration file, but I really could not help myself: the MAF file. Its purpose was to simplify the declaration of the file list for a target in the build definition. The syntax was simple enough so that I could write a parser directly in any scripting language, so beside initially added to Silvercat, I have written also a parser in CMake script language so that it can be used in CMake-based builds. The syntax is very simple: first you have the heading label, which must start with an uppercase letter or a space and takes the whole first line, in the next lines there are filenames. The list of filenames is terminated by an empty line. Later I also added conditionals that can refer to the variables in the build script so that the interpreter can merge lists with the same label, skipping parts that refer to an unset conditional variable.

But then, there should be a “close to perfect” configuration syntax language provided, right? YAML. It has lots of advantages – simple syntax, kinda based on Python (indent as nesting depth), easy to edit as text, with quite a lot of freedom… Yeah, these are advantages. Disadvantage is: really complicated syntax rules, very strict rules for using tabs and spaces (Python, right? XD), very easy to make a mistake, which the parser can only respond with “syntax error here” and that’s about all. This has become a popular configuration syntax for various development tools in web services, such as CI, and make just one mistake in this syntax and the tools just don’t work. Just parse error somewhere and GFY. I was also thinking about writing a 2-way translation tool to some more sensible syntax, but it wasn’t exactly worth a shot.

Might be then there is no sense to have any universal configuration file syntax. Maybe we need sometimes very specific purpose for a configuration file and a syntax that is simplified to the need. But rarely any such use was because of this need. And laziness is not the only reason – some people seem to be even proud of using particular technology (because it’s widespread, popular, all specialists speak about it), even if they make their life harder through that.

Text formatting

As I have made already a separate detailed article about that, the details about formatting will be shorter, but then it summarizes also some of the statements above.

The primary need

As you know, in order to print some text containing values, you need to use some runtime values intermixed with constants, mainly some text. This was always based on a dilemma, what method you should use:

  • The formatting stencil, which contains constant text and tags to fill with runtime values.
  • The series of instructions that would take some constant text and runtime values, wherever needed.
  • A method of gluing together the items, be they constant text or runtime value, passed sequentially.
  • A mix of these two with stencils used for a single segment, then binding segments with instructions.

Now, can we have any universal method of doing things?

Unfortunately no, mainly because whichever turns out to be more comfortable in particular case, it depends on the balance of 3 factors:

  • A relationship between constant text and runtime values
  • The complexity of the conditional tree that determines the segmentation
  • The purpose of the presentation

So, as you remember, the HTML language has been designed for the text with tags that control the rendering, but the state of these above factors was more-less like this:

  • You have mainly text, with some enrichment and some specifically-rendered elements
  • Most of the time you have just one segment, in very specific cases you have more, but usually for subpages only.
  • The presentation was visual-interactive.

The problem is, no one has predicted that these factors (maybe except the last one) will quickly become out of date, as the internet gets popular and simple “enriched text” webpages will turn into wholly interactive applications, also with customizable look and feel. More important than the text on the webpage there turned to be these extra elements, especially interactive, and it turned out to be more required to be “programmed” than written. The web browser vendors have quickly developed more advanced things to be used with webpages (obviously not compatible with one another) – Mozilla provided JavaScript, Opera – CSS, MS Internet Explorer – ActiveX. Fortunately finally two web browser engines remained and the elements were quickly standardized, additionally there appeared technologies for server-side rendering to leave only the simplest part for the browser. Finally the webpages have turned into fully programmed interactive applications and no one even is using bare HTML anymore.

Falsely understood simplification

But what happened in the programming world simultaneously?

Of course, you have to admit one thing: printing some things on standard output for a human is something that is used only in simple or example programs, for learning the programming and the language, but in a real-world programming they are being used at best for handmade debugging or temporary testing support. The biggest use of any output pipes is just one: logging.

So, even though in order to communicate with the outside world, even with the simplest method, when any kind of graphical presentation didn’t exist yet, there was provided the printf function in C, which directly was used more-less as I described above, this function didn’t exist alone. Actually printf was an alias to calling fprintf with stdout as the first argument, while the most logically general function was sprintf, which was preparing the exact text with the formatting. So, this printf was only a convenience alias for the simple uses, while all the logging facilities had to use this formatting as this was actually the only way to convert a numeric type value (double or int) into displayable text.

So, formatting text was provided out of the box, segmenting displayable text was done naturally as this one being a programming language already, but how about sequenced concatenation (segments, as mentioned above)? Well, in the C language this has always been a problem.

Remember in the beginning as I described the horror of string type operations in C? Yes, this spreads just as well here. And here the problem isn’t exactly with strings, but with dynamic strings. For example, you want to print a simple thing like:

Transmitted 205 packets in 55s

Normally we’d expect that the programming language allow me to do something like this – as we know from many other languages:

line = str_concat("Transmitted ", npackets, " packets in ", tdiff_s, "s");

The first problem is, in C we don’t have any system of recognizing the type and applying any translation to string for the given value. The least we need is to use it explicitly:

line = str_concat("Transmitted ", fmt_int(npackets), " packets in ", fmt_duration(tdiff_s), "s");

That would be still kinda acceptable – no problem with translating the value size_t npackets and int tdiff_s into displayable text, but where should we store it? We need as much characters as needed, we need this here where it is going to be displayed, but we need to be able to dispose it when no longer needed.

So, we can still use temporary buffers, we can even reuse one buffer for multiple values in the same call. But the buffer is not the only problem – we also need its size. You know that you should not use sprintf function if you are not sure how much at maximum the string form of the value will take characters – the only generally safe function here is snprintf, which requires the buffer and its capacity.

That’s only one problem. The other problem is that in C you can’t really have a function that can adjust itself to any number of arguments. The only form of a variadic function in C is the so-called forced argument passing, the arguments are copied to the stack in their standard form, and they are then available in the called function by reaching out to the stack memory beyond the last fixed argument. How much of this memory is there and whether the user has filled it in the right size and the right format, the function is unable to check or recognize. Not only must it trust the user that it was filled correctly, but it must also get the explicit information from the caller about the size, format and count of the passed parameters. So, sequenced passing like this – even friendly for the C’s inability to handle dynamic strings:

str_concatn(output, output_size, "Transmitted ", fmt_int(tbuf, tbuf_size, npackets, ""), " packets in ", fmt_duration(tbuf, tbuf_size, tdiff_s, ""), "s");

is simply impossible to implement in this language. This is because even if you ensure that every argument is a string (the fmt_* functions return the buffer passed as the first argument), this function has no idea where the list of the parameters ends. We might do this like with the strings, that is, NULL pointer value should mark the end, but this will have to be still passed manually. So finally our call would have to be:

str_concatn(output, output_size, "Transmitted ", fmt_int(tbuf, tbuf_size, npackets, ""), " packets in ", fmt_duration(tbuf, tbuf_size, tdiff_s, ""), "s", NULL);

So, was the use of snprintf instead like this more comfortable? Of course it was:

snprintf(output, output_size, "Transmitted %d packets in %ds", npackets, tdiff_s);

BUT:

Does this mean that the sequenced passing is bad, useless, harder, whatever? Of course not. It’s simply impossible to be programmed simple way in C language. In many other languages, including scripting ones, it was used widely a long time before the C language came into life.

Of course, may will argue that “stencil filling” has its merit and is often much more useful than sequenced concatenation!

This is limitedly true. It’s true that “stencil filling” is a useful feature and some form of it should be provided. It’s not true that mixing the stencil filling and format configuration specification is a good idea – while this is exactly what the printf function family has become. Stencil filling is expected in this form:

line = str_fill("Transmitted %pkt packets in %{diff}s", "pkt", npackets, "diff", tdiff_s);

and if any formatting tricks need to be applied, they should still be applied where the value is expected:

line = str_fill("Value: %val, size %size", "val", fmt(val, "08X"), "size", size);

Yeah, you may also say that the format specification is important to be in the stencil string because it declares, how much space it should take in the string. I can kinda agree with that, except one thing: this is true for SIZE specification, and moreover, if the size is limited, the displayed text is shortened if needed etc. – that is:

line = str_fill("Value: %{val:n8}", fmt(val, "X"));

So this will result in the following, for example:

0x1234 -> Value: 00001234
0x1234ABCD -> Value: 1234ABCD
0xABCD12345678 -> Value: ABCD1... OR something like: Value: ABCD123*

This is the only solution that makes sense. If your explanation is that the stencil contains the size so that you know what to expect, this size should be also limited. This “n8” declares that it will be the “numeric” filling (zero-filling in the front, unlike “s” that would do space-filling) and the number limits the number of character space to be filled with the displayed number. If this is only the value to be filled with minimum length, or just with any tricky formatting, these tricks can be declared with simplified name in the stencil variables.

New, crazy API

C++ did it a bit better by providing the sequenced concatenation. The problem is, they made it simultaneously harder to use formatting with specific format settings. Even worse, this was state-based, which means that at the moment when your instruction is being executed, even if it’s in a separate function, you don’t know what the formatting settings are:

void display_values(int a, int b)
{
    cout << "Values: " << a << ", " << b << endl;
}
int main()
{
    int a = 16, b = 20;
    display_values(a, b);
    cout << hex;
    display_values(a, b);
    return 0;
}

You will see:

Values: 16, 20
Values: 10, 14

Even though it’s the same function, the same call form, the same values. And if you wanted to display an integer with hex uppercase with 8 ciphers, and then a default decimal value, this “so outdated” printf required:

printf("Value: %08X, size %zu", val, size);

while the same thing with iostream requires:

cout << "Value: " << setfill('0') << setw(8) << hex << uppercase << val << dec << size;

Fortunately you didn’t have to restore setw(0) because it happens automatically after you print a value, and setfill is not required because with width 0 it doesn’t matter, but dec still had to be restored explicitly. The result of this was easy to predict – first, even the developers of gcc have provided at first some extension to the standard library (ostream::form and istream::scan methods were provided – later removed) and the developers have been still using the printf-like formatting system extensively.

Reason? Exactly the same: lack of feedback, lack of good ideas, not responding to the problems at the moment when they first appear. Because once you make a workaround for a problem and adjust yourself to using it, it is too late to provide a good solution. People have used to wrong solutions and in effect they won’t be trying to adopt new solutions, no matter how good they would prove to be in the end.

Effect? C++20 has introduced stencil-based formatting, or in other words, “printf on steroids”. While the single-call function that would sequentially concatenate the arguments was kinda “unnecessary”, even though already in C++11 it was possible thanks to introduction of the variadic templates, even in such a primitive form:

template<typename Stream, typename... Args>
inline void print(Stream& out, const Args&... args)
{
    ((out << args), ...);
}

Obviously, there were two main problems with this:

  1. Special manipulators that resolve through overloading, like endl, could not be used here (this can’t be simply passed to a function; it works with operator<< only through a special overload for it with a scrambled-named type and which performs overload resolution).
  2. This suffers of the same problem as the use of operator<< in general – it modifies the state of the stream, while the function call would visually suggest that whatever you have modified as a stream state in this call, will restore the default formatting settings at the end

This was likely the reason, why no such thing was introduced. Although I would rather see another one: the same exactly problem as with strcmp: why should we introduce this print() while we still can use operator<<?

So, was that a stupid solution in the very beginning? No. This solution could still be fixed and I have also developed a way to fix it. How adaptable it will be, is about to be seen. This relies on two rules:

  1. Printing a value with no extra markers uses default formatting; for strings it simply means to send the whole string to the output as is.
  2. To apply extra non-default formatting, you use the fmt function call with specifying formatting configuration, either in the form of particular settings spec, or by having one predefined with specific variable name.

Why didn’t anyone invent it before: same problem as always – the printing/formatting system was unnecessary for anyone, unless someone needed it in a logging system (and the latter, in the form of spdlog, was the reason to develop the “{fmt}” library, later adopted by C++20), while until then it was good enough for anyone to use snprintf.

Summary?

Not much to summarize. I remember a proverb that my grandma once told me explaining why I should make a better effort when learning to play piano: One, who doesn’t go forward, goes backward.

Same could be said here. If you hold yourself from making life easier, you make life harder. Maybe you just accept this fact and maybe didn’t even notice. But no one would even pay attention, if you only make life harder only for yourself. Much worse is if one is a member of a standard committee, head of the software project, or head of the company making a widely used solution.

And no, it’s not that you cannot do anything because you think you are too little significant. By accepting the hard solutions proposed by the others, the making of the life harder starts with YOU.

Posted in Uncategorized | Tagged , | Leave a comment

Dat yoozless do-while

Have you ever used the “do-while” loop, known also as REPEAT-UNTIL loop in Pascal?

Well, judging by the source code availble for viewing it’s actually not the most favourite type of loop used by C/C++ programmers, to say the least. Actually the problem isn’t exactly in the loop itself. The problem is what exactly the “continue” instruction does.

How useless are the loops

Know what? There’s just one really useful loop in C++. It’s this:

for (;;)
{
   // body
}

Scholars probably have palpitations already. But scholars wish they had such a long experience with programming as I have, so triggering them is a pleasure.

This is first of all a universal loop. You can break it at any time, or in other words, you can put a condition for breaking or continuing at any place inside the loop. Scholars would always say that this shall never be used because such a loop has no end condition, hence it’s infinite!

But how “infinite” is any other loop? Very simple way – it should just contain a condition that in runtime will never be satisfied. Infinite as hell, although it’s not visible in the code. This here “infinite” loop should simply contain a condition that will be surely satisfied in runtime and it’s not infinite. Even if a condition looks like any other kind of instruction inside the body.

Have scholars prevented any runtime problem? No, condemning the for(;;) loop did more harm than good. For example, these two codes are identical:

while (o = get_object())
{
    process(o);
}

for (;;)
{
    o = get_object();
    if (!o)
        break;
    process(o);
}

Just with a small exception that using assignment in the conditional expression in the loop is kinda dangerous, people often use = instead of == in this field so compilers complain, you then either turn off warnings or use while ((o = get_object())) to please the compiler. But you can’t use it normally with separate assignment and condition check. That’s because you are actually using the trick that allows you to put multiple instructions with condition check at the end, all in the conditional expression, just by one simple stupid reason: because you chose to put all instructions that are necessary prior to condition check in the conditional expression. In C++17 it has been even extended to make people able to do even worse things like:

while (View* o = get_object(); o && (o->full() || o->last()))
{
    process(o);
}

Just as if it were any “more readable”, “easier” or “look more professional” than this:

for (;;)
{
   View* o = get_object();
   if (!o)
      break;
   if (!o->full() && !o->last())
      continue;

   process(o);
}

But even that not always helps, so stupid programmers do sometimes things like:

View* o = get_object();

while (o && (o->full() || o->last()))
{
   process(o);
   o = get_object();
}

Only because of one reason: to place the condition in the conditional expression of the loop. Sacrifice is never too great for this, even readability, repeated code, inverted order of natural things – all just for one: to put condition in the conditional expression. It’s even sometimes necessary to even use gotos inside. All sacrified for just one thing: avoid using for(;;).

Whereas it turns out that actually all types of loops are useless, except for. Yes, for, I’m not even talking about infinite for. The for loop’s initial expression is exactly designed for that reason: simulate the range of items for which it is designed – hence it can be used for both a range of integer number values, as well as iterating over nodes bound to one another through the next field, and even for the “list safe loop”, a bit complicated, but still best expressed through the for loop:

for (Item* i = list->head(), inext; i != NULL; i = inext)
{
   inext = i->next;
   if (!process(*i))
      list->erase(i);
}

So, the for-loop with expressions is useful as a loop that well expressed the intention of the looping instruction, whereas the “infinite for-loop” is simply a universal looping instruction. All other types of loops could be simply aligned to this one and expressed like for (; condition; ) instead of while. Or this is also the only way to implement the restartable one-shot loop.

Restartable one-shot loop

It’s an unusual type of loop, which on the other hand are not so rare in programming. Unfortunately there’s no looping instruction in C++ that could support it, hence for(;;) is the only way to do it.

What is the “restartable one-shot” loop in general? Its simply a range of instructions, which normally should be executed exactly once (so the “loop” is to be executed at least once), however if some unlikely conditions are satisfied, the whole series of instructions should be executed again, and of course, the condition rechecked. Example:

for (;;)
{
    View* o = get_object();
    if (!o)
    {
        check_yield();
        continue;
    }
    process(o);
    break;
}

The characteristic treat of this loop is that it always has an UNCONDITIONAL BREAK at the very end of the body, whereas every occurrence of continue inside the loop body means to “restart” the loop.

A variant of this loop is the “conditional restartable loop”, still the intention is that that the condition is satisfied in the beginning, and during the run of the loop it should be no longer satisfied and at best the loop should be run only once:

while (condition)
{
    View* o = get_object();
    if (!o)
    {
        check_yield();
        continue;
    }
    process(o);
    // we state we're done here, condition need not be rechecked
    break;
}

So, well, hard to say whether this should use for or while, both actually look clumsy by one reason: the information that it should be a “one-shot repeatable loop” must be somehow placed in the comment because it’s required to be visible at the head of the loop, while the instruction that makes it really the one-shot loop, the break instruction, must be always placed unconditionally at the end of the body.

And here someone might think that it could be a perfect solution to use the do-while loop here. Naiive, though.

The useless do-while loop

Ok, one might think that the do-while loop with false condition should be the perfect solution for a one-shot loop. The do-while with false condition has been also long used as an idiom for macrodefinitions to force the user put the semicolon at the end (to prevent compiling formally non-erroneous, but unwanted code).

And that’s right – you have the condition false, but the loop is guaranteed to be run at least once. Then it runs until the end and it won’t be repeated because the condition is already false. Should match our needs perfectly, right?

The problem is when you try to repeat this loop using the continue instruction:

    int i = 2;
    do
    {
        cout << "ONCE #" << (2-i) << "\n";
        if (--i)
            continue;

        cout << "EXTRAS\n";
    } while (false);

That’s what we wanted here, right? When the i value didn’t reach the value 0 yet, we run the loop body again from the start, right? Unfortunately when you run this code it will surprisingly run the body only once, not twice as you might expect. Why?

Because the condition maybe is at the end, but continue doesn’t jump to the beginning of the loop, as you might have thought it does in case of the while or for loop. In case of this loop the continue instruction doesn’t jump to the beginning of the body, but to the very end of the body (which theoretically doesn’t make a difference because for a loop an end is a new beginning). What matters here is that continue causes the condition in the while part of this loop to be checked again. And, as it is explicitly false, it will always lead to interrupting the loop. To achieve what you really wanted, it should be fixed this way, for example:

    int i = 2;
    do
    {
        REPEAT:
        cout << "ONCE #" << (2-i) << "\n";
        if (--i)
            goto REPEAT;

        cout << "EXTRAS\n";
    } while (false);

Ugh, this ugly goto again! Can we go without this?

Of course, I just used it so that you can imagine what really was expected here and see what the difference is. The goto instruction not only needs to be avoided (scholars, again, I know!), but in C++ the goto instruction also had limitations. In loops you often use local variables that may have constructors and destructors, and the goto instruction in C++ is requested to work strictly within the purview of the local objects – that is, it can’t jump over an initialization or cause reinitialization without destruction first. This doesn’t mean it can’t be used – this way the problem of repeatable loop can be solved in many cases.

Another solution can use a combination of boolean variables with for loop:

    int i = 2;
    for (bool cont = true, breaking = true; cont; cont = !breaking, breaking = true)
    {
        cout << "ONCE #" << (2-i) << "\n";
        if (--i)
        {
            breaking = false;
            continue;
        }
        cout << "EXTRAS\n";
    }

As the elaborate code messes up with the true intention, it can be even hidden in preprocessor macros, which in this case can be even done the way that fits well with syntax highligher and intellisense:

#define oneshot() (bool cont = true, breaking = true; cont; cont = !breaking, breaking = true)
#define repeat {breaking = false; continue;}

...

    int i = 2;
    for oneshot()
    {
        cout << "ONCE #" << (2-i) << "\n";
        if (--i)
            repeat;

        cout << "EXTRAS\n";
    }

Not sure if the compiler would nicely optimize it, but at least it looks clearly as for the intention. Unfortunately you can’t just use continue here, instead you need to use the pseudoinstruction repeat here. The version with precondition can be also created out of it, you just need to create a different macro, say oneshot_while(cond) and place cond also within the conditional expression in the for loop. Of course, the condition will be rechecked together with the continuation marker.

Summary

As the while loop can be easily simulated by placing the condition in the top of the loop’s body in the for (;;) loop, the do-while loop can be simulated the same way by placing the condition at the end. Although not quite – if you do this with using the continue instruction inside, it will behave just like the repeat macro in the examples above. But then, is there any necessity to use it the way it does? What was exactly the merit and use cases for this do-while loop?

As I personally rarely use it and I can’t even recall a single case when I have used this loop the way that the creators of it have imagined, it is even hard for me to give an example. Every single example that I can think of is a version of the last mentioned “emulation” of this loop, but then with for (;;) you can actually do more things or implement things more reliable way.

This loop is at least intended for situation that you know from upside that some condition is satisfied and you do things without checking it, then it’s checked at the end. But even in this case I wouldn’t even imagine using the continue instruction, which should be understood as “go to the end of the body and recheck the condition“. A better name for this instruction for such kind of use would be “skip”, not “continue”. And what I really wouldn’t imagine is in what situation in such a loop I would use “skip” as I can’t think of any. As I said, this is the REPEAT-UNTIL loop type from Pascal, but Pascal didn’t have any “continue” instruction (at least not the first version, preceding C). If you wanted to use it, you just had to construct the condition tree inside the loop correctly – but in this case this very condition dictated whether the rest of the body would be skipped or the whole loop repeated. While for implementing the repeatable one-shot loop this loop type is useless anyway.

Posted in Uncategorized | Tagged | Leave a comment

C++20 Modules and K-Modules – comparison

Reasoning

As a motivation, why I still think the works on K-Modules make sense, even though the “standard” module system for C++20 has been already implemented in many compilers and is ready to work, I’d like to show all differences, not just in the design, but as consequences for the programmers and software production in general.

Let me bring in the most important factors, which decide that adoption of C++20 modules in the software industry isn’t really going to happen.

The matter of header files

Header files, together with the whole preprocessor thing, brought together with C language, has been a burden for a long time. Actually they have more than just one disadvantage, and I can see that not all of them are correctly understood. The following things are among them:

  1. The definitions from earlier header files influence interpretation of the next ones. Same applies to command-line-defined macros, but these are at least directly handled in the build.
  2. The compiler doesn’t require header files to be entity-complete (it would also have problems with checking it).
  3. Every header must have macroguards, which also undergo potential name conflicts (even though very rare).
  4. From the C++ standard perspective, the preprocessor is an external to C++ language itself, which is taken as such only with preprocessing already resolved. Header files are then treated as a part of the input of one compilation unit, not a separate source unit (more about this below).
  5. Header file is the only way how you can provide an interface for an entity defined in particular compilation unit to be used in another compilation unit. Although theoretically you can generate them from the implementation files, this possibility is limited and usually clumsy (more about this below).
  6. Every declaration that is contained in the header file must be parsed and interpreted by the compiler every time anew, which largely increases the wasted compiling time. This problem is partially mitigated through precompiled headers.
  7. In various indirect rules the C++ standard mandates that the resolved form of the header file be exactly the same in every compilation unit of the same project, while it’s impossible to guarantee.
  8. Header file is the only way to provide an API for a library – and it must be a dedicated header file, extracted during the library build and installation, separate from the inter-module header file.
  9. If the entity (actually a function or a method) is defined in the source file, then the declaration providing the interface for it in the header file must be actually repeated there and kept in sync all the time.
  10. Several types of entities must be provided completely in the header file (like type definitions) and some type of information can be only provided in one and not the other associated part of the definition (default parameters, which shall be in the function/method declaration, but not in the definition etc.). This makes that usually you have to split the definitions that touch upon a single module into two physical files – and it’s not just something that comprises only an “interface part” of the module. The header file is an integral part of the module, just stored in a separate file.

Ok, now, why am I enumerating all these things?

Because I’m going to prove that the K-Modules system solves all these above problems, while the C++20 module system solves only part of them, while it also withdraws some of the C++ features that were so far available with the C-module system. What are then the features of C-modules that could be endangered by the module system?

I’m trying to enumerate them here, but keep in mind that I don’t treat them all equally as worth saving. Some of them are of little usefulness and some can be replaced with better alternatives:

  1. Allow to interface compilation units towards the other units, including those, which’s interface is used by this compilation unit.
  2. Allow to be configured through the command-line macros.
  3. Allow to be configured also through the macros defined before including this file (known case of <stdint.h> header and __STDC_FORMAT_MACROS macro for example).
  4. Can be included conditionally (potentially various different header variants can be included depending on conditions).
  5. Can provide various different variats of the interface, depending on conditions

The C-Modules description

As a small extension to the problem 4 from the description above, note that the C++ standard does mention the preprocessor and does mention compilation units as a system – but there exist several rules that in practice must be kept always in every C++ project, of which the C++ standard speaks completely nothing, like:

  1. A function that is defined in the header file must be either inline or static function. Actually if it is static, its definition will be provided the same way separately in every compilation unit that includes this header, so this, although possible, shall not be done. The standard doesn’t mention this at all; about inline functions it only says that the definition should be provided separately in every compilation unit, but in each one of them it should be defined the same way (like it was sensibly possible any other way than through a common header file).
  2. Every implementation (or “source”) file, which provides some entities declared in a header file, must include this very header file. This theoretically isn’t necessary when you only declare functions, but inevitable, if you declare a class.
  3. A class to be used by more than one compilation unit must be completely defined in the header file. Or at least that part with methods to be available for other units. This is also the reason why methods defined completely inside the class are inline, and they are only “extern” if defined outside the class, while for free functions inline must be specified explicitly, otherwise they are extern. This inconsistency (unfortunately not very possible to be changed) is the direct consequence of the use C-Modules.

This way the entities in the C++ language can be split into 3 categories: physical, ephemeral and vague:

1. Physical entities

These are the following entities:

  • Function definitions (bodies), including external method definitions
  • Global object definitions (both variables and external constants)

These are definitions that have some heavy contents and are identified as a linkage symbol. The unique treat of physical entities is that they must be unique throughout the whole target package: in all files linked together into one target this symbol may occur only once, otherwise the linker reports an error.

Note that physical entity category doesn’t exist in C language (that’s a point of backward incompatibility for C++). In C these entities are vague.

2. Vague entities

Vague is similar to physical – the difference is that multiple identical symbols are allowed for vague entities, and the compiler will take the first found as a good deal. It is assumed, however, that every occurrence of this symbol designates an entity defined identically. In C++ they are only entities that are generated by the compiler, normally for the sake of various ephemeral entities:

  • Virtual method tables for polymorphic classes
  • RTTI information
  • External versions of inline functions (a compiler may decide to make a callable version of an inline function; unlike the explicitly defined external function, this kind of entity is vague, not physical)

Interesting thing – static class fields could be aligned to that, but they weren’t (actually this qualification is something that compilers must have come up with in order to be able to physically implement any crazy C++ ideas). Therefore static class fields have there first in-class definition – which is ephemeral – but the physical entity defining this field must be also provided separately.

3. Ephemeral entities

These are all entities that do not have any contents stored in the compiled object file:

  • type definitions (classes, structures, unions, typedefs, enums)
  • inline functions
  • static constant definitions (static is default for constants in C++, unless overridden by extern), including static constants defined inside a class
  • extern global object declarations

4. Rules for entity categories

The entity categories’ definitions are important because they also undergo the following rules:

  1. All ephemeral entities must be placed in a header file, if they are used by entities from more than one compilation unit.
  2. All physical entities must be placed in the implementation file.
  3. Templates can only exist as a class definition or an inline function. Physical entities for templates can only be explicit instantiations (of either a function template or a method of a class template). There were created some compilers that tried to overcome this limitation (allowed physical template entities), but this was only an experimental feature, never used in the industry.
  4. No namespace shortcuts are allowed within the header file. The using namespace statement is not allowed at all, and using with particular symbol name is only allowed in order to re-export a symbol in a new namespace.

Note that in the K-modules these limitations concerning templates still hold, but they are at least easier to handle.

The ‘import’ instruction for header files

It was under discussion for many years that the #include directive could be replaced by some include instruction (or import, as it turned out to be eventually) in order to eliminate the problem that the feature number 3 brings in. This way the “environment” (set of the macrodefinitions available at the moment) was different: every header file was compiled in the “fresh” environment (“polluted” only by the compiler and command-line), and all the macros that they define would be only visible in the source file that includes them.

This alone clears out the 1-3 of the above mentioned problems (maybe 4 partially, too). All others were expected to be solved by modules.

The “makeheaders” legacy – ignored by C++20 modules

One of the problems with header files seems to be quite important – splitting the source code into two files – and there were tried some ideas to fix it (the problem number 5).

One of the ideas, which is still compiler-dependent, but anyway interesting, was the use of __INCLUDE_LEVEL__ macro provided by gcc (and clang as well I think). This value can be read and checked – if it is 0, it means that the code being compiled at the moment comes directly from the file, otherwise it is contained in a file being included. This way you can have both header things and implementation things in one file, just the implementation things should be surrounded with the #if __INCLUDE_LEVEL == 0 condition. Then other files may simply include this file. This method solves the problem of keeping things in one file, but with this you still have to keep the interface and implementation separate. Of course, you still have a possibility of using this directive in multiple places, so you can do something like, e. g.:

int Range(int lower, int value, int upper)
#if __INCLUDE_LEVEL__ == 0
{
   if (value < lower)
        return lower;
   return std::max(value, upper);
}
#else
;
#endif

This could eliminate then also the problem of repeating the signature (problem 9), but I think you admit, it’s clumsy, and there’s nothing you can do to make it any more comfortable. Could be also something like:

#if __INCLUDE_LEVEL__ == 0
#define BODY(body) {body}
#else
#define BODY(body) ;
#endif

// ...

int Range(int lower, int value, int upper)
BODY(
   if (value < lower)
        return lower;
   return std::max(value, upper);
)

// ...

#undef BODY

Still clumsy, if you ask me.

I found then also a very old program named “makeheaders“, which actually works in the frames of the C-module system (it was actually designed for C language initially). With this tool you define everything in just one implementation file, and the header file is generated out of it. It’s maybe less clumsy than the method using the __INCLUDE_LEVEL__ macro, but it’s still clumsy. For example, for a function it suffices if you mark it EXPORT, but if you have a structure, you have to surround it with #if INTERFACE.

It’s said to be working also with C++, but I doubt that it will cope with more complicated things like:

  • cutting off the method bodies into an external definition (required if you want to define all methods inside the class, but still want them to be external)
  • identifying the symbols in the namespace to be put into the header file fully expanded.

The comparison

Ok, so enough introductions, let’s get to work.

Single pass vs. multi-pass

The most important difference between C++20 modules and K-modules is that in C++20 modules there’s still kept intact the single pass principle. That is, when you compile a given file, you are doing it only once, and produce all required results at once, and never come back to this file again. This influences lots of other features.

In case of K-modules the compiler is required to work in a multi-pass style. That is, it can tokenize the whole file and prepare the AST of everything, but it must then be able to put definitions into separate databases of 3 different categories: forwarders, interface, and implementation. Only then should it start interpreting them, all one after another for the complete group. That’s why it must have all forwarders already known before it starts interpreting interfaces, and it must have also all interfaces before it starts interpreting the implementation – which are mainly method bodies and global variable definitions with possible initialization expressions.

The emulation implementation should then extract all these things from the source file and store all 3 groups separately in separate files, then the forwarder is included in the interface header file, then the latter in the implementation file, as well in every other source file that imports this module. This extraction happens independently on whether the entity is exported or not.

The particular compiler command should then extract only one of these three categories, while skipping the others, that is, do it later, in a separate call. The compiler must somehow organize the file identification and partial result storage. This is necessary for a case when you want to compile the interface, but not implementation, of the same module.

Multiple module files

In C++20 modules you can define the contents of your module in multiple files, hence you have to provide one of these files with interface (using export module declaration), plus possibly more with implementations. You can as well provide only the interface file, but then you might want to provide some non-exported definitions there.

One may ask: why would you need such a thing? Can’t a single module be defined in a single file?

So, there is one: this is because when you compile a module’s source file (any of them, as here), you must already have all interfaces that this module imports already compiled. This is the consequence of the single-pass principle: you can’t compile the file, which’s dependencies you can’t resolve – so you must shift the dependent part into a separate file so that it can be compiled later. This actually keeps the problems 9 and 10 intact – instead of having header and implementation files for one module, now you have one interface source file and one remaining implementation source file – still two files with directly defined entity categories that must fit there.

In K-Modules you can always keep the entities for one single module in a single file, even if you have cross-dependencies with other modules, as you compile all interfaces first in the order of interface-on-interface dependencies, then you compile implementations of these same modules after you already have interfaces compiled for every module imported by the compiled one.

Therefore there’s no export module nor module :private section. If by some reason you have to split the contents of one module into multiple files, use partitions.

The ordering matter

In C++20 the order of declarations still matters, just like in the all earlier versions of C++. This is still because of the single pass principle. This means, for example, that:

  1. If you have a function A() calling B(), the B() function must be either completely defined before A(), or at least the declaration of B() must be placed before A().
  2. If you have a functional definition (function, method, operator) that could be a better overload for particular type, for which some worse overload already exists, and this definition will be provided after the call inside the function body, the worse overload will be preferred to the better one because the better one isn’t known at the moment when compiling the body containing this call. Note that this rule isn’t kept if both definitions are inside a class.

This means that even if you have a function defined in the same file, and even if this is a static function, which can’t be accessed by its symbol from outside, you still need to make a forwarding declaration before the definition of a function that calls it. The ordering rule is actually still the legacy of header files, which was reasonable stating that the compiler actually reads declarations from all files one by one merged together.

Although the ordering may matter in some cases, there’s no need to keep the strict ordering in case of the function bodies, which is usually the implementation part. That’s also partially the reason, why in order to be able to have cross-dependencies between modules, you need the “forward part” to be available before you try to compile the dependent module.

In K-Modules you have multi-pass, which means that the only case where the order matters is when you have dependencies on the same level, mainly interface-on-interface – such as calling an inline function in another inline function, deriving another class, or placing the plain-typed (“sunken”) field of this class in another class. For everything used inside a function or method body, regardless if inline or external, you can refer to entities declared anywhere in this file, including after the body.

The function interface matter

In C++20 modules the dependencies follow the definition order and the matter of inline is still to be solved by the compiler – in theory because no compiler has ever implemented the inline expansion across compilation units (which means, every method you defined in the interface source file can be potentially inline, but not the one in the further implementation files). So, you can define the complete method in the module’s interface source (the one declared with export module), but whether you can do it or not, depends on whether all the dependencies are available when compiling it.

In K-Modules the use of inline is important: The inline function is a part of the interface together with its body, while for external functions only the signature is the part of the interface. Whatever is then used in the body of the inline function, must be reexported by the interface that provides this function. The same then applies to the class methods, and that’s why methods can be added the extern modifier, which makes the declaration extern and therefore the body isn’t part of the interface.

The partitions

Most of the things defined as partitions in C++20 are preserved in K-Modules. The main difference is that partitions in C++20 modules are like separate modules, just accessible only through the master module source(s). Still, entities that are not exported belong to the “internal interface” category, and although they are not accessible outside the module, they are accessible within all sources of the module.

The important treat of partitions in K-Modules is that the interface defined in the master module source (both exported and internal) is automatically a dependency of all partition files. Partitions still can export their own parts of the interface and should be then reexported by the master module source.

The default module name

Modules in C++20 must have an explicitly defined name. The filename of the module never has a thing to do with it.

In K-Modules you can make the module name follow the root filename, which is the case when you declare module default. This can be useful if you want to strictly follow the file naming to be the same as module names. This isn’t possible in case when the module is split into partitions.

The preprocessor macros

In C++20 modules the preprocessor macros are never exported. The only way to get a macro from an external definition is to include this file in the GMF.

In K-Modules you can export macros through #export directive. This makes the macrodefinition visible in the source file that imports the module. Note though that not every macro can be exported. A macro to be exported must be expression-complete – that is, it must resolve to either a complete entity definition, or a single expression (which can be part of another expression). If the definition is an expression, composed with operators, it must be also surrounded by parentheses. So, the following macros can be exported:

// Single value is a complete expression.
#define BUFSIZ 512
// A compound expression is still a complete expression
#define ADD3(a, b, c) (a + b + c)
// A function signature is a complete expression, even if without ; or {}
#define ENTRY(name) int Parse_##name (const char* buf)
// Note: just "+0" is not allowed because it wouldn't be a complete expression
#define POS_ZERO (+0)

while such types of macros can’t be exported:

#define ENTRY_TABLE_BEGIN(name) EventEntry entry_table_##name [] = {
#define ENTRY_TABLE_END() }
#define AS_INT 0+

Note that the only place where exported macros can be used is the implementation. This means they can’t be used, for example, in inline functions. The same applies to macros brought in into the file through GMF. Exported macros do get re-exported when the module interface providing them is export-imported, but they still cannot be used in the interface definition.

Interface variants

In C++20 only solid, unchangeable and non-conditional interfaces are possible.

In K-Modules there is a feature that allows creating module template form files, which can contain alternative interfaces that can be selected using the preprocessor macros provided in the command line. Note that the same set of macros must be provided when compiling every other compilation unit for the same target.

In other words: if you have a module file that contains preprocessor conditionals for providing variants of the code, you can require compiling a module template form, that is, the code is interpreted the way of having particular conditional expression turning to be true or false, and both will be available in the compiled module form file. This will have to be then resolved into the module interface file by instantiating the macrodefinitions. Of course, in the whole project you can only use one variant of particular module and define the variant resolution in the build process.

The libraries

It doesn’t look like that C++20 modules have any idea for implementing libraries. Several projects have been trying to get implemented as a module, but most of them were simply header-only libraries. There is no idea how to distribute that library in a compiled form nor is there any distinction between exporting the library API and exporting entities that should be only accessible for other modules of the same library. There were some ongoing discussions on how to implement this, but it requires some standard interchangeable form of the compiled module file, which is at least the same in one platform, but this is still in the phase of a concept. Just as well there’s no concept of how to distinguish interfaces between modules internally for the project and interfaces that have to be exposed as library API.

K-Modules provide the public module interface feature and they distinguish between importing interfaces of modules that belong to the same project and interfaces that are brought in from an externally compiled library. As an example, let’s take a private module “packetfilter” and a public module “packetfilter_api”:

The “packetfilter” module:

  • Module declaration: module packetfilter;
  • Generated interface filename: packetfilter.cmi
  • Imported by other modules by: import .packetfilter;
  • Available for: only modules from the same project (linkage group)

The “packetfilter_api” module:

  • Module declaration: public module packetfilter_api;
  • Generated interface filename: packetfilter_api-public.cmi
  • Imported by other modules by: import packetfilter_api;
  • Available for: any project

Note also that a single module may contain as well both public and private declarations. In that case the module is still declared without public, but then you should simply use public export instead of export for all entities that need to be part of the public interface. If you do so with the “packetfilter” module, you’ll have:

  • Module declaration: module packetfilter;
  • Generated interface filename: both packetfilter.cmi and packetfilter-public.cmi
  • Imported by other modules of the same project: import .packetfilter; (note: both public and private)
  • Imported by modules of a foreign project: import packetfilter; (note: only public interfaces)
  • Available: the public part by the foreign projects, and both parts by the current project

Although the possibilities for the implementation of the libraries are limited and should follow most of the current practices developed for C-Modules, it is also potentially possible to develop a more elaborate library distribution forms, which may contain files like MODULE_NAME.cm that contains both public and private interface, as well as the implementation (in the form of embedded object file), of which only the first one is accessible externally. When a better format than the object file is developed, this can go even further and potentially allow to store things like inline-expandable functions or templates to be generated functions from in these files.

Reviewing problems

Ok, so let’s see how particular problems with header files that I mentioned in the beginning, are approached by particular solutions:

  1. This problem is solved already on the level of header files, which you can also include using the import instruction. So the basic header importing feature solves this problem already. Note also that the macrodefintions provided in the command-line are still visible there before interpretation of the header file. These macros, in case of importing the module’s interface by name, influence the implementation and the form in the source syntax, but they don’t influence anyhow the interface. Note that K-Modules offer something called “module template form file”, which contains all alternative definitions available by appropriate macro setup, so conditional control of the interface is still possible.
  2. Not sure about that, but including a file through import instruction already requires the header file to be entity-complete. Various compilers implement it different ways, but for example gcc requires that the header file be “precompiled” so that it can be imported. And this won’t work if the header isn’t entity-complete.
  3. Macroguards are not required when you include the header file through the import instruction.
  4. With importable headers, this time the standard must somehow treat the header files as a separate beings. In C++20 the only things you distinguish is the interface file created with export module declaration. In K-Modules the only thing distinguishing the interface parts is the export declaration in entities.
  5. Interface files compiled out of the source files provide the interface part required by other modules just as well. However, in C++20, if you have cross-dependencies between modules, you have to keep the interface in a separate source file. In K-Modules you don’t need to have compiled all interfaces from all dependent modules in order to compile the interface of particular module.
  6. Compilers do mitigate this problem by a special requirement that an importable header file must be precompiled. In C++20 modules, you compile the interface file once and then you have a compiled form already. In K-Modules, you compile the interface part of the source file the same way.
  7. Unsure how this works in case of C++20 modules, although there can be only one form of the interface anyway. K-Modules should use file checksum in order to ensure that all intermediate files in the compiled module directory still refer to the same source file. The checksum should be calculated on the tokenized form, which should be also saved in the module directory file (so formatting or adding comments do not change the checksum). Anyway, even if there are macros defined in the command line, they can only influence the form of the interface when compiling the interface, but they do not influence anything when compiling the implementation using that interface as dependency.
  8. C++20 doesn’t have any provided support for a specifically declared library API. In K-Modules the library API can be defined as the public interface, declared through public export modifier, as well as in K-Modules importing of an interface from an external library or from a module in the same project are distinguished by syntax.
  9. This is still a problem in C++20 the same as in case of header files. It can be avoided if your module’s implementation and interface is independent on any other module in the same project, but if you have something like the use of interface of two modules in the implementation, you have to do “forward declarations” by keeping the interface in a separate module interface source file. In K-Modules you are never forced to do this. You can define every entity’s details only in one place, regardless of where the dependent parties are. This includes methods that normally are declared inside the class and defined outside in the implementation file: when they are marked extern, the result is as if you have defined them outside the class.
  10. You are free of this problem in C++20 modules, as long as your implementation is independent on other modules. Otherwise you have to split the definition of the module into the interface and implementation part and have the same situation as with header files. This means then that the class would have to be provided only and exclusively in this module interface source file. In K-Modules there’s no such distinction, as well as you may only have one source file per module, as long as you don’t use partitions. You can still split the module’s source into multiple files by using partitions if you want, but this is never required.

Summary

The main principle for K-Modules is the ability to continue with the current projects written in C++ using the C-Modules system with only benefits and minimum required work. So, you need first to do the minimum work of reshaping your project so that every module is done according to one of the following models:

  1. A single-header module without the implementation file.
  2. A module consisting of a single header file and single implementation file.
  3. A module consisting of multiple implementation files with a single header file for all of them.
  4. A “main” module without a header file.

You can rework every module separately and you can also work with only parts of the modules being transformed. The only difference is that if a module was transformed, all files using it should import it as a module, while those not yet transformed should remain with importing headers. This is then how you transform them:

  1. The single-header module is turned into the module source, with all entities marked as export. Note that not every entity must be actually exported, but mind the dependencies – if an inline function calls another function from this module, that second function must be also exported.
  2. In this case you just put the contents of the header and implementation in one file, as well as method bodies can be all put inside the class. Parts that were in the header file are just marked export. Methods that are not suitable to be “inline” (which was always the case when defined inside the class) should be just marked extern.
  3. In this case you should turn the header file into the master module source and implementation file into partitions. If you think it makes sense, you can also select one of these implementation files and make it to the master module file. If you have a system of “protected headers” (header files, which are intended to be only used by the group of selected source files), you can make them part of the partition source files.
  4. This one you just turn into a single module source file.

Note that in actually all cases you have one single file per module, except for the case 3, where you might want to use partitions to keep the definition of a single module in multiple files. Even in this case though you may consolidate the interface and the “main source”, should you have something like that, in one file. No repeating or forwarding is required.

Posted in Uncategorized | Tagged , | Leave a comment

K-Modules in C++ – concise example

Motivation – introduction

The idea of K-Modules is the module system for C++, which is different to the proposal in C++20 and is not compatible with it, although it shares most of the ideas from it, as well as it retains all possible features that the “C modules” system provided (and the C++20 modules proposal has partially damaged). What is interesting is that this system can be as well applied to C, and in contradiction to normal treats of C++, I think it might be interesting for the C community, at least because it actually restores some treats of C that were made obsolete in ANSI C. Let me enumerate some important principles of this design:

  1. All features of C++ available with the current C-Modules should be maintained, just with a different syntax.
  2. The idea of header files should be eliminated by making it possible that every entity is defined only in one place and one instance. The “forwarding declaration” method is still possible, but unnecessary.
  3. Only one kind of features is to be eliminated: an ability to configure the next header file through the definitions ahead of the header inclusion directive, including from other header files. Actually this feature isn’t completely eliminated, just moved to its own separate section (GMF).

Here I’ll be trying to explain the idea using simple examples.

As for the name: I was simply attempting to create a trial implementation (which should just generate the header and implementation files) by using a wrapper over the gcc command, which should be then transparent for all other options for gcc command itself. Therefore I was trying to find some model for options that aren’t handled by gcc so that I can freely reuse them and it looked like that gcc doesn’t have any option starting from -k. Hence I decided to reuse it and then also in the feature name.

Let’s start with several highlights of K-Modules and relation to C++20 modules:

  1. Things that remain (almost) the same:
    • GMF (Global Module Fragment)
    • Importing header files
    • General module functionality (importing by name, selective entity exporting)
    • Partitions,
      • except dependency on the master module interface
      • including internal interface accessibility
  2. Features from C++20 not provided in K-Modules
    • The export module declaration
      • the “one file per module name” rule
      • multiple files per module supported only through partitions
    • Module private section (unnecessary in this situation)
  3. Features from K-Modules that overcome limitations in C++20
    • Order-free declarations: Implementation part (function bodies) may access interface of other entities regardless of the order of declaration.
    • Cross-dependencies: modules may depend on each other, as long as it’s an implementation-on-interface dependency
  4. Extra features in K-Modules
    • Preprocessor macros can be exported
    • Modules named after the filename (module default; declaration)
    • Library API exposure through public export or public module declaration
    • Distinction of project-local modules and external library modules

Let’s take some simple examples then.

General example

module;
// Global Module Fragment. Here you can freely use #include,
// but you can't define entities directly.

#define USES_CONTAINERS 1
#include "../common_defs.h"

// The "module" with name starts the actual module section and
// sets the name of the module. Allowed characters are identifier
// characters and a dot. Partition names can also start with a cipher
// character. If the name is "default", the actual module name
// will be taken from the source filename.
module default;

// Local imports: these are modules that belong to the same PROJECT.
// PROJECT: set of files that are ingredients of the same TARGET.
// TARGET: application or library.
// Local module interfaces are searched in the same directory as the
// one where compiled modules are stored. Filenames follow the name
// except the leading dot, added with appropriate extension.
import .types;
import .utilities;
import .storage.json; // Interface file name: "storage.json.cmi"
import .cmain;

// Global imports: these are foreign modules reached out through the
// public interface of a library. Global modules follow the global
// imports path that can be configured with multiple directories.
// Filenames follow the name plus the "-public" suffix, added with
// appropriate extension.
import std;
import curl.http;
import glibmm.gio.application; // "glibmm.gio.application-public.cmi"

// NOTE: import declaration may only follow the named module
// declaration or another import declatation.

// This declaration is only allowed after imports and before any other
// entity, as this imports this for the whole file and in other place
// could be misleading. This can be still placed locally in a function
// body and in this case there are no restrictions.
using namespace std;

export void cmain(const vector<string>& args)
{
    // Note: Application is still declared in the same file, so it
    // can be used. It doesn't have to be declared above the function.
    // Ordering is required only if you have interface-on-interface
    // type dependency.
    int code = Application::main(args);
    if (code != 0) throw code;
}

// This is a class used internally in this file,
// so it doesn't have to be exported.
class Application: public Gio::Application
{
	Application()
    {
		set_inactivity_timeout(10000);
	}
	public:

	void activate () override
    {
	    cout.println("activated");
	}

    // A method marked "extern" behaves like a method defined outside
    // the class body.
	extern void open (const array<File>& files, string hint) override
	{
		for(auto& file: files)
		{
			string uri = file.get_uri();
			cout.println(uri);
		}
	}

	extern static int main(const vector<string>& args) {
		Application app;
		int status = app.run(args);
		return status;
	}
};


General changes in the source code writing (towards C++17)

0. Pre-statement: The source file is split into 3 sections

The sections are: GMF (Global Module Fragment), Import (the set of import declarations) and Entities (normal contents of the source file). GMF starts with module; declaration (without a name) and holds until the module <name>; declaration which ends the GMF section and starts the Import section. Then the first entity declaration that is not an import declaration begins the Entities section. The preprocessor conditionals are allowed to be used in each of these sections, however they enclose this way “conditional subsections” (contents of a conditional). The limitation here is that a conditional subsection cannot exceed the lifetime of a section. This means that:

  • The declaration module <name>; is explicit; the symbol used here is taken as is, even if it corresponds to a name of an existing macro. This declaration also can’t be inside a preprocessor conditional.
  • The following series of import instructions can be enclosed in conditional section, but then any open conditional section must be closed before the first entity declaration appears (or, in other words, it must be closed before the next section begins)

Declarations in these sections are not interchangeable and they have specific definitions of how they influence rest of the file:

  • The GMF section can contain all possible preprocessor directives, but no entities and no imports. They can include or define explicitly macrodefinitions, which will be then visible in both next sections. GMF is optional; if you don’t need it, you should start the import section as first.
  • The Import section can contain only import declarations. It is allowed to use preprocessor conditionals there, as well as all other preprocessor facilities except #include. Any macros defined in GMF section will be visible here. Any explicitly defined macros will be visible in this and the next section. However macros that are exported into the module interface will not be visible in the import section.
  • The Entities section can contain all entities, but not import instructions and no #include directive. All macros defined in the previous sections and all macros exported into the module interface will be visible here.

1. Use import instruction for getting access to a particular interface

In a usual C++ you could use #include directive anywhere and do any kind of gluing of the source code.

In C++20 – and here the K-Modules use the same rules – you should avoid that and prefer using import for adding a dependency on a module’s interface, as well as also usual header files. If by some reason the file cannot be imported, you can use #include as before, in the GMF section (anywhere else in the file the use of #include is not allowed).

2. Limited use of preprocessor macros in the interface

Macrodefinitions can be exported in K-Modules, but there are limitations – they must be expression-complete, they must be explicitly exported and they cannot be used in the interface (even though they can be re-exported). This means that they can be used in the definition of the class or an inline function, but they will be present in the interface in their expanded form. Macros also do not get automatically reexported, unless requested explicitly in the reexporting interface.

3. One common file for all kinds of entities

In a usual C++ you have a split of the entities into physical (variables and external functions) and ephemeral (type definitions, inline functions); the first should be in the source file, the latter in the header file – at least if they have to be accessible for entities defined in other source files.

In K-Modules they are all in the same file, and it is defined for particular entity type, what part of it constitutes its interface. The equivalent of putting things into a header file is the export modifier, which declares that the part that constitutes the interface will be available for import. Without this the interface remains internal, that is, it’s available for other entities in the same module only – including partitions. To compare it to the previous rules – you just mark as export the parts that should be in the header file, while all others will remain local to the file (note that in the old rules there’s nothing to remind the use of partitions – a “private header” kind of thing could be something of the kind).

The default inline scope for methods defined inside the class remains, and you can still define out-of-line methods outside the class, but you can also additionally define out-of-line methods inside the class by marking them as extern. The same symmetry exists for “free” functions, except that for these the extern scope is default.

What constitutes the interface part of an entity, depends on entity types; details described below.

4. You can’t freely mix body parts of different entities in a single source file

In a usual C++ you are free to distribute the physical entities (or their physical parts) throughout the source files as you please. This includes a possibility to place physical entity parts of entities, defined also in different header files (which would map to different modules in case of K-Modules), in one common source file.

In K-Modules this isn’t possible. A class is assigned to the module, in which it is defined, so all its separately defined parts must be placed also in the same module source – either in the same file, where the class is defined, or in a partition of that module. Simultaneously one source file cannot enclose entity definitions that belong to different modules.

5. Lesser restrictions

If you use K-Modules, the following things are no longer required:

  • You don’t have to keep the order of definitions. For example, you can define the main() function first, and then provide a definition of a function that main() will be calling – you don’t need to provide the header of the function ahead of main(). This is in force in all cases when you have an implementation-on-interface type of dependency (where “implementation” is actually the function body in this case). The same, you can use a class, which’s declaration is provided after the definition of a function using it.
  • Static fields in the classes don’t need any additional definition outside the class. Even if it requires any constructor call, you can do it just as well inside the class. The outside-class declaration is still possible, just not required.
  • Non-inline methods just need to be declared extern and they can be just as well defined inside the class.

Note that this free ordering is in force only if you have an implementation-on-interface type of dependency. If you have an interface-on-interface type of dependency, like e.g. you want to derive another class in your class definition, this another class must be fully defined ahead of this class. The same applies to a function, if it needs to use a locally defined type in the declaration header – this definition must be provided ahead of this inline function. If this function is inline, this additionally applies on its whole body.

Entity parts

The further explanations might make an impression that I’ll be trying to redefine C++ from scratch – but no. These are the definitions that apply to the today C++, and actually they strech up from ANSI C. Even though even this language didn’t explicitly define such a thing as a header file (at least not in case of those used in a project) nor the rules where particular definitions should be placed.

So these definitions follow the current practice used in the “C modules” – “K modules” just try to keep up to these rules as much as possible. The term “entity” is also already used in the C++ standard terminology and it means every single thing that you can define in the language. In every such entity there are three always main parts (some of them being optional of course):

  • INTERFACE PART: This is the part visible for other entities. It may be visible for other entities (and form a dependency of them), depending on the declaration:
    • exported: Visible for the entities from other modules – when marked with export keyword
    • internal: Visible only for the entities in the same module, including its partitions. This is the default.
    • static: Visible only for the entities in the same file – when marked with static keyword or placed in an unnamed namespace.
  • FORWARD INTERFACE PART: This is the part of the type declaring entity that is comprised of only its name. It may be a dependency on other interface part of another module. Not every entity has it, but very specific rules apply to templates.
  • IMPLEMENTATION PART: The part of the entity not visible for other entities, but are accessible through the interface.

These definitions are important for the following perspective:

  1. The interface part can be made available for import by other modules, as well as re-exported, if export import was used.
  2. The forward interface part is always reexported when import is used for the module – unless particular module doesn’t export any interface.
  3. The implementation is only available through the interface and it is isolated. This means that its interface is independent on what the implementation requires, although there are limitations of how the entity that has the implementation part can be defined and used.

With that, the following parts are propertied in various entity types:

Entity typeForward int.InterfaceImplementation
Inline functions or methods(none)The whole definition body(none)
External functions or methods(none)The call signatureThe function’s body
TypesThe type nameThe type definition (methods follow functions’ rules)Characteristic data, if present (e.g. virtual tables, RTTI information).(*)
Global variables and external constantsThe extern declaration if using type’s forward interfaceThe extern declaration if using type’s complete interfaceThe definition, possibly with initialization
Global static constants(none)The complete definition(none)
Type templatesThe template declaration with template parameters, including default assignmentsThe complete type template definition (without default assignments, if forward interface is present)(none)(**)

(*) If the type declaration contains methods, and then the methods are treated as a part of the type, then the method bodies will be effectively treated as an implementation part of that type.

(**) Note that the templates have limitations towards the types. They do not provide anything that a class provides for virtual methods, but these will be provided in the instantiations. Their placement is then where the instantiation is declared. The same applies to functions.

The matter of templates is a bit more complicated than the others. As you saw, templates can have default parameters, but then if you use the forward interface of the template, these default parameters should be in the forward interface, and cannot be simultaneously specified in the type definition. Obviously when using K-Modules you won’t have to worry about this – just define the type template. Important is though that – unlike fixed types – the forward interface of the templates can be dependent on other definitions, such as those that provide the forward interfaces of types, which are used as default, as well as constant values, if they are used there.

Templates have also limitations that result in the linkage system used today, which means that a function template must be always inline, or you can make only a pure interface of that function, while providing explicit instantiations as extern. This is also similar in case of methods of a type template. This limitation might be potentially overcome, if some better linkage system is developed for C++, for example using some virtual machine language with JIT compiling, which could be also called from the shared linkage system.

So, let’s try to present a fragment of the code with appropriately marked parts (and some parts extracted for visibility). This is a fragment of the above code. Here we have the forward interface in blue, interface in green and implementation in red:

Let’s take then some examples. Here is a function:

Full definitionextern int high(int a, int b)
{
return abs(a) + abs(b);
}
Forward interface(none)
Interfaceint high(int a, int b);
Implementationint high(int a, int b)
{
return abs(a) + abs(b);
}

A little bit different is an inline function:

Full definitioninline int high(int a, int b)
{
return abs(a) + abs(b);
}
Forward interface(none)
Interface
int high(int a, int b)
{
return abs(a) + abs(b);
}
Implementation(none)

A simple structure:

Full definitionstruct Color
{
int red, green, blue;
};
Forward interfacestruct Color;
Interfacestruct Color
{
int red, green, blue;
};
Implementation(none)

Things get a little complicated when you have a class with also virtual methods:

Full definitionclass Vehicle
{
int mil = 0;

public:
virtual void run()
{
throw std::runtime_error("no engine");
}

extern int mileage() { return mil; }
};
Forward interfaceclass Vehicle;
Interfaceclass Vehicle
{
int mil = 0;
public:
virtual void run();
int mileage();
};

inline void Vehicle::run()
{
throw std::runtime_error("no engine");
}
Implementationint Vehicle::mileage()
{ return mil; }

[virtual table for Vehicle class]

In case of function templates, you need to note that it looks merely like any other inline function. Function templates have restrictions for the definition purview: they may be only inline or static (including through the unnamed namespace), and extern can only be an explicit instantiation of it. This is mainly the result of the limitations of the compiled binary file format (“object” file), although if this limitation can be overcome by some compiler in the future, it might be possible to implement also other cases.

Type templates are a little bit more complicated. To make it more realistic, I’ll use a fragmented example of a real type here:

Full definitiontemplate<typename _CharT, typename _Traits
= std::char_traits<_CharT>>
class basic_string_view
{
// ...
constexpr void swap(

basic_string_view& __sv) noexcept
{
auto __tmp = *this;
*this = __sv;
__sv = __tmp;
}
// ...
size_t len;
const _CharT* str;
};
Forward interfacetemplate<typename _CharT,
typename _Traits=std::char_traits<_CharT>>
class basic_string_view;
Interfacetemplate<typename _CharT, typename _Traits>
class basic_string_view
{
// ...
constexpr void swap(

basic_string_view& __sv) noexcept;

// ...
size_t len;
const _CharT* str;
};


template<typename _CharT, typename _Traits>
inline constexpr void
basic_string_view<_CharT, _Traits>::swap(
basic_string_view& __sv) noexcept
{
auto __tmp = *this;
*this = __sv;
__sv = __tmp;
}
Implementation(none)

Pay attention here on transformation rules into the C-modules’ equivalents:

  1. In the classes, all methods’ definitions are thrown outside the class definition. This is done so independently whether a method is inline or extern. The difference is only that the inline method is still provided as inline, and so a part of the interface, while extern is then moved to the implementation part.
  2. If a type template has default parameters, these default parameters are present exclusively in the forward interface, while in the interface they are no longer there.
  3. This transformation looks the same way regardless if the entity is exported or not. The difference is that if an entity is exported, its interface is added to the “exported interface”. If not, it’s an “internal interface”.

Note that these three separate parts of the entity are defined for one reason:

Dependencies

Entity declarations contain other entity parts in their declarations. It could be done the following way:

  1. A function (including a type’s method) contains some user-defined type names in their parameters or return type.
  2. A type definition contains fields of user-defined types, or derive a user-defined type.
  3. A template may use default values of user-defined types, variables, constants, or may have parameters typed with user-defined type.
  4. A global variable may be of a user-defined type and the user of the variable may use the value itself, or only take its reference.

So, let’s define the cases of dependencies:

Entity typeForward interface dependenciesInterface dependencies
Function(not available)* calling this function
* getting this function’s pointer
Structured type and its template* pointer or reference to the type
* argument or return type in the function
* any use of that type in a template that resolves to any of the above
* constructing an object of that type
* referring to fields or methods of this type
Dependencies on particular entity types

There’s one more complicated things about the dependency of the functions:

EntityFunction’s interface depsFunction’s implementation deps
Inline function definition* called functions’ interfaces
* types which’s details or values are used in the body
(not available)
External function definition* forward interface of types* called functions’ interfaces
* types which’s details or values are used in the body
Dependencies in inline and external functions

So, in summary:

A. The forward interface of a type is sufficient for:

  1. Using reference or pointer type of that type in:
    • Function parameters and return type
    • Type’s field declarations
    • An instruction inside the function’s body or initialization expression, if it is not dereferenced
  2. Having a function in the current purview, without calling it, which uses this type in return or parameters passed by value. Even if the parameter or return type declares passing by value, the complete type interface is only required for an expression that calls this function.

B. The following things depend on the type’s complete interface:

  1. Declaring variables of this type (also constants)
  2. Dereferencing the pointer or reference to this type
  3. Using the value of this type through the variable or temporary object (also its fields or methods)
  4. Calling a function that returns this type by value or gets arguments of this type by value

C. The following depend on a function’s signature:

  1. Calling this function
  2. Taking this function’s pointer

Note that this is the same for inline and external functions. The only notion of an inline function is that as provided in the interface it can undergo better optimizations as the compiler can adjust its body to the needs of the call (yes, this function can be just as well expanded inline, as also called here directly, as well as the compiler is free to generate a static function in the current unit as a simplified version of the inline function). From the dependent entity there’s no difference. The only advantage of inline is that the compiler can see the body of the function in the unit that is calling it, but the expense is that this function brings in stronger dependencies: if the inline function uses details of the type’s value in the body (just not in the signature), it is dependent on the complete interface of that type, while in case of external function, only the implementation part is dependent on the types complete interface, while the interface part of that function is only dependent on the forward interface of that type.

Now that we have all these rules explained, let’s discuss the difference between the import declaration and the export import declaration as per what dependencies it defines:

  1. If a module is declared import, then:
    • The module’s implementation is dependent on the imported module’s complete interface
    • The module’s interface is dependent on the imported module’s forward interface. This can be optionally declared by export import IMPORTED_MODULE:default, but it should not be necessary.
  2. If a module is declared export import, you make the implementation and the interface of the current module dependent on the imported module’s interface (note that the interface is always dependent on its forward interface).

Module dependency rules here map directly to the dependency rules of the entities’ parts.

For example: if you have module X that provides an external function, which declares some types of the parameters, that are defined in yet another module Y, the module X doesn’t have to re-export the interface of Y, as this isn’t necessary for providing the interface of this function. If the user imports the module X, it gets the interface of this function. But to call this function this is not enough because the call involves operating with the value of that type. So in order to be able to call it, module Y must be also imported. On the other hand, if this function is marked inline, then module X must this time re-export the Y module.

Consider: we have modules A, B and C. C defines a class named Block. B defines a function that creates and returns a block by value. A wants to call this function. We have then:

module C;

export class Block
{
...
};

------------------------------

module B;
import C; //NOTE: re-exports only C's fwd interface

export Block create_block(int channel, int side)
{
  Block b; ...
  ...
  ...
  return b;
}

-------------------------------

module A;
import C;
import B; //NOTE: imports C's fwd interface

export void Read(int channel)
{
    // C's forward interface is not enough,
    // hence you need also B.
    Block b = create_block(channel, SIDE_FRONT);
    ...
}

Ok, what has happened here?

Module B doesn’t have to do export import C because it doesn’t need its declaration in its interface. It provides a function, which returns Block by value. So it does need to have access to the full interface of Block and therefore it imports module C. But then, it doesn’t have to attach it to its own interface – the signature of the create_block function doesn’t need the interface of the Block type. But it is needed by the function Read in the module A and therefore, beside importing module B (which might bring in some other interfaces that don’t need simultaneously the interfaces from A to be usable), it must also import module C. That’s why when you call create_block, you have to import both C and B explicitly. Of course, the creator of module B could declare export import C, just to make things easy, but then it brings in the definition of the Block type that is maybe not required by other users of module B. Also, there could have been a reason, why this function is external because if it was inline, re-exporting C would be necessary anyway.

Note also that the compiler may find the problem quite quickly: Because import B provides the forward interface of C, which contains the declaration of the Block type, the compiler knows which module has provided this type, so it can quickly recognize the situation and hint you that “you should also import module C”. This is quite an advantage over the current situation in C-modules.

So, summing up: a module source file defines entities. Particular of these 3 parts of all entities (interface, forward interface, implementation) comprise also the same kind of parts of a module. In general, possible dependencies are on both forward and complete interface, but all 3 parts can be potentially dependent on them. There are just several special cases:

  1. A forward interface suffices, if the type’s pointer or reference is used, or a type in the external function’s signature. Just as well as a template parameter, if this parameter is used inside the template’s definition only this way. Otherwise you need the complete interface as a dependency.
  2. You need a complete interface wherever you use any details of the type, even if the definition is considered a foreward interface, in either of these situations:
    • A type expression in the typedef definition (also through using)
    • A template with parameters that use default assignments, which use details of that type (like <typename Val, typename Unsigned = std::unsigned_type<Val>::type>)

Note that there’s no dependency on the implementation possible. A dependency on the implementation could be thought of at best as a link-time dependency, in which case we only need that the implementation exists, but no requirements apply to its contents.

Note also that K-Modules allow for something that in case of C++20 modules is considered a circular dependency (and therefore not allowed), when you have something like:

// --- a.kcc
module A;
import B;
...

----------------------------------
// --- b.kcc
module B;
import A;
...

This only seems to be a circular dependency because module A imports module B and vice versa. It’s not, however; this is a cross-dependency: it’s not that A and B depend on each other, it’s that A’s implementation depends on B’s interface and B’s implementation depends on A’s interface. Obviously there’s also a dependency of A’s interface on B’s forward interface and vice-versa, but this is still a dependency on different level, so this is still a cross-dependency.

However, if you have an interface-on-interface kind of dependency, this may only exist in one direction. So, if you have in module A export import B, in the module B you can still have import A, but not export import A.

So, for example, when you have an exported function declaration with a type name with passing by value, which is defined in another module X, and in your module you are calling this function in some inline function, you need to do export import X (because you have interface-on-interface dependency here). Similarly, if you instantiate a type template, where the templated type is used in a declaration of a field (as sunken, that is, not pointer or reference) the instantiation declaration is dependent on the type used as a parameter. This also forms an interface-on-interface dependency.

Partitions

Partitions also exist in the K-modules, but they work slightly differently than in the C++20 modules.

First of all: if you have a module split into partitions, then you have the following files:

  1. The master module of the partition. This file must contain declarations of import for all files that are partitions of this module.
  2. Any number of partition files of this module.

Partitions differ to just dependent modules by three things:

  1. Partitions can be declared imported only by the master module file to which these partitions belong and by other partitions of the same module. Also, in distinction to importing of a module, this imports both internal and exported interface.
  2. Every partition is automatically dependent on the internal master interface of the module.
  3. The interface defined in the master module cannot be dependent on any interface provided in the partition – because the dependency is in the opposite direction already. If you want to split the entities throughout partitions, all base definitions should be defined in the master module.

Partitions are not limited to only implementation – they can also provide their parts of the interface. That’s why the interface of the partitioned module consists of two parts:

  1. The master interface – this is the interface declared in the master module file only.
  2. The integrated interface – this is the master interface with all interface parts provided by partitions

As it was declared earlier, there is an internal and exported interface in a module. In case when you have a module with one partition, where the partition also declares some exports – let’s say M and M:P respectively – you have:

  • The M module, with its “master interface”
  • The M:P partition with its interface

while in both these you have the internal and exported interface parts. Importing is working then the following way:

  • import M – imports the exported interface of the M module and M:P partition.
  • import :P – imports the internal and exported interface of the M:P partition (in the M module or any other partition of module M)
  • import M:P – not allowed
  • export import M – imports and reexports the exported interface part of M and M:P
  • export import :P – imports the internal interface of the M:P partition, and imports-and-reexports the exported interface of the M:P partition
  • module M:P – declares that the current file is a partition :P of module M and it imports internal and exported interface that was declared in the M module source file.

So, let’s say that we have a module named utils.array and some parts are provided by partitions static and dynamic. We have then the master module, which does:

module utils.array;
import (... some other modules ...);
export import :static;
export import :dynamic;

As you can see, we have “export import”, which means that these partitions will provide parts of the interface. If they don’t, you just need “import”.

Now we have for example the “:static” partition:

module utils.array:static;
...

So, whatever interface is defined in the utils.array module sources, this partition is dependent on it. A partition may also import the interface of another partition of the same module, just this time explicitly.

The most important difference in the dependencies of the partitions is that partitions are dependent on the internal interface of the master module (the same applies to the entities defined in the partitions – only if you declare an entity export is that entity part of the module’s interface, but if the entity is not exported, it is still accessible across partitions of the same module). Only if you declare a function as “static” (as well as all kinds of entities that are inside unnamed namespaces) is that entity not a part of even the internal interface and is therefore inaccessible outside the current file.

What exactly are partitions useful for?

  • Private parts of the module that you need to be not exported (including classes), but you also want to have them in a separate file.
  • Single classes that shall be better kept in separate files, but they are closely related and belong to the same category.
  • Implementation of methods that are declared in an exported class in the master module, if you have a large number of them and you want to split them into categories by keeping them in different partition files.

Ordering rules

As I showed it previously, thanks to these new rules, ordering is more loose than in the C++ version with C-Modules. Still, it doesn’t mean that you can declare entities in whichever order. You need to know first in what order the entities are being parsed. In particular, what you saw in the beginning about what parts of the entities there are, you can think of it as “definition depth levels”, which are:

  1. Forward interface
  2. Interface
  3. Implementation

And then you can have actually three types of dependencies:

  1. Upwards. This is the dependency of an interface or implementation on forward interface, or implementation on interface. If you have a dependency of that kind, the dependent entity may be defined in whatever order towards the requester.
  2. Sequential. This is the dependency on the same level, mainly interface-on-interface. If you have that kind of dependency, the order still matters. This means also that if a dependent entity is provided by a module, this module must be reexported in the requester module.
  3. Retrospective. This is the unusual case of a type template that has default type-parameters. This is a kind of dependency of the forward interface on the interface. Like in sequential, the order still matters, and you need to reexport the dependent module, if it provides the interesting type, but then you additionally have a dependency of the forward interface.

That’s why the compiler must perform the tokenization first, but the tokenization database must be stored somewhere for later use because parsing will be done in 3 steps:

  1. Grabbing the forward interface of the entities
  2. Grabbing the complete interface of the entities
  3. Reading the implementation parts

Note also that classes (meaning, types with contents) are also being read in two separate steps:

  1. Grabbing the field declarations and methods only with their signatures (regardless if inline or extern)
  2. Grabbing bodies of the methods

So, when you have a class declaration, in the first step we only get the name of the class and have it in the declared type list. This touches upon all classes declared in this file. This way you can use the name of the class anywhere as incomplete type, as long as it is defined in the same module.

Then in the second step this class is taken its declaration, but method bodies are not yet interpreted, just read as tokens. This way you have the class, you have the field information, and method signatures, so you can access fields and call methods of this class in any other entity declared in the same file, including in the bodies of the inline methods in the classes.

Only one thing in case of classes you are not allowed to do in the reverse order: if you have a type-on-type dependency which requires an interface-on-interface dependency – for example, if you declare a field of this type as sunken (that is, not pointer or reference) or you derive from this type. So, for example, if your class B derives from class A, then class A cannot be defined in the order after the class B. The class B must be defined first because otherwise it’s not even possible to verify the correctness of class A.

On the other hand, you have a completely free ordering in the function bodies, regardless if these are external or inline functions. Just note that inline functions are part of the interface together with their bodies (regardless if exported or not). Therefore you need to regard just as well the ordering in case of free functions that are inline: if you have a B() function that calls A(), and both are inline, A() must be completely defined before the definition of B(). This makes also that cross-recursive calls are not possible if both these functions are inline (which holds true also in the current C++ – as long as you keep up to the rule that inline functions should be defined in header files). Of course, cross-recursive calls are still possible, just both these functions must be extern.

Also, you need to regard that if the inline function is in the interface together with its body, then from there you need to provide also all of its dependencies. This means, for example, that if you have an exported inline function, and in its body there’s called another function, be it even extern, this function must be as well exported. If this function is provided in another module, the module that defines this exported inline function must also re-export this another module. On the other hand, if you have an inline function in the internal interface, it can call both exported and non-exported functions. It’s the internal interface also dependent on the exported interface.

The inline methods of a class are affected exactly the same way. What is important here is that classes will be stored in the header files in the order of their declaration in the source file, and even though all classes will be stored before their inline methods, inline methods of the classes will be also stored in the order of the declaration of their classes. This means, for example, that if you declare class A first and then class B, the methods of class A may refer to fields in class B and they can also call methods of class B, just not inline ones cross-recursively.

In general, ordering is something you shouldn’t worry about in case of sources written with K-Modules, except for the order of type definitions. Just making dependencies circular is just not allowed at all, no matter in what order you try to declare entities.

Let’s try some examples then. The already mentioned short code fragment:

module default;
import std.threads;
import std.functional;
import .mainapp;
 
int main()
{
     start(mainapp::startup);
     return mainapp::loop();
}
 
void start(std::function<void()> fn)
{
    ::mainthr = std::thread(fn);
}
 
std::thread mainthr;

What is read here in the subsequent passes:

  1. Forward interfaces. Here we have only the declaration of the variable mainthr; for this it suffices to have the incomplete type std::thread, so this declaration can be extracted as extern std::thread mainthr that is put into the internal header file (internal because it’s not exported).
  2. Interfaces:
    • int main(); – not dependent on any user-defined entities
    • void start(std::function<void()>); – dependent on the interface of std::function; this one is provided by import std.functional;
    • extern std::thread mainthr; – just derived from the forward interface, this time however requires a complete interface of std::thread so that it can be used – this one is provided by std.threads.
  3. Implementation: The body of main and start functions, where we have:
    • The call to start. This can be done due to extracted signature in step 2.
    • The use of mainapp::startup and mainapp::loop. This is provided by import .mainapp.
    • In the start function we have a use of mainthr variable. This is possible as the interface of this variable was grabbed in step 2.
    • The declaration of the mainthr variable, which provides its physical entity.

Ok, let’s try something competely different, then. As I mentioned already, K-modules could be just as well used in the C language. I found an idea lately to use a special form of header and source in one file. This trick uses the __INCLUDE_LEVEL__ macro provided in gcc to check if this file is currently being included by another source file. Thanks to this you can have everything in one file – so that’s more-less what the modules aim to achieve – but the declarations are still split into the explicit interface section. Let’s show this example file:

#ifndef mtvec_h
#define mtvec_h

#include <stdio.h>
#include <stdint.h>

typedef struct mtvec_t mtvec_t;

struct mtvec_t
{
    void** data;
    uint32_t length;
    uint32_t length_real;
};

mtvec_t* mtvec_alloc(void);
void mtvec_dealloc( void* vector );
void mtvec_reset( mtvec_t* vector );

#endif

#if __INCLUDE_LEVEL__ == 0

mtvec_t* mtvec_alloc( )
{
    mtvec_t* vector = mtmem_calloc( sizeof( mtvec_t ) , mtvec_dealloc );
    vector->data = mtmem_calloc( sizeof( void* ) * 10 , NULL );
    vector->length = 0;
    vector->length_real = 10;
    return vector;
}

void mtvec_dealloc( void* pointer )
{
    mtvec_t* vector = pointer;

    for ( uint32_t index = 0 ; index < vector->length ; index++ ) {
    mtmem_release( vector->data[index] );
    }
    mtmem_release( vector->data );
}

void mtvec_reset( mtvec_t* vector )
{
    for ( uint32_t index = 0 ; index < vector->length ; index++ ) mtmem_release( vector->data[index] );

    vector->length = 0;
}

#endif

So, let’s try to translate this into the K-modules version:

module mtvec;
import <stdio.h>;
import <stdint.h>;
import .mtmem; // NOTE: This wasn't used in the original example, but there are functions used

export typedef struct mtvec_t mtvec_t;

export struct mtvec_t
{
    void** data;
    uint32_t length;
    uint32_t length_real;
};

export mtvec_t* mtvec_alloc( )
{
    mtvec_t* vector = mtmem_calloc( sizeof( mtvec_t ) , mtvec_dealloc );
    vector->data = mtmem_calloc( sizeof( void* ) * 10 , NULL );
    vector->length = 0;
    vector->length_real = 10;
    return vector;
}

export void mtvec_dealloc( void* pointer )
{
    mtvec_t* vector = pointer;

    for ( uint32_t index = 0 ; index < vector->length ; index++ ) {
        mtmem_release( vector->data[index] );
    }
    mtmem_release( vector->data );
}

export void mtvec_reset( mtvec_t* vector )
{
    for ( uint32_t index = 0 ; index < vector->length ; index++ )
       mtmem_release( vector->data[index] );

    vector->length = 0;
}

The author has also tried, as per example, to transform some of the other projects into this “common file form”, but then I think even with this transformation he forgot about the “minimum dependency” principle. Let see into this project, in particular, this file for example. I’ll paste here the ALREADY FIXED form of it as there are includes with too much of a range, which should be changed:

#ifndef mt_channel_h
#define mt_channel_h

#include <stdint.h>

typedef struct mt_channel_t mt_channel_t;
struct mt_channel_t
{
    char*  flags;
    void** boxes;

    uint32_t size;
    uint32_t rpos; // read position
    uint32_t wpos; // write position
};

mt_channel_t* mt_channel_new(uint32_t size);
void          mt_channel_del(void* pointer);
char          mt_channel_send(mt_channel_t* ch, void* data);
void*         mt_channel_recv(mt_channel_t* ch);

#endif

#if __INCLUDE_LEVEL__ == 0
#include "mt_memory.c"
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <time.h>

void mt_channel_del(void* pointer)
{
    assert(pointer != NULL);

    mt_channel_t* ch = pointer;

    REL(ch->flags);
    REL(ch->boxes);
}

void mt_channel_describe(void* p, int level)
{
    mt_channel_t* ch = p;
    printf("mt_channel, size %u read pos %u write pos %u", ch->size, ch->rpos, ch->wpos);
}

void mt_channel_describe_flags(void* p, int level)
{
    printf("mt_channel flags");
}

void mt_channel_describe_boxes(void* p, int level)
{
    printf("mt_channel boxes");
}

mt_channel_t* mt_channel_new(uint32_t size)
{
    mt_channel_t* ch = CAL(sizeof(mt_channel_t), mt_channel_del, mt_channel_describe);

    ch->flags = CAL(sizeof(char) * size, NULL, mt_channel_describe_flags);
    ch->boxes = CAL(sizeof(void*) * size, NULL, mt_channel_describe_boxes);
    ch->size  = size;
    ch->rpos  = 0;
    ch->wpos  = 0;

    return ch;
}

char mt_channel_send(mt_channel_t* ch, void* data)
{
    assert(ch != NULL);
    assert(data != NULL);

    // wait for the box to get empty

    if (ch->flags[ch->wpos] == 0)
    {
	/* swap these rows to cause a race condition and a failing test */
	ch->boxes[ch->wpos] = data; // first store data
	ch->flags[ch->wpos] = 1;    // then set flag, it doesn't have to be atomic, only the last bit counts

	ch->wpos += 1; // increment write index, doesn't have to be atomic, this thread uses it only
	if (ch->wpos == ch->size)
	    ch->wpos = 0;

	return 1;
    }

    return 0;
}

void* mt_channel_recv(mt_channel_t* ch)
{
    assert(ch != NULL);

    if (ch->flags[ch->rpos] == 1)
    {
	void* result = ch->boxes[ch->rpos];

	ch->boxes[ch->rpos] = NULL; // empty box
	ch->flags[ch->rpos] = 0;    // set flag, it doesn't have to be atomic, only the last bit counts

	ch->rpos += 1; // increment read index, it doesn't have to be atomic, this thread uses it only

	if (ch->rpos == ch->size)
	    ch->rpos = 0;

	return result;
    }

    return NULL;
}
#endif

So, in the form of K-modules, it is:

module mt_channel;
export import <stdint.h>;
import .mt_memory;
import <assert.h>;
import <pthread.h>;
import <stdio.h>;
import <time.h>;

export typedef struct mt_channel_t mt_channel_t;
export struct mt_channel_t
{
    char*  flags;
    void** boxes;

    uint32_t size;
    uint32_t rpos; // read position
    uint32_t wpos; // write position
};

export void mt_channel_del(void* pointer)
{
    assert(pointer != NULL);

    mt_channel_t* ch = pointer;

    REL(ch->flags);
    REL(ch->boxes);
}

export mt_channel_t* mt_channel_new(uint32_t size)
{
    mt_channel_t* ch = CAL(sizeof(mt_channel_t), mt_channel_del, mt_channel_describe);

    ch->flags = CAL(sizeof(char) * size, NULL, mt_channel_describe_flags);
    ch->boxes = CAL(sizeof(void*) * size, NULL, mt_channel_describe_boxes);
    ch->size  = size;
    ch->rpos  = 0;
    ch->wpos  = 0;

    return ch;
}

void mt_channel_describe(void* p, int level)
{
    mt_channel_t* ch = p;
    printf("mt_channel, size %u read pos %u write pos %u", ch->size, ch->rpos, ch->wpos);
}

void mt_channel_describe_flags(void* p, int level)
{
    printf("mt_channel flags");
}

void mt_channel_describe_boxes(void* p, int level)
{
    printf("mt_channel boxes");
}

export char mt_channel_send(mt_channel_t* ch, void* data)
{
    assert(ch != NULL);
    assert(data != NULL);

    // wait for the box to get empty

    if (ch->flags[ch->wpos] == 0)
    {
	/* swap these rows to cause a race condition and a failing test */
	ch->boxes[ch->wpos] = data; // first store data
	ch->flags[ch->wpos] = 1;    // then set flag, it doesn't have to be atomic, only the last bit counts

	ch->wpos += 1; // increment write index, doesn't have to be atomic, this thread uses it only
	if (ch->wpos == ch->size)
	    ch->wpos = 0;

	return 1;
    }

    return 0;
}

export void* mt_channel_recv(mt_channel_t* ch)
{
    assert(ch != NULL);

    if (ch->flags[ch->rpos] == 1)
    {
	void* result = ch->boxes[ch->rpos];

	ch->boxes[ch->rpos] = NULL; // empty box
	ch->flags[ch->rpos] = 0;    // set flag, it doesn't have to be atomic, only the last bit counts

	ch->rpos += 1; // increment read index, it doesn't have to be atomic, this thread uses it only

	if (ch->rpos == ch->size)
	    ch->rpos = 0;

	return result;
    }

    return NULL;
}

As you can see here, the compiler must test first what symbols are provided by what header files or modules. So, when you had made above import <stdint.h>, then it would be known that this file provides the symbols for int32_t and so on. When you have this symbol used in the definition of the exported structure, it means that the module interface (or header, in this case) that is providing this symbol must be also exported.

I’ve changed also the order of definitions – the functions named with mt_channel_describe* have been moved below the function that uses them. This is possible, as long as the functions are just defined in the same file.

Libraries

For libraries the module system has some extra definitions. Unlike applications, they need to provide an API so that other application or a library can use it. Like everything else, this is still defined in modules, so exporting an interface for availability of other modules in the same project has to be distinct to the interface that should make the library’s API.

As for the language itself, this needs to use one extra word: public. This is already a keyword and also it won’t be used in the same context as public right now – it must be simply placed together with export. So let’s try some very abstract example:

module hark.utilities;
import std.string;
import std.vector;
import std.map;

using namespace std;

export map<string, string> g_names;

public export void AddName(const string& name) { g_names[name] = "."; }
public export void RemoveName(const string& name) {g_names.erase(name);}

Here we have a module named hark.utilities that will become part of the library. As you can see here, the AddName and RemoveName functions are exported as public, so they will be the part of the library API, while the g_names global variable is exported, so it will be available in other modules of the same library, but not exposed into the API.

When compiling the interface of such file there would have to be created more separate sets:

  • The “public” header, which contains only declarations marked as “public export”.
  • The “export” header, which contains declarations marked as export
  • The “internal” header, which contains non-exported parts

So, now we will have two module interface files for that module, one is hark.utilities-public.cmi and it will be available for other projects by import hark.utilities; there will be available these AddName and RemoveName functions. Then there will be hark.utilities.cmi file that will import the first one and additionally it will provide also access to the g_names variable for other files in the current project, which will import it by import .hark.utilities instruction.

We have two general ways how to deal with libraries:

  1. Keep all in the module files (theoretical for now, at best only for static libraries)
  2. Consolidate the library into a single library file and expose additionally interface files

So as currently only the 2nd method is possible, a special option will have to do the “library linkage”, which will create the following:

  • The library file (either *.a for a static library or *.so for a shared library – appropriate command will be done with extracting all object files from module files)
  • Out of all module files that should be ingredients for this library’s project there are produced files named with the module name with -public.cmi suffix.

The devel library package will then contain all the *-public.cmi files, plus optionally the static library file.

Content and parsing rules

One of the problems is that the source file needs to be not only parsed in passes, but also it can’t be just once passed through the preprocessor. Hence, at least in some regions, the preprocessor must be interpreted together with the language.

The first thing then is to identify three sections:

  1. GMF
  2. IMPORTS
  3. ENTITIES

Important thing is that in every section the rules of how to run the preprocessor are different. Hence the parse must read both the preprocessor directives and the C++ instructions, until the ranges of these sections are determined. Only in the particular section can the preprocessor be used specific way.

First set of rules then, which are verified, and the file is rejected if these rules are not satisfied is that the source of KC++ must start either with module; declaration (for GMF, optionally), or with module <name>; declaration. It is not allowed to encounter any preprocessor directive prior to this declaration, nor can this declaration be somehow preprocessor-conditional. The only syntax elements other than the module declaration preceding it are comments.

By this above rule it is now clear how to embrace the GMF part and then the start of the IMPORT part. Now, the end of IMPORT part should be recognized by having at least one non-import entity declaration. Important thing is though that while reading the imports section, the preprocessor directives must be at least structurally interpreted (not “executed”, of course), so conditionals are allowed there, as well as defining macros, just the conditional statements must be complete within the section. Example:

module encryption;
import std.vector;
import std.algorithm;

#ifdef USING_ENC_OPENSSL
import crypto.openssl;
#elif defined(USING_ENC_MBEDTLS)
import crypto.mbedtls;
#endif
// <--- end of import section

using namespace std;

It is not allowed to mix import sections with anything else, even within the directives. For example, this is not allowed:

module encryption;
import std.vector;
import std.algorithm;

#ifdef USING_ENC_OPENSSL
import crypto.openssl;
using Crypto = CryptoOpenSSL; // <--- ERROR: declaring entity while #if not closed
#elif defined(USING_ENC_MBEDTLS)
import crypto.mbedtls;
using Crypto = CryptoMbedTLS;
#endif

using namespace std;

This has to be resolved this way:

module encryption;
import std.vector;
import std.algorithm;

#ifdef USING_ENC_OPENSSL
import crypto.openssl;
#elif defined(USING_ENC_MBEDTLS)
import crypto.mbedtls;
#endif
// <--- here is the end of import section, as latest import with closing conditional #endif

#ifdef USING_ENC_OPENSSL
using Crypto = CryptoOpenSSL;  // <--- this entity declaration declares end of import
#elif defined(USING_ENC_MBEDTLS)
using Crypto = CryptoMbedTLS;
#endif

using namespace std;

The “separation entity” can be declared inside a conditional, just it cannot be in a common conditional together with some import.

If the source file provides a GMF and it was recognized by having module; declaration in the beginning. If this one is encountered, preprocessor directives are read and checked, and as well the conditional statements must be completely closed before the module <name>; declaration is encountered. Note that in the GMF you might have also included files through preprocessor, and this may potentially contain any incomplete declarations. No matter that, the preprocessor completeness is checked only on the toplevel, that is, instructions provided directly in this section.

After all 3 sections have been rounded and the borders between them defined, they are being now interpreted, separately.

First, the GMF is passed through, if provided, and first there goes the preprocessor. All macrodefinitions provided this way – including those provided by the #include directives indirectly – are visible in the rest of these 2 sections for compiling the sources (so, for example, you can potentially use these macros in conditionals surrounding any import declaration). So, GMF is compiled as itself, the macros are then available, and the resulting set of entity declarations are being compiled into the compiling database for the implementation. Note that GMF can’t take any part of the interface, although you are allowed to export macrodefinitions provided from there. Interface entities (structures or function declarations) are also allowed to be exported, but this must be done explicitly in the source file.

Then the preprocessor is applied to the import section and the complete import list is prepared. The compiler has to check if all files in the import declaration are available – both header files, possibly with their precompiled versions, and the module interface files. This is providing also the database with declarations required for compiling the source.

Now the entities section is being preprocessed, and in this process there are taken into account the preprocessor directives provided by:

  1. Environment (compiler builtin and command-line provided).
  2. GMF declarations, including those provided by the included files.
  3. Macros defined in the import section, if any.
  4. Exported macros by the module interface.
  5. Any further defined macros in the sources.

The result of this preprocessing is the pure source entity set, which is then compiled, with having the declaration databases provided from:

  1. GMF
  2. Imported module interfaces

And this process still proceeds in 3 steps:

  1. Forwarding declarations (incomplete types etc.)
  2. Interface declarations
  3. Implementation

The tokenization goes first and during this process the interpreted meaning of particular token is assigned. The file must be completely walked through for each of these types of declarations. Note that if the first initial phase is to read the tokens and interpret the nature of the entities, it should be easy to walk through all the type declarations in order to read the database of the type names. Only then, during the second pass, are the iterface declarations interpreted – which include type declarations, function signatures (both free functions and methods) and global variable declarations. When compiling the interface part only, this is the end, and the tokenized version of the source should be stored for later use, as it is not required at this moment that all interfaces that this file imports are compiled – only those that are export-imported.

Note that all these three steps need 3 different compiling options because:

  1. The forwarding section of this file is required for compiling INTERFACE of every module that declares this module as import.
  2. The interface section of this file is required for compiling INTERFACE of every module that declares this module as export import, AND is required for compiling IMPLEMENTATION of every module that declares this module as import.

That’s not all. Compiling a forwarding section may also be dependent on an interface of another module, hence it’s not that simple just to compile all forwarders first. You need to have – possibly also in the compiler – some tool that will tell you what dependencies apply to EVERY pass of compiling the module source. The order of commands compiling particular parts must be then determined by these dependencies.

C-module equivalents and generation of C-modules

The implementation of the K-modules can be initially made using code generation, which can be also useful not only initially, but also later for verifying correctness. Let’s start then with the simplest case.

You should have your module source in a single source file. Inside you have entity declarations, which are then tested for their declarations and the following parts are generated into appropriate files, which are:

  1. Private header: This header file is only included by the implementation file. If you have module partitions, all partitions include that header. The idea of the private header is to allow entities to be accessed in a reverse order towards their declaration. Normally if you want to do this in C++, you need to make a “forward declaration” of a function that you want to call in some function defined before that function. Such a kind of “forward declaration” would be then the part of the private header.
  2. Public header: This is the header file that comprises the interface.
    • This is included by every implementation file of the module that declares import with this module.
    • This is included by every header file generated for the module that declares export import with this module.

For a module that contains partitions, the following files are generated beside of these above:

  1. The private header of the master module. This is included by all partitions’ private header files.
  2. The public header of the master module. This includes all partitions’ public header files.
  3. The implementation files of the master module and partitions.

So let’s discuss now what parts of the declared entity are written back to which generated files:

A. Functions

For an external function we have a separate signature and the whole declaration with a body. If a function is exported, this signature is written into the public header, if not – to the private header, and then the whole declaration with the body is written into the implementation file. If the function is marked static or it is defined inside an unnamed namespace, its signature is only stored in the beginning of the implementation file. Note that exporting anything from the unnamed namespace is not allowed, as well as static and export cannot be combined (for free functions only, of course).

Inline functions are also split the declaration off. The declaration, with inline of course, lands in the appropriate interface header file (depending on the export marker), and then the same exactly function with the body lands in the same header file later, after classes’ declaration (see point D).

B. Classes (types with contents in general)

The class is taken as a whole first, and the contents is only checked for methods. All methods of the class are being transformed into the external definition, and in this class declaration only the signature remains. If a method is marked as extern, this part is put into the implementation file, if not (if it’s inline, also by default), this method is put into the same place as the class declaration, just following all class declarations, with inline modifier. Like with the function, the class transformed this way (and later also all its inline methods) will be written into the right place depending on its exporting declaration:

  • exported class: to the public header
  • non-exported class: to the private header
  • unnamed namespace: to the beginning of the implementation file

C. Macrodefinitions

Yes, in K-Modules you can also export macrodefinitions:

#export VALUE 20  // instead of #define
#export (VALUE, STATE) // export an already defined macro

There are limitations, though: a macro to be exported must be entity-complete, that is, it can be a single value or a block of code, or even a single instruction without a semicolon at the end, or a function signature. It cannot be, however, any set of characters that cannot be fully parsed and cannot contain any unpaired bracket-like characters. Simply it cannot be something that would destroy the current parsing process if appropriate macros are not used in pairs.

All macrodefinitions are placed in headers. Exported macros are placed simply in the public header, while all others land in the private header.

D. Putting things together

Note the order of the entities into which the entities declared in the K-Modules-C++ will be stored:

  1. Incomplete declarations (“forward interface”) of all classes declared there. This includes also all typedefs. This typically goes to the forwarder header file and it’s then included by the interface header file.
  2. Macrodefinitions
  3. Signatures of all free functions (also inline – this is required for a case when a default parameter of a function in a class declaration contains the function name to be taken by pointer-to-function).
  4. Type declarations – which, if contain methods, contain these declarations without bodies. They are stored in the order of declaration in the original file.
  5. Inline methods of the classes.
  6. Inline free functions.

Note that this makes also the order regarding the export declarations. This is because the export declaration makes the entity land in a different file than the non-exported declaration. This means, for example, that the inline methods of an exported class cannot call inline methods of a non-exported class. This isn’t an insolvable problem, just the calling method cannot be inline. If extern, it will then land in the implementation file, and this one will have access to all public and private interfaces of everything declared there.

So, let’s try to see how such a transformation would look like with the file that is already presented in the previous article (slightly fixed):

module messenger;
 
import <QUdpSocket>;
import <QAudio>;
import <QAudioInput>;
import <QAudioOutput>;
import <QDebug>;
export import <QObject>;
export import <QString>;
export import .buffer;
export import .voiceio;
export import .voicesocket;
 
export class Messenger : public QObject
{
    Q_OBJECT;
public:
    extern explicit Messenger(QString address, QObject *parent = 0)
        : QObject(parent)
    {
        quint16 buffersize = 0;
        buf1 = new Buffer(buffersize);
        buf2 = new Buffer(buffersize);

        vso = new VoiceSocket();
        vio = new VoiceIO();

        connectAddress(address, 30011);

        vso->setEnabled(true);
        vso->startListen();

        // Voice in
        connect(vio,  SIGNAL(readVoice(QByteArray)), buf1, SLOT(input(QByteArray)));
        connect(buf1, SIGNAL(output(QByteArray)),    vso,  SLOT(writeData(QByteArray)));

        // Voice out
        connect(vso,  SIGNAL(readData(QByteArray)),  buf2, SLOT(input(QByteArray)));
        connect(buf2, SIGNAL(output(QByteArray)), vio, SLOT(writeVoice(QByteArray)));
    }

    void connectAddress(const QString& address, unsigned short port)
    {
        if(address != "")
        {
            vso->connectToHost(QHostAddress(address), port); // QHostAddress::LocalHost
            qDebug() << "Connecting to " << address;
        }
        else
        {
            qDebug() << "No peer address specified. Will only play sound from others";
        }
    }

private:
    // Voice
    VoiceIO* vio;
    VoiceSocket* vso;
    Buffer* buf1;
    Buffer* buf2;
};

Ok, so let’s say, we have this file named messenger.cck and out of it we have generated the following files:

  • messenger.cck.export.h
  • messenger.cck.private.h
  • messenger.cck.forward.h
  • messenger.cck.cc

Here messenger.cck.private.h will be empty – all this file declares is one top-level entity that is exported. It is however dependent on the public part, so it will contain just:

#include "messenger.cck.export.h"

So this will land in the messenger.cck.export.h file:

#ifndef CCK_INC_MESSENGER_CCK_PUBLIC_H
#define CCK_INC_MESSENGER_CCK_PUBLIC_H

#include <QObject>
#include <QString>

#include "buffer.cck.public.h"
#include "voiceio.cck.public.h"
#include "voicesocket.cck.public.h"

// CCK: FUNCTION SIGNATURES

// CCK: TYPE DEFINITIONS
class Messenger : public QObject
{
    Q_OBJECT;
public:
    explicit Messenger(QString address, QObject *parent = 0);

    void connectAddress(const QString& address, unsigned short port):

private:
    // Voice
    VoiceIO* vio;
    VoiceSocket* vso;
    Buffer* buf1;
    Buffer* buf2;
};

// CCK: INLINE CLASS METHODS
inline void Messenger::connectAddress(const QString& uaddress, unsigned short port)
{
    if(address != "")
    {
        vso->connectToHost(QHostAddress(address), port); // QHostAddress::LocalHost
        qDebug() << "Connecting to " << address;
    }
    else
    {
        qDebug() << "No peer address specified. Will only play sound from others";
    }
}

// CCK: INLINE FUNCTIONS


#endif

The remaining messenger.cck.forward.h will contain just:

class Messenger;

Note that the inline method has been extracted from the class anyway, even if it is placed still in the same file. This is because all class definitions should go one after another first, and only then there are inline methods from all the classes previously declared. This way you can refer to any of these classes in an inline method of another class, regardless of the order of definition.

And finally we have the implementation file, messenger.cck.cc.

#include <QAudio>
#include <QAudioInput>
#include <QAudioOutput>
#include <QDebug>

#include "messenger.cck.private.h"

Messenger::Messenger(QString address, QObject *parent = 0)
    : QObject(parent)
{
    quint16 buffersize = 0;
    buf1 = new Buffer(buffersize);
    buf2 = new Buffer(buffersize);

    vso = new VoiceSocket();
    vio = new VoiceIO();

    connectAddress(address, 30011);

    vso->setEnabled(true);
    vso->startListen();

    // Voice in
    connect(vio,  SIGNAL(readVoice(QByteArray)), buf1, SLOT(input(QByteArray)));
    connect(buf1, SIGNAL(output(QByteArray)),    vso,  SLOT(writeData(QByteArray)));

    // Voice out
    connect(vso,  SIGNAL(readData(QByteArray)),  buf2, SLOT(input(QByteArray)));
    connect(buf2, SIGNAL(output(QByteArray)), vio, SLOT(writeVoice(QByteArray)));
}

Of course, that’s not all. We could have then the following commands required to compile all ingredients:

# Compile interfaces
kc++ -kmi voiceio.cck
kc++ -kmi voicesocket.cck
kc++ -kmi messenger.cck

# Result: we have appropriate *.cck.public.h files and manifest files
# required to compile these next ones:

# Compile modules
kc++ -kmc voiceio.cck
kc++ -kmc voicesocket.cck
kc++ -kmc messenger.cck  # includes voiceio.cck.public.h etc.

# These resolve to:
# >>> Source file generation -> messenger.cck.cc
# >>> g++ messenger.cck.cc -o messenger.cck.o ...

# Compile main module
kc++ -kma main.cck -o volan

# This resolves to:
# >>> Source file generation -> main.cck.cc, and the manifest file
# >>> g++ main.cck.cc -o main.cck.o
#  --- information about all other modules to be linked together extracted from manifest
# >>> g++ -o volan main.cck.o voiceio.cck.o voicesocket.cck.o messenger.cck.o

Note also that “compiling modules” consists of multiple commands that modify the same “entity”, which is the compiled module itself, so we should have then, for example, for the messenger module:

  • messenger.cm.d (directory), containing:
    • messenger.cm.mf (the manifest file)
    • messenger.cck.export.h (exported declarations)
    • messenger.cck.private.h (non-exported declarations)
    • messenger.cck.forward.h (forward part of the exported declarations)
    • messenger.cck.export.h.pch (precompiled header)
    • messenger.cck.o (compiled source)

As this is a part of the application, I didn’t mention messenger.cck.public.h and its precompiled counterpart – this would be there in case of a library. This will be later used to create the public API interface file that would be named messenger-public.cmi, which will be an archive file containing messenger.cck.public.h (plus *.pch) and the manifest file describing these two.

Every command needs to create the directory if needed, as well as the manifest file. The manifest file is created once in the beginning and needs no modifications. It should contain all the dependency information and the files that should be there with their properties, even if they don’t exist yet (will be created by next commands). So, the first thing to read from the *.cck source file is to get the dependency information and read the hash value from the *.cck source file (this is needed to make sure that the file wasn’t altered since the previous command). Then, if the directory already exists, the manifest file is read and check if recent; if it is, it’s left as is, otherwise it’s recreated and the directory contents are deleted, then all things have to start afresh.

So, there would be the following working mode, each one dependent on the previous one:

  • -kmdeploy: create the directory and manifest file – doesn’t have to be explicitly used
  • -kmi: create the interfaces – exported, internal and forward; also precompile them (depends on -kmdeploy, as well as on interfaces of all export-imported modules)
  • -kmc: create the implementation: generate the implementation file and compile it (depends on -kmi, as well as on interfaces of all imported modules)
  • -kma: create the application out of a module: get the module with main() function and all dependent modules and link them together to create the executable file. If used with -shared, it will create a shared library and the main() function shall not be present
  • -kml: create a library out of a module. Whether it’s static or shared, it should be followed by either of -static or -shared option. The set of all modules belonging to the project should be passed to compiling, but you can also do something to make it all-depends collector file that would have the .all suffix, in which case you need only this module to be specified.

Note that it wasn’t explicitly defined in what situation the “forward” header file is used. Forward header is included in every public header of the module, which declares import .messenger. So, if there is, say, a module named mg that declares it, the mg.cck.export.h file will contain #include "messenger.cck.forward.h" instruction, while #include "messenger.cck.export.h" will be placed in the mg.cck.cc file.

Summary

I personally think this whole system should make C++ code more concise and help with all struggles with manually preparing header files, synchronizing and reordering, while simultaneously doesn’t make C++ more complicated, as well as it retains all the features that C-Modules had so far.

Posted in Uncategorized | Leave a comment

Deceived by benchmarks

Simulated measurements and all that stuff – it’s useful, just like various different measurements in the software development. Just on one condition: as long as you don’t treat them all too seriously.

That’s something I’ve always said about quality measurements in the software development: the idea behind them was to give programmers a hint, as to what’s wrong or what’s worth paying closer attention for. It shows a point for improvement – but it should be still up to the developer whether and how they will use this knowledge.

The use of them has been widely misunderstood first of all by managers, who were often deciding to use them as a “lash” for “unruly” programmers, causing this way more harm than good. But many programmers happened to fall into this kind of trap, too, by taking various measurements without reflection.

This happened usually with performance profiling – I’ve often seen people saying things like: if you can’t see a proof in the profiler, do not waste time to optimize. Performance profiling can be valuable, but only if you have something clearly heavier than other parts. If you have “some fat to trim out here and there”, profiling is useless – you can either optimize everything (possibly with the help of static code analysis tools) or live with it. And also miracles don’t happen – a linear complexity algorithm will always be slower than a constant complexity (even if amortized), we can at best quarrel how much of a difference it makes for the whole solution.

Since in the end you’ll still have to perform the measurement of the overall solution in the real conditions, connected with trial fixes in the various most basic (that is, the code on which the whole solution depends) parts of the solution. This simply gives you the only real data. I’ve learned this lately quite a hard way.

Case study: implementation of the logging system

I’ve created once a logging system, for the SRT project. This library works in a “live mode”, so a logging system is actually the only way to trace the execution without interfering significantly with its time-dependent activities (as the debugger usually does). Of course there were various different such systems available in foreign libraries, but rarely any has satisfied all of these requirements:

  • Using Functional Area specification (ability to selectively switch off whole group of logs)
  • Using multiple (only 5 actually) severity levels with configurable maximum
  • Short and comfortable call form, involving the severity level and FA
  • Sequential arguments (like in cout << x)
  • Displays the name or ID of the thread in which the instruction was executed
  • Usable in a library (can coexist with the same system used in another library with the same application without conflicts)

All found solutions in the OS world not only required C++11, but they mostly could not be fit in a library (was using global variables), and argument specification was using some “dead horse” printf-like formatting, or some improved version of it. I’ve said enough about that, so let’s skip the explanation.

So I created this system as per a need, I’ve reused operator << and internally redirected the argument to std::stringstream objects for completing the formatted printable line (so, iomanip objects could be also used – except, of course, non-forwardable ones, like endl), and then also ensured the EOL character always at the end, by sending it from the destructor of a proxy object (cases when conditional fragments are necessary could use a separate std::stringstream buffer). So far so good.

Fixing the unsuitable

I have seen the iostream formatting always superior to printf by many reasons – although let’s even say that at this time it was just my personal preference. But the iostream formatting has one thing stupidly designed: the default formatting was a good thing, but any non-default formatting is done through manipulators, changing a particular configuration item. The concepts were changing how it should work, and in the end the rules were that mostly the manipulators change them forever, but some items get restored after printing a value – for example, the width parameter gets reset to 0 after printing a value by any standard overload of operator <<. Other items stay with the set values until explicitly changed.

For example then, something that printf does:

printf("%d-%02x-%d", a, x, b);

in the C++ iostream version, you have to do this way:

cout << a << "-" << hex << setw(2) << setfill('0') << x << dec << "-" << b;

So, theoretically after printing x you have to reverse all flags to their defaults. But dec was the only necessary here because width gets reset to 0 after printing x, and with that value the fill character doesn’t matter. Still, this is far from being clear and precise formatting definition.

Therefore in one of the side projects I got an idea: the on-demand tagged formatting. The idea relies on calling a function, which applies any non-default formatting only for a single value and the overall formatting configuration remains intact:

cout << a << "-" << fmt(x, hex, setw(2), setfill('0')) << "-" << b;

The name had to be short and handy, so I named it simply fmt. There are many ways how you can implement it, the simplest one is just using the std::ostringstream object internally and returning std::string at the end. Other solutions I tried were to do save-and-restore so that simultaneously manipulators can be still used, but this one was finally proven to have the worst performance of all. The most refined version I’ve created was that the operator << overloaded for the proxy class, embedding the std::stringstream and then sending the buffer’s rdbuf() to do buffer-to-buffer direct copy.

This was necessary for making the solution at least implementable using different backends (or at least with negligible enough differences so that a simple search-replace can be used). Simply put, the code like this:

LOGC(glog.Debug, log << "Confidence: " << iconf << ", code: 0x"
     << hex << setw(2) << setfill('0') << code);

would have to be replaced by:

LOGC(glog.Debug, log << "Confidence: " << iconf << ", code: 0x"
     << fmt(code, hex, setw(2), setfill('0')));

This kind of API wouldn’t be exactly flexible (for a drop-in replacement), but at least the call to fmt itself and the formatting arguments could be later easily replaced by something else if needed.

Later on I have replaced it with a version that could be used in C++03, didn’t pollute the global namespace, and made the formatting configuration possible to be saved and used through a shortcut. So this above instruction would be:

LOGC(glog.Debug, log << "Confidence: " << iconf << ", code: 0x"
     << fmt(code, fmtc().hex().width(2).fillzero()));

A second important change that improved this solution was to create a separate class as a replacement for std::ostringstream, which was using the overloads for operator << that exempted all known string-like types from formatting – those were simply copied directly to the stream, like binary data. That aimed at performance improvement, as strings were simply the majority of data items to be printed, while the default formatting for a string is to “print it as is”, and non-default formatting would be provided by the fmt() call anyway.

The alternative solutions for logging systems

One of the found solutions in the opensource world, as I mentioned earlier, was a library called spdlog that employed for formatting the {fmt} library. It came with good recommendations.

The {fmt} library was a base solution for what was later added to C++20. That was one of the most disappointing decision of the C++ standard committee by two facts:

  • The formatting setup was a sealed part of the solution. You could either use it under the dictatorship of the provided API, or not use it at all.
  • The function, which was doing the same thing as printf has been named print. Note that this f in printf was there for a reason – it wasn’t just printing, it was printing with formatting. It also contradicts many uses of this name in other languages (also historic), where print is a function that accepts sequential arguments and doesn’t use any “formatting string”, e.g:
    • In BASIC (formatting, if needed, could be done by separate functions)
    • In FORTRAN – although it does use format specifier, but it works differently than printf (there’s no tagged string possible), and it features also the “free format” specification, which looks almost the same as the one in BASIC.
    • In Perl (although interpolation is also possible). There exists also a function for string-formatted printing, and it’s called… printf.
    • In Python. The “formatting” functionality does exist, using a similar syntax as {fmt} (allegedly being an “inspiration” for it), but is done through the String.format method exposed also as % operator

That {fmt} library wouldn’t be then anything to pay attention at (another dead horse in the new tatters), but then I was hinted that this library offers immense performance in comparison to even sprintf, and it also beats the standard C++ iostream by even an order of magnitude – and there are available also benchmarks for this as a proof!

Well, then, if this performance is so good, then maybe let’s use it? Not directly of course, I didn’t even think of employing this idiotic format string thingies. But to implement even this, it had to use already some formatting facilities and configuration structures – so adding the on-demand tagged formatting to it should be doable.

I’ve started then taking a look at the {fmt} library. But there were some more problems.

The compatibility burden

I didn’t have yet that version for C++03, and {fmt} was requiring C++11, hence I could use these solutions for testing, but something had to be decided in the future, and some solution that already can be supported for C++03 was required. But then, from the benchmarks provided for {fmt} I learned that even the sprintf-based solution seems to already have a better performance than iostream. So I decided to try with some snprintf wrapper.

The {fmt} library contained also some utilities I could use as inspiration – the lightweight buffer that could be used to carry out the formatted values. So I created a simplified verion out of it, and then employed snprintf to do the formatting – this way I have created the sfmt solution. This function could take one or two arguments, and at first, it took the value and the string for formatting. I created also that wrapper formatter class, as mentioned above – to bypass formatting for strings and pass all others through default formatting.

This way the above instruction would look like this:

LOGC(glog.Debug, log << "Confidence: " << iconf << ", code: 0x" << sfmt(code, "02x"));

It didn’t support this way the runtime width and precision parameters, hence I added a second possibility through a temporary configuration class – e.g. instead of "02x" you can specify it as sfmc().fillzero().width(2).hex() (similar as the mentioned fmtc() above).

Forking the {fmt} library

So, I wanted to use this fmt function solution also with the formatting configuration facilities provided by the {fmt} library. But it was impossible without reaching out into the guts of this library, not exposed in the API – so forking was the only solution. I tried first to keep myself away from this, as I knew the dangers – I haven’t written the code, I might be using it incorrectly, especially that the solution I needed could not be done using the public API – I had to screw in my parts at best at the places where I could access the formatting facility directly, bypassing the parsing and interpreting that stupid format string specification. Fighting the high level of C++ wizardry, which I have been mastering for years, this time also wasn’t easy (the level of that has scared even me). But still, I have successfully created a solution.

There came then the problem with naming:

  1. The fmt name was already used as a namespace there, and due to weird solution for naming in the namespace feature in C++, you can’t reuse the namespace name as a local name, no matter how deep in another namespace. So I simply doubled the f and made it ffmt.
  2. I needed also a function that could replace the series of cout << x << y << z and the best name for it was print. But, as you know, it was already taken. So I decided to reuse this ff and named it ffprint.

So I followed for other use cases and there came similarly the ffwrite function that was writing the text into a character container, and ffcat that finally returns the whole text as std::string. This was then added as an on-demand tagged formatting API in my fork of {fmt}.

Benchmarking

I decided to use the existing benchmarks for {fmt} to measure all these solutions to check how useful they are – for all 3 candidates for implementing the logging system:

  1. The on-demanded tagged API created on top of the {fmt} library
  2. The fmt function using buffer-to-buffer copy
  3. The sfmt solution based on snprintf call

What was the benchmark about? Well, actually it has accumulated about a thousand calls to a single function to print the integer value as hex, for a list of various different integer values. The measurement of speed was simply how much time it takes to format them all.

In the original benchmarks, the solution using std::stringstream was shown as the slowest. The solution based on {fmt} was shown always the fastest. I added then the solution using sfmt and it was still slower than {fmt}, but already faster than the standard std::stringstream.

I have also added then the on-demand tagged API versions for both buffer-to-buffer copy and the one for {fmt} using the ffmto function (format the value and copy to the output buffer, similar to ffcat, but it copies instead of returning). The results were similar: the iostream-based version was still the slowest and the version for {fmt} was slightly slower than the original {fmt}, but the difference was negligible. In summary, this was the order from the fastest to slowest according to the benchmarks:

  1. Original {fmt}
  2. On-demand tagged API added to {fmt}
  3. Direct snprintf
  4. On-demand tagged API on top of snprintf
  5. On-demand tagged API using buffer-to-buffer copy of std::stringstream
  6. The direct use of std::stringstream

Putting solution into work

In the end then, I have prepared appropriately modified versions of the SRT project, which was using different solutions for the logging system; out of these above it was:

  1. ODT API for {fmt}
  2. ODT API with snprintf
  3. ODT API with double-layered std::stringstream
  4. Original API using direct std::stringstream.

The first one was the changed version of {fmt}, that is, using ffwrite function for completing the single log line and ffmt for specific formatting. The last one was the original logging system without ODT API.

Having this done, I decided that I can just compile it together with the whole SRT project using this logging system, run a trial session of the SRT testing application, and see how much of CPU it consumes in every version.

The results? Shocking.

The real performance

So, finally I had 4 different solutions to compare:

  1. Original: the original code using directly formatted std::ostringstream with manipulators if needed (not using the fmt function).
  2. LIBFMT: the {fmt} library with on-demand tagged API. For that the extra operator << was sending the fmt::memory_buffer type object to the stream directly (using ostream::write).
  3. SFMT: a homecooked solution using the on-demand tagged API implemented on top of snprintf.
  4. Fmt function: a simple fmt function that was formatting a value using internal std::stringstream and passing the result to the upper std::stringstream.

Now, what was the CPU usage?

  1. Original: 25-30%
  2. LIBFMT: 33-38%
  3. SFMT: 30-35%
  4. Fmt function: 27-31%

Actually the difference between 1 and 4 was negligible, but then all other solutions are obviously not acceptable. But worst of all, the {fmt}-based solution, for which I have put so much of a hope, was looking good only in the benchmarks.

Hard to say, what the reason was of such a difference. Might be that the benchmarks were measuring how fast the numbers can be formatted, not how much CPU the solution will have to consume. But this simply means that a time measurement, even if it measures the speed (number of operations per second), it involves some hidden factors, such as time spent in sleeping. This is an important thing for a live solution actually because the true speed is determined by the switching abilities of the platform, while in order to synchronize the speed with some other parts there’s often done things like in-thread sleeping, waiting on a CV, switching threads determined by occasional mutex locking, and this speed is usually enough for the task. However the CPU usage is the real measurement because the speed of the logging system will always be good enough as long as CPU usage remains relatively low.

Misheap

What is exactly the problem with benchmarks? Well, it doesn’t exactly measure what we need, especially if we are talking about live solutions and processes in a real time system.

Because in a usual solution we don’t need that it run operations “as fast as possible” or that it perform “as many operations per second as possible”. What we simply need is that with a particular type of configuration, it simply can always perform the minimum set of operations in a given time. If it can already perform potentially 10 times more of these operation in the same timeslice, that’s good enough; we don’t care if it can also perform 100 or 1000 times more operations because we simply won’t be performing them. We do need though that this solution use as little CPU as possible, while doing exactly the same number of operations in every example solution. Simply because with CPU less busy we can potentially do more things on this machine at the same time, or with the increased required number of operations per second, we have further the limit for them ahead of us. What is even more important, with less CPU usage, the live or realtime requirements can be fulfilled more accurate way – thread switching may happen more regularly and the operations required to be timely executed may suffer less unexpected delays.

It is still unclear for me, why a solution that can perform more operations per second, if performed linearly one after another, can consume actually more CPU. I could speculate that it might have something to do with the today processor architecture, which focuses more on increasing the number of processing units, to allow for more parallelism, rather than increasing the speed of a single thread of execution – and the software, including libraries, operating system, and also applications, follow these manners. This also seems to be the exact requirement for today software and expectations of how it should fulfill its tasks. And this will unlikely end, we should rather expect diving deeper into it, and the software must have accurate performance in these exactly conditions.

Posted in Uncategorized | Leave a comment

Binary library packages using C++ modules

0. Introduction

As I wrote previously about C++ modules, I have found out that the Standard Committee has likely completely ignored the today practice of software development when designing the C++ modules, just like before with “export templates”: C++ cannot exist without the environment allowing to turn the language statements into the executable code. And that the only one used today is clumsy and prone to ABI compatibility problems.

As you know, the first C++ compiler has been created as a translator to C, which then was compiled using the C compiler, as it was easiest to do. Later compilers have been translating C++ directly, but they were still producing the same output as the C compiler: an object file containing variables and functions. Distribution of libraries was also done the same way: whatever can be aligned to a variable or function was put into the library, and everything else was provided by header files.

It wasn’t the best system even for C language, but in case of C++ it caused much more problems. Some things had to be emulated, some generated special way, even new features were required in the linker, like “strong linkage” support (C language uses vague linkage only). But the most important problem was when the shared libraries were introduced, suddenly language entities have been split into “static” and “dynamic” part, which not only isn’t defined in the language, but no development tools are even capable of checking the resulting ABI incompatibilities (it’s possible only through special tools that maintain access to multiple versions of the source code that should guard the compatibility version line).

God knows that C++ needs the new modularization system, and urgently. But this requires to create at least some new standard for linkage, libraries, distribution, and – what is most problematic for C++ – the compiler-independent (although no problem with platform-dependent) format for the interface.

1. The present situation

The software distribution and dependencies were done with the only modularization system available, that is, the one created for C language, which relies on the following rules:

  1. There is a library file that contains two types of entities, mapped to a named symbol:
    • A variable (saved space of particular size, possibly with some initial contents)
    • A function (executable code fragment)
  2. As an interface part, there’s distributed a header file containing language-defined entities, which should include symbols that should be mapped to entities found in the library
  3. The compiling part uses language entities provided by the header file, which may leave named references to other symbols to be provided “elsewhere” (that is, by a library file)
  4. Once the single parts are compiled, the linker should create the target by providing entities from the library to the object files that refer to them by name.

There are also several different forms in which the target can be provided:

  1. An archive with objects with assigned symbolic names, which may also contain references to symbols not provided in this archive (aka “static library”)
  2. A self-executable file with entities assigned to symbols, which can be used in two forms:
    • as an executable file, if it provides the main execution entry
    • a shared library otherwise

All of these forms can contain linkage entities – variables or functions – which may contain references to other variables or functions that have to be found possibly in other libraries used for linkage. The linkage can be done as a part of the build process, in order to resolve entities already there, or done by the OS-provided tools when running the executable file.

2. Problems before C++

As I said, this is also not the best modularization system for the C language – just in case of the C language it wasn’t seen as a problem. There were actually two reasons for it: the things provided in the header files were minor and little influential to the overall build process, and second was, well, that the C language programmers are – as my experience shows – used to just live with problems, or dodge them by using adhesive tape, instead of solving them.

The C language exists since 1978 year and many problems were identified already in the beginning of 1980, and lots of them have still not been solved (see the Wikipedia page for C23 to see what kind of problems they solved “after all these years”, and see that there’s still no function that returns true when two strings are equal). No different is the linkage and modularization system. C++ has been provided with lots of resolution for many problems (although not that new features didn’t bring in new problems). But it’s still improving. I hope that making you aware of how many problems haven’t been solved for such a long time, and that they still do apply to C++ just because it uses the same modularization system, can convince you how urgently the new and improved modularization system is needed for C++. Even the C language might benefit from it.

For starters then: there do exist entity types in the C language that can be used in the sources, influence the result of compiling, but cannot be provided anyhow in the library files:

  1. Preprocessor macros
  2. Global constants (as compile-time constants – that is, for example, which defines a global array size)
  3. Structures
  4. Inline functions

Let’s say that the preprocessor is kind of another story. The macro defined as #define ESIZE 64 and defined as #define END } are treated the same way by the language, both are allowed and both can be placed in the header file and this way be shared between the compiled source files. Provided in the first place the global compile-time constants and inline functions by C++ have given an opportunity to take this out of the preprocessor and hence increase a chance to provide them anywhere else than header files – but this didn’t happen so far. But then, as inline functions were added to C as well – although I’m not sure if it changed anything except the hint for inlining because C still uses only the vague linkage mode – this could be also done without the use of preprocessor.

As libraries feature only variables and functions, they never are complete. That itself wasn’t a problem, until the shared libraries came to life. For static linkage there’s no difference which parts are in the libraries and which have to be completed by information provided in the header – in result everything was in one place. With shared libraries things got different: entities provided in the header became a “static part”, and those in the library – “dynamic part”. The difference was that:

  1. The “static part” are things that are taken by the compiler when compiling a single object file and things provided by it are “encoded inside” (“hardcoded” I would say). The header file only allows them all to be encoded the same way (although the compiler is incapable of checking if you have provided entities tied to particular symbols using the same header file – not even mentioning compiling with different environment of macros, compiler options etc.).
  2. The “dynamic part” are things contained in the libraries – variables and functions – that are linked to the requiring executable file when it is being executed. This happens at a completely different time than building the requiring target file and it is not guaranteed to access always the same library file (which is also an advantage known as “separated upgrade”).

A short example: If you have a function defined in the source file, and the header provides only its signature, it’s dynamic. The same function provided in the header file with inline modifier is static. A class definition provided in the public header of the library is completely static. Every method defined inside it is static. Unless you only announce the method so that it is defined in the source file separately, and this way it’s dynamic. Do you have any language marker as a modifier to mark these things? Of course not. The language and the compiler are not even aware of these things. But they do exist and every programmer must be aware of it. That’s why the “pimple” pattern is so popular. Not only because it speeds up compiling during development. Also because you can freely change whatever you want in the “implementation” class – add or delete fields, change them, add or modify methods inside, whatever. Only one thing you can’t change: the existing methods in the “interface class”, which is the only visible class in the public header file. As the implementation class isn’t provided in the public header file, it’s the dynamic part of the library. Of course, the “pimple” pattern causes then problems with the basic feature of OO programming: derivation. But without this, classes are prone to ABI compatibility problems.

Imagine that you have a library that provides a structure in the header file. Your application is using this header and this structure, as the library provides a function that fills in the fields of this structure. You call this function in your application. The library is shared and it links to your application during execution time. Now you get the new version of the library and you install this in your system. You run your application and it crashes. Why? Because the developer of the library has added two extra fields in the structure in this new version. The function that fills this in is referring to these fields. But your object is the old version of the structure from before the upgrade, so your object is smaller and the fields that this function tries to fill in refer to a memory already outside of this object (note that what really happens here is memory override and a crash is only one of the possibilities here).

How do you think, how easy it is to make such a problem? It looks extremely easy. It doesn’t happen so often only because today developers are well aware of it. There are also already tools that allow to verify problems like this – just like there are lint tools, code style tools, coverage, and all that. But there’s nothing defined on the language level and nothing that the compiler can make you aware of.

But the fact that problems are not trivial to avoid is only one side of the story. The other is: imagine that this structure is somehow added to the library. There are known fields – even if not their types as such, then at least their size and hence the offset, as well as the size of the structure. And when fields are referred to, there aren’t just assembly code commands with appropriate immediate mode offset to refer to the particular field, but – just like with variables and functions – there’s a reference to appropriate name symbol in the library. This way, if your application allocates the object of this structure, it allocates the size as specified by the library, uses fields’ offsets as specified in the library using constant values provided in the library information. It doesn’t mean that all ABI compatibility problems disappear, but at least they are easier to track. There still are rules for it, but they are way lighter and easier to avoid: in this case all you are not allowed to do is to remove fields, or change the type of existing fields, but you can still add new ones or reorder existing ones. And the worst thing that can happen if you violate this rule is that you have a runtime linkage error because your application refers to a nonexistent field. It doesn’t compare to a problem of memory override that would be caused by this situation today.

3. Adjustment to C++

There are things that the standard committee gives no damn of, and then they had to be solved with adhesive tape by the compiler vendors. It simply starts with a very simple thing: the first vendor of the compiler provides his own way how to do things, and then there are other compiler vendors that, volens nolens, adjust to the existing situation, and that’s how the “standard” comes to life. Fortunately, there’s no need for a fully portable standard for it – things must be compatible only within the frames of a single operating system. But still, some standard must be defined, or otherwise libraries compiled by one compiler cannot be used by applications compiled with a different compiler.

In the early days, I remember that in the 1990 years, there were two different compilers on Windows, one provided by Microsoft, the other provided by Borland (that company is a kind of different story in itself, but that’s not important here), there was also Watcom, and at some point MinGW was screwed in, each one having a different system for mangling C++ entities. At some point all have likely aligned to the Microsoft’s definition, as without it it was not possible to distribute software dependencies. Early library vendors were also providing binary packages with alternative “Microsoft version” and “Borland version”. On Linux things were looking much better since the beginning because it has only one compiler available: GCC (“GNU C Compiler” initially, but after adding support for C++ and Fortran it was renamed to “GNU Compiler Collection”), and this one has been defining the standard here. I’m not sure how it was in case of other compiler vendors on other POSIX systems (like Sun’s C++ compiler, for example), but as gcc has been available on all POSIX systems, it has de facto dictated the standard there.

What is even funnier, this standard was changing, as changes were needed with the evolving language, making this way libraries compiled with the earlier standard incompatible – and so on. Things look much better now, but I have still never heard about any standard committee to standardize it. Pity, but that’s our reality. The standard for this has been defined by:

  • gcc development team, in case of Linux (clang followed, for example)
  • Microsoft in case of Windows
  • Apple in case of Mac (not sure which compiler they were using before clang – might be that since clang they have even adjusted to the latest standard provided by GCC, I didn’t check)

What things were these C++-specific things? For example:

  1. The way to encode the function-like or global-variable C++ entity identifier as a linker symbol name (“mangling”)
  2. The way to encode “physical” part of a class, that is, the “class characteristic object” (containing, at least in the current C++ standard, the VTable and the RTTI data).

4. Linker features required

Let’s start with this most general feature: The linker should feature immediate constants.

I’m not an expert of the linker, and I think an appropriate feature is provided already, but it’s not in use by compilers. It’s about having a value assigned to a symbol that is initialized and the value itself will be filled as a replacement of a symbol, not the alleged address of the entity (as it is for functions and variables, even in read-only flavor). Such a value should be also able to be used and interpreted by the linker itself, if this defines, for example, a size of some other data.

Here is required such a possibility that when an object is referred to, its address is replaced by the linker, but when you need to reach out to one of the fields of primitive type (integer or pointer) there’s an offset used likely with some address that is defined by the compiler directly in the assembly code (“hardcoded”). With this feature, this offset, instead of being directly encoded, should also use a symbol replacement. However this time the linker would have to replace it not with the address of the entity, but with the content that is written in the symbol definition.

Similar, although simpler thing is with the size of the structure. Whenever you use the sizeof (MyStruct) expression, it should refer to an appropriate symbol in the object file with a constant that contains the value being this size. This constant is then directly replaced in every place where the reference to this symbol is used. It might even have an appropriate naming convention, as long as linkers support appropriate types of symbols, so this is not just a “constant”, but a constant being a size of the structure, and therefore it holds an appropriate naming convention and name mangling.

This can be then extended to compile-time constants. You theoretically compile-in things here, but still, there’s no need to physically read them from memory if it can be provided already as an immediate value.

A bigger problem is that constants in the language can be used by way different ways than the address-based entities. Offsets in structures, their size, or just constants to be used in some evaluations are piece of cake. Worse things are such as, for example, when your constant defines a size of an array, which is a global variable. Hence the linker would have to provide also a possibility to not only support constants, but also to use constants when resolving the variable: linker must also “link itself” by referring to the size of the variable that is provided also by the constant found at a given symbol.

Even bigger problem is with inline functions and templates. But then, very few of them are to be solved by a linker. From the linker we need only these things:

  1. Have a symbolic entity type, which define the convention that the name is using, and also how this should be understood
  2. Support immediate constants, where the linker fills in the contents of the symbol, not its address
  3. Support global variables with symbol-defined size

5. C++ entities that could use new linker features

It doesn’t mean that C++ compiler would have to make use of these new linker features in the new modularization. Whether such a linker exists, it depends on the system, and it only allows or not to provide particular language features, such as sharable classes or templates. Might be that many of them could be provided in the future. Such as:

  1. External classes. This is a class that has this size and field layout defined in the library. As such, it will go with less restrictions referring to the ABI compatibility.
  2. Compile-time external constants. They do exist today, but the compiler can generate a constant symbol that resolves to an immediate value.

This can also extend to functions, if these are used with them, as well with their signature. The functions themselves are referred in the linker by its address only, but the size and layout of the stack frame for arguments is dependent on the signature. This can also be encoded by appropriate constants so that the call form remains compatible even if, for example, someone replaces int32_t with int64_t in one of arguments. This doesn’t free the library developer from any compat requirements, but at least gives them more flexibility.

6. C++ interface form files

And here is the thing absolutely required for module: a standardized interface file format, which will be portable, at least in the frames of a single operating system. That is, it may contain some variants that might be specific for the system, but this format is at least interchangeable in a single operating system and platform, simply just as portable the binary packages can be. It’s not easy to define as it would have to be a mixture of C++-language specific things and platform-specific things.

The first biggest problem is the preprocessor. This could be at best got rid of, but it’s not that easy. The preprocessor macros are still used in header files and translation of projects to the form not using it won’t be that simple. They are being used for different purposes, and not all of them could be allowed in this form. You might want for example:

  1. To reshape a constant per the application’s need.
  2. To enable or disable a library feature – the reason being that an enabled feature turns on a dependency on some external library, or that it requires some specific support from the operating system that is not always available.
  3. To turn on or reshape some development-specific thing, for which the library support isn’t needed, or is provided anyway as it’s considered cheap.

This is what I know that is being used in various projects, but this list definitely isn’t complete, it’s just to give you idea. This list should be better completed by reviewing various different projects to see how they are using preprocessor and especially -D option in the compiler. Interesting is the case when appropriate -D option is used for the compile command to compile the library user code (not the library itself!), which influences on the results of interpretation of this library’s header file. Every such case better be got rid of or somehow replaced, for example:

  1. Any specific value should be contained in the library specific configuration so that they can be specific for the installation.
  2. If there is a feature that could be enabled or disabled for the whole library, then this should be provided for both the library itself and its interface. The final library form may contain also some manifest file that enumerates the features, of which it is expected that a compatible library must have the list of features identical with the requiring library user or otherwise linkage is not possible. This should be also included in the format because this feature list should be attached to the library. Something like this is being used today by providing versioning to functions in the library, but this is also using some linker tricks to achieve it. This time it would have to be an official feature of the linker, coordinated by the features in the interface file.
  3. This kind of configuration could be provided in the runtime configuration, but if there is any reason to hardcode it in the target, this could also in perspective use the immediate constant entity feature in the linker. This way there should be some method to transform the compiler option into a constant – likely something like a symbol that is provided with some defined value and can be replaced by a compiler option.

Anyway, the influence of the preprocessor macros on the form of the interface must be completely eliminated. The definition of C++ modules should make things motivating enough, I’m not sure up to which grade it is so, but then if you have a module-instrumented C++ source file, there should be the following restrictions applying to it:

  • The use of any preprocessor directive is restricted to the use in the implementation only.
  • Module interfaces can provide a preprocessor macro, but it must be syntactically complete. That is, they can resolve to a single instruction, single declaration or a single value, but never a fragment of one.
  • The use of #include in the module-instrumented source files is only allowed in the Global Module Fragment. Symbols provided by it can be only used in the implementation. Reexporting any parts of it, including when a symbol is a part of the definition provided explicitly in the module, require that the export declaration be explicitly declared.
  • Preprocessor directives may be used for conditionally including some part of the declaration, but then this information must be added to the feature list (so that a binary package with this thing included is different to the binary package with this thing excluded, both in the interface and in the implementation).

With these restrictions on, the module interface extracted from the source file should be free of any preprocessor dependencies – that is, the use of -D option in the compiler doesn’t influence anything in the interface.

Next, every language entity as defined in this interface must have its form appropriately encoded: the name, the signature, encoded built-in types, encoded references to library-defined or user-defined types. This is something that must be agreed upon by all compiler vendors. It’s so because this is the kind of immediate form that is understood directly by the compiler after it parses and interprets the contents of a header file. Every compiler does it and each one is generating some form of the internal database from it. The thing here is to have an interchangeable format of this database so that it can be loaded quickly by the compiler, without the need to preprocess and parse the header files with all indirect includes inside.

I know that actually the compiler doesn’t distinguish between header file and the source file, but then there is already known a practice of so-called “precompiled headers”, which is a “half-compiled” form of a header. This is a good place to start, but can’t really be a final solution. That’s also because, for example, even on Linux gcc and clang use different formats, different methods of creating them, different filename extensions – because it was never thought of as for any other use than for the current build process. This time we need something that will be produced identically by every compiler on the platform, so that it is interchangeable, and can be distributed together with libraries instead of header files.

For example: such things as structures, classes (stating that we don’t provide method bodies), or even class templates, should look the same everywhere, regardless of the platform and compiler vendor. This is the language-specific entity. On the other hand, it should have such a form that every compiler should be able to turn it quickly into its internal database as being prepared to build the rest of it when compiling the source code.

A little bit different story is with the inline functions. Inline functions could be provided with their out-of-line version (I think in the new modularization system it should be required, today it’s optional), but the inline version must be completely contained in the interface (that’s why inline functions shall not be allowed to be recursive, and multiple inline functions shall also not be mutually recursive). For inline functions it must be predicted that at the place of their call they will be “dissolved” into the calling environment. Therefore it’s unlikely that they can be compiled into the target assembly code. Probably some fragments of it can, as long as this can be framed independently, but normally the compiler should do optimizations on the code after the inline function has been dissolved (for example: there’s usually no argument passing on the stack, argument values are taken directly from the code where they were evaluated, the writing to the variable being returned is using direct writing to the variable assigned etc.). That’s why there has to be rather created some smart binary coding method to which the function body can be translated, and the compiler will still have to translate it to its assembly code. This binary code need not be portable in general, only within the frames of the particular operating system – so it can be without problems specific to the target system and machine platform. But still it’s unlikely to simply be the same form of assembly code as the compiler would do with normal functions. Not only because of required simplifications that would be specific to the place of usage (alleged call), but also that likely this same would have to be done to function templates, which’s details after compiling into a normal code would be dependent on the type parameters.

7. Binding together

As I mentioned already the binary code for inline functions, you might ask: would it be possible to have a smart compiler that translates it to the assembly code on the fly, which would be called by the linker? Not sure how complicated this is, but if this is possible, you may simply have a C++-specific dynamic linker, which in perspective can free us all from all problems known as “ABI compatibility” – or at least most of them, while shifting all the remaining problems to the category of “linker errors” (which is a large improvement towards the undefined behavior).

If you have a function template, for example, its final form needs to be a function containing the assembly code to execute, but some specifics need to be resolved depending on the size and specifics of some types used as template parameters. Templates, however – in distinction to preprocessor macros – don’t have syntax-specific dependencies; all their properties are at the C++ level, and as such, can be so encoded. If you have a specific inline function to be expanded, you use the general method to do it, as for all functions. If a type size, or specific builtin operation – this should be defined in the binary code standard for the inline functions. All this must be so simple that finally this can be done quickly by the subroutine called by the dynamic linker.

But that’s not all. What we currently have is that we have libraries, they are being opened when an application needs it, it’s loaded into memory (text only), and then there are per-application instances. The latter must be created anyway, but as for the “text” part we don’t really need to have the whole library in the memory – only text entities that are in use.

This, however, means that the library would not be the separate namespace, as it is today. This is unfortunately a method that potentially allows to provide a symbol of the same name, but by different libraries, while the potential conflict would not be properly prevented from and it’s hard to detect. This time you might want to require particular module contained in the library package and only require its specific version, maybe possibly somehow the variant (as a set of features – mentioned above). Those should be able to coexist, as long as the system can identify symbols provided by particular variant of the library. So, this way, you may have a specific library and a symbol provided by this very library package, but it is known from upside, which of the libraries package provides this symbol (because it is encoded in the interface files that the target was requesting) and that symbol is loaded to the memory if not yet present.

Once having this, the system can simply use single C++ “module form files” that provide both interface and implementation in one file, and the unit of caching in the system is still the single linker entity as required by the application. As long as it is possible to do any dependency tracking between entities, the system must load only those entities that are in use. The system also records the time when the entity was last open and when the next application requires access to the same entity, it will wink into the already cached entity, or will load the entity anew, if the library file is newer. Anyway, loaded and cached in memory are single entities, not whole libraries.

This way we don’t even need library files anymore – that is, the *.a and *.so files. Every module is simply compiled into module form files, which finally consist of interface and implementation, but provided as a single file. When compiling a library user, the request to the given module is resolved to opening the module form file, in order to reach out to its interface, but the exactly same module file is then used for linkage – both static and shared.

8. Considerations

Not that I have even made any feasibility study on that. This is only a pure concept, which can be also implemented partially. Most important thing for modules, as I mentioned in the previous article, is that the transition into modules can be done smoothly, according to the procedure I have shown. This means that there must exist initially a method to provide just “pure” module interface files with the traditional library files, but also single module form files containing the interface and implementation in one, just as well as generate a header file out of the binary interface file (yes, including “decoding” the inline functions).

I admit, I just sketched the concept and haven’t even checked if all these things are possible to be done, but I believe they just require a bit work and general development, which includes a bit giving up of the market competition, and most of the work would have to be done by the compiler vendors. But I do believe that it’s worth it.

Posted in Uncategorized | Tagged , | Leave a comment

Format string considered not exactly that harmless

Introduction

I have written this article basing on getting unexpectedly involved with the formatting feature added to C++20 and also earlier defined as the {fmt} library, which has been looking since the very beginning as an unfortunate attempt to revive the C’s printf function in the new light. Note then that as a software developer I am interested mainly in how particular solution improves productivity and I evaluate solutions exclusively with that regard.

Since software development activities consist of three types of activities:

  1. Writing the code the first time
  2. Reading the code someone else has written
  3. Fixing the code someone else has written

A “shorter” and concise way to encode an instruction is good, but if it doesn’t come together with clearance and intuitive understanding, it helps only in the first one, which happens once in a software lifecycle, while the others happen and repeat multiple times. That’s why it’s not enough that something is written “shorter” – first of all it must be clear and easily understood, and if it’s not, this concise syntax shall better be sacrificed for this. If it’s not, it may lead to creating a so-called “write-only software”.

I decided to make this introduction first because all solutions using the formatting specifier in the string is being always explained by its enthusiasts that “it is short” and therefore “easy to write”. So, yes, this exactly refers to activity 1. Without mentioning the truth about the rest.

Some historical background

Before we explain how printf came to life, let’s see what methods of printing a series of values were available in some older languages.

Let’s make a short example: we have data for a rectangle: left, top, right, bottom. We have variables with these exactly names that carry these data. Now you want to display the origin point as cartesian coordinates (so, x=left, y=bottom) and their sizes (width=right-left, height=top-bottom) and it should look like: origin=x,y dimensions=width x height. We also have a color in RGB format and we display it as color=#RRGGBB (hex).

write(*, *) 'origin=', left, ',', bottom, ' dimensions=', (right-left), ' x ', (top-bottom)
write(*, '(Z6)') 'color=#', color

As VisualBasic is kinda too evolved, and it still does have many original concepts, it got too complicated for historical explanation, so let’s use the Commodore C64 version, also similar was that on Atari XE. Note here that the semicolon was different to comma in that comma was adding a space between printed parameters, while semicolon makes them just glued together, and also left alone at the end prevented adding the EOL.

PRINT "origin="; left; ","; bottom; " dimensions="; (right-left); " x "; (top-bottom)
PRINT "color=#"; HEX$(color)
Writeln("origin=", left, ",", bottom, " dimensions=", (right-left), " x ", (top-bottom));
Writeln("color=#", HexStr(color, 6));

(Let’s not forget also that formatting a floating-point value in Pascal is done by using value:width:precision expression inside the Writeln arguments).

Ok, but now let’s turn to something more from today. So let’s try scripting languages. All of them have such a feature as “interpolated string”, that is, you specify everything you need in a string. So let’s try now…

puts "origin=$left,$bottom dimensions=[expr {$right-$left}] x [expr {$top-$bottom}]"
puts "color=#[format %06X $color]"

Of course not every language is capable of having such a feature as interpolated string, so let me show you also how it would look like without it. The puts instruction in Tcl gets only one string to print (actually Tcl is known of that in this language “everything is a string”, so that’s not a big deal for it anyway), but there’s also a concat instruction to glue in values, so this can be used instead. So, let me show you how it would look like if there is no string interpolation and let’s imagine also that concat is the only way where you can interpret the value as string:

puts [concat "origin=" $left "," $bottom " dimensions=" [expr {$right-$left}] " x " [expr {$top-$bottom}]
puts [concat "color=#" [format %06X $color]]

Of course, let’s not forget that the format command in Tcl has been created after the C’s printf function, but we are using here just the simple format specifier for a single value. This isn’t the only way to do it in Tcl because we have both possibilities – either this way, or the same way as in C’s printf by simply using puts [format "%d %d %d" $a $b $c], which looks similar to printf("%d %d %d\n", a, b, c);.

Ok, I may also mention Python, for which all variations are available, but you still can do simply:

print("origin=", left, ",", bottom, " dimensions=", (right-left), " x ", (top-bottom))
print("color=#", format(color, '02X'))

Not that this is the only way available, the string formatting like in printf or interpolated strings (f-strings in Python) are also available.

So, what do all these things have in common?

The way of formatting the printable string is to glue all values together, while format configuration details are specified directly by the value being formatted.

Suffices to say that when the new file stream system was being developed for C++, the first thing to do was to return to the old, good method of formatting, which predated the C language, stating that C++ already has appropriate capabilities to provide them in the “userspace” (not as a language-builtin feature):

cout << "origin=" << left << "," << bottom << " dimensions=" << (right-left) << " x " << (top-bottom) << endl;
cout << "color=#" << hex << setfill('0') << setw(6) << color << endl;

Did people like it?

Well, some did, but this solution also faced criticism – mainly including silent one, that is, the people simply weren’t using it and resorted to printf-clones instead. This C++ version was attempting to be free of formatting string, but then one annoying treat of this is that the formatting flags modify the stream state. This is not only annoying for the programmer, but also causes performance problems.

In the meantime, in other languages many derivative works have been developed basing on the original idea of the format string, slightly improved, without the most obvious problems of the C’s printf version, but still with a format string. I personally find that obnoxious.

Sinking in C

So, how did this exactly happen that the C language got that printf function as a universal way of printing values on the screen?

There’s simply one and the only reason: because of this language’s limitations. Of course, it could be just as well added as a language feature, as it was done with many other languages before, but there were good reasons not to do it this way (Pascal did it on the language level and that resulted in an inconsistent and limitedly useful feature). Even if you had to resolve to a concept-mixing weird style of a format string.

The formatted string function was done this way because it was the only possibility with the following language limitations:

  • Inability to handle dynamic strings.
  • Inability to handle the protocol of various types of data passed to a function. Although there exist standard ways of “encoding” a value when passing to a function, there’s no way to recognize its type or even size. The function call must provide this information separately.
  • Inability to pass a single argument that designates an array with known size.

The latter is still a problem even today (even in C23), and it includes also a case when you might want to specify an array with constant values to designate things to be specified in variadic arguments. No one came even with an idea to use a structure with void* and size_t to be passed by value. Even to take the size of a constant array you’d have to use at best a macro, still, if you write it yourself (requires to use an expression with twice sizeof). And even though ANSI C introduced passing structures by value, most programmers were scared of it like a devil of the holy water (check for yourself any project that is being actively developed today in C language and you’ll see that it still holds).

There is only one type of an array in C that has an ability to be passed as a single argument to a function and the programmers don’t have to do anything special to achieve it: a string, which’s size can be manually counted due to being terminated with a special NUL character. It didn’t come without a price, though – when the size is known prematurely, for copying you can use a CPU-accelerated memcpy, while for an array with a termination element you have to walk them through one by one using explicit looping.

In effect, already this was not easy to implement (this call actually mixes static strings and something that could only be a dynamically allocated string, which’s lifetime must be controlled), while it already looks clumsy:

print("Height: ", format(d, "0.4f"), " index: ", format(i, "02d"), "\n", NULL);

so it was decided it will be easier to do this way:

printf("Height: %04.f index: %02d\n", d, i);

It is also important to mention that this function was provided first in the K&R C version, which for the function calls was using the “forced convention”: values are encoded according to the types used at the call and the called function takes it as a good deal (you just have an undefined behavior if they don’t match with what the function expects). Therefore variadic functions existed there naturally – arguments’ types and number information could be just as well runtime-provided. The proper interpretation of them remained a problem, though – the called function just gets the stack frame with parameters, but it knows nothing about their number, sizes, nor how to interpret them. Therefore there are exactly three known conventions, how to use variadic functions in C:

  1. Termination tag. This uses the last fixed argument as a special symbolic tag, which defines how to interpret the next arguments, and a special termination tag symbol is defined that should be always used as the last argument. It may be then an array of pointers, where NULL is that termination value, or the leading value is an integer (usually symbolic) and 0 or -1 is terminal. A disadvantage of this convention is that the termination value must always be specified explicitly as the last argument (forgetting it may lead to an undefined behavior).
  2. String specification. Among the fixed arguments there is a string, which provides a complete information of all variadic arguments. Their number and characteristics must match what is declared in this string. This is the model of all “formatting” functions, mainly printf and all its users.
  3. Single variadic argument. The function is variadic, but it expects exactly one parameter after the last fixed argument. The information provided in the fixed arguments should be used to determine how to interpret it. This convention is largely avoided in favor of passing a value through the variable’s pointer and separately its size – like it’s e. g. in setsockopt.

So, out of these ones only the convention 2 was suitable for printf as the only solution that uses “automatic termination” marker at least for the argument declarator (format string here). Not that it didn’t suffer of further limitations, like:

  1. One single string must define all other arguments. There are many ways how you can achieve that, but the more variants you support, the more complicated it becomes and the formatting string starts looking like a manually encoded assembly language of some weird processing machine. Therefore all usually stay with simple “one tag per argument” manner.
  2. Argument specification must designate the type. How the value is extracted and interpreted for particular type, it must be declared by a type-specific code. The drawback is that the type specification is mandatory, although it’s usually combined with the flavor in one symbol, so the problem is actually minor. Worth noting that this problem, unlike the others, wouldn’t prevent the above example with format function from being implemented (just you wouldn’t be able to use default formatting). This is also the only problem solved by all “improved” printf clones written in C++.
  3. This design of the printf function also mixes two completely unrelated features: turning a value of a known data type into a printable string form in desired flavor, and filling a stencil (replacing tags in a tagged string with specified values – I’ll elaborate on that later). It was done this way only because it was easy to implement and seemed to provide some extra advantage. If the format string was exclusively used for tags (and so with no % marker), it would have to be used this way, for example:
printf("s02ds02ds", "Width: ", w, ", Height: ", h, "\n");

But this would be totally clumsy and error-prone. Especially when you have numeric values or even runtime string values happening occasionally, while the string to be printed was the biggest part of it. So it was easier if the “string is string” already, and only the non-string and runtime values have to be specified:

printf("Width: %02d, Height: %02d\n", w, h);

In other words, the only reason to implement it this way was that the programming practice driven by language limitations has won over the design consistency.

One may, of course, think about alternatives to a format string specification, but they don’t seem very reasonable. There was, for example, a possibility to use convention 1 with requiring that the last fixed argument be a string that declares the first format. The formatting tag should be always at the end, and if it’s not present, there are no further arguments. It would look like this:

print("Height: %0.4f", d, " index: %02d", i, "\n");

That could be a nice solution, but it still suffers of several problems, like:

  • Same as with printf: the format string is not just a string, and it’s logically a different data type. So you can’t just pass a runtime string there, you have to pass the format "%s" and then the string.
  • This requires actually that the last argument be a format string with no tags (or ultimately also NULL could be treated as such), and forgetting about that may cost you a crash (a common problem of convention 1).

Convention 1 could be fixed by making the compiler add the termination value by itself, and some nice syntax for that could be created. But then it would have to be either used for all variadic functions (which would break the ABI compatibility), or require adding “something implicit” to the C language (like declaring the termination value after the ellipsis in the signature). According to a likely principle of its creators, this is completely prohibited in this language. C programmers must obviously “have everything under control”, which means that everything must be written in a kind of “symbolic assembly” language. This problem could have been fixed this way in C++, but no one saw it worth a shot. Therefore variadic calls were first solved by using overloaded operators, and then C++11 introduced true variadic functions based on function templates. Therefore all C functions that use this convention – for example, execl – require passing the NULL argument at the end explicitly. The same thing is done also when arguments are passed through an array, like in execv. For these functions, as they were used rarely, it was acceptable, but for one of the most often used ones, like printf, it obviously wasn’t.

Unforeseen consequences

ANSI C has introduced function signatures and therefore the “fixed passing” convention: the call of a function was matched with the signature, appropriate type conversions applied if needed, and errors at compile time reported when the call was incorrect. Function signatures were already in K&R, but only in the form of “free signature” (empty parentheses), which allowed to declare the return type, if it had to be other than int, while still using “forced passing” of arguments.

As a slight digression, it could be nice to note that the power of signatures was still underestimated (they were actually borrowed from C++ being actively developed at that time) and free calls were still kept in some scripting languages, notably Perl and Javascript. In these languages call arguments are not verified, just in worst case you’ll have “undef” in some and ignored the others. This way some kinds of programming mistakes were hilariously ignored. This mistake wasn’t done in languages like Python or Tcl, where arguments are fixed and variadic calls use a dedicated syntax, even though in these languages you don’t really have data types to control the call signature.

Fixed signatures fixed the problem of “forced passing” in most of the functions, but then there were also functions, such as printf, which could not be implemented this way. Therefore ANSI C provided variadic functions, that is, functions where the fixed argument list was followed by “ellipsis”, meaning that in the call you can pass further arguments after the last fixed one using the “forced passing” convention. There was no other way to do this. ANSI C didn’t have any features that could be used to propose anything better than printf for the same task. The most obvious problems of forced passing, causing an undefined behavior, were later fixed by compilers – all today compilers offer help in checking these calls (and they report mistakes through warnings). But this is limited to a design of known standard functions and even if a declaration syntax is available for user functions as well, it is obviously not portable. And only if the format string is passed as a literal.

And here is the whole explanation. And no, it wasn’t any kind of “new approach” or “comfortable enough”, “better readability” or whatever other bullshit you can invent here. The true reason to invent such a sorry solution was just one: to fit in the limitations of the C language and press out for the programmers the most oil from this dry olive.

But people who designed this solution are excused – they worked with what they had at that time. It’s worth noting also that in the 1970+ years high level compiled languages were a novelty. You could either have Fortran or BCPL, which were merely wrappers for the assembly language, or an interpreted language at best using a virtual machine (like Smalltalk or Simula). Also there was no software written with that level of complexity as we have it today, hence no experience (including bad one) with such solutions, especially if there wasn’t any better alternative for existing solutions. Therefore also excused are people, who had to work with this for such a long time and have found it good enough, even if there are better alternatives already.

But preferring this solution over symbolic flags and gluing values in their right order reminds me of people from some deep provinces in some forgotten lands who still eat meals made of dog meat (I didn’t try myself, but my grandpa, who survived WW2, told me that it stinks), even though they could just as well eat pork or beef. The same thing: people, who were doing it in the far past, did it because they had no other choice, except for starving. But even they could never prefer this over pork, beef or lamb!

But then, am I not simply trying to convince you about my personal preferences?

No. String formatting is objectively bad – and here I’m going to explain, why.

Short introduction to Esoteric Languages

So, you probably heard about esoteric programming languages – like Intercal, Befunge, Brainfuck, Unlambda, Smetana or Malbolge. Ah, I almost forgot – there is one more, which is even today still used to create software: Perl.

There are also esoteric algorithms. For example, there are esoteric sort algorithms, such as dropsort. Beats all algorithms because it has linear complexity. How does it work? Well, it copies the elements to the output, skipping those that are not in order. Who said that all elements must be preserved?

The general idea of esoteric languages is to implement specific language solutions that makes the programming harder, something that are the absolute opposite of being readable, error-avoiding, comfortable and useful. Intercal is a good example because it cumulates not just one, but multiple stupid ideas, among which there are some interesting ones:

  • The PLEASE instruction was required to be used for some number of instructions, otherwise the program is ill-formed as too unkind. But not too many because this way it might be also ill-formed as too fawning.
  • Instead of parentheses, Intercal uses single and double quotes. For example, (x-y*(a-(f-e))) in Intercal would be written as 'x-y*"a-'f-e'"'.
  • And a later addition, COME FROM, which is an inverted version of GO TO (note that in older languages lines had their explicit numbers, as the way to edit the source was only to enter and record a single line at a time – and GO TO referred to that line). It has to be defined in the jump destination location and should specify the line from which the jump should be done. In other words, when subsequent statements are executed, the next one is not, and the jump is made because this line is mentioned at the destination location with COME FROM.

Some specific category of esoteric languages make the languages being some kind of parody of the Turing Machine: Brainfuck, Doublefuck, or Befunge. Befunge is a one-feature language and actually extended version of Brainfuck, which contains only simple instructions of moving down the tape and increasing or decreasing integers on the tape. Befunge is a two-dimensional version of it, where the execution cursor moves through a matrix with instructions. You have additional instructions of changing direction also to horizontal and vertical, and the executed are instructions that are met on the matrix. In order to make a loop you simply have to organize your instructions so that the execution cursor runs in a rectangle path. So, that’s the method of relying on the text layout in the source code driven to absurd.

Why do such things exist? Why people work so hard to even create language specifications and implement compilers, which from the business point of view seems completely wasteful? Because this can serve as a warning and a physical proof that some ideas are just stupid and counter-productive, but without implementation you don’t have a proof. And beside playing around with ideas or intellectual amusement, they do have a value, which is: to openly declare (by sneering), what language features are bad because they contradict readability and usefulness, are most possibly error prone, and simply make the programming harder.

Some didn’t get the joke

Not that it didn’t inspire – unfortunately – creators of other languages. I have mentioned already Perl as one of the languages that prefers often crazy and nice looking statements to rule stability and usefulness, especially for people using also other languages. For example, you can do this in Perl:

if (is_higher($n))
{
    slip($x);
}

but this won’t work:

if (is_higher($n))
    slip($x);

Not that this is impossible without braces. You simply have to specify it this way:

    slip($x)
if (is_higher($n));

I wouldn’t even guess which function call is executed first.

It also has things like unless that can be used instead of if with not, and similar until as a complement for while, and many alternative ways to do the very same thing multiple different ways, all of them the same useful, all of them you have to know if you try to interpret someone else’s code. You should be lucky that no one invented expressions like neither X nor Y to replace (!X && !Y).

It has even inspired me once to create another esoteric language (although I didn’t have enough time and lust to make something out of it and I abandoned this project) – I called it Legal – in which every instruction was a single sentence starting from an uppercase letter and ended with a dot. Instructions were grouped in paragraphs, and single instruction, especially with conditions, as sections. Because if you can write an instruction slip($x) if (is_higher($n)) then you can even go further and say something like Is the value greater than 5? If not, execute the statement mentioned in section 5., can’t you.

There are many bad language decisions for languages still in use. For example the creators of make didn’t get the joke of the Whitespace language (in which the only characters you can use in the source code is space, tabulator and end of line, and beside this it bases on the same idea as Brainfuck) and made in the syntax of the configuration script distinguishing the space and tabulator as a first character in the line, depending on which the line is treated as a script statement or as a command to execute. It cost me once many hours of bug hunting, when one weird editor once turned all tabs to spaces. The problem is known, therefore replacements have been developed, like ninja; also my agmake is free of that problem.

The creators of Python have also unfortunately followed, making it rely on the source code formatting in the language correctness. Some people even praise this feature as something that “makes you keep the program source decently formatted” (playing idiots, of course, because the problem is not that you are forced to keep the program formatted, but that the meaning and syntactic correctness of the program depend on it – like, e.g. you don’t distinguish visually 4 spaces from a single tab when you have set 4 spaces per tab in your editor, but the interpreter surely does).

That’s also not the only stupid thing that was developed in Python. There was a well known problem with multiple inheritance in C++ if a conflict has developed, when you have two identical method signatures in two different (and unrelated), but common derived classes. The most sensible solution (although not so simple to define in the language without having a deprecation period) was to disable this possibility and hide the method solely in the base class (so that doesn’t automatically get exposed in the interface) – that could be also a desired solution for C++. But no, Python not only allows this, but it also allows to specify in the class configuration, which parts of the base class should be how derived. Only to next recommend in the official documentation that multiple inheritance can lead to lots of problems and should be absolutely avoided. Congratulations.

These all above are proofs that even if some solution was already condemned as counter-productive in the software development, these treats still have fans that can’t live without them. When I looked for some tutorial how to print values in Python (which included also the methods I showed above), the author of this tutorial said that “format method of string” is actually the “best solution” (???). Yes, that’s exactly what he said. Doing print("a={} b={}" %a %b) is according to him better than print(f"a={a} b={b}"). I wouldn’t believe unless I saw it with my own eyes. And it was so badly inspiring that someone has even created a library called {fmt}, which is doing the same thing for C++, and that has even been later submitted to the C++20 standard and it’s already available for the most compilers.

I wouldn’t even find it bad that people are so fixed on this string formatting in their own software (for open source projects I don’t really care that someone decided to use a counter-productive technique), except for the fact that in the C++20 and {fmt} the format configuration structure isn’t even a part of the public API, so there’s even no way to make any extensions to improve it, nor to reuse the old good C++ iostream manipulators to configure the output. Likely someone really doesn’t understand, why this string formatting is so counter-productive. Especially that C++ doesn’t suffer the C language limitations and there’s no reason to follow these solutions.

Those who learned from previous mistakes and still chose to repeat them

Many people even misunderstand, what the real reason is that printf is so counter-productive.

No, it’s not the matter of explicit type specifier in a string – as I mentioned already, this really is a minor problem. The biggest problems are contained in a factor generally named as “productivity”. Let’s try this example, written already in the {fmt} style without type specifiers, so that minor problem is taken care of:

print_to(output, "KXDrawTool: configured: color=#{:02X}{:02X}{:02X} thickness={} depth={}\n",
                    settings.color.r, settings.color.g, settings.color.b,
                    settings.thickness, settings.depth);

Let’s say, it’s not a problem if the format string contains up to 4 tags, and well dispersed throughout the formatter (good for you if you have an IDE that helps you here with highlighting – still, ain’t no way that it provide you more support than the compilers). But the more parameters you have, the more they are far away from the place where you can find the declaration of its formatter specifier. That’s exactly the reason why I mentioned this COME FROM from Intercal.

A similar problem is in general in C and C++ (for the latter being even more of a burden) that functions and methods need to be usually declared twice – once for the header and once for the implementation – and they have to be kept manually in sync, and often not even copied 1-to-1 (due to namespace shortcuts, default parameters etc.). Modules in C++ were designed to help here, but I can’t see them quickly adopted (which is another story I described elsewhere).

So, take a look at this and tell me: what exactly should you do to identify, which of the function call parameters, are placed where in the formatted line? There’s no way you do this any other way but simply counting the format tags one by one and then applying this count to the variadic arguments. And why did I mention then the method declarations in C++? Because here you also have two separate things to be kept in sync: the format entry in the string and the value. Want to add one inside? You need to find, which exactly value precedes the place you introduced and then find – by counting – the same exactly place at the variadic arguments. The compiler will check the type specification, but won’t check if you mistook x for y, both being int.

Note that this wouldn’t be a problem if you used intermediate named tags in the format string, so you can simply say "x={x} y={y}" and then specify x and y in whichever order. But as this is supported as one of many features, the syntax for it isn’t that straightforward.

Of course, in order to keep things a little less frustrating you can also indent every argument so that it starts in the position of the { character corresponding with this argument. And here is the real deal:

    print_to(output, "KXDrawTool: configured: "
            "color=#{:02X}{:02X}{:02X} thickness={} depth={}\n",
                    settings.color.r,         // |        |
                          settings.color.g,    //|        |
                                settings.color.b,  //     |
                                                 settings.thickness,
                                                          settings.picture_depth);

And now you can see, how this thing could be improved: follow the Chinese, mate!

The expressions for the values to be printed should be written top to bottom instead of left to right!

Otherwise, you can see, even this doesn’t exactly suffice because the more the argument list grows, the more lines separate the percent sign and the argument. Ok, some column highlighting could help, but this is annoying for some (for me it is) and also it’s a poor text formatting support to half-solve a language problem. Which can even expand to a real horror from some “C-based performance programmer”, who has placed once in the code something like this:

sprintf(output,"%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X,%02X", arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6], arr[7], arr[8], arr[9], arr[10], arr[11], arr[12], arr[13], arr[14], arr[15], arr[16], arr[17], arr[18], arr[19], arr[20], arr[21], arr[22], arr[23], arr[24], arr[25], arr[26], arr[27], arr[28], arr[29], arr[30], arr[31], arr[32], arr[33], arr[34], arr[35], arr[36], arr[37], arr[38], arr[39]);

My boss, who saw this at that time, just asked “and this is certainly in order, right?”.

(As a side note, this code was allegedly written originally by some Chinese guy. Likely he also didn’t come to an idea of writing top-down.)

Yeah, I hear already screaming eagles lecturing me that “it is cleaner if I have a format string with just tagged locations for the values”!

First, it’s not “cleaner” – at best it is the same clean for simple examples using default format, like this:

print(output, "Rectangle : ", left, " ", top, " ", right, " ", bottom, "\n");

Making a pre-formatted single line doesn’t make it any cleaner, while already applying the eye-jumping problem (though still minor in this case):

print(output, "Rectangle: {} {} {} {}\n", left, top, right, bottom);

Of course, cleanest would be to have the interpolated string, but it’s not simple to add to C++ syntax (the expressions in the interpolations must be anyway parsed by the compiler, so such a feature would have to be added on the language level):

print(output, fs_"Rectangle: {left} {top} {right} {bottom}\n");

Second, if I wanted to have a “string template” to be filled with values replacing tags, then this is the example of the right solution:

print(output, "Rectangle %left %top %right %bottom\n",
               "top", top,
               "bottom", bottom,
               "left", left,
               "right", right);

This is a completely separate feature to formatting and there’s completely no reason in mixing them both in a single format string (this was done in C only because it was easiest to implement, not because it was anyhow useful). Moreover, if you need formatting, in this case it should be specified near the expression to be printed, not near the tag in the string:

print(output, "Rectangle %top %left %right %bottom\n",
               "top", setw(6), top,
               "bottom", setw(6), bottom,
               "left", setw(6), left,
               "right", setw(6), right);

I’ll expand on this idea below.

What the programmers actually need

The operator<< for std::ostream was not only made after the << operator in the shell – it was also the matter of sending arguments sequentially, one after another – and this couldn’t be done using a function because variadic functions were only to be added in C++11. If they were in C++98 already, this would have been very simple to define the “print” function, as known from BASIC, Python, and many other languages:

template <class Stream>
inline Stream& print_to(Stream& sout) { return sout;}

template <class Stream, class Arg1, class... Args>
inline Stream& print_to(Stream& sout, Arg1&& arg1, Args&&... args)
{
    sout.operator<<(arg1);
    return print_to(sout, args...);
}

When having this function, you can very easily write the above this way:

    print_to(output, "KXDrawTool: configured: color=#", setw(2), setfill('0'), hex, uppercase,
             settings.color.r, settings.color.g, settings.color.b, dec, setw(0),
			 " thickness=", settings.thickness,
             " depth=", settings.picture_depth, "\n");

Although I personally don’t like runtime state changes and it would be much better to do it with on-demand tagged API:

    print_to(output, "KXDrawTool: configured: color=#",
             fmt(settings.color.r, setw(2), setfill('0'), hex, uppercase),
             fmt(settings.color.g, setw(2), setfill('0'), hex, uppercase),
             fmt(settings.color.b, setw(2), setfill('0'), hex, uppercase),
			 " thickness=", settings.thickness,
             " depth=", settings.picture_depth, "\n");

You can find here, how to define the above fmt. Note though that it has a poor performance, of course, especially in comparison to the C++20 format library (and the same {fmt} library available for earlier standards), but it’s just an idea that can be further improved. The poor performance comes mainly from iostream, especially when you want to save and restore format that this function is doing.

Note that if you find the formatting specifiers better when they are specified by a format string, you can still do it like this (not defined in the above fmt though, but it’s a possible feature) – that’s something very much like the format() function in Python:

    print_to(output, "KXDrawTool: configured: color=#",
             fmt(settings.color.r, "02X"),
             fmt(settings.color.g, "02X"),
             fmt(settings.color.b, "02X"),
			 " thickness=", settings.thickness,
             " depth=", settings.picture_depth, "\n");

Now you can see that:

  • every expression is visible exactly at the place where its value is printed
  • every expression has exactly one instance of itself in this instruction
  • the format specifier is attached directly to the expression it touches upon

But then, if you think that it would be “more readable” if you use format string tags, it could be still done this way:

    print_to(output, "KXDrawTool: configured: color=#%RR%GG%BB thickness=%thicks depth=%depth\n",
             "RR", fmt(settings.color.r, "02X"),
             "GG", fmt(settings.color.g, "02X"),
             "BB", fmt(settings.color.b, "02X"),
             "thicks", settings.thickness,
             "depth", settings.picture_depth);

Still, the main difference to the formatting library is that:

  • The tag-replacement feature is a separate thing to format specification – just a simple tag replacement, nothing more
  • Formatting specifiers are still in use, but they are tied to the value being printed and hence it’s a part of the tag specifier. You can still use any markers in the tag names that would suggest the way how they are intended to be formatted, but this is only an information for the reviewer, not a specification for the language.

You may even resolve to a crazy idea like this:

    print_to(output, "KXDrawTool: configured: color=#",
             settings.color.r %fmt("02X"),
             settings.color.g %fmt("02X"),
             settings.color.b %fmt("02X"),
			 " thickness=", settings.thickness,
             " depth=", settings.picture_depth, "\n");

What then I think would be the ideal solution?

My personal preference is the interpolated string. The above solution is not the same, but close enough. What exactly problems would I have to solve with the format specifiers using language primitives (instead of the string specifier)? I would like to have it specified shorter. But this could be then solved by having something like this before the printer:

    auto H02 = make_fmt(setw(2), setfill('0'), hex, uppercase);
    print_to(output, "KXDrawTool: configured: color=#",
             H02(settings.color.r), H02(settings.color.g), H02(settings.color.b),
			 " thickness=", settings.thickness,
             " depth=", settings.picture_depth, "\n");

Or, should that be more comfortable:

    auto H02 = make_fmt(setw(2), setfill('0'), hex, uppercase);
    print_to(output, "KXDrawTool: configured: color=#",
             settings.color.r %H02, settings.color.g %H02, settings.color.b %H02,
			 " thickness=", settings.thickness,
             " depth=", settings.picture_depth, "\n");

That allows additionally to have a predefined format for particular kind of data for the whole application that can be changed in the central place when needed. All those things are the only problems to solve I can imagine with this kind of formatting.

Yes, I can hear again people screaming that obviously if you have a value of type double and you want to print one with zero-filled 4 digits and precision 8 and one with precision 6 only, with this system you have to do:

print_to(output, "value: ", fmt(value, setfill('0'), setw(4), setprecision(8)),
         " confidence: ", fmt(confidence, setprecision(6)), endl);

or at best with string-specified formatters:

print_to(output, "value: ", fmt(value, "04.8f"),
         " confidence: ", fmt(confidence, ".8"), endl);

which would be much shorter to write even with printf:

fprintf(output, "value: %04.8f confidence: %0.6f\n", value, confidence);

and the same with {fmt} or std::format:

print("value: {:04.8} confidence: {:0.6}\n", value, confidence);

I can admit one thing – this is shorter. I cannot agree with a statement that this is anyhow better for the productivity, as I mentioned in the beginning.

On the other hand, how many times did you happen to use explicit format parameters, unless the need was because it is always required (as in sprintf) or you needed some library- or app-wise consistent formatting, for which you could use a preconfigured format? I can imagine a software that contains lots of printed and formatted floating-point values and strictly placed in a row hexadecimal values with equally 8 digits. But even if, isn’t it simpler to just create a simple function, say “HEX8”, which will format the given value this way (and while the function correctness will be checked by the compiler), than to use "%08X" every single time? Not even mentioning a case that once happened to me when I had an integer value of some logical type to be always formatted the same way that I decided to format as 4-digit hexadecimal value and then the project manager told me that actually it is required to be printed as 4-digit decimal…

So, even if I thought it is better for some reason to use these string-based format specifiers, the best I can imagine for this is:

format_to(output, "value: ", "04.8"_F, value, " confidence: ", "0.6"_F, confidence);

Here I used _F as a UDL applied to a string to turn it into a formatter, as "04.8"_F, value is shorter than specifying fmt(value, "04.8") or value %fmt("04.8").

Ah, of course, additionally it’s better to have a line with short defined expression symbols, without having them so elaborated inside the call. That’s what the tagging feature of the formatting library had to solve, right? You think it’s nice to have them this way, while using then some more elaborate expressions for the actual values:

format_to(output, "value: {value:04.8} confidence: {confidence:0.6}" ... );

If so, you can still use intermediate variables. Just above, not below the general line specifier, but that changes nothing. This can be significant if you use some complicated expression pattern, but if so – see below.

So many features!

So, I was so negligent with the printf function that I have only recently learned that it features argument positioning. That is, you can specify the number of argument in every format specifier, instead of relying on the argument order. This way, instead of counting the position of the percent sign up to ten and then the same in the argument list, you just have to read the 10 number in the specifier and then… again count to ten in the argument list. A perfect solution. And that’s only one of many things that are provided for the fmt library’s {N:} format.

You can also specify tag names, and then tag every argument passed after the format string so that it is known, which argument the format specifier touches upon:

fmt::format("level: {level}, id: {name}",
fmt::arg("level", Rep::level(firsterror.value)),
fmt::arg("name", Rep::name(firsterror.value)));

Nice, but how does it differ to specifying the intermediate variables before the printing instruction and then using them directly in the sequence of printable pieces?

int level = Rep::level(firsterror.value);
string name = Rep::name(firsterror.value);
print_to(output, "level: {", level, "}, id: {", name, "}");

Of course, it can be useful to separate the format pattern from arguments – see below.

In the {fmt} library you can additionally nest the specification so that you can specify also the runtime value of the width or precision – by making it "{:{}}", width, value. Nice, but then the form looks like this:

int valp = 8, valw = 4, confp = 6;
print_to(output, "value: {:0{}.{}} confidence: {:.{}}\n", valw, valp, value, confp, confidence);

PFFF REALLY? And you can really quickly figure out here, which witches watch which watch? Then with the iostream manipulator style + helper fmt function I’d have this:

int valp = 8, valw = 4, confp = 6;
print_to(output, "value: ", fmt(value, setfill('0'), setw(valw), setprecision(valp)),
         " confidence: ", fmt(confidence, setprecision(confp)), endl);

When I call setw(N) or setprecision(N) I can also use the runtime value, and this function can be also overloaded with constexpr if need be. And it needs only to write fmt(value, setw(width)). And doesn’t require adding a format string that looks like expressions in Intercal. This is evidently nothing else than trying to make extra sorry workarounds to allow what with the use of function-like formatting tags comes naturally.

Provided that this is added to the C++20 standard, I’m really wondering what kind of guys are today in the C++ standard committee. I really think that I am kinda one of just a few youngest C++ programmers (even I am barely 50), who have first learned C++, had the first contact with printing on the console as iostream and cout, and only later learned that “in that old, outdated C language there was some ugly printf, but no sane person uses it anymore”. I had this in the ’90s and the last thing I suspected to come in 2020 was some epigone to revive the dead printf horse in the new tatters. Even more astonishing that no one really perceives how counter-productive is the way of pre-specifying the format string to be filled with subsequent, or preselected, list of arguments, in general. Actually the only thing that the creators of {fmt} library can be proud of is that they have achieved an excellent performance by having the format string interpreted at compile time (BUT…). Nice, but somehow that reminds me of C programmers who declare that they will never write software in C++.

Note that I never said that a formatting string with tags is useless in general. It is useful, but only in a form where it’s a feature on its own and not mixed with any formatted printing – and even if the formatted printing is also used, it’s in a different place. This is what I have written once myself when I had to do a simple JSON format printing (I didn’t know about the {fmt} library at that time):

    out << TemplateSubst(
            R"({ "level" : %level, "id" : "%name", )"
                R"("first" : {"time" : "+%basetime", "offset" : %baseoffset}, )"
                R"("last" : {"time" : "+%lasttime", "offset" : %lastoffset}, )"
                R"("details" : "%details", )"
                R"("repeated" : %repeated })",

            "level", fmt(Rep::level(firsterror.value)),
            "name", Rep::name(firsterror.value),
            "basetime", fmt(rel_basetime),
            "baseoffset", fmt(ers.baseoffset),
            "lasttime", fmt(rel_lasttime),
            "lastoffset", fmt(ers.lastoffset),
            "details", ers.details,
            "repeated", fmt(ers.repeated));

The very same thing could be done using the fmt::arg facility together with the formatter:

   fmt::format(
            R"({{ "level" : {level}, "id" : "{name}", )"
                R"("first" : {{"time" : "+{basetime}", "offset" : {baseoffset}}}, )"
                R"("last" : {{"time" : "+{lasttime}", "offset" : {lastoffset}}}, )"
                R"("details" : "{details}", )"
                R"("repeated" : {repeated} }})",
            fmt::arg("level", Rep::level(firsterror.value)),
            fmt::arg("name", Rep::name(firsterror.value)),
            fmt::arg("basetime", rel_basetime),
            fmt::arg("baseoffset", ers.baseoffset),
            fmt::arg("lasttime", rel_lasttime),
            fmt::arg("lastoffset", ers.lastoffset),
            fmt::arg("details", ers.details),
            fmt::arg("repeated", ers.repeated));


That could be tempting, especially due to that fmt::format gives me also a possibility to use compile-time interpretation of the format string and a nice speedup this way. But from the interface and visual presentation perspective the {fmt} version has still disadvantages for me because:

  • Requires additional explicit fmt::arg specification just because there can be also direct values here in the general case (and the necessity for fmt in the call of TemplateSubst are just because it’s written simple way and handles only strings)
  • If I require a format specifier for a particular value, I must specify it in the format string, not in the argument tag declaration
  • The use of {} in this formatting is very unfortunate as per the need of JSON format, messes up with the braces used for JSON, requires them to be escaped by doubling and makes the whole formatting string more messed up than the version with %tag specifiers

You may say that this last problem is a JSON-specific unfortunate case, but the truth is that JSON is currently one of the most popular data interchange format, and various different formats with hierarchized structure are also using braces (out of popular formats only YML could be a notable exception). I also know that % can be then problematic for other formats, but this can be then easily solved by customizing this character (also as a begin-end pair), which is easy if you have a facility, which’s only purpose is to fill the tagged text with a value replacement. The pursue of having a single multi-purpose solution in one, of which it’s at least just as well so easy to use them separately, has created limitations.

Just to sum up

So, again: As for me, in C++ the general case that is interesting for me as formatting specifier is to specify the values to be concatenated sequentially, and a non-default format configuration could be specified using the on-demand tagged API. An interpolated string would be ideal, but in C++ you can only count on that much. The format string facility can provide some interesting features that can be sometimes useful, but these are just rare corner cases, while the use of this format string in most of the cases is counter-productive for the software development.

Therefore I value solutions where you have multiple options at hand, not just one, and exactly the one that is the worst choice for the majority of cases. Adding formatting tags support and formatting functions for intermediate calls in the C++20 format could solve this problem.

Posted in Uncategorized | Leave a comment

C++ modules – harmless considerations

As I have let myself criticize C++20 modules, maybe this time I’d try to make a draft of an idea, how modules in C++ could be added the way that would be in the form usable and desirable by the real C++ developers.

As an attempted identification, I’ve let myself name it “K-Modules”. This is explained in one of the next articles, where I’m trying to show some more examples.

Ok, I was trying to write this article first using the bottom-up method, starting from C-modules and explaining how to transit to the C++20 modules model, but I think top-down will be more interesting. Let me first enumerate several principles of this design. In italic I added some explanation, why, if so, this principle is not fulfilled by C++20 modules:

  1. We need to get rid of header files. All definitions that are normally placed in a single source file should not require an extra separately composed file where most of the definitions are repeated, just to make it usable with the others. An early attempt to do it was the makeheader utility, although it wasn’t widely accepted in the commercial projects. This module system should allow to write all definitions that should belong to a single set of entities in exactly one file. In C++20 not only are you allowed to put definitions of one module in multiple files, but this feature also must be used in case when the implementation is using entities defined in other modules, which’s interfaces may not be ready when compiling the interface of that module (cross-dependencies). If that happens, you need to keep the separate interface file, that is, the main interface source with export module declaration, which is de facto the header file in a different form.
  2. We need interface files being compiler data storage. Header files were a way to expose the interface, but the compiler had to interpret it every time anew, together with all recursive includes. We need instead an interface that will be in the form quickly loadable by the compiler (a precompiled header feature was a good workaround for this, but it was still based on a manually created header file). C++20 modules provide this, except that there is no standard format for compiled interfaces, which makes it unusable for binary-distributable libraries.
  3. We need to retain all features of the “C modules”. We just want to have the same what we had with “C modules”, just without the need of providing additionally header files, and not need to have something “like a header file” in specific situations (which is required in C++20 in case of cross-dependencies). The problem with C++20 modules here was mentioned at 1.
  4. We need to make the build system reflect the module system. One of problems of the “C modules” system is that all information about the module dependencies and the ways to bind things together are based on various different parts of the system to bind the same kinds of things from different perspectives (including header files – linking together object files). In C++20 modules everything happens the old way, with an additional step to compile the interface (which was actually being made already earlier as “precompiled headers”, which is now also obligatory on some compilers, if you want to use import instruction for header files).

Before I start though, let me specify the overall goal of this whole project. Beside the new way how the C++ sources should be written, we also need to:

  • Provide a definition for the build system and creating libraries, which is better suited for this module system, and allows for cleaner way of providing dependency binding statements
  • Allow for smooth transition and partial translation between the current C++ sources and this new way (“module-instrumented” sources). In other words, we need to have the new build system accept also the old form of the sources.
  • Allow for improvements that could enable features like placing classes and templates in the shared libraries in the future.

Stating how the C++ standard is developed one may have a feeling that they define it as a language to write a single application, but it tends to ignore the most vital things in the C++ software development: libraries. I’ll avoid repeating things that I already mentioned elsewhere, just mention the particular problems that needed solutions and the development tools have partially solved them or not solved at all:

  1. Creating some “standard” (at least for one platform) symbol mangling (creating a named identifier for unusual language entities).
  2. Defining “solid” and “sharable” parts of entities, and compatibility rules between one another. This causes problems when the shareable part brought in by a shared library comes from different sources than the application linked against. Usually these problems are not detected by the compiler and result in linkage errors when running the application, or even undefined behavior in runtime.

Although for most of the time it was not a problem that the C++ standard was ignoring them (the software world has provided appropriate patches to make it usable), in case of modules this simply leads to create at best a “half-design”, something that would be then “possibly implemented” by compilers, as long as any of them can make any “full design” out of it, obviously one way incompatible with the other. Therefore let’s first try to look at the complete solution, something that could be, when ready, used in a daily software development job.

Some basic definitions

The software we are writing in files is rarely written as an application in a single file, so we have multiple files, each one compiled separately into an intermediate file, and then they all get linked together to produce the target. We need to have some sensible nomenclature, so I’ll try to reuse names that function already:

  1. Target: an application or a library (the matter of shared libraries will be put aside for now).
  2. Project: a set of definitions to compile single source files and link them together in order to produce a single target. Note that a project may produce multiple output files, but in a single project there can be only one target; if you want to have multiple targets in your build system, then you have multiple projects.

Note also that I’m not trying to redesign the C++20 modules from scratch – I’m trying to reuse as much as possible, even preferably go strictly along with the C++20 module definition, maybe at best adding some small improvement ideas. So let’s consider an example:

Let’s say, I have a small project of an application that contains three files: m.cc, t.cc and u.cc. The m.cc file contains the main() function. How then does this function, or any other function inside m.cc call any function from t.cc or u.cc? For that we need the interface of these files. Those should be built out of the source files basing on a specific mark at the entity that they will be accessible outside this file, that’s all. The modules give us this opportunity. Therefore we have this instruction in m.cc:

import .t;
import .u;

For now, ignore this dot before the t and u names – just pretend they aren’t there. This will be explained later.

Alright, but then what are these t and u here? This is the source file name without extension, sure, but binding it strictly to the filename doesn’t serve the language well. Therefore we want to be able to also declare it explicitly as a name that will be used the same way throughout the whole project. Still, a compiler must have some idea what to search for when this name is seen.

This name then designates a module form file.

Now, the first thing to take into account, before we start with the definition, you need to know that the same file would have to be compiled multiple times by different steps, and the module form file would have to be built in parts. It would be up to the compiler, whether it will make a single directory and particular ingredients will be added in subsequent command calls, or every call will create a different file with appropriate designation. Important is that it is not expected that a complete module form file is created out of a single source file in a single call. Just the form file may be on different stage of completion and only at the last stage is the form file complete.

So there are several types of module form files:

  • A module interface form file is the result of compiling the interface part only, that is, the compiler only grabs the signatures of entities marked with export and makes a database out of it, which can be then used by other files.
  • A module template form file is a special form of a module interface form file, which contains alternative entities or their fragments, which’s form depend on expansion of a preprocessor macro (it has nothing to do with C++ templates, it’s about the preprocessor only). These files are the direct form that can be installed among system files, equally like today the header files, although if there’s no need to have any macro-selectable alternatives inside, the module interface form files can be used instead. If not, the module interface form file for the need of building a dependent project will be created as an intermediate build file basing on the module template form file. Such a file should be built in case when you have any preprocessor conditionals that select conditionally particular exported entities. Note that some macros are platform-provided, compiler-provided and command-provided; only in case of the last ones do we need the template form file.
  • A module instance form file is the result of compiling a single source file (which should contain a complete module or a complete partition). To create such a file you need to compile the source file, while already having compiled the module interface form file for this very module (if one is needed), as well as all dependent module interface form files.
  • A module form file is the interface and instance form file brought together and described by the manifest file, which contains all information about the dependencies. The interface part may be comprised by the module template form file, in which case the module interface form file will be produced during the build and it will be a dedicated interface form for this very project.

So, the names used in the import instructions designate a module interface form file.

The module form files are these intermediate files produced directly out of the source files (plus existing interface files). Note though that we need to be able to compile particular file without having the dependent module form file yet; in case of cyclic dependency between t and u it would be impossible – that’s why we need to produce first the module interface form files. Let’s define then that t and u use entities defined in them both (so they seem to form a cyclic dependency) and finally m uses entities from t and u. Hence we need to first compile their interfaces only, so let’s imagine a set of required command lines for that:

c++ -mi t.cc  #> produces: t.cmi
c++ -mi u.cc  #> produces: u.cmi
c++ -mc m.cc  #> produces m.cm; requires t.cmi and u.cmi
c++ -mc t.cc  #> produces t.cm; requires u.cmi
c++ -mc u.cc  #> produces u.cm; requires t.cmi
c++ -ma m.cm -o myprog  #> produces executable myprog

Alright, but wait: why do we use only m.cm (module form file for m.cc) to produce the application? What about the t and u modules?

It’s simple. They are dependent modules, as declared by the import instruction. And yes, this instruction not only requires to load the interface of the imported module, but applies also a dependency on that module form file. Hence all the information about all other files to be “linked together” with m.cm (speaking the language of the current build definition) is already in there. And yes, you don’t have this way any “separate header file to #include and object file to link against”. You have imported a module – this makes your module dependent on that module, both in the interface part and the linkage part. And yes, every unit in the project is a module (note of course that there still must remain a possibility to link the *.o files because the libraries for older C++ standards and also for C language should be still usable).

For a traditional approach using the make tool we’d have then:

%.cmi: %.cc
   c++ -mi %<

# Now according to dependencies (generated by 'c++ -mMM'):
m.cm: m.cc t.cmi u.cmi
t.cm: t.cc u.cmi
u.cm: u.cc t.cmi
   c++ -mc $<

myprog: m.cm t.cm. u.cm
   c++ -ma m.cm -o myprog

Likely the rule for myprog can be as well generated – we don’t need the list of modules to be linked together, we just need the name of the main module and all deps will be there already, but make must know about them in order to update things the right way.

Ok, just to have an explanation what these options are, there would be a kinda hypothetical C++ compiler that can compile in modules. The following options are used for this c++ command (this is a complete list of options, some of them will be used in later examples – this includes also compiling “uninstrumented” source files, that is, those that do not use the module and export syntax):

  • -mc: create a module form file out of the source file. This is similar to gcc’s -c option that creates an object file.
  • -mi: create a module interface form file. There’s no sensible equivalent in gcc, maybe compiling a header file, which goes without specific options, but this option here is to be used for either header files directly, if the old source layout is in use, or export-instrumented source file. Also the closest equivalent of the module interface file is today the precompiled header file.
  • -ma: create an executable file out of the main module. This is similar to using gcc without build specific options when passing source or object files. Might be that the command line doesn’t need any option, but this is used here for making things clear.
  • -mheader is the option to specify the header file that is associated with the given source file in case when you compile an uninstrumented source file. This option is obligatory in this case, together with -mname
  • -mname allows to specify the module name for the currently compiled module. For uninstrumented sources this is obligatory, as there’s no other way to specify that name. For instrumented module sources this is optional to override the module name.
  • -mdepend: specify the dependent module interface files. This is only for a case when compiling an uninstrumented source file that has specified source dependencies using header files instead of module names (no matter whether by #include or by import), or when compiling a module interface file from a single header file. This is necessary to record a module dependency information in the compiled module form file.
  • -mroot: specify the directory that will be toplevel for the source files given by path. This directory defaults to the current directory, but this option allows to specify the base directory, relative to which the source paths should be. This is necessary when you compile instrumented sources and the default module name should use the file path pattern.

Now, why am I starting with this? Because we need to have a build system working with C++ units as modules (instead of *.o files) first before we even start thinking about the modules in the C++ syntax.

Ok, then, what exactly is the *.cm file and how much does it have to do with *.o file?

So, likely in today’s systems the *.cm file will have to be an archive file (ar theoretically can be used, but it is barely intended to contain anything else than *.o files – likely a tar file would be better, as long as all symbol information and all that the ar provides can be provided similar way) that contains the *.o file inside, and additionally the *.cmi file, and a kind of manifest file with dependencies and other information.

Now; the compiler can easily extract the dependency information (-mMM option) by reading the file’s import instructions. Then the module form files required for linkage are there in the manifest file in the *.cm file. In distinction to #include and even import with specifying header files, the import declarations specifying modules also don’t need to be read recursively – in-module dependencies can be read from the manifest files at the moment when needed.

Build system details: fixed directories and naming

It’s not that simple as it was before with simply *.o files that you could even give whatever names you want. This time it’s serious: the module name is bound with the module form filename and therefore also the directory of the project matters. This is because likely when you have source files placed in a directory, they will have to have directory path names of the modules. Of course, you can configure your build to have intermediate steps, compile all files in a single directory, bind them together, and then those intermediate files bind with other so created intermediate files. Or, you can build everything in one directory, just have the source files distributed throughout a specific directory tree. That’s why we need to decide something here – and that’s why this will already require specific source-to-module binding. Unlike *.o files, the name of the *.cm file matters because this is the name being used in the C++ source files with the import instruction.

We need then two directories to be defined – stating that we may also have shadow builds:

  • The project toplevel directory. This is the directory from which the source path starts for the sake of module naming. Defaults to CWD, can be overridden by -mroot.
  • The build target directory. This is the place where target files will be created as a result of compiling. Defaults to CWD, maybe some option could be used to override it (note that for *.o files you could simply override the output name by the -o option, and this could also include the path; with the module form file names the problem is that you might be able to override the path, but not the filename).

Therefore the most sensible rule for the default module name (that is, used when you have a module default; declaration inside) is the pathname as passed to the command line, either towards the CWD or towards the declared toplevel directory (-mroot option in the examples). Note that this toplevel directory might need to be always explicitly defined in case of shadow builds. So, this command line (stating that we have simply module default; declared inside):

c++ -mc ../common/utils/array.cc -mroot ..

will produce the file named common.utils.array.cm. And it will be accessible for importing under this name. Be careful here: the same exactly file may resolve to a separate module form file if compiled by the compiler using a different toplevel path. How the path to the source file is specified though it doesn’t matter – if it is an absolute path, it will be reshaped towards the toplevel directory, unless it is not directly available from the toplevel directory (without going uplevel), in which case the command reports an error.

The other way around: you may have an explicitly named module, so you have this declaration, for example:

module common.utils.array;

There are two good ways how to translate this into a module name: it could be common.utils.array.cm or common/utils/array.cm. There are various reasons to have the first or the second possibility, or even mixed. The compiler should allow to use either, or even allow to have a mixed form like common/utils.array.cm. Searching for these two alternatives shouldn’t be a problem.

Note though that if you name your module the above way, as common.utils.array, it will always have this name and will be always identifiable by this name, no matter where your source file is located towards the command’s toplevel directory (note that you can also compile a file with an explicit module name even if its path contains uplevel).

The use of partitions

If you saw the design of the C++20 modules, you saw also the idea of partitions. But there was, first, some feature in C++20 that I don’t think is worth saving, without partitions: you can have a single module split into single files. That’s rather a wrong approach, and partitions would be a method to cover that need, among others.

A module partition is defined in a single source file, but it contains definitions that will belong to the module. They cannot be nested and the only module that may import a partition is the partition’s master module. For example, we can have a module common.utils.array (master module) and separate parts can be defined in partitions named common.utils.array:static and common.utils.array:dynamic (note that one single source file must contain either a complete module or a complete partition).

The merit behind the partitions is to allow to split a single module into multiple source files, when splitting into smaller modules is impossible – like, for example, because you have a big class with a lot of methods, or you have a big class hierarchy out of which only one should be exposed as interface.

Every module that contains partitions should also have a “master source” for the module, which declares itself the name of the module and it should import also all partitions. The import declaration for the partition doesn’t exactly have the same meaning as importing foreign modules.

For other modules, it simply declares a dependency on that module. Partitions, however, are not dependencies on the master module – it’s the other way around. That’s why this only defines a binding, it’s a declaration that this partition is an integral part of the module. Partitions can as well be declared export import, in case when they provide their part of the interface. The interface for a partitioned module is a little bit more complicated.

The declarations provided in the master module are the base declarations for all other things in this module and all partitions. Therefore the first thing you do is to compile the “default interface” of the master module source. This interface is imported by default by every partition (that is, there’s assumed “import” for the master module in every partition). Additionally, partitions may even depend on one another by using import :another_partition;. Therefore compiling partition files requires also compiling interfaces of all partitions, and in case when there’s export import in one of them, also with the right order with regard of the dependencies. Then, when all interfaces are done, there’s an interface integrator call which binds all parts together.

As you have seen, the processing of the full partition name turns the : partition separator into the - separator in the filename. So, if you have a partition source file that declares module common.utils.array:static;, the compile command will produce the common.utils.array-static.cm form file. Note that if a source file has to contain a partition, the module name (with partition) must be this time defined explicitly (name deduction in case of partitions isn’t possible). The interface filename for the main part ofthe interface of the partitioned module has then -default suffix. So, summing up, with this setup, you have the following source files:

  • common/utils/array.cc – the master module source
  • common/utils/array-static.cc – the :static partition
  • common/utils/array-dynamic.cc – the :dynamic partition

Now we compile the interface in the following order:

  • common/utils/array.cc -> compile default interface to common.utils.array-default.cmi (this happens always when the compiler has detected at least one partition import inside in a module with no partition name)
  • common/utils/array-static.cc -> compile to common.utils.array-static.cmi dependent on the one above
  • common/utils/array-dynamic.cc -> compile to common.utils.array-dynamic.cmi like above
  • Then call the integrator for all these above *.cmi files to produce common.utils.array.cmi

Note also that the interface contains both the private and exported part. The private part can be accessed only by the module source file from which it comes, and its partitions. Partitions have automatically access to the private and exported interface of the master module file.

Compiling the implementation then simply requires the integrated interface and all dependent interfaces, as usual (for all source files – the master module file and partition source files). Compiling and integrating all partial interfaces first is required for a case when there are interface dependencies.

Local modules

That’s one of many things that likely were forgotten by the designers of C++20 modules.

As you know, with #include directive, you could pass the argument as <file.h> to be searched globally and "file.h" to be searched locally (though with fallback to global). That distinction not always makes sense, but at least for visibility it is often required, at least to mark that particular header file is a file from the current project, not from some external library. Maybe not every project makes this distinction correctly, some others don’t at all – but still, it’s needed, and the lack of this feature may also make programmers stick to includes. Note also that this distinction defined in the C language (already) was likely not thought of as separating a project and the external libraries (mainly it was about separating the headers of the system libraries and the C standard library from everything else), but in today software development it seems to be quite important.

The sensible solution for it would be to use the leading dot in the name. If you use it, it’s local, otherwise it’s global. There are theoretically also other solutions possible, like marking only global ones with double dot (to look like something similar to uplevel), but then you’d have to use it also as import ..std.iostream, which doesn’t look good. A single dot – which reminds the “current directory” in POSIX – should be well understood as “module from the current project”.

Note though an important difference to #include "file.h" – the local path to the header file here is the relative path towards the source file being compiled, which means that you can use the path as your system allows it, even multiple uplevel path specifications. In the module system this isn’t possible – that’s why this toplevel directory is needed for the command line.

So, if you do import .common.utils.array; then it means that the form file should be searched in the build target directory as common.utils.array.cm file (plus combinations with path-separator). If you do import gnome.gtk.widgets; – it will then search the form file in the installation directory for library interfaces, either something like /usr/include and other standard paths, or specified with something similar to -I option.

Whether the module form files for a local module import declaration are to be searched also in the global path (which is the case of #include "file.h"), or exclusively in the local project path, it’s further to be decided, as this should be well thought through, but I personally see no reason for it. If you declare the local path, you want it to be the part of your project and not to be provided otherwise by some external library. Conversely, if you want this to be provided by the external library, you might at best want that it be provided in one of the “external directories”, including your private project’s directories, just added to this list. That’s the most sensible naming control practice.

By this opportunity, let me remind you that many developers are using #include "file.h" syntax even though the actual result would be that this file.h isn’t found in the same directory as the file including it, so the compiler will fallback to global search, including the directories specified with -I option (this is actually quite a popular technique, especially when you keep header files in a directory separate from implementation files). This makes it no different to #include <file.h>, but programmers like to use this syntax just to make it explicit that what is meant here is the file from the local project, just located in some other directory, so people wanted to have a shortcut to #include "../../include/file.h". This is actually a bad practice (I can tell you a lot how often I’ve been untangling long lists of include directory specifications when the #include "common.h" directive has picked up the wrong one out of about 7 various completely different common.h files in the same project), but then programmers often need this distinction, even if this is visual only. That’s why the syntax import .localmod; that refers to a module form file that should exist in the build directory where the compiler is compiling your file, as a distinction from the external library (including the C++ standard library), will be strongly desired.

By the local modules feature there’s one more concern: inside a project you might have various different directories where you have smaller “group” of files, and then you have some bigger parts that rely on them. You could make these parts separate libraries (some project do it this way), but if this isn’t something required to be replaced in runtime or by single installation upgrade, it’s not worth a shot. It also wouldn’t be a good idea that a whole project have to be compiled in a single directory. We need then, for a compiling command line, one directory where it should store currently compiled modules (and it is by default one of local module directories), but you should be able to specify additionally extra local module directories. I know, so far in the compilers there was only one -I option for header files and it was only to extend the list of global paths, but I think – especially that module names have limitations – there should be also a separate option to extend local module path as well as global module path. Still the same idea: local modules are those that are in the current project, global modules are outside of the current project. This is important because limitations of this so far was forcing projects to split into single libraries also within the frames of one application.

There’s also one more merit to distinguish local and global modules: not every module is to be used publicly by the library user. A library, which is to be used by other projects through importing modules, would like to expose only several distinct modules as public ones, and only those should be visible outside the library as those that could be imported. Only within a single project should all modules be accessible for importing. Of course, there’s always a question: could this be “hacked” if needed – that is, can I use private modules from a library because my project needs them? No problem with this – all you have to do is to compile the dependent project the way that allows you to reach out its modules as local ones, and then add the directory where they are accessible to the list of private module directory – this way you will still be able to import them, of course, as local modules.

That’s why specifically for the libraries you need to mark modules that should contain the public interface as public, that is:

public module gnome.gtk.widgets;

Note that a public module cannot re-export non-public modules, although it can obviously import any other module. Such a module will be then compiled into a file named gnome.gtk.widgets-public.cmi. Then, when compiling a library – no matter if it is in the form of one complete library file and a bunch of interface files, or with every module form file provided directly – this interface file will be provided as the only accessible one.

Alternatively you can declare the module normally, just selected entities would be then exported publicly by using public export instead of just export. The public module declaration simply applies public to every exported entity.

The general module syntax

The module syntax in general isn’t going to change much towards what is defined in C++20, although there are some distinct changes. Optional parts are surrounded by ?question marks? like this.

This is the general structure:

module; // optional: Global Module Fragment
...
... (only preprocessor directives directly used)
... (definitions provided here stored on the local files' database)
...
?public? module ModuleName; // starts import section
... (import section)
...
... (contents - up to the end of file)

Explanations for this fragment:

The module; declaration, if GMF is present, must be the very first declaration in the file, possibly except comments. If GMF is not used, then module <name>; must be the first declaration, otherwise it ends the GMF section and starts the import section.

The import section starts after the named module declaration and ends with the first declaration that isn’t import. Since that point, no other import declarations are allowed for the rest of the file.

The named module declaration may have a form of module default; in which case the name of the module is defined by the compiler (the compiler may also reject this request). The named module declaration may be added the public keyword, which makes that it will be accessible through the non-dotted import request.

The import declaration can have the following forms:

import <filename>; // parse the "filename" like in include and attach declarations
import "filename"; // like above, but first search in the same directory
import ModuleName; // import the interface declarations for the source file
export import ModuleName; // import the interface declarations to the interface of this source file

The import instruction with the filename argument may be used without having the module section in the same file, but it is required that the module declaration is in the beginning of the parsed source file, although it may be on any global level also between other toplevel declarations. More practically, the import instruction with the filename argument may be contained in a header file. It does merely the same thing as #include, except that it works in a separate environment, that is, declarations provided in this file will be accessible for the source file that declares this import, also recursively.

The import instruction with the module name can be placed exclusively in the import section. If the export declaration is present, then it creates an interface dependency, otherwise only the implementation is dependent on that imported interface. Note that the export-import must be done in case when exported declarations create parts of the interface dependent on parts of the imported interface (there are strict rules in which case what declarations are part of the interface).

In the module declared as export you can mark various entities as export and this way make them part of the interface. There are several rules how it is done.

  1. The namespace declaration is level-transparent, that is, it only defines the namespace for the contained declarations, while namespaces themselves cannot be exported (that is, you can use export namespace NAME ... statements, but this only makes all contained entities exported). Unnamed namespaces also cannot contain exported declarations. Note that declarations in unnamed namespaces (just like static) are not visible outside the same file, even for other partitions of the same module.
  2. Type names declared using typedef or announced (with e.g. struct MyType;) become part of the interface if they are used anywhere in the interface. Otherwise they can be used if they are explicitly marked export. This concerns also complete types provided by interfaces of other modules that are not export-imported. If these types cannot be used as incomplete in the interface, an error is reported.
  3. Normal functions (with no special storage class, or extern by default), if marked export, have their function signature only declared a part of the interface (not the body). Functions declared with inline are whole part of the interface (together with the body).
  4. Global variables that are exported will be visible with an incomplete declaration of their type. If they are initialized with an initialization expression, this expression will not be a part of the interface. The type of this variable must be explicitly provided in the module that would like to use it, but it’s not necessary to be imported if this global variable is not used.
  5. Complete types (struct/class/enum) can be marked export and this way they become a part of the interface as a whole. Although two new features can be considered:
    • Normally a method defined inside the class is treated as inline. If you declare a method extern, then it will be just like defined outside the class (that is, the body will not be a part of the interface, even if defined inside the class). You can still define the method outside the class (the old way) with the same effect.
    • If you declare the whole class extern, then it will form something like a “pimple pattern”. Every method in such a class will be extern (that is, with only the declaration being part of the interface), and all fields and derived classes must be private. Friends are still allowed, but even for friended classes and functions there’s no access to fields. Special fields must be marked extern to be present in public or protected section or accessible for friends; those are reached out using special accessors that do not rely on the structure offset and can survive changes in the class. In extern classes all exported names are part of the interface, but not the class layout and therefore you can’t do sizeof on such a class, for example.
  6. The preprocessor macros can be exported into the interface. This is accessed through #export directive used either as a replacement for #define or with the syntax of #export (name1, name2...) to declare export for existing symbols.

Free ordering and open classes

Just before we pass on to the smooth transition rules, let’s show also additional opportunities that the modules, defined in one single file without separate header files, and importing (not including) other modules, give us.

The module system provides a unique opportunity to free yourself from the order of definitions. It’s always been annoying in C++ that you have to provide the function signature (which is a repeated the same definition that must be kept in sync with the one in the function definition) before the code that calls it, just to be able to place this function after this code, or reordering the functions’ definitions just to avoid doing it.

Imagine then that you don’t have any #include in your source file, so your source file is plain, reaches out to the other files’ interfaces through import and your file contains only its own entity definitions. Imagine then that the compiler may go multi-pass, where one pass only reads the signatures of the functions, or if you have a class, it reads the class’s contents, derived classes, fields, and method headers, but not method bodies (including initialization expressions for global variables and in-class fields). That’s actually what the compiler has to do when compiling in the interface mode.

If the compiler can do it this way, there’s no need to preserve the order of declarations. That is, you don’t have to extract functions’ signatures into function declarations just to paste it before a function that calls it. Go simply:

module default;
import std.threads;
import std.functional;
import .mainapp;

int main()
{
     start(mainapp::startup);
     return mainapp::loop();
}

void start(std::function<void()> fn)
{
    ::mainthr = std::thread(fn);
}

std::thread mainthr;

This way you are free from any ordering. This should be the rule after the module <name>; declaration, let’s say you can add some extra things before module (in the global module fragment) and there the order matters. But, after the module declaration, all signatures are read separately from bodies, so you don’t have to have function declarations at all, even forwarding declarations. Even if you have a global variable, or even a constant, their name and type will be read and remembered in the first pass, then only the second pass will read their initialization expressions. All that is required for the compiler is that by the syntax it must be able to distinguish the “alleged” (because it’s not yet defined) type name and object name – and the variable declaration should suffice for this distinction (except the infamous case of X Y( Z() );declaration, but that’s to be separately taken care of).

Note of course that not every declaration is possible to be unordered. That’s because the C++ syntax relies on the main qualification of a symbol, whether it is:

  • an unknown symbol (doesn’t exist in the database yet)
  • a type
  • an object
  • a template

So, declaring a variable of a type, which’s declaration will only be provided later, is possible. There are 3 passes actually for reading the entities from the source file:

  1. Forward declarations (type names, headers for type templates, global variable declarations)
  2. Type declarations (function headers, type definitions without method bodies)
  3. Function bodies and global variable full definitions

So, if we have a variable, it requires the type declaration. When we have its incomplete type name, we can declare the extern variable, and that suffices for the variable declaration. Then we have type declarations, so we can then have the variable’s full definition (which is a variable without modifiers, a variable with extern and initialization expression, or a static variable).

This may go even further: open classes. That is, you can declare additional methods for a class without having it prematurely declared in the class, as long as they are declared in the same module as the class. But that’s something that can be added as a new feature, I’m mentioning it here that it might be possible this way.

Smooth transition

And now we have the most important part: we need a method to provide a smooth transition from the current “C modules” style into the C++ module style. That’s why the first thing to do was to define the sensible rules of the build system for C++ using modules. In this system, every source file compiles into a module or a module partition, no matter if the specific module syntax has been used in the source files or not. The sources in the current form with having separate header files were being referred to before as “uninstrumented” sources.

Why is this smooth transition needed and important?

Ok, that’s kinda pathetic, but I feel that I need to explain several things to the people who were designing the modules for C++20.

We are today in a situation that rarely anything in C++ is created from scratch – even if you skip system and standard libraries. The code is being widely reused, and every software company has lots of legacy C++ code and switching to another language is not easy and not always possible.

The C++20 modules design, as defined by the ISO standard, offers completely no possibility for a smooth transition (or, at best, gives this thing up to the compiler designers, while those seem to have completely no idea how to do it). You would have to translate every file in the project to the new form, nothing can be done partially or as shareable with older standards – once switched, there’s no going back. And that’s the problem. Because stating what I said in the previous paragraph, a possibility for a smooth transition is crucial to adoption of C++ modules. Either this is provided, or C++20 modules will be at best used by some maniacs, and will never reach the software business.

The very first thing that would have to be done is to define the new build system. That’s why I started with the build rules using the modules already in the C++ syntax, but now it should be adopted for existing files of the C++ projects that have no C++20 modules syntax in them.

This is a huge task for the high level build systems – such as Autotools, Cmake, or my own project, Silvercat. These systems should offer you just adding a single option to your project definition and take the source files as they were there before, then generate appropriate command lines to produce the intermediate files in the module style.

The first thing you need to do is to be able to provide this new build system also for old sources. So, we had the following instructions in our first example:

c++ -mi t.cc  #> produces: t.cmi
c++ -mi u.cc  #> produces: u.cmi
c++ -mc m.cc  #> produces m.cm; requires t.cmi and u.cmi
c++ -mc t.cc  #> produces t.cm; requires u.cmi
c++ -mc u.cc  #> produces u.cm; requires t.cmi
c++ -ma m.cm -o myprog  #> produces executable myprog

While having instrumented sources. Let’s say we have now uninstrumented sources provided as implementation and header files:

t.cc t.h
u.cc u.h
m.cc

The following instructions should be used to compile them:

c++ -mi -mheader t.h -mname t
c++ -mi -mheader u.h -mname u
c++ -mc m.cc -mname m -mdepend t -mdepend u
c++ -mc t.cc -mheader t.h -mname t -mdepend u
c++ -mc u.cc -mheader u.h -mname u -mdepend t
c++ -ma m.cm -o myprog

Note that the last instruction hasn’t changed. This is because it works on module form files already, and those should be completed just like from the instrumented source files.

Of course it doesn’t look very good especially that you need to mention the module name and also the dependencies. Unfortunately the compiler won’t be able to autodetect dependencies on modules when the interface is being imported as a file, no matter if you use #include or import for it. Only when you use import with the module name can this dependency be autodetected and only then will the -mdepend option be superfluous.

Note also that there should be a possibility to supply multiple dependencies, so the syntax allowed here should be like with -Wl option: either multiple arguments separated by comma, or one argument at a time and multiple single-argument instances of the option are allowed (the latter is used in the above example). For the sake of makefile the second one is actually more comfortable because replacement of a space with comma is, although possible, kinda complicated.

Mixed sources

This build mode for uninstrumented sources will have to be available actually forever. That’s not only because this form is required to be used during the transition. Also in lots of projects there are cases of sharing the source code between projects, of which one must stay with an older standard, and simultaneously we’d like to make use of it in our project, written in the C++ module style.

Hence you should be able to tolerate “traditional” C++ files, having their own interface in the header file, with #include for other header files, which must stay this way, while we want it to fit in the build system with modules.

Let’s try then discuss the smooth transition step by step.

Step 0: Source shaping

You should simply think of single implementation files like single modules, in several cases you might resolve to having one module in multiple files (partitions). So, in the “C modules” system we can have in the source files shaped only as the following cases:

  • A single implementation file (to become a single module) and its header file.
  • Multiple implementation files having one common header file. Note: if you have something like that you really have logically different parts (with few common interfaces) in different implementation files, while just having “a common header file for all”, you better split this one common header file into smaller parts and extract only the common part for all of them to be a common interface file.
  • A single header file without an implementation file (“header only”).
  • A single implementation file without any interface (usually the file with main() function).

If your project contains any differently shaped sources, this must be reworked to fit in these explicit layouts. This is the first thing to do, as in order to switch your project to modules, you have to start “thinking modules”. So you have to have idea, how to assign particular files to modules and define this assignment.

Once this is ready, you can switch to the new building rules.

Step 1: New building rules

I wanted to have some example project – it’s hard to find anything that is in the middle between completely simple and unimaginably complicated, so I finally resolved to the https://github.com/JanSimek/voice-over-lan project that I found on Github.

In this project we have quite a simple structure and a build defined in qmake. When you take a look at this project, you can see that it has a structure very easy to translate – the main.cpp file with main() function and then all files split into implementation and header file. So, for Makefile we’d have the following rules:

QTPKG := QtCore QtGui QtWidgets QtMultimedia

QTHEADERS := `pkg-config --cflags $(QTPKG)`
QTLIBS := `pkg-config --libs $(QTPKG)`

# Compile header files into module interface files. Module names
# are taken explicitly from the file names. Note that we don't
# compile interface for main.cpp - nothing is dependent on it.
voiceio.cmi: voiceio.h 
voicesocket.cmi: voicesocket.h
buffer.cmi: buffer.h
messenger.cmi: messenger.h buffer.cmi voiceio.cmi voicesocket.cmi
%.cmi: %.h
    c++ -mi $< -mname $(basename $<) $(QTHEADERS) $(addprefix -mdepend ,$^)

main.cm: main.cpp messenger.cmi  #<<< 'messenger.cmi' as identified by header 'messenger.h'
    c++ -mc main.cpp -mname main -mdepend messenger.cmi $(QTHEADERS)

# General scheme for modules without dependencies and matching a simple name scheme
%.cm: %.cpp %.h
    c++ -mc $< -mheader $(basename $<).h -mname $(basename $<) $(QTHEADERS)
# This takes ^source    ^its header file        ^module name to be given to this file

messenger.cm: messenger.cpp buffer.cmi voiceio.cmi voicesocket.cmi
   c++ -mc messenger.cpp -mheader messenger.h -mname messenger $(addprefix -mdepend ,$(filter-out $<,$^))  $(QTHEADERS)
# You need -mdepend option because messenger.cpp still uses #include with a header file

# Application executable
QtIntercom: main.cm voiceio.cm voicesocket.cm buffer.cm messenger.cm
   c++ -ma -o QtIntercom $^ $(QTLIBS)


Note one important thing here: these rules cannot be anyhow generated. The definition of the modules in this form is ephemeric – they exist only in the build file and this isn’t known to the source files at all.

And that’s it for now. This build system should work just as well as the traditional one. Actually I had the high level build definition in qmake, but it was easy to prepare the right structure with make, while the right header/libs options can be provided from pkg-config. What is important is that here you have the whole structure defined just as well with the structure of modules without using module declarations explicitly in the code. This is the first step and the build definition may actually stay the same all the time, until you get rid of all the header files finally. Actually it doesn’t disturb that, for example, -mdepend is still in use, it will be simply superfluous in the future, although likely if you, for example, turn messenger.cpp and messenger.h into a single messenger.cpp file, you’d have to change this build rule as well. High level build systems would have to add some special feature to provide in-build module declarations using the source and header file, for every module, just to be blocked systematically for every module converted to a single-source.

Ok, but then let’s explain how this still matches the whole theory of modules. After all, in the module definitions we had the export keyword to mark things to be visible outside, we had the export import variant of the import to mark that things that are exported intermediately, but now we have all these things without declaration. How does this work in this intermediate form?

That’s where the -mheader option comes in. Everything that is in the file that you declare as -mheader in this compiling command is being declared as an interface for the module, which’s name is given in -mname option. This way, everything that this header file declares, is exported. This, obviously, limits the decisiveness, which parts you should be able to export, but then, the visibility of the public parts is still the same as it was with the C-modules style.

Of course, such a header file can as well include another header file – but then, this cannot really be tracked. A dependency like this should be defined by a dependency on a module interface form file, which is only a definition in the build system. If you add any local module dependency by adding include of a local header file, you have to manually update the module interface form file dependency. Fortunately, this will be way less troublesome once you switch to real modules.

Step 2: get rid of #include

We need to replace now every occurrence of #include with import. As per definition in the C++20 modules, import can also take an argument identical as the one for #include and with the same meaning. Also the #include directive with a local path take the path towards the source file being compiled, so you can freely move the toplevel directory as you need in the build definition – only in a case when you move the source file to another location there would be a need to fix the include path. Thanks to that you can prepare the toplevel paths in the build definition as you need.

Note also that you can freely mix #include and import, but #include should not be allowed after the module <name/default>; declaration (that’s why you have the global module fragment started with module; statement). That means, you should fix any cases when you do #include into an implementation file somewhere in the middle, have moved some set of functions to be in the other file, but compiled together with the implementation file (I often saw it as *.inl file). This thing would have to be solved somehow, although the partition feature should be a good enough replacement for such cases. In effect, you should simply translate every #include into import, and leave #include (in the GMF) only if you absolutely have to.

Here we have then the beginning of the voiceio.cpp file:

#include "voiceio.h"

#include <QAudio>
#include <QAudioInput>
#include <QAudioOutput>

#include <QDebug>

VoiceIO::VoiceIO(QObject *parent) : QObject(parent)
{    
    QAudioFormat format;
...

Now we simply change #include to import and nothing more for now.

module default;

import "voiceio.h";

import <QAudio>;
import <QAudioInput>;
import <QAudioOutput>;

import <QDebug>;

VoiceIO::VoiceIO(QObject *parent) : QObject(parent)
{    
    QAudioFormat format;

Why is this step important? Because the project file may unconsciously use so-called “implicit inclusions”, that is, the compiler doesn’t complain about any undefined, but used, entity in a particular header file only because they were included from another header file in the same implementation file earlier. The import instruction, however, doesn’t work this way. Every imported file is being compiled separately in the “default environment” (meaning, having particular preprocessor macros defined) and the resulted database is incorporated into the file that declares import. That is then a good opportunity to get rid of these bad practices. Note that the macroguards in the header files will not be taken properly, as a header file will be working without having any macros defined – but the macroguards will not be necessary anyway, as with import it’s also taken care that the same file imported multiple times in a step will resolve to the very first import. Here also note that it’s an opportunity to get rid of yet another bad practice – including the same file by specifying different paths, even by other header files. No problem if you are referring to a file using a different relative path (because the path will be always recorded as absolute, and with symbolic links resolved), but the problem could be if you take the file with the same name, actually it should resolve to a different path.

So, this step should be quite easy to do, and after that you should recompile the whole project and fix any possible errors that arise from any messup with includes.

Note that this time you need the module declaration in the beginning of the file. This is necessary before any import instruction can be added.

Just a side note – I know that the early implementation of the C++20 modules in gcc requires it to “precompile” particular files explicitly and make the resulting file (*.gcm) available, otherwise even a stupid import <iostream>; won’t work. That’s a wrong approach. The compiler should do exactly the same thing as it did with #include and the only different thing should be that it should be compiled in separation. If any “compiled version of the header” is required, the compiler should take care of it on its own, as it earlier did with the “precompiled headers” feature. If not possible, it should simply grab the raw text file and process it as before, just in the separated environment.

Note that also likely some of the includes will have to stay as they are in this form; if the Qt library, which is used here, isn’t provided with the modules (and that’s a separate large topic that will be taken up later), then the only way to use it would be to use its original header files, so this like import <QAudio>; is likely here to stay for at least longer time, if not forever. Not even mentioning C libraries – hardly anyone would like to provide a special wrapper with C++ modules for them.

Step 3: Translate the module imports

Now that everything is still compiling correctly with import using the header file, let’s change the imports to the module name, using the name that is given to the module in the command line (at least for now). Reminder: with the current build definition, you already compile the project in modules, which means, module form files are produced, and if so, they can be also imported as modules.

Note: you can’t yet remove “importing your own interface” in the implementation files. We are about to change imports that require interfaces of other modules.

In our project we have a kinda unusual situation: a header file includes other header files. We could be not always sure if the intention was to “use” the interface or “reexport” it – but by including a file you always do the second one, so let’s resolve to it and this can always be fixed later. Here’s then the beginning of the messenger.h file:

#ifndef MESSENGER_H
#define MESSENGER_H // keep the macroguard until getting rid of H completely.

import <QUdpSocket>;

import <QAudio>;
import <QAudioInput>;
import <QAudioOutput>;

import <QDebug>;

export import .buffer;
export import .voiceio;
export import .voicesocket;

class Messenger : public QObject
...

Note that even though we don’t have a module declaration file, this is still a header file to be imported into an implementation file, which already has the module declaration. Header files may be imported also by other header files, but even if so, they are at the top level imported from an implementation file, and there the module declaration must be provided.

Note also that we have imported some local names as modules even though they don’t use the module syntax yet. That’s also not a problem. We have the module names given at the compiling command using the -mname option and then the compiler should reach out for the module interface file through the local names in the import instruction.

Note that there still shouldn’t be a problem with replacing the import declaration with the module names only partially or only in several files. Moreover, it will be much more complicated to switch the sources into the module form. Therefore it would be even recommended that you change the import form into the module name for only those modules that you plan to switch to single-source in the first shot.

Step 4: Switch “uninstrumented” module sources to single-source form (first for the least dependent or independent modules).

Ok, as the messenger module in this project seems to be short enough so that I can give it as an example, let me paste here the complete source file that would be the resulting messenger.cpp file after transforming it to the single (“instrumented”) source.

module messenger;

import <QUdpSocket>;

import <QAudio>;
import <QAudioInput>;
import <QAudioOutput>;

import <QDebug>;

import .buffer;
import .voiceio;
import .voicesocket;

export class Messenger : public QObject
{
    Q_OBJECT
public:
    explicit Messenger(QString address, QObject *parent = 0);

signals:

public slots:

private:
    QUdpSocket _udp;

    // Voice
    VoiceIO* vio;
    VoiceSocket* vso;
    Buffer* buf1;
    Buffer* buf2;
};

Messenger::Messenger(QString address, QObject *parent) : QObject(parent)
{
    quint16 buffersize = 0;
    buf1 = new Buffer(buffersize);
    buf2 = new Buffer(buffersize);

    vso = new VoiceSocket();
    vio = new VoiceIO();

    if(address != "")
    {
        vso->connectToHost(QHostAddress(address), 30011); // QHostAddress::LocalHost
        qDebug() << "Connecting to " << address;
    }
    else
    {
        qDebug() << "No peer address specified. Will only play sound from others";
    }

    vso->setEnabled(true);
    vso->startListen();

    // Voice in
    connect(vio,  SIGNAL(readVoice(QByteArray)), buf1, SLOT(input(QByteArray)));
    connect(buf1, SIGNAL(output(QByteArray)),    vso,  SLOT(writeData(QByteArray)));

    // Voice out
    connect(vso,  SIGNAL(readData(QByteArray)),  buf2, SLOT(input(QByteArray)));
    connect(buf2, SIGNAL(output(QByteArray)), vio, SLOT(writeVoice(QByteArray)));
}

Note one important thing here. It’s just a pasted header and implementation file; the definition of the method is still separate from the class, instead of being defined inside the class. That shouldn’t be a problem – you should be able to use either, or even use open classes, as I described earlier.

OTOH we should be able to declare even long methods inside the class. That would require a change in C++, which should allow functions defined inside the class be “external” – for example, by using the extern modifier. Actually inline functions are not just a hint for the compiler to expand them instead of calling, but this also declares the whole body to be a part of the interface. This is currently the only way how this expansion can work because in the current form of the object files inline expansion is not possible for the external functions.

There’s one more special focus here. In the earlier header file, messenger.h, we had the other interfaces used by e.g. export import .buffer, but now we have just import .buffer. This causes that the interface file for the messenger module will not reexport interfaces for buffer, voiceio and voicesocket. Yes, but that’s actually not necessary. Let’s show now the form of the main.cpp file translated into the module form:

module main;

import <QCoreApplication>;
import <QCommandLineParser>;

import .messenger;

export int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    a.setApplicationName("voice-over-lan");
    a.setApplicationVersion("0.1");

    QCommandLineParser parser;
    parser.setApplicationDescription("Voice over LAN");
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument("address", QCoreApplication::translate("main", "Address of the counterpart"));

    parser.process(a);

    QString address("");
    if(!parser.positionalArguments().isEmpty())
    {
        address = parser.positionalArguments().at(0);
    }

    Messenger msgr(address);

    return a.exec();
}

So, was that export import really necessary? Looxlike no. The only part of the messenger module being used in the main module is the Messenger class, so the main module will need the interface of the messenger module and so with linkage, but all other things that this class is using need not be visible. There would be another thing if, for example, this class defined any method in the public interface that uses any types defined in these dependent modules, and the use of the interface of this class required to use a full definition of this type (that is, if it was using just a pointer or reference to this type, which requires only an incomplete type definition, it is still not necessary). But that’s not the case here. If we had hypothetically here any Messenger class public method, which has, for example the const VoiceSocket& parameter, this still doesn’t make it necessary that the messenger module do export import .voicesocket. The module that is using the Messanger class may not even have a need to call this method. However, if it does, and somehow must create the object of the VoiceSocket class in order to be able to call this method, then this module must – independently on the messenger module – do import .voicesocket on its own. On the other hand, if there’s any inline method defined in the class, which uses details of given type, then this class must also reexport the module that defines this type.

As for Qt library itself, there could be another concern – the Qt library has additionally a special generator that generates extra files for implementing things marked in the class by Q_OBJECT and signals markers. That shouldn’t be a big problem in this case – this required previously a header file so that the class definition can be extracted from it, this time it will be the whole module source file. This will likely have to be made a module partition and declared the name in the command line, until the moc generator will get an option to create the source as a module partition.

Problems and the environment

There’s one thing you likely won’t be able to change in the C++ development. This is so-called “environment”.

It’s simply the set of macrodefinitions that are known before parsing the C++ source file first by the preprocessor. Some of them are defined by the compiler internally. Others can be provided in the command line (like with e.g. -DENABLE_LOGGING you provide a macro named ENABLE_LOGGING with the value 1). Additionally, the current form of the preprocessor allows them also to be defined explicitly before the #include directive so that this macro is intentionally visible inside. There’s an infamous example of stdint.h header file that requires that a user do #define __STDC_FORMAT_MACROS before including so that particular part is defined; fortunately the C++ standard didn’t adopt this method, but you can guess that this feature is still largely used in commercial projects, although mostly by using the command line (that is, a header file has declarations based on a condition check of a macro that would be provided in the command line). It can’t be simply said “sorry, not supported, and no replacement is available” because this way this project will simply stay with pure #include.

A different environment used for compiling particular source file may mean a different form of the intermediate file created out of it, as the preprocessor may cause the raw C++ file to be completed differently. That includes the sole C++ syntax. And macros are there everywhere, including the C++ standard library, which also largely relies on the underlying C headers from system libraries.

This simply means that the module interface form files (*.cmi in examples) cannot be a complete replacement for header files – they can replace header files only within the current build environment. Can be also worse – the header files in the current form may be also parametrized by changing the environment before including, or even worse, the same header file configured with a different environment (as included in different implementation files) – either through definitions before including, or by command-line macros – may result in a different “preprocessed text” of that file in different files compiled in the same build environment. That might also render the precompiled headers feature not to work properly.

By this reason, if the module system should be able to go anywhere beyond the current project (that is, when it should be used in the library distribution), we need some form that could look like the header file before preprocessing. Note that the normal workflow for having a header file finally into the code (let’s say, for example, you have an inline function defined in the header) is:

Header source file | preprocess -> preprocessed file | compile -> compiled db | link -> exec

How to place the module form files here? Currently the only sensible method is:

Header source file | preprocess -> preprocessed file | precompile -> precompiled db | link

And this precompiled form can be available as interface. The problem is, it’s preprocessed already. While what we need is something that can be called “a module template form file” (MTFF). Here “template” means that it’s something to be instantiated through the preprocessor macros. So that it can be used this way:

Header source file | templatize -> MTFF | compile -> compiled templated db | preprocess ->…

How to achieve it? Well, it’s not exactly important how to create them, but how to use them, how to incorporate them into the whole application-library system. If a compiler has a problem with preparing something being a “precompiled, but not preprocessed” header file, it can simply resolve to providing an original header file for it, including by generating a header file (by completing it from the exported definitions in a module source file) in case when you already have a single-source form. Then this header file will be simply raw included in the module template form file.

How can I imagine such a thing to exist – a form that has passed compiling, but needs to be run through the preprocessor to resolve to the final linkable form? That’s not impossible, at least I can imagine it as running first through the preprocessor, but not the usual one. A special one is needed, which will also parse the C++ entities, and will not just “resolve” macros in place, but instead generate alternatives. How?

That’s not simple. Definitely it would have to start with grabbing all preprocessor symbols used in conditionals, just to have them in the database. Then walk through the file again to find those macros that are being set in this file (these might be wanted to be exported) and those that are later undefined (these are not exported) – both these are considered not external. Then you need to take every case of a conditional basing on the external macros from its beginning to its end and check if they are inside a declared entity, or on the toplevel. Those on the toplevel will simply declare possibly different entities (note that a namespace declaration is not an entity – it’s a range declaration, although it can also be conditional). If you have the preprocessor conditional inside the entity, then you need to find the beginning and the end of an entity, by probing the version with various macro combinations, and if all result in having a complete entity, build an expression of all macros used inside the entity and build the form of an entity for every combination. Then, of course, all forms of this entity must be compiled. The specification can be as fine-grained as the compiler developers find it possible and sensible. Of course, beside conditionals, there will be also macros that would be resolved inside – this must be also done, and if there are multiple possibilities how a macro will be resolved, every one of them must have its own version. Note btw. that many new errors might be detected during that process, which were missed during the use of that gridded header file, as some combinations were never tried.

And such an interface file should be able to be created so that it can be attached to the library.

Object files and libraries

And here is one of the biggest problems, partially hooked up with the templates and the infamous “export template” feature from C++03.

The object files, as they were defined earlier for the C language, cannot hold any form of templates. They can’t also hold classes, structures, function signatures, and even constants, unless they are kept as variable and maybe the particular platform features marking them as constants.

It’s completely not a problem if you compile everything statically, even if you make a library. You can define a completely new format, which will allow to keep also entities like classes, templates, compile-time constants, and having a module form file that would be used simultaneously as an object file to be linked, and an interface file. Also, you don’t have to worry about upgrades, nor even variants – when you have a newer version of a library, your dependent application would have to be recompiled anyway, in order to take advantage from the upgrade.

The biggest problem here will be with shared libraries. And it’s not possible to simply move all C++ features into the world of shared libraries. At least in the very beginning you’d have to agree that simply only several types of entities are allowed to be “shareable”. Others can be only dependent statically, which means, that if your application is using a shared library, it can only use the next version of a shared library from the predefined library compatibility line and correct variant, and of course not all features may undergo shared upgrade. For example, all publicly used structures must stay the same throughout the whole compatibility line, you can at best modify the code inside the function that operates on it. In case of a structure, you can at best change a name of a field, if it was declared as not being in use (kinda stub or something), but it must remain at the same position and with the same type. This is a problem known as “ABI compatibility” and it’s a big problem in the development today, about which the C++ standard doesn’t care. Moreover, the known “pimple” pattern (by making the class that is the real API have only one field that is a pointer to some internally defined class, and all methods are then defined in the implementation file, and only those will see the true fields of this class) was one of the methods to not only avoid the needs of recompiling, when changing the structure of the class, but make also the class flexible for any internal changes. In a “pimple class” all you must preserve throughout the whole compatibility line are existing methods. In a true class, you are only allowed to add new methods, everything else, especially fields and their order, must be preserved.

Lots has been written and said about the ABI compatibility. Most of these things have come into light during development – I remember there was some guideline created by the KDE developers instructing them what exactly changes are allowed and safe to do to avoid problems related to ABI compatibility. Because the problem isn’t that these compatibility rules aren’t enforced or granted – the problem is that the current software management tools do not give any possibility to take care of the ABI compatibility. At least I saw something in the MacOS system, but actually this problem is much bigger in C++ than in C. The C++ modules feature is a unique opportunity to take care of this problem. If you have a module form file from the old version of the library, there should exist a method to do automatic ABI compatibility check – that is, something that simulates the old compiled application to be used together with the upgraded version of the library. That should be doable, as long as the module form file contains enough information to perform that check. That’s why module form files are superior to object files, just because they do contain this information that would be otherwise wiped out in the library (actually it doesn’t matter if static or dynamic because both base on object files).

Modules in the service of libraries

Modules might still be useless, if we can’t find a way how to make our project use an external library still by importing modules and take all advantages from them. But to allow this, we can’t distribute libraries exactly the same way as before, that is, with header files and *.a and *.so files that will be then referred to by -l option.

Let’s imagine then first that we’d like to distribute a static library – this will be simpler and more general as development package.

We need to distinguish first the module importing method for modules within one project and importing modules from a foreign library – within the source project of the library. We can have interfaces for modules inside the project, but these are kinda “private interfaces” – which sounds maybe kinda ridiculous, but what is meant here is that these are interfaces and modules used in the project, but not to be exposed for the library user, which part is a “public interface”.

And also don’t forget the final form – we want to have everything defined directly in the source implementation file and only have marked particular functions or types that they will be a part of a public interface, while others might be exposed as interface for other modules within the project. Only those parts will go to the public interface and therefore will be stored in the module form file of the public interface.

There are many problems to solve here and several solutions we could use. Note that you can’t make a public part of an existing module any sensible way. A module is compiled into a module form file and is visible under the name of the module. The public interface must at least have a different name, or selected modules must be public (as whole).

The simplest way to solve it – although not quite nice for the programmers (because it simply makes the same thing as the “good ole headers”) is to create separate module that would only become a public interface. You know which modules constitute a public interface and only the interface form files of the public interface (you don’t need full form files because they will be in the library) will be copied to the library package, together with the library.

Another possibility is to create a special name with a partition-like suffix except that it is public. You can then mark any toplevel-capable entity (meaning, classes, structures or functions, but not, for example, methods) as export public, and this way this will be added to the public interface. The compiling command of the module interface will then produce two *.cmi files, including one with -public suffix (as this is a keyword, you can’t make it a partition name). This module will be loaded by default if you use its name with import, even though it has this suffix.

Don’t forget however what was said already about the current form of header files and the module template form files – stating that you can still use preprocessor directives and depending on the externally defined macro provide one or the other version of the function signature (for example), or whether to provide it, the conditional must be also kinda “repeated” in the interface and allow a user to decide about things in their own application. This could be avoided if module form files were created out of modules in your project and land in your build directory, but this is a file to be distributed.

And no, this can’t be avoided. Just because it’s currently possible to decide about that, this possibility must be provided, otherwise many projects won’t be able to be moved to use modules. On the other hand, it’s not that complicated – if the compiler is unable to provide the module template form file in the already compiled form, it can provide it as a hidden header (that is, the whole header file will be put as an ingredient of the module interface form file). If the header isn’t available (you have a single-source form already), the compiler should simply generate it.

The resulting (static) library then should provide:

  • The static library file. This should be something different to the current *.a files (because they are supposed to contain only *.o files), there must be some marker of a different format, and although they should be able to contain also *.o files, they may likely need to contain also some detailed code (might be that also that in the source form) that should be “re-imported” into the application’s source files as per request of the interface through import. Might be something like *.ca file, which will be also just the *.a file, but containing different contents. Linkage against such a library would be specified different way – the directory could be specified more-less like today with -L option, but the name of the library shouldn’t have to be specified – this information should be provided in the module interface form files.
  • The module interface files. You can have as many of these files as you want and you can fine-grain the interface of the library as you wish, just all of them should be provided with the library as a package.

The package can as well contain multiple libraries and there’s no need to have any outside binding of the module interface files per single library. Each module interface file should simply have an information of the library that it interfaces.

Now: when the compiler imports an interface file, which for example contains a function template, then this template will have to be physically provided in the library, not in the interface file (the interface file doesn’t provide any bodies). If it can’t be in the compiled form anyhow (and note that it will still have to be a form of module template form), then it should be provided as a source.

Linkage against such libraries – provided they are still done traditional way, that is, there is a set of *.o files there and additionally some, possibly precompiled, headers – should be done by having them used where it is necessary. Note that in the single-source and module-aware build system we only have an import instruction to load the interface (and this would include also the whole header file inside the module package), and then you compile the main module of your target, which will do linkage of appropriate *.o files when necessary – which ones, it’s already specified in your main module.

Likely your module-based library will also need something like a main module. Your application can then import everything that the library offers, by importing, for example gnome.gtk.all. The module with this name doesn’t have to contain any definitions, just import all modules that this library provides. As per how this can physically be provided, there are two potential possibilities:

  1. Distribute the library as a package of modules. Every module has its name and contents, for both importing and linkage – linkage will be done automatically anyway. The whole package might be dissolved in a particular directory and provide a pkg-config entry that will instruct the compiler where to get the module path. This will contain module form files that will serve as both import source as well as linkage. Note though that this way it would be impossible to use shared libraries.
  2. Distribute the library in the library form and – in place of traditional headers – the module template form files (which, in simplest form, could be raw header files containing also static definitions, that is, non-shareable ones, see below). This is not exactly necessary for static libraries, but it’s then the only way how shared libraries can work, and it’s also doable for static libraries.

Whichever method will be chosen, it actually doesn’t matter for the library user. All you still have to do is to make the compiler know the directory containing the module form files and you use them in your code by importing.

As the first method is quite obvious, let’s try the second method.

This will require likely synthesizing the header files and create some precompiled form of them (provided the compiler can do it) in the preprocessor-templated form. If you are lucky and don’t need it “templated”, it can suffice if you simply create the module interface form files. Note that for entities that are “not shareable” it will have to keep things as “header only”, which will be in this case either true headers, or the “preprocessor-templated precompiled” form.

These form files will serve as interface and simultaneously provider of the “static only” entities, while the “potentially shareable” entities will be provided as before. The library name will be provided in the manifest file in the module interface form file, so it’s enough that one source file imports this module through this module form file and it becomes dependent on the while library.

Motivation for the shared libraries

Before we discuss how this new build system would fit in the shared libraries, let’s check why we need them. There are actually three reasons as to why we need shared libraries, that is, what advantage they have over static libraries:

  1. The TEXT sharing
  2. The file sharing
  3. Separated upgrade

The TEXT is one of memory sections of a program. The program, when started, gets three main memory ranges to use:

  • the stack, used for subroutine calls
  • the DATA section – a dynamically extendable region that is initially allocated for global variables and can be extended by request of the dynamic allocation.
  • the TEXT section – the memory that is read-only (an attempt to modify it crashes the program) and contains the assembly code for the procedures to execute. Sometimes it’s also used to store constant data there.

So here the idea of the TEXT sharing is that if the same set of procedures is used by multiple applications, there could be only one instance of them in the memory, while multiple applications can call them. In case of static linkage, every such procedure would have one instance per application in the memory – at least no one so far developed any way to identify identical procedures in statically linked applications. Not only that – also if you have them provided in a shared library, they are guaranteed to be the same on the same system, while after upgrading one application with the new library version you may have potentially multiple versions of the same function even if it doesn’t make any sense.

A similar situation is with the file sharing – if you have the same library linked to multiple applications, you’ll have multiplied this one library as a part of these applications, even if the linker optimizes the process by not attaching functions that the application doesn’t call.

And the separated upgrade: If you upgrade a static library, nothing will be changed until an application that uses it is itself recompiled and reinstalled. If you upgrade a shared library, all applications using it take advantage from it, while remaining installed as they were before.

With the new rules for C++ shared library we may have to resign from some of these advantages, but can still take advantage of the others. For example, TEXT sharing can only happen if you have one solid piece of procedure to load into the memory, and it has exactly this form everywhere. This can be not possible with a function template, which expands to a different body in every instance (although we may still have a compiler easily detect if multiple instances can be indeed linked to the same compiled version). But even if you can’t do TEXT sharing, you may still take advantage of the shared file and separated upgrade. That’s something for the future, of course, but the build system and the project compiling system can be already prepared to handle these cases, and the system will align to it when ready.

Shared libraries with C++ modules

It was quite easy to define C++ the way that all inline functions can be expanded inline, or if compiled, it’s a compiler’s problem how to implement it (might make each solid implementation static and multiplied in the code), hence it was possible to make shared function templates only as inline functions, or – since C++11 – can be also shared, but not the templates themselves, but only their particular instantiations. Likely, until there are created “dynamic library resolution methods for templates”, sharing should be available only for any solid definitions, hence only those parts will be concerned when upgrading a shared library. In a single-source exporting C++ definition there must be then a way to mark particular parts as capable of putting into a shared library. There would be desired some clear marker to explicitly define, whether a particular entity is going to be put into shared or static part. It was easy in case of the so far C++, where externally visible parts were static, when defined in the header (as a header should not contain any parts that would be visible in the *.o file, as long as not “adapted” for itself by the implementation file), and shared, when defined in the implementation file. But with a single-file definition for everything, you might have an exported solid function defined just as well as an exported function template – the first of which can be easily put into the shared part of the library, but the latter one, at the currently available C++ implementation, could not.

My first idea for this would be to obligatory mark every exported function, that is not shareable, as inline. Exported classes (and other type definitions) would need adding a static modifier. In other words, if you define a class in a single source file, this class is your local (not visible outside the module). If you want to make it visible, you have to mark it as static export. The export (without static) might be available, but only if the compiler supports it, and whether it does, it might also depend on the platform, system and simply compiler capabilities (none of the today compilers and platforms is capable of doing it). The class that is marked export (but not static), or a function template that is marked export (but not inline), will have to be resolved in runtime special way. For example, if you use fields of a class, the code would contain dynamic-resolvable markers with field names, and the advanced C++ runtime linker will resolve these named field references into appropriate field offset by reading the information from the shared library. Such solutions do not exist today, at least not for C++, and we’ll likely not see them soon, but this is the only way how these things may work when a class is shareable through the shared library. Until then, all exported entities that can’t be resolved during shared linkage must have a special marker that defines that they are not shared-linkage-resolvable.

As for the export static class statement, this static can be tolerated with only an extra warning (no software developer would be surprised that a class can’t be shared), which can be also turned off in the compiler options. But export inline would clearly differ to just export when applied to a function and in the simplest implementation it would put the body into the (extra) header or the object file respectively, and the function template might be simply required to be made export inline, while if you want to make use of the shareable template instantiations, then you should simply define the template without exporting and then export explicitly (without inline) the single instantiations, which in this case must be declared anyway.

This is extremely important for the library versioning, upgrades, and keeping up to the ABI compatibility. If you have a shareable class, which’s details are resolved through the runtime linkage, the only thing required for the ability to upgrade the library is that all so far defined methods stay as they are, as well as all fields with their current names and types – but fields may be reordered and new fields can be added (or maybe even some feature can be added that would allow to rename fields, but keep the old name as alias, through using for example). Also if you have an application that calls the library’s function to fill a structure, the new library can also modify the structure by adding new fields and everything still works. The application will use the new structure without even knowing it that it has some extra fields. In the current implementation where structures can be only statically shared, this is impossible – the structure with added fields will not be ABI-compatible with the old structure definition, hence the application will have to be recompiled, or otherwise the call to the function will “render to undefined behavior” due to reaching out to fields that are outside the old version of the structure.

But that’s only for the future. No one will create such a thing soon, so shared libraries must stay what they are – collect only solid entities, that is, functions (including method implementations). They do contain also global variables, but this is only because the functions stored in an *.o file may use variables from another *.o file, so they are shared between calls. And therefore only those solid entities can be upgraded with the upgrade of the library, while all static parts must remain either completely unchanged, or get at best a “compatible upgrade”, that is, for example, a class may be only added new methods (including virtual methods – because adding a virtual method actually modifies the runtime part), but not new fields – and there should also be available a mechanism that takes the compiled version of the earliest-backward-compatible library and checks the differences to the upgraded version whether the static entities differ only in things that do not change the module’s ABI. And, obviously, exported static entities must be marked. The compiler may display only warnings when this isn’t used, as it’s just to make the programmer aware of that.

After having this, we should have simply the library defined just like before: the compiler-linker creates the shared library *.so file and the module template form files (*.cmt) or module interface form files (*.cmi) containing the library’s interface. For static libraries there are still two forms possible: either the above cmi/cmt files as interfaces plus *.a file containing the solid part, or just as well simply cmt/cm single files in the package that will be requested as interface and linkage source by the compiler for the library client. That method could be only available as static so far and only for applications using C++20 and also itself compiled in modules. This may also follow the Java’s method with their *.jar files, so you can similarly have *.car files that are really zip files containing module form files (although if compressed it may better use a *.caz extension :D).

But it is still desired that we have a library that is maybe itself written using C++20, but available for applications that must use an earlier standard, or even interface themselves to C applications. Let’s then talk smooth transition here as well.

Modules in the service of public library

And here is the biggest problem, and something likely not even taken up by the designers of C++20 modules.

We want to have a library that is distributed two-fold:

  • traditionally, like before, with a development package containing header files and optionally a static library, and a runtime package with a shared library
  • some better way, although only available to the newer standard

Actually, for a long time the distribution will have to use both. In order to finally abandon the C++ preprocessor and its key role in interfacing and library distribution, you need to keep the library useful for the older standards, and make it available for the newer one, so that at some point the old way can be abandoned. But the old way will never be abandoned until the new way is widely adopted.

As this has to work just as well in case of libraries that are already written in a single-source module style, the header files that would have to be distributed with the development package of the library will have to be generated. You no longer have any header files, and the older standard can only use header files to access the library’s interface. Obviously, the compiler must be aware of what the oldest standard it should use for the generated header file and which features not to use. For having the header file for the old standard library distribution you will obviously have to have a separate module that will collect all things required for interfacing and mark appropriately the exported parts with a block with export extern "C", which will allow to generate a header marking extern "C" for C++ and just pure function names for C.

Alternatively, of course, if you want to make an interface for C language and prefer to complete the header file yourself, you can simply keep your header file as is, and provide an implementation file that will define direct functions as declared in the header file and it will be compiled still in modules, but using the “intermediate” way to compile an uninstrumnented file as module.

Variants and versioning

Ok, let’s think about this for a while: why would your application require a specific version and variant of the library?

Simply: because your application requires particular features that are only provided in certain variant (if a library can exist in variants) and are available only in given version. All of these things must be obviously defined by the library provider, but then you distribute the application without the required shared library, or even you distribute it in sources and it will be compiled on the target system – it should be known in advance if the user’s system provides the library in a correct variant and version. Obviously though you distribute an application (or a dependent library) compiled in the form matching appropriate variant and version line of the required library. With sources you have more flexibility; you may be variant independent, or require a limited variant selection. In short: if you have a source distribution, you need the API backward compatibility; if binary – you need the ABI backward compatibility. And changing even one detail in the variant selection creates a different ABI. API compatibility defines the ability to even compile your dependent target with this library. ABI compatibility makes particular library’s binary distribution usable with the current binary distribution of the dependent target.

These things make it hard to distribute a shared library and use a shared library by the applications in the system. But there are things that are more and less avoidable. The use of variants shall be at best used only when absolutely necessary, and if possible, several details should be selected in runtime so that multiple variants are available already in the library. Because the version line is defined only within the frames of one “static variant”.

Now, the versions can be upgraded within only a single variant. A variant may be defined by a set of parameters, so it’s such a kind of thing – in theory, you may resolve to multiple parameters and their infinite combinations; in practice, most of the variants align to particular operating systems (so it’s impossible that you have more than one of them in the system), very few refer to some specific dependent libraries implementing particular feature different ways (although still only one of them is usually in use in particular system). Therefore you will rarely have to worry about variants. Problems will be mostly with versions and version line.

What is the version line? It is started by a certain version of the library and continues with the same variant (a single variant is a single line, so forking off a new variant starts a new base version) and continues with preserving the backward compatibility (in case of currently known platforms, it’s about ABI compatibility). A new version of the library may be installed by replacing the old version of the same line and all targets compiled for the earlier version of this library can work just as well with the new one.

But that’s rather a song for the future and things that need consideration from the operating systems and their packaging and installation systems. For now we need to focus on how to write a library in C++ using the single-source modularization and fit the resulting library into the frames of the current (well, of course, prepared mainly for C libraries) operating systems.

Creating libraries in a distributable package

So, we need to have these things compiled as before, of course, in the build system we do have the module form files produced out of source files, but finally this should produce the library, both possibly static and dynamic, but in two possible forms:

  1. For the older standards: the library file and separately header files. Header files should be generated out of declarations that are marked export. Entities marked export static will be put as a whole in the header (actually it’s not imaginable to remain accessible with the old standard with header files and having structures dynamically exported, so for generating the old type package non-static export should be not supported), and similarly functions (including methods) marked as export inline should be put whole into the header file, while for those only marked export, there should be only the function header in the header file. Macrodefinitions should be put there also if they are exported.
  2. For C++20 module users: the library file is also created just like in 1, but instead of header files, you have shorthand module form files (template and interface files, whichever fits better) for every exported module. A possibility might exist to do some specific marking of the public modules, but this is only to make things easier for the build definition (so that you can simply walk through all module form files and take to the package only those that are marked public – might be a good idea that you declare module as public module and if so the module name gets the partition-like suffix -public). If you have any macrodefinition-dependencies detected, the compiler should create then (with -mi flag) the module template form file (*.cmt), otherwise it will be a module interface form file (*.cmi). Of course, the module interface form files must be “instantiated” through the macrodefinitions and they will produce the corresponding module interface form files in the build directory.

In the system using GNU installation manners, the library files will be installed in the same place as usual. Module form files have to find possibly some new place to install, neither /usr/lib nor /usr/include is appropriate, especially that we’d like to have already one directory for C++ modules that would in the future contain either interface and template form files, as well as possibly in the future the full form files. For the sake of further explanations, let’s say it will be /usr/modules.

So, for the interim period we’d need that the library contain both the usual header files installed in /usr/include and the module form files in /usr/modules, as well as libraries in the appropriate place. The module form files that are of interface kind (that is, not full), should contain also information about the library name that they interface.

So, as a raw example, let’s say we have a library like… ok, I really tried to avoid it, but for the sake of the article I’ll go simplest way for me: libsrt. This library provides an interface for C language, although it’s written in C++. This library has one main header file srt.h and several secondary headers for special purposes. The interface implementation file is srt_c_api.cpp file and this one would become the public module. All gets compiled into libsrt.a library file (and similarly shared one) and the installation contains headers: srt/srt.h, srt/access_control.h, and srt/logging_api.h. There would have to be then three public modules defined in these library.

In the stage of “old C++ sources, new compiling rules”, it would compile as the old sources, and header files will be normally put into the installation directory. The static library will be made by extracting all *.o files embeded into *.cm files and bound into an archive. For a shared library they will be linked together into a shared library. The module form files produced out of public modules will be then stored in /usr/modules/srt as srt.cmi, access_control.cmi and logging_api.cmi. The two latter can be simply produced out of an uninstrumented header files, while for srt.cm it will have to use the command that defines the module name srt.srt, and passes srt_c_api.cpp as implementation file and srt.h as header file.

Now let’s say we have an application consiting of two source files: application.cpp(main module) and utils.cpp. The traditionally created program will then use the header files in the application.cpp file in the beginning:

#include <srt/srt.h>
#include <srt/access_control.h>

and the source files of the application will be compiled as (with the help of pkg-config):

c++ -c application.cpp
c++ -c utils.cpp
c++ -o application application.o utils.o -lsrt -lcrypto -lssl

while the new C++20 application (stating that it is already module-instrumented) will do:

module default;

import srt.srt;
import srt.access_control;

and the source files of the application will be compiled as:

c++ -mi utils.cpp
c++ -mc application.cpp
c++ -mc utils.cpp
c++ -o application -ma application.cm

Now, you might ask: is the library specification simply skipped in case of “with module” compilation? No, only superfluous. Your application is still free to mix importing by modules and importing by header files, whichever method the particular library provides, although by using the module specification with import you automatically get the library dependency information so that it’s not necessary to be specified for linkage.

This works also for both static and shared libraries and the resulting application, if it uses shared libraries, has exactly the same shared library dependencies. This method should be also adaptable on every step of the gradual module adaptation, as shown in the beginning.

The future: installing a module package

Of course, potentially there’s another possible method of installing a C++ library built with modules: install them directly as module form files. There are, however, several problems to solve here:

  1. Public module interface files should be marked somehow so that accessing a module from the current project, accessing a public module from an external library (possibly installed in a custom directory) and accessing a private module from an external library are distinguished. And the latter is disallowed. Making a so-far library with extra module interface form files satisfies this condition already, while for this case it should be somehow solved.
  2. The module should be shared-loadable. Therefore a C++ application must have an appropriate format, where various markers will be filled with appropriate “meaning”, and it’s not only about filling in the call of a function defined in a separate file, but also things like instantiating a template or find an appropriate offset of a structure’s field. Yes, that should be done by a C++ dynamic linker at the moment when an application is being run.

These are problems to be solved in the file format on particular platform, not much to fix in the C++ language – although the earlier proposed public module statement should be useful here as well. Might be that – as suggested already – separate options should be available to specify directories with modules used in the current project and separate for directories with modules as external libraries. This allows developers to do tricks here – but on the other hand, here is also proposed a separate syntax for local and global modules. Hence, with the local module syntax you can reach out to any module, while with global syntax it will only load public modules.

Simple naïve implementation

It’s not so that in order to implement such a system you’d have to deal with the compiler loadable database already. If you have it, it’s better, but a simple implementation can base on the simplest things. What the compiler should be capable of is, of course, the header file generation. We have then the following rules here:

  1. If you have a class declaration (or just any other type), it is being ignored (considered as a local type definition, visible only in the implementation file).
  2. If you have a type definition with export modifier, then this type definition will be read whole and placed in the header file. If this is a structure definition and it has any methods defined inside, they will be grabbed as well. Only functions that are defined outside the class will remain only as signatures.
  3. If you have an exported function, only the signature is provided to the header file. If there is an inline modifier, you take the whole definition into the header file.
  4. Templates similarly like classes and functions; important thing is that if there is a non-inline function or a method, the only allowed sharing is through extern template, that is, only explicit instantiations can be exported.

The compiler should add options to generate the header file from it and also to configure its name and the macroguard name, by default being INC_MGEN_FILENAME_H.

The naïve implementation of the interface compiling may do the following:

  1. Generate the header file from the implementation file, as described above.
  2. Create the archive file that contains the following files:
    • The generated header file
    • The manifest file

The manifest file should have a 4-byte header, like normally special type files in POSIX which defines its format. First two characters shoul be then #! so let’s follow them by ^C. And then the NL so that it is then written as key: value form. So this manifest file will contain:

#!^C
module: F
interface-type: header
header-filename: hdr.h

This file will be then written in a file named MODULE.MF. Then the F.cmi file will be the AR archive file containing:

hdr.h
MODULE.MF

Now, when you are compiling a module source file – m.cc – that declares include .F inside, then the compiler should expect to find the F.cmi file, so it finds the MODULE.MF and reads the configuration. This finds the method of interface as header file so it takes its filename, extracts from the archive and performs interpretation in isolation – the same way as it would do in case of import "filename" statement.

Now, when you compile the implementation file itself, f.cc, then the interface module should exist, but not necessary. There should be always expected the location where the module form file should be stored (separately from having the directory where the other modules of the same project should be searched – as those could be also multiple), and the module interface form file should be first searched in this directory. If it is found, it’s read and interpreted, otherwise the compilation is simply performed anew.

Note also that if the implementation file contains any export declarations, then the header file generation must happen; if the module interface form file isn’t found, then the header file generation must still happen. This could be the case of an “independent” module file – that is, a module source that does not import any other modules from the project, so it can be compiled as first without having any other modules’ interfaces. As other modules may also be dependent on it – and it’s usually the intention, if you have anything exported – then effectively the *.cm file will be used as an interface. Therefore compilation of such a file involves all things as per interface, and then rest of the things required for a complete module form file.

Anyway, the final module form file should contain the following:

f.cm:
MODULE.MF
hdr.h
f.o

And of course the manifest file will contain this time:

#!^C
module: F
interface-type: header
header-filename: hdr.h
implementation-type: object
object-filename: f.o

This module is independent; if a module has dependencies, then this list should be also added; for example when a module X is dependent on F nad L, then it has an additional line in the manifest file:

dependencies: F L

So, let’s try to return to our first example. We had t.cc, u.cc and m.cc source files. Contents are known, so let’s show now how the MODULE.MF file will look like in these files. Note that this time we do have dependencies, which have been taken from all import declarations. In practice, this should read only the first-hand import declarations, as more isn’t necessary – from the dependent modules further dependencies will be read recursively.

File: t.cm:

#!^C
module: t
interface-type: header
header-filename: t.h
implementation-type: object
object-filename: t.o
dependencies: .u

File: u.cm:

#!^C
module: u
interface-type: header
header-filename: u.h
implementation-type: object
object-filename: u.o
dependencies: .t

and now m.cm – note that it doesn’t export anything, so there’s no header generated and no interface declared:

#!^C
module: m
interface-type: none
implementation-type: object
object-filename: m.o
dependencies: .t .u

So, these are the files that are produced by the alleged c++ -mc <source.cc> command.

Now there’s the c++ -ma m.cm command that is expected to create an executable (default output filename is, of course, a.out ;). This command does the following:

  1. Read the manifest file from the given module form file. This reads the implementation type (which is the *.o file) and the filename that should be present in this archive file.
  2. Additionally it reads dependencies and finds modules for these names. Module form files identified for these names have been found and their manifests read. This time we have the .t and .u modules, so we look for local module form files named t.cm and u.cm (this time we can’t tolerate having only an interface file, although this could be done in case of public modules of libraries) and read their manifests. This drives us to providing additionally the u.o and t.o object files together with our m.o file, so these files are being extracted and there’s called the linker:
gcc m.o t.o u.o -lstdc++ -o a.out # whatever

The same could be done for libraries. Although this time you may have simply an interface file, which will be distributed together with the library file. These interface files are also simply archive files containing header files plus the manifest.

After having this implementation working, you can bet for more. For example, the interface compilation may actually compile completely the implementation file, just with unresolved details. That is, for example, function bodies cannot be compiled without having the dependent interface, but they still can be tokenized and completed as a database that should be only filled with details once we have an interface of the dependent module. Therefore the *.cmi file will contain the completely compiled file, that is, something that the compiler can next take (without even taking a look into the source file) and simply continue compiling the dependent entities. These parts could he kept in a separate file so that this interface file can be additionally processed to turn it into a “slim” interface file for publishing as a library interface.

Expected implementation

What we actually need is that even with multiple steps, intermediately done interpretation results should be reused in further steps to save time. So compiling a single file should be done in the following steps:

  1. Read the file and purge it of any comments, empty lines, and replace all various types of whitespaces with a single space. Note that the preprocessor directives with their EOL (with extension) termination character are preserved. The file in such a form should be saved in a file as “preformatted” source.
  2. The “preformatted” source should be made the checksum from, and this should be saved in the manifest file, if it doesn’t exist. If the manifest file exists, then after creating the preformatted source and calculating the checksum, it should be compared with the existing one. A decision whether to perform these steps anew can be also based on the current time, although it should be able to be forced on demand. If the checksum is unchanged, all remaining files are considered relevant, otherwise they are deleted.
  3. The preformatted file is read and interpreted only as tokens; this results in creating a database with tokens. Simultaneously the forwarder and interface parts are being interpreted during this process and the forwarder and interface files are being created. The interpretation of the interface part is done from scratch once the forwarder interpretation part is finished.

This is all that is being done for the -mi option, that is, compiling the interface. The -mc option compiles the implementation, after all interface files have been compiled:

  1. Do the source check, like in 1 and 2 and repeat these steps if necessary.
  2. Load the tokenized source, and with the use of all dependent interfaces, interpret and compile the implementation (function bodies, as for now). This creates the *.o file from the source.

Now when we want to create the final target, we do things dependent on the target type:

APPLICATION

The build rule should use the file that declares the main() function, and it should use the module name for it. The compiled module for it should be found and all modules it uses should be added to the dependencies. All dependencies are read flat and the *.o files from all module directories are taken as ingredients for linkage.

STATIC LIBRARY

You can either have a single file that is a library loader (collects all imports for public interface files), or just collect these modules (all those that have the -public suffix). Put them in the package. Then read all modules where public interfaces were found and collect all the flat dependency information. From all dependent modules the *.o files should be read and put into the AR archive. All the public interface files should be then added to the package. This is the form that is expected by the current standard library form.

Alternatively you can create a *.tar file with all module files that belong to the library. The compiler should be able to access them through the filesystem mounting, or extracting them if that’s the only way.

SHARED LIBRARY

This works more-less the same as the static library, except that collecting all *.o files is the only possible way of distribution, so this part is using the linkage by collecting all the *.o files and do the same as for the application, except that there’s no main function and the -shared option is used to create the *.so library. The public interface files are added to the package.

Final notes

I had some more ideas how to go further with this system, but they were rather focused on supporting some old practices, mainly with bad practices widely used in C development and shared with many C++ projects. One of important parts were possibilities to deliver alternative implementations like dependency on a library that can exist in various flavors and with a different API, but created for the same purpose, including having a variant of the main library with no support to features that require dependency on this library. Such a thing will be still a problem and it would be nice to have a solution for it and without the preprocessor.

This what has been proposed above should however allow the C++20 module system to be provided for the real C++ development and help C++ projects do their job better.

Posted in Uncategorized | Leave a comment

C++20 modules Konsidered Yoozless

[DISCLAIMER: this text is still under development and likely will be fixed, but I wanted to collect some more opinions from the public first].

It happened once already. The C++ standard committee has gone very far in completing the idea of templates and their linkage between compilation units that they had to add the export keyword. This way they created a feature that in this exactly form as defined in the standard is implemented literally by no existing C++ compiler in the world. The only one that tried to do it – Comeau – made it more-less working, while requiring conditions that weren’t mentioned in the standard, such as that the original source files, that define these templates, be accessible during compilation of the template’s user.

In the next standard, C++11, they removed that keyword (which wasn’t a problem since no codebase could be harmed by it), while adding a possibility that existed partially already in other compilers as extension: extern templates, which can be linked against across compilation units, and the only condition is that they are explicitly instantiated, so the linkage actually concerns only the selected instantiation, not the template itself. The practice of the software development world, as always, triumphed over the sage-wannabees from the standard committee.

There is one important lesson to be learned from the failure of the exported templates feature – the C++ language cannot live without the “build platform”, which is something that can be called “C modules”, and this build platform has its own rules, such as, for example, the only types of entities to be bound together can be a variable or a function, and if a language entity can’t be aligned to any of these, then the only way to make them accessible in the other unit is by sharing the source. This means that the only way to share templates is to either share them through header files, as source, or as a function that results from the instantiation, which must happen during compiling both the usage unit and the definition one.

Not even 10 years passed, and the committee has created again a feature aimed to replace one of the ugliest part of the C++ language, which again, by a lame-legged dog won’t be used. Just this time it’s way more ambitious: modules.

Those ugly includes

What’s the current situation with C++ and its way to import the interface of other parts of the code, that’s known and despised. We have this ugly #include directive that simply pastes the read file into the text file, or even more precisely, the compiler gets at its input one big text file that consists of all the text pasted from the file as requested by the #include directive in this file, and also all such files recursively. Plus the text consists of things included (or not included) by having a conditional directive resolved, as well as resolved macrodefinitions. Actually the preprocessor is a kind of separate language, or language-in-language, which is different than C++ itself, while having its syntax partially mixed with C++ due to the use of macros.

Bjarne Stroustrup since the very beginning found the preprocessor the worst part of C++ and urgently needed something to replace it. C++ has been first announced in 1982 year, the first standard was committed by ISO in 1998 year, and during the works on C++0x (which became later C++11, as 2009 date was rather unrealistic) they already learned some problems the hard way. But still no sensible replacement for the preprocessor has been found. 10 years later they have developed finally some proposal (I call it “proposal”, even though it’s defined in the committed standard, because it’s a language feature, aimed at being a replacement for one of the core features in the language, but the “old way” is still available, so it’s the matter of whether any developers would like to use it). Before evaluating it, let’s take a closer look at the whole “build platform” being used by C and C++, so called “C modules”, which consist of the preprocessor (as a main tool to have a shared multiple parts of the code), and the C linker.

Ugly, but necessary

So, out of the most important things we have this #include directive, which’s main intention is to inject the interface of a piece of code. For that, we need to have this interface defined somehow, and C++ is still using these “C modules” for it. Using the C++20 nomenclature, you have the “exported” part in the form of a header file, and there’s also an implementation that is “not-exported” in the object file. It’s up to you what you export, however exporting or not exporting particular parts has consequences. Speaking about simplest things, you can have a structure declared as incomplete, which means that you can still use a pointer or reference to it, as well as declare it as a return type of a function (stating that you can still ignore it), but you can’t refer to fields of this structure, nor can you create or copy values of that type. In case of a C++ class it means also that you have to provide a complete class definition in the header file, if you want to be able to call its methods. But this also means that you have to declare also all fields in this file. You can put them in the private section, of course, but they still are “exported” this way. You can also use the so-called “pimple” pattern, that is, use a separate – unexported – structure for fields and keep the pointer to it in the main class, but this is an ugly trick (you walk around a language problem with extra code), and it’s not without consequences (you need to have a dynamic allocation for this structure, if you don’t want to export this structure’s size, and also you can’t implement any methods inline). Bottom line is, this method of exporting the interface forces you to create your class specifically, and split the code of a class into the *.h and *.cpp file, or even three files (exported header, internal header and implementation, if using pimple). What is interesting in case of pimple is that the only reason of using it is that modifying any “real” class contents (that is, except the “exported” part) won’t result in recompiling all its users.

Could there be then any alternative way to do this? Well, of course. If you have an exported parts of the class, then you could be able to access methods, but not fields, you might be not able to get the size of the class if fields are not exported (this way being not even accessible to friends). Why could this be valuable? Because this way you can change the parts not being exported as you please, without any risk of breaking compatibility of any dependent code. But the “C modules” system makes it impossible – you can have only exactly ONE definition of a class, and either it is whole exported or whole hidden, and the only method to make selective method exporting is either through the “pimple”, or full-virtual interface.

Another topic is the use of preprocessor macros. The form of their use is that you can call – or rather apply – them in the form of a function call, they can have a name similar to a function, or it can be a single symbol; whatever you define inside its definition, will be replaced to in the target form. They must only be lexically complete. So it can be used to inject some fragmentary syntax that would only be complete after the macro resolution – it can’t glue in, for example + and = into += operator, but it can potentially paste incomplete operator expressions, leave open parenthesis or brace, to be closed by another macro application. A completely separate story is that it makes today C++ unable to be parsed by a single parser, at least those being in the market currently (I personally started some project of a parser that might potentially be able to do it, but that can only be achieved by a “feedback style”, that is, a language element when resolved should feed the resolved text back into the parser). A nasty problem with macros is that it uses also its own separate naming system, partially conflicting with the C++ namespaces (you can use some symbol looking like a namespace-resolved name or a method call, and the name could be a macro to be resolved to another name), and when anyhow used in the header file it’s exported everywhere.

On the other hand, macrodefinitions are used for something that is controlling the conditional content injection. Some expressions can be already provided by the compiler (either internally or through command-line options), but this is also a method of how a user might want to use parametrization for the include file. You simply make #defines with some symbols that you know will be used inside the file before #include, or even through a compiler option, and then these symbols will be recognized inside and some alternatives will be selected. Not that this is so often used, but it’s one of the things potentially possible and sometimes useful. At least it’s something being used today, even some crazy way, and it will have to stay as is, potentially forever. Whether any alternative or replacement will be available is about to be seen, but it will have to be first widely adopted, otherwise it will never disappear.

And another story is the linkage system. One of the problems is that this is built in into the operating system. And, kinda paradoxally, it wasn’t a language for the system, it was the system that has adjusted itself to the currently used language, and that language was C – ANSI C, in particular. And the C language defines symbols of two types only – functions and variables – and only those are exported out of the object file and externally visible. This also gets forwarded then to shared libraries, which is a thing defined a bit differently in every system, but finally it all aligns to how the C language defines it: you have a shared library file, which is resolved when you execute the program, the dynamic linker is running and symbols from the library are being linked to the application. What symbols? Those that are supported by C language, as I said, functions and variables (note: not even preprocessor macros). The C++ language, volens-nolens, had to adjust to that system if it wanted to exist on them – so global variables, objects, constants, all of them had to be exported as variables, and functions, class methods, both possibly inside the namespace, as functions with some very long “mangled” name, had to be exported as functions.

I think you can see now, why things are “ugly” here:

  1. You can’t export a class, and its layout is unknown not only in the runtime, but also across linkage units. Among others, this makes an excellent point of ABI incompatibility in the changed library version. Imagine, for example, a stupid sizeof applied on a class that in the next version has been added a field. Is there a problem to have a linkage point in the source file that uses this sizeof and puts the real size of the class there, as extracted during the dynamic linkage against a shared library? Theoretically it wouldn’t be, as long as there is predicted such a thing as “immediate value linkage” (today at best it can be aligned to a variable), but not only doesn’t this thing exist in the today linkage systems, but also there’s no way to put this information into the library. The sizeof expression is static in C, and so it must be in C++. The trick here is that for C language, which contained only simple structures with data fields inside, it might be not so important to have the structure layout resolvable at link time. For C++, where “structures” are armed in virtual methods, derivation and nesting, it is unfortunately desired.
  2. Templates can be in practice only fully defined in the header files. In C++11 there’s a possibility of template linkage, but the linkage – just like the system linker for shared libraries – can only refer to a function, which means that your function template (or your class template for all methods it defines) must be instantiated in the same file where it is defined, using the exact parameter set that is going to be used by the template’s user. In some extreme cases it also forces a user to create an implementation “in steps” – one that is a template-based API that the user will use, and the implementation in the header will do some costly parameter translation and will call a “runtime” function that is defined in a style acceptable for the linker (including shared linker). As you know, in C++98 they tried to fix this problem by providing a non-implementable rule for the compiler in the form of export keyword, which had to be later withdrawn. Seems like the standard committee didn’t understand that no matter how they want to make the language complete, they still must settle its rules with the rules of the system linker where the language has to be implemented.
  3. The code must be manually split into the exported and internal part, kept in separate files. Theoretically you might try to use the implementation file as header, just mark the implementation part hidden by a conditional macro, but this can only be used in your own project, not exposed as a library API – in the latter case you must have the header file as the only thing provided in the form of a source (actually a better idea would be to use yet another preprocessing tool to generate the header and implementation part from a common file).
  4. You also need to have defined things in the language that control the linkage export. For example, you can have a constant that is externally linked, but it’s in the form of an exported variable (as exporting works only for variables and functions). Therefore you have in C++ a static const, which is resolved at compile time (but internal), or an extern const, which is a “declaration”, if not initialized, or “definition” if initialized, which isn’t very intuitive if you compare it with how this thing is settled in case of normal variables and functions, that is, something that can be operated in C. There you have a declaration without marker, which defines a variable, and you use extern to mark the importing. A much better “intuitive” implementation would be simply to just define a function or a variable (or a constant or a class) and have some “export” marker to make it exported, otherwise it’s internal. From this you can clearly see that the function declaration (unless it’s just in order to free yourself of the function definition order in the file), or an extern marked variable is simply a technical detail that you have to use explicitly only because the modularity system in C++ is defective.

C++ simply doesn’t have a modularity system on its own that would be designed specifically for its needs. And God knows it needs it urgently.

The Black Sun

For those, who might not exactly understand this term – I mean this term used in the world of Star Wars, which designated a crime syndicate. The name based on a saying that “better a black sun than no sun at all”, and it was then connected to establishing a paramilitary organization that had to restore order in an anarchized society – then this paramilitary organization turned into a crime syndicate.

So, this is more-less the situation about the modules in C++20. And here are several reasons, why this actually is a “black sun” that not a person needs in the software development industry.

1. No real world usage

Let’s start with the toughest pill to swallow for the C++ standard committee:

Among all examples found in the internet that explain the matter of modules, all of them are in the style of FooBar::DoSomething(). That is, I haven’t found so far even one example of a C++ library created in the today style of “C modules” and then the same library written using C++20 modules. Not even mentioning any intermediate form, which can be used both in a “traditional style” and using the import instructions with the proper module names.

Ok, let’s say that the fact that I haven’t found anything doesn’t yet define anything, so I admit, I found some articles that show the same thing done the “old way” and using the new method with C++20 modules (like this one for example). But they are at best extremely simple examples, and even as such they already show what the worst part of it is – you need to translate “very standard” header files into “not standard at all” *.ixx files (Microsoft flavor), once and for all. This is then effectively *.h into *.ixx translation and some syntax change – the whole rest of the project remains completely intact. Should I really say it openly, how useless that system is for any C++ developer?

Nothing “real-world” that would show how pieces that are bound together in the old-style “C modules” can be done now easier way with C++20 modules. In some of them I have even found an example where the “module primary interface” file contained more-less the same things as the old “C++ header”, just without macroguards.

I tried myself to write some simple library that would be used as a module; maybe I didn’t try hard enough, but the module rules seem to be quite complicated, and it’s nothing like that you just put the header and imp file into one and expect that it works. It doesn’t even look this way when you see the examples, the hardest part is when you’d like to make the old library, written for a real use in the earlier standard, useful for C++20 application developers. Even worse when you’d like to only define some extra header files with module declarations for the files that already exist. Simply: there are no sensible transition abilities between the current “C modules” system and the C++20 modules system. Oh, there is one – you can simply replace the #include directive with the import instruction, leaving the argument intact. Really? This will simply make that in the incoming 10 years people will be using the import instruction and continue with the old school header files – of course, if they are patient enough to add the compilation step from the header file into the module cache files, whatever it is the compiler is using. And that’s about all as it comes to usefulness of this feature.

Frankly, this is the biggest defeat for the C++20 modules, if the only code that can be written using C++20 modules could be the completely new code, newly written for C++20 and inaccessible for any other language, notably previous C++ standards. You know how this will end? Very simply: if an old code is to be abandoned in order to take advantage of C++20 modules, the new code will be written in Go, Rust, D, or even maybe some scripting languages, like Lua or Python, or… C++, of course, using the old good syntax working with “C modules”.

2. No consistent definition of the file content and compiler behavior

There are three compilers currently supporting C++20 modules: Clang, GCC and Microsoft Visual. That’s way better than it was with the old export for templates, which was Comeau only, but still there are things not exactly resolved by the standard committee, which means that the compilers had to have their own rules. Even Clang and GCC, which traditionally were keeping options similar to one another to allow interchangeability, have a complete different set of options required for this and even different set of rules. For example, in GCC if you want to use import <iostream>, you have to… compile iostream as a module, and it will be stored in the local cache. What is interesting, that’s a specific solution for gcc, and every compiler does it a little bit different way, but all of them are doing it with some kind of caching – because the standard doesn’t define how the intermediate files should look like. Understandable that the intermediate parts have to be identifiable by name used in the language and this should somehow easily map to the filename – but still, in my Silvercat project I could decide that from the hell_proc.cc file the compiler should make the intermediate file as imfiles/frog-hell_proc.ag.o, as then the linking is known to be then using the object file that is the hell_proc.cc file after compiling, but as this is inside the project, it doesn’t matter. It is understandable that the filename should be able to be mapped after the name used in import instruction, something of a style of Java’s CLASSPATH variable that leads to possible locations where it starts, and with dots translated to slashes as a path separator, which wouldn’t be actually anything different than the compiler’s -I and -L options. But during the build at least this thing should be able to be decided.

You might want to ask why is this necessary to “precompile the system header”, why can’t this file be stored somewhere in the compiler’s installation files, just where the iostream header is? Well, there’s one simple answer: because preprocessor. Because what exactly form this module will have after compiling, it may depend on compiler options and possibly a definition of some macros, which’s combinations may select several parts of the file. And the “compiled module” is a form that is to be then taken by the compiler and compiled together with your source files, where any preprocessing part is already done.

That leads us to the next problem:

3. Modules are compile-side tricks for the build system, not source-side helpers for the developers.

There’s no way to pass any “parameters” to the modules, or better, you cannot “parametrize” what you import. Let’s take a simple example of an existing solution:

#define __STD_FORMAT_MACROS
#include <inttypes.h>

You can of course use import <inttypes.h>, but the #define above it won’t change anything – macros do not get imported from the outside of the import file (macros can be imported and exported in C++20 modules, but only by definition inside the module).

Of course, this is a bad solution that should not be used (in C++ it is discouraged and all parts are always included anyway in the C++ version of this header), and not that I would like to demand keeping this solution available also with the modules. But there are also some other uses of it, for example, by adding macros in the compiler’s command line. There are various purposes of it – can be some extra debugging facilities, can be a variant of the library, for which this part of the project is a wrapper (something like module variants or module version also isn’t anyhow supported). For example, a library that uses encryption and wants to support various encryption libraries, of which each one is using a similar in functionality, but still a different API. This can be an internal problem to solve inside the library, but still you would like to control things by specifying several parameters – for which exactly feature there exists the -D option in the compilers.

When I asked a question about this on Stackoverflow, the people were greatly surprised that I’m even asking for that. Obviously, modules shall not be parametrized. You should simply ask a module to be imported and that’s about all. And the module – that is, something you are asking to be imported – is not a source to be only compiled, but something already compiled, where all possible parameters are already resolved. Whatever is to be conditionally added or blocked, in the “importable module unit” should be already in the target form.

Effectively then, you may even say, you could accept this fact with just such an explanation that for every combination of compiler options and external macros you should have a different form of a compiled module. Yes, but even if you do this, you can’t even distinguish between versions of a compiled module. You can’t even decide its name (let’s say you’d like to have multiple variants of it in the same build) because the name is what identifies the module for the external parts.

You need to distinguish two things, in order to properly understand the modules in C++20: The module source files (the definition, export tables, partitioning etc.) and the module as an “importable unit” – as these two things, despite being both named a “module”, are completely different things. So, you need to remember what is exactly this “thing you import”: it’s a temporary file that exists only among your intermediate build files, it has a predefined name that you are not allowed to change (which is even worse than regular “object files”). Best way to think about it would be that it’s a “generated source file” and not even for C++, but for a different language that can only be reliably interfaced to C++.

This module importable unit not only cannot be parametrized – it also cannot be versioned. This is simply a build intermediate file. If you imagine a typical program in C++ consisting of source files with includes, which are first compiled into “object” files, and from which the linker finally produces a program or a library – the “module importable unit” is something on the level of the object file (although it’s closer to some generated file in some language from which only the object file will be produced). It’s far from both the sources and the final program or library.

Effectively the only possible form of distribution for a code written in C++20 modules is… in the source files. This doesn’t sound any better than “header-only libraries”, just this time the sources can be even very large. But libraries… well, libraries are yet another story:

4. There is no binary standard that can be used to distribute libraries

This is actually a topic that I undertake in another article. There’s not much to write about it. How do we distribute libraries today? As two types of packages:

  • The runtime package, which contains shared libraries and possibly some runtime data files
  • The development package, which contains static libraries (if needed) and… header files. That is, specific forwarding information that allows to refer to entities from other files, but still in the form of C++ source files

Does that have a binary standard? Well, C++ has simply reused the method being used by the C language here: shared libraries are made of the object files (it’s just a form of an executable file without the main entry), so it’s the matter of the platform how it is implemented, but all packages use one platform standard, and forwarding information is just the standard source (header) file.

Note that C++ has brought in one problem: it has more callable types than just a function, and even functions could be overloaded and in namespaces, so it couldn’t use just the function name in the symbol name – this had to be encoded (mangled). This already brought in a problem in standardizing the mangling system. This standardization happened per platform: for Linux the standard was provided by gcc, on Mac – Clang and on Windows – Microsoft (MSVC), all other compilers had to adjust to the existing standard.

With C++20 modules, we can still distribute libraries, even shared ones, but what about the forwarding entries? There’s no other way than distributing the interface files. Of course, you might also generate header files out of the source files (at least clang allows this) and distribute these, but this is stupid: what use is of modules if I can’t get rid of header files?

Maybe this doesn’t have to be a standard for everyone, but surely it should be at least defined for a single platform (so that, again, a program compiled by MinGW can be linked against a library compiled by MSVC). Without such a standard you can’t distribute a binary package with a library written in the C++20 modules.

This also isn’t all. One of the things I’m trying to solve in my separate proposal for C++ modules is a clear distinction between module names provided by the current project and modules provided by the external library package. Today this is a problem even with the header files and various clumsy methods are used to work this around, although none of them is really working. Naming is also only one of problems here – another problem is package versioning (mentioned above) and defining the public, private and protected section of the library itself. And yes, this is something being solved in today libraries by defining this access control per file: when you create a binary package of a library, there are strictly selected header files that are “public headers” and only those are put into the distribution. I haven’t even found any concept or proposal for fixing this problem, let alone be it defined in the design of C++20 modules.

5. C++20 using modules is a completely different language

A program written in C++20 using modules is a “hard handoff”. You can use libraries intended to be written for older standards using import instruction with the header file, which is kinda cosmetic change, with just one small advantage – macros defined in previous headers will not be visible in the next headers, which prevents nasty, sometimes undetectable, name clashes for preprocessor. But that’s about all. The C++20 modules can be used inside your program to maybe better organize your sources, but heck, somehow even large projects coped very well using the traditional “C modules” and didn’t have problems with it. What exactly then can you use modules for?

One of the things that you can already figure out is that you can have a whole class written in one file and you don’t have to worry about creating a specific header file. If there are things you don’t want to be visible outside – you don’t export them.

The question isn’t then how can you use C++20 modules instead of “C modules”, but rather how can you organize your sources. But the biggest problem is that practically the C++20 modules cannot be used across projects by any other way than by source files.

You might have thought that at least with the C++20 modules you can write your library in the more modern style, compile it into a library, which will be then used by an application – still, requiring C++20, but we have already accepted that limitation. Or maybe even you can write this in C++20, but the API can be exposed in the style of some older standard so that other developers can also benefit?

Nutter chance. All you can advantage from C++20 modules is the organization of your program. It doesn’t matter that you can distribute your sources in the style of modules, you can define a class in a single file, dependencies will be easily handled… only within the frames of your project. And for the library you’d like to distribute the only thing you can use is the compiled form and… a header file. Old good header file, containing a class, maybe without method bodies, but definitely with fields. Maybe you can generate it out of the module source file, if there’s a tool to do that. And no, you can’t even make it a library out of C++20 modules even if it requires at least C++20 to use.

6. You need to change the way you think about sharing parts between the project units, and there’s not a smallest thing to remind this in the so far C++.

That’s it. What is a “module” that you import? Any similarity to a header file? Something that earlier was a combination of a header file and implementation file?

What is this “importable unit, identifiable by name” from the perspective of the logic? Because the logics of so far “C modules” represented by a header file, is simply the logics of what is being defined. The implementation part – be it even a compiled object file – was to only provide longer parts to complete what is defined in the header file, but it’s actually the header file that declares things. This is the “power” of the module. It can be conditionally controlled by the language environment (preprocessor macros), it will also decide which parts you can use, and which not (even if they would otherwise refer to parts that are contained in the compiled object file). This is this “thing you import”. This provides you also with things you may use, as well as probably an information of what is currently accessible on the platform or project configuration, for which you may want to adjust your application. This is then exactly the point of true portability.

7. And WORST OF ALL: Circular dependencies are not supported.

Well, it was something wrong for me in the beginning that no documentation has ever mentioned that, I just learned it the hard way when trying this out by trying to use the --precompile option for clang when compiling a *.pcm file from the source. Turns out… the module file for the module mentioned in the import instruction must already exist. Even if all you currently want to do is to compile the interface of the given module source file, which contains completely no dependencies on anything being imported.

Of course I hear it already:

Circular dependency is usually a result

of bad design or coding !!!

Really? For that I have a very simple answer, same as Elon Musk used to respond to his unruly sponsors.

So let me put that perfectly clear: a circular dependency of module implementations on one another’s interface is something that has been functioning everywhere for years, and can be just as well found in all other languages. It can be easily found in every single big project (in C and C++, and even D, which contains a very inspiring model for C++) because it usually happens that header files provide single type sets with its own interface and then an implementation refers to some other type’s interface in the code of the implementation. How would you even make an operation by matrix with a vector, if a vector and matrix classes are defined in different header files?

So, let me clarify what the real deal is: A circular dependency in such a form that B included A’s interface and vice versa, existed in C++ (and C as well) since the very beginning. Implementations can’t have dependencies any other way. There could be also interface on interface dependency, when you use export import <module> – and it would be the same as when one header file includes another, and here the circular dependency is not possible by obvious reasons. But then, isn’t that exactly the reason why implementations exist – to allow to create a function that uses interfaces of two types provided by two different headers?

Of course, some will quickly respond: obviously, circular dependencies with C++20 modules can be still solved! How? Well, exactly by allowing to split module’s implementation files. That is, the file that contains the export module declaration should not contain anything in the implementation that requires an interface of the module, which might be using this one – in short, you should use separate interface and implementation files, so that the part of the module containing the export module declaration does not import the other module, and all declarations that need access to the other module’s dependency is shifted to… another file. Search for yourself on Stackoverflow or something to see how people are desperately trying to work around the inability of using circular dependencies.

So, again: the current “C modules” system forces me to split the contents of one module into a header and implementation files. That’s the disadvantage that is the most problematic for me and I would welcome a solution with modules that doesn’t force me to split contents into two files. But C++20 modules still do.

You know, for example, how circular dependencies are handled in Java? They are just allowed:

  • There is no import declaration in Java (the Java’s import instruction is the equivalent of using in C++, in particular, to shortcut the package-path name of the symbol to only the last part). Symbol definitions are either provided by the current file, or they have to be found later somewhere else.
  • In Java source code you can freely have any kind of unknown entities. Java has here a small advantage over C++ (not without drawbacks, of course) that its syntax allows you to recognize from upside the type of entity designated by the used unknown symbol. That’s why you can generate at least the java bytecode template basing on the file using unresolved symbols.
  • When you compile a project in Java, where dependencies can be found between particular source files, you pass all of these files at once to the Java compiler command. If a symbol is not defined in the currently compiled file, it will be later searched among other files from the same compiling group and class files found in CLASSPATH.

I personally wouldn’t like to have exactly this in C++, but that’s exactly why C++ needs the the import instruction: to declare, which exactly module should provide the symbols – even if they will have to be later linked together.

In short then, this simply removes a widely used feature of the source/header system without providing ANY kind of replacement for it, except for simply keeping the sources split exactly the same way as without modules. So, what will the majority of C++ programmers respond to someone who tell you, well, if you really need a circular dependency, you can split the source into interface and implementation? Simply, maybe I’ll just stay with old good splitting into the source and header file. At least it was working for years, problems are known, and at least no one tells me how I should write my code. That’s exactly the biggest “no go” for modules: if they aren’t going to solve my problem of having open two files – source and header – simultaneously in the editor and worrying where I should search for the part of the code I need, then what exactly problem are they going to solve? All those that we have learned for the last 30 years how to avoid and work them around? Clearly, you could have put your time spent on this design to better use.

Unique like C++

I understand that C++ must do things its own way and not blindly follow all other languages, but experience with various other module systems should be at least inspiring. In the case of C++20 modules it looks like it was done so unique way that likely no one is doing this. Whereas there are some practices among module systems that are there for a reason, like:

  1. Exported module source files must have names equal to the name of the exported symbol.
  2. The module pathname is represented in the filesystem by directories.
  3. The “importable unit” of a module is accessible by the name as mentioned in the importing directive, including pathname directories.
  4. Multiple versions of the same module shall be possible. Importing shall allow to specify version constraints (note that this isn’t supported by Java, but it is supported, for example, by Tcl, and also through some tricks, by Python).
  5. Modules should allow for specifying parameters that are provided explicitly when importing (or simply support variants and an ability to select them some standardized way).
  6. For systems that cannot provide runtime linkers for C++, the specific header generator for a compiled file should exist for the sake of distribution.
  7. For systems that can provide runtime linkers for C++, the C++ libraries should be able to be distributed in the form of specific C++ shared libraries that can be linked against a C++ specific library in runtime.

Not all of them are coming from particular module system, and some of them don’t exist anywhere, but such a requirement results from the nature of C++ and the practice of using it across years.

What the customer actually needed

I don’t know why, but when looking at C++20 modules I feel like being this mythical “customer” of a software company that doesn’t understand exactly what kind of software they want, but the software company then anyway produces software that can be used as a hedgehog instead of a brush. Just this time I – a software developer – am a customer, and software developers are the members of the C++ standard committee.

No, guys. This definitely isn’t what we, developers, want. We want a system that will satisfy the following needs:

  1. Allows to create an intermediate “compiled template” form, which can be still instantiated using compiler options and parameters from the user. Simply, if you don’t, we might resolve to modules and their interfaces, split into as small pieces as possible, then the pieces will be linked together (a series of import instructions) from an old school header file that will be picking up parts basing on user parameters through macros, compiler macros or command-line macros.
  2. The version string is standardized and can be compared; it’s encoded in the compiled module and can be verified. If you don’t, then again, we’ll resolve to a version string written in a global variable and the version symbol in the header file.
  3. The modules have names consistent with the directories and files where they are stored.
  4. The ABI consistency should be able to be resolved across versions. That is e.g.:
    • An exported structure/class must have template entries for class size and field offsets
    • A function or method should be freely added new, default arguments without the need to recompile the user’s source. Same for new overrides of virtual methods.
  5. If possible on particular platform, a reliable runtime-linkable library form should be designed
  6. There should be also possible an “intermediate” form that can be compiled as both module-only capable library and a library for the old “C module” layout.

This is more-less what the developers need in order to replace the “C module” system based on the bare text file inclusion.

There’s also one quite another story. The problem with the current “C module” system is that the build system required for it requires building single files in separate commands and then linking them together. Every file must have its own header file, if another file would like to be dependent on it. The expected module system for C++ should resemble it, except that:

  1. We want to not have a need to have header files. The actual interface should be able to be somehow extracted from the compiled, distributable module files.
  2. The unit of exporting for a C++ module, beside functions and global variables as we know from “C modules”, should be also a constant or a class, as well as templates. In this sense, a static field in a class should be a part of that class, not an external-symbol-marked variable.

Not your stinkun’ problem!

Well, there’s one another very important thing about the “C modules” as a currently used modularization system in C++: it’s everywhere.

Meaning, this system decides about the following things in the whole C++ software development:

  1. Splitting the whole program into single pieces
  2. Binding these pieces together by exposing appropriate “nodes” in every unit
  3. Selecting the smallest unit of change that would require recompiling dependent fragments
  4. Partially also “ABI compatibility” between single units (meaning, which parts of the “user code” must be recompiled after changes in the “service code”).
  5. Distribution of a “service code” for the use of other applications with having the most common code provided in the precompiled form of target platform’s binary

So, the first and foremost problem of C++20 modules is that it aims to replace points 1 and 2, maybe 3 if the compiler supports it well. But rest of the things are not even bothered to be fixed. I didn’t even mention about things being solved exclusively in the frames of header files – that is, platform-dependent things and conditionals; this actually should be mentioned too because header files are also part of the whole system called “C modules”. One other thing that wasn’t also mentioned precisely was that the distribution also embraces situations like linking older applications against newer libraries and possible ABI incompatibilities coming out of it.

The important thing about the “C modules” system is that it’s not only a language tool – it is interfacing the language to local development system, build system, distribution, and the operating system. Out of these four mentioned here, C++20 modules cover the needs of only the first two.

What’s the deal here? Well, the deal is that the “C modules” system is maybe ugly, maybe dirty, hard to use, error-prone, doesn’t serve well the C++ language, it’s ABI-compatibility-unfriendly, but it covers everything that the software development needs for its work. If you want to make a sensible replacement for it, the deal is simple: provide a replacement for everything, or go f*k yourself.

And if you want to make a replacement for “C modules”, you have to start with what the “C modules” system actually is, point out its services currently provided, design a possible coverage for all of them in a different system, cover the needs, design the templating, replacement methods, resolving the binding to another unit, maybe define a possible features of this system better.

For example: the fact that the system linker can only link variables and functions is a simple fact that the linking system has been designed for ANSI C and it didn’t change a little since. Yes, ANSI C, or C-89 otherwise. Newer C language standards have introduced some more features that might even demand some upgrades of the linking system, but this didn’t happen (which means that standards like C-11 must also perform a kind of emulation in some situations).

I can understand the the current library distribution system in today operating systems may be hard to change, but there are several ways as to how to deal with it:

  1. Best solution: provide a resolution system that is separate from the operating-system-supported shared library system. Make the libraries compiled into a single file that contains all the information that should fill in the “node points” in the application and perform the binding of all of them – in this case you’d have to have more types of nodes than a variable or a function, possibility to fill in immediate values, be resistant to reordering fields in the class (because the actual offset of a field would be an information provided from the library) etc. – here the only problem is that the idea of a shared library wasn’t only that it is distributed in binary form and allows multiple applications dependent on it to be distributed without this library compiled-in, but also that the library being used by multiple applications simultaneously occupies, at least for the “text” part, a single piece of memory, not one per application’s instance. This problem would have to be still somehow mitigated.
  2. Intermediate solution: define, which parts of the language features are possible to be “shared”, and which must be “static”, and provide a combined half-shared half-static solution for the libraries. There would have to be strictly defined parts of the language and language system, which when changed, define changes in the dynamic part or in the static part. If you then have changes in the static part, you introduce a backward ABI incompatibility. Of course, this should also be able to identify particular “single pieces” of code, while when adding new, not existing previously, static pieces, also doesn’t break backward ABI compatibility. If you have such a system, you should be able to provide a C++ module in the form of a shared library (which is something required by the operating system) and an additional C++ module interface file, which would contain instructions of how to fill in gaps and linkage nodes in the application template so that it is consistent with the “shared binary” part, distributed as a shared library.

But before we start, we need to understand first how the “C modules” work, what exactly could be improved here, even if it would have to be done using the userspace emulation, and what solution would preserve all the needed advantages as much as possible. Let’s start first with realizing what features currently the “C modules” have (and, more importantly, which they don’t).

Back to the past

So, as you know the “C modules” consist of two main things: a header file and the object file, while the latter can be also adjusted to the form of an archive or shared object (both known as “library”). Note that both the binary format of an executable file and the object file format are parts of the operating system because also the process of dynamic linkage is also undertaken by the operating system. Running it in userspace is kinda tricky because the binary file must be somehow trusted and therefore the privileges matter here, its controlling is usually the matter of the security of the whole system, so “generating a binary file on the fly” by some userspace program requires this program to be extra trusted, which is hard. Therefore we can only do this one way – emulate as much as it’s possible in today’s systems and wait for some operating system to provide dynamic linking system that can be improved appropriately. Note that this means that more or less language features can be qualified as “dynamically linkable” and which ones qualify as such, it will depend on the operating system. It can be at best “full fledged”, where all linkage features can be used and therefore all features can be used there, or it can be only limited to things supported by today system linkers.

That said, I wouldn’t even say that this is the linkage system adjusted exclusively to the C language. It’s worse – it’s a “limited C language support” because not only it doesn’t feature translation of a constant-symbol into an immediate value, but the same concerns, for example, structures and the value of a field offset. The “C modules” offer linkage only for variables and functions, and everything else must be emulated. This way, even though the C language features constants, no one uses them because it’s known that they are actually implemented as variables, for which the language warns you if you are trying to modify them – not as immediate values.

So, if we agree that we might continue with the “emulation” method, we should also agree for generation of kinda “artificial” header files, just like we have artificial symbols. Let’s take then a simple example:

import std.core;
import std.algorithm;

export class stringview
{
	const std::string& source;

public:
    size_t b = 0, e = 0;

    stringview(const std::string& src): source(src) {}

    std::string copy();

    std::string operator+(const std::string& flw);
};

// Exported automatically from exported class
std::string stringview::copy()
{
    return source.substr(b, e);
}

std::string stringview::operator+(const std::string& flw)
{
    std::string output;
    output.reserve(e - b + flw.size());
    copy(source.begin() + b, source.begin() + e, std::back_inserter(output));
    copy(flw.begin(), flw.end(), std::back_inserter(output));
    return output;
}

// Explicit export because it's an external function
export inline std::string operator+(const std::string& fi, const stringview& flw)
{
    std::string output;
    output.reserve(flw.e - flw.b + fi.size());
    copy(fi.begin(), fi.end(), std::back_inserter(output));
    copy(flw.source.begin() + b, flw.source.begin() + e, std::back_inserter(output));
    return output;
}

Don’t worry about this code, it doesn’t make any sense. What is important is that this is being compiled this way: we keep the class as a structure, so its layout isn’t anyhow recorded in the library file, and for that we get the following header file (note that mangling method is just fictional or example, just for the needs of this article):

struct 10stringview__EM__
{
    void* __EM__filler1; // represents a hidden private field
    size_t b;
    size_t e;
};

int __N_copy_M10stringview();
int __N___pl_M10stringviewS_S();
int __N___pl_FS10stringview_S();

You may ask, what exactly is this thing for? It’s only because of the needs of the C module system. These names __N_* are names of the functions that will be used in the object file after this file is compiled. The calls of particular methods will have to be first translated into the required C form and only then linked. That is, for example, this code:

stringview sv(input);
sv.b = input.find('0');
std::string o = "o:" + sv + "ms";

will have to be translated into something of this kind:

struct 10stringview__EM__ sv;
(S*&)&sv.__EM__filler1 = &input;
sv.b = __N__find_Sc(input, '0');
S __t1 = "o:";
S __t2 = __N___pl_FS10stringview_S(__t1, sv);
S __t3 = "ms";
S o = __N___PL_MSS(sv, __t3);

What’s important here is that there’s a call to __N___pl_FS10stringview_S function that will be resolved by finding this exactly symbol in the object file that was generated from that first source file. This is more-less how it is working now – although pay attention that I showed you the desired form of the class definition, from which it is expected to generate the binary form of a file that can undergo linkage and the – artificial this time – header file that will be necessary for the use of other modules. This last translation of the user code is to show you how it should be transformed to prepare the code for the linkage. The use of sv.b is explicit and it doesn’t undergo linkage, also the initialization is resolved because it’s inline. Only the use of the operator +, actually that free function, will turn into a function call, which’s name identifies this function in the object file.

Here you can see clearly, which parts are being resolved exclusively statically, and which can be resolved as shared. You can see here, for example, that resolution of the field offsets can only be done statically – but still can be done by the C++ compiler. Different thing is if the structure is the type of the parameter passed to a function – this layout is then fixed and bound to the binary form. For class templates, everything should be resolved statically, unless you can create a universal form that can be compiled into a solid binary, which would be only parametrized by something extracted from the template parameters and their dependencies – this, however, should not be done automatically as in C++ the programmer should have control over what is common and what is “bloated”, and where the size can be sacrificed for speed and where the other way around.

And that’s exactly where it should have started. If we want to develop the module system for C++, we need to start first with defining, how it will coexist with what we have. We need to inject it into the system where you have an object file and a header file for it, we need to make a method to generate them both, and a way to translate the linkable other objects into the form “edible” by the linker.

The developer and the system

Binding with the system is the toughest part, but the desired module system must first of all take care of appropriate build system that will focus on compiling only the absolute minimum that has been affected by changes since the last build.

You know that theoretically you might be able to write the whole program in one big source file – all classes, all functions, everything, maybe except the standard library. But this doesn’t make much sense by several reasons – when you change just one function, you would like that this function only be recompiled, not everything, or at least the smallest part that contains it. If you didn’t change the function’s signature, then also functions that call this function shouldn’t be recompiled. This problem is currently solved by having this function, callable by others located in different files, in the header file, and if you don’t modify the function’s signature, you don’t modify the header file, so all files dependent on the header file are “fresh”.

This simply means that the current “C modules” system is highly dependent on the existence of the header files and the dependencies defined for the object files by having exported part defined in the header file. You want to replaced it? Then you have to preserve all the dependency system not only between the definitions in the C++ languages, but also files as a unit of ABI dependency control.

So, when you start with a statement that you have the class definition and all its method definitions in one file, you have to have a possibility to generate a header file out of it, and moreover, have this header file defined such a way that would have a defined form of “significant parts” so that when the exactly same form is generated as previously, then the header file generated after that shall not be considered refreshed. This means, for example, that you need to have some form of interface file, where for example, all methods will be put separately to files, sorted alphabetically, and also split into parts, as well as the object files using it should be able to identify which parts of this interface they are dependent on, and be considered stale only if refreshed were these parts, not just because the whole header file was refreshed.

Simply – if you want to have a module system for C++, you should forget the system of object files and header files; there’s a new format to be used, adjusted to the needs of C++, and the real object files will have to be generated only from the “dynamic part” of the code, such that could be later put into the shared library. This intermediate format will have to be added between the source files and object files, as of course, it still may happen that there would be a subproject, to be compiled together with the main project, but the subproject is written in an earlier standard and it must remain so.

The build cannot then rely on object files as they are now. Also unsure if the compiler can use files as a unit of freshness. Maybe a better solution would be some kind of database that will be updated partially and every update will have to be notified with its time so that the freshness of particular parts can be verified again. And then maybe the source would have to be kept in the database, at least for the active development time – something that Bjarne Stroustrup himself has already mentioned a long time ago.

So, in summary, we need to reconsider the following:

  1. Whether a file, as a project unit, is a good enough indication point of a single program part prone to changes and refreshing. And if not, what to use instead.
  2. How to map a source file into the project units. Currently we have a mapping from a single source implementation file (*.cpp file) and an object file, then object files can be linked together. This can be controlled by the compiler, but all you can do is to decide about the filename per source implementation file, or whether to combine multiple source files into one object file.
  3. What exactly we should be able to do with the project units, what kind of entities they may export.
  4. What should be the form of the project unit in the “binary form”, and if not object file as previously, then what. As linkage in “C modules” can only refer to a variable or function, then the object file is a form of a “template”, which can be “instantiated” by replacing the variable or function symbolic reference with the physical reference thereof.
  5. How the interface part of the unit should be defined and what features it should provide in comparison to the current “C module” interfaces, that is, bare header files.

All options open

Look: I’m not trying to show you how I’d develop a better module system for C++, just some principles that you should have in mind when developing it. If you want to base this system on the existing framework of the “C modules”, first thing is to know, how to emulate them, and what kind of limitation this feature will have because of it. Then, how to design the whole system so that the minimum changes can be tracked, as well as to be backward compatible with the “C modules” system and can interface to it. This is the first step.

Then you can think about a different linkage system, which will be able to include structure layouts, constants, and class details and resolve them at least at compile time, and then possibly to resolve some of the details at runtime.

The definition of the modules, export rules, interface management and splitting into parts isn’t all bad. It’s a good start. But for this feature to be useful, there’s still a lot of work to do.

So, a slight reminder for the standard committee: You have committed an experimental stuff not to be used by the software development, already twice. Let’s hope, this time the module definition will not have to be withdrawn from the standard, as it happened to the export template feature. But this thing is currently at best a “partial feature” that can be experimented with, which is a good thing to have, and even good to have standardized, but with annotation that this is something standardized only for the future research, not for software development use. And as such it should be at best put into a separate standard document, not into the language standard.

Posted in Uncategorized | Leave a comment