Skip to content

Commit

Permalink
feat(sexpr): add support for line comments, fix tokenize
Browse files Browse the repository at this point in the history
- update SyntaxOpts
- fix/update tokenize() to emit
  • Loading branch information
postspectacular committed Sep 12, 2023
1 parent 20e1baf commit d3e708e
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 1 deletion.
6 changes: 6 additions & 0 deletions packages/sexpr/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export interface SyntaxOpts {
* Default: `"`
*/
string: string;
/**
* Single character string for comments (always active until next line break)
* Default: `;`
*/
comment: string;
}

export interface Token {
Expand Down Expand Up @@ -107,4 +112,5 @@ export const DEFAULT_SYNTAX: SyntaxOpts = {
scopes: [["(", ")"]],
whiteSpace: /(\s|,)/,
string: '"',
comment: ";",
};
9 changes: 8 additions & 1 deletion packages/sexpr/src/tokenize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export function* tokenize(
scopes: rawScopes,
whiteSpace,
string,
comment,
} = {
...DEFAULT_SYNTAX,
...opts,
Expand All @@ -29,6 +30,7 @@ export function* tokenize(
.join("");
let token = "";
let isString = false;
let isComment = false;
let tokenLine = 0;
let tokenCol = 0;
let line = 0;
Expand All @@ -45,7 +47,9 @@ export function* tokenize(
} else {
col++;
}
if (!isString) {
if (isComment) {
if (c === "\n") isComment = false;
} else if (!isString) {
if (whiteSpace.test(c)) {
token && (yield $(token));
token = "";
Expand All @@ -62,6 +66,8 @@ export function* tokenize(
tokenCol = col;
token = '"';
isString = true;
} else if (c === comment) {
isComment = true;
} else {
if (!token) {
tokenLine = line;
Expand All @@ -78,4 +84,5 @@ export function* tokenize(
token += c;
}
}
token && (yield $(token));
}
36 changes: 36 additions & 0 deletions packages/sexpr/test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,17 @@ group("sexpr", {
});
},

"non-expression root": () => {
assert.deepStrictEqual(parse("x"), {
type: "root",
children: [{ type: "sym", value: "x" }],
});
assert.deepStrictEqual(parse("23"), {
type: "root",
children: [{ type: "num", value: 23 }],
});
},

"custom syntax": () => {
const syntax: Partial<SyntaxOpts> = {
scopes: [
Expand Down Expand Up @@ -149,4 +160,29 @@ group("sexpr", {
"missing fn in env": () => {
assert.throws(() => $eval("(foo)"));
},

"line comment": () => {
assert.deepStrictEqual(
parse(`
; intro
(def x ; ignore me
; line 2
; line 3
23)`),
{
type: "root",
children: [
{
type: "expr",
value: "(",
children: [
{ type: "sym", value: "def" },
{ type: "sym", value: "x" },
{ type: "num", value: 23 },
],
},
],
}
);
},
});

0 comments on commit d3e708e

Please sign in to comment.