c++clang-formatautoformatting

clang-format ignore `**` when auto-formatting


In our department we are using a simplified implementation of C++ for our engineers to code their calculations, which is then translated to C++ before compilation. To bring the whole code base, C++ and the simplified implementation, to the same style, we want to make use of a formatter, preferably clang-format. Unluckily one simplification won't work with clang-format:

As a consequence, clang-format interprets ** as a "pointer to a pointer" and applies formatting, which is breaking the equation.

question

Is there any way in clang-format to either:

A method of last resort could also include using other tools such as uncrustify, but I'd really like to avoid this.


Solution

  • As of course guessed in the comments, my suggestion is to temporarily replace the ** operator with another for the duration of the formatting. This requires that the target operator be otherwise unused, of course: escaping doesn’t work very well when you need a parser to understand the result. Ideally, it should be nearly the same lexical length to avoid bad formatting after restoring the original.

    It also helps if the replacement has nearly the same precedence as the real operator. That hasn’t been specified here, but it surely has at least that of multiplication.

    All of these considerations suggest ->*: it’s already a rare operator, has a precedence only one away from *, /, and %, and is either one character longer or shorter depending on whitespace preferences.