Skip to content

Commit

Permalink
try a method for matching delimiters (#36)
Browse files Browse the repository at this point in the history
How does this look? Is this correct? Should I peek and store that in a
variable for performance? Or readability?

---------

Co-authored-by: Keith Cirkel <[email protected]>
  • Loading branch information
Kristján Oddsson and keithamus authored Jul 26, 2024
1 parent ae5b915 commit ad703d3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 18 deletions.
39 changes: 21 additions & 18 deletions crates/hdx_parser/src/comparison.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::match_delim;
use crate::{unexpected, Parse, Parser, Result};
use hdx_lexer::{Include, Token};
use hdx_lexer::Include;

#[derive(Debug, PartialEq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(tag = "type"))]
Expand All @@ -13,25 +14,27 @@ pub enum Comparison {

impl<'a> Parse<'a> for Comparison {
fn parse(parser: &mut Parser<'a>) -> Result<Comparison> {
Ok(match parser.next() {
Token::Delim('=') => Comparison::Equal,
Token::Delim('>') => {
if let Token::Delim('=') = parser.peek_with(Include::Whitespace) {
parser.advance_with(Include::Whitespace);
Comparison::GreaterThanEqual
} else {
Comparison::GreaterThan
Ok(match_delim! {parser.next() :
'=' => Comparison::Equal,
'>' => {
match_delim!{ parser.peek_with(Include::Whitespace) :
'=' => {
parser.advance_with(Include::Whitespace);
Comparison::GreaterThanEqual
},
_ => Comparison::GreaterThan
}
}
Token::Delim('<') => {
if let Token::Delim('=') = parser.peek_with(Include::Whitespace) {
parser.advance_with(Include::Whitespace);
Comparison::LessThanEqual
} else {
Comparison::LessThan
},
'<' => {
match_delim!{ parser.peek_with(Include::Whitespace) :
'=' => {
parser.advance_with(Include::Whitespace);
Comparison::LessThanEqual
},
_ => Comparison::LessThan
}
}
token => unexpected!(parser, token),
},
token => unexpected!(parser, token)
})
}
}
14 changes: 14 additions & 0 deletions crates/hdx_parser/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,17 @@ macro_rules! match_ignore_case {
}
};
}

#[macro_export]
macro_rules! match_delim {
( $parser: ident.$method: ident($($args: tt)*):
$(
$pattern:pat $(if $guard:expr)? => $then: expr
),+
$(,)?
) => {
match $parser.$method($($args)*).char() {
$(Some($pattern) $( if $guard )? => $then,)+
}
};
}

0 comments on commit ad703d3

Please sign in to comment.