CD Unit - Ii Part-1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 25

UNIT-

SYNIAXNgYSIS)=CRolE oF SYNTAK ANALYzER)=


ntaz Analy3e t alko called as -he pascel, +he Parsea
oblains e shream Toenx hrom he lexrtal Analy 2e
hd,Verifies tbe tokens Crmtacrcaly, hthe tokens ase
accalty Correc hen i wr aenehate a parse tree.

KoutLeattal
pr0
Avaly34 70E SyolarardPa emenltc
nalyae
Intesmeae
Tvee
SeNectotd parse CRec tomepresenle

Spmbo)
Tae

Faposrkon 4 parses compiles model


i e mafy unckt parse tt to chece he syotacke ghucduve

p Code,1 he gtven p Code ic aut <yolachc esd +he

toi nugte a parce tree


P tde. is Consick dynBax'errd, then he i t vepootc an
Cohl to ukes, Noohe Ues Ui Cortaek C relponsibilly
errds.
he uke to covTec thoce
Wth both lecital Analyaes -Synlax
Symbol Ta ble coomeniate
nay2efos he token nosmahon.
Pes pacu Pa

TOP-OWN PARCER BorpoM up


UNVERGAR
N
Recuretve ecent Predeve pace OpeaH- precedene iel
Cyk algo Easty (Badetraclefnq)
Par
cLR
hiy Redued Lr CLR
mTp- douwn pavses Conslruck the pasces tee fron toplsvt)
Ip Ihe botfom (1eqves)
Bottom-up pavce Conctuc t e parce tree from leavee to
(hat bvom p mbol amd educes to dosing slate)

Repsesenlakve 6rammatl =

DscoCiaHvkviy ml precedence ave capred t the-Polloudg grc

tE+TT
TT*F|F Expsettion
TTeme, F> Facs ha- com be
LE d
eHhe paaBheized expsxt)
Thece qammas belorge to Le CA) id
qraomais haave cuflade fos
betom-uP passina.Thie ara Tmanol comotbe uced for top-doun Pachg
Tbe foll owng non-le-VeCUT STVe qvqmmo wfl be uced

fos top-douon pavcin9


ETE

T FT
T *FT'JE
F )id

Poogrammtha erhs a occuTe at mamy diesent levels.


lezital trd
Tnclude misspellng idenifieu, keyoonde, 2 opetatos
denhi
elspseSfae inelead 4 ellfpocae vo miscng guotes

asoud text flended as a ehing.lt "seng


nta TorAA= Micplared CemitdonG ), esra a msng brares 1,}

aPpeasomte Case demen dHhout am enclaing Sotch.


Eg a+lbk) mieing pavanthic,

mimath blo operats mod Operands.


"YP
2tali1 tyPe mísmateh.
The Teltun d avalue tn Tava melhod fth rlt4ype votel.
logitaEnis
Cvds com be anyhig rom fntomeet rratonmg onthe pau4
PrOammÝg
I n " - dhe aeeiqnment opelati fncka (ompalicîmpeah
lc==A)

r r Hamdles i Parce
opos
shouldhe Precence erTa< clealy md aurately.
chould
chould secovey r o each crTA qufckty enougb to detec
he Subsrgaent errds
do he poocescing vemaintn9 Pogaenn
should ro doo
T Recovey tralegiex
Eaot. a,b 2
panic Mode Reovay
h e paYse dicards. /p sqmbolk ata time unkl one 4a deciad

Se Synehsoni3tg okenc foumd.


SThe Synchwoniatng tokene ave delmelad"à3
T Simple to 1mplemertAomd doee no goto « loop
phrae level Recevey
The parse pahorn lotal Covveckon OD remaing wes
he c s ic distoveued.
KOe
T h e Pq7t veplace the Prelt the vemainmg p y
Shing hat altowt he parces to Cary on ite ereuio)
Ea-Teplace a )comma by Lemicolon C) , deleke on eiq
Cemicolom, msa micCPn9 enfcdon t;)
pint"),> poínt4.I")
dijrcul ahen acual erra
iCadvomtage1= tmd Corechoo is
OCcuse behore. the potnt delehn
GDEoT psoduckon,
(Ommon trac a m be esCDuntesec, oe con augmen
ta gemeade
he q7armmas -for
the lomgume wth produckont
eooneou Conchruck.

use a neo ammal for-he pas


0 Global cosreckon=
She atm to mate ome changer hile convestfng
ireorree Vp shhirg to a valrd g
2GramA
afvenven O)
on IncorTett 1/p * nd a fos a velates
PAnKe tee

qiven 6rammal) Auch t a 4 chonge


no
ucng he
Sing w

Cinelton / dele kon) reuird to tronhorm z to 0 1ik miokoay

Too
Costy to mplemen
CoNTEXT FREE GRAMMAR=
Contez Frec arammas
consiss 4-tupks
CFG-(V,T PS)
VSel4
variabes lb) NonHerminals
T e Herminak

P ed Produckon Rules
C tast Synbol.
D Non-terminal=
Renotes et rngs.
UPPertase letlerx easy n aphabet A,B,C,.

SSlast symbo
E,T, F Ezpreseton -E, Term-T, Pacts-F)

Tesnial=
TETmiak ase the base
symbde foon whch sBigp ar forred
TD ken -name ialko called ae femoîna)
The tollo using ae eminal symbds.
aloweltaee letterg fn the alphabels sch a a,b,e.
opesah ymbok uch a + *
PUneuakons "
n1 Prpducfn Concisk 4
"3"C,"D,,".-} &dgik o,.- 9
Non termna) (all hed s side he praducHo).
Thic prducto
dejinec Come d the 4mbds denotd yhehad
bdy ahci de > consicrg 4 3ero move -termn
and Non termingk.
uestate letlene lale to alphabeh X, Y,2 repvecent 6pamma
ynbde ehe da Henna NonHerminals.
, B , . . epreseo ching gsammo Symbo
Sekd produchons A , , ASd Aak alko wrtHen as
hepd
prvdutt ..k
N
NonTemina erhestevmina4 Nonleming (voT

-Con sides -he sammas


t E+ E E EkE
N P S
CF6- (E,T3, S+*a}, P, E)
erive
Rerivalionsi= RerivaHm is process appyng a Ceguenee
produckan sules nOvdes to desne a .
derna an
p Ching trom the classymbol Gramma
fn 0ne more cleps veplating he bead h e prouck
body he produchtoo.
Thev ase too +typek 4 ernakton.
Lelt most RerivalontMD)
(0 RighmosRrrvaHon RMD)
Lett most Rertvalionj-Tn each clep Rigbt most e t n k
we have to >Here, e have to ezpod
ezpand te-mostNon-Hemh
Hhe RighB-mxt non-erna
bMby one t productbn bod
body.
Rmb
estve a
et ididktd E (EStt
LMDEE+E lE3EE) E E (E>ttE)
E d-+e tE-d)
) t+E+ id tE>id)
id+E*E (E->Ekt) Etld* td (E>)
Tid *E (ESid) t d tid *id ( E )
tid)
T l d +d xd
Parse tvte )=
A 6raphital vepsesentahon Aerfva o ic called parce-see
These types nodes n paxe tree
Tnteioy ndde ave Non -ermfra
chdep node Hermfnals
m Parse tree -he Toot nade muct be stest ymbo
Consruc Parse tree tos tp Ching W= ld-tid *d
LMD E PMD

id

4iedpazzetree
Ambiqury CFG G=ViTRS)
7 a Tamas Produtes more-hon one paTse-tree,e9ha

aTqmma i called a
ambju
E)more hom LMD
one
(diherent)
C) m01e hon RMD
one
(dib}eres.
EEEl E*el teid ng d+id kid
LMD atrE
PMDEtE E
Td+E
E+E*E
+Ekd

1d+TdE Etid¥rd td
Ttd+id *Td. Td-+tdid

op2-6 E*E KMD2EE¥E


Eid
EtE*E
d +E*E E d
SjdpidE TEidd
TTT

i d +id *id dthdtid


Fov the above dng e go LMD Rmp ad pascetvees

S o h e given qrammos is ambiguu

Up doion pasKe cot homdle ambiguaue 5mma, so we


need to Convest th
gramos into unambi uttu araTDmal
Nbile ConNesn ambguouC
to umambrguaus=
The
aramma Should fdlow ALsoCrakvy ond precedente ules
opeoqopelarel
*, + l e ALcoCrash (twhen an has opind
Eob sides the cperand chould acocle
1,**,-
23
o ecedente ovde oth
letide operas)
NRITIN 4 G RAMMAR=

Grammas- tt cueed to decCstbe he syolax e progoammíng


lomgunge
lezial ves cus Cyntackc-Andys=
peratng lnBack Crucure nto malles omd anageable
COmponends ital omd non-lexftal Parts
lexital 7ulee are cimple to understemd hom qrammol
We need notalfonc to deccibe. the qramnos.
RE ase uked to Reallime Ezampleg to malke hem cacy to undsdadd
Granmos ave used -oy descrbtna nested sudure uch as
balamted parontheas,
malching bgn-end, ifthen-elte
ElGminaling wwbu
Pouperes 4 CFG
AmbgOus
Le Retursive
3. Leyt actatug.
Concda CFG)
EtE t*E /E) lid
CThere ae parsetreec-fos chivg)
= td+id *id

d
EtE

opath is
Thic valid Pake tree, benuse the
ig the

aPpeaued a betomPae, so i c evaluated rs

Ci)

id
Too fadhs hal-ase necded to be Haber

Precedente
need
Let AcoCtakvttyTo encuse lek aceocratNit, we

to Convest the aammaL_into letreurc


to he LH
leveturstve E+E he leltmost-4ymbol ic equal
tsee ton be qroun en deny
Tearsve, he PaTce
td+d+td tdtid)+Hd (leltexto4e
Etid d
let accoctaivily Can be achieved
(idid)+id
Thic Epreeefon k ewuata Prd-,co #a
i valtd. pasce tree.
EET Cpreced ente)
1d-+Ctdid)
TT¥ F h i g h e e p r e l e d e r v e l

opeLaiew îL EKaHug

T F
ounambiguoug Grammas
The Fina

T T F/F
F d

Bang= ling elke)- Tn progam { there a're mose han one 1f-
a

e t e hen elke part matehed t b wvong if


Srd tha wil lead to
Dg eauk, thedic calleddag
elce.
14 P íe True Then w l l goto P2 omd
g4expb-PT Chect he cone and condrkon,} t alko Tue
Pep) then twi) edecate S
S
Paelsee S . i gnd cond?ton ic falke tt wil ezeude dkr

0 P-is falke ît hac to exeade the ohes


olhel drnt
alement
) But here P-Falke then ¢eatng elee pad-i.e stalema
tie malBehg wtth rong elke.
Cbneides 4he follounng domgling elke qsammos
m f Expr then dnt
then w elke chnd
exps
olhe
The compaund condtlfona) tm fos the above qammas ic

elke íz
E then Si eke 14 t -then S

The parce ov 4hic ctnt

elkr okE
4
S 14 p hen Sm eke

stnE
p ing iP E HMen 1 hen 9
=
elke C
here aict too pqree treee the
hos fiven Ci
ShmE Pas. 1 paxeTe».! StmE

1 ps The t elke sat


Epi her Smt

E Erps The tm eke Smt p hen Smt


S 2 S
thege -tuoo parie trees, în prvgramming Omguog', the iK
Passe tree i concidesed betause, mateh Ahe elke clatemest wrth
docest hen, a E, hen iH then S elke maled dmt
>Co The qiven Grammas it ambiguouc samma
oill be.
The UnambiquouL qoqmma matehed dedol PesecHf
stmt maBthed slmtopen cm open Cmt mpe
malched tmt> 1} ¢zpr hen maBchedchrot eke mchd tnu|ohes
4hen tnt
open m > 1f e
T hen machd shd elke open shn
t Eliminalton d let Recurcion)
treuTLEiNe
1ib hasa
has a
A aramma ik ad4o be
deriation A A for
nDnfeminal A Sch ha here ic a

bme entg .
handle thi gsamma,io
TOP-don parerng methods camot
eed to eliminale leht vecuvsion
AA Clelt secuscive) ,BE (VUT
Lib iS i egual to the tektmDst Non-emina
RH
The shing detved Prom he above Jrama

A
eingg*
B (ay produdion shauro-
B Costatht mbol)
Produchbo AB Couldbe eplated by theko|lowîng
non-let-seurcive ProducH».
BA

qEEAT/T
TTYF/T
Fltd Cleretuveive9vommai)
SO We need tv elimtnale lett-recurcion -/oom he above

Tomma
E
E TEe
=+T
B=T E +Tele
TT¥FF op A A

>FT A A«e
S ts) ojs
T *PTle
doS1ss|e
F>Ð )id (non le}t reuxsie)
Ea3Sl/a-No lebtvecneit
Aeselminating the let veewTsPo) Lyss
oom he 91ammas
ETE
E+Te|e
T-PT
T FT'le
F-lEidle
Elfminatfon lett recuTSFon Fo6 mulple produchon

| Fp
|9 elle
pr zpr+E2pExp Epi4
A A

Ezpridezp
Eap +eprexpr| texprexpr/e

eqpsx|ssbl*la
A

sAsd|las

sxc sbsle
3 >Aalb

A-cat

Balb > N d e}Ereeuic


C
4 Ac sd|f
tliminalkon d tfacl ivg=
ammas cOnBaine Productom ule fo he -fosm

| B) ,
Then that grammas ConBains lek-taclaNg
TDP faeve comt hancde lefocg -he gscmna Comains lgt
e t a m elimnale -the leJ- factovfng y replatng wththe -folloucfng

Pooduckon

6 3= 8sbB/
A = s , d=itts Bre B,=es SF9
B bB
Sietss lg
BBlgE
dees
>anelanl
B-bBb
AA9Plaela
A aA
A Ae ale
sE T+EIT
T t /ioh Tle) T-nt *T /
T-nt 7'it)
6T+E./T
Top. aum pacing-
is Conctrucled rom
Top doun paxcihg,The Pavce tvee
oDot node to child ndde.
lelt-mat erialton to de tve he fnpu
T0P-duwon Paxccs utee
S h yom he grammaj
dat symbol t qramona
ond veackq thep
Shoahng trom

Grmal ic, dertve +he 1p chtng o-abbde


SaABe LMD-S>aABe
Abcb egbcBe
a e
B->d AbbcBe
abblde

TDP Comstruced os he gsQmmaif iix tee o )


ambigut Let secuncTon,
h e pvoblean w1h ToP Parse ie o e have moe hon one attermak

tor PooducHon, ahtch aHernalhve e chauld uce. JEEE+TT+7P||


E T E ) >Unambquout gvamma ambguour, letean-

Shing W= fd+id*id
Rere an p
T-T

F(hd

dep +
T
id e

jd

T id
id

id
id e
Top-doun Pavcs fos u=id+idId
Recusive Recten pazeing= (wHh back toacking)
The concBrucktm Paree tree èlalte foom soot' psuteel to chndrete
Recursm)- A funclion cohrch
is called by Hsel
Recuscive Rectespasesz=
Seps fos COnstruckng
he is non-termnal, hen Call Corvee ponding krerin
C) i/p a

oth ip Symbel
termfnal, hen Compavetermfnal
( )7 he p ic

Came, he incsementínput Ponte


both ave
mosehan one pooduchor then
Non-teminal ConBains
C1)sa shoud be U0tHen in h e cosseepondng
all the producHon code

fncon

e have &- Notemnalk FE, So defive


Ip he afven gammas
ac C-lomg-funchns)
tuo PuncHons, some

Coput== "P)
1oput++
FPRIMË C)S
EPRIMEC)
1-6sammal E>TE E TEl|E
PT>*F1le F>(D
Liop input+* EC) TL
Cinput =- \i') FO
TO
ioput++ EPRIMEL
TPRIML)
EPRIM DS TPRIMEl)
EPRIMEC),
elee Tinput=-'*)
delun nput== Tnpy+
tinput++
TL)
FLO
P Ching: t+74 EPRIME
TPRIMEU
Selee
Tetun
elke
Teu
FL
4nput={)
input +
4Coput=s)
aba iopul+
Vpng w-(od
N elke tt (inpt=-'id')
fnput t

Gactctactng
Ca None -he Product Jo ic
akeyng the conArhio

hen ae chauld check on omohes pocLilty fos s)


pid-+id
maul ++ FC)
EPRImED;
tpRImN; tTE) 14-tmput=0
£lke,
tPeIME) eTelE Te m mput+
-P T
5 (input == '4) 4oput-=")
fnput+t
input++
i(imputs-7)
F(EItd 7PRIMEL; ele

inputo-'rd>
fnput + TPRimEL
PRImE)
Tnput-++
elee APpmElOS mput»)
Telers 3 pu+t
tpIRIMEX)
TPRIMEO)

Pnput+)
1thputt Telusn

Sced ab =Cadd

tos A 1 ahstyng
( Non h e prrcluc
shoulo checie o
d AL Conlon hen w en

posbiliy for 8
Backacde

(8) predt v e PasSfng Cs) LLu) å N) Teursive palses


LLi) - Ma

T Stans he fnput foun lebB to Riaht usti


leht most Raiaen. Septor tonchucitg
L - > )- Loolc abeadalina 1Ehaetdadd e F
1 4 - i p buffes| Otinainet
p ef reusi
etmíinahn o
LLUD Parsesa) dp buffsleht factemg
psedtche palfos
Calculatin AeS ()
&Follout-

Stacg predce Pavcing)tonchauclim P a lable.


toLle
LL pav Ce) parsfng algohm
Ltu parsng tate-Aala cruckre which is coneuded fsom
he l ) 9sqmo
Sla cle Rala studure used tv store he gramna Symb
lcaye the betom he slack i
The ena chauling inbo o pic p hed
4HoTDs,The
ConsucP the påvng table Toehould
Eno e (ompute
shoulo COmpu te

two fumctone. OFIRSTL FOLLOWt )


FIRST G=

X i s a termfnal hen FRST (x)=x}


ix i a Non termîna) 2 X YYY -- Yn fs a
producktn o X.
FIRST C) = FIRST LYD

4FRST (YD Conlams add


e FIeSTCY) to FRST(
all HRST (Y,y- ) Conlane e hen add to FIRSH)
folOw CB)-
l u a s +he follow t) stavting Symbd rs .

FollooLB)-FIRSI (B2
FIRSTLB) Contain E or A B he
add Follow (A) to follttwCE
Eg= aiVen Gramma i
E E+T/T -lept reursiun imfnat leh
T T+F/E (et reuSion ) 7euuTEnletfa cona
fom thera prteluuy
F -
F) lid
E->TE

+TEe
T F
T *Pe
F LE) lid
FIRST tE) = FIRST (T) = FIRST ( = 2 id)

HRCT CE) ={+, e3


FIRST(T) = FIRST (F) -2(, idy
FIRST (T) = 2* ¬E FIRST(P= id

Follbo E) = i Fo
FLE)id
follooce)= Js, FIRST()} 2&,)
Follow tE) 2Follouo lE)+ FolloaCEDI
ETE
e+Tel}le
Follouo ) = Fall®LeLElD}
FollowCT)=ARST (El) 4 Pollbo tE)
ETEl
+TEl/E 2+s,>3
Folloo CT)
PollowT)+ Follbo(T))
TLSFrH
T E'le
FollDw LE) Follow C)+- PIRST+Folbualt)
T-PT s+1s,)
predtcHve passing lable

id C

E7E 6TE

Else ele
T
T-FT
T
T
FFid
d+rd
Stack
fnpu
tdtid Te The p S passed

TE TFT ERS(/
Td +ids h= (a)

AT'el idttd
Tlel +id
TE -anbe
+id BbBle
-"aabb'
rdlf
#Tel id TFT
TEtsietsesla
b Non-Litr))
Pre d Fd
Ente' MBcbrA
Tles T dalE

CLCtepkg
>he
Bcttom-up pavses Con&truct pParke tree from chtld tbottm) ndde

tooot nadel Top).


Boltom up parses ue RmD, fnb Re verse ordes.
T Botom-up pasesp edhuceng tp shfng w to a t m k o l

S>AABE

AAbelb
B-d
Tput chivg we abbtde abbede

aAbcde (A->b)
aAde (A>Abc)
age CBd) aAde
S atbede
CCaAe) abbde

ETFF =rolxid dt id (Fid)


F T>rd
F(EIrd T td Ca0)
Eed id Ficd)
TE (F*E
CEST)

T h e poblem h 8otmup Partes ie twhen to veduce he

t o prdueken.
Tk d T F
Sepr dx id F*id

Homdle R Hondle psunina=


Howdle: 4hondle is a eubchim, kohf¢h matches with igbtcede

prvdu ction it
matehes wtth
te
sighCide prrduthm,4hm
Hmdle
whleb howo rde Non -teyminal
iseplated
S>aABe ) a b b lde
A Abc b
B d

Rght Centental forn Homdle Redu oing prtduchad


BAb
b
abbcde AAbC
Abc
a4bde d

0Ade Sa9Le
aABe
ABe

POYSe Td, rd2


Hand es durtng

2 E+T/T - r d , * id2
TT*F/F
FlEYid

Right SesHentYal FoYm Hamde Reducrng prweuche


id Fid
id id
FF
id
T id id IFid
T T*F
TF
T ET
P Hemdle prunin9 i bbleined by Rght most Reivation sevele

orde.
GShiht-Redute paes )=
Shibl Reduce pate use tuoo Rata drueler clatkph
OStack - is ugestore the aoma_Sypnmoc

nput bahben-heid he hing to be


pase
SHack Toput thAng
Ackions s-Redute Parsel

shibt- ehibt he nezt f/p Sml ontd he top the glact


Reduce -Th he top 4 slack i malched t h Rrahtside c
Procu ctien, hen it is Tedutedto Corespeneding non-Bevmre
ACcept -- Lutteeeheil complehien eh pa
4 EA Dietoves Synlaf
ateus ovd all erTo ve (oveiy mehals
E EHT(T -id* id
TT*PF
(E) id R-Conauratiuy o Shib-Redue pates n pid*
la cie Input Bubhe Acken
Td*id 4 shibt
id Reduce e fid
Td Reduce iF>F
T id
id$ shib
Reduce F>id

TF Redure TST*F
$T Redute EST
Hrepheod
0ntfck urng shibt-Relute parnA
shrht- Redure conhlrck: Cannd dectde ahethes to chrht a bsalue

Tedure- Teduce Contlrct s ih the Productione have Same havdle

&ubhira),
ChH -Redute
L)/a
LSsS paYse he Shing la, l a )ucing sR-paue

Stack TP Bubbs pauing AtHon


aa, can) shrp
,laa) shibt
(a A)$ ReduceS>q
LSReduce
cL shrt
Caa))
&(LC a,s shit
Redute SSq
$CL,S ctpRedute L>s
1, 1)
shihF
Recuce Sq

4L,(LS Recute L>LS

L,L shit
Recdute S3L)
Redute LsLS
(L
Peduce s U
S
ACept

You might also like