From 2b084c6f829b09e83919cad8a4f1bb3886641bec Mon Sep 17 00:00:00 2001 From: Domenic Quirl Date: Sun, 20 Feb 2022 09:34:41 +0100 Subject: [PATCH 1/2] add `SyntaxText::fold_chunks` #33 --- src/syntax/text.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/syntax/text.rs b/src/syntax/text.rs index a51437a..554bd4b 100644 --- a/src/syntax/text.rs +++ b/src/syntax/text.rs @@ -156,6 +156,8 @@ impl<'n, 'i, I: Resolver + ?Sized, L: Language, D> SyntaxText<'n, 'i, I, L, D> { /// If `f` returns `Err`, the error is propagated immediately. /// Otherwise, the result of the current call to `f` will be passed to the invocation of `f` on /// the next token, producing a final value if `f` succeeds on all chunks. + /// + /// See also [`fold_chunks`](SyntaxText::fold_chunks) for folds that always succeed. pub fn try_fold_chunks(&self, init: T, mut f: F) -> Result where F: FnMut(T, &str) -> Result, @@ -165,6 +167,25 @@ impl<'n, 'i, I: Resolver + ?Sized, L: Language, D> SyntaxText<'n, 'i, I, L, D> { }) } + /// Applies the given function to all text chunks (from [`SyntaxToken`]s) that are part of this + /// text, starting from the initial value `init`. + /// + /// The result of the current call to `f` will be passed to the invocation of `f` on the next + /// token, producing a final value after `f` was called on all chunks. + /// + /// See also [`try_fold_chunks`](SyntaxText::try_fold_chunks), which performs the same operation + /// for fallible functions `f`. + pub fn fold_chunks(&self, init: T, mut f: F) -> T + where + F: FnMut(T, &str) -> T, + { + enum Void {} + match self.try_fold_chunks(init, |acc, chunk| Ok::(f(acc, chunk))) { + Ok(t) => t, + Err(void) => match void {}, + } + } + /// Applies the given function to all text chunks that this text is comprised of, in order, /// as long as `f` completes successfully. /// From f88b980ed19a841b8ec84b0728563a1b072a6ab7 Mon Sep 17 00:00:00 2001 From: Domenic Quirl Date: Sun, 20 Feb 2022 09:41:43 +0100 Subject: [PATCH 2/2] use `fold_chunks` in `for_each_chunk` --- src/syntax/text.rs | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/src/syntax/text.rs b/src/syntax/text.rs index 554bd4b..7b577e6 100644 --- a/src/syntax/text.rs +++ b/src/syntax/text.rs @@ -199,17 +199,10 @@ impl<'n, 'i, I: Resolver + ?Sized, L: Language, D> SyntaxText<'n, 'i, I, L, D> { /// Applies the given function to all text chunks that this text is comprised of, in order. /// - /// See also [`try_fold_chunks`](SyntaxText::try_fold_chunks), + /// See also [`fold_chunks`](SyntaxText::fold_chunks), /// [`try_for_each_chunk`](SyntaxText::try_for_each_chunk). pub fn for_each_chunk(&self, mut f: F) { - enum Void {} - match self.try_for_each_chunk(|chunk| { - f(chunk); - Ok::<(), Void>(()) - }) { - Ok(()) => (), - Err(void) => match void {}, - } + self.fold_chunks((), |(), chunk| f(chunk)) } fn tokens_with_ranges(&self) -> impl Iterator, TextRange)> {