1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//-
// Copyright 2017 Jason Lingle
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Defines the core traits used by Proptest.

use std::fmt;
use std::mem;
use std::sync::Arc;

use rand;
use rand::distributions::IndependentSample;

use test_runner::*;

/// A strategy for producing arbitrary values of a given type.
///
/// `fmt::Debug` is a hard requirement for all strategies currently due to
/// `prop_flat_map()`. This constraint will be removed when specialisation
/// becomes stable.
pub trait Strategy : fmt::Debug {
    /// The value tree generated by this `Strategy`.
    ///
    /// This also implicitly describes the ultimate value type governed by the
    /// `Strategy`.
    type Value : ValueTree;

    /// Generate a new value tree from the given runner.
    ///
    /// This may fail if there are constraints on the generated value and the
    /// generator is unable to produce anything that satisfies them. Any
    /// failure is wrapped in `TestError::Abort`.
    fn new_value
        (&self, runner: &mut TestRunner)
         -> Result<Self::Value, String>;

    /// Returns a strategy which produces values transformed by the function
    /// `fun`.
    ///
    /// There is no need (or possibility, for that matter) to define how the
    /// output is to be shrunken. Shrinking continues to take place in terms of
    /// the source value.
    fn prop_map<O : fmt::Debug,
                F : Fn (<Self::Value as ValueTree>::Value) -> O>
        (self, fun: F) -> Map<Self, F>
    where Self : Sized {
        Map { source: self, fun: Arc::new(fun) }
    }

    /// Maps values produced by this strategy into new strategies and picks
    /// values from those strategies.
    ///
    /// `fun` is used to transform the values produced by this strategy into
    /// other strategies. Values are then chosen from the derived strategies.
    /// Shrinking proceeds by shrinking individual values as well as shrinking
    /// the input used to generate the internal strategies.
    ///
    /// ## Shrinking
    ///
    /// In the case of test failure, shrinking will not only shrink the output
    /// from the combinator itself, but also the input, i.e., the strategy used
    /// to generate the output itself. Doing this requires searching the new
    /// derived strategy for a new failing input. The combinator will generate
    /// up to `Config::cases` values for this search.
    ///
    /// As a result, nested `prop_flat_map`/`Flatten` combinators risk
    /// exponential run time on this search for new failing values. To ensure
    /// that test failures occur within a reasonable amount of time, all of
    /// these combinators share a single "flat map regen" counter, and will
    /// stop generating new values if it exceeds `Config::max_flat_map_regens`.
    ///
    /// ## Example
    ///
    /// Generate two integers, where the second is always less than the first,
    /// without using filtering:
    ///
    /// ```
    /// #[macro_use] extern crate proptest;
    ///
    /// use proptest::prelude::*;
    ///
    /// proptest! {
    ///   # /*
    ///   #[test]
    ///   # */
    ///   fn test_two(
    ///     // Pick integers in the 1..65536 range, and derive a strategy
    ///     // which emits a tuple of that integer and another one which is
    ///     // some value less than it.
    ///     (a, b) in (1..65536).prop_flat_map(|a| (Just(a), 0..a))
    ///   ) {
    ///     prop_assert!(b < a);
    ///   }
    /// }
    /// #
    /// # fn main() { test_two(); }
    /// ```
    ///
    /// ## Choosing the right flat-map
    ///
    /// `Strategy` has three "flat-map" combinators. They look very similar at
    /// first, and can be used to produce superficially identical test results.
    /// For example, the following three expressions all produce inputs which
    /// are 2-tuples `(a,b)` where the `b` component is less than `a`.
    ///
    /// ```no_run
    /// # #![allow(unused_variables)]
    /// use proptest::prelude::*;
    ///
    /// let flat_map = (1..10).prop_flat_map(|a| (Just(a), 0..a));
    /// let ind_flat_map = (1..10).prop_ind_flat_map(|a| (Just(a), 0..a));
    /// let ind_flat_map2 = (1..10).prop_ind_flat_map2(|a| 0..a);
    /// ```
    ///
    /// The three do differ however in terms of how they shrink.
    ///
    /// For `flat_map`, both `a` and `b` will shrink, and the invariant that
    /// `b < a` is maintained. This is a "dependent" or "higher-order" strategy
    /// in that it remembers that the strategy for choosing `b` is dependent on
    /// the value chosen for `a`.
    ///
    /// For `ind_flat_map`, the invariant `b < a` is maintained, but only
    /// because `a` does not shrink. This is due to the fact that the
    /// dependency between the strategies is not tracked; `a` is simply seen as
    /// a constant.
    ///
    /// Finally, for `ind_flat_map2`, the invariant `b < a` is _not_
    /// maintained, because `a` can shrink independently of `b`, again because
    /// the dependency between the two variables is not tracked, but in this
    /// case the derivation of `a` is still exposed to the shrinking system.
    ///
    /// The use-cases for the independent flat-map variants is pretty narrow.
    /// For the majority of cases where invariants need to be maintained and
    /// you want all components to shrink, `prop_flat_map` is the way to go.
    /// `prop_ind_flat_map` makes the most sense when the input to the map
    /// function is not exposed in the output and shrinking across strategies
    /// is not expected to be useful. `prop_ind_flat_map2` is useful for using
    /// related values as starting points while not constraining them to that
    /// relation.
    fn prop_flat_map<S : Strategy,
                     F : Fn (<Self::Value as ValueTree>::Value) -> S>
        (self, fun: F) -> Flatten<Map<Self, F>>
    where Self : Sized {
        Flatten::new(Map { source: self, fun: Arc::new(fun) })
    }

    /// Maps values produced by this strategy into new strategies and picks
    /// values from those strategies while considering the new strategies to be
    /// independent.
    ///
    /// This is very similar to `prop_flat_map()`, but shrinking will *not*
    /// attempt to shrink the input that produces the derived strategies. This
    /// is appropriate for when the derived strategies already fully shrink in
    /// the desired way.
    ///
    /// In most cases, you want `prop_flat_map()`.
    ///
    /// See `prop_flat_map()` for a more detailed explanation on how the
    /// three flat-map combinators differ.
    fn prop_ind_flat_map<S : Strategy,
                         F : Fn (<Self::Value as ValueTree>::Value) -> S>
        (self, fun: F) -> IndFlatten<Map<Self, F>>
    where Self : Sized {
        IndFlatten(Map { source: self, fun: Arc::new(fun) })
    }

    /// Similar to `prop_ind_flat_map()`, but produces 2-tuples with the input
    /// generated from `self` in slot 0 and the derived strategy in slot 1.
    ///
    /// See `prop_flat_map()` for a more detailed explanation on how the
    /// three flat-map combinators differ differ.
    fn prop_ind_flat_map2<S : Strategy,
                          F : Fn (<Self::Value as ValueTree>::Value) -> S>
        (self, fun: F) -> IndFlattenMap<Self, F>
    where Self : Sized {
        IndFlattenMap { source: self, fun: Arc::new(fun) }
    }

    /// Returns a strategy which only produces values accepted by `fun`.
    ///
    /// This results in a very naïve form of rejection sampling and should only
    /// be used if (a) relatively few values will actually be rejected; (b) it
    /// isn't easy to express what you want by using another strategy and/or
    /// `map()`.
    ///
    /// There are a lot of downsides to this form of filtering. It slows
    /// testing down, since values must be generated but then discarded.
    /// Proptest only allows a limited number of rejects this way (across the
    /// entire `TestRunner`). Rejection can interfere with shrinking;
    /// particularly, complex filters may largely or entirely prevent shrinking
    /// from substantially altering the original value.
    ///
    /// Local rejection sampling is still preferable to rejecting the entire
    /// input to a test (via `TestCaseError::Reject`), however, and the default
    /// number of local rejections allowed is much higher than the number of
    /// whole-input rejections.
    ///
    /// `whence` is used to record where and why the rejection occurred.
    fn prop_filter<F : Fn (&<Self::Value as ValueTree>::Value) -> bool>
        (self, whence: String, fun: F) -> Filter<Self, F>
    where Self : Sized {
        Filter { source: self, whence: whence, fun: Arc::new(fun) }
    }

    /// Returns a strategy which picks uniformly from `self` and `other`.
    ///
    /// When shrinking, if a value from `other` was originally chosen but that
    /// value can be shrunken no further, it switches to a value from `self`
    /// and starts shrinking that.
    ///
    /// Be aware that chaining `prop_union` calls will result in a very
    /// right-skewed distribution. If this is not what you want, you can call
    /// the `.or()` method on the `Union` to add more values to the same union,
    /// or directly call `Union::new()`.
    ///
    /// Both `self` and `other` must be of the same type. To combine
    /// heterogeneous strategies, call the `boxed()` method on both `self` and
    /// `other` to erase the type differences before calling `prop_union()`.
    fn prop_union(self, other: Self) -> Union<Self>
    where Self : Sized {
        Union::new(vec![self, other])
    }

    /// Generate a recursive structure with `self` items as leaves.
    ///
    /// `recurse` is applied to various strategies that produce the same type
    /// as `self` with nesting depth _n_ to create a strategy that produces the
    /// same type with nesting depth _n+1_. Generated structures will have a
    /// depth between 0 and `depth` and will usually have up to `desired_size`
    /// total elements, though they may have more. `expected_branch_size` gives
    /// the expected maximum size for any collection which may contain
    /// recursive elements and is used to control branch probability to achieve
    /// the desired size. Passing a too small value can result in trees vastly
    /// larger than desired.
    ///
    /// Note that `depth` only counts branches; i.e., `depth = 0` is a single
    /// leaf, and `depth = 1` is a leaf or a branch containing only leaves.
    ///
    /// In practise, generated values usually have a lower depth than `depth`
    /// (but `depth` is a hard limit) and almost always under
    /// `expected_branch_size` (though it is not a hard limit) since the
    /// underlying code underestimates probabilities.
    ///
    /// ## Example
    ///
    /// ```rust,norun
    /// # #![allow(unused_variables)]
    /// use std::collections::HashMap;
    ///
    /// #[macro_use] extern crate proptest;
    /// use proptest::prelude::*;
    ///
    /// /// Define our own JSON AST type
    /// #[derive(Debug, Clone)]
    /// enum JsonNode {
    ///   Null,
    ///   Bool(bool),
    ///   Number(f64),
    ///   String(String),
    ///   Array(Vec<JsonNode>),
    ///   Map(HashMap<String, JsonNode>),
    /// }
    ///
    /// # fn main() {
    /// #
    /// // Define a strategy for generating leaf nodes of the AST
    /// let json_leaf = prop_oneof![
    ///   Just(JsonNode::Null),
    ///   prop::bool::ANY.prop_map(JsonNode::Bool),
    ///   prop::num::f64::ANY.prop_map(JsonNode::Number),
    ///   ".*".prop_map(JsonNode::String),
    /// ];
    ///
    /// // Now define a strategy for a whole tree
    /// let json_tree = json_leaf.prop_recursive(
    ///   4, // No more than 4 branch levels deep
    ///   64, // Target around 64 total elements
    ///   16, // Each collection is up to 16 elements long
    ///   |element| prop_oneof![
    ///     // NB `element` is an `Arc` and we'll need to reference it twice,
    ///     // so we clone it the first time.
    ///     prop::collection::vec(element.clone(), 0..16)
    ///       .prop_map(JsonNode::Array),
    ///     prop::collection::hash_map(".*", element, 0..16)
    ///       .prop_map(JsonNode::Map)
    ///   ].boxed());
    /// # }
    /// ```
    fn prop_recursive<
            F : Fn (Arc<BoxedStrategy<<Self::Value as ValueTree>::Value>>)
                    -> BoxedStrategy<<Self::Value as ValueTree>::Value>>
        (self, depth: u32, desired_size: u32, expected_branch_size: u32, recurse: F)
        -> Recursive<BoxedStrategy<<Self::Value as ValueTree>::Value>, F>
    where Self : Sized + 'static {
        Recursive {
            base: Arc::new(self.boxed()),
            recurse: Arc::new(recurse),
            depth, desired_size, expected_branch_size,
        }
    }

    /// Erases the type of this `Strategy` so it can be passed around as a
    /// simple trait object.
    fn boxed(self) -> BoxedStrategy<<Self::Value as ValueTree>::Value>
    where Self : Sized + 'static {
        Box::new(BoxedStrategyWrapper(self))
    }

    /// Wraps this strategy to prevent values from being subject to shrinking.
    ///
    /// Suppressing shrinking is useful when testing things like linear
    /// approximation functions. Ordinarily, proptest will tend to shrink the
    /// input to the function until the result is just barely outside the
    /// acceptable range whereas the original input may have produced a result
    /// far outside of it. Since this makes it harder to see what the actual
    /// problem is, making the input `NoShrink` allows learning about inputs
    /// that produce more incorrect results.
    fn no_shrink(self) -> NoShrink<Self> where Self : Sized {
        NoShrink(self)
    }
}

macro_rules! proxy_strategy {
    ($typ:ty $(, $lt:tt)*) => {
        impl<$($lt,)* S : Strategy + ?Sized> Strategy for $typ {
            type Value = S::Value;

            fn new_value(&self, runner: &mut TestRunner)
                         -> Result<Self::Value, String>
            { (**self).new_value(runner) }
        }
    };
}
proxy_strategy!(Box<S>);
proxy_strategy!(&'a S, 'a);
proxy_strategy!(&'a mut S, 'a);
proxy_strategy!(::std::rc::Rc<S>);
proxy_strategy!(::std::sync::Arc<S>);

/// A generated value and its associated shrinker.
///
/// Conceptually, a `ValueTree` represents a spectrum between a "minimally
/// complex" value and a starting, randomly-chosen value. For values such as
/// numbers, this can be thought of as a simple binary search, and this is how
/// the `ValueTree` state machine is defined.
///
/// The `ValueTree` state machine notionally has three fields: low, current,
/// and high. Initially, low is the "minimally complex" value for the type, and
/// high and current are both the initially chosen value. It can be queried for
/// its current state. When shrinking, the controlling code tries simplifying
/// the value one step. If the test failure still happens with the simplified
/// value, further simplification occurs. Otherwise, the code steps back up
/// towards the prior complexity.
///
/// The main invariants here are that the "high" value always corresponds to a
/// failing test case, and that repeated calls to `complicate()` will return
/// `false` only once the "current" value has returned to what it was before
/// the last call to `simplify()`.
pub trait ValueTree {
    /// The type of the value produced by this `ValueTree`.
    type Value : fmt::Debug;

    /// Returns the current value.
    fn current(&self) -> Self::Value;
    /// Attempts to simplify the current value. Notionally, this sets the
    /// "high" value to the current value, and the current value to a "halfway
    /// point" between high and low, rounding towards low.
    ///
    /// Returns whether any state changed as a result of this call.
    fn simplify(&mut self) -> bool;
    /// Attempts to partially undo the last simplification. Notionally, this
    /// sets the "low" value to one plus the current value, and the current
    /// value to a "halfway point" between high and the new low, rounding
    /// towards low.
    ///
    /// Returns whether any state changed as a result of this call.
    fn complicate(&mut self) -> bool;
}

impl<T : ValueTree + ?Sized> ValueTree for Box<T> {
    type Value = T::Value;
    fn current(&self) -> Self::Value { (**self).current() }
    fn simplify(&mut self) -> bool { (**self).simplify() }
    fn complicate(&mut self) -> bool { (**self).complicate() }
}

/// Shorthand for a boxed `Strategy` trait object as produced by
/// `Strategy::boxed()`.
pub type BoxedStrategy<T> = Box<Strategy<Value = Box<ValueTree<Value = T>>>>;

#[derive(Debug)]
struct BoxedStrategyWrapper<T>(T);
impl<T : Strategy> Strategy for BoxedStrategyWrapper<T>
where T::Value : 'static {
    type Value = Box<ValueTree<Value = <T::Value as ValueTree>::Value>>;

    fn new_value(&self, runner: &mut TestRunner)
        -> Result<Self::Value, String>
    {
        Ok(Box::new(self.0.new_value(runner)?))
    }
}

/// `Strategy` and `ValueTree` map adaptor.
///
/// See `Strategy::prop_map()`.
pub struct Map<S, F> {
    source: S,
    fun: Arc<F>,
}

impl<S : fmt::Debug, F> fmt::Debug for Map<S, F> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Map")
            .field("source", &self.source)
            .field("fun", &"<function>")
            .finish()
    }
}

impl<S : Clone, F> Clone for Map<S, F> {
    fn clone(&self) -> Self {
        Map {
            source: self.source.clone(),
            fun: self.fun.clone(),
        }
    }
}

impl<S : Strategy, O : fmt::Debug,
     F : Fn (<S::Value as ValueTree>::Value) -> O>
Strategy for Map<S, F> {
    type Value = Map<S::Value, F>;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        self.source.new_value(runner).map(
            |v| Map { source: v, fun: self.fun.clone() })
    }
}

impl<S : ValueTree, O : fmt::Debug, F : Fn (S::Value) -> O>
ValueTree for Map<S, F> {
    type Value = O;

    fn current(&self) -> O {
        (self.fun)(self.source.current())
    }

    fn simplify(&mut self) -> bool {
        self.source.simplify()
    }

    fn complicate(&mut self) -> bool {
        self.source.complicate()
    }
}

/// Adaptor that flattens a `Strategy` which produces other `Strategy`s into a
/// `Strategy` that picks one of those strategies and then picks values from
/// it.
#[derive(Debug, Clone, Copy)]
pub struct Flatten<S> {
    source: S,
}

impl<S : Strategy> Flatten<S> {
    /// Wrap `source` to flatten it.
    pub fn new(source: S) -> Self {
        Flatten { source }
    }
}

impl<S : Strategy> Strategy for Flatten<S>
where <S::Value as ValueTree>::Value : Strategy {
    type Value = FlattenValueTree<S::Value>;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        let meta = self.source.new_value(runner)?;
        FlattenValueTree::new(runner, meta)
    }
}

/// The `ValueTree` produced by `Flatten`.
pub struct FlattenValueTree<S : ValueTree> where S::Value : Strategy {
    meta: S,
    current: <S::Value as Strategy>::Value,
    // The final value to produce after successive calls to complicate() on the
    // underlying objects return false.
    final_complication: Option<<S::Value as Strategy>::Value>,
    // When `simplify()` or `complicate()` causes a new `Strategy` to be
    // chosen, we need to find a new failing input for that case. To do this,
    // we implement `complicate()` by regenerating values up to a number of
    // times corresponding to the maximum number of test cases. A `simplify()`
    // which does not cause a new strategy to be chosen always resets
    // `complicate_regen_remaining` to 0.
    //
    // This does unfortunately depart from the direct interpretation of
    // simplify/complicate as binary search, but is still easier to think about
    // than other implementations of higher-order strategies.
    runner: TestRunner,
    complicate_regen_remaining: u32,
}

impl<S : ValueTree> fmt::Debug for FlattenValueTree<S>
where S::Value : Strategy,
      S : fmt::Debug, <S::Value as Strategy>::Value : fmt::Debug {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("FlattenValueTree")
            .field("meta", &self.meta)
            .field("current", &self.current)
            .field("final_complication", &self.final_complication)
            .field("complicate_regen_remaining",
                   &self.complicate_regen_remaining)
            .finish()
    }
}

impl<S : ValueTree> FlattenValueTree<S> where S::Value : Strategy {
    fn new(runner: &mut TestRunner, meta: S) -> Result<Self, String> {
        let current = meta.current().new_value(runner)?;
        Ok(FlattenValueTree {
            meta, current,
            final_complication: None,
            runner: runner.partial_clone(),
            complicate_regen_remaining: 0
        })
    }
}

impl<S : ValueTree> ValueTree for FlattenValueTree<S>
where S::Value : Strategy {
    type Value = <<S::Value as Strategy>::Value as ValueTree>::Value;

    fn current(&self) -> Self::Value {
        self.current.current()
    }

    fn simplify(&mut self) -> bool {
        self.complicate_regen_remaining = 0;

        if self.current.simplify() {
            true
        } else if !self.meta.simplify() {
            false
        } else {
            match self.meta.current().new_value(&mut self.runner) {
                Ok(v) => {
                    // Shift current into final_complication and `v` into
                    // `current`.
                    self.final_complication = Some(v);
                    mem::swap(self.final_complication.as_mut().unwrap(),
                              &mut self.current);
                    // Initially complicate by regenerating the chosen value.
                    self.complicate_regen_remaining =
                        self.runner.config().cases;
                    true
                },
                Err(_) => false,
            }
        }
    }

    fn complicate(&mut self) -> bool {
        if self.complicate_regen_remaining > 0 {
            if self.runner.flat_map_regen() {
                self.complicate_regen_remaining -= 1;

                if let Ok(v) = self.meta.current().new_value(&mut self.runner) {
                    self.current = v;
                    return true;
                }
            } else {
                self.complicate_regen_remaining = 0;
            }
        }

        let res = if self.current.complicate() {
            true
        } else if self.meta.complicate() {
            match self.meta.current().new_value(&mut self.runner) {
                Ok(v) => {
                    self.complicate_regen_remaining =
                        self.runner.config().cases;
                    self.current = v;
                    true
                },
                Err(_) => false,
            }
        } else {
            false
        };

        if res {
            true
        } else if let Some(v) = self.final_complication.take() {
            self.current = v;
            true
        } else {
            false
        }
    }
}

/// Similar to `Flatten`, but does not shrink the input strategy.
///
/// See `Strategy::prop_ind_flat_map()` fore more details.
#[derive(Clone, Copy, Debug)]
pub struct IndFlatten<S>(S);

impl<S : Strategy> Strategy for IndFlatten<S>
where <S::Value as ValueTree>::Value : Strategy {
    type Value = <<S::Value as ValueTree>::Value as Strategy>::Value;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        let inner = self.0.new_value(runner)?;
        inner.current().new_value(runner)
    }
}

/// Similar to `Map` plus `Flatten`, but does not shrink the input strategy and
/// passes the original input through.
///
/// See `Strategy::prop_ind_flat_map2()` for more details.
pub struct IndFlattenMap<S, F> {
    source: S,
    fun: Arc<F>,
}

impl<S : fmt::Debug, F> fmt::Debug for IndFlattenMap<S, F> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("IndFlattenMap")
            .field("source", &self.source)
            .field("fun", &"<function>")
            .finish()
    }
}

impl<S : Clone, F> Clone for IndFlattenMap<S, F> {
    fn clone(&self) -> Self {
        IndFlattenMap {
            source: self.source.clone(),
            fun: self.fun.clone(),
        }
    }
}

impl<S : Strategy, R : Strategy,
     F : Fn (<S::Value as ValueTree>::Value) -> R>
Strategy for IndFlattenMap<S, F> {
    type Value = ::tuple::TupleValueTree<(S::Value, R::Value)>;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        let left = self.source.new_value(runner)?;
        let right_source = (self.fun)(left.current());
        let right = right_source.new_value(runner)?;

        Ok(::tuple::TupleValueTree::new((left, right)))
    }
}

/// `Strategy` and `ValueTree` filter adaptor.
///
/// See `Strategy::prop_filter()`.
pub struct Filter<S, F> {
    source: S,
    whence: String,
    fun: Arc<F>,
}

impl<S : fmt::Debug, F> fmt::Debug for Filter<S, F> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Filter")
            .field("source", &self.source)
            .field("whence", &self.whence)
            .field("fun", &"<function>")
            .finish()
    }
}

impl<S : Clone, F> Clone for Filter<S, F> {
    fn clone(&self) -> Self {
        Filter {
            source: self.source.clone(),
            whence: self.whence.clone(),
            fun: self.fun.clone(),
        }
    }
}

impl<S : Strategy,
     F : Fn (&<S::Value as ValueTree>::Value) -> bool>
Strategy for Filter<S, F> {
    type Value = Filter<S::Value, F>;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        loop {
            let val = self.source.new_value(runner)?;
            if !(self.fun)(&val.current()) {
                runner.reject_local(self.whence.clone())?;
            } else {
                return Ok(Filter {
                    source: val,
                    whence: self.whence.clone(),
                    fun: self.fun.clone(),
                })
            }
        }
    }
}

impl<S : ValueTree, F : Fn (&S::Value) -> bool>
Filter<S, F> {
    fn ensure_acceptable(&mut self) {
        while !(self.fun)(&self.source.current()) {
            if !self.source.complicate() {
                panic!("Unable to complicate filtered strategy \
                        back into acceptable value");
            }
        }
    }
}

impl<S : ValueTree, F : Fn (&S::Value) -> bool>
ValueTree for Filter<S, F> {
    type Value = S::Value;

    fn current(&self) -> S::Value {
        self.source.current()
    }

    fn simplify(&mut self) -> bool {
        if self.source.simplify() {
            self.ensure_acceptable();
            true
        } else {
            false
        }
    }

    fn complicate(&mut self) -> bool {
        if self.source.complicate() {
            self.ensure_acceptable();
            true
        } else {
            false
        }
    }
}

/// A `Strategy` which picks from one of several delegate `Stragegy`s.
///
/// See `Strategy::prop_union()`.
#[derive(Clone, Debug)]
pub struct Union<T : Strategy> {
    options: Vec<T>,
}

impl<T : Strategy> Union<T> {
    /// Create a strategy which selects uniformly from the given delegate
    /// strategies.
    ///
    /// When shrinking, after maximal simplification of the chosen element, the
    /// strategy will move to earlier options and continue simplification with
    /// those.
    ///
    /// ## Panics
    ///
    /// Panics if `options` is empty.
    pub fn new(options: Vec<T>) -> Self {
        assert!(options.len() > 0);

        Union { options: options }
    }

    /// Add `other` as an additional alternate strategy.
    pub fn or(mut self, other: T) -> Self {
        self.options.push(other);
        self
    }
}

impl<T : Strategy> Strategy for Union<T> {
    type Value = UnionValueTree<T::Value>;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        let pick = rand::distributions::Range::new(0, self.options.len())
            .ind_sample(runner.rng());

        let mut options = Vec::with_capacity(pick);
        for option in &self.options[0..pick+1] {
            options.push(option.new_value(runner)?);
        }

        Ok(UnionValueTree {
            options: options,
            pick: pick,
            min_pick: 0,
            prev_pick: None,
        })
    }
}

/// `ValueTree` corresponding to `Union`.
#[derive(Clone, Debug)]
pub struct UnionValueTree<T : ValueTree> {
    options: Vec<T>,
    pick: usize,
    min_pick: usize,
    prev_pick: Option<usize>,
}

impl<T : ValueTree> ValueTree for UnionValueTree<T> {
    type Value = T::Value;

    fn current(&self) -> T::Value {
        self.options[self.pick].current()
    }

    fn simplify(&mut self) -> bool {
        if self.options[self.pick].simplify() {
            self.prev_pick = None;
            true
        } else if self.pick > self.min_pick {
            self.prev_pick = Some(self.pick);
            self.pick -= 1;
            true
        } else {
            false
        }
    }

    fn complicate(&mut self) -> bool {
        if let Some(pick) = self.prev_pick {
            self.pick = pick;
            self.min_pick = pick;
            self.prev_pick = None;
            true
        } else {
            self.options[self.pick].complicate()
        }
    }
}

/// Return type from `Strategy::prop_recursive()`.
pub struct Recursive<B, F> {
    base: Arc<B>,
    recurse: Arc<F>,
    depth: u32,
    desired_size: u32,
    expected_branch_size: u32,
}

impl<B : fmt::Debug, F> fmt::Debug for Recursive<B, F> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Recursive")
            .field("base", &self.base)
            .field("recurse", &"<function>")
            .field("depth", &self.depth)
            .field("desired_size", &self.desired_size)
            .field("expected_branch_size", &self.expected_branch_size)
            .finish()
    }
}

impl<B, F> Clone for Recursive<B, F> {
    fn clone(&self) -> Self {
        Recursive {
            base: self.base.clone(),
            recurse: self.recurse.clone(),
            depth: self.depth,
            desired_size: self.desired_size,
            expected_branch_size: self.expected_branch_size,
        }
    }
}

impl<T : fmt::Debug + 'static,
     F : Fn (Arc<BoxedStrategy<T>>) -> BoxedStrategy<T>>
Strategy for Recursive<BoxedStrategy<T>, F> {
    type Value = Box<ValueTree<Value = T>>;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        // Since the generator is stateless, we can't implement any "absolutely
        // X many items" rule. We _can_, however, with extremely high
        // probability, obtain a value near what we want by using decaying
        // probabilities of branching as we go down the tree.
        //
        // We are given a target size S and a branch size K (branch size =
        // expected number of items immediately below each branch). We select
        // some probability P for each level.
        //
        // A single level l is thus expected to hold PlK branches. Each of
        // those will have P(l+1)K child branches of their own, so there are
        // PlP(l+1)K² second-level branches. The total branches in the tree is
        // thus (Σ PlK^l) for l from 0 to infinity. Each level is expected to
        // hold K items, so the total number of items is simply K times the
        // number of branches, or (K Σ PlK^l). So we want to find a P sequence
        // such that (lim (K Σ PlK^l) = S), or more simply,
        // (lim Σ PlK^l = S/K).
        //
        // Let Q be a second probability sequence such that Pl = Ql/K^l. This
        // changes the formulation to (lim Σ Ql = S/K). The series Σ0.5^(l+1)
        // converges on 1.0, so we can let Ql = S/K * 0.5^(l+1), and so
        // Pl = S/K^(l+1) * 0.5^(l+1) = S / (2K) ^ (l+1)
        //
        // We don't actually have infinite levels here since we _can_ easily
        // cap to a fixed max depth, so this will be a minor underestimate. We
        // also clamp all probabilities to 0.9 to ensure that we can't end up
        // with levels which are always pure branches, which further
        // underestimates size.

        let mut branch_probabilities = Vec::new();
        let mut k2 = self.expected_branch_size as u64 * 2;
        for _ in 0..self.depth {
            branch_probabilities.push(self.desired_size as f64 / k2 as f64);
            k2 = k2.saturating_mul(self.expected_branch_size as u64 * 2);
        }

        let mut strat = self.base.clone();
        while let Some(branch_probability) = branch_probabilities.pop() {
            let recursive_choice = Arc::new((self.recurse)(strat.clone()));
            let non_recursive_choice = strat;
            strat = Arc::new(
                ::bool::weighted(branch_probability.min(0.9))
                    .prop_ind_flat_map(move |branch| if branch {
                        recursive_choice.clone()
                    } else {
                        non_recursive_choice.clone()
                    }).boxed());
        }

        strat.new_value(runner)
    }
}

/// A `Strategy` which always produces a single value value and never
/// simplifies.
#[derive(Clone, Copy, Debug)]
pub struct Just<T : Clone + fmt::Debug>(
    /// The value produced by this strategy.
    pub T);

/// Deprecated alias for `Just`.
#[deprecated]
pub use self::Just as Singleton;

impl<T : Clone + fmt::Debug> Strategy for Just<T> {
    type Value = Self;

    fn new_value(&self, _: &mut TestRunner) -> Result<Self::Value, String> {
        Ok(self.clone())
    }
}

impl<T : Clone + fmt::Debug> ValueTree for Just<T> {
    type Value = T;

    fn current(&self) -> T {
        self.0.clone()
    }

    fn simplify(&mut self) -> bool { false }
    fn complicate(&mut self) -> bool { false }
}

/// Wraps a `Strategy` or `ValueTree` to suppress shrinking of generated
/// values.
///
/// See `Strategy::no_shrink()` for more details.
#[derive(Clone, Copy, Debug)]
pub struct NoShrink<T>(T);

impl<T : Strategy> Strategy for NoShrink<T> {
    type Value = NoShrink<T::Value>;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<Self::Value, String> {
        self.0.new_value(runner).map(NoShrink)
    }
}

impl<T : ValueTree> ValueTree for NoShrink<T> {
    type Value = T::Value;

    fn current(&self) -> T::Value {
        self.0.current()
    }

    fn simplify(&mut self) -> bool { false }
    fn complicate(&mut self) -> bool { false }
}

#[cfg(test)]
mod test {
    use std::cmp::max;

    use super::*;

    #[test]
    fn test_map() {
        TestRunner::new(Config::default())
            .run(&(0..10).prop_map(|v| v * 2), |&v| {
                assert!(0 == v % 2);
                Ok(())
            }).unwrap();
    }

    #[test]
    fn test_flat_map() {
        // Pick random integer A, then random integer B which is ±5 of A and
        // assert that B <= A if A > 10000. Shrinking should always converge to
        // A=10001, B=10002.
        let input = (0..65536).prop_flat_map(
            |a| (Just(a), (a-5..a+5)));

        let mut failures = 0;
        for _ in 0..1000 {
            let mut runner = TestRunner::new(Config::default());
            let case = input.new_value(&mut runner).unwrap();
            let result = runner.run_one(case, |&(a, b)| {
                if a <= 10000 || b <= a {
                    Ok(())
                } else {
                    Err(TestCaseError::Fail("fail".to_owned()))
                }
            });

            match result {
                Ok(_) => { },
                Err(TestError::Fail(_, v)) => {
                    failures += 1;
                    assert_eq!((10001, 10002), v);
                },
                result => panic!("Unexpected result: {:?}", result),
            }
        }

        assert!(failures > 250);
    }

    #[test]
    fn flat_map_respects_regen_limit() {
        use std::sync::atomic::{AtomicBool, Ordering};

        let input = (0..65536)
            .prop_flat_map(|_| 0..65536)
            .prop_flat_map(|_| 0..65536)
            .prop_flat_map(|_| 0..65536)
            .prop_flat_map(|_| 0..65536)
            .prop_flat_map(|_| 0..65536);

        // Arteficially make the first case fail and all others pass, so that
        // the regeneration logic futilely searches for another failing
        // example and eventually gives up. Unfortunately, the test is sort of
        // semi-decidable; if the limit *doesn't* work, the test just runs
        // almost forever.
        let pass = AtomicBool::new(false);
        let mut runner = TestRunner::new(Config {
            max_flat_map_regens: 1000,
            .. Config::default()
        });
        let case = input.new_value(&mut runner).unwrap();
        let _ = runner.run_one(case, |_| {
            if pass.fetch_or(true, Ordering::SeqCst) {
                Ok(())
            } else {
                Err(TestCaseError::Fail("fail".to_owned()))
            }
        });
    }

    #[test]
    fn test_filter() {
        let input = (0..256).prop_filter("%3".to_owned(), |&v| 0 == v % 3);

        for _ in 0..256 {
            let mut runner = TestRunner::new(Config::default());
            let mut case = input.new_value(&mut runner).unwrap();

            assert!(0 == case.current() % 3);

            while case.simplify() {
                assert!(0 == case.current() % 3);
            }
            assert!(0 == case.current() % 3);
        }
    }

    #[test]
    fn test_union() {
        let input = (10u32..20u32).prop_union(30u32..40u32);
        // Expect that 25% of cases pass (left input happens to be < 15, and
        // left is chosen as initial value). Of the 75% that fail, 50% should
        // converge to 15 and 50% to 30 (the latter because the left is beneath
        // the passing threshold).
        let mut passed = 0;
        let mut converged_low = 0;
        let mut converged_high = 0;
        for _ in 0..256 {
            let mut runner = TestRunner::new(Config::default());
            let case = input.new_value(&mut runner).unwrap();
            let result = runner.run_one(case, |&v| if v < 15 {
                Ok(())
            } else {
                Err(TestCaseError::Fail("fail".to_owned()))
            });

            match result {
                Ok(true) => passed += 1,
                Err(TestError::Fail(_, 15)) => converged_low += 1,
                Err(TestError::Fail(_, 30)) => converged_high += 1,
                e => panic!("Unexpected result: {:?}", e),
            }
        }

        assert!(passed >= 32 && passed <= 96,
                "Bad passed count: {}", passed);
        assert!(converged_low >= 32 && converged_low <= 160,
                "Bad converged_low count: {}", converged_low);
        assert!(converged_high >= 32 && converged_high <= 160,
                "Bad converged_high count: {}", converged_high);
    }

    #[test]
    fn test_recursive() {
        #[derive(Clone, Debug)]
        enum Tree {
            Leaf,
            Branch(Vec<Tree>),
        }

        impl Tree {
            fn stats(&self) -> (u32, u32) {
                match *self {
                    Tree::Leaf => (0, 1),
                    Tree::Branch(ref children) => {
                        let mut depth = 0;
                        let mut count = 0;
                        for child in children {
                            let (d, c) = child.stats();
                            depth = max(d, depth);
                            count += c;
                        }

                        (depth + 1, count + 1)
                    }
                }
            }
        }

        let mut max_depth = 0;
        let mut max_count = 0;

        let strat = Just(Tree::Leaf).prop_recursive(
            4, 64, 16,
            |element| ::collection::vec(element, 8..16)
                .prop_map(Tree::Branch).boxed());


        let mut runner = TestRunner::new(Config::default());
        for _ in 0..65536 {
            let tree = strat.new_value(&mut runner).unwrap().current();
            let (depth, count) = tree.stats();
            assert!(depth <= 4, "Got depth {}", depth);
            assert!(count <= 128, "Got count {}", count);
            max_depth = max(depth, max_depth);
            max_count = max(count, max_count);
        }

        assert!(max_depth >= 3, "Only got max depth {}", max_depth);
        assert!(max_count > 48, "Only got max count {}", max_count);
    }
}