mirror of
https://github.com/usebruno/bruno.git
synced 2025-06-22 04:51:27 +02:00
feat: bru lang - simple parser
This commit is contained in:
parent
62a184c386
commit
104bd272f9
@ -10,6 +10,7 @@
|
|||||||
"test": "jest"
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"arcsecond": "^5.0.0"
|
"arcsecond": "^5.0.0",
|
||||||
|
"ohm-js": "^16.6.0"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
55
packages/bruno-lang/v2/src/index.js
Normal file
55
packages/bruno-lang/v2/src/index.js
Normal 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;
|
17
packages/bruno-lang/v2/tests/index.spec.js
Normal file
17
packages/bruno-lang/v2/tests/index.spec.js
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
Loading…
x
Reference in New Issue
Block a user