compiler programs
Post on 04-Apr-2018
217 Views
Preview:
TRANSCRIPT
-
7/29/2019 Compiler Programs
1/35
VIVEKANANDA INSTITUTE OF TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE AND ENGG.
COMPILER DESIGN LAB
LIST OF EXPERIMENTS:
1. Implementation of token separation.
2. Implementation of symbol table.
3. Implementation of Lexical Analysis in C
4. Implementation of Lexical Analysis in LEX
5. Implementation of Syntax checking using LEX and YAC
6. Implementation of Syntax checking in C
7. Conversion of Infix to postfix.
8. Evaluating postfix expression using LEX
9. Implementation of Intermediate code Generator.
10. Implementation of Operator precedence parser
1. TOKEN SEPARATION
AIM:To write a program to implement the token separation operation
AlGORITHM:
Step 1: Start the program.
Step 2: Store the possible keywords in an array key[][] and their corresponding byte valuein b[].Step 3: Declare all the variables.Step 4: Declare the file pointer fp for file operation.Step 5: Open a file sym.c in write mode.Step 6: Enter valid data into sym.c file until # symbol encountered. Then close the file.Step 7: Open d.c file in read mode.Read the character one by one.
-
7/29/2019 Compiler Programs
2/35
Step 8: If not End of file using switch case check for special symbols.Print the specialsymbol.Step 9: Check whether the string is alphabet or alphanumeric using isalpha() andisalnum() functions.Step 10: If the string is alphabet assign it to variable a and compare with keywords in
array using strcmp() function.Step 11: If string is keyword print the keyword and its corresponding byte value and copythe string to variabledata using strcpy ().Step 12: Else copy to variable sym.Step 13: Check for the character is constant value using isdigti() function and copy theconstant in the variable val using strcpy().Step 14: Print all the datatype, identifier and constant value.Step 15: Stop the program.
PROGRAM:
#include#include#includechar key[5][10]={"int","float","char","double"};int b[5]={2,1,4,8};int main(){
int byte;int label;int i,j,n,k=0;char data[10],sym[10],val[10];
char a[20];char str;FILE *fp;clrscr();fp=fopen("sym.c","w");printf("\n enter a valid declarations:");while((str=getchar())!='#'){
fputc(str,fp);}fclose(fp);
fp=fopen("d.c","r");printf("\n______________________________________");printf("\t\t SYMBOL TABLE\n");printf("\n________________________________________");printf("\ndata-type\tidentifier\tvalue\tbytes-occupied\n");while((str=fgetc(fp))!=EOF){
i=0;
-
7/29/2019 Compiler Programs
3/35
label=0;switch(str){
case ';':printf("\n\t%d\t%c\t a special symbol",n++,str);
break;
default:if(isalpha(str)){do{
a[i]=str;i++;str=fgetc(fp);
}while(isalpha(str)||isalnum(str));a[i]='\0';
fseek(fp,-1,1);for(i=0;i
-
7/29/2019 Compiler Programs
4/35
do{a[i]=str;i++;str=fgetc(fp);
}while(isdigit(str)||str=='.'||isalpha(str));
a[i]='\0';fseek(fp,-1,1);strcpy(val,a);
}}
}fclose(fp);getch();
}
OUTPUT:
enter a valid data:
void main()
{
int a=5;
}
#
TOKEN SEPARATION
token no. token name token-type
1 void a keyword
2 main a keyword
3 ( a special symbol
4 ) a special symbol
5 { a special symbol
6 int a keyword
7 a an identifier
8 = an operator
9 5 a constant
10 ; a special symbol
11 } a special symbol
RESULT:
Thus the program was implemented and verified.
-
7/29/2019 Compiler Programs
5/35
2. SYMBOL TABLE
AIM:To write a program to implement the Symbol table operation
AlGORITHM:
Step 1: Start the program.Step 2: Store the possible keywords in an array key [][] and their corresponding bytevalue in b[].Step 3: Declare all the variables.Step 4: Declare the file pointer fp for file operations.Step 5: Open d.c file in write mode and enter the valid data with # symbol at the end of
file.Then close the file.Step 6:Open d.c in read mode.Read the character one by one.Step 7: If not end of file, using switch case display the character is special symbol or anoperator.Step 8: Check whether the string is alphabet or alphanumeric using isalpha () andisalnum() functions respectively.Step 9: If the string is alphabet assign it to variable a and compare with the keywords inarray using strcmp () function.Step 10: Then print keyword and its corresponding byte value and copy string to variabledata using strcpy ().Step 11: Else copy to variable sym .
Step 12: Check the string is alphabet or digit using isdigit() and isalpha() functions.Step 13: If the string is digit then print the string is constant.Step 14: Take fp to the assigned position.Step 15: Close fp.Step 16: Stop the program.
PROGRAM:
#include#include
#includechar key[5][10]={"int","float","char","double"};int b[5]={2,4,1,8};int main(){ int byte;
int label;int i,j,n,k=0;char data[10],sym[10],val[10];
-
7/29/2019 Compiler Programs
6/35
char a[20];char str;FILE *fp;clrscr();fp=fopen("sym.c","w");
printf("\n enter a valid declarations:");while((str=getchar())!='#'){
fputc(str,fp);}fclose(fp);fp=fopen("sym.c","r");printf("\n______________________________________");printf("\n\t\t SYMBOL TABLE\n");printf("\n________________________________________");printf("\ndata-type\tidentifier\tvalue\tbytes-occupied\n");
while((str=fgetc(fp))!=EOF){i=0;label=0;switch(str){
case ';':printf("\n%s\t\t%s\t\t%s\t\t%d",data,sym,val,byte);break;
default:if(isalpha(str)){do{
a[i]=str;i++;str=fgetc(fp);
}while(isalpha(str)||isalnum(str));a[i]='\0';fseek(fp,-1,1);for(i=0;i
-
7/29/2019 Compiler Programs
7/35
}if(label==0){
strcpy(sym,a);}
}
else if(str=='='){
str=fgetc(fp);if(str=='\'')
str=fgetc(fp);goto aa;
}elseaa:
if(isdigit(str)||isalpha(str)){do{
a[i]=str;i++;str=fgetc(fp);
}while(isdigit(str)||str=='.'||isalpha(str));a[i]='\0';fseek(fp,-1,1);strcpy(val,a);
}}
}fclose(fp);getch();
}
OUTPUT:
enter a valid declarations:int a=5;float f=3.4;double d=6.7;char c='f';#
-
7/29/2019 Compiler Programs
8/35
______________________________________SYMBOL TABLE
________________________________________
data-type identifier value bytes-occupied
int a 5 2float f 3.4 4double d 6.7 8char c f 1
RESULT:
Thus the program was implemented and verified.
-
7/29/2019 Compiler Programs
9/35
3. LEXICAL ANALYSIS USING C
AIM:
To write a program to implement the Lexical analysis using C
AlGORITHM:
Step 1: Start the program.Step 2: Include the necessary header files.Step 3: The ctype header file is to load the file with predicate isdigit.Step 4: The define header file defines the buffer size, numerics, assignmentoperator,relational operator.Step 5: Initialize the necessary variables.
Step 6: To return index of new string S,token t using insert() function.Step 7: Initialize the length for every string.Step 8: Check the necessary condition.Step 9: Call the initialize() function.This function loads the keywords into the symboltable.Step 10: Check the conditions such as white spaces,digits,letters and alphanumerics.Step 11: To return index of the entry for string S,or 0 if S is not found using lookup()function.Step 12: Check this until EOF is found.Step 13: Otherwise initialize the token value to be none.Step 14: In the main function if lookahead equals numeric then the value of attribute num
is given by the global variable tokenval.Step 15: Check the necessary conditions such as arithmetic operators, parenthesis,identifiers, assignment operators and relational operators.Step 16: Stop the program.
PROGRAM:#include#include#include#include#define SIZE 128
#define NONE -1#define EOS '\0'#define NUM 256#define KEYWORD 257#define PAREN 258#define ID 259#define ASSIGN 260#define REL_OP 261
-
7/29/2019 Compiler Programs
10/35
#define DONE 262#define MAX 999char lexemes[MAX],buffer[SIZE];int lastchar=-1,lastentry=0,tokenval=NONE,lineno=1;struct entry
{char *lexptr;int token;}symtable[100];char *keywords[]= {"if","else","for","int","char","return",0,0};void Error_Message(char *m){
fprintf(stderr,"line %d :%s\n",lineno,m);exit(1);
}int look_up(char s[])
{ int k;for(k=lastentry;k>0;k=k-1)
if (strcmp(symtable[k].lexptr,s)==0)return k;
return 0;}
int insert(char s[],int tok){int len;len=strlen(s);
if(lastentry+1>=MAX)Error_Message("Symbol table full");if(lastchar+len+1>=MAX)Error_Message("Lexemes array is full");
lastentry++;symtable[lastentry].token=tok;symtable[lastentry].lexptr=&lexemes[lastchar+1];lastchar=lastchar+len+1;strcpy(symtable[lastentry].lexptr,s);return lastentry;}
void initialize(){struct entry *ptr;for(ptr=keywords;ptr->token;ptr++)insert(ptr->lexptr,ptr->token);}
-
7/29/2019 Compiler Programs
11/35
int lexer(){int t,i=0,val;while(1)
{ t=getchar();if(t==' '||t=='\t')printf("space");else if(t=='\n')lineno++;else if(t=='('|t==')')return PAREN;else if(t=='' | t=='='|t=='!=')return REL_OP;else if(t=='=')
return ASSIGN;else if(isdigit(t)) {ungetc(t,stdin);scanf("%d",&tokenval);return NUM; }
else if(isalpha(t)) {while(isalnum(t)){
buffer[i]=t;t=getchar();i++;if(i>=SIZE)Error_Message("compiler Error");
}buffer[i]=EOS;if(t!=EOF)ungetc(t,stdin);val=look_up(buffer);if(val==0)val=insert(buffer,ID);tokenval=val;return symtable[val].token;}else if(t==EOF)return DONE;else {tokenval=NONE;return t; }
} }void main()
-
7/29/2019 Compiler Programs
12/35
{int lookahead;char ans;clrscr();printf("\n Program for lexical analysis:");
initialize();printf("Enter the expression and put ; at the end\n Press ctrl z to terminate\n");lookahead=lexer();
while(lookahead!=DONE){
if(lookahead==NUM)printf("\n Number %d",tokenval);if(lookahead=='+'|lookahead=='-'|lookahead=='*'|lookahead=='/')printf("\n operator");if(lookahead==PAREN)printf("\n parenthesis");
if(lookahead==ID)printf("\n Identifier%s",symtable[tokenval].lexptr);if(lookahead==ASSIGN)printf("\n Assignment Operator");if(lookahead==REL_OP)printf("\n Relational Operator");lookahead=lexer();
} }
OUTPUT:
Program for lexical analysis:Enter the expression and put ; at the end
press ctrl z to terminate
void main()
Identifiervoid space
Identifiermain
parenthesis
parenthesis
int i=69;
IdentifierintspaceIdentifieri
Assignment Operator
Number69
RESULT:
-
7/29/2019 Compiler Programs
13/35
Thus the program was implemented and verified
LEXICAL ANALYSIS USING LEX TOOLS
AIM:
To write a program to implement the Lexical analysis using LEX
AlGORITHM:
Step 1: Create the lex source with lex specification with the extension .l or .ex.Step 2: Check for the identifier whether it is alphabets or numeric character.Step 3: If it find # then print it is a preproccesor directiveStep 4: Check for the other keywords such as int, float, char, double, while, for, do, if,break, continue, void, switch case, long, struct, const, typedef, return(0),else and if it findany of the above display it is a keyword.
Step 5: Store it in a variable called yytextStep 6: If it encounters \/\/ print it is acommentStep7: The \{ represents the beginning of clock and /} represents the end of the blockStep 8: If it finds then print it is a stringStep 9: It is encountered upto 0-9 then display it is a numberStep10: Echo is like the prints statement character within the double quotesStep11: If it finds = then print an argument operationStep12: If it find the operators such as =,
-
7/29/2019 Compiler Programs
14/35
printf("b");scanf("%d",&b);c=a+b;printf("c=%d",c);getch ();
}
(lex.l)%{int COMMENT=0;%}identifier[a-zA-z][a-zA-z0-9]*%%#.* {printf("\n%s is a preprocessor directive",yytext);}int |
float |char |double |while |for |do |if |break |continue |void |switch |case |long |struct |const |typedef |return |else |
goto { printf("\n\t%s is a keyword",yytext); }if[\t]* { printf("\n\t 'if' is a keyword\n\t"); }\/\/.* { printf("\n\n\t%s is a omment",yytext); }\{ { printf("\nBlock begins"); }\} { printf("\n Block ends"); }radius |area |argv |r |argc { printf("\n%s identifier",yytext); }\".*\" { printf("\n\t %s is a string",yytext); }
-
7/29/2019 Compiler Programs
15/35
[0-9]+ { printf("\n\n\t%s is a number \n",yytext); }\)(\;)? { printf("\n\t");ECHO;printf("\n"); }\(ECHO;= { printf("\n\t %s is a argument operator",yytext); }\= |\< |== |\> printf("\n\t %s is a relational operator",yytext);.|\n;%%int main(int argc,char **argv){if(argc>1){FILE *file;
file = fopen(argv[1],"r");if(!file){printf("Could not open %s\n",argv[1]);exit(0);}yyin=file;}yylex();printf("\n\n");return 0;}int yywrap(){return 0;}
OUTPUT:
[cse@cselinux cse]$ lex lex.l
[cse@cselinux cse]$ cc lex.yy.c
[cse@cselinux cse]$ ./a.out add.c
#include is a preprocessor directive
-
7/29/2019 Compiler Programs
16/35
void is a keyword
)
Block begins
int is a keyword
r identifier
int is a keyword
"a=" is a string
);
"%d" is a string
);
r identifierint is a keyword
"b" is a string
);
"%d" is a string
);
= is a argument operator
r identifier
int is a keyword
"c=%d" is a string
);
);
Block ends
[5]+ Stopped ./a.out add.c
[cse@cselinux cse]$
RESULT:
Thus the program was implemented and verified
-
7/29/2019 Compiler Programs
17/35
4. SYNTAX CHECKING USING LEX AND YACC
AIM:To write a program to implement the syntax analyzer using LEX and YACC
AlGORITHM:Step 1: Lex and yacc can be easily interfacedStep 2: Lex compiler can be used to perform lexical analysis phaseStep 3: Create a lex source with lex specification with extension .lStep 4: In lex code we check for letter ie. Alphabets and we check for digit ie.numericvaluesStep 5: Lex compiler will produce the tokensStep 6: Tokens are used for yacc compiler for syntax analyzingStep 7: In yacc compiler accepts a large class of CFGs but require a lower level analyzerto recognize input tokens
Step 8: In yacc source specifies grammars.i)write the grammar in .y file
eg:list:list stat|list errorii)expr:(expr)|expr * expr|expr(exprexpr|expr%expr.
Step 9: In main function yyparse() is used to call parserStep 10:yyerror() method is used to handle the errors from yaccStep 11: Compile the code produced by YACC as well as LEXStep 12: Link the object files to appropriate libraries for executable parserStep 13: Execute the (program)parser
PROGRAM:(srical.y)%{#includeint regs[26];int base;%}%start list%token DIGIT LETTER%left '|'%left '&'
%left '+' '-'%left '*' '/' '%'%left UMINUS%%list:|list stat '\n'|
-
7/29/2019 Compiler Programs
18/35
list error '\n'{yyerror;};
stat : expr{printf("%d\n",$1);}|LETTER '=' expr{regs[$1]=$3;};expr :
'(' expr ')'{$$=$2;}|expr '*' expr{$$=$1*$3;}|expr '/' expr{$$=$1/$3;}|expr '%' expr{$$=$1%$3;}|expr '+' expr{$$=$1+$3;}|expr '-' expr{$$=$1-$3;}|expr '&' expr
-
7/29/2019 Compiler Programs
19/35
{$$=$1&$3;}|expr '|' expr
{$$=$1|$3;}|'-' expr %prec UMINUS{$$=$2;}|LETTER{
$$=regs[$1];}|number;number : DIGIT{$$=$1;base=($1==0)?8:10;}|number DIGIT{$$=base*$1+$2;};%%main(){return(yyparse());}yyerror(s)char *s;{fprintf(stderr,"%s\n",s);}yywrap(){return(1);}
-
7/29/2019 Compiler Programs
20/35
(sri.l)%{#include#include"y.tab.h"int c;
extern int yylval;%}%%" ";[a-z] {c=yytext[0];yylval=c-'a';return (LETTER);}[0-9] {c=yytext[0];
yylval=c-'0';return (DIGIT);}[^a-z0-9\b] {c=yytext[0];return (c);}
OUTPUT:
[cse@cselinux cse]$ yacc -d srical.y
[cse@cselinux cse]$ lex sri.l
[cse@cselinux cse]$ cc y.tab.c lex.yy.c
[cse@cselinux cse]$ ./a.out
3+5*(5*3)
78
10/5
2
15*3
45
RESULT:
Thus the program was implemented and verified
-
7/29/2019 Compiler Programs
21/35
5. SYNTAX CHECKING USING PREDICTIVE
PARSING
AIM:To write a program to implement the syntax analyzer C
AlGORITHM:
Step1 Include all header filesStep2: Declare four functions E(),E1(),E2()and A()Step3: In the main() function specifies the grammar along with its productions.Thegrammar is used to define arirhmetic expreesionsStep4: An expression is got as input from the user and it is stored in a character array
Step5: Transfer one character at a time from the above array to the character variablelookaheadStep6: Call the finction E() until the end of the array symbol [eg:$] is reached.Step7: In E() perform the following task,
(a)If lookahead is an alphabet then store the entirestring in an array and displayIdentifier goto step 8.
(b)If lookahead is a numeric constant then display Numder and goto step8.(c)If the above two conditions are not satisfied then print Error and terminate.
Step8: In E1() perform the following task,(a)check whether lookahead is an arithmetic operator(b)If 8)a) is satisfied goto step 9.
Step9 :In A() perform the following task,(a)using switchcase verify lookahead is * or / or + or -(b)If 9)a)is true print Arithmetic operator and break out of switchcaseIf lookahead is not alphanumeric then print syntax error
Step10: Finally print Expression is correct if it correct
PROGRAM:
#include
#includevoid E();void E1();void A();char lookahead,*str;int i=0;void main(){
-
7/29/2019 Compiler Programs
22/35
int i,n;clrscr();printf("\nGiven Grammar :\n");printf("E->idE/numE1/n");printf("A->+|-|*|/\n");
printf("Enter String End With $\n");scanf("%s",str);lookahead=str[0];
while(lookahead!='$'){E();}
printf("Given Expression is Correct");getch();}void E()
{ if(isalpha(lookahead)){printf("Identifer : ");
while(isalnum(lookahead)){printf("%c",lookahead);lookahead=str[++i];}
printf("\n");E1();}
else if(isdigit(lookahead)){printf("Number : ");
while(isdigit(lookahead)){printf("%c",lookahead);lookahead=str[++i];}
printf("\n");E1();}
else{printf("Error");exit(0);}
-
7/29/2019 Compiler Programs
23/35
}
void E1(){
if(lookahead=='+'||lookahead=='-'||lookahead=='*'||lookahead=='/')
A(lookahead);}void A(char lt){
switch(lt){case '+':case '-':case '*':case '/':
printf("Arithmetic Operator : %c\n",lt);
lookahead=str[++i];if(!isalnum(lookahead)){printf("Syntax Error\n");exit(0);}
break;}
}
OUTPUT:[cse@cselinux cse]$ cc o ex6 ex6.c
[cse@cselinux cse]$ ./ex6
Given Grammar
E->idE1|numE1
E1->+|-|*|/
Enter the string ending with $
Position+rate*60$
Identifier:position
Arithmetic Operator:+
Identifier:rate
Arithmetic Operator:*Number:60
Given Expression is correct
RESULT:
Thus the program was implemented and verified
-
7/29/2019 Compiler Programs
24/35
6. CONVERSION OF INFIX TO POSTFIX
AIM:To write a C program to convert an infix expression to a postfix expression
.
ALGORITHM:Step 1: Start the program.Step 2: Include all the required header files.Step 3: Declare a global variable namely lookahead. The datatype of lookahead is integer.Step 4: In the main() function get an infix expression as input from the user and call theexpr() function.Step 5: In expr() function perform the following task after calling the term() function.
(a)Inside an infinite while loop i.e., while(1) check the operator.
(b)If lookahead is a + sign then call match(+) and go to step 5.(c)If lookahead is a - sign then call match(-) and go to step 5.(d)If the above two conditions are not satisfied then break out of the loop.
Step 6:In turn() function perform the following tasks,(a)If lookahead is a digit then print the value of lookahead.(b)Then call the match() function with lookahead as the parameter.(c)Else call the error() function.
Step 7:In the error() function print Syntax Error and then terminate the program.Step 8:In match() function perform the following tasks,
(a)If lookahead = = t then use getchar() to get the input from the user.(b)Else call the error() function.
Step 9: Finally display the postfix expression.Step 10:Terminate the program.
PROGRAM:#include#includeChar lookahead;Int main(){
Lookahead=getchar();Expr();Putchar(\n);
}
Expr(){
Term();
-
7/29/2019 Compiler Programs
25/35
While(1){
If(lookahead = =+){Match(+);
Term();Putchar(+);}Else if(lookahead = = -){Match(-);Term();Putchar(-);}
Else break;}
}Term(){If(isdigit(lookahead)){Putchar(lookahead);Match(lookahead);}Else error();}Match(t){If(lookahead==t)Lookahead=getchar();ElseError();}Error(){Printf(\nSyntax Error\n);Exit(1);}OUTPUT:
[cse@cselinux cse]$ cc -0 expr expr.c
[cse@cselinux cse]$ ./expr
1+2
12+
RESULT:
Thus the program was implemented and verified
-
7/29/2019 Compiler Programs
26/35
8. EVALUATING POSTFIX EXPRESSION
AIM:
To write a program to evaluate a postfix expression
ALGORITHM:Step1: Start the program.Step2: Define a stack of size 100 ant two integer variables sp,stack(stack size)Step3: Inside the push() function perform the following task.
a)If (++sp
-
7/29/2019 Compiler Programs
27/35
if(lookahead==t){pos++;lookahead=expression[pos];}
elseerror();}void digit(){
switch(lookahead){case '0':case '1':case '2':case '3':
case '4':case '5':case '6':case '7':case '8':case '9':if(compile_mode==MODE_POSTFIX)
printf("%c",lookahead);else
printf("\tPUSH%c\n",lookahead);match(lookahead);break;default:error();break;}
}void term(){digit();while(1){
switch(lookahead){case '*':match('*');digit();printf("%s",compile_mode==MODE_POSTFIX?"*":"\tPOP B\n\tPOP A\n\tMUL
A,B\n\tPUSH A\n");break;
-
7/29/2019 Compiler Programs
28/35
case '/':match('/');digit();printf("%s",compile_mode==MODE_POSTFIX?"/":"\tPOP B\n\tPOP A\n\tDIV
A,B\n\tPUSH A\n");
break;default:return;}
}}void expr(){term();while(1){
switch(lookahead){case '+':match('+');term();printf("%s",compile_mode==MODE_POSTFIX?"+":"\tPOP B\n\tPOP A\n\tADD
A,B\n\tPUSH A \n");break;case '-':match('-');term();printf("%s",compile_mode==MODE_POSTFIX?"-":"\tPOP B\n\tPOP A\n\tSUB
A,B\n\tPUSH A \n");break;default:return;}
}}int main(int argc,char** argv){clrscr();printf("Please enter the infix_notated expression with single digits\n\n\t");scanf("%20s",expression);printf("\nCompiling to postfix_notated expression:\n\n\t");compile_mode=MODE_POSTFIX;pos=0;lookahead=*expression;expr();printf("\nCompiling to assembly_notated expression:\n\n\t");
-
7/29/2019 Compiler Programs
29/35
compile_mode=MODE_ASSEMBLY;pos=0;lookahead=*expression;expr();getch();
return 0;}
OUTPUT:
[basariya@telnet ~]$ ./a.out
Please enter the infix_notated expression with single digits
5-3
Compiling to postfix_notated expression:
53-Compiling to assembly_notated expression:
PUSH5
PUSH3
POP B
POP A
SUB A,B
PUSH A
RESULT:
Thus the program was implemented and verified
-
7/29/2019 Compiler Programs
30/35
9. IMPLEMENTATION OF INTERMEDIATE
CODE GENERATOR
AIM:
To write the program to implement the intermediate code generation using C.
ALGORITHM:Step 1:Start the program.Step 2:Include all header files.Step 3:Declare two character array str[10] and stk[10][3].Step 4:Decalre an array that holds a list of temporary variables.Step 5:Initialise the top of stack to -1 and ntemp to 0.Step 6:Declare a structure 4 members of datatype char.
-opr for the operator, arg1[5] and arg2[5] for the two arguments and res[5] for theresult.
Step 7:In the main() function get the input string from the user and store it in str[].Step 8:Using for loop the intermediate code statements can be generated as follows.
(a)Initialize the loop variable i to 0.(b)If str[i] is an alphabet then store it in the top of stack and set the next location
i.e., stk[top][1] to null.(c)If the above condition is false then store str[5] in s[++n].opr and copy the TOS
to arg2.(d)If top>-1 then copy TOS to arg1.(e)Copy the temporary variables to res.
If i
-
7/29/2019 Compiler Programs
31/35
Int I,j,k;Printf(\nenter the string:);Scanf(%s,str);
For(i=0;i-1)
Strcpy(s[n].arg1,stk[top1]);Strcpy(s[n].res,temp[ntemp]);Strcpy(stk[++top],temp[ntemp++]);}}Printf(\nOPERRATOR ARG1 ARG2 RESULT\n);For(i=0;i
-
7/29/2019 Compiler Programs
32/35
10. Operator Precedence Parser
AIM:
To write the program to implement the operator precedence parser using C.
ALGORITHM:
Step 1: start.Step 2: Declare the prototypes for functions.Step 3: Enter the String like id*id+idStep 4: Read the string and analyze tokens, identifiers, variables.Step 5: Display the operator precedence table.Step 6: stop.
Program#include#include#includechar *p;e();t();main(){
int i,j=0,n,b[10],k=0;char a[10],c[10];clrscr();printf("Enter the string\n");scanf("%s",a);for(i=0,j=0;i
-
7/29/2019 Compiler Programs
33/35
break;case '^' :
c[j]=a[i];b[j]=3;j++;
break;default :if(k==0){
k=1;c[j]=a[i];b[j]=4;j++;
}}
}
c[j]='$';b[j]=0;j++;printf("\n\n");printf("\n\t----------------------------------");printf("\n\n");for(i=0;i
-
7/29/2019 Compiler Programs
34/35
getch();return 0;
}int e(){
if(*p=='i'){p++;t();t();
}elsereturn 0;
}int t(){
if(*p==NULL)return 1;elseif(*p=='+'||*p=='*'){
p++;if(*p=='i'){
p++;}else{
return 0;}
}else
return 0;}
OUTPUT:
Enter the stringI + I * i
----------------------------------i + * $---------------------------------i = > > >---------------------------------+ < = < >
-
7/29/2019 Compiler Programs
35/35
---------------------------------* < > = >
---------------------------------$ < < < =--------------------------------------
String parsed
top related