xref: /llvm-project/libcxx/docs/CodingGuidelines.rst (revision 48b2ce9c12ec27176611e359db3ed9125a5da64b)
159716479SNikolas Klauser.. _CodingGuidelines:
259716479SNikolas Klauser
359716479SNikolas Klauser========================
459716479SNikolas Klauserlibc++ Coding Guidelines
559716479SNikolas Klauser========================
659716479SNikolas Klauser
759716479SNikolas Klauser.. contents::
859716479SNikolas Klauser  :local:
959716479SNikolas Klauser
1059716479SNikolas KlauserUse ``__ugly_names`` for implementation details
1159716479SNikolas Klauser===============================================
1259716479SNikolas Klauser
1359716479SNikolas KlauserLibc++ uses ``__ugly_names`` or ``_UglyNames`` for implementation details. These names are reserved for implementations,
1459716479SNikolas Klauserso users may not use them in their own applications. When using a name like ``T``, a user may have defined a macro that
1559716479SNikolas Klauserchanges the meaning of ``T``. By using ``__ugly_names`` we avoid that problem.
1659716479SNikolas Klauser
1759716479SNikolas KlauserThis is partially enforced by the clang-tidy check ``readability-identifier-naming`` and
1859716479SNikolas Klauser``libcxx/test/libcxx/system_reserved_names.gen.py``.
1959716479SNikolas Klauser
2059716479SNikolas KlauserDon't use argument-dependent lookup unless required by the standard
2159716479SNikolas Klauser===================================================================
2259716479SNikolas Klauser
2359716479SNikolas KlauserUnqualified function calls are susceptible to
2459716479SNikolas Klauser`argument-dependent lookup (ADL) <https://en.cppreference.com/w/cpp/language/adl>`_. This means calling
2559716479SNikolas Klauser``move(UserType)`` might not call ``std::move``. Therefore, function calls must use qualified names to avoid ADL. Some
2659716479SNikolas Klauserfunctions in the standard library `require ADL usage <http://eel.is/c++draft/contents#3>`_. Names of classes, variables,
2759716479SNikolas Klauserconcepts, and type aliases are not subject to ADL. They don't need to be qualified.
2859716479SNikolas Klauser
2959716479SNikolas KlauserFunction overloading also applies to operators. Using ``&user_object`` may call a user-defined ``operator&``. Use
3059716479SNikolas Klauser``std::addressof`` instead. Similarly, to avoid invoking a user-defined ``operator,``, make sure to cast the result to
3159716479SNikolas Klauser``void`` when using the ``,`` or avoid it in the first place. For example:
3259716479SNikolas Klauser
3359716479SNikolas Klauser.. code-block:: cpp
3459716479SNikolas Klauser
3559716479SNikolas Klauser    for (; __first1 != __last1; ++__first1, (void)++__first2) {
3659716479SNikolas Klauser      ...
3759716479SNikolas Klauser    }
3859716479SNikolas Klauser
3959716479SNikolas KlauserThis is mostly enforced by the clang-tidy checks ``libcpp-robust-against-adl`` and ``libcpp-qualify-declval``.
4059716479SNikolas Klauser
4159716479SNikolas KlauserAvoid including public headers
4259716479SNikolas Klauser==============================
4359716479SNikolas Klauser
4459716479SNikolas Klauserlibc++ uses implementation-detail headers for most code. These are in a directory that starts with two underscores
4559716479SNikolas Klauser(e.g. ``<__type_traits/decay.h>``). These detail headers are significantly smaller than their public counterparts.
4659716479SNikolas KlauserThis reduces the amount of code that is included in a single public header, which reduces compile times.
4759716479SNikolas Klauser
4859716479SNikolas KlauserAdd ``_LIBCPP_HIDE_FROM_ABI`` unless you know better
4959716479SNikolas Klauser====================================================
5059716479SNikolas Klauser
5159716479SNikolas Klauser``_LIBCPP_HIDE_FROM_ABI`` should be on every function in the library unless there is a reason not to do so. The main
5259716479SNikolas Klauserreason not to add ``_LIBCPP_HIDE_FROM_ABI`` is if a function is exported from the libc++ built library. In that case the
5359716479SNikolas Klauserfunction should be marked with ``_LIBCPP_EXPORTED_FROM_ABI``. Virtual functions should be marked with
5459716479SNikolas Klauser``_LIBCPP_HIDE_FROM_ABI_VIRTUAL`` instead.
5559716479SNikolas Klauser
5659716479SNikolas KlauserThis is mostly enforced by the clang-tidy checks ``libcpp-hide-from-abi`` and ``libcpp-avoid-abi-tag-on-virtual``.
5759716479SNikolas Klauser
5859716479SNikolas KlauserDefine configuration macros to 0 or 1
5959716479SNikolas Klauser=====================================
6059716479SNikolas Klauser
6159716479SNikolas KlauserMacros should usually be defined in all configurations, instead of defining them when they're enabled and leaving them
6259716479SNikolas Klauserundefined otherwise. For example, use
6359716479SNikolas Klauser
6459716479SNikolas Klauser.. code-block:: cpp
6559716479SNikolas Klauser
6659716479SNikolas Klauser  #if SOMETHING
6759716479SNikolas Klauser  #  define _LIBCPP_SOMETHING_ENABLED 1
6859716479SNikolas Klauser  #else
6959716479SNikolas Klauser  #  define _LIBCPP_SOMETHING_ENABLED 0
7059716479SNikolas Klauser  #endif
7159716479SNikolas Klauser
7259716479SNikolas Klauserand then check for ``#if _LIBCPP_SOMETHING_ENABLED`` instead of
7359716479SNikolas Klauser
7459716479SNikolas Klauser.. code-block:: cpp
7559716479SNikolas Klauser
7659716479SNikolas Klauser  #if SOMETHING
7759716479SNikolas Klauser  #  define _LIBCPP_SOMETHING_ENABLED
7859716479SNikolas Klauser  #endif
7959716479SNikolas Klauser
8059716479SNikolas Klauserand then checking for ``#ifdef _LIBCPP_SOMETHING_ENABLED``.
8159716479SNikolas Klauser
8259716479SNikolas KlauserThis makes it significantly easier to catch missing includes, since Clang and GCC will warn when using and undefined
8359716479SNikolas Klausermarco inside an ``#if`` statement when using ``-Wundef``. Some macros in libc++ don't use this style yet, so this only
8459716479SNikolas Klauserapplies when introducing a new macro.
8559716479SNikolas Klauser
8659716479SNikolas KlauserThis is partially enforced by the clang-tidy check ``libcpp-internal-ftms``.
8759716479SNikolas Klauser
8859716479SNikolas KlauserUse ``_LIBCPP_STD_VER``
8959716479SNikolas Klauser=======================
9059716479SNikolas Klauser
9159716479SNikolas Klauserlibc++ defines the macro ``_LIBCPP_STD_VER`` for the different libc++ dialects. This should be used instead of
9259716479SNikolas Klauser``__cplusplus``.
9359716479SNikolas Klauser
9459716479SNikolas KlauserThis is mostly enforced by the clang-tidy check ``libcpp-cpp-version-check``.
9559716479SNikolas Klauser
9659716479SNikolas KlauserUse ``__ugly__`` spellings of vendor attributes
9759716479SNikolas Klauser===============================================
9859716479SNikolas Klauser
9959716479SNikolas KlauserVendor attributes should always be ``__uglified__`` to avoid naming clashes with user-defined macros. For gnu-style
10059716479SNikolas Klauserattributes this takes the form ``__attribute__((__foo__))``. C++11-style attributes look like ``[[_Clang::__foo__]]`` or
10159716479SNikolas Klauser``[[__gnu__::__foo__]]`` for Clang or GCC attributes respectively. Clang and GCC also support standard attributes in
10259716479SNikolas Klauserearlier language dialects than they were introduced. These should be spelled as ``[[__foo__]]``. MSVC currently doesn't
10359716479SNikolas Klauserprovide alternative spellings for their attributes, so these should be avoided if at all possible.
10459716479SNikolas Klauser
10559716479SNikolas KlauserThis is enforced by the clang-tidy check ``libcpp-uglify-attributes``.
10659716479SNikolas Klauser
10759716479SNikolas KlauserUse C++11 extensions in C++03 code if they simplify the code
10859716479SNikolas Klauser============================================================
10959716479SNikolas Klauser
11059716479SNikolas Klauserlibc++ only supports Clang in C++98/03 mode. Clang provides many C++11 features in C++03, making it possible to write a
11159716479SNikolas Klauserlot of code in a simpler way than if we were restricted to C++03 features. Some use of extensions is even mandatory,
11259716479SNikolas Klausersince libc++ supports move semantics in C++03.
11359716479SNikolas Klauser
11459716479SNikolas KlauserUse ``using`` aliases instead of ``typedef``
11559716479SNikolas Klauser============================================
11659716479SNikolas Klauser
11759716479SNikolas Klauser``using`` aliases are generally easier to read and support templates. Some code in libc++ uses ``typedef`` for
11859716479SNikolas Klauserhistorical reasons.
11959716479SNikolas Klauser
12059716479SNikolas KlauserWrite SFINAE with ``requires`` clauses in C++20-only code
12159716479SNikolas Klauser=========================================================
12259716479SNikolas Klauser
12359716479SNikolas Klauser``requires`` clauses can be significantly easier to read than ``enable_if`` and friends in some cases, since concepts
12459716479SNikolas Klausersubsume other concepts. This means that overloads based on traits can be written without negating more general cases.
12559716479SNikolas KlauserThey also show intent better.
12659716479SNikolas Klauser
12759716479SNikolas KlauserWrite ``enable_if`` as ``enable_if_t<conditon, int> = 0``
12859716479SNikolas Klauser=========================================================
12959716479SNikolas Klauser
13059716479SNikolas KlauserThe form ``enable_if_t<condition, int> = 0`` is the only one that works in every language mode and for overload sets
13159716479SNikolas Klauserusing the same template arguments otherwise. If the code must work in C++11 or C++03, the libc++-internal alias
13259716479SNikolas Klauser``__enable_if_t`` can be used instead.
13359716479SNikolas Klauser
13459716479SNikolas KlauserPrefer alias templates over class templates
13559716479SNikolas Klauser===========================================
13659716479SNikolas Klauser
13759716479SNikolas KlauserAlias templates are much more lightweight than class templates, since they don't require new instantiations for
13859716479SNikolas Klauserdifferent types. If the only member of a class is an alias, like in type traits, alias templates should be used if
13959716479SNikolas Klauserpossible. They do force more eager evaluation though, which can be a problem in some cases.
14059716479SNikolas Klauser
14159716479SNikolas KlauserApply ``[[nodiscard]]`` where relevant
14259716479SNikolas Klauser======================================
14359716479SNikolas Klauser
14459716479SNikolas KlauserLibc++ adds ``[[nodiscard]]`` whenever relevant to catch potential bugs. The standards committee has decided to _not_
14559716479SNikolas Klauserhave a recommended practice where to put them, so libc++ applies it whenever it makes sense to catch potential bugs.
14659716479SNikolas Klauser
14759716479SNikolas Klauser``[[nodiscard]]`` should be applied to functions
14859716479SNikolas Klauser
14959716479SNikolas Klauser- where discarding the return value is most likely a correctness issue. For example a locking constructor in
15059716479SNikolas Klauser  ``unique_lock``.
15159716479SNikolas Klauser
15259716479SNikolas Klauser- where discarding the return value likely points to the user wanting to do something different. For example
15359716479SNikolas Klauser  ``vector::empty()``, which probably should have been ``vector::clear()``.
15459716479SNikolas Klauser
15559716479SNikolas Klauser  This can help spotting bugs easily which otherwise may take a very long time to find.
15659716479SNikolas Klauser
15759716479SNikolas Klauser- which return a constant. For example ``numeric_limits::min()``.
15859716479SNikolas Klauser- which only observe a value. For example ``string::size()``.
15959716479SNikolas Klauser
16059716479SNikolas Klauser  Code that discards values from these kinds of functions is dead code. It can either be removed, or the programmer
16159716479SNikolas Klauser  meant to do something different.
16259716479SNikolas Klauser
16359716479SNikolas Klauser- where discarding the value is most likely a misuse of the function. For example ``std::find(first, last, val)``.
16459716479SNikolas Klauser
16559716479SNikolas Klauser  This protects programmers from assuming too much about how the internals of a function work, making code more robust
16659716479SNikolas Klauser  in the presence of future optimizations.
16759716479SNikolas Klauser
16859716479SNikolas KlauserApplications of ``[[nodiscard]]`` are code like any other code, so we aim to test them on public interfaces. This can be
16959716479SNikolas Klauserdone with a ``.verify.cpp`` test. Many examples are available. Just look for tests with the suffix
17059716479SNikolas Klauser``.nodiscard.verify.cpp``.
17101512d29SLouis Dionne
17201512d29SLouis DionneDon't use public API names for symbols on the ABI boundary
17301512d29SLouis Dionne==========================================================
17401512d29SLouis Dionne
17501512d29SLouis DionneMost functions in libc++ are defined in headers either as templates or as ``inline`` functions. However, we sometimes
17601512d29SLouis Dionneneed or want to define functions in the built library. Symbols that are declared in the headers and defined in the
17701512d29SLouis Dionnebuilt library become part of the ABI of libc++, which must be preserved for backwards compatibility. This means that
17801512d29SLouis Dionnewe can't easily remove or rename such symbols except in special cases.
17901512d29SLouis Dionne
18001512d29SLouis DionneWhen adding a symbol to the built library, make sure not to use a public name directly. Instead, define a
18101512d29SLouis Dionne``_LIBCPP_HIDE_FROM_ABI`` function in the headers with the public name and have it call a private function in the built
18201512d29SLouis Dionnelibrary. This approach makes it easier to make changes to libc++ like move something from the built library to the
18301512d29SLouis Dionneheaders (which is sometimes required for ``constexpr`` support).
18401512d29SLouis Dionne
18501512d29SLouis DionneWhen defining a function at the ABI boundary, it can also be useful to consider which attributes (like ``[[gnu::pure]]``
18601512d29SLouis Dionneand ``[[clang::noescape]]``) can be added to the function to improve the compiler's ability to optimize.
187*48b2ce9cSNikolas Klauser
188*48b2ce9cSNikolas KlauserLibrary-internal type aliases should be annotated with ``_LIBCPP_NODEBUG``
189*48b2ce9cSNikolas Klauser==========================================================================
190*48b2ce9cSNikolas Klauser
191*48b2ce9cSNikolas KlauserLibc++ has lots of internal type aliases. Accumulated, these can result in significant amounts of debug information that
192*48b2ce9cSNikolas Klauserusers generally don't care about, since users don't try to debug standard library facilities in most cases. For that
193*48b2ce9cSNikolas Klauserreason, all library-internal type aliases that aren't function-local should be annotated with ``_LIBCPP_NODEBUG`` to
194*48b2ce9cSNikolas Klauserprevent compilers from generating said debug information.
195*48b2ce9cSNikolas Klauser
196*48b2ce9cSNikolas KlauserThis is enforced by the clang-tidy check ``libcpp-nodebug-on-aliases``.
197