CS 370 Lab #2: (F)lex and Finite Automata
Name: ____________________________________________________
This lab is practice with regular expressions and finite automata in order
to prepare you to do the main lexical analysis assignment. Do as much as you
can during the lab; when you have a solution bring it up and the TA or I
will look it over. Print a hard copy of this page. Fill in the blanks.
Turn it in to the Dr. J or the TA along with a printed listing of the flex
.l file you write for that part of the lab. Due: before next week's lab.
1. Flex Basics
- Read the
flex manual page, and skim the web site "Flex - a scanner generator"
- Get a copy of the flex word counter flex-wc.l
and save it in a file. Try to compile it with "flex flex-wc.l".
Does it report any error? __________________ What is the output
file named? _____________________
- Try to compile your program with "gcc lex.yy.c -lfl". Does it report
any error? _____________________
- Edit flex-wc.l and add %{ and %} on lines above and below the line
that begins with "int num_lines". Flex may not need them, but they
are important if you want your code to be portable.
- Compile and link your program with "gcc lex.yy.c -lfl". What is the
executable file named?
- Just for fun,
try it without the "-lfl" part: "gcc lex.yy.c". What error
happens? _________________ If you see this later on, you should have
a clue what has happened. Learn to read your system error messages.
- Run the program on itself: "./a.out <flex-wc.l". What does it write:
______________________
2. Flex your assignment #1 away
- Write a regular expression for whitespace.
- Write a regular expression for "contiguous non-whitespace" chunks in
categories 1, 2, 3, 4, and 5, as in homework #1.
- Put these regular expressions in a flex input file (hw1.l)
- Add a semantic action for the contiguous chunks: return 1, 2, 3, 4, or 5
- Run flex on hw1.l to create a lex.yy.c
- Note: you will need to modify your main.c to open a FILE * named
yyin
, instead of yyinput
- Note: you will need to modify your main.c to reference an
extern char *yytext;
-- this variable is declared and allocated by lex.yy.c; things won't work if you define it as a char array.
- Modify your makefile to use hw1.l and lex.yy.c in place of yylex.c
- Compile and link your new homework #1. Run it, test it, fix it, etc.
3. Finite Automata
1. Draw the transition diagram for the finite automaton described below.
Does the automaton below accept the string "abba"?
States: {S0, S1, S2, S3, S4}
Alphabet: {a, b, c, d}
Start State: S0
Final States: {S2, S4}
Move Function:
move(S0, a) : S1
move(S0, b): S2
move(S0, c): S2
move(S1, b): S2
move(S1, d): S4
move(S2, a): S0
move(S2, b): S3
move(S2, d): S4
move(S3, a): S3
move(S3, b): S3
move(S3, c): S3
move(S3, d): S3
move(S4, b): S4
4. Draw a nondeterministic finite automata for...
- C strings? (consider \n, \t, etc)
- C float (real) number literals?
Problems (5) and (6) were deferred to lab #3, they are here for reference