Skip to content

Commit

Permalink
add S-expression example
Browse files Browse the repository at this point in the history
  • Loading branch information
uzmoi committed Jan 16, 2024
1 parent ae4e139 commit 45bb850
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
22 changes: 22 additions & 0 deletions examples/s-expression.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, expect, test } from "@jest/globals";
import { EOI } from "../src";
import { SExpression } from "./s-expression";

describe("S-expression", () => {
test("Hello world!", () => {
const source = '(print "Hello world!")';
expect(SExpression.skip(EOI).parse(source)).toEqual({
success: true,
index: expect.any(Number),
value: ["print", '"Hello world!"'],
});
});
test("quote list", () => {
const source = "'(1 2 3 4)";
expect(SExpression.skip(EOI).parse(source)).toEqual({
success: true,
index: expect.any(Number),
value: ["quote", "1", "2", "3", "4"],
});
});
});
16 changes: 16 additions & 0 deletions examples/s-expression.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { type Parser, choice, el, lazy, many, regex } from "../src";

export type SExpression = string | readonly SExpression[];

const list = lazy(() => SExpression)
.apply(many)
.between(el("("), el(")"));

export const SExpression: Parser<SExpression, string> = choice([
el("'")
.option()
.and(list)
.map(([quote, list]) => (quote ? ["quote", ...list] : list)),
regex(/"([^"]|\\.)*"/),

Check failure

Code scanning / CodeQL

Inefficient regular expression High

This part of the regular expression may cause exponential backtracking on strings starting with '"' and containing many repetitions of '\!'.
regex(/[^\s()"]+/),
]).between(regex(/\s*/));

0 comments on commit 45bb850

Please sign in to comment.