From eca7044361415db47b62326ae3235d97d4cb7420 Mon Sep 17 00:00:00 2001 From: Marcus Tillmanns Date: Thu, 24 Nov 2022 08:52:47 +0100 Subject: [PATCH] Utils: Add std::expected implementation Adds a std::expected implementation that is compatible with >= C++11. FilePath::fileContents and FilePath::writeFileContents as well as FilePath::copyFile are changed to return std::expected. A couple of macros have been added to aid in using the expected types. An auto test was added showing how to use the library. Change-Id: Ibe3aecfc1029a0cf13b45bf5184ff03a04a2393b Reviewed-by: Eike Ziller Reviewed-by: Qt CI Bot --- README.md | 12 + .../overview/creator-acknowledgements.qdoc | 14 + src/libs/3rdparty/tl_expected/COPYING | 121 + src/libs/3rdparty/tl_expected/README.md | 74 + .../tl_expected/include/tl/expected.hpp | 2342 +++++++++++++++++ src/libs/qmljs/qmljsmodelmanagerinterface.cpp | 4 +- src/libs/utils/CMakeLists.txt | 1 + src/libs/utils/devicefileaccess.cpp | 287 +- src/libs/utils/devicefileaccess.h | 74 +- src/libs/utils/elfreader.cpp | 5 +- src/libs/utils/expected.h | 47 + src/libs/utils/filepath.cpp | 64 +- src/libs/utils/filepath.h | 14 +- src/libs/utils/filesearch.cpp | 2 +- src/libs/utils/fileutils.cpp | 41 +- src/libs/utils/fsengine/fsengine_impl.cpp | 12 +- src/plugins/android/androidbuildapkstep.cpp | 4 +- .../cmakeprojectmanager/fileapiparser.cpp | 2 +- .../cmakeprojectmanager/presetsparser.cpp | 5 +- src/plugins/coreplugin/loggingviewer.cpp | 2 +- src/plugins/cppeditor/cpptoolsjsextension.cpp | 5 +- src/plugins/debugger/debuggerprotocol.cpp | 7 +- src/plugins/gitlab/gitlabparameters.cpp | 2 +- src/plugins/projectexplorer/extracompiler.cpp | 16 +- .../contentlibrarybundleimporter.cpp | 4 +- src/plugins/squish/scripthelper.cpp | 4 +- src/plugins/squish/squishtesttreeview.cpp | 4 +- src/plugins/squish/suiteconf.cpp | 12 +- src/plugins/valgrind/callgrindengine.cpp | 5 +- tests/auto/utils/CMakeLists.txt | 1 + tests/auto/utils/expected/CMakeLists.txt | 4 + tests/auto/utils/expected/expected.qbs | 7 + tests/auto/utils/expected/tst_expected.cpp | 38 + tests/auto/utils/fileutils/tst_fileutils.cpp | 14 +- tests/auto/utils/utils.qbs | 1 + 35 files changed, 2986 insertions(+), 265 deletions(-) create mode 100644 src/libs/3rdparty/tl_expected/COPYING create mode 100644 src/libs/3rdparty/tl_expected/README.md create mode 100644 src/libs/3rdparty/tl_expected/include/tl/expected.hpp create mode 100644 src/libs/utils/expected.h create mode 100644 tests/auto/utils/expected/CMakeLists.txt create mode 100644 tests/auto/utils/expected/expected.qbs create mode 100644 tests/auto/utils/expected/tst_expected.cpp diff --git a/README.md b/README.md index 50dd9152a0b..5666df9cb68 100644 --- a/README.md +++ b/README.md @@ -688,3 +688,15 @@ SQLite (https://www.sqlite.org) is in the Public Domain. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +### TartanLlama/expected + + Implementation of std::expected compatible with C++11/C++14/C++17. + + https://github.com/TartanLlama/expected + + To the extent possible under law, the author(s) have dedicated all + copyright and related and neighboring rights to this software to the + public domain worldwide. This software is distributed without any warranty. + + http://creativecommons.org/publicdomain/zero/1.0/ diff --git a/doc/qtcreator/src/overview/creator-acknowledgements.qdoc b/doc/qtcreator/src/overview/creator-acknowledgements.qdoc index 2be1ed05ef0..2ef5125bab2 100644 --- a/doc/qtcreator/src/overview/creator-acknowledgements.qdoc +++ b/doc/qtcreator/src/overview/creator-acknowledgements.qdoc @@ -988,5 +988,19 @@ SOFTWARE. \endcode + \li \b TartanLlama/expected + + Implementation of std::expected compatible with C++11/C++14/C++17. + + The sources can be found in: + \list + \li \c QtCreator/src/libs/3rdparty/tl_expected + \li \l https://github.com/TartanLlama/expected + \endlist + + CC0 1.0 Universal (CC0 1.0) Public Domain Dedication + + https://creativecommons.org/publicdomain/zero/1.0/ + \endlist */ diff --git a/src/libs/3rdparty/tl_expected/COPYING b/src/libs/3rdparty/tl_expected/COPYING new file mode 100644 index 00000000000..0e259d42c99 --- /dev/null +++ b/src/libs/3rdparty/tl_expected/COPYING @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/src/libs/3rdparty/tl_expected/README.md b/src/libs/3rdparty/tl_expected/README.md new file mode 100644 index 00000000000..2a837519b83 --- /dev/null +++ b/src/libs/3rdparty/tl_expected/README.md @@ -0,0 +1,74 @@ +# expected +Single header implementation of `std::expected` with functional-style extensions. + +[![Documentation Status](https://readthedocs.org/projects/tl-docs/badge/?version=latest)](https://tl.tartanllama.xyz/en/latest/?badge=latest) +Clang + GCC: [![Linux Build Status](https://github.com/TartanLlama/expected/actions/workflows/cmake.yml/badge.svg)](https://github.com/TartanLlama/expected/actions/workflows/cmake.yml) +MSVC: [![Windows Build Status](https://ci.appveyor.com/api/projects/status/k5x00xa11y3s5wsg?svg=true)](https://ci.appveyor.com/project/TartanLlama/expected) + +Available on [Vcpkg](https://github.com/microsoft/vcpkg/tree/master/ports/tl-expected) and [Conan](https://github.com/yipdw/conan-tl-expected). + +[`std::expected`](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0323r3.pdf) is proposed as the preferred way to represent object which will either have an expected value, or an unexpected value giving information about why something failed. Unfortunately, chaining together many computations which may fail can be verbose, as error-checking code will be mixed in with the actual programming logic. This implementation provides a number of utilities to make coding with `expected` cleaner. + +For example, instead of writing this code: + +```cpp +std::expected get_cute_cat (const image& img) { + auto cropped = crop_to_cat(img); + if (!cropped) { + return cropped; + } + + auto with_tie = add_bow_tie(*cropped); + if (!with_tie) { + return with_tie; + } + + auto with_sparkles = make_eyes_sparkle(*with_tie); + if (!with_sparkles) { + return with_sparkles; + } + + return add_rainbow(make_smaller(*with_sparkles)); +} +``` + +You can do this: + +```cpp +tl::expected get_cute_cat (const image& img) { + return crop_to_cat(img) + .and_then(add_bow_tie) + .and_then(make_eyes_sparkle) + .map(make_smaller) + .map(add_rainbow); +} +``` + +The interface is the same as `std::expected` as proposed in [p0323r3](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0323r3.pdf), but the following member functions are also defined. Explicit types are for clarity. + +- `map`: carries out some operation on the stored object if there is one. + * `tl::expected s = exp_string.map(&std::string::size);` +- `map_error`: carries out some operation on the unexpected object if there is one. + * `my_error_code translate_error (std::error_code);` + * `tl::expected s = exp_int.map_error(translate_error);` +- `and_then`: like `map`, but for operations which return a `tl::expected`. + * `tl::expected parse (const std::string& s);` + * `tl::expected exp_ast = exp_string.and_then(parse);` +- `or_else`: calls some function if there is no value stored. + * `exp.or_else([] { throw std::runtime_error{"oh no"}; });` + +### Compiler support + +Tested on: + +- Linux + * clang++ 3.5, 3.6, 3.7, 3.8, 3.9, 4, 5, 6, 7, 8, 9, 10, 11 + * g++ 4.8, 4.9, 5.5, 6.4, 7.5, 8, 9, 10 +- Windows + * MSVC 2015, 2017, 2019, 2022 + +---------- + +[![CC0](http://i.creativecommons.org/p/zero/1.0/88x31.png)]("http://creativecommons.org/publicdomain/zero/1.0/") + +To the extent possible under law, [Sy Brand](https://twitter.com/TartanLlama) has waived all copyright and related or neighboring rights to the `expected` library. This work is published from: United Kingdom. diff --git a/src/libs/3rdparty/tl_expected/include/tl/expected.hpp b/src/libs/3rdparty/tl_expected/include/tl/expected.hpp new file mode 100644 index 00000000000..d8ed472bdd1 --- /dev/null +++ b/src/libs/3rdparty/tl_expected/include/tl/expected.hpp @@ -0,0 +1,2342 @@ +/// +// expected - An implementation of std::expected with extensions +// Written in 2017 by Simon Brand (simonrbrand@gmail.com, @TartanLlama) +// +// Documentation available at http://tl.tartanllama.xyz/ +// +// To the extent possible under law, the author(s) have dedicated all +// copyright and related and neighboring rights to this software to the +// public domain worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication +// along with this software. If not, see +// . +/// + +#ifndef TL_EXPECTED_HPP +#define TL_EXPECTED_HPP + +#define TL_EXPECTED_VERSION_MAJOR 1 +#define TL_EXPECTED_VERSION_MINOR 0 +#define TL_EXPECTED_VERSION_PATCH 1 + +#include +#include +#include +#include + +#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) +#define TL_EXPECTED_EXCEPTIONS_ENABLED +#endif + +#if (defined(_MSC_VER) && _MSC_VER == 1900) +#define TL_EXPECTED_MSVC2015 +#define TL_EXPECTED_MSVC2015_CONSTEXPR +#else +#define TL_EXPECTED_MSVC2015_CONSTEXPR constexpr +#endif + +#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ + !defined(__clang__)) +#define TL_EXPECTED_GCC49 +#endif + +#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 4 && \ + !defined(__clang__)) +#define TL_EXPECTED_GCC54 +#endif + +#if (defined(__GNUC__) && __GNUC__ == 5 && __GNUC_MINOR__ <= 5 && \ + !defined(__clang__)) +#define TL_EXPECTED_GCC55 +#endif + +#if (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ <= 9 && \ + !defined(__clang__)) +// GCC < 5 doesn't support overloading on const&& for member functions + +#define TL_EXPECTED_NO_CONSTRR +// GCC < 5 doesn't support some standard C++11 type traits +#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ + std::has_trivial_copy_constructor +#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ + std::has_trivial_copy_assign + +// This one will be different for GCC 5.7 if it's ever supported +#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ + std::is_trivially_destructible + +// GCC 5 < v < 8 has a bug in is_trivially_copy_constructible which breaks std::vector +// for non-copyable types +#elif (defined(__GNUC__) && __GNUC__ < 8 && \ + !defined(__clang__)) +#ifndef TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX +#define TL_GCC_LESS_8_TRIVIALLY_COPY_CONSTRUCTIBLE_MUTEX +namespace tl { + namespace detail { + template + struct is_trivially_copy_constructible : std::is_trivially_copy_constructible{}; +#ifdef _GLIBCXX_VECTOR + template + struct is_trivially_copy_constructible> + : std::false_type{}; +#endif + } +} +#endif + +#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ + tl::detail::is_trivially_copy_constructible +#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ + std::is_trivially_copy_assignable +#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) std::is_trivially_destructible +#else +#define TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(T) \ + std::is_trivially_copy_constructible +#define TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(T) \ + std::is_trivially_copy_assignable +#define TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(T) \ + std::is_trivially_destructible +#endif + +#if __cplusplus > 201103L +#define TL_EXPECTED_CXX14 +#endif + +#ifdef TL_EXPECTED_GCC49 +#define TL_EXPECTED_GCC49_CONSTEXPR +#else +#define TL_EXPECTED_GCC49_CONSTEXPR constexpr +#endif + +#if (__cplusplus == 201103L || defined(TL_EXPECTED_MSVC2015) || \ + defined(TL_EXPECTED_GCC49)) +#define TL_EXPECTED_11_CONSTEXPR +#else +#define TL_EXPECTED_11_CONSTEXPR constexpr +#endif + +namespace tl { +template class expected; + +#ifndef TL_MONOSTATE_INPLACE_MUTEX +#define TL_MONOSTATE_INPLACE_MUTEX +class monostate {}; + +struct in_place_t { + explicit in_place_t() = default; +}; +static constexpr in_place_t in_place{}; +#endif + +template class unexpected { +public: + static_assert(!std::is_same::value, "E must not be void"); + + unexpected() = delete; + constexpr explicit unexpected(const E &e) : m_val(e) {} + + constexpr explicit unexpected(E &&e) : m_val(std::move(e)) {} + + constexpr const E &value() const & { return m_val; } + TL_EXPECTED_11_CONSTEXPR E &value() & { return m_val; } + TL_EXPECTED_11_CONSTEXPR E &&value() && { return std::move(m_val); } + constexpr const E &&value() const && { return std::move(m_val); } + +private: + E m_val; +}; + +template +constexpr bool operator==(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() == rhs.value(); +} +template +constexpr bool operator!=(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() != rhs.value(); +} +template +constexpr bool operator<(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() < rhs.value(); +} +template +constexpr bool operator<=(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() <= rhs.value(); +} +template +constexpr bool operator>(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() > rhs.value(); +} +template +constexpr bool operator>=(const unexpected &lhs, const unexpected &rhs) { + return lhs.value() >= rhs.value(); +} + +template +unexpected::type> make_unexpected(E &&e) { + return unexpected::type>(std::forward(e)); +} + +struct unexpect_t { + unexpect_t() = default; +}; +static constexpr unexpect_t unexpect{}; + +namespace detail { +template +[[noreturn]] TL_EXPECTED_11_CONSTEXPR void throw_exception(E &&e) { +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + throw std::forward(e); +#else + #ifdef _MSC_VER + __assume(0); + #else + __builtin_unreachable(); + #endif +#endif +} + +#ifndef TL_TRAITS_MUTEX +#define TL_TRAITS_MUTEX +// C++14-style aliases for brevity +template using remove_const_t = typename std::remove_const::type; +template +using remove_reference_t = typename std::remove_reference::type; +template using decay_t = typename std::decay::type; +template +using enable_if_t = typename std::enable_if::type; +template +using conditional_t = typename std::conditional::type; + +// std::conjunction from C++17 +template struct conjunction : std::true_type {}; +template struct conjunction : B {}; +template +struct conjunction + : std::conditional, B>::type {}; + +#if defined(_LIBCPP_VERSION) && __cplusplus == 201103L +#define TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND +#endif + +// In C++11 mode, there's an issue in libc++'s std::mem_fn +// which results in a hard-error when using it in a noexcept expression +// in some cases. This is a check to workaround the common failing case. +#ifdef TL_TRAITS_LIBCXX_MEM_FN_WORKAROUND +template struct is_pointer_to_non_const_member_func : std::false_type {}; +template +struct is_pointer_to_non_const_member_func : std::true_type {}; +template +struct is_pointer_to_non_const_member_func : std::true_type {}; +template +struct is_pointer_to_non_const_member_func : std::true_type {}; +template +struct is_pointer_to_non_const_member_func : std::true_type {}; +template +struct is_pointer_to_non_const_member_func : std::true_type {}; +template +struct is_pointer_to_non_const_member_func : std::true_type {}; + +template struct is_const_or_const_ref : std::false_type {}; +template struct is_const_or_const_ref : std::true_type {}; +template struct is_const_or_const_ref : std::true_type {}; +#endif + +// std::invoke from C++17 +// https://stackoverflow.com/questions/38288042/c11-14-invoke-workaround +template ::value + && is_const_or_const_ref::value)>, +#endif + typename = enable_if_t>::value>, + int = 0> + constexpr auto invoke(Fn && f, Args && ... args) noexcept( + noexcept(std::mem_fn(f)(std::forward(args)...))) + -> decltype(std::mem_fn(f)(std::forward(args)...)) { + return std::mem_fn(f)(std::forward(args)...); +} + +template >::value>> + constexpr auto invoke(Fn && f, Args && ... args) noexcept( + noexcept(std::forward(f)(std::forward(args)...))) + -> decltype(std::forward(f)(std::forward(args)...)) { + return std::forward(f)(std::forward(args)...); +} + +// std::invoke_result from C++17 +template struct invoke_result_impl; + +template +struct invoke_result_impl< + F, decltype(detail::invoke(std::declval(), std::declval()...), void()), + Us...> { + using type = decltype(detail::invoke(std::declval(), std::declval()...)); +}; + +template +using invoke_result = invoke_result_impl; + +template +using invoke_result_t = typename invoke_result::type; + +#if defined(_MSC_VER) && _MSC_VER <= 1900 +// TODO make a version which works with MSVC 2015 +template struct is_swappable : std::true_type {}; + +template struct is_nothrow_swappable : std::true_type {}; +#else +// https://stackoverflow.com/questions/26744589/what-is-a-proper-way-to-implement-is-swappable-to-test-for-the-swappable-concept +namespace swap_adl_tests { + // if swap ADL finds this then it would call std::swap otherwise (same + // signature) + struct tag {}; + + template tag swap(T&, T&); + template tag swap(T(&a)[N], T(&b)[N]); + + // helper functions to test if an unqualified swap is possible, and if it + // becomes std::swap + template std::false_type can_swap(...) noexcept(false); + template (), std::declval()))> + std::true_type can_swap(int) noexcept(noexcept(swap(std::declval(), + std::declval()))); + + template std::false_type uses_std(...); + template + std::is_same(), std::declval())), tag> + uses_std(int); + + template + struct is_std_swap_noexcept + : std::integral_constant::value&& + std::is_nothrow_move_assignable::value> {}; + + template + struct is_std_swap_noexcept : is_std_swap_noexcept {}; + + template + struct is_adl_swap_noexcept + : std::integral_constant(0))> {}; +} // namespace swap_adl_tests + +template +struct is_swappable + : std::integral_constant< + bool, + decltype(detail::swap_adl_tests::can_swap(0))::value && + (!decltype(detail::swap_adl_tests::uses_std(0))::value || + (std::is_move_assignable::value && + std::is_move_constructible::value))> {}; + +template +struct is_swappable + : std::integral_constant< + bool, + decltype(detail::swap_adl_tests::can_swap(0))::value && + (!decltype( + detail::swap_adl_tests::uses_std(0))::value || + is_swappable::value)> {}; + +template +struct is_nothrow_swappable + : std::integral_constant< + bool, + is_swappable::value && + ((decltype(detail::swap_adl_tests::uses_std(0))::value + && detail::swap_adl_tests::is_std_swap_noexcept::value) || + (!decltype(detail::swap_adl_tests::uses_std(0))::value && + detail::swap_adl_tests::is_adl_swap_noexcept::value))> { +}; +#endif +#endif + +// Trait for checking if a type is a tl::expected +template struct is_expected_impl : std::false_type {}; +template +struct is_expected_impl> : std::true_type {}; +template using is_expected = is_expected_impl>; + +template +using expected_enable_forward_value = detail::enable_if_t< + std::is_constructible::value && + !std::is_same, in_place_t>::value && + !std::is_same, detail::decay_t>::value && + !std::is_same, detail::decay_t>::value>; + +template +using expected_enable_from_other = detail::enable_if_t< + std::is_constructible::value && + std::is_constructible::value && + !std::is_constructible &>::value && + !std::is_constructible &&>::value && + !std::is_constructible &>::value && + !std::is_constructible &&>::value && + !std::is_convertible &, T>::value && + !std::is_convertible &&, T>::value && + !std::is_convertible &, T>::value && + !std::is_convertible &&, T>::value>; + +template +using is_void_or = conditional_t::value, std::true_type, U>; + +template +using is_copy_constructible_or_void = + is_void_or>; + +template +using is_move_constructible_or_void = + is_void_or>; + +template +using is_copy_assignable_or_void = + is_void_or>; + + +template +using is_move_assignable_or_void = + is_void_or>; + + +} // namespace detail + +namespace detail { +struct no_init_t {}; +static constexpr no_init_t no_init{}; + +// Implements the storage of the values, and ensures that the destructor is +// trivial if it can be. +// +// This specialization is for where neither `T` or `E` is trivially +// destructible, so the destructors must be called on destruction of the +// `expected` +template ::value, + bool = std::is_trivially_destructible::value> +struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&... args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&... args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&... args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&... args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (m_has_val) { + m_val.~T(); + } else { + m_unexpect.~unexpected(); + } + } + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// This specialization is for when both `T` and `E` are trivially-destructible, +// so the destructor of the `expected` can be trivial. +template struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&... args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&... args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&... args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&... args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() = default; + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// T is trivial, E is not. +template struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + TL_EXPECTED_MSVC2015_CONSTEXPR expected_storage_base(no_init_t) + : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&... args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&... args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&... args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&... args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (!m_has_val) { + m_unexpect.~unexpected(); + } + } + + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// E is trivial, T is not. +template struct expected_storage_base { + constexpr expected_storage_base() : m_val(T{}), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_no_init(), m_has_val(false) {} + + template ::value> * = + nullptr> + constexpr expected_storage_base(in_place_t, Args &&... args) + : m_val(std::forward(args)...), m_has_val(true) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected_storage_base(in_place_t, std::initializer_list il, + Args &&... args) + : m_val(il, std::forward(args)...), m_has_val(true) {} + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&... args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&... args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (m_has_val) { + m_val.~T(); + } + } + union { + T m_val; + unexpected m_unexpect; + char m_no_init; + }; + bool m_has_val; +}; + +// `T` is `void`, `E` is trivially-destructible +template struct expected_storage_base { + TL_EXPECTED_MSVC2015_CONSTEXPR expected_storage_base() : m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_val(), m_has_val(false) {} + + constexpr expected_storage_base(in_place_t) : m_has_val(true) {} + + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&... args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&... args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() = default; + struct dummy {}; + union { + unexpected m_unexpect; + dummy m_val; + }; + bool m_has_val; +}; + +// `T` is `void`, `E` is not trivially-destructible +template struct expected_storage_base { + constexpr expected_storage_base() : m_dummy(), m_has_val(true) {} + constexpr expected_storage_base(no_init_t) : m_dummy(), m_has_val(false) {} + + constexpr expected_storage_base(in_place_t) : m_dummy(), m_has_val(true) {} + + template ::value> * = + nullptr> + constexpr explicit expected_storage_base(unexpect_t, Args &&... args) + : m_unexpect(std::forward(args)...), m_has_val(false) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected_storage_base(unexpect_t, + std::initializer_list il, + Args &&... args) + : m_unexpect(il, std::forward(args)...), m_has_val(false) {} + + ~expected_storage_base() { + if (!m_has_val) { + m_unexpect.~unexpected(); + } + } + + union { + unexpected m_unexpect; + char m_dummy; + }; + bool m_has_val; +}; + +// This base class provides some handy member functions which can be used in +// further derived classes +template +struct expected_operations_base : expected_storage_base { + using expected_storage_base::expected_storage_base; + + template void construct(Args &&... args) noexcept { + new (std::addressof(this->m_val)) T(std::forward(args)...); + this->m_has_val = true; + } + + template void construct_with(Rhs &&rhs) noexcept { + new (std::addressof(this->m_val)) T(std::forward(rhs).get()); + this->m_has_val = true; + } + + template void construct_error(Args &&... args) noexcept { + new (std::addressof(this->m_unexpect)) + unexpected(std::forward(args)...); + this->m_has_val = false; + } + + #ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + + // These assign overloads ensure that the most efficient assignment + // implementation is used while maintaining the strong exception guarantee. + // The problematic case is where rhs has a value, but *this does not. + // + // This overload handles the case where we can just copy-construct `T` + // directly into place without throwing. + template ::value> + * = nullptr> + void assign(const expected_operations_base &rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(rhs.get()); + } else { + assign_common(rhs); + } + } + + // This overload handles the case where we can attempt to create a copy of + // `T`, then no-throw move it into place if the copy was successful. + template ::value && + std::is_nothrow_move_constructible::value> + * = nullptr> + void assign(const expected_operations_base &rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + T tmp = rhs.get(); + geterr().~unexpected(); + construct(std::move(tmp)); + } else { + assign_common(rhs); + } + } + + // This overload is the worst-case, where we have to move-construct the + // unexpected value into temporary storage, then try to copy the T into place. + // If the construction succeeds, then everything is fine, but if it throws, + // then we move the old unexpected value back into place before rethrowing the + // exception. + template ::value && + !std::is_nothrow_move_constructible::value> + * = nullptr> + void assign(const expected_operations_base &rhs) { + if (!this->m_has_val && rhs.m_has_val) { + auto tmp = std::move(geterr()); + geterr().~unexpected(); + +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + construct(rhs.get()); + } catch (...) { + geterr() = std::move(tmp); + throw; + } +#else + construct(rhs.get()); +#endif + } else { + assign_common(rhs); + } + } + + // These overloads do the same as above, but for rvalues + template ::value> + * = nullptr> + void assign(expected_operations_base &&rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(std::move(rhs).get()); + } else { + assign_common(std::move(rhs)); + } + } + + template ::value> + * = nullptr> + void assign(expected_operations_base &&rhs) { + if (!this->m_has_val && rhs.m_has_val) { + auto tmp = std::move(geterr()); + geterr().~unexpected(); +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + construct(std::move(rhs).get()); + } catch (...) { + geterr() = std::move(tmp); + throw; + } +#else + construct(std::move(rhs).get()); +#endif + } else { + assign_common(std::move(rhs)); + } + } + + #else + + // If exceptions are disabled then we can just copy-construct + void assign(const expected_operations_base &rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(rhs.get()); + } else { + assign_common(rhs); + } + } + + void assign(expected_operations_base &&rhs) noexcept { + if (!this->m_has_val && rhs.m_has_val) { + geterr().~unexpected(); + construct(std::move(rhs).get()); + } else { + assign_common(rhs); + } + } + + #endif + + // The common part of move/copy assigning + template void assign_common(Rhs &&rhs) { + if (this->m_has_val) { + if (rhs.m_has_val) { + get() = std::forward(rhs).get(); + } else { + destroy_val(); + construct_error(std::forward(rhs).geterr()); + } + } else { + if (!rhs.m_has_val) { + geterr() = std::forward(rhs).geterr(); + } + } + } + + bool has_value() const { return this->m_has_val; } + + TL_EXPECTED_11_CONSTEXPR T &get() & { return this->m_val; } + constexpr const T &get() const & { return this->m_val; } + TL_EXPECTED_11_CONSTEXPR T &&get() && { return std::move(this->m_val); } +#ifndef TL_EXPECTED_NO_CONSTRR + constexpr const T &&get() const && { return std::move(this->m_val); } +#endif + + TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { + return this->m_unexpect; + } + constexpr const unexpected &geterr() const & { return this->m_unexpect; } + TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { + return std::move(this->m_unexpect); + } +#ifndef TL_EXPECTED_NO_CONSTRR + constexpr const unexpected &&geterr() const && { + return std::move(this->m_unexpect); + } +#endif + + TL_EXPECTED_11_CONSTEXPR void destroy_val() { + get().~T(); + } +}; + +// This base class provides some handy member functions which can be used in +// further derived classes +template +struct expected_operations_base : expected_storage_base { + using expected_storage_base::expected_storage_base; + + template void construct() noexcept { this->m_has_val = true; } + + // This function doesn't use its argument, but needs it so that code in + // levels above this can work independently of whether T is void + template void construct_with(Rhs &&) noexcept { + this->m_has_val = true; + } + + template void construct_error(Args &&... args) noexcept { + new (std::addressof(this->m_unexpect)) + unexpected(std::forward(args)...); + this->m_has_val = false; + } + + template void assign(Rhs &&rhs) noexcept { + if (!this->m_has_val) { + if (rhs.m_has_val) { + geterr().~unexpected(); + construct(); + } else { + geterr() = std::forward(rhs).geterr(); + } + } else { + if (!rhs.m_has_val) { + construct_error(std::forward(rhs).geterr()); + } + } + } + + bool has_value() const { return this->m_has_val; } + + TL_EXPECTED_11_CONSTEXPR unexpected &geterr() & { + return this->m_unexpect; + } + constexpr const unexpected &geterr() const & { return this->m_unexpect; } + TL_EXPECTED_11_CONSTEXPR unexpected &&geterr() && { + return std::move(this->m_unexpect); + } +#ifndef TL_EXPECTED_NO_CONSTRR + constexpr const unexpected &&geterr() const && { + return std::move(this->m_unexpect); + } +#endif + + TL_EXPECTED_11_CONSTEXPR void destroy_val() { + //no-op + } +}; + +// This class manages conditionally having a trivial copy constructor +// This specialization is for when T and E are trivially copy constructible +template :: + value &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value> +struct expected_copy_base : expected_operations_base { + using expected_operations_base::expected_operations_base; +}; + +// This specialization is for when T or E are not trivially copy constructible +template +struct expected_copy_base : expected_operations_base { + using expected_operations_base::expected_operations_base; + + expected_copy_base() = default; + expected_copy_base(const expected_copy_base &rhs) + : expected_operations_base(no_init) { + if (rhs.has_value()) { + this->construct_with(rhs); + } else { + this->construct_error(rhs.geterr()); + } + } + + expected_copy_base(expected_copy_base &&rhs) = default; + expected_copy_base &operator=(const expected_copy_base &rhs) = default; + expected_copy_base &operator=(expected_copy_base &&rhs) = default; +}; + +// This class manages conditionally having a trivial move constructor +// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it +// doesn't implement an analogue to std::is_trivially_move_constructible. We +// have to make do with a non-trivial move constructor even if T is trivially +// move constructible +#ifndef TL_EXPECTED_GCC49 +template >::value + &&std::is_trivially_move_constructible::value> +struct expected_move_base : expected_copy_base { + using expected_copy_base::expected_copy_base; +}; +#else +template struct expected_move_base; +#endif +template +struct expected_move_base : expected_copy_base { + using expected_copy_base::expected_copy_base; + + expected_move_base() = default; + expected_move_base(const expected_move_base &rhs) = default; + + expected_move_base(expected_move_base &&rhs) noexcept( + std::is_nothrow_move_constructible::value) + : expected_copy_base(no_init) { + if (rhs.has_value()) { + this->construct_with(std::move(rhs)); + } else { + this->construct_error(std::move(rhs.geterr())); + } + } + expected_move_base &operator=(const expected_move_base &rhs) = default; + expected_move_base &operator=(expected_move_base &&rhs) = default; +}; + +// This class manages conditionally having a trivial copy assignment operator +template >::value + &&TL_EXPECTED_IS_TRIVIALLY_COPY_ASSIGNABLE(E)::value + &&TL_EXPECTED_IS_TRIVIALLY_COPY_CONSTRUCTIBLE(E)::value + &&TL_EXPECTED_IS_TRIVIALLY_DESTRUCTIBLE(E)::value> +struct expected_copy_assign_base : expected_move_base { + using expected_move_base::expected_move_base; +}; + +template +struct expected_copy_assign_base : expected_move_base { + using expected_move_base::expected_move_base; + + expected_copy_assign_base() = default; + expected_copy_assign_base(const expected_copy_assign_base &rhs) = default; + + expected_copy_assign_base(expected_copy_assign_base &&rhs) = default; + expected_copy_assign_base &operator=(const expected_copy_assign_base &rhs) { + this->assign(rhs); + return *this; + } + expected_copy_assign_base & + operator=(expected_copy_assign_base &&rhs) = default; +}; + +// This class manages conditionally having a trivial move assignment operator +// Unfortunately there's no way to achieve this in GCC < 5 AFAIK, since it +// doesn't implement an analogue to std::is_trivially_move_assignable. We have +// to make do with a non-trivial move assignment operator even if T is trivially +// move assignable +#ifndef TL_EXPECTED_GCC49 +template , + std::is_trivially_move_constructible, + std::is_trivially_move_assignable>>:: + value &&std::is_trivially_destructible::value + &&std::is_trivially_move_constructible::value + &&std::is_trivially_move_assignable::value> +struct expected_move_assign_base : expected_copy_assign_base { + using expected_copy_assign_base::expected_copy_assign_base; +}; +#else +template struct expected_move_assign_base; +#endif + +template +struct expected_move_assign_base + : expected_copy_assign_base { + using expected_copy_assign_base::expected_copy_assign_base; + + expected_move_assign_base() = default; + expected_move_assign_base(const expected_move_assign_base &rhs) = default; + + expected_move_assign_base(expected_move_assign_base &&rhs) = default; + + expected_move_assign_base & + operator=(const expected_move_assign_base &rhs) = default; + + expected_move_assign_base & + operator=(expected_move_assign_base &&rhs) noexcept( + std::is_nothrow_move_constructible::value + &&std::is_nothrow_move_assignable::value) { + this->assign(std::move(rhs)); + return *this; + } +}; + +// expected_delete_ctor_base will conditionally delete copy and move +// constructors depending on whether T is copy/move constructible +template ::value && + std::is_copy_constructible::value), + bool EnableMove = (is_move_constructible_or_void::value && + std::is_move_constructible::value)> +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +template +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +template +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = default; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +template +struct expected_delete_ctor_base { + expected_delete_ctor_base() = default; + expected_delete_ctor_base(const expected_delete_ctor_base &) = delete; + expected_delete_ctor_base(expected_delete_ctor_base &&) noexcept = delete; + expected_delete_ctor_base & + operator=(const expected_delete_ctor_base &) = default; + expected_delete_ctor_base & + operator=(expected_delete_ctor_base &&) noexcept = default; +}; + +// expected_delete_assign_base will conditionally delete copy and move +// constructors depending on whether T and E are copy/move constructible + +// assignable +template ::value && + std::is_copy_constructible::value && + is_copy_assignable_or_void::value && + std::is_copy_assignable::value), + bool EnableMove = (is_move_constructible_or_void::value && + std::is_move_constructible::value && + is_move_assignable_or_void::value && + std::is_move_assignable::value)> +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = default; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = default; +}; + +template +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = default; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = delete; +}; + +template +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = delete; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = default; +}; + +template +struct expected_delete_assign_base { + expected_delete_assign_base() = default; + expected_delete_assign_base(const expected_delete_assign_base &) = default; + expected_delete_assign_base(expected_delete_assign_base &&) noexcept = + default; + expected_delete_assign_base & + operator=(const expected_delete_assign_base &) = delete; + expected_delete_assign_base & + operator=(expected_delete_assign_base &&) noexcept = delete; +}; + +// This is needed to be able to construct the expected_default_ctor_base which +// follows, while still conditionally deleting the default constructor. +struct default_constructor_tag { + explicit constexpr default_constructor_tag() = default; +}; + +// expected_default_ctor_base will ensure that expected has a deleted default +// consturctor if T is not default constructible. +// This specialization is for when T is default constructible +template ::value || std::is_void::value> +struct expected_default_ctor_base { + constexpr expected_default_ctor_base() noexcept = default; + constexpr expected_default_ctor_base( + expected_default_ctor_base const &) noexcept = default; + constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = + default; + expected_default_ctor_base & + operator=(expected_default_ctor_base const &) noexcept = default; + expected_default_ctor_base & + operator=(expected_default_ctor_base &&) noexcept = default; + + constexpr explicit expected_default_ctor_base(default_constructor_tag) {} +}; + +// This specialization is for when T is not default constructible +template struct expected_default_ctor_base { + constexpr expected_default_ctor_base() noexcept = delete; + constexpr expected_default_ctor_base( + expected_default_ctor_base const &) noexcept = default; + constexpr expected_default_ctor_base(expected_default_ctor_base &&) noexcept = + default; + expected_default_ctor_base & + operator=(expected_default_ctor_base const &) noexcept = default; + expected_default_ctor_base & + operator=(expected_default_ctor_base &&) noexcept = default; + + constexpr explicit expected_default_ctor_base(default_constructor_tag) {} +}; +} // namespace detail + +template class bad_expected_access : public std::exception { +public: + explicit bad_expected_access(E e) : m_val(std::move(e)) {} + + virtual const char *what() const noexcept override { + return "Bad expected access"; + } + + const E &error() const & { return m_val; } + E &error() & { return m_val; } + const E &&error() const && { return std::move(m_val); } + E &&error() && { return std::move(m_val); } + +private: + E m_val; +}; + +/// An `expected` object is an object that contains the storage for +/// another object and manages the lifetime of this contained object `T`. +/// Alternatively it could contain the storage for another unexpected object +/// `E`. The contained object may not be initialized after the expected object +/// has been initialized, and may not be destroyed before the expected object +/// has been destroyed. The initialization state of the contained object is +/// tracked by the expected object. +template +class expected : private detail::expected_move_assign_base, + private detail::expected_delete_ctor_base, + private detail::expected_delete_assign_base, + private detail::expected_default_ctor_base { + static_assert(!std::is_reference::value, "T must not be a reference"); + static_assert(!std::is_same::type>::value, + "T must not be in_place_t"); + static_assert(!std::is_same::type>::value, + "T must not be unexpect_t"); + static_assert(!std::is_same>::type>::value, + "T must not be unexpected"); + static_assert(!std::is_reference::value, "E must not be a reference"); + + T *valptr() { return std::addressof(this->m_val); } + const T *valptr() const { return std::addressof(this->m_val); } + unexpected *errptr() { return std::addressof(this->m_unexpect); } + const unexpected *errptr() const { return std::addressof(this->m_unexpect); } + + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &val() { + return this->m_val; + } + TL_EXPECTED_11_CONSTEXPR unexpected &err() { return this->m_unexpect; } + + template ::value> * = nullptr> + constexpr const U &val() const { + return this->m_val; + } + constexpr const unexpected &err() const { return this->m_unexpect; } + + using impl_base = detail::expected_move_assign_base; + using ctor_base = detail::expected_default_ctor_base; + +public: + typedef T value_type; + typedef E error_type; + typedef unexpected unexpected_type; + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) & { + return and_then_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) && { + return and_then_impl(std::move(*this), std::forward(f)); + } + template constexpr auto and_then(F &&f) const & { + return and_then_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template constexpr auto and_then(F &&f) const && { + return and_then_impl(std::move(*this), std::forward(f)); + } +#endif + +#else + template + TL_EXPECTED_11_CONSTEXPR auto + and_then(F &&f) & -> decltype(and_then_impl(std::declval(), std::forward(f))) { + return and_then_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR auto and_then(F &&f) && -> decltype( + and_then_impl(std::declval(), std::forward(f))) { + return and_then_impl(std::move(*this), std::forward(f)); + } + template + constexpr auto and_then(F &&f) const & -> decltype( + and_then_impl(std::declval(), std::forward(f))) { + return and_then_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr auto and_then(F &&f) const && -> decltype( + and_then_impl(std::declval(), std::forward(f))) { + return and_then_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto map(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template constexpr auto map(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + template constexpr auto map(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#else + template + TL_EXPECTED_11_CONSTEXPR decltype( + expected_map_impl(std::declval(), std::declval())) + map(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR decltype( + expected_map_impl(std::declval(), std::declval())) + map(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + map(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + map(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template TL_EXPECTED_11_CONSTEXPR auto transform(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template constexpr auto transform(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + template constexpr auto transform(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#else + template + TL_EXPECTED_11_CONSTEXPR decltype( + expected_map_impl(std::declval(), std::declval())) + transform(F &&f) & { + return expected_map_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR decltype( + expected_map_impl(std::declval(), std::declval())) + transform(F &&f) && { + return expected_map_impl(std::move(*this), std::forward(f)); + } + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + transform(F &&f) const & { + return expected_map_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr decltype(expected_map_impl(std::declval(), + std::declval())) + transform(F &&f) const && { + return expected_map_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) + template + TL_EXPECTED_11_CONSTEXPR auto transform_or(F &&f) & + { + return transform_or_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR auto transform_or(F &&f) && + { + return transform_or_impl(std::move(*this), std::forward(f)); + } + template + constexpr auto transform_or(F &&f) const & + { + return transform_or_impl(*this, std::forward(f)); + } + template + constexpr auto transform_or(F &&f) const && + { + return transform_or_impl(std::move(*this), std::forward(f)); + } +#else + template + TL_EXPECTED_11_CONSTEXPR decltype(transform_or_impl(std::declval(), + std::declval())) + transform_or(F &&f) & + { + return transform_or_impl(*this, std::forward(f)); + } + template + TL_EXPECTED_11_CONSTEXPR decltype(transform_or_impl(std::declval(), + std::declval())) + transform_or(F &&f) && + { + return transform_or_impl(std::move(*this), std::forward(f)); + } + template + constexpr decltype(transform_or_impl(std::declval(), std::declval())) + transform_or(F &&f) const & + { + return transform_or_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template + constexpr decltype(transform_or_impl(std::declval(), std::declval())) + transform_or(F &&f) const && + { + return transform_or_impl(std::move(*this), std::forward(f)); + } +#endif +#endif + template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) & { + return or_else_impl(*this, std::forward(f)); + } + + template expected TL_EXPECTED_11_CONSTEXPR or_else(F &&f) && { + return or_else_impl(std::move(*this), std::forward(f)); + } + + template expected constexpr or_else(F &&f) const & { + return or_else_impl(*this, std::forward(f)); + } + +#ifndef TL_EXPECTED_NO_CONSTRR + template expected constexpr or_else(F &&f) const && { + return or_else_impl(std::move(*this), std::forward(f)); + } +#endif + constexpr expected() = default; + constexpr expected(const expected &rhs) = default; + constexpr expected(expected &&rhs) = default; + expected &operator=(const expected &rhs) = default; + expected &operator=(expected &&rhs) = default; + + template ::value> * = + nullptr> + constexpr expected(in_place_t, Args &&... args) + : impl_base(in_place, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template &, Args &&...>::value> * = nullptr> + constexpr expected(in_place_t, std::initializer_list il, Args &&... args) + : impl_base(in_place, il, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template ::value> * = + nullptr, + detail::enable_if_t::value> * = + nullptr> + explicit constexpr expected(const unexpected &e) + : impl_base(unexpect, e.value()), + ctor_base(detail::default_constructor_tag{}) {} + + template < + class G = E, + detail::enable_if_t::value> * = + nullptr, + detail::enable_if_t::value> * = nullptr> + constexpr expected(unexpected const &e) + : impl_base(unexpect, e.value()), + ctor_base(detail::default_constructor_tag{}) {} + + template < + class G = E, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t::value> * = nullptr> + explicit constexpr expected(unexpected &&e) noexcept( + std::is_nothrow_constructible::value) + : impl_base(unexpect, std::move(e.value())), + ctor_base(detail::default_constructor_tag{}) {} + + template < + class G = E, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t::value> * = nullptr> + constexpr expected(unexpected &&e) noexcept( + std::is_nothrow_constructible::value) + : impl_base(unexpect, std::move(e.value())), + ctor_base(detail::default_constructor_tag{}) {} + + template ::value> * = + nullptr> + constexpr explicit expected(unexpect_t, Args &&... args) + : impl_base(unexpect, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template &, Args &&...>::value> * = nullptr> + constexpr explicit expected(unexpect_t, std::initializer_list il, + Args &&... args) + : impl_base(unexpect, il, std::forward(args)...), + ctor_base(detail::default_constructor_tag{}) {} + + template ::value && + std::is_convertible::value)> * = + nullptr, + detail::expected_enable_from_other + * = nullptr> + explicit TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(*rhs); + } else { + this->construct_error(rhs.error()); + } + } + + template ::value && + std::is_convertible::value)> * = + nullptr, + detail::expected_enable_from_other + * = nullptr> + TL_EXPECTED_11_CONSTEXPR expected(const expected &rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(*rhs); + } else { + this->construct_error(rhs.error()); + } + } + + template < + class U, class G, + detail::enable_if_t::value && + std::is_convertible::value)> * = nullptr, + detail::expected_enable_from_other * = nullptr> + explicit TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(std::move(*rhs)); + } else { + this->construct_error(std::move(rhs.error())); + } + } + + template < + class U, class G, + detail::enable_if_t<(std::is_convertible::value && + std::is_convertible::value)> * = nullptr, + detail::expected_enable_from_other * = nullptr> + TL_EXPECTED_11_CONSTEXPR expected(expected &&rhs) + : ctor_base(detail::default_constructor_tag{}) { + if (rhs.has_value()) { + this->construct(std::move(*rhs)); + } else { + this->construct_error(std::move(rhs.error())); + } + } + + template < + class U = T, + detail::enable_if_t::value> * = nullptr, + detail::expected_enable_forward_value * = nullptr> + explicit TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) + : expected(in_place, std::forward(v)) {} + + template < + class U = T, + detail::enable_if_t::value> * = nullptr, + detail::expected_enable_forward_value * = nullptr> + TL_EXPECTED_MSVC2015_CONSTEXPR expected(U &&v) + : expected(in_place, std::forward(v)) {} + + template < + class U = T, class G = T, + detail::enable_if_t::value> * = + nullptr, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t< + (!std::is_same, detail::decay_t>::value && + !detail::conjunction, + std::is_same>>::value && + std::is_constructible::value && + std::is_assignable::value && + std::is_nothrow_move_constructible::value)> * = nullptr> + expected &operator=(U &&v) { + if (has_value()) { + val() = std::forward(v); + } else { + err().~unexpected(); + ::new (valptr()) T(std::forward(v)); + this->m_has_val = true; + } + + return *this; + } + + template < + class U = T, class G = T, + detail::enable_if_t::value> * = + nullptr, + detail::enable_if_t::value> * = nullptr, + detail::enable_if_t< + (!std::is_same, detail::decay_t>::value && + !detail::conjunction, + std::is_same>>::value && + std::is_constructible::value && + std::is_assignable::value && + std::is_nothrow_move_constructible::value)> * = nullptr> + expected &operator=(U &&v) { + if (has_value()) { + val() = std::forward(v); + } else { + auto tmp = std::move(err()); + err().~unexpected(); + + #ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (valptr()) T(std::forward(v)); + this->m_has_val = true; + } catch (...) { + err() = std::move(tmp); + throw; + } + #else + ::new (valptr()) T(std::forward(v)); + this->m_has_val = true; + #endif + } + + return *this; + } + + template ::value && + std::is_assignable::value> * = nullptr> + expected &operator=(const unexpected &rhs) { + if (!has_value()) { + err() = rhs; + } else { + this->destroy_val(); + ::new (errptr()) unexpected(rhs); + this->m_has_val = false; + } + + return *this; + } + + template ::value && + std::is_move_assignable::value> * = nullptr> + expected &operator=(unexpected &&rhs) noexcept { + if (!has_value()) { + err() = std::move(rhs); + } else { + this->destroy_val(); + ::new (errptr()) unexpected(std::move(rhs)); + this->m_has_val = false; + } + + return *this; + } + + template ::value> * = nullptr> + void emplace(Args &&... args) { + if (has_value()) { + val() = T(std::forward(args)...); + } else { + err().~unexpected(); + ::new (valptr()) T(std::forward(args)...); + this->m_has_val = true; + } + } + + template ::value> * = nullptr> + void emplace(Args &&... args) { + if (has_value()) { + val() = T(std::forward(args)...); + } else { + auto tmp = std::move(err()); + err().~unexpected(); + + #ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (valptr()) T(std::forward(args)...); + this->m_has_val = true; + } catch (...) { + err() = std::move(tmp); + throw; + } + #else + ::new (valptr()) T(std::forward(args)...); + this->m_has_val = true; + #endif + } + } + + template &, Args &&...>::value> * = nullptr> + void emplace(std::initializer_list il, Args &&... args) { + if (has_value()) { + T t(il, std::forward(args)...); + val() = std::move(t); + } else { + err().~unexpected(); + ::new (valptr()) T(il, std::forward(args)...); + this->m_has_val = true; + } + } + + template &, Args &&...>::value> * = nullptr> + void emplace(std::initializer_list il, Args &&... args) { + if (has_value()) { + T t(il, std::forward(args)...); + val() = std::move(t); + } else { + auto tmp = std::move(err()); + err().~unexpected(); + + #ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (valptr()) T(il, std::forward(args)...); + this->m_has_val = true; + } catch (...) { + err() = std::move(tmp); + throw; + } + #else + ::new (valptr()) T(il, std::forward(args)...); + this->m_has_val = true; + #endif + } + } + +private: + using t_is_void = std::true_type; + using t_is_not_void = std::false_type; + using t_is_nothrow_move_constructible = std::true_type; + using move_constructing_t_can_throw = std::false_type; + using e_is_nothrow_move_constructible = std::true_type; + using move_constructing_e_can_throw = std::false_type; + + void swap_where_both_have_value(expected &/*rhs*/ , t_is_void) noexcept { + // swapping void is a no-op + } + + void swap_where_both_have_value(expected &rhs, t_is_not_void) { + using std::swap; + swap(val(), rhs.val()); + } + + void swap_where_only_one_has_value(expected &rhs, t_is_void) noexcept( + std::is_nothrow_move_constructible::value) { + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + std::swap(this->m_has_val, rhs.m_has_val); + } + + void swap_where_only_one_has_value(expected &rhs, t_is_not_void) { + swap_where_only_one_has_value_and_t_is_not_void( + rhs, typename std::is_nothrow_move_constructible::type{}, + typename std::is_nothrow_move_constructible::type{}); + } + + void swap_where_only_one_has_value_and_t_is_not_void( + expected &rhs, t_is_nothrow_move_constructible, + e_is_nothrow_move_constructible) noexcept { + auto temp = std::move(val()); + val().~T(); + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + ::new (rhs.valptr()) T(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); + } + + void swap_where_only_one_has_value_and_t_is_not_void( + expected &rhs, t_is_nothrow_move_constructible, + move_constructing_e_can_throw) { + auto temp = std::move(val()); + val().~T(); +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + ::new (rhs.valptr()) T(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); + } catch (...) { + val() = std::move(temp); + throw; + } +#else + ::new (errptr()) unexpected_type(std::move(rhs.err())); + rhs.err().~unexpected_type(); + ::new (rhs.valptr()) T(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); +#endif + } + + void swap_where_only_one_has_value_and_t_is_not_void( + expected &rhs, move_constructing_t_can_throw, + t_is_nothrow_move_constructible) { + auto temp = std::move(rhs.err()); + rhs.err().~unexpected_type(); +#ifdef TL_EXPECTED_EXCEPTIONS_ENABLED + try { + ::new (rhs.valptr()) T(val()); + val().~T(); + ::new (errptr()) unexpected_type(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); + } catch (...) { + rhs.err() = std::move(temp); + throw; + } +#else + ::new (rhs.valptr()) T(val()); + val().~T(); + ::new (errptr()) unexpected_type(std::move(temp)); + std::swap(this->m_has_val, rhs.m_has_val); +#endif + } + +public: + template + detail::enable_if_t::value && + detail::is_swappable::value && + (std::is_nothrow_move_constructible::value || + std::is_nothrow_move_constructible::value)> + swap(expected &rhs) noexcept( + std::is_nothrow_move_constructible::value + &&detail::is_nothrow_swappable::value + &&std::is_nothrow_move_constructible::value + &&detail::is_nothrow_swappable::value) { + if (has_value() && rhs.has_value()) { + swap_where_both_have_value(rhs, typename std::is_void::type{}); + } else if (!has_value() && rhs.has_value()) { + rhs.swap(*this); + } else if (has_value()) { + swap_where_only_one_has_value(rhs, typename std::is_void::type{}); + } else { + using std::swap; + swap(err(), rhs.err()); + } + } + + constexpr const T *operator->() const { return valptr(); } + TL_EXPECTED_11_CONSTEXPR T *operator->() { return valptr(); } + + template ::value> * = nullptr> + constexpr const U &operator*() const & { + return val(); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &operator*() & { + return val(); + } + template ::value> * = nullptr> + constexpr const U &&operator*() const && { + return std::move(val()); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &&operator*() && { + return std::move(val()); + } + + constexpr bool has_value() const noexcept { return this->m_has_val; } + constexpr explicit operator bool() const noexcept { return this->m_has_val; } + + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR const U &value() const & { + if (!has_value()) + detail::throw_exception(bad_expected_access(err().value())); + return val(); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &value() & { + if (!has_value()) + detail::throw_exception(bad_expected_access(err().value())); + return val(); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR const U &&value() const && { + if (!has_value()) + detail::throw_exception(bad_expected_access(std::move(err()).value())); + return std::move(val()); + } + template ::value> * = nullptr> + TL_EXPECTED_11_CONSTEXPR U &&value() && { + if (!has_value()) + detail::throw_exception(bad_expected_access(std::move(err()).value())); + return std::move(val()); + } + + constexpr const E &error() const & { return err().value(); } + TL_EXPECTED_11_CONSTEXPR E &error() & { return err().value(); } + constexpr const E &&error() const && { return std::move(err().value()); } + TL_EXPECTED_11_CONSTEXPR E &&error() && { return std::move(err().value()); } + + template constexpr T value_or(U &&v) const & { + static_assert(std::is_copy_constructible::value && + std::is_convertible::value, + "T must be copy-constructible and convertible to from U&&"); + return bool(*this) ? **this : static_cast(std::forward(v)); + } + template TL_EXPECTED_11_CONSTEXPR T value_or(U &&v) && { + static_assert(std::is_move_constructible::value && + std::is_convertible::value, + "T must be move-constructible and convertible to from U&&"); + return bool(*this) ? std::move(**this) : static_cast(std::forward(v)); + } +}; + +namespace detail { +template using exp_t = typename detail::decay_t::value_type; +template using err_t = typename detail::decay_t::error_type; +template using ret_t = expected>; + +#ifdef TL_EXPECTED_CXX14 +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval()))> +constexpr auto and_then_impl(Exp &&exp, F &&f) { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() + ? detail::invoke(std::forward(f), *std::forward(exp)) + : Ret(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval()))> +constexpr auto and_then_impl(Exp &&exp, F &&f) { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() ? detail::invoke(std::forward(f)) + : Ret(unexpect, std::forward(exp).error()); +} +#else +template struct TC; +template (), + *std::declval())), + detail::enable_if_t>::value> * = nullptr> +auto and_then_impl(Exp &&exp, F &&f) -> Ret { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() + ? detail::invoke(std::forward(f), *std::forward(exp)) + : Ret(unexpect, std::forward(exp).error()); +} + +template ())), + detail::enable_if_t>::value> * = nullptr> +constexpr auto and_then_impl(Exp &&exp, F &&f) -> Ret { + static_assert(detail::is_expected::value, "F must return an expected"); + + return exp.has_value() ? detail::invoke(std::forward(f)) + : Ret(unexpect, std::forward(exp).error()); +} +#endif + +#ifdef TL_EXPECTED_CXX14 +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> +constexpr auto expected_map_impl(Exp &&exp, F &&f) { + using result = ret_t>; + return exp.has_value() ? result(detail::invoke(std::forward(f), + *std::forward(exp))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> +auto expected_map_impl(Exp &&exp, F &&f) { + using result = expected>; + if (exp.has_value()) { + detail::invoke(std::forward(f), *std::forward(exp)); + return result(); + } + + return result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> +constexpr auto expected_map_impl(Exp &&exp, F &&f) { + using result = ret_t>; + return exp.has_value() ? result(detail::invoke(std::forward(f))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> +auto expected_map_impl(Exp &&exp, F &&f) { + using result = expected>; + if (exp.has_value()) { + detail::invoke(std::forward(f)); + return result(); + } + + return result(unexpect, std::forward(exp).error()); +} +#else +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> + +constexpr auto expected_map_impl(Exp &&exp, F &&f) + -> ret_t> { + using result = ret_t>; + + return exp.has_value() ? result(detail::invoke(std::forward(f), + *std::forward(exp))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), + *std::declval())), + detail::enable_if_t::value> * = nullptr> + +auto expected_map_impl(Exp &&exp, F &&f) -> expected> { + if (exp.has_value()) { + detail::invoke(std::forward(f), *std::forward(exp)); + return {}; + } + + return unexpected>(std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> + +constexpr auto expected_map_impl(Exp &&exp, F &&f) + -> ret_t> { + using result = ret_t>; + + return exp.has_value() ? result(detail::invoke(std::forward(f))) + : result(unexpect, std::forward(exp).error()); +} + +template >::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval())), + detail::enable_if_t::value> * = nullptr> + +auto expected_map_impl(Exp &&exp, F &&f) -> expected> { + if (exp.has_value()) { + detail::invoke(std::forward(f)); + return {}; + } + + return unexpected>(std::forward(exp).error()); +} +#endif + +#if defined(TL_EXPECTED_CXX14) && !defined(TL_EXPECTED_GCC49) && \ + !defined(TL_EXPECTED_GCC54) && !defined(TL_EXPECTED_GCC55) +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto transform_or_impl(Exp &&exp, F &&f) +{ + using result = expected, detail::decay_t>; + return exp.has_value() + ? result(*std::forward(exp)) + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto transform_or_impl(Exp &&exp, F &&f) +{ + using result = expected, monostate>; + if (exp.has_value()) { + return result(*std::forward(exp)); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto transform_or_impl(Exp &&exp, F &&f) +{ + using result = expected, detail::decay_t>; + return exp.has_value() + ? result() + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto transform_or_impl(Exp &&exp, F &&f) +{ + using result = expected, monostate>; + if (exp.has_value()) { + return result(); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} +#else +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto transform_or_impl(Exp &&exp, F &&f) -> expected, detail::decay_t> +{ + using result = expected, detail::decay_t>; + + return exp.has_value() + ? result(*std::forward(exp)) + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} + +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto transform_or_impl(Exp &&exp, F &&f) -> expected, monostate> +{ + using result = expected, monostate>; + if (exp.has_value()) { + return result(*std::forward(exp)); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} + +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto transform_or_impl(Exp &&exp, F &&f) -> expected, detail::decay_t> +{ + using result = expected, detail::decay_t>; + + return exp.has_value() + ? result() + : result(unexpect, detail::invoke(std::forward(f), + std::forward(exp).error())); +} + +template>::value> * = nullptr, + class Ret = decltype(detail::invoke(std::declval(), std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto transform_or_impl(Exp &&exp, F &&f) -> expected, monostate> +{ + using result = expected, monostate>; + if (exp.has_value()) { + return result(); + } + + detail::invoke(std::forward(f), std::forward(exp).error()); + return result(unexpect, monostate{}); +} +#endif + +#ifdef TL_EXPECTED_CXX14 +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +constexpr auto or_else_impl(Exp &&exp, F &&f) { + static_assert(detail::is_expected::value, "F must return an expected"); + return exp.has_value() + ? std::forward(exp) + : detail::invoke(std::forward(f), std::forward(exp).error()); +} + +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +detail::decay_t or_else_impl(Exp &&exp, F &&f) { + return exp.has_value() + ? std::forward(exp) + : (detail::invoke(std::forward(f), std::forward(exp).error()), + std::forward(exp)); +} +#else +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +auto or_else_impl(Exp &&exp, F &&f) -> Ret { + static_assert(detail::is_expected::value, "F must return an expected"); + return exp.has_value() + ? std::forward(exp) + : detail::invoke(std::forward(f), std::forward(exp).error()); +} + +template (), + std::declval().error())), + detail::enable_if_t::value> * = nullptr> +detail::decay_t or_else_impl(Exp &&exp, F &&f) { + return exp.has_value() + ? std::forward(exp) + : (detail::invoke(std::forward(f), std::forward(exp).error()), + std::forward(exp)); +} +#endif +} // namespace detail + +template +constexpr bool operator==(const expected &lhs, + const expected &rhs) { + return (lhs.has_value() != rhs.has_value()) + ? false + : (!lhs.has_value() ? lhs.error() == rhs.error() : *lhs == *rhs); +} +template +constexpr bool operator!=(const expected &lhs, + const expected &rhs) { + return (lhs.has_value() != rhs.has_value()) + ? true + : (!lhs.has_value() ? lhs.error() != rhs.error() : *lhs != *rhs); +} + +template +constexpr bool operator==(const expected &x, const U &v) { + return x.has_value() ? *x == v : false; +} +template +constexpr bool operator==(const U &v, const expected &x) { + return x.has_value() ? *x == v : false; +} +template +constexpr bool operator!=(const expected &x, const U &v) { + return x.has_value() ? *x != v : true; +} +template +constexpr bool operator!=(const U &v, const expected &x) { + return x.has_value() ? *x != v : true; +} + +template +constexpr bool operator==(const expected &x, const unexpected &e) { + return x.has_value() ? false : x.error() == e.value(); +} +template +constexpr bool operator==(const unexpected &e, const expected &x) { + return x.has_value() ? false : x.error() == e.value(); +} +template +constexpr bool operator!=(const expected &x, const unexpected &e) { + return x.has_value() ? true : x.error() != e.value(); +} +template +constexpr bool operator!=(const unexpected &e, const expected &x) { + return x.has_value() ? true : x.error() != e.value(); +} + +template ::value || + std::is_move_constructible::value) && + detail::is_swappable::value && + std::is_move_constructible::value && + detail::is_swappable::value> * = nullptr> +void swap(expected &lhs, + expected &rhs) noexcept(noexcept(lhs.swap(rhs))) { + lhs.swap(rhs); +} +} // namespace tl + +#endif diff --git a/src/libs/qmljs/qmljsmodelmanagerinterface.cpp b/src/libs/qmljs/qmljsmodelmanagerinterface.cpp index 71bd55119be..9ba1d43fcf7 100644 --- a/src/libs/qmljs/qmljsmodelmanagerinterface.cpp +++ b/src/libs/qmljs/qmljsmodelmanagerinterface.cpp @@ -875,7 +875,7 @@ static bool findNewQmlLibraryInPath(const Utils::FilePath &path, } // found a new library! - const std::optional contents = qmldirFile.fileContents(); + const expected_str contents = qmldirFile.fileContents(); if (!contents) return false; QString qmldirData = QString::fromUtf8(*contents); @@ -985,7 +985,7 @@ void ModelManagerInterface::parseLoop(QSet &scannedPaths, contents = entry.first; documentRevision = entry.second; } else { - const std::optional fileContents = fileName.fileContents(); + const expected_str fileContents = fileName.fileContents(); if (fileContents) { QTextStream ins(*fileContents); contents = ins.readAll(); diff --git a/src/libs/utils/CMakeLists.txt b/src/libs/utils/CMakeLists.txt index 9d3fb078fb4..e3edc86c15c 100644 --- a/src/libs/utils/CMakeLists.txt +++ b/src/libs/utils/CMakeLists.txt @@ -42,6 +42,7 @@ add_qtc_library(Utils environmentmodel.cpp environmentmodel.h execmenu.cpp execmenu.h executeondestruction.h + expected.h fadingindicator.cpp fadingindicator.h faketooltip.cpp faketooltip.h fancylineedit.cpp fancylineedit.h diff --git a/src/libs/utils/devicefileaccess.cpp b/src/libs/utils/devicefileaccess.cpp index 0814cc29ff8..4a2119b4f5c 100644 --- a/src/libs/utils/devicefileaccess.cpp +++ b/src/libs/utils/devicefileaccess.cpp @@ -6,8 +6,10 @@ #include "algorithm.h" #include "commandline.h" #include "environment.h" +#include "expected.h" #include "hostosinfo.h" #include "qtcassert.h" +#include "utilstr.h" #include #include @@ -18,8 +20,8 @@ #ifdef QTCREATOR_PCH_H #define CALLBACK WINAPI #endif -#include #include +#include #else #include #endif @@ -137,12 +139,13 @@ bool DeviceFileAccess::removeRecursively(const FilePath &filePath, QString *erro return false; } -bool DeviceFileAccess::copyFile(const FilePath &filePath, const FilePath &target) const +expected_str DeviceFileAccess::copyFile(const FilePath &filePath, const FilePath &target) const { Q_UNUSED(filePath) Q_UNUSED(target) QTC_CHECK(false); - return false; + return make_unexpected( + Tr::tr("copyFile is not implemented for \"%1\"").arg(filePath.toUserOutput())); } bool DeviceFileAccess::renameFile(const FilePath &filePath, const FilePath &target) const @@ -166,10 +169,9 @@ FilePath DeviceFileAccess::symLinkTarget(const FilePath &filePath) const return {}; } -void DeviceFileAccess::iterateDirectory( - const FilePath &filePath, - const FilePath::IterateDirCallback &callBack, - const FileFilter &filter) const +void DeviceFileAccess::iterateDirectory(const FilePath &filePath, + const FilePath::IterateDirCallback &callBack, + const FileFilter &filter) const { Q_UNUSED(filePath) Q_UNUSED(callBack) @@ -177,28 +179,28 @@ void DeviceFileAccess::iterateDirectory( QTC_CHECK(false); } -std::optional DeviceFileAccess::fileContents( - const FilePath &filePath, - qint64 limit, - qint64 offset) const +expected_str DeviceFileAccess::fileContents(const FilePath &filePath, + qint64 limit, + qint64 offset) const { Q_UNUSED(filePath) Q_UNUSED(limit) Q_UNUSED(offset) QTC_CHECK(false); - return {}; + return make_unexpected( + Tr::tr("fileContents is not implemented for \"%1\"").arg(filePath.toUserOutput())); } -bool DeviceFileAccess::writeFileContents( - const FilePath &filePath, - const QByteArray &data, - qint64 offset) const +expected_str DeviceFileAccess::writeFileContents(const FilePath &filePath, + const QByteArray &data, + qint64 offset) const { Q_UNUSED(filePath) Q_UNUSED(data) Q_UNUSED(offset) QTC_CHECK(false); - return false; + return make_unexpected( + Tr::tr("writeFileContents is not implemented for \"%1\"").arg(filePath.toUserOutput())); } FilePathInfo DeviceFileAccess::filePathInfo(const FilePath &filePath) const @@ -251,8 +253,7 @@ QByteArray DeviceFileAccess::fileId(const FilePath &filePath) const } std::optional DeviceFileAccess::refersToExecutableFile( - const FilePath &filePath, - FilePath::MatchScope matchScope) const + const FilePath &filePath, FilePath::MatchScope matchScope) const { Q_UNUSED(matchScope) if (isExecutableFile(filePath)) @@ -260,33 +261,29 @@ std::optional DeviceFileAccess::refersToExecutableFile( return {}; } -void DeviceFileAccess::asyncFileContents( - const FilePath &filePath, - const Continuation> &cont, - qint64 limit, - qint64 offset) const +void DeviceFileAccess::asyncFileContents(const FilePath &filePath, + const Continuation> &cont, + qint64 limit, + qint64 offset) const { cont(fileContents(filePath, limit, offset)); } -void DeviceFileAccess::asyncWriteFileContents( - const FilePath &filePath, - const Continuation &cont, - const QByteArray &data, - qint64 offset) const +void DeviceFileAccess::asyncWriteFileContents(const FilePath &filePath, + const Continuation> &cont, + const QByteArray &data, + qint64 offset) const { cont(writeFileContents(filePath, data, offset)); } -void DeviceFileAccess::asyncCopyFile( - const FilePath &filePath, - const Continuation &cont, - const FilePath &target) const +void DeviceFileAccess::asyncCopyFile(const FilePath &filePath, + const Continuation> &cont, + const FilePath &target) const { cont(copyFile(filePath, target)); } - // DesktopDeviceFileAccess DesktopDeviceFileAccess::~DesktopDeviceFileAccess() = default; @@ -303,8 +300,8 @@ bool DesktopDeviceFileAccess::isExecutableFile(const FilePath &filePath) const return fi.isExecutable() && !fi.isDir(); } -static std::optional isWindowsExecutableHelper - (const FilePath &filePath, const QStringView suffix) +static std::optional isWindowsExecutableHelper(const FilePath &filePath, + const QStringView suffix) { const QFileInfo fi(filePath.path().append(suffix)); if (!fi.isExecutable() || fi.isDir()) @@ -314,8 +311,7 @@ static std::optional isWindowsExecutableHelper } std::optional DesktopDeviceFileAccess::refersToExecutableFile( - const FilePath &filePath, - FilePath::MatchScope matchScope) const + const FilePath &filePath, FilePath::MatchScope matchScope) const { if (isExecutableFile(filePath)) return filePath; @@ -432,36 +428,38 @@ bool DesktopDeviceFileAccess::removeRecursively(const FilePath &filePath, QStrin if (dir.isRoot()) { if (error) { *error = QCoreApplication::translate("Utils::FileUtils", - "Refusing to remove root directory."); + "Refusing to remove root directory."); } return false; } if (dir.path() == QDir::home().canonicalPath()) { if (error) { *error = QCoreApplication::translate("Utils::FileUtils", - "Refusing to remove your home directory."); + "Refusing to remove your home directory."); } return false; } - const QStringList fileNames = dir.entryList( - QDir::Files | QDir::Hidden | QDir::System | QDir::Dirs | QDir::NoDotAndDotDot); + const QStringList fileNames = dir.entryList(QDir::Files | QDir::Hidden | QDir::System + | QDir::Dirs | QDir::NoDotAndDotDot); for (const QString &fileName : fileNames) { if (!removeRecursively(filePath / fileName, error)) return false; } if (!QDir::root().rmdir(dir.path())) { if (error) { - *error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove directory \"%1\".") - .arg(filePath.toUserOutput()); + *error = QCoreApplication::translate("Utils::FileUtils", + "Failed to remove directory \"%1\".") + .arg(filePath.toUserOutput()); } return false; } } else { if (!QFile::remove(filePath.path())) { if (error) { - *error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove file \"%1\".") - .arg(filePath.toUserOutput()); + *error = QCoreApplication::translate("Utils::FileUtils", + "Failed to remove file \"%1\".") + .arg(filePath.toUserOutput()); } return false; } @@ -469,9 +467,14 @@ bool DesktopDeviceFileAccess::removeRecursively(const FilePath &filePath, QStrin return true; } -bool DesktopDeviceFileAccess::copyFile(const FilePath &filePath, const FilePath &target) const +expected_str DesktopDeviceFileAccess::copyFile(const FilePath &filePath, + const FilePath &target) const { - return QFile::copy(filePath.path(), target.path()); + if (QFile::copy(filePath.path(), target.path())) + return {}; + return make_unexpected(Tr::tr("Failed to copy file \"%1\" to \"%2\".") + .arg(filePath.toUserOutput()) + .arg(target.toUserOutput())); } bool DesktopDeviceFileAccess::renameFile(const FilePath &filePath, const FilePath &target) const @@ -514,10 +517,9 @@ FilePath DesktopDeviceFileAccess::symLinkTarget(const FilePath &filePath) const return FilePath::fromString(info.symLinkTarget()); } -void DesktopDeviceFileAccess::iterateDirectory( - const FilePath &filePath, - const FilePath::IterateDirCallback &callBack, - const FileFilter &filter) const +void DesktopDeviceFileAccess::iterateDirectory(const FilePath &filePath, + const FilePath::IterateDirCallback &callBack, + const FileFilter &filter) const { QDirIterator it(filePath.path(), filter.nameFilters, filter.fileFilters, filter.iteratorFlags); while (it.hasNext()) { @@ -532,18 +534,17 @@ void DesktopDeviceFileAccess::iterateDirectory( } } -std::optional DesktopDeviceFileAccess::fileContents( - const FilePath &filePath, - qint64 limit, - qint64 offset) const +expected_str DesktopDeviceFileAccess::fileContents(const FilePath &filePath, + qint64 limit, + qint64 offset) const { const QString path = filePath.path(); QFile f(path); if (!f.exists()) - return {}; + return make_unexpected(Tr::tr("File \"%1\" does not exist").arg(path)); if (!f.open(QFile::ReadOnly)) - return {}; + return make_unexpected(Tr::tr("Could not open File \"%1\"").arg(path)); if (offset != 0) f.seek(offset); @@ -551,21 +552,35 @@ std::optional DesktopDeviceFileAccess::fileContents( if (limit != -1) return f.read(limit); - return f.readAll(); + const QByteArray data = f.readAll(); + if (f.error() != QFile::NoError) { + return make_unexpected( + Tr::tr("Cannot read \"%1\": %2").arg(filePath.toUserOutput(), f.errorString())); + } + + return data; } -bool DesktopDeviceFileAccess::writeFileContents( - const FilePath &filePath, - const QByteArray &data, - qint64 offset) const +expected_str DesktopDeviceFileAccess::writeFileContents(const FilePath &filePath, + const QByteArray &data, + qint64 offset) const { QFile file(filePath.path()); const bool isOpened = file.open(QFile::WriteOnly | QFile::Truncate); - QTC_ASSERT(isOpened, return false); + if (!isOpened) + return make_unexpected( + Tr::tr("Could not open file \"%1\" for writing").arg(filePath.toUserOutput())); + if (offset != 0) file.seek(offset); qint64 res = file.write(data); - return res == data.size(); + if (res != data.size()) + return make_unexpected( + Tr::tr("Could not write to file \"%1\" (only %2 of %3 bytes written)") + .arg(filePath.toUserOutput()) + .arg(res) + .arg(data.size())); + return res; } QDateTime DesktopDeviceFileAccess::lastModified(const FilePath &filePath) const @@ -603,7 +618,9 @@ static inline QByteArray fileIdWin7(HANDLE handle) BY_HANDLE_FILE_INFORMATION info; if (GetFileInformationByHandle(handle, &info)) { char buffer[sizeof "01234567:0123456701234567\0"]; - qsnprintf(buffer, sizeof(buffer), "%lx:%08lx%08lx", + qsnprintf(buffer, + sizeof(buffer), + "%lx:%08lx%08lx", info.dwVolumeSerialNumber, info.nFileIndexHigh, info.nFileIndexLow); @@ -618,20 +635,25 @@ static QByteArray fileIdWin8(HANDLE handle) QByteArray result; FILE_ID_INFO infoEx; if (GetFileInformationByHandleEx(handle, - static_cast(18), // FileIdInfo in Windows 8 - &infoEx, sizeof(FILE_ID_INFO))) { + static_cast( + 18), // FileIdInfo in Windows 8 + &infoEx, + sizeof(FILE_ID_INFO))) { result = QByteArray::number(infoEx.VolumeSerialNumber, 16); result += ':'; // Note: MinGW-64's definition of FILE_ID_128 differs from the MSVC one. - result += QByteArray(reinterpret_cast(&infoEx.FileId), int(sizeof(infoEx.FileId))).toHex(); + result += QByteArray(reinterpret_cast(&infoEx.FileId), + int(sizeof(infoEx.FileId))) + .toHex(); } return result; } static QByteArray fileIdWin(HANDLE fHandle) { - return QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows8 ? - fileIdWin8(HANDLE(fHandle)) : fileIdWin7(HANDLE(fHandle)); + return QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows8 + ? fileIdWin8(HANDLE(fHandle)) + : fileIdWin7(HANDLE(fHandle)); } #endif @@ -640,10 +662,13 @@ QByteArray DesktopDeviceFileAccess::fileId(const FilePath &filePath) const QByteArray result; #ifdef Q_OS_WIN - const HANDLE handle = - CreateFile((wchar_t*)filePath.toUserOutput().utf16(), 0, - FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_FLAG_BACKUP_SEMANTICS, NULL); + const HANDLE handle = CreateFile((wchar_t *) filePath.toUserOutput().utf16(), + 0, + FILE_SHARE_READ, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, + NULL); if (handle != INVALID_HANDLE_VALUE) { result = fileIdWin(handle); CloseHandle(handle); @@ -668,7 +693,6 @@ OsType DesktopDeviceFileAccess::osType(const FilePath &filePath) const return HostOsInfo::hostOs(); } - // UnixDeviceAccess UnixDeviceFileAccess::~UnixDeviceFileAccess() = default; @@ -769,9 +793,19 @@ bool UnixDeviceFileAccess::removeRecursively(const FilePath &filePath, QString * return result.exitCode == 0; } -bool UnixDeviceFileAccess::copyFile(const FilePath &filePath, const FilePath &target) const +expected_str UnixDeviceFileAccess::copyFile(const FilePath &filePath, + const FilePath &target) const { - return runInShellSuccess({"cp", {filePath.path(), target.path()}, OsType::OsTypeLinux}); + const RunResult result = runInShell( + {"cp", {filePath.path(), target.path()}, OsType::OsTypeLinux}); + + if (result.exitCode != 0) { + return make_unexpected(Tr::tr("Failed to copy file \"%1\" to \"%2\": %3") + .arg(filePath.toUserOutput()) + .arg(target.toUserOutput()) + .arg(QString::fromUtf8(result.stdErr))); + } + return {}; } bool UnixDeviceFileAccess::renameFile(const FilePath &filePath, const FilePath &target) const @@ -781,15 +815,15 @@ bool UnixDeviceFileAccess::renameFile(const FilePath &filePath, const FilePath & FilePath UnixDeviceFileAccess::symLinkTarget(const FilePath &filePath) const { - const RunResult result = runInShell({"readlink", {"-n", "-e", filePath.path()}, OsType::OsTypeLinux}); + const RunResult result = runInShell( + {"readlink", {"-n", "-e", filePath.path()}, OsType::OsTypeLinux}); const QString out = QString::fromUtf8(result.stdOut); return out.isEmpty() ? FilePath() : filePath.withNewPath(out); } -std::optional UnixDeviceFileAccess::fileContents( - const FilePath &filePath, - qint64 limit, - qint64 offset) const +expected_str UnixDeviceFileAccess::fileContents(const FilePath &filePath, + qint64 limit, + qint64 offset) const { QStringList args = {"if=" + filePath.path(), "status=none"}; if (limit > 0 || offset > 0) { @@ -802,22 +836,30 @@ std::optional UnixDeviceFileAccess::fileContents( const RunResult r = runInShell({"dd", args, OsType::OsTypeLinux}); if (r.exitCode != 0) - return {}; + return make_unexpected(Tr::tr("Failed reading file \"%1\": %2") + .arg(filePath.toUserOutput()) + .arg(QString::fromUtf8(r.stdErr))); return r.stdOut; } -bool UnixDeviceFileAccess::writeFileContents( - const FilePath &filePath, - const QByteArray &data, - qint64 offset) const +expected_str UnixDeviceFileAccess::writeFileContents(const FilePath &filePath, + const QByteArray &data, + qint64 offset) const { QStringList args = {"of=" + filePath.path()}; if (offset != 0) { args.append("bs=1"); args.append(QString("seek=%1").arg(offset)); } - return runInShellSuccess({"dd", args, OsType::OsTypeLinux}, data); + RunResult result = runInShell({"dd", args, OsType::OsTypeLinux}, data); + + if (result.exitCode != 0) { + return make_unexpected(Tr::tr("Failed writing file \"%1\": %2") + .arg(filePath.toUserOutput()) + .arg(QString::fromUtf8(result.stdErr))); + } + return data.size(); } OsType UnixDeviceFileAccess::osType(const FilePath &filePath) const @@ -828,7 +870,8 @@ OsType UnixDeviceFileAccess::osType(const FilePath &filePath) const QDateTime UnixDeviceFileAccess::lastModified(const FilePath &filePath) const { - const RunResult result = runInShell({"stat", {"-L", "-c", "%Y", filePath.path()}, OsType::OsTypeLinux}); + const RunResult result = runInShell( + {"stat", {"-L", "-c", "%Y", filePath.path()}, OsType::OsTypeLinux}); qint64 secs = result.stdOut.toLongLong(); const QDateTime dt = QDateTime::fromSecsSinceEpoch(secs, Qt::UTC); return dt; @@ -836,10 +879,13 @@ QDateTime UnixDeviceFileAccess::lastModified(const FilePath &filePath) const QFile::Permissions UnixDeviceFileAccess::permissions(const FilePath &filePath) const { - const RunResult result = runInShell({"stat", {"-L", "-c", "%a", filePath.path()}, OsType::OsTypeLinux}); + const RunResult result = runInShell( + {"stat", {"-L", "-c", "%a", filePath.path()}, OsType::OsTypeLinux}); const uint bits = result.stdOut.toUInt(nullptr, 8); QFileDevice::Permissions perm = {}; -#define BIT(n, p) if (bits & (1< nameRegexps = - transform(filter.nameFilters, [](const QString &filter) { - QRegularExpression re; - re.setPattern(QRegularExpression::wildcardToRegularExpression(filter)); - QTC_CHECK(re.isValid()); - return re; - }); + const QList nameRegexps + = transform(filter.nameFilters, [](const QString &filter) { + QRegularExpression re; + re.setPattern(QRegularExpression::wildcardToRegularExpression(filter)); + QTC_CHECK(re.isValid()); + return re; + }); const auto nameMatches = [&nameRegexps](const QString &fileName) { for (const QRegularExpression &re : nameRegexps) { @@ -1009,17 +1058,17 @@ static void iterateLsOutput(const FilePath &base, } } -void UnixDeviceFileAccess::iterateDirectory( - const FilePath &filePath, - const FilePath::IterateDirCallback &callBack, - const FileFilter &filter) const +void UnixDeviceFileAccess::iterateDirectory(const FilePath &filePath, + const FilePath::IterateDirCallback &callBack, + const FileFilter &filter) const { // We try to use 'find' first, because that can filter better directly. // Unfortunately, it's not installed on all devices by default. if (m_tryUseFind) { if (iterateWithFind(filePath, filter, callBack)) return; - m_tryUseFind = false; // remember the failure for the next time and use the 'ls' fallback below. + m_tryUseFind + = false; // remember the failure for the next time and use the 'ls' fallback below. } // if we do not have find - use ls as fallback @@ -1028,4 +1077,4 @@ void UnixDeviceFileAccess::iterateDirectory( iterateLsOutput(filePath, entries, filter, callBack); } -} // Utils +} // namespace Utils diff --git a/src/libs/utils/devicefileaccess.h b/src/libs/utils/devicefileaccess.h index 91390c4d53b..4d06ebb50e1 100644 --- a/src/libs/utils/devicefileaccess.h +++ b/src/libs/utils/devicefileaccess.h @@ -34,7 +34,7 @@ protected: virtual bool exists(const FilePath &filePath) const; virtual bool removeFile(const FilePath &filePath) const; virtual bool removeRecursively(const FilePath &filePath, QString *error) const; - virtual bool copyFile(const FilePath &filePath, const FilePath &target) const; + virtual expected_str copyFile(const FilePath &filePath, const FilePath &target) const; virtual bool renameFile(const FilePath &filePath, const FilePath &target) const; virtual OsType osType(const FilePath &filePath) const; @@ -56,31 +56,27 @@ protected: const FilePath::IterateDirCallback &callBack, const FileFilter &filter) const; - virtual std::optional fileContents( - const FilePath &filePath, - qint64 limit, - qint64 offset) const; - virtual bool writeFileContents( - const FilePath &filePath, - const QByteArray &data, - qint64 offset) const; + virtual expected_str fileContents(const FilePath &filePath, + qint64 limit, + qint64 offset) const; - virtual void asyncFileContents( - const FilePath &filePath, - const Continuation> &cont, - qint64 limit, - qint64 offset) const; + virtual expected_str writeFileContents(const FilePath &filePath, + const QByteArray &data, + qint64 offset) const; - virtual void asyncWriteFileContents( - const FilePath &filePath, - const Continuation &cont, - const QByteArray &data, - qint64 offset) const; + virtual void asyncFileContents(const FilePath &filePath, + const Continuation> &cont, + qint64 limit, + qint64 offset) const; - virtual void asyncCopyFile( - const FilePath &filePath, - const Continuation &cont, - const FilePath &target) const; + virtual void asyncWriteFileContents(const FilePath &filePath, + const Continuation> &cont, + const QByteArray &data, + qint64 offset) const; + + virtual void asyncCopyFile(const FilePath &filePath, + const Continuation> &cont, + const FilePath &target) const; }; class QTCREATOR_UTILS_EXPORT DesktopDeviceFileAccess : public DeviceFileAccess @@ -105,7 +101,7 @@ protected: bool exists(const FilePath &filePath) const override; bool removeFile(const FilePath &filePath) const override; bool removeRecursively(const FilePath &filePath, QString *error) const override; - bool copyFile(const FilePath &filePath, const FilePath &target) const override; + expected_str copyFile(const FilePath &filePath, const FilePath &target) const override; bool renameFile(const FilePath &filePath, const FilePath &target) const override; OsType osType(const FilePath &filePath) const override; @@ -127,14 +123,12 @@ protected: const FilePath::IterateDirCallback &callBack, const FileFilter &filter) const override; - std::optional fileContents( - const FilePath &filePath, - qint64 limit, - qint64 offset) const override; - bool writeFileContents( - const FilePath &filePath, - const QByteArray &data, - qint64 offset) const override; + expected_str fileContents(const FilePath &filePath, + qint64 limit, + qint64 offset) const override; + expected_str writeFileContents(const FilePath &filePath, + const QByteArray &data, + qint64 offset) const override; }; class QTCREATOR_UTILS_EXPORT UnixDeviceFileAccess : public DeviceFileAccess @@ -160,7 +154,7 @@ protected: bool exists(const FilePath &filePath) const override; bool removeFile(const FilePath &filePath) const override; bool removeRecursively(const FilePath &filePath, QString *error) const override; - bool copyFile(const FilePath &filePath, const FilePath &target) const override; + expected_str copyFile(const FilePath &filePath, const FilePath &target) const override; bool renameFile(const FilePath &filePath, const FilePath &target) const override; FilePathInfo filePathInfo(const FilePath &filePath) const override; @@ -178,14 +172,12 @@ protected: const FilePath::IterateDirCallback &callBack, const FileFilter &filter) const override; - std::optional fileContents( - const FilePath &filePath, - qint64 limit, - qint64 offset) const override; - bool writeFileContents( - const FilePath &filePath, - const QByteArray &data, - qint64 offset) const override; + expected_str fileContents(const FilePath &filePath, + qint64 limit, + qint64 offset) const override; + expected_str writeFileContents(const FilePath &filePath, + const QByteArray &data, + qint64 offset) const override; private: bool iterateWithFind( diff --git a/src/libs/utils/elfreader.cpp b/src/libs/utils/elfreader.cpp index 75ff2e16b0f..99534f109cf 100644 --- a/src/libs/utils/elfreader.cpp +++ b/src/libs/utils/elfreader.cpp @@ -3,6 +3,7 @@ #include "elfreader.h" +#include "expected.h" #include "qtcassert.h" #include @@ -85,7 +86,9 @@ ElfMapper::ElfMapper(const ElfReader *reader) bool ElfMapper::map() { if (binary.needsDevice()) { - raw = binary.fileContents().value_or(QByteArray()); + const expected_str contents = binary.fileContents(); + QTC_CHECK(contents); + raw = contents.value_or(QByteArray()); start = raw.constData(); fdlen = raw.size(); return fdlen > 0; diff --git a/src/libs/utils/expected.h b/src/libs/utils/expected.h new file mode 100644 index 00000000000..537569a6454 --- /dev/null +++ b/src/libs/utils/expected.h @@ -0,0 +1,47 @@ +// Copyright (C) 2022 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 + +#pragma once + +#include "qtcassert.h" + +#include "../3rdparty/tl_expected/include/tl/expected.hpp" + +namespace Utils { + +template +using expected = tl::expected; + +template +using expected_str = tl::expected; + +template +using unexpected = tl::unexpected; +using unexpect_t = tl::unexpect_t; + +static constexpr unexpect_t unexpect{}; + +template +constexpr unexpected> make_unexpected(E &&e) +{ + return tl::make_unexpected(e); +} + +} // namespace Utils + +//! If 'expected' has an error the error will be printed and the 'action' will be executed. +#define QTC_ASSERT_EXPECTED(expected, action) \ + { \ + if (Q_LIKELY(expected)) { \ + } else { \ + ::Utils::writeAssertLocation(QString("%1:%2: %3") \ + .arg(__FILE__) \ + .arg(__LINE__) \ + .arg(expected.error()) \ + .toUtf8() \ + .data()); \ + action; \ + } \ + do { \ + } while (0); \ + } diff --git a/src/libs/utils/filepath.cpp b/src/libs/utils/filepath.cpp index 98d5e71ca75..82a391d46cd 100644 --- a/src/libs/utils/filepath.cpp +++ b/src/libs/utils/filepath.cpp @@ -9,15 +9,17 @@ #include "fileutils.h" #include "hostosinfo.h" #include "qtcassert.h" +#include "utilstr.h" -#include +#include #include #include #include #include #include -#include #include +#include +#include #ifdef Q_OS_WIN #ifdef QTCREATOR_PCH_H @@ -494,7 +496,7 @@ void FilePath::iterateDirectories(const FilePaths &dirs, dir.iterateDirectory(callBack, filter); } -std::optional FilePath::fileContents(qint64 maxSize, qint64 offset) const +expected_str FilePath::fileContents(qint64 maxSize, qint64 offset) const { return fileAccess()->fileContents(*this, maxSize, offset); } @@ -510,15 +512,14 @@ bool FilePath::ensureReachable(const FilePath &other) const return false; } -void FilePath::asyncFileContents( - const Continuation &> &cont, - qint64 maxSize, - qint64 offset) const +void FilePath::asyncFileContents(const Continuation &> &cont, + qint64 maxSize, + qint64 offset) const { return fileAccess()->asyncFileContents(*this, cont, maxSize, offset); } -bool FilePath::writeFileContents(const QByteArray &data, qint64 offset) const +expected_str FilePath::writeFileContents(const QByteArray &data, qint64 offset) const { return fileAccess()->writeFileContents(*this, data, offset); } @@ -528,10 +529,9 @@ FilePathInfo FilePath::filePathInfo() const return fileAccess()->filePathInfo(*this); } -void FilePath::asyncWriteFileContents( - const Continuation &cont, - const QByteArray &data, - qint64 offset) const +void FilePath::asyncWriteFileContents(const Continuation &> &cont, + const QByteArray &data, + qint64 offset) const { return fileAccess()->asyncWriteFileContents(*this, cont, data, offset); } @@ -1315,33 +1315,47 @@ bool FilePath::removeRecursively(QString *error) const return fileAccess()->removeRecursively(*this, error); } -bool FilePath::copyFile(const FilePath &target) const +expected_str FilePath::copyFile(const FilePath &target) const { if (host() != target.host()) { // FIXME: This does not scale. - const std::optional ba = fileContents(); - if (!ba) - return false; - const auto perms = permissions(); - if (!target.writeFileContents(*ba)) - return false; + const expected_str contents = fileContents(); + if (!contents) { + return make_unexpected( + Tr::tr("Error while trying to copy file: %1").arg(contents.error())); + } + + const QFile::Permissions perms = permissions(); + const expected_str copyResult = target.writeFileContents(*contents); + + if (!copyResult) + return make_unexpected(Tr::tr("Could not copy file: %1").arg(copyResult.error())); if (!target.setPermissions(perms)) { target.removeFile(); - return false; + return make_unexpected( + Tr::tr("Could not set permissions on \"%1\"").arg(target.toString())); } - return true; + return {}; } return fileAccess()->copyFile(*this, target); } -void FilePath::asyncCopyFile(const std::function &cont, const FilePath &target) const +void FilePath::asyncCopyFile(const Continuation &> &cont, + const FilePath &target) const { if (host() != target.host()) { - asyncFileContents([cont, target](const std::optional &ba) { - if (ba) - target.asyncWriteFileContents(cont, *ba); + asyncFileContents([cont, target](const expected_str &contents) { + if (contents) + target.asyncWriteFileContents( + [cont](const expected_str &result) { + if (result) + cont({}); + else + cont(make_unexpected(result.error())); + }, + *contents); }); return; } diff --git a/src/libs/utils/filepath.h b/src/libs/utils/filepath.h index bc473c29d1c..345362576a8 100644 --- a/src/libs/utils/filepath.h +++ b/src/libs/utils/filepath.h @@ -5,6 +5,7 @@ #include "utils_global.h" +#include "expected.h" #include "filepathinfo.h" #include "osspecificaspects.h" @@ -119,15 +120,15 @@ public: OsType osType() const; bool removeFile() const; bool removeRecursively(QString *error = nullptr) const; - bool copyFile(const FilePath &target) const; + expected_str copyFile(const FilePath &target) const; bool renameFile(const FilePath &target) const; qint64 fileSize() const; qint64 bytesAvailable() const; bool createDir() const; FilePaths dirEntries(const FileFilter &filter, QDir::SortFlags sort = QDir::NoSort) const; FilePaths dirEntries(QDir::Filters filters) const; - std::optional fileContents(qint64 maxSize = -1, qint64 offset = 0) const; - bool writeFileContents(const QByteArray &data, qint64 offset = 0) const; + expected_str fileContents(qint64 maxSize = -1, qint64 offset = 0) const; + expected_str writeFileContents(const QByteArray &data, qint64 offset = 0) const; FilePathInfo filePathInfo() const; bool operator==(const FilePath &other) const; @@ -198,11 +199,12 @@ public: static void sort(FilePaths &files); // Asynchronous interface - void asyncCopyFile(const Continuation &cont, const FilePath &target) const; - void asyncFileContents(const Continuation &> &cont, + void asyncCopyFile(const Continuation &> &cont, + const FilePath &target) const; + void asyncFileContents(const Continuation &> &cont, qint64 maxSize = -1, qint64 offset = 0) const; - void asyncWriteFileContents(const Continuation &cont, + void asyncWriteFileContents(const Continuation &> &cont, const QByteArray &data, qint64 offset = 0) const; diff --git a/src/libs/utils/filesearch.cpp b/src/libs/utils/filesearch.cpp index f91d6516275..3863d13b52c 100644 --- a/src/libs/utils/filesearch.cpp +++ b/src/libs/utils/filesearch.cpp @@ -55,7 +55,7 @@ static bool getFileContent(const FilePath &filePath, if (fileToContentsMap.contains(filePath)) { *tempString = fileToContentsMap.value(filePath); } else { - const std::optional content = filePath.fileContents(); + const expected_str content = filePath.fileContents(); if (!content) return false; *tempString = QTC_GUARD(encoding) ? encoding->toUnicode(*content) diff --git a/src/libs/utils/fileutils.cpp b/src/libs/utils/fileutils.cpp index cfaeb382a73..5750627b335 100644 --- a/src/libs/utils/fileutils.cpp +++ b/src/libs/utils/fileutils.cpp @@ -55,28 +55,12 @@ bool FileReader::fetch(const FilePath &filePath, QIODevice::OpenMode mode) { QTC_ASSERT(!(mode & ~(QIODevice::ReadOnly | QIODevice::Text)), return false); - if (filePath.needsDevice()) { - const std::optional contents = filePath.fileContents(); - if (!contents) { - m_errorString = tr("Cannot read %1").arg(filePath.toUserOutput()); - return false; - } - m_data = *contents; - return true; - } - - QFile file(filePath.toString()); - if (!file.open(QIODevice::ReadOnly | mode)) { - m_errorString = tr("Cannot open %1 for reading: %2").arg( - filePath.toUserOutput(), file.errorString()); - return false; - } - m_data = file.readAll(); - if (file.error() != QFile::NoError) { - m_errorString = tr("Cannot read %1: %2").arg( - filePath.toUserOutput(), file.errorString()); + const expected_str contents = filePath.fileContents(); + if (!contents) { + m_errorString = contents.error(); return false; } + m_data = *contents; return true; } @@ -225,10 +209,10 @@ bool FileSaver::finalize() m_file->close(); m_file->open(QIODevice::ReadOnly); const QByteArray data = m_file->readAll(); - const bool res = m_filePath.writeFileContents(data); + const expected_str res = m_filePath.writeFileContents(data); m_file->remove(); m_file.reset(); - return res; + return res.has_value(); } if (!m_isSafe) @@ -703,15 +687,20 @@ bool FileUtils::copyIfDifferent(const FilePath &srcFilePath, const FilePath &tgt const QDateTime srcModified = srcFilePath.lastModified(); const QDateTime tgtModified = tgtFilePath.lastModified(); if (srcModified == tgtModified) { - const std::optional srcContents = srcFilePath.fileContents(); - const std::optional tgtContents = srcFilePath.fileContents(); - if (srcContents == tgtContents) + // TODO: Create FilePath::hashFromContents() and compare hashes. + const expected_str srcContents = srcFilePath.fileContents(); + const expected_str tgtContents = srcFilePath.fileContents(); + if (srcContents && srcContents == tgtContents) return true; } tgtFilePath.removeFile(); } - return srcFilePath.copyFile(tgtFilePath); + const expected_str copyResult = srcFilePath.copyFile(tgtFilePath); + + // TODO forward error to caller instead of assert, since IO errors can always be expected + QTC_ASSERT_EXPECTED(copyResult, return false); + return true; } QString FileUtils::fileSystemFriendlyName(const QString &name) diff --git a/src/libs/utils/fsengine/fsengine_impl.cpp b/src/libs/utils/fsengine/fsengine_impl.cpp index 4436f4a3cdc..d3f9a724ea8 100644 --- a/src/libs/utils/fsengine/fsengine_impl.cpp +++ b/src/libs/utils/fsengine/fsengine_impl.cpp @@ -4,6 +4,7 @@ #include "fsengine_impl.h" #include "diriterator.h" +#include "expected.h" #include "filepathinfocache.h" #include "../filepath.h" @@ -62,8 +63,11 @@ bool FSEngineImpl::open(QIODevice::OpenMode openMode) return false; if (read || append) { - const std::optional contents = m_filePath.fileContents(); - QTC_ASSERT(contents && m_tempStorage->write(*contents) >= 0, return false); + const expected_str readResult = m_filePath.fileContents(); + QTC_ASSERT_EXPECTED(readResult, return false); + + const expected_str writeResult = m_tempStorage->write(*readResult); + QTC_ASSERT_EXPECTED(writeResult, return false); if (!append) m_tempStorage->seek(0); @@ -133,7 +137,9 @@ bool FSEngineImpl::remove() bool FSEngineImpl::copy(const QString &newName) { - return m_filePath.copyFile(FilePath::fromString(newName)); + expected_str result = m_filePath.copyFile(FilePath::fromString(newName)); + QTC_ASSERT_EXPECTED(result, return false); + return true; } bool FSEngineImpl::rename(const QString &newName) diff --git a/src/plugins/android/androidbuildapkstep.cpp b/src/plugins/android/androidbuildapkstep.cpp index b6c18f84693..74bacb4c68e 100644 --- a/src/plugins/android/androidbuildapkstep.cpp +++ b/src/plugins/android/androidbuildapkstep.cpp @@ -680,7 +680,9 @@ static bool copyFileIfNewer(const FilePath &sourceFilePath, if (!destinationFilePath.parentDir().ensureWritableDir()) return false; - return sourceFilePath.copyFile(destinationFilePath); + expected_str result = sourceFilePath.copyFile(destinationFilePath); + QTC_ASSERT_EXPECTED(result, return false); + return true; } void AndroidBuildApkStep::doRun() diff --git a/src/plugins/cmakeprojectmanager/fileapiparser.cpp b/src/plugins/cmakeprojectmanager/fileapiparser.cpp index 24feaf215ce..ddfb6b5b03c 100644 --- a/src/plugins/cmakeprojectmanager/fileapiparser.cpp +++ b/src/plugins/cmakeprojectmanager/fileapiparser.cpp @@ -75,7 +75,7 @@ static QJsonDocument readJsonFile(const FilePath &filePath) qCDebug(cmakeFileApi) << "readJsonFile:" << filePath; QTC_ASSERT(!filePath.isEmpty(), return {}); - const std::optional contents = filePath.fileContents(); + const expected_str contents = filePath.fileContents(); if (!contents) return {}; const QJsonDocument doc = QJsonDocument::fromJson(*contents); diff --git a/src/plugins/cmakeprojectmanager/presetsparser.cpp b/src/plugins/cmakeprojectmanager/presetsparser.cpp index 6cddec91234..bafe129afdb 100644 --- a/src/plugins/cmakeprojectmanager/presetsparser.cpp +++ b/src/plugins/cmakeprojectmanager/presetsparser.cpp @@ -2,10 +2,11 @@ // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 #include "presetsparser.h" -#include "utils/algorithm.h" #include "cmakeprojectmanagertr.h" +#include + #include #include #include @@ -391,7 +392,7 @@ const PresetsData &PresetsParser::presetsData() const bool PresetsParser::parse(const Utils::FilePath &jsonFile, QString &errorMessage, int &errorLine) { - const std::optional jsonContents = jsonFile.fileContents(); + const Utils::expected_str jsonContents = jsonFile.fileContents(); if (!jsonContents) { errorMessage = Tr::tr("Failed to read %1 file").arg(jsonFile.fileName()); return false; diff --git a/src/plugins/coreplugin/loggingviewer.cpp b/src/plugins/coreplugin/loggingviewer.cpp index d0f9190dfd1..847b32d6c2f 100644 --- a/src/plugins/coreplugin/loggingviewer.cpp +++ b/src/plugins/coreplugin/loggingviewer.cpp @@ -652,7 +652,7 @@ void LoggingViewManagerWidget::loadAndUpdateFromPreset() if (fp.isEmpty()) return; // read file, update categories - const std::optional contents = fp.fileContents(); + const Utils::expected_str contents = fp.fileContents(); if (!contents) { QMessageBox::critical(ICore::dialogParent(), tr("Error"), diff --git a/src/plugins/cppeditor/cpptoolsjsextension.cpp b/src/plugins/cppeditor/cpptoolsjsextension.cpp index 938f24e6f12..c223a29d3d4 100644 --- a/src/plugins/cppeditor/cpptoolsjsextension.cpp +++ b/src/plugins/cppeditor/cpptoolsjsextension.cpp @@ -136,9 +136,8 @@ bool CppToolsJsExtension::hasQObjectParent(const QString &klassName) const const WorkingCopy workingCopy = CppModelManager::instance()->workingCopy(); QByteArray source = workingCopy.source(item->filePath()); if (source.isEmpty()) { - std::optional contents = item->filePath().fileContents(); - if (!contents) - return false; + const Utils::expected_str contents = item->filePath().fileContents(); + QTC_ASSERT_EXPECTED(contents, return false); source = *contents; } const auto doc = snapshot.preprocessedDocument(source, item->filePath()); diff --git a/src/plugins/debugger/debuggerprotocol.cpp b/src/plugins/debugger/debuggerprotocol.cpp index bf250b29d27..558392717ca 100644 --- a/src/plugins/debugger/debuggerprotocol.cpp +++ b/src/plugins/debugger/debuggerprotocol.cpp @@ -15,12 +15,7 @@ #include #include - -#define QTC_ASSERT_STRINGIFY_HELPER(x) #x -#define QTC_ASSERT_STRINGIFY(x) QTC_ASSERT_STRINGIFY_HELPER(x) -#define QTC_ASSERT_STRING(cond) qDebug("SOFT ASSERT: \"" cond"\" in file " __FILE__ ", line " QTC_ASSERT_STRINGIFY(__LINE__)) -#define QTC_ASSERT(cond, action) if (cond) {} else { QTC_ASSERT_STRING(#cond); action; } do {} while (0) -#define QTC_CHECK(cond) if (cond) {} else { QTC_ASSERT_STRING(#cond); } do {} while (0) +#include namespace Debugger::Internal { diff --git a/src/plugins/gitlab/gitlabparameters.cpp b/src/plugins/gitlab/gitlabparameters.cpp index 41d37716ef7..749f8f65083 100644 --- a/src/plugins/gitlab/gitlabparameters.cpp +++ b/src/plugins/gitlab/gitlabparameters.cpp @@ -129,7 +129,7 @@ static QList readTokensFile(const Utils::FilePath &filePath) { if (!filePath.exists()) return {}; - std::optional contents = filePath.fileContents(); + const Utils::expected_str contents = filePath.fileContents(); if (!contents) return {}; const QByteArray content = *contents; diff --git a/src/plugins/projectexplorer/extracompiler.cpp b/src/plugins/projectexplorer/extracompiler.cpp index e92e49f051d..9edcd5d2953 100644 --- a/src/plugins/projectexplorer/extracompiler.cpp +++ b/src/plugins/projectexplorer/extracompiler.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -98,8 +99,10 @@ ExtraCompiler::ExtraCompiler(const Project *project, const FilePath &source, if (!d->compileTime.isValid() || d->compileTime > lastModified) d->compileTime = lastModified; - if (const std::optional contents = target.fileContents()) - setContent(target, *contents); + const expected_str contents = target.fileContents(); + QTC_ASSERT_EXPECTED(contents, return); + + setContent(target, *contents); } } @@ -169,10 +172,11 @@ void ExtraCompiler::onTargetsBuilt(Project *project) if (d->compileTime >= generateTime) return; - if (const std::optional contents = target.fileContents()) { - d->compileTime = generateTime; - setContent(target, *contents); - } + const expected_str contents = target.fileContents(); + QTC_ASSERT_EXPECTED(contents, return); + + d->compileTime = generateTime; + setContent(target, *contents); } }); } diff --git a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarybundleimporter.cpp b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarybundleimporter.cpp index 086ce32379a..019865f3383 100644 --- a/src/plugins/qmldesigner/components/contentlibrary/contentlibrarybundleimporter.cpp +++ b/src/plugins/qmldesigner/components/contentlibrary/contentlibrarybundleimporter.cpp @@ -224,7 +224,7 @@ void ContentLibraryBundleImporter::handleImportTimer() QVariantHash ContentLibraryBundleImporter::loadAssetRefMap(const Utils::FilePath &bundlePath) { FilePath assetRefPath = bundlePath.resolvePath(QLatin1String(Constants::COMPONENT_BUNDLES_ASSET_REF_FILE)); - const std::optional content = assetRefPath.fileContents(); + const Utils::expected_str content = assetRefPath.fileContents(); if (content) { QJsonParseError error; QJsonDocument bundleDataJsonDoc = QJsonDocument::fromJson(*content, &error); @@ -266,7 +266,7 @@ QString ContentLibraryBundleImporter::unimportComponent(const QString &qmlFile) removedFiles.append(qmlFile); FilePath qmldirPath = bundleImportPath.resolvePath(QStringLiteral("qmldir")); - const std::optional qmldirContent = qmldirPath.fileContents(); + const expected_str qmldirContent = qmldirPath.fileContents(); QByteArray newContent; QString qmlType = qmlFilePath.baseName(); diff --git a/src/plugins/squish/scripthelper.cpp b/src/plugins/squish/scripthelper.cpp index 916a3c99fa9..391e526eac9 100644 --- a/src/plugins/squish/scripthelper.cpp +++ b/src/plugins/squish/scripthelper.cpp @@ -144,7 +144,9 @@ bool ScriptHelper::writeScriptFile(const Utils::FilePath &outScriptFile, for (const QByteArray &line : functionFooter(m_language)) data.append(line).append('\n'); - return outScriptFile.writeFileContents(data); + const Utils::expected_str result = outScriptFile.writeFileContents(data); + QTC_ASSERT_EXPECTED(result, return false); + return true; } } // namespace Internal diff --git a/src/plugins/squish/squishtesttreeview.cpp b/src/plugins/squish/squishtesttreeview.cpp index 8f3c1237483..ec36e4d79e8 100644 --- a/src/plugins/squish/squishtesttreeview.cpp +++ b/src/plugins/squish/squishtesttreeview.cpp @@ -179,8 +179,8 @@ static bool copyScriptTemplates(const SuiteConf &suiteConf, const Utils::FilePat const Utils::FilePath test = scripts.pathAppended(testStr + extension); const Utils::FilePath testFile = destination.pathAppended("test" + extension); QTC_ASSERT(!testFile.exists(), return false); - ok = test.copyFile(testFile); - QTC_ASSERT(ok, return false); + const Utils::expected_str result = test.copyFile(testFile); + QTC_ASSERT_EXPECTED(result, return false) if (scripted) ok = suiteConf.ensureObjectMapExists(); diff --git a/src/plugins/squish/suiteconf.cpp b/src/plugins/squish/suiteconf.cpp index 4b34a94bd5c..2d183c5c0a3 100644 --- a/src/plugins/squish/suiteconf.cpp +++ b/src/plugins/squish/suiteconf.cpp @@ -80,7 +80,7 @@ static QMap readSuiteConfContent(const Utils::FilePath &file) if (!file.isReadableFile()) return {}; - std::optional suiteConfContent = file.fileContents(); + const Utils::expected_str suiteConfContent = file.fileContents(); if (!suiteConfContent) return {}; @@ -112,7 +112,9 @@ static bool writeSuiteConfContent(const Utils::FilePath &file, const QMap result = file.writeFileContents(outData); + QTC_ASSERT_EXPECTED(result, return false); + return true; } bool SuiteConf::read() @@ -306,9 +308,9 @@ bool SuiteConf::ensureObjectMapExists() const const Utils::FilePath objectMap = scripts.pathAppended("objectmap_template" + extension); bool ok = destinationObjectMap.parentDir().ensureWritableDir(); QTC_ASSERT(ok, return false); - ok = objectMap.copyFile(destinationObjectMap); - QTC_ASSERT(ok, return false); - return ok; + const Utils::expected_str result = objectMap.copyFile(destinationObjectMap); + QTC_ASSERT_EXPECTED(result, return false); + return true; } } // namespace Internal diff --git a/src/plugins/valgrind/callgrindengine.cpp b/src/plugins/valgrind/callgrindengine.cpp index 94491a32328..248084c6f1f 100644 --- a/src/plugins/valgrind/callgrindengine.cpp +++ b/src/plugins/valgrind/callgrindengine.cpp @@ -256,9 +256,8 @@ void CallgrindToolRunner::triggerParse() m_hostOutputFile = FilePath::fromString(dataFile.fileName()); } - const auto afterCopy = [this](bool res) { - QTC_CHECK(res); - QTC_ASSERT(m_hostOutputFile.exists(), return); + const auto afterCopy = [this](expected_str res) { + QTC_ASSERT_EXPECTED(res, return); showStatusMessage(Tr::tr("Parsing Profile Data...")); m_parser.parse(m_hostOutputFile); }; diff --git a/tests/auto/utils/CMakeLists.txt b/tests/auto/utils/CMakeLists.txt index 34532e8f918..29548a5680f 100644 --- a/tests/auto/utils/CMakeLists.txt +++ b/tests/auto/utils/CMakeLists.txt @@ -2,6 +2,7 @@ add_subdirectory(ansiescapecodehandler) add_subdirectory(asynctask) add_subdirectory(commandline) add_subdirectory(deviceshell) +add_subdirectory(expected) add_subdirectory(fileutils) add_subdirectory(fsengine) add_subdirectory(fuzzymatcher) diff --git a/tests/auto/utils/expected/CMakeLists.txt b/tests/auto/utils/expected/CMakeLists.txt new file mode 100644 index 00000000000..cfc5c62c3f3 --- /dev/null +++ b/tests/auto/utils/expected/CMakeLists.txt @@ -0,0 +1,4 @@ +add_qtc_test(tst_utils_expected + DEPENDS Utils + SOURCES tst_expected.cpp +) diff --git a/tests/auto/utils/expected/expected.qbs b/tests/auto/utils/expected/expected.qbs new file mode 100644 index 00000000000..490a721928a --- /dev/null +++ b/tests/auto/utils/expected/expected.qbs @@ -0,0 +1,7 @@ +import qbs + +QtcAutotest { + name: "Expected autotest" + Depends { name: "Utils" } + files: "tst_expected.cpp" +} diff --git a/tests/auto/utils/expected/tst_expected.cpp b/tests/auto/utils/expected/tst_expected.cpp new file mode 100644 index 00000000000..0003dc01ba4 --- /dev/null +++ b/tests/auto/utils/expected/tst_expected.cpp @@ -0,0 +1,38 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 + +#include +#include + +#include +#include + +using namespace Utils; + +class tst_expected : public QObject +{ + Q_OBJECT + +private slots: + void initTestCase() {} + + void tryMonads() + { + FilePath p = "idontexists.ne"; + + auto result = p.fileContents() + .and_then([](auto) { return expected_str{}; }) + .or_else([](auto error) { + return expected_str( + make_unexpected(QString("Error: " + error))); + }) + .transform_or([](auto error) -> QString { + return QString(QString("More Info: ") + error); + }); + + QVERIFY(!result); + } +}; +QTEST_GUILESS_MAIN(tst_expected) + +#include "tst_expected.moc" diff --git a/tests/auto/utils/fileutils/tst_fileutils.cpp b/tests/auto/utils/fileutils/tst_fileutils.cpp index 8b202317860..cf5f2758e1b 100644 --- a/tests/auto/utils/fileutils/tst_fileutils.cpp +++ b/tests/auto/utils/fileutils/tst_fileutils.cpp @@ -1,9 +1,9 @@ // Copyright (C) 2016 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0+ OR GPL-3.0 WITH Qt-GPL-exception-1.0 -#include #include #include +#include #include #include @@ -13,12 +13,12 @@ using namespace Utils; namespace QTest { - template<> - char *toString(const FilePath &filePath) - { - return qstrdup(filePath.toString().toLocal8Bit().constData()); - } +template<> +char *toString(const FilePath &filePath) +{ + return qstrdup(filePath.toString().toLocal8Bit().constData()); } +} // namespace QTest class tst_fileutils : public QObject { @@ -1027,7 +1027,7 @@ void tst_fileutils::asyncLocalCopy() const FilePath orig = FilePath::fromString(rootPath).pathAppended("x/y/fileToCopy.txt"); QVERIFY(orig.exists()); const FilePath dest = FilePath::fromString(rootPath).pathAppended("x/fileToCopyDest.txt"); - auto afterCopy = [&orig, &dest, this] (bool result) { + auto afterCopy = [&orig, &dest, this](expected_str result) { QVERIFY(result); // check existence, size and content QVERIFY(dest.exists()); diff --git a/tests/auto/utils/utils.qbs b/tests/auto/utils/utils.qbs index 138b1b72ed9..eea36644236 100644 --- a/tests/auto/utils/utils.qbs +++ b/tests/auto/utils/utils.qbs @@ -7,6 +7,7 @@ Project { "asynctask/asynctask.qbs", "commandline/commandline.qbs", "deviceshell/deviceshell.qbs", + "expected/expected.qbs", "fileutils/fileutils.qbs", "fsengine/fsengine.qbs", "fuzzymatcher/fuzzymatcher.qbs",