This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
1. Develop a lexical analyzer to recognize a few patterns in PASCAL and C.(Ex. identifiers, constants, comments, operators etc.)
#include<stdio.h>#include<conio.h>#include<ctype.h>#include<string.h>#include<stdlib.h>#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#define DONE 262#define MAX 999char lexemes[MAX];char buffer[SIZE];int lastchar = -1;int lastentry = 0;int tokenval=NONE;int lineno=1;struct entry{
int lookahead;char ans;clrscr();printf(“\n]t]t Program for Lexical Analysis \n”);Initialize();printf(“\n Enter the expression and put ; at the end”);printf(“\n Press Ctrl + Z to terminate... \n”);lookahead=lexer();while(lookahead!=DONE){
errormsg("symtable is full");if(lastentry+len+1>=MAX)
errormsg("lexemes array is full");lastentry=lastentry+1;symtable[lastentry].token=tok;symtable[lastentry].lexptr=&lexemes[lastchar+1];lastchar=lastchar+len+1;strcpy(symtable[lastentry].lexptr,s);return lastentry;
char input[30];void input_to_code(char infix[30]);clrscr();printf("\n Enter an input in the form of expression ");scanf("%s",input);input_to_code(input);getch();
clrscr();printf(“\n Program to perform various operations on heap
using dynamic memory management”);printf (“\n1.Create”):printf (“\n2.Display”):printf (“\n3.Insert an element in a list”);printf (“\n4.Delete an element from list”);printf (“\n5.Quit”);printf (“\n Enter Your Choice(1-5)”);scanf(“%d,&choice”);switch(choice){
/*flag to indicate whether a new node is created for the first time or not*/
do{
printf(“\n Enter the Element”);scanf(“%d”,&val);/*allocate new node*/new =get_node();
if(new==NULL)printf(“\n Memory is not allocated”);new-> data=val;if (flag==TRUE)/* Executed only for the first time*/{
head=new;temp=head; /*head is the first node in the heap*/flag=FALSE;
}else{/*temp keeps track of the most recently created node*/
temp->next=new;temp=new;
}printf(\nDo you want to enter more elements?(y/n)”);ans=getch();
}while(ans= = ‘y’);
printf(“\nThe list is created”);getch();clrscr();return head;
}
node *get_node(){
node *temp;temp=(node*)malloc(sizeof(node));
//using the mem. Allocation functiontemp->next=NULL;return temp;
}
/**The display function *Input:Address of the first node of the list*Output:Displays the list of allocated nodes*Parameter Passing Method : call by value*Called by main**/
void display(node*head){
node *temp;temp=head;if(temp= =NULL){
printf(“\n The list is empty\n”);getch();clrscr();return;
}while(temp!= NULL){
printf(“%d->”,temp-> data);temp=temp->next;
}print(“NULL”);getch();clrscr();
}
/**The search function *Input: Address of the starting node and the element which is *to be searched*Output:Searches for the element in list*If found returns pointer to that node Otherwise NULL*Parameter passing Method:call by value*Called by:main*Calls:None**/
node *search(node *head,int key){
node*temp;int found;temp=head;if (temp= =Null){
printf(“The linked list is empty\n”);getch();clrscr();return NULL;
}
found=FALSE;While(temp!= NULL && found= =FALSE){
if(temp->data != key)temp = temp->next;
elsefound = True;
}
if(found == TRUE){
printf(“\n The Elements is present in the list”\n);getch();return temp;
}else
printf(“\n The Element is not present in the list\n”);getch();return NULL;
}
/**The insert function*Input: Address of starting node of the list*Output:inserts element into the list*Parameter Passing Methods: call by value*Called by : main*Calls : search()**/
node *insert(node *head){
int choice;node *insert_head(node*);void insert_after(node*);void insert_last(node*);printf(“\n”1.Insert a node as a head node”);printf(“\n”1.Insert a node as a last node”); printf(“\n”1.Insert a node as at the intermediate position in
the list ”); printf(“\n”1.Enter your choice for insertion of node ”); scanf(“%d”,&choice);switch(choice){
case 1:head = insert_head(head);break;
case2:insert_last(head);break;
case2:insert_after (head);break;
}return head;
}
/*Insertion of node at first position*/
node *insert_head(node*head){
node *New,*temp;New = get_node();printf (“\n Enter the element which you want to insert ”);scanf(“%d”,&New->data);if(head == NULL)head = New;else{
temp=head;New->next = temp;head= New;
}return head;
}
/*Insertion of node at last position*/
void insert_last(node *head) {
node *New,*temp;New = get_node();printf (“\n Enter the element which you want to insert ”);scanf(“%d”,&New->data);if(head == NULL){
int key;node *New,*temp;New = get_node();printf(“Enter the element after which you want to insert ”);scanf(“%d”,&key);temp=head;
do{
if(temp->data==key) {
printf (“Enter element which you want to insert ”);scanf(“%d”,&New->data);New->next=temp->next;temp->next=New;return;
}else
temp=temp->next;}while(temp!=NULL);
}
/**The get prev function*Input: Address of starting node and the elemnt to be *searched*Output:looks for the element in the list*If found returns pointer to the previous node otherwise NULL*Parameter Passing Methods: call by value*Called by : dele()*Calls : none**/
/* *The get prev function*Input: Address of starting node and the elemnt to be *searched*Output:looks for the element in the list*If found returns pointer to the previous node otherwise NULL*Parameter Passing Methods: call by value*Called by : dele()*Calls : none**/
void dele(node **head) {
int key;node *New,*temp;temp=*head;if (temp== NULL){
printf (“\n The list is empty\n ”);getch();clrscr();return;
}
clrscr();printf("\nENTER the Element you want to delete:");scanf("%d".&key);temp= search(*head,key);if(temp !=NULL){
prev = get_prev(*head,key);if(prev != NULL){
prev ->next = temp-> next;free(temp);
}else{
*head = temp->next;free(temp); // using the mem. Dellocation function
}printf(“\n”The Element is deleted\n”);getch();clrscr();
}}
Output:
Program to perform various operations on heap using Dynamic memory management.
1. Create2. Display3. Insert an element in a list4. Delete an element from list5. QuitEnter your choice(1-5) 1
Enter the element: 10
Do you want to enter more elements? (y/n) y
Enter the element:20
Do you want to enter more elements?(y/n)y
Enter the element:30
Do you want to enter more elements?(y/n)n
The List is created
Program to perform various operations on Heap using Dynamic memory management.
1. Create2. Display3. Insert an element in a list4. Delete an element from list5. Quit Enter your choice(1-5) 4
Enter the element you want to delete: 20
The element is present in the list
The element is deleted
Program to perform various operations on Heap using Dynamic memory management.
1. Create2. Display3. Insert an element in a list4. Delete an element from list5. QuitEnter your choice(1-5) 2
\( ECHO;= {if(!COMMENT)printf("\n\t%s is an ASSIGNMENT OPERATOR",yytext)}
\+|\- {if(!COMMENT)printf("\n\t%s is an OPERATOR",yytext);}
\<=|\>=|\<|==|\> {if(!COMMENT)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(“\n Could not open %s”,argv[1]; exit(0); } yyin = file;}yylex();printf(“ \n Total number of comments are %d”,cnt);return 0;
/* This is a double line comment */ double radius = atof(argv[1]); double area = area_of_circle(radius); printf(“ Area of circle with radius %f = %f \n”,radius,area);}return 0;
double is a KEYWORDarea is an INDENTIFIERof is an INDENTIFIERcircle is an INDENTIFIER(double is a KEYWORDr is an INDENTIFIER
);
int is a KEYWORDmain is an INDENTIFIER(int is a KEYWORDargc is an INDENTIFIERchar is a KEYWORDargv[] is an INDENTIFIER
)
BLOCK BEGINSif is a KEYWORD(argc is an INDENTIFIER
< is a RELATIONAL OPERATOR2 is a NUMBER
)
BLOCK BEGINSprintf is an INDENTIFIER(“ Usage: %s radius \n”,is a STRING
argv[0] is an INDENTIFIER);
exit is an INDENTIFIER (1 is a NUMBER
);
BLOCK ENDSelse is a KEYWORD
BLOCK BEGINSdouble is a KEYWORDradius is an INDENTIFIER= is an ASSIGNMENT OPERATOR
atof is an INDENTIFIER(argv[1]is an INDENTIFIER);
double is a KEYWORDarea is an INDENTIFIER= is an ASSIGNMENT OPERATORarea is an INDENTIFIERof is an INDENTIFIERcircle is an INDENTIFIER(radius is an INDENTIFIER);
printf is an INDENTIFIER(“Area of circle with radius %f = %f \n”, is a STRINGradius is an INDENTIFIERarea is an INDENTIFIER
);
BLOCK ENDSreturn is a KEYWORD0 is a NUMBER
BLOCK ENDSTotal number of comments are 3{root@localhost]#
7. Generate YACC specification for a few syntactic categories.a) Program to recognize a valid arithmetic expression that uses
operator +, - , * and /.
Program name:arith_id.l
%{/* This LEX program returns the tokens for the expression */#include “y.tab.h”%}
%%“=” {printf(“\n Operator is EQUAL”);}“+” {printf(“\n Operator is PLUS”);}“-“ {printf(“\n Operator is MINUS”);}“/” {printf(“\n Operator is DIVISION”);}“*” {printf(“\n Operator is MULTIPLICATION”);}
Identifier is xOperator is EQUALIdentifier is aOperator is PLUSIdentifier is b
b) Program to recognise a valid variable which starts with a letter followed by any number of letters or digits.
Program name: variable_test.l
%{/* This LEX program returns the tokens for the Expression */#include "y.tab.h"%}%%"int " {return INT;}"float" {return FLOAT;}"double" {return DOUBLE;}[a-zA-Z]*[0-9]*{
printf("\nIdentifier is %s",yytext);return ID;
}return yytext[0];
\n return 0;int yywrap(){return 1;}
Program name: variable_test.y
%{#include <stdio.h>/* This YACC program is for recognising the Expression*/%}%token ID INT FLOAT DOUBLE%%D;T L;L:L,ID |ID;T:INT |FLOAT |DOUBLE;%%extern FILE *yyin;main(){do { yyparse(); }while(!feof(yyin));}yyerror(char*s){}
d) Implementation of Calculator using LEX and YACC
Program name:calci.l
%{#include "y.tab.h" /*defines the tokens*/#include ,math.h.%}%%
/*To recognise a valid number*/([0-9] + |([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval = atof(yytext);
return NUMBER;}/*For log no | Log no (log base 10)*/
log | LOG {return LOG;}
/*For ln no (Natural Log)*/ln {return nLOG;}
/*For sin angle*/sin | SIN {return SINE;}
/*For cos angle*/cos | COS {return COS;}
/*For tan angle*/tan | TAN {return TAN;}/*For memory*/mem {return MEM;}
[\t] ; /*Ignore white spaces*/
/*End of input*/\$ {return 0;}
/*Catch the remaining and return a single character token to the parser*/
\n| return yytext[0];%%
Program Name : calci.y
%{double memvar;
%}
/*To define possible symbol types*/%token <dval> NUMBER%token <dval> MEM%token LOG SINE nLOG COS TAN
/*Defining the precedences and associativity*/%left ‘-’ ‘+’ /*Lowest precedence*/%left ‘*’ ‘/’%right ‘^’%left LOG SINE nLOG COS TAN/*Highest precence*/
*/Trigonometric functions*/| SINE expression {$$ = sin($2 * 3.141592654 / 180);}| COS expression {$$ = cos($2 * 3.141592654 / 180);}| TAN expression {$$ = tan($2 * 3.141592654 / 180);}| NUMBER {$$ = $1;}| MEM {$$ = $1;}; /*Retrieving the memory contents*/
%%main(){
printf(“Enter the expression:”);yyparse();
}int yyerror(char *error){
fprintf(stderr,”%s\n”,error);}
Output:
The output of the program can be obtained by following commands[root@localhost]]# lex calci.l[root@localhost]]# yacc –d calci.y[root@localhost]]# cc y.tab.c lexyy.c –ll –ly –lm[root@localhost]]# ./a.out
Enter the expression: 2+@Answer = 4
2 * 2 + 5 / 4Answer = 5.25
mem = cos 45sin 45/memAnswer = 1
ln 10Answer = 2.30259
8. Given any intermediate code form implement code optimization techniques.
/*******************************************************************Program for Code Optimization Technique of Constant Folding
if(isdigit(Token[i+1][0])||Token[i+1][0] == ’.’){ /*If yes then saving that number and its variable In the Opt_Data array*/ flag=1; strcpy(Opt_Data[New_Index].New_Str,Token[i-1]); strcpy(Opt_Data[New_Index++].str,Token[i+1]);}//End if
void main(){int p[2],i,j;clrscr();printf("Enter the no. of productions :");scanf("%d",&n);printf("Enter the productions :\n");for(i=0;i<n;i++)scanf("%s",array[i]);for(i=0;i<n;i++){
void main(){int p[2],i,j;clrscr();printf("Enter the no. of productions :");scanf("%d",&n);printf("Enter the productions :\n");for(i=0;i<n;i++)scanf("%s",array[i]);for(i=0,t=0;i<n;i++,t++){
Output:Enter the no. of productions :6Enter the productions :S/aBDhB/cCC/bC/@D/E/FE/g/@F/f/@First(S) : [ a ].First(B) : [ c ].First(C) : [ b,@ ].First(D) : [ g,@,f ].