This repository was archived by the owner on Apr 2, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 209
Added with_slice, updated logos example #439
Open
zesterer
wants to merge
1
commit into
main
Choose a base branch
from
with_slice
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,7 +4,7 @@ | |
|
|
||
| use ariadne::{Color, Label, Report, ReportKind, Source}; | ||
| use chumsky::{ | ||
| input::{Stream, ValueInput}, | ||
| input::{SliceInput, Stream, ValueInput}, | ||
| prelude::*, | ||
| }; | ||
| use logos::Logos; | ||
|
|
@@ -31,33 +31,38 @@ enum Token<'a> { | |
| #[token(")")] | ||
| RParen, | ||
|
|
||
| #[regex("[A-Za-z_]+")] | ||
| Ident, | ||
|
|
||
| #[regex(r"[ \t\f\n]+", logos::skip)] | ||
| Whitespace, | ||
| } | ||
|
|
||
| impl<'a> fmt::Display for Token<'a> { | ||
| fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
| match self { | ||
| Self::Float(s) => write!(f, "{}", s), | ||
| Self::Float(s) => write!(f, "{s}"), | ||
| Self::Add => write!(f, "+"), | ||
| Self::Sub => write!(f, "-"), | ||
| Self::Mul => write!(f, "*"), | ||
| Self::Div => write!(f, "/"), | ||
| Self::LParen => write!(f, "("), | ||
| Self::RParen => write!(f, ")"), | ||
| Self::Whitespace => write!(f, "<whitespace>"), | ||
| Self::Ident => write!(f, "<ident>"), | ||
| Self::Error => write!(f, "<error>"), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[derive(Debug)] | ||
| enum SExpr { | ||
| enum SExpr<'a> { | ||
| Float(f64), | ||
| Add, | ||
| Sub, | ||
| Mul, | ||
| Div, | ||
| Ident(&'a str), | ||
| List(Vec<Self>), | ||
| } | ||
|
|
||
|
|
@@ -71,9 +76,9 @@ enum SExpr { | |
| // - Has an input type of type `I`, the one we declared as a type parameter | ||
| // - Produces an `SExpr` as its output | ||
| // - Uses `Rich`, a built-in error type provided by chumsky, for error generation | ||
| fn parser<'a, I>() -> impl Parser<'a, I, SExpr, extra::Err<Rich<'a, Token<'a>>>> | ||
| fn parser<'a, I>() -> impl Parser<'a, I, SExpr<'a>, extra::Err<Rich<'a, Token<'a>>>> | ||
| where | ||
| I: ValueInput<'a, Token = Token<'a>, Span = SimpleSpan>, | ||
| I: ValueInput<'a, Token = Token<'a>, Span = SimpleSpan> + SliceInput<'a, Slice = &'a str>, | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Tbf, to avaid humongous types, trait "aliases" should be used. pub type TokenParserExtra<'a> = Full<Rich<'a, Token>, (), ()>;
pub trait TokenInput<'a>: ValueInput<'a, Token = Token, Span = SimpleSpan> {}
impl<'a, T> TokenInput<'a> for T where T: ValueInput<'a, Token = Token, Span = SimpleSpan> {}
pub trait TokenParser<'a, I: TokenInput<'a>, O>:
Parser<'a, I, O, TokenParserExtra<'a>> + Clone {
}
impl<'a, I: TokenInput<'a>, O, T> TokenParser<'a, I, O> for T where T: Parser<'a, I, O, TokenParserExtra<'a>> + Clone {}until real trait aliases are available |
||
| { | ||
| recursive(|sexpr| { | ||
| let atom = select! { | ||
|
|
@@ -84,17 +89,19 @@ where | |
| Token::Div => SExpr::Div, | ||
| }; | ||
|
|
||
| let ident = just(Token::Ident).slice().map(SExpr::Ident); | ||
|
|
||
| let list = sexpr | ||
| .repeated() | ||
| .collect() | ||
| .map(SExpr::List) | ||
| .delimited_by(just(Token::LParen), just(Token::RParen)); | ||
|
|
||
| atom.or(list) | ||
| atom.or(ident).or(list) | ||
| }) | ||
| } | ||
|
|
||
| impl SExpr { | ||
| impl<'a> SExpr<'a> { | ||
| // Recursively evaluate an s-expression | ||
| fn eval(&self) -> Result<f64, &'static str> { | ||
| match self { | ||
|
|
@@ -103,6 +110,7 @@ impl SExpr { | |
| Self::Sub => Err("Cannot evaluate operator '-'"), | ||
| Self::Mul => Err("Cannot evaluate operator '*'"), | ||
| Self::Div => Err("Cannot evaluate operator '/'"), | ||
| Self::Ident(_) => Err("Identifiers not supported"), | ||
| Self::List(list) => match &list[..] { | ||
| [Self::Add, tail @ ..] => tail.iter().map(SExpr::eval).sum(), | ||
| [Self::Mul, tail @ ..] => tail.iter().map(SExpr::eval).product(), | ||
|
|
@@ -142,7 +150,8 @@ fn main() { | |
| let token_stream = Stream::from_iter(token_iter) | ||
| // Tell chumsky to split the (Token, SimpleSpan) stream into its parts so that it can handle the spans for us | ||
| // This involves giving chumsky an 'end of input' span: we just use a zero-width span at the end of the string | ||
| .spanned((SRC.len()..SRC.len()).into()); | ||
| .spanned((SRC.len()..SRC.len()).into()) | ||
| .with_slice(SRC); | ||
|
|
||
| // Parse the token stream with our chumsky parser | ||
| match parser().parse(token_stream).into_result() { | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can be moved under the
#[derive(...)]using#[logos(skip r"[ \t\f\n]+")]