


















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!



















y^ Lex & Yacc
, Levine, Mason and Brown
Preprocessed source code, read char by char
if (b == 0) a = b; Lexical Analysis or Scanner
if^
(^
b^
==^
0
)^
a^
=^
b^
;
Lexical analysis
y^ -2.3E+17, -2.3e-17, -2.3E
else
x^
elsex = 0;
2 elsex
y^ Token specification order often defines priority
tokens
Flex Flex Spec
request
user defs^ tables lexer and action routines user code
token names, etc
lex.yy.c
yylex()
foo.l
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");
pattern
action
#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