mirror of
https://github.com/vale981/tridactyl
synced 2025-03-08 19:01:40 -05:00

- Add and build grammars - Add to content.ts for interactive use - Add tests - Change bracketExpr parser - Improve comments - Apply prettier
42 lines
1.1 KiB
TypeScript
42 lines
1.1 KiB
TypeScript
import * as nearley from "nearley"
|
|
|
|
/** Friendlier interface around nearley parsers */
|
|
export class Parser {
|
|
private parser
|
|
private initial_state
|
|
/* public results */
|
|
|
|
constructor(grammar) {
|
|
this.parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar))
|
|
this.initial_state = this.parser.save()
|
|
/* this.results = this.parser.results */
|
|
}
|
|
|
|
feedUntilError(input) {
|
|
let lastResult = undefined
|
|
let consumedIndex = 0
|
|
try {
|
|
for (let val of input) {
|
|
this.parser.feed(val)
|
|
lastResult = this.parser.results[0]
|
|
consumedIndex++
|
|
}
|
|
} catch (e) {
|
|
} finally {
|
|
this.reset()
|
|
if (lastResult === undefined) {
|
|
throw "Error: no result!"
|
|
} else {
|
|
return [lastResult, input.slice(consumedIndex)]
|
|
}
|
|
}
|
|
}
|
|
|
|
private reset() {
|
|
this.parser.restore(this.initial_state)
|
|
}
|
|
|
|
/* feed(input) { */
|
|
/* return this.parser.feed(input) */
|
|
/* } */
|
|
}
|