Skip to content

Commit 5971647

Browse files
authored
[libc++] Add coding guidelines to the docs (#117051)
We have a buch of coding guidelines which are either documented as design docs, which aren't really applicable or not at all. This moves coding guidelines we have currently in the design docs into a separate file and adds a bunch of guidelines which we have but aren't documented anywhere.
1 parent 81c8813 commit 5971647

File tree

5 files changed

+185
-161
lines changed

5 files changed

+185
-161
lines changed

libcxx/docs/CodingGuidelines.rst

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
.. _CodingGuidelines:
2+
3+
========================
4+
libc++ Coding Guidelines
5+
========================
6+
7+
.. contents::
8+
:local:
9+
10+
Use ``__ugly_names`` for implementation details
11+
===============================================
12+
13+
Libc++ uses ``__ugly_names`` or ``_UglyNames`` for implementation details. These names are reserved for implementations,
14+
so users may not use them in their own applications. When using a name like ``T``, a user may have defined a macro that
15+
changes the meaning of ``T``. By using ``__ugly_names`` we avoid that problem.
16+
17+
This is partially enforced by the clang-tidy check ``readability-identifier-naming`` and
18+
``libcxx/test/libcxx/system_reserved_names.gen.py``.
19+
20+
Don't use argument-dependent lookup unless required by the standard
21+
===================================================================
22+
23+
Unqualified function calls are susceptible to
24+
`argument-dependent lookup (ADL) <https://en.cppreference.com/w/cpp/language/adl>`_. This means calling
25+
``move(UserType)`` might not call ``std::move``. Therefore, function calls must use qualified names to avoid ADL. Some
26+
functions in the standard library `require ADL usage <http://eel.is/c++draft/contents#3>`_. Names of classes, variables,
27+
concepts, and type aliases are not subject to ADL. They don't need to be qualified.
28+
29+
Function overloading also applies to operators. Using ``&user_object`` may call a user-defined ``operator&``. Use
30+
``std::addressof`` instead. Similarly, to avoid invoking a user-defined ``operator,``, make sure to cast the result to
31+
``void`` when using the ``,`` or avoid it in the first place. For example:
32+
33+
.. code-block:: cpp
34+
35+
for (; __first1 != __last1; ++__first1, (void)++__first2) {
36+
...
37+
}
38+
39+
This is mostly enforced by the clang-tidy checks ``libcpp-robust-against-adl`` and ``libcpp-qualify-declval``.
40+
41+
Avoid including public headers
42+
==============================
43+
44+
libc++ uses implementation-detail headers for most code. These are in a directory that starts with two underscores
45+
(e.g. ``<__type_traits/decay.h>``). These detail headers are significantly smaller than their public counterparts.
46+
This reduces the amount of code that is included in a single public header, which reduces compile times.
47+
48+
Add ``_LIBCPP_HIDE_FROM_ABI`` unless you know better
49+
====================================================
50+
51+
``_LIBCPP_HIDE_FROM_ABI`` should be on every function in the library unless there is a reason not to do so. The main
52+
reason not to add ``_LIBCPP_HIDE_FROM_ABI`` is if a function is exported from the libc++ built library. In that case the
53+
function should be marked with ``_LIBCPP_EXPORTED_FROM_ABI``. Virtual functions should be marked with
54+
``_LIBCPP_HIDE_FROM_ABI_VIRTUAL`` instead.
55+
56+
This is mostly enforced by the clang-tidy checks ``libcpp-hide-from-abi`` and ``libcpp-avoid-abi-tag-on-virtual``.
57+
58+
Define configuration macros to 0 or 1
59+
=====================================
60+
61+
Macros should usually be defined in all configurations, instead of defining them when they're enabled and leaving them
62+
undefined otherwise. For example, use
63+
64+
.. code-block:: cpp
65+
66+
#if SOMETHING
67+
# define _LIBCPP_SOMETHING_ENABLED 1
68+
#else
69+
# define _LIBCPP_SOMETHING_ENABLED 0
70+
#endif
71+
72+
and then check for ``#if _LIBCPP_SOMETHING_ENABLED`` instead of
73+
74+
.. code-block:: cpp
75+
76+
#if SOMETHING
77+
# define _LIBCPP_SOMETHING_ENABLED
78+
#endif
79+
80+
and then checking for ``#ifdef _LIBCPP_SOMETHING_ENABLED``.
81+
82+
This makes it significantly easier to catch missing includes, since Clang and GCC will warn when using and undefined
83+
marco inside an ``#if`` statement when using ``-Wundef``. Some macros in libc++ don't use this style yet, so this only
84+
applies when introducing a new macro.
85+
86+
This is partially enforced by the clang-tidy check ``libcpp-internal-ftms``.
87+
88+
Use ``_LIBCPP_STD_VER``
89+
=======================
90+
91+
libc++ defines the macro ``_LIBCPP_STD_VER`` for the different libc++ dialects. This should be used instead of
92+
``__cplusplus``.
93+
94+
This is mostly enforced by the clang-tidy check ``libcpp-cpp-version-check``.
95+
96+
Use ``__ugly__`` spellings of vendor attributes
97+
===============================================
98+
99+
Vendor attributes should always be ``__uglified__`` to avoid naming clashes with user-defined macros. For gnu-style
100+
attributes this takes the form ``__attribute__((__foo__))``. C++11-style attributes look like ``[[_Clang::__foo__]]`` or
101+
``[[__gnu__::__foo__]]`` for Clang or GCC attributes respectively. Clang and GCC also support standard attributes in
102+
earlier language dialects than they were introduced. These should be spelled as ``[[__foo__]]``. MSVC currently doesn't
103+
provide alternative spellings for their attributes, so these should be avoided if at all possible.
104+
105+
This is enforced by the clang-tidy check ``libcpp-uglify-attributes``.
106+
107+
Use C++11 extensions in C++03 code if they simplify the code
108+
============================================================
109+
110+
libc++ only supports Clang in C++98/03 mode. Clang provides many C++11 features in C++03, making it possible to write a
111+
lot of code in a simpler way than if we were restricted to C++03 features. Some use of extensions is even mandatory,
112+
since libc++ supports move semantics in C++03.
113+
114+
Use ``using`` aliases instead of ``typedef``
115+
============================================
116+
117+
``using`` aliases are generally easier to read and support templates. Some code in libc++ uses ``typedef`` for
118+
historical reasons.
119+
120+
Write SFINAE with ``requires`` clauses in C++20-only code
121+
=========================================================
122+
123+
``requires`` clauses can be significantly easier to read than ``enable_if`` and friends in some cases, since concepts
124+
subsume other concepts. This means that overloads based on traits can be written without negating more general cases.
125+
They also show intent better.
126+
127+
Write ``enable_if`` as ``enable_if_t<conditon, int> = 0``
128+
=========================================================
129+
130+
The form ``enable_if_t<condition, int> = 0`` is the only one that works in every language mode and for overload sets
131+
using the same template arguments otherwise. If the code must work in C++11 or C++03, the libc++-internal alias
132+
``__enable_if_t`` can be used instead.
133+
134+
Prefer alias templates over class templates
135+
===========================================
136+
137+
Alias templates are much more lightweight than class templates, since they don't require new instantiations for
138+
different types. If the only member of a class is an alias, like in type traits, alias templates should be used if
139+
possible. They do force more eager evaluation though, which can be a problem in some cases.
140+
141+
Apply ``[[nodiscard]]`` where relevant
142+
======================================
143+
144+
Libc++ adds ``[[nodiscard]]`` whenever relevant to catch potential bugs. The standards committee has decided to _not_
145+
have a recommended practice where to put them, so libc++ applies it whenever it makes sense to catch potential bugs.
146+
147+
``[[nodiscard]]`` should be applied to functions
148+
149+
- where discarding the return value is most likely a correctness issue. For example a locking constructor in
150+
``unique_lock``.
151+
152+
- where discarding the return value likely points to the user wanting to do something different. For example
153+
``vector::empty()``, which probably should have been ``vector::clear()``.
154+
155+
This can help spotting bugs easily which otherwise may take a very long time to find.
156+
157+
- which return a constant. For example ``numeric_limits::min()``.
158+
- which only observe a value. For example ``string::size()``.
159+
160+
Code that discards values from these kinds of functions is dead code. It can either be removed, or the programmer
161+
meant to do something different.
162+
163+
- where discarding the value is most likely a misuse of the function. For example ``std::find(first, last, val)``.
164+
165+
This protects programmers from assuming too much about how the internals of a function work, making code more robust
166+
in the presence of future optimizations.
167+
168+
Applications of ``[[nodiscard]]`` are code like any other code, so we aim to test them on public interfaces. This can be
169+
done with a ``.verify.cpp`` test. Many examples are available. Just look for tests with the suffix
170+
``.nodiscard.verify.cpp``.

libcxx/docs/Contributing.rst

Lines changed: 14 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -36,56 +36,10 @@ Every change in libc++ must come with appropriate tests. Libc++ has an extensive
3636
should be run locally by developers before submitting patches and is also run as part of our CI
3737
infrastructure. The documentation about writing tests and running them is :ref:`here <testing>`.
3838

39-
Coding standards
40-
================
39+
Coding Guidelines
40+
=================
4141

42-
In general, libc++ follows the `LLVM Coding Standards <https://llvm.org/docs/CodingStandards.html>`_.
43-
There are some deviations from these standards.
44-
45-
Libc++ uses ``__ugly_names``. These names are reserved for implementations, so
46-
users may not use them in their own applications. When using a name like ``T``,
47-
a user may have defined a macro that changes the meaning of ``T``. By using
48-
``__ugly_names`` we avoid that problem. Other standard libraries and compilers
49-
use these names too. To avoid common clashes with other uglified names used in
50-
other implementations (e.g. system headers), the test in
51-
``libcxx/test/libcxx/system_reserved_names.gen.py`` contains the list of
52-
reserved names that can't be used.
53-
54-
Unqualified function calls are susceptible to
55-
`argument-dependent lookup (ADL) <https://en.cppreference.com/w/cpp/language/adl>`_.
56-
This means calling ``move(UserType)`` might not call ``std::move``. Therefore,
57-
function calls must use qualified names to avoid ADL. Some functions in the
58-
standard library `require ADL usage <http://eel.is/c++draft/contents#3>`_.
59-
Names of classes, variables, concepts, and type aliases are not subject to ADL.
60-
They don't need to be qualified.
61-
62-
Function overloading also applies to operators. Using ``&user_object`` may call
63-
a user-defined ``operator&``. Use ``std::addressof`` instead. Similarly, to
64-
avoid invoking a user-defined ``operator,``, make sure to cast the result to
65-
``void`` when using the ``,``. For example:
66-
67-
.. code-block:: cpp
68-
69-
for (; __first1 != __last1; ++__first1, (void)++__first2) {
70-
...
71-
}
72-
73-
In general, try to follow the style of existing code. There are a few
74-
exceptions:
75-
76-
- Prefer ``using foo = int`` over ``typedef int foo``. The compilers supported
77-
by libc++ accept alias declarations in all standard modes.
78-
79-
Other tips are:
80-
81-
- Keep the number of formatting changes in patches minimal.
82-
- Provide separate patches for style fixes and for bug fixes or features. Keep in
83-
mind that large formatting patches may cause merge conflicts with other patches
84-
under review. In general, we prefer to avoid large reformatting patches.
85-
- Keep patches self-contained. Large and/or complicated patches are harder to
86-
review and take a significant amount of time. It's fine to have multiple
87-
patches to implement one feature if the feature can be split into
88-
self-contained sub-tasks.
42+
libc++'s coding guidelines are documented :ref:`here <CodingGuidelines>`.
8943

9044

9145
Resources
@@ -186,6 +140,17 @@ rule -- for very simple patches, use your judgement. The `"libc++" review group
186140
consists of frequent libc++ contributors with a good understanding of the project's
187141
guidelines -- if you would like to be added to it, please reach out on Discord.
188142

143+
Some tips:
144+
145+
- Keep the number of formatting changes in patches minimal.
146+
- Provide separate patches for style fixes and for bug fixes or features. Keep in
147+
mind that large formatting patches may cause merge conflicts with other patches
148+
under review. In general, we prefer to avoid large reformatting patches.
149+
- Keep patches self-contained. Large and/or complicated patches are harder to
150+
review and take a significant amount of time. It's fine to have multiple
151+
patches to implement one feature if the feature can be split into
152+
self-contained sub-tasks.
153+
189154
Exporting new symbols from the library
190155
======================================
191156

libcxx/docs/DesignDocs/ExtendedCXX03Support.rst

Lines changed: 0 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -47,72 +47,3 @@ Provided C++11 Library Extensions
4747

4848
This section will be updated once the libc++ developer community has further discussed the
4949
future of C++03 with libc++.
50-
51-
52-
Using Minimal C++11 in libc++
53-
=============================
54-
55-
This section is for developers submitting patches to libc++. It describes idioms that should be
56-
used in libc++ code, even in C++03, and the reasons behind them.
57-
58-
59-
Use Alias Templates over Class Templates
60-
----------------------------------------
61-
62-
Alias templates should be used instead of class templates in metaprogramming. Unlike class templates,
63-
Alias templates do not produce a new instantiation every time they are used. This significantly
64-
decreases the amount of memory used by the compiler.
65-
66-
For example, libc++ should not use ``add_const`` internally. Instead it should use an alias template
67-
like
68-
69-
.. code-block:: cpp
70-
71-
template <class _Tp>
72-
using _AddConst = const _Tp;
73-
74-
Use Default Template Parameters for SFINAE
75-
------------------------------------------
76-
77-
There are three places in a function declaration that SFINAE may occur: In the template parameter list,
78-
in the function parameter list, and in the return type. For example:
79-
80-
.. code-block:: cpp
81-
82-
template <class _Tp, class _ = enable_if_t</*...*/ >
83-
void foo(_Tp); // #1
84-
85-
template <class _Tp>
86-
void bar(_Tp, enable_if_t</*...*/>* = nullptr); // # 2
87-
88-
template <class _Tp>
89-
enable_if_t</*...*/> baz(_Tp); // # 3
90-
91-
Using default template parameters for SFINAE (#1) should always be preferred.
92-
93-
Option #2 has two problems. First, users can observe and accidentally pass values to the SFINAE
94-
function argument. Second, the default argument creates a live variable, which causes debug
95-
information to be emitted containing the text of the SFINAE.
96-
97-
Option #3 can also cause more debug information to be emitted than is needed, because the function
98-
return type will appear in the debug information.
99-
100-
Use ``unique_ptr`` when allocating memory
101-
------------------------------------------
102-
103-
The standard library often needs to allocate memory and then construct a user type in it.
104-
If the users constructor throws, the library needs to deallocate that memory. The idiomatic way to
105-
achieve this is with ``unique_ptr``.
106-
107-
``__builtin_new_allocator`` is an example of this idiom. Example usage would look like:
108-
109-
.. code-block:: cpp
110-
111-
template <class T>
112-
T* __create() {
113-
using _UniquePtr = unique_ptr<void*, __default_new_allocator::__default_new_deleter>;
114-
_UniquePtr __p = __default_new_allocator::__allocate_bytes(sizeof(T), alignof(T));
115-
T* __res = ::new(__p.get()) T();
116-
(void)__p.release();
117-
return __res;
118-
}

libcxx/docs/DesignDocs/NodiscardPolicy.rst

Lines changed: 0 additions & 42 deletions
This file was deleted.

libcxx/docs/index.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ Getting Started with libc++
3838
UserDocumentation
3939
VendorDocumentation
4040
Contributing
41+
CodingGuidelines
4142
TestingLibcxx
4243
ImplementationDefinedBehavior
4344
Modules
@@ -216,7 +217,6 @@ Design Documents
216217
DesignDocs/FeatureTestMacros
217218
DesignDocs/FileTimeType
218219
DesignDocs/HeaderRemovalPolicy
219-
DesignDocs/NodiscardPolicy
220220
DesignDocs/NoexceptPolicy
221221
DesignDocs/PSTLIntegration
222222
DesignDocs/ThreadingSupportAPI

0 commit comments

Comments
 (0)