Require C++14
[alexxy/gromacs.git] / docs / dev-manual / language-features.rst
1 Allowed language features
2 =========================
3
4 Most of these are not strict rules, but you should have a very good
5 reason for deviating from them.
6
7 Portability considerations
8 ^^^^^^^^^^^^^^^^^^^^^^^^^^
9
10 Most |Gromacs| files compile as C++14, but some files remain that compile as C99.
11 C++ has a lot of features, but to keep the source code maintainable and easy to read, 
12 we will avoid using some of them in |Gromacs| code. The basic principle is to keep things 
13 as simple as possible.
14 For compatiblity, certain work-arounds are required because not all compilers support 
15 these standards fully.
16
17 * MSVC supports only a subset of C99 and work-arounds are required in those cases.
18 * We should be able to use virtually all C++11 features outside of OpenCL kernels
19   (which compile as C), and for consistency also in CUDA kernels.
20
21 C++ Standard Library
22 --------------------
23
24 |Gromacs| code must support the lowest common denominator of C++14 standard library
25 features available on supported platforms.
26 Some modern features are useful enough to warrant back-porting.
27 Consistent and forward-compatible headers are provided in ``src/gromacs/compat/``
28 as described in the `Library documentation <../doxygen/html-lib/group__group__compatibility.xhtml>`_
29
30 General considerations
31 ^^^^^^^^^^^^^^^^^^^^^^
32 As a baseline, |Gromacs| follows the C++ Core Guidelines |linkref1|, unless
33 our own more specific guidelines below say otherwise. We tend to be more restrictive
34 in some areas, both because we depend on the code compiling with a lot of different
35 C++ compilers, and because we want to increase readability. However, |Gromacs| is an
36 advanced projects in constant development, and as our needs evolve we will both
37 relax and tighten many of these points. Some of these changes happen naturally as
38 part of agreements in code review, while major parts where we don't agree should be
39 pushed to a redmine thread. Large changes should be suggested early in the development
40 cycle for each release so we avoid being hit by last-minute compiler bugs just before
41 a release.
42
43 * Use namespaces. Everything in ``libgromacs`` should be in a ``gmx``
44   namespace. Don't use using in headers except possibly for aliasing
45   some commonly-used names, and avoid file-level blanket ``using
46   namespace gmx`` and similar. If only a small number of ``gmx``
47   namespace symbols needed in a not-yet-updated file, consider
48   importing just those symbols. See also |linkref2|.
49 * Use STL, but do not use iostreams outside of the unit tests. iostreams can have
50   a negative impact on performance compared to other forms 
51   of string streams, depending on the use case. Also, they don't always
52   play well with using C ``stdio`` routines at the same time, which
53   are used extensively in the current code. However, since Google tests
54   rely on iostreams, you should use it in the unit test code.
55 * Don't use non-const references as function parameters. They make it
56   impossible to tell whether a variable passed as a parameter may
57   change as a result of a function call without looking up the
58   prototype.
59 * Use ``not_null<T>`` pointers wherever possible to convey the
60   semantics that a pointer to a valid is required, and a reference
61   is inappropriate. See also |linkrefnotnull|.
62 * Don't use C-style casts; use ``const_cast``, ``static_cast`` or
63   ``reinterpret_cast as appropriate``. See the point on RTTI for
64   ``dynamic_cast``. For emphasizing type (e.g. intentional integer division)
65   use constructor syntax. For creating real constants use the user-defined literal
66   _real (e.g. 2.5_real instead of static_cast<real>(2.5)).
67 * Avoid overloading functions unless all variants really do the same
68   thing, just with different types. Instead, consider making the
69   function names more descriptive.
70 * Avoid using default function arguments. They can lead to the code
71   being less readable than without (see |linkref3|). If you think that your specific
72   case improves readability (see |linkref4|), you can justify their use.
73 * Don't overload operators before thorough consideration whether it
74   really is the best thing to do. Never overload ``&&``, ``||``, or
75   the comma operator, because it's impossible to keep their original
76   behavior with respect to evaluation order.
77 * Try to avoid complex templates, complex template specialization or
78   techniques like SFINAE as much as possible. If nothing else, they
79   can make the code more difficult to understand.
80 * Don't use multiple inheritance. Inheriting from multiple pure
81   interfaces is OK, as long as at most one base class (which should be
82   the first base class) has any code. Please also refer to the
83   explanation |linkref5| and |linkref6|.
84 * Don't write excessively deep inheritance graphs. Try to not inherit
85   implementation just to save a bit of coding; follow the principle
86   "inherit to be reused, not to reuse." Also, you should not
87   mix implementation and interface inheritance. For explanation please
88   see |linkref7|.
89 * Don't include unnecessary headers.
90 * Make liberal use of assertions to help document your intentions (but
91   prefer to write the code such that no assertion is necessary).
92 * Prefer ``GMX_ASSERT()`` and ``GMX_RELEASE_ASSERT()`` to naked
93   ``assert()`` because the former permit you to add descriptive text.
94 * Use gmx::Mutex rather than pthreads, std or raw thread-MPI mutexes.
95 * Use proper enums for variable whose type can only contain one of a
96   limited set of values. C++ is much better than C in catching errors
97   in such code. Ideally, all enums should be typed enums, please
98   see |linkref8|. 
99 * When writing a new class, think whether it will be necessary to make
100   copies of that class. If not, declare the copy constructor and the
101   assignment operator as private and don't define them, making any
102   attempt to copy objects of that class fail. If you allow copies,
103   either provide the copy constructor and the assignment operator, or
104   write a clear comment that the compiler-generated ones will do (and
105   make sure that they do what you
106   want). ``src/gromacs/utility/classhelpers.h`` has some convenience
107   macros for doing this well.
108   You can also use deleted functions in this case.
109 * Declare all constructors with one parameter as explicit unless you
110   really know what you are doing. Otherwise, they can be used for
111   implicit type conversions, which can make the code difficult to
112   understand, or even hide bugs that would be otherwise reported by
113   the compiler. For the same reason, don't declare operators for
114   converting your classes to other types without thorough
115   consideration. For an explanation, please see |linkref9|.
116 * Write const-correct code (no ``const_cast`` unless absolutely
117   necessary).
118 * Avoid using RTTI (run-time type information, in practice
119   ``dynamic_cast`` and ``typeid``) unless you really need it. The cost
120   of RTTI is very high, both in binary size (which you always
121   pay if you compile with it) and in execution time (which you pay
122   only if you use it). If your problem seems to require RTTI, think
123   about whether there would be an alternative design that
124   wouldn't. Such alternative designs are often better.
125 * Don't depend on compiler metadata propagation. struct elements
126   and captured lambda parameters tend to have ``restrict`` and
127   alignment qualifiers discarded by compilers, so when you later
128   define an instance of that structure or allocate memory to
129   hold it, the data member might not be aligned at all.
130 * Plan for code that runs in compute-sensitive kernels to have useful
131   data layout for re-use, alignment for SIMD memory operations
132 * Recognize that some parts of the code have different requirements -
133   compute kernels, mdrun setup code, high-level MD-loop code,
134   simulation setup tools, and analysis tools have different needs, and
135   the trade-off point between correctness vs reviewer time vs
136   developer time vs compile time vs run time will differ.
137
138
139 .. |linkref1| replace:: `c++ guidelines <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines>`__
140 .. |linkref2| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#sf7-dont-write-using-namespace-in-a-header-file>`__
141 .. |linkref3| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#i23-keep-the-number-of-function-arguments-low>`__
142 .. |linkref4| replace:: `here <https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#f51-where-there-is-a-choice-prefer-default-arguments-over-overloading>`__
143 .. |linkref5| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c135-use-multiple-inheritance-to-represent-multiple-distinct-interfaces>`__
144 .. |linkref6| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c136-use-multiple-inheritance-to-represent-the-union-of-implementation-attributes>`__
145 .. |linkref7| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#c129-when-designing-a-class-hierarchy-distinguish-between-implementation-inheritance-and-interface-inheritance>`__
146 .. |linkref8| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Renum-class>`__
147 .. |linkref9| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-explicit>`__
148 .. |linkrefnotnull| replace:: `here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Ri-nullptr> and here <http://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-nullptr>`__
149
150 .. _implementing exceptions:
151
152 Implementing exceptions for error handling
153 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
154 See :ref:`error handling` for the approach to handling run-time
155 errors, ie. use exceptions.
156
157 * Write exception-safe code. All new code has to offer at least the
158   basic or nothrow guarantee to make this feasible.
159 * Use std (or custom) containers wherever possible.
160 * Use smart pointers for memory management. By default, use
161   ``std::unique_ptr`` and ``gmx::unique_cptr`` in assocation with any
162   necessary raw ``new`` or ``snew`` calls. ``std::shared_ptr`` can be
163   used wherever responsibility for lifetime must be shared.
164   Never use ``malloc``.
165 * Use RAII for managing resources (memory, mutexes, file handles, ...).
166 * It is preferable to avoid calling a function which might throw an
167   exception from a legacy function which is not exception safe. However,
168   we make the practical exception to permit the use of features such
169   as ``std::vector`` and ``std::string`` that could throw
170   ``std::bad_alloc`` when out of memory. In particular, |Gromacs| has
171   a lot of old C-style memory handling that checking tools continue
172   to issue valid warnings about as the tools acquire more
173   functionality, and fixing these with old constructs is an
174   inefficient use of developer time.
175 * Functions / methods should be commented whether they are exception
176   safe, whether they might throw an exception (even indirectly), and
177   if so, which exception(s) they might throw.
178
179 Preprocessor considerations
180 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
181 * Don't use preprocessor defines for things other than directly
182   related to configuring the build. Use templates or inline functions
183   to generate code, and enums or const variables for constants.
184 * Preprocessing variables used for configuring the build should be
185   organized so that a valid value is always defined, i.e. we never
186   test whether one of our preprocessor variables is defined, rather we
187   test what value it has. This is much more robust under maintance,
188   because a compiler can tell you that the variable is undefined.
189 * Avoid code with lengthy segments whose compilation depends on #if
190   (or worse, #ifdef).
191 * Prefer to organize the definition of a const variable at the top of
192   the source code file, and use that in the code.  This helps keep all
193   compilation paths built in all configurations, which reduces the
194   incidence of silent bugs.
195 * Indent nested preprocessor conditions if nesting is necessary and
196   the result looks clearer than without indenting.
197 * Please strongly consider a comment repeating the preprocessor condition at the end
198   of the region, if a lengthy region is neccessary and benefits from
199   that. For long regions this greatly helps in understanding 
200   and debugging the code.