


















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



















Lexical Analysis or Scanner
if (b == 0) a = b;
Preprocessed source code, read char by char
if
(^
b
==
0
)^
a
=
b
;
Lexical analysis
)
y
-2.3E+17, -2.3e-17, -2.3E
y
Token specification order often defines priority
else
x
elsex
Flex
Flex Spec
user defs
tables lexer and
action routines
user code
lex.yy.c
foo.l
yylex()
tokens
request
token names, etc
»
All code contained within “%{“and “%}” is copied to theresultant program. Usually hastoken defns established by theparser »
User can provide names forcomplex patterns used in rules »
Any additional lexing states(states prefaced by %s directive) »
Pattern and state definitionsmust start in column 1 (All lineswith a blank in column 1 arecopied to resulting C file)
lex file always has 3 sections:
definition section
rules section
user functions section
%% if
printf ("IF statement\n");
[a-z]+
printf ("tag, value %s\n", yytext);
printf ("decimal number %s\n", yytext);
printf ("unary op\n");
printf ("binary op\n");
action
pattern
%{
#include <stdio.h>int num_lines = 0, num_chars = 0;
%} %%\n
++num_lines; ++num_chars;
.^
++num_chars;
%%main(){
yylex();
printf( "# of lines = %d, # of chars = %d \n",num_lines, num_chars );
} Running the above program:[ 17 ] sandbox -: flex count.l[ 18 ] sandbox -: gcc lex.yy.c -lfl[ 19 ] sandbox -: a.out < count.l# of lines = 16, # of chars = 245
Meta Char
Meaning
.^
match any single char (except \n ?)
Kleene closure (0 or more)
[]
Match any character within brackets - in first position matches - ^ in first position inverts set
^
matches beginning of line
$
matches end of line
{a,b}
match count of preceding pattern
from a to b times, b optional
**^
escape for metacharacters
+
positive closure (1 or more)
?
matches 0 or 1 REs
|^
alteration
/^
provides lookahead
()
grouping of RE
<>
restricts pattern to matching only in that state
Think of using 2 states Keyword BEGIN “state” takes you to that state