Chapter 9 - LEX - LabManual
Chapter 9 - LEX - LabManual
C compiler
lex.yy.c a.out
-lfl
%{
1. Declarations
%}
%%
2. Translation rules
%%
3. Auxiliary functions
Implementation of Lexical Analyzer using Lex
A lex program has the following form:
1. Declarations
– It includes declaration of variables used in the code segment and
regular definitions .
– Variable declarations are specified within %{ and %}.
2. Translation rules
– Translation rules each have the form: {Pattern} Action
– Each pattern is a regular expression, which may use the regular
definitions of the declaration section.
– Each section is divided with %%
3. Auxiliary functions
– It holds whatever additional functions are used in the actions.
Regular Expression
The characters that form regular expressions are:
– . : Matches any single character except the newline
character (“\n”).
– * : Matches zero or more copies of the preceding
expression.
– [] : A character class which matches any character
within the brackets.
– ^ : Matches the beginning of a line as the first character
of a regular expression. Also used for negation within
square brackets.
Regular Expression
The characters that form regular expressions are:
– $ : Matches the end of a line as the last character of a regular
expression.
– {} : Indicates how many times the previous pattern is allowed
. | \n {ECHO; }
%%
int main(){
printf(“enter the string: \n “);
yylex();
}
int yywrap(){
return 1;
}
Lex example with multiple parts of
speech.
%{
%}
%%
[\t ]+ /* ignore whitespace */ ;
is | am |are |were | was |be |being |been |do |does |did |
will |would |should |can |could |has |have |had
|go { printf("%s: is a verb\n", yytext); }
very | simply |gently |quietly |calmly
| angrily { printf("%s: is an adverb\n", yytext); }
from |behind |above |below
|between { printf("%s: is a preposition\n", yytext); }
Lex example with multiple parts of
speech…
if | then |and |but |or { printf("%s: is a conjunction\n",
yytext); }
their |my |your |his |her |its { printf("%s: is a adjective\n",
yytext); }
I |you |he |she |we |they { printf("%s: is a pronoun\n",
yytext); }
[a-zA-Z]+ {printf("%s: don't recognize, might be a noun\n",
yytext);}
.|\n { ECHO; }
%%
main()
{
yylex();
}