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
//! This crate provides procedural macros for [quit].
//!
//! **Do not add this crate as a dependency.** It has no backward compatibility
//! guarantees. Use the macros re-exported from [quit] instead.
//!
//! [quit]: https://crates.io/crates/quit

#![forbid(unsafe_code)]
#![warn(unused_results)]

extern crate proc_macro;

use std::iter;
use std::iter::FromIterator;
use std::result;

use proc_macro::Delimiter;
use proc_macro::Group;
use proc_macro::Ident;
use proc_macro::Literal;
use proc_macro::Punct;
use proc_macro::Spacing;
use proc_macro::Span;
use proc_macro::TokenStream;
use proc_macro::TokenTree;

trait TokenStreamExt {
    fn push<TToken>(&mut self, token: TToken)
    where
        TToken: Into<TokenTree>;
}

impl TokenStreamExt for TokenStream {
    fn push<TToken>(&mut self, token: TToken)
    where
        TToken: Into<TokenTree>,
    {
        self.extend(iter::once(token.into()))
    }
}

fn path(module: &str, name: &str) -> impl Iterator<Item = TokenTree> {
    vec![
        Punct::new(':', Spacing::Joint).into(),
        Punct::new(':', Spacing::Alone).into(),
        Ident::new(module, Span::call_site()).into(),
        Punct::new(':', Spacing::Joint).into(),
        Punct::new(':', Spacing::Alone).into(),
        Ident::new(name, Span::call_site()).into(),
    ]
    .into_iter()
}

// https://docs.rs/syn/1.0/syn/struct.Error.html
#[derive(Copy, Clone)]
struct Error {
    start: Span,
    end: Span,
    message: &'static str,
}

impl Error {
    const fn new(span: Span, message: &'static str) -> Self {
        Self {
            start: span,
            end: span,
            message,
        }
    }

    fn new_spanned<TTokens>(tokens: TTokens, message: &'static str) -> Self
    where
        TTokens: Into<TokenStream>,
    {
        let mut tokens = tokens.into().into_iter();
        let start = tokens
            .next()
            .map(|x| x.span())
            .unwrap_or_else(Span::call_site);
        Self {
            start,
            end: tokens.last().map(|x| x.span()).unwrap_or(start),
            message,
        }
    }

    fn to_compile_error(self) -> TokenStream {
        let mut result: TokenStream = path("std", "compile_error")
            .chain(iter::once(Punct::new('!', Spacing::Alone).into()))
            .map(|mut token| {
                token.set_span(self.start);
                token
            })
            .collect();

        let mut literal = Literal::string(self.message);
        literal.set_span(self.end);

        let mut group =
            Group::new(Delimiter::Brace, TokenTree::Literal(literal).into());
        group.set_span(self.end);

        result.push(group);
        result
    }
}

// https://docs.rs/syn/1.0/syn/type.Result.html
type Result<TOk> = result::Result<TOk, Error>;

fn parse_main_fn(tokens: TokenStream) -> Result<(TokenStream, TokenTree)> {
    let mut tokens = tokens.into_iter();
    let mut signature = TokenStream::new();

    loop {
        let token = tokens.next().ok_or_else(|| {
            Error::new(
                Span::call_site(),
                "`#[quit::main]` can only be attached to functions",
            )
        })?;

        match &token {
            TokenTree::Ident(keyword) if keyword.to_string() == "fn" => {
                signature.push(token);
                break;
            }
            _ => {}
        }
        signature.push(token);
    }

    if let Some(name) = tokens.next() {
        if name.to_string() != "main" {
            return Err(Error::new_spanned(
                name,
                "`#[quit::main]` can only be attached to `main`",
            ));
        }
        signature.push(name);
    }

    let body = loop {
        let token = tokens.next().ok_or_else(|| {
            Error::new(
                Span::call_site(),
                "`#[quit::main]` can only be attached to functions with a \
                body",
            )
        })?;

        match &token {
            TokenTree::Group(group)
                if group.delimiter() == Delimiter::Brace =>
            {
                break token;
            }
            _ => {}
        }
        signature.push(token);
    };

    assert!(tokens.next().is_none());

    Ok((signature, body))
}

#[inline]
#[proc_macro_attribute]
pub fn main(args: TokenStream, item: TokenStream) -> TokenStream {
    if !args.is_empty() {
        return Error::new_spanned(args, "arguments are not accepted")
            .to_compile_error();
    }

    let (mut result, body) = match parse_main_fn(item) {
        Ok(result) => result,
        Err(error) => return error.to_compile_error(),
    };

    let mut args = TokenStream::from_iter(vec![
        TokenTree::Punct(Punct::new(
            '|',
            Spacing::Alone,
        ));
        2
    ]);
    args.push(body);

    let mut body: TokenStream = path("quit", "__run").collect();
    body.push(Group::new(Delimiter::Parenthesis, args));

    result.push(Group::new(Delimiter::Brace, body));
    result
}