parjs
Version:
Library for building parsers using combinators.
59 lines • 1.97 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.int = void 0;
const errors_1 = require("../../errors");
const utils_1 = require("../../utils");
const parser_1 = require("../parser");
const result_1 = require("../result");
const numeric_helpers_1 = require("./numeric-helpers");
const defaultOptions = {
allowSign: true,
base: 10
};
class Int extends parser_1.ParjserBase {
constructor(options, expecting) {
super();
this.options = options;
this.expecting = expecting;
this.type = "int";
}
_apply(ps) {
const { allowSign, base } = this.options;
let { position } = ps;
const { input } = ps;
const initPos = ps.position;
let sign = allowSign ? numeric_helpers_1.NumericHelpers.parseSign(ps) : 0;
let parsedSign = false;
if (sign !== 0) {
parsedSign = true;
}
else {
sign = 1;
}
position = ps.position;
numeric_helpers_1.NumericHelpers.parseDigitsInBase(ps, base);
const value = parseInt(input.substring(initPos, ps.position), base);
if (ps.position === position) {
ps.kind = parsedSign ? result_1.ResultKind.HardFail : result_1.ResultKind.SoftFail;
}
else {
ps.value = value;
ps.kind = result_1.ResultKind.Ok;
}
}
}
/**
* Returns a parser that will parse a single integer, with the options given by `options`.
*
* @param pOptions A set of options for parsing integers.
*/
function int(pOptions) {
const options = (0, utils_1.defaults)(pOptions, defaultOptions);
if (options.base > 36) {
throw new errors_1.ParserDefinitionError("int", "invalid base");
}
const expecting = `expecting a ${options.allowSign ? "signed" : "unsigned"} integer in base ${options.base}`;
return new Int(options, expecting);
}
exports.int = int;
//# sourceMappingURL=int.js.map