Debian Codegraph @

clang-tools-extra/docs/clang-tidy/checks/bugprone/unchecked-optional-access.rst

raw
1 .. title:: clang-tidy - bugprone-unchecked-optional-access
2
3 bugprone-unchecked-optional-access
4 ==================================
5
6 *Note*: This check uses a flow-sensitive static analysis to produce its
7 results. Therefore, it may be more resource intensive (RAM, CPU) than the
8 average clang-tidy check.
9
10 This check identifies unsafe accesses to values contained in
11 ``std::optional<T>``, ``absl::optional<T>``, ``base::Optional<T>``, or
12 ``folly::Optional<T>`` objects. Below we will refer to all these types
13 collectively as ``optional<T>``.
14
15 An access to the value of an ``optional<T>`` occurs when one of its ``value``,
16 ``operator*``, or ``operator->`` member functions is invoked. To align with
17 common misconceptions, the check considers these member functions as equivalent,
18 even though there are subtle differences related to exceptions versus undefined
19 behavior. See *Additional notes*, below, for more information on this topic.
20
21 An access to the value of an ``optional<T>`` is considered safe if and only if
22 code in the local scope (for example, a function body) ensures that the
23 ``optional<T>`` has a value in all possible execution paths that can reach the
24 access. That should happen either through an explicit check, using the
25 ``optional<T>::has_value`` member function, or by constructing the
26 ``optional<T>`` in a way that shows that it unambiguously holds a value (e.g
27 using ``std::make_optional`` which always returns a populated
28 ``std::optional<T>``).
29
30 Below we list some examples, starting with unsafe optional access patterns,
31 followed by safe access patterns.
32
33 Unsafe access patterns
34 ~~~~~~~~~~~~~~~~~~~~~~
35
36 Access the value without checking if it exists
37 ----------------------------------------------
38
39 The check flags accesses to the value that are not locally guarded by
40 existence check:
41
42 .. code-block:: c++
43
44 void f(std::optional<int> opt) {
45 use(*opt); // unsafe: it is unclear whether `opt` has a value.
46 }
47
48 Access the value in the wrong branch
49 ------------------------------------
50
51 The check is aware of the state of an optional object in different
52 branches of the code. For example:
53
54 .. code-block:: c++
55
56 void f(std::optional<int> opt) {
57 if (opt.has_value()) {
58 } else {
59 use(opt.value()); // unsafe: it is clear that `opt` does *not* have a value.
60 }
61 }
62
63 Assume a function result to be stable
64 -------------------------------------
65
66 The check is aware that function results might not be stable. That is,
67 consecutive calls to the same function might return different values.
68 For example:
69
70 .. code-block:: c++
71
72 void f(Foo foo) {
73 if (foo.opt().has_value()) {
74 use(*foo.opt()); // unsafe: it is unclear whether `foo.opt()` has a value.
75 }
76 }
77
78 Rely on invariants of uncommon APIs
79 -----------------------------------
80
81 The check is unaware of invariants of uncommon APIs. For example:
82
83 .. code-block:: c++
84
85 void f(Foo foo) {
86 if (foo.HasProperty("bar")) {
87 use(*foo.GetProperty("bar")); // unsafe: it is unclear whether `foo.GetProperty("bar")` has a value.
88 }
89 }
90
91 Check if a value exists, then pass the optional to another function
92 -------------------------------------------------------------------
93
94 The check relies on local reasoning. The check and value access must
95 both happen in the same function. An access is considered unsafe even if
96 the caller of the function performing the access ensures that the
97 optional has a value. For example:
98
99 .. code-block:: c++
100
101 void g(std::optional<int> opt) {
102 use(*opt); // unsafe: it is unclear whether `opt` has a value.
103 }
104
105 void f(std::optional<int> opt) {
106 if (opt.has_value()) {
107 g(opt);
108 }
109 }
110
111 Safe access patterns
112 ~~~~~~~~~~~~~~~~~~~~
113
114 Check if a value exists, then access the value
115 ----------------------------------------------
116
117 The check recognizes all straightforward ways for checking if a value
118 exists and accessing the value contained in an optional object. For
119 example:
120
121 .. code-block:: c++
122
123 void f(std::optional<int> opt) {
124 if (opt.has_value()) {
125 use(*opt);
126 }
127 }
128
129
130 Check if a value exists, then access the value from a copy
131 ----------------------------------------------------------
132
133 The criteria that the check uses is semantic, not syntactic. It
134 recognizes when a copy of the optional object being accessed is known to
135 have a value. For example:
136
137 .. code-block:: c++
138
139 void f(std::optional<int> opt1) {
140 if (opt1.has_value()) {
141 std::optional<int> opt2 = opt1;
142 use(*opt2);
143 }
144 }
145
146
147 Ensure that a value exists using common macros
148 ----------------------------------------------
149
150 The check is aware of common macros like ``CHECK`` and ``DCHECK``. Those can be
151 used to ensure that an optional object has a value. For example:
152
153 .. code-block:: c++
154
155 void f(std::optional<int> opt) {
156 DCHECK(opt.has_value());
157 use(*opt);
158 }
159
160 Ensure that a value exists, then access the value in a correlated branch
161 ------------------------------------------------------------------------
162
163 The check is aware of correlated branches in the code and can figure out
164 when an optional object is ensured to have a value on all execution
165 paths that lead to an access. For example:
166
167 .. code-block:: c++
168
169 void f(std::optional<int> opt) {
170 bool safe = false;
171 if (opt.has_value() && SomeOtherCondition()) {
172 safe = true;
173 }
174 // ... more code...
175 if (safe) {
176 use(*opt);
177 }
178 }
179
180 Stabilize function results
181 ~~~~~~~~~~~~~~~~~~~~~~~~~~
182
183 Since function results are not assumed to be stable across calls, it is best to
184 store the result of the function call in a local variable and use that variable
185 to access the value. For example:
186
187 .. code-block:: c++
188
189 void f(Foo foo) {
190 if (const auto& foo_opt = foo.opt(); foo_opt.has_value()) {
191 use(*foo_opt);
192 }
193 }
194
195 Do not rely on uncommon-API invariants
196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
197
198 When uncommon APIs guarantee that an optional has contents, do not rely on it --
199 instead, check explicitly that the optional object has a value. For example:
200
201 .. code-block:: c++
202
203 void f(Foo foo) {
204 if (const auto& property = foo.GetProperty("bar")) {
205 use(*property);
206 }
207 }
208
209 instead of the `HasProperty`, `GetProperty` pairing we saw above.
210
211 Do not rely on caller-performed checks
212 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
213
214 If you know that all of a function's callers have checked that an optional
215 argument has a value, either change the function to take the value directly or
216 check the optional again in the local scope of the callee. For example:
217
218 .. code-block:: c++
219
220 void g(int val) {
221 use(val);
222 }
223
224 void f(std::optional<int> opt) {
225 if (opt.has_value()) {
226 g(*opt);
227 }
228 }
229
230 and
231
232 .. code-block:: c++
233
234 struct S {
235 std::optional<int> opt;
236 int x;
237 };
238
239 void g(const S &s) {
240 if (s.opt.has_value() && s.x > 10) {
241 use(*s.opt);
242 }
243
244 void f(S s) {
245 if (s.opt.has_value()) {
246 g(s);
247 }
248 }
249
250 Additional notes
251 ~~~~~~~~~~~~~~~~
252
253 Aliases created via ``using`` declarations
254 ------------------------------------------
255
256 The check is aware of aliases of optional types that are created via
257 ``using`` declarations. For example:
258
259 .. code-block:: c++
260
261 using OptionalInt = std::optional<int>;
262
263 void f(OptionalInt opt) {
264 use(opt.value()); // unsafe: it is unclear whether `opt` has a value.
265 }
266
267 Lambdas
268 -------
269
270 The check does not currently report unsafe optional accesses in lambdas.
271 A future version will expand the scope to lambdas, following the rules
272 outlined above. It is best to follow the same principles when using
273 optionals in lambdas.
274
275 Access with ``operator*()`` vs. ``value()``
276 -------------------------------------------
277
278 Given that ``value()`` has well-defined behavior (either throwing an exception
279 or terminating the program), why treat it the same as ``operator*()`` which
280 causes undefined behavior (UB)? That is, why is it considered unsafe to access
281 an optional with ``value()``, if it's not provably populated with a value? For
282 that matter, why is ``CHECK()`` followed by ``operator*()`` any better than
283 ``value()``, given that they are semantically equivalent (on configurations that
284 disable exceptions)?
285
286 The answer is that we assume most users do not realize the difference between
287 ``value()`` and ``operator*()``. Shifting to ``operator*()`` and some form of
288 explicit value-presence check or explicit program termination has two
289 advantages:
290
291 * Readability. The check, and any potential side effects like program
292 shutdown, are very clear in the code. Separating access from checks can
293 actually make the checks more obvious.
294
295 * Performance. A single check can cover many or even all accesses within
296 scope. This gives the user the best of both worlds -- the safety of a
297 dynamic check, but without incurring redundant costs.