Tokenizer

Struct Tokenizer 

Source
pub struct Tokenizer<'a> { /* private fields */ }
Expand description

The Crossandra tokenizer, operating on literals and patterns.

§Literals

Literals indicate values that have to be exactly matched by the tokenizer. They are represented by a slice of (name, value) pairs. For example, a literal map for Brainfuck would be defined like this:

let literals = [
    ("add", "+"),
    ("sub", "-"),
    ("left", "<"),
    ("right", ">"),
    ("read", ","),
    ("write", "."),
    ("begin_loop", "["),
    ("end_loop", "]"),
];

Literals take precedence over patterns.

§Patterns

Patterns are regular expressions that match more complex token structures. They are represented as pairs of strings (name, pattern) in a Vec to maintain a consistent matching order.

The order of patterns matters as the tokenizer will use the first matching pattern it finds. Duplicate pattern names are not allowed and will result in an error. This crate also provides a collection of commonly used patterns in the common module. For example, patterns covering binary, octal, and hexadecimal literals could be defined like this:

let patterns = vec![
    ("binary".into(), r"0[bB][01]+".into()),
    ("octal".into(), r"0[Oo][0-7]+".into()),
    ("hexadecimal".into(), r"(?i)0x[0-9a-f]+".into()),
];

§Other options

§ignore_whitespace

Whether to ignore the following whitespace characters:

CodeCharacter
0x9Tab (\t)
0xaLine feed (\n)
0xbVertical tab
0xcForm feed
0xdCarriage return (\r)
0x20Space ( )

Defaults to false.

§ignored_characters

A set of characters to ignore during tokenization. Defaults to an empty Vec.

§Fast Mode

When all literals are of length 1 and there are no patterns, Crossandra uses a simpler tokenization method.

For instance, tokenizing a 1MB random Brainfuck file with 10% of the file being comments is ~300x faster with Fast Mode (32.5s vs 110ms on Apple M2).

Do note that this is a rather extreme case; for a 1KB file, the speedup is ~2.3x.

Implementations§

Source§

impl<'a> Tokenizer<'a>

Source

pub fn new( literals: &[(&'a str, &'a str)], patterns: Vec<(String, String)>, ignored_characters: FxHashSet<char>, ignore_whitespace: bool, ) -> Result<Self, Error>

Creates a new Tokenizer with the specified configuration.

§Errors

This function will return an error if:

Source

pub fn tokenize( &'a self, source: &'a str, ) -> Box<dyn Iterator<Item = Result<Token, Error>> + 'a>

Tokenizes the given source code and returns an Iterator of Tokens.

Source

pub fn tokenize_lines( &'a self, source: &'a str, ) -> impl ParallelIterator<Item = Result<Vec<Token>, Error>> + 'a

Splits the given source code into lines and tokenizes each line separately. Returns an Iterator of Vecs of Tokens.

§Errors

This function will return an error if any line fails to tokenize.

Source

pub fn with_literals( self, literals: &[(&'a str, &'a str)], ) -> Result<Self, Error>

Sets the literals of this Tokenizer and returns itself.

§Errors

This function will return an error if any literal is empty.

Source

pub fn with_patterns( self, patterns: Vec<(String, String)>, ) -> Result<Self, Error>

Sets the patterns of this Tokenizer and returns itself.

§Errors

This function will return an error if:

  • there are duplicate patterns, or
  • any pattern regex is invalid.
Source

pub fn with_ignored_characters( self, ignored_characters: FxHashSet<char>, ) -> Self

Sets the ignored characters of this Tokenizer and returns itself.

Source

pub fn with_ignore_whitespace(self, ignore_whitespace: bool) -> Self

Sets the ignore_whitespace option of this Tokenizer and returns itself.

Source

pub fn set_literals( &mut self, literals: &[(&'a str, &'a str)], ) -> Result<(), Error>

Sets the literals of this Tokenizer.

§Errors

This function will return an error if any literal is empty.

Source

pub fn set_patterns( &mut self, patterns: Vec<(String, String)>, ) -> Result<(), Error>

Sets the patterns of this Tokenizer.

§Errors

This function will return an error if:

  • there are duplicate patterns, or
  • any pattern regex is invalid.
Source

pub fn set_ignored_characters(&mut self, ignored_characters: FxHashSet<char>)

Sets the ignored characters of this Tokenizer.

Source

pub fn set_ignore_whitespace(&mut self, ignore_whitespace: bool)

Sets the ignore_whitespace option of this Tokenizer.

Trait Implementations§

Source§

impl<'a> Clone for Tokenizer<'a>

Source§

fn clone(&self) -> Tokenizer<'a>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Debug for Tokenizer<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Tokenizer<'_>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl PartialEq for Tokenizer<'_>

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Tokenizer<'_>

Auto Trait Implementations§

§

impl<'a> Freeze for Tokenizer<'a>

§

impl<'a> RefUnwindSafe for Tokenizer<'a>

§

impl<'a> Send for Tokenizer<'a>

§

impl<'a> Sync for Tokenizer<'a>

§

impl<'a> Unpin for Tokenizer<'a>

§

impl<'a> UnwindSafe for Tokenizer<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.