AIM:
To create a simple scanner using FLEX (Fast LEXical analyzer) for recognizing and displaying the tokens like identifier, number, operator and delimiters used in Declaration and Assignment Statements.
ALGORITHM:
1. Declare constants for the tokens like Identifier (ID), number (NUM), operator (OP), and delimiter (DELIM).
2. Include the option noyywrap.
3. Specify the tokens using Regular Expression (R.E.) notations.
4. Return the corresponding constant at the recognition of each and every token in main().
5. Declare the variable ‘id’ for holding the return value
6. Call the function yylex() to get the next token from the lexical analyzer and store it in ‘id’.
7. Check the value of ‘id’. If it is greater than 0 (id>0) then conclude that the next token is a valid one.
8. Use switch case statement for taking appropriate action for each and every token identified.
PROGRAM SPECIFICATION:
/*** Definition Section ***/
%{
#include <stdio.h>
#include <stdlib.h>
#define NUM 1
#define KEYWD 2
#define OP 3
#define DELIM 4
#define ID 5
%}
/* This tells flex to read only one input file */
%option noyywrap
dgt [0-9]
id [a-zA-Z][a-zA-Z0-0]*
%%
{dgt}+|{dgt}+.{dgt}+ { return(NUM); }
int|float { return(KEYWD); }
{id} { return(ID); }
\+ { return(OP); }
- { return(OP); }
\* { return(OP); }
= { return(OP); }
; { return(DELIM); }
. { /* Ignore all other characters */ }
%%
/*** C Code Section ***/
int main(void)
{
int tid;
/* Call the lexer, then quit. */
while((tid = yylex()) >0)
{
switch(tid)
{
case 1:
printf("NUM ");
break;
case 2:
printf("KEY ");
break;
case 3:
printf("OP ");
break;
case 4:
printf("DELIM ");
break;
case 5:
printf("ID ");
break;
default:
printf("Unknown: %s", yytext);
}
}
return 0;
}
PROCEDURE:
1. Store the specification given above in a file named with the extension .l (ScanDigit.l)
2. Compile the file by passing the file name as a parameter to the Flex tool as follows:
Flex ScanDigit.l
3. The FLEX tool will generate a C file with the name lex.yy.c
4. Compile the generated C file with a C compiler and then Execute to run the Scanner