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
//-
// 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.

//! Strategies for generating `char` values.
//!
//! Unlike most strategies in Proptest, character generation is by default
//! biased to particular values known to be difficult to handle in various
//! circumstances.
//!
//! The main things of interest are `ANY` to generate truly arbitrary
//! characters, and `range()` and `ranges()` to select characters from
//! inclusive ranges.

use std::borrow::Cow;

use rand::Rng;

use num;
use strategy::*;
use test_runner::*;

/// A default set of characters to consider as "special" during character
/// generation.
///
/// Most of the characters here were chosen specifically because they are
/// difficult to handle in particular contexts.
pub const DEFAULT_SPECIAL_CHARS: &[char] = &[
    // Things to give shell scripts and filesystem logic difficulties
    '/', '\\', '$', '.', '*', '{', '\'', '"', '`', ':',
    // Characters with special significance in URLs and elsewhere
    '?', '%', '=', '&', '<',
    // Interesting ASCII control characters
    // NUL, HT,   CR,   LF,   VT      ESC     DEL
    '\x00', '\t', '\r', '\n', '\x0B', '\x1B', '\x7F',
    // ¥ both to test simple Unicode handling and because it has interesting
    // properties on MS Shift-JIS systems.
    '¥',
    // No non-Unicode encoding has both ¥ and Ѩ
    'Ѩ',
    // More Unicode edge-cases: BOM, replacement character, and non-BMP
    '\u{FEFF}', '\u{FFFD}', '🕴',
];

/// A default sequence of ranges used preferentially when generating random
/// characters.
pub const DEFAULT_PREFERRED_RANGES: &[(char, char)] = &[
    // ASCII printable
    (' ', '~'), (' ', '~'), (' ', '~'), (' ', '~'), (' ', '~'),
    // Latin-1
    ('\u{0040}', '\u{00ff}'),
];

/// Selects a random character the way `CharStrategy` does.
///
/// If `special` is non-empty, there is a 50% chance that a character from this
/// array is chosen randomly, and will be returned if that character falls
/// within `ranges`.
///
/// If `preferred` is non-empty, there is a 50% chance that any generation
/// which gets past the `special` step picks a random element from this list,
/// then a random character from within that range (both endpoints inclusive).
/// That character will be returned if it falls within `ranges`.
///
/// In all other cases, an element is picked randomly from `ranges` and a
/// random character within the range (both endpoints inclusive) is chosen and
/// returned.
///
/// Notice that in all cases, `ranges` completely defines the set of characters
/// that can possibly be defined.
///
/// It is legal for ranges in all cases to contain non-characters.
///
/// Both `preferred` and `ranges` bias selection towards characters in smaller
/// ranges. This is deliberate. `preferred` is usually tuned to select
/// particular characters anyway. `ranges` is usually derived from some
/// external property, and the fact that a range is small often means it is
/// more interesting.
pub fn select_char<R : Rng>(rnd: &mut R,
                            special: &[char],
                            preferred: &[(char,char)],
                            ranges: &[(char,char)]) -> char {
    let (base, offset) = select_range_index(rnd, special, preferred, ranges);
    ::std::char::from_u32(base + offset).expect("bad character selected")
}

fn select_range_index<R : Rng>(rnd: &mut R,
                               special: &[char],
                               preferred: &[(char,char)],
                               ranges: &[(char,char)])
                               -> (u32, u32) {
    fn in_range(ranges: &[(char,char)], ch: char) -> Option<(u32, u32)> {
        ranges.iter().find(|&&(lo, hi)| ch >= lo && ch <= hi).map(
            |&(lo, _)| (lo as u32, ch as u32 - lo as u32))
    }

    if !special.is_empty() && rnd.gen() {
        let s = special[rnd.gen_range(0, special.len())];
        if let Some(ret) = in_range(ranges, s) { return ret; }
    }

    if !preferred.is_empty() && rnd.gen() {
        let (lo, hi) = preferred[rnd.gen_range(0, preferred.len())];
        if let Some(ch) = ::std::char::from_u32(
            rnd.gen_range(lo as u32, hi as u32 + 1))
        {
            if let Some(ret) = in_range(ranges, ch) { return ret; }
        }
    }

    for _ in 0..65536 {
        let (lo, hi) = ranges[rnd.gen_range(0, ranges.len())];
        if let Some(ch) = ::std::char::from_u32(
            rnd.gen_range(lo as u32, hi as u32 + 1))
        { return (lo as u32, ch as u32 - lo as u32); }
    }

    // Give up and return a character we at least know is valid.
    (ranges[0].0 as u32, 0)
}

/// Strategy for generating `char`s.
///
/// Character selection is more sophisticated than integer selection. Naïve
/// selection (particularly in the larger context of generating strings) would
/// result in starting inputs like `ꂡ螧轎ቶᢹ糦狥芹ᘆ㶏曊ᒀ踔虙ჲ` and "simplified"
/// inputs consisting mostly of control characters. It also has difficulty
/// locating edge cases, since the vast majority of code points (such as the
/// enormous CJK regions) don't cause problems for anything with even basic
/// Unicode support.
///
/// Instead, character selection is always based on explicit ranges, and is
/// designed to bias to specifically chosen characters and character ranges to
/// produce inputs that are both more useful and easier for humans to
/// understand. There are also hard-wired simplification targets based on ASCII
/// instead of simply simplifying towards NUL to avoid problematic inputs being
/// reduced to a bunch of NUL characters.
///
/// Shrinking never crosses ranges. If you have a complex range like `[A-Za-z]`
/// and the starting point `x` is chosen, it will not shrink to the first `A-Z`
/// group, but rather simply to `a`.
///
/// The usual way to get instances of this class is with the module-level `ANY`
/// constant or `range` function. Directly constructing a `CharStrategy` is
/// only necessary for complex ranges or to override the default biases.
#[derive(Debug, Clone)]
pub struct CharStrategy<'a> {
    special: Cow<'a, [char]>,
    preferred: Cow<'a, [(char,char)]>,
    ranges: Cow<'a, [(char,char)]>,
}

impl<'a> CharStrategy<'a> {
    /// Construct a new `CharStrategy` with the parameters it will pass to the
    /// function underlying `select_char()`.
    ///
    /// All arguments as per `select_char()`.
    pub fn new(special: Cow<'a, [char]>,
               preferred: Cow<'a, [(char,char)]>,
               ranges: Cow<'a, [(char,char)]>) -> Self {
        CharStrategy {
            special: special,
            preferred: preferred,
            ranges: ranges,
        }
    }
}

const WHOLE_RANGE: &[(char,char)] = &[
    ('\x00', ::std::char::MAX)
];

/// The `CharStrategy` which picks from literally any character, with
/// the default biases.
pub const ANY: CharStrategy<'static> = CharStrategy {
    special: Cow::Borrowed(DEFAULT_SPECIAL_CHARS),
    preferred: Cow::Borrowed(DEFAULT_PREFERRED_RANGES),
    ranges: Cow::Borrowed(WHOLE_RANGE),
};

/// Creates a `CharStrategy` which selects characters within the given
/// endpoints, inclusive, using the default biases.
pub fn range(start: char, end: char) -> CharStrategy<'static> {
    CharStrategy {
        special: Cow::Borrowed(DEFAULT_SPECIAL_CHARS),
        preferred: Cow::Borrowed(DEFAULT_PREFERRED_RANGES),
        ranges: Cow::Owned(vec![(start, end)]),
    }
}

/// Creates a `CharStrategy` which selects characters within the given ranges,
/// all inclusive, using the default biases.
pub fn ranges(ranges: Cow<[(char, char)]>) -> CharStrategy {
    CharStrategy {
        special: Cow::Borrowed(DEFAULT_SPECIAL_CHARS),
        preferred: Cow::Borrowed(DEFAULT_PREFERRED_RANGES),
        ranges: ranges,
    }
}

/// The `ValueTree` corresponding to `CharStrategy`.
#[derive(Debug, Clone, Copy)]
pub struct CharValueTree {
    value: num::u32::BinarySearch,
}

impl<'a> Strategy for CharStrategy<'a> {
    type Value = CharValueTree;

    fn new_value(&self, runner: &mut TestRunner)
                 -> Result<CharValueTree, String> {
        let (base, offset) = select_range_index(
            runner.rng(), &self.special, &self.preferred, &self.ranges);

        // Select a minimum point more convenient than 0
        let start = base + offset;
        let bottom = if start >= '¡' as u32 && base < '¡' as u32 {
            '¡' as u32
        } else if start >= 'a' as u32 && base < 'a' as u32 {
            'a' as u32
        } else if start >= 'A' as u32 && base < 'A' as u32 {
            'A' as u32
        } else if start >= '0' as u32 && base < '0' as u32 {
            '0' as u32
        } else if start >= ' ' as u32 && base < ' ' as u32 {
            ' ' as u32
        } else {
            base
        };

        Ok(CharValueTree {
            value: num::u32::BinarySearch::new_above(bottom, start)
        })
    }
}

impl CharValueTree {
    fn reposition(&mut self) {
        while ::std::char::from_u32(self.value.current()).is_none() {
            if !self.value.complicate() {
                panic!("Converged to non-char value");
            }
        }
    }
}

impl ValueTree for CharValueTree {
    type Value = char;

    fn current(&self) -> char {
        ::std::char::from_u32(self.value.current()).expect(
            "Generated non-char value")
    }

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

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

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

    use super::*;
    use collection;

    #[test]
    fn stays_in_range() {
        let meta_input = collection::vec(
            (0..::std::char::MAX as u32,
             0..::std::char::MAX as u32),
            1..5);
        TestRunner::new(Config::default()).run(
            &meta_input, |input_ranges| {
                let input = ranges(Cow::Owned(input_ranges.iter().map(
                    |&(lo, hi)| ::std::char::from_u32(lo).and_then(
                        |lo| ::std::char::from_u32(hi).map(
                            |hi| (min(lo, hi), max(lo, hi))))
                        .ok_or_else(|| TestCaseError::Reject(
                            "non-char".to_owned())))
                    .collect::<Result<Vec<(char,char)>,_>>()?));

                let mut runner = TestRunner::new(Config::default());
                for _ in 0..256 {
                    let mut value = input.new_value(&mut runner).unwrap();
                    loop {
                        let ch = value.current() as u32;
                        assert!(input_ranges.iter().any(
                            |&(lo, hi)| ch >= min(lo, hi) &&
                                ch <= max(lo, hi)));

                        if !value.simplify() { break; }
                    }
                }

                Ok(())
            }).unwrap()
    }

    #[test]
    fn applies_desired_bias() {
        let mut men_in_business_suits_levitating = 0;
        let mut ascii_printable = 0;
        let mut runner = TestRunner::new(Config::default());

        for _ in 0..1024 {
            let ch = ANY.new_value(&mut runner).unwrap().current();
            if '🕴' == ch {
                men_in_business_suits_levitating += 1;
            } else if ch >= ' ' && ch <= '~' {
                ascii_printable += 1;
            }
        }

        assert!(ascii_printable >= 256);
        assert!(men_in_business_suits_levitating >= 1);
    }

    #[test]
    fn doesnt_shrink_to_ascii_control() {
        let mut accepted = 0;
        let mut runner = TestRunner::new(Config::default());

        for _ in 0..256 {
            let mut value = ANY.new_value(&mut runner).unwrap();

            if value.current() <= ' ' { continue; }

            while value.simplify() { }

            assert!(value.current() >= ' ');
            accepted += 1;
        }

        assert!(accepted >= 200);
    }
}