logos-codegen 0.16.1

Create ridiculously fast Lexers
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
//! <img src="https://raw.githubusercontent.com/maciejhirsz/logos/master/logos.svg?sanitize=true" alt="Logos logo" width="250" align="right">
//!
//! # Logos
//!
//! 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"]
#![doc(html_logo_url = "https://maciej.codes/kosz/logos.png")]

mod error;
mod generator;
mod graph;
mod leaf;
mod parser;
mod pattern;
mod util;

#[macro_use]
#[allow(missing_docs)]
mod macros;

use std::error::Error;
use std::ffi::OsStr;
use std::mem;
use std::path::Path;

use error::Errors;
use generator::Generator;
use graph::{Graph, GraphError};
use leaf::Leaf;
use parser::Parser;
use pattern::Pattern;
use quote::ToTokens;

use proc_macro2::{TokenStream, TokenTree};
use quote::quote;
use syn::spanned::Spanned;
use syn::{parse_quote, LitBool};
use syn::{Fields, ItemEnum};

use crate::graph::Config;
use crate::leaf::VariantKind;
use crate::parser::{Definition, ErrorType, Subpatterns};

const LOGOS_ATTR: &str = "logos";
const ERROR_ATTR: &str = "error";
const TOKEN_ATTR: &str = "token";
const REGEX_ATTR: &str = "regex";

/// Generate a `Logos` implementation for the given struct, provided as a stream of rust tokens.
pub fn generate(input: TokenStream) -> TokenStream {
    debug!("Reading input token streams");

    let mut item: ItemEnum = syn::parse2(input).expect("Logos can be only be derived for enums");
    let item_span = item.span();

    let name = &item.ident;

    let mut parser = Parser::default();

    for param in item.generics.params {
        parser.parse_generic(param);
    }

    for attr in &mut item.attrs {
        parser.try_parse_logos(attr);
    }

    debug!("Iterating through subpatterns and skips");

    let utf8_mode = parser
        .utf8_mode
        .as_ref()
        .map(LitBool::value)
        .unwrap_or(true);
    let config = Config { utf8_mode };
    let subpatterns = Subpatterns::new(&parser.subpatterns, utf8_mode, &mut parser.errors);

    let mut pats = Vec::new();

    for skip in mem::take(&mut parser.skips) {
        let Some(pattern_source) = subpatterns.subst_subpatterns(
            &skip.literal.escape(false),
            skip.literal.span(),
            &mut parser.errors,
        ) else {
            continue;
        };

        let pattern = match Pattern::compile(
            false,
            &pattern_source,
            skip.literal.token().to_string(),
            skip.literal.unicode(),
            false,
        ) {
            Ok(pattern) => pattern,
            Err(err) => {
                parser.errors.err(err, skip.literal.span());
                continue;
            }
        };
        greedy_dotall_check(&skip, &pattern, &mut parser);

        let default_priority = pattern.priority();
        pats.push(
            Leaf::new(skip.literal.span(), pattern)
                .priority(skip.priority.unwrap_or(default_priority))
                .callback(skip.callback),
        );
    }

    debug!("Iterating through enum variants");

    for variant in &mut item.variants {
        let var_ident = variant.ident.clone();

        let var_kind = match &mut variant.fields {
            Fields::Unit => VariantKind::Unit(var_ident),
            Fields::Unnamed(fields) => {
                if fields.unnamed.len() != 1 {
                    parser.err(
                        format!(
                            "Logos currently only supports variants with one field, found {}",
                            fields.unnamed.len(),
                        ),
                        fields.span(),
                    );
                }

                let ty = &mut fields
                    .unnamed
                    .first_mut()
                    .expect("Already checked len; qed")
                    .ty;
                let ty = parser.get_type(ty);

                VariantKind::Value(var_ident, ty)
            }
            Fields::Named(fields) => {
                parser.err("Logos doesn't support named fields yet.", fields.span());

                VariantKind::Skip
            }
        };

        for attr in &mut variant.attrs {
            let attr_name = match attr.path().get_ident() {
                Some(ident) => ident.to_string(),
                None => continue,
            };

            match attr_name.as_str() {
                ERROR_ATTR => {
                    // TODO: Remove in future versions
                    parser.err(
                        concat!(
                            "Since 0.13 Logos no longer requires the #[error] variant.",
                            "\n\n",
                            "For help with migration see release notes: ",
                            "https://github.com/maciejhirsz/logos/releases"
                        ),
                        attr.span(),
                    );
                }
                TOKEN_ATTR => {
                    let definition = match parser.parse_definition_attr(attr) {
                        Some(definition) => definition,
                        None => {
                            parser.err("Expected #[token(...)]", attr.span());
                            continue;
                        }
                    };

                    let pattern_res = if definition.ignore_flags.ignore_case {
                        let pattern_src = definition.literal.escape(true);
                        Pattern::compile(
                            true,
                            &pattern_src,
                            definition.literal.token().to_string(),
                            definition.literal.unicode(),
                            true,
                        )
                    } else {
                        Pattern::compile_lit(&definition.literal)
                    };

                    let pattern = match pattern_res {
                        Ok(pattern) => pattern,
                        Err(err) => {
                            parser.err(err, definition.literal.span());
                            continue;
                        }
                    };

                    let literal_len = match &definition.literal {
                        parser::Literal::Utf8(lit_str) => lit_str.value().len(),
                        parser::Literal::Bytes(lit_byte_str) => lit_byte_str.value().len(),
                    };

                    pats.push(
                        Leaf::new(definition.literal.span(), pattern)
                            .variant_kind(var_kind.clone())
                            .priority(definition.priority.unwrap_or(literal_len * 2))
                            .callback(definition.callback),
                    );
                }
                REGEX_ATTR => {
                    let definition = match parser.parse_definition_attr(attr) {
                        Some(definition) => definition,
                        None => {
                            parser.err("Expected #[regex(...)]", attr.span());
                            continue;
                        }
                    };

                    let Some(pattern_source) = subpatterns.subst_subpatterns(
                        &definition.literal.escape(false),
                        definition.literal.span(),
                        &mut parser.errors,
                    ) else {
                        continue;
                    };

                    let unicode = definition.literal.unicode();
                    let ignore_case = definition.ignore_flags.ignore_case;
                    let pattern = match Pattern::compile(
                        false,
                        &pattern_source,
                        definition.literal.token().to_string(),
                        unicode,
                        ignore_case,
                    ) {
                        Ok(pattern) => pattern,
                        Err(err) => {
                            parser.err(err, definition.literal.span());
                            continue;
                        }
                    };

                    greedy_dotall_check(&definition, &pattern, &mut parser);
                    let default_priority = pattern.priority();
                    pats.push(
                        Leaf::new(definition.literal.span(), pattern)
                            .variant_kind(var_kind.clone())
                            .priority(definition.priority.unwrap_or(default_priority))
                            .callback(definition.callback),
                    );
                }
                _ => (),
            }
        }
    }

    debug!("Parsing additional options (extras, utf8, ...)");

    let ErrorType {
        ty: error_type,
        callback: error_callback,
    } = parser.error_type.take().unwrap_or_default();
    let extras = parser.extras.take();
    let non_utf8_pats = pats
        .iter()
        .filter(|leaf| !leaf.pattern.hir().properties().is_utf8())
        .collect::<Vec<_>>();
    if utf8_mode && !non_utf8_pats.is_empty() {
        // If utf8 mode is specified, make sure no patterns match illegal utf8
        for leaf in non_utf8_pats {
            parser.err(format!(concat!(
                "UTF-8 mode is requested, but the pattern {} of variant `{}` can match invalid utf8.\n",
                "You can disable UTF-8 mode with #[logos(utf8 = false)]"
            ), leaf.pattern.source(), leaf.kind), leaf.span);
        }
    };

    let source = match utf8_mode {
        true => quote!(str),
        false => quote!([u8]),
    };
    let logos_path = parser
        .logos_path
        .take()
        .unwrap_or_else(|| parse_quote!(::logos));

    let generics = parser.generics();
    let this = quote!(#name #generics);

    let impl_logos = |body| {
        quote! {
            impl<'s> #logos_path::Logos<'s> for #this {
                type Error = #error_type;

                type Extras = #extras;

                type Source = #source;

                fn lex(lex: &mut #logos_path::Lexer<'s, Self>)
                    -> core::option::Option<core::result::Result<Self, <Self as #logos_path::Logos<'s>>::Error>> {
                    #body
                }
            }
        }
    };

    if cfg!(feature = "debug") {
        let leaves_rendered = pats
            .iter()
            .enumerate()
            .map(|(leaf_id, leaf)| format!("  {}: {} (priority: {})", leaf_id, leaf, leaf.priority))
            .collect::<Vec<_>>()
            .join("\n");
        debug!("Generated leaves:\n{leaves_rendered}");
    }

    debug!("Generating graph from leaves");

    let graph = match Graph::new(pats, config) {
        Ok(nfa) => nfa,
        Err(msg) => {
            let mut errors = Errors::default();
            errors.err(msg, item_span);
            return impl_logos(errors.render().unwrap());
        }
    };

    debug!("Generated Automaton:\n{:?}", graph.dfa());
    debug!("Generated Graph:\n{graph}");
    debug!("Root node: {:?}", graph.root());

    if cfg!(feature = "debug") {
        if let Some(export_path) = parser.export_path.as_ref() {
            debug!("Exporting graphs");
            let lower_name = name.to_string().to_lowercase();

            if let Err(err) = generate_graphs(export_path, &lower_name, &graph) {
                debug!("Failed to export graphs: {err}");
            }
        }
    }

    debug!("Checking if any two tokens have the same priority");

    for error in graph.errors() {
        match error {
            GraphError::Disambiguation(matching) => {
                for leaf_id in matching {
                    let leaf = &graph.leaves()[leaf_id.0];
                    let priority = leaf.priority;

                    let matching = matching
                        .iter()
                        .filter(|&id| id != leaf_id)
                        .map(|match_id| format!("  {}", &graph.leaves()[match_id.0]))
                        .collect::<Vec<_>>()
                        .join("\n");

                    parser.err(
                        format!(
                            concat!(
                                "The pattern {} can match simultaneously with the following variants:\n",
                                "{}\n",
                                "\n",
                                "(all at the priority {})"
                            ),
                            leaf, matching, priority
                        ),
                        leaf.span,
                    );
                }
            }
            GraphError::NoUniversalStart => {
                parser.err(concat!(
                    "The state machine implementing this lexer is missing a universal start state,",
                    "which is unsupported by logos. This is most likely do to a lookbehind assertion ",
                    "at the start of the regex."
                ), item_span);
            }
            GraphError::EmptyMatch(leaf_id) => {
                parser.err(
                    format!(
                        "The pattern {} can match the empty string, which is unsupported by logos.",
                        &graph.leaves()[leaf_id.0],
                    ),
                    graph.leaves()[leaf_id.0].span,
                );
            }
        }
    }

    if let Some(errors) = parser.errors.render() {
        return impl_logos(errors);
    }

    debug!("Generating code from graph");

    let config = generator::Config {
        use_state_machine_codegen: cfg!(feature = "state_machine_codegen"),
    };
    let mut generator = Generator::new(config, name, &this, &graph, &error_callback);

    let body = generator.generate();
    impl_logos(quote! {
        use #logos_path::internal::{
            LexerInternal,
            CallbackRetVal,
            CallbackResult,
            SkipRetVal,
            SkipResult,
        };
        use core::result::Result as _Result;
        use core::option::Option as _Option;
        use #logos_path::Logos;

        type _Lexer<'s> = #logos_path::Lexer<'s, #this>;

        #body
    })
}

fn greedy_dotall_check(definition: &Definition, pattern: &Pattern, parser: &mut Parser) {
    let allow_greedy = definition.allow_greedy.unwrap_or(false);
    if !allow_greedy && pattern.check_for_greedy_all() {
        parser.err(
            concat!(
                "This pattern contains an unbounded greedy dot repetition, i.e. `.*` or `.+` ",
                "(or a character class that is equivalent to a dot, i.e., `[^\\n]*`). ",
                "This will cause the entirety of the input to be read for every token. ",
                "Consider making your repetition non-greedy or changing it to a more ",
                "specific character class. If this is the intended behavior, add ",
                "#[regex(..., allow_greedy = true)] or",
                "#[logos(skip(..., allow_greedy = true))]"
            ),
            definition.literal.span(),
        );
    }
}

/// Strip all logos attributes from the given struct, allowing it to be used in code without `logos-derive` present.
pub fn strip_attributes(input: TokenStream) -> TokenStream {
    let mut item: ItemEnum = syn::parse2(input).expect("Logos can be only be derived for enums");

    strip_attrs_from_vec(&mut item.attrs);

    for attr in &mut item.attrs {
        if let syn::Meta::List(meta) = &mut attr.meta {
            if meta.path.is_ident("derive") {
                let mut tokens =
                    std::mem::replace(&mut meta.tokens, TokenStream::new()).into_iter();

                while let Some(TokenTree::Ident(ident)) = tokens.next() {
                    let punct = tokens.next();

                    if ident == "Logos" {
                        continue;
                    }

                    meta.tokens.extend([TokenTree::Ident(ident)]);
                    meta.tokens.extend(punct);
                }
            }
        }
    }

    for variant in &mut item.variants {
        strip_attrs_from_vec(&mut variant.attrs);
        for field in &mut variant.fields {
            strip_attrs_from_vec(&mut field.attrs);
        }
    }

    item.to_token_stream()
}

fn strip_attrs_from_vec(attrs: &mut Vec<syn::Attribute>) {
    attrs.retain(|attr| !is_logos_attr(attr))
}

fn is_logos_attr(attr: &syn::Attribute) -> bool {
    attr.path().is_ident(LOGOS_ATTR)
        || attr.path().is_ident(TOKEN_ATTR)
        || attr.path().is_ident(REGEX_ATTR)
}

fn generate_graphs(path_str: &str, name: &str, graph: &Graph) -> Result<(), Box<dyn Error>> {
    let path = Path::new(path_str).to_owned();

    let (dot_path, mmd_path) = match path.extension().map(OsStr::to_str) {
        Some(Some("dot")) => (Some(path), None),
        Some(Some("mmd")) => (None, Some(path)),
        Some(_) => {
            return Err(String::from(
                "Export path must end in '.dot' or '.mmd', or it must be a directory.",
            )
            .into())
        }
        None => {
            let dot_path = path.join(format!("{name}.dot"));
            let mmd_path = path.join(format!("{name}.mmd"));
            (Some(dot_path), Some(mmd_path))
        }
    };

    for (path, is_dot) in [(dot_path, true), (mmd_path, false)] {
        let Some(path) = path else { continue };

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        let s = if is_dot {
            graph.get_dot()
        } else {
            graph.get_mermaid()
        }?;
        std::fs::write(path, s)?;
    }

    Ok(())
}