0% found this document useful (0 votes)
29 views

Cdrec 1

Compiler Design Lab Manual

Uploaded by

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

Cdrec 1

Compiler Design Lab Manual

Uploaded by

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

EX NO: 1(a)

DEVELOP A LEXICAL ANALYZER TO RECOGNIZE


DATE : A FEW PATTERNS IN C

AIM:
To develop a lexical analyser to recognize a few patterns in C using the LEX tool.

ALGORITHM:
STEP 1: Start the program by including the necessary header files.
STEP 2: Declare global variables and arrays to store keywords, header files,
operators, punctuation, and other data.
STEP 3: Open the input file “input.c” in read mode and store the file pointer in’fp’.
STEP 4: Print “Input program” to the console.
STEP 5: Iterate through the input file until the end is reached, Read and store a
character from the file in arr[0] and print the character to the console.
STEP 6: Close the input file using ‘fclose(fp)’.
STEP 7: Print the “symbol table” to the console.
STEP 8: Reopen the input file “input.c” in read mode, store the file pointer in ‘fp’.
STEP 9: Print”keywords” to the console.
STEP 10: Iterate through the input file until the end is reached.
1. Read and store a character from the file in ‘arr[0]’.
2. Read a word from the file using’fscanf()’.
3. Check if the read word is one of the predefined keywords in the
‘kw’ array. If it matches a keyword print the keyword to the
console.

STEP 11: Close the input file using ‘fclose(fp)’..


STEP 12: Repeat the step 8,9,10 process for Operators, Punctuation, Identifiers,
Constants.
STEP 13: Close the input file using ‘fclose(fp)’.
STEP 14: Wait for the user input to keep the console window open.

1
PROGRAM:(pattern.c)
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<string.h>
void main()
{
FILE *fp;
int i,j;
char arr[100],k;
char
kw[10][10]={"int","float","double","end","main","void","include","printf","scanf"};
char hf[2][10]={"stdio.h","conio.h"};
char op[5]={'+','-','*','/','%'};
char punc[6]={'(',')','{','}',','};
clrscr();
fp=fopen("input.c","r");
printf("Input Program:\n\n");
while(!feof(fp))
{
arr[0]=fgetc(fp);
printf("%c",arr[0]);
}
fclose(fp); printf("\
nSymbol table:\n");
fp=fopen("input.c","r");
printf("\nKeywords");
while(!feof(fp))
{
arr[0]=fgetc(fp);
fscanf(fp,"%s",arr);
for(i=0;i<10;i++)
{
if(strcmp(arr,kw[i])==0)
{
printf("\t%s",arr);
}
}
}
fclose(fp);
/*fp=fopen("input.c","r");
printf("\nHeader files");

while(!feof(fp))
{
arr[0]=fgetc(fp);
fscanf(fp,"%s",arr);
for(i=0;i<2;i++)
{
if(strcmp(arr,hf[i])==0)

2
{
printf("\t%s",arr);
}
}
}
fclose(fp);*/
fp=fopen("input.c","r");
printf("\nOperators");
while(!feof(fp))
{
arr[0]=fgetc(fp);
for(i=0;i<5;i++)
{
if(arr[0]==op[i])
{
printf("\t%c",arr[0]);
}
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\nPunctuation");
while(!feof(fp))
{
arr[0]=fgetc(fp);
for(i=0;i<6;i++)
{
if(arr[0]==punc[i])
{
printf("\t%c",arr[0]);
}
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\nConstants ");
while(!feof(fp))
{

arr[0]=fgetc(fp);
if(isdigit(arr[0]))
{
printf("\t%c",arr[0]);
}
}
fclose(fp);
fp=fopen("input.c","r");
printf("\nIdentifier\t");
while(!feof(fp))
{

3
fscanf(fp,"%s",arr);
for(i=0;i<2;i++)
{
if(strcmp(arr,kw[i])==0)
{
fscanf(fp,"%s",arr);
j=0;
while(j<strlen(arr)&&arr[j]!=';')
{
printf("%c",arr[j]);
j++;
}
}
}

}
fclose(fp);
getch();
}

INPUT:(input.c)
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c;
clrscr();
a=2;
b=3;
c=a+b;
printf("The sum is %d",c);
getch();
}

4
OUTPUT:

RESULT:
Thus the implementation of lexical analyzer to recognize a few patterns in C using
LEX tool is executed successfully.

5
EX NO: 1(b)
IMPLEMENTATION OF SYMBOL TABLE
DATE :

AIM:
To implement the symbol table using the C.

ALGORITHM:
STEP 1: Start the program.
STEP 2: Include the necessary header files
STEP 3: Declare the variables ‘i’, ’j’, ’x’, ’n’, ’flag’ , ’p’, ’add[5]’, ’ch’, ’srch’,
’b[15]’, ’d[15]’ and ‘c’.
STEP 4: Prompt the user to enter an expression terminated by the ‘$’ symbol.
Continuously read characters from the user until ‘$’ is entered, and stored these
characters in array ‘b’
STEP 5: Calculate the length of the entered expression (‘n’).
STEP 6: Print “given expression” and then, using a loop display the characters of the
expression from the ‘b’ array
STEP 7: Print the header for the symbol table with columns “symbol”, “adder”, and
“type”.
STEP 8: Initialize ‘j’ to 0 to start scanning the expression.
STEP 9: Iterate through Expressions
1. Get the character at position ‘j’ from the ‘b’ array and store it in
‘c’.
2. Check if ‘c’ is an alphabetical character using ‘isalpha(toascii(c))’.
3. If ‘c’ is an alphabetical character, check if ‘j’ is equal to ‘n’(end of
the expression)
a. Allocate memory for identifier and store its address in ‘p’
b. Store the identifier in the ‘d’ array at position ‘x’.
c. Display the symbol in the symbol table.
4. If ‘j’ is not at the end
a. Get the next character ‘ch’.
b. Check if ‘ch’ is one of ‘+’, ‘=’, ‘*’, or ‘-’.
c. Allocate memory for the identifier , store its address in ‘p’.
d. Store the identifier in the ‘d’ array at position ‘x’.
e. Display the symbol and symbol table and increment ‘x’.
5. Increment ‘j’ to move to the next character in the expression.

STEP 10: Prompt the user to enter the symbol to search for, and store it in the ‘srch’.
STEP 11: Loop through the symbol enteries, Display the symbol table entry for the
searched symbol and set the ‘flag’ variable to 1 to
\indicate a successful search.
STEP 12: If the flag is still 0 after the search loop, display a message indicating that
the symbol was not found.
STEP 13: Use ‘getch()’ to wait for user input and exit the program.

6
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#include<alloc.h>
#include<string.h>
#include<math.h>
void main()
{
int i=0,j=0,x=0,n=0,flag=0;
void *p,*add[5];
char ch,srch,b[15],d[15],c;
clrscr();
printf("expression terminated by $:");
while((c=getchar())!='$')
{
b[i]=c;
i++;
}
n=i-1;
printf("given expression:");
i=0;
while(i<=n)
{
printf("%c",b[i]);
i++;
}
printf("\nsymbol table:\n");
printf("symbol\tadder\ttype");
while(j<=n)
{
c=b[j];
if(isalpha(toascii(c)))
{
if(j==n)
{
p=malloc(c);
add[x]=p;
d[x]=c; printf("%c\t%d\
tidentifier",c,p);
}
els
e
{

ch=b[j+1];
if(ch=='+'||ch=='-'||ch=='*'||ch=='=')
{
p=malloc(c);
add[x]=p;
d[x]=c;
7
printf("\n%c\t%d\tidentifier\n",c,p);
x++;
}
}
} j+
+;
}
printf("\nThe symbol is to be searched");
srch=getch();
for(i=0;i<=x;i++)
{
if(srch==d[i])
{
printf("\nSymbol table:"); printf("\n%c\t%s\t%d\
n",srch,"@address",add[i]); flag=1;
}
}
if(flag==0)
printf("\nsymbol not found");
getch();
}

OUTPUT:

RESULT:
Thus the execution of implementing the symbol table using C is executed
successfully.

8
EX NO: 2
IMPLEMENTATION OF LEXICAL ANALYZER
DATE : USING LEX TOOLS

AIM:
To implement the lexical analyzer using LEX tools.
ALGORITHM:
STEP 1: The program starts with ‘%{‘ and ‘%}’ tags, which enclose C code to be
included directly in the generated C program.
STEP 2: Define a regular expression to recognize identifiers. It matches strings
starting with a letter followed by letters, numbers, or underscores.
STEP 3: Use ‘%%’ to separate the initialization section from the rules section.’ to
separate the initialization section from the rules section.
STEP 4: Define a rule to match and print pre-processor directives using ‘#.*’ and the
content of the directive is printed.
STEP 5: Define a list of C keywords. When any of these keywords are encountered,
the program prints that it’s a keyword.
STEP 6: Define a rule to recognize and print function names when they are followed
by an opening parenthesis.
STEP 7: Define rules to recognize the start ‘\{‘ and end ‘\}’ of code blocks, printing
corresponding messages.
STEP 8: Define rules for various operators and relational operators. When any of
these are encountered, print that it’s an operator or a relational operator.
STEP 9: Define a rule to recognize and print numbers using ‘[0-9]+’. When a
sequence of digits is found, print it as a number.
STEP 10: Define a rule to recognize and print string literals enclosed in double
quotes ‘\”.*\”’.
STEP 11: Define rules for any other characters using ‘.’ Or newlines ‘\n’. These
characters are not explicitly printed but are part of the processing flow.
STEP 12: Create a main function, open and read the “input.c” file.
STEP 13: If it fails to open,, print an error message and exit.
STEP 14: Set the input for the lexer to be the file and call’yylex()’ to perform lexical
analysis.
STEP 15: After analysis, print two newlines for separation and return 0 to indicate
successful execution

9
PROGRAM: (lex.l)

%{
%}
identifier[a-zA-Z][a-zA-Z0-9]*
%%
#.* {printf("\n%s is a preprocessor directive",yytext);}
int |
float |
char |
double |
while |
do |
if |
break |
continue |
void |
switch |
return |
else |
goto {printf("\n%s is a keyword",yytext);}
{identifier}\( {printf("\n function %s",yytext);}
\{ {printf("\nblock begins");}
\} {printf("\nblock ends");}
\( {printf("\n");ECHO;}
{identifier}(\[[0-9]*\])* {printf("\n%s is an identifier",yytext);}
\".*\" {printf("\n %s is a string ",yytext);}
[0-9]+ {printf("\n%s is a number",yytext);
}
\<= |
\>= |
\< |
\> |
\== {printf("\n %s is a relational operator",yytext);}
\= |
\+ |
\- |
\/ |
\& |
% {printf("\n %s is a operator",yytext);}
.|
\n;
%%
int main(int argc,char **argv)
{
FILE *file;
file=fopen("input.c","r");
if(!file)
{
printf("could not open the file!!!");

10
exit(0);
}
yyin=file;
yylex();
printf("\n\n");
return(0);
}
int yywrap()
{
return 1;
}

INPUT: (input.c)

#include<stdio.h>
void main()
{
int a,b,c;
printf("enter the value for a,b");
scanf("%d%d",&a,&b)';
c=a+b;
printf("the value of c:%d",&c);
}

OUTPUT:

RESULT:
Thus the program to implement the lexical analyzer using LEX tool is executed
successfully.

11
EX NO: 3(a) PROGRAM TO RECOGNIZE A VALID ARITHMETIC
EXPRESSION USING YACC SPECIFICATIONS
DATE :

AIM:
To write a program to recognize a valid arithmetic expression that uses operator ‘+’,
’-‘, * and / using YACC specification.

ALGORITHM:
STEP 1: The program starts with ‘%{‘ and ‘%}’ tags, which enclose C code that will
be directly included in the generated C program. In this standard libraries are
included, and the type ‘YYSTYPE’ is defined as double.
STEP 2: Define a token type called ’num’ to represent numeric values in the
grammer rules.
STEP 3: Define the precedence and associativity of the operators ‘+’ and ‘-‘ and the
operators ‘*’ and ‘/’.
STEP 4: Use ‘%%’ to separate the Lex section form the YACC section.
STEP 5: Define a set of grammar rules for the YACC parser.
STEP 6: Define the expression rule.
STEP 7: Create the ‘main’ function, print a message asking the user to enter an
expression to validate.
STEP 8: Call the ‘yyparse()’ to initiate the parsing process.
STEP 9: Create the ‘yylex’ function, which is responsible for scanning the input
stream.
STEP 10: Define the ‘yyerror’ function, to handle the error messages.
STEP 11: The ‘main’ function prints a prompt and calls ‘yyparse()’ to initiate the
parsing process.
STEP 12: End of the program.

12
PROGRAM: (operator.y)
%{
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include<string.h>
#define YYSTYPE double
%}
%token num
%left '+' '-'
%left '*' '/'
%%
st: st expr '\n' {printf("Valid");}
|st '\n'
|
|error '\n' {printf("INVALID");}
;
expr: num
|expr '+' expr
|expr ‘*’ expr
|expr '/' expr
%%
main() {
printf(" ENTER AN EXPRESSION TO VALIDATE");
yyparse();
}
yylex()
{
int ch;
while((ch=getchar())==' ');
if(isdigit(ch)|ch=='.') {
ungetc(ch,stdin);
scanf("%lf",&yylval);
return num;
}
return ch;
}
yyerror(char *s)
{
printf("%S",s);
}

13
OUTPUT:

RESULT:
Thus the program to recognize a valid arithmetic expression that uses operator ‘+’, ’-‘,
* and / using YACC specification is executed successfully.

14
RECOGNIZE
EXANO:
VALID
3(b) VARIABLE WHICH STARTS WITH A LETTER FOLLOWED BY ANY

DATE :

AIM:
To develop a program to recognize a valid variable which starts with a letter followed
by any number of letters or digits.

ALGORITHM:
STEP 1: Start the program with YACC initialization section, which may include ‘%’
and ‘%}’ tags for embedding C code.
STEP 2: Define a token for representing identifiers, which can be used to recognize
variables.
STEP 3: Define grammar rules to specify the structure of valid variables.
STEP 4: Define a set of functions for scanning the input stream and handling error
messages.
STEP 5: Include a ‘main’ function to read input and initiate the parsing process.
STEP 6: End of the program.

15
PROGRAM: (digit.y)
%{
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
%}
%token let dig
%%
TERM: XTERM'\n'{printf("\nAccepted\n");exit(0);}
|error {yyerror("Rejected\n");exit(0);}
;
XTERM: XTERM let
|XTERM dig
|let
;
%%
main()
{
printf("Enter a variable:");
yyparse();
}
yylex()
{
char ch;
while((ch=getchar())=='');
if(isalpha(ch))
return let;
if(isdigit(ch))
return dig;
return ch;
}
yyerror(char *s)
{
printf("%s",s);
}

16
OUTPUT:

RESULT:
Thus the program to recognize a valid variable which starts with a letter followed
by any number of letters or digits has successfully executed.

17
EX NO: 3(c) RECOGNIZE A VALID CONTROL STRUCTURE SYNTAX OF C L

DATE :

AIM :
To develop a program to recognize a valid control structures syntax of C language
(for loop ,while loop , if – else , if-else if- else )

ALGORITHM :
STEP 1: Start .
STEP 2: Read the input source code character by character
STEP 3: Tokenize the input into a stream of tokens (e.g., keywords, identifiers,
operators, and literals).
STEP 4: Use a Yacc/Bison-based grammar to define the syntax of C control
structures. Define rules for control structures like if, while, and for statements.
STEP 5: Perform semantic checks, including type checking, scoping, and variable
resolution. Ensure that variables are declared before use and that their types match
in expressions.
STEP 6: Generate intermediate code or target code (e.g., assembly) based on the AST
for further processing or execution.
STEP 7: Detect and report syntax errors and semantic errors, providing meaningful
error messages to the user.
STEP 8: Stop .

18
PROGRAM :
Lexer.l
%{
#include <stdio.h>
#include "y.tab.h"
%}
%%
"if" { return IF; }
"else" { return ELSE; }
"while" { return WHILE; }
"for" { return FOR; }
"(" { return LPAREN; }
")" { return RPAREN; }
"{" { return LBRACE; }
"}" { return RBRACE; }
";" { return SEMICOLON; }
[a-zA-Z_][a-zA-Z0-9_]* { yylval.sval = strdup(yytext); return IDENTIFIER; }
[0-9]+ { yylval.ival = atoi(yytext); return INT_LITERAL; }
[ \t\n] ; // Skip whitespace
. { fprintf(stderr, "Error: Unrecognized token: %s\n", yytext); }
%%
int yywrap() {
return 1;
}

Parser.y
%{
#include <stdio.h>
%}

%token IF ELSE WHILE FOR


%token LPAREN RPAREN LBRACE RBRACE SEMICOLON
%token IDENTIFIER INT_LITERAL
%%
program:
| control_structure
| program control_structure
;
control_structure
: if_statement
| while_loop
| for_loop
;
if_statement:
IF LPAREN condition RPAREN LBRACE program RBRACE
| IF LPAREN condition RPAREN LBRACE program RBRACE ELSE LBRACE program
RBRACE
;
while_loop:
WHILE LPAREN condition RPAREN LBRACE program RBRACE

19
;
for_loop:
FOR LPAREN expression SEMICOLON condition SEMICOLON expression RPAREN
LBRACE program RBRACE
;
condition:
expression
;
expression:
IDENTIFIER
| INT_LITERAL
| expression "+" expression
| expression "-" expression
| expression "*" expression
| expression "/" expression
;
%%
int main() {
if (x > 10) {
y = x + 5;
} else {
y = x - 5;
}
while (y > 0) {
x = x - 1;
}
for (i = 0; i < 5; i = i + 1) {
x = x + i;
}
yyparse();
printf("Parsing completed.\n");
return 0;}

OUTPUT :
Parsing completed .

RESULT :
Thus the c program to develop a program to recognize a valid control structures
syntax of C language (for loop ,while loop , if – else , if-else if- else ) is successfully
executed.

20
EX NO: 3(d)
IMPLEMENTATION OF CALCULATOR USING
DATE : LEX AND YACC

AIM:
To write a program for the implementation of calculator using LEX and YACC
specifications.

ALGORITHM: (Lex Specification)


STEP 1: Start the program by defining the Lex specification which involves
recognizing tokens in the input expression.
STEP 2: Define the regular expressions for recognizing numbers, operators, and
parenthesis.
STEP 3: Include additional rules or definitions needed for special tokens, such as
functions and constants.
STEP 4: Use ‘%token’ to declare token names, which will use in YACC
specification.

ALGORITHM: (YACC Specification)


STEP 1: Define a grammar rule for the ‘expression’ or ‘program’ will represent the
input.
STEP 2: Define rules for various types of expressions, including addition,
subtraction, multiplication, division, parentheses, and more complex operations like
functions.
STEP 3: Use semantic actions within the rules to build the syntax tree.
STEP 4: Handle operator precedence and associativity by declaring them using
‘%left’, ‘%right’, or ‘%nonassoc’
STEP 5: Traverse the syntax tree using a recursive algorithm. Starting from the root
node, recursively calculate the result by following the tree’s structure.
STEP 6: Evaluate basic arithmetic operations and handle parenthesis according to the
syntax tree’s structure.
STEP 7: In the ‘main’ function, prompt the user to enter an expression and provide
instructions.
STEP 8: Initialize the lexer and parser, call the lexer and parser to tokenize and parse
the input expression.
STEP 9: Retrieve and print the result from the syntax tree.
STEP 10: Implement error handling to catch issues like division by zero or invalid
input expressions.
STEP 11: Run the program and allow users to enter the mathematical expression,
which are tokenized, parsed, and evaluated.

21
PROGRAM: (cal.l)

%{
#include<stdio.h>
#include<math.h>
#include"y.tab.h"
%}
%%
([0-9]+|([0-9]*\.[0-9]+)([eE][-+]?[0-9]+)?) {yylval.dval=atof(yytext);
return NUMBER;}
MEM {return MEM;}
[\t];
\$ {return 0;}
\n {return yytext[0];}
{return yytext[0];}
%%

PROGRAM: (cal.y)
%{
#include<stdio.h>
#include<math.h>
double memvar;
%}
%union{ dou
ble dval;}
%token<dval> NUMBER
%token<dval> MEM
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
%type<dval> expression%%
start:statement '\n'
|start statement '\n'
statement:MEM '=' expression {memvar=$3;}
|expression {printf("answer=%g\n",$1);};
expression:expression'+'expression {$$=$1+$3;}
|expression'-'expression {$$=$1-$3;}
|expression'*'expression {$$=$1*$3;}
|expression'/'expression {if($3==0)
yyerror("divide by zero");
else
$$=$1/$3;};
expression:'-'expression %prec UMINUS {$$= -$2;}
|'('expression')' {$$=$2;}
|NUMBER {$$=$1;}
|MEM {$$=memvar;};
%%
int main(void)
{

22
printf("Enter the expression");
yyparse();
printf("\n\n");
return 0;
}
int yywrap(){
return 0;
}
int yyerror(char *error){
printf("%s\n",error);
return 0;
}

OUTPUT:

RESULT:
Thus the program for the implementation of calculator using LEX and YACC
specifications has been successfully executed.

23
EX NO:4
GENERATE A THREE ADDRESS CODE FOR
DATE: A SIMPLE PROGRAM USING LEX AND
YAAC

AIM :
Write a C program to generate a three address code for a simple program using lex
and yaac .

ALGORITHM :
STEP 1: Start .
STEP 2: Define lexical rules for recognizing tokens like numbers, operators, and
whitespace. Use regular expressions to match and tokenize the input expression.
(lexer.l) .
STEP 3: Define the YAAC grammar rules for the program structure. Specify how
expressions are constructed, including precedence and associativity of operators.
STEP 4: Define data structures for storing the parsed input, such as a symbol table for
variables and their values. Declare variables for temporary variables used in the three-
address code.
STEP 5: Extend the Yacc rules to generate three-address code during
parsing. Introduce temporary variables to hold intermediate results. Emit code
for each operation (e.g., addition, multiplication) as you parse the input
expression.
STEP 6: Now we should write the main program .
STEP 7: Compile the YAAC and LEX code with the main program .
STEP 8 :Stop .

24
PROGRAM :
Lexer.l
%{
#include "parser.tab.h"
%}
DIGIT [0-9]
WS [ \t\n]
%%
{DIGIT}+ {
yylval.num = atoi(yytext);
return NUM;
}
{WS} /* Skip whitespace */
. {}
%%

Parser.y
%{
#include <stdio.h>
extern int yylex();
void yyerror(const char* s);
%}
%token NUM
%left '+' '-'
%left '*' '/'
%%
program:
expr { printf("%d\n", $1); }
;
expr:
expr '+' expr {
$$ = $1 + $3;
printf("ADD t%d, t%d, t%d\n", ++temp_count, $1, $3);
}
| expr '*' expr {
$$ = $1 * $3;
printf("MUL t%d, t%d, t%d\n", ++temp_count, $1, $3);
}
| NUM {
$$ = $1;
printf("t%d = %d\n", ++temp_count, $1);
}
;
%%
int main() {
yyparse();
return 0;
}
void yyerror(const char* s) {
fprintf(stderr, "Error: %s\n", s);

25
}
int temp_count = 0;
int main() {
yyparse();
return 0;
}

Compile the program


lex lexer.l
yacc -d parser.y
gcc lex.yy.c y.tab.c -o your_compiler

Run the program


./your_compiler

OUTPUT :
Input :3 + 4 * 5
t1 = 3
t2 = 4
t3 = 5
t4 = t2 * t3
t5 = t1 + t4
15

RESULT :
Thus a C program to generate a three address code for a simple program using lex and
yaac is successfully executed .

26
EX NO :5
IMPLEMENT TYPE CHECKING USING LEX AND YAAC
DATE :

AIM :
To write a C program to implement type checking using LEX and YAAC .

ALGORITHM :
STEP 1: Start .
STEP 2: Define the context free grammer .
STEP 3: Use Lex (or Flex) to create a scanner that reads the source code and
generates tokens. Define regular expressions to match keywords, identifiers, literals,
and other language constructs.
STEP 4: Use Yacc (or Bison) to create a parser that reads the tokens produced by the
scanner and constructs an abstract syntax tree (AST) based on your grammar rules
STEP 5: Define a set of semantic rules and type checking algorithms to verify that
expressions and assignments are type-correct according to your language's rules.
STEP 6: When a type error is encountered during traversal, report the error with a
description of what went wrong and the location in the source code where the
error occurred.
STEP 7: After parsing and type checking, you can generate intermediate code,
bytecode, or report the success or failure of type checking to the user.
STEP 8: Stop .

27
PROGRAM :
#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
int check(char c[25])
{
int i,f=1;
for(i=0;i<strlen(c);i++)
{
if(!(isdigit(c[i])))
{ f=
0;
break;
}
}
if(f==1)
return 1;
else
return 0;
}
void main()
{
int i,j;
char a[25],b[25];
clrscr();
printf("\nEnter the 2 nos.");
scanf("%s%s",a,b);
i=check(a);
j=check(b);
if(i==0 || j==0)
printf("Type mismatch");
else
printf("\nsum:=%d",atoi(a)+atoi(b));
getch();
}

28
OUTPUT :

RESULT :
Thus a C program to implement type checking using LEX and YAAC is successfully
executed .

29

You might also like