/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* A template class for tagged unions. */ #include #include #include "mozilla/Alignment.h" #include "mozilla/Assertions.h" #include "mozilla/Move.h" #include "mozilla/TypeTraits.h" #ifndef mozilla_Variant_h #define mozilla_Variant_h namespace mozilla { template class Variant; namespace detail { // MaxSizeOf computes the maximum sizeof(T) for each T in Ts. template struct MaxSizeOf { static const size_t size = sizeof(T) > MaxSizeOf::size ? sizeof(T) : MaxSizeOf::size; }; template struct MaxSizeOf { static const size_t size = sizeof(T); }; // The `IsVariant` helper is used in conjunction with static_assert and // `mozilla::EnableIf` to catch passing non-variant types to `Variant::is()` // and friends at compile time, rather than at runtime. It ensures that the // given type `Needle` is one of the types in the set of types `Haystack`. template struct IsVariant; template struct IsVariant { static const bool value = false; }; template struct IsVariant { static const bool value = true; }; template struct IsVariant : public IsVariant { }; /// SelectVariantTypeHelper is used in the implementation of SelectVariantType. template struct SelectVariantTypeHelper; template struct SelectVariantTypeHelper { }; template struct SelectVariantTypeHelper { typedef T Type; }; template struct SelectVariantTypeHelper { typedef const T Type; }; template struct SelectVariantTypeHelper { typedef const T& Type; }; template struct SelectVariantTypeHelper { typedef T&& Type; }; template struct SelectVariantTypeHelper : public SelectVariantTypeHelper { }; /** * SelectVariantType takes a type T and a list of variant types Variants and * yields a type Type, selected from Variants, that can store a value of type T * or a reference to type T. If no such type was found, Type is not defined. */ template struct SelectVariantType : public SelectVariantTypeHelper::Type>::Type, Variants...> { }; // Compute a fast, compact type that can be used to hold integral values that // distinctly map to every type in Ts. template struct VariantTag { private: static const size_t TypeCount = sizeof...(Ts); public: using Type = typename Conditional::Type >::Type; }; // TagHelper gets the given sentinel tag value for the given type T. This has to // be split out from VariantImplementation because you can't nest a partial // template specialization within a template class. template struct TagHelper; // In the case where T != U, we continue recursion. template struct TagHelper { static Tag tag() { return Next::template tag(); } }; // In the case where T == U, return the tag number. template struct TagHelper { static Tag tag() { return Tag(N); } }; // The VariantImplementation template provides the guts of mozilla::Variant. We // create a VariantImplementation for each T in Ts... which handles // construction, destruction, etc for when the Variant's type is T. If the // Variant's type isn't T, it punts the request on to the next // VariantImplementation. template struct VariantImplementation; // The singly typed Variant / recursion base case. template struct VariantImplementation { template static Tag tag() { static_assert(mozilla::IsSame::value, "mozilla::Variant: tag: bad type!"); return Tag(N); } template static void copyConstruct(void* aLhs, const Variant& aRhs) { new (aLhs) T(aRhs.template as()); } template static void moveConstruct(void* aLhs, Variant&& aRhs) { new (aLhs) T(aRhs.template extract()); } template static void destroy(Variant& aV) { aV.template as().~T(); } template static bool equal(const Variant& aLhs, const Variant& aRhs) { return aLhs.template as() == aRhs.template as(); } template static auto match(Matcher&& aMatcher, ConcreteVariant& aV) -> decltype(aMatcher.match(aV.template as())) { return aMatcher.match(aV.template as()); } }; // VariantImplementation for some variant type T. template struct VariantImplementation { // The next recursive VariantImplementation. using Next = VariantImplementation; template static Tag tag() { return TagHelper::value>::tag(); } template static void copyConstruct(void* aLhs, const Variant& aRhs) { if (aRhs.template is()) { new (aLhs) T(aRhs.template as()); } else { Next::copyConstruct(aLhs, aRhs); } } template static void moveConstruct(void* aLhs, Variant&& aRhs) { if (aRhs.template is()) { new (aLhs) T(aRhs.template extract()); } else { Next::moveConstruct(aLhs, aRhs); } } template static void destroy(Variant& aV) { if (aV.template is()) { aV.template as().~T(); } else { Next::destroy(aV); } } template static bool equal(const Variant& aLhs, const Variant& aRhs) { if (aLhs.template is()) { MOZ_ASSERT(aRhs.template is()); return aLhs.template as() == aRhs.template as(); } else { return Next::equal(aLhs, aRhs); } } template static auto match(Matcher&& aMatcher, ConcreteVariant& aV) -> decltype(aMatcher.match(aV.template as())) { if (aV.template is()) { return aMatcher.match(aV.template as()); } else { // If you're seeing compilation errors here like "no matching // function for call to 'match'" then that means that the // Matcher doesn't exhaust all variant types. There must exist a // Matcher::match(T&) for every variant type T. // // If you're seeing compilation errors here like "cannot // initialize return object of type <...> with an rvalue of type // <...>" then that means that the Matcher::match(T&) overloads // are returning different types. They must all return the same // Matcher::ReturnType type. return Next::match(aMatcher, aV); } } }; /** * AsVariantTemporary stores a value of type T to allow construction of a * Variant value via type inference. Because T is copied and there's no * guarantee that the copy can be elided, AsVariantTemporary is best used with * primitive or very small types. */ template struct AsVariantTemporary { explicit AsVariantTemporary(const T& aValue) : mValue(aValue) {} template explicit AsVariantTemporary(U&& aValue) : mValue(Forward(aValue)) {} AsVariantTemporary(const AsVariantTemporary& aOther) : mValue(aOther.mValue) {} AsVariantTemporary(AsVariantTemporary&& aOther) : mValue(Move(aOther.mValue)) {} AsVariantTemporary() = delete; void operator=(const AsVariantTemporary&) = delete; void operator=(AsVariantTemporary&&) = delete; typename RemoveConst::Type>::Type mValue; }; } // namespace detail /** * # mozilla::Variant * * A variant / tagged union / heterogenous disjoint union / sum-type template * class. Similar in concept to (but not derived from) `boost::variant`. * * Sometimes, you may wish to use a C union with non-POD types. However, this is * forbidden in C++ because it is not clear which type in the union should have * its constructor and destructor run on creation and deletion * respectively. This is the problem that `mozilla::Variant` solves. * * ## Usage * * A `mozilla::Variant` instance is constructed (via move or copy) from one of * its variant types (ignoring const and references). It does *not* support * construction from subclasses of variant types or types that coerce to one of * the variant types. * * Variant v1('a'); * Variant, B, C> v2(MakeUnique()); * * Because specifying the full type of a Variant value is often verbose, * AsVariant() can be used to construct a Variant value using type inference in * contexts such as expressions or when returning values from functions. Because * AsVariant() must copy or move the value into a temporary and this cannot * necessarily be elided by the compiler, it's mostly appropriate only for use * with primitive or very small types. * * * Variant Foo() { return AsVariant('x'); } * // ... * Variant v1 = Foo(); // v1 holds char('x'). * * All access to the contained value goes through type-safe accessors. * * void * Foo(Variant v) * { * if (v.is()) { * A& ref = v.as(); * ... * } else { * ... * } * } * * Attempting to use the contained value as type `T1` when the `Variant` * instance contains a value of type `T2` causes an assertion failure. * * A a; * Variant v(a); * v.as(); // <--- Assertion failure! * * Trying to use a `Variant` instance as some type `U` that is not a * member of the set of `Ts...` is a compiler error. * * A a; * Variant v(a); * v.as(); // <--- Compiler error! * * Additionally, you can turn a `Variant` that `is` into a `T` by moving it * out of the containing `Variant` instance with the `extract` method: * * Variant, B, C> v(MakeUnique()); * auto ptr = v.extract>(); * * Finally, you can exhaustively match on the contained variant and branch into * different code paths depending which type is contained. This is preferred to * manually checking every variant type T with is() because it provides * compile-time checking that you handled every type, rather than runtime * assertion failures. * * // Bad! * char* foo(Variant& v) { * if (v.is()) { * return ...; * } else if (v.is()) { * return ...; * } else { * return doSomething(v.as()); // Forgot about case D! * } * } * * // Good! * struct FooMatcher * { * // The return type of all matchers must be identical. * char* match(A& a) { ... } * char* match(B& b) { ... } * char* match(C& c) { ... } * char* match(D& d) { ... } // Compile-time error to forget D! * } * char* foo(Variant& v) { * return v.match(FooMatcher()); * } * * ## Examples * * A tree is either an empty leaf, or a node with a value and two children: * * struct Leaf { }; * * template * struct Node * { * T value; * Tree* left; * Tree* right; * }; * * template * using Tree = Variant>; * * A copy-on-write string is either a non-owning reference to some existing * string, or an owning reference to our copy: * * class CopyOnWriteString * { * Variant> string; * * ... * }; */ template class MOZ_INHERIT_TYPE_ANNOTATIONS_FROM_TEMPLATE_ARGS Variant { using Tag = typename detail::VariantTag::Type; using Impl = detail::VariantImplementation; using RawData = AlignedStorage::size>; // Raw storage for the contained variant value. RawData raw; // Each type is given a unique tag value that lets us keep track of the // contained variant value's type. Tag tag; void* ptr() { return reinterpret_cast(&raw); } public: /** Perfect forwarding construction for some variant type T. */ template::Type> explicit Variant(RefT&& aT) : tag(Impl::template tag()) { new (ptr()) T(Forward(aT)); } /** * Constructs this Variant from an AsVariantTemporary such that T can be * stored in one of the types allowable in this Variant. This is used in the * implementation of AsVariant(). */ template::Type> MOZ_IMPLICIT Variant(detail::AsVariantTemporary&& aValue) : tag(Impl::template tag()) { new (ptr()) T(Move(aValue.mValue)); } /** Copy construction. */ Variant(const Variant& aRhs) : tag(aRhs.tag) { Impl::copyConstruct(ptr(), aRhs); } /** Move construction. */ Variant(Variant&& aRhs) : tag(aRhs.tag) { Impl::moveConstruct(ptr(), Move(aRhs)); } /** Copy assignment. */ Variant& operator=(const Variant& aRhs) { MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); this->~Variant(); new (this) Variant(aRhs); return *this; } /** Move assignment. */ Variant& operator=(Variant&& aRhs) { MOZ_ASSERT(&aRhs != this, "self-assign disallowed"); this->~Variant(); new (this) Variant(Move(aRhs)); return *this; } /** Move assignment from AsVariant(). */ template Variant& operator=(detail::AsVariantTemporary&& aValue) { this->~Variant(); new (this) Variant(Move(aValue)); return *this; } ~Variant() { Impl::destroy(*this); } /** Check which variant type is currently contained. */ template bool is() const { static_assert(detail::IsVariant::value, "provided a type not found in this Variant's type list"); return Impl::template tag() == tag; } /** * Operator == overload that defers to the variant type's operator== * implementation if the rhs is tagged as the same type as this one. */ bool operator==(const Variant& aRhs) const { return tag == aRhs.tag && Impl::equal(*this, aRhs); } /** * Operator != overload that defers to the negation of the variant type's * operator== implementation if the rhs is tagged as the same type as this * one. */ bool operator!=(const Variant& aRhs) const { return !(*this == aRhs); } // Accessors for working with the contained variant value. /** Mutable reference. */ template T& as() { static_assert(detail::IsVariant::value, "provided a type not found in this Variant's type list"); MOZ_ASSERT(is()); return *reinterpret_cast(&raw); } /** Immutable const reference. */ template const T& as() const { static_assert(detail::IsVariant::value, "provided a type not found in this Variant's type list"); MOZ_ASSERT(is()); return *reinterpret_cast(&raw); } /** * Extract the contained variant value from this container into a temporary * value. On completion, the value in the variant will be in a * safely-destructible state, as determined by the behavior of T's move * constructor when provided the variant's internal value. */ template T extract() { static_assert(detail::IsVariant::value, "provided a type not found in this Variant's type list"); MOZ_ASSERT(is()); return T(Move(as())); } // Exhaustive matching of all variant types on the contained value. /** Match on an immutable const reference. */ template auto match(Matcher&& aMatcher) const -> decltype(Impl::match(aMatcher, *this)) { return Impl::match(aMatcher, *this); } /** Match on a mutable non-const reference. */ template auto match(Matcher&& aMatcher) -> decltype(Impl::match(aMatcher, *this)) { return Impl::match(aMatcher, *this); } }; /* * AsVariant() is used to construct a Variant value containing the * provided T value using type inference. It can be used to construct Variant * values in expressions or return them from functions without specifying the * entire Variant type. * * Because AsVariant() must copy or move the value into a temporary and this * cannot necessarily be elided by the compiler, it's mostly appropriate only * for use with primitive or very small types. * * AsVariant() returns a AsVariantTemporary value which is implicitly * convertible to any Variant that can hold a value of type T. */ template detail::AsVariantTemporary AsVariant(T&& aValue) { return detail::AsVariantTemporary(Forward(aValue)); } } // namespace mozilla #endif /* mozilla_Variant_h */