Skip to content

Commit f86294b

Browse files
authored
Merge pull request #63 from ilo-token/master
Reduce memory usage
2 parents 0c974c6 + 6a4f01c commit f86294b

2 files changed

Lines changed: 14 additions & 10 deletions

File tree

src/parser/lexer.ts

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,6 @@ const longWord = choiceOnlyOne(matchString("a"), matchString("n"))
116116
)
117117
.skip(spaces);
118118

119-
Parser.startCache(cache);
120-
121119
/** Parses X ala X constructions if allowed by the settings. */
122120
const xAlaX = lazy(() => {
123121
if (settings.xAlaXPartialParsing) {
@@ -131,8 +129,6 @@ const xAlaX = lazy(() => {
131129
})
132130
.map<Token>((word) => ({ type: "x ala x", word }));
133131

134-
Parser.endCache();
135-
136132
/** Parses a punctuation. */
137133
const punctuation = choiceOnlyOne(
138134
match(/[.,:;?!·\u{F199C}\u{F199D}]+/u, "punctuation")

src/parser/parser-lib.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,13 @@ export class Parser<T> {
1717
readonly #parser: (src: string) => ParserResult<T>;
1818
static cache: null | Cache = null;
1919
constructor(parser: (src: string) => ParserResult<T>) {
20-
const cache = new Map<string, ParserResult<T>>();
21-
Parser.addToCache(cache);
22-
this.#parser = memoize(parser, { cache });
20+
if (Parser.cache != null) {
21+
const cache = new Map<string, ParserResult<T>>();
22+
Parser.addToCache(cache);
23+
this.#parser = memoize(parser, { cache });
24+
} else {
25+
this.#parser = parser;
26+
}
2327
}
2428
parser(src: string): ParserResult<T> {
2529
return ArrayResult.from(() => this.#parser(src));
@@ -140,9 +144,13 @@ export function lookAhead<T>(parser: Parser<T>): Parser<T> {
140144
*/
141145
export function lazy<T>(parser: () => Parser<T>): Parser<T> {
142146
const { cache } = Parser;
143-
const cachedParser = new Lazy(() => Parser.inContext(parser, cache));
144-
Parser.addToCache(cachedParser);
145-
return new Parser((src) => cachedParser.getValue().parser(src));
147+
if (Parser.cache != null) {
148+
const cachedParser = new Lazy(() => Parser.inContext(parser, cache));
149+
Parser.addToCache(cachedParser);
150+
return new Parser((src) => cachedParser.getValue().parser(src));
151+
} else {
152+
return new Parser((src) => Parser.inContext(parser, cache).parser(src));
153+
}
146154
}
147155
/**
148156
* Evaluates all parsers on the same source string and sums it all on a single

0 commit comments

Comments
 (0)