Nitin Verma’s Blog

Posts Tagged ‘lex

flex – fast lexical analyzer generator

// This is the flex version I have.
$ flex -V
flex version 2.5.4

// A Hello World lexical scanner.
$ cat -n hw.lex
     1  %{
     2  // Hello World!!!
     3  %}
     4  %%
     5
     6  [\t ]+  ;
     7
     8  a { printf( "' %s '", yytext); }
     9  hw { printf( "' -%s- '", yytext); }
    10  ^hw$ { printf( "' %s '", yytext); }
    11  ^exit$ { printf( "%s :have a nice day!!!\n", yytext); exit(0); }
    12
    13  %%
    14
    15  int yywrap()
    16  {
    17          return 1;
    18  }

// Generate your C code, with lex debug messages on. ( remove -d if you do not need those ).
$ flex -d -ohw.yy.c  hw.lex

$ more hw.yy.c
#line 2 "hw.yy.c"
/* A lexical scanner generated by flex*/

/* Scanner skeleton version:
 * $Header: /home/daffy/u0/vern/flex/RCS/flex.skl,v 2.91 96/09/10 16:58:48 vern Exp $
 */

#define FLEX_SCANNER
#define YY_FLEX_MAJOR_VERSION 2
#define YY_FLEX_MINOR_VERSION 5

#include <stdio .h>
#include <unistd .h>


/* cfront 1.2 defines "c_plusplus" instead of "__cplusplus" */
#ifdef c_plusplus
#ifndef __cplusplus
#define __cplusplus
#endif
#endif


#ifdef __cplusplus

#include <stdlib .h>

/* Use prototypes in function declarations. */
#define YY_USE_PROTOS

/* The "const" storage-class-modifier is valid. */
#define YY_USE_CONST

#else   /* ! __cplusplus */

#if __STDC__

#define YY_USE_PROTOS
#define YY_USE_CONST

#endif  /* __STDC__ */
#endif  /* ! __cplusplus */

#ifdef __TURBOC__
 #pragma warn -rch
 #pragma warn -use
#include <io .h>
#include <stdlib .h>
#define YY_USE_CONST
#define YY_USE_PROTOS
#endif
...

// Compile 

$ gcc -o hw -ll hw.yy.c

// Run your lexical scanner binary!!!

$ ./hw
--(end of buffer or a NUL)
hw
--accepting rule at line 10 ("hw
")
--accepting default rule ("
")
' hw '
--(end of buffer or a NUL)
hwhwa
--accepting rule at line 9 ("hw")
--accepting rule at line 9 ("hw")
--accepting rule at line 8 ("a")
--accepting default rule ("
")
' -hw- '' -hw- '' a '
--(end of buffer or a NUL)
hw hw a
--accepting rule at line 9 ("hw")
--accepting rule at line 6 (" ")
--accepting rule at line 9 ("hw")
--accepting rule at line 6 (" ")
--accepting rule at line 8 ("a")
--accepting default rule ("
")
' -hw- '' -hw- '' a '
--(end of buffer or a NUL)
exit
--accepting rule at line 11 ("exit
")
exit :have a nice day!!!