Regular Expressions To Finite Automata: - High-Level Sketch
Regular Expressions To Finite Automata: - High-Level Sketch
• High-level sketch
NFA
Regular
DFA
expressions
Lexical Table-driven
Specification Implementation of DFA
59
Regular Expressions to NFA (0)
For ϵ
ϵ
For input a
a
61
Regular Expressions to NFA (2)
For AB
A B
For A | B
ϵ B ϵ
ϵ
ϵ A
62
Regular Expressions to NFA (3)
For A*
ϵ
ϵ A ϵ
63
Example of RegExp -> NFA conversion
ϵ C
1 ϵ
E 1
A ϵ B ϵ
ϵ 0 ϵ
G H I
D F
ϵ
64
NFA to DFA. The Trick
65
NFA -> DFA Example: Machine for (1|0)*1
C
1 ϵ
ϵ E
ϵ 1
A B 0 G ϵ H I
ϵ D F ϵ
66
ϵ -closure(A) = DFA Start State
ϵ -closure(A) ϵ
1 ϵ
ϵ C E
A ϵ B G ϵ
1
0 H I
ϵ D F ϵ
ϵ
(States reachable from A on ϵ−transitions)
S
Call this “S”.
ABCDH Where can we get from
S on input “0”?
(ϵ -closure(F))
67
Second DFA state, Reachable on 0 from
Start State
ϵ -closure(F) ϵ
1 ϵ
ϵ C E
A ϵ B G ϵ
1
0 H I
ϵ D F ϵ
ϵ
T 0
S 0 BCDFGH
ABCDH
Call this “T”. Next: back to “S” to look
Where can we get for another possible state
from T on input “0”? 68
Answer: only back to T
DFA Start State Again
ϵ
1 ϵ
ϵ C E
A ϵ B G ϵ
1
0 H I
ϵ D F ϵ
ϵ
T 0 Call this “U”.
Because this
S 0 BCDFGH
includes
0 1 state I, it is
ABCDH 1 an accepting
1 BCDEGHI state.
U 70
The Resultant DFA: Three States
(1|0)*1
0
0 T
S 0 1
1
1 U
71
NFA to DFA. Remarks
72
Implementation
73
Table Implementation of a DFA
0
0 T
S 0 1
1
1 U
(1|0)*1
0 1 “U” is the
S T U accepting
state, so it
T T U is marked
with a “*”.
U* T U
74
Algorithm to simulate DFA (Fig 3.22, p.116)
array move[ ] input int final(int s) {/* “1” iff s is final */
return (s == 2);
state 0 1
}
0 1 2 int scan() {
1 1 2 int s = 0; -- current state
int c, move[3,2];
2* 1 2 c = getchar();
while (c != EOF) {
s = move[s,c];
S,T, & U are now states c = getchar();
0, 1, and 2
}
if (final(s)) return (YES);
This algorithm reads
an input string, else return (NO);
attempting to verify }
it using a DFA encoded
as a table.
75
Implementation (Wrap-up)
76
Lex and Flex: Scanner Generators
a.out
lex.yy.c C (binary
compiler
executable)
candidate token
a.out
text file stream
77
Lex “Program” Structure
%{
.....C header stuff, copied into lex.yy.c.....
%}
.....Regular Definitions....
%%
.....Translation Rules for all tokens.....
%%
.....Auxiliary C Procedures, also copied
into lex.yy.c
78
Regular Definitions and Translation Rules
D1 R1
D2 R2
D3 R3
%%
P1 { action1 }
P2 { action2 }
P3 { action3 }
P4 { action4 }
79
Earlier Example Token Specs
(Added ASSIGN token)
83
Demonstration of Lex Example
84
Compile, Link and Run..
87
Example Program: Factorial.cl
class Fac {
computeFac(num : Int) : Int {
if num < 1 then 1
else num * (computeFac(num-1)) fi
};
};
class Main {
main() : Object {
{ out_string("Enter a number ");
out_int((new Fac).computeFac(in_int()));
out_string("\n");
}
};
}; 88
Project (continued)
90