Skip to content

Commit 7edc0fb

Browse files
committed
ensure then combinator have proper cache
1 parent b0933d0 commit 7edc0fb

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

src/parser/parser-lib.ts

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,11 @@ export class Parser<T> {
4949
* parser is then also parsed.
5050
*/
5151
then<U>(mapper: (value: T) => Parser<U>): Parser<U> {
52-
return new Parser((src) =>
53-
this.parser(src).flatMap(({ value, rest }) => mapper(value).parser(rest))
54-
);
52+
const { cache } = Parser;
53+
return new Parser((src) => {
54+
const parser = Parser.inContext(() => this.parser(src), cache);
55+
return parser.flatMap(({ value, rest }) => mapper(value).parser(rest));
56+
});
5557
}
5658
sort(comparer: (left: T, right: T) => number): Parser<T> {
5759
return new Parser((src) =>
@@ -84,6 +86,13 @@ export class Parser<T> {
8486
static startOrEndCache(cache: null | Cache = null): void {
8587
Parser.cache = cache;
8688
}
89+
static inContext<T>(fn: () => T, cache: null | Cache = null): T {
90+
const previousCache = Parser.cache;
91+
Parser.startOrEndCache(cache);
92+
const value = fn();
93+
Parser.startOrEndCache(previousCache);
94+
return value;
95+
}
8796
}
8897
/** Represents Error with unexpected and expected elements. */
8998
export class UnexpectedError extends ArrayResultError {
@@ -131,13 +140,7 @@ export function lookAhead<T>(parser: Parser<T>): Parser<T> {
131140
*/
132141
export function lazy<T>(parser: () => Parser<T>): Parser<T> {
133142
const { cache } = Parser;
134-
const cachedParser = new Lazy(() => {
135-
const previousCache = Parser.cache;
136-
Parser.startOrEndCache(cache);
137-
const useParser = parser();
138-
Parser.startOrEndCache(previousCache);
139-
return useParser;
140-
});
143+
const cachedParser = new Lazy(() => Parser.inContext(parser, cache));
141144
Parser.addToCache(cachedParser);
142145
return new Parser((src) => cachedParser.getValue().parser(src));
143146
}

0 commit comments

Comments
 (0)