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
#![feature(proc_macro_span)]
#![feature(proc_macro_diagnostic)]

use proc_macro2::{TokenStream, TokenTree, Punct, Group, Ident, Span};
use proc_macro::{Diagnostic, TokenStream as TokenStream1};
use boolinator::Boolinator;
use std::iter::Peekable;
use quote::{quote, quote_spanned, ToTokens};

#[proc_macro]
pub fn cmd(input: TokenStream1) -> TokenStream1 {
    let c = parse_cmd(TokenStream::from(input))
        .map_err(|e| e.emit())
        .expect("Error parsing commands");
    c.into_token_stream().into()
}

pub(crate) struct Cmd {
    commands: Vec<Command>,
}

struct Command {
    span: Span,
    terms: Vec<Expr>
}

pub(crate) fn parse_cmd(input: TokenStream) -> Result<Cmd, Diagnostic> {
    let mut tokens = input.into_iter().peekable();

    let mut commands: Vec<Command> = vec![];
    loop {
        let command = parse_command(&mut tokens)?;
        commands.push(command);

        match next_punct_is(&mut tokens, '|') {
            Ok(_) => { tokens.next(); },
            Err(NextError::EOF) => break,
            _ => return Err(
                span_remaining(&mut tokens)
                    .unwrap()
                    .error("expected EOF or | after end of command")
            ),
        }
    }

    Ok(Cmd{
        commands,
    })
}

fn parse_command<I>(input: &mut Peekable<I>) -> Result<Command, Diagnostic>
where I: Iterator<Item=TokenTree>
{
    let first_term = parse_term(input)?;
    let mut span = first_term.span();
    let mut terms = vec![first_term];

    loop {
        if next_punct_is(input, '|').is_ok() || is_eof(input)  {
            break;
        }

        let term = parse_term(input)?;
        let term_span = term.span();
        terms.push(term);

        span = span.join(term_span).ok_or(
            span.unwrap().error("internal error: could not join spans")
        )?;
    }

    Ok(Command{span, terms})
}

fn is_eof<I>(input: &mut Peekable<I>) -> bool
where I: Iterator<Item=TokenTree>
{
    input.peek().is_none()
}

enum Expr {
    Literal(String, Span),
    Expr(syn::Expr, Span),
}

impl Expr {
    pub fn span(&self) -> Span {
        match self {
            Expr::Literal(_, span) => *span,
            Expr::Expr(_, span) => *span,
        }
    }
}

impl ToTokens for Expr {
    fn to_tokens(&self, t: &mut TokenStream) {
        t.extend(match self {
            Expr::Literal(str, span) => quote_spanned!{*span=> #str },
            Expr::Expr(e, span) => quote_spanned! {*span=> format!("{}", #e) },
        })
    }
}

const ALONE_HASH_ERROR: &str = "'#' must not be alone. use '##' if you meant to pass a literal '#' symbol.
To pass two or more, only one extra '#' must be supplied
Example: `cmd!(echo ####a###)` is equiavalent to `$ echo ###a###`";

const UNEXPECTED_HASH_ERROR: &str = "'#' should be followed by an ident, an expression wrapped in any or (), {}, [] or another #
Example:
cmd!(echo ##) // echo #

let hello = \"hello world\";
cmd!(echo #hello) // echo \"hello world\"

let hello = \"hello\"
let world = \"world\";
cmd!(echo #{[hello, world].join(\" \")}) // echo \"hello world\"
";

fn parse_term<I>(input: &mut Peekable<I>) -> Result<Expr, Diagnostic>
where I: Iterator<Item=TokenTree>
{
    if next_punct_is(input, '#').is_ok() {
        let p = punct(input)
            .expect("internal error: peeked '#' but could not parse punct. please file a bug report");
        
        match input.peek() {
            None => return Err(p.span().unwrap().error(ALONE_HASH_ERROR)),
            Some(tt) => {
                let span = to_span(tt);

                if !joined(p.span(), span) {
                    return Err(p.span().unwrap().error(ALONE_HASH_ERROR));
                }

                match tt {
                    TokenTree::Punct(p) => 
                        match p.as_char() {
                            '#' => {}, // Do nothing. Valid term
                            _ => return Err(p.span().unwrap().error(UNEXPECTED_HASH_ERROR)),
                        },
                    TokenTree::Ident(_) => {
                        return parse_ident(ident(input)
                            .expect("internal error: peeked ident but could not parse ident. please file a bug report"))
                    }
                    TokenTree::Group(_) => {
                        return parse_expr(group(input)
                            .expect("internal error: peeked group but could not parse group. please file a bug report"))
                    }
                    _ => return Err(p.span().unwrap().error(UNEXPECTED_HASH_ERROR)),
                }
                
            }
        }
    }

    parse_literal(input).map(|(lit, span)| Expr::Literal(lit, span))  
}

fn parse_literal<I>(input: &mut Peekable<I>) -> Result<(String, Span), Diagnostic>
where I: Iterator<Item=TokenTree> {
    // We check for EOF in parse_command so this should not return None
    // Unless we're parsing a Group like `{}`, which will check the literal before
    // joining the span
    let first = match input.next() {
        None => return Ok((String::new(), Span::call_site())),
        Some(term) => term,
    };

    let (mut lit, mut span) = to_string_span(first)?;

    loop {
        let peek = match input.peek() {
            Some(tt) => tt,
            None => break,
        };

        if !joined(span, peek.span()) {
            break;
        }

        let (new_lit, new_span) = to_string_span(input.next()
            .expect("internal error: peeked token but could not parse token. please file a bug report"))?;

        lit = [lit, new_lit].join("");
        span = span.join(new_span)
            .ok_or(span.unwrap().error("internal error: could not join spans"))?;
    }

    Ok((lit, span))
}

fn to_string_span(tt: TokenTree) -> Result<(String, Span), Diagnostic> {
    match tt {
        TokenTree::Literal(l) => Ok((l.to_string(), l.span())),
        TokenTree::Ident(i) => Ok((i.to_string(), i.span())),
        TokenTree::Punct(p) => Ok((p.to_string(), p.span())),
        TokenTree::Group(g) => {
            let mut tokens = g.stream().into_iter().peekable();
            // TODO: refactor. This currently gets confused.
            // cmd!(echo {a | foo }) will run `echo {a}`
            let (lit, _) = parse_literal(&mut tokens)?;
            let lit = match g.delimiter() {
                proc_macro2::Delimiter::None => lit,
                proc_macro2::Delimiter::Parenthesis => format!("({})", lit),
                proc_macro2::Delimiter::Brace => format!("{{{}}}", lit),
                proc_macro2::Delimiter::Bracket => format!("<{}>", lit),
            };
            Ok((lit, g.span()))
        }
    }
}

fn parse_ident(i: Ident) -> Result<Expr, Diagnostic> {
    use syn::{PathSegment, PathArguments, ExprPath, Path, token::Colon2, punctuated::Punctuated};
    let mut p: Punctuated::<PathSegment, Colon2> = Punctuated::new();

    let span = i.span();

    p.push_value(PathSegment{
        ident: i,
        arguments: PathArguments::None,
    });

    Ok(Expr::Expr(
        syn::Expr::Path(
            ExprPath {
                attrs: vec![],
                qself: None,
                path: Path {
                    leading_colon: None,
                    segments: p,
                }
            }
        ),
        span,
    ))
}

fn parse_expr(g: Group) -> Result<Expr, Diagnostic> {
    let expr = syn::parse2::<syn::Expr>(g.stream())
        .map_err(|err| err.span().unwrap().error(err.to_string()))?;
    Ok(Expr::Expr(expr, g.span()))
}

#[derive(Debug)]
enum NextError {
    EOF,
    NotFound,
}

fn to_span(tt: &TokenTree) -> Span {
    match tt {
        TokenTree::Literal(l) => l.span(),
        TokenTree::Group(g) => g.span(),
        TokenTree::Punct(p) => p.span(),
        TokenTree::Ident(i) => i.span(),
    }
}

fn punct<I>(tokens: &mut I) -> Result<Punct, NextError>
where I: Iterator<Item=TokenTree>
{
    match tokens.next().ok_or(NextError::EOF)? {
        TokenTree::Punct(p) => Ok(p),
        _ => Err(NextError::NotFound)
    }
}

fn next_punct_is<I>(tokens: &mut Peekable<I>, is: char) -> Result<Span, NextError>
where I: Iterator<Item=TokenTree>
{
    match tokens.peek().ok_or(NextError::EOF)? {
        TokenTree::Punct(p) => (p.as_char() == is).as_result(p.span(), NextError::NotFound),
        _ => Err(NextError::NotFound),
    }
}

fn ident<I>(tokens: &mut I) -> Result<Ident, NextError>
where I: Iterator<Item=TokenTree>
{
    match tokens.next().ok_or(NextError::EOF)? {
        TokenTree::Ident(i) => Ok(i),
        _ => Err(NextError::NotFound),
    }
}

fn group<I>(tokens: &mut I) -> Result<Group, NextError>
where I: Iterator<Item=TokenTree>
{
    match tokens.next().ok_or(NextError::EOF)? {
        TokenTree::Group(g) => Ok(g),
        _ => Err(NextError::NotFound),
    }
}

fn span_remaining<I>(tokens: &mut I) -> Span 
where I: Iterator<Item=TokenTree>
{
    let mut spans = tokens
        .map(|x| x.span());

	let mut result = match spans.next() {
        Some(span) => span,
        None => Span::call_site(),
    };
    
	for span in spans {
		result = match result.join(span) {
			None => return Span::from(result),
			Some(span) => span,
		}
    }
    result
}
    
fn joined(lhs: Span, rhs: Span) -> bool {
    let a = lhs.end();
    let b = rhs.start();
    a == b
}

impl ToTokens for Cmd {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        if self.commands.len() == 0 {
            tokens.extend(quote!{
                Err(
                    std::io::Error::new(
                        std::io::ErrorKind::Other,
                        "no command input",
                    )
                )
            });
            return
        }

        let mut prev: Option<Ident> = None;
        let mut stdin = None;
        let cmds: Vec<TokenStream> = self.commands.iter().zip(0..).map(|(cmd, i)| {
            
            let ident = Ident::new(&format!("x{}", i), cmd.span);

            let command = cmd.to_tokens(ident.clone(), stdin.clone(), i == self.commands.len() - 1);

            prev = Some(ident);
            stdin = prev.clone().map(|p| quote!{
                #p.stdout.unwrap()
            });

            command
        }).collect();

        let prev = prev.unwrap();

        tokens.extend(quote!{
            || -> std::io::Result<std::process::Output> {
                #(
                    #cmds;
                )*
                Ok(#prev)
            }()
        })
    }
}

impl Command {
    fn to_tokens(&self, ident: Ident, stdin: Option<TokenStream>, last: bool) -> TokenStream {
        let mut terms = (*self.terms).into_iter();
        let first = match terms.next() {
            None => return quote!{},
            Some(term) => term,
        };

        let command = terms.fold(
            quote!{ std::process::Command::new(#first) }, // Create the command
            |command, arg| quote!{ #command.arg(#arg) }, // and add all the args
        );

        // If a previous command exists, add it's stdin to the stdin
        // TODO: expand on this in future to support stderr => stdin
        let command = match stdin {
            Some(stdin) => quote!{ #command.stdin(#stdin) },
            None => command,
        };

        // If this is the last command, get the output
        // Otherwise, create a pipe for the stdout and spawn the command
        // TODO: maybe in future always use pipes and return pipes for the user to deal with
        if last {
            quote!{ let #ident = #command.output()? }
        } else {
            quote!{ let #ident = #command.stdout(std::process::Stdio::piped()).spawn()? }
        }
    }
}