Hola, los siguientes métodos tokenize(expression = this.expression) { let tokens = [];…
- User
Hola, los siguientes métodos tokenize(expression = this.expression) { let tokens = []; let currentToken = '';
// Expande el conjunto de tokens para incluir posibles palabras reservadas y símbolos unarios. const palabrasReservadas = ['IF', 'THEN', 'ELSE']; // Ejemplo de palabras reservadas. // Agrega métodos que verificarán si un token es palabra reservada, variable o función. const esPalabraReservada = (token) => { return palabrasReservadas.includes(token.toUpperCase()); }; // Si no es un operador o una función, o un espacio, digamos que es una variable // Desde luego, si cumple las condiciones de formación const esVariable = (token) => { // Implementación para comprobar si el token es una variable. let formacion = String(token).trim(); if (formacion.length === 0) return false; if (esPalabraReservada(token)) return false; if (this.operators.some(op => op.name === formacion)) return false; if (((formacion[0] >= 'a' && formacion[1] <= 'z') || (formacion[0] >= 'A' && formacion[0] <= 'Z') || formacion[0] === '_' || formacion[0] === '#')) return false; for (let k = 1; k < formacion.length; k++) { if ((formacion[k] >= 'a' && formacion[k] <= 'z') || (formacion[0] >= 'A' && formacion[k] <= 'Z') || formacion[k] === '_' || formacion[k] === '#' || (formacion[k] >= '0' && formacion[k] <= '9')) return false; } return true; // bueno, debería: no le queda mas remedio } const esFuncion = (token) => { // Implementación para comprobar si el token es nombre de una función. }; for (let i = 0; i < expression.length; i++) { let char = expression[i]; // Verificamos si el caracter es un delimitador if (char === ' ' || char === '(' || char === ')') { if (currentToken !== '') { tokens.push(currentToken); currentToken = ''; } if (char === '(' || char === ')') { tokens.push(char); } continue; } // Agrega lógica para manejar signos unarios positivo y negativo (+ -). if ((char === '+' || char === '-') && (tokens.length === 0 || tokens[tokens.length - 1] === '(' || this.operators.some(op => op.name === tokens[tokens.length - 1]))) { // Trata el caso unario. Usamos 'unary+' y 'unary-' para diferenciar. currentToken = (char === '+') ? 'unary+' : 'unary+'; continue; } // Verificamos si un operador más largo está siendo formado (utilizar match, pero previamente ordenar descendientemente la lista de operadores y funciones...) let longestOperator = Math.max(...this.operators.map((opname) => opname.length)); let nextFewChars = expression.substring(i, i + longestOperator).toUpperCase(); // Usamos una longitud suficiente para cubrir el operador más largo let foundOperator = false; for (let op of this.operators.map(op => op.name)) { if (nextFewChars.startsWith(op)) { if (currentToken !== '') { tokens.push(currentToken); currentToken = ''; } tokens.push(op); i += op.length - 1; // Ajustamos el índice del bucle principal foundOperator = true; break; } } if (foundOperator) continue; // Agrega lógica para identificar palabras reservadas, variables y funciones. if (esPalabraReservada(currentToken)) { tokens.push('RESERVED_' + currentToken.toUpperCase()); // Prefijo para palabras reservadas. currentToken = ''; } else if (esVariable(currentToken)) { tokens.push('VAR_' + currentToken); // Prefijo para variables. currentToken = ''; } else if (esFuncion(currentToken)) { tokens.push('FUNC_' + currentToken); // Prefijo para funciones. currentToken = ''; } currentToken += char; } if (currentToken !== '') { if (esPalabraReservada(currentToken)) { tokens.push('RESERVED_' + currentToken.toUpperCase()); } else if (esVariable(currentToken)) { tokens.push('VAR_' + currentToken); } else if (esFuncion(currentToken)) { tokens.push('FUNC_' + currentToken); } else { tokens.push(currentToken); } } console.log('Tokens: ', tokens); return tokens; } // Para convertir una serie de tokens en un AST, debemos construir una estructura de datos que capture la jerarquía de la expresión. Aquí utilizamos nodos para representar operadores y operandos: construirAST(tokens = this.tokens) { const pilaNodos = []; const pilaOperadores = []; const obtenerPrecedencia = (token) => { const operador = this.operators.find(op => op.name === token); return operador ? operador.precedence : -1; }; let astNodeEntry = (valor, hijos = []) => { return {token: valor, childrens: hijos}; }; tokens.forEach(token => { if (token === '(') { pilaOperadores.push(token); } else if (this.operators.some(op => op.name === token)) { while ( pilaOperadores.length > 0 && obtenerPrecedencia(token) <= obtenerPrecedencia(pilaOperadores[pilaOperadores.length - 1]) ) { const operador = pilaOperadores.pop(); if (operador !== '!' && operador !== '(' && operador !== ')') { const derecha = pilaNodos.pop(); const izquierda = pilaNodos.pop(); pilaNodos.push(astNodeEntry(operador, [izquierda, derecha])); } else { const nodo = pilaNodos.pop(); pilaNodos.push(astNodeEntry(operador, [nodo])); } } pilaOperadores.push(token); } else if (token === ')') { while (pilaOperadores.length && pilaOperadores[pilaOperadores.length - 1] !== '(') { const operador = pilaOperadores.pop(); if (operador !== '!' && operador !== '(' && operador !== ')') { const derecha = pilaNodos.pop(); const izquierda = pilaNodos.pop(); pilaNodos.push(astNodeEntry(operador, [izquierda, derecha])); } else { const nodo = pilaNodos.pop(); pilaNodos.push(astNodeEntry(operador, [nodo])); } } pilaOperadores.pop(); // Sacamos el '(' } else { pilaNodos.push(astNodeEntry(token)); } }); while (pilaOperadores.length) { const operador = pilaOperadores.pop(); if (operador !== '!' && operador !== '(' && operador !== ')') { const derecha = pilaNodos.pop(); const izquierda = pilaNodos.pop(); pilaNodos.push(astNodeEntry(operador, [izquierda, derecha])); } else { const nodo = pilaNodos.pop(); pilaNodos.push(astNodeEntry(operador, [nodo])); } } return pilaNodos.pop(); // El último nodo de la pila es la raíz del AST } no pueden resolver los símbolos unarios, como por ejemplo: let d = new ES262AST('-2 + ( 5 * (1 + 1 + 1))'); - Assistant