1.1 Will the calculator accept a line that contains only a comment? Why not? Would it be easier to fix this in the scanner or in the parser?
The program before will not accept a line that contains only a comment. Add “calclist EOL” to “calclist”, (parser), is easier to fix this
// fbcal.y
calclist:
| calclist exp EOL { printf("= %d\n", $2);}
| calclist EOL { printf("= 0\n"); }
;
1.2 Make the calculator into a hex calculator that accepts both hex and decimal num- bers. In the scanner add a pattern such as 0x[a-f0-9]+ to match a hex number, and in the action code use strtol to convert the string to a number that you store in yylval; then return a NUMBER token. Adjust the output printf to print the result in both decimal and hex.
Using sscanf() to convert Hexadecimal number to decimal. and using %x to print Hexadecimal number
// fbcal.l
0x[A-Fa-f0-9]+ { sscanf(yytext,"%i",&yylval); return NUMBER; }
// fbcal.y
calclist exp EOL { printf("= %d or 0x%x\n", $2, $2);}
1.3 (extra credit) Add bit operators such as AND and OR to the calculator. The obvious operator to use for OR is a vertical bar, but that’s already the unary absolute value operator. What happens if you also use it as a binary OR operator, for example, exp ABS factor?
// fbcal.l
"&" { return AND; }
"|" { return OR; }
// fbcal.y
factor: ter { $$ = $1; }
| factor MUL ter { $$ = $1 * $3; }
| factor DIV ter { $$ = $1 / $3; }
;
ter: term
| ter AND term {$$ = $1 & $3; }
| ter OR term { $$ = $1 | $3; }
;
term: NUMBER { $$ = $1; }
| OR term { $$ = $2 >= 0 ? $2 : -$2; }
| OP exp CP { $$ = $2; }
;
1.4 Does the handwritten version of the scanner from Example 1-4 recognize exactly the same tokens as the flex version?
This part is not exactly same, yylval might overflow
if (isdigit(c)) {
int i = c - '0';
while( isdigit(c = getc(yyin)))
i = (10*i) + c-'0';
yylval = i;
}
1.5 Can you think of languages for which flex wouldn’t be a good tool to write a scanner?
I searched on the internet. Flex is not a good tool to scan these languages that ambiguous, such as c++ and javascript
1.6 Rewrite the word count program in C. Run some large files through both versions. Is the C version noticeably faster? How much harder was it to debug?
#include <stdio.h>
int main(int argc, char **argv) {
int chars = 0;
int words = 0;
int lines = 0;
int inword = 0;
char s[] = "The boy stood on the burning deck\n shelling peanuts by the peck\n";
for( int i = 0; s[i] != '\0'; ++i) {
chars++;
if (('a'<=s[i] && s[i]<='z') || ('A'<=s[i] && s[i]<='Z')) {
if (!inword) {
inword = 1;
words++;
}
} else {
inword = 0;
}
if (s[i] == '\n') lines++;
}
printf("%8d%8d%8d\n", lines, words, chars);
return 0;
}