2 * Copyright 2014 Facebook, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 #ifndef FOLLY_GEN_CORE_H
18 #error This file may only be included from folly/gen/Core.h
21 #include <type_traits>
24 // Ignore shadowing warnings within this file, so includers can use -Wshadow.
25 #pragma GCC diagnostic push
26 #pragma GCC diagnostic ignored "-Wshadow"
28 namespace folly { namespace gen {
31 * IsCompatibleSignature - Trait type for testing whether a given Functor
32 * matches an expected signature.
35 * IsCompatibleSignature<FunctorType, bool(int, float)>::value
37 template<class Candidate, class Expected>
38 class IsCompatibleSignature {
39 static constexpr bool value = false;
42 template<class Candidate,
45 class IsCompatibleSignature<Candidate, ExpectedReturn(ArgTypes...)> {
48 decltype(std::declval<F>()(std::declval<ArgTypes>()...)),
49 bool good = std::is_same<ExpectedReturn, ActualReturn>::value>
50 static constexpr bool testArgs(int* p) {
55 static constexpr bool testArgs(...) {
59 static constexpr bool value = testArgs<Candidate>(nullptr);
63 * FBounded - Helper type for the curiously recurring template pattern, used
64 * heavily here to enable inlining and obviate virtual functions
68 const Self& self() const {
69 return *static_cast<const Self*>(this);
73 return *static_cast<Self*>(this);
78 * Operator - Core abstraction of an operation which may be applied to a
79 * generator. All operators implement a method compose(), which takes a
80 * generator and produces an output generator.
83 class Operator : public FBounded<Self> {
86 * compose() - Must be implemented by child class to compose a new Generator
87 * out of a given generator. This function left intentionally unimplemented.
89 template<class Source,
91 class ResultGen = void>
92 ResultGen compose(const GenImpl<Value, Source>& source) const;
96 Operator(Operator&&) noexcept = default;
97 Operator(const Operator&) = default;
98 Operator& operator=(Operator&&) noexcept = default;
99 Operator& operator=(const Operator&) = default;
103 * operator|() - For composing two operators without binding it to a
104 * particular generator.
108 class Composed = detail::Composed<Left, Right>>
109 Composed operator|(const Operator<Left>& left,
110 const Operator<Right>& right) {
111 return Composed(left.self(), right.self());
116 class Composed = detail::Composed<Left, Right>>
117 Composed operator|(const Operator<Left>& left,
118 Operator<Right>&& right) {
119 return Composed(left.self(), std::move(right.self()));
124 class Composed = detail::Composed<Left, Right>>
125 Composed operator|(Operator<Left>&& left,
126 const Operator<Right>& right) {
127 return Composed(std::move(left.self()), right.self());
132 class Composed = detail::Composed<Left, Right>>
133 Composed operator|(Operator<Left>&& left,
134 Operator<Right>&& right) {
135 return Composed(std::move(left.self()), std::move(right.self()));
139 * GenImpl - Core abstraction of a generator, an object which produces values by
140 * passing them to a given handler lambda. All generator implementations must
141 * implement apply(). foreach() may also be implemented to special case the
142 * condition where the entire sequence is consumed.
144 template<class Value,
146 class GenImpl : public FBounded<Self> {
148 // To prevent slicing
150 GenImpl(GenImpl&&) = default;
151 GenImpl(const GenImpl&) = default;
152 GenImpl& operator=(GenImpl&&) = default;
153 GenImpl& operator=(const GenImpl&) = default;
156 typedef Value ValueType;
157 typedef typename std::decay<Value>::type StorageType;
160 * apply() - Send all values produced by this generator to given handler until
161 * the handler returns false. Returns false if and only if the handler passed
162 * in returns false. Note: It should return true even if it completes (without
163 * the handler returning false), as 'Chain' uses the return value of apply to
164 * determine if it should process the second object in its chain.
166 template<class Handler>
167 bool apply(Handler&& handler) const;
170 * foreach() - Send all values produced by this generator to given lambda.
173 void foreach(Body&& body) const {
174 this->self().apply([&](Value value) -> bool {
175 static_assert(!infinite, "Cannot call foreach on infinite GenImpl");
176 body(std::forward<Value>(value));
181 // Child classes should override if the sequence generated is *definitely*
182 // infinite. 'infinite' may be false_type for some infinite sequences
183 // (due the the Halting Problem).
184 static constexpr bool infinite = false;
187 template<class LeftValue,
191 class Chain = detail::Chain<LeftValue, Left, Right>>
192 Chain operator+(const GenImpl<LeftValue, Left>& left,
193 const GenImpl<RightValue, Right>& right) {
195 std::is_same<LeftValue, RightValue>::value,
196 "Generators may ony be combined if Values are the exact same type.");
197 return Chain(left.self(), right.self());
200 template<class LeftValue,
204 class Chain = detail::Chain<LeftValue, Left, Right>>
205 Chain operator+(const GenImpl<LeftValue, Left>& left,
206 GenImpl<RightValue, Right>&& right) {
208 std::is_same<LeftValue, RightValue>::value,
209 "Generators may ony be combined if Values are the exact same type.");
210 return Chain(left.self(), std::move(right.self()));
213 template<class LeftValue,
217 class Chain = detail::Chain<LeftValue, Left, Right>>
218 Chain operator+(GenImpl<LeftValue, Left>&& left,
219 const GenImpl<RightValue, Right>& right) {
221 std::is_same<LeftValue, RightValue>::value,
222 "Generators may ony be combined if Values are the exact same type.");
223 return Chain(std::move(left.self()), right.self());
226 template<class LeftValue,
230 class Chain = detail::Chain<LeftValue, Left, Right>>
231 Chain operator+(GenImpl<LeftValue, Left>&& left,
232 GenImpl<RightValue, Right>&& right) {
234 std::is_same<LeftValue, RightValue>::value,
235 "Generators may ony be combined if Values are the exact same type.");
236 return Chain(std::move(left.self()), std::move(right.self()));
240 * operator|() which enables foreach-like usage:
241 * gen | [](Value v) -> void {...};
243 template<class Value,
246 typename std::enable_if<
247 IsCompatibleSignature<Handler, void(Value)>::value>::type
248 operator|(const GenImpl<Value, Gen>& gen, Handler&& handler) {
249 static_assert(!Gen::infinite,
250 "Cannot pull all values from an infinite sequence.");
251 gen.self().foreach(std::forward<Handler>(handler));
255 * operator|() which enables foreach-like usage with 'break' support:
256 * gen | [](Value v) -> bool { return shouldContinue(); };
258 template<class Value,
261 typename std::enable_if<
262 IsCompatibleSignature<Handler, bool(Value)>::value, bool>::type
263 operator|(const GenImpl<Value, Gen>& gen, Handler&& handler) {
264 return gen.self().apply(std::forward<Handler>(handler));
268 * operator|() for composing generators with operators, similar to boosts' range
270 * gen | map(square) | sum
272 template<class Value,
275 auto operator|(const GenImpl<Value, Gen>& gen, const Operator<Op>& op) ->
276 decltype(op.self().compose(gen.self())) {
277 return op.self().compose(gen.self());
280 template<class Value,
283 auto operator|(GenImpl<Value, Gen>&& gen, const Operator<Op>& op) ->
284 decltype(op.self().compose(std::move(gen.self()))) {
285 return op.self().compose(std::move(gen.self()));
291 * Composed - For building up a pipeline of operations to perform, absent any
292 * particular source generator. Useful for building up custom pipelines.
294 * This type is usually used by just piping two operators together:
296 * auto valuesOf = filter([](Optional<int>& o) { return o.hasValue(); })
297 * | map([](Optional<int>& o) -> int& { return o.value(); });
299 * auto valuesIncluded = from(optionals) | valuesOf | as<vector>();
301 template<class First,
303 class Composed : public Operator<Composed<First, Second>> {
309 Composed(First first, Second second)
310 : first_(std::move(first))
311 , second_(std::move(second)) {}
313 template<class Source,
315 class FirstRet = decltype(std::declval<First>()
316 .compose(std::declval<Source>())),
317 class SecondRet = decltype(std::declval<Second>()
318 .compose(std::declval<FirstRet>()))>
319 SecondRet compose(const GenImpl<Value, Source>& source) const {
320 return second_.compose(first_.compose(source.self()));
323 template<class Source,
325 class FirstRet = decltype(std::declval<First>()
326 .compose(std::declval<Source>())),
327 class SecondRet = decltype(std::declval<Second>()
328 .compose(std::declval<FirstRet>()))>
329 SecondRet compose(GenImpl<Value, Source>&& source) const {
330 return second_.compose(first_.compose(std::move(source.self())));
335 * Chain - For concatenating the values produced by two Generators.
337 * This type is primarily used through using '+' to combine generators, like:
339 * auto nums = seq(1, 10) + seq(20, 30);
340 * int total = nums | sum;
342 template<class Value, class First, class Second>
343 class Chain : public GenImpl<Value,
344 Chain<Value, First, Second>> {
348 explicit Chain(First first, Second second)
349 : first_(std::move(first))
350 , second_(std::move(second)) {}
352 template<class Handler>
353 bool apply(Handler&& handler) const {
354 return first_.apply(std::forward<Handler>(handler))
355 && second_.apply(std::forward<Handler>(handler));
359 void foreach(Body&& body) const {
360 first_.foreach(std::forward<Body>(body));
361 second_.foreach(std::forward<Body>(body));
364 static constexpr bool infinite = First::infinite || Second::infinite;
371 #pragma GCC diagnostic pop