xref: /llvm-project/clang/unittests/Analysis/FlowSensitive/UncheckedOptionalAccessModelTest.cpp (revision d4fb829b718059eb044843aea7b03d5b65556351)
1 //===- UncheckedOptionalAccessModelTest.cpp -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 // FIXME: Move this to clang/unittests/Analysis/FlowSensitive/Models.
9 
10 #include "clang/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.h"
11 #include "TestingSupport.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchers.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Tooling/Tooling.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/Support/Error.h"
19 #include "gmock/gmock.h"
20 #include "gtest/gtest.h"
21 #include <optional>
22 #include <string>
23 #include <utility>
24 #include <vector>
25 
26 using namespace clang;
27 using namespace dataflow;
28 using namespace test;
29 
30 using ::testing::ContainerEq;
31 
32 // FIXME: Move header definitions in separate file(s).
33 static constexpr char CSDtdDefHeader[] = R"(
34 #ifndef CSTDDEF_H
35 #define CSTDDEF_H
36 
37 namespace std {
38 
39 typedef decltype(sizeof(char)) size_t;
40 
41 using nullptr_t = decltype(nullptr);
42 
43 } // namespace std
44 
45 #endif // CSTDDEF_H
46 )";
47 
48 static constexpr char StdTypeTraitsHeader[] = R"(
49 #ifndef STD_TYPE_TRAITS_H
50 #define STD_TYPE_TRAITS_H
51 
52 #include "cstddef.h"
53 
54 namespace std {
55 
56 template <typename T, T V>
57 struct integral_constant {
58   static constexpr T value = V;
59 };
60 
61 using true_type = integral_constant<bool, true>;
62 using false_type = integral_constant<bool, false>;
63 
64 template< class T > struct remove_reference      {typedef T type;};
65 template< class T > struct remove_reference<T&>  {typedef T type;};
66 template< class T > struct remove_reference<T&&> {typedef T type;};
67 
68 template <class T>
69   using remove_reference_t = typename remove_reference<T>::type;
70 
71 template <class T>
72 struct remove_extent {
73   typedef T type;
74 };
75 
76 template <class T>
77 struct remove_extent<T[]> {
78   typedef T type;
79 };
80 
81 template <class T, size_t N>
82 struct remove_extent<T[N]> {
83   typedef T type;
84 };
85 
86 template <class T>
87 struct is_array : false_type {};
88 
89 template <class T>
90 struct is_array<T[]> : true_type {};
91 
92 template <class T, size_t N>
93 struct is_array<T[N]> : true_type {};
94 
95 template <class>
96 struct is_function : false_type {};
97 
98 template <class Ret, class... Args>
99 struct is_function<Ret(Args...)> : true_type {};
100 
101 namespace detail {
102 
103 template <class T>
104 struct type_identity {
105   using type = T;
106 };  // or use type_identity (since C++20)
107 
108 template <class T>
109 auto try_add_pointer(int) -> type_identity<typename remove_reference<T>::type*>;
110 template <class T>
111 auto try_add_pointer(...) -> type_identity<T>;
112 
113 }  // namespace detail
114 
115 template <class T>
116 struct add_pointer : decltype(detail::try_add_pointer<T>(0)) {};
117 
118 template <bool B, class T, class F>
119 struct conditional {
120   typedef T type;
121 };
122 
123 template <class T, class F>
124 struct conditional<false, T, F> {
125   typedef F type;
126 };
127 
128 template <class T>
129 struct remove_cv {
130   typedef T type;
131 };
132 template <class T>
133 struct remove_cv<const T> {
134   typedef T type;
135 };
136 template <class T>
137 struct remove_cv<volatile T> {
138   typedef T type;
139 };
140 template <class T>
141 struct remove_cv<const volatile T> {
142   typedef T type;
143 };
144 
145 template <class T>
146 using remove_cv_t = typename remove_cv<T>::type;
147 
148 template <class T>
149 struct decay {
150  private:
151   typedef typename remove_reference<T>::type U;
152 
153  public:
154   typedef typename conditional<
155       is_array<U>::value, typename remove_extent<U>::type*,
156       typename conditional<is_function<U>::value, typename add_pointer<U>::type,
157                            typename remove_cv<U>::type>::type>::type type;
158 };
159 
160 template <bool B, class T = void>
161 struct enable_if {};
162 
163 template <class T>
164 struct enable_if<true, T> {
165   typedef T type;
166 };
167 
168 template <bool B, class T = void>
169 using enable_if_t = typename enable_if<B, T>::type;
170 
171 template <class T, class U>
172 struct is_same : false_type {};
173 
174 template <class T>
175 struct is_same<T, T> : true_type {};
176 
177 template <class T>
178 struct is_void : is_same<void, typename remove_cv<T>::type> {};
179 
180 namespace detail {
181 
182 template <class T>
183 auto try_add_lvalue_reference(int) -> type_identity<T&>;
184 template <class T>
185 auto try_add_lvalue_reference(...) -> type_identity<T>;
186 
187 template <class T>
188 auto try_add_rvalue_reference(int) -> type_identity<T&&>;
189 template <class T>
190 auto try_add_rvalue_reference(...) -> type_identity<T>;
191 
192 }  // namespace detail
193 
194 template <class T>
195 struct add_lvalue_reference : decltype(detail::try_add_lvalue_reference<T>(0)) {
196 };
197 
198 template <class T>
199 struct add_rvalue_reference : decltype(detail::try_add_rvalue_reference<T>(0)) {
200 };
201 
202 template <class T>
203 typename add_rvalue_reference<T>::type declval() noexcept;
204 
205 namespace detail {
206 
207 template <class T>
208 auto test_returnable(int)
209     -> decltype(void(static_cast<T (*)()>(nullptr)), true_type{});
210 template <class>
211 auto test_returnable(...) -> false_type;
212 
213 template <class From, class To>
214 auto test_implicitly_convertible(int)
215     -> decltype(void(declval<void (&)(To)>()(declval<From>())), true_type{});
216 template <class, class>
217 auto test_implicitly_convertible(...) -> false_type;
218 
219 }  // namespace detail
220 
221 template <class From, class To>
222 struct is_convertible
223     : integral_constant<bool,
224                         (decltype(detail::test_returnable<To>(0))::value &&
225                          decltype(detail::test_implicitly_convertible<From, To>(
226                              0))::value) ||
227                             (is_void<From>::value && is_void<To>::value)> {};
228 
229 template <class From, class To>
230 inline constexpr bool is_convertible_v = is_convertible<From, To>::value;
231 
232 template <class...>
233 using void_t = void;
234 
235 template <class, class T, class... Args>
236 struct is_constructible_ : false_type {};
237 
238 template <class T, class... Args>
239 struct is_constructible_<void_t<decltype(T(declval<Args>()...))>, T, Args...>
240     : true_type {};
241 
242 template <class T, class... Args>
243 using is_constructible = is_constructible_<void_t<>, T, Args...>;
244 
245 template <class T, class... Args>
246 inline constexpr bool is_constructible_v = is_constructible<T, Args...>::value;
247 
248 template <class _Tp>
249 struct __uncvref {
250   typedef typename remove_cv<typename remove_reference<_Tp>::type>::type type;
251 };
252 
253 template <class _Tp>
254 using __uncvref_t = typename __uncvref<_Tp>::type;
255 
256 template <bool _Val>
257 using _BoolConstant = integral_constant<bool, _Val>;
258 
259 template <class _Tp, class _Up>
260 using _IsSame = _BoolConstant<__is_same(_Tp, _Up)>;
261 
262 template <class _Tp, class _Up>
263 using _IsNotSame = _BoolConstant<!__is_same(_Tp, _Up)>;
264 
265 template <bool>
266 struct _MetaBase;
267 template <>
268 struct _MetaBase<true> {
269   template <class _Tp, class _Up>
270   using _SelectImpl = _Tp;
271   template <template <class...> class _FirstFn, template <class...> class,
272             class... _Args>
273   using _SelectApplyImpl = _FirstFn<_Args...>;
274   template <class _First, class...>
275   using _FirstImpl = _First;
276   template <class, class _Second, class...>
277   using _SecondImpl = _Second;
278   template <class _Result, class _First, class... _Rest>
279   using _OrImpl =
280       typename _MetaBase<_First::value != true && sizeof...(_Rest) != 0>::
281           template _OrImpl<_First, _Rest...>;
282 };
283 
284 template <>
285 struct _MetaBase<false> {
286   template <class _Tp, class _Up>
287   using _SelectImpl = _Up;
288   template <template <class...> class, template <class...> class _SecondFn,
289             class... _Args>
290   using _SelectApplyImpl = _SecondFn<_Args...>;
291   template <class _Result, class...>
292   using _OrImpl = _Result;
293 };
294 
295 template <bool _Cond, class _IfRes, class _ElseRes>
296 using _If = typename _MetaBase<_Cond>::template _SelectImpl<_IfRes, _ElseRes>;
297 
298 template <class... _Rest>
299 using _Or = typename _MetaBase<sizeof...(_Rest) !=
300                                0>::template _OrImpl<false_type, _Rest...>;
301 
302 template <bool _Bp, class _Tp = void>
303 using __enable_if_t = typename enable_if<_Bp, _Tp>::type;
304 
305 template <class...>
306 using __expand_to_true = true_type;
307 template <class... _Pred>
308 __expand_to_true<__enable_if_t<_Pred::value>...> __and_helper(int);
309 template <class...>
310 false_type __and_helper(...);
311 template <class... _Pred>
312 using _And = decltype(__and_helper<_Pred...>(0));
313 
314 template <class _Pred>
315 struct _Not : _BoolConstant<!_Pred::value> {};
316 
317 struct __check_tuple_constructor_fail {
318   static constexpr bool __enable_explicit_default() { return false; }
319   static constexpr bool __enable_implicit_default() { return false; }
320   template <class...>
321   static constexpr bool __enable_explicit() {
322     return false;
323   }
324   template <class...>
325   static constexpr bool __enable_implicit() {
326     return false;
327   }
328 };
329 
330 template <typename, typename _Tp>
331 struct __select_2nd {
332   typedef _Tp type;
333 };
334 template <class _Tp, class _Arg>
335 typename __select_2nd<decltype((declval<_Tp>() = declval<_Arg>())),
336                       true_type>::type
337 __is_assignable_test(int);
338 template <class, class>
339 false_type __is_assignable_test(...);
340 template <class _Tp, class _Arg,
341           bool = is_void<_Tp>::value || is_void<_Arg>::value>
342 struct __is_assignable_imp
343     : public decltype((__is_assignable_test<_Tp, _Arg>(0))) {};
344 template <class _Tp, class _Arg>
345 struct __is_assignable_imp<_Tp, _Arg, true> : public false_type {};
346 template <class _Tp, class _Arg>
347 struct is_assignable : public __is_assignable_imp<_Tp, _Arg> {};
348 
349 template <class _Tp>
350 struct __libcpp_is_integral : public false_type {};
351 template <>
352 struct __libcpp_is_integral<bool> : public true_type {};
353 template <>
354 struct __libcpp_is_integral<char> : public true_type {};
355 template <>
356 struct __libcpp_is_integral<signed char> : public true_type {};
357 template <>
358 struct __libcpp_is_integral<unsigned char> : public true_type {};
359 template <>
360 struct __libcpp_is_integral<wchar_t> : public true_type {};
361 template <>
362 struct __libcpp_is_integral<short> : public true_type {};  // NOLINT
363 template <>
364 struct __libcpp_is_integral<unsigned short> : public true_type {};  // NOLINT
365 template <>
366 struct __libcpp_is_integral<int> : public true_type {};
367 template <>
368 struct __libcpp_is_integral<unsigned int> : public true_type {};
369 template <>
370 struct __libcpp_is_integral<long> : public true_type {};  // NOLINT
371 template <>
372 struct __libcpp_is_integral<unsigned long> : public true_type {};  // NOLINT
373 template <>
374 struct __libcpp_is_integral<long long> : public true_type {};  // NOLINT
375 template <>                                                    // NOLINTNEXTLINE
376 struct __libcpp_is_integral<unsigned long long> : public true_type {};
377 template <class _Tp>
378 struct is_integral
379     : public __libcpp_is_integral<typename remove_cv<_Tp>::type> {};
380 
381 template <class _Tp>
382 struct __libcpp_is_floating_point : public false_type {};
383 template <>
384 struct __libcpp_is_floating_point<float> : public true_type {};
385 template <>
386 struct __libcpp_is_floating_point<double> : public true_type {};
387 template <>
388 struct __libcpp_is_floating_point<long double> : public true_type {};
389 template <class _Tp>
390 struct is_floating_point
391     : public __libcpp_is_floating_point<typename remove_cv<_Tp>::type> {};
392 
393 template <class _Tp>
394 struct is_arithmetic
395     : public integral_constant<bool, is_integral<_Tp>::value ||
396                                          is_floating_point<_Tp>::value> {};
397 
398 template <class _Tp>
399 struct __libcpp_is_pointer : public false_type {};
400 template <class _Tp>
401 struct __libcpp_is_pointer<_Tp*> : public true_type {};
402 template <class _Tp>
403 struct is_pointer : public __libcpp_is_pointer<typename remove_cv<_Tp>::type> {
404 };
405 
406 template <class _Tp>
407 struct __libcpp_is_member_pointer : public false_type {};
408 template <class _Tp, class _Up>
409 struct __libcpp_is_member_pointer<_Tp _Up::*> : public true_type {};
410 template <class _Tp>
411 struct is_member_pointer
412     : public __libcpp_is_member_pointer<typename remove_cv<_Tp>::type> {};
413 
414 template <class _Tp>
415 struct __libcpp_union : public false_type {};
416 template <class _Tp>
417 struct is_union : public __libcpp_union<typename remove_cv<_Tp>::type> {};
418 
419 template <class T>
420 struct is_reference : false_type {};
421 template <class T>
422 struct is_reference<T&> : true_type {};
423 template <class T>
424 struct is_reference<T&&> : true_type {};
425 
426 template <class T>
427 inline constexpr bool is_reference_v = is_reference<T>::value;
428 
429 struct __two {
430   char __lx[2];
431 };
432 
433 namespace __is_class_imp {
434 template <class _Tp>
435 char __test(int _Tp::*);
436 template <class _Tp>
437 __two __test(...);
438 }  // namespace __is_class_imp
439 template <class _Tp>
440 struct is_class
441     : public integral_constant<bool,
442                                sizeof(__is_class_imp::__test<_Tp>(0)) == 1 &&
443                                    !is_union<_Tp>::value> {};
444 
445 template <class _Tp>
446 struct __is_nullptr_t_impl : public false_type {};
447 template <>
448 struct __is_nullptr_t_impl<nullptr_t> : public true_type {};
449 template <class _Tp>
450 struct __is_nullptr_t
451     : public __is_nullptr_t_impl<typename remove_cv<_Tp>::type> {};
452 template <class _Tp>
453 struct is_null_pointer
454     : public __is_nullptr_t_impl<typename remove_cv<_Tp>::type> {};
455 
456 template <class _Tp>
457 struct is_enum
458     : public integral_constant<
459           bool, !is_void<_Tp>::value && !is_integral<_Tp>::value &&
460                     !is_floating_point<_Tp>::value && !is_array<_Tp>::value &&
461                     !is_pointer<_Tp>::value && !is_reference<_Tp>::value &&
462                     !is_member_pointer<_Tp>::value && !is_union<_Tp>::value &&
463                     !is_class<_Tp>::value && !is_function<_Tp>::value> {};
464 
465 template <class _Tp>
466 struct is_scalar
467     : public integral_constant<
468           bool, is_arithmetic<_Tp>::value || is_member_pointer<_Tp>::value ||
469                     is_pointer<_Tp>::value || __is_nullptr_t<_Tp>::value ||
470                     is_enum<_Tp>::value> {};
471 template <>
472 struct is_scalar<nullptr_t> : public true_type {};
473 
474 } // namespace std
475 
476 #endif // STD_TYPE_TRAITS_H
477 )";
478 
479 static constexpr char AbslTypeTraitsHeader[] = R"(
480 #ifndef ABSL_TYPE_TRAITS_H
481 #define ABSL_TYPE_TRAITS_H
482 
483 #include "std_type_traits.h"
484 
485 namespace absl {
486 
487 template <typename... Ts>
488 struct conjunction : std::true_type {};
489 
490 template <typename T, typename... Ts>
491 struct conjunction<T, Ts...>
492     : std::conditional<T::value, conjunction<Ts...>, T>::type {};
493 
494 template <typename T>
495 struct conjunction<T> : T {};
496 
497 template <typename T>
498 struct negation : std::integral_constant<bool, !T::value> {};
499 
500 template <bool B, typename T = void>
501 using enable_if_t = typename std::enable_if<B, T>::type;
502 
503 } // namespace absl
504 
505 #endif // ABSL_TYPE_TRAITS_H
506 )";
507 
508 static constexpr char StdStringHeader[] = R"(
509 #ifndef STRING_H
510 #define STRING_H
511 
512 namespace std {
513 
514 struct string {
515   string(const char*);
516   ~string();
517   bool empty();
518 };
519 bool operator!=(const string &LHS, const char *RHS);
520 
521 } // namespace std
522 
523 #endif // STRING_H
524 )";
525 
526 static constexpr char StdUtilityHeader[] = R"(
527 #ifndef UTILITY_H
528 #define UTILITY_H
529 
530 #include "std_type_traits.h"
531 
532 namespace std {
533 
534 template <typename T>
535 constexpr remove_reference_t<T>&& move(T&& x);
536 
537 template <typename T>
538 void swap(T& a, T& b) noexcept;
539 
540 } // namespace std
541 
542 #endif // UTILITY_H
543 )";
544 
545 static constexpr char StdInitializerListHeader[] = R"(
546 #ifndef INITIALIZER_LIST_H
547 #define INITIALIZER_LIST_H
548 
549 namespace std {
550 
551 template <typename T>
552 class initializer_list {
553  public:
554   initializer_list() noexcept;
555 };
556 
557 } // namespace std
558 
559 #endif // INITIALIZER_LIST_H
560 )";
561 
562 static constexpr char StdOptionalHeader[] = R"(
563 #include "std_initializer_list.h"
564 #include "std_type_traits.h"
565 #include "std_utility.h"
566 
567 namespace std {
568 
569 struct in_place_t {};
570 constexpr in_place_t in_place;
571 
572 struct nullopt_t {
573   constexpr explicit nullopt_t() {}
574 };
575 constexpr nullopt_t nullopt;
576 
577 template <class _Tp>
578 struct __optional_destruct_base {
579   constexpr void reset() noexcept;
580 };
581 
582 template <class _Tp>
583 struct __optional_storage_base : __optional_destruct_base<_Tp> {
584   constexpr bool has_value() const noexcept;
585 };
586 
587 template <typename _Tp>
588 class optional : private __optional_storage_base<_Tp> {
589   using __base = __optional_storage_base<_Tp>;
590 
591  public:
592   using value_type = _Tp;
593 
594  private:
595   struct _CheckOptionalArgsConstructor {
596     template <class _Up>
597     static constexpr bool __enable_implicit() {
598       return is_constructible_v<_Tp, _Up&&> && is_convertible_v<_Up&&, _Tp>;
599     }
600 
601     template <class _Up>
602     static constexpr bool __enable_explicit() {
603       return is_constructible_v<_Tp, _Up&&> && !is_convertible_v<_Up&&, _Tp>;
604     }
605   };
606   template <class _Up>
607   using _CheckOptionalArgsCtor =
608       _If<_IsNotSame<__uncvref_t<_Up>, in_place_t>::value &&
609               _IsNotSame<__uncvref_t<_Up>, optional>::value,
610           _CheckOptionalArgsConstructor, __check_tuple_constructor_fail>;
611   template <class _QualUp>
612   struct _CheckOptionalLikeConstructor {
613     template <class _Up, class _Opt = optional<_Up>>
614     using __check_constructible_from_opt =
615         _Or<is_constructible<_Tp, _Opt&>, is_constructible<_Tp, _Opt const&>,
616             is_constructible<_Tp, _Opt&&>, is_constructible<_Tp, _Opt const&&>,
617             is_convertible<_Opt&, _Tp>, is_convertible<_Opt const&, _Tp>,
618             is_convertible<_Opt&&, _Tp>, is_convertible<_Opt const&&, _Tp>>;
619     template <class _Up, class _QUp = _QualUp>
620     static constexpr bool __enable_implicit() {
621       return is_convertible<_QUp, _Tp>::value &&
622              !__check_constructible_from_opt<_Up>::value;
623     }
624     template <class _Up, class _QUp = _QualUp>
625     static constexpr bool __enable_explicit() {
626       return !is_convertible<_QUp, _Tp>::value &&
627              !__check_constructible_from_opt<_Up>::value;
628     }
629   };
630 
631   template <class _Up, class _QualUp>
632   using _CheckOptionalLikeCtor =
633       _If<_And<_IsNotSame<_Up, _Tp>, is_constructible<_Tp, _QualUp>>::value,
634           _CheckOptionalLikeConstructor<_QualUp>,
635           __check_tuple_constructor_fail>;
636 
637 
638   template <class _Up, class _QualUp>
639   using _CheckOptionalLikeAssign = _If<
640       _And<
641           _IsNotSame<_Up, _Tp>,
642           is_constructible<_Tp, _QualUp>,
643           is_assignable<_Tp&, _QualUp>
644       >::value,
645       _CheckOptionalLikeConstructor<_QualUp>,
646       __check_tuple_constructor_fail
647     >;
648 
649  public:
650   constexpr optional() noexcept {}
651   constexpr optional(const optional&) = default;
652   constexpr optional(optional&&) = default;
653   constexpr optional(nullopt_t) noexcept {}
654 
655   template <
656       class _InPlaceT, class... _Args,
657       class = enable_if_t<_And<_IsSame<_InPlaceT, in_place_t>,
658                              is_constructible<value_type, _Args...>>::value>>
659   constexpr explicit optional(_InPlaceT, _Args&&... __args);
660 
661   template <class _Up, class... _Args,
662             class = enable_if_t<is_constructible_v<
663                 value_type, initializer_list<_Up>&, _Args...>>>
664   constexpr explicit optional(in_place_t, initializer_list<_Up> __il,
665                               _Args&&... __args);
666 
667   template <
668       class _Up = value_type,
669       enable_if_t<_CheckOptionalArgsCtor<_Up>::template __enable_implicit<_Up>(),
670                 int> = 0>
671   constexpr optional(_Up&& __v);
672 
673   template <
674       class _Up,
675       enable_if_t<_CheckOptionalArgsCtor<_Up>::template __enable_explicit<_Up>(),
676                 int> = 0>
677   constexpr explicit optional(_Up&& __v);
678 
679   template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up const&>::
680                                      template __enable_implicit<_Up>(),
681                                  int> = 0>
682   constexpr optional(const optional<_Up>& __v);
683 
684   template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up const&>::
685                                      template __enable_explicit<_Up>(),
686                                  int> = 0>
687   constexpr explicit optional(const optional<_Up>& __v);
688 
689   template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up&&>::
690                                      template __enable_implicit<_Up>(),
691                                  int> = 0>
692   constexpr optional(optional<_Up>&& __v);
693 
694   template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up&&>::
695                                      template __enable_explicit<_Up>(),
696                                  int> = 0>
697   constexpr explicit optional(optional<_Up>&& __v);
698 
699   constexpr optional& operator=(nullopt_t) noexcept;
700 
701   optional& operator=(const optional&);
702 
703   optional& operator=(optional&&);
704 
705   template <class _Up = value_type,
706             class = enable_if_t<_And<_IsNotSame<__uncvref_t<_Up>, optional>,
707                                    _Or<_IsNotSame<__uncvref_t<_Up>, value_type>,
708                                        _Not<is_scalar<value_type>>>,
709                                    is_constructible<value_type, _Up>,
710                                    is_assignable<value_type&, _Up>>::value>>
711   constexpr optional& operator=(_Up&& __v);
712 
713   template <class _Up, enable_if_t<_CheckOptionalLikeAssign<_Up, _Up const&>::
714                                      template __enable_assign<_Up>(),
715                                  int> = 0>
716   constexpr optional& operator=(const optional<_Up>& __v);
717 
718   template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up&&>::
719                                      template __enable_assign<_Up>(),
720                                  int> = 0>
721   constexpr optional& operator=(optional<_Up>&& __v);
722 
723   const _Tp& operator*() const&;
724   _Tp& operator*() &;
725   const _Tp&& operator*() const&&;
726   _Tp&& operator*() &&;
727 
728   const _Tp* operator->() const;
729   _Tp* operator->();
730 
731   const _Tp& value() const&;
732   _Tp& value() &;
733   const _Tp&& value() const&&;
734   _Tp&& value() &&;
735 
736   template <typename U>
737   constexpr _Tp value_or(U&& v) const&;
738   template <typename U>
739   _Tp value_or(U&& v) &&;
740 
741   template <typename... Args>
742   _Tp& emplace(Args&&... args);
743 
744   template <typename U, typename... Args>
745   _Tp& emplace(std::initializer_list<U> ilist, Args&&... args);
746 
747   using __base::reset;
748 
749   constexpr explicit operator bool() const noexcept;
750   using __base::has_value;
751 
752   constexpr void swap(optional& __opt) noexcept;
753 };
754 
755 template <typename T>
756 constexpr optional<typename std::decay<T>::type> make_optional(T&& v);
757 
758 template <typename T, typename... Args>
759 constexpr optional<T> make_optional(Args&&... args);
760 
761 template <typename T, typename U, typename... Args>
762 constexpr optional<T> make_optional(std::initializer_list<U> il,
763                                     Args&&... args);
764 
765 template <typename T, typename U>
766 constexpr bool operator==(const optional<T> &lhs, const optional<U> &rhs);
767 template <typename T, typename U>
768 constexpr bool operator!=(const optional<T> &lhs, const optional<U> &rhs);
769 
770 template <typename T>
771 constexpr bool operator==(const optional<T> &opt, nullopt_t);
772 template <typename T>
773 constexpr bool operator==(nullopt_t, const optional<T> &opt);
774 template <typename T>
775 constexpr bool operator!=(const optional<T> &opt, nullopt_t);
776 template <typename T>
777 constexpr bool operator!=(nullopt_t, const optional<T> &opt);
778 
779 template <typename T, typename U>
780 constexpr bool operator==(const optional<T> &opt, const U &value);
781 template <typename T, typename U>
782 constexpr bool operator==(const T &value, const optional<U> &opt);
783 template <typename T, typename U>
784 constexpr bool operator!=(const optional<T> &opt, const U &value);
785 template <typename T, typename U>
786 constexpr bool operator!=(const T &value, const optional<U> &opt);
787 
788 } // namespace std
789 )";
790 
791 static constexpr char AbslOptionalHeader[] = R"(
792 #include "absl_type_traits.h"
793 #include "std_initializer_list.h"
794 #include "std_type_traits.h"
795 #include "std_utility.h"
796 
797 namespace absl {
798 
799 struct nullopt_t {
800   constexpr explicit nullopt_t() {}
801 };
802 constexpr nullopt_t nullopt;
803 
804 struct in_place_t {};
805 constexpr in_place_t in_place;
806 
807 template <typename T>
808 class optional;
809 
810 namespace optional_internal {
811 
812 template <typename T, typename U>
813 struct is_constructible_convertible_from_optional
814     : std::integral_constant<
815           bool, std::is_constructible<T, optional<U>&>::value ||
816                     std::is_constructible<T, optional<U>&&>::value ||
817                     std::is_constructible<T, const optional<U>&>::value ||
818                     std::is_constructible<T, const optional<U>&&>::value ||
819                     std::is_convertible<optional<U>&, T>::value ||
820                     std::is_convertible<optional<U>&&, T>::value ||
821                     std::is_convertible<const optional<U>&, T>::value ||
822                     std::is_convertible<const optional<U>&&, T>::value> {};
823 
824 template <typename T, typename U>
825 struct is_constructible_convertible_assignable_from_optional
826     : std::integral_constant<
827           bool, is_constructible_convertible_from_optional<T, U>::value ||
828                     std::is_assignable<T&, optional<U>&>::value ||
829                     std::is_assignable<T&, optional<U>&&>::value ||
830                     std::is_assignable<T&, const optional<U>&>::value ||
831                     std::is_assignable<T&, const optional<U>&&>::value> {};
832 
833 }  // namespace optional_internal
834 
835 template <typename T>
836 class optional {
837  public:
838   constexpr optional() noexcept;
839 
840   constexpr optional(nullopt_t) noexcept;
841 
842   optional(const optional&) = default;
843 
844   optional(optional&&) = default;
845 
846   template <typename InPlaceT, typename... Args,
847             absl::enable_if_t<absl::conjunction<
848                 std::is_same<InPlaceT, in_place_t>,
849                 std::is_constructible<T, Args&&...>>::value>* = nullptr>
850   constexpr explicit optional(InPlaceT, Args&&... args);
851 
852   template <typename U, typename... Args,
853             typename = typename std::enable_if<std::is_constructible<
854                 T, std::initializer_list<U>&, Args&&...>::value>::type>
855   constexpr explicit optional(in_place_t, std::initializer_list<U> il,
856                               Args&&... args);
857 
858   template <
859       typename U = T,
860       typename std::enable_if<
861           absl::conjunction<absl::negation<std::is_same<
862                                 in_place_t, typename std::decay<U>::type>>,
863                             absl::negation<std::is_same<
864                                 optional<T>, typename std::decay<U>::type>>,
865                             std::is_convertible<U&&, T>,
866                             std::is_constructible<T, U&&>>::value,
867           bool>::type = false>
868   constexpr optional(U&& v);
869 
870   template <
871       typename U = T,
872       typename std::enable_if<
873           absl::conjunction<absl::negation<std::is_same<
874                                 in_place_t, typename std::decay<U>::type>>,
875                             absl::negation<std::is_same<
876                                 optional<T>, typename std::decay<U>::type>>,
877                             absl::negation<std::is_convertible<U&&, T>>,
878                             std::is_constructible<T, U&&>>::value,
879           bool>::type = false>
880   explicit constexpr optional(U&& v);
881 
882   template <typename U,
883             typename std::enable_if<
884                 absl::conjunction<
885                     absl::negation<std::is_same<T, U>>,
886                     std::is_constructible<T, const U&>,
887                     absl::negation<
888                         optional_internal::
889                             is_constructible_convertible_from_optional<T, U>>,
890                     std::is_convertible<const U&, T>>::value,
891                 bool>::type = false>
892   optional(const optional<U>& rhs);
893 
894   template <typename U,
895             typename std::enable_if<
896                 absl::conjunction<
897                     absl::negation<std::is_same<T, U>>,
898                     std::is_constructible<T, const U&>,
899                     absl::negation<
900                         optional_internal::
901                             is_constructible_convertible_from_optional<T, U>>,
902                     absl::negation<std::is_convertible<const U&, T>>>::value,
903                 bool>::type = false>
904   explicit optional(const optional<U>& rhs);
905 
906   template <
907       typename U,
908       typename std::enable_if<
909           absl::conjunction<
910               absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
911               absl::negation<
912                   optional_internal::is_constructible_convertible_from_optional<
913                       T, U>>,
914               std::is_convertible<U&&, T>>::value,
915           bool>::type = false>
916   optional(optional<U>&& rhs);
917 
918   template <
919       typename U,
920       typename std::enable_if<
921           absl::conjunction<
922               absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
923               absl::negation<
924                   optional_internal::is_constructible_convertible_from_optional<
925                       T, U>>,
926               absl::negation<std::is_convertible<U&&, T>>>::value,
927           bool>::type = false>
928   explicit optional(optional<U>&& rhs);
929 
930   optional& operator=(nullopt_t) noexcept;
931 
932   optional& operator=(const optional& src);
933 
934   optional& operator=(optional&& src);
935 
936   template <
937       typename U = T,
938       typename = typename std::enable_if<absl::conjunction<
939           absl::negation<
940               std::is_same<optional<T>, typename std::decay<U>::type>>,
941           absl::negation<
942               absl::conjunction<std::is_scalar<T>,
943                                 std::is_same<T, typename std::decay<U>::type>>>,
944           std::is_constructible<T, U>, std::is_assignable<T&, U>>::value>::type>
945   optional& operator=(U&& v);
946 
947   template <
948       typename U,
949       typename = typename std::enable_if<absl::conjunction<
950           absl::negation<std::is_same<T, U>>,
951           std::is_constructible<T, const U&>, std::is_assignable<T&, const U&>,
952           absl::negation<
953               optional_internal::
954                   is_constructible_convertible_assignable_from_optional<
955                       T, U>>>::value>::type>
956   optional& operator=(const optional<U>& rhs);
957 
958   template <typename U,
959             typename = typename std::enable_if<absl::conjunction<
960                 absl::negation<std::is_same<T, U>>, std::is_constructible<T, U>,
961                 std::is_assignable<T&, U>,
962                 absl::negation<
963                     optional_internal::
964                         is_constructible_convertible_assignable_from_optional<
965                             T, U>>>::value>::type>
966   optional& operator=(optional<U>&& rhs);
967 
968   const T& operator*() const&;
969   T& operator*() &;
970   const T&& operator*() const&&;
971   T&& operator*() &&;
972 
973   const T* operator->() const;
974   T* operator->();
975 
976   const T& value() const&;
977   T& value() &;
978   const T&& value() const&&;
979   T&& value() &&;
980 
981   template <typename U>
982   constexpr T value_or(U&& v) const&;
983   template <typename U>
984   T value_or(U&& v) &&;
985 
986   template <typename... Args>
987   T& emplace(Args&&... args);
988 
989   template <typename U, typename... Args>
990   T& emplace(std::initializer_list<U> ilist, Args&&... args);
991 
992   void reset() noexcept;
993 
994   constexpr explicit operator bool() const noexcept;
995   constexpr bool has_value() const noexcept;
996 
997   void swap(optional& rhs) noexcept;
998 };
999 
1000 template <typename T>
1001 constexpr optional<typename std::decay<T>::type> make_optional(T&& v);
1002 
1003 template <typename T, typename... Args>
1004 constexpr optional<T> make_optional(Args&&... args);
1005 
1006 template <typename T, typename U, typename... Args>
1007 constexpr optional<T> make_optional(std::initializer_list<U> il,
1008                                     Args&&... args);
1009 
1010 template <typename T, typename U>
1011 constexpr bool operator==(const optional<T> &lhs, const optional<U> &rhs);
1012 template <typename T, typename U>
1013 constexpr bool operator!=(const optional<T> &lhs, const optional<U> &rhs);
1014 
1015 template <typename T>
1016 constexpr bool operator==(const optional<T> &opt, nullopt_t);
1017 template <typename T>
1018 constexpr bool operator==(nullopt_t, const optional<T> &opt);
1019 template <typename T>
1020 constexpr bool operator!=(const optional<T> &opt, nullopt_t);
1021 template <typename T>
1022 constexpr bool operator!=(nullopt_t, const optional<T> &opt);
1023 
1024 template <typename T, typename U>
1025 constexpr bool operator==(const optional<T> &opt, const U &value);
1026 template <typename T, typename U>
1027 constexpr bool operator==(const T &value, const optional<U> &opt);
1028 template <typename T, typename U>
1029 constexpr bool operator!=(const optional<T> &opt, const U &value);
1030 template <typename T, typename U>
1031 constexpr bool operator!=(const T &value, const optional<U> &opt);
1032 
1033 } // namespace absl
1034 )";
1035 
1036 static constexpr char BaseOptionalHeader[] = R"(
1037 #include "std_initializer_list.h"
1038 #include "std_type_traits.h"
1039 #include "std_utility.h"
1040 
1041 namespace base {
1042 
1043 struct in_place_t {};
1044 constexpr in_place_t in_place;
1045 
1046 struct nullopt_t {
1047   constexpr explicit nullopt_t() {}
1048 };
1049 constexpr nullopt_t nullopt;
1050 
1051 template <typename T>
1052 class Optional;
1053 
1054 namespace internal {
1055 
1056 template <typename T>
1057 using RemoveCvRefT = std::remove_cv_t<std::remove_reference_t<T>>;
1058 
1059 template <typename T, typename U>
1060 struct IsConvertibleFromOptional
1061     : std::integral_constant<
1062           bool, std::is_constructible<T, Optional<U>&>::value ||
1063                     std::is_constructible<T, const Optional<U>&>::value ||
1064                     std::is_constructible<T, Optional<U>&&>::value ||
1065                     std::is_constructible<T, const Optional<U>&&>::value ||
1066                     std::is_convertible<Optional<U>&, T>::value ||
1067                     std::is_convertible<const Optional<U>&, T>::value ||
1068                     std::is_convertible<Optional<U>&&, T>::value ||
1069                     std::is_convertible<const Optional<U>&&, T>::value> {};
1070 
1071 template <typename T, typename U>
1072 struct IsAssignableFromOptional
1073     : std::integral_constant<
1074           bool, IsConvertibleFromOptional<T, U>::value ||
1075                     std::is_assignable<T&, Optional<U>&>::value ||
1076                     std::is_assignable<T&, const Optional<U>&>::value ||
1077                     std::is_assignable<T&, Optional<U>&&>::value ||
1078                     std::is_assignable<T&, const Optional<U>&&>::value> {};
1079 
1080 }  // namespace internal
1081 
1082 template <typename T>
1083 class Optional {
1084  public:
1085   using value_type = T;
1086 
1087   constexpr Optional() = default;
1088   constexpr Optional(const Optional& other) noexcept = default;
1089   constexpr Optional(Optional&& other) noexcept = default;
1090 
1091   constexpr Optional(nullopt_t);
1092 
1093   template <typename U,
1094             typename std::enable_if<
1095                 std::is_constructible<T, const U&>::value &&
1096                     !internal::IsConvertibleFromOptional<T, U>::value &&
1097                     std::is_convertible<const U&, T>::value,
1098                 bool>::type = false>
1099   Optional(const Optional<U>& other) noexcept;
1100 
1101   template <typename U,
1102             typename std::enable_if<
1103                 std::is_constructible<T, const U&>::value &&
1104                     !internal::IsConvertibleFromOptional<T, U>::value &&
1105                     !std::is_convertible<const U&, T>::value,
1106                 bool>::type = false>
1107   explicit Optional(const Optional<U>& other) noexcept;
1108 
1109   template <typename U,
1110             typename std::enable_if<
1111                 std::is_constructible<T, U&&>::value &&
1112                     !internal::IsConvertibleFromOptional<T, U>::value &&
1113                     std::is_convertible<U&&, T>::value,
1114                 bool>::type = false>
1115   Optional(Optional<U>&& other) noexcept;
1116 
1117   template <typename U,
1118             typename std::enable_if<
1119                 std::is_constructible<T, U&&>::value &&
1120                     !internal::IsConvertibleFromOptional<T, U>::value &&
1121                     !std::is_convertible<U&&, T>::value,
1122                 bool>::type = false>
1123   explicit Optional(Optional<U>&& other) noexcept;
1124 
1125   template <class... Args>
1126   constexpr explicit Optional(in_place_t, Args&&... args);
1127 
1128   template <class U, class... Args,
1129             class = typename std::enable_if<std::is_constructible<
1130                 value_type, std::initializer_list<U>&, Args...>::value>::type>
1131   constexpr explicit Optional(in_place_t, std::initializer_list<U> il,
1132                               Args&&... args);
1133 
1134   template <
1135       typename U = value_type,
1136       typename std::enable_if<
1137           std::is_constructible<T, U&&>::value &&
1138               !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
1139               !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
1140               std::is_convertible<U&&, T>::value,
1141           bool>::type = false>
1142   constexpr Optional(U&& value);
1143 
1144   template <
1145       typename U = value_type,
1146       typename std::enable_if<
1147           std::is_constructible<T, U&&>::value &&
1148               !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
1149               !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
1150               !std::is_convertible<U&&, T>::value,
1151           bool>::type = false>
1152   constexpr explicit Optional(U&& value);
1153 
1154   Optional& operator=(const Optional& other) noexcept;
1155 
1156   Optional& operator=(Optional&& other) noexcept;
1157 
1158   Optional& operator=(nullopt_t);
1159 
1160   template <typename U>
1161   typename std::enable_if<
1162       !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
1163           std::is_constructible<T, U>::value &&
1164           std::is_assignable<T&, U>::value &&
1165           (!std::is_scalar<T>::value ||
1166            !std::is_same<typename std::decay<U>::type, T>::value),
1167       Optional&>::type
1168   operator=(U&& value) noexcept;
1169 
1170   template <typename U>
1171   typename std::enable_if<!internal::IsAssignableFromOptional<T, U>::value &&
1172                               std::is_constructible<T, const U&>::value &&
1173                               std::is_assignable<T&, const U&>::value,
1174                           Optional&>::type
1175   operator=(const Optional<U>& other) noexcept;
1176 
1177   template <typename U>
1178   typename std::enable_if<!internal::IsAssignableFromOptional<T, U>::value &&
1179                               std::is_constructible<T, U>::value &&
1180                               std::is_assignable<T&, U>::value,
1181                           Optional&>::type
1182   operator=(Optional<U>&& other) noexcept;
1183 
1184   const T& operator*() const&;
1185   T& operator*() &;
1186   const T&& operator*() const&&;
1187   T&& operator*() &&;
1188 
1189   const T* operator->() const;
1190   T* operator->();
1191 
1192   const T& value() const&;
1193   T& value() &;
1194   const T&& value() const&&;
1195   T&& value() &&;
1196 
1197   template <typename U>
1198   constexpr T value_or(U&& v) const&;
1199   template <typename U>
1200   T value_or(U&& v) &&;
1201 
1202   template <typename... Args>
1203   T& emplace(Args&&... args);
1204 
1205   template <typename U, typename... Args>
1206   T& emplace(std::initializer_list<U> ilist, Args&&... args);
1207 
1208   void reset() noexcept;
1209 
1210   constexpr explicit operator bool() const noexcept;
1211   constexpr bool has_value() const noexcept;
1212 
1213   void swap(Optional& other);
1214 };
1215 
1216 template <typename T>
1217 constexpr Optional<typename std::decay<T>::type> make_optional(T&& v);
1218 
1219 template <typename T, typename... Args>
1220 constexpr Optional<T> make_optional(Args&&... args);
1221 
1222 template <typename T, typename U, typename... Args>
1223 constexpr Optional<T> make_optional(std::initializer_list<U> il,
1224                                     Args&&... args);
1225 
1226 template <typename T, typename U>
1227 constexpr bool operator==(const Optional<T> &lhs, const Optional<U> &rhs);
1228 template <typename T, typename U>
1229 constexpr bool operator!=(const Optional<T> &lhs, const Optional<U> &rhs);
1230 
1231 template <typename T>
1232 constexpr bool operator==(const Optional<T> &opt, nullopt_t);
1233 template <typename T>
1234 constexpr bool operator==(nullopt_t, const Optional<T> &opt);
1235 template <typename T>
1236 constexpr bool operator!=(const Optional<T> &opt, nullopt_t);
1237 template <typename T>
1238 constexpr bool operator!=(nullopt_t, const Optional<T> &opt);
1239 
1240 template <typename T, typename U>
1241 constexpr bool operator==(const Optional<T> &opt, const U &value);
1242 template <typename T, typename U>
1243 constexpr bool operator==(const T &value, const Optional<U> &opt);
1244 template <typename T, typename U>
1245 constexpr bool operator!=(const Optional<T> &opt, const U &value);
1246 template <typename T, typename U>
1247 constexpr bool operator!=(const T &value, const Optional<U> &opt);
1248 
1249 } // namespace base
1250 )";
1251 
1252 /// Replaces all occurrences of `Pattern` in `S` with `Replacement`.
1253 static void ReplaceAllOccurrences(std::string &S, const std::string &Pattern,
1254                                   const std::string &Replacement) {
1255   size_t Pos = 0;
1256   while (true) {
1257     Pos = S.find(Pattern, Pos);
1258     if (Pos == std::string::npos)
1259       break;
1260     S.replace(Pos, Pattern.size(), Replacement);
1261   }
1262 }
1263 
1264 struct OptionalTypeIdentifier {
1265   std::string NamespaceName;
1266   std::string TypeName;
1267 };
1268 
1269 class UncheckedOptionalAccessTest
1270     : public ::testing::TestWithParam<OptionalTypeIdentifier> {
1271 protected:
1272   void ExpectDiagnosticsFor(std::string SourceCode) {
1273     ExpectDiagnosticsFor(SourceCode, ast_matchers::hasName("target"));
1274   }
1275 
1276   template <typename FuncDeclMatcher>
1277   void ExpectDiagnosticsFor(std::string SourceCode,
1278                             FuncDeclMatcher FuncMatcher) {
1279     ReplaceAllOccurrences(SourceCode, "$ns", GetParam().NamespaceName);
1280     ReplaceAllOccurrences(SourceCode, "$optional", GetParam().TypeName);
1281 
1282     std::vector<std::pair<std::string, std::string>> Headers;
1283     Headers.emplace_back("cstddef.h", CSDtdDefHeader);
1284     Headers.emplace_back("std_initializer_list.h", StdInitializerListHeader);
1285     Headers.emplace_back("std_string.h", StdStringHeader);
1286     Headers.emplace_back("std_type_traits.h", StdTypeTraitsHeader);
1287     Headers.emplace_back("std_utility.h", StdUtilityHeader);
1288     Headers.emplace_back("std_optional.h", StdOptionalHeader);
1289     Headers.emplace_back("absl_type_traits.h", AbslTypeTraitsHeader);
1290     Headers.emplace_back("absl_optional.h", AbslOptionalHeader);
1291     Headers.emplace_back("base_optional.h", BaseOptionalHeader);
1292     Headers.emplace_back("unchecked_optional_access_test.h", R"(
1293       #include "absl_optional.h"
1294       #include "base_optional.h"
1295       #include "std_initializer_list.h"
1296       #include "std_optional.h"
1297       #include "std_string.h"
1298       #include "std_utility.h"
1299 
1300       template <typename T>
1301       T Make();
1302     )");
1303     UncheckedOptionalAccessModelOptions Options{
1304         /*IgnoreSmartPointerDereference=*/true};
1305     std::vector<SourceLocation> Diagnostics;
1306     llvm::Error Error = checkDataflow<UncheckedOptionalAccessModel>(
1307         AnalysisInputs<UncheckedOptionalAccessModel>(
1308             SourceCode, std::move(FuncMatcher),
1309             [](ASTContext &Ctx, Environment &) {
1310               return UncheckedOptionalAccessModel(Ctx);
1311             })
1312             .withPostVisitCFG(
1313                 [&Diagnostics,
1314                  Diagnoser = UncheckedOptionalAccessDiagnoser(Options)](
1315                     ASTContext &Ctx, const CFGElement &Elt,
1316                     const TransferStateForDiagnostics<NoopLattice>
1317                         &State) mutable {
1318                   auto EltDiagnostics =
1319                       Diagnoser.diagnose(Ctx, &Elt, State.Env);
1320                   llvm::move(EltDiagnostics, std::back_inserter(Diagnostics));
1321                 })
1322             .withASTBuildArgs(
1323                 {"-fsyntax-only", "-std=c++17", "-Wno-undefined-inline"})
1324             .withASTBuildVirtualMappedFiles(
1325                 tooling::FileContentMappings(Headers.begin(), Headers.end())),
1326         /*VerifyResults=*/[&Diagnostics](
1327                               const llvm::DenseMap<unsigned, std::string>
1328                                   &Annotations,
1329                               const AnalysisOutputs &AO) {
1330           llvm::DenseSet<unsigned> AnnotationLines;
1331           for (const auto &[Line, _] : Annotations) {
1332             AnnotationLines.insert(Line);
1333           }
1334           auto &SrcMgr = AO.ASTCtx.getSourceManager();
1335           llvm::DenseSet<unsigned> DiagnosticLines;
1336           for (SourceLocation &Loc : Diagnostics) {
1337             DiagnosticLines.insert(SrcMgr.getPresumedLineNumber(Loc));
1338           }
1339 
1340           EXPECT_THAT(DiagnosticLines, ContainerEq(AnnotationLines));
1341         });
1342     if (Error)
1343       FAIL() << llvm::toString(std::move(Error));
1344   }
1345 };
1346 
1347 INSTANTIATE_TEST_SUITE_P(
1348     UncheckedOptionalUseTestInst, UncheckedOptionalAccessTest,
1349     ::testing::Values(OptionalTypeIdentifier{"std", "optional"},
1350                       OptionalTypeIdentifier{"absl", "optional"},
1351                       OptionalTypeIdentifier{"base", "Optional"}),
1352     [](const ::testing::TestParamInfo<OptionalTypeIdentifier> &Info) {
1353       return Info.param.NamespaceName;
1354     });
1355 
1356 TEST_P(UncheckedOptionalAccessTest, EmptyFunctionBody) {
1357   ExpectDiagnosticsFor(R"(
1358     void target() {
1359       (void)0;
1360     }
1361   )");
1362 }
1363 
1364 TEST_P(UncheckedOptionalAccessTest, UnwrapUsingValueNoCheck) {
1365   ExpectDiagnosticsFor(
1366       R"(
1367     #include "unchecked_optional_access_test.h"
1368 
1369     void target($ns::$optional<int> opt) {
1370       opt.value(); // [[unsafe]]
1371     }
1372   )");
1373 
1374   ExpectDiagnosticsFor(
1375       R"(
1376     #include "unchecked_optional_access_test.h"
1377 
1378     void target($ns::$optional<int> opt) {
1379       std::move(opt).value(); // [[unsafe]]
1380     }
1381   )");
1382 }
1383 
1384 TEST_P(UncheckedOptionalAccessTest, UnwrapUsingOperatorStarNoCheck) {
1385   ExpectDiagnosticsFor(
1386       R"(
1387     #include "unchecked_optional_access_test.h"
1388 
1389     void target($ns::$optional<int> opt) {
1390       *opt; // [[unsafe]]
1391     }
1392   )");
1393 
1394   ExpectDiagnosticsFor(
1395       R"(
1396     #include "unchecked_optional_access_test.h"
1397 
1398     void target($ns::$optional<int> opt) {
1399       *std::move(opt); // [[unsafe]]
1400     }
1401   )");
1402 }
1403 
1404 TEST_P(UncheckedOptionalAccessTest, UnwrapUsingOperatorArrowNoCheck) {
1405   ExpectDiagnosticsFor(
1406       R"(
1407     #include "unchecked_optional_access_test.h"
1408 
1409     struct Foo {
1410       void foo();
1411     };
1412 
1413     void target($ns::$optional<Foo> opt) {
1414       opt->foo(); // [[unsafe]]
1415     }
1416   )");
1417 
1418   ExpectDiagnosticsFor(
1419       R"(
1420     #include "unchecked_optional_access_test.h"
1421 
1422     struct Foo {
1423       void foo();
1424     };
1425 
1426     void target($ns::$optional<Foo> opt) {
1427       std::move(opt)->foo(); // [[unsafe]]
1428     }
1429   )");
1430 }
1431 
1432 TEST_P(UncheckedOptionalAccessTest, HasValueCheck) {
1433   ExpectDiagnosticsFor(R"(
1434     #include "unchecked_optional_access_test.h"
1435 
1436     void target($ns::$optional<int> opt) {
1437       if (opt.has_value()) {
1438         opt.value();
1439       }
1440     }
1441   )");
1442 }
1443 
1444 TEST_P(UncheckedOptionalAccessTest, OperatorBoolCheck) {
1445   ExpectDiagnosticsFor(R"(
1446     #include "unchecked_optional_access_test.h"
1447 
1448     void target($ns::$optional<int> opt) {
1449       if (opt) {
1450         opt.value();
1451       }
1452     }
1453   )");
1454 }
1455 
1456 TEST_P(UncheckedOptionalAccessTest, UnwrapFunctionCallResultNoCheck) {
1457   ExpectDiagnosticsFor(
1458       R"(
1459     #include "unchecked_optional_access_test.h"
1460 
1461     void target() {
1462       Make<$ns::$optional<int>>().value(); // [[unsafe]]
1463       (void)0;
1464     }
1465   )");
1466 
1467   ExpectDiagnosticsFor(
1468       R"(
1469     #include "unchecked_optional_access_test.h"
1470 
1471     void target($ns::$optional<int> opt) {
1472       std::move(opt).value(); // [[unsafe]]
1473     }
1474   )");
1475 }
1476 
1477 TEST_P(UncheckedOptionalAccessTest, DefaultConstructor) {
1478   ExpectDiagnosticsFor(
1479       R"(
1480     #include "unchecked_optional_access_test.h"
1481 
1482     void target() {
1483       $ns::$optional<int> opt;
1484       opt.value(); // [[unsafe]]
1485     }
1486   )");
1487 }
1488 
1489 TEST_P(UncheckedOptionalAccessTest, NulloptConstructor) {
1490   ExpectDiagnosticsFor(
1491       R"(
1492     #include "unchecked_optional_access_test.h"
1493 
1494     void target() {
1495       $ns::$optional<int> opt($ns::nullopt);
1496       opt.value(); // [[unsafe]]
1497     }
1498   )");
1499 }
1500 
1501 TEST_P(UncheckedOptionalAccessTest, NulloptConstructorWithSugaredType) {
1502   ExpectDiagnosticsFor(
1503       R"(
1504     #include "unchecked_optional_access_test.h"
1505     template <typename T>
1506     using wrapper = T;
1507 
1508     template <typename T>
1509     wrapper<T> wrap(T);
1510 
1511     void target() {
1512       $ns::$optional<int> opt(wrap($ns::nullopt));
1513       opt.value(); // [[unsafe]]
1514     }
1515   )");
1516 }
1517 
1518 TEST_P(UncheckedOptionalAccessTest, InPlaceConstructor) {
1519   ExpectDiagnosticsFor(R"(
1520     #include "unchecked_optional_access_test.h"
1521 
1522     void target() {
1523       $ns::$optional<int> opt($ns::in_place, 3);
1524       opt.value();
1525     }
1526   )");
1527 
1528   ExpectDiagnosticsFor(R"(
1529     #include "unchecked_optional_access_test.h"
1530 
1531     struct Foo {};
1532 
1533     void target() {
1534       $ns::$optional<Foo> opt($ns::in_place);
1535       opt.value();
1536     }
1537   )");
1538 
1539   ExpectDiagnosticsFor(R"(
1540     #include "unchecked_optional_access_test.h"
1541 
1542     struct Foo {
1543       explicit Foo(int, bool);
1544     };
1545 
1546     void target() {
1547       $ns::$optional<Foo> opt($ns::in_place, 3, false);
1548       opt.value();
1549     }
1550   )");
1551 
1552   ExpectDiagnosticsFor(R"(
1553     #include "unchecked_optional_access_test.h"
1554 
1555     struct Foo {
1556       explicit Foo(std::initializer_list<int>);
1557     };
1558 
1559     void target() {
1560       $ns::$optional<Foo> opt($ns::in_place, {3});
1561       opt.value();
1562     }
1563   )");
1564 }
1565 
1566 TEST_P(UncheckedOptionalAccessTest, ValueConstructor) {
1567   ExpectDiagnosticsFor(R"(
1568     #include "unchecked_optional_access_test.h"
1569 
1570     void target() {
1571       $ns::$optional<int> opt(21);
1572       opt.value();
1573     }
1574   )");
1575 
1576   ExpectDiagnosticsFor(R"(
1577     #include "unchecked_optional_access_test.h"
1578 
1579     void target() {
1580       $ns::$optional<int> opt = $ns::$optional<int>(21);
1581       opt.value();
1582     }
1583   )");
1584   ExpectDiagnosticsFor(R"(
1585     #include "unchecked_optional_access_test.h"
1586 
1587     void target() {
1588       $ns::$optional<$ns::$optional<int>> opt(Make<$ns::$optional<int>>());
1589       opt.value();
1590     }
1591   )");
1592 
1593   ExpectDiagnosticsFor(R"(
1594     #include "unchecked_optional_access_test.h"
1595 
1596     struct MyString {
1597       MyString(const char*);
1598     };
1599 
1600     void target() {
1601       $ns::$optional<MyString> opt("foo");
1602       opt.value();
1603     }
1604   )");
1605 
1606   ExpectDiagnosticsFor(R"(
1607     #include "unchecked_optional_access_test.h"
1608 
1609     struct Foo {};
1610 
1611     struct Bar {
1612       Bar(const Foo&);
1613     };
1614 
1615     void target() {
1616       $ns::$optional<Bar> opt(Make<Foo>());
1617       opt.value();
1618     }
1619   )");
1620 
1621   ExpectDiagnosticsFor(R"(
1622     #include "unchecked_optional_access_test.h"
1623 
1624     struct Foo {
1625       explicit Foo(int);
1626     };
1627 
1628     void target() {
1629       $ns::$optional<Foo> opt(3);
1630       opt.value();
1631     }
1632   )");
1633 }
1634 
1635 TEST_P(UncheckedOptionalAccessTest, ConvertibleOptionalConstructor) {
1636   ExpectDiagnosticsFor(
1637       R"(
1638     #include "unchecked_optional_access_test.h"
1639 
1640     struct Foo {};
1641 
1642     struct Bar {
1643       Bar(const Foo&);
1644     };
1645 
1646     void target() {
1647       $ns::$optional<Bar> opt(Make<$ns::$optional<Foo>>());
1648       opt.value(); // [[unsafe]]
1649     }
1650   )");
1651 
1652   ExpectDiagnosticsFor(
1653       R"(
1654     #include "unchecked_optional_access_test.h"
1655 
1656     struct Foo {};
1657 
1658     struct Bar {
1659       explicit Bar(const Foo&);
1660     };
1661 
1662     void target() {
1663       $ns::$optional<Bar> opt(Make<$ns::$optional<Foo>>());
1664       opt.value(); // [[unsafe]]
1665     }
1666   )");
1667 
1668   ExpectDiagnosticsFor(
1669       R"(
1670     #include "unchecked_optional_access_test.h"
1671 
1672     struct Foo {};
1673 
1674     struct Bar {
1675       Bar(const Foo&);
1676     };
1677 
1678     void target() {
1679       $ns::$optional<Foo> opt1 = $ns::nullopt;
1680       $ns::$optional<Bar> opt2(opt1);
1681       opt2.value(); // [[unsafe]]
1682     }
1683   )");
1684 
1685   ExpectDiagnosticsFor(R"(
1686     #include "unchecked_optional_access_test.h"
1687 
1688     struct Foo {};
1689 
1690     struct Bar {
1691       Bar(const Foo&);
1692     };
1693 
1694     void target() {
1695       $ns::$optional<Foo> opt1(Make<Foo>());
1696       $ns::$optional<Bar> opt2(opt1);
1697       opt2.value();
1698     }
1699   )");
1700 
1701   ExpectDiagnosticsFor(R"(
1702     #include "unchecked_optional_access_test.h"
1703 
1704     struct Foo {};
1705 
1706     struct Bar {
1707       explicit Bar(const Foo&);
1708     };
1709 
1710     void target() {
1711       $ns::$optional<Foo> opt1(Make<Foo>());
1712       $ns::$optional<Bar> opt2(opt1);
1713       opt2.value();
1714     }
1715   )");
1716 }
1717 
1718 TEST_P(UncheckedOptionalAccessTest, MakeOptional) {
1719   ExpectDiagnosticsFor(R"(
1720     #include "unchecked_optional_access_test.h"
1721 
1722     void target() {
1723       $ns::$optional<int> opt = $ns::make_optional(0);
1724       opt.value();
1725     }
1726   )");
1727 
1728   ExpectDiagnosticsFor(R"(
1729     #include "unchecked_optional_access_test.h"
1730 
1731     struct Foo {
1732       Foo(int, int);
1733     };
1734 
1735     void target() {
1736       $ns::$optional<Foo> opt = $ns::make_optional<Foo>(21, 22);
1737       opt.value();
1738     }
1739   )");
1740 
1741   ExpectDiagnosticsFor(R"(
1742     #include "unchecked_optional_access_test.h"
1743 
1744     struct Foo {
1745       constexpr Foo(std::initializer_list<char>);
1746     };
1747 
1748     void target() {
1749       char a = 'a';
1750       $ns::$optional<Foo> opt = $ns::make_optional<Foo>({a});
1751       opt.value();
1752     }
1753   )");
1754 }
1755 
1756 TEST_P(UncheckedOptionalAccessTest, ValueOr) {
1757   ExpectDiagnosticsFor(R"(
1758     #include "unchecked_optional_access_test.h"
1759 
1760     void target() {
1761       $ns::$optional<int> opt;
1762       opt.value_or(0);
1763       (void)0;
1764     }
1765   )");
1766 }
1767 
1768 TEST_P(UncheckedOptionalAccessTest, ValueOrComparison) {
1769   // Pointers.
1770   ExpectDiagnosticsFor(
1771       R"code(
1772     #include "unchecked_optional_access_test.h"
1773 
1774     void target($ns::$optional<int*> opt) {
1775       if (opt.value_or(nullptr) != nullptr) {
1776         opt.value();
1777       } else {
1778         opt.value(); // [[unsafe]]
1779       }
1780     }
1781   )code");
1782 
1783   // Integers.
1784   ExpectDiagnosticsFor(
1785       R"code(
1786     #include "unchecked_optional_access_test.h"
1787 
1788     void target($ns::$optional<int> opt) {
1789       if (opt.value_or(0) != 0) {
1790         opt.value();
1791       } else {
1792         opt.value(); // [[unsafe]]
1793       }
1794     }
1795   )code");
1796 
1797   // Strings.
1798   ExpectDiagnosticsFor(
1799       R"code(
1800     #include "unchecked_optional_access_test.h"
1801 
1802     void target($ns::$optional<std::string> opt) {
1803       if (!opt.value_or("").empty()) {
1804         opt.value();
1805       } else {
1806         opt.value(); // [[unsafe]]
1807       }
1808     }
1809   )code");
1810 
1811   ExpectDiagnosticsFor(
1812       R"code(
1813     #include "unchecked_optional_access_test.h"
1814 
1815     void target($ns::$optional<std::string> opt) {
1816       if (opt.value_or("") != "") {
1817         opt.value();
1818       } else {
1819         opt.value(); // [[unsafe]]
1820       }
1821     }
1822   )code");
1823 
1824   // Pointer-to-optional.
1825   //
1826   // FIXME: make `opt` a parameter directly, once we ensure that all `optional`
1827   // values have a `has_value` property.
1828   ExpectDiagnosticsFor(
1829       R"code(
1830     #include "unchecked_optional_access_test.h"
1831 
1832     void target($ns::$optional<int> p) {
1833       $ns::$optional<int> *opt = &p;
1834       if (opt->value_or(0) != 0) {
1835         opt->value();
1836       } else {
1837         opt->value(); // [[unsafe]]
1838       }
1839     }
1840   )code");
1841 }
1842 
1843 TEST_P(UncheckedOptionalAccessTest, Emplace) {
1844   ExpectDiagnosticsFor(R"(
1845     #include "unchecked_optional_access_test.h"
1846 
1847     void target() {
1848       $ns::$optional<int> opt;
1849       opt.emplace(0);
1850       opt.value();
1851     }
1852   )");
1853 
1854   ExpectDiagnosticsFor(R"(
1855     #include "unchecked_optional_access_test.h"
1856 
1857     void target($ns::$optional<int> *opt) {
1858       opt->emplace(0);
1859       opt->value();
1860     }
1861   )");
1862 
1863   // FIXME: Add tests that call `emplace` in conditional branches:
1864   //  ExpectDiagnosticsFor(
1865   //      R"(
1866   //    #include "unchecked_optional_access_test.h"
1867   //
1868   //    void target($ns::$optional<int> opt, bool b) {
1869   //      if (b) {
1870   //        opt.emplace(0);
1871   //      }
1872   //      if (b) {
1873   //        opt.value();
1874   //      } else {
1875   //        opt.value(); // [[unsafe]]
1876   //      }
1877   //    }
1878   //  )");
1879 }
1880 
1881 TEST_P(UncheckedOptionalAccessTest, Reset) {
1882   ExpectDiagnosticsFor(
1883       R"(
1884     #include "unchecked_optional_access_test.h"
1885 
1886     void target() {
1887       $ns::$optional<int> opt = $ns::make_optional(0);
1888       opt.reset();
1889       opt.value(); // [[unsafe]]
1890     }
1891   )");
1892 
1893   ExpectDiagnosticsFor(
1894       R"(
1895     #include "unchecked_optional_access_test.h"
1896 
1897     void target($ns::$optional<int> &opt) {
1898       if (opt.has_value()) {
1899         opt.reset();
1900         opt.value(); // [[unsafe]]
1901       }
1902     }
1903   )");
1904 
1905   // FIXME: Add tests that call `reset` in conditional branches:
1906   //  ExpectDiagnosticsFor(
1907   //      R"(
1908   //    #include "unchecked_optional_access_test.h"
1909   //
1910   //    void target(bool b) {
1911   //      $ns::$optional<int> opt = $ns::make_optional(0);
1912   //      if (b) {
1913   //        opt.reset();
1914   //      }
1915   //      if (b) {
1916   //        opt.value(); // [[unsafe]]
1917   //      } else {
1918   //        opt.value();
1919   //      }
1920   //    }
1921   //  )");
1922 }
1923 
1924 TEST_P(UncheckedOptionalAccessTest, ValueAssignment) {
1925   ExpectDiagnosticsFor(R"(
1926     #include "unchecked_optional_access_test.h"
1927 
1928     struct Foo {};
1929 
1930     void target() {
1931       $ns::$optional<Foo> opt;
1932       opt = Foo();
1933       opt.value();
1934     }
1935   )");
1936 
1937   ExpectDiagnosticsFor(R"(
1938     #include "unchecked_optional_access_test.h"
1939 
1940     struct Foo {};
1941 
1942     void target() {
1943       $ns::$optional<Foo> opt;
1944       (opt = Foo()).value();
1945       (void)0;
1946     }
1947   )");
1948 
1949   ExpectDiagnosticsFor(R"(
1950     #include "unchecked_optional_access_test.h"
1951 
1952     struct MyString {
1953       MyString(const char*);
1954     };
1955 
1956     void target() {
1957       $ns::$optional<MyString> opt;
1958       opt = "foo";
1959       opt.value();
1960     }
1961   )");
1962 
1963   ExpectDiagnosticsFor(R"(
1964     #include "unchecked_optional_access_test.h"
1965 
1966     struct MyString {
1967       MyString(const char*);
1968     };
1969 
1970     void target() {
1971       $ns::$optional<MyString> opt;
1972       (opt = "foo").value();
1973     }
1974   )");
1975 }
1976 
1977 TEST_P(UncheckedOptionalAccessTest, OptionalConversionAssignment) {
1978   ExpectDiagnosticsFor(
1979       R"(
1980     #include "unchecked_optional_access_test.h"
1981 
1982     struct Foo {};
1983 
1984     struct Bar {
1985       Bar(const Foo&);
1986     };
1987 
1988     void target() {
1989       $ns::$optional<Foo> opt1 = Foo();
1990       $ns::$optional<Bar> opt2;
1991       opt2 = opt1;
1992       opt2.value();
1993     }
1994   )");
1995 
1996   ExpectDiagnosticsFor(
1997       R"(
1998     #include "unchecked_optional_access_test.h"
1999 
2000     struct Foo {};
2001 
2002     struct Bar {
2003       Bar(const Foo&);
2004     };
2005 
2006     void target() {
2007       $ns::$optional<Foo> opt1;
2008       $ns::$optional<Bar> opt2;
2009       if (opt2.has_value()) {
2010         opt2 = opt1;
2011         opt2.value(); // [[unsafe]]
2012       }
2013     }
2014   )");
2015 
2016   ExpectDiagnosticsFor(
2017       R"(
2018     #include "unchecked_optional_access_test.h"
2019 
2020     struct Foo {};
2021 
2022     struct Bar {
2023       Bar(const Foo&);
2024     };
2025 
2026     void target() {
2027       $ns::$optional<Foo> opt1 = Foo();
2028       $ns::$optional<Bar> opt2;
2029       (opt2 = opt1).value();
2030       (void)0;
2031     }
2032   )");
2033 }
2034 
2035 TEST_P(UncheckedOptionalAccessTest, NulloptAssignment) {
2036   ExpectDiagnosticsFor(
2037       R"(
2038     #include "unchecked_optional_access_test.h"
2039 
2040     void target() {
2041       $ns::$optional<int> opt = 3;
2042       opt = $ns::nullopt;
2043       opt.value(); // [[unsafe]]
2044     }
2045   )");
2046 
2047   ExpectDiagnosticsFor(
2048       R"(
2049     #include "unchecked_optional_access_test.h"
2050 
2051     void target() {
2052       $ns::$optional<int> opt = 3;
2053       (opt = $ns::nullopt).value(); // [[unsafe]]
2054     }
2055   )");
2056 }
2057 
2058 TEST_P(UncheckedOptionalAccessTest, OptionalSwap) {
2059   ExpectDiagnosticsFor(
2060       R"(
2061     #include "unchecked_optional_access_test.h"
2062 
2063     void target() {
2064       $ns::$optional<int> opt1 = $ns::nullopt;
2065       $ns::$optional<int> opt2 = 3;
2066 
2067       opt1.swap(opt2);
2068 
2069       opt1.value();
2070 
2071       opt2.value(); // [[unsafe]]
2072     }
2073   )");
2074 
2075   ExpectDiagnosticsFor(
2076       R"(
2077     #include "unchecked_optional_access_test.h"
2078 
2079     void target() {
2080       $ns::$optional<int> opt1 = $ns::nullopt;
2081       $ns::$optional<int> opt2 = 3;
2082 
2083       opt2.swap(opt1);
2084 
2085       opt1.value();
2086 
2087       opt2.value(); // [[unsafe]]
2088     }
2089   )");
2090 }
2091 
2092 TEST_P(UncheckedOptionalAccessTest, StdSwap) {
2093   ExpectDiagnosticsFor(
2094       R"(
2095     #include "unchecked_optional_access_test.h"
2096 
2097     void target() {
2098       $ns::$optional<int> opt1 = $ns::nullopt;
2099       $ns::$optional<int> opt2 = 3;
2100 
2101       std::swap(opt1, opt2);
2102 
2103       opt1.value();
2104 
2105       opt2.value(); // [[unsafe]]
2106     }
2107   )");
2108 
2109   ExpectDiagnosticsFor(
2110       R"(
2111     #include "unchecked_optional_access_test.h"
2112 
2113     void target() {
2114       $ns::$optional<int> opt1 = $ns::nullopt;
2115       $ns::$optional<int> opt2 = 3;
2116 
2117       std::swap(opt2, opt1);
2118 
2119       opt1.value();
2120 
2121       opt2.value(); // [[unsafe]]
2122     }
2123   )");
2124 }
2125 
2126 TEST_P(UncheckedOptionalAccessTest, SwapUnmodeledLocLeft) {
2127   ExpectDiagnosticsFor(
2128       R"(
2129     #include "unchecked_optional_access_test.h"
2130 
2131     struct L { $ns::$optional<int> hd; L* tl; };
2132 
2133     void target() {
2134       $ns::$optional<int> foo = 3;
2135       L bar;
2136 
2137       // Any `tl` beyond the first is not modeled.
2138       bar.tl->tl->hd.swap(foo);
2139 
2140       bar.tl->tl->hd.value(); // [[unsafe]]
2141       foo.value(); // [[unsafe]]
2142     }
2143   )");
2144 }
2145 
2146 TEST_P(UncheckedOptionalAccessTest, SwapUnmodeledLocRight) {
2147   ExpectDiagnosticsFor(
2148       R"(
2149     #include "unchecked_optional_access_test.h"
2150 
2151     struct L { $ns::$optional<int> hd; L* tl; };
2152 
2153     void target() {
2154       $ns::$optional<int> foo = 3;
2155       L bar;
2156 
2157       // Any `tl` beyond the first is not modeled.
2158       foo.swap(bar.tl->tl->hd);
2159 
2160       bar.tl->tl->hd.value(); // [[unsafe]]
2161       foo.value(); // [[unsafe]]
2162     }
2163   )");
2164 }
2165 
2166 TEST_P(UncheckedOptionalAccessTest, SwapUnmodeledValueLeftSet) {
2167   ExpectDiagnosticsFor(
2168       R"(
2169     #include "unchecked_optional_access_test.h"
2170 
2171     struct S { int x; };
2172     struct A { $ns::$optional<S> late; };
2173     struct B { A f3; };
2174     struct C { B f2; };
2175     struct D { C f1; };
2176 
2177     void target() {
2178       $ns::$optional<S> foo = S{3};
2179       D bar;
2180 
2181       bar.f1.f2.f3.late.swap(foo);
2182 
2183       bar.f1.f2.f3.late.value();
2184       foo.value(); // [[unsafe]]
2185     }
2186   )");
2187 }
2188 
2189 TEST_P(UncheckedOptionalAccessTest, SwapUnmodeledValueLeftUnset) {
2190   ExpectDiagnosticsFor(
2191       R"(
2192     #include "unchecked_optional_access_test.h"
2193 
2194     struct S { int x; };
2195     struct A { $ns::$optional<S> late; };
2196     struct B { A f3; };
2197     struct C { B f2; };
2198     struct D { C f1; };
2199 
2200     void target() {
2201       $ns::$optional<S> foo;
2202       D bar;
2203 
2204       bar.f1.f2.f3.late.swap(foo);
2205 
2206       bar.f1.f2.f3.late.value(); // [[unsafe]]
2207       foo.value(); // [[unsafe]]
2208     }
2209   )");
2210 }
2211 
2212 // fixme: use recursion instead of depth.
2213 TEST_P(UncheckedOptionalAccessTest, SwapUnmodeledValueRightSet) {
2214   ExpectDiagnosticsFor(
2215       R"(
2216     #include "unchecked_optional_access_test.h"
2217 
2218     struct S { int x; };
2219     struct A { $ns::$optional<S> late; };
2220     struct B { A f3; };
2221     struct C { B f2; };
2222     struct D { C f1; };
2223 
2224     void target() {
2225       $ns::$optional<S> foo = S{3};
2226       D bar;
2227 
2228       foo.swap(bar.f1.f2.f3.late);
2229 
2230       bar.f1.f2.f3.late.value();
2231       foo.value(); // [[unsafe]]
2232     }
2233   )");
2234 }
2235 
2236 TEST_P(UncheckedOptionalAccessTest, SwapUnmodeledValueRightUnset) {
2237   ExpectDiagnosticsFor(
2238       R"(
2239     #include "unchecked_optional_access_test.h"
2240 
2241     struct S { int x; };
2242     struct A { $ns::$optional<S> late; };
2243     struct B { A f3; };
2244     struct C { B f2; };
2245     struct D { C f1; };
2246 
2247     void target() {
2248       $ns::$optional<S> foo;
2249       D bar;
2250 
2251       foo.swap(bar.f1.f2.f3.late);
2252 
2253       bar.f1.f2.f3.late.value(); // [[unsafe]]
2254       foo.value(); // [[unsafe]]
2255     }
2256   )");
2257 }
2258 
2259 TEST_P(UncheckedOptionalAccessTest, UniquePtrToOptional) {
2260   // We suppress diagnostics for optionals in smart pointers (other than
2261   // `optional` itself).
2262   ExpectDiagnosticsFor(
2263       R"(
2264     #include "unchecked_optional_access_test.h"
2265 
2266     template <typename T>
2267     struct smart_ptr {
2268       T& operator*() &;
2269       T* operator->();
2270     };
2271 
2272     void target() {
2273       smart_ptr<$ns::$optional<bool>> foo;
2274       foo->value();
2275       (*foo).value();
2276     }
2277   )");
2278 }
2279 
2280 TEST_P(UncheckedOptionalAccessTest, UniquePtrToStructWithOptionalField) {
2281   // We suppress diagnostics for optional fields reachable from smart pointers
2282   // (other than `optional` itself) through (exactly) one member access.
2283   ExpectDiagnosticsFor(
2284       R"(
2285     #include "unchecked_optional_access_test.h"
2286 
2287     template <typename T>
2288     struct smart_ptr {
2289       T& operator*() &;
2290       T* operator->();
2291     };
2292 
2293     struct Foo {
2294       $ns::$optional<int> opt;
2295     };
2296 
2297     void target() {
2298       smart_ptr<Foo> foo;
2299       *foo->opt;
2300       *(*foo).opt;
2301     }
2302   )");
2303 }
2304 
2305 TEST_P(UncheckedOptionalAccessTest, CallReturningOptional) {
2306   ExpectDiagnosticsFor(
2307       R"(
2308     #include "unchecked_optional_access_test.h"
2309 
2310     $ns::$optional<int> MakeOpt();
2311 
2312     void target() {
2313       $ns::$optional<int> opt = 0;
2314       opt = MakeOpt();
2315       opt.value(); // [[unsafe]]
2316     }
2317   )");
2318   ExpectDiagnosticsFor(
2319       R"(
2320     #include "unchecked_optional_access_test.h"
2321 
2322     const $ns::$optional<int>& MakeOpt();
2323 
2324     void target() {
2325       $ns::$optional<int> opt = 0;
2326       opt = MakeOpt();
2327       opt.value(); // [[unsafe]]
2328     }
2329   )");
2330 
2331   ExpectDiagnosticsFor(
2332       R"(
2333     #include "unchecked_optional_access_test.h"
2334 
2335     using IntOpt = $ns::$optional<int>;
2336     IntOpt MakeOpt();
2337 
2338     void target() {
2339       IntOpt opt = 0;
2340       opt = MakeOpt();
2341       opt.value(); // [[unsafe]]
2342     }
2343   )");
2344 
2345   ExpectDiagnosticsFor(
2346       R"(
2347     #include "unchecked_optional_access_test.h"
2348 
2349     using IntOpt = $ns::$optional<int>;
2350     const IntOpt& MakeOpt();
2351 
2352     void target() {
2353       IntOpt opt = 0;
2354       opt = MakeOpt();
2355       opt.value(); // [[unsafe]]
2356     }
2357   )");
2358 }
2359 
2360 
2361 TEST_P(UncheckedOptionalAccessTest, EqualityCheckLeftSet) {
2362   ExpectDiagnosticsFor(
2363       R"(
2364     #include "unchecked_optional_access_test.h"
2365 
2366     void target() {
2367       $ns::$optional<int> opt1 = 3;
2368       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2369 
2370       if (opt1 == opt2) {
2371         opt2.value();
2372       } else {
2373         opt2.value(); // [[unsafe]]
2374       }
2375     }
2376   )");
2377 }
2378 
2379 TEST_P(UncheckedOptionalAccessTest, EqualityCheckRightSet) {
2380   ExpectDiagnosticsFor(
2381       R"(
2382     #include "unchecked_optional_access_test.h"
2383 
2384     void target() {
2385       $ns::$optional<int> opt1 = 3;
2386       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2387 
2388       if (opt2 == opt1) {
2389         opt2.value();
2390       } else {
2391         opt2.value(); // [[unsafe]]
2392       }
2393     }
2394   )");
2395 }
2396 
2397 TEST_P(UncheckedOptionalAccessTest, EqualityCheckVerifySetAfterEq) {
2398   ExpectDiagnosticsFor(
2399       R"(
2400     #include "unchecked_optional_access_test.h"
2401 
2402     void target() {
2403       $ns::$optional<int> opt1 = Make<$ns::$optional<int>>();
2404       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2405 
2406       if (opt1 == opt2) {
2407         if (opt1.has_value())
2408           opt2.value();
2409         if (opt2.has_value())
2410           opt1.value();
2411       }
2412     }
2413   )");
2414 }
2415 
2416 TEST_P(UncheckedOptionalAccessTest, EqualityCheckLeftUnset) {
2417   ExpectDiagnosticsFor(
2418       R"(
2419     #include "unchecked_optional_access_test.h"
2420 
2421     void target() {
2422       $ns::$optional<int> opt1 = $ns::nullopt;
2423       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2424 
2425       if (opt1 == opt2) {
2426         opt2.value(); // [[unsafe]]
2427       } else {
2428         opt2.value();
2429       }
2430     }
2431   )");
2432 }
2433 
2434 TEST_P(UncheckedOptionalAccessTest, EqualityCheckRightUnset) {
2435   ExpectDiagnosticsFor(
2436       R"(
2437     #include "unchecked_optional_access_test.h"
2438 
2439     void target() {
2440       $ns::$optional<int> opt1 = $ns::nullopt;
2441       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2442 
2443       if (opt2 == opt1) {
2444         opt2.value(); // [[unsafe]]
2445       } else {
2446         opt2.value();
2447       }
2448     }
2449   )");
2450 }
2451 
2452 TEST_P(UncheckedOptionalAccessTest, EqualityCheckRightNullopt) {
2453   ExpectDiagnosticsFor(
2454       R"(
2455     #include "unchecked_optional_access_test.h"
2456 
2457     void target() {
2458       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2459 
2460       if (opt == $ns::nullopt) {
2461         opt.value(); // [[unsafe]]
2462       } else {
2463         opt.value();
2464       }
2465     }
2466   )");
2467 }
2468 
2469 TEST_P(UncheckedOptionalAccessTest, EqualityCheckLeftNullopt) {
2470   ExpectDiagnosticsFor(
2471       R"(
2472     #include "unchecked_optional_access_test.h"
2473 
2474     void target() {
2475       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2476 
2477       if ($ns::nullopt == opt) {
2478         opt.value(); // [[unsafe]]
2479       } else {
2480         opt.value();
2481       }
2482     }
2483   )");
2484 }
2485 
2486 TEST_P(UncheckedOptionalAccessTest, EqualityCheckRightValue) {
2487   ExpectDiagnosticsFor(
2488       R"(
2489     #include "unchecked_optional_access_test.h"
2490 
2491     void target() {
2492       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2493 
2494       if (opt == 3) {
2495         opt.value();
2496       } else {
2497         opt.value(); // [[unsafe]]
2498       }
2499     }
2500   )");
2501 }
2502 
2503 TEST_P(UncheckedOptionalAccessTest, EqualityCheckLeftValue) {
2504   ExpectDiagnosticsFor(
2505       R"(
2506     #include "unchecked_optional_access_test.h"
2507 
2508     void target() {
2509       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2510 
2511       if (3 == opt) {
2512         opt.value();
2513       } else {
2514         opt.value(); // [[unsafe]]
2515       }
2516     }
2517   )");
2518 }
2519 
2520 TEST_P(UncheckedOptionalAccessTest, InequalityCheckLeftSet) {
2521   ExpectDiagnosticsFor(
2522       R"(
2523     #include "unchecked_optional_access_test.h"
2524 
2525     void target() {
2526       $ns::$optional<int> opt1 = 3;
2527       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2528 
2529       if (opt1 != opt2) {
2530         opt2.value(); // [[unsafe]]
2531       } else {
2532         opt2.value();
2533       }
2534     }
2535   )");
2536 }
2537 
2538 TEST_P(UncheckedOptionalAccessTest, InequalityCheckRightSet) {
2539   ExpectDiagnosticsFor(
2540       R"(
2541     #include "unchecked_optional_access_test.h"
2542 
2543     void target() {
2544       $ns::$optional<int> opt1 = 3;
2545       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2546 
2547       if (opt2 != opt1) {
2548         opt2.value(); // [[unsafe]]
2549       } else {
2550         opt2.value();
2551       }
2552     }
2553   )");
2554 }
2555 
2556 TEST_P(UncheckedOptionalAccessTest, InequalityCheckVerifySetAfterEq) {
2557   ExpectDiagnosticsFor(
2558       R"(
2559     #include "unchecked_optional_access_test.h"
2560 
2561     void target() {
2562       $ns::$optional<int> opt1 = Make<$ns::$optional<int>>();
2563       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2564 
2565       if (opt1 != opt2) {
2566         if (opt1.has_value())
2567           opt2.value(); // [[unsafe]]
2568         if (opt2.has_value())
2569           opt1.value(); // [[unsafe]]
2570       }
2571     }
2572   )");
2573 }
2574 
2575 TEST_P(UncheckedOptionalAccessTest, InequalityCheckLeftUnset) {
2576   ExpectDiagnosticsFor(
2577       R"(
2578     #include "unchecked_optional_access_test.h"
2579 
2580     void target() {
2581       $ns::$optional<int> opt1 = $ns::nullopt;
2582       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2583 
2584       if (opt1 != opt2) {
2585         opt2.value();
2586       } else {
2587         opt2.value(); // [[unsafe]]
2588       }
2589     }
2590   )");
2591 }
2592 
2593 TEST_P(UncheckedOptionalAccessTest, InequalityCheckRightUnset) {
2594   ExpectDiagnosticsFor(
2595       R"(
2596     #include "unchecked_optional_access_test.h"
2597 
2598     void target() {
2599       $ns::$optional<int> opt1 = $ns::nullopt;
2600       $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2601 
2602       if (opt2 != opt1) {
2603         opt2.value();
2604       } else {
2605         opt2.value(); // [[unsafe]]
2606       }
2607     }
2608   )");
2609 }
2610 
2611 TEST_P(UncheckedOptionalAccessTest, InequalityCheckRightNullopt) {
2612   ExpectDiagnosticsFor(
2613       R"(
2614     #include "unchecked_optional_access_test.h"
2615 
2616     void target() {
2617       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2618 
2619       if (opt != $ns::nullopt) {
2620         opt.value();
2621       } else {
2622         opt.value(); // [[unsafe]]
2623       }
2624     }
2625   )");
2626 }
2627 
2628 TEST_P(UncheckedOptionalAccessTest, InequalityCheckLeftNullopt) {
2629   ExpectDiagnosticsFor(
2630       R"(
2631     #include "unchecked_optional_access_test.h"
2632 
2633     void target() {
2634       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2635 
2636       if ($ns::nullopt != opt) {
2637         opt.value();
2638       } else {
2639         opt.value(); // [[unsafe]]
2640       }
2641     }
2642   )");
2643 }
2644 
2645 TEST_P(UncheckedOptionalAccessTest, InequalityCheckRightValue) {
2646   ExpectDiagnosticsFor(
2647       R"(
2648     #include "unchecked_optional_access_test.h"
2649 
2650     void target() {
2651       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2652 
2653       if (opt != 3) {
2654         opt.value(); // [[unsafe]]
2655       } else {
2656         opt.value();
2657       }
2658     }
2659   )");
2660 }
2661 
2662 TEST_P(UncheckedOptionalAccessTest, InequalityCheckLeftValue) {
2663   ExpectDiagnosticsFor(
2664       R"(
2665     #include "unchecked_optional_access_test.h"
2666 
2667     void target() {
2668       $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2669 
2670       if (3 != opt) {
2671         opt.value(); // [[unsafe]]
2672       } else {
2673         opt.value();
2674       }
2675     }
2676   )");
2677 }
2678 
2679 // Verifies that the model sees through aliases.
2680 TEST_P(UncheckedOptionalAccessTest, WithAlias) {
2681   ExpectDiagnosticsFor(
2682       R"(
2683     #include "unchecked_optional_access_test.h"
2684 
2685     template <typename T>
2686     using MyOptional = $ns::$optional<T>;
2687 
2688     void target(MyOptional<int> opt) {
2689       opt.value(); // [[unsafe]]
2690     }
2691   )");
2692 }
2693 
2694 TEST_P(UncheckedOptionalAccessTest, OptionalValueOptional) {
2695   // Basic test that nested values are populated.  We nest an optional because
2696   // its easy to use in a test, but the type of the nested value shouldn't
2697   // matter.
2698   ExpectDiagnosticsFor(
2699       R"(
2700     #include "unchecked_optional_access_test.h"
2701 
2702     using Foo = $ns::$optional<std::string>;
2703 
2704     void target($ns::$optional<Foo> foo) {
2705       if (foo && *foo) {
2706         foo->value();
2707       }
2708     }
2709   )");
2710 
2711   // Mutation is supported for nested values.
2712   ExpectDiagnosticsFor(
2713       R"(
2714     #include "unchecked_optional_access_test.h"
2715 
2716     using Foo = $ns::$optional<std::string>;
2717 
2718     void target($ns::$optional<Foo> foo) {
2719       if (foo && *foo) {
2720         foo->reset();
2721         foo->value(); // [[unsafe]]
2722       }
2723     }
2724   )");
2725 }
2726 
2727 // Tests that structs can be nested. We use an optional field because its easy
2728 // to use in a test, but the type of the field shouldn't matter.
2729 TEST_P(UncheckedOptionalAccessTest, OptionalValueStruct) {
2730   ExpectDiagnosticsFor(
2731       R"(
2732     #include "unchecked_optional_access_test.h"
2733 
2734     struct Foo {
2735       $ns::$optional<std::string> opt;
2736     };
2737 
2738     void target($ns::$optional<Foo> foo) {
2739       if (foo && foo->opt) {
2740         foo->opt.value();
2741       }
2742     }
2743   )");
2744 }
2745 
2746 TEST_P(UncheckedOptionalAccessTest, OptionalValueInitialization) {
2747   // FIXME: Fix when to initialize `value`. All unwrapping should be safe in
2748   // this example, but `value` initialization is done multiple times during the
2749   // fixpoint iterations and joining the environment won't correctly merge them.
2750   ExpectDiagnosticsFor(
2751       R"(
2752     #include "unchecked_optional_access_test.h"
2753 
2754     using Foo = $ns::$optional<std::string>;
2755 
2756     void target($ns::$optional<Foo> foo, bool b) {
2757       if (!foo.has_value()) return;
2758       if (b) {
2759         if (!foo->has_value()) return;
2760         // We have created `foo.value()`.
2761         foo->value();
2762       } else {
2763         if (!foo->has_value()) return;
2764         // We have created `foo.value()` again, in a different environment.
2765         foo->value();
2766       }
2767       // Now we merge the two values. UncheckedOptionalAccessModel::merge() will
2768       // throw away the "value" property.
2769       foo->value(); // [[unsafe]]
2770     }
2771   )");
2772 }
2773 
2774 // This test is aimed at the core model, not the diagnostic. It is a regression
2775 // test against a crash when using non-trivial smart pointers, like
2776 // `std::unique_ptr`. As such, it doesn't test the access itself, which would be
2777 // ignored regardless because of `IgnoreSmartPointerDereference = true`, above.
2778 TEST_P(UncheckedOptionalAccessTest, AssignThroughLvalueReferencePtr) {
2779   ExpectDiagnosticsFor(
2780       R"(
2781     #include "unchecked_optional_access_test.h"
2782 
2783     template <typename T>
2784     struct smart_ptr {
2785       typename std::add_lvalue_reference<T>::type operator*() &;
2786     };
2787 
2788     void target() {
2789       smart_ptr<$ns::$optional<int>> x;
2790       // Verify that this assignment does not crash.
2791       *x = 3;
2792     }
2793   )");
2794 }
2795 
2796 TEST_P(UncheckedOptionalAccessTest, CorrelatedBranches) {
2797   ExpectDiagnosticsFor(R"code(
2798     #include "unchecked_optional_access_test.h"
2799 
2800     void target(bool b, $ns::$optional<int> opt) {
2801       if (b || opt.has_value()) {
2802         if (!b) {
2803           opt.value();
2804         }
2805       }
2806     }
2807   )code");
2808 
2809   ExpectDiagnosticsFor(R"code(
2810     #include "unchecked_optional_access_test.h"
2811 
2812     void target(bool b, $ns::$optional<int> opt) {
2813       if (b && !opt.has_value()) return;
2814       if (b) {
2815         opt.value();
2816       }
2817     }
2818   )code");
2819 
2820   ExpectDiagnosticsFor(
2821       R"code(
2822     #include "unchecked_optional_access_test.h"
2823 
2824     void target(bool b, $ns::$optional<int> opt) {
2825       if (opt.has_value()) b = true;
2826       if (b) {
2827         opt.value(); // [[unsafe]]
2828       }
2829     }
2830   )code");
2831 
2832   ExpectDiagnosticsFor(R"code(
2833     #include "unchecked_optional_access_test.h"
2834 
2835     void target(bool b, $ns::$optional<int> opt) {
2836       if (b) return;
2837       if (opt.has_value()) b = true;
2838       if (b) {
2839         opt.value();
2840       }
2841     }
2842   )code");
2843 
2844   ExpectDiagnosticsFor(R"(
2845     #include "unchecked_optional_access_test.h"
2846 
2847     void target(bool b, $ns::$optional<int> opt) {
2848       if (opt.has_value() == b) {
2849         if (b) {
2850           opt.value();
2851         }
2852       }
2853     }
2854   )");
2855 
2856   ExpectDiagnosticsFor(R"(
2857     #include "unchecked_optional_access_test.h"
2858 
2859     void target(bool b, $ns::$optional<int> opt) {
2860       if (opt.has_value() != b) {
2861         if (!b) {
2862           opt.value();
2863         }
2864       }
2865     }
2866   )");
2867 
2868   ExpectDiagnosticsFor(R"(
2869     #include "unchecked_optional_access_test.h"
2870 
2871     void target(bool b) {
2872       $ns::$optional<int> opt1 = $ns::nullopt;
2873       $ns::$optional<int> opt2;
2874       if (b) {
2875         opt2 = $ns::nullopt;
2876       } else {
2877         opt2 = $ns::nullopt;
2878       }
2879       if (opt2.has_value()) {
2880         opt1.value();
2881       }
2882     }
2883   )");
2884 }
2885 
2886 TEST_P(UncheckedOptionalAccessTest, JoinDistinctValues) {
2887   ExpectDiagnosticsFor(
2888       R"code(
2889     #include "unchecked_optional_access_test.h"
2890 
2891     void target(bool b) {
2892       $ns::$optional<int> opt;
2893       if (b) {
2894         opt = Make<$ns::$optional<int>>();
2895       } else {
2896         opt = Make<$ns::$optional<int>>();
2897       }
2898       if (opt.has_value()) {
2899         opt.value();
2900       } else {
2901         opt.value(); // [[unsafe]]
2902       }
2903     }
2904   )code");
2905 
2906   ExpectDiagnosticsFor(R"code(
2907     #include "unchecked_optional_access_test.h"
2908 
2909     void target(bool b) {
2910       $ns::$optional<int> opt;
2911       if (b) {
2912         opt = Make<$ns::$optional<int>>();
2913         if (!opt.has_value()) return;
2914       } else {
2915         opt = Make<$ns::$optional<int>>();
2916         if (!opt.has_value()) return;
2917       }
2918       opt.value();
2919     }
2920   )code");
2921 
2922   ExpectDiagnosticsFor(
2923       R"code(
2924     #include "unchecked_optional_access_test.h"
2925 
2926     void target(bool b) {
2927       $ns::$optional<int> opt;
2928       if (b) {
2929         opt = Make<$ns::$optional<int>>();
2930         if (!opt.has_value()) return;
2931       } else {
2932         opt = Make<$ns::$optional<int>>();
2933       }
2934       opt.value(); // [[unsafe]]
2935     }
2936   )code");
2937 
2938   ExpectDiagnosticsFor(
2939       R"code(
2940     #include "unchecked_optional_access_test.h"
2941 
2942     void target(bool b) {
2943       $ns::$optional<int> opt;
2944       if (b) {
2945         opt = 1;
2946       } else {
2947         opt = 2;
2948       }
2949       opt.value();
2950     }
2951   )code");
2952 
2953   ExpectDiagnosticsFor(
2954       R"code(
2955     #include "unchecked_optional_access_test.h"
2956 
2957     void target(bool b) {
2958       $ns::$optional<int> opt;
2959       if (b) {
2960         opt = 1;
2961       } else {
2962         opt = Make<$ns::$optional<int>>();
2963       }
2964       opt.value(); // [[unsafe]]
2965     }
2966   )code");
2967 }
2968 
2969 TEST_P(UncheckedOptionalAccessTest, AccessValueInLoop) {
2970   ExpectDiagnosticsFor(R"(
2971     #include "unchecked_optional_access_test.h"
2972 
2973     void target() {
2974       $ns::$optional<int> opt = 3;
2975       while (Make<bool>()) {
2976         opt.value();
2977       }
2978     }
2979   )");
2980 }
2981 
2982 TEST_P(UncheckedOptionalAccessTest, ReassignValueInLoopWithCheckSafe) {
2983   ExpectDiagnosticsFor(R"(
2984     #include "unchecked_optional_access_test.h"
2985 
2986     void target() {
2987       $ns::$optional<int> opt = 3;
2988       while (Make<bool>()) {
2989         opt.value();
2990 
2991         opt = Make<$ns::$optional<int>>();
2992         if (!opt.has_value()) return;
2993       }
2994     }
2995   )");
2996 }
2997 
2998 TEST_P(UncheckedOptionalAccessTest, ReassignValueInLoopNoCheckUnsafe) {
2999   ExpectDiagnosticsFor(
3000       R"(
3001     #include "unchecked_optional_access_test.h"
3002 
3003     void target() {
3004       $ns::$optional<int> opt = 3;
3005       while (Make<bool>()) {
3006         opt.value(); // [[unsafe]]
3007 
3008         opt = Make<$ns::$optional<int>>();
3009       }
3010     }
3011   )");
3012 }
3013 
3014 TEST_P(UncheckedOptionalAccessTest, ReassignValueInLoopToUnsetUnsafe) {
3015   ExpectDiagnosticsFor(
3016       R"(
3017     #include "unchecked_optional_access_test.h"
3018 
3019     void target() {
3020       $ns::$optional<int> opt = 3;
3021       while (Make<bool>())
3022         opt = $ns::nullopt;
3023       $ns::$optional<int> opt2 = $ns::nullopt;
3024       if (opt.has_value())
3025         opt2 = $ns::$optional<int>(3);
3026       opt2.value(); // [[unsafe]]
3027     }
3028   )");
3029 }
3030 
3031 TEST_P(UncheckedOptionalAccessTest, ReassignValueInLoopToSetUnsafe) {
3032   ExpectDiagnosticsFor(
3033       R"(
3034     #include "unchecked_optional_access_test.h"
3035 
3036     void target() {
3037       $ns::$optional<int> opt = $ns::nullopt;
3038       while (Make<bool>())
3039         opt = $ns::$optional<int>(3);
3040       $ns::$optional<int> opt2 = $ns::nullopt;
3041       if (!opt.has_value())
3042         opt2 = $ns::$optional<int>(3);
3043       opt2.value(); // [[unsafe]]
3044     }
3045   )");
3046 }
3047 
3048 TEST_P(UncheckedOptionalAccessTest, ReassignValueInLoopToUnknownUnsafe) {
3049   ExpectDiagnosticsFor(
3050       R"(
3051     #include "unchecked_optional_access_test.h"
3052 
3053     void target() {
3054       $ns::$optional<int> opt = $ns::nullopt;
3055       while (Make<bool>())
3056         opt = Make<$ns::$optional<int>>();
3057       $ns::$optional<int> opt2 = $ns::nullopt;
3058       if (!opt.has_value())
3059         opt2 = $ns::$optional<int>(3);
3060       opt2.value(); // [[unsafe]]
3061     }
3062   )");
3063 }
3064 
3065 TEST_P(UncheckedOptionalAccessTest, ReassignValueInLoopBadConditionUnsafe) {
3066   ExpectDiagnosticsFor(
3067       R"(
3068     #include "unchecked_optional_access_test.h"
3069 
3070     void target() {
3071       $ns::$optional<int> opt = 3;
3072       while (Make<bool>()) {
3073         opt.value(); // [[unsafe]]
3074 
3075         opt = Make<$ns::$optional<int>>();
3076         if (!opt.has_value()) continue;
3077       }
3078     }
3079   )");
3080 }
3081 
3082 TEST_P(UncheckedOptionalAccessTest, StructuredBindingsFromStruct) {
3083   ExpectDiagnosticsFor(R"(
3084     #include "unchecked_optional_access_test.h"
3085 
3086     struct kv { $ns::$optional<int> opt; int x; };
3087     int target() {
3088       auto [contents, x] = Make<kv>();
3089       return contents ? *contents : x;
3090     }
3091   )");
3092 
3093   ExpectDiagnosticsFor(R"(
3094     #include "unchecked_optional_access_test.h"
3095 
3096     template <typename T1, typename T2>
3097     struct pair { T1 fst;  T2 snd; };
3098     int target() {
3099       auto [contents, x] = Make<pair<$ns::$optional<int>, int>>();
3100       return contents ? *contents : x;
3101     }
3102   )");
3103 }
3104 
3105 TEST_P(UncheckedOptionalAccessTest, StructuredBindingsFromTupleLikeType) {
3106   ExpectDiagnosticsFor(R"(
3107     #include "unchecked_optional_access_test.h"
3108 
3109     namespace std {
3110     template <class> struct tuple_size;
3111     template <size_t, class> struct tuple_element;
3112     template <class...> class tuple;
3113 
3114     template <class... T>
3115     struct tuple_size<tuple<T...>> : integral_constant<size_t, sizeof...(T)> {};
3116 
3117     template <size_t I, class... T>
3118     struct tuple_element<I, tuple<T...>> {
3119       using type =  __type_pack_element<I, T...>;
3120     };
3121 
3122     template <class...> class tuple {};
3123     template <size_t I, class... T>
3124     typename tuple_element<I, tuple<T...>>::type get(tuple<T...>);
3125     } // namespace std
3126 
3127     std::tuple<$ns::$optional<const char *>, int> get_opt();
3128     void target() {
3129       auto [content, ck] = get_opt();
3130       content ? *content : "";
3131     }
3132   )");
3133 }
3134 
3135 TEST_P(UncheckedOptionalAccessTest, CtorInitializerNullopt) {
3136   using namespace ast_matchers;
3137   ExpectDiagnosticsFor(
3138       R"(
3139     #include "unchecked_optional_access_test.h"
3140 
3141     struct Target {
3142       Target(): opt($ns::nullopt) {
3143         opt.value(); // [[unsafe]]
3144       }
3145       $ns::$optional<int> opt;
3146     };
3147   )",
3148       cxxConstructorDecl(ofClass(hasName("Target"))));
3149 }
3150 
3151 TEST_P(UncheckedOptionalAccessTest, CtorInitializerValue) {
3152   using namespace ast_matchers;
3153   ExpectDiagnosticsFor(
3154       R"(
3155     #include "unchecked_optional_access_test.h"
3156 
3157     struct Target {
3158       Target(): opt(3) {
3159         opt.value();
3160       }
3161       $ns::$optional<int> opt;
3162     };
3163   )",
3164       cxxConstructorDecl(ofClass(hasName("Target"))));
3165 }
3166 
3167 // This is regression test, it shouldn't crash.
3168 TEST_P(UncheckedOptionalAccessTest, Bitfield) {
3169   using namespace ast_matchers;
3170   ExpectDiagnosticsFor(
3171       R"(
3172     #include "unchecked_optional_access_test.h"
3173     struct Dst {
3174       unsigned int n : 1;
3175     };
3176     void target() {
3177       $ns::$optional<bool> v;
3178       Dst d;
3179       if (v.has_value())
3180         d.n = v.value();
3181     }
3182   )");
3183 }
3184 // FIXME: Add support for:
3185 // - constructors (copy, move)
3186 // - assignment operators (default, copy, move)
3187 // - invalidation (passing optional by non-const reference/pointer)
3188