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
use alloc::vec::Vec;
use core::{cmp::max, marker::PhantomData};
use hashbrown::HashMap;
use serde::{Deserialize, Serialize};

use crate::{
    bolts::{rands::Rand, tuples::Named},
    corpus::Corpus,
    generators::GramatronGenerator,
    inputs::{GramatronInput, Terminal},
    mutators::{MutationResult, Mutator},
    state::{HasCorpus, HasMetadata, HasRand},
    Error,
};

pub struct GramatronRandomMutator<'a, R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    generator: &'a GramatronGenerator<'a, R, S>,
}

impl<'a, R, S> Mutator<GramatronInput, S> for GramatronRandomMutator<'a, R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    fn mutate(
        &mut self,
        state: &mut S,
        input: &mut GramatronInput,
        _stage_idx: i32,
    ) -> Result<MutationResult, Error> {
        if !input.terminals().is_empty() {
            let size = state.rand_mut().below(input.terminals().len() as u64 + 1) as usize;
            input.terminals_mut().truncate(size);
        }
        if self.generator.append_generated_terminals(input, state) > 0 {
            Ok(MutationResult::Mutated)
        } else {
            Ok(MutationResult::Skipped)
        }
    }
}

impl<'a, R, S> Named for GramatronRandomMutator<'a, R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    fn name(&self) -> &str {
        "GramatronRandomMutator"
    }
}

impl<'a, R, S> GramatronRandomMutator<'a, R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    /// Creates a new [`GramatronRandomMutator`].
    #[must_use]
    pub fn new(generator: &'a GramatronGenerator<'a, R, S>) -> Self {
        Self { generator }
    }
}

#[derive(Serialize, Deserialize)]
pub struct GramatronIdxMapMetadata {
    pub map: HashMap<usize, Vec<usize>>,
}

crate::impl_serdeany!(GramatronIdxMapMetadata);

impl GramatronIdxMapMetadata {
    #[must_use]
    pub fn new(input: &GramatronInput) -> Self {
        let mut map = HashMap::default();
        for i in 0..input.terminals().len() {
            let entry = map.entry(input.terminals()[i].state).or_insert(vec![]);
            (*entry).push(i);
        }
        Self { map }
    }
}

#[derive(Default)]
pub struct GramatronSpliceMutator<C, R, S>
where
    C: Corpus<GramatronInput>,
    S: HasRand<R> + HasCorpus<C, GramatronInput> + HasMetadata,
    R: Rand,
{
    phantom: PhantomData<(C, R, S)>,
}

impl<C, R, S> Mutator<GramatronInput, S> for GramatronSpliceMutator<C, R, S>
where
    C: Corpus<GramatronInput>,
    S: HasRand<R> + HasCorpus<C, GramatronInput> + HasMetadata,
    R: Rand,
{
    fn mutate(
        &mut self,
        state: &mut S,
        input: &mut GramatronInput,
        _stage_idx: i32,
    ) -> Result<MutationResult, Error> {
        if input.terminals().is_empty() {
            return Ok(MutationResult::Skipped);
        }

        let count = state.corpus().count();
        let idx = state.rand_mut().below(count as u64) as usize;

        let insert_at = state.rand_mut().below(input.terminals().len() as u64) as usize;

        let rand_num = state.rand_mut().next() as usize;

        let mut other_testcase = state.corpus().get(idx)?.borrow_mut();
        other_testcase.load_input()?; // Preload the input

        if !other_testcase.has_metadata::<GramatronIdxMapMetadata>() {
            let meta = GramatronIdxMapMetadata::new(other_testcase.input().as_ref().unwrap());
            other_testcase.add_metadata(meta);
        }
        let meta = other_testcase
            .metadata()
            .get::<GramatronIdxMapMetadata>()
            .unwrap();
        let other = other_testcase.input().as_ref().unwrap();

        meta.map.get(&input.terminals()[insert_at].state).map_or(
            Ok(MutationResult::Skipped),
            |splice_points| {
                let from = splice_points[rand_num % splice_points.len()];

                input.terminals_mut().truncate(insert_at);
                input
                    .terminals_mut()
                    .extend_from_slice(&other.terminals()[from..]);

                Ok(MutationResult::Mutated)
            },
        )
    }
}

impl<C, R, S> Named for GramatronSpliceMutator<C, R, S>
where
    C: Corpus<GramatronInput>,
    S: HasRand<R> + HasCorpus<C, GramatronInput> + HasMetadata,
    R: Rand,
{
    fn name(&self) -> &str {
        "GramatronSpliceMutator"
    }
}

impl<'a, C, R, S> GramatronSpliceMutator<C, R, S>
where
    C: Corpus<GramatronInput>,
    S: HasRand<R> + HasCorpus<C, GramatronInput> + HasMetadata,
    R: Rand,
{
    /// Creates a new [`GramatronSpliceMutator`].
    #[must_use]
    pub fn new() -> Self {
        Self {
            phantom: PhantomData,
        }
    }
}

#[derive(Default)]
pub struct GramatronRecursionMutator<R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    counters: HashMap<usize, (usize, usize, usize)>,
    states: Vec<usize>,
    temp: Vec<Terminal>,
    phantom: PhantomData<(R, S)>,
}

impl<R, S> Mutator<GramatronInput, S> for GramatronRecursionMutator<R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    fn mutate(
        &mut self,
        state: &mut S,
        input: &mut GramatronInput,
        _stage_idx: i32,
    ) -> Result<MutationResult, Error> {
        if input.terminals().is_empty() {
            return Ok(MutationResult::Skipped);
        }

        self.counters.clear();
        self.states.clear();
        for i in 0..input.terminals().len() {
            let s = input.terminals()[i].state;
            if let Some(entry) = self.counters.get_mut(&s) {
                if entry.0 == 1 {
                    // Keep track only of states with more than one node
                    self.states.push(s);
                }
                entry.0 += 1;
                entry.2 = max(entry.2, i);
            } else {
                self.counters.insert(s, (1, i, i));
            }
        }

        if self.states.is_empty() {
            return Ok(MutationResult::Skipped);
        }

        let chosen = *state.rand_mut().choose(&self.states);
        let chosen_nums = self.counters.get(&chosen).unwrap().0;

        #[allow(clippy::cast_sign_loss, clippy::pedantic)]
        let mut first = state.rand_mut().below(chosen_nums as u64 - 1) as i64;
        #[allow(clippy::cast_sign_loss, clippy::pedantic)]
        let mut second = state
            .rand_mut()
            .between(first as u64 + 1, chosen_nums as u64 - 1) as i64;

        let mut idx_1 = 0;
        let mut idx_2 = 0;
        for i in (self.counters.get(&chosen).unwrap().1)..=(self.counters.get(&chosen).unwrap().2) {
            if input.terminals()[i].state == chosen {
                if first == 0 {
                    idx_1 = i;
                }
                if second == 0 {
                    idx_2 = i;
                    break;
                }
                first -= 1;
                second -= 1;
            }
        }
        debug_assert!(idx_1 < idx_2);

        self.temp.clear();
        self.temp.extend_from_slice(&input.terminals()[idx_2..]);

        input.terminals_mut().truncate(idx_2);
        input.terminals_mut().extend_from_slice(&self.temp);

        Ok(MutationResult::Mutated)
    }
}

impl<R, S> Named for GramatronRecursionMutator<R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    fn name(&self) -> &str {
        "GramatronRecursionMutator"
    }
}

impl<R, S> GramatronRecursionMutator<R, S>
where
    S: HasRand<R> + HasMetadata,
    R: Rand,
{
    /// Creates a new [`GramatronRecursionMutator`].
    #[must_use]
    pub fn new() -> Self {
        Self {
            counters: HashMap::default(),
            states: vec![],
            temp: vec![],
            phantom: PhantomData,
        }
    }
}