Skip to content

Commit 1f2092b

Browse files
committed
[libc++] Add coding guidelines to the docs
1 parent 3e15bce commit 1f2092b

File tree

4 files changed

+185
-156
lines changed

4 files changed

+185
-156
lines changed

libcxx/docs/CodingGuidelines.rst

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
.. _CodingGuidelines:
2+
3+
========================
4+
libc++ Coding Guidelines
5+
========================
6+
7+
Use ``__ugly_names`` for implementation details
8+
===============================================
9+
10+
Libc++ uses ``__ugly_names`` for implementation details. These names are reserved for implementations, so users may not
11+
use them in their own applications. When using a name like ``T``, a user may have defined a macro that changes the
12+
meaning of ``T``. By using ``__ugly_names`` we avoid that problem. Other standard libraries and compilers use these
13+
names too.
14+
15+
This is partially enforced by the clangh-tidy check ``readability-identifier-naming`` and
16+
``libcxx/test/libcxx/system_reserved_names.gen.py``.
17+
18+
Don't use argument-dependent lookup unless required by the standard
19+
===================================================================
20+
21+
Unqualified function calls are susceptible to
22+
`argument-dependent lookup (ADL) <https://en.cppreference.com/w/cpp/language/adl>`_. This means calling
23+
``move(UserType)`` might not call ``std::move``. Therefore, function calls must use qualified names to avoid ADL. Some
24+
functions in the standard library `require ADL usage <http://eel.is/c++draft/contents#3>`_. Names of classes, variables,
25+
concepts, and type aliases are not subject to ADL. They don't need to be qualified.
26+
27+
Function overloading also applies to operators. Using ``&user_object`` may call a user-defined ``operator&``. Use
28+
``std::addressof`` instead. Similarly, to avoid invoking a user-defined ``operator,``, make sure to cast the result to
29+
``void`` when using the ``,`` or avoid it in the first place. For example:
30+
31+
.. code-block:: cpp
32+
33+
for (; __first1 != __last1; ++__first1, (void)++__first2) {
34+
...
35+
}
36+
37+
This is mostly enforced by the clang-tidy checks ``libcpp-robust-against-adl`` and ``libcpp-qualify-declval``.
38+
39+
Avoid including public headers
40+
==============================
41+
42+
libc++ uses implementation-detail headers for most code. These are either top-level headers starting with two
43+
underscores (e.g. ``<__locale>``) or are in a directory that starts with two underscores
44+
(e.g. ``<__type_traits/decay.h>``). These detail headers are significantly smaller than their public counterparts.
45+
This reduces the amount of code that is included in a single public header, reducing compile times in turn.
46+
47+
Add ``_LIBCPP_HIDE_FROM_ABI`` unless you know better
48+
====================================================
49+
50+
``_LIBCPP_HIDE_FROM_ABI`` should be on every function in the library unless there is a reason not to do so. The main
51+
resason to not add ``_LIBCPP_HIDE_FROM_ABI`` is if a function is exported libc++ dylib. In that case a function should
52+
be marked ``_LIBCPP_EXPORTED_FROM_ABI``. Virtual functions should be marked ``_LIBCPP_HIDE_FROM_ABI_VIRTUAL`` instead.
53+
54+
This is mostly enforced by the clang-tidy checks ``libcpp-hide-from-abi`` and ``libcpp-avoid-abi-tag-on-virtual``.
55+
56+
Always define macros
57+
====================
58+
59+
Macros should usually be defined in all configurations. This makes it significantly easier to catch missing includes,
60+
since Clang and GCC will warn when using and undefined marco inside an ``#if`` statement when using ``-Wundef``. Some
61+
macros in libc++ don't use this style yet, so this only applies when introducing a new macro.
62+
63+
This is partially enforced by the clang-tidy check ``libcpp-internal-ftms``.
64+
65+
Use ``_LIBCPP_STD_VER``
66+
=======================
67+
68+
libc++ defines the macro ``_LIBCPP_STD_VER`` for the different libc++ dialects. This should be used instead of
69+
``__cplusplus``. The form ``_LIBCPP_STD_VER >= <version>`` is preferred over ``_LIBCPP_STD_VER > <previous-version>``.
70+
71+
This is mostly enforced by the clang-tidy check ``libcpp-cpp-version-check``.
72+
73+
Use \_\_ugly\_\_ spellings of vendor attributes
74+
===============================================
75+
76+
Vendor attributes should always be \_\_uglified\_\_ to avoid naming clashes with user-defined macros. For gnu-style
77+
attributes this takes the form ``__attribute__((__attribute__))``. C++11-style attributes look like
78+
``[[_Clang::__attribute__]]`` or ``[[__gnu__::__attribute__]]`` for Clang or GCC attributes respectively. Clang and GCC
79+
also support standard attributes in earlier language dialects than they were introduced. These should be spelled as
80+
``[[__attribute__]]`` in these cases. MSVC currently doesn't provide alternative spellings for their attributes, so
81+
these should be avoided if at all possible.
82+
83+
This is enforced by the clang-tidy check ``libcpp-uglify-attributes``.
84+
85+
Use C++11 extensions in C++03 code if they simplify the code
86+
============================================================
87+
88+
libc++ only supports Clang in C++98/03 mode. Clang provides many C++11 features in C++03, making it possible to write a
89+
lot of code in a simpler way than if we were restricted to C++03 features. Some use of extensions is even mandatory,
90+
since libc++ supports move semantics in C++03.
91+
92+
Use ``using`` aliases instead of ``typedef``
93+
============================================
94+
95+
``using`` aliases are generally easier to read and support templates. Some code in libc++ uses ``typedef`` for
96+
historical reasons.
97+
98+
Write SFINAE with ``requires`` clauses in C++20-only code
99+
=========================================================
100+
101+
``requires`` clauses can be significantly easier to read than ``enable_if`` and friends in some cases, since concepts
102+
subsume other concepts. This means that overloads based on traits can be written without negating more general cases.
103+
They also show intent better.
104+
105+
For example
106+
.. code-block:: cpp
107+
108+
template <class _Iter>
109+
requires forward_iterator<_Iter>
110+
void func(_Iter);
111+
112+
template <class _Iter>
113+
requires bidirectional_iterator<_Iter>
114+
void func(_Iter);
115+
116+
is perfectly fine code, but ``enable_if`` would need ``!forward_iterator<_Iter> && bidirectional_iterator<_Iter>`` for
117+
the second overload.
118+
119+
Write ``enable_if``s as ``enable_if_t<conditon, int> = 0``
120+
==========================================================
121+
122+
The form ``enable_if_t<condition, int> = 0`` is the only form that works in every language mode and for overload sets
123+
using the same template arguments otherwise. If the code must work in C++11 or C++03, the libc++-internal alias
124+
``__enable_if_t`` can be used instead.
125+
126+
Prefer alias templates over class templates
127+
===========================================
128+
129+
Alias templates are much more light weight than class templates, since they don't require new instantiations for
130+
different types. They do force more eager evaluation though, which can be a problem in some cases.
131+
132+
Use ``unique_ptr`` when allocating memory
133+
=========================================
134+
135+
The standard library often needs to allocate memory and then construct a user type in it. If the users constructor
136+
throws, the library needs to deallocate that memory. The idiomatic way to achieve this is with ``unique_ptr``.
137+
138+
Apply ``[[nodiscard]]`` liberally
139+
=================================
140+
141+
Libc++ adds ``[[nodiscard]]`` to functions in a lot of places. The standards committee has decided to not have a
142+
recommended practice where to put them, so libc++ has its own guidelines on when to apply ``[[nodiscard]]``.
143+
144+
When should ``[[nodiscard]]`` be added?
145+
---------------------------------------
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 ``find``.
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+
What should be done when adding ``[[nodiscard]]`` to a function?
169+
----------------------------------------------------------------
170+
171+
Applications of ``[[nodiscard]]`` are code like any other code, so we aim to test them. This can be done with a
172+
``.verify.cpp`` test. Many examples are available. Just look for tests with the suffix ``.nodiscard.verify.cpp``.

libcxx/docs/Contributing.rst

Lines changed: 13 additions & 48 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
39+
Coding Guidelines
4040
================
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-
}
Lines changed: 0 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,3 @@
11
===================================================
22
Guidelines for applying ``[[nodiscard]]`` in libc++
33
===================================================
4-
5-
Libc++ adds ``[[nodiscard]]`` to functions in a lot of places. The standards
6-
committee has decided to not have a recommended practice where to put them, so
7-
this document lists where ``[[nodiscard]]`` should be applied in libc++.
8-
9-
When should ``[[nodiscard]]`` be added to functions?
10-
====================================================
11-
12-
``[[nodiscard]]`` should be applied to functions
13-
14-
- where discarding the return value is most likely a correctness issue.
15-
For example a locking constructor in ``unique_lock``.
16-
17-
- where discarding the return value likely points to the user wanting to do
18-
something different. For example ``vector::empty()``, which probably should
19-
have been ``vector::clear()``.
20-
21-
This can help spotting bugs easily which otherwise may take a very long time
22-
to find.
23-
24-
- which return a constant. For example ``numeric_limits::min()``.
25-
- which only observe a value. For example ``string::size()``.
26-
27-
Code that discards values from these kinds of functions is dead code. It can
28-
either be removed, or the programmer meant to do something different.
29-
30-
- where discarding the value is most likely a misuse of the function. For
31-
example ``find``.
32-
33-
This protects programmers from assuming too much about how the internals of
34-
a function work, making code more robust in the presence of future
35-
optimizations.
36-
37-
What should be done when adding ``[[nodiscard]]`` to a function?
38-
================================================================
39-
40-
Applications of ``[[nodiscard]]`` are code like any other code, so we aim to
41-
test them. This can be done with a ``.verify.cpp`` test. Many examples are
42-
available. Just look for tests with the suffix ``.nodiscard.verify.cpp``.

0 commit comments

Comments
 (0)