thiserror_impl/
fmt.rs

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::ast::{ContainerKind, Field};
use crate::attr::{Display, Trait};
use crate::scan_expr::scan_expr;
use crate::unraw::{IdentUnraw, MemberUnraw};
use proc_macro2::{Delimiter, TokenStream, TokenTree};
use quote::{format_ident, quote, quote_spanned, ToTokens as _};
use std::collections::{BTreeSet, HashMap};
use std::iter;
use syn::ext::IdentExt;
use syn::parse::discouraged::Speculative;
use syn::parse::{Error, ParseStream, Parser, Result};
use syn::{Expr, Ident, Index, LitStr, Token};

impl Display<'_> {
    pub fn expand_shorthand(&mut self, fields: &[Field], container: ContainerKind) -> Result<()> {
        let raw_args = self.args.clone();
        let FmtArguments {
            named: user_named_args,
            first_unnamed,
        } = explicit_named_args.parse2(raw_args).unwrap();

        let mut member_index = HashMap::new();
        let mut extra_positional_arguments_allowed = true;
        for (i, field) in fields.iter().enumerate() {
            member_index.insert(&field.member, i);
            extra_positional_arguments_allowed &= matches!(&field.member, MemberUnraw::Named(_));
        }

        let span = self.fmt.span();
        let fmt = self.fmt.value();
        let mut read = fmt.as_str();
        let mut out = String::new();
        let mut has_bonus_display = false;
        let mut infinite_recursive = false;
        let mut implied_bounds = BTreeSet::new();
        let mut bindings = Vec::new();
        let mut macro_named_args = BTreeSet::new();

        self.requires_fmt_machinery = self.requires_fmt_machinery || fmt.contains('}');

        while let Some(brace) = read.find('{') {
            self.requires_fmt_machinery = true;
            out += &read[..brace + 1];
            read = &read[brace + 1..];
            if read.starts_with('{') {
                out.push('{');
                read = &read[1..];
                continue;
            }
            let next = match read.chars().next() {
                Some(next) => next,
                None => return Ok(()),
            };
            let member = match next {
                '0'..='9' => {
                    let int = take_int(&mut read);
                    if !extra_positional_arguments_allowed {
                        if let Some(first_unnamed) = &first_unnamed {
                            let msg = format!("ambiguous reference to positional arguments by number in a {container}; change this to a named argument");
                            return Err(Error::new_spanned(first_unnamed, msg));
                        }
                    }
                    match int.parse::<u32>() {
                        Ok(index) => MemberUnraw::Unnamed(Index { index, span }),
                        Err(_) => return Ok(()),
                    }
                }
                'a'..='z' | 'A'..='Z' | '_' => {
                    if read.starts_with("r#") {
                        continue;
                    }
                    let repr = take_ident(&mut read);
                    if repr == "_" {
                        // Invalid. Let rustc produce the diagnostic.
                        out += repr;
                        continue;
                    }
                    let ident = IdentUnraw::new(Ident::new(repr, span));
                    if user_named_args.contains(&ident) {
                        // Refers to a named argument written by the user, not to field.
                        out += repr;
                        continue;
                    }
                    MemberUnraw::Named(ident)
                }
                _ => continue,
            };
            let end_spec = match read.find('}') {
                Some(end_spec) => end_spec,
                None => return Ok(()),
            };
            let mut bonus_display = false;
            let bound = match read[..end_spec].chars().next_back() {
                Some('?') => Trait::Debug,
                Some('o') => Trait::Octal,
                Some('x') => Trait::LowerHex,
                Some('X') => Trait::UpperHex,
                Some('p') => Trait::Pointer,
                Some('b') => Trait::Binary,
                Some('e') => Trait::LowerExp,
                Some('E') => Trait::UpperExp,
                Some(_) => Trait::Display,
                None => {
                    bonus_display = true;
                    has_bonus_display = true;
                    Trait::Display
                }
            };
            infinite_recursive |= member == *"self" && bound == Trait::Display;
            let field = match member_index.get(&member) {
                Some(&field) => field,
                None => {
                    out += &member.to_string();
                    continue;
                }
            };
            implied_bounds.insert((field, bound));
            let formatvar_prefix = if bonus_display {
                "__display"
            } else if bound == Trait::Pointer {
                "__pointer"
            } else {
                "__field"
            };
            let mut formatvar = IdentUnraw::new(match &member {
                MemberUnraw::Unnamed(index) => format_ident!("{}{}", formatvar_prefix, index),
                MemberUnraw::Named(ident) => {
                    format_ident!("{}_{}", formatvar_prefix, ident.to_string())
                }
            });
            while user_named_args.contains(&formatvar) {
                formatvar = IdentUnraw::new(format_ident!("_{}", formatvar.to_string()));
            }
            formatvar.set_span(span);
            out += &formatvar.to_string();
            if !macro_named_args.insert(formatvar.clone()) {
                // Already added to bindings by a previous use.
                continue;
            }
            let mut binding_value = match &member {
                MemberUnraw::Unnamed(index) => format_ident!("_{}", index),
                MemberUnraw::Named(ident) => ident.to_local(),
            };
            binding_value.set_span(span.resolved_at(fields[field].member.span()));
            let wrapped_binding_value = if bonus_display {
                quote_spanned!(span=> #binding_value.as_display())
            } else if bound == Trait::Pointer {
                quote!(::thiserror::__private::Var(#binding_value))
            } else {
                binding_value.into_token_stream()
            };
            bindings.push((formatvar.to_local(), wrapped_binding_value));
        }

        out += read;
        self.fmt = LitStr::new(&out, self.fmt.span());
        self.has_bonus_display = has_bonus_display;
        self.infinite_recursive = infinite_recursive;
        self.implied_bounds = implied_bounds;
        self.bindings = bindings;
        Ok(())
    }
}

struct FmtArguments {
    named: BTreeSet<IdentUnraw>,
    first_unnamed: Option<TokenStream>,
}

#[allow(clippy::unnecessary_wraps)]
fn explicit_named_args(input: ParseStream) -> Result<FmtArguments> {
    let ahead = input.fork();
    if let Ok(set) = try_explicit_named_args(&ahead) {
        input.advance_to(&ahead);
        return Ok(set);
    }

    let ahead = input.fork();
    if let Ok(set) = fallback_explicit_named_args(&ahead) {
        input.advance_to(&ahead);
        return Ok(set);
    }

    input.parse::<TokenStream>().unwrap();
    Ok(FmtArguments {
        named: BTreeSet::new(),
        first_unnamed: None,
    })
}

fn try_explicit_named_args(input: ParseStream) -> Result<FmtArguments> {
    let mut syn_full = None;
    let mut args = FmtArguments {
        named: BTreeSet::new(),
        first_unnamed: None,
    };

    while !input.is_empty() {
        input.parse::<Token![,]>()?;
        if input.is_empty() {
            break;
        }

        let mut begin_unnamed = None;
        if input.peek(Ident::peek_any) && input.peek2(Token![=]) && !input.peek2(Token![==]) {
            let ident: IdentUnraw = input.parse()?;
            input.parse::<Token![=]>()?;
            args.named.insert(ident);
        } else {
            begin_unnamed = Some(input.fork());
        }

        let ahead = input.fork();
        if *syn_full.get_or_insert_with(is_syn_full) && ahead.parse::<Expr>().is_ok() {
            input.advance_to(&ahead);
        } else {
            scan_expr(input)?;
        }

        if let Some(begin_unnamed) = begin_unnamed {
            if args.first_unnamed.is_none() {
                args.first_unnamed = Some(between(&begin_unnamed, input));
            }
        }
    }

    Ok(args)
}

fn fallback_explicit_named_args(input: ParseStream) -> Result<FmtArguments> {
    let mut args = FmtArguments {
        named: BTreeSet::new(),
        first_unnamed: None,
    };

    while !input.is_empty() {
        if input.peek(Token![,])
            && input.peek2(Ident::peek_any)
            && input.peek3(Token![=])
            && !input.peek3(Token![==])
        {
            input.parse::<Token![,]>()?;
            let ident: IdentUnraw = input.parse()?;
            input.parse::<Token![=]>()?;
            args.named.insert(ident);
        } else {
            input.parse::<TokenTree>()?;
        }
    }

    Ok(args)
}

fn is_syn_full() -> bool {
    // Expr::Block contains syn::Block which contains Vec<syn::Stmt>. In the
    // current version of Syn, syn::Stmt is exhaustive and could only plausibly
    // represent `trait Trait {}` in Stmt::Item which contains syn::Item. Most
    // of the point of syn's non-"full" mode is to avoid compiling Item and the
    // entire expansive syntax tree it comprises. So the following expression
    // being parsed to Expr::Block is a reliable indication that "full" is
    // enabled.
    let test = quote!({
        trait Trait {}
    });
    match syn::parse2(test) {
        Ok(Expr::Verbatim(_)) | Err(_) => false,
        Ok(Expr::Block(_)) => true,
        Ok(_) => unreachable!(),
    }
}

fn take_int<'a>(read: &mut &'a str) -> &'a str {
    let mut int_len = 0;
    for ch in read.chars() {
        match ch {
            '0'..='9' => int_len += 1,
            _ => break,
        }
    }
    let (int, rest) = read.split_at(int_len);
    *read = rest;
    int
}

fn take_ident<'a>(read: &mut &'a str) -> &'a str {
    let mut ident_len = 0;
    for ch in read.chars() {
        match ch {
            'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => ident_len += 1,
            _ => break,
        }
    }
    let (ident, rest) = read.split_at(ident_len);
    *read = rest;
    ident
}

fn between<'a>(begin: ParseStream<'a>, end: ParseStream<'a>) -> TokenStream {
    let end = end.cursor();
    let mut cursor = begin.cursor();
    let mut tokens = TokenStream::new();

    while cursor < end {
        let (tt, next) = cursor.token_tree().unwrap();

        if end < next {
            if let Some((inside, _span, _after)) = cursor.group(Delimiter::None) {
                cursor = inside;
                continue;
            }
            if tokens.is_empty() {
                tokens.extend(iter::once(tt));
            }
            break;
        }

        tokens.extend(iter::once(tt));
        cursor = next;
    }

    tokens
}