Skip to content

Parse SQL keywords and identifiers? #699

Answered by zesterer
jennykwan asked this question in Q&A
Discussion options

You must be logged in to vote

My personal view is that the simplest way to set up keyword and identifier parsing looks something like this:

pub enum Token<'src> {
    KwSelect,
    KwAlter,
    ...
    Ident(&'src str),
}

text::ident().map(|x| match x {
    x if x.eq_ignore_ascii_case("select") => Token::KwSelect,
    x if x.eq_ignore_ascii_case("alter") => Token::KwAlter,
    ...
    x => Token::Ident(x),
})

This parses any C-style identifier, then checks to see whether it is a lower-case match with any of the given keywords, mapping it to the relevant keyword token if so. If not, it'll fall back to the identifier token.

If you really want other cases to fall back to an error, try_map can be used instead of map as m…

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@jennykwan
Comment options

@Zij-IT
Comment options

@zesterer
Comment options

Answer selected by jennykwan
@jennykwan
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants