0% found this document useful (0 votes)
4 views

Compiler Design Lab

The document appears to be a collection of source code snippets and explanations related to lexical analysis, tokenization, and finite automata. It discusses the implementation of various components such as identifiers, keywords, and arithmetic expressions, along with methods for converting non-deterministic finite automata (NFA) to deterministic finite automata (DFA). Additionally, it includes checks for valid identifiers and comments in code, emphasizing the importance of syntax in programming languages.

Uploaded by

Priyanshu Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Compiler Design Lab

The document appears to be a collection of source code snippets and explanations related to lexical analysis, tokenization, and finite automata. It discusses the implementation of various components such as identifiers, keywords, and arithmetic expressions, along with methods for converting non-deterministic finite automata (NFA) to deterministic finite automata (DFA). Additionally, it includes checks for valid identifiers and comments in code, emphasizing the importance of syntax in programming languages.

Uploaded by

Priyanshu Rajput
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Tnegsuaml

implemet
tabs and mee ine.

tho
thowe f Confiletion reust.
Jeye) eaks the code hato tokes Wich ae
He snaleest imdisual mits
omai n gecus is to rak daon the code
Cter
iuto mclle tohons.
Sounce Code>
mtert e
(AsSIGN',a!), ('oprRATOR , '[4\-*),
(KEYWoRD', n'\b(flelse (eskilelfen)\6),
(SkIR, [tlnt ), C'MISMATc H '),]

fer ain in token afucifeaten)


cade infut Enden
clen lintd. Cale):
adilefestlon

onatch
= token.

1:'SkIP and ye-l: 'A1sMATCH:


velt

ffndayeale)

chanacter at fesidon ifatin})


break
tekens?
fer then in
pittekon)

ceole!
('NUMBER , )
('NMGER', '4)
(NUnBIR, '
('NUD8tRY)
(hmgER, ' )

('NUnBER
Psaqsuam: 2.
ler toal

Toale> Lex oa

of chauctory leto tekondl.


thiets He stom
s a comiler. e ler borpilea
inft and
take he
qenenaly wed th YACc Yet fn other

data, it may be an
eorateh at
eecompeed
Jeyunxe of characters hat can nat te Ddimitenb
fusher >kewonda, ddentfend, ofenaton4
kygonds 1> /nt, cha, loat, const
uyvicable, and usen
Commad,
Dlimtersl> Punctuato: Smbels wsed such cus
demicaland, biocel!.

mtont thder as dey


Nunber,
Pu',
ID',

ELSE
2fAREN)
'RPAREN,

t Raren

c':'ELSE

tvalue.value)
Jetwnt

n'[a-2A-Z-][4-zAz0gy'
lexulintet le w value)

chaneeter'talu loJ})

d a t a

elsei

#Tokenize

tet lerentekeny

buak

ey Tot enzD, ,2,)


!,2,6)
Aer Teken (PLUS
Lex Teken(I),'Y2)
TllyalChaacten';!
' , 3 , 2

(1D ' : ' , 3,2)


T e k c n

Ley
4323)
4,al
(ELSE,'else,

Tcken charac er ':


Loxteken(IDy54)
te
L e x T e k e n ( E , ' = ' , 5 , 4 4 1 .

5,545)

n ( N m b e n ,

LexToke
benerale

vald awithm.etic
yeatos
and |.
tood
tool wed
YACC A
a
Tesgt

cheekU whether
C
ond

Ssunce Code:

lex
jfot pley od

PLUs',INUs','TiMEs', ovgE')
ttos (NUMBE R,

-imes= ' |
tedivde

fitald chovoten:.t-valel3)

de t-Nunent):

ttt. vale)
te vabe =

TiEs
"ht("Ete an aitntie
cyuo. ;

beak
not S;

cytrssion 3tS*2
aithmetie
Eidon an
Valid entreuiow
)Bupm
wlak aletern thocd by any mumberd littons on

Sounce Code '>


intent tlyley as tex
a
tokens - IDENTIEIER)
f-1DENTIFER= '[a-zA-z)[a-zA-z o-9)*

trnt'Iyal ed chancter,t.valut [oj)


leyer: dkikli)
yevibble' LOENTIFIER"
pritl'vealiol vaicble ame')

þitnelid vaieble neme ')

infut a va ickle name' )

brak Ectore iaiade na me' de


nat s Inyalel vevdcbl eme
Cotnut
fuudn farae (5)
(C).
bycaleulator tvadnates aithmelte cxasinu)
wmer les
Sownce Cade *>
ter astex

tokens (('NUMBER, 'pLDS', MINUS','TIMES,'DDED

t-Uale iutt.Uelu)
tnt
clefl4.eehld) :
ritvaliel choracterni "t. ala[oj)
4.tyvit1)
Iryenly Lex )

23-: oJ- -p3j

ti2]=/:
ely peelf)

trser yact. yoccl)


on")

briak
4 not S:
Conti e
riat ("losult:yeguH)

bnter exbusdoni
Trogham o1
Obilctua'ite a to

seochable from Adate poh E tronditiont.


Jhe ep los clort /s as amentencd bolo

Sowrce Code s>


def esilonclojure(tronsitiowd,Atate):
clos we iMatej
stack -[stote]
cohle stack:
Cyreutstack popU
tnemsitio nsJC aurvat,
)):
fon nerttate in

closwcnadod net-tate)
Mack.femcllmetstate )
tunn clowe

("0','): /'1'7,
(",): j'?2'}.
("30''a'):|',
(':i'4'?,
St ates -['e', ",22']
for tate jn states
clenws(thenstio, state)
clorou =efpi lo

gii' 'y2'}
Esilon cloue
Cbictive t’ Wsite hroam to couyod NEA 4h
E-translton to NEA othout transion.
heosg 3> To Convet an NEA bh stranstfion
to an NEA thout s f i o nd cIe
he ecloscoe of Cach ttte, uich | the set
tates seachahle oom a ttate w "
conideing all passible tronstis n
Cach i ymkol, taking to acteuut Hhe
we
acudt le Anal ttatea
reorch
to include any state that can be
a final state dhang tronidtond.
Sowce ode 8>
def filoncesowlofa, tate):
clyswe jtote}
tack [tate]
shle stack:
S-Stock.popo
next-stete

transhttows'J [SJ:
merttale mot in clonune!
clocoe addlnetstate)
aack.afenol me stslate )
Setun clogune
dy

fon Atate n ofaltates': tatoJ:


ton cop- state mebsilm cloveofo,

Ambel!-'z':

aaonstat eJlsymbol].ufdateehsnle
epsorclaya
intalstatessjtate fn tete in mfa ['tated] if ang in naltinalstate
ofa,atat o)fon f n
>utunj stote': nfalstate'], alphabet':nfal'athabet ],tramtt
tewsrton,'start.tale': fa sttstete], nalttotes'=
final-tetes3
ofa wth.efilon
'tateso, 2i'2',
Whabt': 1'a, 'b'},
9':'b'={',2':f 'a':f'23}1, 'c7slon tro
'Stattete'= 12o
'final-tat':|213
#ransfion'.i22': 'bset), a' =f'2','20':1k'
22',o'),'a i''}, '2'-1'%'-j'2r'}, a'-set0i3
Stout tate:'e', inalstat '=121'3
Paaam-6.
yeetues>0ite fcg 'ram to Cowent NFA to DFH.
zoAtate
heony &> An NEA can hove ZOO, one
On a

move ferm a gue hove ull moves(moves

Ayobol. An NFA can con also

qiven tocte on
move foom a
a

Souce Code t>


fsom collectpnd mforet stdefaultdicd.doque
class NFfA" tira):
iait-Ceftte, albhabet Atart ocepla,
def
Ael ttetsstotes
albhaket -alfhabet
Ase tat tat

defrfato.ofalnfa:
starit-set- fruzeaset lbyasttI)
qeue-deyeltstatset )
stocte-mapfAtartset:ao3
da-tsa'11
Coant-|
whe queue?

eh Aym in ma.ahab:t
nertet setC)
Curent: .ijset

i mot
Cotinue
Adotumabineyd. sel]-f'AsCount}'
Countl
qucuafpnd(nertset) mapld-otJ
mplcwvent1JCSy m-s fate.
anltate
fa-ocpts.add
CHotmainextset])
dlaachtbdtnd
tatt-wap alelo, 'ç&o,
netwn
onfa-NFAC
states L'A '8,],

0tat 'A
accaptslc']
'A:o:A 8], '':LA?
s':':''y3
tate,duitont: nftoay
stod es. tat.tant acejds.
rint ("f A datest)tCstcles ))
int"tart Stete : '),Atat-ttate)
Jistlorcet-stotes)
fint Accabtst ates: ).
a3'1
DFAStotestt'o, '6,'2,
Stant tate. o
Accept states: L'As'a)

6 1 - - O - a

A l - - 1 -> 0 8 2

382
to to0 de

dtotes
Ohe set l cotaln all

difeet

chauge in fottion)

mmiwzed fa wtll he egial to no


btates n
Souhce Code t
from callcous ioftort default id.

d dfatdietocd)
ktukle orertCi n t-dine nmerafdns
d[k].addrq)
s t - dvaluesty

82- {m3: m{self-sctta for a in self-.z1f a in seslI)

dfa- DF AC
E-['o''),
tat'A,
f-l'c'],
'A''o': '8,'1: 'A'3,
'3'.{'o': 'c',':'o},
'c':{'o:C, ",'},

pilut ('states. ', min-dfa)


fihut CAccept:, t omin-dlaf)
phitTawitns: )
on ain mifa.s[s]:

Stat 3
Acced:['ao']
Inabs: Q6-- 6->a0

8 - - | -6 0
lne is
Com met o mot.
a comet begins sih tho t sjnbol.
heory>an ythoncheck i a gheu line o con met by
mbol at he
funce fthis
line, wtile faces.

Sowrce Code s>


isComment(line) :
retwrn l n e . t r i f ( ) d t a t s h l C # )

ine ="4This is aa com ment "

This line is a comnezl)


printl
else: comment')
frit(This line ! mot a

This line is a Com ment


Objectiuet> Witea
string 2'keoond.
heoy> We can se dhe builtin keyord mocele
to check f a
keycoxd.
are the eseved cooo hat
can nt use as idetifiers(iki vasia ble vane)
be cawse they have
hav6 sfeclal meinig in
Souwnce Code 8

retun keyond.skeyuatd(opnd)
LiDnd =tupt(nter a oord: ")
pziatlf"iandy a
else:

Entor a cond: br
fyon keyord
Objeotiei> lWrite a ogm to finc wheth en the

can we he built-in oldentferl)


Iheoty&> We
mchod to check ahether a
Vald ideutifenlhe valid va riahlulfclas nom d).
Sowce Code
omd.sldeitfen)
coordy
cond= inputEnten a
sideatfienlo»d:
it a valid identifien)
pritfnde
elsti

Enter a wodt 12 3abe


'I23abe' mot a mlid ldextifer

You might also like