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
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
use std::{
    collections::HashMap,
    fs::{self, FileType},
    path::{Path, PathBuf},
    process::Output,
};

use anyhow::Context;
use ignore::{overrides::OverrideBuilder, WalkBuilder};
use serde::{Deserialize, Serialize};

use crate::{
    code::Code,
    languages::{CustomLanguage, Language},
    SpanContent,
};

#[derive(Debug)]
pub struct Project {
    pub root: PathBuf,
    pub files: Vec<ProjectFile>,
    pub config: Option<ProjectConfig>,
}

#[derive(Debug)]
pub struct ProjectFile {
    pub path: PathBuf,
    pub code: Code,
}

/// Project configuration
#[derive(Debug, Serialize, Deserialize)]
pub struct ProjectConfig {
    /// List of languages that should be analyzed for mutations
    pub languages: Vec<Language>,
    /// List of glob strings to ignore
    pub ignore: Vec<String>,
    /// Whether to ignore files based on .gitignore
    pub use_gitignore: bool,
    /// Custom languages outside of the standart set
    pub custom_languages: Vec<CustomLanguage>,
}

impl Default for ProjectConfig {
    fn default() -> Self {
        ProjectConfig {
            languages: vec![],
            ignore: vec![],
            use_gitignore: true,
            custom_languages: vec![],
        }
    }
}

impl Project {
    pub fn new(path: &Path, pattern: Option<&str>) -> anyhow::Result<Self> {
        let cfg = if let Some(cfg_path) = std::env::var("MARAUDER_CONFIG").ok() {
            fs::read_to_string(cfg_path).ok()
        } else {
            fs::read_to_string(path.join("marauder.toml")).ok()
        };

        if let Some(cfg) = cfg {
            log::info!("found project config at '{}'", path.to_string_lossy());
            if pattern.is_some() {
                // todo: allow advancing the pattern to the project config
                log::warn!("ignoring pattern, project config found");
            }
            let project_config: ProjectConfig = toml::from_str(&cfg)?;
            Project::with_config(path, project_config)
        } else {
            Project::with_pattern(path, pattern)
        }
    }

    pub fn with_pattern(path: &Path, pattern: Option<&str>) -> anyhow::Result<Self> {
        let root = PathBuf::from(path);

        let mut overrides = OverrideBuilder::new(path);

        if let Some(s) = pattern {
            overrides.add(s)?;
        }

        let walk = WalkBuilder::new(path).overrides(overrides.build()?).build();

        let files = walk
            .filter_map(|entry| {
                let entry = entry.unwrap();
                if entry
                    .file_type()
                    .map(|f| FileType::is_dir(&f))
                    .unwrap_or(false)
                {
                    return None;
                }

                let code = Code::from_file(entry.path(), &vec![]);
                match code {
                    Ok(code) => Some(ProjectFile {
                        path: entry.path().to_path_buf(),
                        code,
                    }),
                    Err(err) => {
                        log::warn!(
                            "could not read file '{}': {}",
                            entry.path().to_string_lossy(),
                            err
                        );
                        None
                    }
                }
            })
            .collect();

        Ok(Project {
            root,
            files,
            config: None,
        })
    }

    pub fn with_config(path: &Path, config: ProjectConfig) -> anyhow::Result<Self> {
        let root = PathBuf::from(path);

        let mut overrides = OverrideBuilder::new(path);

        // Add language patterns
        for lang in &config.languages {
            overrides.add(format!("**/*.{}", lang.file_extension()).as_str())?;
        }
        // Add custom language patterns
        for custom in &config.custom_languages {
            overrides.add(format!("**/*.{}", custom.extension).as_str())?;
        }

        // Add ignore patterns
        for ignore in &config.ignore {
            overrides.add(format!("!{ignore}").as_str())?;
        }

        let walk = WalkBuilder::new(path)
            .git_ignore(config.use_gitignore)
            .overrides(overrides.build()?)
            .build();

        let files = walk
            .filter_map(|entry| {
                let entry = entry.unwrap();
                if entry.file_type().unwrap().is_dir() {
                    return None;
                }
                log::trace!("found file: {}", entry.path().to_string_lossy());
                let code = Code::from_file(entry.path(), &config.custom_languages);
                match code {
                    Ok(code) => Some(ProjectFile {
                        path: entry.path().to_path_buf(),
                        code,
                    }),
                    Err(err) => {
                        log::error!(
                            "could not read file '{}': {}",
                            entry.path().to_string_lossy(),
                            err
                        );
                        None
                    }
                }
            })
            .collect::<Vec<ProjectFile>>();

        Ok(Project {
            root,
            files,
            config: Some(config),
        })
    }

    pub fn with_language(path: &Path, lang: &Language) -> anyhow::Result<Self> {
        Self::with_pattern(
            path,
            Some(format!("**/*.{}", lang.file_extension()).as_str()),
        )
    }
}

impl Project {
    /// Returns the list of active variants in the project
    pub fn active_variants(&self) -> Vec<&str> {
        let mut variants = Vec::new();
        for file in &self.files {
            for span in &file.code.spans {
                if let SpanContent::Variation(v) = &span.content {
                    if v.active != 0 {
                        variants.push(v.variants[v.active - 1].name.as_str());
                    }
                }
            }
        }
        variants
    }

    /// Returns a hashmap of tag names, to a list of variations that have that tag
    pub fn tag_map(&self) -> HashMap<String, Vec<String>> {
        let mut tag_map = HashMap::new();
        for file in &self.files {
            for span in &file.code.spans {
                if let SpanContent::Variation(v) = &span.content {
                    if let Some(name) = &v.name {
                        for tag in &v.tags {
                            let tag = tag.to_string();
                            let variations = tag_map.entry(tag).or_insert(vec![]);
                            variations.push(name.clone());
                        }
                    }
                }
            }
        }
        tag_map
    }

    /// Returns a hashmap of variation names, to the list of variants in that variation
    pub fn variation_map(&self) -> HashMap<String, Vec<String>> {
        let mut variation_map = HashMap::new();
        for file in &self.files {
            for span in &file.code.spans {
                if let SpanContent::Variation(v) = &span.content {
                    // Only add variations with a name
                    if let Some(name) = &v.name {
                        let variants = variation_map.entry(name.clone()).or_insert(vec![]);
                        for variant in &v.variants {
                            variants.push(variant.name.clone());
                        }
                    }
                }
            }
        }
        variation_map
    }

    /// Returns a list of all variants in the project
    pub fn all_variants(&self) -> Vec<String> {
        let mut variants = vec![];
        for file in &self.files {
            for span in &file.code.spans {
                if let SpanContent::Variation(v) = &span.content {
                    for variant in &v.variants {
                        variants.push(variant.name.clone());
                    }
                }
            }
        }
        variants
    }

    /// Sets the active variant
    pub fn set(&mut self, variant: &str) -> anyhow::Result<()> {
        let mut found = false;
        let mut variants = vec![];
        for file in self.files.iter_mut() {
            let code = &mut file.code;
            if let Some((variation_index, variation)) =
                code.spans
                    .iter()
                    .enumerate()
                    .find(|(_, v)| match &v.content {
                        SpanContent::Variation(v) => v.variants.iter().any(|v| v.name == variant),
                        _ => false,
                    })
            {
                found = true;
                let variation = match &variation.content {
                    SpanContent::Variation(v) => v,
                    _ => unreachable!(),
                };

                let (variant_index, _) = variation
                    .variants
                    .iter()
                    .enumerate()
                    .find(|(_, v)| v.name == variant)
                    .ok_or_else(|| anyhow::anyhow!("variant not found"))?;

                // Shift index by because 0 is reserved for the base code
                let variant_index = variant_index + 1;

                log::info!(
                    "variant index is '{}' at '({}, {})'",
                    variant_index,
                    variation.name.as_deref().unwrap_or("anonymous"),
                    variation_index,
                );

                code.set_active_variant(variation_index, variant_index)?;

                log::info!("active variant set to '{}'", variant);
            } else {
                variants.extend(
                    code.get_all_variants()
                        .into_iter()
                        .map(|v| (file.path.clone(), v)),
                );
            }
        }

        if !found {
            log::error!(
                "variant '{variant}' not found, possible variants are (\n{}\n)",
                variants
                    .iter()
                    .map(|(path, v): &(PathBuf, String)| format!(
                        "\t'{}' at '{}'",
                        v,
                        path.to_string_lossy()
                    ))
                    .collect::<Vec<String>>()
                    .join(",\n")
            )
        }

        Ok(())
    }

    /// Sets the active variants for a test
    pub fn set_many(&mut self, test: &Vec<String>) -> anyhow::Result<()> {
        for variant in test {
            self.set(variant)?;
        }
        Ok(())
    }

    /// Runs a command at the project root
    pub fn run(&self, command: &str) -> anyhow::Result<Output> {
        std::process::Command::new("sh")
            .arg("-c")
            .arg(command)
            .current_dir(&self.root)
            .output()
            .context("failed to run command")
    }

    /// Resets a project to the base
    pub fn reset(&mut self) -> anyhow::Result<()> {
        for file in self.files.iter_mut() {
            file.code.spans.iter_mut().for_each(|span| {
                if let SpanContent::Variation(v) = &mut span.content {
                    v.active = 0;
                    v.activate_base();
                }
            });

            file.code.save_to_file(&file.path)?;
        }

        Ok(())
    }
}

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

    #[test]
    fn test_project_new() {
        let project = Project::with_pattern(Path::new("test"), None).unwrap();
        assert_eq!(project.root, PathBuf::from("test"));
        let file_paths = project
            .files
            .iter()
            .map(|f| f.path.clone())
            .collect::<Vec<_>>();
        // Should find all supported language files in test directory
        assert!(file_paths.contains(&PathBuf::from("test/rocq/BST.v")));
        assert!(file_paths.contains(&PathBuf::from("test/rocq/RBT.v")));
        assert!(file_paths.contains(&PathBuf::from("test/rocq/STLC.v")));
        assert!(file_paths.contains(&PathBuf::from("test/racket/BST.rkt")));
        assert!(file_paths.contains(&PathBuf::from("test/python/bst.py")));
        assert!(file_paths.contains(&PathBuf::from("test/haskell/BST.hs")));
        let rust_fixture = PathBuf::from("test/rust/bst.rs");
        let expected_min = if rust_fixture.exists() { 7 } else { 6 };
        if rust_fixture.exists() {
            assert!(file_paths.contains(&rust_fixture));
        }
        assert!(project.files.len() >= expected_min);
    }

    #[test]
    fn test_project_recursive() {
        let project = Project::with_pattern(Path::new("."), Some("!src/lib.rs")).unwrap();
        assert_eq!(project.root, PathBuf::from("."));
        let file_paths = project
            .files
            .iter()
            .map(|f| f.path.clone().canonicalize().unwrap())
            .collect::<Vec<_>>();

        println!("{:?}", file_paths);
        assert!(file_paths.contains(&PathBuf::from("test/rocq/BST.v").canonicalize().unwrap()));
        assert!(file_paths.contains(&PathBuf::from("src/syntax/mod.rs").canonicalize().unwrap()));
    }

    #[test]
    fn test_project_lang() {
        let project = Project::with_language(Path::new("."), &Language::Rocq).unwrap();
        assert_eq!(project.root, PathBuf::from("."));
        let file_paths = project
            .files
            .iter()
            .map(|f| f.path.clone().canonicalize().unwrap())
            .collect::<Vec<_>>();
        assert!(file_paths.contains(&PathBuf::from("test/rocq/BST.v").canonicalize().unwrap()));
        assert!(file_paths.contains(&PathBuf::from("test/rocq/STLC.v").canonicalize().unwrap()));
    }

    #[test]
    fn test_project_config() {
        let config = ProjectConfig {
            languages: vec![Language::Rust],
            ignore: vec!["src/syntax".to_string(), "**/src/lib.rs".to_string()],
            use_gitignore: false,
            custom_languages: vec![],
        };
        let project = Project::with_config(Path::new("."), config).unwrap();
        assert_eq!(project.root, PathBuf::from("."));

        let file_paths = project
            .files
            .iter()
            .map(|f| f.path.clone().canonicalize().unwrap())
            .collect::<Vec<_>>();
        assert!(file_paths.contains(&PathBuf::from("src/cli.rs").canonicalize().unwrap()));
        assert!(!file_paths.contains(
            &PathBuf::from("./src/syntax/comment.rs")
                .canonicalize()
                .unwrap()
        ));
        assert!(!file_paths.contains(&PathBuf::from("test/rocq/BST.v").canonicalize().unwrap()));
    }

    #[test]
    fn test_project_config_gitignore() {
        let config = ProjectConfig {
            languages: vec![Language::Rust],
            ignore: vec!["src/syntax".to_string(), "src/lib.rs".to_string()],
            use_gitignore: true,
            custom_languages: vec![],
        };
        let project = Project::with_config(Path::new("."), config).unwrap();
        assert_eq!(project.root, PathBuf::from("."));

        let file_paths = project
            .files
            .iter()
            .map(|f| f.path.clone().canonicalize().unwrap())
            .collect::<Vec<_>>();
        assert!(file_paths.contains(&PathBuf::from("src/cli.rs").canonicalize().unwrap()));
        assert!(!file_paths.contains(
            &PathBuf::from("./src/syntax/comment.rs")
                .canonicalize()
                .unwrap()
        ));
        assert!(!file_paths.contains(&PathBuf::from("test/rocq/BST.v").canonicalize().unwrap()));
        // todo: make this work in the CI
        // assert!(!file_paths.contains(
        //     &PathBuf::from("target/package/marauder-0.0.1/src/cli.rs")
        //         .canonicalize()
        //         .unwrap()
        // ));
    }

    #[test]
    fn test_project_config_custom_language() {
        let config = ProjectConfig {
            languages: vec![],
            ignore: vec!["src/syntax".to_string(), "src/lib.rs".to_string()],
            use_gitignore: true,
            custom_languages: vec![CustomLanguage {
                name: "Marauder".to_string(),
                extension: "rs".to_string(),
                comment_begin: "/*".to_string(),
                comment_end: "*/".to_string(),
                mutation_marker: "|".to_string(),
            }],
        };
        let project = Project::with_config(Path::new("."), config).unwrap();
        assert_eq!(project.root, PathBuf::from("."));
        let file_paths = project
            .files
            .iter()
            .map(|f| f.path.clone().canonicalize().unwrap())
            .collect::<Vec<_>>();
        assert!(file_paths.contains(&PathBuf::from("src/cli.rs").canonicalize().unwrap()));
        assert!(!file_paths.contains(
            &PathBuf::from("./src/syntax/comment.rs")
                .canonicalize()
                .unwrap()
        ));
        assert!(!file_paths.contains(&PathBuf::from("test/rocq/BST.v").canonicalize().unwrap()));
    }
}