bake-test-rust 0.3.1

Reusable Rust test tasks for Bake
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
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
// Released under the MIT License.
// Copyright, 2026, by Samuel Williams.

use bake::{Error, Result};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::ops::Range;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};

static REPORT_ID: AtomicU64 = AtomicU64::new(0);

#[derive(Debug)]
pub(crate) struct CoverageReport {
    directory: PathBuf,
    path: PathBuf,
}

impl CoverageReport {
    pub(crate) fn new() -> Result<Self> {
        Self::new_in(&std::env::temp_dir())
    }

    fn new_in(temporary_directory: &Path) -> Result<Self> {
        let identifier = REPORT_ID.fetch_add(1, Ordering::Relaxed);
        let directory = temporary_directory.join(format!(
            "bake-test-rust-coverage-{}-{identifier}",
            std::process::id()
        ));

        fs::create_dir(&directory).map_err(|error| {
            Error::new(format!(
                "failed to create temporary coverage report directory {}: {error}",
                directory.display()
            ))
        })?;

        let path = directory.join("coverage.json");
        Ok(Self { directory, path })
    }

    pub(crate) fn path(&self) -> &Path {
        &self.path
    }

    pub(crate) fn read(&self, source_root: &Path) -> Result<Summary> {
        let report = fs::read_to_string(&self.path).map_err(|error| {
            Error::new(format!(
                "failed to read coverage report {}: {error}",
                self.path.display()
            ))
        })?;

        summarize(&report, source_root)
    }
}

impl Drop for CoverageReport {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.directory);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct Position {
    line: usize,
    column: usize,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct SourceRegion {
    path: PathBuf,
    start: Position,
    end: Position,
    kind: usize,
}

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Summary {
    covered_regions: usize,
    measured_regions: usize,
    uncovered_regions: Vec<SourceRegion>,
    excluded_unreachable_regions: usize,
}

impl Summary {
    pub(crate) fn is_complete(&self) -> bool {
        self.uncovered_regions.is_empty()
    }

    pub(crate) fn success_message(&self) -> String {
        format!(
            "Region coverage passed: {}/{} measured source regions covered (excluded: {} unreachable regions)",
            self.covered_regions, self.measured_regions, self.excluded_unreachable_regions,
        )
    }

    pub(crate) fn failure_message(&self) -> String {
        let mut message = format!(
            "region coverage is {}/{} measured source regions (excluded: {} unreachable regions); {} source regions remain uncovered",
            self.covered_regions,
            self.measured_regions,
            self.excluded_unreachable_regions,
            self.uncovered_regions.len(),
        );

        for region in &self.uncovered_regions {
            message.push_str(&format!(
                "\n  {}:{}:{}-{}:{}",
                region.path.display(),
                region.start.line,
                region.start.column,
                region.end.line,
                region.end.column,
            ));
        }

        message
    }
}

#[derive(Debug)]
struct SourceFile {
    text: String,
    line_starts: Vec<usize>,
    unreachable_macros: Vec<Range<usize>>,
}

impl SourceFile {
    fn read(path: &Path) -> Result<Self> {
        let text = fs::read_to_string(path).map_err(|error| {
            Error::new(format!(
                "failed to read covered source file {}: {error}",
                path.display()
            ))
        })?;

        Ok(Self::new(text))
    }

    fn new(text: String) -> Self {
        let mut line_starts = vec![0];
        for (index, byte) in text.bytes().enumerate() {
            if byte == b'\n' {
                line_starts.push(index + 1);
            }
        }

        let unreachable_macros = find_unreachable_macros(&text);

        Self {
            text,
            line_starts,
            unreachable_macros,
        }
    }

    fn offset(&self, position: Position) -> Result<usize> {
        if position.line == 0 || position.column == 0 {
            return Err(Error::new("coverage region has a zero source position"));
        }

        let Some(&line_start) = self.line_starts.get(position.line - 1) else {
            return Err(Error::new(
                "coverage region starts past the end of its source file",
            ));
        };

        let line_end = self
            .line_starts
            .get(position.line)
            .copied()
            .map(|next_line_start| next_line_start - 1)
            .unwrap_or(self.text.len());
        let offset = line_start
            .checked_add(position.column - 1)
            .ok_or_else(|| Error::new("coverage region column exceeds its source line"))?;
        if offset > line_end {
            return Err(Error::new("coverage region column exceeds its source line"));
        }

        Ok(offset)
    }

    fn span(&self, region: &SourceRegion) -> Result<Range<usize>> {
        let start = self.offset(region.start)?;
        let end = self.offset(region.end)?;
        if end < start {
            return Err(Error::new("coverage region ends before it starts"));
        }
        if self.text.get(start..end).is_none() {
            return Err(Error::new(
                "coverage region does not align with source text",
            ));
        }

        Ok(start..end)
    }

    fn is_unreachable(&self, span: &Range<usize>) -> bool {
        self.unreachable_macros
            .iter()
            .any(|macro_span| span.start >= macro_span.start && span.end <= macro_span.end)
    }
}

fn summarize(report: &str, source_root: &Path) -> Result<Summary> {
    let json: Value = serde_json::from_str(report)
        .map_err(|error| Error::new(format!("invalid cargo-llvm-cov JSON report: {error}")))?;

    let data = json
        .get("data")
        .and_then(Value::as_array)
        .ok_or_else(|| Error::new("cargo-llvm-cov JSON report has no data array"))?;
    let mut sources = HashMap::new();
    let mut regions = HashMap::<SourceRegion, bool>::new();
    let mut report_file_count = 0;
    let mut region_record_count = 0;

    for item in data {
        let files = item
            .get("files")
            .and_then(Value::as_array)
            .ok_or_else(|| Error::new("cargo-llvm-cov JSON report has no files array"))?;
        let mut item_paths = HashSet::new();

        for file in files {
            report_file_count += 1;
            let reported_path = file
                .get("filename")
                .and_then(Value::as_str)
                .ok_or_else(|| Error::new("coverage file has no filename"))?;
            let path = resolve_source_path(Path::new(reported_path), source_root);
            item_paths.insert(path.clone());
            if !sources.contains_key(&path) {
                sources.insert(path.clone(), SourceFile::read(&path)?);
            }
        }

        let functions = item
            .get("functions")
            .and_then(Value::as_array)
            .ok_or_else(|| Error::new("cargo-llvm-cov JSON report has no functions array"))?;

        for function in functions {
            let filenames = function
                .get("filenames")
                .and_then(Value::as_array)
                .ok_or_else(|| Error::new("coverage function has no filenames array"))?;
            let function_regions = function
                .get("regions")
                .and_then(Value::as_array)
                .ok_or_else(|| Error::new("coverage function has no regions array"))?;

            for region in function_regions {
                let fields = region
                    .as_array()
                    .filter(|fields| fields.len() >= 8)
                    .ok_or_else(|| {
                        Error::new("coverage report contains an invalid source region")
                    })?;
                let file_id = json_usize_field(fields, 5, "source region file id")?;
                let Some(filename) = filenames.get(file_id).and_then(Value::as_str) else {
                    return Err(Error::new("coverage source region has an invalid file id"));
                };
                let path = resolve_source_path(Path::new(filename), source_root);
                if !item_paths.contains(&path) {
                    continue;
                }

                let kind = json_usize_field(fields, 7, "source region kind")?;
                if kind != 0 && kind != 1 {
                    continue;
                }

                region_record_count += 1;
                let region = SourceRegion {
                    path,
                    start: Position {
                        line: json_usize_field(fields, 0, "source region start line")?,
                        column: json_usize_field(fields, 1, "source region start column")?,
                    },
                    end: Position {
                        line: json_usize_field(fields, 2, "source region end line")?,
                        column: json_usize_field(fields, 3, "source region end column")?,
                    },
                    kind,
                };
                let count = json_usize_field(fields, 4, "source region execution count")?;
                regions
                    .entry(region)
                    .and_modify(|covered| *covered |= count > 0)
                    .or_insert(count > 0);
            }
        }
    }

    if report_file_count == 0 {
        return Err(Error::new(
            "cargo-llvm-cov JSON report contains no source files",
        ));
    }
    if region_record_count == 0 {
        return Err(Error::new(
            "cargo-llvm-cov JSON report contains no source regions",
        ));
    }

    let mut summary = Summary {
        covered_regions: 0,
        measured_regions: 0,
        uncovered_regions: Vec::new(),
        excluded_unreachable_regions: 0,
    };

    for (region, covered) in regions {
        let Some(source) = sources.get(&region.path) else {
            unreachable!("coverage regions must refer to reported source files");
        };
        let span = source.span(&region)?;
        if source.is_unreachable(&span) {
            summary.excluded_unreachable_regions += 1;
        } else {
            summary.measured_regions += 1;
            if covered {
                summary.covered_regions += 1;
            } else {
                summary.uncovered_regions.push(region);
            }
        }
    }

    summary.uncovered_regions.sort_by(compare_regions);

    Ok(summary)
}

fn compare_regions(left: &SourceRegion, right: &SourceRegion) -> std::cmp::Ordering {
    left.path
        .cmp(&right.path)
        .then_with(|| left.start.line.cmp(&right.start.line))
        .then_with(|| left.start.column.cmp(&right.start.column))
        .then_with(|| left.end.line.cmp(&right.end.line))
        .then_with(|| left.end.column.cmp(&right.end.column))
        .then_with(|| left.kind.cmp(&right.kind))
}

fn json_usize_field(fields: &[Value], index: usize, description: &str) -> Result<usize> {
    fields
        .get(index)
        .and_then(Value::as_u64)
        .and_then(|value| usize::try_from(value).ok())
        .ok_or_else(|| Error::new(format!("coverage {description} is invalid")))
}

fn resolve_source_path(reported_path: &Path, source_root: &Path) -> PathBuf {
    let path = if reported_path.is_absolute() {
        reported_path.to_owned()
    } else {
        source_root.join(reported_path)
    };

    fs::canonicalize(&path).unwrap_or(path)
}

/// Finds `unreachable!()` invocations in Rust source already validated by the compiler.
fn find_unreachable_macros(source: &str) -> Vec<Range<usize>> {
    let mut ranges = Vec::new();
    let mut index = 0;

    while index < source.len() {
        if let Some(next) = skip_non_code(source, index) {
            index = next;
            continue;
        }

        if source[index..].starts_with("unreachable")
            && is_identifier_boundary_before(source, index)
        {
            let name_end = index + "unreachable".len();
            if is_identifier_boundary_after(source, name_end) {
                let bang = skip_trivia(source, name_end);
                if source.as_bytes().get(bang) == Some(&b'!') {
                    let opening = skip_trivia(source, bang + 1);
                    let Some(&delimiter) = source.as_bytes().get(opening) else {
                        unreachable!("compiled Rust macro invocations have an opening delimiter");
                    };
                    let closing = matching_group_end(source, opening, delimiter);
                    ranges.push(macro_path_start(source, index)..closing);
                    index = closing;
                    continue;
                }
            }
        }

        index += source[index..].chars().next().map_or(1, char::len_utf8);
    }

    ranges
}

fn is_identifier_boundary_before(source: &str, index: usize) -> bool {
    index == 0 || !is_identifier_byte(source.as_bytes()[index - 1])
}

fn is_identifier_boundary_after(source: &str, index: usize) -> bool {
    source
        .as_bytes()
        .get(index)
        .is_none_or(|byte| !is_identifier_byte(*byte))
}

fn is_identifier_byte(byte: u8) -> bool {
    byte == b'_' || byte.is_ascii_alphanumeric() || byte >= 0x80
}

fn skip_trivia(source: &str, mut index: usize) -> usize {
    loop {
        while source
            .as_bytes()
            .get(index)
            .is_some_and(u8::is_ascii_whitespace)
        {
            index += 1;
        }

        let Some(next) = skip_comment(source, index) else {
            return index;
        };
        index = next;
    }
}

fn skip_non_code(source: &str, index: usize) -> Option<usize> {
    if let Some(next) = skip_comment(source, index) {
        return Some(next);
    }
    if let Some(next) = skip_raw_string(source, index) {
        return Some(next);
    }
    if let Some(next) = skip_quoted_string(source, index) {
        return Some(next);
    }
    skip_character_literal(source, index)
}

fn skip_comment(source: &str, index: usize) -> Option<usize> {
    let bytes = source.as_bytes();
    if bytes.get(index..index + 2) == Some(b"//") {
        return Some(
            bytes[index..]
                .iter()
                .position(|byte| *byte == b'\n')
                .map_or(source.len(), |offset| index + offset + 1),
        );
    }
    if bytes.get(index..index + 2) != Some(b"/*") {
        return None;
    }

    let mut depth = 1;
    let mut cursor = index + 2;
    while cursor < bytes.len() {
        if bytes.get(cursor..cursor + 2) == Some(b"/*") {
            depth += 1;
            cursor += 2;
        } else if bytes.get(cursor..cursor + 2) == Some(b"*/") {
            depth -= 1;
            cursor += 2;
            if depth == 0 {
                return Some(cursor);
            }
        } else {
            cursor += 1;
        }
    }

    unreachable!("compiled Rust source has closed block comments");
}

fn skip_raw_string(source: &str, index: usize) -> Option<usize> {
    let bytes = source.as_bytes();
    let raw_prefix = if bytes.get(index..index + 2) == Some(b"br")
        || bytes.get(index..index + 2) == Some(b"cr")
    {
        index + 1
    } else if bytes.get(index) == Some(&b'r') {
        index
    } else {
        return None;
    };

    let mut quote = raw_prefix + 1;
    while bytes.get(quote) == Some(&b'#') {
        quote += 1;
    }
    if bytes.get(quote) != Some(&b'"') {
        return None;
    }

    let hashes = quote - raw_prefix - 1;
    let mut cursor = quote + 1;
    while cursor < bytes.len() {
        if bytes[cursor] == b'"'
            && bytes
                .get(cursor + 1..cursor + 1 + hashes)
                .is_some_and(|suffix| suffix.iter().all(|byte| *byte == b'#'))
        {
            return Some(cursor + 1 + hashes);
        }
        cursor += 1;
    }

    unreachable!("compiled Rust source has closed raw strings");
}

fn skip_quoted_string(source: &str, index: usize) -> Option<usize> {
    let bytes = source.as_bytes();
    let quote = match bytes.get(index) {
        Some(b'"') => index,
        Some(b'b' | b'c') if bytes.get(index + 1) == Some(&b'"') => index + 1,
        _ => return None,
    };

    let mut cursor = quote + 1;
    while cursor < bytes.len() {
        match bytes[cursor] {
            b'\\' => cursor = (cursor + 2).min(bytes.len()),
            b'"' => return Some(cursor + 1),
            _ => cursor += 1,
        }
    }

    unreachable!("compiled Rust source has closed strings");
}

fn skip_character_literal(source: &str, index: usize) -> Option<usize> {
    let bytes = source.as_bytes();
    let quote = match bytes.get(index) {
        Some(b'\'') => index,
        Some(b'b') if bytes.get(index + 1) == Some(&b'\'') => index + 1,
        _ => return None,
    };

    let mut cursor = quote + 1;
    while cursor < bytes.len() && bytes[cursor] != b'\n' {
        match bytes[cursor] {
            b'\\' => cursor = (cursor + 2).min(bytes.len()),
            b'\'' => return Some(cursor + 1),
            _ => cursor += 1,
        }
    }

    None
}

fn matching_group_end(source: &str, opening: usize, delimiter: u8) -> usize {
    let closing = match delimiter {
        b'(' => b')',
        b'[' => b']',
        b'{' => b'}',
        _ => unreachable!("macro invocation starts with a group delimiter"),
    };
    let mut stack = vec![closing];
    let mut index = opening + 1;

    while index < source.len() {
        if let Some(next) = skip_non_code(source, index) {
            index = next;
            continue;
        }

        match source.as_bytes()[index] {
            b'(' => stack.push(b')'),
            b'[' => stack.push(b']'),
            b'{' => stack.push(b'}'),
            b')' | b']' | b'}' => {
                if stack.pop() != Some(source.as_bytes()[index]) {
                    unreachable!("compiled Rust macro token trees have balanced delimiters");
                }
                if stack.is_empty() {
                    return index + 1;
                }
            }
            _ => {}
        }

        index += source[index..].chars().next().map_or(1, char::len_utf8);
    }

    unreachable!("compiled Rust macro token trees have closing delimiters");
}

fn macro_path_start(source: &str, index: usize) -> usize {
    let bytes = source.as_bytes();
    let mut start = index;
    loop {
        if start >= 2 && bytes.get(start - 2..start) == Some(b"r#") {
            return start - 2;
        }

        if start < 2 || bytes.get(start - 2..start) != Some(b"::") {
            return start;
        }

        let mut segment_start = start - 2;
        while segment_start > 0 && is_identifier_byte(bytes[segment_start - 1]) {
            segment_start -= 1;
        }
        if segment_start == start - 2 {
            return start - 2;
        }
        start = segment_start;
    }
}

#[cfg(test)]
#[path = "coverage/tests.rs"]
mod tests;