comlexr_macro 1.5.0

Dynamically build Command objects with conditional expressions
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use quote::{quote, ToTokens};
use syn::{
    braced, bracketed,
    parse::{discouraged::Speculative, Parse},
    punctuated::Punctuated,
    token, Token,
};

use crate::macros::enum_to_tokens;

pub struct Command {
    cd: CurrentDir,
    env_vars: EnvVars,
    program: Value,
    args: Option<Punctuated<LogicArg, Token![,]>>,
}

impl Parse for Command {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let cd = input.parse()?;
        let env_vars = input.parse()?;
        let program = input.parse()?;

        if input.is_empty() {
            Ok(Self {
                cd,
                env_vars,
                program,
                args: None,
            })
        } else {
            _ = input.parse::<Token![,]>()?;
            Ok(Self {
                cd,
                env_vars,
                program,
                args: Some(Punctuated::parse_terminated(input)?),
            })
        }
    }
}

impl ToTokens for Command {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            cd,
            env_vars,
            program,
            args,
        } = self;
        let program = quote! { ::std::process::Command::new(#program) };
        let args = args
            .as_ref()
            .map(Punctuated::iter)
            .map_or_else(Vec::new, Iterator::collect);

        tokens.extend(quote! {
            {
                let mut _c = #program;
                #cd
                #env_vars
                #(#args)*
                _c
            }
        });
    }
}

pub struct CommandMut {
    cd: CurrentDir,
    env_vars: EnvVars,
    cmd: ValueNoLit,
    args: Option<Punctuated<LogicArg, Token![,]>>,
}

impl Parse for CommandMut {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let cd = input.parse()?;
        let env_vars = input.parse()?;
        let cmd = input.parse()?;

        if input.is_empty() {
            Ok(Self {
                cd,
                env_vars,
                cmd,
                args: None,
            })
        } else {
            _ = input.parse::<Token![,]>()?;
            Ok(Self {
                cd,
                env_vars,
                cmd,
                args: Some(Punctuated::parse_terminated(input)?),
            })
        }
    }
}

impl ToTokens for CommandMut {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            cd,
            env_vars,
            cmd,
            args,
        } = self;
        let args = args
            .as_ref()
            .map(Punctuated::iter)
            .map_or_else(Vec::new, Iterator::collect);

        tokens.extend(quote! {
            {
                let _c: &mut ::std::process::Command = #cmd;
                #cd
                #env_vars
                #(#args)*
                _c
            }
        });
    }
}

enum LogicArg {
    Expr(SingleArg),
    ForIter(ForIter),
    ForIn(ForIn),
    IfLet(IfLet),
    If(If),
    Match(Match),
    Closure(Closure),
}

impl Parse for LogicArg {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        if input.peek(Token![for]) {
            let pat_fork = input.fork();
            _ = pat_fork.parse::<Token![for]>()?;

            if pat_fork.call(syn::Pat::parse_single).is_ok() && pat_fork.peek(Token![in]) {
                input.parse().map(Self::ForIn)
            } else {
                input.parse().map(Self::ForIter)
            }
        } else if input.peek(Token![if]) {
            if input.peek2(Token![let]) {
                input.parse().map(Self::IfLet)
            } else {
                input.parse().map(Self::If)
            }
        } else if input.peek(Token![match]) {
            input.parse().map(Self::Match)
        } else if input.peek(Token![||]) {
            input.parse().map(Self::Closure)
        } else {
            input.parse().map(Self::Expr)
        }
    }
}

enum_to_tokens! {LogicArg: Expr, ForIter, ForIn, IfLet, If, Match, Closure}

struct ForIter {
    expr: Value,
}

impl Parse for ForIter {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        _ = input.parse::<Token![for]>()?;
        let expr = input.parse()?;

        Ok(Self { expr })
    }
}

impl ToTokens for ForIter {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let expr = &self.expr;

        tokens.extend(quote! {
            for _a in #expr {
                _c.arg(_a);
            }
        });
    }
}

struct ForIn {
    pattern: syn::Pat,
    iter: Value,
    args: Arguments,
}

impl Parse for ForIn {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        _ = input.parse::<Token![for]>()?;
        let pattern = input.call(syn::Pat::parse_single)?;
        _ = input.parse::<Token![in]>()?;
        let iter = input.parse()?;
        _ = input.parse::<Token![=>]>()?;
        let args = input.parse()?;

        Ok(Self {
            pattern,
            iter,
            args,
        })
    }
}

impl ToTokens for ForIn {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            pattern,
            iter,
            args,
        } = self;

        tokens.extend(quote! {
            for #pattern in #iter {
                #args
            }
        });
    }
}

struct IfLet {
    pattern: syn::Pat,
    expr: Value,
    args: Arguments,
}

impl Parse for IfLet {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        _ = input.parse::<Token![if]>()?;
        _ = input.parse::<Token![let]>()?;
        let pattern = input.call(syn::Pat::parse_single)?;
        _ = input.parse::<Token![=]>()?;
        let expr = input.parse()?;
        _ = input.parse::<Token![=>]>()?;
        let args = input.parse()?;

        Ok(Self {
            pattern,
            expr,
            args,
        })
    }
}

impl ToTokens for IfLet {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            pattern,
            expr,
            args,
        } = &self;

        tokens.extend(quote! {
            if let #pattern = #expr {
                #args
            }
        });
    }
}

struct If {
    expr: Value,
    args: Arguments,
}

impl Parse for If {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        _ = input.parse::<Token![if]>()?;
        let expr = input.parse()?;
        _ = input.parse::<Token![=>]>()?;
        let args = input.parse()?;

        Ok(Self { expr, args })
    }
}

impl ToTokens for If {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self { expr, args } = self;

        tokens.extend(quote! {
            if #expr {
                #args
            }
        });
    }
}

struct Match {
    expr: Value,
    match_arms: Punctuated<MatchArm, Token![,]>,
}

impl Parse for Match {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        _ = input.parse::<Token![match]>()?;
        let expr = input.parse()?;
        let arms;
        braced!(arms in input);
        let match_arms = Punctuated::parse_terminated(&arms)?;

        Ok(Self { expr, match_arms })
    }
}

impl ToTokens for Match {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self { expr, match_arms } = self;
        let match_arms = match_arms.iter();

        tokens.extend(quote! {
            match #expr {
                #(#match_arms)*
            }
        });
    }
}

struct MatchArm {
    pattern: syn::Pat,
    if_expr: Option<Value>,
    args: Arguments,
}

impl Parse for MatchArm {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let pattern = input.call(syn::Pat::parse_multi)?;
        let if_expr = if input.peek(Token![if]) {
            _ = input.parse::<Token![if]>()?;
            Some(input.parse()?)
        } else {
            None
        };
        _ = input.parse::<Token![=>]>()?;
        let args = input.parse()?;

        Ok(Self {
            pattern,
            if_expr,
            args,
        })
    }
}

impl ToTokens for MatchArm {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            pattern,
            if_expr,
            args,
        } = self;

        tokens.extend(if_expr.as_ref().map_or_else(
            || {
                quote! {
                    #pattern => {
                        #args
                    }
                }
            },
            |if_expr| {
                quote! {
                    #pattern if #if_expr => {
                        #args
                    }
                }
            },
        ));
    }
}

struct Closure(syn::Expr);

impl Parse for Closure {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        _ = input.parse::<Token![||]>()?;

        input.parse().map(Self)
    }
}

impl ToTokens for Closure {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self(block) = self;

        tokens.extend(quote! {
            let _fn = || #block;
            for _a in _fn() {
                _c.arg(_a);
            }
        });
    }
}

enum Arguments {
    Single(SingleArg),
    Multi(MultiArg),
}

impl Parse for Arguments {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        if input.peek(token::Bracket) {
            input.parse().map(Self::Multi)
        } else {
            input.parse().map(Self::Single)
        }
    }
}

enum_to_tokens! {Arguments: Single, Multi}

struct MultiArg(Punctuated<SingleArg, Token![,]>);

impl Parse for MultiArg {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let args;
        bracketed!(args in input);

        Punctuated::parse_terminated(&args).map(Self)
    }
}

impl ToTokens for MultiArg {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let args = self.0.iter().collect::<Vec<_>>();

        tokens.extend(quote! { #(#args)* });
    }
}

struct SingleArg(Value);

impl Parse for SingleArg {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        input.parse().map(Self)
    }
}

impl ToTokens for SingleArg {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let arg = &self.0;
        tokens.extend(quote! {
            _c.arg(#arg);
        });
    }
}

struct EnvVars(Option<Punctuated<EnvVar, Token![,]>>);

impl Parse for EnvVars {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let fork = input.fork();
        let ident = fork.cursor().ident();

        match ident {
            Some((ident, _)) if ident == "env" => {
                _ = fork.parse::<syn::Ident>()?;
                let envs;
                braced!(envs in fork);
                Punctuated::parse_terminated(&envs)
                    .and_then(|envs| {
                        _ = fork.parse::<Token![;]>()?;
                        input.advance_to(&fork);
                        Ok(Self(Some(envs)))
                    })
                    .or_else(|_| Ok(Self(None)))
            }
            _ => Ok(Self(None)),
        }
    }
}

impl ToTokens for EnvVars {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self(envs) = self;
        let envs = envs
            .as_ref()
            .map_or_else(Vec::new, |envs| envs.iter().collect());

        tokens.extend(quote! {
            #(#envs)*
        });
    }
}

struct EnvVar {
    key: Value,
    value: Value,
    conditional: bool,
}

impl Parse for EnvVar {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let key = input.parse()?;

        _ = input.parse::<Token![:]>()?;

        let conditional = if input.lookahead1().peek(Token![?]) {
            input.parse::<Token![?]>()?;
            true
        } else {
            false
        };

        let value = input.parse()?;

        Ok(Self {
            key,
            value,
            conditional,
        })
    }
}

impl ToTokens for EnvVar {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            key,
            value,
            conditional,
        } = self;

        if *conditional {
            tokens.extend(quote! {
                if ::std::env::var(#key).ok().is_none() {
                    _c.env(#key, #value);
                }
            });
        } else {
            tokens.extend(quote! { _c.env(#key, #value); });
        }
    }
}

struct CurrentDir(Option<Value>);

impl Parse for CurrentDir {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let fork = input.fork();
        let ident = fork.cursor().ident();

        match ident {
            Some((ident, _)) if ident == "cd" => {
                _ = fork.parse::<syn::Ident>();
                fork.parse()
                    .and_then(|value| {
                        _ = fork.parse::<Token![;]>()?;
                        input.advance_to(&fork);
                        Ok(Self(Some(value)))
                    })
                    .or_else(|_| Ok(Self(None)))
            }
            _ => Ok(Self(None)),
        }
    }
}

impl ToTokens for CurrentDir {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self(cd) = self;
        let cd = cd.iter();

        tokens.extend(quote! { #(_c.current_dir(#cd);)* });
    }
}

pub enum Value {
    Lit(syn::Lit),
    Ident(syn::Ident),
    Expr(syn::Expr),
}

impl Parse for Value {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let expr_fork = input.fork();
        expr_fork
            .parse()
            .map(|expr| {
                input.advance_to(&expr_fork);
                Self::Expr(expr)
            })
            .or_else(|_| {
                if input.peek(syn::Ident) {
                    input.parse().map(Self::Ident)
                } else if input.peek(syn::Lit) {
                    input.parse().map(Self::Lit)
                } else {
                    Err(syn::Error::new(
                        input.span(),
                        "Expected an expression, ident, or literal",
                    ))
                }
            })
    }
}

enum_to_tokens! {Value: Lit, Ident, Expr}

pub enum ValueNoLit {
    Ident(syn::Ident),
    Expr(syn::Expr),
}

impl Parse for ValueNoLit {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let expr_fork = input.fork();
        expr_fork
            .parse()
            .map(|expr| {
                input.advance_to(&expr_fork);
                Self::Expr(expr)
            })
            .or_else(|_| {
                if input.peek(syn::Ident) {
                    input.parse().map(Self::Ident)
                } else {
                    Err(syn::Error::new(
                        input.span(),
                        "Expected an expression, ident, or literal",
                    ))
                }
            })
    }
}

enum_to_tokens! {ValueNoLit: Ident, Expr}