All Projects → maciejhirsz → Logos

maciejhirsz / Logos

Licence: other
Create ridiculously fast Lexers

Programming Languages

rust
11053 projects

Projects that are alternatives of or similar to Logos

Graphql Go Tools
Tools to write high performance GraphQL applications using Go/Golang.
Stars: ✭ 96 (-90.41%)
Mutual labels:  lexer, parser, parsing
Php Parser
🌿 NodeJS PHP Parser - extract AST or tokens (PHP5 and PHP7)
Stars: ✭ 400 (-60.04%)
Mutual labels:  lexer, parser
Verible
Verible is a suite of SystemVerilog developer tools, including a parser, style-linter, and formatter.
Stars: ✭ 384 (-61.64%)
Mutual labels:  lexer, parser
Minigo
minigo🐥is a small Go compiler made from scratch. It can compile itself.
Stars: ✭ 456 (-54.45%)
Mutual labels:  lexer, parser
Syntax Parser
Light and fast 🚀parser! With zero dependents. - Sql Parser Demo added!
Stars: ✭ 317 (-68.33%)
Mutual labels:  lexer, parser
Jflex
The fast scanner generator for Java™ with full Unicode support
Stars: ✭ 380 (-62.04%)
Mutual labels:  lexer, parsing
Tiny Compiler
A tiny compiler for a language featuring LL(2) with Lexer, Parser, ASM-like codegen and VM. Complex enough to give you a flavour of how the "real" thing works whilst not being a mere toy example
Stars: ✭ 425 (-57.54%)
Mutual labels:  lexer, parser
sb-dynlex
Configurable lexer for PHP featuring a fluid API.
Stars: ✭ 27 (-97.3%)
Mutual labels:  parsing, lexer
Meriyah
A 100% compliant, self-hosted javascript parser - https://meriyah.github.io/meriyah
Stars: ✭ 690 (-31.07%)
Mutual labels:  parser, parsing
Esprima
ECMAScript parsing infrastructure for multipurpose analysis
Stars: ✭ 6,391 (+538.46%)
Mutual labels:  parser, parsing
Fuzi
A fast & lightweight XML & HTML parser in Swift with XPath & CSS support
Stars: ✭ 894 (-10.69%)
Mutual labels:  parser, parsing
Kgt
BNF wrangling and railroad diagrams
Stars: ✭ 312 (-68.83%)
Mutual labels:  parser, parsing
Exprtk
C++ Mathematical Expression Parsing And Evaluation Library
Stars: ✭ 301 (-69.93%)
Mutual labels:  lexer, parser
Errorstacks
Tiny library to parse error stack traces
Stars: ✭ 29 (-97.1%)
Mutual labels:  parser, parsing
Nearley
📜🔜🌲 Simple, fast, powerful parser toolkit for JavaScript.
Stars: ✭ 3,089 (+208.59%)
Mutual labels:  parser, parsing
Seafox
A blazing fast 100% spec compliant, self-hosted javascript parser written in Typescript
Stars: ✭ 425 (-57.54%)
Mutual labels:  parser, parsing
Jkt
Simple helper to parse JSON based on independent schema
Stars: ✭ 22 (-97.8%)
Mutual labels:  parser, parsing
Cub
The Cub Programming Language
Stars: ✭ 198 (-80.22%)
Mutual labels:  lexer, parser
re-typescript
An opinionated attempt at finally solving typescript interop for ReasonML / OCaml.
Stars: ✭ 68 (-93.21%)
Mutual labels:  parsing, lexer
Self Attentive Parser
High-accuracy NLP parser with models for 11 languages.
Stars: ✭ 569 (-43.16%)
Mutual labels:  parser, parsing
Logos logo

Logos

Test Crates.io version shield Docs Crates.io license shield

Create ridiculously fast Lexers.

Logos has two goals:

  • To make it easy to create a Lexer, so you can focus on more complex problems.
  • To make the generated Lexer faster than anything you'd write by hand.

To achieve those, Logos:

Example

use logos::Logos;

#[derive(Logos, Debug, PartialEq)]
enum Token {
    // Tokens can be literal strings, of any length.
    #[token("fast")]
    Fast,

    #[token(".")]
    Period,

    // Or regular expressions.
    #[regex("[a-zA-Z]+")]
    Text,

    // Logos requires one token variant to handle errors,
    // it can be named anything you wish.
    #[error]
    // We can also use this variant to define whitespace,
    // or any other matches we wish to skip.
    #[regex(r"[ \t\n\f]+", logos::skip)]
    Error,
}

fn main() {
    let mut lex = Token::lexer("Create ridiculously fast Lexers.");

    assert_eq!(lex.next(), Some(Token::Text));
    assert_eq!(lex.span(), 0..6);
    assert_eq!(lex.slice(), "Create");

    assert_eq!(lex.next(), Some(Token::Text));
    assert_eq!(lex.span(), 7..19);
    assert_eq!(lex.slice(), "ridiculously");

    assert_eq!(lex.next(), Some(Token::Fast));
    assert_eq!(lex.span(), 20..24);
    assert_eq!(lex.slice(), "fast");

    assert_eq!(lex.next(), Some(Token::Text));
    assert_eq!(lex.span(), 25..31);
    assert_eq!(lex.slice(), "Lexers");

    assert_eq!(lex.next(), Some(Token::Period));
    assert_eq!(lex.span(), 31..32);
    assert_eq!(lex.slice(), ".");

    assert_eq!(lex.next(), None);
}

Callbacks

Logos can also call arbitrary functions whenever a pattern is matched, which can be used to put data into a variant:

use logos::{Logos, Lexer};

// Note: callbacks can return `Option` or `Result`
fn kilo(lex: &mut Lexer<Token>) -> Option<u64> {
    let slice = lex.slice();
    let n: u64 = slice[..slice.len() - 1].parse().ok()?; // skip 'k'
    Some(n * 1_000)
}

fn mega(lex: &mut Lexer<Token>) -> Option<u64> {
    let slice = lex.slice();
    let n: u64 = slice[..slice.len() - 1].parse().ok()?; // skip 'm'
    Some(n * 1_000_000)
}

#[derive(Logos, Debug, PartialEq)]
enum Token {
    #[error]
    #[regex(r"[ \t\n\f]+", logos::skip)]
    Error,

    // Callbacks can use closure syntax, or refer
    // to a function defined elsewhere.
    //
    // Each pattern can have it's own callback.
    #[regex("[0-9]+", |lex| lex.slice().parse())]
    #[regex("[0-9]+k", kilo)]
    #[regex("[0-9]+m", mega)]
    Number(u64),
}

fn main() {
    let mut lex = Token::lexer("5 42k 75m");

    assert_eq!(lex.next(), Some(Token::Number(5)));
    assert_eq!(lex.slice(), "5");

    assert_eq!(lex.next(), Some(Token::Number(42_000)));
    assert_eq!(lex.slice(), "42k");

    assert_eq!(lex.next(), Some(Token::Number(75_000_000)));
    assert_eq!(lex.slice(), "75m");

    assert_eq!(lex.next(), None);
}

Logos can handle callbacks with following return types:

Return type Produces
() Token::Unit
bool Token::Unit or <Token as Logos>::ERROR
Result<(), _> Token::Unit or <Token as Logos>::ERROR
T Token::Value(T)
Option<T> Token::Value(T) or <Token as Logos>::ERROR
Result<T, _> Token::Value(T) or <Token as Logos>::ERROR
Skip skips matched input
Filter<T> Token::Value(T) or skips matched input

Callbacks can be also used to do perform more specialized lexing in place where regular expressions are too limiting. For specifics look at Lexer::remainder and Lexer::bump.

Token disambiguation

Rule of thumb is:

  • Longer beats shorter.
  • Specific beats generic.

If any two definitions could match the same input, like fast and [a-zA-Z]+ in the example above, it's the longer and more specific definition of Token::Fast that will be the result.

This is done by comparing numeric priority attached to each definition. Every consecutive, non-repeating single byte adds 2 to the priority, while every range or regex class adds 1. Loops or optional blocks are ignored, while alternations count the shortest alternative:

  • [a-zA-Z]+ has a priority of 1 (lowest possible), because at minimum it can match a single byte to a class.
  • foobar has a priority of 12.
  • (foo|hello)(bar)? has a priority of 6, foo being it's shortest possible match.

If two definitions compute to the same priority and can match the same input Logos will fail to compile, point out the problematic definitions, and ask you to specify a manual priority for either of them.

For example: [abc]+ and [cde]+ both can match sequences of c, and both have priority of 1. Turning the first definition to #[regex("[abc]+", priority = 2)] will allow for tokens to be disambiguated again, in this case all sequences of c will match [abc]+.

How fast?

Ridiculously fast!

test identifiers                       ... bench:         647 ns/iter (+/- 27) = 1204 MB/s
test keywords_operators_and_punctators ... bench:       2,054 ns/iter (+/- 78) = 1037 MB/s
test strings                           ... bench:         553 ns/iter (+/- 34) = 1575 MB/s

Acknowledgements

Thank you

Logos is very much a labor of love. If you find it useful, consider getting me some coffee. ☕

License

This code is distributed under the terms of both the MIT license and the Apache License (Version 2.0), choose whatever works for you.

See LICENSE-APACHE and LICENSE-MIT for details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].