1<!--===- docs/C++style.md
2
3   Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4   See https://llvm.org/LICENSE.txt for license information.
5   SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
7-->
8
9## In brief:
10* Use *clang-format*
11from llvm 7
12on all C++ source and header files before
13every merge to master.  All code layout should be determined
14by means of clang-format.
15* Where a clear precedent exists in the project, follow it.
16* Otherwise, where [LLVM's C++ style guide](https://llvm.org/docs/CodingStandards.html#style-issues)
17is clear on usage, follow it.
18* Otherwise, where a good public C++ style guide is relevant and clear,
19  follow it.  [Google's](https://google.github.io/styleguide/cppguide.html)
20  is pretty good and comes with lots of justifications for its rules.
21* Reasonable exceptions to these guidelines can be made.
22* Be aware of some workarounds for known issues in older C++ compilers that should
23  still be able to compile f18. They are listed at the end of this document.
24
25## In particular:
26
27Use serial commas in comments, error messages, and documentation
28unless they introduce ambiguity.
29
30### Error messages
311. Messages should be a single sentence with few exceptions.
321. Fortran keywords should appear in upper case.
331. Names from the program appear in single quotes.
341. Messages should start with a capital letter.
351. Messages should not end with a period.
36
37### Files
381. File names should use dashes, not underscores.  C++ sources have the
39extension ".cpp", not ".C" or ".cc" or ".cxx".  Don't create needless
40source directory hierarchies.
411. Header files should be idempotent.  Use the usual technique:
42```
43#ifndef FORTRAN_header_H_
44#define FORTRAN_header_H_
45// code
46#endif  // FORTRAN_header_H_
47```
481. `#include` every header defining an entity that your project header or source
49file actually uses directly.  (Exception: when foo.cpp starts, as it should,
50with `#include "foo.h"`, and foo.h includes bar.h in order to define the
51interface to the module foo, you don't have to redundantly `#include "bar.h"`
52in foo.cpp.)
531. In the source file "foo.cpp", put its corresponding `#include "foo.h"`
54first in the sequence of inclusions.
55Then `#include` other project headers in alphabetic order; then C++ standard
56headers, also alphabetically; then C and system headers.
571. Don't use `#include <iostream>`.  If you need it for temporary debugging,
58remove the inclusion before committing.
59
60### Naming
611. C++ names that correspond to well-known interfaces from the STL, LLVM,
62and Fortran standard
63can and should look like their models when the reader can safely assume that
64they mean the same thing -- e.g., `clear()` and `size()` member functions
65in a class that implements an STL-ish container.
66Fortran intrinsic function names are conventionally in ALL CAPS.
671. Non-public data members should be named with leading miniscule (lower-case)
68letters, internal camelCase capitalization, and a trailing underscore,
69e.g. `DoubleEntryBookkeepingSystem myLedger_;`.  POD structures with
70only public data members shouldn't use trailing underscores, since they
71don't have class functions from which data members need to be distinguishable.
721. Accessor member functions are named with the non-public data member's name,
73less the trailing underscore.  Mutator member functions are named `set_...`
74and should return `*this`.  Don't define accessors or mutators needlessly.
751. Other class functions should be named with leading capital letters,
76CamelCase, and no underscores, and, like all functions, should be based
77on imperative verbs, e.g. `HaltAndCatchFire()`.
781. It is fine to use short names for local variables with limited scopes,
79especially when you can declare them directly in a `for()`/`while()`/`if()`
80condition.  Otherwise, prefer complete English words to abbreviations
81when creating names.
82
83### Commentary
841. Use `//` for all comments except for short `/*notes*/` within expressions.
851. When `//` follows code on a line, precede it with two spaces.
861. Comments should matter.  Assume that the reader knows current C++ at least as
87well as you do and avoid distracting her by calling out usage of new
88features in comments.
89
90### Layout
91Always run `clang-format` on your changes before committing code. LLVM
92has a `git-clang-format` script to facilitate running clang-format only
93on the lines that have changed.
94
95Here's what you can expect to see `clang-format` do:
961. Indent with two spaces.
971. Don't indent public:, protected:, and private:
98accessibility labels.
991. Never use more than 80 characters per source line.
1001. Don't use tabs.
1011. Don't indent the bodies of namespaces, even when nested.
1021. Function result types go on the same line as the function and argument
103names.
104
105Don't try to make columns of variable names or comments
106align vertically -- they are maintenance problems.
107
108Always wrap the bodies of `if()`, `else`, `while()`, `for()`, `do`, &c.
109with braces, even when the body is a single statement or empty.  The
110opening `{` goes on
111the end of the line, not on the next line.  Functions also put the opening
112`{` after the formal arguments or new-style result type, not on the next
113line.  Use `{}` for empty inline constructors and destructors in classes.
114
115If any branch of an `if`/`else if`/`else` cascade ends with a return statement,
116they all should, with the understanding that the cases are all unexceptional.
117When testing for an error case that should cause an early return, do so with
118an `if` that doesn't have a following `else`.
119
120Don't waste space on the screen with needless blank lines or elaborate block
121commentary (lines of dashes, boxes of asterisks, &c.).  Write code so as to be
122easily read and understood with a minimum of scrolling.
123
124Avoid using assignments in controlling expressions of `if()` &c., even with
125the idiom of wrapping them with extra parentheses.
126
127In multi-element initializer lists (especially `common::visitors{...}`),
128including a comma after the last element often causes `clang-format` to do
129a better jobs of formatting.
130
131### C++ language
132Use *C++17*, unless some compiler to which we must be portable lacks a feature
133you are considering.
134However:
1351. Never throw or catch exceptions.
1361. Never use run-time type information or `dynamic_cast<>`.
1371. Never declare static data that executes a constructor.
138   (This is why `#include <iostream>` is contraindicated.)
1391. Use `{braced initializers}` in all circumstances where they work, including
140default data member initialization.  They inhibit implicit truncation.
141Don't use `= expr` initialization just to effect implicit truncation;
142prefer an explicit `static_cast<>`.
143With C++17, braced initializers work fine with `auto` too.
144Sometimes, however, there are better alternatives to empty braces;
145e.g., prefer `return std::nullopt;` to `return {};` to make it more clear
146that the function's result type is a `std::optional<>`.
1471. Avoid unsigned types apart from `size_t`, which must be used with care.
148When `int` just obviously works, just use `int`.  When you need something
149bigger than `int`, use `std::int64_t` rather than `long` or `long long`.
1501. Use namespaces to avoid conflicts with client code.  Use one top-level
151`Fortran` project namespace.  Don't introduce needless nested namespaces within the
152project when names don't conflict or better solutions exist.  Never use
153`using namespace ...;` outside test code; never use `using namespace std;`
154anywhere.  Access STL entities with names like `std::unique_ptr<>`,
155without a leading `::`.
1561. Prefer `static` functions over functions in anonymous namespaces in source files.
1571. Use `auto` judiciously.  When the type of a local variable is known,
158monomorphic, and easy to type, be explicit rather than using `auto`.
159Don't use `auto` functions unless the type of the result of an outlined member
160function definition can be more clear due to its use of types declared in the
161class.
1621. Use move semantics and smart pointers to make dynamic memory ownership
163clear.  Consider reworking any code that uses `malloc()` or a (non-placement)
164`operator new`.
165See the section on Pointers below for some suggested options.
1661. When defining argument types, use values when object semantics are
167not required and the value is small and copyable without allocation
168(e.g., `int`);
169use `const` or rvalue references for larger values (e.g., `std::string`);
170use `const` references to rather than pointers to immutable objects;
171and use non-`const` references for mutable objects, including "output" arguments
172when they can't be function results.
173Put such output arguments last (_pace_ the standard C library conventions for `memcpy()` & al.).
1741. Prefer `typename` to `class` in template argument declarations.
1751. Prefer `enum class` to plain `enum` wherever `enum class` will work.
176We have an `ENUM_CLASS` macro that helps capture the names of constants.
1771. Use `constexpr` and `const` generously.
1781. When a `switch()` statement's labels do not cover all possible case values
179explicitly, it should contain either a `default:;` at its end or a
180`default:` label that obviously crashes; we have a `CRASH_NO_CASE` macro
181for such situations.
1821. On the other hand, when a `switch()` statement really does cover all of
183the values of an `enum class`, please insert a call to the `SWITCH_COVERS_ALL_CASES`
184macro at the top of the block.  This macro does the right thing for G++ and
185clang to ensure that no warning is emitted when the cases are indeed all covered.
1861. When using `std::optional` values, avoid unprotected access to their content.
187This is usually by means of `x.has_value()` guarding execution of `*x`.
188This is implicit when they are function results assigned to local variables
189in `if`/`while` predicates.
190When no presence test is obviously protecting a `*x` reference to the
191contents, and it is assumed that the contents are present, validate that
192assumption by using `x.value()` instead.
1931. We use `c_str()` rather than `data()` when converting a `std::string`
194to a `const char *` when the result is expected to be NUL-terminated.
1951. Avoid explicit comparisions of pointers to `nullptr` and tests of
196presence of `optional<>` values with `.has_value()` in the predicate
197expressions of control flow statements, but prefer them to implicit
198conversions to `bool` when initializing `bool` variables and arguments,
199and to the use of the idiom `!!`.
200
201#### Classes
2021. Define POD structures with `struct`.
2031. Don't use `this->` in (non-static) member functions, unless forced to
204do so in a template member function.
2051. Define accessor and mutator member functions (implicitly) inline in the
206class, after constructors and assignments.  Don't needlessly define
207(implicit) inline member functions in classes unless they really solve a
208performance problem.
2091. Try to make class definitions in headers concise specifications of
210interfaces, at least to the extent that C++ allows.
2111. When copy constructors and copy assignment are not necessary,
212and move constructors/assignment is present, don't declare them and they
213will be implicitly deleted.  When neither copy nor move constructors
214or assignments should exist for a class, explicitly `=delete` all of them.
2151. Make single-argument constructors (other than copy and move constructors)
216'explicit' unless you really want to define an implicit conversion.
217
218#### Pointers
219There are many -- perhaps too many -- means of indirect addressing
220data in this project.
221Some of these are standard C++ language and library features,
222while others are local inventions in `lib/Common`:
223* Bare pointers (`Foo *p`): these are obviously nullable, non-owning,
224undefined when uninitialized, shallowly copyable, reassignable, and often
225not the right abstraction to use in this project.
226But they can be the right choice to represent an optional
227non-owning reference, as in a function result.
228Use the `DEREF()` macro to convert a pointer to a reference that isn't
229already protected by an explicit test for null.
230* References (`Foo &r`, `const Foo &r`): non-nullable, not owning,
231shallowly copyable, and not reassignable.
232References are great for invisible indirection to objects whose lifetimes are
233broader than that of the reference.
234Take care when initializing a reference with another reference to ensure
235that a copy is not made because only one of the references is `const`;
236this is a pernicious C++ language pitfall!
237* Rvalue references (`Foo &&r`): These are non-nullable references
238*with* ownership, and they are ubiquitously used for formal arguments
239wherever appropriate.
240* `std::reference_wrapper<>`: non-nullable, not owning, shallowly
241copyable, and (unlike bare references) reassignable, so suitable for
242use in STL containers and for data members in classes that need to be
243copyable or assignable.
244* `common::Reference<>`: like `std::reference_wrapper<>`, but also supports
245move semantics, member access, and comparison for equality; suitable for use in
246`std::variant<>`.
247* `std::unique_ptr<>`: A nullable pointer with ownership, null by default,
248not copyable, reassignable.
249F18 has a helpful `Deleter<>` class template that makes `unique_ptr<>`
250easier to use with forward-referenced data types.
251* `std::shared_ptr<>`: A nullable pointer with shared ownership via reference
252counting, null by default, shallowly copyable, reassignable, and slow.
253* `Indirection<>`: A non-nullable pointer with ownership and
254optional deep copy semantics; reassignable.
255Often better than a reference (due to ownership) or `std::unique_ptr<>`
256(due to non-nullability and copyability).
257Can be wrapped in `std::optional<>` when nullability is required.
258Usable with forward-referenced data types with some use of `extern template`
259in headers and explicit template instantiation in source files.
260* `CountedReference<>`: A nullable pointer with shared ownership via
261reference counting, null by default, shallowly copyable, reassignable.
262Safe to use *only* when the data are private to just one
263thread of execution.
264Used sparingly in place of `std::shared_ptr<>` only when the overhead
265of that standard feature is prohibitive.
266
267A feature matrix:
268
269| indirection           | nullable | default null | owning | reassignable | copyable          | undefined type ok? |
270| -----------           | -------- | ------------ | ------ | ------------ | --------          | ------------------ |
271| `*p`                  | yes      | no           | no     | yes          | shallowly         | yes                |
272| `&r`                  | no       | n/a          | no     | no           | shallowly         | yes                |
273| `&&r`                 | no       | n/a          | yes    | no           | shallowly         | yes                |
274| `reference_wrapper<>` | no       | n/a          | no     | yes          | shallowly         | yes                |
275| `Reference<>`         | no       | n/a          | no     | yes          | shallowly         | yes                |
276| `unique_ptr<>`        | yes      | yes          | yes    | yes          | no                | yes, with work     |
277| `shared_ptr<>`        | yes      | yes          | yes    | yes          | shallowly         | no                 |
278| `Indirection<>`       | no       | n/a          | yes    | yes          | optionally deeply | yes, with work     |
279| `CountedReference<>`  | yes      | yes          | yes    | yes          | shallowly         | no                 |
280
281### Overall design preferences
282Don't use dynamic solutions to solve problems that can be solved at
283build time; don't solve build time problems by writing programs that
284produce source code when macros and templates suffice; don't write macros
285when templates suffice.  Templates are statically typed, checked by the
286compiler, and are (or should be) visible to debuggers.
287
288### Exceptions to these guidelines
289Reasonable exceptions will be allowed; these guidelines cannot anticipate
290all situations.
291For example, names that come from other sources might be more clear if
292their original spellings are preserved rather than mangled to conform
293needlessly to the conventions here, as Google's C++ style guide does
294in a way that leads to weirdly capitalized abbreviations in names
295like `Http`.
296Consistency is one of many aspects in the pursuit of clarity,
297but not an end in itself.
298
299## C++ compiler bug workarounds
300Below is a list of workarounds for C++ compiler bugs met with f18 that, even
301if the bugs are fixed in latest C++ compiler versions, need to be applied so
302that all desired tool-chains can compile f18.
303
304### Explicitly move noncopyable local variable into optional results
305
306The following code is legal C++ but fails to compile with the
307default Ubuntu 18.04 g++ compiler (7.4.0-1ubuntu1~18.0.4.1):
308
309```
310class CantBeCopied {
311 public:
312 CantBeCopied(const CantBeCopied&) = delete;
313 CantBeCopied(CantBeCopied&&) = default;
314 CantBeCopied() {}
315};
316std::optional<CantBeCopied> fooNOK() {
317  CantBeCopied result;
318  return result; // Legal C++, but does not compile with Ubuntu 18.04 default g++
319}
320std::optional<CantBeCopied> fooOK() {
321  CantBeCopied result;
322  return {std::move(result)}; // Compiles OK everywhere
323}
324```
325The underlying bug is actually not specific to `std::optional` but this is the most common
326case in f18 where the issue may occur. The actual bug can be reproduced with any class `B`
327that has a perfect forwarding constructor taking `CantBeCopied` as argument:
328`template<typename CantBeCopied> B(CantBeCopied&& x) x_{std::forward<CantBeCopied>(x)} {}`.
329In such scenarios, Ubuntu 18.04 g++ fails to instantiate the move constructor
330and to construct the returned value as it should, instead it complains about a
331missing copy constructor.
332
333Local result variables do not need to and should not be explicitly moved into optionals
334if they have a copy constructor.
335