translation.html 101 KB

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