Skip to content

Commit

Permalink
feat(sexpr): add ParseError
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Sep 12, 2019
1 parent 1c152d3 commit 7998afe
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
3 changes: 2 additions & 1 deletion packages/sexpr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
},
"dependencies": {
"@thi.ng/api": "^6.3.3",
"@thi.ng/defmulti": "1.1.3"
"@thi.ng/defmulti": "1.1.3",
"@thi.ng/errors": "1.2.0"
},
"keywords": [
"DSL",
Expand Down
11 changes: 9 additions & 2 deletions packages/sexpr/src/parse.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assert } from "@thi.ng/api";
import { defError } from "@thi.ng/errors";
import {
DEFAULT_SYNTAX,
Expression,
Expand All @@ -7,6 +7,8 @@ import {
SyntaxOpts
} from "./api";

const ParseError = defError<string>((msg?) => msg || "Parser error", () => "");

export const parse = (tokens: Iterable<string>, opts?: Partial<SyntaxOpts>) => {
const { scopeOpen, scopeClose } = {
...DEFAULT_SYNTAX,
Expand All @@ -18,7 +20,9 @@ export const parse = (tokens: Iterable<string>, opts?: Partial<SyntaxOpts>) => {
tree.push({ type: "expr", value: t, children: [] });
} else if (scopeClose.indexOf(t) !== -1) {
// TODO check matching scope type
assert(tree.length > 1, "invalid nesting");
if (tree.length < 2) {
throw new ParseError(`unmatched '${t}'`);
}
(<Expression>tree[tree.length - 2]).children!.push(tree.pop()!);
} else {
let node: Node;
Expand All @@ -37,5 +41,8 @@ export const parse = (tokens: Iterable<string>, opts?: Partial<SyntaxOpts>) => {
(<Expression>tree[tree.length - 1]).children!.push(node);
}
}
if (tree.length > 1) {
throw new ParseError("invalid s-expression");
}
return <RootNode>tree[0];
};

0 comments on commit 7998afe

Please sign in to comment.