1 //===- UncheckedOptionalAccessModelTest.cpp -------------------------------===//
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
7 //===----------------------------------------------------------------------===//
8 // FIXME: Move this to clang/unittests/Analysis/FlowSensitive/Models.
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/Frontend/TextDiagnostic.h"
16 #include "clang/Tooling/Tooling.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/Support/Error.h"
20 #include "gmock/gmock.h"
21 #include "gtest/gtest.h"
27 using namespace clang
;
28 using namespace dataflow
;
31 using ::testing::ContainerEq
;
33 // FIXME: Move header definitions in separate file(s).
34 static constexpr char CSDtdDefHeader
[] = R
"(
40 typedef decltype(sizeof(char)) size_t;
42 using nullptr_t = decltype(nullptr);
49 static constexpr char StdTypeTraitsHeader
[] = R
"(
50 #ifndef STD_TYPE_TRAITS_H
51 #define STD_TYPE_TRAITS_H
57 template <typename T, T V>
58 struct integral_constant {
59 static constexpr T value = V;
62 using true_type = integral_constant<bool, true>;
63 using false_type = integral_constant<bool, false>;
65 template< class T > struct remove_reference {typedef T type;};
66 template< class T > struct remove_reference<T&> {typedef T type;};
67 template< class T > struct remove_reference<T&&> {typedef T type;};
70 using remove_reference_t = typename remove_reference<T>::type;
73 struct remove_extent {
78 struct remove_extent<T[]> {
82 template <class T, size_t N>
83 struct remove_extent<T[N]> {
88 struct is_array : false_type {};
91 struct is_array<T[]> : true_type {};
93 template <class T, size_t N>
94 struct is_array<T[N]> : true_type {};
97 struct is_function : false_type {};
99 template <class Ret, class... Args>
100 struct is_function<Ret(Args...)> : true_type {};
105 struct type_identity {
107 }; // or use type_identity (since C++20)
110 auto try_add_pointer(int) -> type_identity<typename remove_reference<T>::type*>;
112 auto try_add_pointer(...) -> type_identity<T>;
114 } // namespace detail
117 struct add_pointer : decltype(detail::try_add_pointer<T>(0)) {};
119 template <bool B, class T, class F>
124 template <class T, class F>
125 struct conditional<false, T, F> {
134 struct remove_cv<const T> {
138 struct remove_cv<volatile T> {
142 struct remove_cv<const volatile T> {
147 using remove_cv_t = typename remove_cv<T>::type;
152 typedef typename remove_reference<T>::type U;
155 typedef typename conditional<
156 is_array<U>::value, typename remove_extent<U>::type*,
157 typename conditional<is_function<U>::value, typename add_pointer<U>::type,
158 typename remove_cv<U>::type>::type>::type type;
161 template <bool B, class T = void>
165 struct enable_if<true, T> {
169 template <bool B, class T = void>
170 using enable_if_t = typename enable_if<B, T>::type;
172 template <class T, class U>
173 struct is_same : false_type {};
176 struct is_same<T, T> : true_type {};
179 struct is_void : is_same<void, typename remove_cv<T>::type> {};
184 auto try_add_lvalue_reference(int) -> type_identity<T&>;
186 auto try_add_lvalue_reference(...) -> type_identity<T>;
189 auto try_add_rvalue_reference(int) -> type_identity<T&&>;
191 auto try_add_rvalue_reference(...) -> type_identity<T>;
193 } // namespace detail
196 struct add_lvalue_reference : decltype(detail::try_add_lvalue_reference<T>(0)) {
200 struct add_rvalue_reference : decltype(detail::try_add_rvalue_reference<T>(0)) {
204 typename add_rvalue_reference<T>::type declval() noexcept;
209 auto test_returnable(int)
210 -> decltype(void(static_cast<T (*)()>(nullptr)), true_type{});
212 auto test_returnable(...) -> false_type;
214 template <class From, class To>
215 auto test_implicitly_convertible(int)
216 -> decltype(void(declval<void (&)(To)>()(declval<From>())), true_type{});
217 template <class, class>
218 auto test_implicitly_convertible(...) -> false_type;
220 } // namespace detail
222 template <class From, class To>
223 struct is_convertible
224 : integral_constant<bool,
225 (decltype(detail::test_returnable<To>(0))::value &&
226 decltype(detail::test_implicitly_convertible<From, To>(
228 (is_void<From>::value && is_void<To>::value)> {};
230 template <class From, class To>
231 inline constexpr bool is_convertible_v = is_convertible<From, To>::value;
236 template <class, class T, class... Args>
237 struct is_constructible_ : false_type {};
239 template <class T, class... Args>
240 struct is_constructible_<void_t<decltype(T(declval<Args>()...))>, T, Args...>
243 template <class T, class... Args>
244 using is_constructible = is_constructible_<void_t<>, T, Args...>;
246 template <class T, class... Args>
247 inline constexpr bool is_constructible_v = is_constructible<T, Args...>::value;
251 typedef typename remove_cv<typename remove_reference<_Tp>::type>::type type;
255 using __uncvref_t = typename __uncvref<_Tp>::type;
258 using _BoolConstant = integral_constant<bool, _Val>;
260 template <class _Tp, class _Up>
261 using _IsSame = _BoolConstant<__is_same(_Tp, _Up)>;
263 template <class _Tp, class _Up>
264 using _IsNotSame = _BoolConstant<!__is_same(_Tp, _Up)>;
269 struct _MetaBase<true> {
270 template <class _Tp, class _Up>
271 using _SelectImpl = _Tp;
272 template <template <class...> class _FirstFn, template <class...> class,
274 using _SelectApplyImpl = _FirstFn<_Args...>;
275 template <class _First, class...>
276 using _FirstImpl = _First;
277 template <class, class _Second, class...>
278 using _SecondImpl = _Second;
279 template <class _Result, class _First, class... _Rest>
281 typename _MetaBase<_First::value != true && sizeof...(_Rest) != 0>::
282 template _OrImpl<_First, _Rest...>;
286 struct _MetaBase<false> {
287 template <class _Tp, class _Up>
288 using _SelectImpl = _Up;
289 template <template <class...> class, template <class...> class _SecondFn,
291 using _SelectApplyImpl = _SecondFn<_Args...>;
292 template <class _Result, class...>
293 using _OrImpl = _Result;
296 template <bool _Cond, class _IfRes, class _ElseRes>
297 using _If = typename _MetaBase<_Cond>::template _SelectImpl<_IfRes, _ElseRes>;
299 template <class... _Rest>
300 using _Or = typename _MetaBase<sizeof...(_Rest) !=
301 0>::template _OrImpl<false_type, _Rest...>;
303 template <bool _Bp, class _Tp = void>
304 using __enable_if_t = typename enable_if<_Bp, _Tp>::type;
307 using __expand_to_true = true_type;
308 template <class... _Pred>
309 __expand_to_true<__enable_if_t<_Pred::value>...> __and_helper(int);
311 false_type __and_helper(...);
312 template <class... _Pred>
313 using _And = decltype(__and_helper<_Pred...>(0));
315 template <class _Pred>
316 struct _Not : _BoolConstant<!_Pred::value> {};
318 struct __check_tuple_constructor_fail {
319 static constexpr bool __enable_explicit_default() { return false; }
320 static constexpr bool __enable_implicit_default() { return false; }
322 static constexpr bool __enable_explicit() {
326 static constexpr bool __enable_implicit() {
331 template <typename, typename _Tp>
332 struct __select_2nd {
335 template <class _Tp, class _Arg>
336 typename __select_2nd<decltype((declval<_Tp>() = declval<_Arg>())),
338 __is_assignable_test(int);
339 template <class, class>
340 false_type __is_assignable_test(...);
341 template <class _Tp, class _Arg,
342 bool = is_void<_Tp>::value || is_void<_Arg>::value>
343 struct __is_assignable_imp
344 : public decltype((__is_assignable_test<_Tp, _Arg>(0))) {};
345 template <class _Tp, class _Arg>
346 struct __is_assignable_imp<_Tp, _Arg, true> : public false_type {};
347 template <class _Tp, class _Arg>
348 struct is_assignable : public __is_assignable_imp<_Tp, _Arg> {};
351 struct __libcpp_is_integral : public false_type {};
353 struct __libcpp_is_integral<bool> : public true_type {};
355 struct __libcpp_is_integral<char> : public true_type {};
357 struct __libcpp_is_integral<signed char> : public true_type {};
359 struct __libcpp_is_integral<unsigned char> : public true_type {};
361 struct __libcpp_is_integral<wchar_t> : public true_type {};
363 struct __libcpp_is_integral<short> : public true_type {}; // NOLINT
365 struct __libcpp_is_integral<unsigned short> : public true_type {}; // NOLINT
367 struct __libcpp_is_integral<int> : public true_type {};
369 struct __libcpp_is_integral<unsigned int> : public true_type {};
371 struct __libcpp_is_integral<long> : public true_type {}; // NOLINT
373 struct __libcpp_is_integral<unsigned long> : public true_type {}; // NOLINT
375 struct __libcpp_is_integral<long long> : public true_type {}; // NOLINT
376 template <> // NOLINTNEXTLINE
377 struct __libcpp_is_integral<unsigned long long> : public true_type {};
380 : public __libcpp_is_integral<typename remove_cv<_Tp>::type> {};
383 struct __libcpp_is_floating_point : public false_type {};
385 struct __libcpp_is_floating_point<float> : public true_type {};
387 struct __libcpp_is_floating_point<double> : public true_type {};
389 struct __libcpp_is_floating_point<long double> : public true_type {};
391 struct is_floating_point
392 : public __libcpp_is_floating_point<typename remove_cv<_Tp>::type> {};
396 : public integral_constant<bool, is_integral<_Tp>::value ||
397 is_floating_point<_Tp>::value> {};
400 struct __libcpp_is_pointer : public false_type {};
402 struct __libcpp_is_pointer<_Tp*> : public true_type {};
404 struct is_pointer : public __libcpp_is_pointer<typename remove_cv<_Tp>::type> {
408 struct __libcpp_is_member_pointer : public false_type {};
409 template <class _Tp, class _Up>
410 struct __libcpp_is_member_pointer<_Tp _Up::*> : public true_type {};
412 struct is_member_pointer
413 : public __libcpp_is_member_pointer<typename remove_cv<_Tp>::type> {};
416 struct __libcpp_union : public false_type {};
418 struct is_union : public __libcpp_union<typename remove_cv<_Tp>::type> {};
421 struct is_reference : false_type {};
423 struct is_reference<T&> : true_type {};
425 struct is_reference<T&&> : true_type {};
428 inline constexpr bool is_reference_v = is_reference<T>::value;
434 namespace __is_class_imp {
436 char __test(int _Tp::*);
439 } // namespace __is_class_imp
442 : public integral_constant<bool,
443 sizeof(__is_class_imp::__test<_Tp>(0)) == 1 &&
444 !is_union<_Tp>::value> {};
447 struct __is_nullptr_t_impl : public false_type {};
449 struct __is_nullptr_t_impl<nullptr_t> : public true_type {};
451 struct __is_nullptr_t
452 : public __is_nullptr_t_impl<typename remove_cv<_Tp>::type> {};
454 struct is_null_pointer
455 : public __is_nullptr_t_impl<typename remove_cv<_Tp>::type> {};
459 : public integral_constant<
460 bool, !is_void<_Tp>::value && !is_integral<_Tp>::value &&
461 !is_floating_point<_Tp>::value && !is_array<_Tp>::value &&
462 !is_pointer<_Tp>::value && !is_reference<_Tp>::value &&
463 !is_member_pointer<_Tp>::value && !is_union<_Tp>::value &&
464 !is_class<_Tp>::value && !is_function<_Tp>::value> {};
468 : public integral_constant<
469 bool, is_arithmetic<_Tp>::value || is_member_pointer<_Tp>::value ||
470 is_pointer<_Tp>::value || __is_nullptr_t<_Tp>::value ||
471 is_enum<_Tp>::value> {};
473 struct is_scalar<nullptr_t> : public true_type {};
477 #endif // STD_TYPE_TRAITS_H
480 static constexpr char AbslTypeTraitsHeader
[] = R
"(
481 #ifndef ABSL_TYPE_TRAITS_H
482 #define ABSL_TYPE_TRAITS_H
484 #include "std_type_traits
.h
"
488 template <typename... Ts>
489 struct conjunction : std::true_type {};
491 template <typename T, typename... Ts>
492 struct conjunction<T, Ts...>
493 : std::conditional<T::value, conjunction<Ts...>, T>::type {};
495 template <typename T>
496 struct conjunction<T> : T {};
498 template <typename T>
499 struct negation : std::integral_constant<bool, !T::value> {};
501 template <bool B, typename T = void>
502 using enable_if_t = typename std::enable_if<B, T>::type;
506 #endif // ABSL_TYPE_TRAITS_H
509 static constexpr char StdStringHeader
[] = R
"(
520 bool operator!=(const string &LHS, const char *RHS);
527 static constexpr char StdUtilityHeader
[] = R
"(
531 #include "std_type_traits
.h
"
535 template <typename T>
536 constexpr remove_reference_t<T>&& move(T&& x);
538 template <typename T>
539 void swap(T& a, T& b) noexcept;
546 static constexpr char StdInitializerListHeader
[] = R
"(
547 #ifndef INITIALIZER_LIST_H
548 #define INITIALIZER_LIST_H
552 template <typename T>
553 class initializer_list {
556 initializer_list() noexcept;
561 #endif // INITIALIZER_LIST_H
564 static constexpr char StdOptionalHeader
[] = R
"(
565 #include "std_initializer_list
.h
"
566 #include "std_type_traits
.h
"
567 #include "std_utility
.h
"
571 struct in_place_t {};
572 constexpr in_place_t in_place;
575 constexpr explicit nullopt_t() {}
577 constexpr nullopt_t nullopt;
580 struct __optional_destruct_base {
581 constexpr void reset() noexcept;
585 struct __optional_storage_base : __optional_destruct_base<_Tp> {
586 constexpr bool has_value() const noexcept;
589 template <typename _Tp>
590 class optional : private __optional_storage_base<_Tp> {
591 using __base = __optional_storage_base<_Tp>;
594 using value_type = _Tp;
597 struct _CheckOptionalArgsConstructor {
599 static constexpr bool __enable_implicit() {
600 return is_constructible_v<_Tp, _Up&&> && is_convertible_v<_Up&&, _Tp>;
604 static constexpr bool __enable_explicit() {
605 return is_constructible_v<_Tp, _Up&&> && !is_convertible_v<_Up&&, _Tp>;
609 using _CheckOptionalArgsCtor =
610 _If<_IsNotSame<__uncvref_t<_Up>, in_place_t>::value &&
611 _IsNotSame<__uncvref_t<_Up>, optional>::value,
612 _CheckOptionalArgsConstructor, __check_tuple_constructor_fail>;
613 template <class _QualUp>
614 struct _CheckOptionalLikeConstructor {
615 template <class _Up, class _Opt = optional<_Up>>
616 using __check_constructible_from_opt =
617 _Or<is_constructible<_Tp, _Opt&>, is_constructible<_Tp, _Opt const&>,
618 is_constructible<_Tp, _Opt&&>, is_constructible<_Tp, _Opt const&&>,
619 is_convertible<_Opt&, _Tp>, is_convertible<_Opt const&, _Tp>,
620 is_convertible<_Opt&&, _Tp>, is_convertible<_Opt const&&, _Tp>>;
621 template <class _Up, class _QUp = _QualUp>
622 static constexpr bool __enable_implicit() {
623 return is_convertible<_QUp, _Tp>::value &&
624 !__check_constructible_from_opt<_Up>::value;
626 template <class _Up, class _QUp = _QualUp>
627 static constexpr bool __enable_explicit() {
628 return !is_convertible<_QUp, _Tp>::value &&
629 !__check_constructible_from_opt<_Up>::value;
633 template <class _Up, class _QualUp>
634 using _CheckOptionalLikeCtor =
635 _If<_And<_IsNotSame<_Up, _Tp>, is_constructible<_Tp, _QualUp>>::value,
636 _CheckOptionalLikeConstructor<_QualUp>,
637 __check_tuple_constructor_fail>;
640 template <class _Up, class _QualUp>
641 using _CheckOptionalLikeAssign = _If<
643 _IsNotSame<_Up, _Tp>,
644 is_constructible<_Tp, _QualUp>,
645 is_assignable<_Tp&, _QualUp>
647 _CheckOptionalLikeConstructor<_QualUp>,
648 __check_tuple_constructor_fail
652 constexpr optional() noexcept {}
653 constexpr optional(const optional&) = default;
654 constexpr optional(optional&&) = default;
655 constexpr optional(nullopt_t) noexcept {}
658 class _InPlaceT, class... _Args,
659 class = enable_if_t<_And<_IsSame<_InPlaceT, in_place_t>,
660 is_constructible<value_type, _Args...>>::value>>
661 constexpr explicit optional(_InPlaceT, _Args&&... __args);
663 template <class _Up, class... _Args,
664 class = enable_if_t<is_constructible_v<
665 value_type, initializer_list<_Up>&, _Args...>>>
666 constexpr explicit optional(in_place_t, initializer_list<_Up> __il,
670 class _Up = value_type,
671 enable_if_t<_CheckOptionalArgsCtor<_Up>::template __enable_implicit<_Up>(),
673 constexpr optional(_Up&& __v);
677 enable_if_t<_CheckOptionalArgsCtor<_Up>::template __enable_explicit<_Up>(),
679 constexpr explicit optional(_Up&& __v);
681 template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up const&>::
682 template __enable_implicit<_Up>(),
684 constexpr optional(const optional<_Up>& __v);
686 template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up const&>::
687 template __enable_explicit<_Up>(),
689 constexpr explicit optional(const optional<_Up>& __v);
691 template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up&&>::
692 template __enable_implicit<_Up>(),
694 constexpr optional(optional<_Up>&& __v);
696 template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up&&>::
697 template __enable_explicit<_Up>(),
699 constexpr explicit optional(optional<_Up>&& __v);
701 constexpr optional& operator=(nullopt_t) noexcept;
703 optional& operator=(const optional&);
705 optional& operator=(optional&&);
707 template <class _Up = value_type,
708 class = enable_if_t<_And<_IsNotSame<__uncvref_t<_Up>, optional>,
709 _Or<_IsNotSame<__uncvref_t<_Up>, value_type>,
710 _Not<is_scalar<value_type>>>,
711 is_constructible<value_type, _Up>,
712 is_assignable<value_type&, _Up>>::value>>
713 constexpr optional& operator=(_Up&& __v);
715 template <class _Up, enable_if_t<_CheckOptionalLikeAssign<_Up, _Up const&>::
716 template __enable_assign<_Up>(),
718 constexpr optional& operator=(const optional<_Up>& __v);
720 template <class _Up, enable_if_t<_CheckOptionalLikeCtor<_Up, _Up&&>::
721 template __enable_assign<_Up>(),
723 constexpr optional& operator=(optional<_Up>&& __v);
725 const _Tp& operator*() const&;
727 const _Tp&& operator*() const&&;
728 _Tp&& operator*() &&;
730 const _Tp* operator->() const;
733 const _Tp& value() const&;
735 const _Tp&& value() const&&;
738 template <typename U>
739 constexpr _Tp value_or(U&& v) const&;
740 template <typename U>
741 _Tp value_or(U&& v) &&;
743 template <typename... Args>
744 _Tp& emplace(Args&&... args);
746 template <typename U, typename... Args>
747 _Tp& emplace(std::initializer_list<U> ilist, Args&&... args);
751 constexpr explicit operator bool() const noexcept;
752 using __base::has_value;
754 constexpr void swap(optional& __opt) noexcept;
757 template <typename T>
758 constexpr optional<typename std::decay<T>::type> make_optional(T&& v);
760 template <typename T, typename... Args>
761 constexpr optional<T> make_optional(Args&&... args);
763 template <typename T, typename U, typename... Args>
764 constexpr optional<T> make_optional(std::initializer_list<U> il,
767 template <typename T, typename U>
768 constexpr bool operator==(const optional<T> &lhs, const optional<U> &rhs);
769 template <typename T, typename U>
770 constexpr bool operator!=(const optional<T> &lhs, const optional<U> &rhs);
772 template <typename T>
773 constexpr bool operator==(const optional<T> &opt, nullopt_t);
775 // C++20 and later do not define the following overloads because they are
776 // provided by rewritten candidates instead.
777 #if __cplusplus < 202002L
778 template <typename T>
779 constexpr bool operator==(nullopt_t, const optional<T> &opt);
780 template <typename T>
781 constexpr bool operator!=(const optional<T> &opt, nullopt_t);
782 template <typename T>
783 constexpr bool operator!=(nullopt_t, const optional<T> &opt);
784 #endif // __cplusplus < 202002L
786 template <typename T, typename U>
787 constexpr bool operator==(const optional<T> &opt, const U &value);
788 template <typename T, typename U>
789 constexpr bool operator==(const T &value, const optional<U> &opt);
790 template <typename T, typename U>
791 constexpr bool operator!=(const optional<T> &opt, const U &value);
792 template <typename T, typename U>
793 constexpr bool operator!=(const T &value, const optional<U> &opt);
798 static constexpr char AbslOptionalHeader
[] = R
"(
799 #include "absl_type_traits
.h
"
800 #include "std_initializer_list
.h
"
801 #include "std_type_traits
.h
"
802 #include "std_utility
.h
"
807 constexpr explicit nullopt_t() {}
809 constexpr nullopt_t nullopt;
811 struct in_place_t {};
812 constexpr in_place_t in_place;
814 template <typename T>
817 namespace optional_internal {
819 template <typename T, typename U>
820 struct is_constructible_convertible_from_optional
821 : std::integral_constant<
822 bool, std::is_constructible<T, optional<U>&>::value ||
823 std::is_constructible<T, optional<U>&&>::value ||
824 std::is_constructible<T, const optional<U>&>::value ||
825 std::is_constructible<T, const optional<U>&&>::value ||
826 std::is_convertible<optional<U>&, T>::value ||
827 std::is_convertible<optional<U>&&, T>::value ||
828 std::is_convertible<const optional<U>&, T>::value ||
829 std::is_convertible<const optional<U>&&, T>::value> {};
831 template <typename T, typename U>
832 struct is_constructible_convertible_assignable_from_optional
833 : std::integral_constant<
834 bool, is_constructible_convertible_from_optional<T, U>::value ||
835 std::is_assignable<T&, optional<U>&>::value ||
836 std::is_assignable<T&, optional<U>&&>::value ||
837 std::is_assignable<T&, const optional<U>&>::value ||
838 std::is_assignable<T&, const optional<U>&&>::value> {};
840 } // namespace optional_internal
842 template <typename T>
845 constexpr optional() noexcept;
847 constexpr optional(nullopt_t) noexcept;
849 optional(const optional&) = default;
851 optional(optional&&) = default;
853 template <typename InPlaceT, typename... Args,
854 absl::enable_if_t<absl::conjunction<
855 std::is_same<InPlaceT, in_place_t>,
856 std::is_constructible<T, Args&&...>>::value>* = nullptr>
857 constexpr explicit optional(InPlaceT, Args&&... args);
859 template <typename U, typename... Args,
860 typename = typename std::enable_if<std::is_constructible<
861 T, std::initializer_list<U>&, Args&&...>::value>::type>
862 constexpr explicit optional(in_place_t, std::initializer_list<U> il,
867 typename std::enable_if<
868 absl::conjunction<absl::negation<std::is_same<
869 in_place_t, typename std::decay<U>::type>>,
870 absl::negation<std::is_same<
871 optional<T>, typename std::decay<U>::type>>,
872 std::is_convertible<U&&, T>,
873 std::is_constructible<T, U&&>>::value,
875 constexpr optional(U&& v);
879 typename std::enable_if<
880 absl::conjunction<absl::negation<std::is_same<
881 in_place_t, typename std::decay<U>::type>>,
882 absl::negation<std::is_same<
883 optional<T>, typename std::decay<U>::type>>,
884 absl::negation<std::is_convertible<U&&, T>>,
885 std::is_constructible<T, U&&>>::value,
887 explicit constexpr optional(U&& v);
889 template <typename U,
890 typename std::enable_if<
892 absl::negation<std::is_same<T, U>>,
893 std::is_constructible<T, const U&>,
896 is_constructible_convertible_from_optional<T, U>>,
897 std::is_convertible<const U&, T>>::value,
899 optional(const optional<U>& rhs);
901 template <typename U,
902 typename std::enable_if<
904 absl::negation<std::is_same<T, U>>,
905 std::is_constructible<T, const U&>,
908 is_constructible_convertible_from_optional<T, U>>,
909 absl::negation<std::is_convertible<const U&, T>>>::value,
911 explicit optional(const optional<U>& rhs);
915 typename std::enable_if<
917 absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
919 optional_internal::is_constructible_convertible_from_optional<
921 std::is_convertible<U&&, T>>::value,
923 optional(optional<U>&& rhs);
927 typename std::enable_if<
929 absl::negation<std::is_same<T, U>>, std::is_constructible<T, U&&>,
931 optional_internal::is_constructible_convertible_from_optional<
933 absl::negation<std::is_convertible<U&&, T>>>::value,
935 explicit optional(optional<U>&& rhs);
937 optional& operator=(nullopt_t) noexcept;
939 optional& operator=(const optional& src);
941 optional& operator=(optional&& src);
945 typename = typename std::enable_if<absl::conjunction<
947 std::is_same<optional<T>, typename std::decay<U>::type>>,
949 absl::conjunction<std::is_scalar<T>,
950 std::is_same<T, typename std::decay<U>::type>>>,
951 std::is_constructible<T, U>, std::is_assignable<T&, U>>::value>::type>
952 optional& operator=(U&& v);
956 typename = typename std::enable_if<absl::conjunction<
957 absl::negation<std::is_same<T, U>>,
958 std::is_constructible<T, const U&>, std::is_assignable<T&, const U&>,
961 is_constructible_convertible_assignable_from_optional<
962 T, U>>>::value>::type>
963 optional& operator=(const optional<U>& rhs);
965 template <typename U,
966 typename = typename std::enable_if<absl::conjunction<
967 absl::negation<std::is_same<T, U>>, std::is_constructible<T, U>,
968 std::is_assignable<T&, U>,
971 is_constructible_convertible_assignable_from_optional<
972 T, U>>>::value>::type>
973 optional& operator=(optional<U>&& rhs);
975 const T& operator*() const&;
977 const T&& operator*() const&&;
980 const T* operator->() const;
983 const T& value() const&;
985 const T&& value() const&&;
988 template <typename U>
989 constexpr T value_or(U&& v) const&;
990 template <typename U>
991 T value_or(U&& v) &&;
993 template <typename... Args>
994 T& emplace(Args&&... args);
996 template <typename U, typename... Args>
997 T& emplace(std::initializer_list<U> ilist, Args&&... args);
999 void reset() noexcept;
1001 constexpr explicit operator bool() const noexcept;
1002 constexpr bool has_value() const noexcept;
1004 void swap(optional& rhs) noexcept;
1007 template <typename T>
1008 constexpr optional<typename std::decay<T>::type> make_optional(T&& v);
1010 template <typename T, typename... Args>
1011 constexpr optional<T> make_optional(Args&&... args);
1013 template <typename T, typename U, typename... Args>
1014 constexpr optional<T> make_optional(std::initializer_list<U> il,
1017 template <typename T, typename U>
1018 constexpr bool operator==(const optional<T> &lhs, const optional<U> &rhs);
1019 template <typename T, typename U>
1020 constexpr bool operator!=(const optional<T> &lhs, const optional<U> &rhs);
1022 template <typename T>
1023 constexpr bool operator==(const optional<T> &opt, nullopt_t);
1024 template <typename T>
1025 constexpr bool operator==(nullopt_t, const optional<T> &opt);
1026 template <typename T>
1027 constexpr bool operator!=(const optional<T> &opt, nullopt_t);
1028 template <typename T>
1029 constexpr bool operator!=(nullopt_t, const optional<T> &opt);
1031 template <typename T, typename U>
1032 constexpr bool operator==(const optional<T> &opt, const U &value);
1033 template <typename T, typename U>
1034 constexpr bool operator==(const T &value, const optional<U> &opt);
1035 template <typename T, typename U>
1036 constexpr bool operator!=(const optional<T> &opt, const U &value);
1037 template <typename T, typename U>
1038 constexpr bool operator!=(const T &value, const optional<U> &opt);
1043 static constexpr char BaseOptionalHeader
[] = R
"(
1044 #include "std_initializer_list
.h
"
1045 #include "std_type_traits
.h
"
1046 #include "std_utility
.h
"
1050 struct in_place_t {};
1051 constexpr in_place_t in_place;
1054 constexpr explicit nullopt_t() {}
1056 constexpr nullopt_t nullopt;
1058 template <typename T>
1061 namespace internal {
1063 template <typename T>
1064 using RemoveCvRefT = std::remove_cv_t<std::remove_reference_t<T>>;
1066 template <typename T, typename U>
1067 struct IsConvertibleFromOptional
1068 : std::integral_constant<
1069 bool, std::is_constructible<T, Optional<U>&>::value ||
1070 std::is_constructible<T, const Optional<U>&>::value ||
1071 std::is_constructible<T, Optional<U>&&>::value ||
1072 std::is_constructible<T, const Optional<U>&&>::value ||
1073 std::is_convertible<Optional<U>&, T>::value ||
1074 std::is_convertible<const Optional<U>&, T>::value ||
1075 std::is_convertible<Optional<U>&&, T>::value ||
1076 std::is_convertible<const Optional<U>&&, T>::value> {};
1078 template <typename T, typename U>
1079 struct IsAssignableFromOptional
1080 : std::integral_constant<
1081 bool, IsConvertibleFromOptional<T, U>::value ||
1082 std::is_assignable<T&, Optional<U>&>::value ||
1083 std::is_assignable<T&, const Optional<U>&>::value ||
1084 std::is_assignable<T&, Optional<U>&&>::value ||
1085 std::is_assignable<T&, const Optional<U>&&>::value> {};
1087 } // namespace internal
1089 template <typename T>
1092 using value_type = T;
1094 constexpr Optional() = default;
1095 constexpr Optional(const Optional& other) noexcept = default;
1096 constexpr Optional(Optional&& other) noexcept = default;
1098 constexpr Optional(nullopt_t);
1100 template <typename U,
1101 typename std::enable_if<
1102 std::is_constructible<T, const U&>::value &&
1103 !internal::IsConvertibleFromOptional<T, U>::value &&
1104 std::is_convertible<const U&, T>::value,
1105 bool>::type = false>
1106 Optional(const Optional<U>& other) noexcept;
1108 template <typename U,
1109 typename std::enable_if<
1110 std::is_constructible<T, const U&>::value &&
1111 !internal::IsConvertibleFromOptional<T, U>::value &&
1112 !std::is_convertible<const U&, T>::value,
1113 bool>::type = false>
1114 explicit Optional(const Optional<U>& other) noexcept;
1116 template <typename U,
1117 typename std::enable_if<
1118 std::is_constructible<T, U&&>::value &&
1119 !internal::IsConvertibleFromOptional<T, U>::value &&
1120 std::is_convertible<U&&, T>::value,
1121 bool>::type = false>
1122 Optional(Optional<U>&& other) noexcept;
1124 template <typename U,
1125 typename std::enable_if<
1126 std::is_constructible<T, U&&>::value &&
1127 !internal::IsConvertibleFromOptional<T, U>::value &&
1128 !std::is_convertible<U&&, T>::value,
1129 bool>::type = false>
1130 explicit Optional(Optional<U>&& other) noexcept;
1132 template <class... Args>
1133 constexpr explicit Optional(in_place_t, Args&&... args);
1135 template <class U, class... Args,
1136 class = typename std::enable_if<std::is_constructible<
1137 value_type, std::initializer_list<U>&, Args...>::value>::type>
1138 constexpr explicit Optional(in_place_t, std::initializer_list<U> il,
1142 typename U = value_type,
1143 typename std::enable_if<
1144 std::is_constructible<T, U&&>::value &&
1145 !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
1146 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
1147 std::is_convertible<U&&, T>::value,
1148 bool>::type = false>
1149 constexpr Optional(U&& value);
1152 typename U = value_type,
1153 typename std::enable_if<
1154 std::is_constructible<T, U&&>::value &&
1155 !std::is_same<internal::RemoveCvRefT<U>, in_place_t>::value &&
1156 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
1157 !std::is_convertible<U&&, T>::value,
1158 bool>::type = false>
1159 constexpr explicit Optional(U&& value);
1161 Optional& operator=(const Optional& other) noexcept;
1163 Optional& operator=(Optional&& other) noexcept;
1165 Optional& operator=(nullopt_t);
1167 template <typename U>
1168 typename std::enable_if<
1169 !std::is_same<internal::RemoveCvRefT<U>, Optional<T>>::value &&
1170 std::is_constructible<T, U>::value &&
1171 std::is_assignable<T&, U>::value &&
1172 (!std::is_scalar<T>::value ||
1173 !std::is_same<typename std::decay<U>::type, T>::value),
1175 operator=(U&& value) noexcept;
1177 template <typename U>
1178 typename std::enable_if<!internal::IsAssignableFromOptional<T, U>::value &&
1179 std::is_constructible<T, const U&>::value &&
1180 std::is_assignable<T&, const U&>::value,
1182 operator=(const Optional<U>& other) noexcept;
1184 template <typename U>
1185 typename std::enable_if<!internal::IsAssignableFromOptional<T, U>::value &&
1186 std::is_constructible<T, U>::value &&
1187 std::is_assignable<T&, U>::value,
1189 operator=(Optional<U>&& other) noexcept;
1191 const T& operator*() const&;
1193 const T&& operator*() const&&;
1196 const T* operator->() const;
1199 const T& value() const&;
1201 const T&& value() const&&;
1204 template <typename U>
1205 constexpr T value_or(U&& v) const&;
1206 template <typename U>
1207 T value_or(U&& v) &&;
1209 template <typename... Args>
1210 T& emplace(Args&&... args);
1212 template <typename U, typename... Args>
1213 T& emplace(std::initializer_list<U> ilist, Args&&... args);
1215 void reset() noexcept;
1217 constexpr explicit operator bool() const noexcept;
1218 constexpr bool has_value() const noexcept;
1220 void swap(Optional& other);
1223 template <typename T>
1224 constexpr Optional<typename std::decay<T>::type> make_optional(T&& v);
1226 template <typename T, typename... Args>
1227 constexpr Optional<T> make_optional(Args&&... args);
1229 template <typename T, typename U, typename... Args>
1230 constexpr Optional<T> make_optional(std::initializer_list<U> il,
1233 template <typename T, typename U>
1234 constexpr bool operator==(const Optional<T> &lhs, const Optional<U> &rhs);
1235 template <typename T, typename U>
1236 constexpr bool operator!=(const Optional<T> &lhs, const Optional<U> &rhs);
1238 template <typename T>
1239 constexpr bool operator==(const Optional<T> &opt, nullopt_t);
1240 template <typename T>
1241 constexpr bool operator==(nullopt_t, const Optional<T> &opt);
1242 template <typename T>
1243 constexpr bool operator!=(const Optional<T> &opt, nullopt_t);
1244 template <typename T>
1245 constexpr bool operator!=(nullopt_t, const Optional<T> &opt);
1247 template <typename T, typename U>
1248 constexpr bool operator==(const Optional<T> &opt, const U &value);
1249 template <typename T, typename U>
1250 constexpr bool operator==(const T &value, const Optional<U> &opt);
1251 template <typename T, typename U>
1252 constexpr bool operator!=(const Optional<T> &opt, const U &value);
1253 template <typename T, typename U>
1254 constexpr bool operator!=(const T &value, const Optional<U> &opt);
1259 /// Replaces all occurrences of `Pattern` in `S` with `Replacement`.
1260 static void ReplaceAllOccurrences(std::string
&S
, const std::string
&Pattern
,
1261 const std::string
&Replacement
) {
1264 Pos
= S
.find(Pattern
, Pos
);
1265 if (Pos
== std::string::npos
)
1267 S
.replace(Pos
, Pattern
.size(), Replacement
);
1271 struct OptionalTypeIdentifier
{
1272 std::string NamespaceName
;
1273 std::string TypeName
;
1276 static raw_ostream
&operator<<(raw_ostream
&OS
,
1277 const OptionalTypeIdentifier
&TypeId
) {
1278 OS
<< TypeId
.NamespaceName
<< "::" << TypeId
.TypeName
;
1282 class UncheckedOptionalAccessTest
1283 : public ::testing::TestWithParam
<OptionalTypeIdentifier
> {
1285 void ExpectDiagnosticsFor(std::string SourceCode
,
1286 bool IgnoreSmartPointerDereference
= true) {
1287 ExpectDiagnosticsFor(SourceCode
, ast_matchers::hasName("target"),
1288 IgnoreSmartPointerDereference
);
1291 void ExpectDiagnosticsForLambda(std::string SourceCode
,
1292 bool IgnoreSmartPointerDereference
= true) {
1293 ExpectDiagnosticsFor(
1295 ast_matchers::hasDeclContext(
1296 ast_matchers::cxxRecordDecl(ast_matchers::isLambda())),
1297 IgnoreSmartPointerDereference
);
1300 template <typename FuncDeclMatcher
>
1301 void ExpectDiagnosticsFor(std::string SourceCode
, FuncDeclMatcher FuncMatcher
,
1302 bool IgnoreSmartPointerDereference
= true) {
1303 // Run in C++17 and C++20 mode to cover differences in the AST between modes
1304 // (e.g. C++20 can contain `CXXRewrittenBinaryOperator`).
1305 for (const char *CxxMode
: {"-std=c++17", "-std=c++20"})
1306 ExpectDiagnosticsFor(SourceCode
, FuncMatcher
, CxxMode
,
1307 IgnoreSmartPointerDereference
);
1310 template <typename FuncDeclMatcher
>
1311 void ExpectDiagnosticsFor(std::string SourceCode
, FuncDeclMatcher FuncMatcher
,
1312 const char *CxxMode
,
1313 bool IgnoreSmartPointerDereference
) {
1314 ReplaceAllOccurrences(SourceCode
, "$ns", GetParam().NamespaceName
);
1315 ReplaceAllOccurrences(SourceCode
, "$optional", GetParam().TypeName
);
1317 std::vector
<std::pair
<std::string
, std::string
>> Headers
;
1318 Headers
.emplace_back("cstddef.h", CSDtdDefHeader
);
1319 Headers
.emplace_back("std_initializer_list.h", StdInitializerListHeader
);
1320 Headers
.emplace_back("std_string.h", StdStringHeader
);
1321 Headers
.emplace_back("std_type_traits.h", StdTypeTraitsHeader
);
1322 Headers
.emplace_back("std_utility.h", StdUtilityHeader
);
1323 Headers
.emplace_back("std_optional.h", StdOptionalHeader
);
1324 Headers
.emplace_back("absl_type_traits.h", AbslTypeTraitsHeader
);
1325 Headers
.emplace_back("absl_optional.h", AbslOptionalHeader
);
1326 Headers
.emplace_back("base_optional.h", BaseOptionalHeader
);
1327 Headers
.emplace_back("unchecked_optional_access_test.h", R
"(
1328 #include "absl_optional
.h
"
1329 #include "base_optional
.h
"
1330 #include "std_initializer_list
.h
"
1331 #include "std_optional
.h
"
1332 #include "std_string
.h
"
1333 #include "std_utility
.h
"
1335 template <typename T>
1338 UncheckedOptionalAccessModelOptions Options
{IgnoreSmartPointerDereference
};
1339 std::vector
<SourceLocation
> Diagnostics
;
1340 llvm::Error Error
= checkDataflow
<UncheckedOptionalAccessModel
>(
1341 AnalysisInputs
<UncheckedOptionalAccessModel
>(
1342 SourceCode
, std::move(FuncMatcher
),
1343 [](ASTContext
&Ctx
, Environment
&Env
) {
1344 return UncheckedOptionalAccessModel(Ctx
, Env
);
1346 .withDiagnosisCallbacks(
1347 {/*Before=*/[&Diagnostics
,
1349 UncheckedOptionalAccessDiagnoser(Options
)](
1350 ASTContext
&Ctx
, const CFGElement
&Elt
,
1351 const TransferStateForDiagnostics
<
1352 UncheckedOptionalAccessLattice
>
1354 auto EltDiagnostics
= Diagnoser(Elt
, Ctx
, State
);
1355 llvm::move(EltDiagnostics
, std::back_inserter(Diagnostics
));
1359 {"-fsyntax-only", CxxMode
, "-Wno-undefined-inline"})
1360 .withASTBuildVirtualMappedFiles(
1361 tooling::FileContentMappings(Headers
.begin(), Headers
.end())),
1362 /*VerifyResults=*/[&Diagnostics
](
1363 const llvm::DenseMap
<unsigned, std::string
>
1365 const AnalysisOutputs
&AO
) {
1366 llvm::DenseSet
<unsigned> AnnotationLines
;
1367 for (const auto &[Line
, _
] : Annotations
) {
1368 AnnotationLines
.insert(Line
);
1370 auto &SrcMgr
= AO
.ASTCtx
.getSourceManager();
1371 llvm::DenseSet
<unsigned> DiagnosticLines
;
1372 for (SourceLocation
&Loc
: Diagnostics
) {
1373 unsigned Line
= SrcMgr
.getPresumedLineNumber(Loc
);
1374 DiagnosticLines
.insert(Line
);
1375 if (!AnnotationLines
.contains(Line
)) {
1376 IntrusiveRefCntPtr
<DiagnosticOptions
> DiagOpts(
1377 new DiagnosticOptions());
1378 TextDiagnostic
TD(llvm::errs(), AO
.ASTCtx
.getLangOpts(),
1380 TD
.emitDiagnostic(FullSourceLoc(Loc
, SrcMgr
),
1381 DiagnosticsEngine::Error
,
1382 "unexpected diagnostic", {}, {});
1386 EXPECT_THAT(DiagnosticLines
, ContainerEq(AnnotationLines
));
1389 FAIL() << llvm::toString(std::move(Error
));
1393 INSTANTIATE_TEST_SUITE_P(
1394 UncheckedOptionalUseTestInst
, UncheckedOptionalAccessTest
,
1395 ::testing::Values(OptionalTypeIdentifier
{"std", "optional"},
1396 OptionalTypeIdentifier
{"absl", "optional"},
1397 OptionalTypeIdentifier
{"base", "Optional"}),
1398 [](const ::testing::TestParamInfo
<OptionalTypeIdentifier
> &Info
) {
1399 return Info
.param
.NamespaceName
;
1402 // Verifies that similarly-named types are ignored.
1403 TEST_P(UncheckedOptionalAccessTest
, NonTrackedOptionalType
) {
1404 ExpectDiagnosticsFor(
1408 template <typename T>
1414 void target($ns::$optional<int> opt) {
1421 TEST_P(UncheckedOptionalAccessTest
, EmptyFunctionBody
) {
1422 ExpectDiagnosticsFor(R
"(
1429 TEST_P(UncheckedOptionalAccessTest
, UnwrapUsingValueNoCheck
) {
1430 ExpectDiagnosticsFor(
1432 #include "unchecked_optional_access_test
.h
"
1434 void target($ns::$optional<int> opt) {
1435 opt.value(); // [[unsafe]]
1439 ExpectDiagnosticsFor(
1441 #include "unchecked_optional_access_test
.h
"
1443 void target($ns::$optional<int> opt) {
1444 std::move(opt).value(); // [[unsafe]]
1449 TEST_P(UncheckedOptionalAccessTest
, UnwrapUsingOperatorStarNoCheck
) {
1450 ExpectDiagnosticsFor(
1452 #include "unchecked_optional_access_test
.h
"
1454 void target($ns::$optional<int> opt) {
1459 ExpectDiagnosticsFor(
1461 #include "unchecked_optional_access_test
.h
"
1463 void target($ns::$optional<int> opt) {
1464 *std::move(opt); // [[unsafe]]
1469 TEST_P(UncheckedOptionalAccessTest
, UnwrapUsingOperatorArrowNoCheck
) {
1470 ExpectDiagnosticsFor(
1472 #include "unchecked_optional_access_test
.h
"
1478 void target($ns::$optional<Foo> opt) {
1479 opt->foo(); // [[unsafe]]
1483 ExpectDiagnosticsFor(
1485 #include "unchecked_optional_access_test
.h
"
1491 void target($ns::$optional<Foo> opt) {
1492 std::move(opt)->foo(); // [[unsafe]]
1497 TEST_P(UncheckedOptionalAccessTest
, HasValueCheck
) {
1498 ExpectDiagnosticsFor(R
"(
1499 #include "unchecked_optional_access_test
.h
"
1501 void target($ns::$optional<int> opt) {
1502 if (opt.has_value()) {
1509 TEST_P(UncheckedOptionalAccessTest
, OperatorBoolCheck
) {
1510 ExpectDiagnosticsFor(R
"(
1511 #include "unchecked_optional_access_test
.h
"
1513 void target($ns::$optional<int> opt) {
1521 TEST_P(UncheckedOptionalAccessTest
, UnwrapFunctionCallResultNoCheck
) {
1522 ExpectDiagnosticsFor(
1524 #include "unchecked_optional_access_test
.h
"
1527 Make<$ns::$optional<int>>().value(); // [[unsafe]]
1532 ExpectDiagnosticsFor(
1534 #include "unchecked_optional_access_test
.h
"
1536 void target($ns::$optional<int> opt) {
1537 std::move(opt).value(); // [[unsafe]]
1542 TEST_P(UncheckedOptionalAccessTest
, DefaultConstructor
) {
1543 ExpectDiagnosticsFor(
1545 #include "unchecked_optional_access_test
.h
"
1548 $ns::$optional<int> opt;
1549 opt.value(); // [[unsafe]]
1554 TEST_P(UncheckedOptionalAccessTest
, NulloptConstructor
) {
1555 ExpectDiagnosticsFor(
1557 #include "unchecked_optional_access_test
.h
"
1560 $ns::$optional<int> opt($ns::nullopt);
1561 opt.value(); // [[unsafe]]
1566 TEST_P(UncheckedOptionalAccessTest
, NulloptConstructorWithSugaredType
) {
1567 ExpectDiagnosticsFor(
1569 #include "unchecked_optional_access_test
.h
"
1570 template <typename T>
1573 template <typename T>
1577 $ns::$optional<int> opt(wrap($ns::nullopt));
1578 opt.value(); // [[unsafe]]
1583 TEST_P(UncheckedOptionalAccessTest
, InPlaceConstructor
) {
1584 ExpectDiagnosticsFor(R
"(
1585 #include "unchecked_optional_access_test
.h
"
1588 $ns::$optional<int> opt($ns::in_place, 3);
1593 ExpectDiagnosticsFor(R
"(
1594 #include "unchecked_optional_access_test
.h
"
1599 $ns::$optional<Foo> opt($ns::in_place);
1604 ExpectDiagnosticsFor(R
"(
1605 #include "unchecked_optional_access_test
.h
"
1608 explicit Foo(int, bool);
1612 $ns::$optional<Foo> opt($ns::in_place, 3, false);
1617 ExpectDiagnosticsFor(R
"(
1618 #include "unchecked_optional_access_test
.h
"
1621 explicit Foo(std::initializer_list<int>);
1625 $ns::$optional<Foo> opt($ns::in_place, {3});
1631 TEST_P(UncheckedOptionalAccessTest
, ValueConstructor
) {
1632 ExpectDiagnosticsFor(R
"(
1633 #include "unchecked_optional_access_test
.h
"
1636 $ns::$optional<int> opt(21);
1641 ExpectDiagnosticsFor(R
"(
1642 #include "unchecked_optional_access_test
.h
"
1645 $ns::$optional<int> opt = $ns::$optional<int>(21);
1649 ExpectDiagnosticsFor(R
"(
1650 #include "unchecked_optional_access_test
.h
"
1653 $ns::$optional<$ns::$optional<int>> opt(Make<$ns::$optional<int>>());
1658 ExpectDiagnosticsFor(R
"(
1659 #include "unchecked_optional_access_test
.h
"
1662 MyString(const char*);
1666 $ns::$optional<MyString> opt("foo
");
1671 ExpectDiagnosticsFor(R
"(
1672 #include "unchecked_optional_access_test
.h
"
1681 $ns::$optional<Bar> opt(Make<Foo>());
1686 ExpectDiagnosticsFor(R
"(
1687 #include "unchecked_optional_access_test
.h
"
1694 $ns::$optional<Foo> opt(3);
1700 TEST_P(UncheckedOptionalAccessTest
, ConvertibleOptionalConstructor
) {
1701 ExpectDiagnosticsFor(
1703 #include "unchecked_optional_access_test
.h
"
1712 $ns::$optional<Bar> opt(Make<$ns::$optional<Foo>>());
1713 opt.value(); // [[unsafe]]
1717 ExpectDiagnosticsFor(
1719 #include "unchecked_optional_access_test
.h
"
1724 explicit Bar(const Foo&);
1728 $ns::$optional<Bar> opt(Make<$ns::$optional<Foo>>());
1729 opt.value(); // [[unsafe]]
1733 ExpectDiagnosticsFor(
1735 #include "unchecked_optional_access_test
.h
"
1744 $ns::$optional<Foo> opt1 = $ns::nullopt;
1745 $ns::$optional<Bar> opt2(opt1);
1746 opt2.value(); // [[unsafe]]
1750 ExpectDiagnosticsFor(R
"(
1751 #include "unchecked_optional_access_test
.h
"
1760 $ns::$optional<Foo> opt1(Make<Foo>());
1761 $ns::$optional<Bar> opt2(opt1);
1766 ExpectDiagnosticsFor(R
"(
1767 #include "unchecked_optional_access_test
.h
"
1772 explicit Bar(const Foo&);
1776 $ns::$optional<Foo> opt1(Make<Foo>());
1777 $ns::$optional<Bar> opt2(opt1);
1783 TEST_P(UncheckedOptionalAccessTest
, MakeOptional
) {
1784 ExpectDiagnosticsFor(R
"(
1785 #include "unchecked_optional_access_test
.h
"
1788 $ns::$optional<int> opt = $ns::make_optional(0);
1793 ExpectDiagnosticsFor(R
"(
1794 #include "unchecked_optional_access_test
.h
"
1801 $ns::$optional<Foo> opt = $ns::make_optional<Foo>(21, 22);
1806 ExpectDiagnosticsFor(R
"(
1807 #include "unchecked_optional_access_test
.h
"
1810 constexpr Foo(std::initializer_list<char>);
1815 $ns::$optional<Foo> opt = $ns::make_optional<Foo>({a});
1821 TEST_P(UncheckedOptionalAccessTest
, ValueOr
) {
1822 ExpectDiagnosticsFor(R
"(
1823 #include "unchecked_optional_access_test
.h
"
1826 $ns::$optional<int> opt;
1833 TEST_P(UncheckedOptionalAccessTest
, ValueOrComparisonPointers
) {
1834 ExpectDiagnosticsFor(
1836 #include "unchecked_optional_access_test
.h
"
1838 void target($ns::$optional<int*> opt) {
1839 if (opt.value_or(nullptr) != nullptr) {
1842 opt.value(); // [[unsafe]]
1848 TEST_P(UncheckedOptionalAccessTest
, ValueOrComparisonIntegers
) {
1849 ExpectDiagnosticsFor(
1851 #include "unchecked_optional_access_test
.h
"
1853 void target($ns::$optional<int> opt) {
1854 if (opt.value_or(0) != 0) {
1857 opt.value(); // [[unsafe]]
1863 TEST_P(UncheckedOptionalAccessTest
, ValueOrComparisonStrings
) {
1864 ExpectDiagnosticsFor(
1866 #include "unchecked_optional_access_test
.h
"
1868 void target($ns::$optional<std::string> opt) {
1869 if (!opt.value_or("").empty()) {
1872 opt.value(); // [[unsafe]]
1877 ExpectDiagnosticsFor(
1879 #include "unchecked_optional_access_test
.h
"
1881 void target($ns::$optional<std::string> opt) {
1882 if (opt.value_or("") != "") {
1885 opt.value(); // [[unsafe]]
1891 TEST_P(UncheckedOptionalAccessTest
, ValueOrComparisonPointerToOptional
) {
1892 // FIXME: make `opt` a parameter directly, once we ensure that all `optional`
1893 // values have a `has_value` property.
1894 ExpectDiagnosticsFor(
1896 #include "unchecked_optional_access_test
.h
"
1898 void target($ns::$optional<int> p) {
1899 $ns::$optional<int> *opt = &p;
1900 if (opt->value_or(0) != 0) {
1903 opt->value(); // [[unsafe]]
1909 TEST_P(UncheckedOptionalAccessTest
, Emplace
) {
1910 ExpectDiagnosticsFor(R
"(
1911 #include "unchecked_optional_access_test
.h
"
1914 $ns::$optional<int> opt;
1920 ExpectDiagnosticsFor(R
"(
1921 #include "unchecked_optional_access_test
.h
"
1923 void target($ns::$optional<int> *opt) {
1929 // FIXME: Add tests that call `emplace` in conditional branches:
1930 // ExpectDiagnosticsFor(
1932 // #include "unchecked_optional_access_test.h"
1934 // void target($ns::$optional<int> opt, bool b) {
1941 // opt.value(); // [[unsafe]]
1947 TEST_P(UncheckedOptionalAccessTest
, Reset
) {
1948 ExpectDiagnosticsFor(
1950 #include "unchecked_optional_access_test
.h
"
1953 $ns::$optional<int> opt = $ns::make_optional(0);
1955 opt.value(); // [[unsafe]]
1959 ExpectDiagnosticsFor(
1961 #include "unchecked_optional_access_test
.h
"
1963 void target($ns::$optional<int> &opt) {
1964 if (opt.has_value()) {
1966 opt.value(); // [[unsafe]]
1971 // FIXME: Add tests that call `reset` in conditional branches:
1972 // ExpectDiagnosticsFor(
1974 // #include "unchecked_optional_access_test.h"
1976 // void target(bool b) {
1977 // $ns::$optional<int> opt = $ns::make_optional(0);
1982 // opt.value(); // [[unsafe]]
1990 TEST_P(UncheckedOptionalAccessTest
, ValueAssignment
) {
1991 ExpectDiagnosticsFor(R
"(
1992 #include "unchecked_optional_access_test
.h
"
1997 $ns::$optional<Foo> opt;
2003 ExpectDiagnosticsFor(R
"(
2004 #include "unchecked_optional_access_test
.h
"
2009 $ns::$optional<Foo> opt;
2010 (opt = Foo()).value();
2015 ExpectDiagnosticsFor(R
"(
2016 #include "unchecked_optional_access_test
.h
"
2019 MyString(const char*);
2023 $ns::$optional<MyString> opt;
2029 ExpectDiagnosticsFor(R
"(
2030 #include "unchecked_optional_access_test
.h
"
2033 MyString(const char*);
2037 $ns::$optional<MyString> opt;
2038 (opt = "foo
").value();
2043 TEST_P(UncheckedOptionalAccessTest
, OptionalConversionAssignment
) {
2044 ExpectDiagnosticsFor(
2046 #include "unchecked_optional_access_test
.h
"
2055 $ns::$optional<Foo> opt1 = Foo();
2056 $ns::$optional<Bar> opt2;
2062 ExpectDiagnosticsFor(
2064 #include "unchecked_optional_access_test
.h
"
2073 $ns::$optional<Foo> opt1;
2074 $ns::$optional<Bar> opt2;
2075 if (opt2.has_value()) {
2077 opt2.value(); // [[unsafe]]
2082 ExpectDiagnosticsFor(
2084 #include "unchecked_optional_access_test
.h
"
2093 $ns::$optional<Foo> opt1 = Foo();
2094 $ns::$optional<Bar> opt2;
2095 (opt2 = opt1).value();
2101 TEST_P(UncheckedOptionalAccessTest
, NulloptAssignment
) {
2102 ExpectDiagnosticsFor(
2104 #include "unchecked_optional_access_test
.h
"
2107 $ns::$optional<int> opt = 3;
2109 opt.value(); // [[unsafe]]
2113 ExpectDiagnosticsFor(
2115 #include "unchecked_optional_access_test
.h
"
2118 $ns::$optional<int> opt = 3;
2119 (opt = $ns::nullopt).value(); // [[unsafe]]
2124 TEST_P(UncheckedOptionalAccessTest
, OptionalSwap
) {
2125 ExpectDiagnosticsFor(
2127 #include "unchecked_optional_access_test
.h
"
2130 $ns::$optional<int> opt1 = $ns::nullopt;
2131 $ns::$optional<int> opt2 = 3;
2137 opt2.value(); // [[unsafe]]
2141 ExpectDiagnosticsFor(
2143 #include "unchecked_optional_access_test
.h
"
2146 $ns::$optional<int> opt1 = $ns::nullopt;
2147 $ns::$optional<int> opt2 = 3;
2153 opt2.value(); // [[unsafe]]
2158 TEST_P(UncheckedOptionalAccessTest
, OptionalReturnedFromFuntionCall
) {
2159 ExpectDiagnosticsFor(
2161 #include "unchecked_optional_access_test
.h
"
2164 $ns::$optional<float> x;
2171 getOptional().x = 0;
2176 TEST_P(UncheckedOptionalAccessTest
, NonConstMethodMayClearOptionalField
) {
2177 ExpectDiagnosticsFor(
2179 #include "unchecked_optional_access_test
.h
"
2182 $ns::$optional<std::string> opt;
2183 void clear(); // assume this may modify the opt field's state
2186 void target(Foo& foo) {
2190 foo.opt.value(); // [[unsafe]]
2196 TEST_P(UncheckedOptionalAccessTest
,
2197 NonConstMethodMayNotClearConstOptionalField
) {
2198 ExpectDiagnosticsFor(
2200 #include "unchecked_optional_access_test
.h
"
2203 const $ns::$optional<std::string> opt;
2207 void target(Foo& foo) {
2217 TEST_P(UncheckedOptionalAccessTest
, StdSwap
) {
2218 ExpectDiagnosticsFor(
2220 #include "unchecked_optional_access_test
.h
"
2223 $ns::$optional<int> opt1 = $ns::nullopt;
2224 $ns::$optional<int> opt2 = 3;
2226 std::swap(opt1, opt2);
2230 opt2.value(); // [[unsafe]]
2234 ExpectDiagnosticsFor(
2236 #include "unchecked_optional_access_test
.h
"
2239 $ns::$optional<int> opt1 = $ns::nullopt;
2240 $ns::$optional<int> opt2 = 3;
2242 std::swap(opt2, opt1);
2246 opt2.value(); // [[unsafe]]
2251 TEST_P(UncheckedOptionalAccessTest
, SwapUnmodeledLocLeft
) {
2252 ExpectDiagnosticsFor(
2254 #include "unchecked_optional_access_test
.h
"
2256 struct L { $ns::$optional<int> hd; L* tl; };
2259 $ns::$optional<int> foo = 3;
2262 // Any `tl` beyond the first is not modeled.
2263 bar.tl->tl->hd.swap(foo);
2265 bar.tl->tl->hd.value(); // [[unsafe]]
2266 foo.value(); // [[unsafe]]
2271 TEST_P(UncheckedOptionalAccessTest
, SwapUnmodeledLocRight
) {
2272 ExpectDiagnosticsFor(
2274 #include "unchecked_optional_access_test
.h
"
2276 struct L { $ns::$optional<int> hd; L* tl; };
2279 $ns::$optional<int> foo = 3;
2282 // Any `tl` beyond the first is not modeled.
2283 foo.swap(bar.tl->tl->hd);
2285 bar.tl->tl->hd.value(); // [[unsafe]]
2286 foo.value(); // [[unsafe]]
2291 TEST_P(UncheckedOptionalAccessTest
, SwapUnmodeledValueLeftSet
) {
2292 ExpectDiagnosticsFor(
2294 #include "unchecked_optional_access_test
.h
"
2296 struct S { int x; };
2297 struct A { $ns::$optional<S> late; };
2303 $ns::$optional<S> foo = S{3};
2306 bar.f1.f2.f3.late.swap(foo);
2308 bar.f1.f2.f3.late.value();
2309 foo.value(); // [[unsafe]]
2314 TEST_P(UncheckedOptionalAccessTest
, SwapUnmodeledValueLeftUnset
) {
2315 ExpectDiagnosticsFor(
2317 #include "unchecked_optional_access_test
.h
"
2319 struct S { int x; };
2320 struct A { $ns::$optional<S> late; };
2326 $ns::$optional<S> foo;
2329 bar.f1.f2.f3.late.swap(foo);
2331 bar.f1.f2.f3.late.value(); // [[unsafe]]
2332 foo.value(); // [[unsafe]]
2337 // fixme: use recursion instead of depth.
2338 TEST_P(UncheckedOptionalAccessTest
, SwapUnmodeledValueRightSet
) {
2339 ExpectDiagnosticsFor(
2341 #include "unchecked_optional_access_test
.h
"
2343 struct S { int x; };
2344 struct A { $ns::$optional<S> late; };
2350 $ns::$optional<S> foo = S{3};
2353 foo.swap(bar.f1.f2.f3.late);
2355 bar.f1.f2.f3.late.value();
2356 foo.value(); // [[unsafe]]
2361 TEST_P(UncheckedOptionalAccessTest
, SwapUnmodeledValueRightUnset
) {
2362 ExpectDiagnosticsFor(
2364 #include "unchecked_optional_access_test
.h
"
2366 struct S { int x; };
2367 struct A { $ns::$optional<S> late; };
2373 $ns::$optional<S> foo;
2376 foo.swap(bar.f1.f2.f3.late);
2378 bar.f1.f2.f3.late.value(); // [[unsafe]]
2379 foo.value(); // [[unsafe]]
2384 TEST_P(UncheckedOptionalAccessTest
, UniquePtrToOptional
) {
2385 // We suppress diagnostics for optionals in smart pointers (other than
2386 // `optional` itself).
2387 ExpectDiagnosticsFor(
2389 #include "unchecked_optional_access_test
.h
"
2391 template <typename T>
2398 smart_ptr<$ns::$optional<bool>> foo;
2405 TEST_P(UncheckedOptionalAccessTest
, UniquePtrToStructWithOptionalField
) {
2406 // We suppress diagnostics for optional fields reachable from smart pointers
2407 // (other than `optional` itself) through (exactly) one member access.
2408 ExpectDiagnosticsFor(
2410 #include "unchecked_optional_access_test
.h
"
2412 template <typename T>
2419 $ns::$optional<int> opt;
2430 TEST_P(UncheckedOptionalAccessTest
, CallReturningOptional
) {
2431 ExpectDiagnosticsFor(
2433 #include "unchecked_optional_access_test
.h
"
2435 $ns::$optional<int> MakeOpt();
2438 $ns::$optional<int> opt = 0;
2440 opt.value(); // [[unsafe]]
2443 ExpectDiagnosticsFor(
2445 #include "unchecked_optional_access_test
.h
"
2447 const $ns::$optional<int>& MakeOpt();
2450 $ns::$optional<int> opt = 0;
2452 opt.value(); // [[unsafe]]
2456 ExpectDiagnosticsFor(
2458 #include "unchecked_optional_access_test
.h
"
2460 using IntOpt = $ns::$optional<int>;
2466 opt.value(); // [[unsafe]]
2470 ExpectDiagnosticsFor(
2472 #include "unchecked_optional_access_test
.h
"
2474 using IntOpt = $ns::$optional<int>;
2475 const IntOpt& MakeOpt();
2480 opt.value(); // [[unsafe]]
2486 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckLeftSet
) {
2487 ExpectDiagnosticsFor(
2489 #include "unchecked_optional_access_test
.h
"
2492 $ns::$optional<int> opt1 = 3;
2493 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2498 opt2.value(); // [[unsafe]]
2504 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckRightSet
) {
2505 ExpectDiagnosticsFor(
2507 #include "unchecked_optional_access_test
.h
"
2510 $ns::$optional<int> opt1 = 3;
2511 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2516 opt2.value(); // [[unsafe]]
2522 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckVerifySetAfterEq
) {
2523 ExpectDiagnosticsFor(
2525 #include "unchecked_optional_access_test
.h
"
2528 $ns::$optional<int> opt1 = Make<$ns::$optional<int>>();
2529 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2532 if (opt1.has_value())
2534 if (opt2.has_value())
2541 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckLeftUnset
) {
2542 ExpectDiagnosticsFor(
2544 #include "unchecked_optional_access_test
.h
"
2547 $ns::$optional<int> opt1 = $ns::nullopt;
2548 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2551 opt2.value(); // [[unsafe]]
2559 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckRightUnset
) {
2560 ExpectDiagnosticsFor(
2562 #include "unchecked_optional_access_test
.h
"
2565 $ns::$optional<int> opt1 = $ns::nullopt;
2566 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2569 opt2.value(); // [[unsafe]]
2577 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckRightNullopt
) {
2578 ExpectDiagnosticsFor(
2580 #include "unchecked_optional_access_test
.h
"
2583 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2585 if (opt == $ns::nullopt) {
2586 opt.value(); // [[unsafe]]
2594 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckLeftNullopt
) {
2595 ExpectDiagnosticsFor(
2597 #include "unchecked_optional_access_test
.h
"
2600 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2602 if ($ns::nullopt == opt) {
2603 opt.value(); // [[unsafe]]
2611 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckRightValue
) {
2612 ExpectDiagnosticsFor(
2614 #include "unchecked_optional_access_test
.h
"
2617 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2622 opt.value(); // [[unsafe]]
2628 TEST_P(UncheckedOptionalAccessTest
, EqualityCheckLeftValue
) {
2629 ExpectDiagnosticsFor(
2631 #include "unchecked_optional_access_test
.h
"
2634 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2639 opt.value(); // [[unsafe]]
2645 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckLeftSet
) {
2646 ExpectDiagnosticsFor(
2648 #include "unchecked_optional_access_test
.h
"
2651 $ns::$optional<int> opt1 = 3;
2652 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2655 opt2.value(); // [[unsafe]]
2663 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckRightSet
) {
2664 ExpectDiagnosticsFor(
2666 #include "unchecked_optional_access_test
.h
"
2669 $ns::$optional<int> opt1 = 3;
2670 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2673 opt2.value(); // [[unsafe]]
2681 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckVerifySetAfterEq
) {
2682 ExpectDiagnosticsFor(
2684 #include "unchecked_optional_access_test
.h
"
2687 $ns::$optional<int> opt1 = Make<$ns::$optional<int>>();
2688 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2691 if (opt1.has_value())
2692 opt2.value(); // [[unsafe]]
2693 if (opt2.has_value())
2694 opt1.value(); // [[unsafe]]
2700 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckLeftUnset
) {
2701 ExpectDiagnosticsFor(
2703 #include "unchecked_optional_access_test
.h
"
2706 $ns::$optional<int> opt1 = $ns::nullopt;
2707 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2712 opt2.value(); // [[unsafe]]
2718 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckRightUnset
) {
2719 ExpectDiagnosticsFor(
2721 #include "unchecked_optional_access_test
.h
"
2724 $ns::$optional<int> opt1 = $ns::nullopt;
2725 $ns::$optional<int> opt2 = Make<$ns::$optional<int>>();
2730 opt2.value(); // [[unsafe]]
2736 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckRightNullopt
) {
2737 ExpectDiagnosticsFor(
2739 #include "unchecked_optional_access_test
.h
"
2742 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2744 if (opt != $ns::nullopt) {
2747 opt.value(); // [[unsafe]]
2753 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckLeftNullopt
) {
2754 ExpectDiagnosticsFor(
2756 #include "unchecked_optional_access_test
.h
"
2759 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2761 if ($ns::nullopt != opt) {
2764 opt.value(); // [[unsafe]]
2770 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckRightValue
) {
2771 ExpectDiagnosticsFor(
2773 #include "unchecked_optional_access_test
.h
"
2776 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2779 opt.value(); // [[unsafe]]
2787 TEST_P(UncheckedOptionalAccessTest
, InequalityCheckLeftValue
) {
2788 ExpectDiagnosticsFor(
2790 #include "unchecked_optional_access_test
.h
"
2793 $ns::$optional<int> opt = Make<$ns::$optional<int>>();
2796 opt.value(); // [[unsafe]]
2804 // Verifies that the model sees through aliases.
2805 TEST_P(UncheckedOptionalAccessTest
, WithAlias
) {
2806 ExpectDiagnosticsFor(
2808 #include "unchecked_optional_access_test
.h
"
2810 template <typename T>
2811 using MyOptional = $ns::$optional<T>;
2813 void target(MyOptional<int> opt) {
2814 opt.value(); // [[unsafe]]
2819 TEST_P(UncheckedOptionalAccessTest
, OptionalValueOptional
) {
2820 // Basic test that nested values are populated. We nest an optional because
2821 // its easy to use in a test, but the type of the nested value shouldn't
2823 ExpectDiagnosticsFor(
2825 #include "unchecked_optional_access_test
.h
"
2827 using Foo = $ns::$optional<std::string>;
2829 void target($ns::$optional<Foo> foo) {
2836 // Mutation is supported for nested values.
2837 ExpectDiagnosticsFor(
2839 #include "unchecked_optional_access_test
.h
"
2841 using Foo = $ns::$optional<std::string>;
2843 void target($ns::$optional<Foo> foo) {
2846 foo->value(); // [[unsafe]]
2852 TEST_P(UncheckedOptionalAccessTest
, NestedOptionalAssignValue
) {
2853 ExpectDiagnosticsFor(
2855 #include "unchecked_optional_access_test
.h
"
2857 using OptionalInt = $ns::$optional<int>;
2859 void target($ns::$optional<OptionalInt> opt) {
2862 // Accessing the outer optional is OK now.
2865 // But accessing the nested optional is still unsafe because we haven't
2867 **opt; // [[unsafe]]
2871 // Accessing the nested optional is safe after assigning a value to it.
2877 TEST_P(UncheckedOptionalAccessTest
, NestedOptionalAssignOptional
) {
2878 ExpectDiagnosticsFor(
2880 #include "unchecked_optional_access_test
.h
"
2882 using OptionalInt = $ns::$optional<int>;
2884 void target($ns::$optional<OptionalInt> opt) {
2887 // Accessing the outer optional is OK now.
2890 // But accessing the nested optional is still unsafe because we haven't
2892 **opt; // [[unsafe]]
2894 // Assign from `optional<short>` so that we trigger conversion assignment
2895 // instead of move assignment.
2896 *opt = $ns::$optional<short>();
2898 // Accessing the nested optional is still unsafe after assigning an empty
2900 **opt; // [[unsafe]]
2905 // Tests that structs can be nested. We use an optional field because its easy
2906 // to use in a test, but the type of the field shouldn't matter.
2907 TEST_P(UncheckedOptionalAccessTest
, OptionalValueStruct
) {
2908 ExpectDiagnosticsFor(
2910 #include "unchecked_optional_access_test
.h
"
2913 $ns::$optional<std::string> opt;
2916 void target($ns::$optional<Foo> foo) {
2917 if (foo && foo->opt) {
2924 // FIXME: A case that we should handle but currently don't.
2925 // When there is a field of type reference to non-optional, we may
2926 // stop recursively creating storage locations.
2927 // E.g., the field `second` below in `pair` should eventually lead to
2928 // the optional `x` in `A`.
2929 TEST_P(UncheckedOptionalAccessTest
, NestedOptionalThroughNonOptionalRefField
) {
2930 ExpectDiagnosticsFor(R
"(
2931 #include "unchecked_optional_access_test
.h
"
2934 $ns::$optional<int> x;
2943 $ns::$optional<pair>& nonConstGetRef();
2947 const auto& maybe_pair = b.nonConstGetRef();
2948 if (!maybe_pair.has_value())
2951 if(!maybe_pair->second.x.has_value())
2953 maybe_pair->second.x.value(); // [[unsafe]]
2958 TEST_P(UncheckedOptionalAccessTest
, OptionalValueInitialization
) {
2959 ExpectDiagnosticsFor(
2961 #include "unchecked_optional_access_test
.h
"
2963 using Foo = $ns::$optional<std::string>;
2965 void target($ns::$optional<Foo> foo, bool b) {
2966 if (!foo.has_value()) return;
2968 if (!foo->has_value()) return;
2969 // We have created `foo.value()`.
2972 if (!foo->has_value()) return;
2973 // We have created `foo.value()` again, in a different environment.
2976 // Now we merge the two values. UncheckedOptionalAccessModel::merge() will
2977 // throw away the "value
" property.
2983 // This test is aimed at the core model, not the diagnostic. It is a regression
2984 // test against a crash when using non-trivial smart pointers, like
2985 // `std::unique_ptr`. As such, it doesn't test the access itself, which would be
2986 // ignored regardless because of `IgnoreSmartPointerDereference = true`, above.
2987 TEST_P(UncheckedOptionalAccessTest
, AssignThroughLvalueReferencePtr
) {
2988 ExpectDiagnosticsFor(
2990 #include "unchecked_optional_access_test
.h
"
2992 template <typename T>
2994 typename std::add_lvalue_reference<T>::type operator*() &;
2998 smart_ptr<$ns::$optional<int>> x;
2999 // Verify that this assignment does not crash.
3005 TEST_P(UncheckedOptionalAccessTest
, CorrelatedBranches
) {
3006 ExpectDiagnosticsFor(R
"code(
3007 #include "unchecked_optional_access_test
.h
"
3009 void target(bool b, $ns::$optional<int> opt) {
3010 if (b || opt.has_value()) {
3018 ExpectDiagnosticsFor(R
"code(
3019 #include "unchecked_optional_access_test
.h
"
3021 void target(bool b, $ns::$optional<int> opt) {
3022 if (b && !opt.has_value()) return;
3029 ExpectDiagnosticsFor(
3031 #include "unchecked_optional_access_test
.h
"
3033 void target(bool b, $ns::$optional<int> opt) {
3034 if (opt.has_value()) b = true;
3036 opt.value(); // [[unsafe]]
3041 ExpectDiagnosticsFor(R
"code(
3042 #include "unchecked_optional_access_test
.h
"
3044 void target(bool b, $ns::$optional<int> opt) {
3046 if (opt.has_value()) b = true;
3053 ExpectDiagnosticsFor(R
"(
3054 #include "unchecked_optional_access_test
.h
"
3056 void target(bool b, $ns::$optional<int> opt) {
3057 if (opt.has_value() == b) {
3065 ExpectDiagnosticsFor(R
"(
3066 #include "unchecked_optional_access_test
.h
"
3068 void target(bool b, $ns::$optional<int> opt) {
3069 if (opt.has_value() != b) {
3077 ExpectDiagnosticsFor(R
"(
3078 #include "unchecked_optional_access_test
.h
"
3080 void target(bool b) {
3081 $ns::$optional<int> opt1 = $ns::nullopt;
3082 $ns::$optional<int> opt2;
3084 opt2 = $ns::nullopt;
3086 opt2 = $ns::nullopt;
3088 if (opt2.has_value()) {
3095 TEST_P(UncheckedOptionalAccessTest
, JoinDistinctValues
) {
3096 ExpectDiagnosticsFor(
3098 #include "unchecked_optional_access_test
.h
"
3100 void target(bool b) {
3101 $ns::$optional<int> opt;
3103 opt = Make<$ns::$optional<int>>();
3105 opt = Make<$ns::$optional<int>>();
3107 if (opt.has_value()) {
3110 opt.value(); // [[unsafe]]
3115 ExpectDiagnosticsFor(R
"code(
3116 #include "unchecked_optional_access_test
.h
"
3118 void target(bool b) {
3119 $ns::$optional<int> opt;
3121 opt = Make<$ns::$optional<int>>();
3122 if (!opt.has_value()) return;
3124 opt = Make<$ns::$optional<int>>();
3125 if (!opt.has_value()) return;
3131 ExpectDiagnosticsFor(
3133 #include "unchecked_optional_access_test
.h
"
3135 void target(bool b) {
3136 $ns::$optional<int> opt;
3138 opt = Make<$ns::$optional<int>>();
3139 if (!opt.has_value()) return;
3141 opt = Make<$ns::$optional<int>>();
3143 opt.value(); // [[unsafe]]
3147 ExpectDiagnosticsFor(
3149 #include "unchecked_optional_access_test
.h
"
3151 void target(bool b) {
3152 $ns::$optional<int> opt;
3162 ExpectDiagnosticsFor(
3164 #include "unchecked_optional_access_test
.h
"
3166 void target(bool b) {
3167 $ns::$optional<int> opt;
3171 opt = Make<$ns::$optional<int>>();
3173 opt.value(); // [[unsafe]]
3178 TEST_P(UncheckedOptionalAccessTest
, AccessValueInLoop
) {
3179 ExpectDiagnosticsFor(R
"(
3180 #include "unchecked_optional_access_test
.h
"
3183 $ns::$optional<int> opt = 3;
3184 while (Make<bool>()) {
3191 TEST_P(UncheckedOptionalAccessTest
, ReassignValueInLoopWithCheckSafe
) {
3192 ExpectDiagnosticsFor(R
"(
3193 #include "unchecked_optional_access_test
.h
"
3196 $ns::$optional<int> opt = 3;
3197 while (Make<bool>()) {
3200 opt = Make<$ns::$optional<int>>();
3201 if (!opt.has_value()) return;
3207 TEST_P(UncheckedOptionalAccessTest
, ReassignValueInLoopNoCheckUnsafe
) {
3208 ExpectDiagnosticsFor(
3210 #include "unchecked_optional_access_test
.h
"
3213 $ns::$optional<int> opt = 3;
3214 while (Make<bool>()) {
3215 opt.value(); // [[unsafe]]
3217 opt = Make<$ns::$optional<int>>();
3223 TEST_P(UncheckedOptionalAccessTest
, ReassignValueInLoopToUnsetUnsafe
) {
3224 ExpectDiagnosticsFor(
3226 #include "unchecked_optional_access_test
.h
"
3229 $ns::$optional<int> opt = 3;
3230 while (Make<bool>())
3232 $ns::$optional<int> opt2 = $ns::nullopt;
3233 if (opt.has_value())
3234 opt2 = $ns::$optional<int>(3);
3235 opt2.value(); // [[unsafe]]
3240 TEST_P(UncheckedOptionalAccessTest
, ReassignValueInLoopToSetUnsafe
) {
3241 ExpectDiagnosticsFor(
3243 #include "unchecked_optional_access_test
.h
"
3246 $ns::$optional<int> opt = $ns::nullopt;
3247 while (Make<bool>())
3248 opt = $ns::$optional<int>(3);
3249 $ns::$optional<int> opt2 = $ns::nullopt;
3250 if (!opt.has_value())
3251 opt2 = $ns::$optional<int>(3);
3252 opt2.value(); // [[unsafe]]
3257 TEST_P(UncheckedOptionalAccessTest
, ReassignValueInLoopToUnknownUnsafe
) {
3258 ExpectDiagnosticsFor(
3260 #include "unchecked_optional_access_test
.h
"
3263 $ns::$optional<int> opt = $ns::nullopt;
3264 while (Make<bool>())
3265 opt = Make<$ns::$optional<int>>();
3266 $ns::$optional<int> opt2 = $ns::nullopt;
3267 if (!opt.has_value())
3268 opt2 = $ns::$optional<int>(3);
3269 opt2.value(); // [[unsafe]]
3274 TEST_P(UncheckedOptionalAccessTest
, ReassignValueInLoopBadConditionUnsafe
) {
3275 ExpectDiagnosticsFor(
3277 #include "unchecked_optional_access_test
.h
"
3280 $ns::$optional<int> opt = 3;
3281 while (Make<bool>()) {
3282 opt.value(); // [[unsafe]]
3284 opt = Make<$ns::$optional<int>>();
3285 if (!opt.has_value()) continue;
3291 TEST_P(UncheckedOptionalAccessTest
, StructuredBindingsFromStruct
) {
3292 ExpectDiagnosticsFor(R
"(
3293 #include "unchecked_optional_access_test
.h
"
3295 struct kv { $ns::$optional<int> opt; int x; };
3297 auto [contents, x] = Make<kv>();
3298 return contents ? *contents : x;
3302 ExpectDiagnosticsFor(R
"(
3303 #include "unchecked_optional_access_test
.h
"
3305 template <typename T1, typename T2>
3306 struct pair { T1 fst; T2 snd; };
3308 auto [contents, x] = Make<pair<$ns::$optional<int>, int>>();
3309 return contents ? *contents : x;
3314 TEST_P(UncheckedOptionalAccessTest
, StructuredBindingsFromTupleLikeType
) {
3315 ExpectDiagnosticsFor(R
"(
3316 #include "unchecked_optional_access_test
.h
"
3319 template <class> struct tuple_size;
3320 template <size_t, class> struct tuple_element;
3321 template <class...> class tuple;
3323 template <class... T>
3324 struct tuple_size<tuple<T...>> : integral_constant<size_t, sizeof...(T)> {};
3326 template <size_t I, class... T>
3327 struct tuple_element<I, tuple<T...>> {
3328 using type = __type_pack_element<I, T...>;
3331 template <class...> class tuple {};
3332 template <size_t I, class... T>
3333 typename tuple_element<I, tuple<T...>>::type get(tuple<T...>);
3336 std::tuple<$ns::$optional<const char *>, int> get_opt();
3338 auto [content, ck] = get_opt();
3339 content ? *content : "";
3344 TEST_P(UncheckedOptionalAccessTest
, CtorInitializerNullopt
) {
3345 using namespace ast_matchers
;
3346 ExpectDiagnosticsFor(
3348 #include "unchecked_optional_access_test
.h
"
3351 Target(): opt($ns::nullopt) {
3352 opt.value(); // [[unsafe]]
3354 $ns::$optional<int> opt;
3357 cxxConstructorDecl(ofClass(hasName("Target"))));
3360 TEST_P(UncheckedOptionalAccessTest
, CtorInitializerValue
) {
3361 using namespace ast_matchers
;
3362 ExpectDiagnosticsFor(
3364 #include "unchecked_optional_access_test
.h
"
3370 $ns::$optional<int> opt;
3373 cxxConstructorDecl(ofClass(hasName("Target"))));
3376 // This is regression test, it shouldn't crash.
3377 TEST_P(UncheckedOptionalAccessTest
, Bitfield
) {
3378 using namespace ast_matchers
;
3379 ExpectDiagnosticsFor(
3381 #include "unchecked_optional_access_test
.h
"
3386 $ns::$optional<bool> v;
3394 TEST_P(UncheckedOptionalAccessTest
, LambdaParam
) {
3395 ExpectDiagnosticsForLambda(R
"(
3396 #include "unchecked_optional_access_test
.h
"
3399 []($ns::$optional<int> opt) {
3400 if (opt.has_value()) {
3403 opt.value(); // [[unsafe]]
3405 }(Make<$ns::$optional<int>>());
3410 TEST_P(UncheckedOptionalAccessTest
, LambdaCaptureByCopy
) {
3411 ExpectDiagnosticsForLambda(R
"(
3412 #include "unchecked_optional_access_test
.h
"
3414 void target($ns::$optional<int> opt) {
3416 if (opt.has_value()) {
3419 opt.value(); // [[unsafe]]
3426 TEST_P(UncheckedOptionalAccessTest
, LambdaCaptureByReference
) {
3427 ExpectDiagnosticsForLambda(R
"(
3428 #include "unchecked_optional_access_test
.h
"
3430 void target($ns::$optional<int> opt) {
3432 if (opt.has_value()) {
3435 opt.value(); // [[unsafe]]
3442 TEST_P(UncheckedOptionalAccessTest
, LambdaCaptureWithInitializer
) {
3443 ExpectDiagnosticsForLambda(R
"(
3444 #include "unchecked_optional_access_test
.h
"
3446 void target($ns::$optional<int> opt) {
3448 if (opt2.has_value()) {
3451 opt2.value(); // [[unsafe]]
3458 TEST_P(UncheckedOptionalAccessTest
, LambdaCaptureByCopyImplicit
) {
3459 ExpectDiagnosticsForLambda(R
"(
3460 #include "unchecked_optional_access_test
.h
"
3462 void target($ns::$optional<int> opt) {
3464 if (opt.has_value()) {
3467 opt.value(); // [[unsafe]]
3474 TEST_P(UncheckedOptionalAccessTest
, LambdaCaptureByReferenceImplicit
) {
3475 ExpectDiagnosticsForLambda(R
"(
3476 #include "unchecked_optional_access_test
.h
"
3478 void target($ns::$optional<int> opt) {
3480 if (opt.has_value()) {
3483 opt.value(); // [[unsafe]]
3490 TEST_P(UncheckedOptionalAccessTest
, LambdaCaptureThis
) {
3491 ExpectDiagnosticsForLambda(R
"(
3492 #include "unchecked_optional_access_test
.h
"
3495 $ns::$optional<int> opt;
3499 if (opt.has_value()) {
3502 opt.value(); // [[unsafe]]
3510 TEST_P(UncheckedOptionalAccessTest
, LambdaCaptureStateNotPropagated
) {
3511 // We can't propagate information from the surrounding context.
3512 ExpectDiagnosticsForLambda(R
"(
3513 #include "unchecked_optional_access_test
.h
"
3515 void target($ns::$optional<int> opt) {
3516 if (opt.has_value()) {
3518 opt.value(); // [[unsafe]]
3525 TEST_P(UncheckedOptionalAccessTest
, ClassDerivedFromOptional
) {
3526 ExpectDiagnosticsFor(R
"(
3527 #include "unchecked_optional_access_test
.h
"
3529 struct Derived : public $ns::$optional<int> {};
3531 void target(Derived opt) {
3533 if (opt.has_value())
3536 // The same thing, but with a pointer receiver.
3537 Derived *popt = &opt;
3538 **popt; // [[unsafe]]
3539 if (popt->has_value())
3545 TEST_P(UncheckedOptionalAccessTest
, ClassTemplateDerivedFromOptional
) {
3546 ExpectDiagnosticsFor(R
"(
3547 #include "unchecked_optional_access_test
.h
"
3550 struct Derived : public $ns::$optional<T> {};
3552 void target(Derived<int> opt) {
3554 if (opt.has_value())
3557 // The same thing, but with a pointer receiver.
3558 Derived<int> *popt = &opt;
3559 **popt; // [[unsafe]]
3560 if (popt->has_value())
3566 TEST_P(UncheckedOptionalAccessTest
, ClassDerivedPrivatelyFromOptional
) {
3567 // Classes that derive privately from optional can themselves still call
3568 // member functions of optional. Check that we model the optional correctly
3569 // in this situation.
3570 ExpectDiagnosticsFor(R
"(
3571 #include "unchecked_optional_access_test
.h
"
3573 struct Derived : private $ns::$optional<int> {
3575 **this; // [[unsafe]]
3576 if (this->has_value())
3581 ast_matchers::hasName("Method"));
3584 TEST_P(UncheckedOptionalAccessTest
, ClassDerivedFromOptionalValueConstructor
) {
3585 ExpectDiagnosticsFor(R
"(
3586 #include "unchecked_optional_access_test
.h
"
3588 struct Derived : public $ns::$optional<int> {
3592 void target(Derived opt) {
3600 TEST_P(UncheckedOptionalAccessTest
, ConstRefAccessor
) {
3601 ExpectDiagnosticsFor(R
"cc(
3602 #include "unchecked_optional_access_test
.h
"
3605 const $ns::$optional<int>& get() const { return x; }
3606 $ns::$optional<int> x;
3610 if (a.get().has_value()) {
3617 TEST_P(UncheckedOptionalAccessTest
, ConstRefAccessorWithModInBetween
) {
3618 ExpectDiagnosticsFor(R
"cc(
3619 #include "unchecked_optional_access_test
.h
"
3622 const $ns::$optional<int>& get() const { return x; }
3624 $ns::$optional<int> x;
3628 if (a.get().has_value()) {
3630 a.get().value(); // [[unsafe]]
3636 TEST_P(UncheckedOptionalAccessTest
, ConstRefAccessorWithModReturningOptional
) {
3637 ExpectDiagnosticsFor(R
"cc(
3638 #include "unchecked_optional_access_test
.h
"
3641 const $ns::$optional<int>& get() const { return x; }
3642 $ns::$optional<int> take();
3643 $ns::$optional<int> x;
3647 if (a.get().has_value()) {
3648 $ns::$optional<int> other = a.take();
3649 a.get().value(); // [[unsafe]]
3650 if (other.has_value()) {
3658 TEST_P(UncheckedOptionalAccessTest
, ConstRefAccessorDifferentObjects
) {
3659 ExpectDiagnosticsFor(R
"cc(
3660 #include "unchecked_optional_access_test
.h
"
3663 const $ns::$optional<int>& get() const { return x; }
3664 $ns::$optional<int> x;
3667 void target(A& a1, A& a2) {
3668 if (a1.get().has_value()) {
3669 a2.get().value(); // [[unsafe]]
3675 TEST_P(UncheckedOptionalAccessTest
, ConstRefAccessorLoop
) {
3676 ExpectDiagnosticsFor(R
"cc(
3677 #include "unchecked_optional_access_test
.h
"
3680 const $ns::$optional<int>& get() const { return x; }
3681 $ns::$optional<int> x;
3684 void target(A& a, int N) {
3685 for (int i = 0; i < N; ++i) {
3686 if (a.get().has_value()) {
3694 TEST_P(UncheckedOptionalAccessTest
, ConstByValueAccessor
) {
3695 ExpectDiagnosticsFor(R
"cc(
3696 #include "unchecked_optional_access_test
.h
"
3699 $ns::$optional<int> get() const { return x; }
3700 $ns::$optional<int> x;
3704 if (a.get().has_value()) {
3711 TEST_P(UncheckedOptionalAccessTest
, ConstByValueAccessorWithModInBetween
) {
3712 ExpectDiagnosticsFor(R
"cc(
3713 #include "unchecked_optional_access_test
.h
"
3716 $ns::$optional<int> get() const { return x; }
3718 $ns::$optional<int> x;
3722 if (a.get().has_value()) {
3724 a.get().value(); // [[unsafe]]
3730 TEST_P(UncheckedOptionalAccessTest
, ConstPointerAccessor
) {
3731 ExpectDiagnosticsFor(R
"cc(
3732 #include "unchecked_optional_access_test
.h
"
3735 $ns::$optional<int> x;
3738 struct MyUniquePtr {
3739 A* operator->() const;
3742 void target(MyUniquePtr p) {
3748 /*IgnoreSmartPointerDereference=*/false);
3751 TEST_P(UncheckedOptionalAccessTest
, ConstPointerAccessorWithModInBetween
) {
3752 ExpectDiagnosticsFor(R
"cc(
3753 #include "unchecked_optional_access_test
.h
"
3756 $ns::$optional<int> x;
3759 struct MyUniquePtr {
3760 A* operator->() const;
3764 void target(MyUniquePtr p) {
3767 *p->x; // [[unsafe]]
3771 /*IgnoreSmartPointerDereference=*/false);
3774 TEST_P(UncheckedOptionalAccessTest
, SmartPointerAccessorMixed
) {
3775 ExpectDiagnosticsFor(R
"cc(
3776 #include "unchecked_optional_access_test
.h
"
3779 $ns::$optional<int> x;
3783 template<typename T>
3788 const T& operator*() const&;
3791 const T* operator->() const;
3794 const T& value() const;
3799 void target(absl::StatusOr<A> &mut, const absl::StatusOr<A> &imm) {
3800 if (!mut.ok() || !imm.ok())
3803 if (mut->x.has_value()) {
3806 (mut.value().x).value();
3808 // check flagged after modifying
3810 mut->x.value(); // [[unsafe]]
3812 if (imm->x.has_value()) {
3815 (imm.value().x).value();
3819 /*IgnoreSmartPointerDereference=*/false);
3822 TEST_P(UncheckedOptionalAccessTest
, ConstBoolAccessor
) {
3823 ExpectDiagnosticsFor(R
"cc(
3824 #include "unchecked_optional_access_test
.h
"
3827 bool isFoo() const { return f; }
3832 std::optional<int> opt;
3843 TEST_P(UncheckedOptionalAccessTest
, ConstBoolAccessorWithModInBetween
) {
3844 ExpectDiagnosticsFor(R
"cc(
3845 #include "unchecked_optional_access_test
.h
"
3848 bool isFoo() const { return f; }
3854 std::optional<int> opt;
3860 opt.value(); // [[unsafe]]
3866 // FIXME: Add support for:
3867 // - constructors (copy, move)
3868 // - assignment operators (default, copy, move)
3869 // - invalidation (passing optional by non-const reference/pointer)