translation.html 103 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
  2. <html><head>
  3. <title>pas2js - Translation of Pascal (Delphi/FPC) programs to JavaScript</title>
  4. <meta name="description" content="Translation of Pascal (Delphi/FPC) programs to JavaScript">
  5. <meta name="keywords" content="translation,program,Delphi,Pascal,javascript,pas2js">
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <style type="text/css">
  8. body {
  9. padding: 20px;
  10. margin-left: 20px;
  11. }
  12. table.sample th {
  13. background-color: #cccccc;
  14. font: 120% gelvetica,arial,tahoma;
  15. }
  16. table.sample pre {
  17. color: blue;
  18. }
  19. table.sample td {
  20. padding-left: 20px;
  21. padding-right: 20px;
  22. }
  23. .section {
  24. padding-bottom: 1em;
  25. }
  26. </style>
  27. </head>
  28. <body>
  29. <div id="head">
  30. </div>
  31. <div class="section">
  32. <h2>Overview</h2>
  33. <a href="#about">About pas2js</a><br>
  34. <a href="#commandlineparameters">Command line parameters</a><br>
  35. <a href="#mode">Delphi and ObjFPC mode</a><br>
  36. <a href="#modules">Translating modules</a><br>
  37. <a href="#variables">Translating variables</a><br>
  38. <a href="#string">Translating string</a><br>
  39. <a href="#resourcestrings">Translating resourcestrings</a><br>
  40. <a href="#currency">Translating currency</a><br>
  41. <a href="#types">Translating types</a><br>
  42. <a href="#pointer">Translating pointer</a><br>
  43. <a href="#record">Translating record</a><br>
  44. <a href="#functions">Translating functions</a><br>
  45. <a href="#anonymousfunctions">Translating anonymous functions</a><br>
  46. <a href="#passbyref">Translating passing a parameter by reference</a><br>
  47. <a href="#nested functions">Translating nested functions</a><br>
  48. <a href="#forloop">Translating for-loop</a><br>
  49. <a href="#repeatuntil">Translating repeat..until</a><br>
  50. <a href="#whiledo">Translating while..do</a><br>
  51. <a href="#withdo">Translating with..do</a><br>
  52. <a href="#enums">Translating enums</a><br>
  53. <a href="#sets">Translating sets</a><br>
  54. <a href="#array">Translating array type</a><br>
  55. <a href="#class">Translating class type</a><br>
  56. <a href="#classof">Translating class-of type</a><br>
  57. <a href="#tobjectfree">Translating TObject.Free</a><br>
  58. <a href="#classinterfaces">Translating class interfaces</a><br>
  59. <a href="#helpers">Translating helpers</a><br>
  60. <a href="#attributes">Translating attributes</a><br>
  61. <a href="#tryfinally">Translating try..finally</a><br>
  62. <a href="#tryexcept">Translating try..except</a><br>
  63. <a href="#enumerators">Translating enumerators</a><br>
  64. <a href="#functiontype">Translating function types</a><br>
  65. <a href="#absolute">Translating var modifier absolute</a><br>
  66. <a href="#assert">Translating assert()</a><br>
  67. <a href="#dispatch">Dispatch messages</a><br>
  68. <a href="#calljavascript">Calling JavaScript from Pascal</a><br>
  69. <a href="#asm">The asm block</a><br>
  70. <a href="#assembler">The procedure modifier assembler</a><br>
  71. <a href="#externalproc">The procedure modifier external</a><br>
  72. <a href="#varargs">The procedure modifier varargs</a><br>
  73. <a href="#externalvar">The var modifier external</a><br>
  74. <a href="#externalmembers">The external modifier of class members</a><br>
  75. <a href="#externalclass">External classes</a><br>
  76. <a href="#externalclassancestor">External class as ancestor</a><br>
  77. <a href="#jsvalue">The JSValue type</a><br>
  78. <a href="#bracketaccessor">Accessing JS object properties with the bracket accessor</a><br>
  79. <a href="#rtti">RTTI - Run Time Type Information</a><br>
  80. <a href="#compilerdirectives">Compiler directives</a><br>
  81. <a href="#othersupportedelements">Other supported Pascal elements</a><br>
  82. <a href="#notsupportedelements">Not supported elements</a><br>
  83. <a href="#sourcemaps">Creating source maps</a><br>
  84. </div>
  85. <div class="section">
  86. <h2 id="about">About pas2js</h2>
  87. pas2js is a compiler/transpiler to translate programs written in Pascal (subset of Delphi/ObjFPC syntax)
  88. to JavaScript.<br>
  89. The goal is to use strong typing, while still be able to use low level whenever you choose.<br>
  90. The compiled Pascal functions can be used in DOM events or called by JavaScript.<br>
  91. pas2js is written completely in FPC, runs on many platforms like Windows, Mac and Linux and more.
  92. It is built modular consisting of the following parts:
  93. <ul>
  94. <li>file cache - loading, caching files, converting to UTF-8</li>
  95. <li>file resolver - handling search paths, finding used units and include files</li>
  96. <li>scanner - reading tokens, handling compiler directives like $IfDef and $Include</li>
  97. <li>parser - reading the tokens, checking syntax, creating Pascal nodes</li>
  98. <li>resolver - resolving references, type checking and checking duplicate identifiers</li>
  99. <li>use analyzer - finding unused identifiers, emit hints and warning</li>
  100. <li>converter - translating Pascal nodes into JavaScript nodes</li>
  101. <li>compiler - handling config files, parameters, compiling recursively all used units, writes js</li>
  102. <li>command line interface - a small wrapper to embed the compiler into a console program</li>
  103. <li>library and interface - a small wrapper to embed the compiler into a library</li>
  104. </ul>
  105. Each part is tested separately and is used by other FPC tools as well. For example
  106. the scanner and parser are used by fpdoc too. Thus they are tested and extended by other
  107. programmers, reducing greatly the work for developing pas2js. Consistency is kept by
  108. several test suites, containing thousands of tests.
  109. </div>
  110. <div class="section">
  111. Note: The modular structure allows to compile any parts or the whole compiler into an IDE addon (not yet started).
  112. </div>
  113. <div class="section">
  114. <h2 id="commandlineparameters">Command line parameters</h2>
  115. Most parameters work the same as their FPC equivalent. pas2js has some options of its own (see -J options).
  116. <pre>
  117. Usage: pas2js &lt;your.pas&gt;
  118. Options:
  119. Put + after a boolean switch option to enable it, - to disable it
  120. @&lt;x&gt; : Read compiler options from file &lt;x&gt; in addition to the default pas2js.cfg
  121. -B : Rebuild all
  122. -d&lt;x&gt; : Defines the symbol &lt;x&gt;. Optional: -d&lt;x&gt;:=&lt;value&gt;
  123. -i&lt;x&gt; : Write information and halt. &lt;x&gt; is a combination of the following:
  124. -iD : Write compiler date
  125. -iSO : Write compiler OS
  126. -iSP : Write compiler host processor
  127. -iTO : Write target platform
  128. -iTP : Write target processor
  129. -iV : Write short compiler version
  130. -iW : Write full compiler version
  131. -ic : Write list of supported JS processors usable by -P&lt;x&gt;
  132. -io : Write list of supported optimizations usable by -Oo&lt;x&gt;
  133. -it : Write list of supported targets usable by -T&lt;x&gt;
  134. -iJ : Write list of supported JavaScript identifiers -JoRTL-&lt;x&gt;
  135. -C&lt;x&gt; : Code generation options. &lt;x&gt; is a combination of the following letters:
  136. o : Overflow checking
  137. r : Range checking
  138. R : Object checks. Verify method calls and object type casts.
  139. -F... Set file names and paths:
  140. -Fe&lt;x&gt; : Redirect output to file &lt;x&gt;. UTF-8 encoded.
  141. -FE&lt;x&gt; : Set main output path to &lt;x&gt;
  142. -Fi&lt;x&gt; : Add &lt;x&gt; to include paths
  143. -FN&lt;x&gt; : add &lt;x&gt; to namespaces. Namespaces with trailing - are removed.
  144. Delphi calls this flag "unit scope names".
  145. -Fu&lt;x&gt; : Add &lt;x&gt; to unit paths
  146. -FU&lt;x&gt; : Set unit output path to &lt;x&gt;
  147. -I&lt;x&gt; : Add &lt;x&gt; to include paths, same as -Fi
  148. -J... Extra options of pas2js
  149. -Jc : Write all JavaScript concatenated into the output file
  150. -Je&lt;x&gt; : Encode messages as &lt;x&gt;.
  151. -Jeconsole : Console codepage. Default.
  152. -Jesystem : System codepage. On non Windows console and system are the same.
  153. -Jeutf-8 : Unicode UTF-8. Default when using -Fe.
  154. -JeJSON : Output compiler messages as JSON. Logo etc are outputted as-is.
  155. -Ji&lt;x&gt; : Insert JS file &lt;x&gt; into main JS file. E.g. -Jirtl.js. Can be given multiple times.
  156. -Jl : lower case identifiers
  157. -Jm : generate source maps
  158. -Jmsourceroot=&lt;x&gt; : use x as "sourceRoot", prefix URL for source file names.
  159. -Jmbasedir=&lt;x&gt; : write source file names relative to directory x, default is map file folder.
  160. -Jminclude : include Pascal sources in source map.
  161. -Jmabsolute: store absolute filenames, not relative.
  162. -Jmxssiheader : start source map with XSSI protection )]}.
  163. -Jm- : disable generating source maps
  164. -Jo&lt;x&gt; : Enable or disable extra option. The x is case insensitive:
  165. -JoSearchLikeFPC : search source files like FPC, default: search case insensitive.
  166. -JoUseStrict : add "use strict" to modules, default.
  167. -JoCheckVersion-: do not add rtl version check, default. (since 1.1)
  168. -JoCheckVersion=main: insert rtl version check into main. (since 1.1)
  169. -JoCheckVersion=system: insert rtl version check into system unit init. (since 1.1)
  170. -JoCheckVersion=unit: insert rtl version check into every unit init. (since 1.1)
  171. -JoRTL-&lt;x&gt;=&lt;y&gt;: set RTL identifier x to value y. See -iJ. (since 1.1)
  172. -Jpcmd&lt;command&gt; : Run postprocessor. For each generated js execute
  173. command passing the js as stdin and read the new js from stdout.
  174. This option can be added multiple times to call several
  175. postprocessors in succession.
  176. -Ju&lt;x&gt; : Add &lt;x&gt; to foreign unit paths. Foreign units are not compiled.
  177. -l : Write logo
  178. -MDelphi: Delphi 7 compatibility mode
  179. -MObjFPC: FPC's Object Pascal compatibility mode (default)
  180. -NS&lt;x&gt; : obsolete: add &lt;x&gt; to namespaces. Same as -FN&lt;x&gt;
  181. -n : Do not read the default config files
  182. -o&lt;x&gt; : Change main JavaScript file to &lt;x&gt;, "." means stdout
  183. -O&lt;x&gt; : Optimizations:
  184. -O- : Disable optimizations
  185. -O1 : Level 1 optimizations (quick and debugger friendly)
  186. -Oo&lt;x&gt; : Enable or disable optimization. The x is case insensitive:
  187. -OoEnumNumbers[-] : write enum values as number instead of name. Default in -O1.
  188. -OoRemoveNotUsedPrivates[-] : Default is enabled
  189. -OoRemoveNotUsedDeclarations[-] : Default enabled for programs with -Jc
  190. -OoRemoveNotUsedPublished[-] : Default is disabled
  191. -P&lt;x&gt; : Set target processor. Case insensitive:
  192. -Pecmascript5 : default
  193. -Pecmascript6
  194. -S&lt;x&gt; : Syntax options. &lt;x&gt; is a combination of the following letters:
  195. a : Turn on assertions
  196. c : Support operators like C (*=,+=,/= and -=)
  197. d : Same as -Mdelphi
  198. m : Enables macro replacements
  199. 2 : Same as -Mobjfpc (default)
  200. -SI&lt;x&gt; : Set interface style to &lt;x&gt;
  201. -SIcom : COM, reference counted interface (default)
  202. -SIcorba : CORBA interface
  203. -T&lt;x&gt; : Set target platform, case insensitive.
  204. -Tbrowser : default
  205. -Tnodejs : add pas.run(), includes -Jc
  206. -u&lt;x&gt; : Undefines the symbol &lt;x&gt;
  207. -v&lt;x&gt; : Be verbose. &lt;x&gt; is a combination of the following letters:
  208. e : Show errors (default)
  209. w : Show warnings
  210. n : Show notes
  211. h : Show hints
  212. i : Show info
  213. l : Show line numbers, needs -vi
  214. a : Show everything
  215. 0 : Show nothing (except errors)
  216. b : Show file names with full path
  217. c : Show conditionals
  218. t : Show tried/used files
  219. d : Show debug notes and info, enables -vni
  220. q : Show message numbers
  221. x : Show used tools
  222. v : Write pas2jsdebug.log with lots of debugging info
  223. z : Write messages to stderr, -o. still uses stdout.
  224. -vm&lt;x&gt;,&lt;y&gt;: Do not show messages numbered &lt;x&gt; and &lt;y&gt;.
  225. -? : Show this help
  226. -h : Show this help
  227. </pre>
  228. </div>
  229. <div class="section">
  230. <h2 id="mode">Delphi and ObjFPC mode</h2>
  231. <h3>Delphi mode</h3>
  232. <ul>
  233. <li>Defines macro <i>DELPHI</i></li>
  234. <li>Assigning a function to a function type variable does not require the @ operator.
  235. For example, you can write either <i>OnGetThing:=GetValue;</i> or <i>OnGetThing:=@GetValue;</i>.</li>
  236. <li>A function type variable reference without brackets is treated as a call.
  237. For example: If <i>OnGetThing</i> is a variable of type <i>function: integer</i>
  238. you can write: <i>If OnGetThing=3 then ;</i>.</li>
  239. <li>You must use the @@ operator to get the procedure address (i.e. JS reference) of a procedure type variable.
  240. For example instead of <i>If OnClick=nil then ;</i> you must use <i>if @@OnClick=nil then ;</i>.</li>
  241. <li>Every procedure/method overload needs the 'overload' modifier.</li>
  242. </ul>
  243. <h3>ObjFPC mode</h3>
  244. This the default mode of pas2js and is generally more strict than the Delphi mode, and allows some more operations.
  245. <ul>
  246. <li>Defines macro <i>OBJFPC</i></li>
  247. <li>Assigning a function to a function type variable requires the @ operator.
  248. For example: <i>OnGetThing:=@GetValue;</i>.</li>
  249. <li>A function type variable always needs brackets to be called.
  250. For example: If <i>OnGetThing</i> is a variable of type <i>function: integer</i>
  251. then this is allowed: <i>If OnGetThing()=3 then ;</i>.
  252. While this gives an error: <i>If OnGetThing=3 then ;</i>.</li>
  253. <li>You can compare a procedure type with <i>nil</i>.
  254. For example <i>If OnClick=nil then ;</i>.</li>
  255. <li>You can compare a procedure type with a procedure address (i.e. JS reference).
  256. For example <i>If OnClick=@OnFormClick then ;</i>.</li>
  257. <li>The procedure modifier 'overload' can be omitted when all overloads are
  258. in one scope, e.g. a unit or a class. And if one procedure has such modifier
  259. all procedures with same name and in same scope are overloads as well.</li>
  260. </ul>
  261. </div>
  262. <div class="section">
  263. <h2 id="modules">Translating modules</h2>
  264. A Pascal Program is translated into the following JavaScript structure:
  265. <table class="sample">
  266. <tbody>
  267. <tr>
  268. <th>Pascal</th>
  269. <th>JavaScript Structure, not code!</th>
  270. </tr>
  271. <tr>
  272. <td>
  273. <pre>Program &lt;unitname&gt;;
  274. Implementation
  275. [implementation section]
  276. Begin
  277. [main code]
  278. End.
  279. </pre>
  280. </td>
  281. <td>
  282. <pre>pas.&lt;program&gt;={
  283. [implementation section],
  284. $main: function() {
  285. [main code]
  286. }
  287. };
  288. </pre>
  289. </td>
  290. </tr>
  291. </tbody>
  292. </table>
  293. </div>
  294. <div class="section">
  295. A Pascal Unit is translated into the following JavaScript structure:
  296. <table class="sample">
  297. <tbody>
  298. <tr>
  299. <th>Pascal</th>
  300. <th>JavaScript Structure, not code!</th>
  301. </tr>
  302. <tr>
  303. <td>
  304. <pre>Unit &lt;unitname&gt;;
  305. Interface
  306. [interface section]
  307. Implementation
  308. [implementation section]
  309. Initialization
  310. [initialization section]
  311. End.
  312. </pre>
  313. </td>
  314. <td>
  315. <pre>pas.&lt;unitname&gt;={
  316. [interface section],
  317. $impl: {
  318. [implementation section],
  319. },
  320. $init: function() {
  321. [initialization section]
  322. }
  323. };
  324. </pre>
  325. </td>
  326. </tr>
  327. </tbody>
  328. </table>
  329. Note: The <b>finalization</b> section is not supported by pas2js.<br>
  330. </div>
  331. <div class="section">
  332. To create and initialize the units in topological order the compiler translates
  333. an Unit to the following JavaScript code:
  334. <table class="sample">
  335. <tbody>
  336. <tr>
  337. <th>Pascal</th>
  338. <th>JavaScript</th>
  339. </tr>
  340. <tr>
  341. <td>
  342. <pre>Unit &lt;unitname&gt;;
  343. Interface
  344. [interface section]
  345. Implementation
  346. [implementation section]
  347. Initialization
  348. [initialization section]
  349. End.
  350. </pre>
  351. </td>
  352. <td>
  353. <pre>rtl.module('&lt;unitname&gt;',
  354. ['system',...other used units of the interface section...],
  355. function(){
  356. [interface section]
  357. this.$init=function(){
  358. [initialization section]
  359. };
  360. },
  361. [...used units of the implementation section],
  362. function(){
  363. [implementation section]
  364. }};
  365. </pre>
  366. </td>
  367. </tr>
  368. </tbody>
  369. </table>
  370. </div>
  371. <div class="section">
  372. Here is a more detailed example to make it more clear:
  373. <table class="sample">
  374. <tbody>
  375. <tr>
  376. <th>Pascal</th>
  377. <th>JavaScript</th>
  378. </tr>
  379. <tr>
  380. <td>
  381. <pre>Unit MyModule;
  382. Interface
  383. Uses Sysutils;
  384. var
  385. dIntf: double;
  386. sIntf: string = 'abc';
  387. procedure MyIntfProc;
  388. Implementation
  389. Uses Classes;
  390. Var dImpl:double;
  391. Procedure MyIntfProc;
  392. Begin
  393. dImpl:=dIntf;
  394. End;
  395. Procedure MyImplProc;
  396. Begin
  397. dImpl:=dIntf;
  398. End;
  399. Initialization
  400. End.
  401. </pre>
  402. </td>
  403. <td>
  404. <pre>rtl.module("MyModule",
  405. ["System","SysUtils"],
  406. function(){
  407. var $mod = this;
  408. var $impl = $mod.$impl;
  409. this.dIntf = 0.0;
  410. this.sIntf = "abc";
  411. this.MyIntfProc = function(){
  412. $impl.dImpl = $mod.dIntf;
  413. };
  414. this.$init = function() {
  415. };
  416. },
  417. ["Classes"],
  418. function(){
  419. var $mod = this;
  420. var $impl = $mod.$impl;
  421. $impl.dImpl = 0.0;
  422. $impl.MyImplProc = function() {
  423. $impl.dImpl = $mod.dIntf;
  424. };
  425. });
  426. </pre>
  427. </td>
  428. </tr>
  429. </tbody>
  430. </table>
  431. Notes:
  432. <ul>
  433. <li>Unit <i>System</i> is always loaded implicitely.</li>
  434. <li>References to other units are translated to full path. For example
  435. <i>TObject</i> is translated to <i>pas.system.TObject</i></li>
  436. <li>References to dotted unitnames, aka units with namespaces are translated
  437. to <i>pas["namespace.unitname"]</i>.</li>
  438. </ul>
  439. </div>
  440. <div class="section">
  441. <h2 id="variables">Translating variables</h2>
  442. Variables are converted without type, because JavaScript lacks a clear type.
  443. They are however always initialized, which helps JavaScript engines to optimize.
  444. <table class="sample">
  445. <tbody>
  446. <tr>
  447. <th>Pascal</th>
  448. <th>JavaScript</th>
  449. </tr>
  450. <tr>
  451. <td>
  452. <pre>Unit MyModule;
  453. Interface
  454. Uses Classes,Forms;
  455. const
  456. c1:integer=3;
  457. c2 = 'abc';
  458. c3 = 234;
  459. c4 = 12.45;
  460. c5 = nil;
  461. var
  462. v1:string;
  463. v2,v3:double;
  464. v4:byte=0;
  465. v5:TForm;
  466. v6:TIdentMapEntry;
  467. v7:string='abcäöü';
  468. v8:char='c';
  469. v9:array of byte;
  470. Implementation
  471. End.
  472. </pre>
  473. </td>
  474. <td>
  475. <pre>rtl.module("MyModule",
  476. ["System","Classes","Forms"],
  477. function(){
  478. this.c1 = 3;
  479. this.c2 = "abc";
  480. this.c3 = 234;
  481. this.c4 = 12.45;
  482. this.c5 = null;
  483. this.v1 = "";
  484. this.v2 = 0.0;
  485. this.v3 = 0.0;
  486. this.v4 = 0;
  487. this.v5 = null;
  488. this.v6 = new pas.Classes.TIdentMapEntry();
  489. this.v7 = "abcäöü";
  490. this.v8 = "c";
  491. this.v9 = [];
  492. },
  493. []);
  494. </pre>
  495. </td>
  496. </tr>
  497. </tbody>
  498. </table>
  499. Notes:
  500. <ul>
  501. <li>Type casting a <i>boolean</i> to <i>integer</i>, gives <i>0</i> for <i>false</i> and <i>1</i> for <i>true</i>.</li>
  502. <li>Type casting an <i>integer</i> to <i>boolean</i>, gives <i>false</i> for <i>0</i> and <i>true</i> otherwise.</li>
  503. <li>A <b>char</b> is translated to a JS string, because JS lacks a native char type.</li>
  504. <li>A <b>char</b> is a single JS char code. An UTF-16 codepoint can contain one or two <b>char</b>.</li>
  505. <li><b>Integers overflows</b> at runtime differ from Delphi/FPC, due to the double format.
  506. For example adding <i>var i: byte = 200; ... i:=i+100;</i> will result in
  507. <i>i=300</i> instead of <i>i=44</i> as in Delphi/FPC.
  508. When range checking <i>{$R+}</i> is enabled <i>i:=300</i> will raise an ERangeError.</li>
  509. <li><b>type cast integer to integer</b>, e.g. <i>byte(aLongInt)</i>
  510. <ul>
  511. <li>with range checking enabled: error if outside range</li>
  512. <li>without range checking: emulates the FPC/Delphi behaviour:
  513. e.g. <i>byte(value)</i> translates to <i>value &amp; 0xff</i>,
  514. <i>shortint(value)</i> translates to <i>value &amp; 0xff &lt;&lt;24 &gt;&gt; 24.</i></li>
  515. </ul>
  516. </li>
  517. <li>The <b>mod-operator</b> works 32-bit signed in JS.</li>
  518. </ul>
  519. </div>
  520. <div class="section">
  521. <h2 id="string">Translating string</h2>
  522. Strings are translated to JavaScript strings. They are initialized with ""
  523. and are never <b>null</b>.<br>
  524. There are no <i>ShortString, AnsiString or RawByteString</i>.
  525. <i>Unicodestring</i> and <i>Widestring</i> are alias of <i>String</i>.<br>
  526. JavaScript strings are immutable, which means
  527. that changing a single character in a string, creates a new string. So a <i>s[2]:='c';</i>
  528. is a slow operation in pas2js compared to Delphi/FPC.<br>
  529. Although pas2js creates .js files encoded as UTF-8 with BOM, JavaScript strings are
  530. UTF-16 at runtime. Keep in mind that one UTF-16 codepoint can need two <i>char</i>,
  531. and a visible glyph can need several codepoints. Same as in Delphi.
  532. </div>
  533. <div class="section">
  534. <h2 id="resourcestrings">Translating resourcestrings</h2>
  535. Resourcestrings are translated to JS objects with original (org) and current value.
  536. <table class="sample">
  537. <tbody>
  538. <tr>
  539. <th>Pascal</th>
  540. <th>JavaScript</th>
  541. </tr>
  542. <tr>
  543. <td>
  544. <pre>Unit MyModule;
  545. Interface
  546. resourcestring
  547. rsCompiler = 'pas2js';
  548. var
  549. s:string;
  550. Implementation
  551. initialization
  552. s:=rsCompiler;
  553. End.
  554. </pre>
  555. </td>
  556. <td>
  557. <pre>rtl.module("test1",["System"],function () {
  558. var $mod = this;
  559. this.s = "";
  560. $mod.$resourcestrings = {rsCompiler: {org: "pas2js"}};
  561. $mod.$init = function () {
  562. $mod.s = rtl.getResStr(pas.test1,"rsCompiler");
  563. };
  564. });
  565. </pre>
  566. </td>
  567. </tr>
  568. </tbody>
  569. </table>
  570. </div>
  571. <div class="section">
  572. <h2 id="currency">Translating currency</h2>
  573. <i>Currency</i> in Delphi/FPC is an int64 with a factor of 10000. This is
  574. translated to a double with factor 10000 and truncated.
  575. <ul>
  576. <li><i>CurA := 1.12345</i> -> <i>CurA = 11234</i></li>
  577. <li><i>CurA + CurB</i> -> <i>CurA + CurB</i></li>
  578. <li><i>CurA * CurB</i> -> <i>CurA * CurB/10000</i></li>
  579. <li><i>CurA / CurB</i> -> <i>Math.floor(CurA/CurB * 10000)</i></li>
  580. <li><i>CurA ^^ CurB</i> -> <i>Math.floor(Math.pow(CurA/10000,CurB/10000) * 10000)</i></li>
  581. <li><i>Currency + Double</i> -> <i>Currency + (Double*10000)</i></li>
  582. <li><i>Double := Currency</i> -> <i>Double = Currency/10000</i></li>
  583. <li><i>Currency := Double</i> -> <i>Currency = Math.floor(Double*10000)</i></li>
  584. <li><i>JSValue := Currency</i> -> <i>JSValue = Currency/10000</i></li>
  585. <li>Keep in mind that a double has only 54 bits for the number, so calculating
  586. values greater than 900,719,925,474 might give a different result than in Delphi/FPC.
  587. See SysUtils.MinCurrency/MaxCurrency</li>
  588. </ul>
  589. </div>
  590. <div class="section">
  591. <h2 id="types">Translating Types</h2>
  592. JavaScript type design has no declarative form, except for object types
  593. (so-called prototypes).
  594. That's why all the derivatives from simple Pascal types can not be translated.
  595. The compiler ensures type safety at compile time though, which is a big plus
  596. for using Pascal.<br>
  597. Complex Pascal types (classes, records, or arrays) are translated into
  598. JavaScript objects or arrays respectively.<br>
  599. </div>
  600. <div class="section">
  601. <h2 id="pointer">Translating pointer</h2>
  602. A <i>pointer</i> is translated to a JS reference. It can be assigned a class,
  603. a class instance, a class-of, an array, a procedure var, a method var, a @proc address,
  604. a @method address, or a pointer of record.
  605. There is no pointer arithmetic, i.e. no p+1, and no typed pointers,
  606. except for pointer of record.
  607. You can find out its type using the functions <i>isArray</i>,
  608. <i>isClass</i>, <i>isClassRef</i>, <i>isCallback</i>, etc of unit <i>JS</i>.
  609. </div>
  610. <div class="section">
  611. <h2 id="record">Translating record type</h2>
  612. A record is translated to a JavaScript object.
  613. <table class="sample">
  614. <tbody>
  615. <tr>
  616. <th>Pascal</th>
  617. <th>JS Pas2js 1.3</th>
  618. <th>JS Pas2js 1.2</th>
  619. </tr>
  620. <tr>
  621. <td>
  622. <pre>Unit MyModule;
  623. Interface
  624. Type
  625. TMyRecord = Record
  626. i: integer;
  627. s: string;
  628. d: TDateTime;
  629. End;
  630. Var
  631. r, s: TMyRecord;
  632. Implementation
  633. Initialization
  634. r.i := 123;
  635. r:=s;
  636. if r=s then ;
  637. End.
  638. </pre>
  639. </td>
  640. <td>
  641. <pre>rtl.module("MyModule",
  642. ["System"],
  643. function(){
  644. var $mod = this;
  645. rtl.recNewT($mod, "TMyRecord", function() {
  646. this.i = 0;
  647. this.s = "";
  648. this.d = 0.0;
  649. this.$eq = function (b) {
  650. return (this.i == b.i) &&
  651. (this.s == b.i) && (this.d == b.d);
  652. };
  653. this.$assign = function (s) {
  654. this.i = s.i;
  655. this.s = s.s;
  656. this.d = s.d;
  657. return this;
  658. };
  659. };
  660. this.r = this.TMyRecord.$new();
  661. $mod.$init = function() {
  662. $mod.r.i=123;
  663. $mod.r.$assign($mod.s);
  664. if ($mod.r.$eq($mod.s)) ;
  665. },
  666. },
  667. []);
  668. </pre>
  669. </td>
  670. <td>
  671. <pre>rtl.module("MyModule",
  672. ["System"],
  673. function(){
  674. var $mod = this;
  675. this.TMyRecord = function(s) {
  676. if (s){
  677. this.i = s.i;
  678. this.s = s.s;
  679. this.d = s.d;
  680. } else {
  681. this.i = 0;
  682. this.s = "";
  683. this.d = 0.0;
  684. };
  685. this.$equal = function (b) {
  686. return (this.i == b.i) &&
  687. (this.s == b.i) && (this.d == b.d);
  688. };
  689. };
  690. this.r = new this.TMyRecord();
  691. $mod.$init = function() {
  692. $mod.r.i=123;
  693. $mod.r = new $mod.TMyRecord($mod.s);
  694. if ($mod.r.$equal($mod.s)) ;
  695. },
  696. },
  697. []);
  698. </pre>
  699. </td>
  700. </tr>
  701. </tbody>
  702. </table>
  703. <ul>
  704. <li>The record variable creates a JavaScript object.</li>
  705. <li>Variant records are not supported.</li>
  706. <li>Supported: Assign, pass as argument, equal, not equal,
  707. array of record, pointer of record, const, default(), RTTI.</li>
  708. <li>Advanced record (since pas2js 1.3):
  709. <ul>
  710. <li>visibility private, strict private, public, default is public</li>
  711. <li>methods, class methods (must be static like in Delphi/FPC)</li>
  712. <li>class vars</li>
  713. <li>const fields</li>
  714. <li>property, class property, array property, default array property</li>
  715. <li>sub types</li>
  716. <li>constructor</li>
  717. <li>class constructor</li>
  718. </ul>
  719. </li>
  720. <li>Not yet implemented:
  721. <ul>
  722. <li>operator overloading</li>
  723. <li>reference counted interfaces as fields</li>
  724. <li>Interfaces as nested types</li>
  725. <li>default non array property</li>
  726. </ul>
  727. </li>
  728. <li>Until Pas2js 1.2 when assigning a record it is cloned, creating a new
  729. JS object. Since Pas2js 1.3 only values are copied,
  730. keeping the object, so pointer of record is compatible.</li>
  731. <li>Since record types are JS objects it is possible to typecast a record type
  732. to the JS Object, e.g. <i>TJSObject(TPoint)</i>.
  733. Note that you cannot typecast directly to a <i>TJSObject</i> descendant.
  734. You can use <i>TJSWindow(TJSObject(aRecord))</i>.</li>
  735. <li>A pointer of record is simply a reference.
  736. <ul>
  737. <li><i>p:=@r</i> translates to <i>p=r</i></li>
  738. <li><i>p^.x</i> becomes <i>p.x</i>.</li>
  739. <li><i>New(PointerOfRecord)</i> creates a new record</li>
  740. <li><i>Dispose(PointerOfRecord)</i> Sets the variable to null if possible.</li>
  741. </ul>
  742. </li>
  743. <li>Passing a record to an untyped arguments (e.g. ''TObject.Dispatch(var Msg)'')
  744. passes the record JS object directly, not creating a temporary reference object.</li>
  745. <li>Typecasting RecordType(UntypedArgument) returns the argument, i.e. no conversion.</li>
  746. </ul>
  747. </div>
  748. <div class="section">
  749. <h2 id="functions">Translating functions</h2>
  750. <table class="sample">
  751. <tbody>
  752. <tr>
  753. <th>Pascal</th>
  754. <th>JavaScript</th>
  755. </tr>
  756. <tr>
  757. <td>
  758. <pre>Unit MyModule;
  759. Interface
  760. Function DoubleIt(n: integer): integer;
  761. Implementation
  762. Function DoubleIt(n: integer): integer;
  763. Begin
  764. Result:=2*n;
  765. End;
  766. End.
  767. </pre>
  768. </td>
  769. <td>
  770. <pre>rtl.module("MyModule",
  771. ["System"],
  772. function(){
  773. this.DoubleIt = function(n){
  774. Result = 0;
  775. Result = 2*n;
  776. return Result;
  777. };
  778. },
  779. []);
  780. </pre>
  781. </td>
  782. </tr>
  783. </tbody>
  784. </table>
  785. Notes:
  786. <ul>
  787. <li>Local variables become local JavaScript variables: <i>var l = 0;</i>.</li>
  788. <li>Local constants become JavaScript variables in the unit/program implementation section.</li>
  789. <li>Local types are elevated to module.</li>
  790. <li>Overloaded functions are given an unique name by appending $1, $2, ...</li>
  791. <li>Supported: default values, const/var/out/default, FuncName:=</li>
  792. </ul>
  793. </div>
  794. <div class="section">
  795. <h2 id="passbyref">Translating passing a parameter by reference</h2>
  796. JavaScript lacks passing by reference. Instead a temporary object is created
  797. with a <i>get</i> and <i>set</i> function.
  798. That means changes within the procedure are immediately visible outside, compatible with Pascal.
  799. <table class="sample">
  800. <tbody>
  801. <tr>
  802. <th>Pascal</th>
  803. <th>JavaScript</th>
  804. </tr>
  805. <tr>
  806. <td>
  807. <pre>Program MyModule;
  808. Procedure DoubleIt(var n: integer);
  809. Begin
  810. n:=2*n;
  811. End;
  812. Function Doubling(n: integer): integer;
  813. Begin
  814. DoubleIt(n);
  815. Result:=n;
  816. End;
  817. Var
  818. i: integer = 7;
  819. Begin
  820. Doubling(i);
  821. End.
  822. </pre>
  823. </td>
  824. <td>
  825. <pre>rtl.module("program",
  826. ["System"],
  827. function(){
  828. var $mod = this;
  829. this.i = 7;
  830. this.DoubleIt = function(n){
  831. n.set(2*n.get());
  832. };
  833. this.Doubling = function(n){
  834. var Result = 0;
  835. DoubleIt({
  836. get:function(){
  837. return n
  838. },
  839. set:function(v){
  840. n=v;
  841. }
  842. });
  843. Result = n;
  844. return n;
  845. };
  846. $mod.$main = function(){
  847. Doubling($mod.i);
  848. }
  849. },
  850. []);
  851. </pre>
  852. </td>
  853. </tr>
  854. </tbody>
  855. </table>
  856. When the passed value is from another context, the context is passed too:
  857. <table class="sample">
  858. <tbody>
  859. <tr>
  860. <th>Pascal</th>
  861. <th>JavaScript</th>
  862. </tr>
  863. <tr>
  864. <td>
  865. <pre>Program MyModule;
  866. Procedure DoubleIt(var n: integer);
  867. Begin
  868. n:=2*n;
  869. End;
  870. Var
  871. i: integer = 7;
  872. Begin
  873. DoubleIt(i);
  874. End.
  875. </pre>
  876. </td>
  877. <td>
  878. <pre>rtl.module("program",
  879. ["System"],
  880. function(){
  881. var $mod = this;
  882. this.i = 7;
  883. this.DoubleIt = function(n){
  884. n.set(2*n.get());
  885. };
  886. $mod.$main = function(){
  887. DoubleIt({
  888. p:$mod,
  889. get:function(){
  890. return this.p.i
  891. },
  892. set:function(v){
  893. this.p.i=v;
  894. }
  895. });
  896. }
  897. },
  898. []);
  899. </pre>
  900. </td>
  901. </tr>
  902. </tbody>
  903. </table>
  904. Notes:
  905. <ul>
  906. <li>Contrary to Delphi/FPC it is allowed to pass a property to a </i>var/out</i> parameter.</li>
  907. </ul>
  908. </div>
  909. <div class="section">
  910. <h2 id="nested functions">Translating nested functions</h2>
  911. A nested function is translated to a local variable.
  912. <table class="sample">
  913. <tbody>
  914. <tr>
  915. <th>Pascal</th>
  916. <th>JavaScript</th>
  917. </tr>
  918. <tr>
  919. <td>
  920. <pre>Unit MyModule;
  921. Interface
  922. Function SumNNumbers(n, Adder: integer): integer;
  923. Implementation
  924. Function SumNNumbers(n, Adder: integer): integer;
  925. Function Add(k: integer): integer;
  926. Begin
  927. if k=1 then
  928. Result:=1
  929. else
  930. Result:=Add(k-1)+Adder;
  931. End;
  932. Begin
  933. Result:=Add(n);
  934. End;
  935. End.
  936. </pre>
  937. </td>
  938. <td>
  939. <pre>rtl.module("MyModule",
  940. ["System"],
  941. function(){
  942. this.DoubleIt = function(n,Adder){
  943. Result = 0;
  944. var Add = function(k) {
  945. Result = 0;
  946. if (k==1) {
  947. Result = 1;
  948. } else {
  949. Result = Add(k-1)+Adder;
  950. }
  951. return Result;
  952. };
  953. Result = Add(n);
  954. return Result;
  955. };
  956. },
  957. []);
  958. </pre>
  959. </td>
  960. </tr>
  961. </tbody>
  962. </table>
  963. Note: You can assign a nested procedure to a procedure variable. A nested
  964. procedure of a method can be assigned to a method variable.<br>
  965. JavaScript preserves the current local scope, including references to the
  966. local variables of parent functions. Local types and constants belong to the
  967. unit scope (singleton).<br>
  968. When a method has nested functions, the compiler adds a local var <i>Self</i>.
  969. </div>
  970. <div class="section">
  971. <h2 id="forloop">Translating for-loops</h2>
  972. The JavaScript for-loop executes the end expression every iteration, while
  973. Pascal only executes it once. Therefore a local variable is introduced.
  974. If the loop is not entered at all, the variable is not touched. If the loop
  975. was entered the variable contanis the last value.
  976. <table class="sample">
  977. <tbody>
  978. <tr>
  979. <th>Pascal</th>
  980. <th>JavaScript</th>
  981. </tr>
  982. <tr>
  983. <td>
  984. <pre>Unit MyModule;
  985. Interface
  986. Function SumNNumbers(n: integer): integer;
  987. Implementation
  988. Function SumNNumbers(n: integer): integer;
  989. Var
  990. i, j: integer;
  991. Begin
  992. j:=0;
  993. For i:=1 To n Do
  994. Begin
  995. j:=j+i;
  996. End;
  997. if i&lt;1 then j:=1;
  998. Result:=j;
  999. End;
  1000. End.
  1001. </pre>
  1002. </td>
  1003. <td>
  1004. <pre>rtl.module("MyModule",
  1005. ["System"],
  1006. function(){
  1007. this.SumNNumbers=function(n){
  1008. Result = 0;
  1009. j = 0;
  1010. for (var $l1 = 1, $le2 = n; $l1 &lt;= $le2; $l1++) {
  1011. i = $l1;
  1012. j = j + i;
  1013. };
  1014. if (i&lt;1) j=1;
  1015. Result = j;
  1016. return Result;
  1017. };
  1018. },
  1019. []);
  1020. </pre>
  1021. </td>
  1022. </tr>
  1023. </tbody>
  1024. </table>
  1025. Note: The after-loop decrement is only added if <i>i</i> is read after the loop.<br>
  1026. </div>
  1027. <div class="section">
  1028. <h2 id="repeatuntil">Translating repeat..until</h2>
  1029. The <i>repeat..until</i> is translated to a <i>do{}while()</i>.
  1030. <table class="sample">
  1031. <tbody>
  1032. <tr>
  1033. <th>Pascal</th>
  1034. <th>JavaScript</th>
  1035. </tr>
  1036. <tr>
  1037. <td>
  1038. <pre>Unit MyModule;
  1039. Interface
  1040. Function SumNNumbers(n: integer): integer;
  1041. Implementation
  1042. Function SumNNumbers(n: integer): integer;
  1043. Var
  1044. i, j: integer;
  1045. Begin
  1046. j:=0;
  1047. i:=0;
  1048. Repeat
  1049. i:=i+1;
  1050. j:=j+i;
  1051. Until i>=n;
  1052. Result:=j;
  1053. End;
  1054. End.
  1055. </pre>
  1056. </td>
  1057. <td>
  1058. <pre>rtl.module("MyModule",
  1059. ["System"],
  1060. function(){
  1061. this.SumNNumbers=function(n){
  1062. Result = 0;
  1063. j = 0;
  1064. i = 0;
  1065. do{
  1066. i = (i + 1);
  1067. j = (j + i);
  1068. } while (!(i>=n));
  1069. Result = j;
  1070. return Result;
  1071. };
  1072. },
  1073. []);
  1074. </pre>
  1075. </td>
  1076. </tr>
  1077. </tbody>
  1078. </table>
  1079. </div>
  1080. <div class="section">
  1081. <h2 id="whiledo">Translating while..do</h2>
  1082. <table class="sample">
  1083. <tbody>
  1084. <tr>
  1085. <th>Pascal</th>
  1086. <th>JavaScript</th>
  1087. </tr>
  1088. <tr>
  1089. <td>
  1090. <pre>Unit MyModule;
  1091. Interface
  1092. Function SumNNumbers(n: integer): integer;
  1093. Implementation
  1094. Function SumNNumbers(n: integer): integer;
  1095. Var
  1096. i, j: integer;
  1097. Begin
  1098. j:=0;
  1099. i:=0;
  1100. While i&lt;n Do Begin
  1101. i:=i+1;
  1102. j:=j+i;
  1103. End;
  1104. Result:=j;
  1105. End;
  1106. End.
  1107. </pre>
  1108. </td>
  1109. <td>
  1110. <pre>rtl.module("MyModule",
  1111. ["System"],
  1112. function(){
  1113. this.SumNNumbers=function(n){
  1114. var Result = 0;
  1115. var j = 0;
  1116. var i = 0;
  1117. while(i&lt;n){
  1118. i = (i + 1);
  1119. j = (j + i);
  1120. };
  1121. Result = j;
  1122. return Result;
  1123. };
  1124. },
  1125. []);
  1126. </pre>
  1127. </td>
  1128. </tr>
  1129. </tbody>
  1130. </table>
  1131. </div>
  1132. <div class="section">
  1133. <h2 id="casedo">Translating case..do</h2>
  1134. Although JavaScript has something similar in form of the "switch" statement,
  1135. it lacks ranges and is on current JS engines often slower than "if-else".
  1136. Therefore a case..of is translated to if..else.
  1137. <table class="sample">
  1138. <tbody>
  1139. <tr>
  1140. <th>Pascal</th>
  1141. <th>JavaScript</th>
  1142. </tr>
  1143. <tr>
  1144. <td>
  1145. <pre>Program MyModule;
  1146. Var
  1147. i: integer;
  1148. Begin
  1149. case i of
  1150. 1: ;
  1151. 2: i:=3;
  1152. else
  1153. i:=4;
  1154. end;
  1155. End.
  1156. </pre>
  1157. </td>
  1158. <td>
  1159. <pre>rtl.module("program",
  1160. ["System"],
  1161. function(){
  1162. var $mod = this;
  1163. this.i = 0;
  1164. $mod.$main=function(n){
  1165. $tmp1 = $mod.i;
  1166. if ($tmp1 == 1){
  1167. } else if ($tmp1 == 2) {
  1168. i=3;
  1169. } else {
  1170. i=4;
  1171. }
  1172. };
  1173. },
  1174. []);
  1175. </pre>
  1176. </td>
  1177. </tr>
  1178. </tbody>
  1179. </table>
  1180. </div>
  1181. <div class="section">
  1182. <h2 id="withdo">Translating with..do</h2>
  1183. JavaScript has a <b>with</b>, but it is slow and deprecated.
  1184. Instead a temporary variable is used:
  1185. <table class="sample">
  1186. <tbody>
  1187. <tr>
  1188. <th>Pascal</th>
  1189. <th>JavaScript</th>
  1190. </tr>
  1191. <tr>
  1192. <td>
  1193. <pre>Unit MyModule;
  1194. Interface
  1195. type
  1196. TClassA = class
  1197. i: integer;
  1198. end;
  1199. procedure DoIt;
  1200. Implementation
  1201. procedure DoIt;
  1202. begin
  1203. with TClassA.Create do
  1204. i:=3;
  1205. end;
  1206. End.
  1207. </pre>
  1208. </td>
  1209. <td>
  1210. <pre>rtl.module("MyModule",
  1211. ["System"],
  1212. function(){
  1213. var $mod = this;
  1214. rtl.createClass($mod, "TClassA", pas.System.TObject, function () {
  1215. this.$init = function () {
  1216. this.i = 0;
  1217. };
  1218. });
  1219. this.DoIt = function(){
  1220. var $with1 = $mod.TClassA.$create("Create");
  1221. $with1.i = 3;
  1222. };
  1223. },
  1224. []);
  1225. </pre>
  1226. </td>
  1227. </tr>
  1228. </tbody>
  1229. </table>
  1230. Note: If the with-expression is already a local variable no new variable is
  1231. created. This is Delphi/FPC compatible.
  1232. </div>
  1233. <div class="section">
  1234. <h2 id="enums">Translating enums</h2>
  1235. Enum values are translated to numbers. The enum type is translated to an
  1236. object containing a mapping from name to number and number to name.
  1237. <table class="sample">
  1238. <tbody>
  1239. <tr>
  1240. <th>Pascal</th>
  1241. <th>JavaScript</th>
  1242. </tr>
  1243. <tr>
  1244. <td>
  1245. <pre>Unit MyModule;
  1246. Interface
  1247. type
  1248. TMyEnum = (
  1249. Red,
  1250. Green,
  1251. Blue);
  1252. var
  1253. e: TMyEnum = Blue;
  1254. procedure DoIt;
  1255. Implementation
  1256. procedure DoIt;
  1257. begin
  1258. e := Green;
  1259. end;
  1260. End.
  1261. </pre>
  1262. </td>
  1263. <td>
  1264. <pre>rtl.module("MyModule",
  1265. ["System"],
  1266. function(){
  1267. var $mod = this;
  1268. this.TMyEnum = {
  1269. "0":"Red",
  1270. Red:0,
  1271. "1":"Green",
  1272. Green:1,
  1273. "2":"Blue",
  1274. Blue:2
  1275. };
  1276. this.e = $mod.TMyEnum.Blue;
  1277. this.DoIt = function(){
  1278. $mod.e = $mod.TMyEnum.Green;
  1279. };
  1280. },
  1281. []);
  1282. </pre>
  1283. </td>
  1284. </tr>
  1285. </tbody>
  1286. </table>
  1287. <ul>
  1288. <li>Supported: ord(), low(), high(), pred(), succ(), type cast number to enum.</li>
  1289. <li>With optimization level -O1 the compiler uses numbers instead of names.</li>
  1290. <li>Not yet implemented: custom values for enum values.</li>
  1291. </ul>
  1292. </div>
  1293. <div class="section">
  1294. <h2 id="sets">Translating sets</h2>
  1295. A set s is translated to a JavaScript object, where for each included enum
  1296. holds <i>s.enumvalue==true</i>.
  1297. This allows arbitrary large sets and the <i>in</i> operator is fast.
  1298. <table class="sample">
  1299. <tbody>
  1300. <tr>
  1301. <th>Pascal</th>
  1302. <th>JavaScript</th>
  1303. </tr>
  1304. <tr>
  1305. <td>
  1306. <pre>Unit MyModule;
  1307. Interface
  1308. type
  1309. TColor = (Red, Green, Blue);
  1310. TColors = set of TColor;
  1311. procedure DoIt;
  1312. Implementation
  1313. procedure DoIt;
  1314. var
  1315. c: TColor;
  1316. S, T: TColors;
  1317. b: boolean;
  1318. begin
  1319. S:=T;
  1320. b:=Red in S;
  1321. Include(S,Blue);
  1322. Exclude(S,Blue);
  1323. S:=S+T;
  1324. S:=S-[Red,c];
  1325. b:=c in [Red..Blue];
  1326. end;
  1327. End.
  1328. </pre>
  1329. </td>
  1330. <td>
  1331. <pre>rtl.module("MyModule",
  1332. ["System"],
  1333. function(){
  1334. var $mod = this;
  1335. this.TColor = {
  1336. "0":"Red",
  1337. Red:0,
  1338. "1":"Green",
  1339. Green:1,
  1340. "2":"Blue",
  1341. Blue:2
  1342. };
  1343. $mod.DoIt = function(){
  1344. var c = 0;
  1345. var S = {};
  1346. var T = {};
  1347. var b = false;
  1348. S = rtl.refSet(T);
  1349. b = $mod.TColor.Red in S;
  1350. S = rtl.includeSet(S,$mod.TColor.Blue);
  1351. S = rtl.excludeSet(S,$mod.TColor.Blue);
  1352. S = rtl.unionSet(S,T);
  1353. S = rtl.diffSet(S,rtl.createSet($mod.TColor.Red,c));
  1354. b = c in rtl.createSet(null,$mod.TColor.Red,$mod.TColor.Blue);
  1355. };
  1356. },
  1357. []);
  1358. </pre>
  1359. </td>
  1360. </tr>
  1361. </tbody>
  1362. </table>
  1363. <ul>
  1364. <li>Supported:
  1365. <ul>
  1366. <li>Include</li>
  1367. <li>Exclude</li>
  1368. <li>literal</li>
  1369. <li>literal range, e.g. <i>[EnumA..EnumB], ['a'..'z']</i></li>
  1370. <li>union +</li>
  1371. <li>difference -</li>
  1372. <li>intersect *</li>
  1373. <li>symmetrical difference >&lt;</li>
  1374. <li>equal =</li>
  1375. <li>unequal &lt;></li>
  1376. <li>subset &lt;=</li>
  1377. <li>superset >=</li>
  1378. <li>set of anonymous enum type: <i>set of (enum1,enum2,...)</i></li>
  1379. </ul>
  1380. </li>
  1381. <li>Not supported: set of char, set of boolean</li>
  1382. <li>There is no optimization yet for small sets like in Delphi/FPC.</li>
  1383. <li>Assigning a set or passing the set as an argument only creates a
  1384. reference and marks the set as <i>shared</i>.
  1385. When a <i>shared</i> set is altered with Include/Exclude a new set is
  1386. created (copy on write).</li>
  1387. <li>Passing a set as an argument might clone the set.
  1388. Use the <i>const</i> modifier for parameters whenever possible.</li>
  1389. <li>Constant sets in expressions (e.g. <i>if c in ['a'..'z'] then</i>)
  1390. are not yet optimized and created every time. Create a <i>const</i> to avoid this.</li>
  1391. </ul>
  1392. </div>
  1393. <div class="section">
  1394. <h2 id="array">Translating array type</h2>
  1395. All arrays are translated into JavaScript arrays.<br>
  1396. Contrary to Delphi/FPC dynamic arrays are
  1397. not reference counted and do not copy on write. That means if you pass an
  1398. array to a procedure and change an element, the original array is changed.
  1399. <table class="sample">
  1400. <tbody>
  1401. <tr>
  1402. <th>Pascal</th>
  1403. <th>JavaScript</th>
  1404. </tr>
  1405. <tr>
  1406. <td>
  1407. <pre>Unit MyModule;
  1408. Interface
  1409. Type
  1410. TIntArr = Array of integer;
  1411. TObjArr = Array of TObject;
  1412. TRec = record c: char; end;
  1413. TRecArr = Array of TRec;
  1414. Procedure Test;
  1415. Implementation
  1416. Procedure Test;
  1417. Var
  1418. IntArr: TIntArr = (1,2,3);
  1419. ObjArr: TObjArr;
  1420. RecArr: TRecArr;
  1421. Begin
  1422. IntArr:=nil;
  1423. SetLength(IntArr,4);
  1424. IntArr[2]:=2;
  1425. IntArr[1]:=length(IntArr);
  1426. SetLength(ObjArr,5);
  1427. SetLength(RecArr,2,TRec);
  1428. End;
  1429. End.
  1430. </pre>
  1431. </td>
  1432. <td>
  1433. <pre>rtl.module("MyModule",
  1434. ["System"],
  1435. function(){
  1436. var $mod = this;
  1437. this.Test = function(){
  1438. this.TRec = function(s){
  1439. if (s){
  1440. this.c = s.c;
  1441. } else {
  1442. this.c = "";
  1443. };
  1444. this.$equal = function(b){
  1445. return (this.c == b.c);
  1446. };
  1447. };
  1448. this.IntArr = [1,2,3];
  1449. this.ObjArr = [];
  1450. this.RecArr = [];
  1451. this.Test = function(){
  1452. $mod.IntArr = [];
  1453. rtl.arraySetLength($mod.IntArr,4,0);
  1454. $mod.IntArr[2] = 2;
  1455. $mod.IntArr[1] = $mod.IntArr.length;
  1456. rtl.setArrayLength($mod.ObjArr,5,null);
  1457. rtl.setArrayLength($mod.RecArr,2,$mod.TRec);
  1458. }
  1459. };
  1460. },
  1461. []);
  1462. </pre>
  1463. </td>
  1464. </tr>
  1465. </tbody>
  1466. </table>
  1467. Notes:
  1468. <ul>
  1469. <li>Supported features of dynamic arrays: SetLength(), Length(), equal/notequal nil, low(), high(),
  1470. assigned(), concat(), copy(), insert(), delete(), multi dimensional, array of record</li>
  1471. <li>Dynamic array constants. E.g. in mode ObjFPC <i>const a: array of byte = (1,2)</i>.
  1472. In mode Delphi you must use square brackets, <i>... = [1,2]</i></li>
  1473. <li>Supported features of static arrays: length(), low(), high(),
  1474. assigned(), concat(), copy(), const, const records </li>
  1475. <li>Open arrays are implemented as dynamic arrays.</li>
  1476. <li>Calling <i>Concat()</i> with only one array simply returns the array
  1477. (no cloning). Calling it with multiple arrays creates a clone.
  1478. This is Delphi 10.1 compatible.</li>
  1479. <li>In Delphi/FPC an empty array is <i>nil</i>. In JS it can be <i>null</i> or <i>[]</i>.
  1480. For compatibility comparing an array with <i>nil</i> checks for <i>length(a)>0</i>.</li>
  1481. <li><i>function Assigned(array): boolean</i> results true iff <i>length(array)>0</i>.</li>
  1482. <li>array of const:
  1483. <ul>
  1484. <li>Works the same: vtInteger, vtBoolean, vtPointer, vtObject, vtClass, vtWideChar, vtInterface, vtUnicodeString</li>
  1485. <li>''longword'' is converted to ''vtNativeInt''. Delphi/FPC converts to ''vtInteger'', changing big numbers to negative numbers.</li>
  1486. <li>vtExtended is double, Delphi/FPC: PExtended</li>
  1487. <li>vtCurrency is currency, Delphi/FPC: PCurrency</li>
  1488. <li>Not supported: vtChar, vtString, vtPChar, vtPWideChar, vtAnsiString, vtVariant, vtWideString, vtInt64, vtQWord</li>
  1489. <li>only in pas2js: vtNativeInt, vtJSValue</li>
  1490. </ul></li>
  1491. <li>Assignation using constant array, e.g. <i>a:=[1,1,2];</i></li>
  1492. <li>String like operation: + operator concatenates arrays. e.g. <i>a:=[1]+[2];</i>.
  1493. This is controlled by modeswitch arrayoperators, which is enabled in mode delphi.</li>
  1494. <li><i>function copy(array,start=0,count=max): array</i></li>
  1495. <li><i>procedure insert(item,var array,const position)</i></li>
  1496. <li><i>procedure delete(var array,const start,count)</i></li>
  1497. </ul>
  1498. </div>
  1499. <div class="section">
  1500. <h2 id="class">Translating class type</h2>
  1501. Classes are implemented using <i>Object.create</i> and some rtl magic.
  1502. <table class="sample">
  1503. <tbody>
  1504. <tr>
  1505. <th>Pascal</th>
  1506. <th>JavaScript</th>
  1507. </tr>
  1508. <tr>
  1509. <td>
  1510. <pre>Unit MyModule;
  1511. Interface
  1512. Type
  1513. TClassA = Class(TObject)
  1514. Public
  1515. i: integer;
  1516. Procedure Add(a: integer);
  1517. End;
  1518. var
  1519. ObjA: TClassA;
  1520. Implementation
  1521. Procedure TClassA.Add(a: integer);
  1522. Begin
  1523. i:=i+a;
  1524. End;
  1525. Initialization
  1526. ObjA:=TClassA.Create;
  1527. End.
  1528. </pre>
  1529. </td>
  1530. <td>
  1531. <pre>rtl.module("MyModule",
  1532. ["System"],
  1533. function(){
  1534. var $mod = this;
  1535. rtl.createClass($mod,"TClassA",pas.System.TObject,function(){
  1536. this.$init = function () {
  1537. this.i = 0;
  1538. };
  1539. this.Add = function(a){
  1540. this.i = this.i + a;
  1541. };
  1542. });
  1543. this.ObjA = null;
  1544. $mod.$init = function(){
  1545. $mod.ObjA = $mod.TClassA.$create("Create");
  1546. };
  1547. },
  1548. []);
  1549. </pre>
  1550. </td>
  1551. </tr>
  1552. </tbody>
  1553. </table>
  1554. Notes:
  1555. <ul>
  1556. <li>Each class and each instance is an JS object.</li>
  1557. <li>Each class has a globally unique JS object, created by rtl.createClass.</li>
  1558. <li><i>Self</i> is never <i>nil</i>.</li>
  1559. <li>The method <i>TObject.Free</i> is using compiler magic. See <a href="#tobjectfree">Translating TObject.Free</a>.</li>
  1560. <li><i>Class.$class</i> is a reference to the class itself.</li>
  1561. <li><i>Class.$ancestor</i> is a reference to the ancestor class.</li>
  1562. <li>A class has <i>c.$ancestor == Object.getPrototypeOf(c)</i>.</li>
  1563. <li>A class instance has <i>o.$class == Object.getPrototypeOf(o)</i>.</li>
  1564. <li><i>Class.$classname</i> is the short name. E.g. <i>TClassA.$classname == 'TClassA'</i>.</li>
  1565. <li><i>Class.$name</i> is the long name. E.g. <i>TClassA.$name == 'MyModule.TClassA'</i>.</li>
  1566. <li><i>Class.$unitname</i> is the unit name. E.g. <i>TClassA.$unitname == 'MyModule'</i>.</li>
  1567. <li>The "<i>is</i>"-operator is implemented using "<i>isPrototypeOf</i>". Note that "<i>instanceof</i>" cannot be used, because classes are JS objects.</li>
  1568. <li>The "<i>as</i>" operator is implemented as <i>rtl.as(Object,Class)</i>.</li>
  1569. <li>Supported:
  1570. <ul>
  1571. <li>constructor, destructor</li>
  1572. <li>private, protected, public, strict private, strict protected</li>
  1573. <li>class vars, const, nested types</li>
  1574. <li>methods, class methods, class constructor, external methods</li>
  1575. <li>method modifiers overload, reintroduce, virtual, override, abstract,
  1576. static, external name, message integer, message string</li>
  1577. <li>call inherited</li>
  1578. <li>assigned()</li>
  1579. <li>type cast</li>
  1580. <li>class sealed, class abstract</li>
  1581. </ul>
  1582. </li>
  1583. <li>Not supported: class destructor</li>
  1584. <li>Property:
  1585. <ul>
  1586. <li>References are replaced by getter/setter.</li>
  1587. <li>Supported: argument lists, default property, class property,
  1588. stored modifier, index modifier.</li>
  1589. <li>Not supported: getter/setter to an array element,
  1590. e.g. <i>property A: char read FArray[0];</i> </li>
  1591. <li>Class property getter/setter can be static or non static. Delphi: must be static.</li>
  1592. <li>The <i>Index</i> modifier supports any constant, e.g. a string, while
  1593. Delphi only allows an ordinal (longint). -2147483648 is not a special
  1594. number in pas2js. Overriding a property with an index property is allowed
  1595. in Delphi and pas2js.</li>
  1596. </ul>
  1597. </li>
  1598. </ul>
  1599. </div>
  1600. <div class="section">
  1601. <h2 id="classof">Translating class-of type</h2>
  1602. A class-of is a reference to a class. See above about translating class.
  1603. <table class="sample">
  1604. <tbody>
  1605. <tr>
  1606. <th>Pascal</th>
  1607. <th>JavaScript</th>
  1608. </tr>
  1609. <tr>
  1610. <td>
  1611. <pre>Unit MyModule;
  1612. Interface
  1613. Type
  1614. TBird = Class(TObject)
  1615. Public
  1616. Class var Count: integer;
  1617. Class Procedure Add(a: integer); virtual;
  1618. End;
  1619. TBirds = class of TBird;
  1620. TPigeon = Class(TBird)
  1621. Public
  1622. Class Procedure Add(a: integer); override;
  1623. End;
  1624. var
  1625. BirdType: TBirds;
  1626. Implementation
  1627. Class Procedure TBird.Add(a: integer);
  1628. Begin
  1629. Count:=Count+a;
  1630. End;
  1631. Class Procedure TPigeon.Add(a: integer);
  1632. Begin
  1633. inherited Add(a+1);
  1634. End;
  1635. Initialization
  1636. BirdType:=TPigeon;
  1637. BirdType.Add(1);
  1638. End.
  1639. </pre>
  1640. </td>
  1641. <td>
  1642. <pre>rtl.module("MyModule",
  1643. ["System"],
  1644. function(){
  1645. var $mod = this;
  1646. rtl.createClass($mod,"TBird",pas.System.TObject,function () {
  1647. this.Count = 0;
  1648. this.Add = function (a) {
  1649. this.Count = this.Count + a;
  1650. };
  1651. });
  1652. rtl.createClass($mod,"TPigeon",$mod.TBird,function () {
  1653. this.Add = function (a) {
  1654. $mod.TBird.Add.call(this,a + 1);
  1655. };
  1656. });
  1657. $mod.$init = function(){
  1658. $mod.BirdType = $mod.TPigeon;
  1659. $mod.BirdType.Add(1);
  1660. };
  1661. },
  1662. []);
  1663. </pre>
  1664. </td>
  1665. </tr>
  1666. </tbody>
  1667. </table>
  1668. Note that <i>this</i> in a class method is the class itself.<br>
  1669. <br>
  1670. Notes:<br>
  1671. <ul>
  1672. <li>Contrary to Delphi/FPC the "is" operator works with class-of.</li>
  1673. </ul>
  1674. </div>
  1675. <div class="section">
  1676. <h2 id="tobjectfree">Translating TObject.Free</h2>
  1677. In Delphi/FPC AnObject.Free checks if Self is nil, then calls the destructor
  1678. and frees the memory, without changing the reference.
  1679. In JavaScript however calling a method with AnObject=nil causes a crash.
  1680. And memory cannot be freed explicitely. Memory is only
  1681. freed if all references are gone (e.g. set to <i>null</i>).<br>
  1682. Therefore pas2js adds code to call the destructor and sets the variable to <i>nil</i>:<br>
  1683. <ul>
  1684. <li><i>Obj.Free</i> on a local variable or argument is translated to
  1685. <i>Obj = rtl.freeLoc(Obj);</i>.</li>
  1686. <li><i>Obj.Free</i> on a non local variable is translated to
  1687. <i>rtl.free(this,"Obj");</i>.</li>
  1688. <li>Not supported: Freeing a property or function result.<br>
  1689. For example <i>List[i].Free</i> gives a compiler error. The property
  1690. setter might create side effects, which would be incompatible to Delphi/FPC.
  1691. </li>
  1692. </ul>
  1693. Notes:
  1694. <ul>
  1695. <li>If the destructor raises an exception, the variable is not set to <i>nil</i>.
  1696. This is compatible to Delphi/FPC, where the memory is not freed in this case.</li>
  1697. <li>Alternatively you can use <i>FreeAndNil</i>, which first changes
  1698. the variable to <i>nil</i> and then calls the destructor.</li>
  1699. </ul>
  1700. </div>
  1701. <div class="section">
  1702. <h2 id="classinterfaces">Translating class interfaces</h2>
  1703. JavaScript has nothing like it, so they are emulated.<br>
  1704. An interfacetype is a JS-object with some hidden properties, containing
  1705. the GUID ($guid) and an array with the method names ($names). Here is how
  1706. IUnknown looks like in JS:<br>
  1707. <pre>
  1708. {
  1709. $module: [object Object],
  1710. $name: "IUnknown",
  1711. $fullname: "System.IUnknown",
  1712. $guid: "{00000000-0000-0000-C000-000000000046}",
  1713. $names: ["QueryInterface","_AddRef","_Release"],
  1714. $rtti: [object Object],
  1715. $kind: "com",
  1716. }
  1717. </pre>
  1718. A class implementing interfaces has a variable <i>$intfmaps</i>, which has
  1719. for each implemented GUID a map or delegator function. A map
  1720. is a JS instance of the interfacetype plus a for each method name a
  1721. function to call the class method. Here is an example map of <i>IUnknown</i> of
  1722. <i>TInterfacedObject</i>:<br>
  1723. <pre>
  1724. {
  1725. QueryInterface: function (){ return fn.apply(this.$o,arguments); },
  1726. _AddRef: function (){ return fn.apply(this.$o,arguments); },
  1727. _Release: function (){ return fn.apply(this.$o,arguments); },
  1728. ...
  1729. }
  1730. </pre>
  1731. When an interface is created for an object (here: a Pascal class instance),
  1732. for example by using the <i>as</i>-operator "<i>ObjVar as IUnknown</i>",
  1733. a JS object is created, which
  1734. is an instance of the map object with its <i>$o</i> set to the <i>ObjVar</i>.<br>
  1735. <br>
  1736. Supported:
  1737. <ul>
  1738. <li>methods, properties, default property</li>
  1739. <li><i>{$interfaces com|corba|default}</i><br>
  1740. <ul>
  1741. <li>COM is default, default ancestor is IUnknown (mode delphi: IInterface),
  1742. managed type, i.e. automatically reference counted via _AddRef, _Release, the checks for support call QueryInterface</li>
  1743. <li>CORBA: lightweight, no automatic reference counting,
  1744. no default ancestor, fast support checks.</li>
  1745. </ul>
  1746. </li>
  1747. <li>inheriting</li>
  1748. <li>An interface without a GUID gets one autogenerated from its name and method names.</li>
  1749. <li>Contrary to Delphi/FPC you can assign an interface type or var to
  1750. the type TGuidString.</li>
  1751. <li>a class implementing an interface must not be external</li>
  1752. <li>a ClassType "supports" an interface, if it itself or one of its
  1753. ancestors implements the interface.
  1754. It does not automatically support an ancestor of the interface.</li>
  1755. <li>method resolution, procedure IUnknown._AddRef = IncRef;</li>
  1756. <li>delegation: property Name: interface|class read Field|Getter implements AnInterface;</li>
  1757. <li>is-operator:</li>
  1758. <ul>
  1759. <li>IntfVar is IntfType - types must be releated</li>
  1760. <li>IntfVar is ClassType - types can be unrelated, class must not be external</li>
  1761. <li>ObjVar is IntfType - can be unrelated</li>
  1762. </ul>
  1763. <li>as-operator</li>
  1764. <ul>
  1765. <li>IntfVar as IntfType - types must be releated</li>
  1766. <li>IntfVar as ClassType - types can be unrelated, nil returns nil,
  1767. invalid raises EInvalidCast</li>
  1768. <li>ObjVar as IntfType - can be unrelated, nil if not found, COM: uses _AddRef</li>
  1769. </ul>
  1770. <li>typecast:</li>
  1771. <ul>
  1772. <li>IntfType(IntfVar) - must be related</li>
  1773. <li>ClassType(IntfVar) - can be unrelated, nil if invalid</li>
  1774. <li>IntfType(ObjVar) - nil if not found,
  1775. COM: if ObjVar has delegate uses _AddRef</li>
  1776. <li>TJSObject(IntfTypeOrVar). Note that you cannot typecast directly
  1777. to a <i>TJSObject</i> descendant. You can use <i>TJSWindow(TJSObject(IntfType))</i>.</li>
  1778. <li>jsvalue(intfvar)</li>
  1779. </ul>
  1780. <li>Assign operator:</li>
  1781. <ul>
  1782. <li>IntfVar:=nil;</li>
  1783. <li>IntfVar:=IntfVar2; - IntfVar2 must be same type or a descendant</li>
  1784. <li>IntfVar:=ObjVar; - nil if unsupported</li>
  1785. <li>jsvalue:=IntfVar;</li>
  1786. <li>TGUIDVar:=IntfType;</li>
  1787. <li>TGUIDVar:=IntfVar;</li>
  1788. <li>TGUIDVar:=stringconstant;</li>
  1789. <li>TGUIDStringVar:=IntfVar;</li>
  1790. <li>StringVar:=GuidVar;</li>
  1791. </ul>
  1792. <li>Equal/Inequal operator:</li>
  1793. <ul>
  1794. <li>IntfVar=nil;</li>
  1795. <li>IntfVar=IntfVar2; - must be related</li>
  1796. <li>jsvalue=IntfVar;</li>
  1797. <li>TGUIDVar=IntfType;</li>
  1798. <li>TGUIDVar=IntfVar;</li>
  1799. <li>TGUIDVar=string;</li>
  1800. <li>TGUIDStringVar=IntfVar;</li>
  1801. </ul>
  1802. <li>Passing an COMIntfVar to an untyped parameter does not trigger _AddRef, _Release.</li>
  1803. <li>Assigned(IntfVar)</li>
  1804. <li>RTTI, typeinfo(IntfType), typeinfo(IntfVar)</li>
  1805. </ul>
  1806. Not yet supported: array of intferfacetype, interface as record member.
  1807. </div>
  1808. <div class="section">
  1809. <h2 id="helpers">Translating helpers</h2>
  1810. Pas2js supports class helpers, record helpers and type helpers since 1.3.
  1811. The extend is only virtual, the helped type is kept untouched.
  1812. <br>
  1813. <ul>
  1814. <li>A <b>class helper</b> can "extend" Pascal classes and external JS classes.</li>
  1815. <li>A <b>record helper</b> can "extend" a record type. In $mode delphi a
  1816. record helper can extend other types as well, see <i>type helper</i></li>
  1817. <li>A <b>type helper</b> can extend all base types like integer, string,
  1818. char, boolean, double, currency, and some user types like enumeration,
  1819. set, range and array types. It cannot extend interfaces or helpers.<br>
  1820. Type helpers are enabled by default in <i>$mode delphi</i> and disabled in <i>$mode objfpc</i>.
  1821. You can enable them with <b>{$modeswitch typehelpers}</b>.
  1822. </li>
  1823. <li>By default only one helper is active per type, same as in FPC/Delphi.
  1824. If there are multiple helpers for the same type, the last helper in scope wins.<br>
  1825. A class with ancestors can have one active helper per ancestor type, so
  1826. multiple helpers can be active, same as FPC/Delphi.<br>
  1827. Using <b>{$modeswitch multihelpers}</b> you can activate all helpers
  1828. within scope.
  1829. </li>
  1830. <li>Nested helpers (e.g. <i>TDemo.TSub.THelper</i>) are elevated.
  1831. Visibility is ignored. Same as FPC/Delphi.</li>
  1832. <li>Helpers cannot be forward defined (e.g. no <i>THelper = helper;</i>).</li>
  1833. <li>Helpers must not have fields.</li>
  1834. <li><b>Class Var, Const, Type</b></li>
  1835. <li><b>Visibility</b> : <i>strict private .. published</i></li>
  1836. <li><b>Function, procedure</b>:
  1837. In class and record helpers <i>Self</i> is the class/record instance. For other
  1838. types Self is a reference to the passed value.
  1839. </li>
  1840. <li><b>Class function, class procedure</b>: Helpers for Pascal classes/records can
  1841. add <i>static</i> and non static class functions. Helpers for external classes
  1842. and other types can only add static class functions.</li>
  1843. <li><b>Constructor</b>. Not for external classes. Works similar to
  1844. construcors, i.e. <i>THelpedClass.Create</i> creates a new instance, while
  1845. <i>AnObj.Create</i> calls the constructor function as normal method. Note that
  1846. Delphi does not allow calling helper construcors as normal method.</li>
  1847. <li>no destructor</li>
  1848. <li><b>Property</b> : getters/setters can refer to members of the helper, its
  1849. ancestors and the helped class/record.</li>
  1850. <li><b>Class property</b> : getter can be static or non static. Delphi/FPC only allows static.</li>
  1851. <li><b>Ancestors</b> : Helpers can have an ancestor helper, but they
  1852. do not have a shared root class, especially not <i>TObject</i>.</li>
  1853. <li><b>no virtual, abstract, override</b>. Delphi allows them, but 10.3 crashes when calling.</li>
  1854. <li><b>inherited</b> :
  1855. <i>inherited</i> inside a method of a class/record calls helper of ancestor.<br>
  1856. <i>inherited</i> inside a helper depends on the $mode:
  1857. <ul>
  1858. <li> <i>$mode objfpc</i> : <i>inherited;</i> and <i>inherited Name(args);</i>
  1859. work the same and searches first in HelperForType, then in ancestor(s).</li>
  1860. <li><i>$mode delphi: inherited;</i> : skip ancestors and HelperForType,
  1861. searches first in helper(s) of ancestor of HelperForType.</li>
  1862. <li><i>$mode delphi: inherited name(args);</i> :
  1863. same as $mode objfpc first searches in HelperForType, then Ancestor(s)</li>
  1864. </ul>
  1865. In any case if <i>inherited;</i> has no ancestor to call, it is silently ignored,
  1866. while <i>inherited Name;</i> gives an error.
  1867. </li>
  1868. <li><b>RTTI</b>: <i>typeinfo(somehelper)</i> returns a pointer to <i>TTypeInfoHelper</i> with <i>Kind tkHelper</i>.</li>
  1869. <li>There are some special cases when using a <b>type helper</b> function/procedure on a value:
  1870. <ul>
  1871. <li><i>function result</i> : using a temporary variable</li>
  1872. <li><i>const, const argument</i> : When helper function tries to assign a value,
  1873. pas2js raises a EPropReadOnly exception. FPC/Delphi use a temporary variable allowing the write. </li>
  1874. <li><i>property</i> : uses only the getter, ignoring the setter.
  1875. This breaks OOP, as it allows to change fields without calling the setter.
  1876. This is FPC/Delphi compatible.</li>
  1877. <li><i>with value do ;</i> : uses a temporary variable. Delphi/FPC do not support it.</li>
  1878. </ul>
  1879. </li>
  1880. </ul>
  1881. </div>
  1882. <div class="section">
  1883. <h2 id="attributes">Translating attributes</h2>
  1884. Attributes are stored in the TTypeInfo objects as streams stored in an array.
  1885. See the <i>TypInfo</i> function <i>GetRTTIAttributes</i> for details.
  1886. </div>
  1887. <div class="section">
  1888. <h2 id="tryfinally">Translating try..finally</h2>
  1889. JavaScript has the same, so it translates straight forward.
  1890. </div>
  1891. <div class="section">
  1892. <h2 id="tryexcept">Translating try..except</h2>
  1893. <table class="sample">
  1894. <tbody>
  1895. <tr>
  1896. <th>Pascal</th>
  1897. <th>JavaScript</th>
  1898. </tr>
  1899. <tr>
  1900. <td>
  1901. <pre>Unit MyModule;
  1902. Interface
  1903. Uses SysUtils, Math, JS;
  1904. Function DoIt(n: integer): double;
  1905. Implementation
  1906. Function DoIt(n: integer): double;
  1907. var E: Exception;
  1908. Begin
  1909. try
  1910. Result:=double(7.0)/n;
  1911. if not IsFinite(Result) then
  1912. if n=0 then
  1913. raise EZeroDivide.Create
  1914. else
  1915. raise EOverflow.Create;
  1916. except
  1917. on EZeroDivide do Result:=0.0;
  1918. on E2: EOverflow do Result:=0.0;
  1919. else
  1920. raise EAbort.Create('Something other: '+String(JS.JSExceptObject));
  1921. end;
  1922. End;
  1923. End.
  1924. </pre>
  1925. </td>
  1926. <td>
  1927. <pre>rtl.module("MyModule",
  1928. ["System","SysUtils"],
  1929. function(){
  1930. this.DoIt=function(n){
  1931. Result = 0;
  1932. var E = null;
  1933. try{
  1934. Result = 7.0 / n;
  1935. if (!IsFinite(Result)){
  1936. if (n==0){
  1937. throw pas.SysUtils.EZeroDivide.$create("Create");
  1938. } else {
  1939. throw pas.SysUtils.EOverflow.$create("Create");
  1940. };
  1941. };
  1942. }catch($e){
  1943. if (pas.SysUtils.EZeroDivide.isPrototypeOf($e)){
  1944. Result = 0.0;
  1945. } else if (pas.SysUtils.EOverflow.isPrototypeOf($e)){
  1946. var E2 = $e;
  1947. Result = 0.0;
  1948. } else {
  1949. throw pas.SysUtils.EAbort.$create("Create",["Something other: "+(""+$e)]);
  1950. }
  1951. }
  1952. return Result;
  1953. };
  1954. },
  1955. []);
  1956. </pre>
  1957. </td>
  1958. </tr>
  1959. </tbody>
  1960. </table>
  1961. Notes:
  1962. <ul>
  1963. <li>Division by zero does not raise an exception in JavaScript. Instead it results in Infinity, except for 0/0 which results in NaN.</li>
  1964. <li>There is no ExceptObject in SysUtils.</li>
  1965. <li>When calling external functions keep in mind that JS allows to
  1966. throw (raise) any value, often a string.<br>
  1967. You can access the current except value via JSExceptValue in unit JS.<br>
  1968. Note that this is only valid inside the catch-block. The compiler will not warn,
  1969. if you use it outside.</li>
  1970. </div>
  1971. <div class="section">
  1972. <h2 id="enumerators">Translating enumerators</h2>
  1973. The for..in..do supports enumerating:
  1974. <ul>
  1975. <li>ordinal types like char, boolean,
  1976. byte, ..., longword, enums, custom ranges are translated to a for loop.</li>
  1977. <li>set types are translated to a for loop, while const sets and set variables are enumerated via a for(...in...) loop.</li>
  1978. <li>string and array variables are enumerated via for loops.</li>
  1979. <li>for aString in ArrayOfString do ...</li>
  1980. <li><i>for key in jsvalue do</i> translates to <i>for (key in jsvalue){}</i></li>
  1981. <li><i>for key in ExternalClass do</i><br>
  1982. <ul>
  1983. <li>If the externalclass has a ''length'' and a matching default property
  1984. it uses the enumeration of an array. For example
  1985. <i>for value in TJSArray do</i> enumerates the values of the array, not the index.
  1986. It checks if the array is nil.</li>
  1987. <li>Otherwise it translates to <i>for (key in externalclass){}</i>,
  1988. which enumerates the keys (property names) of the JS object.</li>
  1989. </ul>
  1990. </ul>
  1991. The class GetEnumerator function is translated like this:
  1992. <table class="sample">
  1993. <tbody>
  1994. <tr>
  1995. <th>Pascal</th>
  1996. <th>JavaScript</th>
  1997. </tr>
  1998. <tr>
  1999. <td>
  2000. <pre>Unit MyModule;
  2001. Interface
  2002. uses Classes;
  2003. procedure DoIt(List: TList);
  2004. Implementation
  2005. procedure DoIt(List: TList);
  2006. var
  2007. Item: Pointer;
  2008. begin
  2009. for Item in List do
  2010. if Item<>nil then ;
  2011. end;
  2012. End.
  2013. </pre>
  2014. </td>
  2015. <td>
  2016. <pre>rtl.module("MyModule",
  2017. ["System","Classes"],
  2018. function(){
  2019. this.DoIt=function(List){
  2020. var Item = null;
  2021. var $in1 = List;
  2022. try {
  2023. while ($in1.MoveNext()) {
  2024. Item = $in1.GetCurrent();
  2025. if (Item !== null) ;
  2026. }
  2027. } finally {
  2028. $in1 = rtl.freeLoc($in1)
  2029. };
  2030. };
  2031. },
  2032. []);
  2033. </pre>
  2034. </td>
  2035. </tr>
  2036. </tbody>
  2037. </table>
  2038. Notes:
  2039. <ul>
  2040. <li>Not supported: operator Enumerator, member modifier enumerator (i.e. custom Current and MoveNext)</li>
  2041. </ul>
  2042. </div>
  2043. <div class="section">
  2044. <h2 id="functiontype">Translating function types</h2>
  2045. JavaScript functions work like Delphi's "reference to function", which
  2046. means like closures, capturing outer variables.
  2047. Assigning a normal function or nested function to a procedural variable is
  2048. translated to a simple assignment.
  2049. A Pascal method needs <b>this</b> to be the class or class instance.<br>
  2050. Note that <i>bind</i> cannot be used, because it does not support the <i>equal</i> operator.
  2051. Instead a wrapper is created:
  2052. <table class="sample">
  2053. <tbody>
  2054. <tr>
  2055. <th>Pascal</th>
  2056. <th>JavaScript</th>
  2057. </tr>
  2058. <tr>
  2059. <td>
  2060. <pre>Program MyModule;
  2061. type
  2062. TMyMethod = procedure(n: integer) of object;
  2063. TBird = class
  2064. procedure DoIt(n: integer); virtual; abstract;
  2065. end;
  2066. TMyProc = procedure(n: integer);
  2067. procedure DoSome(n: integer);
  2068. begin
  2069. end;
  2070. var
  2071. m: TMyMethod;
  2072. Bird: TBird;
  2073. p: TMyProc;
  2074. Begin
  2075. m:[email protected];
  2076. m(3);
  2077. p:=@DoSome;
  2078. p(4);
  2079. End.
  2080. </pre>
  2081. </td>
  2082. <td>
  2083. <pre>rtl.module("program",
  2084. ["System","UnitA"],
  2085. function(){
  2086. var $mod = this;
  2087. rtl.createClass($mod,"TBird",pas.System.TObject,function(){
  2088. this.DoIt = function (n) {
  2089. };
  2090. });
  2091. this.DoSome = function (n) {
  2092. };
  2093. this.m = null;
  2094. this.Bird = null;
  2095. this.p = null;
  2096. $mod.$main = function() {
  2097. $mod.m = rtl.createCallback($mod.Bird,"DoIt");
  2098. $mod.m(3);
  2099. $mod.p = $mod.DoSome;
  2100. $mod.p(4);
  2101. };
  2102. },
  2103. []);
  2104. rtl = {
  2105. ...
  2106. createCallback: function(scope, fn){
  2107. var cb = function(){
  2108. return scope[fn].apply(scope,arguments);
  2109. };
  2110. cb.scope = scope;
  2111. cb.fn = fn;
  2112. return cb;
  2113. },
  2114. ...
  2115. </pre>
  2116. </td>
  2117. </tr>
  2118. </tbody>
  2119. </table>
  2120. Notes:
  2121. <ul>
  2122. <li>You can assign a nested procedure to procedure variable.
  2123. You don't need and you must not add the FPC "<i>is nested</i>" modifier.</li>
  2124. <li>A procedural typed declared as 'reference to' accepts in pas2js procedures,
  2125. local procedures and methods. Delphi only supports capturing procedures and methods.
  2126. FPC 3.0.4 does not support reference-to.</li>
  2127. </ul>
  2128. </div>
  2129. <div class="section">
  2130. <h2 id="anonymousfunctions">Translating anonymous functions</h2>
  2131. Anonymous functions are supported since pas2js 1.1.<br>
  2132. Note that in pas2js local procedures are closures as well. See below.<br>
  2133. For pas2js 1.0 the next best thing are local procedures. For example:
  2134. <table class="sample">
  2135. <tbody>
  2136. <tr>
  2137. <th>Delphi</th>
  2138. <th>Pas2js</th>
  2139. </tr>
  2140. <tr>
  2141. <td>
  2142. <pre>Program MyModule;
  2143. type
  2144. TAdder = reference to function(n: integer): integer;
  2145. function CreateAdder(a: integer): TAdder;
  2146. begin
  2147. Result:=function(b: integer)
  2148. begin
  2149. Result:=a+b;
  2150. end;
  2151. end;
  2152. var
  2153. Adder: TAdder;
  2154. Begin
  2155. Adder:=CreateAdder(3);
  2156. writeln(Adder(5)); // gives 8
  2157. End.
  2158. </pre>
  2159. </td>
  2160. <td>
  2161. <pre>Program MyModule;
  2162. type
  2163. TAdder = reference to function(n: integer): integer;
  2164. function CreateAdder(a: integer): TAdder;
  2165. function Add(b: integer): integer;
  2166. begin
  2167. Result:=a+b;
  2168. end;
  2169. begin
  2170. Result:=@Add;
  2171. end;
  2172. var
  2173. Adder: TAdder;
  2174. Begin
  2175. Adder:=CreateAdder(3);
  2176. writeln(Adder(5)); // gives 8
  2177. End.
  2178. </pre>
  2179. </td>
  2180. </tr>
  2181. </tbody>
  2182. </table>
  2183. </div>
  2184. <div class="section">
  2185. <h2 id="absolute">Translating var modifier absolute</h2>
  2186. The absolute modifier works as an alias. That means it works FPC/Delphi
  2187. compatible for related types like Pointer and TObject, and works
  2188. incompatible for unrelated types like longword and record (e.g. <i>var r: TPoint absolute MyLongInt</i>).<br>
  2189. The modifier is currently only supported for local variables.
  2190. </div>
  2191. <div class="section">
  2192. <h2 id="assert">Translating assert()</h2>
  2193. The Assert(boolean[,string]) function is translated to <i>if(bool) throw x</i>.
  2194. If unit sysutils is used, it creates an EAssertFailed exception.<br>
  2195. Otherwise it throws a string.<br>
  2196. <ul>
  2197. <li>Command line enable with -Sa, disable with -Sa-</li>
  2198. <li>In code enable with <i>{$C+}</i> or <i>{$Assertions on}</i>,
  2199. disable with <i>{$C-}</i> or <i>{$Assertions off}</i></li>
  2200. </ul>
  2201. </div>
  2202. <div class="section">
  2203. <h2 id="dispatch">Dispatch messages</h2>
  2204. The procedure modifier <b>message</b> and the <b>Dispatch</b> works
  2205. similar to FPC/Delphi, as it expects a record of a specific format and
  2206. <b>Dispatch</b> calls the method with that message number or string.<br>
  2207. The procedure modifier <i>message &lt;integer&gt;</i> adds an entry to the
  2208. <i>$msgint</i> object, and modifier <i>message &lt;string&gt;</i> adds an entry
  2209. to the <i>$msgstr</i> object.<br>
  2210. Two new directives <i>{$DispatchField fieldname}</i> and <i>{$DispatchStrField fieldname}</i>
  2211. were added. Insert these directives in front of your dispatch methods
  2212. to let the compiler check all methods with message modifiers whether they
  2213. pass a record with the right field. For example:
  2214. <pre>
  2215. TMyComponent = class
  2216. {$DispatchField Msg}
  2217. procedure Dispatch(var aMessage); virtual;
  2218. {$DispatchStrField MsgStr}
  2219. procedure DispatchStr(var aMessage); virtual;
  2220. end;
  2221. TMouseDownMsg = record
  2222. Id: integer; // Id instead of Msg, works in FPC, but not in pas2js
  2223. x,y: integer;
  2224. end;
  2225. TMouseUpMsg = record
  2226. MsgStr: string;
  2227. X,Y: integer;
  2228. end;
  2229. TWinControl = class
  2230. procedure MouseDownMsg(var Msg: TMouseDownMsg); message 3; // warning: Dispatch requires record field Msg
  2231. procedure MouseUpMsg(var Msg: TMouseUpMsg); message 'up'; // ok, record with string field name MsgStr
  2232. end;
  2233. </pre>
  2234. </div>
  2235. <div class="section">
  2236. <h2 id="calljavascript">Calling JavaScript from Pascal</h2>
  2237. Pas2js allows to write low level functions and/or access a JavaScript library
  2238. with the following possibilities:
  2239. </div>
  2240. <div class="section">
  2241. <h2 id="asm">The asm block</h2>
  2242. The asm block is pure JavaScript, that is copied directly into the generated .js file.
  2243. <table class="sample">
  2244. <tbody>
  2245. <tr>
  2246. <th>Pascal</th>
  2247. <th>JavaScript</th>
  2248. </tr>
  2249. <tr>
  2250. <td>
  2251. <pre>Program MyModule;
  2252. var
  2253. s: string;
  2254. Begin
  2255. s = 'Hello World!';
  2256. Asm
  2257. console.log(s);
  2258. End;
  2259. End.
  2260. </pre>
  2261. </td>
  2262. <td>
  2263. <pre>rtl.module("program",
  2264. ["System"],
  2265. function(){
  2266. var $mod = this;
  2267. this.s = '';
  2268. $mod.$main = function(){
  2269. $mod.s = "Hello World!";
  2270. console.log(s);
  2271. };
  2272. },
  2273. []);
  2274. </pre>
  2275. </td>
  2276. </tr>
  2277. </tbody>
  2278. </table>
  2279. Notes:
  2280. <ul>
  2281. <li>The block is indented to produce more readable JS code.
  2282. All lines are indented or unindented the same amount, i.e. sub indentation is kept.</li>
  2283. <li>The compiler does neither parse, nor check the syntax of the JS.</li>
  2284. <li>The compiler does not know what Pascal identifiers are used by the
  2285. asm-block and might remove them, if no Pascal code is using them.
  2286. To make sure that an identifier is kept, add some dummy code like
  2287. <i>if MyVar=0 then;</i></li>
  2288. <li>Accessing an interface, program or library identifier:<br>
  2289. <ul>
  2290. <li>From inside the module you can use <i>$mod.Identifier</i>.</li>
  2291. <li>Otherwise use the fully qualified path <i>pas.Unitname.Identifier</i>.</li>
  2292. </ul>
  2293. </li>
  2294. <li>Accessing an implementation identifier:<br>
  2295. <ul>
  2296. <li>From inside the unit you can use <i>$impl.Identifier</i>.</li>
  2297. <li>Otherwise use the path <i>pas.Unitname.$impl.Identifier</i>.</li>
  2298. </ul>
  2299. </li>
  2300. <li>Accessing a class instance member (field, procedure, function,
  2301. constructor, destructor) from a method of the class: use <i>this.Identifier</i>.
  2302. Inside a nested function of a method you use the <i>Self.Identifier</i>.
  2303. </li>
  2304. <li>Accessing a class member (class var, class procedure, class function)
  2305. from a method of the class: for writing use <i>this.$class.Identifier</i>,
  2306. for reading you can omit the <i>$class</i>.</li>
  2307. <li>Accessing a class member (class var, class procedure, class function)
  2308. from a class method of the class: use <i>this.Identifier</i>.</li>
  2309. <li>Access to Properties must use the getter/setter.</li>
  2310. <li>When calling a Pascal method, make sure the <b>this</b> is correct:
  2311. <ul>
  2312. <li>A class method (e.g. <i>class function</i>, <i>class procedure</i>)
  2313. needs the class as <i>this</i>.<br>
  2314. <b>Wrong</b>: <i>aCar.DoIt(params,...)</i><br>
  2315. <b>Correct</b>: <i>aCar.$class.DoIt(params,...)</i><br>
  2316. </li>
  2317. </ul>
  2318. </li>
  2319. <li>Calling a Pascal function from a HTML/DOM-element:
  2320. For example to call a function when user clicks a DOM element you can
  2321. assign a function to the <i>onclick</i> property. This will call
  2322. the function with <i>this</i> set to the DOM element.<br>
  2323. Pascal methods needs a wrapper to set <i>this</i> to the
  2324. instance. Examples:
  2325. <ul>
  2326. <li>An unit function: <i>DOMElement.onclick = $mod.DoIt;</i></li>
  2327. <li>An implementation function: <i>DOMElement.onclick = $impl.DoIt;</i>.</li>
  2328. <li>A method: <i>DOMElement.onclick = this.DoIt.bind(this);</i></li>
  2329. <li>A class function/procedure: <i>DOMElement.onclick = this.DoIt.bind(this.$class);</i></li>
  2330. <li>A nested function: <i>DOMElement.onclick = DoIt;</i>.</li>
  2331. </ul>
  2332. </li>
  2333. </li>
  2334. </ul>
  2335. </div>
  2336. <div class="section">
  2337. <h2 id="assembler">The procedure modifier assembler</h2>
  2338. You can write pure JavaScript functions like this:
  2339. <table class="sample">
  2340. <tbody>
  2341. <tr>
  2342. <th>Pascal</th>
  2343. <th>JavaScript</th>
  2344. </tr>
  2345. <tr>
  2346. <td>
  2347. <pre>Program MyModule;
  2348. Procedure Log(const s: string); assembler;
  2349. Asm
  2350. console.log(s);
  2351. end;
  2352. Begin
  2353. Log('Hello World!');
  2354. End.
  2355. </pre>
  2356. </td>
  2357. <td>
  2358. <pre>rtl.module("program",
  2359. ["System"],
  2360. function(){
  2361. var $mod = this;
  2362. this.Log = function(s){
  2363. console.log(s);
  2364. };
  2365. $mod.$main = function(){
  2366. $mod.Log("Hello World!");
  2367. };
  2368. },
  2369. []);
  2370. </pre>
  2371. </td>
  2372. </tr>
  2373. </tbody>
  2374. </table>
  2375. See also <a href="#asm">asm</a>.
  2376. </div>
  2377. <div class="section">
  2378. <h2 id="externalproc">The procedure modifier external</h2>
  2379. The procedure modifier <i>external</i> requires a string constant and tells the
  2380. compiler to replace a reference with this string value. The value is not
  2381. checked for JS syntax.
  2382. <table class="sample">
  2383. <tbody>
  2384. <tr>
  2385. <th>Pascal</th>
  2386. <th>JavaScript</th>
  2387. </tr>
  2388. <tr>
  2389. <td>
  2390. <pre>Program MyModule;
  2391. Procedure ConsoleLog(const s: string); external name 'console.log';
  2392. // Note: an external procedure has no begin..end block
  2393. Begin
  2394. ConsoleLog('Hello World!');
  2395. End.
  2396. </pre>
  2397. </td>
  2398. <td>
  2399. <pre>rtl.module("program",
  2400. ["System"],
  2401. function(){
  2402. var $mod = this;
  2403. $mod.$main = function(){
  2404. console.log("Hello World!");
  2405. };
  2406. },
  2407. []);
  2408. </pre>
  2409. </td>
  2410. </tr>
  2411. </tbody>
  2412. </table>
  2413. </div>
  2414. <div class="section">
  2415. <h2 id="varargs">The procedure modifier varargs</h2>
  2416. Appending the <b>varargs</b> modifier to a procedure allows to pass arbitrary
  2417. more parameters to a function. To access these non typed arguments use
  2418. either <i>JSArguments</i> from unit JS or an <i>asm..end</i> block.
  2419. <table class="sample">
  2420. <tbody>
  2421. <tr>
  2422. <th>Pascal</th>
  2423. <th>JavaScript</th>
  2424. </tr>
  2425. <tr>
  2426. <td>
  2427. <pre>Program MyModule;
  2428. uses JS;
  2429. function Sum(b: boolean): longint; varargs;
  2430. var i: longint;
  2431. begin
  2432. if b then
  2433. asm
  2434. for (var i=0; i&lt;arguments.length; i++) Result+=arguments[i];
  2435. end
  2436. else
  2437. for i:=0 to JSArguments.length-1 do
  2438. Result:=Result+longint(JSArguments[i]);
  2439. end;
  2440. var
  2441. i: integer;
  2442. Begin
  2443. i:=Sum(true,2,4,6); // i=12
  2444. i:=Sum(false,2,4,6); // i=12
  2445. End.
  2446. </pre>
  2447. </td>
  2448. <td>
  2449. <pre>rtl.module("program",
  2450. ["System","JS"],
  2451. function(){
  2452. var $mod = this;
  2453. this.Sum = function(b){
  2454. var Result = 0;
  2455. var i = 0;
  2456. if (b){
  2457. for (var i=0; i&lt;arguments.length; i++) Result+=arguments[i];
  2458. } else {
  2459. for (var $l1 = 1, $le2 = argumens.length; $l1 &lt;= $le2; $l1++){
  2460. $i = $l1;
  2461. Result = Result + arguments[i];
  2462. }
  2463. }
  2464. return Result;
  2465. };
  2466. this.i = 0;
  2467. $mod.$main = function(){
  2468. $mod.i = $mod.Sum(true,2,4,6);
  2469. $mod.i = $mod.Sum(false,2,4,6);
  2470. };
  2471. },
  2472. []);
  2473. </pre>
  2474. </td>
  2475. </tr>
  2476. </tbody>
  2477. </table>
  2478. The above example defines a function <i>Sum</i>, that requires the first parameter to
  2479. be a boolean and then an arbitrary number of parameters. The compiler does not
  2480. type check the other parameters, so you can pass anything readable.
  2481. </div>
  2482. <div class="section">
  2483. <h2 id="externalvar">The var modifier external</h2>
  2484. The var modifier <i>external</i> allows to use a JavaScript variable or constant.
  2485. <table class="sample">
  2486. <tbody>
  2487. <tr>
  2488. <th>Pascal</th>
  2489. <th>JavaScript</th>
  2490. </tr>
  2491. <tr>
  2492. <td>
  2493. <pre>Program MyModule;
  2494. var
  2495. EulersNumber: Double; external name 'Math.E';
  2496. d: double;
  2497. Begin
  2498. d:=EulersNumber;
  2499. End.
  2500. </pre>
  2501. </td>
  2502. <td>
  2503. <pre>rtl.module("program",
  2504. ["System"],
  2505. function(){
  2506. var $mod = this;
  2507. this.d = 0.0;
  2508. $mod.$main = function(){
  2509. $mod.d = Math.E;
  2510. };
  2511. },
  2512. []);
  2513. </pre>
  2514. </td>
  2515. </tr>
  2516. </tbody>
  2517. </table>
  2518. </div>
  2519. <div class="section">
  2520. <h2 id="externalmembers">The external modifier of class members</h2>
  2521. The method modifier <i>external</i> works as the procedure modifier, except
  2522. it uses the scope of the class or instance.<br>
  2523. The field modifier <i>external</i> works as the var modifier, except
  2524. it uses the scope of the class or instance.<br>
  2525. Requires the modeswitch <b>externalclass</b>.
  2526. <table class="sample">
  2527. <tbody>
  2528. <tr>
  2529. <th>Pascal</th>
  2530. <th>JavaScript</th>
  2531. </tr>
  2532. <tr>
  2533. <td>
  2534. <pre>Program MyModule;
  2535. {$modeswitch externalclass}
  2536. type
  2537. TWrapper = class
  2538. private
  2539. // let's assume this object has the properties "$Handle", "$id", and "0"
  2540. public
  2541. Id: NativeInt; external name '$Id';
  2542. x: NativeInt; external name '[0]';
  2543. y: NativeInt; external name '["A B"]';
  2544. function GetState(typ: longint): NativeInt; external name '$Handle.GetState';
  2545. procedure DoIt;
  2546. end;
  2547. procedure TWrapper.DoIt;
  2548. begin
  2549. Id := GetState(4);
  2550. end;
  2551. var
  2552. W: TWrapper;
  2553. Begin
  2554. W.Id := 2;
  2555. W.x := 3;
  2556. W.y := 4;
  2557. W.GetState(5);
  2558. End.
  2559. </pre>
  2560. </td>
  2561. <td>
  2562. <pre>rtl.module("program",
  2563. ["System"],
  2564. function(){
  2565. var $mod = this;
  2566. rtl.createClass($mod, "TWrapper", pas.System.TObject, function () {
  2567. this.DoIt = function(){
  2568. this.$Id = this.$Handle.GetState(4);
  2569. };
  2570. });
  2571. this.W = null;
  2572. $mod.$main = function(){
  2573. $mod.W.$Id = 2;
  2574. $mod.W[0] = 3;
  2575. $mod.W["A B"] = 4;
  2576. $mod.W.$Handle.GetState(5);
  2577. };
  2578. },
  2579. []);
  2580. </pre>
  2581. </td>
  2582. </tr>
  2583. </tbody>
  2584. </table>
  2585. <ul>
  2586. <li>Non identifiers like "0" or "A B" must be enclosed in brackets.</li>
  2587. </ul>
  2588. </div>
  2589. <div class="section">
  2590. <h2 id="externalclass">External classes</h2>
  2591. pas2js introduces a new class modifier "<i>external name</i>", which makes
  2592. the whole class external.
  2593. External classes allow to easily declare Pascal wrappers for JavaScript
  2594. objects and function objects.<br>
  2595. They need the modeswitch <b>externalclass</b> in front of the class.<br>
  2596. An external class is not a TObject and has none of its methods.<br>
  2597. All members are external. If you omit the <i>external</i> modifier the
  2598. external name is the member name. Keep in mind that JS is case sensitive.<br>
  2599. Destructors are not allowed.<br>
  2600. Constructors are only allowed with the name <i>New</i> and a call
  2601. translates to <i>new ExtClass(params)</i>.
  2602. Properties work the same as with Pascal classes, i.e. are replaced by Getter/Setter.<br>
  2603. <table class="sample">
  2604. <tbody>
  2605. <tr>
  2606. <th>Pascal</th>
  2607. <th>JavaScript</th>
  2608. </tr>
  2609. <tr>
  2610. <td>
  2611. <pre>Program MyModule;
  2612. {$modeswitch externalclass}
  2613. type
  2614. TJSDate = class external name 'Date'
  2615. private
  2616. function getYear: NativeInt;
  2617. procedure setYear(const AValue: NativeInt);
  2618. public
  2619. constructor New;
  2620. constructor New(const MilliSecsSince1970: NativeInt);
  2621. class function now: NativeInt;
  2622. property Year: NativeInt read getYear write setYear;
  2623. end;
  2624. var
  2625. d: TJSDate;
  2626. Begin
  2627. d:=TJSDate.New;
  2628. d.Year:=d.Year+1;
  2629. End.
  2630. </pre>
  2631. </td>
  2632. <td>
  2633. <pre>rtl.module("program",["System"],function () {
  2634. var $mod = this;
  2635. this.d = null;
  2636. $mod.$main = function () {
  2637. $mod.d = new Date();
  2638. $mod.d.setYear($mod.d.getYear() + 1);
  2639. };
  2640. });
  2641. </pre>
  2642. </td>
  2643. </tr>
  2644. </tbody>
  2645. </table>
  2646. Notes:
  2647. <ul>
  2648. <li>Any class instance can be type casted to any root class.</li>
  2649. <li>A Pascal class can descend from an external class.</li>
  2650. <li>You can define a class-of external class and the <b>is</b> and <b>as</b>
  2651. operators work similar.</li>
  2652. <li>Class variables work as in JavaScript. That means, each descendant and each
  2653. instance can have its own value. For example <i>TExtA.Value</i> might be
  2654. different from <i>InstanceExtA.Value</i>. Setting <i>InstanceExtA.Value</i>
  2655. does not change <i>TExtA.Value</i>.</li>
  2656. <li>Const with an expression are replaced by the expression.</li>
  2657. <li>Const without an expression are treated as a readonly variable.</li>
  2658. <li>Class functions and class procedures are allowed, but can only be called via the class, not via an instance.<br>
  2659. For example you can call the class function <i>TJSString.fromCharCode()</i>, but you cannot
  2660. call <i>aJSString.fromCharCode()</i>.</li>
  2661. <li>An external class can descend from another external class.</li>
  2662. <li>Since class types are JS objects it is possible to typecast a class type
  2663. to the JS Object, e.g. <i>TJSObject(TObject)</i>.
  2664. Note that you cannot typecast directly to a <i>TJSObject</i> descendant
  2665. in $mode objfpc. You can use <i>TJSWindow(TJSObject(ExtClassInstance))</i>.</li>
  2666. <li>You can typecast function addresses and function references to JS
  2667. function, e.g. <i>TJSFunction(@SomeProc)</i>, <i>TJSFunction(OnClick)</i>.
  2668. Keep in mind that typecasting a method address creates a function wrapper
  2669. to bind the Self argument.</li>
  2670. </ul>
  2671. </div>
  2672. <div class="section">
  2673. <h2 id="externalclassancestor">External class as ancestor</h2>
  2674. A Pascal class can descend from an external class.<br>
  2675. The methods <i>AfterConstruction</i> and <i>BeforeDestruction</i>
  2676. are called if they exist.<br>
  2677. New instances are created by default with <i>Object.create(ancestorclass)</i>.<br>
  2678. You can override this, by providing a<br>
  2679. <b>class function NewInstance(fnname: string; const paramsarray): TPasClass; virtual;</b>.
  2680. This method is called to create a new instance and before calling the constructor.
  2681. The name is arbitrary, but the function must be the first non private,
  2682. non external, virtual class function with the class as result type.<br>
  2683. <table class="sample">
  2684. <tbody>
  2685. <tr>
  2686. <th>Pascal</th>
  2687. <th>JavaScript</th>
  2688. </tr>
  2689. <tr>
  2690. <td>
  2691. <pre>Program MyModule;
  2692. {$modeswitch externalclass}
  2693. type
  2694. TExtA = class external name 'ExtA'
  2695. end;
  2696. TMyB = class(TExtA)
  2697. protected
  2698. class function NewInstance(fnname: string; const paramarray): TMyB; virtual;
  2699. end;
  2700. class function TMyB.NewInstance(fnname: string; const paramarray): TMyB;
  2701. Begin
  2702. asm
  2703. Result = Object.create(ExtA);
  2704. end;
  2705. End;
  2706. Begin
  2707. End.
  2708. </pre>
  2709. </td>
  2710. <td>
  2711. <pre>rtl.module("program",["System"],function () {
  2712. var $mod = this;
  2713. rtl.createClassExt($mod, "TMyB", ExtA, "NewInstance", function () {
  2714. this.$init = function () {
  2715. };
  2716. this.$final = function () {
  2717. };
  2718. this.NewInstance = function (fnname, paramarray) {
  2719. var Result = null;
  2720. Result = Object.create(ExtA);
  2721. return Result;
  2722. };
  2723. });
  2724. $mod.$main = function () {
  2725. };
  2726. });
  2727. </pre>
  2728. </td>
  2729. </tr>
  2730. </tbody>
  2731. </table>
  2732. </div>
  2733. <div class="section">
  2734. <h2 id="jsvalue">The JSValue type</h2>
  2735. Pas2js introduces a new type <b>JSValue</b>, which works similar to a JS variable.
  2736. You can assign almost any value to it and it can be type casted to many types.
  2737. JSValue is useful for JS wrappers, when a variable can have multiple types.
  2738. And it can be used for containers storing arbitrary data, e.g. a list of JSValue.<br>
  2739. Key features:<br>
  2740. <ul>
  2741. <li>A JSValue variable initial value is undefined.</li>
  2742. <li>Operators: =, &lt;&gt;</li>
  2743. <li>type casting a <i>JSValue</i> to ...
  2744. <ul>
  2745. <li><i>Integer: Math.floor(aJSValue)</i> Note: may return <i>NaN</i></li>
  2746. <li><i>Boolean: !(aJSValue == false)</i> Note: works for numbers too, <i>0==false</i></li>
  2747. <li><i>Double: rtl.getNumber(aJSValue)</i> Note: <i>typeof(n)=="number"?n:NaN;</i></li>
  2748. <li><i>String: ""+aJSValue</i></li>
  2749. <li><i>Char: rtl.getChar(aJSValue)</i> Note: <i>((typeof(c)!="string") && (c.length==1)) ? c : ""</i></li>
  2750. <li>class instance or class-of: <i>rtl.getObject()</i> Note: checks for type <i>"object"</i></li>
  2751. <li>enum type</li>
  2752. <li>pointer</li>
  2753. </ul>
  2754. </li>
  2755. <li>A JSValue in a conditional expressions <i>If aJSValue then, while aJSValue do,
  2756. repeat until aJSValue</i> has the same meaning as in JS: the condition is
  2757. true, if the value is not <i>undefined, false, null, NaN, 0, ''</i>.
  2758. Note that <i>new Boolean(false)</i> is not <i>null</i> and the condition is true.
  2759. </li>
  2760. <li><i>function Assigned(V: jsvalue): boolean</i> returns true if<br>
  2761. <i>(V!=undefined) && (V!=null) && (!rtl.isArray(V) || (V.length > 0))</i></li>
  2762. <li><i>function StrictEqual(const A: jsvalue; const B): boolean</i></li>
  2763. <li><i>function StrictInequal(const A: jsvalue; const B): boolean</i></li>
  2764. <li>Any array can be assigned to an <i>array of jsvalue</i>.</li>
  2765. <li>is-operator: <i>jsvalue is class-type</i>, <i>jsvalue is class-of-type</i><br>
  2766. <li>The unit JS provides many utility functions for JSValue, like <i>hasString,
  2767. hasValue, isBoolean, isNumber, isInteger, isObject, isClass, isClassInstance, etc..</i></li>
  2768. </ul>
  2769. </div>
  2770. <div class="section">
  2771. <h2 id="bracketaccessor">Accessing JS object properties with the bracket accessor</h2>
  2772. Pas2js allows to define index properties that map directly to the JS object properties.
  2773. For example the default property of TJSObject allows to get and set the
  2774. properties of an object. For example <i>TJSObject(AnObject)['Name']:=Value;</i><br>
  2775. Another example is the default property of TJSArray, that allows access via integers
  2776. <i>aTJSArray[3]:=Value;</i><br>
  2777. To define your own bracket accessor define a normal index property and define
  2778. the getter/setter as <i>external name '[]'</i>.<br>
  2779. Here is an example for a read only accessor:
  2780. <table class="sample">
  2781. <tbody>
  2782. <tr>
  2783. <th>Pascal</th>
  2784. <th>JavaScript</th>
  2785. </tr>
  2786. <tr>
  2787. <td>
  2788. <pre>Program MyModule;
  2789. {$modeswitch externalclass}
  2790. type
  2791. TExtA = class external name 'ExtA'
  2792. private
  2793. function GetItems(Index: integer): String; external name '[]';
  2794. public
  2795. property Items[Index: integer]: String read GetItems; default;
  2796. end;
  2797. var
  2798. Obj: TExtA;
  2799. s: String;
  2800. Begin
  2801. ... get Obj from somewhere ...
  2802. s:=Obj[2];
  2803. End.
  2804. </pre>
  2805. </td>
  2806. <td>
  2807. <pre>rtl.module("program",["System"],function () {
  2808. var $mod = this;
  2809. this.Obj = undefined;
  2810. this.s = "";
  2811. $mod.$main = function () {
  2812. $mod.s = Obj[2];
  2813. };
  2814. });
  2815. </pre>
  2816. </td>
  2817. </tr>
  2818. </tbody>
  2819. </table>
  2820. Notes:
  2821. <ul>
  2822. <li>A property can have a mix of normal accessor and bracket accessor.
  2823. For example a bracket accessor as getter and a normal function as setter.</li>
  2824. </ul>
  2825. </div>
  2826. <div class="section">
  2827. <h2 id="rtti">RTTI - Run Time Type Information</h2>
  2828. The RTTI provides access to the type data of all published properties,
  2829. fields and methods. The type data provides similar information as Delphi/FPC,
  2830. but the internals are very different. Delphi/FPC uses pointers,
  2831. variant records and fake static arrays, which have no equivalent in JS.
  2832. Instead pas2js uses external classes. For example:
  2833. <pre>
  2834. TTypeInfo = class external name 'rtl.tTypeInfo'
  2835. public
  2836. Name: String external name 'name';
  2837. Kind: TTypeKind external name 'kind';
  2838. end;
  2839. TTypeInfoClass = class of TTypeInfo;
  2840. TTypeInfoInteger = class external name 'rtl.tTypeInfoInteger'(TTypeInfo)
  2841. public
  2842. MinValue: NativeInt external name 'minvalue';
  2843. MaxValue: NativeInt external name 'maxvalue';
  2844. OrdType : TOrdType external name 'ordtype';
  2845. end;
  2846. </pre>
  2847. The <b>typeinfo</b> function works on type, var, const and property identifiers.
  2848. By default it returns a <i>pointer</i>. If the typinfo unit is used it returns the
  2849. appropiate <i>TTypeInfo</i>. For instance <i>typeinfo(integer)</i> returns
  2850. a <i>TTypeInfoInteger</i>.<br>
  2851. <i>Typeinfo</i> of a <i>var</i> or <i>const</i> returns the typeinfo of its
  2852. type, not of its current runtime value. The exception is a class and class-of instance
  2853. variable (e.g. <i>var o: TObject; ... typeinfo(o)</i>), which returns the
  2854. typeinfo of the current runtime value.
  2855. If <i>o</i> is <i>null</i> it will give a JS error.<br>
  2856. Local types (i.e. inside a procedure) do not have typeinfo.<br>
  2857. Open array parameters are not yet supported.<br>
  2858. </div>
  2859. <div class="section">
  2860. <h2 id="compilerdirectives">Compiler directives</h2>
  2861. In config files:
  2862. <ul>
  2863. <li>#IFDEF macroname</li>
  2864. <li>#IFNDEF macroname</li>
  2865. <li>#IF expression - same as $if, except only defines</li>
  2866. <li>#ELSEIF</li>
  2867. <li>#ELSE</li>
  2868. <li>#ENDIF</li>
  2869. <li>#ERROR text</li>
  2870. </ul>
  2871. In source files:
  2872. <ul>
  2873. <li>{$Define <i>MacroName</i>}: defines macro <i>MacroName</i> with value '1'.</li>
  2874. <li>{$Define <i>MacroName:=value</i>}: defines macro <i>MacroName</i> with custom value.</li>
  2875. <li>{$Undef <i>MacroName</i>}: undefines macro <i>MacroName</i>.</li>
  2876. <li>{$IfDef <i>MacroName</i>}: if <i>MacroName</i> is not defined, skip to next $Else or $EndIf. Can be nested.</li>
  2877. <li>{$IfNDef <i>MacroName</i>}: as $IfDef, except negated.</li>
  2878. <li>{$If <i>boolean expression</i>}: if <i>expression</i> evaluates to true
  2879. (not '0'), skip to next $Else or $EndIf. Can be nested.<br>
  2880. Supported functions and operators:<br>
  2881. <ul>
  2882. <li>macro - replaced by its value, a simple define has value '1'</li>
  2883. <li>defined(macro) - '1' if defined, '0' otherwise</li>
  2884. <li>undefined(macro) - as <i>not defined(macro)</i></li>
  2885. <li>option(letter) - same as <i>{$IFOpt letter+}</i></li>
  2886. <li>not - first level of precedence</li>
  2887. <li>*, /, div, mod, and, shl, shr - second level of precedence</li>
  2888. <li>+, -, or, xor - third level of precedence</li>
  2889. <li>=, &lt;&gt;, &lt;, &gt;, &lt;=, &gt;= - fourth level of precedence</li>
  2890. <li>If the operands can be converted to numbers they are combined as numbers, otherwise as strings.</li>
  2891. </ul>
  2892. Not supported functions and operators:<br>
  2893. <ul>
  2894. <li>defined(Pascal identifier), undefined(Pascal identifier)</li>
  2895. <li>declared(Pascal identifier)</li>
  2896. <li>in operator</li>
  2897. </ul>
  2898. </li>
  2899. <li>{$IfOpt <i>Letter+,-</i>}: if <i>expression</i> evaluates to true (not '0'), skip to next $Else or $EndIf. Can be nested.</li>
  2900. <li>{$Else}: If previous $IfDef, $If or $IfOpt was skipped, execute next block, otherwise skip.</li>
  2901. <li>{$ElseIf <i>boolean expression</i>}: As $Else, except with an extra expression like $if to test. There can be multiple $elseif.</li>
  2902. <li>{$EndIf}: ends an $IfDef block</li>
  2903. <li>{$mode delphi} or {$mode objfpc}: Same as -Mdelphi or -Mobjfpc, but only for this unit. You can use units of both modes in a program. If present must be at the top of the unit, or after the module name.</li>
  2904. <li>{$modeswitch externalclass}: allow declaring external classes</li>
  2905. <li>{$modeswitch arrayoperators}: allow + operator to concatenate arrays, default in mode delphi</li>
  2906. <li>{$macro on|off} enables macro replacements. Only macros with a value are replaced. Macros are never replaced inside directives.</li>
  2907. <li>{$I filename} or {$include filename} - insert include file</li>
  2908. <li>{$I %param%}:
  2909. <ul>
  2910. <li>%date%: current date as string literal, '[yyyy/mm/dd]'</li>
  2911. <li>%time%: current time as string literal, 'hh:mm:ss'. Note that the
  2912. inclusion of %date% and %time% will not cause the compiler to
  2913. recompile the unit every time it is used:
  2914. the date and time will be the date and time when the unit was last compiled.</li>
  2915. <li>%file%: current source filename as string literal, e.g. <i>'unit1.pas'</i></li>
  2916. <li>%line%: current source line number as string literal, e.g. <i>'123'</i></li>
  2917. <li>%linenum%: current source line number as integer, e.g. <i>123</i></li>
  2918. <li>%currentroutine%: name of current routine as string literal</li>
  2919. <li>%pas2jstarget%, %pas2jstargetos%, %fpctarget%, %fpctargetos%: target os as string literal, e.g. 'Browser'</li>
  2920. <li>%pas2jstargetcpu%, %fpctargetcpu%: target cpu as string literal, e.g. 'ECMAScript5'</li>
  2921. <li>%pas2jsversion%, %fpcversion%: compiler version as strnig literal, e.g. '1.0.2'</li>
  2922. <li>If param is none of the above it will use the environment variable.
  2923. Keep in mind that depending on the platform the name may be case sensitive.
  2924. If there is no such variable an empty string <i>''</i> is inserted.</li>
  2925. </ul>
  2926. </li>
  2927. <li>{$Warnings on|off}</li>
  2928. <li>{$Notes on|off}</li>
  2929. <li>{$Hints on|off}</li>
  2930. <li>{$Error text} : emit an error</li>
  2931. <li>{$Warning text} : emit a warning</li>
  2932. <li>{$Note text} : emit a note</li>
  2933. <li>{$Hint text} : emit a hint</li>
  2934. <li>{$Message hint-text} : emit a hint</li>
  2935. <li>{$Message hint|note|warn|error|fatal text} : emit a message</li>
  2936. <li>{$Warn identifier on|off|default|error} : enable or disable a specific hint.<br>
  2937. Note, that some hints like "Parameter %s not used" are currently using the enable state at the end of the module, not the state at the hint source position.<br>
  2938. Identifier can be a message number as written by -vq or one of the following case insensitive:<br>
  2939. <ul>
  2940. <li>CONSTRUCTING_ABSTRACT: Constructing an instance of a class with abstract methods.</li>
  2941. <li>IMPLICIT_VARIANTS: Implicit use of the variants unit.</li>
  2942. <li>NO_RETVAL: Function result is not set</li>
  2943. <li>SYMBOL_DEPRECATED: Deprecated symbol.</li>
  2944. <li>SYMBOL_EXPERIMENTAL: Experimental symbol</li>
  2945. <li>SYMBOL_LIBRARY</li>
  2946. <li>SYMBOL_PLATFORM: Platform-dependent symbol.</li>
  2947. <li>SYMBOL_UNIMPLEMENTED: Unimplemented symbol.</li>
  2948. <li>HIDDEN_VIRTUAL: method hides virtual method of ancestor</li>
  2949. <li>GARBAGE: text after final end.</li>
  2950. <li>BOUNDS_ERROR: range check errors</li>
  2951. <li>MESSAGE_DIRECTIVE: user defined $message</li>
  2952. </ul>
  2953. </li>
  2954. <li>{$M+}, {$TypeInfo on}: switches default visibility for class members from public to published</li>
  2955. <li>{$ScopedEnums on|off} disabled(default): propagate enums to global scope, enable: needs fqn e.g. TEnumType.EnumValue.</li>
  2956. <li>{$C+} generate code for assertions</li>
  2957. <li>{$H+}, but not {$H-}</li>
  2958. <li>{$J-}, {$WriteableConst off}: Typed const become readonly. For example <i>const i:byte=3; ... i:=4</i> creates a compile time error.</li>
  2959. <li>{$M+} : allow published members
  2960. <li>{$Q+} : not yet supported, ignored
  2961. <li>{$R+}, {$RangeChecks on}: compile time range check hints become errors
  2962. and add runtime range checks for assignments.</li>
  2963. <li>{$ObjectChecks on|off}:
  2964. <ul>
  2965. <li>Verify method calls, i.e. check at runtime in every method if <i>Self</i> is a descendant class.</li>
  2966. <li>Check type casts, e.g. <i>TBird(AnObject)</i> becomes <i>AnObject as TBird</i></li>
  2967. </ul>
  2968. </li>
  2969. </ul>
  2970. Defines:
  2971. <ul>
  2972. <li>PASJS</li>
  2973. <li>PAS2JS_FULLVERSION - major*1000+minor*100+release, e.g. 1.2.3 = 10203</li>
  2974. <li>Target platform: Browser, NodeJS, Pas2JSTargetOS=&lt;value&gt;</li>
  2975. <li>Target processor: ECMAScript5, ECMAScript6, ECMAScript=5, Pas2JSTargetCPU=&lt;value&gt;</li>
  2976. <li>Mode: DELPHI, OBJFPC</li>
  2977. </ul>
  2978. </div>
  2979. <div class="section">
  2980. <h2 id="numbers">Numbers</h2>
  2981. JavaScript only supports double. All Pascal number types and enum values
  2982. are mapped to this. A double supports integers from<br>
  2983. MinInteger = -$10000000000000;<br>
  2984. MaxInteger = $fffffffffffff;<br>
  2985. MinDouble = 5.0e-324;<br>
  2986. MaxDouble = 1.7e+308;<br>
  2987. <br>
  2988. Intrinsic integer types:
  2989. <ul>
  2990. <li>Byte - unsigned 8-bit</li>
  2991. <li>ShortInt - signed 8-bit</li>
  2992. <li>Word - unsigned 16-bit</li>
  2993. <li>SmallInt - signed 16-bit</li>
  2994. <li>LongWord - unsigned 32-bit</li>
  2995. <li>LongInt - signed 32-bit</li>
  2996. <li>NativeUInt - unsigned 53-bit</li>
  2997. <li>NativeInt - signed 54-bit</li>
  2998. </ul>
  2999. Notes:
  3000. <ul>
  3001. <li>Division by zero does not raise an exception. 0/0 results in NaN, positive/0 is Infinity, negative/0 is -Infinity.</li>
  3002. <li>NaN&lt;&gt;NaN</li>
  3003. <li>Overflows work differently. For example in Delphi adding 100 to a byte of 200 gives <i>300 and $ff = 44</i>, while in pas2js it gives 300, which is not a byte anymore.</li>
  3004. <li>Math.isNan(double) tests for NaN. Otherwise false. isNan(Infinity)=false.</li>
  3005. <li>Math.isFinite(double) tests if not NaN, positive or negative infinity.</li>
  3006. <li>Math.isInfinite(double) tests if positive or negative infinity.</li>
  3007. <li>For more functions see unit Math.</li>
  3008. <li>To make porting easier Single is defined in the system unit as alias of
  3009. double, but gives a warning. Since using higher precision might give
  3010. unexpected results you should check every place.</li>
  3011. </ul>
  3012. </div>
  3013. <div class="section">
  3014. <h2 id="othersupportedelements">Other supported Pascal elements</h2>
  3015. <ul>
  3016. <li><b>break</b>, <b>continue</b>, <b>exit</b>, <b>exit()</b></li>
  3017. <li><b>chr</b>, <b>ord</b></li>
  3018. <li>alias type and type alias type</li>
  3019. <li>inc()/dec() to += -=</li>
  3020. <li>Converts "a div b" to "Math.floor(a / b)"</li>
  3021. <li>and, or, xor, not: logical and bitwise</li>
  3022. <li>Name conflicts with JS identifiers are automatically fixed by changing case.
  3023. For example a Pascal function "<i>apply"</i> is renamed to "<i>Apply</i>".</li>
  3024. <li>uses unitname in 'filename'.
  3025. In <i>$mode delphi</i> the in-filenames are only allowed in the program
  3026. and the unitname must fit the filename,
  3027. e.g. <i>uses unit1 in 'sub/Unit1.pas'</i>.<br>
  3028. In <i>$mode objfpc</i> units can use in-filenames too and
  3029. alias are allowed, e.g. <i>uses foo in 'bar.pas'</i>.</li>
  3030. <li>The intrinsic procedure <b>str</b> works with boolean, integer, float and enumvalue.<br>
  3031. Additionally there is <b>str</b> function, that takes an arbitrary number of
  3032. arguments and returns a concatenated string. It supports string as parameter too.
  3033. For example s:=str(i,' ',d:1:5).<br>
  3034. Width and precision is supported. str(i:10) will add spaces to the left to fill up to 10 characters.</b>
  3035. str(aDouble:1:5) returns a string in decimal format with 5 digits for the fraction.</li>
  3036. <li>Intrinsic procedure WriteStr(out s: string; params...)</li>
  3037. <li><i>Debugger;</i> converts to <i>debugger;</i>. If a debugger is running
  3038. it will break on this line just like a break point.</li>
  3039. <li><i>function concat(string1,string2,...): string</i> since 1.3</li>
  3040. <li><i>$mode delphi: function lo|hi(integer): byte</i> since 1.3</li>
  3041. <li><i>$mode objfpc: function lo|hi(integer): byte|word|longword</i> since 1.3</li>
  3042. </ul>
  3043. </div>
  3044. <div class="section">
  3045. <h2 id="notsupportedelements">Not supported elements</h2>
  3046. <ul>
  3047. <li>Class destructor</li>
  3048. <li>Enums with custom values</li>
  3049. <li>Generics</li>
  3050. <li>Global properties</li>
  3051. <li>Futures</li>
  3052. <li>Inline</li>
  3053. <li>Library</li>
  3054. <li>Objects</li>
  3055. <li>Operator overloading</li>
  3056. <li>Pointer arithmetic</li>
  3057. <li>Package</li>
  3058. <li>Resources</li>
  3059. <li>RTTI extended, $RTTI</li>
  3060. <li>Variant records</li>
  3061. <li>Variants</li>
  3062. </ul>
  3063. </div>
  3064. <div class="section">
  3065. <h2 id="targetprocessor">JavaScript Version</h2>
  3066. Code generation depending on -P option:
  3067. <ul>
  3068. <li>ECMAScript5</li>
  3069. <li>ECMAScript6: using 0b for binary literals, and 0o for octal literals</li>
  3070. </ul>
  3071. </div>
  3072. <div class="section">
  3073. <h2 id="sourcemaps">Creating source maps</h2>
  3074. Source maps are files telling the browser what JavaScript comes from which
  3075. original source (e.g. Pascal file), similar to debug information in FPC/Delphi.<br>
  3076. In 2017 FireFox and Chrome supports source maps.<br>
  3077. You can enable generating source map files by using the <i>-Jm</i> option.<br>
  3078. The compiler generates one module.js.map file for every generated module.js file.
  3079. The last line of the .js file contains the line<br>
  3080. <i>//# sourceMappingURL=module.js.map</i><br>
  3081. telling the browser where to find the source map.<br>
  3082. The source map contains references to the Pascal files and included .js
  3083. files (e.g. -Jirtl.js) relative to the location of the source map.
  3084. Note that if the Pascal file lies in a parent directory, the relativ path
  3085. contains '../'. You can change the base directory of the relative paths by using
  3086. the option <i>-Jmbasedir=&lt;x&gt;</i>. For example <i>-JmC:\www\pas</i>
  3087. creates paths relative to C:\www\pas.<br>
  3088. You can set the base URL, where the browser finds the Pascal sources, by passing
  3089. the <i>-Jmsourceroot=&lt;x&gt;</i> option. For example
  3090. <i>-Jmsourceroot=http://www.yoursite.com/pas/</i>. The browser prepends this
  3091. to the source map filenames when downloading the original source files
  3092. (e.g. the .pas files).<br>
  3093. You can include the whole Pascal sources in the source map using the option
  3094. <i>-Jminclude</i>.<br>
  3095. <br>
  3096. To show the generated mapping for each line you can use the tool fpc/packages/fcl-js/examples/srcmapdump.<br>
  3097. <li>Option -JmXSSIHeader: According to the specifications sourcemap
  3098. should start with the XSSI (cross site script inclusion) protection header
  3099. <i>)]}'</i>. If your browser does not support that,
  3100. disable it with <i>-JmXSSIHeader-</i>. See here the specs:
  3101. https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.h7yy76c5il9v
  3102. </li>
  3103. </div>
  3104. <div id="footer">
  3105. </div>
  3106. </body>
  3107. </html>