jaycc
Version:
### the Javascript C Compiler
113 lines (112 loc) • 3.32 kB
JavaScript
// Regular EXception
let QM;
let Star;
let $;
let $$;
QM = Symbol();
Star = Symbol();
$ = Symbol();
$$ = Symbol();
export { QM, Star, $, $$ };
let wildcard;
wildcard = (x) => ((x == QM)
|| (x == Star)
|| (x == $)
|| (x == $$));
export class REX {
es;
caps;
capidx;
capturing;
equality;
constructor(input, eq) {
// add sanity checks
this.es = input;
this.caps = [];
this.capidx = null;
this.capturing = false;
this.equality = eq;
}
match(xs) {
return this.match_(xs, []);
}
match_(xs, cap_) {
let x;
let e;
let cap;
cap = cap_;
// console.log('-- xs=', xs);
// console.log('-- cap=', cap);
x = xs.shift()
|| null;
e = this.es.shift()
|| null;
if (!x)
if (!this.es.length)
return true;
else
return false;
else if (!e)
return false;
if ((this.capidx !== null) && (this.capturing)) {
// console.log(' * adding cap ', x, 'e=', e, 'x=', x);
cap = cap.concat([x]);
}
if (!wildcard(e)) {
if (this.equality(e, x))
return this.match_(xs, cap);
else
return false;
}
else {
switch (e) {
case QM:
// console.log('[?]');
return this.match_(xs, cap);
break;
case Star:
// console.log('[*]');
if ((this.es[0] == x))
void 0;
else if ((wildcard(this.es[0])
&& (this.equality(this.es[1], x)))) {
if (this.es[0] == $$) {
cap.pop();
if (this.capidx === null)
throw "Syntax error";
this.caps[this.capidx] = cap;
this.capturing = false;
this.es.shift();
return this.match_(xs, []);
}
this.es.shift() &&
this.match_(xs, cap);
}
else
this.es = [e].concat(this.es);
return this.match_(xs, cap);
break;
case $:
// console.log('[$]');
if (this.capidx === null)
this.capidx = 0;
else
this.capidx++;
this.capturing = true;
return this.match_([x].concat(xs), []);
break;
case $$:
console.log('[$$]');
if (this.capidx === null)
throw "Syntax error";
cap.pop();
this.caps[this.capidx] = cap;
this.capturing = false;
// console.log(' cap=', cap);
return this.match_([x].concat(xs), []);
break;
}
}
return false;
}
}