feat: bru lang - simple parser

This commit is contained in:
Anoop M D 2023-02-03 04:39:45 +05:30
parent 62a184c386
commit 104bd272f9
3 changed files with 74 additions and 1 deletions

View File

@ -10,6 +10,7 @@
"test": "jest"
},
"dependencies": {
"arcsecond": "^5.0.0"
"arcsecond": "^5.0.0",
"ohm-js": "^16.6.0"
}
}

View File

@ -0,0 +1,55 @@
const ohm = require("ohm-js");
const grammar = ohm.grammar(`Bru {
Headers = "headers" "{" PairList "}"
PairList = Pair ("," Pair)*
Pair = Key ":" Value
Key = identifier
Value = stringLiteral
identifier = alnum*
stringLiteral = letter*
}`);
const sem = grammar.createSemantics().addAttribute('ast', {
Headers(_, _1, PairList, _2) {
return PairList.ast;
},
PairList(pairs, _, rest) {
return [pairs.ast, ...rest.ast];
},
Pair(key, _, value) {
return { key: key.ast, value: value.ast };
},
Key(id) {
return id.sourceString;
},
Value(str) {
return str.sourceString;
},
identifier(id) {
return id.sourceString;
},
stringLiteral(str) {
return str.sourceString;
},
_iter(...elements) {
return elements.map(e => e.ast);
}
});
const input = `headers {
hello: world,
foo: bar
}`;
const parser = (input) => {
const match = grammar.match(input);
if(match.succeeded()) {
return sem(match).ast;
} else {
throw new Error(match.message);
}
}
module.exports = parser;

View File

@ -0,0 +1,17 @@
const parser = require("../src/index");
describe("parser", () => {
it("should parse headers", () => {
const input = `headers {
hello: world,
foo: bar
}`;
const expected = [
{ key: "hello", value: "world" },
{ key: "foo", value: "bar" }
];
expect(parser(input)).toEqual(expected);
});
});