UNPKG

swift-pattern-compiler

Version:

A compiler which transforms SWIFT patterns to an object representation with additional information's.

84 lines 2.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const interfaces_1 = require("./interfaces"); const regExpFactory = (regExp) => (n) => regExp.test(n); const isNumber = regExpFactory(/[0-9]/); const isChar = regExpFactory(/[a-z]/); const isQuant = regExpFactory(/[!\-]/); const isMultilineQuant = regExpFactory(/[*]/); const isSign = regExpFactory(/[/:]/); const isBracket = regExpFactory(/[\[\]]/); const isParen = regExpFactory(/[()]/); const isNewline = regExpFactory(/\n/); const isConst = regExpFactory(/[A-Z]/); /** * The tokenizer accepts a SWIFT field pattern and returns an array of tokens. * * ``` * const tokens = tokenizer("35a"); * // => [{ type: "num", value: "35" }, { type: "char", value: "a" }] * ``` * * @param input the SWIFT field pattern string * @returns the tokens array */ exports.tokenizer = (input) => { const tokens = []; let current = 0; input = input || ""; while (current < input.length) { let char = input[current]; current++; if (isNumber(char)) { let value = char; char = input[current]; while (isNumber(char)) { value += char; char = input[++current]; } tokens.push({ type: interfaces_1.ETokenType.num, value }); continue; } if (isChar(char)) { tokens.push({ type: interfaces_1.ETokenType.char, value: char }); continue; } if (isQuant(char)) { tokens.push({ type: interfaces_1.ETokenType.quant, value: char }); continue; } if (isMultilineQuant(char)) { tokens.push({ type: interfaces_1.ETokenType.multilineQuant, value: char }); continue; } if (isSign(char)) { tokens.push({ type: interfaces_1.ETokenType.sign, value: char }); continue; } if (isBracket(char)) { tokens.push({ type: interfaces_1.ETokenType.bracket, value: char }); continue; } if (isParen(char)) { tokens.push({ type: interfaces_1.ETokenType.paren, value: char }); continue; } if (isNewline(char)) { tokens.push({ type: interfaces_1.ETokenType.newline, value: char }); continue; } if (isConst(char)) { let value = char; char = input[current]; while (isConst(char)) { value += char; char = input[++current]; } tokens.push({ type: interfaces_1.ETokenType.const, value }); continue; } throw new Error(`Unmatched character "${char}"`); } return tokens; }; //# sourceMappingURL=tokenizer.js.map