sucrase
Version:
Super-fast alternative to Babel for when you can target modern JS runtimes
91 lines (90 loc) • 2.74 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class TokenProcessor {
constructor(code, tokens) {
this.code = code;
this.tokens = tokens;
this.resultCode = '';
this.tokenIndex = 0;
}
reset() {
this.resultCode = '';
this.tokenIndex = 0;
}
matchesAtIndex(index, tagLabels) {
if (index < 0) {
return false;
}
for (let i = 0; i < tagLabels.length; i++) {
if (index + i >= this.tokens.length) {
return false;
}
if (this.tokens[index + i].type.label !== tagLabels[i]) {
return false;
}
}
return true;
}
matchesNameAtIndex(index, name) {
return this.matchesAtIndex(index, ['name']) && this.tokens[index].value === name;
}
matches(tagLabels) {
return this.matchesAtIndex(this.tokenIndex, tagLabels);
}
matchesName(name) {
return this.matchesNameAtIndex(this.tokenIndex, name);
}
previousWhitespace() {
return this.code.slice(this.tokenIndex > 0
? this.tokens[this.tokenIndex - 1].end
: 0, this.tokens[this.tokenIndex].start);
}
replaceToken(newCode) {
this.resultCode += this.previousWhitespace();
this.resultCode += newCode;
this.tokenIndex++;
}
replaceTokenTrimmingLeftWhitespace(newCode) {
this.resultCode += this.previousWhitespace().replace(/[\t ]/g, '');
this.resultCode += newCode;
this.tokenIndex++;
}
removeInitialToken() {
this.replaceToken('');
}
removeToken() {
this.replaceTokenTrimmingLeftWhitespace('');
}
copyExpectedToken(label) {
if (this.tokens[this.tokenIndex].type.label !== label) {
throw new Error(`Expected token ${label}`);
}
this.copyToken();
}
copyToken() {
this.resultCode += this.code.slice(this.tokenIndex > 0
? this.tokens[this.tokenIndex - 1].end
: 0, this.tokens[this.tokenIndex].end);
this.tokenIndex++;
}
appendCode(code) {
this.resultCode += code;
}
currentToken() {
return this.tokens[this.tokenIndex];
}
currentIndex() {
return this.tokenIndex;
}
finish() {
if (this.tokenIndex !== this.tokens.length) {
throw new Error('Tried to finish processing tokens before reaching the end.');
}
this.resultCode += this.code.slice(this.tokens[this.tokens.length - 1].end);
return this.resultCode;
}
isAtEnd() {
return this.tokenIndex === this.tokens.length;
}
}
exports.default = TokenProcessor;