Below is the complete Context Free Grammar for the Calc language. PROG is the st
ID: 3580408 • Letter: B
Question
Below is the complete Context Free Grammar for the Calc language. PROG is the start symbol.
PROG STMT EOS PROG
PROG
STMT DIRECT_STMT | IF | 'dump' DIRECT_STMT EXPR | ASSIGN
EOS '!' EOS | '!'
ASSIGN id '=' EXPR
IF 'if' COMP '<<<' DIRECT_STMT '>>>' EXPR '(' EXPR ')' | EXPR MATH VAL | VAL COMP EXPR OP EXPR
MATH '+' | '-' | '/' | '*'
VAL id | num
OP '<' | '>' | '==' | '<>'
Develop an interactive calculator (stdin for input stream) based on the the grammar above using Flex to generate the lexer and Lemon to generate the parser. In the interest of time, we'll assume only valid programs will be entered. For invalid programs, the expected behavior is undefined. Identifier tokens (id) are the same as C style identifiers… a letter followed by 0 or more letters, digits, and/or underscores. Numbers (num) are unsigned positive integers (>=0) formed as one or more decimal digits. The expected performance follows:
1. EXPR statements print their result to the console on a line by itself.
2. ASSIGN statements store expression values with identifiers, replacing old values if a previously assigned identifier is the destination of an assignment.
3. The 'dump' statement prints all identifiers and their current values
4. The DIRECT_STMT of an IF statement should only execute if the COMP condition of the IF evaluates true. In that case, an EXPR for the DIRECT_STMT will have its value printed, and an ASSIGN statement will store the result in the identifier. If the COMP evaluates falsely and the ASSIGN DIRECT_STMT would create a new identifier, the identifier is not created. In that same situation, existing identifiers do not have their values changed.
Develop your solution incrementally. The last thing you should try to get working is IF statements that perform ASSIGNs when true. A ready to go lexer file and token files are given below to work from
Explanation / Answer
#include<stdio.h>
2: #include<string.h>
3: int main()
4: {
5: char gram[20],part1[20],part2[20],modifiedGram[20],newGram[20],tempGram[20];
6: int i,j=0,k=0,l=0,pos;
7: printf("Enter Production : A->");
8: gets(gram);
9: for(i=0;gram[i]!='|';i++,j++)
10: part1[j]=gram[i];
11: part1[j]='';
12: for(j=++i,i=0;gram[j]!='';j++,i++)
13: part2[i]=gram[j];
14: part2[i]='';
15: for(i=0;i<strlen(part1)||i<strlen(part2);i++)
16: {
17: if(part1[i]==part2[i])
18: {
19: modifiedGram[k]=part1[i];
20: k++;
21: pos=i+1;
22: }
23: }
24: for(i=pos,j=0;part1[i]!='';i++,j++){
25: newGram[j]=part1[i];
26: }
27: newGram[j++]='|';
28: for(i=pos;part2[i]!='';i++,j++){
29: newGram[j]=part2[i];
30: }
31: modifiedGram[k]='X';
32: modifiedGram[++k]='';
33: newGram[j]='';
34: printf(" A->%s",modifiedGram);
35: printf(" X->%s ",newGram);
36: }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.