import { Token } from "../types/Token"; import { findRoot } from '.'; /** * Parses a body of text (i.e a line) into individual symbols with their respective (assumed) types */ export function parseTokens( body: string ): Token[] { const words = body.match(/\w+|\[(.*?)\]|"[^"]+"/g) as RegExpMatchArray; let tokens = []; for( let i=0; i < words.length; i++ ) { const word = words[ i ]; let found = false; for( let l=words.length; l > i; l-- ) { const symbol = words.slice( i, l ).join( ' ' ); const vocab = findRoot(symbol); if( vocab ) { tokens.push( vocab ); i += (l - i) - 1; //Advance the first iterator past this point found = true; break; } } if( !found ) { tokens.push( { group: 'custom', section: isEncapsulatedWith( word, '"' ) ? 'string' : isEncapsulatedWith( word, '[', ']' ) ? 'binding' : undefined, key: word, original: word } ); } } tokens = tokens.map( symbol => ( { ...symbol, key: symbol.section === 'string' ? symbol.key.replace(/"/g, '') : symbol.key.replace(/"/g, '').trim() } ) ) as Token[]; return tokens; } function isEncapsulatedWith( str: string, char: string, char2?: string ) { return str.indexOf( char ) === 0 && str.lastIndexOf( char2 || char ) === str.length - 1; }