guard<Exception>()
[folly.git] / folly / experimental / Gen.h
1 /*
2  * Copyright 2013 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #pragma once
18
19 #include <functional>
20 #include <memory>
21 #include <type_traits>
22 #include <utility>
23 #include <algorithm>
24 #include <random>
25 #include <vector>
26 #include <unordered_set>
27
28 #include "folly/Range.h"
29 #include "folly/Optional.h"
30 #include "folly/Conv.h"
31
32 /**
33  * Generator-based Sequence Comprehensions in C++, akin to C#'s LINQ
34  * @author Tom Jackson <tjackson@fb.com>
35  *
36  * This library makes it possible to write declarative comprehensions for
37  * processing sequences of values efficiently in C++. The operators should be
38  * familiar to those with experience in functional programming, and the
39  * performance will be virtually identical to the equivalent, boilerplate C++
40  * implementations.
41  *
42  * Generator objects may be created from either an stl-like container (anything
43  * supporting begin() and end()), from sequences of values, or from another
44  * generator (see below). To create a generator that pulls values from a vector,
45  * for example, one could write:
46  *
47  *   vector<string> names { "Jack", "Jill", "Sara", "Tom" };
48  *   auto gen = from(names);
49  *
50  * Generators are composed by building new generators out of old ones through
51  * the use of operators. These are reminicent of shell pipelines, and afford
52  * similar composition. Lambda functions are used liberally to describe how to
53  * handle individual values:
54  *
55  *   auto lengths = gen
56  *                | mapped([](const fbstring& name) { return name.size(); });
57  *
58  * Generators are lazy; they don't actually perform any work until they need to.
59  * As an example, the 'lengths' generator (above) won't actually invoke the
60  * provided lambda until values are needed:
61  *
62  *   auto lengthVector = lengths | as<std::vector>();
63  *   auto totalLength = lengths | sum;
64  *
65  * 'auto' is useful in here because the actual types of the generators objects
66  * are usually complicated and implementation-sensitive.
67  *
68  * If a simpler type is desired (for returning, as an example), VirtualGen<T>
69  * may be used to wrap the generator in a polymorphic wrapper:
70  *
71  *  VirtualGen<float> powersOfE() {
72  *    return seq(1) | mapped(&expf);
73  *  }
74  *
75  * To learn more about this library, including the use of infinite generators,
76  * see the examples in the comments, or the docs (coming soon).
77 */
78
79 namespace folly { namespace gen {
80
81 template<class Value, class Self>
82 class GenImpl;
83
84 template<class Self>
85 class Operator;
86
87 class EmptySequence : public std::exception {
88 public:
89   virtual const char* what() const noexcept {
90     return "This operation cannot be called on an empty sequence";
91   }
92 };
93
94 class Less {
95 public:
96   template<class First,
97            class Second>
98   auto operator()(const First& first, const Second& second) const ->
99   decltype(first < second) {
100     return first < second;
101   }
102 };
103
104 class Greater {
105 public:
106   template<class First,
107            class Second>
108   auto operator()(const First& first, const Second& second) const ->
109   decltype(first > second) {
110     return first > second;
111   }
112 };
113
114 template<int n>
115 class Get {
116 public:
117   template<class Value>
118   auto operator()(Value&& value) const ->
119   decltype(std::get<n>(std::forward<Value>(value))) {
120     return std::get<n>(std::forward<Value>(value));
121   }
122 };
123
124 template<class Class,
125          class Result>
126 class MemberFunction {
127  public:
128   typedef Result (Class::*MemberPtr)();
129  private:
130   MemberPtr member_;
131  public:
132   explicit MemberFunction(MemberPtr member)
133     : member_(member)
134   {}
135
136   Result operator()(Class&& x) const {
137     return (x.*member_)();
138   }
139
140   Result operator()(Class& x) const {
141     return (x.*member_)();
142   }
143 };
144
145 template<class Class,
146          class Result>
147 class ConstMemberFunction{
148  public:
149   typedef Result (Class::*MemberPtr)() const;
150  private:
151   MemberPtr member_;
152  public:
153   explicit ConstMemberFunction(MemberPtr member)
154     : member_(member)
155   {}
156
157   Result operator()(const Class& x) const {
158     return (x.*member_)();
159   }
160 };
161
162 template<class Class,
163          class FieldType>
164 class Field {
165  public:
166   typedef FieldType (Class::*FieldPtr);
167  private:
168   FieldPtr field_;
169  public:
170   explicit Field(FieldPtr field)
171     : field_(field)
172   {}
173
174   const FieldType& operator()(const Class& x) const {
175     return x.*field_;
176   }
177
178   FieldType& operator()(Class& x) const {
179     return x.*field_;
180   }
181
182   FieldType&& operator()(Class&& x) const {
183     return std::move(x.*field_);
184   }
185 };
186
187 class Move {
188 public:
189   template<class Value>
190   auto operator()(Value&& value) const ->
191   decltype(std::move(std::forward<Value>(value))) {
192     return std::move(std::forward<Value>(value));
193   }
194 };
195
196 class Identity {
197 public:
198   template<class Value>
199   auto operator()(Value&& value) const ->
200   decltype(std::forward<Value>(value)) {
201     return std::forward<Value>(value);
202   }
203 };
204
205 template <class Dest>
206 class Cast {
207  public:
208   template <class Value>
209   Dest operator()(Value&& value) const {
210     return Dest(std::forward<Value>(value));
211   }
212 };
213
214 template <class Dest>
215 class To {
216  public:
217   template <class Value>
218   Dest operator()(Value&& value) const {
219     return ::folly::to<Dest>(std::forward<Value>(value));
220   }
221 };
222
223 // Specialization to allow String->StringPiece conversion
224 template <>
225 class To<StringPiece> {
226  public:
227   StringPiece operator()(StringPiece src) const {
228     return src;
229   }
230 };
231
232 namespace detail {
233
234 template<class Self>
235 struct FBounded;
236
237 /*
238  * Type Traits
239  */
240 template<class Container>
241 struct ValueTypeOfRange {
242  private:
243   static Container container_;
244  public:
245   typedef decltype(*std::begin(container_))
246     RefType;
247   typedef typename std::decay<decltype(*std::begin(container_))>::type
248     StorageType;
249 };
250
251
252 /*
253  * Sources
254  */
255 template<class Container,
256          class Value = typename ValueTypeOfRange<Container>::RefType>
257 class ReferencedSource;
258
259 template<class Value,
260          class Container = std::vector<typename std::decay<Value>::type>>
261 class CopiedSource;
262
263 template<class Value, bool endless = false, bool endInclusive = false>
264 class Sequence;
265
266 template<class Value, class First, class Second>
267 class Chain;
268
269 template<class Value, class Source>
270 class Yield;
271
272 template<class Value>
273 class Empty;
274
275
276 /*
277  * Operators
278  */
279 template<class Predicate>
280 class Map;
281
282 template<class Predicate>
283 class Filter;
284
285 template<class Predicate>
286 class Until;
287
288 class Take;
289
290 template<class Rand>
291 class Sample;
292
293 class Skip;
294
295 template<class Selector, class Comparer = Less>
296 class Order;
297
298 template<class Selector>
299 class Distinct;
300
301 template<class First, class Second>
302 class Composed;
303
304 template<class Expected>
305 class TypeAssertion;
306
307 /*
308  * Sinks
309  */
310 template<class Seed,
311          class Fold>
312 class FoldLeft;
313
314 class First;
315
316 class Any;
317
318 template<class Predicate>
319 class All;
320
321 template<class Reducer>
322 class Reduce;
323
324 class Sum;
325
326 template<class Selector,
327          class Comparer>
328 class Min;
329
330 template<class Container>
331 class Collect;
332
333 template<template<class, class> class Collection = std::vector,
334          template<class> class Allocator = std::allocator>
335 class CollectTemplate;
336
337 template<class Collection>
338 class Append;
339
340 template<class Value>
341 struct GeneratorBuilder;
342
343 template<class Needle>
344 class Contains;
345
346 template<class Exception,
347          class ErrorHandler>
348 class Guard;
349
350 }
351
352 /**
353  * Polymorphic wrapper
354  **/
355 template<class Value>
356 class VirtualGen;
357
358 /*
359  * Source Factories
360  */
361 template<class Container,
362          class From = detail::ReferencedSource<const Container>>
363 From fromConst(const Container& source) {
364   return From(&source);
365 }
366
367 template<class Container,
368          class From = detail::ReferencedSource<Container>>
369 From from(Container& source) {
370   return From(&source);
371 }
372
373 template<class Container,
374          class Value =
375            typename detail::ValueTypeOfRange<Container>::StorageType,
376          class CopyOf = detail::CopiedSource<Value>>
377 CopyOf fromCopy(Container&& source) {
378   return CopyOf(std::forward<Container>(source));
379 }
380
381 template<class Value,
382          class From = detail::CopiedSource<Value>>
383 From from(std::initializer_list<Value> source) {
384   return From(source);
385 }
386
387 template<class Container,
388          class From = detail::CopiedSource<typename Container::value_type,
389                                            Container>>
390 From from(Container&& source) {
391   return From(std::move(source));
392 }
393
394 template<class Value, class Gen = detail::Sequence<Value, false, false>>
395 Gen range(Value begin, Value end) {
396   return Gen(begin, end);
397 }
398
399 template<class Value,
400          class Gen = detail::Sequence<Value, false, true>>
401 Gen seq(Value first, Value last) {
402   return Gen(first, last);
403 }
404
405 template<class Value,
406          class Gen = detail::Sequence<Value, true>>
407 Gen seq(Value begin) {
408   return Gen(begin);
409 }
410
411 template<class Value,
412          class Source,
413          class Yield = detail::Yield<Value, Source>>
414 Yield generator(Source&& source) {
415   return Yield(std::forward<Source>(source));
416 }
417
418 /*
419  * Create inline generator, used like:
420  *
421  *  auto gen = GENERATOR(int) { yield(1); yield(2); };
422  */
423 #define GENERATOR(TYPE)                            \
424   ::folly::gen::detail::GeneratorBuilder<TYPE>() + \
425    [=](const std::function<void(TYPE)>& yield)
426
427 /*
428  * empty() - for producing empty sequences.
429  */
430 template<class Value>
431 detail::Empty<Value> empty() {
432   return {};
433 }
434
435 /*
436  * Operator Factories
437  */
438 template<class Predicate,
439          class Map = detail::Map<Predicate>>
440 Map mapped(Predicate pred = Predicate()) {
441   return Map(std::move(pred));
442 }
443
444 template<class Predicate,
445          class Map = detail::Map<Predicate>>
446 Map map(Predicate pred = Predicate()) {
447   return Map(std::move(pred));
448 }
449
450 /*
451  * member(...) - For extracting a member from each value.
452  *
453  *  vector<string> strings = ...;
454  *  auto sizes = from(strings) | member(&string::size);
455  *
456  * If a member is const overridden (like 'front()'), pass template parameter
457  * 'Const' to select the const version, or 'Mutable' to select the non-const
458  * version:
459  *
460  *  auto heads = from(strings) | member<Const>(&string::front);
461  */
462 enum MemberType {
463   Const,
464   Mutable
465 };
466
467 template<MemberType Constness = Const,
468          class Class,
469          class Return,
470          class Mem = ConstMemberFunction<Class, Return>,
471          class Map = detail::Map<Mem>>
472 typename std::enable_if<Constness == Const, Map>::type
473 member(Return (Class::*member)() const) {
474   return Map(Mem(member));
475 }
476
477 template<MemberType Constness = Mutable,
478          class Class,
479          class Return,
480          class Mem = MemberFunction<Class, Return>,
481          class Map = detail::Map<Mem>>
482 typename std::enable_if<Constness == Mutable, Map>::type
483 member(Return (Class::*member)()) {
484   return Map(Mem(member));
485 }
486
487 /*
488  * field(...) - For extracting a field from each value.
489  *
490  *  vector<Item> items = ...;
491  *  auto names = from(items) | field(&Item::name);
492  *
493  * Note that if the values of the generator are rvalues, any non-reference
494  * fields will be rvalues as well. As an example, the code below does not copy
495  * any strings, only moves them:
496  *
497  *  auto namesVector = from(items)
498  *                   | move
499  *                   | field(&Item::name)
500  *                   | as<vector>();
501  */
502 template<class Class,
503          class FieldType,
504          class Field = Field<Class, FieldType>,
505          class Map = detail::Map<Field>>
506 Map field(FieldType Class::*field) {
507   return Map(Field(field));
508 }
509
510 template<class Predicate,
511          class Filter = detail::Filter<Predicate>>
512 Filter filter(Predicate pred = Predicate()) {
513   return Filter(std::move(pred));
514 }
515
516 template<class Predicate,
517          class All = detail::All<Predicate>>
518 All all(Predicate pred = Predicate()) {
519   return All(std::move(pred));
520 }
521
522 template<class Predicate,
523          class Until = detail::Until<Predicate>>
524 Until until(Predicate pred = Predicate()) {
525   return Until(std::move(pred));
526 }
527
528 template<class Selector,
529          class Comparer = Less,
530          class Order = detail::Order<Selector, Comparer>>
531 Order orderBy(Selector selector = Identity(),
532               Comparer comparer = Comparer()) {
533   return Order(std::move(selector),
534                std::move(comparer));
535 }
536
537 template<class Selector,
538          class Order = detail::Order<Selector, Greater>>
539 Order orderByDescending(Selector selector = Identity()) {
540   return Order(std::move(selector));
541 }
542
543 template<class Selector,
544          class Distinct = detail::Distinct<Selector>>
545 Distinct distinctBy(Selector selector = Identity()) {
546   return Distinct(std::move(selector));
547 }
548
549 template<int n,
550          class Get = detail::Map<Get<n>>>
551 Get get() {
552   return Get();
553 }
554
555 // construct Dest from each value
556 template <class Dest,
557           class Cast = detail::Map<Cast<Dest>>>
558 Cast eachAs() {
559   return Cast();
560 }
561
562 // call folly::to on each value
563 template <class Dest,
564           class To = detail::Map<To<Dest>>>
565 To eachTo() {
566   return To();
567 }
568
569 template<class Value>
570 detail::TypeAssertion<Value> assert_type() {
571   return {};
572 }
573
574 /*
575  * Sink Factories
576  */
577 template<class Seed,
578          class Fold,
579          class FoldLeft = detail::FoldLeft<Seed, Fold>>
580 FoldLeft foldl(Seed seed = Seed(),
581                Fold fold = Fold()) {
582   return FoldLeft(std::move(seed),
583                   std::move(fold));
584 }
585
586 template<class Reducer,
587          class Reduce = detail::Reduce<Reducer>>
588 Reduce reduce(Reducer reducer = Reducer()) {
589   return Reduce(std::move(reducer));
590 }
591
592 template<class Selector = Identity,
593          class Min = detail::Min<Selector, Less>>
594 Min minBy(Selector selector = Selector()) {
595   return Min(std::move(selector));
596 }
597
598 template<class Selector,
599          class MaxBy = detail::Min<Selector, Greater>>
600 MaxBy maxBy(Selector selector = Selector()) {
601   return MaxBy(std::move(selector));
602 }
603
604 template<class Collection,
605          class Collect = detail::Collect<Collection>>
606 Collect as() {
607   return Collect();
608 }
609
610 template<template<class, class> class Container = std::vector,
611          template<class> class Allocator = std::allocator,
612          class Collect = detail::CollectTemplate<Container, Allocator>>
613 Collect as() {
614   return Collect();
615 }
616
617 template<class Collection,
618          class Append = detail::Append<Collection>>
619 Append appendTo(Collection& collection) {
620   return Append(&collection);
621 }
622
623 template<class Needle,
624          class Contains = detail::Contains<typename std::decay<Needle>::type>>
625 Contains contains(Needle&& needle) {
626   return Contains(std::forward<Needle>(needle));
627 }
628
629 template<class Exception,
630          class ErrorHandler,
631          class Guard = detail::Guard<Exception,
632                                      typename std::decay<ErrorHandler>::type>>
633 Guard guard(ErrorHandler&& handler) {
634   return Guard(std::forward<ErrorHandler>(handler));
635 }
636
637 }} // folly::gen
638
639 #include "folly/experimental/Gen-inl.h"