marauders 0.0.13

A tool for hand-crafted mutation analysis and management
Documentation
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
use std::{collections::HashMap, fmt::Display, iter::Peekable, str::Chars};

type Id = String;
type Tag = String;

pub fn compute_mutations(
    expr: &str,
    tag_map: &HashMap<String, Vec<String>>,
    variation_map: &HashMap<String, Vec<String>>,
    variant_list: &Vec<String>,
) -> anyhow::Result<Vec<Vec<String>>> {
    let mut parser = Parser::new(expr);
    let expr = parser.parse();
    expr.into_sum_of_products(tag_map, variation_map, variant_list)
}

#[derive(Debug, PartialEq)]
pub(crate) enum Expr {
    Sum(Box<Expr>, Box<Expr>),
    Product(Box<Expr>, Box<Expr>),
    USum(Tag),
    UProduct(Tag),
    Id(Id),
}

impl Display for Expr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Expr::Sum(lhs, rhs) => write!(f, "({} + {})", lhs, rhs),
            Expr::Product(lhs, rhs) => write!(f, "({} * {})", lhs, rhs),
            Expr::USum(tag) => write!(f, "+{}", tag),
            Expr::UProduct(tag) => write!(f, "*{}", tag),
            Expr::Id(id) => write!(f, "{}", id),
        }
    }
}

impl Expr {
    /// Converts the expression into a sum of products
    /// @self: The expression to convert
    /// @tag_map: A map from tag to a list of ids that have that tag
    /// @variation_map: A map from variation ids to a list of ids that are variants within the variation
    /// @variant_list: A complete list of all variant ids
    /// @return: A list of lists of ids that represent the sum of products
    fn into_sum_of_products(
        &self,
        tag_map: &HashMap<String, Vec<String>>,
        variation_map: &HashMap<String, Vec<String>>,
        variant_list: &Vec<String>,
    ) -> anyhow::Result<Vec<Vec<String>>> {
        // Distributes tags +t into (t1 + t2 + ... + tn) and *t into (t1 * t2 * ... * tn)
        let tagless_expr = self.distribute_tags(tag_map);
        // Distributes variation v into a sum of its alternatives
        let variation_distributed = tagless_expr.distribute_variations(variation_map);
        // Check that all the variants in the expression are in the variant list
        let mut variants = vec![];
        variation_distributed.collect_variants(&mut variants);
        for variant in variants.iter() {
            if !variant_list.contains(variant) {
                anyhow::bail!("Variant {} is not in the variant list", variant);
            }
        }
        let variation_distributed = variation_distributed.distribute();

        Ok(variation_distributed)
    }

    fn collect_variants(&self, variants: &mut Vec<String>) {
        match self {
            Expr::Sum(lhs, rhs) => {
                lhs.collect_variants(variants);
                rhs.collect_variants(variants);
            }
            Expr::Product(lhs, rhs) => {
                lhs.collect_variants(variants);
                rhs.collect_variants(variants);
            }
            Expr::USum(_) | Expr::UProduct(_) => {
                unreachable!("Unary expressions are elimiated in [distributed_tags] phase")
            }
            Expr::Id(id) => {
                variants.push(id.clone());
            }
        }
    }

    fn distribute_tags(&self, tag_map: &HashMap<String, Vec<String>>) -> Expr {
        match self {
            Expr::Sum(lhs, rhs) => {
                let lhs = lhs.distribute_tags(tag_map);
                let rhs = rhs.distribute_tags(tag_map);
                Expr::Sum(Box::new(lhs), Box::new(rhs))
            }
            Expr::Product(lhs, rhs) => {
                let lhs = lhs.distribute_tags(tag_map);
                let rhs = rhs.distribute_tags(tag_map);
                Expr::Product(Box::new(lhs), Box::new(rhs))
            }
            Expr::USum(tag) => {
                let ids = vec![];
                let ids = tag_map.get(tag).unwrap_or(&ids);
                let mut sum = Expr::Id(ids[0].clone());
                for id in ids.iter().skip(1) {
                    sum = Expr::Sum(Box::new(sum), Box::new(Expr::Id(id.clone())));
                }
                sum
            }
            Expr::UProduct(tag) => {
                let ids = vec![];
                let ids = tag_map.get(tag).unwrap_or(&ids);
                let mut product = Expr::Id(ids[0].clone());
                for id in ids.iter().skip(1) {
                    product = Expr::Product(Box::new(product), Box::new(Expr::Id(id.clone())));
                }
                product
            }
            Expr::Id(id) => Expr::Id(id.clone()),
        }
    }

    fn distribute_variations(&self, variation_map: &HashMap<String, Vec<String>>) -> Expr {
        match self {
            Expr::Sum(lhs, rhs) => {
                let lhs = lhs.distribute_variations(variation_map);
                let rhs = rhs.distribute_variations(variation_map);
                Expr::Sum(Box::new(lhs), Box::new(rhs))
            }
            Expr::Product(lhs, rhs) => {
                let lhs = lhs.distribute_variations(variation_map);
                let rhs = rhs.distribute_variations(variation_map);
                Expr::Product(Box::new(lhs), Box::new(rhs))
            }
            Expr::USum(_) | Expr::UProduct(_) => {
                unreachable!("Unary expressions are elimiated in [distributed_tags] phase")
            }
            Expr::Id(id) => match variation_map.get(id) {
                Some(ids) => {
                    let mut sum = Expr::Id(ids[0].clone());
                    for id in ids.iter().skip(1) {
                        sum = Expr::Sum(Box::new(sum), Box::new(Expr::Id(id.clone())));
                    }
                    sum
                }
                None => Expr::Id(id.clone()),
            },
        }
    }

    fn distribute(&self) -> Vec<Vec<String>> {
        match self {
            Expr::Product(lhs, rhs) => {
                let lhs = lhs.distribute();
                let rhs = rhs.distribute();
                let mut result = vec![];
                for l in lhs.iter() {
                    for r in rhs.iter() {
                        let mut sum = l.clone();
                        sum.extend(r.iter().cloned());
                        result.push(sum);
                    }
                }
                result
            }
            Expr::Sum(lhs, rhs) => {
                let mut lhs = lhs.distribute();
                let rhs = rhs.distribute();
                lhs.extend(rhs);
                lhs
            }
            Expr::USum(_) | Expr::UProduct(_) => {
                unreachable!("Unary expressions are elimiated in [distributed_tags] phase")
            }
            Expr::Id(id) => vec![vec![id.clone()]],
        }
    }
}

#[derive(Debug, PartialEq, Clone)]
enum Token {
    Plus,
    Star,
    OpenParen,
    CloseParen,
    Identifier(String),
}

struct Lexer<'a> {
    input: Peekable<Chars<'a>>,
}

impl<'a> Lexer<'a> {
    fn new(input: &'a str) -> Self {
        Self {
            input: input.chars().peekable(),
        }
    }

    fn next_token(&mut self) -> Option<Token> {
        while let Some(&c) = self.input.peek() {
            match c {
                '+' => {
                    self.input.next();
                    return Some(Token::Plus);
                }
                '*' => {
                    self.input.next();
                    return Some(Token::Star);
                }
                '(' => {
                    self.input.next();
                    return Some(Token::OpenParen);
                }
                ')' => {
                    self.input.next();
                    return Some(Token::CloseParen);
                }
                'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => {
                    let mut id = String::new();
                    while let Some(&ch) = self.input.peek() {
                        if ch.is_alphanumeric() || ch == '_' {
                            id.push(ch);
                            self.input.next();
                        } else {
                            break;
                        }
                    }
                    return Some(Token::Identifier(id));
                }
                ' ' | '\t' | '\n' => {
                    self.input.next(); // Skip whitespace
                }
                _ => panic!("Unexpected character: {}", c),
            }
        }
        None
    }
}

struct Parser<'a> {
    lexer: Lexer<'a>,
    current_token: Option<Token>,
}

impl<'a> Parser<'a> {
    fn new(input: &'a str) -> Self {
        let mut lexer = Lexer::new(input);
        let current_token = lexer.next_token();
        Self {
            lexer,
            current_token,
        }
    }

    fn consume(&mut self) {
        self.current_token = self.lexer.next_token();
    }

    fn parse(&mut self) -> Expr {
        self.parse_sum()
    }

    fn parse_sum(&mut self) -> Expr {
        let mut left = self.parse_product();

        while let Some(Token::Plus) = self.current_token {
            self.consume();
            let right = self.parse_product();
            left = Expr::Sum(Box::new(left), Box::new(right));
        }

        left
    }

    fn parse_product(&mut self) -> Expr {
        let mut left = self.parse_primary();

        while let Some(Token::Star) = self.current_token {
            self.consume();
            let right = self.parse_primary();
            left = Expr::Product(Box::new(left), Box::new(right));
        }

        left
    }

    fn parse_primary(&mut self) -> Expr {
        match self.current_token.clone() {
            Some(Token::Plus) => {
                self.consume();
                let tag = match self.current_token.clone() {
                    Some(Token::Identifier(id)) => {
                        self.consume();
                        id
                    }
                    _ => panic!("Expected identifier after unary plus"),
                };
                Expr::USum(tag)
            }
            Some(Token::Star) => {
                self.consume();
                let tag = match self.current_token.clone() {
                    Some(Token::Identifier(id)) => {
                        self.consume();
                        id
                    }
                    _ => panic!("Expected identifier after unary star"),
                };
                Expr::UProduct(tag)
            }
            Some(Token::Identifier(id)) => {
                self.consume();
                Expr::Id(id)
            }
            Some(Token::OpenParen) => {
                self.consume();
                let expr = self.parse();
                if let Some(Token::CloseParen) = self.current_token {
                    self.consume();
                    expr
                } else {
                    panic!("Expected closing parenthesis");
                }
            }
            _ => panic!("Unexpected token: {:?}", self.current_token),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_expr() {
        let input = "a + b * c";
        let mut parser = Parser::new(input);
        let expr = parser.parse();
        assert_eq!(
            expr,
            Expr::Sum(
                Box::new(Expr::Id("a".to_string())),
                Box::new(Expr::Product(
                    Box::new(Expr::Id("b".to_string())),
                    Box::new(Expr::Id("c".to_string()))
                ))
            )
        );
    }

    #[test]
    fn test_nested_expr() {
        let input = "a + ((b * c) + d)";
        let mut parser = Parser::new(input);
        let expr = parser.parse();
        assert_eq!(
            expr,
            Expr::Sum(
                Box::new(Expr::Id("a".to_string())),
                Box::new(Expr::Sum(
                    Box::new(Expr::Product(
                        Box::new(Expr::Id("b".to_string())),
                        Box::new(Expr::Id("c".to_string()))
                    )),
                    Box::new(Expr::Id("d".to_string()))
                ))
            )
        );
    }

    #[test]
    fn test_complex_names() {
        let input = "a1 + b_2 * c3";
        let mut parser = Parser::new(input);
        let expr = parser.parse();
        assert_eq!(
            expr,
            Expr::Sum(
                Box::new(Expr::Id("a1".to_string())),
                Box::new(Expr::Product(
                    Box::new(Expr::Id("b_2".to_string())),
                    Box::new(Expr::Id("c3".to_string()))
                ))
            )
        );
    }

    #[test]
    fn test_unary_expr() {
        let input = "+easy * insert";
        let mut parser = Parser::new(input);
        let expr = parser.parse();
        assert_eq!(
            expr,
            Expr::Product(
                Box::new(Expr::USum("easy".to_string())),
                Box::new(Expr::Id("insert".to_string()))
            )
        );
    }

    #[test]
    fn test_unary_expr_paren() {
        let input = "+easy * (insert + delete)";
        let mut parser = Parser::new(input);
        let expr = parser.parse();
        assert_eq!(
            expr,
            Expr::Product(
                Box::new(Expr::USum("easy".to_string())),
                Box::new(Expr::Sum(
                    Box::new(Expr::Id("insert".to_string())),
                    Box::new(Expr::Id("delete".to_string()))
                ))
            )
        );
    }

    #[test]
    fn test_distribute_tags() {
        let input = "+easy * (insert + delete)";
        let mut parser = Parser::new(input);
        let expr = parser.parse();
        let tag_map = vec![("easy".to_string(), vec!["a".to_string(), "b".to_string()])]
            .into_iter()
            .collect();
        let variation_map = vec![
            (
                "insert".to_string(),
                vec!["insert_1".to_string(), "insert_2".to_string()],
            ),
            (
                "delete".to_string(),
                vec!["delete_1".to_string(), "delete_2".to_string()],
            ),
        ]
        .into_iter()
        .collect();

        let variant_list = vec![
            "a".to_string(),
            "b".to_string(),
            "insert_1".to_string(),
            "insert_2".to_string(),
            "delete_1".to_string(),
            "delete_2".to_string(),
        ];
        let sum_of_products = expr
            .into_sum_of_products(&tag_map, &variation_map, &variant_list)
            .unwrap();
        assert_eq!(
            sum_of_products,
            vec![
                vec!["a".to_string(), "insert_1".to_string()],
                vec!["a".to_string(), "insert_2".to_string()],
                vec!["a".to_string(), "delete_1".to_string()],
                vec!["a".to_string(), "delete_2".to_string()],
                vec!["b".to_string(), "insert_1".to_string()],
                vec!["b".to_string(), "insert_2".to_string()],
                vec!["b".to_string(), "delete_1".to_string()],
                vec!["b".to_string(), "delete_2".to_string()],
            ]
        );
    }
}