ref.tex 194 KB

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