impl_table 0.1.3

Generate table binding and utils for rust-postgres and rusqlite.
Documentation
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
use crate::Argument;
use proc_macro2::{Punct, Spacing, Span, TokenStream, TokenTree};

#[derive(Debug)]
enum State {
    Start,
    Ident(proc_macro2::Ident),
    Assign(proc_macro2::Ident, proc_macro2::Punct),
    Done,
    Next(proc_macro2::Punct),
    End,

    Error(ErrorStruct),
}

#[derive(Debug)]
pub(crate) struct ErrorStruct(proc_macro2::Span, &'static str);

impl From<ErrorStruct> for syn::Error {
    fn from(e: ErrorStruct) -> syn::Error {
        let ErrorStruct(span, message) = e;
        syn::Error::new(span, message.to_string())
    }
}

// The rust compile does not accept ';' as a procedural macro argument.
// Assuming it will not appear in the input TokenStream.
const EOF: char = ';';

macro_rules! build_error {
    ($p:ident, $($body:tt)*) => {
        State::Error(ErrorStruct($p.span(), $($body)*))
    }
}

fn state_machine_transfer(tt: TokenTree, state: State, ret: &mut Vec<Argument>) -> State {
    match state {
        State::Start => match tt {
            TokenTree::Ident(i) => State::Ident(i),
            TokenTree::Punct(p) => {
                if p.as_char() == EOF {
                    State::End
                } else {
                    build_error!(p, "Expecting an identifier.")
                }
            }
            _ => build_error!(tt, "Expecting an identifier or empty list."),
        },
        State::Ident(i) => match tt {
            TokenTree::Punct(p) => match p.as_char() {
                '=' => State::Assign(i, p),
                ',' => {
                    ret.push(Argument::Switch {
                        name: i.to_string(),
                    });
                    State::Next(p)
                }
                EOF => {
                    ret.push(Argument::Switch {
                        name: i.to_string(),
                    });
                    State::End
                }
                _ => build_error!(p, "Expecting '=', ',', or end of argument list."),
            },
            TokenTree::Group(g) => match parse_arguments(g.stream(), g.span()) {
                Ok(args) => {
                    ret.push(Argument::Function {
                        name: i.to_string(),
                        args: args,
                    });
                    State::Done
                }
                Err(e) => State::Error(e),
            },
            _ => build_error!(tt, "Expecting '=', ',', or end of argument list."),
        },
        State::Assign(i, _p) => match tt {
            TokenTree::Ident(to_i) => {
                ret.push(Argument::Flag {
                    key: i.to_string(),
                    value: to_i.to_string(),
                });
                State::Done
            }
            TokenTree::Literal(to_i) => {
                let string_value = to_i.to_string();
                ret.push(Argument::Flag {
                    key: i.to_string(),
                    // Remove the quotes from string literal.
                    value: string_value[1..string_value.len() - 1].into(),
                });
                State::Done
            }
            _ => build_error!(tt, "Expecting an identifier or a string literal."),
        },
        State::Done => {
            if let TokenTree::Punct(p) = tt {
                match p.as_char() {
                    ',' => State::Next(p),
                    EOF => State::End,
                    _ => build_error!(p, "Expecting ',' or end of argument list."),
                }
            } else {
                build_error!(tt, "Expecting ',' or end of argument list.")
            }
        }
        State::Next(_p) => {
            if let TokenTree::Ident(i) = tt {
                State::Ident(i)
            } else {
                build_error!(tt, "Expecting an identifier.")
            }
        }
        State::Error(_) => state,
        State::End => panic!("Reached end state but still receives more token: {}", tt),
    }
}

// Parse the following argument into a structured form.
// `key = string_value, key = ident, invoke_func(flag1, flag2)`
pub(crate) fn parse_arguments(
    attr: TokenStream,
    outer_span: Span,
) -> Result<Vec<Argument>, ErrorStruct> {
    let mut ret = vec![];
    let mut state = State::Start;
    for tt in attr.into_iter() {
        state = state_machine_transfer(tt, state, &mut ret);
    }

    // Push end of line into the machine to get the error message.
    let mut eof = TokenTree::Punct(Punct::new(EOF, Spacing::Alone));
    // TODO: using the outer span yields less than ideal error message. The last element ')' of the
    // outer span is the right thing to point to.
    eof.set_span(outer_span);
    state = state_machine_transfer(eof, state, &mut ret);

    match state {
        State::Error(e) => return Err(e),
        State::End => (),
        _ => panic!("Reached non-end state {:?}", state),
    }

    return Ok(ret);
}

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

    macro_rules! parse_quote {
        ($($body:tt)*) => ({
            let expr = quote! {
                $($body)*
            };
            parse_arguments(expr.into(), Span::call_site())
                .expect(concat!("Unexpected error when parsing {", stringify!($($body)*), "}"))

        })
    }

    macro_rules! parse_quote_error {
        ($($body:tt)*) => ({
            let expr = quote! {
                $($body)*
            };
            parse_arguments(expr.into(), Span::call_site()).err()
                .expect(concat!("Expecting error when parsing {", stringify!($($body)*), "}"))
        })
    }

    macro_rules! assert_parse_quote_error_msg_eq {
        ($msg:expr, $($body:tt)*) => ({
            let ErrorStruct(_,message) = parse_quote_error!($($body)*);
            assert_eq!($msg, message);
        })
    }

    #[test]
    fn test_empty() {
        let args = parse_quote! {};

        assert_eq!(0, args.len());
    }

    #[test]
    fn test_switch() {
        let args = parse_quote! { TurnThisOn };

        assert_eq!(1, args.len());

        assert_eq!(
            Argument::Switch {
                name: "TurnThisOn".into()
            },
            args[0]
        );
    }

    #[test]
    fn test_flag() {
        let args = parse_quote! {
            SetValue = tts, SetStr = "123"
        };

        assert_eq!(2, args.len());

        assert_eq!(
            Argument::Flag {
                key: "SetValue".into(),
                value: "tts".into()
            },
            args[0]
        );

        assert_eq!(
            Argument::Flag {
                key: "SetStr".into(),
                value: "123".into()
            },
            args[1]
        );
    }

    #[test]
    fn test_function() {
        let args = parse_quote! { CallThisFunc() };

        assert_eq!(1, args.len());
        assert_eq!(
            Argument::Function {
                name: "CallThisFunc".into(),
                args: vec![]
            },
            args[0]
        );
    }

    #[test]
    fn test_function_args() {
        let args = parse_quote! { CallThisFunc(DoX, Doy) };

        assert_eq!(1, args.len());
        assert_eq!(
            Argument::Function {
                name: "CallThisFunc".into(),
                args: vec![
                    Argument::Switch { name: "DoX".into() },
                    Argument::Switch { name: "Doy".into() }
                ]
            },
            args[0]
        );
    }

    #[test]
    fn test_nested_functions() {
        let args = parse_quote! { CallThisFunc(DoX, CallAnotherFunc(Doy), DoZ) };

        assert_eq!(1, args.len());
        assert_eq!(
            Argument::Function {
                name: "CallThisFunc".into(),
                args: vec![
                    Argument::Switch { name: "DoX".into() },
                    Argument::Function {
                        name: "CallAnotherFunc".into(),
                        args: vec![Argument::Switch { name: "Doy".into() }]
                    },
                    Argument::Switch { name: "DoZ".into() }
                ]
            },
            args[0]
        );
    }

    #[test]
    fn test_error_in_the_middle() {
        let ErrorStruct(_, message) = parse_quote_error! { A, , A };
        assert_eq!("Expecting an identifier.", message);
    }

    #[test]
    fn test_error_at_the_end() {
        let ErrorStruct(_, message) = parse_quote_error! { A, };
        assert_eq!("Expecting an identifier.", message);
    }

    #[test]
    fn test_all() {
        let args = parse_quote! {
            Switch0,
            Switch1,
            CallThisFunc(Switch8, Flag = "f", NestedFunc(PP)),
            AnotherFlag = VV,
            OneMore = WW,
            Switch7,
            PlusOne = "ZZZ",
            CallAnotherFunc(DD=AAA),
            Join(),
            Switch9
        };

        assert_eq!(
            vec![
                Argument::Switch {
                    name: "Switch0".into()
                },
                Argument::Switch {
                    name: "Switch1".into()
                },
                Argument::Function {
                    name: "CallThisFunc".into(),
                    args: vec![
                        Argument::Switch {
                            name: "Switch8".into()
                        },
                        Argument::Flag {
                            key: "Flag".into(),
                            value: "f".into()
                        },
                        Argument::Function {
                            name: "NestedFunc".into(),
                            args: vec![Argument::Switch { name: "PP".into() }]
                        }
                    ]
                },
                Argument::Flag {
                    key: "AnotherFlag".into(),
                    value: "VV".into()
                },
                Argument::Flag {
                    key: "OneMore".into(),
                    value: "WW".into()
                },
                Argument::Switch {
                    name: "Switch7".into()
                },
                Argument::Flag {
                    key: "PlusOne".into(),
                    value: "ZZZ".into()
                },
                Argument::Function {
                    name: "CallAnotherFunc".into(),
                    args: vec![Argument::Flag {
                        key: "DD".into(),
                        value: "AAA".into()
                    }]
                },
                Argument::Function {
                    name: "Join".into(),
                    args: vec![]
                },
                Argument::Switch {
                    name: "Switch9".into()
                }
            ],
            args
        );
    }

    #[test]
    fn test_state_machine() {
        // start: ident, EOF, other punct, other
        parse_quote! { A };
        parse_quote! {};
        assert_parse_quote_error_msg_eq! {"Expecting an identifier.", : };
        assert_parse_quote_error_msg_eq! {"Expecting an identifier or empty list.", () };

        // ident: '=', ',', EOF, other punct, group, group error, other
        parse_quote! { A = a };
        parse_quote! { A, A };
        parse_quote! { A };
        assert_parse_quote_error_msg_eq! {"Expecting '=', ',', or end of argument list.", A : };
        parse_quote! { A () };
        assert_parse_quote_error_msg_eq! {"Expecting an identifier.", A (:) };
        assert_parse_quote_error_msg_eq! {"Expecting an identifier.", A ( B ( C, :) ) };
        assert_parse_quote_error_msg_eq! {"Expecting '=', ',', or end of argument list.", A  A };

        // assign: ident, literal, other
        parse_quote! { A = a };
        parse_quote! { A = "a" };
        assert_parse_quote_error_msg_eq! {"Expecting an identifier or a string literal.", A = () };

        // done: ',', EOF, other punct, other
        parse_quote! { A = A, A };
        parse_quote! { A = A };
        assert_parse_quote_error_msg_eq! {"Expecting ',' or end of argument list.", A = A: };
        assert_parse_quote_error_msg_eq! {"Expecting ',' or end of argument list.", A = a () };

        // next: ident, other
        parse_quote! { A = A, A };
        assert_parse_quote_error_msg_eq! {"Expecting an identifier.", A = A, () };

        // error: ignores
        assert_parse_quote_error_msg_eq! {"Expecting an identifier.", A, (), A, A, A};
    }

    #[test]
    #[should_panic]
    fn test_end_end() {
        // end: fails,
        parse_quote_error! { ; A };
    }
}