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
use crate::internal::debug_empty_span;
use crate::internal::debug_multi_line_span;
use crate::internal::debug_single_line_span;
use crate::internal::is_empty_span;
use crate::internal::is_single_line_span;

pub fn debug_span(span: proc_macro2::Span, code: &str) -> String {
    if is_empty_span(span) {
        debug_empty_span(span, code)
    } else if is_single_line_span(span) {
        debug_single_line_span(span, code)
    } else {
        debug_multi_line_span(span, code)
    }
}

#[doc(hidden)]
pub mod internal {
    pub fn is_empty_span(span: proc_macro2::Span) -> bool {
        span.start() == span.end()
    }

    pub fn debug_empty_span(_span: proc_macro2::Span, _code: &str) -> String {
        "".to_string()
    }

    pub fn is_single_line_span(span: proc_macro2::Span) -> bool {
        span.start().line == span.end().line
    }

    pub fn debug_single_line_span(span: proc_macro2::Span, code: &str) -> String {
        let empty_line = empty_line(span);
        let range_line = range_line(span);
        let code_line = code_line(span, code);
        let marker_line = marker_line(span);
        format!(
            "{}\n{}\n{}\n{}\n{}\n",
            range_line, empty_line, code_line, marker_line, empty_line,
        )
    }

    pub fn debug_multi_line_span(span: proc_macro2::Span, code: &str) -> String {
        let empty_line = empty_line(span);
        let range_line = range_line(span);
        let start_line = start_line(span, code);
        let code_lines = code_lines(span, code);
        let end_line = end_line(span, code);
        format!(
            "{}\n{}\n{}\n{}\n{}\n{}\n",
            range_line, empty_line, start_line, code_lines, end_line, empty_line,
        )
    }

    pub fn range_line(span: proc_macro2::Span) -> String {
        let line_number_width = span.end().line.to_string().len();
        let range = span_to_range(span);
        format!("{:width$}--> {}", "", range, width = line_number_width,)
    }

    pub fn span_to_range(span: proc_macro2::Span) -> String {
        format!(
            "{}:{}..{}:{}",
            span.start().line,
            span.start().column,
            span.end().line,
            span.end().column,
        )
    }

    pub fn empty_line(span: proc_macro2::Span) -> String {
        let line_number_width = span.end().line.to_string().len();
        format!("{:width$} |", "", width = line_number_width)
    }

    pub fn marker_line(span: proc_macro2::Span) -> String {
        let line_number_width = span.end().line.to_string().len();
        let start_column = span.start().column;
        let end_column = span.end().column;

        let marker = "^".repeat(end_column - start_column);
        format!(
            "{:width$} | {:space$}{}",
            "",
            "",
            marker,
            space = start_column,
            width = line_number_width,
        )
    }

    pub fn code_line(span: proc_macro2::Span, code: &str) -> String {
        let line_number_width = span.end().line.to_string().len();
        let line = code.lines().nth(span.start().line - 1).unwrap();
        format!(
            "{:width$} | {}",
            span.start().line,
            line,
            width = line_number_width,
        )
    }

    const PADDING: usize = 3;

    pub fn start_line(span: proc_macro2::Span, code: &str) -> String {
        let line_number_width = span.end().line.to_string().len();
        let start = span.start();
        let end = span.end();
        let lines = code
            .lines()
            .skip(start.line - 1)
            .take(end.line - start.line + 1);
        let max_line_len = lines.map(|line| line.len()).max().unwrap();
        format!(
            "{:width$} | {}┌{}╮",
            "",
            " ".repeat(start.column),
            "─".repeat(max_line_len + PADDING - start.column),
            width = line_number_width,
        )
    }

    pub fn code_lines(span: proc_macro2::Span, code: &str) -> String {
        let line_number_width = span.end().line.to_string().len();
        let start = span.start();
        let end = span.end();
        let lines = code
            .lines()
            .skip(start.line - 1)
            .take(end.line - start.line + 1);
        let max_line_len = lines.clone().map(|line| line.len()).max().unwrap();
        lines
            .into_iter()
            .enumerate()
            .map(|(i, line)| {
                let line_number = start.line + i;
                format!(
                    "{: >line_number_width$} | {}{}│",
                    line_number,
                    line,
                    " ".repeat(max_line_len + PADDING + 1 - line.len()),
                )
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    pub fn end_line(span: proc_macro2::Span, code: &str) -> String {
        let line_number_width = span.end().line.to_string().len();
        let start = span.start();
        let end = span.end();
        let lines = code
            .lines()
            .skip(start.line - 1)
            .take(end.line - start.line + 1);
        let max_line_len = lines.map(|line| line.len()).max().unwrap();
        format!(
            "{:width$} | {}└{}╯",
            "",
            " ".repeat(end.column - 1),
            "─".repeat(max_line_len + PADDING - end.column + 1),
            width = line_number_width,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use syn::spanned::Spanned;
    use syn::Data;
    use unindent::Unindent;

    #[test]
    fn test_single_line() {
        let input = r###"
            struct Foo;
        "###
        .unindent();
        let derive_input: syn::DeriveInput = syn::parse_str(&input).unwrap();
        let span = derive_input.ident.span();
        let output = debug_span(span, &input);
        insta::assert_snapshot!(output, @r###"
         --> 1:7..1:10
          |
        1 | struct Foo;
          |        ^^^
          |
        "###);
    }
    #[test]
    fn test_single_line_large_line_number() {
        let input = r###"
            struct Foo;
        "###
        .unindent();
        let input = "\n".repeat(120) + &input;
        let derive_input: syn::DeriveInput = syn::parse_str(&input).unwrap();
        let span = derive_input.ident.span();
        let output = debug_span(span, &input);
        insta::assert_snapshot!(output, @r###"
           --> 121:7..121:10
            |
        121 | struct Foo;
            |        ^^^
            |
        "###);
    }

    #[test]
    fn test_multi_line() {
        let input = r###"
            struct Foo {
                a: i32,
                b: i32,
            }
        "###
        .unindent();
        let derive_input: syn::DeriveInput = syn::parse_str(&input).unwrap();
        let span = match derive_input.data {
            Data::Struct(s) => s.fields.span(),
            _ => panic!("expected struct"),
        };

        let output = debug_span(span, &input);
        insta::assert_snapshot!(output, @r###"
         --> 1:11..4:1
          |
          |            ┌────╮
        1 | struct Foo {    │
        2 |     a: i32,     │
        3 |     b: i32,     │
        4 | }               │
          | └───────────────╯
          |
        "###);
    }

    #[test]
    fn test_multi_line_large_line_number() {
        let input = r###"
            struct Foo {
                a: i32,
                b: i32,
            }
        "###
        .unindent();
        let input = "\n".repeat(120) + &input;
        let derive_input: syn::DeriveInput = syn::parse_str(&input).unwrap();
        let span = match derive_input.data {
            Data::Struct(s) => s.fields.span(),
            _ => panic!("expected struct"),
        };

        let output = debug_span(span, &input);
        insta::assert_snapshot!(output, @r###"
           --> 121:11..124:1
            |
            |            ┌────╮
        121 | struct Foo {    │
        122 |     a: i32,     │
        123 |     b: i32,     │
        124 | }               │
            | └───────────────╯
            |
        "###);
    }

    #[test]
    fn test_multi_line_large_line() {
        let input = r###"
            struct Foo {
                a: std::collections::HashMap<i32, i32>,
                b: i32,
            }
        "###
        .unindent();
        let derive_input: syn::DeriveInput = syn::parse_str(&input).unwrap();
        let span = match derive_input.data {
            Data::Struct(s) => s.fields.span(),
            _ => panic!("expected struct"),
        };

        let output = debug_span(span, &input);
        insta::assert_snapshot!(output, @r###"
         --> 1:11..4:1
          |
          |            ┌───────────────────────────────────╮
        1 | struct Foo {                                   │
        2 |     a: std::collections::HashMap<i32, i32>,    │
        3 |     b: i32,                                    │
        4 | }                                              │
          | └──────────────────────────────────────────────╯
          |
        "###);
    }

    #[test]
    fn test_syn_error() {
        let input = r###"
            struct Foo {
                a: i32
                bar: i32,
            }
        "###
        .unindent();
        let derive_input: Result<syn::DeriveInput, _> = syn::parse_str(&input);
        let error = match derive_input {
            Ok(_) => panic!("expected error"),
            Err(e) => e,
        };
        let span = error.span();
        let output = debug_span(span, &input);
        insta::assert_snapshot!(error.to_string(), @"expected `,`");
        insta::assert_snapshot!(output, @r###"
         --> 3:4..3:7
          |
        3 |     bar: i32,
          |     ^^^
          |
        "###);
    }
}