Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement packrat parsing #75

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions src/cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
type Function_ = (...x: never[]) => unknown;

type Memoize<F extends Function_> = {
(...x: Parameters<F>): ReturnType<F>;
clearCache: () => void;
};

const memoizedFunctions: Memoize<Function_>[] = [];

export const memoize = <F extends Function_>(
fn: F,
) => {
const cache = new Map<string, unknown>();

const memoizedFunction = ((...x: never[]) => {
const hash = JSON.stringify(x);
if (cache.has(hash)) {
return cache.get(hash);
} else {
return fn(...x);
}
}) as F;

const memoizedCallableObject = Object.assign(memoizedFunction, {
clearCache: () => {
cache.clear();
}
});

memoizedFunctions.push(memoizedCallableObject);

return memoizedCallableObject;
};

export const clearCache = () => {
memoizedFunctions.forEach(memoizedFunction => {
memoizedFunction.clearCache();
});
}
7 changes: 6 additions & 1 deletion src/parser.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { encoder } from './unicode';
import { InputType, InputTypes, isTypedArray } from './inputTypes';
import { clearCache, memoize } from './cache';

// createParserState :: x -> s -> ParserState e a s
const createParserState = <D>(target: InputType, data: D | null = null): ParserState<null, string | null, D | null> => {
Expand Down Expand Up @@ -90,13 +91,15 @@ export class Parser<T, E = string, D = any> {
p: StateTransformerFunction<T, E, D>;

constructor(p: StateTransformerFunction<T, E, D>) {
this.p = p;
this.p = memoize(p);
}

// run :: Parser e a s ~> x -> Either e a
run(target: InputType): ResultType<T, E, D> {
const state = createParserState(target);

clearCache();

const resultState = this.p(state);

if (resultState.isError) {
Expand All @@ -123,6 +126,8 @@ export class Parser<T, E = string, D = any> {
const state = createParserState(target);
const newState = this.p(state);

clearCache();

if (newState.isError) {
return errorFn(newState.error, newState);
}
Expand Down