Professional Documents
Culture Documents
Compilers
David Walker
Outline
Last Week
Introduction to ML
Toda!
Le"ical #nalsis
Implementation Options!
62 Write a Le"er 'rom scratc&
Implementation Options!
62 Write a Le"er 'rom scratc&
Implementation Options!
62 Write a Le"er 'rom scratc&
Implementation Options!
62 Write a Le"er 'rom scratc&
/ase Cases!
$e%ular )"pression!
0- D e1 00 D 6 D 2 D 3 D 7 D 8 D G D H D I D J1F
$e%ular )"pressions
$e%ular )"pression!
0- D e1 00 D 6 D 2 D 3 D 7 D 8 D G D H D I D J1F
So ,ritin% 00 D 6 D 2 D 3 D 7 D 8 D G D H D I D J1
and even ,orse 0a D + D c D 2221 %ets
tedious222
$e%ular )"pressions 0$)s1
common a++reviations!
Ka-cL :: 0a D + D c1
2 :: an c&aracter e"cept Mn
a; :: one or more
a@ :: >ero or one
)"ample!
?o, do ,e tokeni>e!
)"ample!
?o, do ,e tokeni>e!
i'::P ID0i'1 or I(
ke,ord rules &ave &i%&er priorit t&an identi'ier rule
Le"er Implementation
Implementation Options!
62 Write Le"er 'rom scratc&
/orin% and error-prone
22 5se Le"ical #nal>er <enerator
=uick and eas
ml-le" is a le"ical anal>er %enerator 'or ML2
le" and 'le" are le"ical anal>er %enerators 'or C2
ML-Le" Speci'ication
5ser Declarations!
tpe le"result
tpe o' t&e value returned + eac& rule action2
'un eo' 01
called + le"er ,&en end o' input stream is reac&ed2
ML-L)R De'initions
ML-L)R De'initions!
$ules!
tpe le"result
tpe o' value returned + eac& rule action
special varia+les!
WW/)<I4 L)R)$4#M)9
continue 019
5sin% Multiple Le"ers
tpe le"result : unit 0F mandator F1
'un eo' 01 : 01 0F mandator F1
QQ
Qs COMM)4T
QQ
UI4ITI#LP i' :P 019
UI4ITI#LP Ka->L; :P 019
UI4ITI#LP N0FO :P 0WW/)<I4 COMM)4T9 continue 0119
UCOMM)4TP NF1O :P 0WW/)<I4 I4ITI#L9 continue 0119
UCOMM)4TP NMnO D 2 :P 0continue 0119
# 0Mar%inall1 More )"citin% Le"er
tpe le"result : strin% 0F mandator F1
'un eo' 01 : 0print N)nd o' 'ileMnO9 N)O(O1 0F mandator F1
QQ
Qs COMM)4T
I4T : K6-JL K0-JLF9
QQ
UI4ITI#LP i' :P 0NI(O19
UI4ITI#LP t&en :P 0NT?)4O19
UI4ITI#LP BI4TC :P 0 NI4T0N X te"t X N1O 19
UI4ITI#LP N0FO :P 0WW/)<I4 COMM)4T9 continue 0119
UCOMM)4TP NF1O :P 0WW/)<I4 I4ITI#L9 continue 0119
UCOMM)4TP NMnO D 2 :P 0continue 0119
Implementin% ML-Le"
4D(#!
6
7
237
a-&Y->
'
i
a->0-J
337
Tok2I(
Tok2Id
Tok2Id
a-e%->0-J
a->0-J
Ta+le-driven al%orit&m
# Le"er!