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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
extern crate proc_macro;
extern crate regex;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate quote;
use proc_macro2::Span;
use proc_macro_hack::proc_macro_hack;
use regex::Regex;
use syn::{Token, Error};

fn consume_expr(s: &str) -> (&str, String) {
    lazy_static! {
        // bad hack regex to look for string/character literals
        // we don't want to count braces contained within them
        static ref LITERAL: Regex = Regex::new(
            concat!(r#"^('(?:\\[\s\S]+?|\\'|[^\\'])'"#,
                    r##"|"(?:\\[\s\S]|[^\\])+?")"##)).unwrap();
        // have to handle raw strings separately due to no backrefs
        static ref RAW_STRING_START: Regex = Regex::new(
            r##"^r(#*)""##).unwrap();
    }

    let mut s = s;
    let mut expr = String::new();
    let mut brace_count = 1;
    while let Some(c) = s.chars().next() {
        match c {
            '{' => {
                brace_count += 1;
                s = &s[1..];
                expr.push('{');
            }
            '}' => {
                brace_count -= 1;
                if brace_count == 0 {
                    return (s, expr);
                } else {
                    expr.push('}');
                    s = &s[1..];
                }
            }
            _ => {
                let lit_match = LITERAL.find(s);
                match lit_match {
                    Some(m) => {
                        s = &s[m.end()..];
                        expr.push_str(m.as_str());
                        // TODO this feels off
                        // should we just nest the second match?
                        continue;
                    }
                    None => (),
                }
                let raw_caps = RAW_STRING_START.captures(s);
                match raw_caps {
                    // lazy hack to deal with the lack of backreferences
                    // generate the tail end of the regex
                    Some(c) => {
                        let m = c.get(0).unwrap();
                        s = &s[m.end()..];
                        expr.push_str(m.as_str());

                        let cap = c.get(1).unwrap();
                        let hash_count = cap.end() - cap.start();
                        let end_r =
                            Regex::new(&format!(r##"^[\s\S]+?"#{{{}}}"##, hash_count)).unwrap();
                        let em = end_r.find(s).expect("unclosed internal raw string");

                        expr.push_str(em.as_str());
                        s = &s[em.end()..];
                    }
                    None => {
                        expr.push(c);
                        s = &s[c.len_utf8()..];
                    }
                }
            }
        }
    }

    panic!("unbalanced {");
}

macro_rules! def_ifmt_macro {
    ($name:ident, $to_wrap:ident) => {
        #[proc_macro_hack]
        pub fn $name(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
            use syn::parse_macro_input;
            let FormatContents{fmt, args} = parse_macro_input!(tokens as FormatContents);
            (quote! {
                ::std::$to_wrap!(#fmt, #(#args),*)
            }).into()
        }
    }
}

def_ifmt_macro!(iformat, format);

def_ifmt_macro!(iprint, print);

def_ifmt_macro!(iprintln, println);

def_ifmt_macro!(ieprint, eprint);

def_ifmt_macro!(ieprintln, eprintln);

def_ifmt_macro!(iformat_args, format_args);

def_ifmt_macro!(ipanic, panic);

struct FormatSpec {
    spec: String,
}

fn parse_format_type(id: &str, span: Span, input: syn::parse::ParseStream) -> syn::parse::Result<String> {
    let mut out = String::new();
    if id == "x" || id == "X" {
        out.push_str(&id);
        if input.peek(Token![?]) {
            input.parse::<Token![?]>()?;
            out.push('?');
        }
    } else if id == "o" || id == "p" || id == "b" || id == "e" || id == "E" {
        out.push_str(&id);
    } else if id == "s"  {
        out.push('e');
    } else if id == "S" {
        out.push('E');
    } else {
        return Err(Error::new(span, format!("{} is not a valid format type", id)));
    }
    Ok(out)
}

fn parse_precision_type(input: syn::parse::ParseStream) -> syn::parse::Result<String> {
    // ['.' precision][type]
    // TODO make it so these can be identifiers/exprs as well? maybe in parens?
    let mut spec = String::new();

    let span = input.cursor().span();

    // ['.']
    if input.peek(Token![.]) {
        input.parse::<Token![.]>()?;
        spec.push('.');
        // precision
        let lit = input.parse::<syn::LitInt>()?;
        let lit_str = lit.to_string();
        if lit.suffix() != "" {
            spec.push_str(&lit_str[..lit_str.len() - lit.suffix().len()]);
            // [type]
            spec.push_str(&parse_format_type(&lit.suffix(), span, input)?);
        } else {
            spec.push_str(&lit_str);
        }
    }

    // [type]
    if input.peek(Token![?]) {
        input.parse::<Token![?]>()?;
        spec.push('?');
    // [type]
    } else if input.peek(syn::Ident) {
        let id = input.parse::<syn::Ident>()?.to_string();
        spec.push_str(&parse_format_type(&id, span, input)?);
    }

    Ok(spec)
}


impl syn::parse::Parse for FormatSpec {
    fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        /*
        format_spec := [[fill]align][sign]['#']['0'][width]['.' precision][type]
        fill := character
        align := '<' | '^' | '>'
        sign := '+' | '-'
        width := count
        precision := count | '*'
        type := identifier | '?' | ''
        count := parameter | integer
        parameter := argument '$'
        */
        input.parse::<Token![;]>()?;
        let mut spec = String::new();
        // [[fill]align]
        if input.peek(syn::LitChar) {
            let pad = input.parse::<syn::LitChar>().unwrap();
            spec.push(pad.value());
            let lookahead = input.lookahead1();
            if lookahead.peek(Token![<]) {
                input.parse::<Token![<]>()?;
                spec.push('<');
            } else if lookahead.peek(Token![>]) {
                input.parse::<Token![>]>()?;
                spec.push('>');
            } else if lookahead.peek(Token![^]) {
                input.parse::<Token![^]>()?;
                spec.push('^');
            } else {
                return Err(lookahead.error());
            }
        } else if input.peek(Token![<]) {
            input.parse::<Token![<]>()?;
            spec.push('<');
        } else if input.peek(Token![>]) {
            input.parse::<Token![>]>()?;
            spec.push('>');
        } else if input.peek(Token![^]) {
            input.parse::<Token![^]>()?;
            spec.push('^');
        }

        // [sign]
        if input.peek(Token![+]) {
            input.parse::<Token![+]>()?;
            spec.push('+');
        } else if input.peek(Token![-]) {
            input.parse::<Token![-]>()?;
            spec.push('-');
        }

        // ['#']
        if input.peek(Token![#]) {
            input.parse::<Token![#]>()?;
            spec.push('#');
        }

        // TODO width as an expression
        //  will require some reworking - has to be passed by name
        //  FormatSpec either has to generate an incomplete spec which is templated later
        //  or it needs information on which number expression it's on
        // ['0'][width]['.' precision][type]
        if input.peek(syn::LitFloat) {
            // ['0'][width]['.' precision][type]
            let span = input.cursor().span();
            let lit = input.parse::<syn::LitFloat>()?;
            let lit_str = lit.to_string();
            if lit.suffix() != "" {
                // ['0'][width]['.' precision]
                spec.push_str(&lit_str[..lit_str.len()-lit.suffix().len()]);
                // [type]
                spec.push_str(&parse_format_type(&lit.suffix(), span, input)?);
            } else {
                // ['0'][width]['.' precision]
                spec.push_str(&lit_str);
                // [type]
                if input.peek(syn::Ident) {
                    let id = input.parse::<syn::Ident>()?.to_string();
                    spec.push_str(&parse_format_type(&id, span, input)?);
                }
            }
        } else if input.peek(syn::LitInt) {
            // ['0'][width][type]
            let span = input.cursor().span();
            let lit = input.parse::<syn::LitInt>()?;
            let lit_str = lit.to_string();
            if lit.suffix() != "" {
                spec.push_str(&lit_str[..lit_str.len()-lit.suffix().len()]);
                // [type]
                spec.push_str(&parse_format_type(&lit.suffix(), span, input)?);
            } else {
                // ['.' precision][type]
                spec.push_str(&lit_str);
                spec.push_str(&parse_precision_type(input)?);
            }
        } else {
            spec.push_str(&parse_precision_type(input)?);
        }

        Ok(FormatSpec { spec: spec })
    }
}

struct FormatContents {
    fmt: String,
    args: Vec<syn::Expr>,
}

impl FormatContents {
    fn parse_inlit(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        lazy_static! {
            static ref SPEC: Regex =
            Regex::new(r":([\s\S]?[<^>])?([\+\-])?(#)?(0)?(\d+|\*)?(\.\d+)?(\?|\w+)?$").unwrap();
        }
        let format_str = input.parse::<syn::LitStr>()?.value();

        let mut format_lit = String::from("");
        let mut exprs = vec![];
        let mut s: &str = &format_str;
        while let Some(c) = s.chars().next() {
            match c {
                '{' => {
                    s = &s[1..];
                    match s.chars().next() {
                        Some('{') => format_lit.push_str("{{"),
                        _ => {
                            let (new_s, mut expr) = consume_expr(s);
                            s = new_s;
                            let spec_match = SPEC.find(&expr);
                            match spec_match {
                                Some(m) => {
                                    format_lit.push('{');
                                    format_lit.push_str(m.as_str());
                                    format_lit.push('}');
                                    let si = m.start();

                                    expr.truncate(si);
                                }
                                None => {
                                    format_lit.push_str("{}");
                                }
                            }

                            exprs.push(syn::parse_str::<syn::Expr>(&expr)?);
                        }
                    }
                }
                '}' => {
                    s = &s[1..];
                    if s.chars().next() == Some('}') {
                        format_lit.push_str("}}");
                    } else {
                        panic!("unmatched }");
                    }
                }
                _ => format_lit.push(c),
            }
            s = &s[c.len_utf8()..];
        }

        Ok(FormatContents{fmt: format_lit, args: exprs})
    }

    fn parse_outlit(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        let mut expect_expr = true; // state machine
        let mut fmt = String::new();
        let mut args = vec![];

        while !input.is_empty() {
            let lookahead = input.lookahead1();
            if lookahead.peek(syn::LitStr) {
                let ls = input.parse::<syn::LitStr>().unwrap();
                fmt += &ls.value().replace("{", "{{").replace("}", "}}");
                expect_expr = true;
            } else if expect_expr {
                // Bug in proc_macro_hack(fake_call_site): iformat!("x:" 2 + );'s
                // "unexpected end of input" error span points at the first token in the macro
                // invocation rather than the end.
                // not going to try to work around - probably not a common mistake and
                // if proc_macro_hack becomes a pass-through as mentioned by dtolnay
                // (or, barring that, if I remove it as a dependency) the issue goes away
                let expr = input.parse::<syn::Expr>()?;
                args.push(expr);
                fmt.push_str("{");
                if input.peek(Token![;]) {
                    let spec = &input.parse::<FormatSpec>()?.spec;
                    if !spec.is_empty() {
                        fmt.push_str(":");
                        fmt.push_str(spec);
                    }
                }
                fmt.push('}');
                expect_expr = false;
            } else {
                return Err(lookahead.error());
            }
        }
        Ok(FormatContents{fmt: fmt, args: args})
    }
}

impl syn::parse::Parse for FormatContents {
    fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        // note: eventually one of these branches should go away
        let forked = input.fork();
        if forked.peek(syn::LitStr) && {forked.parse::<syn::LitStr>()?; forked.is_empty()} {
            FormatContents::parse_inlit(input)
        } else {
            FormatContents::parse_outlit(input)
        }
    }
}

struct WriteFormat {
    buf: syn::Expr,
    fmt_contents: FormatContents
}

impl syn::parse::Parse for WriteFormat {
    fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
        Ok(WriteFormat {
            buf: input.parse::<syn::Expr>()?,
            fmt_contents:  if !input.is_empty() {
                    input.parse::<Token![,]>()?;
                    input.parse::<FormatContents>()?
                } else {
                    FormatContents{fmt: "".to_string(), args: vec![]}
                }
        })
    }
}

#[proc_macro_hack]
pub fn iwrite(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    use syn::parse_macro_input;
    let WriteFormat{buf, fmt_contents: FormatContents{fmt, args}} = parse_macro_input!(tokens as WriteFormat);
    (quote! {
        ::std::write!(#buf, #fmt, #(#args),*)
    }).into()
}

#[proc_macro_hack]
pub fn iwriteln(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream {
    use syn::parse_macro_input;
    let WriteFormat{buf, fmt_contents: FormatContents{fmt, args}} = parse_macro_input!(tokens as WriteFormat);
    (quote! {
        ::std::writeln!(#buf, #fmt, #(#args),*)
    }).into()
}