Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In clang-format, what do the penalties do?

The clang-format sytle options documentation includes a number of options called PenaltyXXX. The documentation doesn't explain how these penalties should be used. Can you describe how to use these penalty values and what effect they achieve (perhaps with an example)?

like image 274
Scott Langham Avatar asked Oct 29 '14 16:10

Scott Langham


People also ask

How does clang-format work?

clang-format is a tool to automatically format C/C++/Objective-C code, so that developers don't need to worry about style issues during code reviews. It is highly recommended to format your changed C++ code before opening pull requests, which will save you and the reviewers' time.

Can clang-format break code?

Short answer: YES. The clang-format tool has a -sort-includes option. Changing the order of #include directives can definitely change the behavior of existing code, and may break existing code.

What is clang-format style?

Clang-Format Style Options are flags that are supported by the ClangFormat tool, which became the de-facto standard to format C++ code. Clang offers the option to use one of the predefined styles (LLVM, Google, Chromium, Mozilla, WebKit, Microsoft) or to create a custom configuration by using the given flags.

What is clang-format default style?

clang-format file uses YAML format: key1: value1 key2: value2 # A comment. ... The configuration file can consist of several sections each having different Language: parameter denoting the programming language this section of the configuration is targeted at.


1 Answers

When you have a line that's over the line length limit, clang-format will need to insert one or more breaks somewhere. You can think of penalties as a way of discouraging certain line-breaking behavior. For instance, say you have:

Namespaces::Are::Pervasive::SomeReallyVerySuperDuperLongFunctionName(args); // and the column limit is here:                                        ^ 

Clang-format will probably format to look a little strange:

Namespaces::Are::Pervasive::SomeReallyVerySuperDuperLongFunctionName(     args); 

You might decide that you're willing to violate the line length by a character or two for cases like this, so you could steer that by setting the PenaltyExcessCharacter to a low number and PenaltyBreakBeforeFirstCallParameter to a higher number.

Personally, I really dislike when the return type is on its own line, so I set PenaltyReturnTypeOnItsOwnLine to an absurdly large number.

An aside, this system was inherited from Latex, which allows you to specify all kinds of penalties for line-breaking, pagination, and hyphenation.

like image 83
JHumphrey Avatar answered Sep 21 '22 05:09

JHumphrey