Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

Acropolis Institute of Technology and Research, Indore

EXPERIMENT NO.1
AIM: To study about LEX and YACC compilers.
THEORY:
Lex (software)
Lex is a computer program that generates lexical analyzers ("scanners" or "lexers"). Lex helps
write programs whose control flow is directed by instances of regular expressions in the input
stream. It is well suited for editor-script type transformations and for segmenting input in
preparation for a parsing routine.
Lex source is a table of regular expressions and corresponding program fragments. The table is
translated to a program which reads an input stream, copying it to an output stream and
partitioning the input into strings which match the given expressions. As each such string is
recognized the corresponding program fragment is executed. The recognition of the expressions
is performed by a deterministic finite automaton generated by Lex. The program fragments
written by the user are executed in the order in which the corresponding regular expressions
occur in the input stream. Lex reads an input stream specifying the lexical analyzer and outputs
source code implementing the lexer in the C programming language.
Open source:
Though originally distributed as proprietary software, some versions of Lex are now open
source. Open source versions of Lex, based on the original AT&T code are now distributed as
open source systems such as OpenSolaris and Plan 9 from Bell Labs. One popular open source
version of Lex, called flex, or the "fast lexical analyzer", is not derived from proprietary code.
Structure of a Lex file:
The structure of a Lex file is intentionally similar to that of a yacc file; files are divided into three
sections, separated by lines that contain only two percent signs, as follows:
The definition section defines macros and imports header files written in C. It is also
possible to write any C code here, which will be copied verbatim into the generated source

file.
The rules section associates regular expression patterns with C statements. When the lexer

sees text in the input matching a given pattern, it will execute the associated C code.
The C code section contains C statements and functions that are copied verbatim to the
generated source file. These statements presumably contain code called by the rules in the
rules section. In large programs it is more convenient to place this code in a separate file
linked in at compile time.

RollNo.

Page 1

Acropolis Institute of Technology and Research, Indore


Using Lex with other programming tools:
Using Lex with parser generators
Lex and parser generators, such as Yacc or Bison, are commonly used together. Parser
generators use a formal grammar to parse an input stream, something which Lex cannot do
using simple regular expressions (Lex is limited to simple finite state automata).
It is typically preferable to have a (Yacc-generated, say) parser be fed a token-stream as
input, rather than having it consume the input character-stream directly. Lex is often used to
produce such a token-stream. Scanner less parsing refers to parsing the input character

stream directly, without a distinct lexer.


Lex and make
make is a utility that can be used to maintain programs involving Lex. Make assumes that a
file that has an extension of .l is a Lex source file. The make internal macro LFLAGS can be
used to specify Lex options to be invoked automatically by make.

YACC: Yet Another Compiler-Compiler


Computer program input generally has some structure; in fact, every computer program that does
input can be thought of as defining an ``input language'' which it accepts. An input language may
be as complex as a programming language, or as simple as a sequence of numbers.
Unfortunately, usual input facilities are limited, difficult to use, and often are lax about checking
their inputs for validity. Yacc is a computer program for the Unix operating system. It is a Look
Ahead Left-to-Right (LALR) parser generator, generating a parser, the part of a compiler that
tries to make syntactic sense of the source code, specifically a LALR parser, based on an analytic
grammar written in a notation similar to BackusNaur Form (BNF). Yacc itself used to be
available as the default parser generator on most Unix systems, though it has since been
supplanted as the default by more recent, largely compatible, programs.
Yacc provides a general tool for describing the input to a computer program. The Yacc user
specifies the structures of his input, together with code to be invoked as each such structure is
recognized. Yacc turns such a specification into a subroutine that handles the input process;
frequently, it is convenient and appropriate to have most of the flow of control in the user's
application handled by this subroutine.
Description
YACC is an acronym for "Yet Another Compiler Compiler". It is a LALR parser generator,
generating a parser, the part of a compiler that tries to make syntactic sense of the source code,
specifically a LALR parser, based on an analytic grammar written in a notation similar to BNF. It

RollNo.

Page 2

Acropolis Institute of Technology and Research, Indore


was originally developed in the early 1970s by Stephen C. Johnson at AT&T Corporation and
written in the B programming language, but soon rewritten in C. It appeared as part of Version 3
Unix, and a full description of Yacc was published in 1975.
The input to Yacc is a grammar with snippets of C code (called "actions") attached to its rules. Its
output is a shift-reduce parser in C that executes the C snippets associated with each rule as soon
as the rule is recognized. Typical actions involve the construction of parse trees. Using an
example from Johnson, if the call node (label, left, right) constructs a binary parse tree node with
the specified label and children, then the rule
expr : expr '+' expr { $$ = node('+', $1, $3); }
recognizes summation expressions and constructs nodes for them. The special identifiers $$, $1
and $3 refer to items on the parser's stack.
Yacc and similar programs (largely reimplementations) have been very popular. Yacc itself used
to be available as the default parser generator on most Unix systems, though it has since been
supplanted as the default by more recent, largely compatible, programs such as Berkeley Yacc,
GNU bison, MKS Yacc and Abraxas PCYACC. An updated version of the original AT&T version
is included as part of Sun's OpenSolaris project. Each offers slight improvements and additional
features over the original Yacc, but the concept and syntax have remained the same.[citation
needed] Yacc has also been rewritten for other languages, including OCaml, Ratfor, ML, Ada,
Pascal, Java, Python, Ruby, Go and Common Lisp.
Yacc produces only a parser (phrase analyzer); for full syntactic analysis this requires an external
lexical analyzer to perform the first tokenization stage (word analysis), which is then followed by
the parsing stage proper. Lexical analyzer generators, such as Lex or Flex are widely available.
The IEEE POSIX P1003.2 standard defines the functionality and requirements for both Lex and
Yacc.

EXPERIMENT NO.2
AIM: Write a program for dividing the given input program into lexemes.
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
RollNo.

Page 3

Acropolis Institute of Technology and Research, Indore


#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 999
char lexemes[MAX];
char buffer[SIZE];
int lastchar = -1;
int lastentry = 0;
int tokenval=NONE;
int lineno=1;
struct entry
{
char *lexptr;
int token;
}symtable[100];
struct entry keywords[]={"if",KEYWORD,"else",KEYWORD,"for",KEYWORD,
RollNo.

Page 4

Acropolis Institute of Technology and Research, Indore


"int",KEYWORD,"float",KEYWORD,"double",KEYWORD,"char",KEYWORD,
"struct",KEYWORD,"return",KEYWORD,0,0};
void Error_Message(char *m)
{
printf(stderr,"line %d: %s",lineno,m);
exit(1);
}
int look_up(char s[])
{
int k;
for(k=lastentry;k>0;k--)
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 is Full");
if(lastchar+len+1>=MAX)
Error_Message("Lexemes Array is Full");

RollNo.

Page 5

Acropolis Institute of Technology and Research, Indore


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);
}
int lexer()
{
int t;
int val,i=0;
while(1)
{
t=getchar();
if(t == ' ' || t=='\t');
else if(t=='\n')
lineno++;

RollNo.

Page 6

Acropolis Institute of Technology and Research, Indore


else if(t == '(' || t == ')')
return PAREN;
else if(t=='<' ||t=='>' ||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;

RollNo.

Page 7

Acropolis Institute of Technology and Research, Indore


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()
{
int lookahead;
char ans;
clrscr();
printf("\n]t]t Program for Lexical Analysis \n");

RollNo.

Page 8

Acropolis Institute of Technology and Research, Indore


Initialize();
printf("\n Enter the expression and put ; at the end");
printf("\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==KEYWORD)
printf("\n Keyword");
if(lookahead==ASSIGN)
printf("\n Assignment Operator");
if(lookahead==REL_OP)
printf("\n Relataional Operator");
lookahead=lexer();
}
}

RollNo.

Page 9

Acropolis Institute of Technology and Research, Indore


OUTPUT:

RollNo.

Page 10

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO.3
AIM: Write a program to find the number of whitespaces and Newlines characters.
PROGRAM:
#include <iostream.h>
#include <string.h>
int main()
{
int I, w = 0; char c;
unsigned int space_quantity = 0;
unsigned int newline_quantity = 0;
char x[30],z[30];
for (int i = 0 ; i <= 30;i++)
cin >> x[i];
for (int j = 0 ; j < 30; j++)
{
while (cin >> c) // Read in the character.
{
switch (c)
{
case ' ': // Check for space.
++space_quantity;
break;
case '\n': // Check for newline.
++newlines;
break;
default: // Don't do anything for other characters.
break;
}}
cout << "Spaces: " << space_quantity << '\n';
cout << "Newlines: " << newline_quantity << '\n';
return 0;
getch();
}

OUTPUT:

RollNo.

Page 11

Acropolis Institute of Technology and Research, Indore

RollNo.

Page 12

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 4
AIM: Write a program to identify whether a given string is an identifier or not.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char str[25],i,flag,count=0;
clrscr();
printf("\n Enter a string : ");
gets(str);
if((str[0]>='a'&&str[0]<='z')||(str[0]>='A'&&str[0]<='Z')||str[0]=='_')
{
for(i=0;i<strlen(str);i++)
{
if((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z')||(str[i]>='0'&&str[i]<='9')||str[i]=='_')
count++;
}
if(count==strlen(str))
flag=0;
}
else
flag=1;
if(flag==1)
printf("\n %s is not an identifier",str);
else
printf("\n %s is an identifier",str);
getch();
}

OUTPUT:

RollNo.

Page 13

Acropolis Institute of Technology and Research, Indore

EXPERIMENT NO. 5
AIM: Write a program to check whether a string is a keyword or not.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,flag=0,m;
char s[5][10]={"if","else","goto","continue","return"},st[10];
clrscr();
printf("\n enter the string :");
gets(st);
for(i=0;i<5;i++)
{
m=strcmp(st,s[i]);
if(m==0)
flag=1;
}
if(flag==0)
printf("\n it is not a keyword");
else
printf("\n it is a keyword");
getch();
}

RollNo.

Page 14

Acropolis Institute of Technology and Research, Indore

OUTPUT:

RollNo.

Page 15

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 6
AIM: Write a program to find whether a string is a constant or not.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
charstr[10]; int len,a; clrscr();
printf("\n Input a string :");
gets(str); len=strlen(str);
a=0;
while(a<len)
{
a++;
printf(" It is not a Constant");
break;
if(a==len)
{
printf(" It is a Constant");
}
getch();
}

RollNo.

Page 16

Acropolis Institute of Technology and Research, Indore


OUTPUT:

RollNo.

Page 17

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 7
AIM: Write a program to compute First of all the non terminals.
PROGRAM:
#include<stdio.h>
#include<conio.h>
char array[10][20],temp[10];
int c,n;
void fun(int,int[]);
int fun2(int i,int j,int p[],int );
void main()
{
int p[2],i,j;
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++)
{c=-1,p[0]=-1,p[1]=-1;
fun(i,p);
printf("First(%c) : [ ",array[i][0]);
for(j=0;j<=c;j++)
printf("%c,",temp[j]);
printf("\b ].\n");
getch();
}}
int fun2(int i,int j,int p[],int key)
{
int k;
if(!key)
{for(k=0;k<n;k++)
if(array[i][j]==array[k][0])
break;
p[0]=i;p[1]=j+1;
fun(k,p);
return 0;
}
else{
for(k=0;k<=c;k++)
{
if(array[i][j]==temp[k])
break;
}
if(k>c)return 1;
else return 0;
RollNo.

Page 18

Acropolis Institute of Technology and Research, Indore


}}
void fun(int i,int p[])
{
int j,k,key;
for(j=2;array[i][j] != NULL; j++)
{
if(array[i][j-1]=='/')
{
if(array[i][j]>= 'A' && array[i][j]<='Z')
{
key=0;
fun2(i,j,p,key);
}
else
{
key = 1;
if(fun2(i,j,p,key))
temp[++c] = array[i][j];
if(array[i][j]== '@'&& p[0]!=-1) //taking '@' as null symbol
{
key=0;
fun2(p[0],p[1],p,key);
}
else
if(array[p[0]][p[1]] != '/'&& array[p[0]][p[1]]!=NULL)
{
if(fun2(p[0],p[1],p,key))
temp[++c]=array[p[0]][p[1]];
} } } }}}

OUTPUT:

RollNo.

Page 19

Acropolis Institute of Technology and Research, Indore

RollNo.

Page 20

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 8
AIM: Write a program to compute Follow of all non terminals.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define max 10
#define MAX 15
void ffun(int,int);
void fun(int,int[]);
void follow(int i);
char array[max][MAX],temp[max][MAX];
int c,n,t;
int fun2(int i,int j,int p[],int key)
{
int k;
if(!key){
for(k=0;k<n;k++)
if(array[i][j]==array[k][0])
break;
p[0]=i;p[1]=j+1;
fun(k,p);
return 0;
}
else{
for(k=0;k<=c;k++){
if(array[i][j]==temp[t][k])
break;
}
if(k>c)return 1;
else return 0;
}}
void fun(int i,int p[])
{
int j,k,key;
for(j=2;array[i][j]!=NULL;j++)
{
if(array[i][j-1]=='/'){
if(array[i][j]>='A'&&array[i][j]<='Z'){
key=0;
fun2(i,j,p,key);
}
else{
key=1;
if(fun2(i,j,p,key))
temp[t][++c]=array[i][j];
RollNo.

Page 21

Acropolis Institute of Technology and Research, Indore


if(array[i][j]=='@'&&p[0]!=-1){ //taking ,@, as null symbol.
if(array[p[0]][p[1]]>='A'&&array[p[0]][p[1]]<='Z'){
key=0;
fun2(p[0],p[1],p,key);
}
Else
if(array[p[0]][p[1]]!='/'&&array[p[0]][p[1]]!=NULL){
if(fun2(p[0],p[1],p,key))
temp[t][++c]=array[p[0]][p[1]];
}}}}}}
char fol[max][MAX],ff[max];int f,l,ff0;
void follow(int i)
{int j,k;
for(j=0;j<=ff0;j++)
if(array[i][0]==ff[j])
return;
if(j>ff0)ff[++ff0]=array[i][0];
if(i==0)fol[l][++f]='$';
for(j=0;j<n;j++)
for(k=2;array[j][k]!=NULL;k++)
if(array[j][k]==array[i][0])
ffun(j,k);
}
void ffun(int j,int k)
{int ii,null=0,tt,cc;
if(array[j][k+1]=='/'||array[j][k+1]==NULL)
null=1;
for(ii=k+1;array[j][ii]!='/'&&array[j][ii]!=NULL;ii++){
if(array[j][ii]<='Z'&&array[j][ii]>='A')
{for(tt=0;tt<n;tt++)
if(temp[tt][0]==array[j][ii])
break;
for(cc=1;temp[tt][cc]!=NULL;cc++){
if(temp[tt][cc]=='@')null=1;
else fol[l][++f]=temp[tt][cc];
}}
else fol[l][++f]=array[j][ii];
}if(null)follow(j);
}
int main()
{
int p[2],i,j;
clrscr();
printf("Enter the no. of productions :");
scanf("%d",&n);
printf("Enter the productions :\n");
RollNo.

Page 22

Acropolis Institute of Technology and Research, Indore


for(i=0;i<n;i++)
scanf("%s",array[i]);
for(i=0,t=0;i<n;i++,t++){
c=0,p[0]=-1,p[1]=-1;
temp[t][0]=array[i][0];
fun(i,p);
temp[t][++c]=NULL;
printf("First(%c) : [ ",temp[t][0]);
for(j=1;j<c;j++)
printf("%c,",temp[t][j]);
printf("\b ].\n");
}
for(i=0,l=0;i<n;i++,l++)
{
f=-1;ff0=-1;
fol[l][++f]=array[i][0];
follow(i);
fol[l][++f]=NULL;
}
for(i=0;i<n;i++){
printf("\nFollow[%c] : [ ",fol[i][0]);
for(j=1;fol[i][j]!=NULL;j++)
printf("%c,",fol[i][j]);
printf("\b ]");
}
getch();
return 0;
}

OUTPUT:

RollNo.

Page 23

Acropolis Institute of Technology and Research, Indore

RollNo.

Page 24

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 9
AIM: Write a program to generate parse tree.
PROGRAM:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#define MAX 100
int getREindex ( const char* )
{
signed char productions[MAX][MAX];
int count = 0 , i , j;
char temp[MAX + MAX] , temp2[MAX + MAX];
%token ALPHABET
%left '|'
%left '.'
%nonassoc '*' '+'
%%
S : re '\n' {
printf ( "This is the rightmost derivation--\n" );
for ( i = count - 1 ; i >= 0 ; --i ) {
if ( i == count - 1 ) {
printf ( "\nre => " );
strcpy ( temp , productions[i] );
printf ( "%s" , productions[i] );
}
else {
printf ( "\n => " );
j = getREindex ( temp );
temp[j] = '\0';
sprintf ( temp2 , "%s%s%s" , temp ,
productions[i] , (temp + j + 2) );
printf ( "%s" , temp2 );
strcpy ( temp , temp2 );
}}
printf ( "\n" );
exit ( 0 );
}
ALPHABET {
temp[0] = yylval; temp[1] = '\0';
strcpy ( productions[count++] , temp );
}
| '(' re ')'{ strcpy ( productions[count++] , "(re)" ); }
| re '*'{ strcpy ( productions[count++] , "re*" ); }
| re '+'{ strcpy ( productions[count++] , "re+" ); }
RollNo.

Page 25

Acropolis Institute of Technology and Research, Indore


| re '|' re{strcpy ( productions[count++] , "re | re" );}
| re '.' re{strcpy ( productions[count++] , "re . re" );}
%%
int main ( int argc , char **argv )
{
yyparse();
return 0;
}
yylex()
{
signed char ch = getchar();
yylval = ch;
if ( isalpha ( ch ) )
return ALPHABET;
return ch;
}
yyerror() {
fprintf(stderr , "Invalid Regular Expression!!\n");
exit ( 1 );
}
int getREindex ( const char *str )
{ int i = strlen ( str ) - 1;
for ( ; i >= 0 ; --i ) {
if ( str[i] == 'e' && str[i-1] == 'r' )
return i-1;}
}

OUTPUT:

RollNo.

Page 26

Acropolis Institute of Technology and Research, Indore

RollNo.

Page 27

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 10
AIM: Write a program to design lexical analyzer.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void removeduplicate();
void final();
int Isiden(char ch);
int Isop(char ch);
int Isdel(char ch);
int Iskey(char * str);
void removeduplicate();
char op[8]={'+','-','*','/','=','<','>','%'};
char del[8]={'}','{',';','(',')','[',']',','};
char *key[]={"int","void","main","char","float"};
//char *operato[]={"+","-","/","*","<",">","=","%","<=",">=","++"};
int idi=0,idj=0,k,opi=0,opj=0,deli=0,uqdi=0,uqidi=0,uqoperi=0,kdi=0,liti=0,ci=0;
int uqdeli[20],uqopi[20],uqideni[20],l=0,j;
char uqdel[20],uqiden[20][20],uqop[20][20],keyword[20][20];
char iden[20][20],oper[20][20],delem[20],litral[20][20],lit[20],constant[20][20];
void lexanalysis(char *str)
{
int i=0;
while(str[i]!='\0')
{
if(Isiden(str[i])) //for identifiers {
while(Isiden(str[i]))
{ iden[idi][idj++]=str[i++];
}
iden[idi][idj]='\0';
idi++;idj=0;
} else
if(str[i]=='"')
//for literals {
lit[l++]=str[i];
for(j=i+1;str[j]!='"';j++) {
lit[l++]=str[j];
}
lit[l++]=str[j];lit[l]='\0';
strcpy(litral[liti++],lit);
i=j+1; }
else
if(Isop(str[i]))
// for operators
{ while(Isop(str[i]))
{ oper[opi][opj++]=str[i++];
RollNo.

Page 28

Acropolis Institute of Technology and Research, Indore


}
oper[opi][opj]='\0';
opi++;opj=0;
}
else
if(Isdel(str[i])) {
while(Isdel(str[i]))
{ delem[deli++]=str[i++];
}}
else
{ i++;
}}
removeduplicate();
final();
}
int Isiden(char ch)
{
if(isalpha(ch)||ch=='_'||isdigit(ch)||ch=='.')
return 1;
else
return 0;
}
int Isop(char ch)
{ int f=0,i;
for(i=0;i<8&&!f;i++)
{ if(ch==op[i])
f=1;
}
return f;
}
int Isdel(char ch)
{
int f=0,i;
for(i=0;i<8&&!f;i++)
{ if(ch==del[i])
f=1;
} return f;
}
int Iskey(char * str)
{ int i,f=0;
for(i=0;i<5;i++) {
if(!strcmp(key[i],str))
f=1;
}
return f;
}
RollNo.

Page 29

Acropolis Institute of Technology and Research, Indore


void removeduplicate()
{ int i,j;
for(i=0;i<20;i++)
{ uqdeli[i]=0;
uqopi[i]=0;
uqideni[i]=0;
}
for(i=1;i<deli+1;i++) //removing duplicate delemeters
{
if(uqdeli[i-1]==0)
{
uqdel[uqdi++]=delem[i-1];
for(j=i;j<deli;j++)
{ if(delem[i-1]==delem[j])
uqdeli[j]=1;
}}}
for(i=1;i<idi+1;i++) //removing duplicate identifiers
{ if(uqideni[i-1]==0)
{
strcpy(uqiden[uqidi++],iden[i-1]);
for(j=i;j<idi;j++)
{if(!strcmp(iden[i-1],iden[j]))
uqideni[j]=1;
}}}
for(i=1;i<opi+1;i++) //removing duplicate operators
{ if(uqopi[i-1]==0)
{ strcpy(uqop[uqoperi++],oper[i-1]);
for(j=i;j<opi;j++)
{
if(!strcmp(oper[i-1],oper[j]))
uqopi[j]=1;
}}}}
void final()
{ int i=0;
idi=0;
for(i=0;i<uqidi;i++)
{ if(Iskey(uqiden[i]))
//identifying keywords
strcpy(keyword[kdi++],uqiden[i]);
else
if(isdigit(uqiden[i][0])) //identifying constants
strcpy(constant[ci++],uqiden[i]);
else
strcpy(iden[idi++],uqiden[i]);
}
printf("\n\tDelemeter are : \n");
for(i=0;i<uqdi;i++)
RollNo.

Page 30

Acropolis Institute of Technology and Research, Indore


printf("\t%c\n",uqdel[i]);
printf("\n\tOperators are : \n");
for(i=0;i<uqoperi;i++)
{
printf("\t");
puts(uqop[i]);
}
printf("\n\tIdentifiers are : \n");
for(i=0;i<idi;i++)
{
printf("\t");
puts(iden[i]);
}
printf("\n\tKeywords are : \n");
for(i=0;i<kdi;i++)
{
printf("\t");
puts(keyword[i]);
}
printf("\n\tConstants are :\n");
for(i=0;i<ci;i++)
{ printf("\t");
puts(constant[i]);
}
printf("\n\tLiterals are :\n");
for(i=0;i<liti;i++)
{ printf("\t");
puts(litral[i]);
}}
void main()
{
char str[50];
clrscr();
printf("\nEnter the string : ");
scanf("%[^\n]c",str);lexanalysis(str);
getch();
}

RollNo.

Page 31

Acropolis Institute of Technology and Research, Indore


OUTPUT:

RollNo.

Page 32

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 11
AIM: Write a program to implement operator precedence parsing.
PROGRAM:
#include<stdio.h>
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
void main()
{
int i=0,j=0,k=0,p[10];
char name[20];
char key[20]={'(',')','&','%','^','*','/','+','-','|',';'};
clrscr();
textcolor(2);
cprintf("---Operator Precedence-----\n");
cprintf("\nEnter the expression:");
scanf("%s",&name);
cprintf("\n---output----\n");
for(i=0;i<20;i++)
{
for(j=0;j<strlen(name);j++)
RollNo.

Page 33

Acropolis Institute of Technology and Research, Indore


{
char c;
c=tolower(name[j]);
if(!isalpha(c)&&!isdigit(c))
{
if(key[i]==c)
{
printf("\n %c is executed %d(%c %c %c)\n",c,k++,tolower(name[j1]),c,tolower(name[j+1]));
}
}
}
}
getch();
}

OUTPUT:

RollNo.

Page 34

Acropolis Institute of Technology and Research, Indore

RollNo.

Page 35

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 12
AIM: Write a program to recursive descendent parsing.
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
char input[10];
int i,error;
void E();
void T();
void Eprime();
void Tprime();
void F();
main()
{
i=0;
error=0;
printf("Enter an arithmetic expression : "); // Eg: a+a*a
gets(input);
E();
if(strlen(input)==i&&error==0)
printf("\nAccepted..!!!\n");
else printf("\nRejected..!!!\n");
getch();
}
void E()
{
T();
Eprime();
}
void Eprime()
{
if(input[i]=='+')
{
i++;
T();
Eprime();
}
}
void T()
{
F();
Tprime();
}
void Tprime()
{
RollNo.

Page 36

Acropolis Institute of Technology and Research, Indore


if(input[i]=='*')
{
i++;
F();
Tprime();
}
}
void F()
{
if(isalnum(input[i]))i++;
else if(input[i]=='(')
{
i++;
E();
if(input[i]==')')
i++;
else error=1;
}
else error=1;
}

OUTPUT:

RollNo.

Page 37

Acropolis Institute of Technology and Research, Indore


EXPERIMENT NO. 13
AIM: Study of an object oriented compiler.
THEORY:
A Compiler is a program that can read a program in one language the source language and
translate it into an equivalent program in another language the Target language . An important
role of the compiler is to report any errors in the source program that it detects during the
translation process. An object-oriented language is one that supports object-oriented
programming, a programming style in which a program consists of a collection of objects (i.e.
classes) that interact with one another.
The obvious candidate for object technology in a compiler is the symbol table, a mapping from
user-defined names to their properties as expressed in the program. If the internal representation
is a tree of objects, semantic checking and generation can be accomplished by sending a message
to these objects or by visiting each object. If the result of generation is a set of persistent objects,
program execution can consist of sending a message to a distinguished object in this set.
Object orientation was first introduced in Simula ( in 1967), and has been incorporated in
languages such as Smalltalk, C++, C#, and Java. We have gained them in several projects and
used them to great advantage in two courses on compiler construction with Objective C and Java
It turns out that OOP can be applied productively in every phase of a compiler implementation
and it delivers the expected benefits as :
1. Objects enforce information hiding and state encapsulation.
2. Methods help to develop by divide and conquer technique.
3. All work is carried out by messages , which can be debugged by instrumenting their
methods.
4. Most importantly, classes encourage code reuse between projects .
5. Inheritance allows code reuse within a project and modifications from one project to
another.
6. Modern class libraries contain many pre-fabricated algorithms and data structures.

RollNo.

Page 38

You might also like