New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Programming Language

by: Lisette Hodkiewicz

Programming Language CS 4850

Lisette Hodkiewicz
GPA 3.83


Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 138 page Class Notes was uploaded by Lisette Hodkiewicz on Wednesday September 30, 2015. The Class Notes belongs to CS 4850 at Western Michigan University taught by Staff in Fall. Since its upload, it has received 33 views. For similar materials see /class/216893/cs-4850-western-michigan-university in ComputerScienence at Western Michigan University.

Similar to CS 4850 at WMU

Popular in ComputerScienence


Reviews for Programming Language


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/30/15
Lexical Analysis mamas was Wm u Inns 1 The Sfrucfure of a Compiler mamas was Wm u was 2 Lexical Analysis What do we want To do Example if i J The inpu l is just a sequence of characters fif i jn1 1 z 0nfelsenffz 1 Goal Par li lion inpu l string into subs lrings And classify Them according To Their role mamas was Wm u was 3 Wh aT39s a Token OLITpLIT of lexical analysis is a sTream of Tokens A Token is a synTacTic caTegory In English noun verb adjective In a programming language Identifier Keyword InTeger Float IF THEN Parser relies on The Token disTincTions E g identifiers are treated differently Than keywords mantis was sum u was a Tokens A Token corresponds To a sTring or a seT of Trin s IdenTifier sfr rlgs ofeffers or dy fs sfarf Ilg wf7 a e ffer InTeger a nonempfy sfr rlg of dy fs Keyword IF sTring if WhiTespace a nonempfy sequence of blanks newfiles and fabs OpenPar a leffparenfhess mantis was sum u was s Lexical Analyzer Implemenfafion An r musT do Two Things 1 Recognize subsTrings corresponding To Tokens 2 ReTurn The value or lexeme of The Token Th2 lexeme is the subsTr39 n9 mantis was sum u was 5 Example When reading The following Tif i jnTTz 0nTelsenTTz 1 Tokenlexeme pairs reTurned by The lexer WhiTespace Tquot Keyword IF ifquot IdenT ifier Jquot mantis was Wm u was Lexical Analyzer Implemenfafion The lexer usually discards uninTeresTing Tokens ThaT don39T conTribuTe To parsing Examples WhiTespace CommenTs QuesTion WhaT happens if we remove all whiTespace and all commenTs prior To lexing mantis was Wm u was Lookahead Two imporTanT poinTs The goal is To parTiTion The sTring This is implemenTed by reading leHTorighT recognizing one Token aT a Time Lookahead may be required To decide where one Token ends and The nexl39 Token begins Even our simple example has lookahead issues l vs if V5 N mantis was Wm u was Nexf We need A way To describe The lexemes of each Token IdenT ifier strings oflz ers or digits sfar ng with a le er CompuTer cannoT undersTand The above informal description A way To resolve ambiguiTies 39 Is if Two variables land f I ualsigns a mantis was Wm u was Regular Languages There are several formalisms for specifying Tokens quotformalismquot means a compuTer can recognize Regular languages are The mosT popular Simple and useful Theory Easy To undersTand EfficienT implemenTaTions mantis was Wm u was Languages Def LeT E be a seT of characTers A language avequotE is a seT of sTrings of characTers drawn 2 is called The alphabef mantis was Wm u was 12 Examples of Languages Alphabei39 English characfers Language English seni ences Noi every sfring on English characfers is an English seni ence Alphabef ASCII Language C programs Noie ASCII characfer sef is differeni39 from English characfer sef mamas was Wm u was 13 Nofafion Languages are sets of strings Need some no ia iion for specifying which sets we wan For lexical analysis we care about regular languages which can be described using regular expressans mamas was Wm u Inns 1 Regular Expressions and Regular Languages Each regular expression is a no ia iion for a regular language a set of words If A is a regular expression Then we wri ie LA To refer To The language denoted by A mamas was Wm u was 15 Afomic Regular Expressions Single character 539 if c in 2 W quotaquot Conca lena lion AB where A and B are reg exp LAB ab a in LA and b in LB Example L i39 f39 if we will abbrevial39e i39 f as if mantis was Wm H mus 15 Compound Regular Expressions UnionAIB LA I B s I sinLAorsinLB Examples L if I l39hen I else if then elsequot LO39 139 I 9 0quot 1quot quot9quot Hole The are jusl an abbrevial39ion Another example L O39 I 139 039 I 139 00quot 01quot 10quot quot11quot mantis was Wm H mus n More Compound Regular Expressions So far we do nof have a nol39al39ion for infinil39e languages Il39eral39ion A LA M U LA U LAA U LAAA U Examples L 0quot quot 0quot 00quot 000quot L 1quot0 sl39r39ings sfar39ling wifh 1 and followed by S Lltsgt lt quot3 mantis was Wm H mus lE Example Keyword Keyword quotese ar quot f ar 39Zaegn ar ese I I39f I beg II I Recall else39 abbrevia les e39 39 s39 e39 mantis was sum u was Example Infeger s Infeger a nanempfy sfr rlg of dig7 s digir 0 I 1 I 2 I 3 I 4 I 5 I 6 I 7 I 8 I 9 number digi l digi l Abbrevia lion A A A mantis was sum u was Example Idenfifier Iden lifier sfr Ilgs afeffers or dyfs sfarf rlg wf7 a leffer Ie l ler A39 I I Z39 I a39 I Z39 iden lifier Ie l ler Ie l ler I digi l Is Ie l ler I digi l The same 9 mantis was sum u was Example Whifespace WhiTes pace a nanempfy sequence of blanks Ile wI39Iles and fabs r39 n39 mantis was sum u was Example Phone Numbers Regular expressions are all around you Consider 510 6431481 2 01239 area digi l 3 exchange digi l 3 phone digi l number area 39 exchange 39 phone mantis was sum u was Example Email Addresses Consider wws en cswmc edu 2 e1quotl39ersU name Ie l39l39er address name 39 name 39 name mantis was sum u was Regular Expressions gt Lexical Spec 1 1 SelecT a seT of Tokens Number Keyword IdenTifier 2 WriTe a RE for each Token NJrnber digiT ifkeyword if IdenTifier IeTTer IeTTer digiT OpenPar mantis ems sum u mus 25 Regular Expressions gt Lexical Spec 2 3 ConsTrucT R represenTing a large Token caTe ory RR1R2 R3 FacTs If s in LR Then s is a lexeme Furthermore sin LR for some i This i deTermines The Token ThaT is repor39l39ed mantis was Wm H mus 25 Regular Expressions gt Lexical Spec 3 4 LeT The inpuT be x1xquot x1 x are characTers in The language alphabeT For ls i S n check x1x 5 L01 5 IT musT be ThaT x1x E L021 for some i andj 6 Remove gtlt1gtlti from inpuT and go To 4 mantis was Wm H mus Lexing Example R WhiTespace I InTeger I IdenTifier I 39 Parse 1 3 9quot F maTches R more precisely IdenTifier maTches R more precisey The Toke Identifie WhiTespace 39 quot Identifier quot5quot lexeme pairs are quot We would like To drop The WhiTespace Tokens a er maTching WhiTespace conTinue maTching mantis was Wm u was 22 Ambiguifies 1 There are ambiguiTies in The algoriThm Example R WhiTespace I InTeger I IdenTifier I 39 Parse foo3quot f maTches R more precisely IdenTifier d BuT also foquotmaTches R an foo uT noT Fooquot How much inpuT is used WhaT if x1x 6 L01 and also gtlt1gtltK 6 L01 Maxi al munchquot rule Pick The longesi39 possible subsTring ThaT maTches R c mantis oz Wm u was 29 More Ambiguifies R WhiTespace I new I InTeger I IdenTifier Parse new fooquot quotnewquot maTches R more precisely new39 buT also IdenTifier which one do we pick In general if x1xi e LRJ and x1xi e LRk Rule use rule lisTed firsT if lt k We musT lisT new39 before IdenTifier mantis was Wm u was an Aufomafic Generafion of Lexer s 2 programs developed aT Bell Labs in mid 7039s for use wiTh UNI Lex transducer tran n input stream into the alphabet ofthe grammar processed by yacc Flex tast lex later deyeloped by Free Sottnare Foundation yaccbison yet another compilercompiler next week Ianl l39 To lexer genera ror List of regular expressions n priority order Associated action with each kl Oufpuf Program that reads input stream and breaks it up into tokens accord ng the the kEs CNESSummexllJuus u LaxFlex tokens taken names at yylexO mums was sum ii was 2 Lex Specificafion Definifion secfion r Allco 2 Wu lS Copied to the resultant program Usually has token detns established by the parser de muou seamquot 7 User can pr lde names tor complex patterns used Vi rules ono 7 Any additional lextng states states pretaced by s directive rules mmquot resulting c tile user function section mums was sum ii was a d Mam Wquotth va Wd lex le always Ims sections Lex Specification continued Rules section Conta ns lexical patterns and semantic actions to be performed upon a pattern match Actions should be surrounded by 0 though not always necessary Again all lines with a blank in column lare coped to the resulting c program User function section All lnes n this section are coped to the final c file Unless the functions are very mmediate support rout nes better to put these in a separate file menus was umx ll mus u Partial Flex Program D 09 a a if printfquot17 statementnquot az printfquottag value nosmquot yytext D printf quot decimal number nosmquot yytext vvvv printfquotun o mquot quotquot printf quotbinary opw pattern action risequ CNESSummcrllJuus cs Flex Program mndcssamle hummus armhole u gt h mm mm malt worms d ol clrms o hummus measles gt Running the above program 17 csyEIZr excuuntl 18 csyEIZr gcclexyycrl 19 csyEIZr auutlt cuuntl menus was umx ll was 35 Anofh er Flex Program W l mm lt m gt W a l ml a may mo l wrexo gt menus quotxecagnze uncles a and hgt sktp who epacer scum da mmng m mdmates da same scum as mxtpa em amwvas ts an uhcl n yytext amwvas mmyyexg Not yytexttsapolmeno mst c atoftheto en yylen cagmnokcn ems Wm u was 7 Token Defini ons Exfended Regular Expression Elementary Opera rions single characfer39s excep ltgt concafenafion puf characfer39s fogefher alfer nafion alblc a ak abciLillt azO9 menus a eHer39 or digit y character but a ems Wm u was 2 Token Definifions Com Elementary Opera rions cont mafches quot Kleene C as any characfer39 excepf The newline ure Posifive Closure Exam es P 09quot quot09 note without the quotes it could be any character is whifespace exce tCk 39 There is a blank space character before the l menus ems Wm u was 9 Token Definifions Com Special CharacTers maTches any single characTer excepT newline quoTe The parT as TexT quot double quoTe This means The preceding was opTional alab mantis was sums ii was on Token Definifions Com Special CharacTers cont A means aT The beginnin of The line unless iT is inside of a means aT The end of The line same as n means anyThing exce quot 39qquot is a double quoTed sTring n m n Through m occurrences a13 is a or an or aaa varName iranslaiion of varName from definiiion maTches only if followed by righT parT of 01 means The 0 ofOl buT noT 02 or 03 or o grouping 5 mm was sums ii mus M 39 Programmmg Ruben w Sabesrn Qhapter 1 Topics Reasons for Studying Concepts cif Programming Lan ges Ptogra n39min Dilrrl mail 6 87a m 1 Reasons for Sludying Cancepls of Programming Languages Increased ability to expremdeas g osjn Software LifeCynle 1 2 Program m i hg Dje m ai ns Evaluation Criteria Readability OveraIISImpllclly 7 anageables re u imp mumm Evaluation Criteria Writab ility v and 39orthogOnality st 5 139 ru Evaluation Criteria Reliability Typeshecki ng T trig fo typgei rs dli Evaluation Criterra Cost mam Evaluatian Criteria Others Roriabflitzy 3M5 Hm Evaluation Criteria Readability OveraIISImpllclly 7 anageables re u imp mumm Evaluation Criteria Reliability Typeshecki ng T trig fo typgei rs dli Evaluation Criterra Cost mam Evaluatian Criteria Others Roriabflitzy 3M5 Hm Computer A ch itecrum Influence mo dominant beg ugeLOf Thevon Neumann Armin35mm mem wwmmm 15 Language Categories Imperative 7 Central feature areyariables axxugnmenmtatememx and 1 ration 5 1 6 Language Deslg n Trade Offs to arrawelemenfy alxleafds t 17 Implementation Methads Layered 39V ew of Com purer Ce mp1 atio n The Compila ah Proms Add ional Compilation Te rminalng ies 39e the us f Executlcm of Machine Cede we on raw n N eu man 1 Van Neumann Bottleneck Pure Interpretation Nu ha slali n E Pu re Interpretation PIECE 5 thriri Hybrid Implemeniatio39n Process lmtlally tr39anslate p gramsrm ah interm gd e language h Preprece ssors 18 Programmin g Emil ro n menu The collection on oolx used In o Ware lgpment Summary The iludy of progra m anumb ofreqxo 39 mlng languages 3 yalugblewr a magquot Chapter 13 Topics Introduct lon Introducthn to SubpmgameLevel Concurrmcy em res MessagePasslng Javaaneads CThreads statementeLevel Concurrency Introduction Concurrency can occur at four levels 1 Machlnclnstzuctmnlevcl z llrgrelevel language statement level level e eeruse there are na languagerssuesrn mmumme and pmgamelzvel eaneurreney they are nat adiessed here Introduction l Late WSEIse One genenlepnrpuse pmcesmx andane ar mare spclale rpese pmcessaxs faxmputmdantput apentmns 2 Earlle s e Mmple eanrplete pmcessaxs usedfm pm mmeizvelcancumnc z Midelg s e Multlple pumlpmcessms usedfm msmwonnelzvelcancnmncy A SmgizelnslmtmnM n zeDatnSWDmachmzs Tire same msmwonn gaes tn 5 pmccsmxs eachwnh arrrerent data e e g vectnxpmcessaxs 5 MulnpizelnstmtmnMultlpleeDataGHNDmachmzs pe n messms dutcanbe lrmnaeelorrn izvelcancnmmw Introduction h F sequence ofprogmm points reached as control ows through the progam memy ysxcal cuncmency 7 Multiple mdepmdent prunessurs multiplethr ads Brennan 2 Lugxcal cuncumencyr The appearance ufphysxcal cuncun39ency Is presented by nmershznng une Categories ofConc 1 Ph were multiple threads ufeumi Introduction to SubprogramLevel Concurrency D a mmmmmammm ammmmhmwa f m mama g m a emmma mum Maw maul my ea whammy mama Tammmywkaem mm he mmm M szmbe m Inmamdmmammmizimaemm Introduction to SubprogramLevel Concurrency l Eavpmum 39nsk Ammwuuxusk Em will an Wadi mam ask a m m 5 9mm g m mam zmrwubim 2 Emma mm mm mm m mmmema 5mm a e mam Mm me me mmrm m ma Ina Introduction to SubprogramLevel Concurrency mm 3 mm elm teemmete nu me new eemna malty mane amen em a 0cm 5 Deeds m largelan m anysense 1 M m Introduction to SubprogramLevel Concurrency may or may not have In seq 1 uentla eventually complete lts executlon In a concurrmt mvlronment atask can easlly lose lts llveness If all tasks In a concunent envuonrnent lose Lhelr lweness It 15 called deadlock Introduction to SubprogramLevel Concurrency Deslgn Issues for Concunenc I H y qus eeep Eratmn synchrumzatmn plundeav 3 Huw and when an tasks begin and end executmm Axe tasks statically en dynammally eeeateuv Lh d ofProndlng Synchronlzatlon E z Muntun 3 Message Fassmg Semaphores Dukstxar 1965 A sanaphure is a data meme cunsxsung uf a cuunter and a queue fur stunng task descn turs Semaphures esn be used cu lmplemmt guards Dn the euue that aeeesses shared data structures Semaphureshzve unly twu uperatmns wait and release ungmally called 1 and be DuksLm and cunperanun synchmmzanun Semaphores ceepeueeusmmmamu AswanEu u mm Wmumsmesumuwm Wmmmwsm muss mmd mmsm Vpu mnsmdwmnrdnluse Semaphores mnusemmet u zsemzylwxe39s Emma gt u em nuemu zsemlmwxe39s cmnlu Pm me uller zsemmwxe39s mule Auuvvun tuner mm m m m yl use Mummy mum Wrzmmme s llquotl2 em ymn39scm quot mee mat5km meuakruay If cullml 1n tx dmn mssmeuueeevs queue Producer Consumer Code sunswpmmc r ewtysp csmmc czsk Pmmcex Jon fullspucg Emptyspncsl mm 7 promise mu mu martyspucsh mu m 3pm nzyosmmuzy relezsek lnsp csh Mme in leap ea mu fullspucsh axc n m emPCY mummy x Jensekmptysputsh mange mm mum mu and mm Semaphores Comp etmon Synchromzauon wah Semaphore r u 1 V cuntxul access Bump euan synchrumzauun m saunter afaccess mu mth a Wm n and Suchsemaphmexsca edahmrysemaphme 7 Nutethat um and release mustbe atmmm Producer Consumer Code 3 mum WWI mvgmzi 3 E 2222 153233 2 aair szsgz 2mirsiszzgt Semaphores Evaluatlon ofSemaphores z Mlsuse uf semaphures eau eause failures m t wtll deadluek lthe release ufaccess 15133 uut Monitors ConcurrmLPascal Modula Mesa The Idea encapsulate the shared data and Its opemtlons to restnet ace manner 15 an abstract data type for shared data Monitors Example language ConcmmLPascal e ceheuneht paseal ls paseal elasses pmeesses tasks mumteus and the queue datatype fur semapheues e Prueesses are types dedauhm uaesnatstmsexesuum Anmstancels stazudquotbynt whcha acnzeslts lasu dataandbegnsns execuuan Monitors Momtors are also types Form vmsbles lucal prunedures Expuned prunedures have entry m de mnun mmahzanun euue Monitors Comp etmon Synchromzauon wah Monnors 7 Access m the s ared data m the mummr 15 hmned pm s at a e i E e gm e a g i 2 E ed Cooperation ls SL111 requued e done wah manh m quot Lhe bumun opaahons delay slmxlarto wait and continue slmxlarto release M on itors Coopemuon Synchromzauon wah Momtors pmeess that calls n m the speci ed queue and remuves us exelusve access nghts m the mumtur39s data structure Durrusrmu seuabeeuuse uuuyuwuysbxueksme 51121 mscunnects the caller 39nm me mumtur thus seemg me mummr furuse by muLhEr pmeess n 315 takes 2 empty and starts n Diffusfxam release became n alwayshas same emu release uaesmumgm queu xs empm Monitors Evaluatron ofmomtors e uppurt fur surnpetataun synchmmzanun rs great srrnuar as wrth semaphores su rt has the same pmblems Message Passing Message passmg rs a general model for concurrency 7 1t rs not rust fur Bump eaaun synchrunrzaaun seerng a doctorwmost ofthe tune he warts for you or ou wart for hrrn but when you are both ady you get together or rendezvous don t let tasks mta rupt each other Message Passing In terms oftasks we n ed a Ame hamsrntu alluwatasktumdmate when rtrs ag s i a Q a s rnher whu rs waang tn septed and some fan way uf message 5 message rs sk the a tual Def when asendertask accepted by a receryerta c rendezvous rnessage transcnrssron rs called a Message Passing The Ada 83 MessagesPassing Mo 1 e Adamskshzve wem canun dbudy pans hk packages the spec has the interface winch is Lh enuecann ufentxy pumts e g e e entry 2mm ismn n mom and EX Message Passing The lace when arendezvous occurs while Waiting for the message to be accepted and during the rmdezvous Entry points In the spec are desmbed with accep clauses In the body Message Passing Example ofataskbody task body maximum 5 begln loop accept Emily 1mm 1n FLOAT o end ENTR Iil end loop end TASKJXAMPLE Message Passing Semantics a Thetask executestu die mp ufuie accept clause an mus nramesszge b During exeeuuuu ufuie accept clause the seiueiis summed e eiuieiuibuui uiieeuuus u scuie wenmg messages Rendezvous Time Lines Message Passing Atask Lhathas accep clauses butno other code is called a smatask the mmpie above is a serveriask ALaskwiLhoui accept clauses is called an actor task A Rendezvous C ix n my Message Passing Example acturtask cask wamxinom39rox n speclflczmun cask body mmxinoun39ox 77 body beg mp n mmxiLmEL gt minmn sowuum may yo 77 No mum execumun 7 m a 1m 1 second gm Jeep end wrmxinom39rox Message Passing m L ms Note A smdermust know the entry name otherecewerbutnotv1cevasa asymmemc Message Passing allocaied Example cask type nagm s and type mum 5 access nagmg mm nagmg stack dynzmlc 5 713m n w nski39r zpail n heap Ynzmc Message Passing 7 The muscauumask has an entryclanse fur e task may has an accept clause fur each entry clause placedm aselect clause which is m aluup Message Passing Exampletaskwith mulupleenmes 25x may MM 5 Joey me My mm mm m zcceyc mm mm mm on Message Passing l 7 Ifexactlyune entry queue lsnunempty eheese amessage umlt chuuse me nundetarmmzucally 39nm wideh m acceptamesszge 7 if all are empty wait 7 The Eun mdls u en ealled aselemvevmt c i A A i A c H the clause but before the nexl clause 7 Executed cuncmendy wnld me caller Message Passing Coopemuon Synchronizath with Message Passln 7 PruvldEd by Guarded accept elauses 7 Example when not FULL BUFFER gt ccept DEPOSIT NEVLVALLVE do end DEPOSIT Message Passing e if Dre Lhanune are npen nundetarmmsncallychuuse a Message Passing 7 select r eheeks the guards an all elauses u i m queue amung them in eheek fur messages 7 ifau are elused ms amnurne mu 7 A select elause cznmnlude an else elause tn zvmd mm nune else chase templates une laap repeats Message Passing r a a clauses Note The siation may be out ofgas and thee ma ormay notbe a position available In the Y garage task casismnonianmnmr 5 entry SERVICELISLAND can 2 can mm entry GARAGE can 2 cARiTyPE end GASisTATIONiATTENDANT Message Passing easx may Gasis39naxoxviannm as hegxn em man Message Passing Passlng 7 Examplea shared buffer 7 Eneapsulate the buffer andlts an 7 cennpeaann synehmnizaann is implicit in the semanaes ufaccept elau onyan anygvm ses Message Passing Task Teimination 7 Def The eneeuann ufataskls cumpletedlf cuntxulhasreached the end uflts endehndy 7 if atask has created nu depmdenttasks and is empleed itis tarmnated cumpleted itis nut temnated unal all lts dependent tasks are tarmnated Message Passing terminate state A mmt em nace clause is selected when no accept clause is 0 en when a terminate is selected in atask the ofthe dependents of its master are e ther completed or are waiting at a terminate A block or subprogam is not le until all of its dependent tasks are teiminated Brahms in atask accept dame mata lt eanhe active at nine Message Passing memes 7 The pnunty uf any task can be set Wuhuue prams prlorlty 7 The pnunty ufatask applies u n unly when n 15 m metaskready queue Evaluauon othe Ada 83 Taskmg Model 7 Ifthere arena dismbuted prunessurswlth passng are equally suitable 7 OLherwASE messagepassmgxs clearly supenur Concurrency in Ada 95 Mugs AdaXanmmnmymmwfemms 1 Mcmdobjeds umuxuummmmmmeeumuuu miwdlnwuusswumddzumnmmbadm u how meeeuweuumee mml nmssthPssadw m wuumswumgmmmummm Ammudwaummw e e me u uussmymmda mm u uzudmmumyr mammuumymwu Wuzudabjezu 2 A e um Wedmwmmmsseleccmnms An mmmuemu ummw euuef rmuy mg m uu man5e eugenuwumeummeem uhy hm emgmuwumm Memuuu Java Threads The Thread class runnable interface Java Threads 7 A methnd hunchsz m Synchrumzed mndu39ux ma awsanymhzxmethndfmm mnnmg anthz mm whu u 5 m execntmn lya pun ah me md mnsl be mm mm Interference n e synchmmzed 7 fan canb 7 m um 110an andnoclfyAllmedmdsue Mm m object whmmsm xamchss mm sa 5 abjectsmhznnhzm 7 Thzwzlcmzdmdmustbecallzdmalnap StatementLevel Concurrency ng117perfuxmmce FORTRAN HFF 7 Ethsmns hmwm pmgnmmena pmvlde mfannmmnm m camp um hzlpn apnmue cad fax m npmcessaxcampmexs P xyHPF ecx cmans A39n 1 N ex pmcessms dunmm mama mm x Cyan mu mun Mum W mm mm ammqu ufanz Amyw h um afamthzx um myme wx39m mmme StatementLevel Concurrency cmammpxe mm mman mgum mm mean mum rm mam PM In um msmm am one P um um nwumw m 1 mu mm z W mm 7 mgumw 115v umsq 7 1m mew 1 mm um I x gum I um ammmnmmmuwmm mmw 5mm Goals of the parser given an input program 7Fir1d all syntax errors for each produce an appropriate diagnostic message and recover quickly 7Produce the parse tree or at least a trace of the parse tree for the program The Parsing Problem cont 0 Two categories of parsers 7 Top down produce the parse tree beginning at the root Order is that ofa le most derivation Traces or builds the parse tree in preorder 7 Bottom up produce the parse tree beginning at the leaves Order is that of the reverse of arightmost derivation arsers look only one token ahead in the input P The Parsing Problem cont Topdown Parsers 7 Givena sentential form XAOL the parser must choose the correct Arule to get the next sentential form in the le most derivation using only the rst token produced by A 0 The most common topdown parsing algorithms 7 Recursive descent a coded implementation 7 LL parsers table driven implementation The Parsing Problem cont Bottomup parsers 7 Given a right sentential form 0L determine What substring ofot is the righthand side ofthe rule in the grammar that must be reduced to produce the previous sentential form in the right derivation 7 The most common bottomup parsing algorithms are in the LR fam39 y 7 YACC is inthe LR family YACC Introduction 0 What is YACC Tool which will produce a parser for a given grammar 7 YACC Yet Another Compiler Compiler is a program designed to compile a LALR1 grammar and to produce the source code ofthe syntactic analyzer of a language produced by this grammar History I Yacc original Written by Stephen C Johnson 1975 I Variants lex yacc ATampT bison ayacc replacement GNU ex fast lexical analyzer GNU BSD yacc g PCLEX PCYACC Abraxas oftvwre How YACC Works YACC source foo y E g 0 youtput 1Parse 2Compile Abstract Token stream Syntax Tree 3 Run A YACC File Example w hxnclnde ltstdm h H mm m mm H swam m e apxessmn amass puma mm 5 apmssm amass m mmmlt S 1 s expessm ma w m yyexmxkcmx m lt fpxmtfksthx m y m mamkvuxd lt mama YACC File Format quotM C declam mu39 yutt dedumtinnx Grammar mm w n Addi unal C rude Comments in may appear in any ol Lhe sections Definitions Section include ltstdiohgt include ltstdlibhgt 9stoken ID NU39M 9sstart expr suirt from exfnr Start SYInbol The first nonterminal specified in the grammar specification section 0 To overwrite it use Sta rt declaration start noneterminal Rules Section Is a grammar Example expr expr 3939 term term term term factor factor factor 3939 expr 3939 ID NUM Rules Section Normally written like this Example expr expr 3939 term term term term 3939 factor factor 2 factor II expr II g ID NU39M The Position of Rules expr expr 3939 term 1 3 term 1 term term 3939 factor 1 3 factor 1 factor II expr I39 2 ID NU39M Works wlth LEX LEX O9 cal exO Wexo I rum 7 programs YACC YYPOFSBO 1239 3926 1 N UM 39 NU39M I LEX and YACC need a way to identify tokens ation between LEX and YAcc yacc ed g39ramy Use enumerauon de ne YACC creates ylabh W lemm LEX includes ylabh ytabh Communication between LEX and YAcc v4 rd scannerJ Y3 m y Nlnclude ltStd10hgt produces hnleude ykabh M ytabh id Leezeez genezoemx vs at deflne CHAR 259 nt return my a deflne FLOAT 259 gm 6 1 1313 w defme I 50 ea re urn 1d X re ur 39ID defme 1m 25 f A parsery NJnclude ltstd10hgt Mlnclude ltstd11bhgt vs ystoken 39cHAR FLOA T ID mm H YACC Rules may be recursive Rules may be ambiguousquot Uses bottom up Shi Reduce parsing Get atoken Push onto stack Can it reduced yes Reduce using a rule no Get another token Yacc cannot look ahead more than one token Passing value of token I Every terminaltoken symbol may represent a value or data type May be a numeric quantity in case of a number 42 May be apointer to a string quotHello World I When using lex We put the value into yylval In complex situations yylval is a luuon I Typical lex code 0 1 yyivai atoiyytext return NUM Passing value of token Yacc allows symbols to have multiple types ofvalue symbols union double dval 39nt vblno char strval Passing value of token nunion double dval we int vblno ytabh char strval V 4 extern YYSTYPE yylysl 0491 yylyalvliln ialoioytext momr V Amp yylyslstr sjrdupo39yte i rem STRING L ex file elude ymbh Yacc Example I Taken from Lex amp Yacc I Example Simple calculator a 4 6 a 5110 h 7 c a b a c 17 5 Grammar expression expression term expression term tam term Hr factor factor factor expression 3939 factor E Symbol Table udefine NS I MS 20 maximum 11 0 symbols struct symtab char na e double value symtabmsims struct symtab symlookO parserh H 1nc1ude parserh 1nc1ude ltstr1nghgt kunlon double dval struct symtab symp hoken ltsylupgt NAME hoken ltdva1gt NUMBER hype ltdva1gt expresslon hype ltdva1gt term hype ltdva1gt factor at parsery Parser mu statementillst statement n statementillst statement n statement mm expresslon sneavalue 53 expresslon prntf ysgn 51 expresslon expresslon w term ss s 53 expresslon term 5 e s e 53 may Parser Gourd term term I factor 5 1 53 term 3939 factor 1 3 werrorquotdivide by zeroquot 55153 factor factor expression 3939 factor NUMBER mm parser y Scanner M uinclude quotyrtab h39 uinclude quotparser hquot u nclude numb 6 9696 os 09 wlvalrdv 31 retum NUMBER 09eE o9 atof yytext c ignore white space scannerl Scanner conl39d AZaz AZazOSl retum symbol pointer wlva symp symlookyyex retum NAM retum o end of input n quotWVn cum wtexcm 96 s scannerl Precedence I Assoclatlon 1123 yquot Pep w 2123 1 1 2 3 1 2 3 or 1 2 3 2 1 23 1 23 or 1 23 Yacc Shi Reduce con icts Default is to shift Precedence I Assoclatlon right left lt gt NE LE GE left 7 left 39v v39 highest precedence Precedence I Assoclatlon left w Met W noassoc UMINUS expr expr w expr 5 1 3 expr r expr 16370 yyerror d1v1de 0quot else 55 1 3 expr iprec UMINUS 5 752 IFELSE Ambiguity Consider the following Iule sum 2 IF exp sum IF exp sum ELSE sum How about the following statement 7 IF expr IF expr sum ELSE sum IFELSE Ambiguity 0 It is a shiftreduce con ict 0 Yacc will always choose to shift 0 A solution stut matched unmatched matched otheristm u expn Tun1 matched ELSE matched unmatched 1r expn Tun1 stut 1r expn Tun1 matched ELSE unmatched ShlftIRoduco Con lcts shiftreduce con ict 7 occurs when a mmmar is Written in such a Way that a decision between shi ing and reducing can not be made 7 ex IFEL SE ambiguous To resolve this conflict yacc will choose to shift ReduceReduce Con lcts ReducyRaIuce Cun ictx start chm stmt Expr CONSTANT strut CONSTANT earlier in the grammar NOT GOOD So modify grammar to eliminate them Error Messaes Bad error message 7 Syntax error 7 Compiler needs to give programmer a good advice It is better to track the line number in lex vold yyerror char 3 fprlntfstderr quotllne d snquot yyimeno s Debug Your Parser 1 Use t option 0139 define YYDEBUG to 1 2 Set variable yydebug to 1 when you want to trace parsing status 3 If you want to trace the semantic values 0 De ne your YYPRINT function define YYPRINTifrle type value yypnncu frle type value stalth vuld yypnm FILE 39file mt type 39ziSTiPE value Valuerprregtname17 Valueniaquot 1 39 Shift and Reducing Example stmt stmt 39 stmt Stack NAME exp ltemptygt exp exp 39 exp exp 39 exp inPUt a 7 b 3 a 2 NAME NUMBER 13 Recursive Grammar 0 Left recursion 0 Right recursion LR parser keg yacc prefers left recursion 0 LL parser prefers right recursion YAcc Declarat39on Summary quotnstart39 Specify the grammar s start sympot nunion39 Deetare the coheetmh ofdata types that Semanttcvames rhay haye quotntoken39 Deetare a terrhrhat sympot token type name wth ho precedence or associattvtty speemed quotntype39 Deetare the type otserhahtreyames fora honterrhrhat sympot YACC Doclaratlon Summary Deetare a terrhhat sympot token type harhethat t5 nghtrassoctatwe nleft39 Deetare a terrhhat sympot token type harhethat t5 e rassoctatwe nonassoc39 Deetare a terrhhat syrhpot token type hamethat t5 nonassoctanve usrhg tm a Way that woutd be associative is a Syntax error ex x op y up 2 t5 Syntax error Chapter 8 StatementLevel Control Structures Uncon monalBranchmg Guarded Commands Conclusions MultipleWay Selection Statements Destgnlssues 1 WhathLhe sum and type quhe cuntxul expressmr z Hawareme selectable seguents spen ed7 3 Is executmn uw Lhmngh the structure resm med 4 Whatxs dune abuutunrepresented expressun values7 MultipleWay Selection Statements Early Muluple Selectors 1 RT Nanmmeae IFathreervaysele1ur man expem L1 L2 as Bad aspects 7 Nut Encapsulated selectable segments cuuld be an here 7 Segments requer sores MultipleWay Selection Statements ModemMulhple Selec m Huare s cunmbutmn tn ALGOL N expem g Lust statement canstnntihstin statement end MultipleWay Selection Statements Deslgn choxces ofPascal 1 Expressmnxs any urdmaltyp nt boolean char enum z Segments ean be smgle Dr eumpe Chly une stagnant znbe ex quhe cun md 3 cuted pa Executmn 4 In Wmh s Pascal result uf anunrepresented Standard xtxs gruntme ermr 7 Many 621215 nuwhzve otherwlse urelse clause MultipleWay Selection Statements 2 The c CH and Java sthch swltch Expressmn cunstzntiexpressmnin statement u t statemean 1 cunstzntiexpressmnil atementil MultipleWay Selection Statements Deslgn Cholces for switch tn CCHIava centtul expressmn can be unly an tntege type lslueks Dr eurnpuunu statements An her ufsegrnents can be Executed tn une executmn quhe cunstxuct Tu svututt e pmgamma rnust Supply abreak statement fur esen segrnent A default elsuse ts fur unrepresented values if Lha39els efaultLhawhulestatememdues MultipleWay Selection Statements tvmvayselecturs usmg elserlfclanses ALGOL 68 FORTRAN 9n Ada Ann Iterative Statements compound statement ts accompllshed ether by tteratton or recurston Here we look at tleratton because recurston ts 53 unltrlevel control m General destg tssues for tterntton control Statanents Huwls lteratmn cuntmlled t39 z Wheretstlteeunuulrneelnsntsrntntltelunpv Iterative Statements 1 CounteraConLrolled Loops Deslgn Issues 1 z Whatlsthevalueuftheluup vanableatluup termma 7 3 Shuuldltbe legal urtheluup vanable urluup parameters U be changedm Slump may analf a 4 Shuuld Lheluup parametersbe evaluated unly unce my uncle fur eva39y xteranun 7 Iterative Statements 1 FORTRAN 9U Syntax Do label var slam msh sepslze Stepslze can be any value but zem Fammeta s can be expressluns Deslgu chulces l laapyambl mustbe 1mm 2 Inapvamblz always has la lawn parameters cambecanse Lhzvm mlma anlyam ll dues mm mm Imp cumml 4 map m m mlma anlyam Iterative Statements FORTRAN 90 s OLha Do a Synth name Do vanablelnmal tel39rmnal L sepslze my D0nzme a Lump vanable mustbe an INTEGER Iterative Statements Z ALGOL U Syntax for var ltllst7ufistu gt do staternent where ltllst uf stuD ean nave e expressmn seepexnnsndn unm expressmn pres nan whll baalz aniexpxessmn Iterative Statements ALGOL 60 Deslgn 11101665 1 Centml expressmn can be nt urrealts seepe l5 whatevent l5 deelared tn 2 Centml vanalde has lts last asslgled value a er eep terrnlnataen buttne parameters ean and when they are lt affects lump eentrel 4 parameters are evaluated with every lteratmn malnng ltvery cumplEX and d aedlt tn read Iterative Statements ax for mam e mmal eel downco nal dostntemem Deslgl Chulces l Inapvamblz must be an axdmaltyp arnsnal scrape 2 3 Th Inapvamblz canmtbe changedm tn lann tn Imp nennnters canbe changedbm theyare mlnated Justance 5a ltdnesnata ect Imp cumml A Instance Iterative Statements 4 Ada Syntax for var Jn reverse dtsmeteimnge loop end loop Iterative Statements Ada Destgn chotces t Typeeftneteep vanatsttetstnateftneatserete rangetts seepetstneteep budy tttstmpttntty declared z Theluup vanatsteanesneteansteutstaetneteep 3 butthe easerete range ean tt dues net affeet lump e t 4 The atserete range ts evatuatea juSL unce Iterative Statements 5c Syntax for expzrt exsz tang statement e Tne expressmns eantse wnate statements areven statement sequences wttn tne statements senamteattsyeammas tne tast statement tntne expresstan e z for tr e 0 e 10 ee 1 u e trtne secandexpxessmn ts absent tt ts an tnttntte Imp Iterative Statements c Deslgn Cholces There ts nu expltettlnnp vanahle 3 Everthmg ean he changed tn the lump 4 The tatst expressmnls evaluated nnee hut the nthet twu are evaluated wtth eaeh lteratlun Thls loop statement ts the most ailbIe Iterative Statements 6 C lefers om c tn two ways 1 z The tnttaal exptesstnn canmdudevznable aesnttanns scupe ts ham the aesntann tn the md quheluup budy Java lefers om c tn that the control expreslen mustlte Boolean Iterative Statements 2 Loglcallyecontrolled Loops Deslgnlssues 1 SW 2 Shulde thtshe aweclal ease ufthe enuntanglnnp statement at a separate statementy Iterative Statements Language Examp 1 Pascal has separate prete and pumestlugcal lump stat ments whllerdo and repeatr untll z c and CH alsu havebuth butthe cuntml hkexnthepretest ease whlle e do and do 7 whlle 3 Java s hke c except me eenael Expressmn must be Buulezn and Lhebudy ean unly be entered at Lhebegnnmgnlzvahasnu goto Iterative Statements Language Examples Contlnu d 4 memes as lugcal leaps whlle and untll mm p testlugcal lump Iterative Statements 3 UsenLocated Loop ControlMechamsms ndmunalbepanu e m z Shuuld cuntml be transferable em ufmure than uneluup 7 Iterative Statements amples l Adar cundmunal uruncund tmnal fnranyluup any numberuflevels m may em m0 Iterative Statements c c and Java ebzeak Uncondmonal for anyl op orswlech one el only aceptlava s can have a label 39 There ls also a continue atement for loops 139 Sklps Lhe remalnder othls ltaatlon but does not eat the loop Iterative Statements Iteratlon Based on Data Structures her ufelemmts uf an n 211m a luneaen that ant m some chusen order if amp 7 C s for ear be used tn bulld a useeae nea lteratur for phdri p pnextp Iterative Statements Perl has a bulllrm iterator for anays and hashes 6 foreach sname nalnes prim Sname Unconditional Branching Problem readablllty Some languages do nothave Lhem e g Java 39 Loop exit statemmts are restricted and somewhat camou aged go o s Unconditional Branching Label forms 1 Unslgaed ml constants Pascal Wltn colon Z Identlflers Wlth colons ALGOL 60 c 3 Identlflers ln ltlt da Guarded Commands ansun 1975 Purpose to support a new pmgamrmng development Idea 1mporLa g eprogam should not Guarded Commands 1 Selectmn ultbanhmgtgtltsmmmgt n n W Emma whn39hscuzsmmhsml lld Duhm Guarded Commands z Lumps nonner gt meme new gt ltsmememgt n ltbaalznngtgt ltsmtzmemgt od semanucs Fureachxta39auun e Ewluteallbaalzanexpnssmns e Ifmaxethanamantmchnaseane mndztznnmlsnca y men sum lamp agam 7 Km are mu exn lamp 1the order of evaluation 15 n n Lh 0L specxfy one Guarded Commands progam venflcauon ls Intimate Verlflcatlon IS lrnposslble wlth gotos Verlflcatlon lsposslble Wth only selectlon analoglcalprelesllo s Verlflcatlon IS relatlvely slrnple Wth only guardedcommands Conclusion and loglcal premesf loops IS a lmdeoff between language slze and wrlmblllty quot Programmmg Ruben w 5333quot Pse ud ocode s Speedcodi n9 Sp eedcodmg deyelopedbleachus m 1954 or IBM 701 23 IBM 704 and Fortan Demgn Pm cess of Fortra n Impact Qfmyinonmenl Qndeis ig39nrongorIrar1 I Fairt raw Overview Fartran I Qvawiewwontilrrugc Furtran ll Fartran IV Fartran 7 7 Forth 90 Fart ran Evaluatin 24 Func Dnal quot Prg essing language mgped at M IT by McCarthy Representation of Two LISP Lists c LISP Evaluation Pioneeted functional programming Variab COMMON LI S P 25 The First Step Toward S stieamn ALGOL so Early Design Praeess ALGOL 58 Concept oftypawas formql lzed Lame c 39uld ALGOL 58 Im p l m e hta on ALGDL 3960 Overview ALGOL 68 Evajua39t lon ALGOL W EVaIuatmn Co nti ned Fail ure COBOL Histarica l Background COBOL Design Process 39rsI Desl39gh Me etl ng Pentqg DHJr Max21959 ggals CDBQL Evaluation COED DEB Influence 27 The Beginning of Timesharing BASIC Everything for Evarybady PLI PLl Evaluation 210 The B gginning of DataiAbstragt ion SIMULA 67 D 211 Orthogonal Design ALGOL 68 ALGOL g EVaIuatmn 212 Early Dascendanta of ALGOIS Pascal 1 71 m e mberb the 213 Programming Based on Logic Pmlng 214 H ist e xry s Largest Design Effort Ada Hugg dgsign effortlinvolving hundfeds ufpeqple h nd a l igMears 215 Object Oriented Frog ramming Smalltalk Developed at X Kay late byg 39 216 Combining Imperative and Object Or ie nted Frog ramming C A Deiel ped alBe ll39Labs 1 SL mp inf1980 qlvegl V 39 ed prqgngmrn ing faker 217 An Imperat lve Based Object Oriented Language Java Java Evaluation 218 Stripting Languages for the Web mm 219 A C Ba sed Language for the New Mlllennium C K Part o fth e deVelopm enf piat fbrr n Ba 1 a d 39 0 Ma rku39p ngramming Hybrid Summary Lex Overview Lex IS a tool for Creating lexical analyzers Lexical analyzers tokenize Input streams Tokens are the terminals ofa language Regular expressions de ne tokens Usage Paradigm of LeX chsourcc Lax 1 ny program lcxyyc Campus 7 40 input 7 Ml tokens To Use Lex and Yacc Together ex rce Yacc suurce Lexical Rules Grammar Rules lax yy c min i cal Lex Internals Mechanism Converts regular expressions into DFAs DFAs are implemented as table driven state mach in es lexyyc What it produces a sun mm my mm mm Nka mm vuxxfy advance J yyCXankD 00 00 13 00 00 00 o o lenc yynvi yydvccu 1 o o o yycrank r 0 Hum chranlvJ Ychvcu yyvuuma yyeruma o yywnp may elm yymulehD on 0 m 01 o 01 as 0 012 m m to m m Running Lex To run lex on a source le use the co and This produces the le exyyc which is the C source for the lexical analyzer To compile this use cc 0 prog O lexyyc Versions and Reference Books ATampT lex GNU ex and Win32 version lex amp yacc 2e by John RLevine Tony Mason amp Doug Brown O Reilly Mastering Regular Expressions by Jef 39ey EF Friedl O Reilly General Format of Lex Source m 7 mum ragaxtb mm ltrng xpgt m gum ltnctxougt gaging ltcvongt m u Sabratum c an Input speci cation le is in 3 parts Declarations De nitions Rules Token Descriptions and actions Auxiliary Procedures UserWritten code Three parts are separated by Tips The first part de nes patterns the third part de nes actions the second part puts together to express I we see same pattern then we do some action Regular Policy of None translated Source Remember that Lex is turning the rules into a program Any source not intercepted by Lex is copied into the generated program Any line which is not part of a Lex rule or action which begins with a or Anything included between lines containing n y an Anything after the delimiter Position of Copied Source source input prior to the rst external to any function in the generated code alterthe rst and prior to the second appropriate place for declarations in the function generated by Lex which contains the actions alterthe second after the Lex generated output Regular Policy of Translated Source Various variables or tables whose name pre xed byyy yyieng yysvec yywork Various Jnctions whose name pre xed by W yyiesso yymoreo yywarpo yylexo Various de nition whose name are capital BEGIN INITIAL Default Rules and Actions The first and second part must exist but may be empty the third part and the second are optional If the third part dose not contain a main II will link a default main which calls yylex then exits Unmatched patterns will perform a default action which consists of copying the input to the output Default Input and Output If you don t write your own main to deal with the input and the output of yylex the default input of default main is stdin and the default output of default main is stdout stdin usually is to be keyboard input stdout usually is to be screen output c520 laout lt inputfile gt outputfile Some Simple Lex Source Examples A minimum lex program It only copies the input to the output unchanged A trivial program to deletes three spacing characters tn Another trivial example ti It deletes from the input all blanks or tabs at the 39 es ends of lin A General Lex Source Example l A Example lex source tile This first section contains necessary c declarations and includes to use throughout the lex specifications a 1nclude ltstdlo hgt l blnidlglt o 1 blnidlglt r match all strings of 039s and 139s V Print out message with matching text printfquotBlNARY Snquot yytext l abaaab bbab i ab bbabaaab M match all strings oyer ab containing aa and bb printf quotAABBnquot n M ignore newlines V l A Now this is where you want your main program int mainint argc char argv i call yylex to use the generated lexer a yylegtlt A make sure everything was printed a fflush yyout eX1t07 l Token De nMons Extended Regular Expression Elementary Operations single characters except quotltgt concatenation put characters together alternation abc l quota any character but a Elementary Operations cont NOTE matches any character except the newline Kleene Closure Positive Closure Examples 09quotquot09 note without the quotes it could be any 0 aracter t is whitespace except CR There is a blank space character before the t Special Characters matches any single character except newline and quote the part as text t tab n newline b backspace quot double quote this means the preceding was a Special Characters cont quot means at the beginning of the line unless it is inside of a 39 means at the end of the line same as n quot means anything except quotquotquotquot is a double quoted string nm m through n occurrences a13is a definition translation from definition matches only if followed by right part of 01 means the 0 of01 but not 02 or 03 or grouping ab ab able Definitions 0 NAME REGEXPR digs 09 integer di 5 plainreal digsquotquotdigs expreal digsquotquotdigsEedigs real plainreaexpreal NAME must be a valid C identifier NAME is replaced by prior REGEXPR The definitions can also contain variables and other declarations used by the Code generated by Lex These usually go at the start of this section marked by at the beginning and at the end or the line which begins with a blank ortab Includes usually go here It is usually convenient to maintain a line counter so that error messages can be keyed to the lines in which the errors are found int linecount l DUl Transition Rules ERE ltone or more blanksgt program statement program statement A null statement will ignore the input Four special options ECHO REJECT BEGIN The unmatched token is using a default action that ECHO from the input to the ou pu I indicates that the action for this rule is from the action for the next mle Tokens and Actions Example real return FLOAT egin return BEGIN newline linecountH in eger prlntf l found an lntEgErn return INTEGER 39 l Ambiguous Source Rules If 2 rules match the same pattern Lex will use the rst rule Lex always chooses the longest matching substring for its tokens To overide the choice use action REJECT 39 h s REJEC he h REJECT n M ultiple States lex allows the user to explicitly declare multiple states in De nitions section NT Default states is INITIAL or 0 Transition rules can be classi ed into different states which will be match depend on states BEGIN is used to change state 39 L l mm BEGIN cumEIT I BEGIN DIITXAL l Lex Special Variables identi ers used by Lex and Yacc begin with e yytext W a string euntaining the lexerne e yyleng W the len th at the lexerne Example rilnteger l printf l fuund an integernj sscanfyytext d Styylval return lNTEGER l 7 C chrnrnents W i Lex library function calls yylexo e default rnain eentains a return yylexo WWEI39P e ealleu by lexlcal analyzer it end at the inputrile e ueraultyyvyarpo always return i yylessn e n eharaeters in yytext are retalned oreo e the next lnput Expresslun reeegnizeu i te he tacked en tn the end ertnis lnput User Written Code actions are complicated enough that it is better to describe them with a function call and de ne the function elsew De nitions of this sort go in the last section ofthe Lex input More Example 1 int iengsHOO aZ iengsyyieng in wwrapo int i pnn quotLength Nu wurdsinquot furi0ilt100i iflengsi gt 0 prinlfquot 05diodlnquotilengsi return More Example 2 M museum Hammer WWW 7 Jam r x word twoxdmnw swam yyleng i n chncmm mecmw i inn enunw i 77 maan i yylcx o prnfquotCharactens mesmmn charCoun l is wards u uoxdcmml linecount Using yacc with lex yacc will call yylex to get the token from the input so that each lex rule should end wit retu ken where the appropriate token value is returned An easy way is placing the line include lex cquot in the last section of yacc input 39 Programmmg Ruben w Sabesrn Qhapter 2 Topics 1 Zuse s Plankalkul 2 Minimal Hardw are Programming u otode39s Chapxer 2 TOpICS continued Everything for Everybody PLI Twu Early39 Dyhamuc Languages APL and BBLquot 39 Chapter 2 Toplcs Contlnued l 50bJeC o 6 mbi F d Programming Smalltalk 1 Genealogy of Common Languages Programmlng Languages mm w swell Chapter 3 Topics 1 Introducuo39h 31 Introduction 32 The General Pm bl e m 13f Describing StyMax Term inalagy Formal Definition Of Languages quot Recognizers 33 Fermal Methods 91 Describing Syntax usimaur39Fka jandl ConxexIiFree Chapter 4 TQpics 41 Introduction 41 Introduction com 41 Intrndurtion cm1t 42 Lexical Analysis 42 Lexical Analytls cont Lexical Analysis Using FIhiLejSta te Mac i ne s to Imp1er ent lexical 4 2 Lexical Analysis con1 42 Lexical Analy is COMJ 42 Lexical Analysis cent 42 Lexical Analysig contJ State Diagram luvmrDngxl umquot m gmquot D g l mm gum 42 Lexical Analysis man on axxumeimli iza on Lexical Analysis team 5 far practise on FSMS Chapter 14 Topics Introduction to Exception Handling xcepuonHandmgm da ExcepuonHand11ng1nc 1 o 1 m E 1 do 1 S lt Ex Introduction to Event Handling Evmt Handling 1mm Java Introduction to Exception Handling 1111111131119 mthnntexceptmn handing Whendnexceptmn accnrs cantml gaes tn the apemtmg system when a message 15 displdyzd andthz pmgmm 1s tznmmtzd 1111111131119 withexcepnan handbag ngnms m alinwed tn 1111p sum excepnans unnby pmvldmg d1 pusslhlhtyaf xmg 111 pmblem andeannn Mamlanguages aunw pmgmms tn trap Inputantth emxs mun EOF Def A11 exceptmn 1s anynnnsnai event 1111 ennnms a1 11m dztectahlebyuthzr hardware nsanwan111a11naynd111n spend pman Def n1 spend pmcessmg thatmdybe ndnnd d ndztzconn aran exceptmn 1s sailed excepnan handhng Def n1 exceptmn handing and 111111 xscd ed an exceptmn handhx Introduction to Exception Handling n uncurs Alanguzge that dues nut have Exceptlun handling capabilities ea1 51111 de ne deteEL 1ase a1d 11a1d1e Exceptluns user de ned su thre detected 1 immanme metexaxusethzmum mum V111 in 11111111 511115 11quot annngnn pssed 1nd 2 p155 mexcepnan handhng si npmgmm tn d1 subpmg Advantages 11f Builtrm Exceptmn Handling 1 Ermxdztectmn cad 1s ednn ta wnte 1nd11d111e1s111 gram 2 Exce 1111 dhandlinwsdlu hlmlafxeuse afexce n11 11ndng 15 3 P Introduction to Exception Handling ExceptionHandling Control Flow Luvml mt Exception Handling in Ada An exception handler in Ada can occur in eiLha a subprogam body a package body a task or a block Because exception handlers are to the code in which the excepti raised they do not have parametas usua11y1oca1 oh ca be Exception Handling in Ada Handler ful39m excepclun uh exc pcloninzmelexcepcloninzme e statemalcise u me man mm other e seaeenaae seau 7 me Handla39sareplacedatthemdufthebluckurunltm Whlchtheyuccur Exception Handling in Ada Binding Exeepuunsm Handlers e lfthzb d k whchanexceptmnls niseddms mt vea lzxfaxdutexceponn an exceptmnls ab nandl E 5 h eallex Nat n tn the scape in mahltappaxs thatdeclmdthz Fame ll39ms ahbmynnn m static parent line pmgmm is terminated 4 39r L case mark it damned Exception Handling in Ada Continuation e ebluckurumtthatrzlsesznexcepnunbutdues nut handle n is always termmated alsu any black n my unit in wlneh n is pmpagated ma dues n handle n Exception Handling in Ada UsardefinedExceptions exceptioninameilisl 2 exception raise exceptioniname e the Excepllun namelsnutrequlredlfltls in a handiemnuns exeepann Exception conditions can be disabledwith pragma SUPPRESSacepuonihst Exception Handling in Ada Prede ned Exceptmns cousmnxmimuon rdeX cunslxamts range n a ummcimuou e numene upemllun cannut return a nectvalue uver uw dnnsmn by sea etc nasnalEeen elabumted aromaaimuou e sysLEm runs nut ufheap Tnsnmimmou e an enur assunated with tasks Exception Handling in Ada Evaluation 7 The Ada design fur exceptmn handling embudles the slaterufrtheranmlznguage deslgim 198B 7 A Sign cant advanee uver PHI 7 A meaniyvndeiyusedianguagevnun Exception Handling in C 39 Added to CHm1990 Design 15 based on that ofCLU Ada and ML Exception Handling in C an Hanan mam mil yummy lt nah amt maul lt mama mam marmmauammmmaammwh fmmmkxofethlbenmu mam mkxm mthwzmh Par 1 11 Ink 5min m amt Wmtaxcmbensedm mfex om mmk imam m lam Wmtnxcmbeme lw mwhmhcase maps a mam mt yu imam Exception Handling in C Binding Exceptmnstu Handlers 7 Exc ms at a mscdexplmdybythz statement kzts are mztnsymbal row Mthnntanapxmdcmanlyappu ma imam Wm n appm n simplyxenlses m excepnnn man is than handled elsewth a m typ am expres an dlsamhignatzs m mma mm the fuman m which n is raised Ths pmp agaan cuntmues m the man imam w h m c a Exception Handling in C Continuation 7 A er ahandlercumpletesxts executmn eemtred adws te the rst statemeht a er the last handler m otherDestgn Choices 7 All exceptmns are userrde ned 7 Exceptmns arehetherspeetded hurdeeiared 7 thuut a speetdeataem a functmn can mse my exeeptadh the throw dause Exception Handling in C Evaluation 7 it is add that exceptmns are hut named and th hardware and system su threrdetectable exceptmns cannutbehandled 7 Bmdthg exceptmns te hmdiers Lhruugh the type uf e parameter eertahiy dues hut prumdte readahthty Exception Handling in Java All exeeptaems are abjects ufclasses that are deseehdahts quhe Throw ss ablecla TheJavahbrzrymcludestvm subclasses uf Throwable 1 Error 7 Thmwnb the 1m mte eterrerevehtssdshts hea mmw y m p xceptmns are dsdaiiysdheiasses afthls 7 Has twu predzfmzdsubchsses mmepedem md xurrememepedem e Arrzylndexouco a e uundsilxc pr em ahd NullPolncerExcep on 0 Exception Handling in Java Exception Handling in Java Java Exception Handlers 7 Like these ufcv Except every catchrequires a e pammeta and aii parameters must be aeseehaahts ufThrowable e Exceptmns 2r thmwn wtth throw asih c hut create the abjecL as hrow h m ew MyExceptlon o e Exception Handling in Java 4 t tittptet in Java Lhan ll is in c parametens the same class as the Lhruwn abject Dr an zncesturufit including a throw in the handle a handle could also throw a diffaent exception ehahuaaeh rha hahaiens rathaihthe cry sahsmtet the Search is cahahtteeiihthe heaxest endasmg emahsmtet etc pmpagated in the hethaers eeiiet irha hahaiens fa hd an the ma mam the whims temhatea Ta thsm thataiiexsepaahsm caught a handhxcanbe heinaeeiih any cry sahstmstthat satehes a exceptinns simpiytee ah xcepnmchss pmmztzx Ofcmlrse it mtsihe the iast in the my carsmwt Exception Handling in Java OLhaDesign Choices 7 The Java throws eiause is quite dif rmt 39nm the throw clause qu 7 Exceptmns ufclass Error and RunTlmeExceptlon and all quhElr 7 All uLherexceptmns are called checkedexcepuuns methudmustbe either I Lxmdmthethrowsclmsem 2 Handledon methad Exception Handling in Java throws clause Lhanthe melted at UVEmdes Amethud that eaus amethud that lists a pameuiar anemaaves fur dealing with ma Excepllun Catch and men the excepnan 2 Catch the excepnnn and thmw an excepnan am is teed m quote awn throws clause 3 Exception Handling in Java The finally Clause 7 Can appear atLhe md ufa try cunslmct r Furm flnally 7 Purpuse Tu specify cudethatxstu be executed Exception Handling in Java nutsae exeenannhanahng cry t m nnnax may e we anew flnzll l t H enn of try eonsemee Exception Handling in Java Evaluatlon e The types uf exeenanns makes mure sense than tn the ease ufc e The throws clausels Elena thanthat ufc The throw clause ln c says lltlle tn the pmgzmma e The flna J Jy clausels u en useful that ean he handled by user pmgrzms Introduction to Event Handling as a user lntemotlon through a GUI called In response to an event Event Handling with Java Java Swing GUI Componean 7 Text buxxs an abject efeiass JTextFJeld 7 Applet s alspiavls a 39zme amululzyered structure 7 Cuntentpzne is ne layer where applets put uulput 7 cu cumpunmts ean be placed in a Game 7 Layuut manager ubjects are used In eenaei me placarnent uf cumpunmts Event Handling with Java The Java Event Model 7 Usennteramuns with GUl cumpunents create events at ean be caught by evanthzndlers called event lmeners 7 An Event generaturtells alxslener ufan Event by smdmg amesszge 7 An Interface is used a make evenananailng memeas cun ur mtu agenda a 1 7 A class Lhatlmplemmts ahstenermusl lmpl nmt an Interface fanhe listma Event Handling with Java SemanticEmeClasses 7 ActlonEvent E c 7 FocusEvent Chapter 8 StatementLevel Control Structures Introduction 0 Selection Statements 0 Multiway selection stmts Iterative Statements 0 Unconditional Branching Guarded Commands 0 Conclusions Coovrrgm 2000 Pearson AddisoneWesley AH rgn s reserved 84 MultipleWay Selection Statements Design Issues 1 What is the form and type of the control expression 2 How are the selectable segments specified 3 Is execution ow through the structure restricted to include just a single selectable segment 4 What is done about unrepresented expression values oopvrrgm 2000 Pearson AddisoneWesley AH rgn s reserved 872 MultipleWay Selection Statements Early Multiple Selectors l FORTRAN arithmetic IF a threeway selector IF arithmetic expression L1 L2 L3 0 Bad aspects Not encapsulated selectable segments could be anywhere Segments require GOTOs Coovrrgm 2000 Pearson AddisoneWesley AH rgn s reserved 873 MultipleWay Selection Statem ents Modern Multiple Selectors l Pascal case from Hoare s contribution to ALGOL W case expression 0 f constantilistil statementil constantilistin statementin end Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved 87 MultipleWay Selection Statements Design choices of Pascal 1 Expression is any ordinal type int boolean char enum 2 Segments can be single or compound 3 Only one segment can be executed per execution of the construct 4 In Wirth s Pascal result of an unrepresented control expression value is undefined In 1984 ISO Standard it is a runtime error Many dialects now have otherwise or else clause oopvngm 2000 Pearson AddisoneWesley AH rgn s reserved 875 MultipleWay Selection Statements 2 The C C and Java switch swi tch expression constantexpressionl statementl39 constantexpressionn statementn39 def au 1 t statementnl Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved 876 MultipleWay Selection Statements Design Choices for switch in CCJava 1 Control expression can be only an integer type 2 Selectable segments can be statement sequences blocks or compound statements 3 Any number of segments can be executed in one execution of the construct To avoid it the programmer must supply a break statement for each segment 4 default clause is for unrepresented values if there is no default the whole statement does nothing Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved 877 MultipleWay Selection Statements Multiple Selectors can appear as direct extensions to twoway selectors using elseif clauses ALGOL 68 FORTRAN 90 Ada Adm if then elsif then elsif then else end if oopvngm 2000 Pearson AddisoneWesley AH rgn s reserved 878 Iterative Statements 0 The repeated execution of a statement or compound statement is accomplished either by iteration or recursion 0 Here we look at iteration because recursion is unitlevel control 0 General design issues for iteration control statements 1 How is iteration controlled 2 Where is the control mechanism in the loop Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved 879 Iterative Statements 1 CounterControlled Loops Design Issues 1 What are the type and scope of the loop variable 2 What is the value of the loop variable at loop termination 3 Should it be legal for the loop variable or loop parameters to be changed in the loop body and if so does the change affect loop control 4 Should the loop parameters be evaluated only once or once for every iteration Copyright 2006 Pearson AddrsorrrWeSley AH rgh S reserved 810 Iterative Statements i FORTRAN 9O Syntax DO label var start finish stepsize Stepsize can be any value but zero Parameters can be expressions Design choices 1 Loop variable must be INTEGER 2 Loop variable always has its last value 3 The loop variable cannot be changed in the loop but the parameters can because they are evaluated only once it does not affect loop control 4 Loop parameters are evaluated only once Copyrrgm 2000 Pearson Addisoanesley AH rgh s reserved 811 Iterative Statements FORTRAN 90 s Other DO Syntax name DO variable initial terminal stepsize END DO name Loop variable must be an INTEGER Copyrrgm 2000 Pearson Addisoaneslev AH rgh s reserved 312 Iterative Statements 2 ALGOL 6O Syntax for var ltlistofstuffgt do statement where ltlistofstuffgt can have 7 list of expressions 7 expression step expression until expression 7 expression whi le booleaniexpression for index 1 step 2 until 50 6 0 7 0 8 0 I index 1 until 100 do index l 3 5 7 49 60 70 80 81 82 l 100 Coovngnr 2000 Pearson AddisoneWeslev AH rgn s reserved Iterative Statements ALGOL 60 Design choices 1 Control expression can be int or real its scope is Whatever it is declared to be 2 Control variable has its last assigned value after loop termination 3 The loop variable cannot be changed in the loop but the parameters can and when they are it affects loop control 4 Parameters are evaluated with every iteration making it very complex and difficult to read Copvngnr 2000 Pearson AddisoneWeslev AH rgn s reserved 31 Iterative Statements 3 Pascal Syntax for variable initial to l downto nal do statement Design Choices 1 Loop variable must be an ordinal type of usual scope 2 A er normal termination loop variable is unde ned 3 The loop variable cannot be changed in the loop the loop parameters can be changed but they are evaluated just once so it does not affect loop control 4 Just once Coovngnr 2000 Pearson AddisoneWeslev AH rgn s reserved Iterative Statements 4 Ada Syntax for var in reverse discreterange loop end loop Copyright 2006 Pearson AddisoaneSTey AH rgh S reserved 816 Iterative Statements Ada Design choices 1 Type of the loop variable is that of the discrete range its scope is the loop body it is implicitly declared 2 The loop variable does not exist outside the loop 3 The loop variable cannot be changed in the loop but the discrete range can it does not affect loop control 4 The discrete range is evaluated just once Copyright 2000 Pearson Addisonevvestey AH rgn s reserved 317 Iterative Statements 5C Syntax for expril expr72 expr73 statement 7 The expressions can be whole statements or even statement sequences with the statements separated by commas 7 The value of a multiplestatement expression is the value of the last statement in the expression 9 g for i 0 j 10 j 1 i 7 If the second expression is absent it is an in nite loop Copyright 2000 Pearson Addisonrvvestey AH rgn s reserved 318 Iterative Statements C Design Choices 1 There is no explicit loop variable 2 Irrelevant no explicit loopvar so value after loop is irrelevent 3 Everything can be changed in the loop 4 The first expression is evaluated once but the other two are evaluated with each iteration This loop statement is the most flexible Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved Iterative Statements 6 C Differs from C in two ways 1 The control expression can also be Boolean 2 The initial expression can include variable definitions scope is from the definition to the end of the loop body 7 Java Differs from C in that the control expression must be Boolean Copvngm 2000 Pearson AddisoneWesley AH rgn s reserved Iterative Statements 2 LogicallyControlled Loops Design Issues 1 Pretest or posttest 2 Should this be a special case of the counting loop statement or a separate statement Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved 321 Iterative Statements Language Examples 1 Pascal has separate pretest and posttest logical loop statements whi ledo and repeat un t i 1 2 C and CH also have both but the control expression for the posttest version is treated just like in the pretest case whi 1e do and do whi 1e 3 Java is like C except the control expression must be Boolean and the body can only be entered at the beginningJava has no go to Coovngm 2000 Pearson AddisoneWeslev AH rgn s reserved 322 Iterative Statements Language Examples continued 4 Ada has a pretest version but no posttest 5 FORTRAN 77 and 90 have neither 6 Perl has two pretest logical loops whi 1e and unti 1 but no posttest logical loop Copvngm 2000 Pearson AddisoneWeslev AH rgn s reserved 323 Iterative Statements 3 UserLocated Loop Control Mechanisms Design issues 1 Should the conditional be part of the exit 2 Should control be transferable out of more than one loop Coovngm 2000 Pearson AddisoneWeslev AH rgn s reserved 32 Iterative Statements 39 Examples 39 l Ada conditional or unconditional for any loop any number of levels for loop LOOPl while loop exit when LOOPZ end loop for loop exit LOOPl when end loop LOOPZ end loop LOOPl Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved 325 Iterative Statements 2 C C and Java break 0 Unconditional for any loop or switch one level only except Java s can have a label 0 There is also a continue statement for loops it skips the remainder of this iteration but does not exit the loop Copvngm 2000 Pearson AddisoneWesley AH rgn s reserved 320 Iterative Statements Iteration Based on Data Structures Concept use order and number of elements of some data structure to control iteration Control mechanism is a call to a function that returns the next element in some chosen order if there is one else exit loop C s for can be used to build a userdefined iterator e g for phdr p pnext p Coovngm 2000 Pearson AddisoneWesley AH rgn s reserved 327 Iterative Statements Perl has a builtin iterator for arrays and hashes eg foreach name names print name Coovngm 2000 Pearson AddisoneWesiey Aii rgn s reserved 328 Unconditional Branching Problem readability 0 Some languages do not have them eg Java 0 Loop eXit statements are restricted and somewhat camou aged goto s Copvngm 2000 Pearson AddisoneWesiey Aii rgn s reserved 329 Unconditional Branching Label forms 1 Unsigned int constants Pascal with colon FORTRAN no colon 2 Identi ers with colons ALGOL 60 C 3 Identi ers in ltlt gtgt Ada Coovngm 2000 Pearson AddisoneWesiey Aii rgn s reserved 330 10 Guarded Commands Dijkstra 1975 0 Purpose to support a new programming methodology veri cation during program development 0 Idea if the order of evaluation is not important the program should not specify one Copyright 2006 Pearson AddisonWesley All rgh s reserved 831 Guarded Commands 1 Selection 1 i f ltb0016angt gt ltStatementgt Evaluate all Boolean ltb0016angt gt ltstatementgt expressions ltbooleangt gt ltstatementgt f i Run time error Semantics Execute associated statement When this construct is reached Evaluate all boolean expressions If more than one are true choose Randomly choose one of one nondeterministically the true Boolean expressions If none are true it is a runtime GI39I39OI39 Copyright 2006 Pearson AddisonWesley All rgh s reserved 832 Guarded Commands 2 Loops do ltbooleangt gt ltstatementgt ltbooleangt gt ltstatementgt 1 ltbooleangt gt ltstatementgt 0d Semantics For each iteration Evaluate all boolean expressions If more than one are true choose one nondeterministically then start loop again If none are true exit loop Copyright 2006 Pearson AddisonWesley All rgh s reserved 833 ll Guarded Commands Connection between control statements and program veri cation is intimate Verification is impossible with gotos Verification is possible with only selection and logical pretest loops Verification is relatively simple with only guarded commands Copyrrgm 2000 Pearson AddisoneWesley AH rgh s reserved 33 Conclusion 0 Choice of control statements beyond selection and logical pretest loops is a tradeoff between language size and writability Copyrrgm 2000 Pearson AddisoneWesley AH rgh s reserved 335 12 Chapter 9 Subprogram Units Intxuductmn un ufSuhpmgams i a 12 6 115131 ssuesfurFuncnuns UserDe ned Overluaded Operaturs Cumutmes Introduction Two fundamental aberaeuon fae111ues 7 chess abstxaztmn 1115 chapter cuntml abstxamlun Chapters 77m 7 Dataabslxactmn Chapters 5 5 11 Process abstracuon 7 pmeeaurespmmaeusmaesnea statanems 7 Functmns pmmae usepaeenea uperaturs Fundamentals of dualFormal Parameta Correspondence 1 Fusmunal z Keywurd 7 eg 11111 501mm 1 1mm 7 Amuse 111115me 1m DefauuValues a procedure sothLIsT mum 1 mm mamas 1 1mm sothLIsT gt n Design Issues for Subprograms 1 What parameter passlng methods are provldedv 2 Are pammeler Lyp es checked7 3 Are local varlables slanc or dynamlc7 4 Can subprogam deflnmons appear ln other Subprogram deflnltlons7 5 vmallsmerefecenclng mvlronmentofa passed subprogram7 6 Can subprogams be overloaded7 Local referencing environments Iflocal varlables are stackrdynamlc 7A Van ges a sappmansnaan b singeralacalslssnneamngme sandman s canname new sensave Statlc locals areLhe opposlle Local referencing environments Language Examples F RTRAN 7 and 90 7 most are slanc but the lmplementor can choose elther User can force statlc Wlth SAVE are default 15 slack dynamlc 3 Pascal Java and Ada e dynamlc only Parameter Passing Methods 7 Sananhc models 1 mudE uutmude lnuutmude 2 ysxcally muve avalu e ane an access path pumter reference Models of Parameter Passing an Parameter Passing Methods Implementation Models 1 assebyevaue In mode 7 Extha39byphysmal muve Dr access pan e mare stung dwhcnled space Cast a an mWes1thz parameth xsluge 5 Parameter Passing Methods 2 pass7by7resull out mode 7 lacalvswll ls passedbacktn m can 7 mm m a slolylea ages Noumea am maspm macaquesmolaepmaemmybemmm mm x 7 Valvzafxmthz callzxdzpndsanmdnafasslgnmentsat thenmm 7 Addressewlunan atthzumz afca axatthz mm mm Parameter Passing Methods 3 pass7by7value7resull lnoutmode 7 Physlcal move ofvalue both ways 7 Also called passbycopy 7 IS dvantages Thuse ufpassrbyrresult Thuse afpasslsy alu Parameter Passing Methods 4 Passrbyrrefermce lnout mode 7 Pass an access pa copylng and no dupllcated storage 7 Dlsadvanlages 1 s uwa accesses Parameter Passing Methods e u c b Allows aliasing i Actual parameter collisions e procedure sue me e we subltxy xi Parameter Passing Methods Fassrbyrrefa39ence e disadvantages cunt u Array element eumsmns simian zijii If 1 j Aim sums aim in Culhsmn between funnels and gimbals Ruutcanseufallufthesexs Thecalledsubpmgzmxs pmvldedwida accesstununlucalsthamsnecessary Fassrbyrvaluerresult dues nut alluw these susses but has utha prublansi Parameter Passing Methods 5 Passebyename multiple mode 7 By textual subsumuun quhe callbutaz1ual binding tn 2 value my address takes place at me me uf areference m asslgimem e Purpuse exlbxhtyuflatebmdmg Parameter Passing Methods 5 Pass7by7name 7 Rz dnngsemmcs 1mm xsascalarwmhlz n is psshynfmme Ifac uhsanamyelzmzmxnsllkzmthngelse Placeduxe mm 111 y mm hegln smut ailii Parameter Passing Methods 5 passaymme multiplemude cuntlnued 71mm 5 an ex ssmnwnha reference in avambiz than aisa accessible mthz pmgmm mm hkz nathmg else 111 y 111 z ncir Diadvanmges nrpm by namz Very mef ent references Parameter Passing Methods Language Examples 1 FORTRAN 7 Befure77 passrbyrrefa39ence 7 777sca1 v 125 u en passed by vaiumsm 2 ALGOL so 7 passaymmets default passrbyrvaluexs upaunai 3 ALGOL w 7 Fassrbyrvaluerresult Parameter Passing Methods 7 pasebyvaiue 7 Onewaypassbyeefeeeqee vold funconst nt am nt m 5 Pascal and Modulaz 7 Default is passayvaiue pasebyeefeeeeee is epaenai 7 Like c but alsu alluwsreferencetypeparameters nt meg Parameter Passing Methods 7 All three semanae mudes are available 7 that itcannutbe referenced 7 the it cannutbe assigned meme meta m we Wequot a we t 8 Java 7 Like cw butJavahas nu pmnter unlyrefa39ences Parameter Passing Methods Type checking parameters now cmsidaed Very important for reliability 7 FORTRAN 77 and ungnal C nune r Pascal FORTRAN 9U Java and Ada ms always required 7 Ongnal c and 089 chutnexsmadeby meuse onglna c double slntxi double slntdauble xi double 2 t Parameter Passing Methods Implementing Parameter Passing r ALGOL n and must ufxts descendants use the rename stack e Fasseberalue eupytu stack references are rrrdrreeue sLaek e FassrbyrResult same as vdue e FassebyeRefErenee pumre sddressrrr the stack e FassebyeName rurrdrrreresrderc eede seguean Dr suhpmgams evaluate the address quhe eter e 1ed fur eseh reference in are furmai yerp mve Stack Implementation of ParameterPassing PMum oAri Sunk Wivwr rd Parameter Passing Methods da e Simple variables are passed by eupy vdueresuu e Ths can be apmblem because af xases eference allaws arses bumdueresd ddesrreg prdeedrre termmnnanbyermz err prddree dnffexem actual parameter results ngnm wrasrsrmee re sereneva Parameter Passing Methods Multzdxmmsmnal Arrays as Farameta39s 7 1 axiomasmianay a F552 thiubpmgmmangs t s nmisse t2 cam cam arm in kmwEiclmds fmiungrmbmidthzg t ange mappl r 11 Cand c 7 ngnmmens reqde Inclqu m dzclmdsms arau but m rsts nscnptmthz amai parameter was funimc mm nun 7 Thls dlsallnws wntmg nsxama subpmgmms 7 Samoan passa amenath amyandthz smsam dummans as at parameteran Isexmustmchldz the stung mappmg funcnan which 111 isms afthe 5m paaamsms Parameter Passing Methods Pascal ohmblzm zcbndsm as Mufti whys type Ada Cmmamaysuapsaa 7 Ummmdmzysr smasmaaa armwadaadmaaa 5 xssImIbr An Pawn FORTRAN mg 7 amaipaaamamaaciaaauaasraaaaaayscaammaapasaa pummetzxseg vnim39mxx ms eons mum mm mm ms mm mm Parameter Passing Methods 1 Ef ciency 2 Onaway m cmway a 7 Thesetvm aremcun mtwithuneanutheri V Gaad pragmrmng 7gt hmnedaccess m mahies which means me7waywhznzvex pasams Emsmsy7gt pass bererence as fastest way in pass strucmres uf sngn cmt an Alsafuncuans shm dnma awrefexencepumeuxs ad germ 3 ii se swarm a me D ma Smpztmc a m m 1 mp e m mp e a a e e ra re a 7 em a 7 plums smpztscwdy a s mu harm a nuth a me by 1 6 e n me a SmPZ ta m mpztmz h m an amp 7 a e Parameters that are Subprogram Issues Are pammetertypes checked7 7 Early Pascal and FORTRAN 77 t nut 7 Ada du es nut alluw suhpmgrzm parameters 7 Java dues nut alluwmethudnzmes a be passed as araneers 7 c and c 7 passpumterstu functmns paaneers can be type checked Parameters that are Subprogram Wham the cunectref encmg enmrarrmenm passmmes r us that afthe subpmgnmtlut enacted sum b Instlutaf qes npmgnmtlmdzchndn nah c Ins thatafthe subpmgnmtlm pssedn mum Has mxbeen sed Fur starreseapea languages deep bmdmg rs must natural Fur dynarmeseapealanguages shalluwbmdmgxs must natural Parameters that are Subprogram award 5 1 stz Effflsrmusmv snbA lsml 121 Subx 121 sm rgenwnxmlufsuthhmxhscdlAdmsub sm subA sm sub Overloaded Subprograms e same name as another Subprogram m the same refermclng edvlrorlmedt c and Ada have overloaded subprograms bullfrm and users Can erte thelr Own overloaded subprogams Generic Su bprograms Agell ll l that takes paramaers of dlffereal Lyp es on dlffermt actlvatlons Overloaded subprogamsprovlde ad hoc polymorphlsm ogmm that takes a generlc paramemer provldes paramelrlc polymorphlsm m Generic Su bprograms CH Templahed functlons e g eeneaaee nee Type mxk39l ype fun we semndY eeee u use gt gene a use eeme Generic Su bprograms meme c1255 Typo me gmeucison ype 115 me my lt me my New ye we to m e n my e we 2 we 115 Keep e 115 mum 115 nmuum e we gt g encisonulcilxsc m Separate or Independent Compi a ion Def maepenaem eempuauems eempuauen ufsume quhe umts ufapmgam separately 39nm the rest uf the meme wnhuut the bene t ufmterface Def Separate eempuauems eempuauen ufsume uf pmgrzm usmgmterfacemfurmanuntu eheek the cunecmess quhe interface betwem the m pans Language Examp es e FORTRAN u a FORTRAN 77 e maepenaem e FORTRAN an Ada cw Jame separate hex aws a Design Issues for Functions Are srde effects allowed7 e Tvmrvay parameters Ada dues nut allow 7 Nunlucal reference at anew whauypes ofretum values are allowed7 e FORTRAN Pascal r unly srmplecypes UserDe ned Overloaded Operators overloaded operators 39 User an want A and Ada Not earned over mto Java UserDe ned Overloaded Operators Example Ada assume vaemima has been array type wrur INTEGER slammts n vEcToxiT r39Pm mange Joup Mummy e atmosxn Coroutines and cuntxuls Lhamxtself Alsu calledsymmemccuntxul A eumuuue call is named aresume The rst resume ufa cumutlnelstu its begmmg but subsequent esns enter atthe punt just aha the last eeu e mam n e eumuuue Typically eeuuuuues repeatedly resume each Either pussxblyfurever ceuuuuues pmmue quasrcuncun39ent Execunun uf rugrzm umts the eumuuues hmquot V Hamquot 1 Coroutines mum hum mumt Coroutines


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Bentley McCaw University of Florida

"I was shooting for a perfect 4.0 GPA this semester. Having StudySoup as a study aid was critical to helping me achieve my goal...and I nailed it!"

Janice Dongeun University of Washington

"I used the money I made selling my notes & study guides to pay for spring break in Olympia, Washington...which was Sweet!"

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Parker Thompson 500 Startups

"It's a great way for students to improve their educational experience and it seemed like a product that everybody wants, so all the people participating are winning."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.