UNPKG

propositional

Version:

Propositional logic symbolic computation library

85 lines (84 loc) 2.63 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.tokenise = void 0; const token_1 = require("./token"); function isLetter(c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } function tokenise(source) { let tokens = []; let current = 0; // Current token let start = 0; // Start of current lexeme const advance = () => source[current++]; const match = (char) => { if (current > source.length || source[current] != char) return false; current++; return true; }; // const peek = (n = 0) => { // if (current + n > source.length) return '\0'; // return source[current + n]; // } const addToken = (type, lexeme = source.substring(start, current)) => { tokens.push(new token_1.Token(type, lexeme)); }; while (current < source.length) { // Beginning of current lexeme start = current; let char = advance(); switch (char) { // parentheses case '(': addToken(token_1.TokenType.PAREN_L); break; case ')': addToken(token_1.TokenType.PAREN_R); break; // logical operators case '!': addToken(token_1.TokenType.NOT); break; case '|': addToken(token_1.TokenType.OR); break; case '&': addToken(token_1.TokenType.AND); break; case '^': addToken(token_1.TokenType.XOR); break; case '=': if (match('>')) { addToken(token_1.TokenType.IF); break; } throw Error('expected > after ='); case '<': if (match('=') && match('>')) { addToken(token_1.TokenType.IFF); break; } throw Error('expected => after <'); // constants case '0': case '1': addToken(token_1.TokenType.CONSTANT); break; // ignore case ' ': case '\t': case '\r': case '\n': break; default: if (isLetter(char)) { addToken(token_1.TokenType.VARIABLE); break; } throw Error('Unexpected character ' + char); } } return tokens; } exports.tokenise = tokenise;