| 1 |
#include "Parser.ih" |
| 2 |
|
| 3 |
/* |
| 4 |
Lexical scanner returns a double floating point |
| 5 |
number on the stack and the token NUM, or the ASCII |
| 6 |
character read if not a number. Skips all blanks |
| 7 |
and tabs, returns 0 for EOF. |
| 8 |
*/ |
| 9 |
|
| 10 |
int Parser::lex() |
| 11 |
{ |
| 12 |
char c; |
| 13 |
// get the next non-ws character |
| 14 |
while (cin.get(c) && (c == ' ' || c == '\t')) |
| 15 |
; |
| 16 |
|
| 17 |
if (!cin) // no characters were obtained |
| 18 |
return 0; // indicate End Of Input |
| 19 |
|
| 20 |
if (c == '.' || isdigit (c)) // if a digit char was found |
| 21 |
{ |
| 22 |
cin.putback(c); // return the character |
| 23 |
cin >> d_val_.u_val; // extract a number |
| 24 |
return NUM; // return the NUM token |
| 25 |
} |
| 26 |
|
| 27 |
if (!isalpha(c)) // c doesn't start an identifier: |
| 28 |
return c; // return a single character token. |
| 29 |
|
| 30 |
// in all other cases, an ident is entered. Recognize a var or function |
| 31 |
|
| 32 |
string word; // store the name in a string object |
| 33 |
|
| 34 |
while (true) // process all alphanumerics: |
| 35 |
{ |
| 36 |
word += c; // add 'm to `word' |
| 37 |
if (!cin.get(c)) // no more chars? then done here |
| 38 |
break; |
| 39 |
|
| 40 |
if (!isalnum(c)) // not an alphanumeric: put it back and done. |
| 41 |
{ |
| 42 |
cin.putback(c); |
| 43 |
break; |
| 44 |
} |
| 45 |
} |
| 46 |
// Now lookup the name as a function's name |
| 47 |
unordered_map<string, double (*)(double)>::iterator function = |
| 48 |
s_functions.find(word); |
| 49 |
|
| 50 |
// Got it, so return FPTR |
| 51 |
if (function != s_functions.end()) |
| 52 |
{ |
| 53 |
d_val_.u_fun = function->second; |
| 54 |
return FNCT; |
| 55 |
} |
| 56 |
// no function, so return a VAR. Set |
| 57 |
// u_symbol to the symbol's address in the |
| 58 |
// d_symbol map. The map will add the |
| 59 |
// symbol if not yet there. |
| 60 |
d_val_.u_symbol = &d_symbols[word]; |
| 61 |
return VAR; |
| 62 |
} |