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
//! <p align="center">
//!      <img src="https://raw.github.com/maciejhirsz/logos/master/logos.png?sanitize=true" width="60%" alt="Logos">
//! </p>
//!
//! ## Create ridiculously fast Lexers.
//!
//! This is a `#[derive]` macro crate, [for documentation go to main crate](https://docs.rs/logos).

// The `quote!` macro requires deep recursion.
#![recursion_limit = "196"]

extern crate proc_macro;

mod util;
mod tree;
mod regex;
mod handlers;
mod generator;

use self::regex::Regex;
use self::tree::{Node, Fork, Leaf};
use self::util::{OptionExt, Definition, Literal, value_from_attr};
use self::handlers::{Handlers, Handler, Trivia};
use self::generator::Generator;

use quote::quote;
use proc_macro::TokenStream;
use syn::{ItemEnum, Fields, Ident};

enum Mode {
    Utf8,
    Binary,
}

#[proc_macro_derive(Logos, attributes(
    logos,
    extras,
    error,
    end,
    token,
    regex,
    extras,
    callback,
))]
pub fn logos(input: TokenStream) -> TokenStream {
    let item: ItemEnum = syn::parse(input).expect("#[token] can be only applied to enums");

    let size = item.variants.len();
    let name = &item.ident;

    let mut extras: Option<Ident> = None;
    let mut error = None;
    let mut end = None;
    let mut mode = Mode::Utf8;
    let mut trivia = Trivia::Default;

    // Initially we pack all variants into a single fork, this is where all the logic branching
    // magic happens.
    let mut fork = Fork::default();

    for attr in &item.attrs {
        if let Some(ext) = value_from_attr("extras", attr) {
            extras.insert(ext, |_| panic!("Only one #[extras] attribute can be declared."));
        }

        if let Some(nested) = util::read_attr("logos", attr) {
            for item in nested {
                if let Some(t) = util::value_from_nested::<Option<Literal>>("trivia", item) {
                    let (utf8, regex) = match t {
                        Some(Literal::Utf8(string)) => (true, string),
                        Some(Literal::Bytes(bytes)) => {
                            mode = Mode::Binary;

                            (false, util::bytes_to_regex_string(&bytes))
                        },
                        None => {
                            match trivia {
                                Trivia::Patterns(_) => {},
                                Trivia::Default => trivia = Trivia::Patterns(vec![]),
                            }

                            continue;
                        }
                    };

                    let node = Node::from_regex(&regex, utf8);

                    match node {
                        Node::Branch(ref branch) if branch.then.is_none() && branch.regex.len() == 1 => {
                            let pattern = branch.regex.first().clone();

                            match trivia {
                                Trivia::Patterns(ref mut patterns) => patterns.push(pattern),
                                Trivia::Default => trivia = Trivia::Patterns(vec![pattern]),
                            }

                            continue;
                        },
                        _ => {}
                    }

                    fork.insert(node.leaf(Leaf::Trivia));
                }
            }
        }
    }

    // Then the fork is split into handlers using all possible permutations of the first byte of
    // any branch as the index of a 256-entries-long table.
    let mut handlers = Handlers::new(trivia);

    // Finally the `Generator` will spit out Rust code for all the handlers.
    let mut generator = Generator::new(name);

    let mut variants = Vec::new();

    for variant in &item.variants {
        variants.push(&variant.ident);

        if variant.discriminant.is_some() {
            panic!("`{}::{}` has a discriminant value set. This is not allowed for Tokens.", name, variant.ident);
        }

        match variant.fields {
            Fields::Unit => {},
            _ => panic!("`{}::{}` has fields. This is not allowed for Tokens.", name, variant.ident),
        }

        for attr in &variant.attrs {
            let ident = &attr.path.segments[0].ident;
            let variant = &variant.ident;

            if ident == "error" {
                error.insert(variant, |_| panic!("Only one #[error] variant can be declared."));
            }

            if ident == "end" {
                end.insert(variant, |_| panic!("Only one #[end] variant can be declared."));
            }

            if let Some(definition) = value_from_attr::<Definition<Literal>>("token", attr) {
                let leaf = Leaf::Token {
                    token: variant,
                    callback: definition.callback,
                };

                let bytes = match definition.value {
                    Literal::Utf8(ref string) => string.as_bytes(),
                    Literal::Bytes(ref bytes) => {
                        mode = Mode::Binary;

                        &bytes
                    },
                };

                fork.insert(Node::new(Regex::sequence(bytes)).leaf(leaf));
            } else if let Some(definition) = value_from_attr::<Definition<Literal>>("regex", attr) {
                let leaf = Leaf::Token {
                    token: variant,
                    callback: definition.callback,
                };

                let (utf8, regex) = match definition.value {
                    Literal::Utf8(string) => (true, string),
                    Literal::Bytes(bytes) => {
                        mode = Mode::Binary;

                        (false, util::bytes_to_regex_string(&bytes))
                    },
                };

                fork.insert(Node::from_regex(&regex, utf8).leaf(leaf));
            }

            if let Some(callback) = value_from_attr("callback", attr) {
                generator.set_callback(variant, callback);
            }
        }
    }

    fork.pack();

    // panic!("{:#?}", fork);

    for branch in fork.arms.drain(..) {
        handlers.insert(branch)
    }

    let error = match error {
        Some(error) => error,
        None => panic!("Missing #[error] token variant."),
    };

    let end = match end {
        Some(end) => end,
        None => panic!("Missing #[end] token variant.")
    };

    let extras = match extras {
        Some(ext) => quote!(#ext),
        None      => quote!(()),
    };

    // panic!("{:#?}", handlers);

    let handlers = handlers.into_iter().map(|handler| {
        match handler {
            Handler::Error      => quote!(Some(_error)),
            Handler::Whitespace => quote!(None),
            Handler::Tree(tree) => generator.print_tree(tree),
        }
    }).collect::<Vec<_>>();

    let fns = generator.fns();

    let source = match mode {
        Mode::Utf8   => quote!(Source),
        Mode::Binary => quote!(BinarySource),
    };

    let tokens = quote! {
        impl ::logos::Logos for #name {
            type Extras = #extras;

            const SIZE: usize = #size;
            const ERROR: Self = #name::#error;
            const END: Self = #name::#end;

            fn lexicon<'lexicon, 'source, Source>() -> &'lexicon ::logos::Lexicon<::logos::Lexer<Self, Source>>
            where
                Source: ::logos::Source<'source>,
                Self: ::logos::source::WithSource<Source>,
            {
                use ::logos::internal::LexerInternal;
                use ::logos::source::Split;

                type Lexer<S> = ::logos::Lexer<#name, S>;

                fn _error<'source, S: ::logos::Source<'source>>(lex: &mut Lexer<S>) {
                    lex.bump(1);

                    lex.token = #name::#error;
                }

                #fns

                &[#(#handlers),*]
            }
        }

        impl<'source, Source: ::logos::source::#source<'source>> ::logos::source::WithSource<Source> for #name {}
    };

    // panic!("{}", tokens);

    TokenStream::from(tokens).into()
}