twing
Version:
First-class Twig engine for Node.js
80 lines (79 loc) • 2.79 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.createLexer = exports.TwingLexer = exports.typeToEnglish = void 0;
/**
* Lexes a template string.
*/
const twig_lexer_1 = require("twig-lexer");
const token_stream_1 = require("./token-stream");
const parsing_1 = require("./error/parsing");
const typeToEnglish = (type) => {
switch (type) {
case "EOF":
return 'end of template';
case "TEXT":
return 'text';
case "TAG_START":
return 'begin of statement block';
case "VARIABLE_START":
return 'begin of print statement';
case "TAG_END":
return 'end of statement block';
case "VARIABLE_END":
return 'end of print statement';
case "NAME":
return 'name';
case "NUMBER":
return 'number';
case "STRING":
return 'string';
case "OPERATOR":
return 'operator';
case "PUNCTUATION":
return 'punctuation';
case "INTERPOLATION_START":
return 'begin of string interpolation';
case "INTERPOLATION_END":
return 'end of string interpolation';
case "COMMENT_START":
return 'begin of comment statement';
case "COMMENT_END":
return 'end of comment statement';
case "ARROW":
return 'arrow function';
case "SPREAD_OPERATOR":
return 'spread operator';
default:
throw new Error(`Token of type "${type}" does not exist.`);
}
};
exports.typeToEnglish = typeToEnglish;
class TwingLexer extends twig_lexer_1.Lexer {
constructor(level, binaryOperators, unaryOperators) {
super(level);
// custom operators
for (const operators of [binaryOperators, unaryOperators]) {
for (const { name } of operators) {
if (!this.operators.includes(name)) {
this.operators.push(name);
}
}
}
}
tokenizeSource(source) {
try {
const tokens = this.tokenize(source.code);
return (0, token_stream_1.createTokenStream)(tokens, source);
}
catch (error) {
const { message, line, column } = error;
throw (0, parsing_1.createParsingError)(message, { line, column }, source, error);
}
}
}
exports.TwingLexer = TwingLexer;
const createLexer = (level, binaryOperators, unaryOperators) => {
const keepCompatibleOperator = (operator) => operator.specificationLevel <= level;
return new TwingLexer(level, binaryOperators.filter(keepCompatibleOperator), unaryOperators.filter(keepCompatibleOperator));
};
exports.createLexer = createLexer;