1 /*
2  * Copyright 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <android-base/expected.h>
20 #include <ftl/optional.h>
21 #include <ftl/unit.h>
22 
23 #include <utility>
24 
25 // Given an expression `expr` that evaluates to an ftl::Expected<T, E> result (R for short), FTL_TRY
26 // unwraps T out of R, or bails out of the enclosing function F if R has an error E. The return type
27 // of F must be R, since FTL_TRY propagates R in the error case. As a special case, ftl::Unit may be
28 // used as the error E to allow FTL_TRY expressions when F returns `void`.
29 //
30 // The non-standard syntax requires `-Wno-gnu-statement-expression-from-macro-expansion` to compile.
31 // The UnitToVoid conversion allows the macro to be used for early exit from a function that returns
32 // `void`.
33 //
34 // Example usage:
35 //
36 //   using StringExp = ftl::Expected<std::string, std::errc>;
37 //
38 //   StringExp repeat(StringExp exp) {
39 //     const std::string str = FTL_TRY(exp);
40 //     return StringExp(str + str);
41 //   }
42 //
43 //   assert(StringExp("haha"s) == repeat(StringExp("ha"s)));
44 //   assert(repeat(ftl::Unexpected(std::errc::bad_message)).has_error([](std::errc e) {
45 //     return e == std::errc::bad_message;
46 //   }));
47 //
48 //
49 // FTL_TRY may be used in void-returning functions by using ftl::Unit as the error type:
50 //
51 //   void uppercase(char& c, ftl::Optional<char> opt) {
52 //     c = std::toupper(FTL_TRY(std::move(opt).ok_or(ftl::Unit())));
53 //   }
54 //
55 //   char c = '?';
56 //   uppercase(c, std::nullopt);
57 //   assert(c == '?');
58 //
59 //   uppercase(c, 'a');
60 //   assert(c == 'A');
61 //
62 #define FTL_TRY(expr)                                                     \
63   ({                                                                      \
64     auto exp_ = (expr);                                                   \
65     if (!exp_.has_value()) {                                              \
66       using E = decltype(exp_)::error_type;                               \
67       return android::ftl::details::UnitToVoid<E>::from(std::move(exp_)); \
68     }                                                                     \
69     exp_.value();                                                         \
70   })
71 
72 // Given an expression `expr` that evaluates to an ftl::Expected<T, E> result (R for short),
73 // FTL_EXPECT unwraps T out of R, or bails out of the enclosing function F if R has an error E.
74 // While FTL_TRY bails out with R, FTL_EXPECT bails out with E, which is useful when F does not
75 // need to propagate R because T is not relevant to the caller.
76 //
77 // Example usage:
78 //
79 //   using StringExp = ftl::Expected<std::string, std::errc>;
80 //
81 //   std::errc repeat(StringExp exp, std::string& out) {
82 //     const std::string str = FTL_EXPECT(exp);
83 //     out = str + str;
84 //     return std::errc::operation_in_progress;
85 //   }
86 //
87 //   std::string str;
88 //   assert(std::errc::operation_in_progress == repeat(StringExp("ha"s), str));
89 //   assert("haha"s == str);
90 //   assert(std::errc::bad_message == repeat(ftl::Unexpected(std::errc::bad_message), str));
91 //   assert("haha"s == str);
92 //
93 #define FTL_EXPECT(expr)              \
94   ({                                  \
95     auto exp_ = (expr);               \
96     if (!exp_.has_value()) {          \
97       return std::move(exp_.error()); \
98     }                                 \
99     exp_.value();                     \
100   })
101 
102 namespace android::ftl {
103 
104 // Superset of base::expected<T, E> with monadic operations.
105 //
106 // TODO: Extend std::expected<T, E> in C++23.
107 //
108 template <typename T, typename E>
109 struct Expected final : base::expected<T, E> {
110   using Base = base::expected<T, E>;
111   using Base::expected;
112 
113   using Base::error;
114   using Base::has_value;
115   using Base::value;
116 
117   template <typename P>
has_errorfinal118   constexpr bool has_error(P predicate) const {
119     return !has_value() && predicate(error());
120   }
121 
value_optfinal122   constexpr Optional<T> value_opt() const& {
123     return has_value() ? Optional(value()) : std::nullopt;
124   }
125 
value_optfinal126   constexpr Optional<T> value_opt() && {
127     return has_value() ? Optional(std::move(value())) : std::nullopt;
128   }
129 
130   // Delete new for this class. Its base doesn't have a virtual destructor, and
131   // if it got deleted via base class pointer, it would cause undefined
132   // behavior. There's not a good reason to allocate this object on the heap
133   // anyway.
134   static void* operator new(size_t) = delete;
135   static void* operator new[](size_t) = delete;
136 };
137 
138 template <typename E>
Unexpected(E && error)139 constexpr auto Unexpected(E&& error) {
140   return base::unexpected(std::forward<E>(error));
141 }
142 
143 }  // namespace android::ftl
144