0% found this document useful (0 votes)
15 views27 pages

CD Manual

Uploaded by

Deepa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views27 pages

CD Manual

Uploaded by

Deepa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

GCE,Bodi ,Department of CSE Prepared by Mrs.A.

SARANYA

CS3501- COMPILER DESIGN LAB

Ex no:1A

DEVELOP A LEXICAL ANALYZER TO RECOGNIZE A FEW PATTERNS IN


C
AIM:
To develop a lexical analyzer to identify identifiers, constants, comments,
operators etc using C program
ALGORITHM:
Step1: Start the program.
Step2: Declare all the variables and file pointers.
Step3: Display the input program.
Step4: Separate the keyword in the program and display it.
Step5: Display the header files of the input program
Step6: Separate the operators of the input program and display it.
Step7: Print the punctuation marks.
Step8: Print the constant that are present in input program.
Step9: Print the identifiers of the input program.

PROGRAM CODE:
//Develop a lexical analyzer to recognize a few patterns in C.

#include<string.h>
#include<ctype.h>
#include<stdio.h>
#include<stdlib.h>
void keyword(char str[10])
{
if(strcmp("for",str)==0||strcmp("while",str)==0||strcmp("do",str)==0||
strcmp("int",str)==0||strcmp("float",str)==0||strcmp("char",str)==0||
strcmp("double",str)==0||strcmp("printf",str)==0||strcmp("switch",str)==0||
strcmp("case",str)==0)
printf("\n%s is a keyword",str);
else
printf("\n%s is an identifier",str);
}
void main()
{
FILE *f1,*f2,*f3;
char c,str[10],st1[10];
int num[100],lineno=0,tokenvalue=0,i=0,j=0,k=0;
f1=fopen("input","r");
f2=fopen("identifier","w");
f3=fopen("specialchar","w");
while((c=getc(f1))!=EOF)
{
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

if(isdigit(c))
{
tokenvalue=c-'0';
c=getc(f1);
while(isdigit(c))
{
tokenvalue*=10+c-'0';
c=getc(f1);
}
num[i++]=tokenvalue;
ungetc(c,f1);
}
else
if(isalpha(c))
{
putc(c,f2);
c=getc(f1);
while(isdigit(c)||isalpha(c)||c=='_'||c=='$')
{
putc(c,f2);
c=getc(f1);
}
putc(' ',f2);
ungetc(c,f1);
}
else
if(c==' '||c=='\t')
printf(" ");
else
if(c=='\n')
lineno++;
else
putc(c,f3);
}
fclose(f2);
fclose(f3);
fclose(f1);
printf("\n the no's in the program are:");
for(j=0;j<i;j++)
printf("\t%d",num[j]);
printf("\n");
f2=fopen("identifier","r");
k=0;
printf("the keywords and identifier are:");
while((c=getc(f2))!=EOF)
if(c!=' ')
str[k++]=c;
else
{
str[k]='\0';
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

keyword(str);
k=0;
}
fclose(f2);
f3=fopen("specialchar","r");
printf("\n Special Characters are");
while((c=getc(f3))!=EOF)
printf("\t%c",c);
printf("\n");
fclose(f3);
printf("Total no of lines are:%d",lineno);
}

input file: (input)

create an empty file and name it


as specialchar and identifier
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

OUTPUT:

RESULT:

Thus the program for developing a lexical analyzer to recognize a few patterns
in C has been executed successfully.
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

Ex no:1B IMPLEMENTATION OF SYMBOL TABLE USING C


AIM:
To write a program for implementing Symbol Table using C.

PROGRAM CODE:
//Implementation of symbol table
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
void main()
{
int i=0,j=0,x=0,n;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
printf("Expression terminated by $:");
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

while((c=getchar())!='$')
{
b[i]=c;
i++;
}
n=i-1;
printf("Given Expression:");
i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\n Symbol Table\n");
printf("Symbol \t addr \t type");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
p=malloc(c);
add[x]=p;
d[x]=c;
printf("\n%c \t %d \t identifier\n",c,p);
x++;
j++;
}
else
{
ch=c;
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(ch);
add[x]=p;
d[x]=ch;
printf("\n %c \t %d \t operator\n",ch,p);
x++;
j++;
}}}}
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

Output:

RESULT:

Thus the program for symbol table has been executed successfully.
'
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

Ex No:2 IMPLEMENT A LEXICAL ANALYZER USING LEX TOOL


AIM:

To write a program for implementing a Lexical analyser using LEX tool in


Linux platform.
ALGORITHM:
Step1: Lex program contains three sections: definitions, rules, and user
subroutines. Each section must be separated from the others by a line
containing only the delimiter, %%.The format is as follows: definitions %% rules
%% user_subroutines

Step2: In definition section, the variables make up the left column, and their
definitions make up the right column. Any C statements should be enclosed in
%{..}%. Identifier is defined such that the first letter of an identifier is alphabet
and remaining letters are alphanumeric.

Step3: In rules section, the left column contains the pattern to be recognized
in an input file to yylex(). The right column contains the C program fragment
executed when that pattern is recognized. The various patterns are keywords,
operators, new line character, number, string, identifier, beginning and end of
block, comment statements, preprocessor directive statements etc.

Step4: Each pattern may have a corresponding action, that is, a fragment of C
source code to execute when the pattern is matched.

Step5: When yylex() matches a string in the input stream, it copies the
matched text to an external character array, yytext, before it executes any
actions in the rules section.

Step6: In user subroutine section, main routine calls yylex(). yywrap() is used
to get more input.

Step7: The lex command uses the rules and actions contained in file to
generate a program, lex.yy.c, which can be compiled with the cc command.
That program can then receive input, break the input into the logical pieces
defined by the rules in file, and run program fragments contained in the actions
in file.

PROGRAM CODE: (ex2.l)


//Implementation of Lexical Analyzer using Lex tool
%{
int COMMENT=0;
%}
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

identifier [a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
int |
float |
char |
double |
while |
for |
struct |
typedef |
do |
if |
break |
continue |
void |
switch |
return |
else |
goto {printf("\n\t%s is a keyword",yytext);}
"/*" {COMMENT=1;}{printf("\n\t %s is a COMMENT",yytext);}
{identifier}\( {if(!COMMENT)printf("\nFUNCTION \n\t%s",yytext);}
\{ {if(!COMMENT)printf("\n BLOCK BEGINS");}
\} {if(!COMMENT)printf("BLOCK ENDS ");}
{identifier}(\[[0-9]*\])? {if(!COMMENT) printf("\n %s IDENTIFIER",yytext);}
\".*\" {if(!COMMENT)printf("\n\t %s is a STRING",yytext);}
[0-9]+ {if(!COMMENT) printf("\n %s is a NUMBER ",yytext);}
\)(\:)? {if(!COMMENT)printf("\n\t");ECHO;printf("\n");}
\( ECHO;
= {if(!COMMENT)printf("\n\t %s is an ASSIGNMENT OPERATOR",yytext);}
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

\<= |
\>= |
\< |
== |
\> {if(!COMMENT) printf("\n\t%s is a RELATIONAL OPERATOR",yytext);}
%%
int main(int argc, char **argv)
{
FILE *file;
file=fopen("var.c","r");
if(!file)
{
printf("could not open the file");
exit(0);
}
yyin=file;
yylex();
printf("\n");
return(0);
}
int yywrap()
{
return(1);
}

INPUT:
//var.c
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
a=1;
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

b=2;
c=a+b;
printf("Sum:%d",c);
}
install lex tool refer screenshot
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

OUTPUT:
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

RESULT:

Thus the program for implementation of Lexical Analyzer using Lex tool has
been executed successfully.

Generate YACC specification for a few syntactic categories.


Ex No:3A
Program to recognize a valid arithmetic expression that uses operator +, -, * and /.

AIM:

To write a Yacc program to valid arithmetic expression using Yacc .

ALGORITHM:

Step1: Start the program.

Step2: Reading an expression .

Step3: Checking the validating of the given expression according to the rule using yacc.

Step4: Using expression rule print the result of the given values
Step5: Stop the program.

PROGRAM:
//Program to recognize a valid arithmetic expression that uses operator +, -, * and /

LEX PART: (3a.l)

%{

#include "y.tab.h"

%}

%%

[a-zA-Z_][a-zA-Z_0-9]* return id;

[0-9]+(\.[0-9]*)? return num;


GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

[+/*] return op;

. return yytext[0];

\n return 0;

%%

int yywrap()

return 1;

YACC PART: (3a.y)


%{

#include<stdio.h>

int valid=1;

%}

%token num id op

%%

start : id '=' s ';'

s: id x

| num x

| '-' num x

| '(' s ')' x

;
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

x: op s

| '-' s

%%

int yyerror()

valid=0;

printf("\nInvalid expression!\n");

return 0;

int main()

printf("\nEnter the expression:\n");

yyparse();

if(valid)

printf("\nValid expression!\n");

}
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

OUTPUT:

RESULT:

Thus the program for validating the arithmetic expression using yacc tool has been
executed successfully.
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

Ex No:3b PROGRAM TO RECOGNIZE A VALID VARIABLE WHICH STARTS WITH A


LETTER FOLLOWED BY ANY NUMBER OF LETTERS OR DIGITS

AIM :

To write a yacc program to check valid variable followed by letter or digits

ALGORITHM:

Step1: Start the program

Step2: Reading an expression

Step3: Checking the validating of the given expression according to the rule using yacc.

Step4: Using expression rule print the result of the given values

Step5: Stop the program

PROGRAM CODE:

//Program to recognize a valid variable

LEX PART: (3b.l)


%{

#include "y.tab.h"

%}

%%

[a-zA-Z_][a-zA-Z_0-9]* return letter;

[0-9] return digit;

. return yytext[0];

\n return 0;

%%

int yywrap()

return 1;
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

YACC PART: (3b.y)

%{

#include<stdio.h>

int valid=1;

%}

%token digit letter

%%

start : letter s

s: letter s

| digit s

%%

int yyerror()

printf("\nIts not a identifier!\n");

valid=0;

return 0;

int main()

printf("\nEnter a name to tested for identifier ");

yyparse();

if(valid)
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

printf("\nIt is a identifier!\n");

OUTPUT:

RESULT:
Thus the program to check a valid variable followed by letter or digits using
yacc tool has been executed successfully.
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

Ex No:3c Program to recognize a valid control structures syntax of c


language(For loop, While loop, if-else, if-else-if, switch case,
etc.,

AIM
To write a program to recognize a valid control structures syntax of c language (For loop,
While loop, if-else, if-else-if, switch case, etc.

ALGORITHM
Step 1: Take the C code as input.
Step 2: Tokenize the input code. Split the code into individual tokens (keywords, identifiers,
operators, etc.) for easier processing.
Step 3: Syntax Checking:
For Loop:
Check for tokens that match the pattern: for (initialization; condition; increment) {/* code */}
Ensure proper semicolons separating initialization, condition, and increment parts.
Recursively check the code inside the loop using the same steps.
While Loop:
Check for tokens that match the pattern: while (condition) {/* code */}
Ensure proper parentheses and braces.
Recursively check the code inside the loop.
If-Else Statements:
Check for tokens that match the pattern: if (condition) {/* code */} else {/* code */}
Ensure proper parentheses and braces for both if and else parts.
Recursively check the code inside both if and else blocks.
Else-If Ladder:
Check for tokens that match the pattern:
if (condition) { /* code */ } else if (condition) { /* code */ } ... else { /* code */ }
Ensure proper parentheses and braces for each if and else block.
Recursively check the code inside each block.
Switch-Case Statements:
Check for tokens that match the pattern:
switch (variable) { case constant1: /* code */ break; case constant2: /* code */ break; ... default:
/* code */ break; }
Ensure proper parentheses, colons after cases, and break statements.
Recursively check the code inside each case and default block.
Step 4: If the code passes all syntax checks, output a message indicating that the control
structures are valid. Otherwise, indicate the specific error encountered during the parsing
process.
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

PROGRAM:
LEX PART: ex3c.l

%{
#include<stdio.h>
#include "ex3c.tab.h"
%}
%%
"if" { return IF; }
"else" { return ELSE; }
"while" { return WHILE; }
"for" { return FOR; }
"switch" { return SWITCH; }
"case" { return CASE; }
"default" { return DEFAULT; }
"break" { return BREAK; }
"(" { return OPEN_BRACKET; }
")" { return CLOSE_BRACKET; }
"{" { return OPEN_BRACE; }
"}" { return CLOSE_BRACE; }
";" { return SEMICOLON; }
[\t\n] ;
. ;
%%
int yywrap()
{
return 1;
}

YACC PART: ex3c.y

%{
#include<stdio.h>
int yylex();
%}
%token IF ELSE WHILE FOR SWITCH CASE DEFAULT OPEN_BRACE CLOSE_BRACE
SEMICOLON COLON OPEN_BRACKET CLOSE_BRACKET BREAK
%%
program: statement
| program statement
;
statement:if_statement
|while_loop
|switch_case_statement
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

|for_loop
;
if_statement:IF OPEN_BRACKET expression_opt CLOSE_BRACKET OPEN_BRACE
expression_opt CLOSE_BRACE ELSE OPEN_BRACE expression_opt CLOSE_BRACE
{
printf("Recognized IF Else statement\n");
}
;
while_loop:WHILE OPEN_BRACKET expression_opt CLOSE_BRACKET OPEN_BRACE
expression_opt CLOSE_BRACE
{
printf("Recognized WHILE loop\n");
}
;
switch_case_statement:SWITCH OPEN_BRACKET expression_opt CLOSE_BRACKET
OPEN_BRACE case_list CLOSE_BRACE
{
printf("Recognized SWITCH_CASE statement with DEFAULT\n");
}
;
for_loop:FOR OPEN_BRACKET expression_opt SEMICOLON expression_opt
CLOSE_BRACKET OPEN_BRACE expression_opt CLOSE_BRACE
{
printf("Recognized FOR loop\n");
}
;
case_list:CASE expression COLON expression BREAK
SEMICOLON DEFAULT COLON expression_opt
;
expression_opt:/*empty*/
|expression
|expression SEMICOLON
;
expression:
;
%%
int yyerror(const char *s)
{
fprintf(stderr,"Error=%s\n", s);
return 1;
}
int main() {
if(yyparse()==0){
printf("Parsing completed successfully\n");
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

}
else{
fprintf(stderr,"Parsing encountered errors\n");
}
return 0;
}

OUTPUT:

RESULT:
Thus the program to recognize a valid control structures syntax of c language(For loop,
While loop, if-else, if-else-if, switch case,etc.,was executed successfully.
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

Ex no:3d Implement an Arithmetic Calculator using LEX and YACC

AIM
To write a program for implementing a calculator for computing the given expression using
semantic rules of the YACC tool and LEX.
ALGORITHM
1.A Yacc source program has three parts as follows: Declarations %% translation rules %%
supporting C routines
2.Declarations Section: This section contains entries that:
 Include standard I/O header file.
 Define global variables.
 Define the list rule as the place to start processing.
 Define the tokens used by the parser.
 Define the operators and their precedence.
3.Rules Section: The rules section defines the rules that parse the input stream. Each rule of
a grammar production and the associated semantic action.
4.Programs Section: The programs section contains the following subroutines. Because these
subroutines are included in this file, it is not necessary to use the yacc library when
processing this file.
Main- The required main program that calls the yyparse subroutine to start the program.
yyerror(s) -This error-handling subroutine only prints a syntax error message.
yywrap -The wrap-up subroutine that returns a value of 1 when the end of input occurs. The
calc.lex file contains include statements for standard input and output, as programmar file
information if we use the -d flag with the yacc command. The y.tab.h file contains
definitions for the tokens that the parser program uses.
5. calc.lex contains the rules to generate these tokens from the input stream.

PROGRAM CODE
LEX PART: (ex3d.l)

%{
#include <stdio.h>
#include "ex3d.tab.h"
extern int yylval;
%}
%%
[0-9]+ {
yylval = atoi(yytext);
return NUMBER;
}
[ \t] ;
[\n] return 0;
. {return yytext[0];}
%%
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

int yywrap()
{
return 1;
}

YACC PART: ex3d.y


%{
#include <stdio.h>
int flag = 0;
%}
%token NUMBER
%left '+' '-'
%left '*' '/' '%'
%left '(' ')'
%%
ArithmeticExpression: E {
printf("Result = %d\n", $1);
return 0;
};
E: E '+' E { $$ = $1 + $3; }
| E '-' E { $$ = $1 - $3; }
| E '*' E { $$ = $1 * $3; }
| E '/' E { $$ = $1 / $3; }
| E '%' E { $$ = $1 % $3; }
| '(' E ')' { $$ = $2; }
| NUMBER { $$ = $1; }
;
%%
int main()
{
printf("\nEnter an arithmetic expression that can have operations Addition, Subtraction,
Multiplication,Division, Modulus and Round brackets: ");
yyparse();
if (flag == 0) {
printf("\nEntered arithmetic expression is Valid\n");
}
return 0;
}
void yyerror(const char* s)
{
printf("\nEntered arithmetic expression is Invalid\n");
flag = 1;
}
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

OUTPUT:

Result:
Thus the program for implementing a calculator for computing the given expression
using semantic rules of the YACC tool and LEX was executed successfully.
GCE,Bodi ,Department of CSE Prepared by Mrs.A.SARANYA

You might also like