@cheap-glitch/jsonast
Version:
A JSON to AST parser which allows error recovery.
65 lines (64 loc) • 1.48 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CharacterStream = void 0;
class CharacterStream {
constructor(text) {
this._offset = 0;
this._line = 1;
this._column = 1;
this.text = text;
}
get ch() {
return this.text.charAt(this._offset);
}
get eoi() {
return this.text.length === this._offset;
}
get line() {
return this._line;
}
get column() {
return this._column;
}
get offset() {
return this._offset;
}
get pos() {
return {
line: this.line,
column: this.column,
char: this.offset,
};
}
expect(text) {
if (this.ch !== text) {
const ch = this.ch
.replace('\n', '\\n')
.replace('\r', '\\r')
.replace('\t', '\\t');
throw new Error(`Unexpected character '${ch}' at ${this.line}:${this.column}. Expected '${text}'`);
}
}
next() {
if (this.ch === '\n') {
this._column = 1;
this._line++;
}
else {
this._column++;
}
this._offset++;
}
accept(text) {
this.expect(text);
this.next();
}
skip(text) {
if (this.ch === text) {
this.next();
return true;
}
return false;
}
}
exports.CharacterStream = CharacterStream;