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
extern crate proc_macro;
use ::proc_macro::TokenStream;
use ::quote::{
    quote,
    ToTokens,
};
use ::proc_macro2::{
    TokenStream as TokenStream2,
};
use ::syn::{*,
    parse::{
        Parse,
        ParseStream,
    },
    punctuated::Punctuated,
};
use ::std::ops::Not;

#[macro_use]
mod macros;

#[allow(dead_code)] // dumb compiler does not see the struct being used...
struct Input {
    format_literal: LitStr,
    positional_args: Vec<Expr>,
    named_args: Vec<(Ident, Expr)>,
}

impl Parse for Input {
    fn parse (input: ParseStream) -> Result<Self>
    {
        let format_literal = input.parse()?;
        let mut positional_args = vec![];
        loop {
            if input.parse::<Option<Token![,]>>()?.is_none() {
                return Ok(Self {
                    format_literal,
                    positional_args,
                    named_args: vec![],
                });
            }
            if  input.peek(Ident) &&
                input.peek2(Token![=]) &&
                input.peek3(Token![=]).not()
            {
                // Found a positional parameter
                break;
            }
            positional_args.push(input.parse()?);
        }
        let named_args =
            Punctuated::<_, Token![,]>::parse_terminated_with(
                input,
                |input| Ok({
                    let name: Ident = input.parse()?;
                    let _: Token![=] = input.parse()?;
                    let expr: Expr = input.parse()?;
                    (name, expr)
                }),
            )?
            .into_iter()
            .collect()
        ;
        Ok(Self {
            format_literal,
            positional_args,
            named_args,
        })
    }
}

#[::proc_macro_hack::proc_macro_hack] pub
fn format_args_f (input: TokenStream) -> TokenStream
{
    #[allow(unused)]
    const FUNCTION_NAME: &str = "format_args_f";

    debug_input!(&input);

    let Input {
        mut format_literal,
        mut positional_args,
        mut named_args,
    } = parse_macro_input!(input);

    let s = format_literal.value();
    let ref mut out_format_literal = String::with_capacity(s.len());

    // char_indices returns index and char.
    let mut iterator = s.char_indices().peekable();
    while let Some((i, c)) = iterator.next() {
        out_format_literal.push(c);
        if c != '{' {
            continue;
        }
        // encountered `{`, let's see if it was `{{`
        if let Some(&(_, '{')) = iterator.peek() {
            let _ = iterator.next();
            out_format_literal.push('{');
            continue;
        }
        let (end, colon_or_closing_brace) =
            iterator
                .find(|&(_, c)| c == '}' || c == ':')
                .expect(concat!(
                    "Invalid format string literal\n",
                    "note: if you intended to print `{`, ",
                    "you can escape it using `{{`",
                ))
        ;
        // We use defer to ensure all the `continue`s append the closing char.
        let mut out_format_literal = defer(
            &mut *out_format_literal,
            |it| it.push(colon_or_closing_brace),
        );
        let out_format_literal: &mut String = &mut *out_format_literal;
        let mut arg = s[i + 1 .. end].trim();
        if let Some("=") = arg.get(arg.len().saturating_sub(1) ..) {
            assert_eq!(
                out_format_literal.pop(),  // Remove the opening brace
                Some('{'),
            );
            arg = &arg[.. arg.len() - 1];
            out_format_literal.push_str(arg);
            out_format_literal.push_str(" = {");
        }
        if arg.is_empty() {
            continue;
        }

        enum Segment { Ident(Ident), LitInt(LitInt), Self_(Token![self]) }
        let segments: Vec<Segment> = {
            impl Parse for Segment {
                fn parse (input: ParseStream<'_>)
                  -> Result<Self>
                {
                    let lookahead = input.lookahead1();
                    if lookahead.peek(Ident) {
                        input.parse().map(Segment::Ident)
                    } else if lookahead.peek(LitInt) {
                        input.parse().map(Segment::LitInt)
                    } else if input.peek(Token![self]){
                        input.parse().map(Segment::Self_)
                    } else {
                        Err(lookahead.error())
                    }
                }
            }
            match ::syn::parse::Parser::parse_str(
                Punctuated::<Segment, Token![.]>::parse_separated_nonempty,
                arg,
            )
            {
                | Ok(segments) => segments.into_iter().collect(),
                | Err(err) => return err.to_compile_error().into(),
            }
        };
        match segments.len() {
            | 0 => unreachable!("`parse_separated_nonempty` returned empty"),
            | 1 => {
                out_format_literal.push_str(arg);
                match {segments}.pop().unwrap() {
                    | Segment::LitInt(_) => {
                        // found something like `{0}`, let `format_args!`
                        // handle it.
                        continue;
                    },
                    | Segment::Ident(ident) => {
                        // if `ident = ...` is not yet among the extra args
                        if  named_args
                                .iter()
                                .all(|(it, _)| *it != ident)
                        {
                            named_args.push((
                                ident.clone(),
                                parse_quote!(#ident), // Expr
                            ));
                        }
                    },
                    | Segment::Self_(ident) => {
                        // if `ident = ...` is not yet among the extra args
                        continue;
                    },
                }
            },
            | _ => {
                ::std::fmt::Write::write_fmt(
                    out_format_literal,
                    format_args!("{}", positional_args.len()),
                ).expect("`usize` or `char` Display impl cannot panic");
                let segments: Punctuated<TokenStream2, Token![.]> =
                    segments
                        .into_iter()
                        .map(|it| match it {
                            | Segment::Ident(ident) => {
                                ident.into_token_stream()
                            },
                            | Segment::LitInt(literal) => {
                                literal.into_token_stream()
                            },
                            | Segment::Self_(self_) => {
                                self_.into_token_stream()
                            },
                        })
                        .collect()
                ;
                positional_args.push(parse_quote! {
                    #segments
                })
            }
        }
    }

    let named_args =
        named_args
            .into_iter()
            .map(|(ident, expr)| quote! {
                #ident = #expr
            })
    ;
    format_literal = LitStr::new(
        out_format_literal,
        format_literal.span(),
    );
    TokenStream::from(debug_output!(quote! {
        format_args!(
            #format_literal
            #(, #positional_args)*
            #(, #named_args)*
        )
    }))
}

fn defer<'a, T : 'a, Drop : 'a> (x: T, drop: Drop)
  -> impl ::core::ops::DerefMut<Target = T> + 'a
where
    Drop : FnOnce(T),
{
    use ::core::mem::ManuallyDrop;
    struct Ret<T, Drop> (
        ManuallyDrop<T>,
        ManuallyDrop<Drop>,
    )
    where
        Drop : FnOnce(T),
    ;
    impl<T, Drop> ::core::ops::Drop for Ret<T, Drop>
    where
        Drop : FnOnce(T),
    {
        fn drop (self: &'_ mut Self)
        {
            use ::core::ptr;
            unsafe {
                // # Safety
                //
                //   - This is the canonical example of using `ManuallyDrop`.
                let value = ManuallyDrop::into_inner(ptr::read(&mut self.0));
                let drop = ManuallyDrop::into_inner(ptr::read(&mut self.1));
                drop(value);
            }
        }
    }
    impl<T, Drop> ::core::ops::Deref for Ret<T, Drop>
    where
        Drop : FnOnce(T),
    {
        type Target = T;
        #[inline]
        fn deref (self: &'_ Self)
          -> &'_ Self::Target
        {
            &self.0
        }
    }
    impl<T, Drop> ::core::ops::DerefMut for Ret<T, Drop>
    where
        Drop : FnOnce(T),
    {
        #[inline]
        fn deref_mut (self: &'_ mut Self)
          -> &'_ mut Self::Target
        {
            &mut self.0
        }
    }
    Ret(ManuallyDrop::new(x), ManuallyDrop::new(drop))
}