xref: /llvm-project/clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-print.rst (revision a199fb1229987d0885a4367e3a439db336069156)
1.. title:: clang-tidy - modernize-use-std-print
2
3modernize-use-std-print
4=======================
5
6Converts calls to ``printf``, ``fprintf``, ``absl::PrintF`` and
7``absl::FPrintf`` to equivalent calls to C++23's ``std::print`` or
8``std::println`` as appropriate, modifying the format string appropriately.
9The replaced and replacement functions can be customised by configuration
10options. Each argument that is the result of a call to ``std::string::c_str()`` and
11``std::string::data()`` will have that now-unnecessary call removed in a
12similar manner to the `readability-redundant-string-cstr` check.
13
14In other words, it turns lines like:
15
16.. code-block:: c++
17
18  fprintf(stderr, "The %s is %3d\n", description.c_str(), value);
19
20into:
21
22.. code-block:: c++
23
24  std::println(stderr, "The {} is {:3}", description, value);
25
26If the `ReplacementPrintFunction` or `ReplacementPrintlnFunction` options
27are left at or set to their default values then this check is only enabled
28with `-std=c++23` or later.
29
30Macros starting with ``PRI`` and ``__PRI`` from `<inttypes.h>` are
31expanded, escaping is handled and adjacent strings are concatenated to form
32a single ``StringLiteral`` before the format string is converted. Use of
33any other macros in the format string will cause a warning message to be
34emitted and no conversion will be performed. The converted format string
35will always be a single string literal.
36
37The check doesn't do a bad job, but it's not perfect. In particular:
38
39- It assumes that the format string is correct for the arguments. If you
40  get any warnings when compiling with `-Wformat` then misbehaviour is
41  possible.
42
43- At the point that the check runs, the AST contains a single
44  ``StringLiteral`` for the format string where escapes have been expanded.
45  The check tries to reconstruct escape sequences, they may not be the same
46  as they were written (e.g. ``"\x41\x0a"`` will become ``"A\n"`` and
47  ``"ab" "cd"`` will become ``"abcd"``.)
48
49- It supports field widths, precision, positional arguments, leading zeros,
50  leading ``+``, alignment and alternative forms.
51
52- Use of any unsupported flags or specifiers will cause the entire
53  statement to be left alone and a warning to be emitted. Particular
54  unsupported features are:
55
56  - The ``%'`` flag for thousands separators.
57
58  - The glibc extension ``%m``.
59
60- ``printf`` and similar functions return the number of characters printed.
61  ``std::print`` does not. This means that any invocations that use the
62  return value will not be converted. Unfortunately this currently includes
63  explicitly-casting to ``void``. Deficiencies in this check mean that any
64  invocations inside ``GCC`` compound statements cannot be converted even
65  if the resulting value is not used.
66
67If conversion would be incomplete or unsafe then the entire invocation will
68be left unchanged.
69
70If the call is deemed suitable for conversion then:
71
72- ``printf``, ``fprintf``, ``absl::PrintF``, ``absl::FPrintF`` and any
73  functions specified by the `PrintfLikeFunctions` option or
74  `FprintfLikeFunctions` are replaced with the function specified by the
75  `ReplacementPrintlnFunction` option if the format string ends with ``\n``
76  or `ReplacementPrintFunction` otherwise.
77- the format string is rewritten to use the ``std::formatter`` language. If
78  a ``\n`` is found at the end of the format string not preceded by ``r``
79  then it is removed and `ReplacementPrintlnFunction` is used rather than
80  `ReplacementPrintFunction`.
81- any arguments that corresponded to ``%p`` specifiers that
82  ``std::formatter`` wouldn't accept are wrapped in a ``static_cast``
83  to ``const void *``.
84- any arguments that corresponded to ``%s`` specifiers where the argument
85  is of ``signed char`` or ``unsigned char`` type are wrapped in a
86  ``reinterpret_cast<const char *>``.
87- any arguments where the format string and the parameter differ in
88  signedness will be wrapped in an appropriate ``static_cast`` if `StrictMode`
89  is enabled.
90- any arguments that end in a call to ``std::string::c_str()`` or
91  ``std::string::data()`` will have that call removed.
92
93Options
94-------
95
96.. option:: StrictMode
97
98   When `true`, the check will add casts when converting from variadic
99   functions like ``printf`` and printing signed or unsigned integer types
100   (including fixed-width integer types from ``<cstdint>``, ``ptrdiff_t``,
101   ``size_t`` and ``ssize_t``) as the opposite signedness to ensure that
102   the output matches that of ``printf``. This does not apply when
103   converting from non-variadic functions such as ``absl::PrintF`` and
104   ``fmt::printf``. For example, with `StrictMode` enabled:
105
106  .. code-block:: c++
107
108    int i = -42;
109    unsigned int u = 0xffffffff;
110    printf("%u %d\n", i, u);
111
112  would be converted to:
113
114  .. code-block:: c++
115
116    std::print("{} {}\n", static_cast<unsigned int>(i), static_cast<int>(u));
117
118  to ensure that the output will continue to be the unsigned representation
119  of `-42` and the signed representation of `0xffffffff` (often
120  `4294967254` and `-1` respectively.) When `false` (which is the default),
121  these casts will not be added which may cause a change in the output.
122
123.. option:: PrintfLikeFunctions
124
125   A semicolon-separated list of (fully qualified) function names to
126   replace, with the requirement that the first parameter contains the
127   printf-style format string and the arguments to be formatted follow
128   immediately afterwards. Qualified member function names are supported,
129   but the replacement function name must be unqualified. If neither this
130   option nor `FprintfLikeFunctions` are set then the default value for
131   this option is `printf; absl::PrintF`, otherwise it is empty.
132
133
134.. option:: FprintfLikeFunctions
135
136   A semicolon-separated list of (fully qualified) function names to
137   replace, with the requirement that the first parameter is retained, the
138   second parameter contains the printf-style format string and the
139   arguments to be formatted follow immediately afterwards. Qualified
140   member function names are supported, but the replacement function name
141   must be unqualified. If neither this option nor `PrintfLikeFunctions`
142   are set then the default value for this option is `fprintf;
143   absl::FPrintF`, otherwise it is empty.
144
145.. option:: ReplacementPrintFunction
146
147   The function that will be used to replace ``printf``, ``fprintf`` etc.
148   during conversion rather than the default ``std::print`` when the
149   originalformat string does not end with ``\n``. It is expected that the
150   function provides an interface that is compatible with ``std::print``. A
151   suitable candidate would be ``fmt::print``.
152
153.. option:: ReplacementPrintlnFunction
154
155   The function that will be used to replace ``printf``, ``fprintf`` etc.
156   during conversion rather than the default ``std::println`` when the
157   original format string ends with ``\n``. It is expected that the
158   function provides an interface that is compatible with ``std::println``.
159   A suitable candidate would be ``fmt::println``.
160
161.. option:: PrintHeader
162
163   The header that must be included for the declaration of
164   `ReplacementPrintFunction` so that a ``#include`` directive can be
165   added if required. If `ReplacementPrintFunction` is ``std::print``
166   then this option will default to ``<print>``, otherwise this option will
167   default to nothing and no ``#include`` directive will be added.
168