File: ast.rs

package info (click to toggle)
rust-k9 0.12.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 296 kB
  • sloc: makefile: 2
file content (196 lines) | stat: -rw-r--r-- 5,921 bytes parent folder | download | duplicates (2)
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
use super::source_code::{extract_range, LineColumn, Range};
use anyhow::{Context, Result};
use proc_macro2::{Span, TokenStream, TokenTree};
use syn::spanned::Spanned;
use syn::visit::Visit;
use syn::{Macro, PathSegment};

#[derive(Debug)]
struct MacroVisitor {
    found: Option<(TokenStream, Macro)>,
    line: usize,
    macro_name: String,
}

impl<'ast> Visit<'ast> for MacroVisitor {
    fn visit_macro(&mut self, m: &'ast Macro) {
        let last_path_segment = m.path.segments.last();
        if let Some(PathSegment { ident, .. }) = last_path_segment {
	    if ident == &self.macro_name && ident.span().start().line == self.line {
                self.found.replace((m.tokens.to_owned(), m.to_owned()));
            }
        }
    }
}

/// Find the Range containing the space where snapshot literal needs to be written.
///
/// If a literal already exists, it will return the range of the existing string literal.
///
/// some_macro!(blah);
///                ^
///                |
///        0 length range of the position where
///        new snapshot needs to be written
///            
/// Otherwise, if the snapshot literal is there, return its range
///
/// some_macro(blah, "hello")
///                  ^     ^
///                  |     |
///                   range
pub fn find_snapshot_literal_range<S: Into<String>>(
    file_content: &str,
    macro_name: S,
    line_num: usize,
    literal_exists: bool,
) -> Result<Range> {
    let syntax = syn::parse_file(file_content).expect("Unable to parse file");
    let macro_name = macro_name.into();

    let mut macro_visitor = MacroVisitor {
        found: None,
        line: line_num,
        macro_name: macro_name.clone(),
    };

    macro_visitor.visit_file(&syntax);

    let (tt, macro_node) = macro_visitor.found.with_context(|| {
        format!(
            "Failed to find a macro call AST node with macro name `{}!()`.\nThis macro was called on line `{}`\n\n",
            &macro_name, line_num
        )
    })?;

    if literal_exists {
        let literal = tt.into_iter().last();

        if let Some(TokenTree::Literal(literal)) = literal {
            Ok(Range {
                start: LineColumn {
                    line: literal.span().start().line,
                    // columns might be 0 based? i'm not sure
                    column: literal.span().start().column + 1,
                },
                end: LineColumn {
                    line: literal.span().end().line,
                    column: literal.span().end().column + 1,
                },
            })
        } else {
            let macro_range = syn_span_to_range(macro_node.span());
            let macro_code = extract_range(file_content, &macro_range);
            anyhow::bail!(
                r#"
Failed to extract a snapshot literal from a snapshot macro call.
Snapshot literal must be the last argument to a macro call and must be a string literal. e.g.

assert_matches_inline_snapshot!(12345, "12345");
                                       ^     ^
                                       |     |
                                   snapshot literal

Given macro call:

```
{}
```
"#,
                macro_code,
            )
        }
    } else {
        let last = tt.into_iter().last().expect("must have last tokentree");
        let span = last.span();

        Ok(Range {
            start: LineColumn {
                line: span.end().line,
                column: span.end().column + 1,
            },
            end: LineColumn {
                line: span.end().line,
                column: span.end().column + 1,
            },
        })
    }
}

/// Convert proc_macro2 Span struct to local Range struct, which indexes
/// for Lines and Columns starting from 1 and not 0
fn syn_span_to_range(span: Span) -> Range {
    Range {
        start: LineColumn {
            line: span.start().line,
            column: span.start().column + 1,
        },
        end: LineColumn {
            line: span.end().line,
            column: span.end().column + 1,
        },
    }
}

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

    const SOURCE: &str = r##"                       // 1
fn main() {                                         // 2
    let hello = "world";                            // 3
    random_macro!(hello);                           // 4 
    hello_macro!(stuff, "literal");                 // 5
    wrong_macro!(stuff, not_a_literal);             // 6
}
"##;
    #[test]
    fn no_literal() -> Result<()> {
        let range = find_snapshot_literal_range(SOURCE, "random_macro", 4, false)?;
        k9::assert_equal!(&range.start, &range.end);

        k9::snapshot!(
            format!("{:?}", range),
            r##"Range { start: LineColumn { line: 4, column: 24 }, end: LineColumn { line: 4, column: 24 } }"##
        );
        Ok(())
    }

    #[test]
    fn literal() -> Result<()> {
        let range = find_snapshot_literal_range(SOURCE, "hello_macro", 5, true)?;

        k9::snapshot!(
            format!("{:?}", range),
            r##"Range { start: LineColumn { line: 5, column: 25 }, end: LineColumn { line: 5, column: 34 } }"##
        );
        Ok(())
    }

    #[test]
    #[ignore = "the error stacktrace shows up in the snapshot and causes a mismatch"]
    fn not_a_literal_error() {
        let err = find_snapshot_literal_range(SOURCE, "wrong_macro", 6, true).unwrap_err();

        k9::snapshot!(
            format!("{:?}", err),
            r#"

Failed to extract a snapshot literal from a snapshot macro call.
Snapshot literal must be the last argument to a macro call and must be a string literal. e.g.

assert_matches_inline_snapshot!(12345, "12345");
                                       ^     ^
                                       |     |
                                   snapshot literal

Given macro call:

```
wrong_macro!(stuff, not_a_literal)
```

"#
        );
    }
}