// Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors // Licensed under the MIT License: // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // 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. // This file defines a notion of tuples that is simpler that `std::tuple`. It works as follows: // - `kj::Tuple is the type of a tuple of an A, a B, and a C. // - `kj::tuple(a, b, c)` returns a tuple containing a, b, and c. If any of these are themselves // tuples, they are flattened, so `tuple(a, tuple(b, c), d)` is equivalent to `tuple(a, b, c, d)`. // - `kj::get(myTuple)` returns the element of `myTuple` at index n. // - `kj::apply(func, ...)` calls func on the following arguments after first expanding any tuples // in the argument list. So `kj::apply(foo, a, tuple(b, c), d)` would call `foo(a, b, c, d)`. // // Note that: // - The type `Tuple` is a synonym for T. This is why `get` and `apply` are not members of the // type. // - It is illegal for an element of `Tuple` to itself be a tuple, as tuples are meant to be // flattened. // - It is illegal for an element of `Tuple` to be a reference, due to problems this would cause // with type inference and `tuple()`. #pragma once #if defined(__GNUC__) && !KJ_HEADER_WARNINGS #pragma GCC system_header #endif #include "common.h" namespace kj { namespace _ { // private template struct TypeByIndex_; template struct TypeByIndex_<0, First, Rest...> { typedef First Type; }; template struct TypeByIndex_ : public TypeByIndex_ {}; template struct TypeByIndex_ { static_assert(index != index, "Index out-of-range."); }; template using TypeByIndex = typename TypeByIndex_::Type; // Chose a particular type out of a list of types, by index. template struct Indexes {}; // Dummy helper type that just encapsulates a sequential list of indexes, so that we can match // templates against them and unpack them with '...'. template struct MakeIndexes_: public MakeIndexes_ {}; template struct MakeIndexes_<0, prefix...> { typedef Indexes Type; }; template using MakeIndexes = typename MakeIndexes_::Type; // Equivalent to Indexes<0, 1, 2, ..., end>. template class Tuple; template inline TypeByIndex& getImpl(Tuple& tuple); template inline TypeByIndex&& getImpl(Tuple&& tuple); template inline const TypeByIndex& getImpl(const Tuple& tuple); template struct TupleElement { // Encapsulates one element of a tuple. The actual tuple implementation multiply-inherits // from a TupleElement for each element, which is more efficient than a recursive definition. T value; TupleElement() KJ_DEFAULT_CONSTRUCTOR_VS2015_BUGGY constexpr inline TupleElement(const T& value): value(value) {} constexpr inline TupleElement(T&& value): value(kj::mv(value)) {} }; template struct TupleElement { // A tuple containing references can be constucted using refTuple(). T& value; constexpr inline TupleElement(T& value): value(value) {} }; template struct TupleElement> { static_assert(sizeof(Tuple*) == 0, "Tuples cannot contain other tuples -- they should be flattened."); }; template struct TupleImpl; template struct TupleImpl, Types...> : public TupleElement... { // Implementation of Tuple. The only reason we need this rather than rolling this into class // Tuple (below) is so that we can get "indexes" as an unpackable list. static_assert(sizeof...(indexes) == sizeof...(Types), "Incorrect use of TupleImpl."); TupleImpl() KJ_DEFAULT_CONSTRUCTOR_VS2015_BUGGY template inline TupleImpl(Params&&... params) : TupleElement(kj::fwd(params))... { // Work around Clang 3.2 bug 16303 where this is not detected. (Unfortunately, Clang sometimes // segfaults instead.) static_assert(sizeof...(params) == sizeof...(indexes), "Wrong number of parameters to Tuple constructor."); } template constexpr inline TupleImpl(Tuple&& other) : TupleElement(kj::fwd(getImpl(other)))... {} template constexpr inline TupleImpl(Tuple& other) : TupleElement(getImpl(other))... {} template constexpr inline TupleImpl(const Tuple& other) : TupleElement(getImpl(other))... {} }; struct MakeTupleFunc; struct MakeRefTupleFunc; template class Tuple { // The actual Tuple class (used for tuples of size other than 1). public: Tuple() KJ_DEFAULT_CONSTRUCTOR_VS2015_BUGGY template constexpr inline Tuple(Tuple&& other): impl(kj::mv(other)) {} template constexpr inline Tuple(Tuple& other): impl(other) {} template constexpr inline Tuple(const Tuple& other): impl(other) {} private: template constexpr Tuple(Params&&... params): impl(kj::fwd(params)...) {} TupleImpl, T...> impl; template friend inline TypeByIndex& getImpl(Tuple& tuple); template friend inline TypeByIndex&& getImpl(Tuple&& tuple); template friend inline const TypeByIndex& getImpl(const Tuple& tuple); friend struct MakeTupleFunc; friend struct MakeRefTupleFunc; }; template <> class Tuple<> { // Simplified zero-member version of Tuple. In particular this is important to make sure that // Tuple<>() is constexpr. }; template class Tuple; // Single-element tuple should never be used. The public API should ensure this. template inline TypeByIndex& getImpl(Tuple& tuple) { // Get member of a Tuple by index, e.g. `get<2>(myTuple)`. static_assert(index < sizeof...(T), "Tuple element index out-of-bounds."); return implicitCast>&>(tuple.impl).value; } template inline TypeByIndex&& getImpl(Tuple&& tuple) { // Get member of a Tuple by index, e.g. `get<2>(myTuple)`. static_assert(index < sizeof...(T), "Tuple element index out-of-bounds."); return kj::mv(implicitCast>&>(tuple.impl).value); } template inline const TypeByIndex& getImpl(const Tuple& tuple) { // Get member of a Tuple by index, e.g. `get<2>(myTuple)`. static_assert(index < sizeof...(T), "Tuple element index out-of-bounds."); return implicitCast>&>(tuple.impl).value; } template inline T&& getImpl(T&& value) { // Get member of a Tuple by index, e.g. `getImpl<2>(myTuple)`. // Non-tuples are equivalent to one-element tuples. static_assert(index == 0, "Tuple element index out-of-bounds."); return kj::fwd(value); } template struct ExpandAndApplyResult_; // Template which computes the return type of applying Func to T... after flattening tuples. // SoFar starts as Tuple<> and accumulates the flattened parameter types -- so after this template // is recursively expanded, T... is empty and SoFar is a Tuple containing all the parameters. template struct ExpandAndApplyResult_, First, Rest...> : public ExpandAndApplyResult_, Rest...> {}; template struct ExpandAndApplyResult_, Tuple, Rest...> : public ExpandAndApplyResult_, FirstTypes&&..., Rest...> {}; template struct ExpandAndApplyResult_, Tuple&, Rest...> : public ExpandAndApplyResult_, FirstTypes&..., Rest...> {}; template struct ExpandAndApplyResult_, const Tuple&, Rest...> : public ExpandAndApplyResult_, const FirstTypes&..., Rest...> {}; template struct ExpandAndApplyResult_> { typedef decltype(instance()(instance()...)) Type; }; template using ExpandAndApplyResult = typename ExpandAndApplyResult_, T...>::Type; // Computes the expected return type of `expandAndApply()`. template inline auto expandAndApply(Func&& func) -> ExpandAndApplyResult { return func(); } template struct ExpandAndApplyFunc { Func&& func; First&& first; ExpandAndApplyFunc(Func&& func, First&& first) : func(kj::fwd(func)), first(kj::fwd(first)) {} template auto operator()(T&&... params) -> decltype(this->func(kj::fwd(first), kj::fwd(params)...)) { return this->func(kj::fwd(first), kj::fwd(params)...); } }; template inline auto expandAndApply(Func&& func, First&& first, Rest&&... rest) -> ExpandAndApplyResult { return expandAndApply( ExpandAndApplyFunc(kj::fwd(func), kj::fwd(first)), kj::fwd(rest)...); } template inline auto expandAndApply(Func&& func, Tuple&& first, Rest&&... rest) -> ExpandAndApplyResult { return expandAndApplyWithIndexes(MakeIndexes(), kj::fwd(func), kj::mv(first), kj::fwd(rest)...); } template inline auto expandAndApply(Func&& func, Tuple& first, Rest&&... rest) -> ExpandAndApplyResult { return expandAndApplyWithIndexes(MakeIndexes(), kj::fwd(func), first, kj::fwd(rest)...); } template inline auto expandAndApply(Func&& func, const Tuple& first, Rest&&... rest) -> ExpandAndApplyResult { return expandAndApplyWithIndexes(MakeIndexes(), kj::fwd(func), first, kj::fwd(rest)...); } template inline auto expandAndApplyWithIndexes( Indexes, Func&& func, Tuple&& first, Rest&&... rest) -> ExpandAndApplyResult { return expandAndApply(kj::fwd(func), kj::mv(getImpl(first))..., kj::fwd(rest)...); } template inline auto expandAndApplyWithIndexes( Indexes, Func&& func, const Tuple& first, Rest&&... rest) -> ExpandAndApplyResult { return expandAndApply(kj::fwd(func), getImpl(first)..., kj::fwd(rest)...); } struct MakeTupleFunc { template Tuple...> operator()(Params&&... params) { return Tuple...>(kj::fwd(params)...); } template Decay operator()(Param&& param) { return kj::fwd(param); } }; struct MakeRefTupleFunc { template Tuple operator()(Params&&... params) { return Tuple(kj::fwd(params)...); } template Param operator()(Param&& param) { return kj::fwd(param); } }; } // namespace _ (private) template struct Tuple_ { typedef _::Tuple Type; }; template struct Tuple_ { typedef T Type; }; template using Tuple = typename Tuple_::Type; // Tuple type. `Tuple` (i.e. a single-element tuple) is a synonym for `T`. Tuples of size // other than 1 expand to an internal type. Either way, you can construct a Tuple using // `kj::tuple(...)`, get an element by index `i` using `kj::get(myTuple)`, and expand the tuple // as arguments to a function using `kj::apply(func, myTuple)`. // // Tuples are always flat -- that is, no element of a Tuple is ever itself a Tuple. If you // construct a tuple from other tuples, the elements are flattened and concatenated. template inline auto tuple(Params&&... params) -> decltype(_::expandAndApply(_::MakeTupleFunc(), kj::fwd(params)...)) { // Construct a new tuple from the given values. Any tuples in the argument list will be // flattened into the result. return _::expandAndApply(_::MakeTupleFunc(), kj::fwd(params)...); } template inline auto refTuple(Params&&... params) -> decltype(_::expandAndApply(_::MakeRefTupleFunc(), kj::fwd(params)...)) { // Like tuple(), but if the params include lvalue references, they will be captured as // references. rvalue references will still be captured as whole values (moved). return _::expandAndApply(_::MakeRefTupleFunc(), kj::fwd(params)...); } template inline auto get(Tuple&& tuple) -> decltype(_::getImpl(kj::fwd(tuple))) { // Unpack and return the tuple element at the given index. The index is specified as a template // parameter, e.g. `kj::get<3>(myTuple)`. return _::getImpl(kj::fwd(tuple)); } template inline auto apply(Func&& func, Params&&... params) -> decltype(_::expandAndApply(kj::fwd(func), kj::fwd(params)...)) { // Apply a function to some arguments, expanding tuples into separate arguments. return _::expandAndApply(kj::fwd(func), kj::fwd(params)...); } template struct TupleSize_ { static constexpr size_t size = 1; }; template struct TupleSize_<_::Tuple> { static constexpr size_t size = sizeof...(T); }; template constexpr size_t tupleSize() { return TupleSize_::size; } // Returns size of the tuple T. template struct IndexOfType_; template struct HasType_ { static constexpr bool value = false; }; template struct IndexOfType_ { static constexpr size_t value = 0; }; template struct HasType_ { static constexpr bool value = true; }; template struct IndexOfType_> { static constexpr size_t value = 0; static_assert(!HasType_>::value, "requested type appears multiple times in tuple"); }; template struct HasType_> { static constexpr bool value = true; }; template struct IndexOfType_> { static constexpr size_t value = IndexOfType_>::value + 1; }; template struct HasType_> { static constexpr bool value = HasType_>::value; }; template inline constexpr size_t indexOfType() { static_assert(HasType_::value, "type not present"); return IndexOfType_::value; } template struct TypeOfIndex_; template struct TypeOfIndex_<0, T> { typedef T Type; }; template struct TypeOfIndex_> : public TypeOfIndex_> {}; template struct TypeOfIndex_<0, _::Tuple> { typedef T Type; }; template using TypeOfIndex = typename TypeOfIndex_::Type; } // namespace kj