Skip to content

Commit

Permalink
feat(parser): add built-in patterns
Browse files Browse the repository at this point in the history
  • Loading branch information
watcol committed Jul 26, 2022
1 parent 19768d0 commit 43ab3f6
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 6 deletions.
12 changes: 8 additions & 4 deletions drake-parser/src/pattern.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,21 @@
mod tests;

use drake_types::ast::{Pattern, PatternKind};
use drake_types::token::Token;
use drake_types::token::{Symbol, Token};
use somen::prelude::*;

use crate::key::key;
use crate::token::symbol;

/// A parser for patterns
pub fn pattern<'a, I>() -> impl Parser<I, Output = Pattern<I::Locator>> + 'a
where
I: Input<Ok = Token> + 'a,
{
choice((key().map(PatternKind::Key),))
.with_position()
.map(|(kind, span)| Pattern { kind, span })
choice((
symbol(Symbol::At).prefix(key()).map(PatternKind::Builtin),
key().map(PatternKind::Key),
))
.with_position()
.map(|(kind, span)| Pattern { kind, span })
}
19 changes: 18 additions & 1 deletion drake-parser/src/pattern/tests.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use alloc::string::String;
use drake_types::ast::{Key, KeyKind, Pattern, PatternKind};
use drake_types::token::{Identifier, IdentifierKind, Token};
use drake_types::token::{Identifier, IdentifierKind, Symbol, Token};
use somen::prelude::*;

use crate::test_utils::test_parser;
Expand All @@ -10,6 +10,23 @@ fn pattern() {
test_parser(
super::pattern().complete(),
&[
(
&[
Token::Symbol(Symbol::At),
Token::Identifier(Identifier {
kind: IdentifierKind::Bare,
name: String::from("abc"),
}),
],
Some(Pattern {
kind: PatternKind::Builtin(Key {
kind: KeyKind::Normal,
name: String::from("abc"),
span: 1..2,
}),
span: 0..2,
}),
),
(
&[Token::Identifier(Identifier {
kind: IdentifierKind::Bare,
Expand Down
8 changes: 7 additions & 1 deletion drake-types/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ pub struct Pattern<L> {
pub enum PatternKind<L> {
/// A key pattern
Key(Key<L>),
/// A built-in pattern
Builtin(Key<L>),
}

/// Keys
Expand Down Expand Up @@ -154,13 +156,17 @@ impl<L> fmt::Display for Pattern<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.kind {
PatternKind::Key(ref key) => key.fmt(f),
PatternKind::Builtin(ref key) => write!(f, "@{key}"),
}
}
}

impl<L> fmt::Display for Key<L> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.name.fmt(f)
match self.kind {
KeyKind::Normal => self.name.fmt(f),
KeyKind::Local => write!(f, "_{}", self.name),
}
}
}

Expand Down

0 comments on commit 43ab3f6

Please sign in to comment.