compiletest/runtest/
debugger.rs

1use std::fmt::Write;
2use std::fs::File;
3use std::io::{BufRead, BufReader};
4use std::path::{Path, PathBuf};
5
6use crate::common::Config;
7use crate::runtest::ProcRes;
8
9/// Representation of information to invoke a debugger and check its output
10pub(super) struct DebuggerCommands {
11    /// Commands for the debuuger
12    pub commands: Vec<String>,
13    /// Lines to insert breakpoints at
14    pub breakpoint_lines: Vec<usize>,
15    /// Contains the source line number to check and the line itself
16    check_lines: Vec<(usize, String)>,
17    /// Source file name
18    file: PathBuf,
19}
20
21impl DebuggerCommands {
22    pub fn parse_from(file: &Path, config: &Config, debugger_prefix: &str) -> Result<Self, String> {
23        let command_directive = format!("{debugger_prefix}-command");
24        let check_directive = format!("{debugger_prefix}-check");
25
26        let mut breakpoint_lines = vec![];
27        let mut commands = vec![];
28        let mut check_lines = vec![];
29        let mut counter = 0;
30        let reader = BufReader::new(File::open(file).unwrap());
31        for (line_no, line) in reader.lines().enumerate() {
32            counter += 1;
33            let line = line.map_err(|e| format!("Error while parsing debugger commands: {}", e))?;
34
35            // Breakpoints appear on lines with actual code, typically at the end of the line.
36            if line.contains("#break") {
37                breakpoint_lines.push(counter);
38                continue;
39            }
40
41            let Some(line) = line.trim_start().strip_prefix("//").map(str::trim_start) else {
42                continue;
43            };
44
45            if let Some(command) = config.parse_name_value_directive(&line, &command_directive) {
46                commands.push(command);
47            }
48            if let Some(pattern) = config.parse_name_value_directive(&line, &check_directive) {
49                check_lines.push((line_no, pattern));
50            }
51        }
52
53        Ok(Self { commands, breakpoint_lines, check_lines, file: file.to_owned() })
54    }
55
56    /// Given debugger output and lines to check, ensure that every line is
57    /// contained in the debugger output. The check lines need to be found in
58    /// order, but there can be extra lines between.
59    pub fn check_output(&self, debugger_run_result: &ProcRes) -> Result<(), String> {
60        // (src_lineno, ck_line)  that we did find
61        let mut found = vec![];
62        // (src_lineno, ck_line) that we couldn't find
63        let mut missing = vec![];
64        //  We can find our any current match anywhere after our last match
65        let mut last_idx = 0;
66        let dbg_lines: Vec<&str> = debugger_run_result.stdout.lines().collect();
67
68        for (src_lineno, ck_line) in &self.check_lines {
69            if let Some(offset) = dbg_lines
70                .iter()
71                .skip(last_idx)
72                .position(|out_line| check_single_line(out_line, &ck_line))
73            {
74                last_idx += offset;
75                found.push((src_lineno, dbg_lines[last_idx]));
76            } else {
77                missing.push((src_lineno, ck_line));
78            }
79        }
80
81        if missing.is_empty() {
82            Ok(())
83        } else {
84            let fname = self.file.file_name().unwrap().to_string_lossy();
85            let mut msg = format!(
86                "check directive(s) from `{}` not found in debugger output. errors:",
87                self.file.display()
88            );
89
90            for (src_lineno, err_line) in missing {
91                write!(msg, "\n    ({fname}:{num}) `{err_line}`", num = src_lineno + 1).unwrap();
92            }
93
94            if !found.is_empty() {
95                let init = "\nthe following subset of check directive(s) was found successfully:";
96                msg.push_str(init);
97                for (src_lineno, found_line) in found {
98                    write!(msg, "\n    ({fname}:{num}) `{found_line}`", num = src_lineno + 1)
99                        .unwrap();
100                }
101            }
102
103            Err(msg)
104        }
105    }
106}
107
108/// Check that the pattern in `check_line` applies to `line`. Returns `true` if they do match.
109fn check_single_line(line: &str, check_line: &str) -> bool {
110    // Allow check lines to leave parts unspecified (e.g., uninitialized
111    // bits in the  wrong case of an enum) with the notation "[...]".
112    let line = line.trim();
113    let check_line = check_line.trim();
114    let can_start_anywhere = check_line.starts_with("[...]");
115    let can_end_anywhere = check_line.ends_with("[...]");
116
117    let check_fragments: Vec<&str> =
118        check_line.split("[...]").filter(|frag| !frag.is_empty()).collect();
119    if check_fragments.is_empty() {
120        return true;
121    }
122
123    let (mut rest, first_fragment) = if can_start_anywhere {
124        let Some(pos) = line.find(check_fragments[0]) else {
125            return false;
126        };
127        (&line[pos + check_fragments[0].len()..], 1)
128    } else {
129        (line, 0)
130    };
131
132    for current_fragment in &check_fragments[first_fragment..] {
133        let Some(pos) = rest.find(current_fragment) else {
134            return false;
135        };
136        rest = &rest[pos + current_fragment.len()..];
137    }
138
139    can_end_anywhere || rest.is_empty()
140}