1use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6use anyhow::{Context, Result};
7
8use crate::report::Finding;
9
10pub fn fingerprint(finding: &Finding) -> String {
13 let kind = match finding {
15 Finding::InputGap { .. } => "input_gap",
16 Finding::AssertionGap { .. } | Finding::Survivor { .. } => "assertion_gap",
17 };
18 let (at, survivors) = (finding.at(), finding.survivors());
19 format!(
20 "{kind}\t{}\t{}\t{}",
21 at.file,
22 at.code,
23 survivors.join(" | ")
24 )
25}
26
27#[derive(Debug, PartialEq)]
29pub enum Baseline {
30 Fingerprints(BTreeSet<String>),
32 Ids(BTreeSet<String>),
34}
35
36impl Baseline {
37 pub fn knows(&self, finding: &Finding) -> bool {
38 let at = finding.at();
39 match self {
40 Baseline::Fingerprints(prints) => prints.contains(&fingerprint(finding)),
41 Baseline::Ids(ids) => !at.id.is_empty() && ids.contains(&at.id),
42 }
43 }
44}
45
46const VERSION: u64 = 3;
48const LEGACY_V2: u64 = 2;
50const MAX_BASELINE_BYTES: u64 = 16 * 1024 * 1024;
52
53#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
55#[serde(deny_unknown_fields)]
56pub struct BaselineEntry {
57 pub id: String,
58 #[serde(default, skip_serializing_if = "String::is_empty")]
59 pub kind: String,
60 #[serde(default, skip_serializing_if = "String::is_empty")]
61 pub file: String,
62 #[serde(default, skip_serializing_if = "String::is_empty")]
63 pub item: String,
64 #[serde(default, skip_serializing_if = "String::is_empty")]
65 pub code: String,
66 #[serde(default, skip_serializing_if = "Vec::is_empty")]
67 pub survivors: Vec<String>,
68 #[serde(default)]
69 pub reason: String,
70}
71
72#[derive(serde::Deserialize)]
73#[serde(untagged)]
74enum RawBaselineEntry {
75 Id(String),
76 Detailed(BaselineEntry),
77}
78
79fn read_regular_baseline(path: &Path) -> Result<String> {
80 use std::io::Read as _;
81
82 let metadata = std::fs::symlink_metadata(path)
83 .with_context(|| format!("inspecting {}", path.display()))?;
84 if !metadata.is_file() {
85 anyhow::bail!("{} is not a regular file", path.display());
86 }
87 let file = std::fs::File::open(path).with_context(|| format!("reading {}", path.display()))?;
88 let mut text = String::new();
89 file.take(MAX_BASELINE_BYTES + 1)
90 .read_to_string(&mut text)
91 .with_context(|| format!("reading {}", path.display()))?;
92 let text_len = text.len() as u64;
93 if text_len > MAX_BASELINE_BYTES {
94 anyhow::bail!(
95 "{} exceeds maximum baseline size of {MAX_BASELINE_BYTES} bytes",
96 path.display()
97 );
98 }
99 Ok(text)
100}
101
102pub fn load(path: &Path) -> Result<Baseline> {
105 let text = read_regular_baseline(path)?;
106 parse(&text).with_context(|| format!("{} is not a tmt baseline", path.display()))
107}
108
109fn parse(text: &str) -> Result<Baseline> {
110 parse_with_reasons(text).map(|(baseline, _)| baseline)
111}
112
113fn parse_with_reasons(text: &str) -> Result<(Baseline, BTreeMap<String, String>)> {
114 let mut value: serde_json::Value = serde_json::from_str(text)?;
115 if value.is_array() {
116 return Ok((
117 Baseline::Fingerprints(serde_json::from_value(value)?),
118 BTreeMap::new(),
119 ));
120 }
121 match value["version"].as_u64() {
122 Some(LEGACY_V2) => {
123 let ids: BTreeSet<String> = serde_json::from_value(value["findings"].take())?;
124 Ok((Baseline::Ids(ids), BTreeMap::new()))
125 }
126 Some(VERSION) => {
127 let entries: Vec<RawBaselineEntry> = serde_json::from_value(value["findings"].take())?;
128 let mut ids = BTreeSet::new();
129 let mut reasons = BTreeMap::new();
130 for entry in entries {
131 match entry {
132 RawBaselineEntry::Id(id) => {
133 ids.insert(id);
134 }
135 RawBaselineEntry::Detailed(entry) => {
136 if !entry.reason.is_empty() {
137 reasons.insert(entry.id.clone(), entry.reason);
138 }
139 ids.insert(entry.id);
140 }
141 }
142 }
143 Ok((Baseline::Ids(ids), reasons))
144 }
145 Some(other) => anyhow::bail!("version {other} of the format is not known to this tmt"),
146 None => anyhow::bail!("neither a list nor an object with a version"),
147 }
148}
149
150fn existing_reasons(path: &Path) -> Result<BTreeMap<String, String>> {
151 match std::fs::symlink_metadata(path) {
152 Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
153 Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
154 Ok(meta) if !meta.is_file() => {
155 anyhow::bail!(
156 "refusing to overwrite non-regular baseline path {}",
157 path.display()
158 );
159 }
160 Ok(_) => {}
161 }
162 let text = read_regular_baseline(path)?;
163 let (_, reasons) = parse_with_reasons(&text).with_context(|| {
164 format!(
165 "cannot preserve reasons from existing baseline {} (fix or remove it before rewriting)",
166 path.display()
167 )
168 })?;
169 Ok(reasons)
170}
171
172pub fn write(path: &Path, findings: &[Finding]) -> Result<()> {
173 let reasons = existing_reasons(path)?;
174 let mut text = render_with_reasons(findings, &reasons);
175 text.push('\n');
176 let text_len = text.len() as u64;
177 if text_len > MAX_BASELINE_BYTES {
178 anyhow::bail!(
179 "baseline {} would exceed maximum size of {MAX_BASELINE_BYTES} bytes",
180 path.display()
181 );
182 }
183 let parent = path
184 .parent()
185 .filter(|p| !p.as_os_str().is_empty())
186 .unwrap_or_else(|| Path::new("."));
187 let file_name = path
188 .file_name()
189 .and_then(|n| n.to_str())
190 .unwrap_or("baseline");
191 let tmp = parent.join(format!(
192 ".{file_name}.tmt-tmp-{}-{}",
193 std::process::id(),
194 std::time::SystemTime::now()
195 .duration_since(std::time::UNIX_EPOCH)
196 .map_or(0, |d| d.as_nanos())
197 ));
198 if let Err(err) = std::fs::write(&tmp, &text) {
199 let _ = std::fs::remove_file(&tmp);
200 return Err(err).with_context(|| format!("writing {}", path.display()));
201 }
202 if let Err(err) = std::fs::rename(&tmp, path) {
203 let _ = std::fs::remove_file(&tmp);
204 return Err(err).with_context(|| format!("replacing {}", path.display()));
205 }
206 Ok(())
207}
208
209#[cfg(test)]
210fn render(findings: &[Finding]) -> String {
211 render_with_reasons(findings, &BTreeMap::new())
212}
213
214fn render_with_reasons(
215 findings: &[Finding],
216 existing_reasons: &BTreeMap<String, String>,
217) -> String {
218 #[derive(serde::Serialize)]
219 struct BaselineFile {
220 findings: Vec<BaselineEntry>,
221 version: u64,
222 }
223
224 let mut by_id: BTreeMap<String, BaselineEntry> = BTreeMap::new();
225 for finding in findings {
226 let at = finding.at();
227 by_id.entry(at.id.clone()).or_insert_with(|| BaselineEntry {
228 id: at.id.clone(),
229 kind: finding.kind().to_string(),
230 file: at.file.clone(),
231 item: at.item.clone(),
232 code: at.code.clone(),
233 survivors: finding.survivors().to_vec(),
234 reason: existing_reasons.get(&at.id).cloned().unwrap_or_default(),
235 });
236 }
237 serde_json::to_string_pretty(&BaselineFile {
238 findings: by_id.into_values().collect(),
239 version: VERSION,
240 })
241 .expect("baseline entries serialise")
242}
243
244#[derive(Clone, Debug, PartialEq, Eq)]
246pub enum IgnoreScope {
247 All,
249 Kinds(BTreeSet<String>),
251}
252
253#[derive(Clone, Debug, PartialEq, Eq)]
255pub struct LineIgnore {
256 pub scope: IgnoreScope,
257 pub reason: String,
258}
259
260impl LineIgnore {
261 pub fn matches_kind(&self, kind: &str) -> bool {
262 match &self.scope {
263 IgnoreScope::All => true,
264 IgnoreScope::Kinds(kinds) => kinds.contains(kind),
265 }
266 }
267
268 fn merge(&mut self, other: LineIgnore) {
269 match (&mut self.scope, other.scope) {
270 (IgnoreScope::All, IgnoreScope::All) => {
271 self.reason = other.reason;
273 }
274 (IgnoreScope::All, IgnoreScope::Kinds(_)) => {}
275 (slot, IgnoreScope::All) => {
276 *slot = IgnoreScope::All;
277 self.reason = other.reason;
279 }
280 (IgnoreScope::Kinds(existing), IgnoreScope::Kinds(extra)) => {
281 existing.extend(extra);
282 if !other.reason.is_empty() {
283 self.reason = other.reason;
284 }
285 }
286 }
287 }
288}
289
290fn parse_ignore_comment(comment: &str) -> Option<LineIgnore> {
291 let rest = comment.trim_start().strip_prefix("tmt:ignore")?;
292 if let Some(bracketed) = rest.strip_prefix('[') {
293 let close = bracketed.find(']')?;
294 let inside = &bracketed[..close];
295 let after = &bracketed[close + 1..];
296 if !(after.is_empty() || after.starts_with(|c: char| c.is_whitespace() || c == ':')) {
297 return None;
298 }
299 let mut kinds = BTreeSet::new();
300 for token in inside.split(',') {
301 let normalized = token.trim().replace('-', "_");
302 if matches!(
303 normalized.as_str(),
304 "input_gap" | "assertion_gap" | "survivor"
305 ) {
306 kinds.insert(normalized);
307 }
308 }
309 let reason = after.trim_start_matches(':').trim().to_string();
310 return Some(LineIgnore {
311 scope: IgnoreScope::Kinds(kinds),
312 reason,
313 });
314 }
315 if rest.is_empty() || rest.starts_with(|c: char| c.is_whitespace() || c == ':') {
316 let reason = rest.trim_start_matches(':').trim().to_string();
317 return Some(LineIgnore {
318 scope: IgnoreScope::All,
319 reason,
320 });
321 }
322 None
323}
324
325pub fn ignored_lines(source: &str) -> BTreeMap<usize, String> {
330 line_ignores(source)
331 .into_iter()
332 .filter(|(_, ignore)| matches!(ignore.scope, IgnoreScope::All))
333 .map(|(line, ignore)| (line, ignore.reason))
334 .collect()
335}
336
337pub fn line_ignores(source: &str) -> BTreeMap<usize, LineIgnore> {
341 let mut ignored: BTreeMap<usize, LineIgnore> = BTreeMap::new();
342 let bytes = source.as_bytes();
343 let mut i = 0;
344 let mut line = 1usize;
345 let mut line_start = 0usize;
346 let mut block_depth = 0usize;
347 while i < bytes.len() {
348 if block_depth > 0 {
349 if bytes[i] == b'/' && bytes.get(i + 1) == Some(&b'*') {
350 block_depth += 1;
351 i += 2;
352 } else if bytes[i] == b'*' && bytes.get(i + 1) == Some(&b'/') {
353 block_depth -= 1;
354 i += 2;
355 } else {
356 if bytes[i] == b'\n' {
357 line += 1;
358 line_start = i + 1;
359 }
360 i += 1;
361 }
362 continue;
363 }
364 match bytes[i] {
365 b'\n' => {
366 line += 1;
367 line_start = i + 1;
368 i += 1;
369 }
370 b'/' if bytes.get(i + 1) == Some(&b'/') => {
371 let comment_start = i + 2;
372 let mut end = comment_start;
373 while end < bytes.len() && bytes[end] != b'\n' {
374 end += 1;
375 }
376 let comment = &source[comment_start..end];
377 if let Some(directive) = parse_ignore_comment(comment) {
378 let standalone = source[line_start..i].trim().is_empty();
379 ignored
380 .entry(line)
381 .and_modify(|existing| existing.merge(directive.clone()))
382 .or_insert_with(|| directive.clone());
383 if standalone {
384 ignored
385 .entry(line + 1)
386 .and_modify(|existing| existing.merge(directive.clone()))
387 .or_insert(directive);
388 }
389 }
390 i = end;
391 }
392 b'/' if bytes.get(i + 1) == Some(&b'*') => {
393 block_depth = 1;
394 i += 2;
395 }
396 b'r' if raw_string_hashes(bytes, i).is_some() => {
398 let hashes = raw_string_hashes(bytes, i).unwrap();
399 i += 1 + hashes + 1;
400 while i < bytes.len() {
401 if bytes[i] == b'\n' {
402 line += 1;
403 line_start = i + 1;
404 }
405 if bytes[i] == b'"'
406 && bytes
407 .get(i + 1..i + 1 + hashes)
408 .is_some_and(|s| s.iter().all(|b| *b == b'#'))
409 {
410 i += 1 + hashes;
411 break;
412 }
413 i += 1;
414 }
415 }
416 b'"' => {
417 i += 1;
418 while i < bytes.len() {
419 if bytes[i] == b'\\' {
420 if bytes.get(i + 1) == Some(&b'\n') {
421 line += 1;
422 line_start = i + 2;
423 }
424 i = (i + 2).min(bytes.len());
425 continue;
426 }
427 if bytes[i] == b'\n' {
428 line += 1;
429 line_start = i + 1;
430 }
431 if bytes[i] == b'"' {
432 i += 1;
433 break;
434 }
435 i += 1;
436 }
437 }
438 b'\'' => {
440 if bytes.get(i + 1) == Some(&b'\\') && bytes.get(i + 2).is_some_and(|&b| b != b'\n')
441 {
442 let mut j = i + 3;
445 while j < bytes.len() && bytes[j] != b'\n' && bytes[j] != b'\'' {
446 j += 1;
447 }
448 if bytes.get(j) == Some(&b'\'') {
449 i = j + 1;
450 } else {
451 i += 1;
452 }
453 } else if let Some(ch) = source[i + 1..].chars().next()
454 && bytes.get(i + 1 + ch.len_utf8()) == Some(&b'\'')
455 {
456 i += 1 + ch.len_utf8() + 1;
457 } else {
458 i += 1;
459 }
460 }
461 _ => i += 1,
462 }
463 }
464 ignored
465}
466
467fn raw_string_hashes(bytes: &[u8], r_pos: usize) -> Option<usize> {
468 if r_pos > 0 {
470 let prev = bytes[r_pos - 1];
471 let is_prefix =
472 (prev == b'b' || prev == b'c') && (r_pos == 1 || !is_ident_byte(bytes[r_pos - 2]));
473 if is_ident_byte(prev) && !is_prefix {
474 return None;
475 }
476 }
477 let mut hashes = 0;
478 while bytes.get(r_pos + 1 + hashes) == Some(&b'#') {
479 hashes += 1;
480 }
481 (bytes.get(r_pos + 1 + hashes) == Some(&b'"')).then_some(hashes)
482}
483
484fn is_ident_byte(b: u8) -> bool {
485 b.is_ascii_alphanumeric() || b == b'_'
486}
487
488#[cfg(test)]
489mod tests {
490 use super::*;
491 use crate::report::Location;
492
493 fn gap(line: usize, code: &str, survivors: &[&str]) -> Finding {
494 Finding::AssertionGap {
495 at: Location {
496 file: "src/lib.rs".into(),
497 line,
498 column: 5,
499 code: code.into(),
500 ..Location::default()
501 },
502 survivors: survivors.iter().map(|s| s.to_string()).collect(),
503 tests: vec!["tests::t".into()],
504 effects: vec![],
505 effects_of: None,
506 witness: None,
507 }
508 }
509
510 #[test]
511 fn a_baseline_knows_findings_by_name_and_old_ones_by_fingerprint() {
512 let named = |id: &str, survivors: &[&str]| {
513 let mut finding = gap(10, "a > b", survivors);
514 let Finding::AssertionGap { at, .. } = &mut finding else {
515 unreachable!()
516 };
517 at.id = id.to_string();
518 finding
519 };
520 let one = named("assertion_gap|src/lib.rs|f|a > b|0", &["`a >= b`"]);
521 let other = named("assertion_gap|src/lib.rs|g|a > b|0", &["`a >= b`"]);
522 let written = render(std::slice::from_ref(&one));
523 let baseline = parse(&written).unwrap();
524 assert!(baseline.knows(&one));
525 assert!(!baseline.knows(&other));
527 assert!(baseline.knows(&named(
529 "assertion_gap|src/lib.rs|f|a > b|0",
530 &["`a >= b`", "the negation"]
531 )));
532 assert!(
534 !parse(&render(&[gap(1, "x", &[])]))
535 .unwrap()
536 .knows(&gap(2, "y", &[]))
537 );
538 let old = serde_json::to_string(&[fingerprint(&one)]).unwrap();
540 let baseline = parse(&old).unwrap();
541 assert!(matches!(baseline, Baseline::Fingerprints(_)));
542 assert!(baseline.knows(&one) && baseline.knows(&other));
543 assert!(!baseline.knows(&named("x", &["`a >= b`", "the negation"])));
544 let later = parse(r#"{"version": 4, "findings": []}"#).unwrap_err();
546 assert!(later.to_string().contains("version 4"), "{later}");
547 for bad in [
548 "{}",
549 "3",
550 r#"{"version": 2}"#,
551 r#"{"version": 2, "findings": null}"#,
552 r#"{"version": 2, "findings": [1]}"#,
553 r#"{"version": 3, "findings": [1]}"#,
554 r#"["a", 1]"#,
555 ] {
556 assert!(parse(bad).is_err(), "{bad}");
557 }
558 }
559
560 #[test]
561 fn fingerprints_ignore_position_but_not_content() {
562 let base = fingerprint(&gap(10, "a > b", &["`a >= b`"]));
563 assert_eq!(
564 base,
565 fingerprint(&gap(99, "a > b", &["`a >= b`"])),
566 "moved code"
567 );
568 assert_ne!(base, fingerprint(&gap(10, "a > c", &["`a >= b`"])));
569 assert_ne!(
570 base,
571 fingerprint(&gap(10, "a > b", &["`a >= b`", "`!(a > b)`"])),
572 "a new survivor"
573 );
574 let input = Finding::InputGap {
575 at: Location {
576 file: "src/lib.rs".into(),
577 line: 10,
578 column: 5,
579 code: "a > b".into(),
580 ..Location::default()
581 },
582 survivors: vec!["`a >= b`".into()],
583 survivor_count: 1,
584 add_tests: vec![],
585 observed: None,
586 verified: true,
587 };
588 assert_ne!(base, fingerprint(&input), "another kind of finding");
589 }
590
591 #[test]
592 fn baseline_round_trip() {
593 let path =
594 std::env::temp_dir().join(format!("tmt-baseline-test-{}.json", std::process::id()));
595 let _ = std::fs::remove_file(&path);
596 let mut findings = vec![
597 gap(1, "a > b", &["`a >= b`"]),
598 gap(2, "x();", &["delete `x();`"]),
599 ];
600 for (index, finding) in findings.iter_mut().enumerate() {
601 let Finding::AssertionGap { at, .. } = finding else {
602 unreachable!()
603 };
604 at.id = format!("id-{index}-é\n");
605 at.item = format!("fn_{index}");
606 }
607 findings.reverse();
608 findings.push(findings[0].clone());
609 write(&path, &findings).unwrap();
610 let written: serde_json::Value =
611 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
612 assert_eq!(written["version"], 3);
613 let entries = written["findings"].as_array().unwrap();
614 assert_eq!(entries.len(), 2);
615 assert_eq!(entries[0]["id"], "id-0-é\n");
616 assert_eq!(entries[0]["kind"], "assertion_gap");
617 assert_eq!(entries[0]["file"], "src/lib.rs");
618 assert_eq!(entries[0]["item"], "fn_0");
619 assert_eq!(entries[0]["code"], "a > b");
620 assert_eq!(entries[0]["survivors"], serde_json::json!(["`a >= b`"]));
621 assert_eq!(entries[0]["reason"], "");
622 assert_eq!(entries[1]["id"], "id-1-é\n");
623
624 let mut edited = written.clone();
626 edited["findings"][0]["reason"] = serde_json::json!("equivalent in domain");
627 std::fs::write(&path, serde_json::to_string_pretty(&edited).unwrap()).unwrap();
628 write(&path, &findings).unwrap();
629 let rewritten: serde_json::Value =
630 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
631 assert_eq!(rewritten["findings"][0]["reason"], "equivalent in domain");
632 assert_eq!(rewritten["findings"][1]["reason"], "");
633
634 let loaded = load(&path).unwrap();
635 let ids: BTreeSet<String> = ["id-0-é\n", "id-1-é\n"].map(str::to_string).into();
636 assert_eq!(loaded, Baseline::Ids(ids));
637 assert!(findings.iter().all(|f| loaded.knows(f)));
638
639 let broken = r#"{"version": 3, "findings": [{"id": "id-0", "reasons": "typo"}]}"#;
641 std::fs::write(&path, broken).unwrap();
642 assert!(write(&path, &findings).is_err());
643 assert_eq!(std::fs::read_to_string(&path).unwrap(), broken);
644
645 std::fs::write(&path, "not json").unwrap();
646 assert!(load(&path).is_err());
647 assert!(write(&path, &findings).is_err());
648 assert_eq!(std::fs::read_to_string(&path).unwrap(), "not json");
649 std::fs::remove_file(&path).unwrap();
650 assert!(load(&path).is_err());
651 }
652
653 #[test]
654 fn baseline_accepts_legacy_strings_and_structured_entries_mixed() {
655 let v2 = r#"{"version": 2, "findings": ["v2-id"]}"#;
656 assert_eq!(
657 parse(v2).unwrap(),
658 Baseline::Ids(["v2-id"].map(str::to_string).into())
659 );
660
661 let mixed = r#"{
662 "version": 3,
663 "findings": [
664 "legacy-id",
665 {
666 "id": "structured-id",
667 "kind": "input_gap",
668 "file": "src/lib.rs",
669 "code": "x > 0",
670 "survivors": ["`x >= 0`"],
671 "reason": "zero is unreachable"
672 }
673 ]
674}"#;
675 let (baseline, reasons) = parse_with_reasons(mixed).unwrap();
676 assert_eq!(
677 baseline,
678 Baseline::Ids(["legacy-id", "structured-id"].map(str::to_string).into())
679 );
680 assert_eq!(
681 reasons.get("structured-id").map(String::as_str),
682 Some("zero is unreachable")
683 );
684 assert!(!reasons.contains_key("legacy-id"));
685
686 let typo = r#"{"version": 3, "findings": [{"id": "x", "reasons": "typo"}]}"#;
688 assert!(parse(typo).is_err());
689 let missing_id = r#"{"version": 3, "findings": [{"reason": "no id"}]}"#;
690 assert!(parse(missing_id).is_err());
691 }
692
693 #[test]
694 fn selective_ignore_comments() {
695 let source = "\
696fn f() {
697 // tmt:ignore[input_gap] boundary is equivalent
698 if a >= b { a } else { b }
699 let x = 1; // tmt:ignore[assertion-gap, survivor]: intentional
700 // tmt:ignore[input_gap] above
701 let y = 2; // tmt:ignore[assertion_gap] inline
702 // tmt:ignore[unknown_kind] should not suppress anything
703 let z = 3;
704 let empty = 4; // tmt:ignore[] empty list
705 let unclosed = 5; // tmt:ignore[input_gap missing bracket
706 let attached = 6; // tmt:ignore[input_gap]extra
707}
708";
709 let ignores = line_ignores(source);
710 assert!(ignores[&3].matches_kind("input_gap"));
712 assert!(!ignores[&3].matches_kind("assertion_gap"));
713 assert!(!ignores[&3].matches_kind("survivor"));
714 assert_eq!(ignores[&3].reason, "boundary is equivalent");
715
716 assert!(!ignores[&4].matches_kind("input_gap"));
718 assert!(ignores[&4].matches_kind("assertion_gap"));
719 assert!(ignores[&4].matches_kind("survivor"));
720 assert_eq!(ignores[&4].reason, "intentional");
721
722 assert!(ignores[&6].matches_kind("input_gap"));
724 assert!(ignores[&6].matches_kind("assertion_gap"));
725 assert!(!ignores[&6].matches_kind("survivor"));
726
727 assert!(!ignores[&8].matches_kind("input_gap"));
729 assert!(!ignores[&8].matches_kind("assertion_gap"));
730 assert!(!ignores[&8].matches_kind("survivor"));
731
732 assert!(!ignores[&9].matches_kind("input_gap"));
734
735 assert!(!ignores.contains_key(&10));
737 assert!(!ignores.contains_key(&11));
738
739 assert!(ignored_lines(source).is_empty());
741
742 let overlap = "\
744fn g() {
745 // tmt:ignore above
746 let a = 1; // tmt:ignore inline
747 // tmt:ignore[input_gap] scoped above
748 let b = 2; // tmt:ignore unscoped inline
749}
750";
751 let legacy = ignored_lines(overlap);
752 assert_eq!(legacy.get(&3).map(String::as_str), Some("inline"));
753 assert_eq!(legacy.get(&5).map(String::as_str), Some("unscoped inline"));
754 }
755
756 #[test]
757 fn ignore_comments() {
758 let source = "\
759fn f() {
760 // tmt:ignore equivalent: both branches return the same
761 if a >= b { a } else { b }
762 let x = 1; // tmt:ignore
763 let y = 2;
764 let z = 3;
765 let w = 4; // tmt:ignore: with a colon
766 // tmt:ignored is another word
767 // not tmt:ignore here? it is: tmt:ignore must start the comment
768 let url = \"http://tmt:ignore reason\";
769 let ok = \"https://example.com\"; // tmt:ignore after url
770 let raw = r#\"// tmt:ignore inside raw string\"#;
771 /* // tmt:ignore inside block comment */
772 let ch = '\"'; // tmt:ignore after quote char
773 let quotes = ['\\'', '\"'];
774 let fake = \"// tmt:ignore fake after escaped quote\";
775 let real = 5; // tmt:ignore after escaped quote
776}
777";
778 let ignored = ignored_lines(source);
779 assert_eq!(
780 ignored.keys().copied().collect::<Vec<_>>(),
781 [2, 3, 4, 7, 11, 14, 17]
782 );
783 assert_eq!(ignored[&7], "with a colon");
784 assert_eq!(ignored[&2], "equivalent: both branches return the same");
785 assert_eq!(ignored[&3], "equivalent: both branches return the same");
786 assert_eq!(ignored[&4], "");
787 assert_eq!(ignored[&11], "after url");
788 assert_eq!(ignored[&14], "after quote char");
789 assert_eq!(ignored[&17], "after escaped quote");
790 assert!(ignored_lines("").is_empty());
791 }
792}