Skip to content

Commit

Permalink
Fix filter sometimes overwriting inner parser's expected values
Browse files Browse the repository at this point in the history
  • Loading branch information
bwrrp committed Mar 29, 2022
1 parent 48854f8 commit e890fb5
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
3 changes: 0 additions & 3 deletions src/parser-combinators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,9 +197,6 @@ export function filter<T>(
return (input, offset) => {
const res = parser(input, offset);
if (!res.success) {
if (res.offset === offset) {
return error(offset, expected);
}
return res;
}
if (!filter(res.value)) {
Expand Down
12 changes: 10 additions & 2 deletions test/parser-combinators.tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ describe('parser combinators', () => {
expect(res2.offset).toBe(3);
});

it('replaces the expected value for child errors only if the child fails at the same offset', () => {
it('retains the expected value for child errors if the inner parser fails', () => {
const parser = filter(
then(token('a'), token('b'), (a, b) => b + a),
() => true,
Expand All @@ -116,13 +116,21 @@ describe('parser combinators', () => {
const res1 = parser('bb', 0);
expect(res1.success).toBe(false);
expect(res1.offset).toBe(0);
expect((res1 as any).expected).toEqual(['expected']);
expect((res1 as any).expected).toEqual(['a']);

const res2 = parser('aa', 0);
expect(res2.success).toBe(false);
expect(res2.offset).toBe(1);
expect((res2 as any).expected).toEqual(['b']);
});

it('returns the given expected value if the filter rejects', () => {
const parser = filter(token('a'), (a) => false, ['expected']);
const res1 = parser('a', 0);
expect(res1.success).toBe(false);
expect(res1.offset).toBe(0);
expect((res1 as any).expected).toEqual(['expected']);
});
});

describe('or', () => {
Expand Down

0 comments on commit e890fb5

Please sign in to comment.