cbon
Version:
Common Bracket Object Notation
76 lines (75 loc) • 2.75 kB
JavaScript
import { parser as raw_parser } from "./parser";
import { toJsObj } from "./toJsObj";
import { getErrorsMsgs } from "./utils";
import { tokenizer } from "./tokenizer";
import { WhenError } from "./state_machine";
import { AlwaysFalse } from "./canceller";
export * from './stringify';
export function parser(code, config) {
var _a, _b, _c, _d, _e, _f, _g;
const cancel = (_b = (_a = config) === null || _a === void 0 ? void 0 : _a.cancel, (_b !== null && _b !== void 0 ? _b : AlwaysFalse));
const show_all_err = (_d = (_c = config) === null || _c === void 0 ? void 0 : _c.show_all_err, (_d !== null && _d !== void 0 ? _d : false));
const async = (_f = (_e = config) === null || _e === void 0 ? void 0 : _e.async, (_f !== null && _f !== void 0 ? _f : false));
let isCancel = false;
const errmsg = [];
let root;
function* main(cancel) {
var _a, _b;
try {
const r = yield raw_parser(yield tokenizer(code, {
show_all_err,
iterable: true,
async,
cancel
}), {
show_all_err,
async,
cancel
});
if (r.err != null) {
errmsg.push(...getErrorsMsgs(r.err));
}
root = r.val;
}
catch (e) {
if (e instanceof WhenError) {
errmsg.push(e.err.msg);
}
else
throw e;
}
if (errmsg.length !== 0) {
throw new SyntaxError(`\n ${errmsg.join('\n ')}\n`);
}
if (yield /** is cancel */)
return null;
const o = yield toJsObj(root, { async });
if (_b = (_a = config) === null || _a === void 0 ? void 0 : _a.alwaysDocs, (_b !== null && _b !== void 0 ? _b : false))
return o;
if (o.length == 1) {
return o[0];
}
else
return o;
}
const def = ((_g = config) === null || _g === void 0 ? void 0 : _g.async) ? async function () {
async function Cancel() {
if (!isCancel)
isCancel = await cancel();
return isCancel;
}
const g = main(Cancel);
g.next(await g.next(await g.next().value).value);
return g.next(await g.next(await Cancel()).value).value;
} : function () {
function Cancel() {
if (!isCancel)
isCancel = cancel();
return isCancel;
}
const g = main(Cancel);
g.next(g.next(g.next().value).value);
return g.next(g.next(Cancel()).value).value;
};
return def();
}