@multila/multila-parser-generator
Version:
An LR(1) Parser Generator written in TypeScript
111 lines • 3.04 kB
JavaScript
;
/*
MULTILA Compiler and Computer Architecture Infrastructure
Copyright (c) 2022 by Andreas Schwenk, contact@multila.org
Licensed by GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.LR1_RuleItem = exports.LR1_RuleItemType = exports.LR1_Rule = void 0;
/**
* production rule
*/
class LR1_Rule {
/**
* Creates a new rule.
* @param lhs non-terminal of the left-hand side of the rule
*/
constructor(lhs = '') {
/**
* index of the current rule
*/
this.index = -1;
/**
* ID of the non-terminal on the left-hand side
*/
this.lhs = '';
/**
* items of the right-hand side of the rule
*/
this.rhs = [];
/**
* (optional) identifier of a function that is called after reduction of rule.
*/
this.callBackId = '';
this.lhs = lhs;
}
/**
* Adds a new terminal item to the right-hand side of the rule.
* @param s 'INT' for integer constant, 'REAL' for real valued constant,
* 'HEX' for hexadecimal values, 'ID' for identifier', 'STR' for a string,
* ':TER' for a terminal (with TER an arbitrary string)
*/
addTerminalItem(s) {
const t = new LR1_RuleItem();
t.type = LR1_RuleItemType.Terminal;
t.value = s;
this.rhs.push(t);
}
/**
* Adds a new non-terminal item to the right-hand side of the rule.
* @param s identifier of the non-terminal
*/
addNonTerminalItem(s) {
const nt = new LR1_RuleItem();
nt.type = LR1_RuleItemType.NonTerminal;
nt.value = s;
this.rhs.push(nt);
}
/**
* Stringify rule.
* @param dotPos (optionally) writes '.' after the i-th item of the right-hand
* side of the rule
* @returns stringified rule
*/
toString(dotPos = -1) {
let s = this.lhs + ' = ';
for (let i = 0; i < this.rhs.length; i++) {
const item = this.rhs[i];
if (i == dotPos)
s += '. ';
s += item.toString() + ' ';
}
if (this.rhs.length == dotPos)
s += '. ';
s = s.trim();
s += ';';
return s;
}
}
exports.LR1_Rule = LR1_Rule;
/**
* type of rule items
*/
var LR1_RuleItemType;
(function (LR1_RuleItemType) {
LR1_RuleItemType["Terminal"] = "T";
LR1_RuleItemType["NonTerminal"] = "NT";
})(LR1_RuleItemType = exports.LR1_RuleItemType || (exports.LR1_RuleItemType = {}));
/**
* rule item
*/
class LR1_RuleItem {
constructor() {
/**
* value
*/
this.value = '';
}
/**
* Stringify item.
* @returns stringified item
*/
toString() {
let s = this.value;
if (this.type === LR1_RuleItemType.Terminal) {
s = '"' + s + '"';
}
return s;
}
}
exports.LR1_RuleItem = LR1_RuleItem;
//# sourceMappingURL=lr1rule.js.map