ref.tex 195 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426
  1. %
  2. % $Id$
  3. % This file is part of the FPC documentation.
  4. % Copyright (C) 1997, by Michael Van Canneyt
  5. %
  6. % The FPC documentation is free text; you can redistribute it and/or
  7. % modify it under the terms of the GNU Library General Public License as
  8. % published by the Free Software Foundation; either version 2 of the
  9. % License, or (at your option) any later version.
  10. %
  11. % The FPC Documentation is distributed in the hope that it will be useful,
  12. % but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. % Library General Public License for more details.
  15. %
  16. % You should have received a copy of the GNU Library General Public
  17. % License along with the FPC documentation; see the file COPYING.LIB. If not,
  18. % write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  19. % Boston, MA 02111-1307, USA.
  20. %
  21. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  22. % Preamble.
  23. \input{preamble.inc}
  24. \begin{latexonly}
  25. \ifpdf
  26. \pdfinfo{/Author(Michael Van Canneyt)
  27. /Title(Free Pascal Language Reference Guide)
  28. /Subject(Free Pascal Reference guide)
  29. /Keywords(Free Pascal, Language)
  30. }
  31. \fi
  32. \end{latexonly}
  33. %
  34. % Settings
  35. %
  36. \makeindex
  37. %
  38. % Syntax style
  39. %
  40. \usepackage{syntax}
  41. \input{syntax/diagram.tex}
  42. %
  43. % Start of document.
  44. %
  45. \begin{document}
  46. \renewcommand{\hline}{\xspace}
  47. \title{Free Pascal :\\ Reference guide.}
  48. \docdescription{Reference guide for Free Pascal, version \fpcversion}
  49. \docversion{2.0}
  50. \input{date.inc}
  51. \author{Micha\"el Van Canneyt}
  52. \maketitle
  53. \tableofcontents
  54. \newpage
  55. \listoftables
  56. \newpage
  57. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  58. % Introduction
  59. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  60. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  61. % About this guide
  62. \section*{About this guide}
  63. This document serves as the reference for the Pascal langauge as implemented
  64. by the \fpc compiler. It describes all Pascal constructs supported by
  65. \fpc, and lists all supported data types. It does not, however, give a
  66. detailed explanation of the pascal language. The aim is to list which
  67. Pascal constructs are supported, and to show where the \fpc implementation
  68. differs from the Turbo Pascal or Delphi implementations.
  69. Earlier versions of this document also contained the reference documentation
  70. of the \file{system} unit and \file{objpas} unit. This has been moved to the
  71. RTL reference guide.
  72. \subsection*{Notations}
  73. Throughout this document, we will refer to functions, types and variables
  74. with \var{typewriter} font. Functions and procedures have their own
  75. subsections, and for each function or procedure we have the following
  76. topics:
  77. \begin{description}
  78. \item [Declaration] The exact declaration of the function.
  79. \item [Description] What does the procedure exactly do ?
  80. \item [Errors] What errors can occur.
  81. \item [See Also] Cross references to other related functions/commands.
  82. \end{description}
  83. The cross-references come in two flavours:
  84. \begin{itemize}
  85. \item References to other functions in this manual. In the printed copy, a
  86. number will appear after this reference. It refers to the page where this
  87. function is explained. In the on-line help pages, this is a hyperlink,
  88. which can be clicked to jump to the declaration.
  89. \item References to Unix manual pages. (For linux and unix related things only) they
  90. are printed in \var{typewriter} font, and the number after it is the Unix
  91. manual section.
  92. \end{itemize}
  93. \subsection*{Syntax diagrams}
  94. All elements of the pascal language are explained in syntax diagrams.
  95. Syntax diagrams are like flow charts. Reading a syntax diagram means getting
  96. from the left side to the right side, following the arrows.
  97. When the right side of a syntax diagram is reached, and it ends with a single
  98. arrow, this means the syntax diagram is continued on the next line. If
  99. the line ends on 2 arrows pointing to each other, then the diagram is
  100. ended.
  101. Syntactical elements are written like this
  102. \begin{mysyntdiag}
  103. \synt{syntactical\ elements\ are\ like\ this}
  104. \end{mysyntdiag}
  105. Keywords which must be typed exactly as in the diagram:
  106. \begin{mysyntdiag}
  107. \lit*{keywords\ are\ like\ this}
  108. \end{mysyntdiag}
  109. When something can be repeated, there is an arrow around it:
  110. \begin{mysyntdiag}
  111. \begin{rep}[b] \synt{this\ can\ be\ repeated} \\ \end{rep}
  112. \end{mysyntdiag}
  113. When there are different possibilities, they are listed in columns:
  114. \begin{mysyntdiag}
  115. \begin{stack}
  116. \synt{First\ possibility} \\
  117. \synt{Second\ possibility}
  118. \end{stack}
  119. \end{mysyntdiag}
  120. Note, that one of the possibilities can be empty:
  121. \begin{mysyntdiag}
  122. \begin{stack}\\
  123. \synt{First\ possibility} \\
  124. \synt{Second\ possibility}
  125. \end{stack}
  126. \end{mysyntdiag}
  127. This means that both the first or second possibility are optional.
  128. Of course, all these elements can be combined and nested.
  129. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  130. % The Pascal language
  131. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  132. \chapter{Pascal Tokens}
  133. In this chapter we describe all the pascal reserved words, as well as the
  134. various ways to denote strings, numbers, identifiers etc.
  135. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  136. % Symbols
  137. \section{Symbols}
  138. Free Pascal allows all characters, digits and some special ASCII symbols
  139. in a Pascal source file.
  140. \input{syntax/symbol.syn}
  141. The following characters have a special meaning:
  142. \begin{verbatim}
  143. + - * / = < > [ ] . , ( ) : ^ @ { } $ #
  144. \end{verbatim}
  145. and the following character pairs too:
  146. \begin{verbatim}
  147. <= >= := += -= *= /= (* *) (. .) //
  148. \end{verbatim}
  149. When used in a range specifier, the character pair \var{(.} is equivalent to
  150. the left square bracket \var{[}. Likewise, the character pair \var{.)} is
  151. equivalent to the right square bracket \var{]}.
  152. When used for comment delimiters, the character pair \var{(*} is equivalent
  153. to the left brace \var{\{} and the character pair \var{*)} is equivalent
  154. to the right brace \var{\}}.
  155. These character pairs retain their normal meaning in string expressions.
  156. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  157. % Comments
  158. \section{Comments}
  159. \fpc supports the use of nested comments. The following constructs are valid
  160. comments:
  161. \begin{verbatim}
  162. (* This is an old style comment *)
  163. { This is a Turbo Pascal comment }
  164. // This is a Delphi comment. All is ignored till the end of the line.
  165. \end{verbatim}
  166. The following are valid ways of nesting comments:
  167. \begin{verbatim}
  168. { Comment 1 (* comment 2 *) }
  169. (* Comment 1 { comment 2 } *)
  170. { comment 1 // Comment 2 }
  171. (* comment 1 // Comment 2 *)
  172. // comment 1 (* comment 2 *)
  173. // comment 1 { comment 2 }
  174. \end{verbatim}
  175. The last two comments {\em must} be on one line. The following two will give
  176. errors:
  177. \begin{verbatim}
  178. // Valid comment { No longer valid comment !!
  179. }
  180. \end{verbatim}
  181. and
  182. \begin{verbatim}
  183. // Valid comment (* No longer valid comment !!
  184. *)
  185. \end{verbatim}
  186. The compiler will react with a 'invalid character' error when it encounters
  187. such constructs, regardless of the \var{-So} switch.
  188. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  189. % Reserved words
  190. \section{Reserved words}
  191. Reserved words are part of the Pascal language, and cannot be redefined.
  192. They will be denoted as {\sffamily\bfseries this} throughout the syntax
  193. diagrams. Reserved words can be typed regardless of case, i.e. Pascal is
  194. case insensitive.
  195. We make a distinction between Turbo Pascal and Delphi reserved words, since
  196. with the \var{-So} switch, only the Turbo Pascal reserved words are
  197. recognised, and the Delphi ones can be redefined. By default, \fpc
  198. recognises the Delphi reserved words.
  199. \subsection{Turbo Pascal reserved words}
  200. The following keywords exist in Turbo Pascal mode
  201. \begin{multicols}{4}
  202. \begin{verbatim}
  203. absolute
  204. and
  205. array
  206. asm
  207. begin
  208. break
  209. case
  210. const
  211. constructor
  212. continue
  213. destructor
  214. div
  215. do
  216. downto
  217. else
  218. end
  219. file
  220. for
  221. function
  222. goto
  223. if
  224. implementation
  225. in
  226. inherited
  227. inline
  228. interface
  229. label
  230. mod
  231. nil
  232. not
  233. object
  234. of
  235. on
  236. operator
  237. or
  238. packed
  239. procedure
  240. program
  241. record
  242. repeat
  243. self
  244. set
  245. shl
  246. shr
  247. string
  248. then
  249. to
  250. type
  251. unit
  252. until
  253. uses
  254. var
  255. while
  256. with
  257. xor
  258. \end{verbatim}
  259. \end{multicols}
  260. \subsection{Delphi reserved words}
  261. The Delphi (II) reserved words are the same as the pascal ones, plus the
  262. following ones:
  263. \begin{multicols}{4}
  264. \begin{verbatim}
  265. as
  266. class
  267. except
  268. exports
  269. finalization
  270. finally
  271. initialization
  272. is
  273. library
  274. on
  275. property
  276. raise
  277. threadvar
  278. try
  279. \end{verbatim}
  280. \end{multicols}
  281. \subsection{\fpc reserved words}
  282. On top of the Turbo Pascal and Delphi reserved words, \fpc also considers
  283. the following as reserved words:
  284. \begin{multicols}{4}
  285. \begin{verbatim}
  286. dispose
  287. exit
  288. false
  289. new
  290. true
  291. \end{verbatim}
  292. \end{multicols}
  293. \subsection{Modifiers}
  294. The following is a list of all modifiers. They are not exactly reserved
  295. words in the sense that they can be used as identifiers, but in specific
  296. places, they have a special meaning for the compiler.
  297. \begin{multicols}{4}
  298. \begin{verbatim}
  299. absolute
  300. abstract
  301. alias
  302. assembler
  303. cdecl
  304. default
  305. export
  306. external
  307. far
  308. far16
  309. forward
  310. fpccall
  311. index
  312. name
  313. near
  314. override
  315. pascal
  316. popstack
  317. private
  318. protected
  319. public
  320. published
  321. read
  322. register
  323. safecall
  324. saveregisters
  325. softfloat
  326. stdcall
  327. virtual
  328. write
  329. \end{verbatim}
  330. \end{multicols}
  331. \begin{remark}
  332. Predefined types such as \var{Byte}, \var{Boolean} and constants
  333. such as \var{maxint} are {\em not} reserved words. They are
  334. identifiers, declared in the system unit. This means that these types
  335. can be redefined in other units. The programmer is, however, not
  336. encouraged to do this, as it will cause a lot of confusion.
  337. \end{remark}
  338. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  339. % Identifiers
  340. \section{Identifiers}
  341. Identifiers denote constants, types, variables, procedures and functions,
  342. units, and programs. All names of things that are defined are identifiers.
  343. An identifier consists of 255 significant characters (letters, digits and
  344. the underscore character), from which the first must be an alphanumeric
  345. character, or an underscore (\var{\_})
  346. The following diagram gives the basic syntax for identifiers.
  347. \input{syntax/identifier.syn}
  348. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  349. % Numbers
  350. \section{Numbers}
  351. Numbers are by default denoted in decimal notation.
  352. Real (or decimal) numbers are written using engineering or scientific
  353. notation (e.g. \var{0.314E1}).
  354. For integer type constants, \fpc supports 4 formats:
  355. \begin{enumerate}
  356. \item Normal, decimal format (base 10). This is the standard format.
  357. \item Hexadecimal format (base 16), in the same way as Turbo Pascal does.
  358. To specify a constant value in hexadecimal format, prepend it with a dollar
  359. sign (\var{\$}). Thus, the hexadecimal \var{\$FF} equals 255 decimal.
  360. Note that case is insignificant when using hexadecimal constants.
  361. \item As of version 1.0.7, Octal format (base 8) is also supported.
  362. To specify a constant in octal format, prepend it with a ampersand (\&).
  363. For instance 15 is specified in octal notation as \var{\&17}.
  364. \item Binary notation (base 2). A binary number can be specified
  365. by preceding it with a percent sign (\var{\%}). Thus, \var{255} can be
  366. specified in binary notation as \var{\%11111111}.
  367. \end{enumerate}
  368. The following diagrams show the syntax for numbers.
  369. \input{syntax/numbers.syn}
  370. \begin{remark}
  371. It is to note that all decimal constants which do no fit within
  372. the -2147483648..2147483647 range, are silently and automatically
  373. parsed as 64-bit integer constants as of version 1.9.0. Earliers
  374. versions would convert it to a real-typed constant.
  375. \end{remark}
  376. \begin{remark}
  377. Note that Octal and Binary notation are not supported in TP or Delphi compatibility
  378. mode.
  379. \end{remark}
  380. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  381. % Labels
  382. \section{Labels}
  383. Labels can be digit sequences or identifiers.
  384. \input{syntax/label.syn}
  385. \begin{remark}
  386. Note that the \var{-Sg} switch must be specified before labels can be used.
  387. By default, \fpc doesn't support \var{label} and \var{goto} statements.
  388. \end{remark}
  389. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  390. % Character strings
  391. \section{Character strings}
  392. A character string (or string for short) is a sequence of zero or more
  393. characters from the ASCII character set, enclosed by single quotes, and on 1
  394. line of the program source.
  395. A character set with nothing between the quotes (\var{'{}'}) is an empty
  396. string.
  397. \input{syntax/string.syn}
  398. \chapter{Constants}
  399. Just as in Turbo Pascal, \fpc supports both normal and typed constants.
  400. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  401. % Ordinary constants
  402. \section{Ordinary constants}
  403. Ordinary constants declarations are not different from the Turbo Pascal or
  404. Delphi implementation.
  405. \input{syntax/const.syn}
  406. The compiler must be able to evaluate the expression in a constant
  407. declaration at compile time. This means that most of the functions
  408. in the Run-Time library cannot be used in a constant declaration.
  409. Operators such as \var{+, -, *, /, not, and, or, div, mod, ord, chr,
  410. sizeof, pi, int, trunc, round, frac, odd} can be used, however. For more
  411. information on expressions, see \seec{Expressions}.
  412. Only constants of the following types can be declared: \var{Ordinal types},
  413. \var{Real types}, \var{Char}, and \var{String}.
  414. The following are all valid constant declarations:
  415. \begin{verbatim}
  416. Const
  417. e = 2.7182818; { Real type constant. }
  418. a = 2; { Ordinal (Integer) type constant. }
  419. c = '4'; { Character type constant. }
  420. s = 'This is a constant string'; {String type constant.}
  421. s = chr(32)
  422. ls = SizeOf(Longint);
  423. \end{verbatim}
  424. Assigning a value to an ordinary constant is not permitted.
  425. Thus, given the previous declaration, the following will result
  426. in a compiler error:
  427. \begin{verbatim}
  428. s := 'some other string';
  429. \end{verbatim}
  430. Prior to version 1.9, \fpc did not correctly support 64-bit constants. As
  431. of version 1.9, 64-bits constants can be specified.
  432. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  433. % Typed constants
  434. \section{Typed constants}
  435. Typed constants serve to provide a program with initialised variables.
  436. Contrary to ordinary constants, they may be assigned to at run-time.
  437. The difference with normal variables is that their value is initialised
  438. when the program starts, whereas normal variables must be initialised
  439. explicitly.
  440. \input{syntax/tconst.syn}
  441. Given the declaration:
  442. \begin{verbatim}
  443. Const
  444. S : String = 'This is a typed constant string';
  445. \end{verbatim}
  446. The following is a valid assignment:
  447. \begin{verbatim}
  448. S := 'Result : '+Func;
  449. \end{verbatim}
  450. Where \var{Func} is a function that returns a \var{String}.
  451. Typed constants are often used to initialize arrays and records. For arrays,
  452. the initial elements must be specified, surrounded by round brackets, and
  453. separated by commas. The number of elements must be exactly the same as
  454. the number of elements in the declaration of the type.
  455. As an example:
  456. \begin{verbatim}
  457. Const
  458. tt : array [1..3] of string[20] = ('ikke', 'gij', 'hij');
  459. ti : array [1..3] of Longint = (1,2,3);
  460. \end{verbatim}
  461. For constant records, each element of the record should be specified, in
  462. the form \var{Field : Value}, separated by commas, and surrounded by round
  463. brackets.
  464. As an example:
  465. \begin{verbatim}
  466. Type
  467. Point = record
  468. X,Y : Real
  469. end;
  470. Const
  471. Origin : Point = (X:0.0; Y:0.0);
  472. \end{verbatim}
  473. The order of the fields in a constant record needs to be the same as in the type declaration,
  474. otherwise a compile-time error will occur.
  475. \begin{remark}
  476. It should be stressed that typed constants are initialized at program start.
  477. This is also true for {\em local} typed constants. Local typed constants are
  478. also initialized at program start. If their value was changed during previous
  479. invocations of the function, they will retain their changed value, i.e. they
  480. are not initialized each time the function is invoked.
  481. \end{remark}
  482. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  483. % resource strings
  484. \section{Resource strings}
  485. \label{se:resourcestring}
  486. A special kind of constant declaration part is the \var{Resourestring}
  487. part. This part is like a \var{Const} section, but it only allows
  488. to declare constant of type string. This part is only available in the
  489. \var{Delphi} or \var{objfpc} mode.
  490. The following is an example of a resourcestring definition:
  491. \begin{verbatim}
  492. Resourcestring
  493. FileMenu = '&File...';
  494. EditMenu = '&Edit...';
  495. \end{verbatim}
  496. All string constants defined in the resourcestring section are stored
  497. in special tables, allowing to manipulate the values of the strings
  498. at runtime with some special mechanisms.
  499. Semantically, the strings are like constants; Values can not be assigned to
  500. them, except through the special mechanisms in the objpas unit. However,
  501. they can be used in assignments or expressions as normal constants.
  502. The main use of the resourcestring section is to provide an easy means
  503. of internationalization.
  504. More on the subject of resourcestrings can be found in the \progref, and
  505. in the chapter on the \file{objpas} later in this manual.
  506. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  507. % Types
  508. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  509. \chapter{Types}
  510. All variables have a type. \fpc supports the same basic types as Turbo
  511. Pascal, with some extra types from Delphi.
  512. The programmer can declare his own types, which is in essence defining an identifier
  513. that can be used to denote this custom type when declaring variables further
  514. in the source code.
  515. \input{syntax/typedecl.syn}
  516. There are 7 major type classes :
  517. \input{syntax/type.syn}
  518. The last class, {\sffamily type identifier}, is just a means to give another
  519. name to a type. This presents a way to make types platform independent, by
  520. only using these types, and then defining these types for each platform
  521. individually. The programmer that uses these units doesn't have to worry
  522. about type size and so on. It also allows to use shortcut names for
  523. fully qualified type names. e.g. define \var{system.longint} as
  524. \var{Olongint} and then redefine \var{longint}.
  525. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  526. % Base types
  527. \section{Base types}
  528. The base or simple types of \fpc are the Delphi types.
  529. We will discuss each separate.
  530. \input{syntax/typesim.syn}
  531. \subsection{Ordinal types}
  532. With the exception of \var{int64}, \var{qword} and Real types,
  533. all base types are ordinal types. Ordinal types have the following
  534. characteristics:
  535. \begin{enumerate}
  536. \item Ordinal types are countable and ordered, i.e. it is, in principle,
  537. possible to start counting them one bye one, in a specified order.
  538. This property allows the operation of functions as \seep{Inc}, \seef{Ord},
  539. \seep{Dec}
  540. on ordinal types to be defined.
  541. \item Ordinal values have a smallest possible value. Trying to apply the
  542. \seef{Pred} function on the smallest possible value will generate a range
  543. check error if range checking is enabled.
  544. \item Ordinal values have a largest possible value. Trying to apply the
  545. \seef{Succ} function on the largest possible value will generate a range
  546. check error if range checking is enabled.
  547. \end{enumerate}
  548. \subsubsection{Integers}
  549. A list of pre-defined integer types is presented in \seet{integerstyp}
  550. %
  551. \begin{table}[ht]
  552. \caption{Predefined integer types}
  553. \label{tab:integerstyp}
  554. \begin{center}
  555. \begin{tabular}{l}
  556. %\begin{FPCltable}{l}{Predefined integer types}{integerstyp}
  557. Name\\ \hline
  558. Integer \\
  559. Shortint \\
  560. SmallInt \\
  561. Longint \\
  562. Longword \\
  563. Int64 \\
  564. Byte \\
  565. Word \\
  566. Cardinal \\
  567. QWord \\
  568. Boolean \\
  569. ByteBool \\
  570. LongBool \\
  571. Char \\ \hline
  572. \end{tabular}
  573. \end{center}
  574. \end{table}
  575. %\end{FPCltable}
  576. The integer types, and their ranges and sizes, that are predefined in
  577. \fpc are listed in \seet{integersranges}. It is to note that
  578. the \var{qword} and \var{int64} types are not true ordinals, so
  579. some pascal constructs will not work with these two integer types.
  580. \begin{FPCltable}{lcr}{Predefined integer types}{integersranges}
  581. Type & Range & Size in bytes \\ \hline
  582. Byte & 0 .. 255 & 1 \\
  583. Shortint & -128 .. 127 & 1\\
  584. Smallint & -32768 .. 32767 & 2\\
  585. Word & 0 .. 65535 & 2 \\
  586. Integer & either smallint, longint or int64 & size 2,4 or 8 \\
  587. Cardinal & either word, longword or qword & size 2,4 or 8 \\
  588. Longint & -2147483648 .. 2147483647 & 4\\
  589. Longword & 0..4294967295 & 4 \\
  590. Int64 & -9223372036854775808 .. 9223372036854775807 & 8 \\
  591. QWord & 0 .. 18446744073709551615 & 8 \\ \hline
  592. \end{FPCltable}
  593. The \var{integer} type maps to the smallint type in the default
  594. \fpc mode. It maps to either a longint or int64 in either Delphi or ObjFPC
  595. mode. The \var{cardinal} type is currently always mapped to the
  596. longword type. The definition of the \var{cardinal} and \var{integer}
  597. types may change from one architecture to another and from one
  598. compiler mode to another. They usually have the same size as the
  599. underlying target architecture.
  600. % This IS NOT TRUE, this is a 32-bit compiler, so the integer type
  601. % will always be the same independently the CPU type.
  602. %This is summarized in \seet{integer32type} for 32-bit processors
  603. %(such as Intel 80x86, Motorola 680x0, PowerPC 32-bit, SPARC v7, MIPS32), and
  604. %in \seet{integer64type} for 64-bit processors (such as Alpha AXP,
  605. %SPARC v9 or later, Intel Itanium, MIPS64).
  606. %\begin{FPCltable}{lcr}{\var{Integer} type mapping for 32-bit processors}{integer32type}
  607. %Compiler mode & Range & Size in bytes \\ \hline
  608. %<default> & -32768 .. 32767 & 2\\
  609. %tp & -32768 .. 32767 & 2\\
  610. %Delphi & -2147483648 .. 2147483647 & 4\\
  611. %ObjFPC & -2147483648 .. 2147483647 & 4\\
  612. %\end{FPCltable}
  613. %\begin{FPCltable}{lcr}{\var{Integer} type mapping for 64-bit processors}{integer64type}
  614. %Compiler mode & Range & Size in bytes \\ \hline
  615. %<default> & -32768 .. 32767 & 2\\
  616. %tp & -32768 .. 32767 & 2\\
  617. %Delphi & -9223372036854775808 .. 9223372036854775807 & 8 \\
  618. %ObjFPC & -9223372036854775808 .. 9223372036854775807 & 8 \\
  619. %\end{FPCltable}
  620. \fpc does automatic type conversion in expressions where different kinds of
  621. integer types are used.
  622. \subsubsection{Boolean types}
  623. \fpc supports the \var{Boolean} type, with its two pre-defined possible
  624. values \var{True} and \var{False}. It also supports the \var{ByteBool},
  625. \var{WordBool} and \var{LongBool} types. These are the only two values that can be
  626. assigned to a \var{Boolean} type. Of course, any expression that resolves
  627. to a \var{boolean} value, can also be assigned to a boolean type.
  628. \begin{FPCltable}{lll}{Boolean types}{booleantypes}
  629. Name & Size & Ord(True) \\ \hline
  630. Boolean & 1 & 1 \\
  631. ByteBool & 1 & Any nonzero value \\
  632. WordBool & 2 & Any nonzero value \\
  633. LongBool & 4 & Any nonzero value \\ \hline
  634. \end{FPCltable}
  635. Assuming \var{B} to be of type \var{Boolean}, the following are valid
  636. assignments:
  637. \begin{verbatim}
  638. B := True;
  639. B := False;
  640. B := 1<>2; { Results in B := True }
  641. \end{verbatim}
  642. Boolean expressions are also used in conditions.
  643. \begin{remark}
  644. In \fpc, boolean expressions are always evaluated in such a
  645. way that when the result is known, the rest of the expression will no longer
  646. be evaluated (Called short-cut evaluation). In the following example, the function \var{Func} will never
  647. be called, which may have strange side-effects.
  648. \begin{verbatim}
  649. ...
  650. B := False;
  651. A := B and Func;
  652. \end{verbatim}
  653. Here \var{Func} is a function which returns a \var{Boolean} type.
  654. \end{remark}
  655. \subsubsection{Enumeration types}
  656. Enumeration types are supported in \fpc. On top of the Turbo Pascal
  657. implementation, \fpc allows also a C-style extension of the
  658. enumeration type, where a value is assigned to a particular element of
  659. the enumeration list.
  660. \input{syntax/typeenum.syn}
  661. (see \seec{Expressions} for how to use expressions)
  662. When using assigned enumerated types, the assigned elements must be in
  663. ascending numerical order in the list, or the compiler will complain.
  664. The expressions used in assigned enumerated elements must be known at
  665. compile time.
  666. So the following is a correct enumerated type declaration:
  667. \begin{verbatim}
  668. Type
  669. Direction = ( North, East, South, West );
  670. \end{verbatim}
  671. The C style enumeration type looks as follows:
  672. \begin{verbatim}
  673. Type
  674. EnumType = (one, two, three, forty := 40,fortyone);
  675. \end{verbatim}
  676. As a result, the ordinal number of \var{forty} is \var{40}, and not \var{3},
  677. as it would be when the \var{':= 40'} wasn't present.
  678. The ordinal value of \var{fortyone} is then {41}, and not \var{4}, as it
  679. would be when the assignment wasn't present. After an assignment in an
  680. enumerated definition the compiler adds 1 to the assigned value to assign to
  681. the next enumerated value.
  682. When specifying such an enumeration type, it is important to keep in mind
  683. that the enumerated elements should be kept in ascending order. The
  684. following will produce a compiler error:
  685. \begin{verbatim}
  686. Type
  687. EnumType = (one, two, three, forty := 40, thirty := 30);
  688. \end{verbatim}
  689. It is necessary to keep \var{forty} and \var{thirty} in the correct order.
  690. When using enumeration types it is important to keep the following points
  691. in mind:
  692. \begin{enumerate}
  693. \item The \var{Pred} and \var{Succ} functions cannot be used on
  694. this kind of enumeration types. Trying to do this anyhow will result in a
  695. compiler error.
  696. \item Enumeration types stored using a default size. This behaviour can be changed
  697. with the \var{\{\$PACKENUM n\}} compiler directive, which
  698. tells the compiler the minimal number of bytes to be used for enumeration
  699. types.
  700. For instance
  701. \begin{verbatim}
  702. Type
  703. {$PACKENUM 4}
  704. LargeEnum = ( BigOne, BigTwo, BigThree );
  705. {$PACKENUM 1}
  706. SmallEnum = ( one, two, three );
  707. Var S : SmallEnum;
  708. L : LargeEnum;
  709. begin
  710. WriteLn ('Small enum : ',SizeOf(S));
  711. WriteLn ('Large enum : ',SizeOf(L));
  712. end.
  713. \end{verbatim}
  714. will, when run, print the following:
  715. \begin{verbatim}
  716. Small enum : 1
  717. Large enum : 4
  718. \end{verbatim}
  719. \end{enumerate}
  720. More information can be found in the \progref, in the compiler directives
  721. section.
  722. \subsubsection{Subrange types}
  723. A subrange type is a range of values from an ordinal type (the {\em host}
  724. type). To define a subrange type, one must specify it's limiting values: the
  725. highest and lowest value of the type.
  726. \input{syntax/typesubr.syn}
  727. Some of the predefined \var{integer} types are defined as subrange types:
  728. \begin{verbatim}
  729. Type
  730. Longint = $80000000..$7fffffff;
  731. Integer = -32768..32767;
  732. shortint = -128..127;
  733. byte = 0..255;
  734. Word = 0..65535;
  735. \end{verbatim}
  736. Subrange types of enumeration types can also be defined:
  737. \begin{verbatim}
  738. Type
  739. Days = (monday,tuesday,wednesday,thursday,friday,
  740. saturday,sunday);
  741. WorkDays = monday .. friday;
  742. WeekEnd = Saturday .. Sunday;
  743. \end{verbatim}
  744. \subsection{Real types}
  745. \fpc uses the math coprocessor (or emulation) for all its floating-point
  746. calculations. The Real native type is processor dependant,
  747. but it is either Single or Double. Only the IEEE floating point types are
  748. supported, and these depend on the target processor and emulation options.
  749. The true Turbo Pascal compatible types are listed in
  750. \seet{Reals}.
  751. \begin{FPCltable}{lccr}{Supported Real types}{Reals}
  752. Type & Range & Significant digits & Size \\ \hline
  753. Real & platform dependant & ??? & 4 or 8 \\
  754. Single & 1.5E-45 .. 3.4E38 & 7-8 & 4 \\
  755. Double & 5.0E-324 .. 1.7E308 & 15-16 & 8 \\
  756. Extended & 1.9E-4951 .. 1.1E4932 & 19-20 & 10\\
  757. Comp & -2E64+1 .. 2E63-1 & 19-20 & 8 \\
  758. \end{FPCltable}
  759. The \var{Comp} type is, in effect, a 64-bit integer and is not available
  760. on all target platforms. To get more information on the supported types
  761. for each platform, refer to the \progref.
  762. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  763. % Character types
  764. \section{Character types}
  765. \subsection{Char}
  766. \fpc supports the type \var{Char}. A \var{Char} is exactly 1 byte in
  767. size, and contains one character.
  768. A character constant can be specified by enclosing the character in single
  769. quotes, as follows : 'a' or 'A' are both character constants.
  770. A character can also be specified by its ASCII
  771. value, by preceding the ASCII value with the number symbol (\#). For example
  772. specifying \var{\#65} would be the same as \var{'A'}.
  773. Also, the caret character (\verb+^+) can be used in combination with a letter to
  774. specify a character with ASCII value less than 27. Thus \verb+^G+ equals
  775. \var{\#7} (G is the seventh letter in the alphabet.)
  776. When the single quote character must be represented, it should be typed
  777. two times successively, thus \var{''''} represents the single quote character.
  778. \subsection{Strings}
  779. \fpc supports the \var{String} type as it is defined in Turbo Pascal
  780. (A sequence of characters with a specified length) and it
  781. supports ansistrings as in Delphi.
  782. To declare a variable as a string, use the following type specification:
  783. \input{syntax/sstring.syn}
  784. The meaning of a string declaration statement is interpreted differently
  785. depending on the \var{\{\$H\}} switch. The above declaration can declare an
  786. ansistrng or a short string.
  787. Whatever the actual type, ansistrings and short strings can be used
  788. interchangeably. The compiler always takes care of the necessary type
  789. conversions. Note, however, that the result of an expression that contains
  790. ansistrings and short strings will always be an ansistring.
  791. \subsection{Short strings}
  792. A string declaration declares a short string in the following cases:
  793. \begin{enumerate}
  794. \item If the switch is off: \var{\{\$H-\}}, the string declaration
  795. will always be a short string declaration.
  796. \item If the switch is on \var{\{\$H+\}}, and there is a length
  797. specifier, the declaration is a short string declaration.
  798. \end{enumerate}
  799. The predefined type \var{ShortString} is defined as a string of length 255:
  800. \begin{verbatim}
  801. ShortString = String[255];
  802. \end{verbatim}
  803. If the size of the string is not specified, \var{255} is taken as a
  804. default. The length of the string can be obtained with the \seef{Length}
  805. standard runtime routine.
  806. For example in
  807. \begin{verbatim}
  808. {$H-}
  809. Type
  810. NameString = String[10];
  811. StreetString = String;
  812. \end{verbatim}
  813. \var{NameString} can contain a maximum of 10 characters. While
  814. \var{StreetString} can contain up to 255 characters.
  815. \subsection{Ansistrings}
  816. Ansistrings are strings that have no length limit. They are reference
  817. counted and null terminated. Internally, an ansistring is treated as
  818. a pointer. This is all handled transparantly, i.e. they can be manipulated
  819. as a normal short string. Ansistrings can be defined using the predefined
  820. \var{AnsiString} type.
  821. If the \var{\{\$H\}} switch is on, then a string definition using the
  822. regular \var{String} keyword and that doesn't contain a length specifier,
  823. will be regarded as an ansistring as well. If a length specifier is present,
  824. a short string will be used, regardless of the \var{\{\$H\}} setting.
  825. If the string is empty (\var{''}), then the internal pointer representation
  826. of the string pointer is \var{Nil}. If the string is not empty, then the
  827. pointer points to a structure in heap memory.
  828. The internal representation as a pointer, and the automatic null-termination
  829. make it possible to typecast an ansistring to a pchar. If the string is empty
  830. (so the pointer is nil) then the compiler makes sure that the typecasted
  831. pchar will point to a null byte.
  832. Assigning one ansistring to another doesn't involve moving the actual
  833. string. A statement
  834. \begin{verbatim}
  835. S2:=S1;
  836. \end{verbatim}
  837. results in the reference count of \var{S2} being decreased by one,
  838. The referece count of \var{S1} is increased by one, and finally \var{S1}
  839. (as a pointer) is copied to \var{S2}. This is a significant speed-up in
  840. the code.
  841. If the reference count reaches zero, then the memory occupied by the
  842. string is deallocated automatically, so no memory leaks arise.
  843. When an ansistring is declared, the \fpc compiler initially
  844. allocates just memory for a pointer, not more. This pointer is guaranteed
  845. to be nil, meaning that the string is initially empty. This is
  846. true for local and global ansistrings or anstrings that are part of a
  847. structure (arrays, records or objects).
  848. This does introduce an overhead. For instance, declaring
  849. \begin{verbatim}
  850. Var
  851. A : Array[1..100000] of string;
  852. \end{verbatim}
  853. Will copy 100,000 times \var{nil} into \var{A}. When \var{A} goes out of scope, then
  854. the reference count of the 100,000 strings will be decreased by 1 for each
  855. of these strings. All this happens
  856. invisibly for the programmer, but when considering performance issues,
  857. this is important.
  858. Memory will be allocated only when the string is assigned a value.
  859. If the string goes out of scope, then its reference count is automatically
  860. decreased by 1. If the reference count reaches zero, the memory reserved for
  861. the string is released.
  862. If a value is assigned to a character of a string that has a reference count
  863. greater than 1, such as in the following
  864. statements:
  865. \begin{verbatim}
  866. S:=T; { reference count for S and T is now 2 }
  867. S[I]:='@';
  868. \end{verbatim}
  869. then a copy of the string is created before the assignment. This is known
  870. as {\em copy-on-write} semantics.
  871. The \seef{Length} function must be used to get the length of an
  872. ansistring.
  873. To set the length of an ansistring, the \seep{SetLength} function must be used.
  874. Constant ansistrings have a reference count of -1 and are treated specially.
  875. Ansistrings are converted to short strings by the compiler if needed,
  876. this means that the use of ansistrings and short strings can be mixed
  877. without problems.
  878. Ansistrings can be typecasted to \var{PChar} or \var{Pointer} types:
  879. \begin{verbatim}
  880. Var P : Pointer;
  881. PC : PChar;
  882. S : AnsiString;
  883. begin
  884. S :='This is an ansistring';
  885. PC:=Pchar(S);
  886. P :=Pointer(S);
  887. \end{verbatim}
  888. There is a difference between the two typecasts. When an empty
  889. ansistring is typecasted to a pointer, the pointer wil be \var{Nil}. If an
  890. empty ansistring is typecasted to a \var{PChar}, then the result will be a pointer to a
  891. zero byte (an empty string).
  892. The result of such a typecast must be used with care. In general, it is best
  893. to consider the result of such a typecast as read-only, i.e. suitable for
  894. passing to a procedure that needs a constant pchar argument.
  895. It is therefore NOT advisable to typecast one of the following:
  896. \begin{enumerate}
  897. \item expressions.
  898. \item strings that have reference count larger than 0.
  899. (call uniquestring to ensure a string has reference count 1)
  900. \end{enumerate}
  901. \subsection{WideStrings}
  902. Widestrings (used to represent unicode character strings) are implemented in much
  903. the same way as ansistrings: reference counted, null-terminated arrays, only they
  904. are implemented as arrays of \var{WideChars} instead of regular \var{Chars}.
  905. A \var{WideChar} is a two-byte character (an element of a DBCS: Double Byte
  906. Character Set). Mostly the same rules apply for \var{WideStrings} as for
  907. \var{AnsiStrings}. The compiler transparantly converts WideStrings to
  908. AnsiStrings and vice versa.
  909. Similarly to the typecast of an Ansistring to a \var{PChar} null-terminated
  910. array of characters, a WideString can be converted to a \var{PWideChar}
  911. null-terminated array of characters.
  912. Note that the \var{PWideChar} array is terminated by 2 null bytes instead of
  913. 1, so a typecast to a pchar is not automatic.
  914. The compiler itself provides no support for any conversion from Unicode to
  915. ansistrings or vice versa; 2 procedural variables are present in the system
  916. unit which can be set to handle the conversion. For more information, see
  917. the system units reference.
  918. % Constant strings
  919. \subsection{Constant strings}
  920. To specify a constant string, it must be enclosed in single-quotes, just
  921. as a \var{Char} type, only now more than one character is allowed.
  922. Given that \var{S} is of type \var{String}, the following are valid assignments:
  923. \begin{verbatim}
  924. S := 'This is a string.';
  925. S := 'One'+', Two'+', Three';
  926. S := 'This isn''t difficult !';
  927. S := 'This is a weird character : '#145' !';
  928. \end{verbatim}
  929. As can be seen, the single quote character is represented by 2 single-quote
  930. characters next to each other. Strange characters can be specified by their
  931. ASCII value.
  932. The example shows also that two strings can be added. The resulting string is
  933. just the concatenation of the first with the second string, without spaces in
  934. between them. Strings can not be substracted, however.
  935. Whether the constant string is stored as an ansistring or a short string
  936. depends on the settings of the \var{\{\$H\}} switch.
  937. % PChar
  938. \subsection{PChar - Null terminated strings}
  939. \fpc supports the Delphi implementation of the \var{PChar} type. \var{PChar}
  940. is defined as a pointer to a \var{Char} type, but allows additional
  941. operations.
  942. The \var{PChar} type can be understood best as the Pascal equivalent of a
  943. C-style null-terminated string, i.e. a variable of type \var{PChar} is a
  944. pointer that points to an array of type \var{Char}, which is ended by a
  945. null-character (\var{\#0}).
  946. \fpc supports initializing of \var{PChar} typed constants, or a direct
  947. assignment. For example, the following pieces of code are equivalent:
  948. \begin{verbatim}
  949. program one;
  950. var p : PChar;
  951. begin
  952. P := 'This is a null-terminated string.';
  953. WriteLn (P);
  954. end.
  955. \end{verbatim}
  956. Results in the same as
  957. \begin{verbatim}
  958. program two;
  959. const P : PChar = 'This is a null-terminated string.'
  960. begin
  961. WriteLn (P);
  962. end.
  963. \end{verbatim}
  964. These examples also show that it is possible to write {\em the contents} of
  965. the string to a file of type \var{Text}.
  966. The \seestrings unit contains procedures and functions that manipulate the
  967. \var{PChar} type as in the standard C library.
  968. Since it is equivalent to a pointer to a type \var{Char} variable, it is
  969. also possible to do the following:
  970. \begin{verbatim}
  971. Program three;
  972. Var S : String[30];
  973. P : PChar;
  974. begin
  975. S := 'This is a null-terminated string.'#0;
  976. P := @S[1];
  977. WriteLn (P);
  978. end.
  979. \end{verbatim}
  980. This will have the same result as the previous two examples.
  981. Null-terminated strings cannot be added as normal Pascal
  982. strings. If two \var{PChar} strings mustt be concatenated; the functions from
  983. the unit \seestrings must be used.
  984. However, it is possible to do some pointer arithmetic. The
  985. operators \var{+} and \var{-} can be used to do operations on \var{PChar} pointers.
  986. In \seet{PCharMath}, \var{P} and \var{Q} are of type \var{PChar}, and
  987. \var{I} is of type \var{Longint}.
  988. \begin{FPCltable}{lr}{\var{PChar} pointer arithmetic}{PCharMath}
  989. Operation & Result \\ \hline
  990. \var{P + I} & Adds \var{I} to the address pointed to by \var{P}. \\
  991. \var{I + P} & Adds \var{I} to the address pointed to by \var{P}. \\
  992. \var{P - I} & Substracts \var{I} from the address pointed to by \var{P}. \\
  993. \var{P - Q} & Returns, as an integer, the distance between 2 addresses \\
  994. & (or the number of characters between \var{P} and \var{Q}) \\
  995. \hline
  996. \end{FPCltable}
  997. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  998. % Structured Types
  999. \section{Structured Types}
  1000. A structured type is a type that can hold multiple values in one variable.
  1001. Stuctured types can be nested to unlimited levels.
  1002. \input{syntax/typestru.syn}
  1003. Unlike Delphi, \fpc does not support the keyword \var{Packed} for all
  1004. structured types, as can be seen in the syntax diagram. It will be mentioned
  1005. when a type supports the \var{packed} keyword.
  1006. In the following, each of the possible structured types is discussed.
  1007. \subsection{Arrays}
  1008. \fpc supports arrays as in Turbo Pascal, multi-dimensional arrays
  1009. and packed arrays are also supported, as well as the dynamic arrays of
  1010. Delphi:
  1011. \input{syntax/typearr.syn}
  1012. \subsubsection{Static arrays}
  1013. When the range of the array is included in the array definition, it is
  1014. called a static array. Trying to access an element with an index that is
  1015. outside the declared range will generate a run-time error (if range checking
  1016. is on). The following is an example of a valid array declaration:
  1017. \begin{verbatim}
  1018. Type
  1019. RealArray = Array [1..100] of Real;
  1020. \end{verbatim}
  1021. Valid indexes for accessing an element of the array are between 1 and 100,
  1022. where the borders 1 and 100 are included.
  1023. As in Turbo Pascal, if the array component type is in itself an array, it is
  1024. possible to combine the two arrays into one multi-dimensional array. The
  1025. following declaration:
  1026. \begin{verbatim}
  1027. Type
  1028. APoints = array[1..100] of Array[1..3] of Real;
  1029. \end{verbatim}
  1030. is equivalent to the following declaration:
  1031. \begin{verbatim}
  1032. Type
  1033. APoints = array[1..100,1..3] of Real;
  1034. \end{verbatim}
  1035. The functions \seef{High} and \seef{Low} return the high and low bounds of
  1036. the leftmost index type of the array. In the above case, this would be 100
  1037. and 1.
  1038. When static array-type variables are assigned to each other, the contents of the
  1039. whole array is copied. This is also true for multi-dimensional arrays:
  1040. \begin{verbatim}
  1041. program testarray1;
  1042. Type
  1043. TA = Array[0..9,0..9] of Integer;
  1044. var
  1045. A,B : TA;
  1046. I,J : Integer;
  1047. begin
  1048. For I:=0 to 9 do
  1049. For J:=0 to 9 do
  1050. A[I,J]:=I*J;
  1051. For I:=0 to 9 do
  1052. begin
  1053. For J:=0 to 9 do
  1054. Write(A[I,J]:2,' ');
  1055. Writeln;
  1056. end;
  1057. B:=A;
  1058. Writeln;
  1059. For I:=0 to 9 do
  1060. For J:=0 to 9 do
  1061. A[9-I,9-J]:=I*J;
  1062. For I:=0 to 9 do
  1063. begin
  1064. For J:=0 to 9 do
  1065. Write(B[I,J]:2,' ');
  1066. Writeln;
  1067. end;
  1068. end.
  1069. \end{verbatim}
  1070. The output will be 2 identical matrices.
  1071. \subsubsection{Dynamic arrays}
  1072. As of version 1.1, \fpc also knows dynamic arrays: In that case, the array
  1073. range is omitted, as in the following example:
  1074. \begin{verbatim}
  1075. Type
  1076. TByteArray : Array of Byte;
  1077. \end{verbatim}
  1078. When declaring a variable of a dynamic array type, the initial length of the
  1079. array is zero. The actual length of the array must be set with the standard
  1080. \var{SetLength} function, which will allocate the memory to contain the
  1081. array elements on the heap. The following example will set the length to
  1082. 1000:
  1083. \begin{verbatim}
  1084. Var
  1085. A : TByteArray;
  1086. begin
  1087. SetLength(A,1000);
  1088. \end{verbatim}
  1089. After a call to \var{SetLength}, valid array indexes are 0 to 999: the array
  1090. index is always zero-based.
  1091. Note that the length of the array is set in elements, not in bytes of
  1092. allocated memory (although these may be the same). The amount of
  1093. memory allocated is the size of the array multiplied by the size of
  1094. 1 element in the array. The memory will be disposed of at the exit of the
  1095. current procedure or function.
  1096. It is also possible to resize the array: in that case, as much of the
  1097. elements in the array as will fit in the new size, will be kept. The array
  1098. can be resized to zero, which effectively resets the variable.
  1099. At all times, trying to access an element of the array that is not in the
  1100. current length of the array will generate a run-time error.
  1101. Assignment of one dynamic array-type variable to another will let both
  1102. variables point to the same array. Contrary to ansistrings, an
  1103. assignment to an element of one array will be reflected in the
  1104. other:
  1105. \begin{verbatim}
  1106. Var
  1107. A,B : TByteArray;
  1108. begin
  1109. SetLength(A,10);
  1110. A[1]:=33;
  1111. B:=A;
  1112. A[1]:=31;
  1113. \end{verbatim}
  1114. After the second assignment, the first element in B will also contain 31.
  1115. It can also be seen from the output of the following example:
  1116. \begin{verbatim}
  1117. program testarray1;
  1118. Type
  1119. TA = Array of array of Integer;
  1120. var
  1121. A,B : TA;
  1122. I,J : Integer;
  1123. begin
  1124. Setlength(A,10,10);
  1125. For I:=0 to 9 do
  1126. For J:=0 to 9 do
  1127. A[I,J]:=I*J;
  1128. For I:=0 to 9 do
  1129. begin
  1130. For J:=0 to 9 do
  1131. Write(A[I,J]:2,' ');
  1132. Writeln;
  1133. end;
  1134. B:=A;
  1135. Writeln;
  1136. For I:=0 to 9 do
  1137. For J:=0 to 9 do
  1138. A[9-I,9-J]:=I*J;
  1139. For I:=0 to 9 do
  1140. begin
  1141. For J:=0 to 9 do
  1142. Write(B[I,J]:2,' ');
  1143. Writeln;
  1144. end;
  1145. end.
  1146. \end{verbatim}
  1147. The output will be a matrix of numbers, and then the same matrix, mirrorred.
  1148. Dynamic arrays are reference counted: if in one of the previous examples A
  1149. goes out of scope and B does not, then the array is not yet disposed of: the
  1150. reference count of A (and B) is decreased with 1. As soon as the reference
  1151. count reaches zero, the memory is disposed of.
  1152. It is also possible to copy and/or resize the array with the standard
  1153. \var{Copy} function, which acts as the copy function for strings:
  1154. \begin{verbatim}
  1155. program testarray3;
  1156. Type
  1157. TA = array of Integer;
  1158. var
  1159. A,B : TA;
  1160. I : Integer;
  1161. begin
  1162. Setlength(A,10);
  1163. For I:=0 to 9 do
  1164. A[I]:=I;
  1165. B:=Copy(A,3,9);
  1166. For I:=0 to 5 do
  1167. Writeln(B[I]);
  1168. end.
  1169. \end{verbatim}
  1170. The \var{Copy} function will copy 9 elements of the array to a new array.
  1171. Starting at the element at index 3 (i.e. the fourth element) of the array.
  1172. The \var{Low} function on a dynamic array will always return 0, and the
  1173. High function will return the value \var{Length-1}, i.e., the value of the
  1174. highest allowed array index. The \var{Length} function will return the
  1175. number of elements in the array.
  1176. \subsection{Record types}
  1177. \fpc supports fixed records and records with variant parts.
  1178. The syntax diagram for a record type is
  1179. \input{syntax/typerec.syn}
  1180. So the following are valid record types declarations:
  1181. \begin{verbatim}
  1182. Type
  1183. Point = Record
  1184. X,Y,Z : Real;
  1185. end;
  1186. RPoint = Record
  1187. Case Boolean of
  1188. False : (X,Y,Z : Real);
  1189. True : (R,theta,phi : Real);
  1190. end;
  1191. BetterRPoint = Record
  1192. Case UsePolar : Boolean of
  1193. False : (X,Y,Z : Real);
  1194. True : (R,theta,phi : Real);
  1195. end;
  1196. \end{verbatim}
  1197. The variant part must be last in the record. The optional identifier in the
  1198. case statement serves to access the tag field value, which otherwise would
  1199. be invisible to the programmer. It can be used to see which variant is
  1200. active at a certain time. In effect, it introduces a new field in the
  1201. record.
  1202. \begin{remark}
  1203. It is possible to nest variant parts, as in:
  1204. \begin{verbatim}
  1205. Type
  1206. MyRec = Record
  1207. X : Longint;
  1208. Case byte of
  1209. 2 : (Y : Longint;
  1210. case byte of
  1211. 3 : (Z : Longint);
  1212. );
  1213. end;
  1214. \end{verbatim}
  1215. \end{remark}
  1216. The size of a record is the sum of the sizes of its fields, each size of a
  1217. field is rounded up to a power of two. If the record contains a variant part, the size
  1218. of the variant part is the size of the biggest variant, plus the size of the
  1219. tag field type {\em if an identifier was declared for it}. Here also, the size of
  1220. each part is first rounded up to two. So in the above example,
  1221. \seef{SizeOf} would return 24 for \var{Point}, 24 for \var{RPoint} and
  1222. 26 for \var{BetterRPoint}. For \var{MyRec}, the value would be 12.
  1223. If a typed file with records, produced by a Turbo Pascal program, must be read,
  1224. then chances are that attempting to read that file correctly will fail.
  1225. The reason for this is that by default, elements of a record are aligned at
  1226. 2-byte boundaries, for performance reasons. This default behaviour can be
  1227. changed with the \var{\{\$PackRecords n\}} switch. Possible values for
  1228. \var{n} are 1, 2, 4, 16 or \var{Default}.
  1229. This switch tells the compiler to align elements of a record or object or
  1230. class that have size larger than \var{n} on \var{n} byte boundaries.
  1231. Elements that have size smaller or equal than \var{n} are aligned on
  1232. natural boundaries, i.e. to the first power of two that is larger than or
  1233. equal to the size of the record element.
  1234. The keyword \var{Default} selects the default value for the platform
  1235. that the code is compiled for (currently, this is 2 on all platforms)
  1236. Take a look at the following program:
  1237. \begin{verbatim}
  1238. Program PackRecordsDemo;
  1239. type
  1240. {$PackRecords 2}
  1241. Trec1 = Record
  1242. A : byte;
  1243. B : Word;
  1244. end;
  1245. {$PackRecords 1}
  1246. Trec2 = Record
  1247. A : Byte;
  1248. B : Word;
  1249. end;
  1250. {$PackRecords 2}
  1251. Trec3 = Record
  1252. A,B : byte;
  1253. end;
  1254. {$PackRecords 1}
  1255. Trec4 = Record
  1256. A,B : Byte;
  1257. end;
  1258. {$PackRecords 4}
  1259. Trec5 = Record
  1260. A : Byte;
  1261. B : Array[1..3] of byte;
  1262. C : byte;
  1263. end;
  1264. {$PackRecords 8}
  1265. Trec6 = Record
  1266. A : Byte;
  1267. B : Array[1..3] of byte;
  1268. C : byte;
  1269. end;
  1270. {$PackRecords 4}
  1271. Trec7 = Record
  1272. A : Byte;
  1273. B : Array[1..7] of byte;
  1274. C : byte;
  1275. end;
  1276. {$PackRecords 8}
  1277. Trec8 = Record
  1278. A : Byte;
  1279. B : Array[1..7] of byte;
  1280. C : byte;
  1281. end;
  1282. Var rec1 : Trec1;
  1283. rec2 : Trec2;
  1284. rec3 : TRec3;
  1285. rec4 : TRec4;
  1286. rec5 : Trec5;
  1287. rec6 : TRec6;
  1288. rec7 : TRec7;
  1289. rec8 : TRec8;
  1290. begin
  1291. Write ('Size Trec1 : ',SizeOf(Trec1));
  1292. Writeln (' Offset B : ',Longint(@rec1.B)-Longint(@rec1));
  1293. Write ('Size Trec2 : ',SizeOf(Trec2));
  1294. Writeln (' Offset B : ',Longint(@rec2.B)-Longint(@rec2));
  1295. Write ('Size Trec3 : ',SizeOf(Trec3));
  1296. Writeln (' Offset B : ',Longint(@rec3.B)-Longint(@rec3));
  1297. Write ('Size Trec4 : ',SizeOf(Trec4));
  1298. Writeln (' Offset B : ',Longint(@rec4.B)-Longint(@rec4));
  1299. Write ('Size Trec5 : ',SizeOf(Trec5));
  1300. Writeln (' Offset B : ',Longint(@rec5.B)-Longint(@rec5),
  1301. ' Offset C : ',Longint(@rec5.C)-Longint(@rec5));
  1302. Write ('Size Trec6 : ',SizeOf(Trec6));
  1303. Writeln (' Offset B : ',Longint(@rec6.B)-Longint(@rec6),
  1304. ' Offset C : ',Longint(@rec6.C)-Longint(@rec6));
  1305. Write ('Size Trec7 : ',SizeOf(Trec7));
  1306. Writeln (' Offset B : ',Longint(@rec7.B)-Longint(@rec7),
  1307. ' Offset C : ',Longint(@rec7.C)-Longint(@rec7));
  1308. Write ('Size Trec8 : ',SizeOf(Trec8));
  1309. Writeln (' Offset B : ',Longint(@rec8.B)-Longint(@rec8),
  1310. ' Offset C : ',Longint(@rec8.C)-Longint(@rec8));
  1311. end.
  1312. \end{verbatim}
  1313. The output of this program will be :
  1314. \begin{verbatim}
  1315. Size Trec1 : 4 Offset B : 2
  1316. Size Trec2 : 3 Offset B : 1
  1317. Size Trec3 : 2 Offset B : 1
  1318. Size Trec4 : 2 Offset B : 1
  1319. Size Trec5 : 8 Offset B : 4 Offset C : 7
  1320. Size Trec6 : 8 Offset B : 4 Offset C : 7
  1321. Size Trec7 : 12 Offset B : 4 Offset C : 11
  1322. Size Trec8 : 16 Offset B : 8 Offset C : 15
  1323. \end{verbatim}
  1324. And this is as expected. In \var{Trec1}, since \var{B} has size 2, it is
  1325. aligned on a 2 byte boundary, thus leaving an empty byte between \var{A}
  1326. and \var{B}, and making the total size 4. In \var{Trec2}, \var{B} is aligned
  1327. on a 1-byte boundary, right after \var{A}, hence, the total size of the
  1328. record is 3.
  1329. For \var{Trec3}, the sizes of \var{A,B} are 1, and hence they are aligned on 1
  1330. byte boundaries. The same is true for \var{Trec4}.
  1331. For \var{Trec5}, since the size of B -- 3 -- is smaller than 4, \var{B} will
  1332. be on a 4-byte boundary, as this is the first power of two that is
  1333. larger than it's size. The same holds for \var{Trec6}.
  1334. For \var{Trec7}, \var{B} is aligned on a 4 byte boundary, since it's size --
  1335. 7 -- is larger than 4. However, in \var{Trec8}, it is aligned on a 8-byte
  1336. boundary, since 8 is the first power of two that is greater than 7, thus
  1337. making the total size of the record 16.
  1338. \fpc supports also the 'packed record', this is a record where all the
  1339. elements are byte-aligned.
  1340. Thus the two following declarations are equivalent:
  1341. \begin{verbatim}
  1342. {$PackRecords 1}
  1343. Trec2 = Record
  1344. A : Byte;
  1345. B : Word;
  1346. end;
  1347. {$PackRecords 2}
  1348. \end{verbatim}
  1349. and
  1350. \begin{verbatim}
  1351. Trec2 = Packed Record
  1352. A : Byte;
  1353. B : Word;
  1354. end;
  1355. \end{verbatim}
  1356. Note the \var{\{\$PackRecords 2\}} after the first declaration !
  1357. \subsection{Set types}
  1358. \fpc supports the set types as in Turbo Pascal. The prototype of a set
  1359. declaration is:
  1360. \input{syntax/typeset.syn}
  1361. Each of the elements of \var{SetType} must be of type \var{TargetType}.
  1362. \var{TargetType} can be any ordinal type with a range between \var{0} and
  1363. \var{255}. A set can contain maximally \var{255} elements.
  1364. The following are valid set declaration:
  1365. \begin{verbatim}
  1366. Type
  1367. Junk = Set of Char;
  1368. Days = (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
  1369. WorkDays : Set of days;
  1370. \end{verbatim}
  1371. Given this set declarations, the following assignment is legal:
  1372. \begin{verbatim}
  1373. WorkDays := [ Mon, Tue, Wed, Thu, Fri];
  1374. \end{verbatim}
  1375. The operators and functions for manipulations of sets are listed in
  1376. \seet{SetOps}.
  1377. \begin{FPCltable}{lr}{Set Manipulation operators}{SetOps}
  1378. Operation & Operator \\ \hline
  1379. Union & + \\
  1380. Difference & - \\
  1381. Intersection & * \\
  1382. Add element & \var{include} \\
  1383. Delete element & \var{exclude} \\ \hline
  1384. \end{FPCltable}
  1385. Two sets can be compared with the \var{<>} and \var{=} operators, but not
  1386. (yet) with the \var{<} and \var{>} operators.
  1387. The compiler stores small sets (less than 32 elements) in a Longint, if the
  1388. type range allows it. This allows for faster processing and decreases
  1389. program size. Otherwise, sets are stored in 32 bytes.
  1390. \subsection{File types}
  1391. File types are types that store a sequence of some base type, which can be
  1392. any type except another file type. It can contain (in principle) an infinite
  1393. number of elements.
  1394. File types are used commonly to store data on disk. Nothing prevents the programmer,
  1395. however, from writing a file driver that stores it's data in memory.
  1396. Here is the type declaration for a file type:
  1397. \input{syntax/typefil.syn}
  1398. If no type identifier is given, then the file is an untyped file; it can be
  1399. considered as equivalent to a file of bytes. Untyped files require special
  1400. commands to act on them (see \seep{Blockread}, \seep{Blockwrite}).
  1401. The following declaration declares a file of records:
  1402. \begin{verbatim}
  1403. Type
  1404. Point = Record
  1405. X,Y,Z : real;
  1406. end;
  1407. PointFile = File of Point;
  1408. \end{verbatim}
  1409. Internally, files are represented by the \var{FileRec} record, which is
  1410. declared in the DOS unit.
  1411. A special file type is the \var{Text} file type, represented by the
  1412. \var{TextRec} record. A file of type \var{Text} uses special input-output
  1413. routines.
  1414. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1415. % Pointers
  1416. \section{Pointers}
  1417. \fpc supports the use of pointers. A variable of the pointer type
  1418. contains an address in memory, where the data of another variable may be
  1419. stored.
  1420. \input{syntax/typepoin.syn}
  1421. As can be seen from this diagram, pointers are typed, which means that
  1422. they point to a particular kind of data. The type of this data must be
  1423. known at compile time.
  1424. Dereferencing the pointer (denoted by adding \var{\^{}} after the variable
  1425. name) behaves then like a variable. This variable has the type declared in
  1426. the pointer declaration, and the variable is stored in the address that is
  1427. pointed to by the pointer variable.
  1428. Consider the following example:
  1429. \begin{verbatim}
  1430. Program pointers;
  1431. type
  1432. Buffer = String[255];
  1433. BufPtr = ^Buffer;
  1434. Var B : Buffer;
  1435. BP : BufPtr;
  1436. PP : Pointer;
  1437. etc..
  1438. \end{verbatim}
  1439. In this example, \var{BP} {\em is a pointer to} a \var{Buffer} type; while \var{B}
  1440. {\em is} a variable of type \var{Buffer}. \var{B} takes 256 bytes memory,
  1441. and \var{BP} only takes 4 bytes of memory (enough to keep an adress in
  1442. memory).
  1443. \begin{remark} \fpc treats pointers much the same way as C does. This means
  1444. that a pointer to some type can be treated as being an array of this type.
  1445. The pointer then points to the zeroeth element of this array. Thus the
  1446. following pointer declaration
  1447. \begin{verbatim}
  1448. Var p : ^Longint;
  1449. \end{verbatim}
  1450. Can be considered equivalent to the following array declaration:
  1451. \begin{verbatim}
  1452. Var p : array[0..Infinity] of Longint;
  1453. \end{verbatim}
  1454. The difference is that the former declaration allocates memory for the
  1455. pointer only (not for the array), and the second declaration allocates
  1456. memory for the entire array. If the former is used, the memory must be
  1457. allocated manually, using the \seep{Getmem} function.
  1458. The reference \var{P\^{}} is then the same as \var{p[0]}. The following program
  1459. illustrates this maybe more clear:
  1460. \begin{verbatim}
  1461. program PointerArray;
  1462. var i : Longint;
  1463. p : ^Longint;
  1464. pp : array[0..100] of Longint;
  1465. begin
  1466. for i := 0 to 100 do pp[i] := i; { Fill array }
  1467. p := @pp[0]; { Let p point to pp }
  1468. for i := 0 to 100 do
  1469. if p[i]<>pp[i] then
  1470. WriteLn ('Ohoh, problem !')
  1471. end.
  1472. \end{verbatim}
  1473. \end{remark}
  1474. \fpc supports pointer arithmetic as C does. This means that, if \var{P} is a
  1475. typed pointer, the instructions
  1476. \begin{verbatim}
  1477. Inc(P);
  1478. Dec(P);
  1479. \end{verbatim}
  1480. Will increase, respectively decrease the address the pointer points to
  1481. with the size of the type \var{P} is a pointer to. For example
  1482. \begin{verbatim}
  1483. Var P : ^Longint;
  1484. ...
  1485. Inc (p);
  1486. \end{verbatim}
  1487. will increase \var{P} with 4.
  1488. Normal arithmetic operators on pointers can also be used, that is, the
  1489. following are valid pointer arithmetic operations:
  1490. \begin{verbatim}
  1491. var p1,p2 : ^Longint;
  1492. L : Longint;
  1493. begin
  1494. P1 := @P2;
  1495. P2 := @L;
  1496. L := P1-P2;
  1497. P1 := P1-4;
  1498. P2 := P2+4;
  1499. end.
  1500. \end{verbatim}
  1501. Here, the value that is added or substracted {\em is } multiplied by the
  1502. size of the type the pointer points to. In the previous
  1503. example \var{P1} will be decremented by 16 bytes, and
  1504. \var{P2} will be incremented by 16.
  1505. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1506. % Forward type declarations
  1507. \section{Forward type declarations}
  1508. Programs often need to maintain a linked list of records. Each record then
  1509. contains a pointer to the next record (and possibly to the previous record
  1510. as well). For type safety, it is best to define this pointer as a typed
  1511. pointer, so the next record can be allocated on the heap using the \var{New}
  1512. call. In order to do so, the record should be defined something like this:
  1513. \begin{verbatim}
  1514. Type
  1515. TListItem = Record
  1516. Data : Integer;
  1517. Next : ^TListItem;
  1518. end;
  1519. \end{verbatim}
  1520. When trying to compile this, the compiler will complain that the
  1521. \var{TListItem} type is not yet defined when it encounters the \var{Next}
  1522. declaration: This is correct, as the definition is still being parsed.
  1523. To be able to have the \var{Next} element as a typed pointer, a 'Forward
  1524. type declaration' must be introduced:
  1525. \begin{verbatim}
  1526. Type
  1527. PListItem = ^TListItem;
  1528. TListItem = Record
  1529. Data : Integer;
  1530. Next : PTListItem;
  1531. end;
  1532. \end{verbatim}
  1533. When the compiler encounters a typed pointer declaration where the
  1534. referenced type is not yet known, it postpones resolving the reference later
  1535. on: The pointer definition is a 'Forward type declaration'. The referenced
  1536. type should be introduced later in the same \var{Type} block. No other block
  1537. may come between the definition of the pointer type and the referenced type.
  1538. Indeed, even the word \var{Type} itself may not re-appear: in effect it
  1539. would start a new type-block, causing the compiler to resolve all pending
  1540. declarations in the current block. In most cases, the definition of the
  1541. referenced type will follow immediatly after the definition of the pointer
  1542. type, as shown in the above listing. The forward defined type can be used in
  1543. any type definition following its declaration.
  1544. Note that a forward type declaration is only possible with pointer types and
  1545. classes, not with other types.
  1546. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1547. % Procedural types
  1548. \section{Procedural types}
  1549. \fpc has support for procedural types, although it differs a little from
  1550. the Turbo Pascal implementation of them. The type declaration remains the
  1551. same, as can be seen in the following syntax diagram:
  1552. \input{syntax/typeproc.syn}
  1553. For a description of formal parameter lists, see \seec{Procedures}.
  1554. The two following examples are valid type declarations:
  1555. \begin{verbatim}
  1556. Type TOneArg = Procedure (Var X : integer);
  1557. TNoArg = Function : Real;
  1558. var proc : TOneArg;
  1559. func : TNoArg;
  1560. \end{verbatim}
  1561. One can assign the following values to a procedural type variable:
  1562. \begin{enumerate}
  1563. \item \var{Nil}, for both normal procedure pointers and method pointers.
  1564. \item A variable reference of a procedural type, i.e. another variable of
  1565. the same type.
  1566. \item A global procedure or function address, with matching function or
  1567. procedure header and calling convention.
  1568. \item A method address.
  1569. \end{enumerate}
  1570. Given these declarations, the following assignments are valid:
  1571. \begin{verbatim}
  1572. Procedure printit (Var X : Integer);
  1573. begin
  1574. WriteLn (x);
  1575. end;
  1576. ...
  1577. Proc := @printit;
  1578. Func := @Pi;
  1579. \end{verbatim}
  1580. From this example, the difference with Turbo Pascal is clear: In Turbo
  1581. Pascal it isn't necessary to use the address operator (\var{@})
  1582. when assigning a procedural type variable, whereas in \fpc it is required
  1583. (unless the \var{-So} switch is used, in which case the address
  1584. operator can be dropped.)
  1585. \begin{remark} The modifiers concerning the calling conventions
  1586. must be the same as the declaration;
  1587. i.e. the following code would give an error:
  1588. \begin{verbatim}
  1589. Type TOneArgCcall = Procedure (Var X : integer);cdecl;
  1590. var proc : TOneArgCcall;
  1591. Procedure printit (Var X : Integer);
  1592. begin
  1593. WriteLn (x);
  1594. end;
  1595. begin
  1596. Proc := @printit;
  1597. end.
  1598. \end{verbatim}
  1599. Because the \var{TOneArgCcall} type is a procedure that uses the cdecl
  1600. calling convention.
  1601. \end{remark}
  1602. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1603. % Variant types
  1604. \section{Variant types}
  1605. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1606. % Definition
  1607. \subsection{Definition}
  1608. As of version 1.1, FPC has support for variants. For variant support to be
  1609. enabled, the \file{variants} unit must be included in every unit that uses
  1610. variants in some way. Furthermore, the compiler must be in \var{Delphi} or
  1611. \var{ObjFPC} mode.
  1612. The type of a value stored in a variant is only determined at runtime:
  1613. it depends what has been assigned to the to the variant. Almost any type
  1614. can be assigned to variants: ordinal types, string types, int64 types.
  1615. Structured types such as sets, records, arrays, files, objects and classes
  1616. are not assign-compatible with a variant, as well as pointers. Interfaces
  1617. and COM or CORBA objects can be assigned to a variant.
  1618. This means that the following assignments are valid:
  1619. \begin{verbatim}
  1620. Type
  1621. TMyEnum = (One,Two,Three);
  1622. Var
  1623. V : Variant;
  1624. I : Integer;
  1625. B : Byte;
  1626. W : Word;
  1627. Q : Int64;
  1628. E : Extended;
  1629. D : Double;
  1630. En : TMyEnum;
  1631. AS : AnsiString;
  1632. WS : WideString;
  1633. begin
  1634. V:=I;
  1635. V:=B;
  1636. V:=W;
  1637. V:=Q;
  1638. V:=E;
  1639. V:=En;
  1640. V:=D:
  1641. V:=AS;
  1642. V:=WS;
  1643. end;
  1644. \end{verbatim}
  1645. And of course vice-versa as well.
  1646. \begin{remark}
  1647. The enumerated type assignment is broken in the early 1.1 development series of the
  1648. compiler. It is expected that this is fixed soon.
  1649. \end{remark}
  1650. A variant can hold an an array of values: All elements in the array have the
  1651. same type (but can be of type 'variant'). For a variant that contains an
  1652. array, the variant can be indexed:
  1653. \begin{verbatim}
  1654. Program testv;
  1655. uses variants;
  1656. Var
  1657. A : Variant;
  1658. I : integer;
  1659. begin
  1660. A:=VarArrayCreate([1,10],varInteger);
  1661. For I:=1 to 10 do
  1662. A[I]:=I;
  1663. end.
  1664. \end{verbatim}
  1665. (for the explanation of \var{VarArrayCreate}, see \unitsref.)
  1666. Note that when the array contains a string, this is not considered an 'array
  1667. of characters', and so the variant cannot be indexed to retrieve a character
  1668. at a certain position in the string.
  1669. \begin{remark}
  1670. The array functionality is broken in the early 1.1 development series of the
  1671. compiler. It is expected that this is fixed soon.
  1672. \end{remark}
  1673. \subsection{Variants in assignments and expressions}
  1674. As can be seen from the definition above, most simple types can be assigned
  1675. to a variant. Likewise, a variant can be assigned to a simple type: If
  1676. possible, the value of the variant will be converted to the type that is
  1677. being assigned to. This may fail: Assigning a variant containing a string
  1678. to an integer will fail unless the string represents a valid integer. In the
  1679. following example, the first assignment will work, the second will fail:
  1680. \begin{verbatim}
  1681. program testv3;
  1682. uses Variants;
  1683. Var
  1684. V : Variant;
  1685. I : Integer;
  1686. begin
  1687. V:='100';
  1688. I:=V;
  1689. Writeln('I : ',I);
  1690. V:='Something else';
  1691. I:=V;
  1692. Writeln('I : ',I);
  1693. end.
  1694. \end{verbatim}
  1695. The first assignment will work, but the second will not, as \var{Something else}
  1696. cannot be converted to a valid integer value. An \var{EConvertError} exception
  1697. will be the result.
  1698. The result of an expression involving a variant will be of type variant again,
  1699. but this can be assigned to a variable of a different type - if the result
  1700. can be converted to a variable of this type.
  1701. Note that expressions involving variants take more time to be evaluated, and
  1702. should therefore be used with caution. If a lot of calculations need to be
  1703. made, it is best to avoid the use of variants.
  1704. When considering implicit type conversions (e.g. byte to integer, integer to
  1705. double, char to string) the compiler will ignore variants unless a variant
  1706. appears explicitly in the expression.
  1707. \subsection{Variants and interfaces}
  1708. \begin{remark}
  1709. Dispatch interface support for variants is currently broken in the compiler.
  1710. \end{remark}
  1711. Variants can contain a reference to an interface - a normal interface
  1712. (descending from \var{IInterface}) or a dispatchinterface (descending
  1713. from \var{IDispatch}). Variants containing a reference to a dispatch
  1714. interface can be used to control the object behind it: the compiler will use
  1715. late binding to perform the call to the dispatch interface: there will be no
  1716. run-time checking of the function names and parameters or arguments given to
  1717. the functions. The result type is also not checked. The compiler will simply
  1718. insert code to make the dispatch call and retrieve the result.
  1719. This means basically, that you can do the following on Windows:
  1720. \begin{verbatim}
  1721. Var
  1722. W : Variant;
  1723. V : String;
  1724. begin
  1725. W:=CreateOleObject('Word.Application');
  1726. V:=W.Application.Version;
  1727. Writeln('Installed version of MS Word is : ',V);
  1728. end;
  1729. \end{verbatim}
  1730. The line
  1731. \begin{verbatim}
  1732. V:=W.Application.Version;
  1733. \end{verbatim}
  1734. is executed by inserting the necessary code to query the dispatch interface
  1735. stored in the variant \var{W}, and execute the call if the needed dispatch
  1736. information is found.
  1737. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1738. % Variables
  1739. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1740. \chapter{Variables}
  1741. \label{ch:Variables}
  1742. \section{Definition}
  1743. Variables are explicitly named memory locations with a certain type. When
  1744. assigning values to variables, the \fpc compiler generates machine code
  1745. to move the value to the memory location reserved for this variable. Where
  1746. this variable is stored depends on where it is declared:
  1747. \begin{itemize}
  1748. \item Global variables are variables declared in a unit or program, but not
  1749. inside a procedure or function. They are stored in fixed memory locations,
  1750. and are available during the whole execution time of the program.
  1751. \item Local variables are declared inside a procedure or function. Their
  1752. value is stored on the program stack, i.e. not at fixed locations.
  1753. \end{itemize}
  1754. The \fpc compiler handles the allocation of these memory locations
  1755. transparantly, although this location can be influenced in the declaration.
  1756. The \fpc compiler also handles reading values from or writing values to
  1757. the variables transparantly. But even this can be explicitly handled by the
  1758. programmer when using properties.
  1759. Variables must be explicitly declared when they are needed. No memory is
  1760. allocated unless a variable is declared. Using an variable identifier (for
  1761. instance, a loop variable) which is not declared first, is an error which
  1762. will be reported by the compiler.
  1763. \section{Declaration}
  1764. The variables must be declared in a variable declaration section of a unit
  1765. or a procedure or function. It looks as follows:
  1766. \input{syntax/vardecl.syn}
  1767. This means that the following are valid variable declarations:
  1768. \begin{verbatim}
  1769. Var
  1770. curterm1 : integer;
  1771. curterm2 : integer; cvar;
  1772. curterm3 : integer; cvar; external;
  1773. curterm4 : integer; external name 'curterm3';
  1774. curterm5 : integer; external 'libc' name 'curterm9';
  1775. curterm6 : integer absolute curterm1;
  1776. curterm7 : integer; cvar; export;
  1777. curterm8 : integer; cvar; public;
  1778. curterm9 : integer; export name 'me';
  1779. curterm10 : integer; public name 'ma';
  1780. curterm11 : integer = 1 ;
  1781. \end{verbatim}
  1782. The difference between these declarations is as follows:
  1783. \begin{enumerate}
  1784. \item The first form (\var{curterm1}) defines a regular variable. The
  1785. compiler manages everything by itself.
  1786. \item The second form (\var{curterm2}) declares also a regular variable,
  1787. but specifies that the assembler name for this variable equals the name
  1788. of the variable as written in the source.
  1789. \item The third form (\var{curterm3}) declares a variable which is located
  1790. externally: the compiler will assume memory is located elsewhere, and that
  1791. the assembler name of this location is specified by the name of the
  1792. variable, as written in the source. The name may not be specified.
  1793. \item The fourth form is completely equivalent to the third, it declares a
  1794. variable which is stored externally, and explicitly gives the assembler
  1795. name of the location. If \var{cvar} is not used, the name must be specified.
  1796. \item The fifth form is a variant of the fourth form, only the name of the
  1797. library in which the memory is reserved is specified as well.
  1798. \item The sixth form declares a variable (\var{curterm6}), and tells the compiler that it is
  1799. stored in the same location as another variable (\var{curterm1})
  1800. \item The seventh form declares a variable (\var{curterm7}), and tells the
  1801. compiler that the assembler label of this variable should be the name of the
  1802. variable (case sensitive) and must be made public. (i.e. it can be
  1803. referenced from other object files)
  1804. \item The eight form (\var{curterm8}) is equivalent to the seventh: 'public'
  1805. is an alias for 'export'.
  1806. \item The ninth and tenth form are equivalent: they specify the assembler
  1807. name of the variable.
  1808. \item the elevents form declares a variable (\var{curterm11}) and
  1809. initializes it with a value (1 in the above case).
  1810. \end{enumerate}
  1811. Note that assembler names must be unique. It's not possible to declare or
  1812. export 2 variables with the same assembler name.
  1813. \section{Scope}
  1814. Variables, just as any identifier, obey the general rules of scope.
  1815. In addition, initialized variables are initialized when they enter scope:
  1816. \begin{itemize}
  1817. \item Global initialized variables are initialized once, when the program starts.
  1818. \item Local initialized variables are initialized each time the procedure is
  1819. entered.
  1820. \end{itemize}
  1821. Note that the behaviour for local initialized variables is different from
  1822. the one of a local typed constant. A local typed constant behaves like a
  1823. global initialized variable.
  1824. \section{Thread Variables}
  1825. For a program which uses threads, the variables can be really global, i.e. the same for all
  1826. threads, or thread-local: this means that each thread gets a copy of the variable.
  1827. Local variables (defined inside a procedure) are always thread-local. Global
  1828. variables are normally the same for all threads. A global variable can be
  1829. declared thread-local by replacing the \var{var} keyword at the start of the
  1830. variable declaration block with \var{Threadvar}:
  1831. \begin{verbatim}
  1832. Threadvar
  1833. IOResult : Integer;
  1834. \end{verbatim}
  1835. If no threads are used, the variable behaves as an ordinary variable.
  1836. If threads are used then a copy is made
  1837. for each thread (including the main thread). Note that the copy is
  1838. made with the original value of the variable, {\em not} with the
  1839. value of the variable at the time the thread is started.
  1840. Threadvars should be used sparingly: There is an overhead for retrieving
  1841. or setting the variable's value. If possible at all, consider using local
  1842. variables; they are always faster than thread variables.
  1843. Threads are not enabled by default. For more information about programming
  1844. threads, see the chapter on threads in the \progref.
  1845. \section{Properties}
  1846. A global block can declare properties, just as they could be defined in a
  1847. class. The difference is that the global property does not need a class
  1848. instance: there is only 1 instance of this property. Other than that, a
  1849. global property behaves like a class property. The read/write specifiers for
  1850. the global property must also be regular procedures, not methods.
  1851. The concept of a global property is specific to \fpc, and does not exist in
  1852. Delphi.
  1853. The concept of a global property can be used to 'hide' the location of the
  1854. value, or to calculate the value on the fly, or to check the values which
  1855. are written to the property.
  1856. The declaration is as follows:
  1857. \input{syntax/propvar.syn}
  1858. The following is an example:
  1859. \begin{verbatim}
  1860. {$mode objfpc}
  1861. unit testprop;
  1862. Interface
  1863. Function GetMyInt : Integer;
  1864. Procedure SetMyInt(Value : Integer);
  1865. Property
  1866. MyProp : Integer Read GetMyInt Write SetMyInt;
  1867. Implementation
  1868. Uses sysutils;
  1869. Var
  1870. FMyInt : Integer;
  1871. Function GetMyInt : Integer;
  1872. begin
  1873. Result:=FMyInt;
  1874. end;
  1875. Procedure SetMyInt(Value : Integer);
  1876. begin
  1877. If ((Value mod 2)=1) then
  1878. Raise Exception.Create('MyProp can only contain even value');
  1879. FMyInt:=Value;
  1880. end;
  1881. end.
  1882. \end{verbatim}
  1883. The read/write specifiers can be hidden by declaring them in another unit
  1884. which must be in the \var{uses} clause of the unit. This can be used to hide
  1885. the read/write access specifiers for programmers, just as if they were in a
  1886. \var{private} section of a class (discussed below). For the previous
  1887. example, this could look as follows:
  1888. \begin{verbatim}
  1889. {$mode objfpc}
  1890. unit testrw;
  1891. Interface
  1892. Function GetMyInt : Integer;
  1893. Procedure SetMyInt(Value : Integer);
  1894. Implementation
  1895. Uses sysutils;
  1896. Var
  1897. FMyInt : Integer;
  1898. Function GetMyInt : Integer;
  1899. begin
  1900. Result:=FMyInt;
  1901. end;
  1902. Procedure SetMyInt(Value : Integer);
  1903. begin
  1904. If ((Value mod 2)=1) then
  1905. Raise Exception.Create('Only even values are allowed');
  1906. FMyInt:=Value;
  1907. end;
  1908. end.
  1909. \end{verbatim}
  1910. The unit \file{testprop} would then look like:
  1911. \begin{verbatim}
  1912. {$mode objfpc}
  1913. unit testprop;
  1914. Interface
  1915. uses testrw;
  1916. Property
  1917. MyProp : Integer Read GetMyInt Write SetMyInt;
  1918. Implementation
  1919. end.
  1920. \end{verbatim}
  1921. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1922. % Objects
  1923. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1924. \chapter{Objects}
  1925. \label{ch:Objects}
  1926. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1927. % Declaration
  1928. \section{Declaration}
  1929. \fpc supports object oriented programming. In fact, most of the compiler is
  1930. written using objects. Here we present some technical questions regarding
  1931. object oriented programming in \fpc.
  1932. Objects should be treated as a special kind of record. The record contains
  1933. all the fields that are declared in the objects definition, and pointers
  1934. to the methods that are associated to the objects' type.
  1935. An object is declared just as a record would be declared; except that
  1936. now,procedures and functions can be declared as if they were part of the record.
  1937. Objects can ''inherit'' fields and methods from ''parent'' objects. This means
  1938. that these fields and methods can be used as if they were included in the
  1939. objects declared as a ''child'' object.
  1940. Furthermore, a concept of visibility is introduced: fields, procedures and functions
  1941. can be delcared as \var{public} or \var{private}. By default, fields and
  1942. methods are \var{public}, and are
  1943. exported outside the current unit. Fields or methods that are declared
  1944. \var{private} are only accessible in the current unit.
  1945. The prototype declaration of an object is as follows:
  1946. \input{syntax/typeobj.syn}
  1947. As can be seen, as many \var{private} and \var{public} blocks as needed can be
  1948. declared.
  1949. \var{Method definitions} are normal function or procedure declarations.
  1950. Fields cannot be declared after methods in the same block, i.e. the following
  1951. will generate an error when compiling:
  1952. \begin{verbatim}
  1953. Type MyObj = Object
  1954. Procedure Doit;
  1955. Field : Longint;
  1956. end;
  1957. \end{verbatim}
  1958. But the following will be accepted:
  1959. \begin{verbatim}
  1960. Type MyObj = Object
  1961. Public
  1962. Procedure Doit;
  1963. Private
  1964. Field : Longint;
  1965. end;
  1966. \end{verbatim}
  1967. because the field is in a different section.
  1968. \begin{remark}
  1969. \fpc also supports the packed object. This is the same as an object, only
  1970. the elements (fields) of the object are byte-aligned, just as in the packed
  1971. record.
  1972. The declaration of a packed object is similar to the declaration
  1973. of a packed record :
  1974. \begin{verbatim}
  1975. Type
  1976. TObj = packed object;
  1977. Constructor init;
  1978. ...
  1979. end;
  1980. Pobj = ^TObj;
  1981. Var PP : Pobj;
  1982. \end{verbatim}
  1983. Similarly, the \var{\{\$PackRecords \}} directive acts on objects as well.
  1984. \end{remark}
  1985. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1986. % Fields
  1987. \section{Fields}
  1988. Object Fields are like record fields. They are accessed in the same way as
  1989. a record field would be accessed : by using a qualified identifier. Given the
  1990. following declaration:
  1991. \begin{verbatim}
  1992. Type TAnObject = Object
  1993. AField : Longint;
  1994. Procedure AMethod;
  1995. end;
  1996. Var AnObject : TAnObject;
  1997. \end{verbatim}
  1998. then the following would be a valid assignment:
  1999. \begin{verbatim}
  2000. AnObject.AField := 0;
  2001. \end{verbatim}
  2002. Inside methods, fields can be accessed using the short identifier:
  2003. \begin{verbatim}
  2004. Procedure TAnObject.AMethod;
  2005. begin
  2006. ...
  2007. AField := 0;
  2008. ...
  2009. end;
  2010. \end{verbatim}
  2011. Or, one can use the \var{self} identifier. The \var{self} identifier refers
  2012. to the current instance of the object:
  2013. \begin{verbatim}
  2014. Procedure TAnObject.AMethod;
  2015. begin
  2016. ...
  2017. Self.AField := 0;
  2018. ...
  2019. end;
  2020. \end{verbatim}
  2021. One cannot access fields that are in a private section of an object from
  2022. outside the objects' methods. If this is attempted anyway, the compiler will complain about
  2023. an unknown identifier.
  2024. It is also possible to use the \var{with} statement with an object instance:
  2025. \begin{verbatim}
  2026. With AnObject do
  2027. begin
  2028. Afield := 12;
  2029. AMethod;
  2030. end;
  2031. \end{verbatim}
  2032. In this example, between the \var{begin} and \var{end}, it is as if
  2033. \var{AnObject} was prepended to the \var{Afield} and \var{Amethod}
  2034. identifiers. More about this in \sees{With}
  2035. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2036. % Constructors and destructors
  2037. \section{Constructors and destructors }
  2038. \label{se:constructdestruct}
  2039. As can be seen in the syntax diagram for an object declaration, \fpc supports
  2040. constructors and destructors. The programmer is responsible for calling the
  2041. constructor and the destructor explicitly when using objects.
  2042. The declaration of a constructor or destructor is as follows:
  2043. \input{syntax/construct.syn}
  2044. A constructor/destructor pair is {\em required} if the object uses virtual methods.
  2045. In the declaration of the object type, a simple identifier should be used
  2046. for the name of the constuctor or destructor. When the constructor or destructor
  2047. is implemented, A qualified method identifier should be used,
  2048. i.e. an identifier of the form \var{objectidentifier.methodidentifier}.
  2049. \fpc supports also the extended syntax of the \var{New} and \var{Dispose}
  2050. procedures. In case a dynamic variable of an object type must be allocated
  2051. the constructor's name can be specified in the call to \var{New}.
  2052. The \var{New} is implemented as a function which returns a pointer to the
  2053. instantiated object. Consider the following declarations:
  2054. \begin{verbatim}
  2055. Type
  2056. TObj = object;
  2057. Constructor init;
  2058. ...
  2059. end;
  2060. Pobj = ^TObj;
  2061. Var PP : Pobj;
  2062. \end{verbatim}
  2063. Then the following 3 calls are equivalent:
  2064. \begin{verbatim}
  2065. pp := new (Pobj,Init);
  2066. \end{verbatim}
  2067. and
  2068. \begin{verbatim}
  2069. new(pp,init);
  2070. \end{verbatim}
  2071. and also
  2072. \begin{verbatim}
  2073. new (pp);
  2074. pp^.init;
  2075. \end{verbatim}
  2076. In the last case, the compiler will issue a warning that the
  2077. extended syntax of \var{new} and \var{dispose} must be used to generate instances of an
  2078. object. It is possible to ignore this warning, but it's better programming practice to
  2079. use the extended syntax to create instances of an object.
  2080. Similarly, the \var{Dispose} procedure accepts the name of a destructor. The
  2081. destructor will then be called, before removing the object from the heap.
  2082. In view of the compiler warning remark, the following chapter presents the
  2083. Delphi approach to object-oriented programming, and may be considered a
  2084. more natural way of object-oriented programming.
  2085. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2086. % Methods
  2087. \section{Methods}
  2088. Object methods are just like ordinary procedures or functions, only they
  2089. have an implicit extra parameter : \var{self}. Self points to the object
  2090. with which the method was invoked.
  2091. When implementing methods, the fully qualified identifier must be given
  2092. in the function header. When declaring methods, a normal identifier must be
  2093. given.
  2094. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2095. % Method invocation
  2096. \section{Method invocation}
  2097. Methods are called just as normal procedures are called, only they have an
  2098. object instance identifier prepended to them (see also \seec{Statements}).
  2099. To determine which method is called, it is necessary to know the type of
  2100. the method. We treat the different types in what follows.
  2101. \subsubsection{Static methods}
  2102. Static methods are methods that have been declared without a \var{abstract}
  2103. or \var{virtual} keyword. When calling a static method, the declared (i.e.
  2104. compile time) method of the object is used.
  2105. For example, consider the following declarations:
  2106. \begin{verbatim}
  2107. Type
  2108. TParent = Object
  2109. ...
  2110. procedure Doit;
  2111. ...
  2112. end;
  2113. PParent = ^TParent;
  2114. TChild = Object(TParent)
  2115. ...
  2116. procedure Doit;
  2117. ...
  2118. end;
  2119. PChild = ^TChild;
  2120. \end{verbatim}
  2121. As it is visible, both the parent and child objects have a method called
  2122. \var{Doit}. Consider now the following declarations and calls:
  2123. \begin{verbatim}
  2124. Var ParentA,ParentB : PParent;
  2125. Child : PChild;
  2126. ParentA := New(PParent,Init);
  2127. ParentB := New(PChild,Init);
  2128. Child := New(PChild,Init);
  2129. ParentA^.Doit;
  2130. ParentB^.Doit;
  2131. Child^.Doit;
  2132. \end{verbatim}
  2133. Of the three invocations of \var{Doit}, only the last one will call
  2134. \var{TChild.Doit}, the other two calls will call \var{TParent.Doit}.
  2135. This is because for static methods, the compiler determines at compile
  2136. time which method should be called. Since \var{ParentB} is of type
  2137. \var{TParent}, the compiler decides that it must be called with
  2138. \var{TParent.Doit}, even though it will be created as a \var{TChild}.
  2139. There may be times when the method that is actually called should
  2140. depend on the actual type of the object at run-time. If so, the method
  2141. cannot be a static method, but must be a virtual method.
  2142. \subsubsection{Virtual methods}
  2143. To remedy the situation in the previous section, \var{virtual} methods are
  2144. created. This is simply done by appending the method declaration with the
  2145. \var{virtual} modifier.
  2146. Going back to the previous example, consider the following alternative
  2147. declaration:
  2148. \begin{verbatim}
  2149. Type
  2150. TParent = Object
  2151. ...
  2152. procedure Doit;virtual;
  2153. ...
  2154. end;
  2155. PParent = ^TParent;
  2156. TChild = Object(TParent)
  2157. ...
  2158. procedure Doit;virtual;
  2159. ...
  2160. end;
  2161. PChild = ^TChild;
  2162. \end{verbatim}
  2163. As it is visible, both the parent and child objects have a method called
  2164. \var{Doit}. Consider now the following declarations and calls :
  2165. \begin{verbatim}
  2166. Var ParentA,ParentB : PParent;
  2167. Child : PChild;
  2168. ParentA := New(PParent,Init);
  2169. ParentB := New(PChild,Init);
  2170. Child := New(PChild,Init);
  2171. ParentA^.Doit;
  2172. ParentB^.Doit;
  2173. Child^.Doit;
  2174. \end{verbatim}
  2175. Now, different methods will be called, depending on the actual run-time type
  2176. of the object. For \var{ParentA}, nothing changes, since it is created as
  2177. a \var{TParent} instance. For \var{Child}, the situation also doesn't
  2178. change: it is again created as an instance of \var{TChild}.
  2179. For \var{ParentB} however, the situation does change: Even though it was
  2180. declared as a \var{TParent}, it is created as an instance of \var{TChild}.
  2181. Now, when the program runs, before calling \var{Doit}, the program
  2182. checks what the actual type of \var{ParentB} is, and only then decides which
  2183. method must be called. Seeing that \var{ParentB} is of type \var{TChild},
  2184. \var{TChild.Doit} will be called.
  2185. The code for this run-time checking of the actual type of an object is
  2186. inserted by the compiler at compile time.
  2187. The \var{TChild.Doit} is said to {\em override} the \var{TParent.Doit}.
  2188. It is possible to acces the \var{TParent.Doit} from within the
  2189. var{TChild.Doit}, with the \var{inherited} keyword:
  2190. \begin{verbatim}
  2191. Procedure TChild.Doit;
  2192. begin
  2193. inherited Doit;
  2194. ...
  2195. end;
  2196. \end{verbatim}
  2197. In the above example, when \var{TChild.Doit} is called, the first thing it
  2198. does is call \var{TParent.Doit}. The inherited keyword cannot be used in
  2199. static methods, only on virtual methods.
  2200. \subsubsection{Abstract methods}
  2201. An abstract method is a special kind of virtual method. A method can not be
  2202. abstract if it is not virtual (this is not obvious from the syntax diagram).
  2203. An instance of an object that has an abstract method cannot be created directly.
  2204. The reason is obvious: there is no method where the compiler could jump to !
  2205. A method that is declared \var{abstract} does not have an implementation for
  2206. this method. It is up to inherited objects to override and implement this
  2207. method. Continuing our example, take a look at this:
  2208. \begin{verbatim}
  2209. Type
  2210. TParent = Object
  2211. ...
  2212. procedure Doit;virtual;abstract;
  2213. ...
  2214. end;
  2215. PParent=^TParent;
  2216. TChild = Object(TParent)
  2217. ...
  2218. procedure Doit;virtual;
  2219. ...
  2220. end;
  2221. PChild = ^TChild;
  2222. \end{verbatim}
  2223. As it is visible, both the parent and child objects have a method called
  2224. \var{Doit}. Consider now the following declarations and calls :
  2225. \begin{verbatim}
  2226. Var ParentA,ParentB : PParent;
  2227. Child : PChild;
  2228. ParentA := New(PParent,Init);
  2229. ParentB := New(PChild,Init);
  2230. Child := New(PChild,Init);
  2231. ParentA^.Doit;
  2232. ParentB^.Doit;
  2233. Child^.Doit;
  2234. \end{verbatim}
  2235. First of all, Line 3 will generate a compiler error, stating that one cannot
  2236. generate instances of objects with abstract methods: The compiler has
  2237. detected that \var{PParent} points to an object which has an abstract
  2238. method. Commenting line 3 would allow compilation of the program.
  2239. \begin{remark}
  2240. If an abstract method is overridden, The parent method cannot be called
  2241. with \var{inherited}, since there is no parent method; The compiler
  2242. will detect this, and complain about it, like this:
  2243. \begin{verbatim}
  2244. testo.pp(32,3) Error: Abstract methods can't be called directly
  2245. \end{verbatim}
  2246. If, through some mechanism, an abstract method is called at run-time,
  2247. then a run-time error will occur. (run-time error 211, to be precise)
  2248. \end{remark}
  2249. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2250. % Visibility
  2251. \section{Visibility}
  2252. For objects, 3 visibility specifiers exist : \var{private}, \var{protected} and
  2253. \var{public}. If a visibility specifier is not specified, \var{public}
  2254. is assumed.
  2255. Both methods and fields can be hidden from a programmer by putting them
  2256. in a \var{private} section. The exact visibility rule is as follows:
  2257. \begin{description}
  2258. \item [Private\ ] All fields and methods that are in a \var{private} block,
  2259. can only be accessed in the module (i.e. unit or program) that contains
  2260. the object definition.
  2261. They can be accessed from inside the object's methods or from outside them
  2262. e.g. from other objects' methods, or global functions.
  2263. \item [Protected\ ] Is the same as \var{Private}, except that the members of
  2264. a \var{Protected} section are also accessible to descendent types, even if
  2265. they are implemented in other modules.
  2266. \item [Public\ ] sections are always accessible, from everywhere.
  2267. Fields and metods in a \var{public} section behave as though they were part
  2268. of an ordinary \var{record} type.
  2269. \end{description}
  2270. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2271. % Classes
  2272. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2273. \chapter{Classes}
  2274. \label{ch:Classes}
  2275. In the Delphi approach to Object Oriented Programming, everything revolves
  2276. around the concept of 'Classes'. A class can be seen as a pointer to an
  2277. object, or a pointer to a record.
  2278. \begin{remark}
  2279. In earlier versions of \fpc it was necessary, in order to use classes,
  2280. to put the \file{objpas} unit in the uses clause of a unit or program.
  2281. {\em This is no longer needed} as of version 0.99.12. As of version 0.99.12
  2282. the \file{system} unit contains the basic definitions of \var{TObject}
  2283. and \var{TClass}, as well as some auxiliary methods for using classes.
  2284. The \file{objpas} unit still exists, and contains some redefinitions of
  2285. basic types, so they coincide with Delphi types. The unit will be loaded
  2286. automatically when the \var{-S2} or \var{-Sd} options are specified.
  2287. \end{remark}
  2288. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2289. % Class definitions
  2290. \section{Class definitions}
  2291. The prototype declaration of a class is as follows :
  2292. \input{syntax/typeclas.syn}
  2293. As many \var{private}, \var{protected}, \var{published}
  2294. and \var{public} blocks as needed can be repeated.
  2295. Methods are normal function or procedure declarations.
  2296. As can be seen, the declaration of a class is almost identical to the
  2297. declaration of an object. The real difference between objects and classes
  2298. is in the way they are created (see further in this chapter).
  2299. The visibility of the different sections is as follows:
  2300. \begin{description}
  2301. \item [Private\ ] All fields and methods that are in a \var{private} block, can
  2302. only be accessed in the module (i.e. unit) that contains the class definition.
  2303. They can be accessed from inside the classes' methods or from outside them
  2304. (e.g. from other classes' methods)
  2305. \item [Protected\ ] Is the same as \var{Private}, except that the members of
  2306. a \var{Protected} section are also accessible to descendent types, even if
  2307. they are implemented in other modules.
  2308. \item [Public\ ] sections are always accessible.
  2309. \item [Published\ ] Is the same as a \var{Public} section, but the compiler
  2310. generates also type information that is needed for automatic streaming of
  2311. these classes. Fields defined in a \var{published} section must be of class type.
  2312. Array peroperties cannot be in a \var{published} section.
  2313. \end{description}
  2314. It is also possible to define class reference types:
  2315. \input{syntax/classref.syn}
  2316. Class reference types are used to create instances of a certain class, which
  2317. is not yet known at compile time, but which is specified at run time.
  2318. Essentially, a variable of a class reference type contains a pointer to the
  2319. VMT of the speficied class. This can be used to construct an instance of the
  2320. class corresponding to the VMT. The following example shows how it works:
  2321. \begin{verbatim}
  2322. Type
  2323. TComponentClass = Class of TComponent;
  2324. Function CreateComponent(AClass : TComponentClass; AOwner : TComponent) : TComponent;
  2325. begin
  2326. // ...
  2327. Result:=AClass.Create(AOwner);
  2328. // ...
  2329. end;
  2330. \end{verbatim}
  2331. More about instantiating a class can be found in the next section.
  2332. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2333. % Class instantiation
  2334. \section{Class instantiation}
  2335. Classes must be created using their constructor. Remember that a class is a
  2336. pointer to an object, so when a variable of some class is declared, the
  2337. compiler just allocates a pointer, not the entire object. The constructor of
  2338. a class returns a pointer to an initialized instance of the object.
  2339. So, to initialize an instance of some class, one would do the following :
  2340. \begin{verbatim}
  2341. ClassVar := ClassType.ConstructorName;
  2342. \end{verbatim}
  2343. The extended syntax of \var{new} and \var{dispose} can be used to
  2344. instantiate and destroy class instances.
  2345. That construct is reserved for use with objects only.
  2346. Calling the constructor will provoke a call to \var{getmem}, to allocate
  2347. enough space to hold the class instance data.
  2348. After that, the constuctor's code is executed.
  2349. The constructor has a pointer to it's data, in \var{self}.
  2350. \begin{remark}
  2351. \begin{itemize}
  2352. \item The \var{\{\$PackRecords \}} directive also affects classes.
  2353. i.e. the alignment in memory of the different fields depends on the
  2354. value of the \var{\{\$PackRecords \}} directive.
  2355. \item Just as for objects and records, a packed class can be declared.
  2356. This has the same effect as on an object, or record, namely that the
  2357. elements are aligned on 1-byte boundaries. i.e. as close as possible.
  2358. \item \var{SizeOf(class)} will return 4, since a class is but a pointer to
  2359. an object. To get the size of the class instance data, use the
  2360. \var{TObject.InstanceSize} method.
  2361. \end{itemize}
  2362. \end{remark}
  2363. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2364. % Methods
  2365. \section{Methods}
  2366. \subsection{invocation}
  2367. Method invocation for classes is no different than for objects. The
  2368. following is a valid method invocation:
  2369. \begin{verbatim}
  2370. Var AnObject : TAnObject;
  2371. begin
  2372. AnObject := TAnObject.Create;
  2373. ANobject.AMethod;
  2374. \end{verbatim}
  2375. \subsection{Virtual methods}
  2376. Classes have virtual methods, just as objects do. There is however a
  2377. difference between the two. For objects, it is sufficient to redeclare the
  2378. same method in a descendent object with the keyword \var{virtual} to
  2379. override it. For classes, the situation is different:
  2380. virtual methods {\em must} be overridden with the \var{override} keyword. Failing to do so,
  2381. will start a {\em new} batch of virtual methods, hiding the previous
  2382. one. The \var{Inherited} keyword will not jump to the inherited method, if
  2383. virtual was used.
  2384. The following code is {\em wrong}:
  2385. \begin{verbatim}
  2386. Type
  2387. ObjParent = Class
  2388. Procedure MyProc; virtual;
  2389. end;
  2390. ObjChild = Class(ObjPArent)
  2391. Procedure MyProc; virtual;
  2392. end;
  2393. \end{verbatim}
  2394. The compiler will produce a warning:
  2395. \begin{verbatim}
  2396. Warning: An inherited method is hidden by OBJCHILD.MYPROC
  2397. \end{verbatim}
  2398. The compiler will compile it, but using \var{Inherited} can
  2399. produce strange effects.
  2400. The correct declaration is as follows:
  2401. \begin{verbatim}
  2402. Type ObjParent = Class
  2403. Procedure MyProc; virtual;
  2404. end;
  2405. ObjChild = Class(ObjPArent)
  2406. Procedure MyProc; override;
  2407. end;
  2408. \end{verbatim}
  2409. This will compile and run without warnings or errors.
  2410. \subsection{Class methods}
  2411. Class methods are methods that do not have an instance, but which follow
  2412. the scoping and inheritance rules of a class. They can be called from inside
  2413. a regular method, but can also be called using a class identifier:
  2414. \begin{verbatim}
  2415. Var
  2416. AClass : TClass;
  2417. begin
  2418. ..
  2419. if CompareText(AClass.ClassName,'TCOMPONENT')=0 then
  2420. ...
  2421. \end{verbatim}
  2422. But calling them from an instance is also possible:
  2423. \begin{verbatim}
  2424. Var
  2425. MyClass : TObject;
  2426. begin
  2427. ..
  2428. if MyClass.ClassNameis('TCOMPONENT') then
  2429. ...
  2430. \end{verbatim}
  2431. Inside a class method, the <var>self</var> identifier points to the VMT
  2432. table of the class. No fields, properties or regular methods are available
  2433. inside a class method. Accessing a regular property or method will result in
  2434. a compiler error. The reverse is possible: a class method can be called from
  2435. a regular method.
  2436. Note that class methods can be virtual, and can be overridden.
  2437. Class methods cannot be used as read or write specifiers for a property.
  2438. \subsection{Message methods}
  2439. New in classes are \var{message} methods. Pointers to message methods are
  2440. stored in a special table, together with the integer or string cnstant that
  2441. they were declared with. They are primarily intended to ease programming of
  2442. callback functions in several \var{GUI} toolkits, such as \var{Win32} or
  2443. \var{GTK}. In difference with Delphi, \fpc also accepts strings as message
  2444. identifiers.
  2445. Message methods that are declared with an integer constant can take only one
  2446. var argument (typed or not):
  2447. \begin{verbatim}
  2448. Procedure TMyObject.MyHandler(Var Msg); Message 1;
  2449. \end{verbatim}
  2450. The method implementation of a message function is no different from an
  2451. ordinary method. It is also possible to call a message method directly,
  2452. but this should not be done. Instead, the \var{TObject.Dispatch} method
  2453. should be used.
  2454. The \var{TOBject.Dispatch} method can be used to call a \var{message}
  2455. handler. It is declared in the \file{system} unit and will accept a var
  2456. parameter which must have at the first position a cardinal with the
  2457. message ID that should be called. For example:
  2458. \begin{verbatim}
  2459. Type
  2460. TMsg = Record
  2461. MSGID : Cardinal
  2462. Data : Pointer;
  2463. Var
  2464. Msg : TMSg;
  2465. MyObject.Dispatch (Msg);
  2466. \end{verbatim}
  2467. In this example, the \var{Dispatch} method will look at the object and all
  2468. it's ancestors (starting at the object, and searching up the class tree),
  2469. to see if a message method with message \var{MSGID} has been
  2470. declared. If such a method is found, it is called, and passed the
  2471. \var{Msg} parameter.
  2472. If no such method is found, \var{DefaultHandler} is called.
  2473. \var{DefaultHandler} is a virtual method of \var{TObject} that doesn't do
  2474. anything, but which can be overridden to provide any processing that might be
  2475. needed. \var{DefaultHandler} is declared as follows:
  2476. \begin{verbatim}
  2477. procedure defaulthandler(var message);virtual;
  2478. \end{verbatim}
  2479. In addition to the message method with a \var{Integer} identifier,
  2480. \fpc also supports a message method with a string identifier:
  2481. \begin{verbatim}
  2482. Procedure TMyObject.MyStrHandler(Var Msg); Message 'OnClick';
  2483. \end{verbatim}
  2484. The working of the string message handler is the same as the ordinary
  2485. integer message handler:
  2486. The \var{TOBject.DispatchStr} method can be used to call a \var{message}
  2487. handler. It is declared in the system unit and will accept one parameter
  2488. which must have at the first position a string with the message ID that
  2489. should be called. For example:
  2490. \begin{verbatim}
  2491. Type
  2492. TMsg = Record
  2493. MsgStr : String[10]; // Arbitrary length up to 255 characters.
  2494. Data : Pointer;
  2495. Var
  2496. Msg : TMSg;
  2497. MyObject.DispatchStr (Msg);
  2498. \end{verbatim}
  2499. In this example, the \var{DispatchStr} method will look at the object and
  2500. all it's ancestors (starting at the object, and searching up the class tree),
  2501. to see if a message method with message \var{MsgStr} has been
  2502. declared. If such a method is found, it is called, and passed the
  2503. \var{Msg} parameter.
  2504. If no such method is found, \var{DefaultHandlerStr} is called.
  2505. \var{DefaultHandlerStr} is a virtual method of \var{TObject} that doesn't do
  2506. anything, but which can be overridden to provide any processing that might be
  2507. needed. \var{DefaultHandlerStr} is declared as follows:
  2508. \begin{verbatim}
  2509. procedure DefaultHandlerStr(var message);virtual;
  2510. \end{verbatim}
  2511. In addition to this mechanism, a string message method accepts a \var{self}
  2512. parameter:
  2513. \begin{verbatim}
  2514. TMyObject.StrMsgHandler(Data : Pointer; Self : TMyObject);Message 'OnClick';
  2515. \end{verbatim}
  2516. When encountering such a method, the compiler will generate code that loads
  2517. the \var{Self} parameter into the object instance pointer. The result of
  2518. this is that it is possible to pass \var{Self} as a parameter to such a
  2519. method.
  2520. \begin{remark}
  2521. The type of the \var{Self} parameter must be of the same class
  2522. as the class the method is defined in.
  2523. \end{remark}
  2524. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2525. % Properties
  2526. \section{Properties}
  2527. Classes can contain properties as part of their fields list. A property
  2528. acts like a normal field, i.e. its value can be retrieved or set, but it
  2529. allows to redirect the access of the field through functions and
  2530. procedures. They provide a means to associate an action with an assignment
  2531. of or a reading from a class 'field'. This allows for e.g. checking that a
  2532. value is valid when assigning, or, when reading, it allows to construct the
  2533. value on the fly. Moreover, properties can be read-only or write only.
  2534. The prototype declaration of a property is as follows:
  2535. \input{syntax/property.syn}
  2536. A \var{read specifier} is either the name of a field that contains the
  2537. property, or the name of a method function that has the same return type as
  2538. the property type. In the case of a simple type, this
  2539. function must not accept an argument. A \var{read specifier} is optional,
  2540. making the property write-only. Note that class methods cannot be used as
  2541. read specifiers.
  2542. A \var{write specifier} is optional: If there is no \var{write specifier}, the
  2543. property is read-only. A write specifier is either the name of a field, or
  2544. the name of a method procedure that accepts as a sole argument a variable of
  2545. the same type as the property.
  2546. The section (\var{private}, \var{published}) in which the specified function or
  2547. procedure resides is irrelevant. Usually, however, this will be a protected
  2548. or private method.
  2549. Example:
  2550. Given the following declaration:
  2551. \begin{verbatim}
  2552. Type
  2553. MyClass = Class
  2554. Private
  2555. Field1 : Longint;
  2556. Field2 : Longint;
  2557. Field3 : Longint;
  2558. Procedure Sety (value : Longint);
  2559. Function Gety : Longint;
  2560. Function Getz : Longint;
  2561. Public
  2562. Property X : Longint Read Field1 write Field2;
  2563. Property Y : Longint Read GetY Write Sety;
  2564. Property Z : Longint Read GetZ;
  2565. end;
  2566. Var MyClass : TMyClass;
  2567. \end{verbatim}
  2568. The following are valid statements:
  2569. \begin{verbatim}
  2570. WriteLn ('X : ',MyClass.X);
  2571. WriteLn ('Y : ',MyClass.Y);
  2572. WriteLn ('Z : ',MyClass.Z);
  2573. MyClass.X := 0;
  2574. MyClass.Y := 0;
  2575. \end{verbatim}
  2576. But the following would generate an error:
  2577. \begin{verbatim}
  2578. MyClass.Z := 0;
  2579. \end{verbatim}
  2580. because Z is a read-only property.
  2581. What happens in the above statements is that when a value needs to be read,
  2582. the compiler inserts a call to the various \var{getNNN} methods of the
  2583. object, and the result of this call is used. When an assignment is made,
  2584. the compiler passes the value that must be assigned as a paramater to
  2585. the various \var{setNNN} methods.
  2586. Because of this mechanism, properties cannot be passed as var arguments to a
  2587. function or procedure, since there is no known address of the property (at
  2588. least, not always).
  2589. If the property definition contains an index, then the read and write
  2590. specifiers must be a function and a procedure. Moreover, these functions
  2591. require an additional parameter : An integer parameter. This allows to read
  2592. or write several properties with the same function. For this, the properties
  2593. must have the same type.
  2594. The following is an example of a property with an index:
  2595. \begin{verbatim}
  2596. {$mode objfpc}
  2597. Type TPoint = Class(TObject)
  2598. Private
  2599. FX,FY : Longint;
  2600. Function GetCoord (Index : Integer): Longint;
  2601. Procedure SetCoord (Index : Integer; Value : longint);
  2602. Public
  2603. Property X : Longint index 1 read GetCoord Write SetCoord;
  2604. Property Y : Longint index 2 read GetCoord Write SetCoord;
  2605. Property Coords[Index : Integer]:Longint Read GetCoord;
  2606. end;
  2607. Procedure TPoint.SetCoord (Index : Integer; Value : Longint);
  2608. begin
  2609. Case Index of
  2610. 1 : FX := Value;
  2611. 2 : FY := Value;
  2612. end;
  2613. end;
  2614. Function TPoint.GetCoord (INdex : Integer) : Longint;
  2615. begin
  2616. Case Index of
  2617. 1 : Result := FX;
  2618. 2 : Result := FY;
  2619. end;
  2620. end;
  2621. Var P : TPoint;
  2622. begin
  2623. P := TPoint.create;
  2624. P.X := 2;
  2625. P.Y := 3;
  2626. With P do
  2627. WriteLn ('X=',X,' Y=',Y);
  2628. end.
  2629. \end{verbatim}
  2630. When the compiler encounters an assignment to \var{X}, then \var{SetCoord}
  2631. is called with as first parameter the index (1 in the above case) and with
  2632. as a second parameter the value to be set.
  2633. Conversely, when reading the value of \var{X}, the compiler calls
  2634. \var{GetCoord} and passes it index 1.
  2635. Indexes can only be integer values.
  2636. Array propertie also exist. These are properties that accept an
  2637. index, just as an array does. Only now the index doesn't have to be an
  2638. ordinal type, but can be any type.
  2639. A \var{read specifier} for an array property is the name method function
  2640. that has the same return type as the property type.
  2641. The function must accept as a sole arguent a variable of the same type as
  2642. the index type. For an array property, one cannot specify fields as \var{read
  2643. specifiers}.
  2644. A \var{write specifier} for an array property is the name of a method
  2645. procedure that accepts two arguments: The first argument has the same
  2646. type as the index, and the second argument is a parameter of the same
  2647. type as the property type.
  2648. As an example, see the following declaration:
  2649. \begin{verbatim}
  2650. Type TIntList = Class
  2651. Private
  2652. Function GetInt (I : Longint) : longint;
  2653. Function GetAsString (A : String) : String;
  2654. Procedure SetInt (I : Longint; Value : Longint;);
  2655. Procedure SetAsString (A : String; Value : String);
  2656. Public
  2657. Property Items [i : Longint] : Longint Read GetInt
  2658. Write SetInt;
  2659. Property StrItems [S : String] : String Read GetAsString
  2660. Write SetAsstring;
  2661. end;
  2662. Var AIntList : TIntList;
  2663. \end{verbatim}
  2664. Then the following statements would be valid:
  2665. \begin{verbatim}
  2666. AIntList.Items[26] := 1;
  2667. AIntList.StrItems['twenty-five'] := 'zero';
  2668. WriteLn ('Item 26 : ',AIntList.Items[26]);
  2669. WriteLn ('Item 25 : ',AIntList.StrItems['twenty-five']);
  2670. \end{verbatim}
  2671. While the following statements would generate errors:
  2672. \begin{verbatim}
  2673. AIntList.Items['twenty-five'] := 1;
  2674. AIntList.StrItems[26] := 'zero';
  2675. \end{verbatim}
  2676. Because the index types are wrong.
  2677. Array properties can be declared as \var{default} properties. This means that
  2678. it is not necessary to specify the property name when assigning or reading
  2679. it. If, in the previous example, the definition of the items property would
  2680. have been
  2681. \begin{verbatim}
  2682. Property Items[i : Longint]: Longint Read GetInt
  2683. Write SetInt; Default;
  2684. \end{verbatim}
  2685. Then the assignment
  2686. \begin{verbatim}
  2687. AIntList.Items[26] := 1;
  2688. \end{verbatim}
  2689. Would be equivalent to the following abbreviation.
  2690. \begin{verbatim}
  2691. AIntList[26] := 1;
  2692. \end{verbatim}
  2693. Only one default property per class is allowed, and descendent classes
  2694. cannot redeclare the default property.
  2695. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2696. % Interfaces
  2697. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2698. \chapter{Interfaces}
  2699. \label{ch:Interfaces}
  2700. \section{Definition}
  2701. As of version 1.1, FPC supports interfaces. Interfaces are an
  2702. alternative to multiple inheritance (where a class can have multiple
  2703. parent classes) as implemented for instance in C++. An interface is
  2704. basically a named set of methods and properties: A class that
  2705. {\em implements} the interface provides {\em all} the methods as
  2706. they are enumerated in the Interface definition. It is not possible for a
  2707. class to implement only part of the interface: it is all or nothing.
  2708. Interfaces can also be ordered in a hierarchy, exactly as classes:
  2709. An interface definition that inherits from another interface definition
  2710. contains all the methods from the parent interface, as well as the methods
  2711. explicitly named in the interface definition. A class implementing an
  2712. interface must then implement all members of the interface as well as the
  2713. methods of the parent interface(s).
  2714. An interface can be uniquely identified by a GUID (GUID is an acronym for
  2715. Globally Unique Identifier, a 128-bit integer guaranteed always to be
  2716. unique\footnote{In theory, of course.}. Especially on Windows systems, the
  2717. GUID of an interface can and must be used when using COM.
  2718. The definition of an Interface has the following form:
  2719. \input{syntax/typeintf.syn}
  2720. Along with this definition the following must be noted:
  2721. \begin{itemize}
  2722. \item Interfaces can only be used in \var{DELPHI} mode or in \var{OBJFPC}
  2723. mode.
  2724. \item There are no visibility specifiers. All members are public (indeed,
  2725. it would make little sense to make them private or protected).
  2726. \item The properties declared in an interface can only have methods as read and
  2727. write specifiers.
  2728. \item There are no constructors or destructors. Instances of interfaces
  2729. cannot be created directly: instead, an instance of a class implementing
  2730. the interface must be created.
  2731. \item Only calling convention modifiers may be present in the definition of
  2732. a method. Modifiers as \var{virtual}, \var{abstract} or \var{dynamic}, and
  2733. hence also \var{override} cannot be present in the definition of a interface
  2734. definition.
  2735. \end{itemize}
  2736. \section{Interface identification: A GUID}
  2737. An interface can be identified by a GUID. This is a 128-bit number, which is
  2738. represented in a text representation (a string literal):
  2739. \begin{verbatim}
  2740. ['{HHHHHHHH-HHHH-HHHH-HHHH-HHHHHHHHHHHH}']
  2741. \end{verbatim}
  2742. Each \var{H} character represents a hexadecimal number (0-9,A-F). The format
  2743. contains 8-4-4-4-12 numbers. A GUID can also be represented by the following
  2744. record, defined in the \file{objpas} unit (included automatically when in
  2745. \var{DELPHI} or \var{OBJFPC} mode:
  2746. \begin{verbatim}
  2747. PGuid = ^TGuid;
  2748. TGuid = packed record
  2749. case integer of
  2750. 1 : (
  2751. Data1 : DWord;
  2752. Data2 : word;
  2753. Data3 : word;
  2754. Data4 : array[0..7] of byte;
  2755. );
  2756. 2 : (
  2757. D1 : DWord;
  2758. D2 : word;
  2759. D3 : word;
  2760. D4 : array[0..7] of byte;
  2761. );
  2762. end;
  2763. \end{verbatim}
  2764. A constant of type TGUID can be specified using a string literal:
  2765. \begin{verbatim}
  2766. {$mode objfpc}
  2767. program testuid;
  2768. Const
  2769. MyGUID : TGUID = '{10101010-1010-0101-1001-110110110110}';
  2770. begin
  2771. end.
  2772. \end{verbatim}
  2773. Normally, the GUIDs are only used in Windows, when using COM interfaces.
  2774. More on this in the next section.
  2775. \section{Interfaces and COM}
  2776. When using interfaces on Windows which should be available to the COM
  2777. subsystem, the calling convention should be \var{stdcall} - this is not the
  2778. default \fpc calling convention, so it should be specified explicitly.
  2779. COM does not know properties. It only knows methods. So when specifying
  2780. property definitions as part of an interface definition, be aware that the
  2781. properties will only be known in the \fpc compiled program: other Windows
  2782. programs will not be aware of the property definitions. For this reason,
  2783. property definitions must always have interface methods as the read/write
  2784. specifiers.
  2785. \section*{Interface implementations}
  2786. When a class implements an interface, it should implement all methods of the
  2787. interface. If a method of an interface is not implemented, then the compiler
  2788. will give an error. For example:
  2789. \begin{verbatim}
  2790. Type
  2791. IMyInterface = Interface
  2792. Function MyFunc : Integer;
  2793. Function MySecondFunc : Integer;
  2794. end;
  2795. TMyClass = Class(TInterfacedObject,IMyInterface)
  2796. Function MyFunc : Integer;
  2797. Function MyOtherFunc : Integer;
  2798. end;
  2799. Function TMyClass.MyFunc : Integer;
  2800. begin
  2801. Result:=23;
  2802. end;
  2803. Function TMyClass.MyOtherFunc : Integer;
  2804. begin
  2805. Result:=24;
  2806. end;
  2807. \end{verbatim}
  2808. will result in a compiler error:
  2809. \begin{verbatim}
  2810. Error: No matching implementation for interface method
  2811. "IMyInterface.MySecondFunc:LongInt" found
  2812. \end{verbatim}
  2813. At the moment of writing, the compiler does not yet support providing
  2814. aliases for an interface as in Delphi. i.e. the following will not yet
  2815. compile:
  2816. \begin{verbatim}
  2817. ype
  2818. IMyInterface = Interface
  2819. Function MyFunc : Integer;
  2820. end;
  2821. TMyClass = Class(TInterfacedObject,IMyInterface)
  2822. Function MyOtherFunction : Integer;
  2823. // The following fails in FPC.
  2824. Function IMyInterface.MyFunc = MyOtherFunction;
  2825. end;
  2826. \end{verbatim}
  2827. This declaration should tell the compiler that the \var{MyFunc} method of
  2828. the \var{IMyInterface} interface is implemented in the \var{MyOtherFunction}
  2829. method of the \var{TMyClass} class.
  2830. \section{CORBA and other Interfaces}
  2831. COM is not the only architecture where interfaces are used. CORBA knows
  2832. interfaces, UNO (the OpenOffice API) uses interfaces, and Java as well.
  2833. These languages do not know the \var{IUnknown} interface used as the basis of
  2834. all interfaces in COM. It would therefore be a bad idea if an interface
  2835. automatically descended from \var{IUnknown} if no parent interface was
  2836. specified. Therefore, a directive \var{\{\$INTERFACES\}} was introduced in
  2837. \fpc: it specifies what the parent interface is of an interface, declared
  2838. without parent. More information about this directive can be found in the
  2839. \progref.
  2840. Note that COM interfaces are by default reference counted.
  2841. CORBA interfaces are not necessarily reference counted.
  2842. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2843. % Expressions
  2844. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2845. \chapter{Expressions}
  2846. \label{ch:Expressions}
  2847. Expressions occur in assignments or in tests. Expressions produce a value,
  2848. of a certain type.
  2849. Expressions are built with two components: Operators and their operands.
  2850. Usually an operator is binary, i.e. it requires 2 operands. Binary operators
  2851. occur always between the operands (as in \var{X/Y}). Sometimes an
  2852. operator is unary, i.e. it requires only one argument. A unary operator
  2853. occurs always before the operand, as in \var{-X}.
  2854. When using multiple operands in an expression, the precedence rules of
  2855. \seet{OperatorPrecedence} are used.
  2856. \begin{FPCltable}{lll}{Precedence of operators}{OperatorPrecedence}
  2857. Operator & Precedence & Category \\ \hline
  2858. \var{Not, @} & Highest (first) & Unary operators\\
  2859. \var{* / div mod and shl shr as} & Second & Multiplying operators\\
  2860. \var{+ - or xor} & Third & Adding operators \\
  2861. \var{< <> < > <= >= in is} & Lowest (Last) & relational operators \\
  2862. \hline
  2863. \end{FPCltable}
  2864. When determining the precedence, the compiler uses the following rules:
  2865. \begin{enumerate}
  2866. \item In operations with unequal precedences the operands belong to the
  2867. operater with the highest precedence. For example, in \var{5*3+7}, the
  2868. multiplication is higher in precedence than the addition, so it is
  2869. executed first. The result would be 22.
  2870. \item If parentheses are used in an expression, their contents is evaluated
  2871. first. Thus, \var {5*(3+7)} would result in 50.
  2872. \end{enumerate}
  2873. \begin{remark}
  2874. The order in which expressions of the same precedence are evaluated is not
  2875. guaranteed to be left-to-right. In general, no assumptions on which expression
  2876. is evaluated first should be made in such a case.
  2877. The compiler will decide which expression to evaluate first based on
  2878. optimization rules. Thus, in the following expression:
  2879. \begin{verbatim}
  2880. a := g(3) + f(2);
  2881. \end{verbatim}
  2882. \var{f(2)} may be executed before \var{g(3)}. This behaviour is distinctly
  2883. different from \delphi or \tp.
  2884. If one expression {\em must} be executed before the other, it is necessary
  2885. to split up the statement using temporary results:
  2886. \begin{verbatim}
  2887. e1 := g(3);
  2888. a := e1 + f(2);
  2889. \end{verbatim}
  2890. \end{remark}
  2891. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2892. % Expression syntax
  2893. \section{Expression syntax}
  2894. An expression applies relational operators to simple expressions. Simple
  2895. expressions are a series of terms (what a term is, is explained below), joined by
  2896. adding operators.
  2897. \input{syntax/expsimpl.syn}
  2898. The following are valid expressions:
  2899. \begin{verbatim}
  2900. GraphResult<>grError
  2901. (DoItToday=Yes) and (DoItTomorrow=No);
  2902. Day in Weekend
  2903. \end{verbatim}
  2904. And here are some simple expressions:
  2905. \begin{verbatim}
  2906. A + B
  2907. -Pi
  2908. ToBe or NotToBe
  2909. \end{verbatim}
  2910. Terms consist of factors, connected by multiplication operators.
  2911. \input{syntax/expterm.syn}
  2912. Here are some valid terms:
  2913. \begin{verbatim}
  2914. 2 * Pi
  2915. A Div B
  2916. (DoItToday=Yes) and (DoItTomorrow=No);
  2917. \end{verbatim}
  2918. Factors are all other constructions:
  2919. \input{syntax/expfact.syn}
  2920. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2921. % Function calls
  2922. \section{Function calls}
  2923. Function calls are part of expressions (although, using extended syntax,
  2924. they can be statements too). They are constructed as follows:
  2925. \input{syntax/fcall.syn}
  2926. The \synt{variable reference} must be a procedural type variable reference.
  2927. A method designator can only be used inside the method of an object. A
  2928. qualified method designator can be used outside object methods too.
  2929. The function that will get called is the function with a declared parameter
  2930. list that matches the actual parameter list. This means that
  2931. \begin{enumerate}
  2932. \item The number of actual parameters must equal the number of declared
  2933. parameters (unless default parameter values are used).
  2934. \item The types of the parameters must be compatible. For variable
  2935. reference parameters, the parameter types must be exactly the same.
  2936. \end{enumerate}
  2937. If no matching function is found, then the compiler will generate an error.
  2938. Depending on the fact of the function is overloaded (i.e. multiple functions
  2939. with the same name, but different parameter lists) the error will be
  2940. different.
  2941. There are cases when the compiler will not execute the function call in an
  2942. expression. This is the case when assigning a value to a procedural
  2943. type variable, as in the following example:
  2944. \begin{verbatim}
  2945. Type
  2946. FuncType = Function: Integer;
  2947. Var A : Integer;
  2948. Function AddOne : Integer;
  2949. begin
  2950. A := A+1;
  2951. AddOne := A;
  2952. end;
  2953. Var F : FuncType;
  2954. N : Integer;
  2955. begin
  2956. A := 0;
  2957. F := AddOne; { Assign AddOne to F, Don't call AddOne}
  2958. N := AddOne; { N := 1 !!}
  2959. end.
  2960. \end{verbatim}
  2961. In the above listing, the assigment to F will not cause the function AddOne
  2962. to be called. The assignment to N, however, will call AddOne.
  2963. A problem with this syntax is the following construction:
  2964. \begin{verbatim}
  2965. If F = AddOne Then
  2966. DoSomethingHorrible;
  2967. \end{verbatim}
  2968. Should the compiler compare the addresses of \var{F} and \var{AddOne},
  2969. or should it call both functions, and compare the result ? \fpc solves this
  2970. by deciding that a procedural variable is equivalent to a pointer. Thus the
  2971. compiler will give a type mismatch error, since AddOne is considered a
  2972. call to a function with integer result, and F is a pointer, Hence a type
  2973. mismatch occurs.
  2974. How then, should one compare whether \var{F} points to the function
  2975. \var{AddOne} ? To do this, one should use the address operator \var{@}:
  2976. \begin{verbatim}
  2977. If F = @AddOne Then
  2978. WriteLn ('Functions are equal');
  2979. \end{verbatim}
  2980. The left hand side of the boolean expression is an address. The right hand
  2981. side also, and so the compiler compares 2 addresses.
  2982. How to compare the values that both functions return ? By adding an empty
  2983. parameter list:
  2984. \begin{verbatim}
  2985. If F()=Addone then
  2986. WriteLn ('Functions return same values ');
  2987. \end{verbatim}
  2988. Remark that this behaviour is not compatible with Delphi syntax.
  2989. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2990. % Set constructors
  2991. \section{Set constructors}
  2992. When a set-type constant must be entered in an expression, a
  2993. set constructor must be given. In essence this is the same thing as when a
  2994. type is defined, only there is no identifier to identify the set with.
  2995. A set constructor is a comma separated list of expressions, enclosed in
  2996. square brackets.
  2997. \input{syntax/setconst.syn}
  2998. All set groups and set elements must be of the same ordinal type.
  2999. The empty set is denoted by \var{[]}, and it can be assigned to any type of
  3000. set. A set group with a range \var{[A..Z]} makes all values in the range a
  3001. set element. If the first range specifier has a bigger ordinal value than
  3002. the second the set is empty, e.g., \var{[Z..A]} denotes an empty set.
  3003. The following are valid set constructors:
  3004. \begin{verbatim}
  3005. [today,tomorrow]
  3006. [Monday..Friday,Sunday]
  3007. [ 2, 3*2, 6*2, 9*2 ]
  3008. ['A'..'Z','a'..'z','0'..'9']
  3009. \end{verbatim}
  3010. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3011. % Value typecasts
  3012. \section{Value typecasts}
  3013. Sometimes it is necessary to change the type of an expression, or a part of
  3014. the expression, to be able to be assignment compatible. This is done through
  3015. a value typecast. The syntax diagram for a value typecast is as follows:
  3016. \input{syntax/tcast.syn}
  3017. Value typecasts cannot be used on the left side of assignments, as variable
  3018. typecasts.
  3019. Here are some valid typecasts:
  3020. \begin{verbatim}
  3021. Byte('A')
  3022. Char(48)
  3023. boolean(1)
  3024. longint(@Buffer)
  3025. \end{verbatim}
  3026. The type size of the expression and the size of the type cast must be the
  3027. same. That is, the following doesn't work:
  3028. \begin{verbatim}
  3029. Integer('A')
  3030. Char(4875)
  3031. boolean(100)
  3032. Word(@Buffer)
  3033. \end{verbatim}
  3034. This is different from Delphi or Turbo Pascal behaviour.
  3035. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3036. % The @ operator
  3037. \section{The @ operator}
  3038. The address operator \var{@} returns the address of a variable, procedure
  3039. or function. It is used as follows:
  3040. \input{syntax/address.syn}
  3041. The \var{@} operator returns a typed pointer if the \var{\$T} switch is on.
  3042. If the \var{\$T} switch is off then the address operator returns an untyped
  3043. pointer, which is assigment compatible with all pointer types. The type of
  3044. the pointer is \var{\^{}T}, where \var{T} is the type of the variable
  3045. reference.
  3046. For example, the following will compile
  3047. \begin{verbatim}
  3048. Program tcast;
  3049. {$T-} { @ returns untyped pointer }
  3050. Type art = Array[1..100] of byte;
  3051. Var Buffer : longint;
  3052. PLargeBuffer : ^art;
  3053. begin
  3054. PLargeBuffer := @Buffer;
  3055. end.
  3056. \end{verbatim}
  3057. Changing the \var{\{\$T-\}} to \var{\{\$T+\}} will prevent the compiler from
  3058. compiling this. It will give a type mismatch error.
  3059. By default, the address operator returns an untyped pointer.
  3060. Applying the address operator to a function, method, or procedure identifier
  3061. will give a pointer to the entry point of that function. The result is an
  3062. untyped pointer.
  3063. By default, the address operator must be used if a value must be assigned
  3064. to a procedural type variable. This behaviour can be avoided by using the
  3065. \var{-So} or \var{-S2} switches, which result in a more compatible Delphi or
  3066. Turbo Pascal syntax.
  3067. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3068. % Operators
  3069. \section{Operators}
  3070. Operators can be classified according to the type of expression they
  3071. operate on. We will discuss them type by type.
  3072. \subsection{Arithmetic operators}
  3073. Arithmetic operators occur in arithmetic operations, i.e. in expressions
  3074. that contain integers or reals. There are 2 kinds of operators : Binary and
  3075. unary arithmetic operators.
  3076. Binary operators are listed in \seet{binaroperators}, unary operators are
  3077. listed in \seet{unaroperators}.
  3078. \begin{FPCltable}{ll}{Binary arithmetic operators}{binaroperators}
  3079. Operator & Operation \\ \hline
  3080. \var{+} & Addition\\
  3081. \var{-} & Subtraction\\
  3082. \var{*} & Multiplication \\
  3083. \var{/} & Division \\
  3084. \var{Div} & Integer division \\
  3085. \var{Mod} & Remainder \\ \hline
  3086. \end{FPCltable}
  3087. With the exception of \var{Div} and \var{Mod}, which accept only integer
  3088. expressions as operands, all operators accept real and integer expressions as
  3089. operands.
  3090. For binary operators, the result type will be integer if both operands are
  3091. integer type expressions. If one of the operands is a real type expression,
  3092. then the result is real.
  3093. As an exception : division (\var{/}) results always in real values.
  3094. \begin{FPCltable}{ll}{Unary arithmetic operators}{unaroperators}
  3095. Operator & Operation \\ \hline
  3096. \var{+} & Sign identity\\
  3097. \var{-} & Sign inversion \\ \hline
  3098. \end{FPCltable}
  3099. For unary operators, the result type is always equal to the expression type.
  3100. The division (\var{/}) and \var{Mod} operator will cause run-time errors if
  3101. the second argument is zero.
  3102. The sign of the result of a \var{Mod} operator is the same as the sign of
  3103. the left side operand of the \var{Mod} operator. In fact, the \var{Mod}
  3104. operator is equivalent to the following operation :
  3105. \begin{verbatim}
  3106. I mod J = I - (I div J) * J
  3107. \end{verbatim}
  3108. but it executes faster than the right hand side expression.
  3109. \subsection{Logical operators}
  3110. Logical operators act on the individual bits of ordinal expressions.
  3111. Logical operators require operands that are of an integer type, and produce
  3112. an integer type result. The possible logical operators are listed in
  3113. \seet{logicoperations}.
  3114. \begin{FPCltable}{ll}{Logical operators}{logicoperations}
  3115. Operator & Operation \\ \hline
  3116. \var{not} & Bitwise negation (unary) \\
  3117. \var{and} & Bitwise and \\
  3118. \var{or} & Bitwise or \\
  3119. \var{xor} & Bitwise xor \\
  3120. \var{shl} & Bitwise shift to the left \\
  3121. \var{shr} & Bitwise shift to the right \\ \hline
  3122. \end{FPCltable}
  3123. The following are valid logical expressions:
  3124. \begin{verbatim}
  3125. A shr 1 { same as A div 2, but faster}
  3126. Not 1 { equals -2 }
  3127. Not 0 { equals -1 }
  3128. Not -1 { equals 0 }
  3129. B shl 2 { same as B * 4 for integers }
  3130. 1 or 2 { equals 3 }
  3131. 3 xor 1 { equals 2 }
  3132. \end{verbatim}
  3133. \subsection{Boolean operators}
  3134. Boolean operators can be considered logical operations on a type with 1 bit
  3135. size. Therefore the \var{shl} and \var{shr} operations have little sense.
  3136. Boolean operators can only have boolean type operands, and the resulting
  3137. type is always boolean. The possible operators are listed in
  3138. \seet{booleanoperators}
  3139. \begin{FPCltable}{ll}{Boolean operators}{booleanoperators}
  3140. Operator & Operation \\ \hline
  3141. \var{not} & logical negation (unary) \\
  3142. \var{and} & logical and \\
  3143. \var{or} & logical or \\
  3144. \var{xor} & logical xor \\ \hline
  3145. \end{FPCltable}
  3146. \begin{remark} Boolean expressions are always evaluated with short-circuit
  3147. evaluation. This means that from the moment the result of the complete
  3148. expression is known, evaluation is stopped and the result is returned.
  3149. For instance, in the following expression:
  3150. \begin{verbatim}
  3151. B := True or MaybeTrue;
  3152. \end{verbatim}
  3153. The compiler will never look at the value of \var{MaybeTrue}, since it is
  3154. obvious that the expression will always be true. As a result of this
  3155. strategy, if \var{MaybeTrue} is a function, it will not get called !
  3156. (This can have surprising effects when used in conjunction with properties)
  3157. \end{remark}
  3158. \subsection{String operators}
  3159. There is only one string operator : \var{+}. It's action is to concatenate
  3160. the contents of the two strings (or characters) it stands between.
  3161. One cannot use \var{+} to concatenate null-terminated (\var{PChar}) strings.
  3162. The following are valid string operations:
  3163. \begin{verbatim}
  3164. 'This is ' + 'VERY ' + 'easy !'
  3165. Dirname+'\'
  3166. \end{verbatim}
  3167. The following is not:
  3168. \begin{verbatim}
  3169. Var Dirname = Pchar;
  3170. ...
  3171. Dirname := Dirname+'\';
  3172. \end{verbatim}
  3173. Because \var{Dirname} is a null-terminated string.
  3174. \subsection{Set operators}
  3175. The following operations on sets can be performed with operators:
  3176. Union, difference and intersection. The operators needed for this are listed
  3177. in \seet{setoperators}.
  3178. \begin{FPCltable}{ll}{Set operators}{setoperators}
  3179. Operator & Action \\ \hline
  3180. \var{+} & Union \\
  3181. \var{-} & Difference \\
  3182. \var{*} & Intersection \\ \hline
  3183. \end{FPCltable}
  3184. The set type of the operands must be the same, or an error will be
  3185. generated by the compiler.
  3186. \subsection{Relational operators}
  3187. The relational operators are listed in \seet{relationoperators}
  3188. \begin{FPCltable}{ll}{Relational operators}{relationoperators}
  3189. Operator & Action \\ \hline
  3190. \var{=} & Equal \\
  3191. \var{<>} & Not equal \\
  3192. \var{<} & Stricty less than\\
  3193. \var{>} & Strictly greater than\\
  3194. \var{<=} & Less than or equal \\
  3195. \var{>=} & Greater than or equal \\
  3196. \var{in} & Element of \\ \hline
  3197. \end{FPCltable}
  3198. Left and right operands must be of the same type. Only integer
  3199. and real types can be mixed in relational expressions.
  3200. Comparing strings is done on the basis of their ASCII code representation.
  3201. When comparing pointers, the addresses to which they point are compared.
  3202. This also is true for \var{PChar} type pointers. To compare the strings
  3203. the \var{Pchar} point to, the \var{StrComp} function
  3204. from the \file{strings} unit must be used.
  3205. The \var{in} returns \var{True} if the left operand (which must have the same
  3206. ordinal type as the set type, and which must be in the range 0..255) is an
  3207. element of the set which is the right operand, otherwise it returns \var{False}
  3208. \chapter{Statements}
  3209. \label{ch:Statements}
  3210. The heart of each algorithm are the actions it takes. These actions are
  3211. contained in the statements of a program or unit. Each statement can be
  3212. labeled and jumped to (within certain limits) with \var{Goto} statements.
  3213. This can be seen in the following syntax diagram:
  3214. \input{syntax/statement.syn}
  3215. A label can be an identifier or an integer digit.
  3216. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3217. % Simple statements
  3218. \section{Simple statements}
  3219. A simple statement cannot be decomposed in separate statements. There are
  3220. basically 4 kinds of simple statements:
  3221. \input{syntax/simstate.syn}
  3222. Of these statements, the {\em raise statement} will be explained in the
  3223. chapter on Exceptions (\seec{Exceptions})
  3224. \subsection{Assignments}
  3225. Assignments give a value to a variable, replacing any previous value the
  3226. variable might have had:
  3227. \input{syntax/assign.syn}
  3228. In addition to the standard Pascal assignment operator (\var{ := }), which
  3229. simply replaces the value of the varable with the value resulting from the
  3230. expression on the right of the { := } operator, \fpc
  3231. supports some c-style constructions. All available constructs are listed in
  3232. \seet{assignments}.
  3233. \begin{FPCltable}{lr}{Allowed C constructs in \fpc}{assignments}
  3234. Assignment & Result \\ \hline
  3235. a += b & Adds \var{b} to \var{a}, and stores the result in \var{a}.\\
  3236. a -= b & Substracts \var{b} from \var{a}, and stores the result in
  3237. \var{a}. \\
  3238. a *= b & Multiplies \var{a} with \var{b}, and stores the result in
  3239. \var{a}. \\
  3240. a /= b & Divides \var{a} through \var{b}, and stores the result in
  3241. \var{a}. \\ \hline
  3242. \end{FPCltable}
  3243. For these constructs to work, the \var{-Sc} command-line switch must
  3244. be specified.
  3245. \begin{remark}
  3246. These constructions are just for typing convenience, they
  3247. don't generate different code.
  3248. Here are some examples of valid assignment statements:
  3249. \begin{verbatim}
  3250. X := X+Y;
  3251. X+=Y; { Same as X := X+Y, needs -Sc command line switch}
  3252. X/=2; { Same as X := X/2, needs -Sc command line switch}
  3253. Done := False;
  3254. Weather := Good;
  3255. MyPi := 4* Tan(1);
  3256. \end{verbatim}
  3257. \end{remark}
  3258. \subsection{Procedure statements}
  3259. Procedure statements are calls to subroutines. There are
  3260. different possibilities for procedure calls: A normal procedure call, an
  3261. object method call (fully qualified or not), or even a call to a procedural
  3262. type variable. All types are present in the following diagram.
  3263. \input{syntax/procedure.syn}
  3264. The \fpc compiler will look for a procedure with the same name as given in
  3265. the procedure statement, and with a declared parameter list that matches the
  3266. actual parameter list.
  3267. The following are valid procedure statements:
  3268. \begin{verbatim}
  3269. Usage;
  3270. WriteLn('Pascal is an easy language !');
  3271. Doit();
  3272. \end{verbatim}
  3273. \subsection{Goto statements}
  3274. \fpc supports the \var{goto} jump statement. Its prototype syntax is
  3275. \input{syntax/goto.syn}
  3276. When using \var{goto} statements, the following must be kept in mind:
  3277. \begin{enumerate}
  3278. \item The jump label must be defined in the same block as the \var{Goto}
  3279. statement.
  3280. \item Jumping from outside a loop to the inside of a loop or vice versa can
  3281. have strange effects.
  3282. \item To be able to use the \var{Goto} statement, the \var{-Sg} compiler
  3283. switch must be used.
  3284. \end{enumerate}
  3285. \var{Goto} statements are considered bad practice and should be avoided as
  3286. much as possible. It is always possible to replace a \var{goto} statement by a
  3287. construction that doesn't need a \var{goto}, although this construction may
  3288. not be as clear as a goto statement.
  3289. For instance, the following is an allowed goto statement:
  3290. \begin{verbatim}
  3291. label
  3292. jumpto;
  3293. ...
  3294. Jumpto :
  3295. Statement;
  3296. ...
  3297. Goto jumpto;
  3298. ...
  3299. \end{verbatim}
  3300. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3301. % Structured statements
  3302. \section{Structured statements}
  3303. Structured statements can be broken into smaller simple statements, which
  3304. should be executed repeatedly, conditionally or sequentially:
  3305. \input{syntax/struct.syn}
  3306. Conditional statements come in 2 flavours :
  3307. \input{syntax/conditio.syn}
  3308. Repetitive statements come in 3 flavours:
  3309. \input{syntax/repetiti.syn}
  3310. The following sections deal with each of these statements.
  3311. \subsection{Compound statements}
  3312. Compound statements are a group of statements, separated by semicolons,
  3313. that are surrounded by the keywords \var{Begin} and \var{End}. The
  3314. Last statement doesn't need to be followed by a semicolon, although it is
  3315. allowed. A compound statement is a way of grouping statements together,
  3316. executing the statements sequentially. They are treated as one statement
  3317. in cases where Pascal syntax expects 1 statement, such as in
  3318. \var{if ... then} statements.
  3319. \input{syntax/compound.syn}
  3320. \subsection{The \var{Case} statement}
  3321. \fpc supports the \var{case} statement. Its syntax diagram is
  3322. \input{syntax/case.syn}
  3323. The constants appearing in the various case parts must be known at
  3324. compile-time, and can be of the following types : enumeration types,
  3325. Ordinal types (except boolean), and chars. The expression must be also of
  3326. this type, or a compiler error will occur. All case constants must
  3327. have the same type.
  3328. The compiler will evaluate the expression. If one of the case constants
  3329. values matches the value of the expression, the statement that follows
  3330. this constant is executed. After that, the program continues after the final
  3331. \var{end}.
  3332. If none of the case constants match the expression value, the statement
  3333. after the \var{else} keyword is executed. This can be an empty statement.
  3334. If no else part is present, and no case constant matches the expression
  3335. value, program flow continues after the final \var{end}.
  3336. The case statements can be compound statements
  3337. (i.e. a \var{begin..End} block).
  3338. \begin{remark}
  3339. Contrary to Turbo Pascal, duplicate case labels are not
  3340. allowed in \fpc, so the following code will generate an error when
  3341. compiling:
  3342. \begin{verbatim}
  3343. Var i : integer;
  3344. ...
  3345. Case i of
  3346. 3 : DoSomething;
  3347. 1..5 : DoSomethingElse;
  3348. end;
  3349. \end{verbatim}
  3350. The compiler will generate a \var{Duplicate case label} error when compiling
  3351. this, because the 3 also appears (implicitly) in the range \var{1..5}. This
  3352. is similar to Delphi syntax.
  3353. \end{remark}
  3354. The following are valid case statements:
  3355. \begin{verbatim}
  3356. Case C of
  3357. 'a' : WriteLn ('A pressed');
  3358. 'b' : WriteLn ('B pressed');
  3359. 'c' : WriteLn ('C pressed');
  3360. else
  3361. WriteLn ('unknown letter pressed : ',C);
  3362. end;
  3363. \end{verbatim}
  3364. Or
  3365. \begin{verbatim}
  3366. Case C of
  3367. 'a','e','i','o','u' : WriteLn ('vowel pressed');
  3368. 'y' : WriteLn ('This one depends on the language');
  3369. else
  3370. WriteLn ('Consonant pressed');
  3371. end;
  3372. \end{verbatim}
  3373. \begin{verbatim}
  3374. Case Number of
  3375. 1..10 : WriteLn ('Small number');
  3376. 11..100 : WriteLn ('Normal, medium number');
  3377. else
  3378. WriteLn ('HUGE number');
  3379. end;
  3380. \end{verbatim}
  3381. \subsection{The \var{If..then..else} statement}
  3382. The \var{If .. then .. else..} prototype syntax is
  3383. \input{syntax/ifthen.syn}
  3384. The expression between the \var{if} and \var{then} keywords must have a
  3385. boolean return type. If the expression evaluates to \var{True} then the
  3386. statement following \var{then} is executed.
  3387. If the expression evaluates to \var{False}, then the statement following
  3388. \var{else} is executed, if it is present.
  3389. Be aware of the fact that the boolean expression will be short-cut evaluated.
  3390. (Meaning that the evaluation will be stopped at the point where the
  3391. outcome is known with certainty)
  3392. Also, before the \var {else} keyword, no semicolon (\var{;}) is allowed,
  3393. but all statements can be compound statements.
  3394. In nested \var{If.. then .. else} constructs, some ambiguity may araise as
  3395. to which \var{else} statement pairs with which \var{if} statement. The rule
  3396. is that the \var{else } keyword matches the first \var{if} keyword not
  3397. already matched by an \var{else} keyword.
  3398. For example:
  3399. \begin{verbatim}
  3400. If exp1 Then
  3401. If exp2 then
  3402. Stat1
  3403. else
  3404. stat2;
  3405. \end{verbatim}
  3406. Despite it's appearance, the statement is syntactically equivalent to
  3407. \begin{verbatim}
  3408. If exp1 Then
  3409. begin
  3410. If exp2 then
  3411. Stat1
  3412. else
  3413. stat2
  3414. end;
  3415. \end{verbatim}
  3416. and not to
  3417. \begin{verbatim}
  3418. { NOT EQUIVALENT }
  3419. If exp1 Then
  3420. begin
  3421. If exp2 then
  3422. Stat1
  3423. end
  3424. else
  3425. stat2
  3426. \end{verbatim}
  3427. If it is this latter construct is needed, the \var{begin} and \var{end}
  3428. keywords must be present. When in doubt, it is better to add them.
  3429. The following is a valid statement:
  3430. \begin{verbatim}
  3431. If Today in [Monday..Friday] then
  3432. WriteLn ('Must work harder')
  3433. else
  3434. WriteLn ('Take a day off.');
  3435. \end{verbatim}
  3436. \subsection{The \var{For..to/downto..do} statement}
  3437. \fpc supports the \var{For} loop construction. A for loop is used in case
  3438. one wants to calculated something a fixed number of times.
  3439. The prototype syntax is as follows:
  3440. \input{syntax/for.syn}
  3441. \var{Statement} can be a compound statement.
  3442. When this statement is encountered, the control variable is initialized with
  3443. the initial value, and is compared with the final value.
  3444. What happens next depends on whether \var{to} or \var{downto} is used:
  3445. \begin{enumerate}
  3446. \item In the case \var{To} is used, if the initial value is larger than the final
  3447. value then \var{Statement} will never be executed.
  3448. \item In the case \var{DownTo} is used, if the initial value is less than the final
  3449. value then \var{Statement} will never be executed.
  3450. \end{enumerate}
  3451. After this check, the statement after \var{Do} is executed. After the
  3452. execution of the statement, the control variable is increased or decreased
  3453. with 1, depending on whether \var{To} or \var{Downto} is used.
  3454. The control variable must be an ordinal type, no other
  3455. types can be used as counters in a loop.
  3456. \begin{remark}
  3457. Contrary to ANSI pascal specifications, \fpc first initializes
  3458. the counter variable, and only then calculates the upper bound.
  3459. \end{remark}
  3460. The following are valid loops:
  3461. \begin{verbatim}
  3462. For Day := Monday to Friday do Work;
  3463. For I := 100 downto 1 do
  3464. WriteLn ('Counting down : ',i);
  3465. For I := 1 to 7*dwarfs do KissDwarf(i);
  3466. \end{verbatim}
  3467. If the statement is a compound statement, then the \seep{Break} and
  3468. \seep{Continue} reserved words can be used to jump to the end or just
  3469. after the end of the \var{For} statement.
  3470. \subsection{The \var{Repeat..until} statement}
  3471. The \var{repeat} statement is used to execute a statement until a certain
  3472. condition is reached. The statement will be executed at least once.
  3473. The prototype syntax of the \var{Repeat..until} statement is
  3474. \input{syntax/repeat.syn}
  3475. This will execute the statements between \var{repeat} and \var{until} up to
  3476. the moment when \var{Expression} evaluates to \var{True}.
  3477. Since the \var{expression} is evaluated {\em after} the execution of the
  3478. statements, they are executed at least once.
  3479. Be aware of the fact that the boolean expression \var{Expression} will be
  3480. short-cut evaluated. (Meaning that the evaluation will be stopped at the
  3481. point where the outcome is known with certainty)
  3482. The following are valid \var{repeat} statements
  3483. \begin{verbatim}
  3484. repeat
  3485. WriteLn ('I =',i);
  3486. I := I+2;
  3487. until I>100;
  3488. repeat
  3489. X := X/2
  3490. until x<10e-3
  3491. \end{verbatim}
  3492. The \seep{Break} and \seep{Continue} reserved words can be used to jump to
  3493. the end or just after the end of the \var{repeat .. until } statement.
  3494. \subsection{The \var{While..do} statement}
  3495. A \var{while} statement is used to execute a statement as long as a certain
  3496. condition holds. This may imply that the statement is never executed.
  3497. The prototype syntax of the \var{While..do} statement is
  3498. \input{syntax/while.syn}
  3499. This will execute \var{Statement} as long as \var{Expression} evaluates to
  3500. \var{True}. Since \var{Expression} is evaluated {\em before} the execution
  3501. of \var{Statement}, it is possible that \var{Statement} isn't executed at
  3502. all. \var{Statement} can be a compound statement.
  3503. Be aware of the fact that the boolean expression \var{Expression} will be
  3504. short-cut evaluated. (Meaning that the evaluation will be stopped at the
  3505. point where the outcome is known with certainty)
  3506. The following are valid \var{while} statements:
  3507. \begin{verbatim}
  3508. I := I+2;
  3509. while i<=100 do
  3510. begin
  3511. WriteLn ('I =',i);
  3512. I := I+2;
  3513. end;
  3514. X := X/2;
  3515. while x>=10e-3 do
  3516. X := X/2;
  3517. \end{verbatim}
  3518. They correspond to the example loops for the \var{repeat} statements.
  3519. If the statement is a compound statement, then the \seep{Break} and
  3520. \seep{Continue} reserved words can be used to jump to the end or just
  3521. after the end of the \var{While} statement.
  3522. \subsection{The \var{With} statement}
  3523. \label{se:With}
  3524. The \var{with} statement serves to access the elements of a record
  3525. or object or class, without having to specify the name of the each time.
  3526. The syntax for a \var{with} statement is
  3527. \input{syntax/with.syn}
  3528. The variable reference must be a variable of a record, object or class type.
  3529. In the \var{with} statement, any variable reference, or method reference is
  3530. checked to see if it is a field or method of the record or object or class.
  3531. If so, then that field is accessed, or that method is called.
  3532. Given the declaration:
  3533. \begin{verbatim}
  3534. Type Passenger = Record
  3535. Name : String[30];
  3536. Flight : String[10];
  3537. end;
  3538. Var TheCustomer : Passenger;
  3539. \end{verbatim}
  3540. The following statements are completely equivalent:
  3541. \begin{verbatim}
  3542. TheCustomer.Name := 'Michael';
  3543. TheCustomer.Flight := 'PS901';
  3544. \end{verbatim}
  3545. and
  3546. \begin{verbatim}
  3547. With TheCustomer do
  3548. begin
  3549. Name := 'Michael';
  3550. Flight := 'PS901';
  3551. end;
  3552. \end{verbatim}
  3553. The statement
  3554. \begin{verbatim}
  3555. With A,B,C,D do Statement;
  3556. \end{verbatim}
  3557. is equivalent to
  3558. \begin{verbatim}
  3559. With A do
  3560. With B do
  3561. With C do
  3562. With D do Statement;
  3563. \end{verbatim}
  3564. This also is a clear example of the fact that the variables are tried {\em last
  3565. to first}, i.e., when the compiler encounters a variable reference, it will
  3566. first check if it is a field or method of the last variable. If not, then it
  3567. will check the last-but-one, and so on.
  3568. The following example shows this;
  3569. \begin{verbatim}
  3570. Program testw;
  3571. Type AR = record
  3572. X,Y : Longint;
  3573. end;
  3574. PAR = Record;
  3575. Var S,T : Ar;
  3576. begin
  3577. S.X := 1;S.Y := 1;
  3578. T.X := 2;T.Y := 2;
  3579. With S,T do
  3580. WriteLn (X,' ',Y);
  3581. end.
  3582. \end{verbatim}
  3583. The output of this program is
  3584. \begin{verbatim}
  3585. 2 2
  3586. \end{verbatim}
  3587. Showing thus that the \var{X,Y} in the \var{WriteLn} statement match the
  3588. \var{T} record variable.
  3589. \begin{remark}
  3590. When using a \var{With} statement with a pointer, or a class, it is not
  3591. permitted to change the pointer or the class in the \var{With} block.
  3592. With the definitions of the previous example, the following illustrates
  3593. what it is about:
  3594. \begin{verbatim}
  3595. Var p : PAR;
  3596. begin
  3597. With P^ do
  3598. begin
  3599. // Do some operations
  3600. P:=OtherP;
  3601. X:=0.0; // Wrong X will be used !!
  3602. end;
  3603. \end{verbatim}
  3604. The reason the pointer cannot be changed is that the address is stored
  3605. by the compiler in a temporary register. Changing the pointer won't change
  3606. the temporary address. The same is true for classes.
  3607. \end{remark}
  3608. \subsection{Exception Statements}
  3609. \fpc supports exceptions. Exceptions provide a convenient way to
  3610. program error and error-recovery mechanisms, and are
  3611. closely related to classes.
  3612. Exception support is explained in \seec{Exceptions}
  3613. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3614. % Assembler statements
  3615. \section{Assembler statements}
  3616. An assembler statement allows to insert assembler code right in the
  3617. pascal code.
  3618. \input{syntax/statasm.syn}
  3619. More information about assembler blocks can be found in the \progref.
  3620. The register list is used to indicate the registers that are modified by an
  3621. assembler statement in the assembler block. The compiler stores certain results in the
  3622. registers. If the registers are modified in an assembler statement, the compiler
  3623. should, sometimes, be told about it. The registers are denoted with their
  3624. Intel names for the I386 processor, i.e., \var{'EAX'}, \var{'ESI'} etc...
  3625. As an example, consider the following assembler code:
  3626. \begin{verbatim}
  3627. asm
  3628. Movl $1,%ebx
  3629. Movl $0,%eax
  3630. addl %eax,%ebx
  3631. end; ['EAX','EBX'];
  3632. \end{verbatim}
  3633. This will tell the compiler that it should save and restore the contents of
  3634. the \var{EAX} and \var{EBX} registers when it encounters this asm statement.
  3635. \fpc supports various styles of assembler syntax. By default, \var{AT\&T}
  3636. syntax is assumed for the 80386 and compatibles platform.
  3637. The default assembler style can be changed with the \var{\{\$asmmode xxx\}}
  3638. switch in the code, or the \var{-R} command-line option. More about this can
  3639. be found in the \progref.
  3640. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3641. % Using functions and procedures.
  3642. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3643. \chapter{Using functions and procedures}
  3644. \label{ch:Procedures}
  3645. \fpc supports the use of functions and procedures, but with some extras:
  3646. Function overloading is supported, as well as \var{Const} parameters and
  3647. open arrays.
  3648. \begin{remark} In many of the subsequent paragraphs the words \var{procedure}
  3649. and \var{function} will be used interchangeably. The statements made are
  3650. valid for both, except when indicated otherwise.
  3651. \end{remark}
  3652. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3653. % Procedure declaration
  3654. \section{Procedure declaration}
  3655. A procedure declaration defines an identifier and associates it with a
  3656. block of code. The procedure can then be called with a procedure statement.
  3657. \input{syntax/procedur.syn}
  3658. See \sees{Parameters} for the list of parameters.
  3659. A procedure declaration that is followed by a block implements the action of
  3660. the procedure in that block.
  3661. The following is a valid procedure :
  3662. \begin{verbatim}
  3663. Procedure DoSomething (Para : String);
  3664. begin
  3665. Writeln ('Got parameter : ',Para);
  3666. Writeln ('Parameter in upper case : ',Upper(Para));
  3667. end;
  3668. \end{verbatim}
  3669. Note that it is possible that a procedure calls itself.
  3670. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3671. % Function declaration
  3672. \section{Function declaration}
  3673. A function declaration defines an identifier and associates it with a
  3674. block of code. The block of code will return a result.
  3675. The function can then be called inside an expression, or with a procedure
  3676. statement, if extended syntax is on.
  3677. \input{syntax/function.syn}
  3678. The result type of a function can be any previously declared type.
  3679. contrary to Turbo pascal, where only simple types could be returned.
  3680. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3681. % Parameter lists
  3682. \section{Parameter lists}
  3683. \label{se:Parameters}
  3684. When arguments must be passed to a function or procedure, these parameters
  3685. must be declared in the formal parameter list of that function or procedure.
  3686. The parameter list is a declaration of identifiers that can be referred to
  3687. only in that procedure or function's block.
  3688. \input{syntax/params.syn}
  3689. Constant parameters and variable parameters can also be \var{untyped}
  3690. parameters if they have no type identifier.
  3691. As of version 1.1, \fpc supports default values for both constant parameters
  3692. and value parameters, but only for simple types. The compiler must be in
  3693. \var{OBJFPC} or \var{DELPHI} mode to accept default values.
  3694. \subsection{Value parameters}
  3695. Value parameters are declared as follows:
  3696. \input{syntax/paramval.syn}
  3697. When parameters are declared as value parameters, the procedure gets {\em
  3698. a copy} of the parameters that the calling block passes. Any modifications
  3699. to these parameters are purely local to the procedure's block, and do not
  3700. propagate back to the calling block.
  3701. A block that wishes to call a procedure with value parameters must pass
  3702. assignment compatible parameters to the procedure. This means that the types
  3703. should not match exactly, but can be converted (conversion code is inserted
  3704. by the compiler itself)
  3705. Care must be taken when using value parameters: Value parameters makes heavy
  3706. use of the stack, especially when using large parameters. The total size of
  3707. all parameters in the formal parameter list should be below 32K for
  3708. portability's sake (the Intel version limits this to 64K).
  3709. Open arrays can be passed as value parameters. See \sees{openarray} for
  3710. more information on using open arrays.
  3711. For a parameter of a simple type (i.e. not a structured type), a default
  3712. value can be specified. This can be an untyped constant. If the function
  3713. call omits the parameter, the default value will be passed on to the
  3714. function. For dynamic arrays or other types that can be considered as
  3715. equivalent to a pointer, the only possible default value is \var{Nil}.
  3716. The following example will print 20 on the screen:
  3717. \begin{verbatim}
  3718. program testp;
  3719. Const
  3720. MyConst = 20;
  3721. Procedure MyRealFunc(I : Integer = MyConst);
  3722. begin
  3723. Writeln('Function received : ',I);
  3724. end;
  3725. begin
  3726. MyRealFunc;
  3727. end.
  3728. \end{verbatim}
  3729. \subsection{Variable parameters}
  3730. \label{se:varparams}
  3731. Variable parameters are declared as follows:
  3732. \input{syntax/paramvar.syn}
  3733. When parameters are declared as variable parameters, the procedure or
  3734. function accesses immediatly the variable that the calling block passed in
  3735. its parameter list. The procedure gets a pointer to the variable that was
  3736. passed, and uses this pointer to access the variable's value.
  3737. From this, it follows that any changes made to the parameter, will
  3738. propagate back to the calling block. This mechanism can be used to pass
  3739. values back in procedures.
  3740. Because of this, the calling block must pass a parameter of {\em exactly}
  3741. the same type as the declared parameter's type. If it does not, the compiler
  3742. will generate an error.
  3743. Variable and constant parameters can be untyped. In that case the variable has no type,
  3744. and hence is incompatible with all other types. However, the address operator
  3745. can be used on it, or it can be can passed to a function that has also an
  3746. untyped parameter. If an untyped parameter is used in an assigment,
  3747. or a value must be assigned to it, a typecast must be used.
  3748. File type variables must always be passed as variable parameters.
  3749. Open arrays can be passed as variable parameters. See \sees{openarray} for
  3750. more information on using open arrays.
  3751. Note that default values are not supported for variable parameters. This
  3752. would make little sense since it defeats the purpose of being able to pass a
  3753. value back to the caller.
  3754. \subsection{Out parameters}
  3755. \label{se:outparams}
  3756. Out parameters (output parameters) are declared as follows:
  3757. \input{syntax/paramout.syn}
  3758. The purpose of an \var{out} parameter is to pass values back to the calling
  3759. routine: The variable is passed by reference. The initial value of the
  3760. parameter on function entry is discarded, and should not be used.
  3761. If a variable must be used to pass a value to a function and retrieve data
  3762. from the function, then a variable parameter must be used. If only a value
  3763. must be retrieved, a \var{out} parameter can be used.
  3764. Needless to say, default values are not supported for \var{out} parameters.
  3765. \subsection{Constant parameters}
  3766. In addition to variable parameters and value parameters \fpc also supports
  3767. Constant parameters. A constant parameter as can be specified as follows:
  3768. \input{syntax/paramcon.syn}
  3769. A constant argument is passed by reference if it's size is larger than a
  3770. pointer. It is passed by value if the size is equal or is less then the
  3771. size of a native pointer.
  3772. This means that the function or procedure receives a pointer to the passed
  3773. argument, but it cannot be assigned to, this will result in a
  3774. compiler error. Furthermore a const parameter cannot be passed on to another
  3775. function that requires a variable parameter.
  3776. The main use for this is reducing the stack size, hence improving
  3777. performance, and still retaining the semantics of passing by value...
  3778. Constant parameters can also be untyped. See \sees{varparams} for more
  3779. information about untyped parameters.
  3780. As for value parameters, constant parameters can get default values.
  3781. Open arrays can be passed as constant parameters. See \sees{openarray} for
  3782. more information on using open arrays.
  3783. \subsection{Open array parameters}
  3784. \label{se:openarray}
  3785. \fpc supports the passing of open arrays, i.e. a procedure can be declared
  3786. with an array of unspecified length as a parameter, as in Delphi.
  3787. Open array parameters can be accessed in the procedure or function as an
  3788. array that is declared with starting index 0, and last element
  3789. index \var{High(paremeter)}.
  3790. For example, the parameter
  3791. \begin{verbatim}
  3792. Row : Array of Integer;
  3793. \end{verbatim}
  3794. would be equivalent to
  3795. \begin{verbatim}
  3796. Row : Array[0..N-1] of Integer;
  3797. \end{verbatim}
  3798. Where \var{N} would be the actual size of the array that is passed to the
  3799. function. \var{N-1} can be calculated as \var{High(Row)}.
  3800. Open parameters can be passed by value, by reference or as a constant
  3801. parameter. In the latter cases the procedure receives a pointer to the
  3802. actual array. In the former case, it receives a copy of the array.
  3803. In a function or procedure, open arrays can only be passed to functions which
  3804. are also declared with open arrays as parameters, {\em not} to functions or
  3805. procedures which accept arrays of fixed length.
  3806. The following is an example of a function using an open array:
  3807. \begin{verbatim}
  3808. Function Average (Row : Array of integer) : Real;
  3809. Var I : longint;
  3810. Temp : Real;
  3811. begin
  3812. Temp := Row[0];
  3813. For I := 1 to High(Row) do
  3814. Temp := Temp + Row[i];
  3815. Average := Temp / (High(Row)+1);
  3816. end;
  3817. \end{verbatim}
  3818. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3819. % The array of const construct
  3820. \subsection{Array of const}
  3821. In Object Pascal or Delphi mode, \fpc supports the \var{Array of Const}
  3822. construction to pass parameters to a subroutine.
  3823. This is a special case of the \var{Open array} construction, where it is
  3824. allowed to pass any expression in an array to a function or procedure.
  3825. In the procedure, passed the arguments can be examined using a special
  3826. record:
  3827. \begin{verbatim}
  3828. Type
  3829. PVarRec = ^TVarRec;
  3830. TVarRec = record
  3831. case VType : Longint of
  3832. vtInteger : (VInteger: Longint);
  3833. vtBoolean : (VBoolean: Boolean);
  3834. vtChar : (VChar: Char);
  3835. vtExtended : (VExtended: PExtended);
  3836. vtString : (VString: PShortString);
  3837. vtPointer : (VPointer: Pointer);
  3838. vtPChar : (VPChar: PChar);
  3839. vtObject : (VObject: TObject);
  3840. vtClass : (VClass: TClass);
  3841. vtAnsiString : (VAnsiString: Pointer);
  3842. vtWideString : (VWideString: Pointer);
  3843. vtInt64 : (VInt64: PInt64);
  3844. end;
  3845. \end{verbatim}
  3846. Inside the procedure body, the array of const is equivalent to
  3847. an open array of TVarRec:
  3848. \begin{verbatim}
  3849. Procedure Testit (Args: Array of const);
  3850. Var I : longint;
  3851. begin
  3852. If High(Args)<0 then
  3853. begin
  3854. Writeln ('No aguments');
  3855. exit;
  3856. end;
  3857. Writeln ('Got ',High(Args)+1,' arguments :');
  3858. For i:=0 to High(Args) do
  3859. begin
  3860. write ('Argument ',i,' has type ');
  3861. case Args[i].vtype of
  3862. vtinteger :
  3863. Writeln ('Integer, Value :',args[i].vinteger);
  3864. vtboolean :
  3865. Writeln ('Boolean, Value :',args[i].vboolean);
  3866. vtchar :
  3867. Writeln ('Char, value : ',args[i].vchar);
  3868. vtextended :
  3869. Writeln ('Extended, value : ',args[i].VExtended^);
  3870. vtString :
  3871. Writeln ('ShortString, value :',args[i].VString^);
  3872. vtPointer :
  3873. Writeln ('Pointer, value : ',Longint(Args[i].VPointer));
  3874. vtPChar :
  3875. Writeln ('PCHar, value : ',Args[i].VPChar);
  3876. vtObject :
  3877. Writeln ('Object, name : ',Args[i].VObject.Classname);
  3878. vtClass :
  3879. Writeln ('Class reference, name :',Args[i].VClass.Classname);
  3880. vtAnsiString :
  3881. Writeln ('AnsiString, value :',AnsiString(Args[I].VAnsiStr
  3882. else
  3883. Writeln ('(Unknown) : ',args[i].vtype);
  3884. end;
  3885. end;
  3886. end;
  3887. \end{verbatim}
  3888. In code, it is possible to pass an arbitrary array of elements
  3889. to this procedure:
  3890. \begin{verbatim}
  3891. S:='Ansistring 1';
  3892. T:='AnsiString 2';
  3893. Testit ([]);
  3894. Testit ([1,2]);
  3895. Testit (['A','B']);
  3896. Testit ([TRUE,FALSE,TRUE]);
  3897. Testit (['String','Another string']);
  3898. Testit ([S,T]) ;
  3899. Testit ([P1,P2]);
  3900. Testit ([@testit,Nil]);
  3901. Testit ([ObjA,ObjB]);
  3902. Testit ([1.234,1.234]);
  3903. TestIt ([AClass]);
  3904. \end{verbatim}
  3905. If the procedure is declared with the \var{cdecl} modifier, then the
  3906. compiler will pass the array as a C compiler would pass it. This, in effect,
  3907. emulates the C construct of a variable number of arguments, as the following
  3908. example will show:
  3909. \begin{verbatim}
  3910. program testaocc;
  3911. {$mode objfpc}
  3912. Const
  3913. P : Pchar = 'example';
  3914. Fmt : PChar =
  3915. 'This %s uses printf to print numbers (%d) and strings.'#10;
  3916. // Declaration of standard C function printf:
  3917. procedure printf (fm : pchar; args : array of const);cdecl; external 'c';
  3918. begin
  3919. printf(Fmt,[P,123]);
  3920. end.
  3921. \end{verbatim}
  3922. Remark that this is not true for Delphi, so code relying on this feature
  3923. will not be portable.
  3924. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3925. % Function overloading
  3926. \section{Function overloading}
  3927. Function overloading simply means that the same function is defined more
  3928. than once, but each time with a different formal parameter list.
  3929. The parameter lists must differ at least in one of it's elements type.
  3930. When the compiler encounters a function call, it will look at the function
  3931. parameters to decide which one of the defined functions it should call.
  3932. This can be useful when the same function must be defined for different
  3933. types. For example, in the RTL, the \var{Dec} procedure could be
  3934. defined as:
  3935. \begin{verbatim}
  3936. ...
  3937. Dec(Var I : Longint;decrement : Longint);
  3938. Dec(Var I : Longint);
  3939. Dec(Var I : Byte;decrement : Longint);
  3940. Dec(Var I : Byte);
  3941. ...
  3942. \end{verbatim}
  3943. When the compiler encounters a call to the dec function, it will first search
  3944. which function it should use. It therefore checks the parameters in a
  3945. function call, and looks if there is a function definition which matches the
  3946. specified parameter list. If the compiler finds such a function, a call is
  3947. inserted to that function. If no such function is found, a compiler error is
  3948. generated.
  3949. functions that have a \var{cdecl} modifier cannot be overloaded.
  3950. (Technically, because this modifier prevents the mangling of
  3951. the function name by the compiler).
  3952. Prior to version 1.9 of the compiler, the overloaded functions needed to be
  3953. in the same unit. Now the compiler will continue searching in other units if
  3954. it doesn't find a matching version of an overloaded function in one unit.
  3955. The compiler accepts the presence of the \var{overload} modifier as in
  3956. Delphi, but it is not required, unless in Delphi mode.
  3957. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  3958. % forward defined functions
  3959. \section{Forward defined functions}
  3960. A function can be declared without having it followed by it's implementation,
  3961. by having it followed by the \var{forward} procedure. The effective
  3962. implementation of that function must follow later in the module.
  3963. The function can be used after a \var{forward} declaration as if it had been
  3964. implemented already.
  3965. The following is an example of a forward declaration.
  3966. \begin{verbatim}
  3967. Program testforward;
  3968. Procedure First (n : longint); forward;
  3969. Procedure Second;
  3970. begin
  3971. WriteLn ('In second. Calling first...');
  3972. First (1);
  3973. end;
  3974. Procedure First (n : longint);
  3975. begin
  3976. WriteLn ('First received : ',n);
  3977. end;
  3978. begin
  3979. Second;
  3980. end.
  3981. \end{verbatim}
  3982. A function can be defined as forward only once.
  3983. Likewise, in units, it is not allowed to have a forward declared function
  3984. of a function that has been declared in the interface part. The interface
  3985. declaration counts as a \var{forward} declaration.
  3986. The following unit will give an error when compiled:
  3987. \begin{verbatim}
  3988. Unit testforward;
  3989. interface
  3990. Procedure First (n : longint);
  3991. Procedure Second;
  3992. implementation
  3993. Procedure First (n : longint); forward;
  3994. Procedure Second;
  3995. begin
  3996. WriteLn ('In second. Calling first...');
  3997. First (1);
  3998. end;
  3999. Procedure First (n : longint);
  4000. begin
  4001. WriteLn ('First received : ',n);
  4002. end;
  4003. end.
  4004. \end{verbatim}
  4005. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4006. % External functions
  4007. \section{External functions}
  4008. \label{se:external}
  4009. The \var{external} modifier can be used to declare a function that resides in
  4010. an external object file. It allows to use the function in some code, and at
  4011. linking time, the object file containing the implementation of the function
  4012. or procedure must be linked in.
  4013. \input{syntax/external.syn}
  4014. It replaces, in effect, the function or procedure code block.
  4015. As an example:
  4016. \begin{verbatim}
  4017. program CmodDemo;
  4018. {$Linklib c}
  4019. Const P : PChar = 'This is fun !';
  4020. Function strlen (P : PChar) : Longint; cdecl; external;
  4021. begin
  4022. WriteLn ('Length of (',p,') : ',strlen(p))
  4023. end.
  4024. \end{verbatim}
  4025. \begin{remark}
  4026. The parameters in our declaration of the \var{external} function
  4027. should match exactly the ones in the declaration in the object file.
  4028. \end{remark}
  4029. If the \var{external} modifier is followed by a string constant:
  4030. \begin{verbatim}
  4031. external 'lname';
  4032. \end{verbatim}
  4033. Then this tells the compiler that the function resides in library
  4034. 'lname'. The compiler will then automatically link this library to
  4035. the program.
  4036. The name that the function has in the library can also be specified:
  4037. \begin{verbatim}
  4038. external 'lname' name 'Fname';
  4039. \end{verbatim}
  4040. This tells the compiler that the function resides in library 'lname',
  4041. but with name 'Fname'.The compiler will then automatically link this
  4042. library to the program, and use the correct name for the function.
  4043. Under \windows and \ostwo, the following form can also be used:
  4044. \begin{verbatim}
  4045. external 'lname' Index Ind;
  4046. \end{verbatim}
  4047. This tells the compiler that the function resides in library 'lname',
  4048. but with index \var{Ind}. The compiler will then automatically
  4049. link this library to the program, and use the correct index for the
  4050. function.
  4051. Finally, the external directive can be used to specify the external name
  4052. of the function :
  4053. \begin{verbatim}
  4054. {$L myfunc.o}
  4055. external name 'Fname';
  4056. \end{verbatim}
  4057. This tells the compiler that the function has the name 'Fname'. The
  4058. correct library or object file (in this case myfunc.o) must still be linked.
  4059. so that the function 'Fname' is included in the linking stage.
  4060. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4061. % Assembler functions
  4062. \section{Assembler functions}
  4063. Functions and procedures can be completely implemented in assembly
  4064. language. To indicate this, use the \var{assembler} keyword:
  4065. \input{syntax/asm.syn}
  4066. Contrary to Delphi, the assembler keyword must be present to indicate an
  4067. assembler function.
  4068. For more information about assembler functions, see the chapter on using
  4069. assembler in the \progref.
  4070. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4071. % Modifiers
  4072. \section{Modifiers}
  4073. A function or procedure declaration can contain modifiers. Here we list the
  4074. various possibilities:
  4075. \input{syntax/modifiers.syn}
  4076. \fpc doesn't support all Turbo Pascal modifiers, but
  4077. does support a number of additional modifiers. They are used mainly for assembler and
  4078. reference to C object files.
  4079. \subsection{alias}
  4080. The \var{alias} modifier allows the programmer to specify a different name for a
  4081. procedure or function. This is mostly useful for referring to this procedure
  4082. from assembly language constructs or from another object file. As an example,
  4083. consider the following program:
  4084. \begin{verbatim}
  4085. Program Aliases;
  4086. Procedure Printit;alias : 'DOIT';
  4087. begin
  4088. WriteLn ('In Printit (alias : "DOIT")');
  4089. end;
  4090. begin
  4091. asm
  4092. call DOIT
  4093. end;
  4094. end.
  4095. \end{verbatim}
  4096. \begin{remark} the specified alias is inserted straight into the assembly
  4097. code, thus it is case sensitive.
  4098. \end{remark}
  4099. The \var{alias} modifier does not make the symbol public to other modules,
  4100. unless the routine is also declared in the interface part of a unit, or
  4101. the \var{public} modifier is used to force it as public. Consider the
  4102. following:
  4103. \begin{verbatim}
  4104. unit testalias;
  4105. interface
  4106. procedure testroutine;
  4107. implementation
  4108. procedure testroutine;alias:'ARoutine';
  4109. begin
  4110. WriteLn('Hello world');
  4111. end;
  4112. end.
  4113. \end{verbatim}
  4114. This will make the routine \var{testroutine} available publicly to
  4115. external object files uunder the label name \var{ARoutine}.
  4116. \subsection{cdecl}
  4117. \label{se:cdecl}
  4118. The \var{cdecl} modifier can be used to declare a function that uses a C
  4119. type calling convention. This must be used when accessing functions residing in
  4120. an object file generated by standard C compilers. It allows to use the function in
  4121. the code, and at linking time, the object file containing the
  4122. \var{C} implementation of the function or procedure must be linked in.
  4123. As an example:
  4124. \begin{verbatim}
  4125. program CmodDemo;
  4126. {$LINKLIB c}
  4127. Const P : PChar = 'This is fun !';
  4128. Function strlen (P : PChar) : Longint; cdecl; external name 'strlen';
  4129. begin
  4130. WriteLn ('Length of (',p,') : ',strlen(p))
  4131. end.
  4132. \end{verbatim}
  4133. When compiling this, and linking to the C-library, the \var{strlen} function
  4134. can be called throughout the program. The \var{external} directive tells
  4135. the compiler that the function resides in an external object filebrary
  4136. with the 'strlen' name (see \ref{se:external}).
  4137. \begin{remark}
  4138. The parameters in our declaration of the \var{C} function should
  4139. match exactly the ones in the declaration in \var{C}.
  4140. \end{remark}
  4141. \subsection{export}
  4142. The export modifier is used to export names when creating a shared library
  4143. or an executable program. This means that the symbol will be publicly
  4144. available, and can be imported from other programs. For more information
  4145. on this modifier, consult the section on Programming dynamic libraries
  4146. in the \progref.
  4147. \subsection{inline}
  4148. \label{se:inline}
  4149. Procedures that are declared inline are copied to the places where they
  4150. are called. This has the effect that there is no actual procedure call,
  4151. the code of the procedure is just copied to where the procedure is needed,
  4152. this results in faster execution speed if the function or procedure is
  4153. used a lot.
  4154. By default, \var{inline} procedures are not allowed. Inline code must be enabled
  4155. using the command-line switch \var{-Si} or \var{\{\$inline on\}}
  4156. directive.
  4157. \begin{enumerate}
  4158. \item Inline code is NOT exported from a unit. This means that when
  4159. calling an inline procedure from another unit, a normal procedure call will be
  4160. performed. Only inside units, \var{Inline} procedures are really inlined.
  4161. \item Recursive inline functions are not allowed. i.e. an inline function
  4162. that calls itself is not allowed.
  4163. \end{enumerate}
  4164. \subsection{interrupt}
  4165. \label{se:interrupt}
  4166. The \var{interrupt} keyword is used to declare a routine which will
  4167. be used as an interrupt handler. On entry to this routine, all the registers
  4168. will be saved and on exit, all registers will be restored
  4169. and an interrupt or trap return will be executed (instead of the normal return
  4170. from subroutine instruction).
  4171. On platforms where a return from interrupt does not exist, the normal exit
  4172. code of routines will be done instead. For more information on the generated
  4173. code, consult the \progref.
  4174. \subsection{pascal}
  4175. \label{se:pascal}
  4176. The \var{pascal} modifier can be used to declare a function that uses the
  4177. classic pascal type calling convention (passing parameters from left to right).
  4178. For more information on the pascal calling convention, consult the \progref.
  4179. \subsection{popstack}
  4180. \label{se:popstack}
  4181. Popstack does the same as \var{cdecl}, namely it tells the \fpc compiler
  4182. that a function uses the C calling convention. In difference with the
  4183. \var{cdecl} modifier, it still mangles the name of the function as it would
  4184. for a normal pascal function.
  4185. With \var{popstack}, functions can be called by their pascal names in a
  4186. library.
  4187. \subsection{public}
  4188. The \var{Public} keyword is used to declare a function globally in a unit.
  4189. This is useful if the function should not be accessible from the unit
  4190. file (i.e. another unit/program using the unit doesn't see the function),
  4191. but must be accessible from the object file. as an example:
  4192. \begin{verbatim}
  4193. Unit someunit;
  4194. interface
  4195. Function First : Real;
  4196. Implementation
  4197. Function First : Real;
  4198. begin
  4199. First := 0;
  4200. end;
  4201. Function Second : Real; [Public];
  4202. begin
  4203. Second := 1;
  4204. end;
  4205. end.
  4206. \end{verbatim}
  4207. If another program or unit uses this unit, it will not be able to use the
  4208. function \var{Second}, since it isn't declared in the interface part.
  4209. However, it will be possible to access the function \var{Second} at the
  4210. assembly-language level, by using it's mangled name (see the \progref).
  4211. \subsection{register}
  4212. \label{se:register}
  4213. The \var{register} keyword is used for compatibility with Delphi. In
  4214. version 1.0.x of the compiler, this directive has no effect on the
  4215. generated code. As of the 1.9.X versions, this directive is supported. The
  4216. first three arguments are passed in registers EAX,ECX and EDX.
  4217. \subsection{saveregisters}
  4218. If this modifier is specified after a procedure or function, then the
  4219. \fpc compiler will save all registers on procedure entry, and restore
  4220. them when the procedure exits (except for registers where return values
  4221. are stored).
  4222. This modifier is not used under normal circumstances, except maybe when
  4223. calling assembler code.
  4224. \subsection{safecall}
  4225. This modifier ressembles closely the \var{stdcall} modifier. It sends
  4226. parameters from right to left on the stack. The called procedure saves and
  4227. restores all registers.
  4228. More information about this modifier can be found in the \progref, in the
  4229. section on the calling mechanism and the chapter on linking.
  4230. \subsection{softfloat}
  4231. This modifier makes sense only on the ARM architecture.
  4232. \subsection{stdcall}
  4233. This modifier pushes the parameters from right to left on the stack,
  4234. it also aligns all the parameters to a default alignment.
  4235. More information about this modifier can be found in the \progref, in the
  4236. section on the calling mechanism and the chapter on linking.
  4237. \subsection{varargs}
  4238. This modifier can only be used together with the \var{cdecl} modifier, for
  4239. external C procedures. It indicates that the procedure accepts a variable
  4240. number of arguments after the last declared variable. These arguments are
  4241. passed on without any type checking. It is equivalent to using the
  4242. \var{array of const} construction for \var{cdecl} procedures, without having
  4243. to declare the \var{array of const}. The square brackets around the variable
  4244. arguments do not need to be used when this form of declaration is used.
  4245. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4246. % Unsupported Turbo Pascal modifiers
  4247. \section{Unsupported Turbo Pascal modifiers}
  4248. The modifiers that exist in Turbo pascal, but aren't supported by \fpc, are
  4249. listed in \seet{Modifs}.
  4250. \begin{FPCltable}{lr}{Unsupported modifiers}{Modifs}
  4251. Modifier & Why not supported ? \\ \hline
  4252. Near & \fpc is a 32-bit compiler.\\
  4253. Far & \fpc is a 32-bit compiler. \\
  4254. \end{FPCltable}
  4255. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4256. % Operator overloading
  4257. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4258. \chapter{Operator overloading}
  4259. \label{ch:operatoroverloading}
  4260. \section{Introduction}
  4261. \fpc supports operator overloading. This means that it is possible to
  4262. define the action of some operators on self-defined types, and thus allow
  4263. the use of these types in mathematical expressions.
  4264. Defining the action of an operator is much like the definition of a
  4265. function or procedure, only there are some restrictions on the possible
  4266. definitions, as will be shown in the subsequent.
  4267. Operator overloading is, in essence, a powerful notational tool;
  4268. but it is also not more than that, since the same results can be
  4269. obtained with regular function calls. When using operator overloading,
  4270. It is important to keep in mind that some implicit rules may produce
  4271. some unexpected results. This will be indicated.
  4272. \section{Operator declarations}
  4273. To define the action of an operator is much like defining a function:
  4274. \input{syntax/operator.syn}
  4275. The parameter list for a comparision operator or an arithmetic operator
  4276. must always contain 2 parameters. The result type of the comparision
  4277. operator must be \var{Boolean}.
  4278. \begin{remark}
  4279. When compiling in \var{Delphi} mode or \var{Objfpc} mode, the result
  4280. identifier may be dropped. The result can then be accessed through
  4281. the standard \var{Result} symbol.
  4282. If the result identifier is dropped and the compiler is not in one
  4283. of these modes, a syntax error will occur.
  4284. \end{remark}
  4285. The statement block contains the necessary statements to determine the
  4286. result of the operation. It can contain arbitrary large pieces of code;
  4287. it is executed whenever the operation is encountered in some expression.
  4288. The result of the statement block must always be defined; error conditions
  4289. are not checked by the compiler, and the code must take care of all possible
  4290. cases, throwing a run-time error if some error condition is encountered.
  4291. In the following, the three types of operator definitions will be examined.
  4292. As an example, throughout this chapter the following type will be used to
  4293. define overloaded operators on :
  4294. \begin{verbatim}
  4295. type
  4296. complex = record
  4297. re : real;
  4298. im : real;
  4299. end;
  4300. \end{verbatim}
  4301. this type will be used in all examples.
  4302. The sources of the Run-Time Library contain a unit \file{ucomplex},
  4303. which contains a complete calculus for complex numbers, based on
  4304. operator overloading.
  4305. \section{Assignment operators}
  4306. The assignment operator defines the action of a assignent of one type of
  4307. variable to another. The result type must match the type of the variable
  4308. at the left of the assignment statement, the single parameter to the
  4309. assignment operator must have the same type as the expression at the
  4310. right of the assignment operator.
  4311. This system can be used to declare a new type, and define an assignment for
  4312. that type. For instance, to be able to assign a newly defined type 'Complex'
  4313. \begin{verbatim}
  4314. Var
  4315. C,Z : Complex; // New type complex
  4316. begin
  4317. Z:=C; // assignments between complex types.
  4318. end;
  4319. \end{verbatim}
  4320. The following assignment operator would have to be defined:
  4321. \begin{verbatim}
  4322. Operator := (C : Complex) z : complex;
  4323. \end{verbatim}
  4324. To be able to assign a real type to a complex type as follows:
  4325. \begin{verbatim}
  4326. var
  4327. R : real;
  4328. C : complex;
  4329. begin
  4330. C:=R;
  4331. end;
  4332. \end{verbatim}
  4333. the following assignment operator must be defined:
  4334. \begin{verbatim}
  4335. Operator := (r : real) z : complex;
  4336. \end{verbatim}
  4337. As can be seen from this statement, it defines the action of the operator
  4338. \var{:=} with at the right a real expression, and at the left a complex
  4339. expression.
  4340. an example implementation of this could be as follows:
  4341. \begin{verbatim}
  4342. operator := (r : real) z : complex;
  4343. begin
  4344. z.re:=r;
  4345. z.im:=0.0;
  4346. end;
  4347. \end{verbatim}
  4348. As can be seen in the example, the result identifier (\var{z} in this case)
  4349. is used to store the result of the assignment. When compiling in Delphi mode
  4350. or objfpc mode, the use of the special identifier \var{Result} is also
  4351. allowed, and can be substituted for the \var{z}, so the above would be
  4352. equivalent to
  4353. \begin{verbatim}
  4354. operator := (r : real) z : complex;
  4355. begin
  4356. Result.re:=r;
  4357. Result.im:=0.0;
  4358. end;
  4359. \end{verbatim}
  4360. The assignment operator is also used to convert types from one type to
  4361. another. The compiler will consider all overloaded assignment operators
  4362. till it finds one that matches the types of the left hand and right hand
  4363. expressions. If no such operator is found, a 'type mismatch' error
  4364. is given.
  4365. \begin{remark}
  4366. The assignment operator is not commutative; the compiler will never reverse
  4367. the role of the two arguments. in other words, given the above definition of
  4368. the assignment operator, the following is {\em not} possible:
  4369. \begin{verbatim}
  4370. var
  4371. R : real;
  4372. C : complex;
  4373. begin
  4374. R:=C;
  4375. end;
  4376. \end{verbatim}
  4377. if the reverse assignment should be possible (this is not so for reals and
  4378. complex numbers) then the assigment operator must be defined for that as well.
  4379. \end{remark}
  4380. \begin{remark}
  4381. The assignment operator is also used in implicit type conversions. This can
  4382. have unwanted effects. Consider the following definitions:
  4383. \begin{verbatim}
  4384. operator := (r : real) z : complex;
  4385. function exp(c : complex) : complex;
  4386. \end{verbatim}
  4387. then the following assignment will give a type mismatch:
  4388. \begin{verbatim}
  4389. Var
  4390. r1,r2 : real;
  4391. begin
  4392. r1:=exp(r2);
  4393. end;
  4394. \end{verbatim}
  4395. because the compiler will encounter the definition of the \var{exp} function
  4396. with the complex argument. It implicitly converts r2 to a complex, so it can
  4397. use the above \var{exp} function. The result of this function is a complex,
  4398. which cannot be assigned to r1, so the compiler will give a 'type mismatch'
  4399. error. The compiler will not look further for another \var{exp} which has
  4400. the correct arguments.
  4401. It is possible to avoid this particular problem by specifying
  4402. \begin{verbatim}
  4403. r1:=system.exp(r2);
  4404. \end{verbatim}
  4405. An experimental solution for this problem exists in the compiler, but is
  4406. not enabled by default. Maybe someday it will be.
  4407. \end{remark}
  4408. \section{Arithmetic operators}
  4409. Arithmetic operators define the action of a binary operator. Possible
  4410. operations are:
  4411. \begin{description}
  4412. \item[multiplication] to multiply two types, the \var{*} multiplication
  4413. operator must be overloaded.
  4414. \item[division] to divide two types, the \var{/} division
  4415. operator must be overloaded.
  4416. \item[addition] to add two types, the \var{+} addition
  4417. operator must be overloaded.
  4418. \item[substraction] to substract two types, the \var{-} substraction
  4419. operator must be overloaded.
  4420. \item[exponentiation] to exponentiate two types, the \var{**} exponentiation
  4421. operator must be overloaded.
  4422. \end{description}
  4423. The definition of an arithmetic operator takes two parameters. The first
  4424. parameter must be of the type that occurs at the left of the operator,
  4425. the second parameter must be of the type that is at the right of the
  4426. arithmetic operator. The result type must match the type that results
  4427. after the arithmetic operation.
  4428. To compile an expression as
  4429. \begin{verbatim}
  4430. var
  4431. R : real;
  4432. C,Z : complex;
  4433. begin
  4434. C:=R*Z;
  4435. end;
  4436. \end{verbatim}
  4437. one needs a definition of the multiplication operator as:
  4438. \begin{verbatim}
  4439. Operator * (r : real; z1 : complex) z : complex;
  4440. begin
  4441. z.re := z1.re * r;
  4442. z.im := z1.im * r;
  4443. end;
  4444. \end{verbatim}
  4445. As can be seen, the first operator is a real, and the second is
  4446. a complex. The result type is complex.
  4447. Multiplication and addition of reals and complexes are commutative
  4448. operations. The compiler, however, has no notion of this fact so even
  4449. if a multiplication between a real and a complex is defined, the
  4450. compiler will not use that definition when it encounters a complex
  4451. and a real (in that order). It is necessary to define both operations.
  4452. So, given the above definition of the multiplication,
  4453. the compiler will not accept the following statement:
  4454. \begin{verbatim}
  4455. var
  4456. R : real;
  4457. C,Z : complex;
  4458. begin
  4459. C:=Z*R;
  4460. end;
  4461. \end{verbatim}
  4462. since the types of \var{Z} and \var{R} don't match the types in the
  4463. operator definition.
  4464. The reason for this behaviour is that it is possible that a multiplication
  4465. is not always commutative. e.g. the multiplication of a \var{(n,m)} with a
  4466. \var{(m,n)} matrix will result in a \var{(n,n)} matrix, while the
  4467. mutiplication of a \var{(m,n)} with a \var{(n,m)} matrix is a \var{(m,m)}
  4468. matrix, which needn't be the same in all cases.
  4469. \section{Comparision operator}
  4470. The comparision operator can be overloaded to compare two different types
  4471. or to compare two equal types that are not basic types. The result type of
  4472. a comparision operator is always a boolean.
  4473. The comparision operators that can be overloaded are:
  4474. \begin{description}
  4475. \item[equal to] (=) to determine if two variables are equal.
  4476. \item[less than] ($<$) to determine if one variable is less than another.
  4477. \item[greater than] ($>$) to determine if one variable is greater than another.
  4478. \item[greater than or equal to] ($>=$) to determine if one variable is greater than
  4479. or equal to another.
  4480. \item[less than or equal to] ($<=$) to determine if one variable is greater
  4481. than or equal to another.
  4482. \end{description}
  4483. There is no separate operator for {\em unequal to} ($<>$). To evaluate a
  4484. statement that contans the {\em unequal to} operator, the compiler uses the
  4485. {\em equal to} operator (=), and negates the result.
  4486. As an example, the following opetrator allows to compare two complex
  4487. numbers:
  4488. \begin{verbatim}
  4489. operator = (z1, z2 : complex) b : boolean;
  4490. \end{verbatim}
  4491. the above definition allows comparisions of the following form:
  4492. \begin{verbatim}
  4493. Var
  4494. C1,C2 : Complex;
  4495. begin
  4496. If C1=C2 then
  4497. Writeln('C1 and C2 are equal');
  4498. end;
  4499. \end{verbatim}
  4500. The comparision operator definition needs 2 parameters, with the types that
  4501. the operator is meant to compare. Here also, the compiler doesn't apply
  4502. commutativity; if the two types are different, then it necessary to
  4503. define 2 comparision operators.
  4504. In the case of complex numbers, it is, for instance necessary to define
  4505. 2 comparsions: one with the complex type first, and one with the real type
  4506. first.
  4507. Given the definitions
  4508. \begin{verbatim}
  4509. operator = (z1 : complex;r : real) b : boolean;
  4510. operator = (r : real; z1 : complex) b : boolean;
  4511. \end{verbatim}
  4512. the following two comparisions are possible:
  4513. \begin{verbatim}
  4514. Var
  4515. R,S : Real;
  4516. C : Complex;
  4517. begin
  4518. If (C=R) or (S=C) then
  4519. Writeln ('Ok');
  4520. end;
  4521. \end{verbatim}
  4522. Note that the order of the real and complex type in the two comparisions
  4523. is reversed.
  4524. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4525. % Programs, Units, Blocks
  4526. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4527. \chapter{Programs, units, blocks}
  4528. A Pascal program consists of modules called \var{units}. A unit can be used
  4529. to group pieces of code together, or to give someone code without giving
  4530. the sources.
  4531. Both programs and units consist of code blocks, which are mixtures of
  4532. statements, procedures, and variable or type declarations.
  4533. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4534. % Programs
  4535. \section{Programs}
  4536. A pascal program consists of the program header, followed possibly by a
  4537. 'uses' clause, and a block.
  4538. \input{syntax/program.syn}
  4539. The program header is provided for backwards compatibility, and is ignored
  4540. by the compiler.
  4541. The uses clause serves to identify all units that are needed by the program.
  4542. The system unit doesn't have to be in this list, since it is always loaded
  4543. by the compiler.
  4544. The order in which the units appear is significant, it determines in
  4545. which order they are initialized. Units are initialized in the same order
  4546. as they appear in the uses clause. Identifiers are searched in the opposite
  4547. order, i.e. when the compiler searches for an identifier, then it looks
  4548. first in the last unit in the uses clause, then the last but one, and so on.
  4549. This is important in case two units declare different types with the same
  4550. identifier.
  4551. When the compiler looks for unit files, it adds the extension \file{.ppu}
  4552. (\file{.ppw} for Win32 platforms) to the name of the unit. On \linux and in
  4553. operating systems where filenames are case sensitive, when looking for a unit,
  4554. the unit name is first looked for in the original case, and when not found,
  4555. converted to all lowercase and searched for.
  4556. If a unit name is longer than 8 characters, the compiler will first look for
  4557. a unit name with this length, and then it will truncate the name to 8
  4558. characters and look for it again. For compatibility reasons, this is also
  4559. true on platforms that suport long file names.
  4560. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4561. % Units
  4562. \section{Units}
  4563. A unit contains a set of declarations, procedures and functions that can be
  4564. used by a program or another unit.
  4565. The syntax for a unit is as follows:
  4566. \input{syntax/unit.syn}
  4567. The interface part declares all identifiers that must be exported from the
  4568. unit. This can be constant, type or variable identifiers, and also procedure
  4569. or function identifier declarations. Declarations inside the
  4570. implementation part are {\em not} accessible outside the unit. The
  4571. implementation must contain a function declaration for each function or
  4572. procedure that is declared in the interface part. If a function is declared
  4573. in the interface part, but no declaration of that function is present in the
  4574. implementation part, then the compiler will give an error.
  4575. When a program uses a unit (say \file{unitA}) and this units uses a second
  4576. unit, say \file{unitB}, then the program depends indirectly also on
  4577. \var{unitB}. This means that the compiler must have access to \file{unitB} when
  4578. trying to compile the program. If the unit is not present at compile time,
  4579. an error occurs.
  4580. Note that the identifiers from a unit on which a program depends indirectly,
  4581. are not accessible to the program. To have access to the identifiers of a
  4582. unit, the unit must be in the uses clause of the program or unit where the
  4583. identifiers are needed.
  4584. Units can be mutually dependent, that is, they can reference each other in
  4585. their uses clauses. This is allowed, on the condition that at least one of
  4586. the references is in the implementation section of the unit. This also holds
  4587. for indirect mutually dependent units.
  4588. If it is possible to start from one interface uses clause of a unit, and to return
  4589. there via uses clauses of interfaces only, then there is circular unit
  4590. dependence, and the compiler will generate an error.
  4591. As and example : the following is not allowed:
  4592. \begin{verbatim}
  4593. Unit UnitA;
  4594. interface
  4595. Uses UnitB;
  4596. implementation
  4597. end.
  4598. Unit UnitB
  4599. interface
  4600. Uses UnitA;
  4601. implementation
  4602. end.
  4603. \end{verbatim}
  4604. But this is allowed :
  4605. \begin{verbatim}
  4606. Unit UnitA;
  4607. interface
  4608. Uses UnitB;
  4609. implementation
  4610. end.
  4611. Unit UnitB
  4612. implementation
  4613. Uses UnitA;
  4614. end.
  4615. \end{verbatim}
  4616. Because \file{UnitB} uses \file{UnitA} only in it's implentation section.
  4617. In general, it is a bad idea to have circular unit dependencies, even if it is
  4618. only in implementation sections.
  4619. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4620. % Blocks
  4621. \section{Blocks}
  4622. Units and programs are made of blocks. A block is made of declarations of
  4623. labels, constants, types variables and functions or procedures. Blocks can
  4624. be nested in certain ways, i.e., a procedure or function declaration can
  4625. have blocks in themselves.
  4626. A block looks like the following:
  4627. \input{syntax/block.syn}
  4628. Labels that can be used to identify statements in a block are declared in
  4629. the label declaration part of that block. Each label can only identify one
  4630. statement.
  4631. Constants that are to be used only in one block should be declared in that
  4632. block's constant declaration part.
  4633. Variables that are to be used only in one block should be declared in that
  4634. block's constant declaration part.
  4635. Types that are to be used only in one block should be declared in that
  4636. block's constant declaration part.
  4637. Lastly, functions and procedures that will be used in that block can be
  4638. declared in the procedure/function declaration part.
  4639. After the different declaration parts comes the statement part. This
  4640. contains any actions that the block should execute.
  4641. All identifiers declared before the statement part can be used in that
  4642. statement part.
  4643. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4644. % Scope
  4645. \section{Scope}
  4646. Identifiers are valid from the point of their declaration until the end of
  4647. the block in which the declaration occurred. The range where the identifier
  4648. is known is the {\em scope} of the identifier. The exact scope of an
  4649. identifier depends on the way it was defined.
  4650. \subsection{Block scope}
  4651. The {\em scope} of a variable declared in the declaration part of a block,
  4652. is valid from the point of declaration until the end of the block.
  4653. If a block contains a second block, in which the identfier is
  4654. redeclared, then inside this block, the second declaration will be valid.
  4655. Upon leaving the inner block, the first declaration is valid again.
  4656. Consider the following example:
  4657. \begin{verbatim}
  4658. Program Demo;
  4659. Var X : Real;
  4660. { X is real variable }
  4661. Procedure NewDeclaration
  4662. Var X : Integer; { Redeclare X as integer}
  4663. begin
  4664. // X := 1.234; {would give an error when trying to compile}
  4665. X := 10; { Correct assigment}
  4666. end;
  4667. { From here on, X is Real again}
  4668. begin
  4669. X := 2.468;
  4670. end.
  4671. \end{verbatim}
  4672. In this example, inside the procedure, X denotes an integer variable.
  4673. It has it's own storage space, independent of the variable \var{X} outside
  4674. the procedure.
  4675. \subsection{Record scope}
  4676. The field identifiers inside a record definition are valid in the following
  4677. places:
  4678. \begin{enumerate}
  4679. \item to the end of the record definition.
  4680. \item field designators of a variable of the given record type.
  4681. \item identifiers inside a \var{With} statement that operates on a variable
  4682. of the given record type.
  4683. \end{enumerate}
  4684. \subsection{Class scope}
  4685. A component identifier is valid in the following places:
  4686. \begin{enumerate}
  4687. \item From the point of declaration to the end of the class definition.
  4688. \item In all descendent types of this class, unless it is in the private
  4689. part of the class declaration.
  4690. \item In all method declaration blocks of this class and descendent classes.
  4691. \item In a with statement that operators on a variable of the given class's
  4692. definition.
  4693. \end{enumerate}
  4694. Note that method designators are also considered identifiers.
  4695. \subsection{Unit scope}
  4696. All identifiers in the interface part of a unit are valid from the point of
  4697. declaration, until the end of the unit. Furthermore, the identifiers are
  4698. known in programs or units that have the unit in their uses clause.
  4699. Identifiers from indirectly dependent units are {\em not} available.
  4700. Identifiers declared in the implementation part of a unit are valid from the
  4701. point of declaration to the end of the unit.
  4702. The system unit is automatically used in all units and programs.
  4703. It's identifiers are therefore always known, in each pascal program, library
  4704. or unit.
  4705. The rules of unit scope imply that an identifier of a
  4706. unit can be redefined. To have access to an identifier of another unit that was redeclared in
  4707. the current unit, precede it with that other units name, as in the following
  4708. example:
  4709. \begin{verbatim}
  4710. unit unitA;
  4711. interface
  4712. Type
  4713. MyType = Real;
  4714. implementation
  4715. end.
  4716. Program prog;
  4717. Uses UnitA;
  4718. { Redeclaration of MyType}
  4719. Type MyType = Integer;
  4720. Var A : Mytype; { Will be Integer }
  4721. B : UnitA.MyType { Will be real }
  4722. begin
  4723. end.
  4724. \end{verbatim}
  4725. This is especially useful when redeclaring the system unit's identifiers.
  4726. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4727. % Libraries
  4728. \section{Libraries}
  4729. \fpc supports making of dynamic libraries (DLLs under Win32 and \ostwo) trough
  4730. the use of the \var{Library} keyword.
  4731. A Library is just like a unit or a program:
  4732. \input{syntax/library.syn}
  4733. By default, functions and procedures that are declared and implemented in
  4734. library are not available to a programmer that wishes to use this library.
  4735. In order to make functions or procedures available from the library,
  4736. they must be exported in an export clause:
  4737. \input{syntax/exports.syn}
  4738. Under Win32, an index clause can be added to an exports entry.
  4739. an index entry must be a positive number larger or equal than 1.
  4740. Optionally, an exports entry can have a name specifier. If present, the name
  4741. specifier gives the exact name (case sensitive) of the function in the
  4742. library.
  4743. If neither of these constructs is present, the functions or procedures
  4744. are exported with the exact names as specified in the exports clause.
  4745. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4746. % Exceptions
  4747. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4748. \chapter{Exceptions}
  4749. \label{ch:Exceptions}
  4750. Exceptions provide a convenient way to program error and error-recovery
  4751. mechanisms, and are closely related to classes.
  4752. Exception support is based on 3 constructs:
  4753. \begin{description}
  4754. \item [Raise\ ] statements. To raise an exeption. This is usually done to signal an
  4755. error condition.
  4756. \item [Try ... Except\ ] blocks. These block serve to catch exceptions
  4757. raised within the scope of the block, and to provide exception-recovery
  4758. code.
  4759. \item [Try ... Finally\ ] blocks. These block serve to force code to be
  4760. executed irrespective of an exception occurrence or not. They generally
  4761. serve to clean up memory or close files in case an exception occurs.
  4762. The compiler generates many implicit \var{Try ... Finally} blocks around
  4763. procedure, to force memory consistence.
  4764. \end{description}
  4765. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4766. % The raise statement
  4767. \section{The raise statement}
  4768. The \var{raise} statement is as follows:
  4769. \input{syntax/raise.syn}
  4770. This statement will raise an exception. If it is specified, the exception
  4771. instance must be an initialized instance of a class, which is the raise
  4772. type. The address exception is optional. If itis not specified, the compiler
  4773. will provide the address by itself.
  4774. If the exception instance is omitted, then the current exception is
  4775. re-raised. This construct can only be used in an exception handling
  4776. block (see further).
  4777. \begin{remark} Control {\em never} returns after an exception block. The
  4778. control is transferred to the first \var{try...finally} or
  4779. \var{try...except} statement that is encountered when unwinding the stack.
  4780. If no such statement is found, the \fpc Run-Time Library will generate a
  4781. run-time error 217 (see also \sees{exceptclasses}).
  4782. \end{remark}
  4783. As an example: The following division checks whether the denominator is
  4784. zero, and if so, raises an exception of type \var{EDivException}
  4785. \begin{verbatim}
  4786. Type EDivException = Class(Exception);
  4787. Function DoDiv (X,Y : Longint) : Integer;
  4788. begin
  4789. If Y=0 then
  4790. Raise EDivException.Create ('Division by Zero would occur');
  4791. Result := X Div Y;
  4792. end;
  4793. \end{verbatim}
  4794. The class \var{Exception} is defined in the \file{Sysutils} unit of the rtl.
  4795. (\sees{exceptclasses})
  4796. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4797. % The try...except statement
  4798. \section{The try...except statement}
  4799. A \var{try...except} exception handling block is of the following form :
  4800. \input{syntax/try.syn}
  4801. If no exception is raised during the execution of the \var{statement list},
  4802. then all statements in the list will be executed sequentially, and the
  4803. except block will be skipped, transferring program flow to the statement
  4804. after the final \var{end}.
  4805. If an exception occurs during the execution of the \var{statement list}, the
  4806. program flow will be transferred to the except block. Statements in the
  4807. statement list between the place where the exception was raised and the
  4808. exception block are ignored.
  4809. In the exception handling block, the type of the exception is checked,
  4810. and if there is an exception handler where the class type matches the
  4811. exception object type, or is a parent type of
  4812. the exception object type, then the statement following the corresponding
  4813. \var{Do} will be executed. The first matching type is used. After the
  4814. \var{Do} block was executed, the program continues after the \var{End}
  4815. statement.
  4816. The identifier in an exception handling statement is optional, and declares
  4817. an exception object. It can be used to manipulate the exception object in
  4818. the exception handling code. The scope of this declaration is the statement
  4819. block foillowing the \var{Do} keyword.
  4820. If none of the \var{On} handlers matches the exception object type, then the
  4821. statement list after \var{else} is executed. If no such list is
  4822. found, then the exception is automatically re-raised. This process allows
  4823. to nest \var{try...except} blocks.
  4824. If, on the other hand, the exception was caught, then the exception object is
  4825. destroyed at the end of the exception handling block, before program flow
  4826. continues. The exception is destroyed through a call to the object's
  4827. \var{Destroy} destructor.
  4828. As an example, given the previous declaration of the \var{DoDiv} function,
  4829. consider the following
  4830. \begin{verbatim}
  4831. Try
  4832. Z := DoDiv (X,Y);
  4833. Except
  4834. On EDivException do Z := 0;
  4835. end;
  4836. \end{verbatim}
  4837. If \var{Y} happens to be zero, then the DoDiv function code will raise an
  4838. exception. When this happens, program flow is transferred to the except
  4839. statement, where the Exception handler will set the value of \var{Z} to
  4840. zero. If no exception is raised, then program flow continues past the last
  4841. \var{end} statement.
  4842. To allow error recovery, the \var{Try ... Finally} block is supported.
  4843. A \var{Try...Finally} block ensures that the statements following the
  4844. \var{Finally} keyword are guaranteed to be executed, even if an exception
  4845. occurs.
  4846. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4847. % The try...finally statement
  4848. \section{The try...finally statement}
  4849. A \var{Try..Finally} statement has the following form:
  4850. \input{syntax/finally.syn}
  4851. If no exception occurs inside the \var{statement List}, then the program
  4852. runs as if the \var{Try}, \var{Finally} and \var{End} keywords were not
  4853. present.
  4854. If, however, an exception occurs, the program flow is immediatly
  4855. transferred from the point where the excepion was raised to the first
  4856. statement of the \var{Finally statements}.
  4857. All statements after the finally keyword will be executed, and then
  4858. the exception will be automatically re-raised. Any statements between the
  4859. place where the exception was raised and the first statement of the
  4860. \var{Finally Statements} are skipped.
  4861. As an example consider the following routine:
  4862. \begin{verbatim}
  4863. Procedure Doit (Name : string);
  4864. Var F : Text;
  4865. begin
  4866. Try
  4867. Assign (F,Name);
  4868. Rewrite (name);
  4869. ... File handling ...
  4870. Finally
  4871. Close(F);
  4872. end;
  4873. \end{verbatim}
  4874. If during the execution of the file handling an execption occurs, then
  4875. program flow will continue at the \var{close(F)} statement, skipping any
  4876. file operations that might follow between the place where the exception
  4877. was raised, and the \var{Close} statement.
  4878. If no exception occurred, all file operations will be executed, and the file
  4879. will be closed at the end.
  4880. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4881. % Exception handling nesting
  4882. \section{Exception handling nesting}
  4883. It is possible to nest \var{Try...Except} blocks with \var{Try...Finally}
  4884. blocks. Program flow will be done according to a \var{lifo} (last in, first
  4885. out) principle: The code of the last encountered \var{Try...Except} or
  4886. \var{Try...Finally} block will be executed first. If the exception is not
  4887. caught, or it was a finally statement, program flow will be transferred to
  4888. the last-but-one block, {\em ad infinitum}.
  4889. If an exception occurs, and there is no exception handler present, then a
  4890. runerror 217 will be generated. When using the \file{sysutils} unit, a default
  4891. handler is installed which will show the exception object message, and the
  4892. address where the exception occurred, after which the program will exit with
  4893. a \var{Halt} instruction.
  4894. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4895. % Exception classes
  4896. \section{Exception classes}
  4897. \label{se:exceptclasses}
  4898. The \file{sysutils} unit contains a great deal of exception handling.
  4899. It defines the following exception types:
  4900. \begin{verbatim}
  4901. Exception = class(TObject)
  4902. private
  4903. fmessage : string;
  4904. fhelpcontext : longint;
  4905. public
  4906. constructor create(const msg : string);
  4907. constructor createres(indent : longint);
  4908. property helpcontext : longint read fhelpcontext write fhelpcontext;
  4909. property message : string read fmessage write fmessage;
  4910. end;
  4911. ExceptClass = Class of Exception;
  4912. { mathematical exceptions }
  4913. EIntError = class(Exception);
  4914. EDivByZero = class(EIntError);
  4915. ERangeError = class(EIntError);
  4916. EIntOverflow = class(EIntError);
  4917. EMathError = class(Exception);
  4918. \end{verbatim}
  4919. The sysutils unit also installs an exception handler. If an exception is
  4920. unhandled by any exception handling block, this handler is called by the
  4921. Run-Time library. Basically, it prints the exception address, and it prints
  4922. the message of the Exception object, and exits with a exit code of 217.
  4923. If the exception object is not a descendent object of the \var{Exception}
  4924. object, then the class name is printed instead of the exception message.
  4925. It is recommended to use the \var{Exception} object or a descendant class for
  4926. all \var{raise} statements, since then the message field of the
  4927. exception object can be used.
  4928. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4929. % Using Assembler
  4930. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4931. \chapter{Using assembler}
  4932. \fpc supports the use of assembler in code, but not inline
  4933. assembler macros. To have more information on the processor
  4934. specific assembler syntax and its limitations, see the \progref.
  4935. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4936. % Assembler statements
  4937. \section{Assembler statements }
  4938. The following is an example of assembler inclusion in pascal code.
  4939. \begin{verbatim}
  4940. ...
  4941. Statements;
  4942. ...
  4943. Asm
  4944. the asm code here
  4945. ...
  4946. end;
  4947. ...
  4948. Statements;
  4949. \end{verbatim}
  4950. The assembler instructions between the \var{Asm} and \var{end} keywords will
  4951. be inserted in the assembler generated by the compiler.
  4952. Conditionals can be used ib assembler, the compiler will recognise it,
  4953. and treat it as any other conditionals.
  4954. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  4955. % Assembler procedures and functions
  4956. \section{Assembler procedures and functions}
  4957. Assembler procedures and functions are declared using the
  4958. \var{Assembler} directive. This permits the code generator to make a number
  4959. of code generation optimizations.
  4960. The code generator does not generate any stack frame (entry and exit
  4961. code for the routine) if it contains no local variables and no
  4962. parameters. In the case of functions, ordinal values must be returned
  4963. in the accumulator. In the case of floating point values, these depend
  4964. on the target processor and emulation options.
  4965. %
  4966. % The index.
  4967. %
  4968. \printindex
  4969. \end{document}