translation.html 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162
  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. TJSObject(TPoint)</li>
  732. <li>A pointer of record is simply a reference.
  733. <ul>
  734. <li><i>p:=@r</i> translates to <i>p=r</i></li>
  735. <li><i>p^.x</i> becomes <i>p.x</i>.</li>
  736. <li><i>New(PointerOfRecord)</i> creates a new record</li>
  737. <li><i>Dispose(PointerOfRecord)</i> Sets the variable to null if possible.</li>
  738. </ul>
  739. </li>
  740. </ul>
  741. </div>
  742. <div class="section">
  743. <h2 id="functions">Translating functions</h2>
  744. <table class="sample">
  745. <tbody>
  746. <tr>
  747. <th>Pascal</th>
  748. <th>JavaScript</th>
  749. </tr>
  750. <tr>
  751. <td>
  752. <pre>Unit MyModule;
  753. Interface
  754. Function DoubleIt(n: integer): integer;
  755. Implementation
  756. Function DoubleIt(n: integer): integer;
  757. Begin
  758. Result:=2*n;
  759. End;
  760. End.
  761. </pre>
  762. </td>
  763. <td>
  764. <pre>rtl.module("MyModule",
  765. ["System"],
  766. function(){
  767. this.DoubleIt = function(n){
  768. Result = 0;
  769. Result = 2*n;
  770. return Result;
  771. };
  772. },
  773. []);
  774. </pre>
  775. </td>
  776. </tr>
  777. </tbody>
  778. </table>
  779. Notes:
  780. <ul>
  781. <li>Local variables become local JavaScript variables: <i>var l = 0;</i>.</li>
  782. <li>Local constants become JavaScript variables in the unit/program implementation section.</li>
  783. <li>Overloaded functions are given an unique name by appending $1, $2, ...<br>
  784. Overloading is always on. You don't need to add the <i>overload</i> modifier.</li>
  785. <li>Supported: default values, local types, FuncName:=</li>
  786. </ul>
  787. </div>
  788. <div class="section">
  789. <h2 id="passbyref">Translating passing a parameter by reference</h2>
  790. JavaScript lacks passing by reference. Instead a temporary object is created
  791. with a <i>get</i> and <i>set</i> function.
  792. That means changes within the procedure are immediately visible outside, compatible with Pascal.
  793. <table class="sample">
  794. <tbody>
  795. <tr>
  796. <th>Pascal</th>
  797. <th>JavaScript</th>
  798. </tr>
  799. <tr>
  800. <td>
  801. <pre>Program MyModule;
  802. Procedure DoubleIt(var n: integer);
  803. Begin
  804. n:=2*n;
  805. End;
  806. Function Doubling(n: integer): integer;
  807. Begin
  808. DoubleIt(n);
  809. Result:=n;
  810. End;
  811. Var
  812. i: integer = 7;
  813. Begin
  814. Doubling(i);
  815. End.
  816. </pre>
  817. </td>
  818. <td>
  819. <pre>rtl.module("program",
  820. ["System"],
  821. function(){
  822. var $mod = this;
  823. this.i = 7;
  824. this.DoubleIt = function(n){
  825. n.set(2*n.get());
  826. };
  827. this.Doubling = function(n){
  828. var Result = 0;
  829. DoubleIt({
  830. get:function(){
  831. return n
  832. },
  833. set:function(v){
  834. n=v;
  835. }
  836. });
  837. Result = n;
  838. return n;
  839. };
  840. $mod.$main = function(){
  841. Doubling($mod.i);
  842. }
  843. },
  844. []);
  845. </pre>
  846. </td>
  847. </tr>
  848. </tbody>
  849. </table>
  850. When the passed value is from another context, the context is passed too:
  851. <table class="sample">
  852. <tbody>
  853. <tr>
  854. <th>Pascal</th>
  855. <th>JavaScript</th>
  856. </tr>
  857. <tr>
  858. <td>
  859. <pre>Program MyModule;
  860. Procedure DoubleIt(var n: integer);
  861. Begin
  862. n:=2*n;
  863. End;
  864. Var
  865. i: integer = 7;
  866. Begin
  867. DoubleIt(i);
  868. End.
  869. </pre>
  870. </td>
  871. <td>
  872. <pre>rtl.module("program",
  873. ["System"],
  874. function(){
  875. var $mod = this;
  876. this.i = 7;
  877. this.DoubleIt = function(n){
  878. n.set(2*n.get());
  879. };
  880. $mod.$main = function(){
  881. DoubleIt({
  882. p:$mod,
  883. get:function(){
  884. return this.p.i
  885. },
  886. set:function(v){
  887. this.p.i=v;
  888. }
  889. });
  890. }
  891. },
  892. []);
  893. </pre>
  894. </td>
  895. </tr>
  896. </tbody>
  897. </table>
  898. Notes:
  899. <ul>
  900. <li>Contrary to Delphi/FPC it is allowed to pass a property to a </i>var/out</i> parameter.</li>
  901. </ul>
  902. </div>
  903. <div class="section">
  904. <h2 id="nested functions">Translating nested functions</h2>
  905. A nested function is translated to a local variable.
  906. <table class="sample">
  907. <tbody>
  908. <tr>
  909. <th>Pascal</th>
  910. <th>JavaScript</th>
  911. </tr>
  912. <tr>
  913. <td>
  914. <pre>Unit MyModule;
  915. Interface
  916. Function SumNNumbers(n, Adder: integer): integer;
  917. Implementation
  918. Function SumNNumbers(n, Adder: integer): integer;
  919. Function Add(k: integer): integer;
  920. Begin
  921. if k=1 then
  922. Result:=1
  923. else
  924. Result:=Add(k-1)+Adder;
  925. End;
  926. Begin
  927. Result:=Add(n);
  928. End;
  929. End.
  930. </pre>
  931. </td>
  932. <td>
  933. <pre>rtl.module("MyModule",
  934. ["System"],
  935. function(){
  936. this.DoubleIt = function(n,Adder){
  937. Result = 0;
  938. var Add = function(k) {
  939. Result = 0;
  940. if (k==1) {
  941. Result = 1;
  942. } else {
  943. Result = Add(k-1)+Adder;
  944. }
  945. return Result;
  946. };
  947. Result = Add(n);
  948. return Result;
  949. };
  950. },
  951. []);
  952. </pre>
  953. </td>
  954. </tr>
  955. </tbody>
  956. </table>
  957. Note: You can assign a nested procedure to a procedure variable. A nested
  958. procedure of a method can be assigned to a method variable.<br>
  959. JavaScript preserves the current local scope, including references to the
  960. local variables of parent functions. Local types and constants belong to the
  961. unit scope (singleton).<br>
  962. When a method has nested functions, the compiler adds a local var <i>Self</i>.
  963. </div>
  964. <div class="section">
  965. <h2 id="forloop">Translating for-loops</h2>
  966. The JavaScript for-loop executes the end expression every iteration, while
  967. Pascal only executes it once. Therefore a local variable is introduced.
  968. If the loop is not entered at all, the variable is not touched. If the loop
  969. was entered the variable contanis the last value.
  970. <table class="sample">
  971. <tbody>
  972. <tr>
  973. <th>Pascal</th>
  974. <th>JavaScript</th>
  975. </tr>
  976. <tr>
  977. <td>
  978. <pre>Unit MyModule;
  979. Interface
  980. Function SumNNumbers(n: integer): integer;
  981. Implementation
  982. Function SumNNumbers(n: integer): integer;
  983. Var
  984. i, j: integer;
  985. Begin
  986. j:=0;
  987. For i:=1 To n Do
  988. Begin
  989. j:=j+i;
  990. End;
  991. if i&lt;1 then j:=1;
  992. Result:=j;
  993. End;
  994. End.
  995. </pre>
  996. </td>
  997. <td>
  998. <pre>rtl.module("MyModule",
  999. ["System"],
  1000. function(){
  1001. this.SumNNumbers=function(n){
  1002. Result = 0;
  1003. j = 0;
  1004. for (var $l1 = 1, $le2 = n; $l1 &lt;= $le2; $l1++) {
  1005. i = $l1;
  1006. j = j + i;
  1007. };
  1008. if (i&lt;1) j=1;
  1009. Result = j;
  1010. return Result;
  1011. };
  1012. },
  1013. []);
  1014. </pre>
  1015. </td>
  1016. </tr>
  1017. </tbody>
  1018. </table>
  1019. Note: The after-loop decrement is only added if <i>i</i> is read after the loop.<br>
  1020. </div>
  1021. <div class="section">
  1022. <h2 id="repeatuntil">Translating repeat..until</h2>
  1023. The <i>repeat..until</i> is translated to a <i>do{}while()</i>.
  1024. <table class="sample">
  1025. <tbody>
  1026. <tr>
  1027. <th>Pascal</th>
  1028. <th>JavaScript</th>
  1029. </tr>
  1030. <tr>
  1031. <td>
  1032. <pre>Unit MyModule;
  1033. Interface
  1034. Function SumNNumbers(n: integer): integer;
  1035. Implementation
  1036. Function SumNNumbers(n: integer): integer;
  1037. Var
  1038. i, j: integer;
  1039. Begin
  1040. j:=0;
  1041. i:=0;
  1042. Repeat
  1043. i:=i+1;
  1044. j:=j+i;
  1045. Until i>=n;
  1046. Result:=j;
  1047. End;
  1048. End.
  1049. </pre>
  1050. </td>
  1051. <td>
  1052. <pre>rtl.module("MyModule",
  1053. ["System"],
  1054. function(){
  1055. this.SumNNumbers=function(n){
  1056. Result = 0;
  1057. j = 0;
  1058. i = 0;
  1059. do{
  1060. i = (i + 1);
  1061. j = (j + i);
  1062. } while (!(i>=n));
  1063. Result = j;
  1064. return Result;
  1065. };
  1066. },
  1067. []);
  1068. </pre>
  1069. </td>
  1070. </tr>
  1071. </tbody>
  1072. </table>
  1073. </div>
  1074. <div class="section">
  1075. <h2 id="whiledo">Translating while..do</h2>
  1076. <table class="sample">
  1077. <tbody>
  1078. <tr>
  1079. <th>Pascal</th>
  1080. <th>JavaScript</th>
  1081. </tr>
  1082. <tr>
  1083. <td>
  1084. <pre>Unit MyModule;
  1085. Interface
  1086. Function SumNNumbers(n: integer): integer;
  1087. Implementation
  1088. Function SumNNumbers(n: integer): integer;
  1089. Var
  1090. i, j: integer;
  1091. Begin
  1092. j:=0;
  1093. i:=0;
  1094. While i&lt;n Do Begin
  1095. i:=i+1;
  1096. j:=j+i;
  1097. End;
  1098. Result:=j;
  1099. End;
  1100. End.
  1101. </pre>
  1102. </td>
  1103. <td>
  1104. <pre>rtl.module("MyModule",
  1105. ["System"],
  1106. function(){
  1107. this.SumNNumbers=function(n){
  1108. var Result = 0;
  1109. var j = 0;
  1110. var i = 0;
  1111. while(i&lt;n){
  1112. i = (i + 1);
  1113. j = (j + i);
  1114. };
  1115. Result = j;
  1116. return Result;
  1117. };
  1118. },
  1119. []);
  1120. </pre>
  1121. </td>
  1122. </tr>
  1123. </tbody>
  1124. </table>
  1125. </div>
  1126. <div class="section">
  1127. <h2 id="casedo">Translating case..do</h2>
  1128. Although JavaScript has something similar in form of the "switch" statement,
  1129. it lacks ranges and is on current JS engines often slower than "if-else".
  1130. Therefore a case..of is translated to if..else.
  1131. <table class="sample">
  1132. <tbody>
  1133. <tr>
  1134. <th>Pascal</th>
  1135. <th>JavaScript</th>
  1136. </tr>
  1137. <tr>
  1138. <td>
  1139. <pre>Program MyModule;
  1140. Var
  1141. i: integer;
  1142. Begin
  1143. case i of
  1144. 1: ;
  1145. 2: i:=3;
  1146. else
  1147. i:=4;
  1148. end;
  1149. End.
  1150. </pre>
  1151. </td>
  1152. <td>
  1153. <pre>rtl.module("program",
  1154. ["System"],
  1155. function(){
  1156. var $mod = this;
  1157. this.i = 0;
  1158. $mod.$main=function(n){
  1159. $tmp1 = $mod.i;
  1160. if ($tmp1 == 1){
  1161. } else if ($tmp1 == 2) {
  1162. i=3;
  1163. } else {
  1164. i=4;
  1165. }
  1166. };
  1167. },
  1168. []);
  1169. </pre>
  1170. </td>
  1171. </tr>
  1172. </tbody>
  1173. </table>
  1174. </div>
  1175. <div class="section">
  1176. <h2 id="withdo">Translating with..do</h2>
  1177. JavaScript has a <b>with</b>, but it is slow and deprecated.
  1178. Instead a temporary variable is used:
  1179. <table class="sample">
  1180. <tbody>
  1181. <tr>
  1182. <th>Pascal</th>
  1183. <th>JavaScript</th>
  1184. </tr>
  1185. <tr>
  1186. <td>
  1187. <pre>Unit MyModule;
  1188. Interface
  1189. type
  1190. TClassA = class
  1191. i: integer;
  1192. end;
  1193. procedure DoIt;
  1194. Implementation
  1195. procedure DoIt;
  1196. begin
  1197. with TClassA.Create do
  1198. i:=3;
  1199. end;
  1200. End.
  1201. </pre>
  1202. </td>
  1203. <td>
  1204. <pre>rtl.module("MyModule",
  1205. ["System"],
  1206. function(){
  1207. var $mod = this;
  1208. rtl.createClass($mod, "TClassA", pas.System.TObject, function () {
  1209. this.$init = function () {
  1210. this.i = 0;
  1211. };
  1212. });
  1213. this.DoIt = function(){
  1214. var $with1 = $mod.TClassA.$create("Create");
  1215. $with1.i = 3;
  1216. };
  1217. },
  1218. []);
  1219. </pre>
  1220. </td>
  1221. </tr>
  1222. </tbody>
  1223. </table>
  1224. Note: If the with-expression is already a local variable no new variable is
  1225. created. This is Delphi/FPC compatible.
  1226. </div>
  1227. <div class="section">
  1228. <h2 id="enums">Translating enums</h2>
  1229. Enum values are translated to numbers. The enum type is translated to an
  1230. object containing a mapping from name to number and number to name.
  1231. <table class="sample">
  1232. <tbody>
  1233. <tr>
  1234. <th>Pascal</th>
  1235. <th>JavaScript</th>
  1236. </tr>
  1237. <tr>
  1238. <td>
  1239. <pre>Unit MyModule;
  1240. Interface
  1241. type
  1242. TMyEnum = (
  1243. Red,
  1244. Green,
  1245. Blue);
  1246. var
  1247. e: TMyEnum = Blue;
  1248. procedure DoIt;
  1249. Implementation
  1250. procedure DoIt;
  1251. begin
  1252. e := Green;
  1253. end;
  1254. End.
  1255. </pre>
  1256. </td>
  1257. <td>
  1258. <pre>rtl.module("MyModule",
  1259. ["System"],
  1260. function(){
  1261. var $mod = this;
  1262. this.TMyEnum = {
  1263. "0":"Red",
  1264. Red:0,
  1265. "1":"Green",
  1266. Green:1,
  1267. "2":"Blue",
  1268. Blue:2
  1269. };
  1270. this.e = $mod.TMyEnum.Blue;
  1271. this.DoIt = function(){
  1272. $mod.e = $mod.TMyEnum.Green;
  1273. };
  1274. },
  1275. []);
  1276. </pre>
  1277. </td>
  1278. </tr>
  1279. </tbody>
  1280. </table>
  1281. <ul>
  1282. <li>Supported: ord(), low(), high(), pred(), succ(), type cast number to enum.</li>
  1283. <li>With optimization level -O1 the compiler uses numbers instead of names.</li>
  1284. <li>Not yet implemented: custom values for enum values.</li>
  1285. </ul>
  1286. </div>
  1287. <div class="section">
  1288. <h2 id="sets">Translating sets</h2>
  1289. A set s is translated to a JavaScript object, where for each included enum
  1290. holds <i>s.enumvalue==true</i>.
  1291. This allows arbitrary large sets and the <i>in</i> operator is fast.
  1292. <table class="sample">
  1293. <tbody>
  1294. <tr>
  1295. <th>Pascal</th>
  1296. <th>JavaScript</th>
  1297. </tr>
  1298. <tr>
  1299. <td>
  1300. <pre>Unit MyModule;
  1301. Interface
  1302. type
  1303. TColor = (Red, Green, Blue);
  1304. TColors = set of TColor;
  1305. procedure DoIt;
  1306. Implementation
  1307. procedure DoIt;
  1308. var
  1309. c: TColor;
  1310. S, T: TColors;
  1311. b: boolean;
  1312. begin
  1313. S:=T;
  1314. b:=Red in S;
  1315. Include(S,Blue);
  1316. Exclude(S,Blue);
  1317. S:=S+T;
  1318. S:=S-[Red,c];
  1319. b:=c in [Red..Blue];
  1320. end;
  1321. End.
  1322. </pre>
  1323. </td>
  1324. <td>
  1325. <pre>rtl.module("MyModule",
  1326. ["System"],
  1327. function(){
  1328. var $mod = this;
  1329. this.TColor = {
  1330. "0":"Red",
  1331. Red:0,
  1332. "1":"Green",
  1333. Green:1,
  1334. "2":"Blue",
  1335. Blue:2
  1336. };
  1337. $mod.DoIt = function(){
  1338. var c = 0;
  1339. var S = {};
  1340. var T = {};
  1341. var b = false;
  1342. S = rtl.refSet(T);
  1343. b = $mod.TColor.Red in S;
  1344. S = rtl.includeSet(S,$mod.TColor.Blue);
  1345. S = rtl.excludeSet(S,$mod.TColor.Blue);
  1346. S = rtl.unionSet(S,T);
  1347. S = rtl.diffSet(S,rtl.createSet($mod.TColor.Red,c));
  1348. b = c in rtl.createSet(null,$mod.TColor.Red,$mod.TColor.Blue);
  1349. };
  1350. },
  1351. []);
  1352. </pre>
  1353. </td>
  1354. </tr>
  1355. </tbody>
  1356. </table>
  1357. <ul>
  1358. <li>Supported:
  1359. <ul>
  1360. <li>Include</li>
  1361. <li>Exclude</li>
  1362. <li>literal</li>
  1363. <li>literal range, e.g. <i>[EnumA..EnumB], ['a'..'z']</i></li>
  1364. <li>union +</li>
  1365. <li>difference -</li>
  1366. <li>intersect *</li>
  1367. <li>symmetrical difference >&lt;</li>
  1368. <li>equal =</li>
  1369. <li>unequal &lt;></li>
  1370. <li>subset &lt;=</li>
  1371. <li>superset >=</li>
  1372. <li>set of anonymous enum type: <i>set of (enum1,enum2,...)</i></li>
  1373. </ul>
  1374. </li>
  1375. <li>Not supported: set of char, set of boolean</li>
  1376. <li>There is no optimization yet for small sets like in Delphi/FPC.</li>
  1377. <li>Assigning a set or passing the set as an argument only creates a
  1378. reference and marks the set as <i>shared</i>.
  1379. When a <i>shared</i> set is altered with Include/Exclude a new set is
  1380. created (copy on write).</li>
  1381. <li>Passing a set as an argument might clone the set.
  1382. Use the <i>const</i> modifier for parameters whenever possible.</li>
  1383. <li>Constant sets in expressions (e.g. <i>if c in ['a'..'z'] then</i>)
  1384. are not yet optimized and created every time. Create a <i>const</i> to avoid this.</li>
  1385. </ul>
  1386. </div>
  1387. <div class="section">
  1388. <h2 id="array">Translating array type</h2>
  1389. All arrays are translated into JavaScript arrays.<br>
  1390. Contrary to Delphi/FPC dynamic arrays are
  1391. not reference counted and do not copy on write. That means if you pass an
  1392. array to a procedure and change an element, the original array is changed.
  1393. <table class="sample">
  1394. <tbody>
  1395. <tr>
  1396. <th>Pascal</th>
  1397. <th>JavaScript</th>
  1398. </tr>
  1399. <tr>
  1400. <td>
  1401. <pre>Unit MyModule;
  1402. Interface
  1403. Type
  1404. TIntArr = Array of integer;
  1405. TObjArr = Array of TObject;
  1406. TRec = record c: char; end;
  1407. TRecArr = Array of TRec;
  1408. Procedure Test;
  1409. Implementation
  1410. Procedure Test;
  1411. Var
  1412. IntArr: TIntArr = (1,2,3);
  1413. ObjArr: TObjArr;
  1414. RecArr: TRecArr;
  1415. Begin
  1416. IntArr:=nil;
  1417. SetLength(IntArr,4);
  1418. IntArr[2]:=2;
  1419. IntArr[1]:=length(IntArr);
  1420. SetLength(ObjArr,5);
  1421. SetLength(RecArr,2,TRec);
  1422. End;
  1423. End.
  1424. </pre>
  1425. </td>
  1426. <td>
  1427. <pre>rtl.module("MyModule",
  1428. ["System"],
  1429. function(){
  1430. var $mod = this;
  1431. this.Test = function(){
  1432. this.TRec = function(s){
  1433. if (s){
  1434. this.c = s.c;
  1435. } else {
  1436. this.c = "";
  1437. };
  1438. this.$equal = function(b){
  1439. return (this.c == b.c);
  1440. };
  1441. };
  1442. this.IntArr = [1,2,3];
  1443. this.ObjArr = [];
  1444. this.RecArr = [];
  1445. this.Test = function(){
  1446. $mod.IntArr = [];
  1447. rtl.arraySetLength($mod.IntArr,4,0);
  1448. $mod.IntArr[2] = 2;
  1449. $mod.IntArr[1] = $mod.IntArr.length;
  1450. rtl.setArrayLength($mod.ObjArr,5,null);
  1451. rtl.setArrayLength($mod.RecArr,2,$mod.TRec);
  1452. }
  1453. };
  1454. },
  1455. []);
  1456. </pre>
  1457. </td>
  1458. </tr>
  1459. </tbody>
  1460. </table>
  1461. Notes:
  1462. <ul>
  1463. <li>Supported features of dynamic arrays: SetLength(), Length(), equal/notequal nil, low(), high(),
  1464. assigned(), concat(), copy(), insert(), delete(), multi dimensional, array of record</li>
  1465. <li>Dynamic array constants. E.g. in mode ObjFPC <i>const a: array of byte = (1,2)</i>.
  1466. In mode Delphi you must use square brackets, <i>... = [1,2]</i></li>
  1467. <li>Supported features of static arrays: length(), low(), high(),
  1468. assigned(), concat(), copy(), const, const records </li>
  1469. <li>Open arrays are implemented as dynamic arrays.</li>
  1470. <li>Calling <i>Concat()</i> with only one array simply returns the array
  1471. (no cloning). Calling it with multiple arrays creates a clone.
  1472. This is Delphi 10.1 compatible.</li>
  1473. <li>In Delphi/FPC an empty array is <i>nil</i>. In JS it can be <i>null</i> or <i>[]</i>.
  1474. For compatibility comparing an array with <i>nil</i> checks for <i>length(a)>0</i>.</li>
  1475. <li><i>function Assigned(array): boolean</i> results true iff <i>length(array)>0</i>.</li>
  1476. <li>array of const:
  1477. <ul>
  1478. <li>Works the same: vtInteger, vtBoolean, vtPointer, vtObject, vtClass, vtWideChar, vtInterface, vtUnicodeString</li>
  1479. <li>''longword'' is converted to ''vtNativeInt''. Delphi/FPC converts to ''vtInteger'', changing big numbers to negative numbers.</li>
  1480. <li>vtExtended is double, Delphi/FPC: PExtended</li>
  1481. <li>vtCurrency is currency, Delphi/FPC: PCurrency</li>
  1482. <li>Not supported: vtChar, vtString, vtPChar, vtPWideChar, vtAnsiString, vtVariant, vtWideString, vtInt64, vtQWord</li>
  1483. <li>only in pas2js: vtNativeInt, vtJSValue</li>
  1484. </ul></li>
  1485. <li>Assignation using constant array, e.g. <i>a:=[1,1,2];</i></li>
  1486. <li>String like operation: + operator concatenates arrays. e.g. <i>a:=[1]+[2];</i>.
  1487. This is controlled by modeswitch arrayoperators, which is enabled in mode delphi.</li>
  1488. <li><i>function copy(array,start=0,count=max): array</i></li>
  1489. <li><i>procedure insert(item,var array,const position)</i></li>
  1490. <li><i>procedure delete(var array,const start,count)</i></li>
  1491. </ul>
  1492. </div>
  1493. <div class="section">
  1494. <h2 id="class">Translating class type</h2>
  1495. Classes are implemented using <i>Object.create</i> and some rtl magic.
  1496. <table class="sample">
  1497. <tbody>
  1498. <tr>
  1499. <th>Pascal</th>
  1500. <th>JavaScript</th>
  1501. </tr>
  1502. <tr>
  1503. <td>
  1504. <pre>Unit MyModule;
  1505. Interface
  1506. Type
  1507. TClassA = Class(TObject)
  1508. Public
  1509. i: integer;
  1510. Procedure Add(a: integer);
  1511. End;
  1512. var
  1513. ObjA: TClassA;
  1514. Implementation
  1515. Procedure TClassA.Add(a: integer);
  1516. Begin
  1517. i:=i+a;
  1518. End;
  1519. Initialization
  1520. ObjA:=TClassA.Create;
  1521. End.
  1522. </pre>
  1523. </td>
  1524. <td>
  1525. <pre>rtl.module("MyModule",
  1526. ["System"],
  1527. function(){
  1528. var $mod = this;
  1529. rtl.createClass($mod,"TClassA",pas.System.TObject,function(){
  1530. this.$init = function () {
  1531. this.i = 0;
  1532. };
  1533. this.Add = function(a){
  1534. this.i = this.i + a;
  1535. };
  1536. });
  1537. this.ObjA = null;
  1538. $mod.$init = function(){
  1539. $mod.ObjA = $mod.TClassA.$create("Create");
  1540. };
  1541. },
  1542. []);
  1543. </pre>
  1544. </td>
  1545. </tr>
  1546. </tbody>
  1547. </table>
  1548. Notes:
  1549. <ul>
  1550. <li>Each class and each instance is an JS object.</li>
  1551. <li>Each class has a globally unique JS object, created by rtl.createClass.</li>
  1552. <li><i>Self</i> is never <i>nil</i>.</li>
  1553. <li>The method <i>TObject.Free</i> is using compiler magic. See <a href="#tobjectfree">Translating TObject.Free</a>.</li>
  1554. <li><i>Class.$class</i> is a reference to the class itself.</li>
  1555. <li><i>Class.$ancestor</i> is a reference to the ancestor class.</li>
  1556. <li>A class has <i>c.$ancestor == Object.getPrototypeOf(c)</i>.</li>
  1557. <li>A class instance has <i>o.$class == Object.getPrototypeOf(o)</i>.</li>
  1558. <li><i>Class.$classname</i> is the short name. E.g. <i>TClassA.$classname == 'TClassA'</i>.</li>
  1559. <li><i>Class.$name</i> is the long name. E.g. <i>TClassA.$name == 'MyModule.TClassA'</i>.</li>
  1560. <li><i>Class.$unitname</i> is the unit name. E.g. <i>TClassA.$unitname == 'MyModule'</i>.</li>
  1561. <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>
  1562. <li>The "<i>as</i>" operator is implemented as <i>rtl.as(Object,Class)</i>.</li>
  1563. <li>Supported:
  1564. <ul>
  1565. <li>constructor, destructor</li>
  1566. <li>private, protected, public, strict private, strict protected</li>
  1567. <li>class vars, const, nested types</li>
  1568. <li>methods, class methods, class constructor, external methods</li>
  1569. <li>method modifiers overload, reintroduce, virtual, override, abstract, static, external name</li>
  1570. <li>call inherited</li>
  1571. <li>assigned()</li>
  1572. <li>type cast</li>
  1573. <li>class sealed, class abstract</li>
  1574. </ul>
  1575. </li>
  1576. <li>Not supported: class destructor</li>
  1577. <li>Property:
  1578. <ul>
  1579. <li>References are replaced by getter/setter.</li>
  1580. <li>Supported: argument lists, default property, class property,
  1581. stored modifier, index modifier.</li>
  1582. <li>Not supported: getter/setter to an array element,
  1583. e.g. <i>property A: char read FArray[0];</i> </li>
  1584. <li>Class property getter/setter can be static or non static. Delphi: must be static.</li>
  1585. <li>The <i>Index</i> modifier supports any constant, e.g. a string, while
  1586. Delphi only allows an ordinal (longint). -2147483648 is not a special
  1587. number in pas2js. Overriding a property with an index property is allowed
  1588. in Delphi and pas2js.</li>
  1589. </ul>
  1590. </li>
  1591. </ul>
  1592. </div>
  1593. <div class="section">
  1594. <h2 id="classof">Translating class-of type</h2>
  1595. A class-of is a reference to a class. See above about translating class.
  1596. <table class="sample">
  1597. <tbody>
  1598. <tr>
  1599. <th>Pascal</th>
  1600. <th>JavaScript</th>
  1601. </tr>
  1602. <tr>
  1603. <td>
  1604. <pre>Unit MyModule;
  1605. Interface
  1606. Type
  1607. TBird = Class(TObject)
  1608. Public
  1609. Class var Count: integer;
  1610. Class Procedure Add(a: integer); virtual;
  1611. End;
  1612. TBirds = class of TBird;
  1613. TPigeon = Class(TBird)
  1614. Public
  1615. Class Procedure Add(a: integer); override;
  1616. End;
  1617. var
  1618. BirdType: TBirds;
  1619. Implementation
  1620. Class Procedure TBird.Add(a: integer);
  1621. Begin
  1622. Count:=Count+a;
  1623. End;
  1624. Class Procedure TPigeon.Add(a: integer);
  1625. Begin
  1626. inherited Add(a+1);
  1627. End;
  1628. Initialization
  1629. BirdType:=TPigeon;
  1630. BirdType.Add(1);
  1631. End.
  1632. </pre>
  1633. </td>
  1634. <td>
  1635. <pre>rtl.module("MyModule",
  1636. ["System"],
  1637. function(){
  1638. var $mod = this;
  1639. rtl.createClass($mod,"TBird",pas.System.TObject,function () {
  1640. this.Count = 0;
  1641. this.Add = function (a) {
  1642. this.Count = this.Count + a;
  1643. };
  1644. });
  1645. rtl.createClass($mod,"TPigeon",$mod.TBird,function () {
  1646. this.Add = function (a) {
  1647. $mod.TBird.Add.call(this,a + 1);
  1648. };
  1649. });
  1650. $mod.$init = function(){
  1651. $mod.BirdType = $mod.TPigeon;
  1652. $mod.BirdType.Add(1);
  1653. };
  1654. },
  1655. []);
  1656. </pre>
  1657. </td>
  1658. </tr>
  1659. </tbody>
  1660. </table>
  1661. Note that <i>this</i> in a class method is the class itself.<br>
  1662. <br>
  1663. Notes:<br>
  1664. <ul>
  1665. <li>Contrary to Delphi/FPC the "is" operator works with class-of.</li>
  1666. </ul>
  1667. </div>
  1668. <div class="section">
  1669. <h2 id="tobjectfree">Translating TObject.Free</h2>
  1670. In Delphi/FPC AnObject.Free checks if Self is nil, then calls the destructor
  1671. and frees the memory, without changing the reference.
  1672. In JavaScript however calling a method with AnObject=nil causes a crash.
  1673. And memory cannot be freed explicitely. Memory is only
  1674. freed if all references are gone (e.g. set to <i>null</i>).<br>
  1675. Therefore pas2js adds code to call the destructor and sets the variable to <i>nil</i>:<br>
  1676. <ul>
  1677. <li><i>Obj.Free</i> on a local variable or argument is translated to
  1678. <i>Obj = rtl.freeLoc(Obj);</i>.</li>
  1679. <li><i>Obj.Free</i> on a non local variable is translated to
  1680. <i>rtl.free(this,"Obj");</i>.</li>
  1681. <li>Not supported: Freeing a property or function result.<br>
  1682. For example <i>List[i].Free</i> gives a compiler error. The property
  1683. setter might create side effects, which would be incompatible to Delphi/FPC.
  1684. </li>
  1685. </ul>
  1686. Notes:
  1687. <ul>
  1688. <li>If the destructor raises an exception, the variable is not set to <i>nil</i>.
  1689. This is compatible to Delphi/FPC, where the memory is not freed in this case.</li>
  1690. <li>Alternatively you can use <i>FreeAndNil</i>, which first changes
  1691. the variable to <i>nil</i> and then calls the destructor.</li>
  1692. </ul>
  1693. </div>
  1694. <div class="section">
  1695. <h2 id="classinterfaces">Translating class interfaces</h2>
  1696. JavaScript has nothing like it, so they are emulated.<br>
  1697. An interfacetype is a JS-object with some hidden properties, containing
  1698. the GUID ($guid) and an array with the method names ($names). Here is how
  1699. IUnknown looks like in JS:<br>
  1700. <pre>
  1701. {
  1702. $module: [object Object],
  1703. $name: "IUnknown",
  1704. $fullname: "System.IUnknown",
  1705. $guid: "{00000000-0000-0000-C000-000000000046}",
  1706. $names: ["QueryInterface","_AddRef","_Release"],
  1707. $rtti: [object Object],
  1708. $kind: "com",
  1709. }
  1710. </pre>
  1711. A class implementing interfaces has a variable <i>$intfmaps</i>, which has
  1712. for each implemented GUID a map or delegator function. A map
  1713. is a JS instance of the interfacetype plus a for each method name a
  1714. function to call the class method. Here is an example map of <i>IUnknown</i> of
  1715. <i>TInterfacedObject</i>:<br>
  1716. <pre>
  1717. {
  1718. QueryInterface: function (){ return fn.apply(this.$o,arguments); },
  1719. _AddRef: function (){ return fn.apply(this.$o,arguments); },
  1720. _Release: function (){ return fn.apply(this.$o,arguments); },
  1721. ...
  1722. }
  1723. </pre>
  1724. When an interface is created for an object (here: a Pascal class instance),
  1725. for example by using the <i>as</i>-operator "<i>ObjVar as IUnknown</i>",
  1726. a JS object is created, which
  1727. is an instance of the map object with its <i>$o</i> set to the <i>ObjVar</i>.<br>
  1728. <br>
  1729. Supported:
  1730. <ul>
  1731. <li>methods, properties, default property</li>
  1732. <li><i>{$interfaces com|corba|default}</i><br>
  1733. <ul>
  1734. <li>COM is default, default ancestor is IUnknown (mode delphi: IInterface),
  1735. managed type, i.e. automatically reference counted via _AddRef, _Release, the checks for support call QueryInterface</li>
  1736. <li>CORBA: lightweight, no automatic reference counting,
  1737. no default ancestor, fast support checks.</li>
  1738. </ul>
  1739. </li>
  1740. <li>inheriting</li>
  1741. <li>An interface without a GUID gets one autogenerated from its name and method names.</li>
  1742. <li>Contrary to Delphi/FPC you can assign an interface type or var to
  1743. the type TGuidString.</li>
  1744. <li>a class implementing an interface must not be external</li>
  1745. <li>a ClassType "supports" an interface, if it itself or one of its
  1746. ancestors implements the interface.
  1747. It does not automatically support an ancestor of the interface.</li>
  1748. <li>method resolution, procedure IUnknown._AddRef = IncRef;</li>
  1749. <li>delegation: property Name: interface|class read Field|Getter implements AnInterface;</li>
  1750. <li>is-operator:</li>
  1751. <ul>
  1752. <li>IntfVar is IntfType - types must be releated</li>
  1753. <li>IntfVar is ClassType - types can be unrelated, class must not be external</li>
  1754. <li>ObjVar is IntfType - can be unrelated</li>
  1755. </ul>
  1756. <li>as-operator</li>
  1757. <ul>
  1758. <li>IntfVar as IntfType - types must be releated</li>
  1759. <li>IntfVar as ClassType - types can be unrelated, nil returns nil,
  1760. invalid raises EInvalidCast</li>
  1761. <li>ObjVar as IntfType - can be unrelated, nil if not found, COM: uses _AddRef</li>
  1762. </ul>
  1763. <li>typecast:</li>
  1764. <ul>
  1765. <li>IntfType(IntfVar) - must be related</li>
  1766. <li>ClassType(IntfVar) - can be unrelated, nil if invalid</li>
  1767. <li>IntfType(ObjVar) - nil if not found,
  1768. COM: if ObjVar has delegate uses _AddRef</li>
  1769. <li>TJSObject(IntfTypeOrVar)</li>
  1770. <li>jsvalue(intfvar)</li>
  1771. </ul>
  1772. <li>Assign operator:</li>
  1773. <ul>
  1774. <li>IntfVar:=nil;</li>
  1775. <li>IntfVar:=IntfVar2; - IntfVar2 must be same type or a descendant</li>
  1776. <li>IntfVar:=ObjVar; - nil if unsupported</li>
  1777. <li>jsvalue:=IntfVar;</li>
  1778. <li>TGUIDVar:=IntfType;</li>
  1779. <li>TGUIDVar:=IntfVar;</li>
  1780. <li>TGUIDVar:=stringconstant;</li>
  1781. <li>TGUIDStringVar:=IntfVar;</li>
  1782. <li>StringVar:=GuidVar;</li>
  1783. </ul>
  1784. <li>Equal/Inequal operator:</li>
  1785. <ul>
  1786. <li>IntfVar=nil;</li>
  1787. <li>IntfVar=IntfVar2; - must be related</li>
  1788. <li>jsvalue=IntfVar;</li>
  1789. <li>TGUIDVar=IntfType;</li>
  1790. <li>TGUIDVar=IntfVar;</li>
  1791. <li>TGUIDVar=string;</li>
  1792. <li>TGUIDStringVar=IntfVar;</li>
  1793. </ul>
  1794. <li>Passing an COMIntfVar to an untyped parameter does not trigger _AddRef, _Release.</li>
  1795. <li>Assigned(IntfVar)</li>
  1796. <li>RTTI, typeinfo(IntfType), typeinfo(IntfVar)</li>
  1797. </ul>
  1798. Not yet supported: array of intferfacetype, interface as record member.
  1799. </div>
  1800. <div class="section">
  1801. <h2 id="helpers">Translating helpers</h2>
  1802. Pas2js supports class helpers, record helpers and type helpers since 1.3.
  1803. The extend is only virtual, the helped type is kept untouched.
  1804. <br>
  1805. <ul>
  1806. <li>A <b>class helper</b> can "extend" Pascal classes and external JS classes.</li>
  1807. <li>A <b>record helper</b> can "extend" a record type. In $mode delphi a
  1808. record helper can extend other types as well, see <i>type helper</i></li>
  1809. <li>A <b>type helper</b> can extend all base types like integer, string,
  1810. char, boolean, double, currency, and some user types like enumeration,
  1811. set, range and array types. It cannot extend interfaces or helpers.<br>
  1812. Type helpers are enabled by default in <i>$mode delphi</i> and disabled in <i>$mode objfpc</i>.
  1813. You can enable them with <b>{$modeswitch typehelpers}</b>.
  1814. </li>
  1815. <li>By default only one helper is active per type, same as in FPC/Delphi.
  1816. If there are multiple helpers for the same type, the last helper in scope wins.<br>
  1817. A class with ancestors can have one active helper per ancestor type, so
  1818. multiple helpers can be active, same as FPC/Delphi.<br>
  1819. Using <b>{$modeswitch multiplescopehelpers}</b> you can activate all helpers
  1820. within scope.
  1821. </li>
  1822. <li>Nested helpers (e.g. <i>TDemo.TSub.THelper</i>) are elevated.
  1823. Visibility is ignored. Same as FPC/Delphi.</li>
  1824. <li>Helpers cannot be forward defined (e.g. no <i>THelper = helper;</i>).</li>
  1825. <li>Helpers must not have fields.</li>
  1826. <li><b>Class Var, Const, Type</b></li>
  1827. <li><b>Visibility</b> : <i>strict private .. published</i></li>
  1828. <li><b>Function, procedure</b>:
  1829. In class and record helpers <i>Self</i> is the class/record instance. For other
  1830. types Self is a reference to the passed value.
  1831. </li>
  1832. <li><b>Class function, class procedure</b>: Helpers for Pascal classes/records can
  1833. add <i>static</i> and non static class functions. Helpers for external classes
  1834. and other types can only add static class functions.</li>
  1835. <li><b>Constructor</b>. Not for external classes. Works similar to
  1836. construcors, i.e. <i>THelpedClass.Create</i> creates a new instance, while
  1837. <i>AnObj.Create</i> calls the constructor function as normal method. Note that
  1838. Delphi does not allow calling helper construcors as normal method.</li>
  1839. <li>no destructor</li>
  1840. <li><b>Property</b> : getters/setters can refer to members of the helper, its
  1841. ancestors and the helped class/record.</li>
  1842. <li><b>Class property</b> : getter can be static or non static. Delphi/FPC only allows static.</li>
  1843. <li><b>Ancestors</b> : Helpers can have an ancestor helper, but they
  1844. do not have a shared root class, especially not <i>TObject</i>.</li>
  1845. <li><b>no virtual, abstract, override</b>. Delphi allows them, but 10.3 crashes when calling.</li>
  1846. <li><b>inherited</b> :
  1847. <i>inherited</i> inside a method of a class/record calls helper of ancestor.<br>
  1848. <i>inherited</i> inside a helper depends on the $mode:
  1849. <ul>
  1850. <li> <i>$mode objfpc</i> : <i>inherited;</i> and <i>inherited Name(args);</i>
  1851. work the same and searches first in HelperForType, then in ancestor(s).</li>
  1852. <li><i>$mode delphi: inherited;</i> : skip ancestors and HelperForType,
  1853. searches first in helper(s) of ancestor of HelperForType.</li>
  1854. <li><i>$mode delphi: inherited name(args);</i> :
  1855. same as $mode objfpc first searches in HelperForType, then Ancestor(s)</li>
  1856. </ul>
  1857. In any case if <i>inherited;</i> has no ancestor to call, it is silently ignored,
  1858. while <i>inherited Name;</i> gives an error.
  1859. </li>
  1860. <li><b>RTTI</b>: <i>typeinfo(somehelper)</i> returns a pointer to <i>TTypeInfoHelper</i> with <i>Kind tkHelper</i>.</li>
  1861. <li>There are some special cases when using a <b>type helper</b> function/procedure on a value:
  1862. <ul>
  1863. <li><i>function result</i> : using a temporary variable</li>
  1864. <li><i>const, const argument</i> : When helper function tries to assign a value,
  1865. pas2js raises a EPropReadOnly exception. FPC/Delphi use a temporary variable allowing the write. </li>
  1866. <li><i>property</i> : uses only the getter, ignoring the setter.
  1867. This breaks OOP, as it allows to change fields without calling the setter.
  1868. This is FPC/Delphi compatible.</li>
  1869. <li><i>with value do ;</i> : uses a temporary variable. Delphi/FPC do not support it.</li>
  1870. </ul>
  1871. </li>
  1872. </ul>
  1873. </div>
  1874. <div class="section">
  1875. <h2 id="attributes">Translating attributes</h2>
  1876. Attributes are stored in the TTypeInfo objects as streams stored in an array.
  1877. See the <i>TypInfo</i> function <i>GetRTTIAttributes</i> for details.
  1878. </div>
  1879. <div class="section">
  1880. <h2 id="tryfinally">Translating try..finally</h2>
  1881. JavaScript has the same, so it translates straight forward.
  1882. </div>
  1883. <div class="section">
  1884. <h2 id="tryexcept">Translating try..except</h2>
  1885. <table class="sample">
  1886. <tbody>
  1887. <tr>
  1888. <th>Pascal</th>
  1889. <th>JavaScript</th>
  1890. </tr>
  1891. <tr>
  1892. <td>
  1893. <pre>Unit MyModule;
  1894. Interface
  1895. Uses SysUtils, Math, JS;
  1896. Function DoIt(n: integer): double;
  1897. Implementation
  1898. Function DoIt(n: integer): double;
  1899. var E: Exception;
  1900. Begin
  1901. try
  1902. Result:=double(7.0)/n;
  1903. if not IsFinite(Result) then
  1904. if n=0 then
  1905. raise EZeroDivide.Create
  1906. else
  1907. raise EOverflow.Create;
  1908. except
  1909. on EZeroDivide do Result:=0.0;
  1910. on E2: EOverflow do Result:=0.0;
  1911. else
  1912. raise EAbort.Create('Something other: '+String(JS.JSExceptObject));
  1913. end;
  1914. End;
  1915. End.
  1916. </pre>
  1917. </td>
  1918. <td>
  1919. <pre>rtl.module("MyModule",
  1920. ["System","SysUtils"],
  1921. function(){
  1922. this.DoIt=function(n){
  1923. Result = 0;
  1924. var E = null;
  1925. try{
  1926. Result = 7.0 / n;
  1927. if (!IsFinite(Result)){
  1928. if (n==0){
  1929. throw pas.SysUtils.EZeroDivide.$create("Create");
  1930. } else {
  1931. throw pas.SysUtils.EOverflow.$create("Create");
  1932. };
  1933. };
  1934. }catch($e){
  1935. if (pas.SysUtils.EZeroDivide.isPrototypeOf($e)){
  1936. Result = 0.0;
  1937. } else if (pas.SysUtils.EOverflow.isPrototypeOf($e)){
  1938. var E2 = $e;
  1939. Result = 0.0;
  1940. } else {
  1941. throw pas.SysUtils.EAbort.$create("Create",["Something other: "+(""+$e)]);
  1942. }
  1943. }
  1944. return Result;
  1945. };
  1946. },
  1947. []);
  1948. </pre>
  1949. </td>
  1950. </tr>
  1951. </tbody>
  1952. </table>
  1953. Notes:
  1954. <ul>
  1955. <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>
  1956. <li>There is no ExceptObject in SysUtils.</li>
  1957. <li>When calling external functions keep in mind that JS allows to
  1958. throw (raise) any value, often a string.<br>
  1959. You can access the current except value via JSExceptValue in unit JS.<br>
  1960. Note that this is only valid inside the catch-block. The compiler will not warn,
  1961. if you use it outside.</li>
  1962. </div>
  1963. <div class="section">
  1964. <h2 id="enumerators">Translating enumerators</h2>
  1965. The for..in..do supports enumerating:
  1966. <ul>
  1967. <li>ordinal types like char, boolean,
  1968. byte, ..., longword, enums, custom ranges are translated to a for loop.</li>
  1969. <li>set types are translated to a for loop, while const sets and set variables are enumerated via a for(...in...) loop.</li>
  1970. <li>string and array variables are enumerated via for loops.</li>
  1971. <li>for aString in ArrayOfString do ...</li>
  1972. <li><i>for key in jsvalue do</i> translates to <i>for (key in jsvalue){}</i></li>
  1973. <li><i>for key in ExternalClass do</i><br>
  1974. <ul>
  1975. <li>If the externalclass has a ''length'' and a matching default property
  1976. it uses the enumeration of an array. For example
  1977. <i>for value in TJSArray do</i> enumerates the values of the array, not the index.
  1978. It checks if the array is nil.</li>
  1979. <li>Otherwise it translates to <i>for (key in externalclass){}</i>,
  1980. which enumerates the keys (property names) of the JS object.</li>
  1981. </ul>
  1982. </ul>
  1983. The class GetEnumerator function is translated like this:
  1984. <table class="sample">
  1985. <tbody>
  1986. <tr>
  1987. <th>Pascal</th>
  1988. <th>JavaScript</th>
  1989. </tr>
  1990. <tr>
  1991. <td>
  1992. <pre>Unit MyModule;
  1993. Interface
  1994. uses Classes;
  1995. procedure DoIt(List: TList);
  1996. Implementation
  1997. procedure DoIt(List: TList);
  1998. var
  1999. Item: Pointer;
  2000. begin
  2001. for Item in List do
  2002. if Item<>nil then ;
  2003. end;
  2004. End.
  2005. </pre>
  2006. </td>
  2007. <td>
  2008. <pre>rtl.module("MyModule",
  2009. ["System","Classes"],
  2010. function(){
  2011. this.DoIt=function(List){
  2012. var Item = null;
  2013. var $in1 = List;
  2014. try {
  2015. while ($in1.MoveNext()) {
  2016. Item = $in1.GetCurrent();
  2017. if (Item !== null) ;
  2018. }
  2019. } finally {
  2020. $in1 = rtl.freeLoc($in1)
  2021. };
  2022. };
  2023. },
  2024. []);
  2025. </pre>
  2026. </td>
  2027. </tr>
  2028. </tbody>
  2029. </table>
  2030. Notes:
  2031. <ul>
  2032. <li>Not supported: operator Enumerator, member modifier enumerator (i.e. custom Current and MoveNext)</li>
  2033. </ul>
  2034. </div>
  2035. <div class="section">
  2036. <h2 id="functiontype">Translating function types</h2>
  2037. JavaScript functions work like Delphi's "reference to function", which
  2038. means like closures, capturing outer variables.
  2039. Assigning a normal function or nested function to a procedural variable is
  2040. translated to a simple assignment.
  2041. A Pascal method needs <b>this</b> to be the class or class instance.<br>
  2042. Note that <i>bind</i> cannot be used, because it does not support the <i>equal</i> operator.
  2043. Instead a wrapper is created:
  2044. <table class="sample">
  2045. <tbody>
  2046. <tr>
  2047. <th>Pascal</th>
  2048. <th>JavaScript</th>
  2049. </tr>
  2050. <tr>
  2051. <td>
  2052. <pre>Program MyModule;
  2053. type
  2054. TMyMethod = procedure(n: integer) of object;
  2055. TBird = class
  2056. procedure DoIt(n: integer); virtual; abstract;
  2057. end;
  2058. TMyProc = procedure(n: integer);
  2059. procedure DoSome(n: integer);
  2060. begin
  2061. end;
  2062. var
  2063. m: TMyMethod;
  2064. Bird: TBird;
  2065. p: TMyProc;
  2066. Begin
  2067. m:[email protected];
  2068. m(3);
  2069. p:=@DoSome;
  2070. p(4);
  2071. End.
  2072. </pre>
  2073. </td>
  2074. <td>
  2075. <pre>rtl.module("program",
  2076. ["System","UnitA"],
  2077. function(){
  2078. var $mod = this;
  2079. rtl.createClass($mod,"TBird",pas.System.TObject,function(){
  2080. this.DoIt = function (n) {
  2081. };
  2082. });
  2083. this.DoSome = function (n) {
  2084. };
  2085. this.m = null;
  2086. this.Bird = null;
  2087. this.p = null;
  2088. $mod.$main = function() {
  2089. $mod.m = rtl.createCallback($mod.Bird,"DoIt");
  2090. $mod.m(3);
  2091. $mod.p = $mod.DoSome;
  2092. $mod.p(4);
  2093. };
  2094. },
  2095. []);
  2096. rtl = {
  2097. ...
  2098. createCallback: function(scope, fn){
  2099. var cb = function(){
  2100. return scope[fn].apply(scope,arguments);
  2101. };
  2102. cb.scope = scope;
  2103. cb.fn = fn;
  2104. return cb;
  2105. },
  2106. ...
  2107. </pre>
  2108. </td>
  2109. </tr>
  2110. </tbody>
  2111. </table>
  2112. Notes:
  2113. <ul>
  2114. <li>You can assign a nested procedure to procedure variable.
  2115. You don't need and you must not add the FPC "<i>is nested</i>" modifier.</li>
  2116. <li>A procedural typed declared as 'reference to' accepts in pas2js procedures,
  2117. local procedures and methods. Delphi only supports capturing procedures and methods.
  2118. FPC 3.0.4 does not support reference-to.</li>
  2119. </ul>
  2120. </div>
  2121. <div class="section">
  2122. <h2 id="anonymousfunctions">Translating anonymous functions</h2>
  2123. Anonymous functions are supported since pas2js 1.1.<br>
  2124. Note that in pas2js local procedures are closures as well. See below.<br>
  2125. For pas2js 1.0 the next best thing are local procedures. For example:
  2126. <table class="sample">
  2127. <tbody>
  2128. <tr>
  2129. <th>Delphi</th>
  2130. <th>Pas2js</th>
  2131. </tr>
  2132. <tr>
  2133. <td>
  2134. <pre>Program MyModule;
  2135. type
  2136. TAdder = reference to function(n: integer): integer;
  2137. function CreateAdder(a: integer): TAdder;
  2138. begin
  2139. Result:=function(b: integer)
  2140. begin
  2141. Result:=a+b;
  2142. end;
  2143. end;
  2144. var
  2145. Adder: TAdder;
  2146. Begin
  2147. Adder:=CreateAdder(3);
  2148. writeln(Adder(5)); // gives 8
  2149. End.
  2150. </pre>
  2151. </td>
  2152. <td>
  2153. <pre>Program MyModule;
  2154. type
  2155. TAdder = reference to function(n: integer): integer;
  2156. function CreateAdder(a: integer): TAdder;
  2157. function Add(b: integer): integer;
  2158. begin
  2159. Result:=a+b;
  2160. end;
  2161. begin
  2162. Result:=@Add;
  2163. end;
  2164. var
  2165. Adder: TAdder;
  2166. Begin
  2167. Adder:=CreateAdder(3);
  2168. writeln(Adder(5)); // gives 8
  2169. End.
  2170. </pre>
  2171. </td>
  2172. </tr>
  2173. </tbody>
  2174. </table>
  2175. </div>
  2176. <div class="section">
  2177. <h2 id="absolute">Translating var modifier absolute</h2>
  2178. The absolute modifier works as an alias. That means it works FPC/Delphi
  2179. compatible for related types like Pointer and TObject, and works
  2180. incompatible for unrelated types like longword and record (e.g. <i>var r: TPoint absolute MyLongInt</i>).<br>
  2181. The modifier is currently only supported for local variables.
  2182. </div>
  2183. <div class="section">
  2184. <h2 id="assert">Translating assert()</h2>
  2185. The Assert(boolean[,string]) function is translated to <i>if(bool) throw x</i>.
  2186. If unit sysutils is used, it creates an EAssertFailed exception.<br>
  2187. Otherwise it throws a string.<br>
  2188. <ul>
  2189. <li>Command line enable with -Sa, disable with -Sa-</li>
  2190. <li>In code enable with <i>{$C+}</i> or <i>{$Assertions on}</i>,
  2191. disable with <i>{$C-}</i> or <i>{$Assertions off}</i></li>
  2192. </ul>
  2193. </div>
  2194. <div class="section">
  2195. <h2 id="calljavascript">Calling JavaScript from Pascal</h2>
  2196. Pas2js allows to write low level functions and/or access a JavaScript library
  2197. with the following possibilities:
  2198. </div>
  2199. <div class="section">
  2200. <h2 id="asm">The asm block</h2>
  2201. The asm block is pure JavaScript, that is copied directly into the generated .js file.
  2202. <table class="sample">
  2203. <tbody>
  2204. <tr>
  2205. <th>Pascal</th>
  2206. <th>JavaScript</th>
  2207. </tr>
  2208. <tr>
  2209. <td>
  2210. <pre>Program MyModule;
  2211. var
  2212. s: string;
  2213. Begin
  2214. s = 'Hello World!';
  2215. Asm
  2216. console.log(s);
  2217. End;
  2218. End.
  2219. </pre>
  2220. </td>
  2221. <td>
  2222. <pre>rtl.module("program",
  2223. ["System"],
  2224. function(){
  2225. var $mod = this;
  2226. this.s = '';
  2227. $mod.$main = function(){
  2228. $mod.s = "Hello World!";
  2229. console.log(s);
  2230. };
  2231. },
  2232. []);
  2233. </pre>
  2234. </td>
  2235. </tr>
  2236. </tbody>
  2237. </table>
  2238. Notes:
  2239. <ul>
  2240. <li>The block is indented to produce more readable JS code.
  2241. All lines are indented or unindented the same amount, i.e. sub indentation is kept.</li>
  2242. <li>The compiler does neither parse, nor check the syntax of the JS.</li>
  2243. <li>The compiler does not know what Pascal identifiers are used by the
  2244. asm-block and might remove them, if no Pascal code is using them.
  2245. To make sure that an identifier is kept, add some dummy code like
  2246. <i>if MyVar=0 then;</i></li>
  2247. <li>Accessing an interface, program or library identifier:<br>
  2248. <ul>
  2249. <li>From inside the module you can use <i>$mod.Identifier</i>.</li>
  2250. <li>Otherwise use the fully qualified path <i>pas.Unitname.Identifier</i>.</li>
  2251. </ul>
  2252. </li>
  2253. <li>Accessing an implementation identifier:<br>
  2254. <ul>
  2255. <li>From inside the unit you can use <i>$impl.Identifier</i>.</li>
  2256. <li>Otherwise use the path <i>pas.Unitname.$impl.Identifier</i>.</li>
  2257. </ul>
  2258. </li>
  2259. <li>Accessing a class instance member (field, procedure, function,
  2260. constructor, destructor) from a method of the class: use <i>this.Identifier</i>.
  2261. Inside a nested function of a method you use the <i>Self.Identifier</i>.
  2262. </li>
  2263. <li>Accessing a class member (class var, class procedure, class function)
  2264. from a method of the class: for writing use <i>this.$class.Identifier</i>,
  2265. for reading you can omit the <i>$class</i>.</li>
  2266. <li>Accessing a class member (class var, class procedure, class function)
  2267. from a class method of the class: use <i>this.Identifier</i>.</li>
  2268. <li>Access to Properties must use the getter/setter.</li>
  2269. <li>When calling a Pascal method, make sure the <b>this</b> is correct:
  2270. <ul>
  2271. <li>A class method (e.g. <i>class function</i>, <i>class procedure</i>)
  2272. needs the class as <i>this</i>.<br>
  2273. <b>Wrong</b>: <i>aCar.DoIt(params,...)</i><br>
  2274. <b>Correct</b>: <i>aCar.$class.DoIt(params,...)</i><br>
  2275. </li>
  2276. </ul>
  2277. </li>
  2278. <li>Calling a Pascal function from a HTML/DOM-element:
  2279. For example to call a function when user clicks a DOM element you can
  2280. assign a function to the <i>onclick</i> property. This will call
  2281. the function with <i>this</i> set to the DOM element.<br>
  2282. Pascal methods needs a wrapper to set <i>this</i> to the
  2283. instance. Examples:
  2284. <ul>
  2285. <li>An unit function: <i>DOMElement.onclick = $mod.DoIt;</i></li>
  2286. <li>An implementation function: <i>DOMElement.onclick = $impl.DoIt;</i>.</li>
  2287. <li>A method: <i>DOMElement.onclick = this.DoIt.bind(this);</i></li>
  2288. <li>A class function/procedure: <i>DOMElement.onclick = this.DoIt.bind(this.$class);</i></li>
  2289. <li>A nested function: <i>DOMElement.onclick = DoIt;</i>.</li>
  2290. </ul>
  2291. </li>
  2292. </li>
  2293. </ul>
  2294. </div>
  2295. <div class="section">
  2296. <h2 id="assembler">The procedure modifier assembler</h2>
  2297. You can write pure JavaScript functions like this:
  2298. <table class="sample">
  2299. <tbody>
  2300. <tr>
  2301. <th>Pascal</th>
  2302. <th>JavaScript</th>
  2303. </tr>
  2304. <tr>
  2305. <td>
  2306. <pre>Program MyModule;
  2307. Procedure Log(const s: string); assembler;
  2308. Asm
  2309. console.log(s);
  2310. end;
  2311. Begin
  2312. Log('Hello World!');
  2313. End.
  2314. </pre>
  2315. </td>
  2316. <td>
  2317. <pre>rtl.module("program",
  2318. ["System"],
  2319. function(){
  2320. var $mod = this;
  2321. this.Log = function(s){
  2322. console.log(s);
  2323. };
  2324. $mod.$main = function(){
  2325. $mod.Log("Hello World!");
  2326. };
  2327. },
  2328. []);
  2329. </pre>
  2330. </td>
  2331. </tr>
  2332. </tbody>
  2333. </table>
  2334. See also <a href="#asm">asm</a>.
  2335. </div>
  2336. <div class="section">
  2337. <h2 id="externalproc">The procedure modifier external</h2>
  2338. The procedure modifier <i>external</i> requires a string constant and tells the
  2339. compiler to replace a reference with this string value. The value is not
  2340. checked for JS syntax.
  2341. <table class="sample">
  2342. <tbody>
  2343. <tr>
  2344. <th>Pascal</th>
  2345. <th>JavaScript</th>
  2346. </tr>
  2347. <tr>
  2348. <td>
  2349. <pre>Program MyModule;
  2350. Procedure ConsoleLog(const s: string); external name 'console.log';
  2351. // Note: an external procedure has no begin..end block
  2352. Begin
  2353. ConsoleLog('Hello World!');
  2354. End.
  2355. </pre>
  2356. </td>
  2357. <td>
  2358. <pre>rtl.module("program",
  2359. ["System"],
  2360. function(){
  2361. var $mod = this;
  2362. $mod.$main = function(){
  2363. console.log("Hello World!");
  2364. };
  2365. },
  2366. []);
  2367. </pre>
  2368. </td>
  2369. </tr>
  2370. </tbody>
  2371. </table>
  2372. </div>
  2373. <div class="section">
  2374. <h2 id="varargs">The procedure modifier varargs</h2>
  2375. Appending the <b>varargs</b> modifier to a procedure allows to pass arbitrary
  2376. more parameters to a function. To access these non typed arguments use
  2377. either <i>JSArguments</i> from unit JS or an <i>asm..end</i> block.
  2378. <table class="sample">
  2379. <tbody>
  2380. <tr>
  2381. <th>Pascal</th>
  2382. <th>JavaScript</th>
  2383. </tr>
  2384. <tr>
  2385. <td>
  2386. <pre>Program MyModule;
  2387. uses JS;
  2388. function Sum(b: boolean): longint; varargs;
  2389. var i: longint;
  2390. begin
  2391. if b then
  2392. asm
  2393. for (var i=0; i&lt;arguments.length; i++) Result+=arguments[i];
  2394. end
  2395. else
  2396. for i:=0 to JSArguments.length-1 do
  2397. Result:=Result+longint(JSArguments[i]);
  2398. end;
  2399. var
  2400. i: integer;
  2401. Begin
  2402. i:=Sum(true,2,4,6); // i=12
  2403. i:=Sum(false,2,4,6); // i=12
  2404. End.
  2405. </pre>
  2406. </td>
  2407. <td>
  2408. <pre>rtl.module("program",
  2409. ["System","JS"],
  2410. function(){
  2411. var $mod = this;
  2412. this.Sum = function(b){
  2413. var Result = 0;
  2414. var i = 0;
  2415. if (b){
  2416. for (var i=0; i&lt;arguments.length; i++) Result+=arguments[i];
  2417. } else {
  2418. for (var $l1 = 1, $le2 = argumens.length; $l1 &lt;= $le2; $l1++){
  2419. $i = $l1;
  2420. Result = Result + arguments[i];
  2421. }
  2422. }
  2423. return Result;
  2424. };
  2425. this.i = 0;
  2426. $mod.$main = function(){
  2427. $mod.i = $mod.Sum(true,2,4,6);
  2428. $mod.i = $mod.Sum(false,2,4,6);
  2429. };
  2430. },
  2431. []);
  2432. </pre>
  2433. </td>
  2434. </tr>
  2435. </tbody>
  2436. </table>
  2437. The above example defines a function <i>Sum</i>, that requires the first parameter to
  2438. be a boolean and then an arbitrary number of parameters. The compiler does not
  2439. type check the other parameters, so you can pass anything readable.
  2440. </div>
  2441. <div class="section">
  2442. <h2 id="externalvar">The var modifier external</h2>
  2443. The var modifier <i>external</i> allows to use a JavaScript variable or constant.
  2444. <table class="sample">
  2445. <tbody>
  2446. <tr>
  2447. <th>Pascal</th>
  2448. <th>JavaScript</th>
  2449. </tr>
  2450. <tr>
  2451. <td>
  2452. <pre>Program MyModule;
  2453. var
  2454. EulersNumber: Double; external name 'Math.E';
  2455. d: double;
  2456. Begin
  2457. d:=EulersNumber;
  2458. End.
  2459. </pre>
  2460. </td>
  2461. <td>
  2462. <pre>rtl.module("program",
  2463. ["System"],
  2464. function(){
  2465. var $mod = this;
  2466. this.d = 0.0;
  2467. $mod.$main = function(){
  2468. $mod.d = Math.E;
  2469. };
  2470. },
  2471. []);
  2472. </pre>
  2473. </td>
  2474. </tr>
  2475. </tbody>
  2476. </table>
  2477. </div>
  2478. <div class="section">
  2479. <h2 id="externalmembers">The external modifier of class members</h2>
  2480. The method modifier <i>external</i> works as the procedure modifier, except
  2481. it uses the scope of the class or instance.<br>
  2482. The field modifier <i>external</i> works as the var modifier, except
  2483. it uses the scope of the class or instance.<br>
  2484. Requires the modeswitch <b>externalclass</b>.
  2485. <table class="sample">
  2486. <tbody>
  2487. <tr>
  2488. <th>Pascal</th>
  2489. <th>JavaScript</th>
  2490. </tr>
  2491. <tr>
  2492. <td>
  2493. <pre>Program MyModule;
  2494. {$modeswitch externalclass}
  2495. type
  2496. TWrapper = class
  2497. private
  2498. // let's assume this object has the properties "$Handle", "$id", and "0"
  2499. public
  2500. Id: NativeInt; external name '$Id';
  2501. x: NativeInt; external name '[0]';
  2502. y: NativeInt; external name '["A B"]';
  2503. function GetState(typ: longint): NativeInt; external name '$Handle.GetState';
  2504. procedure DoIt;
  2505. end;
  2506. procedure TWrapper.DoIt;
  2507. begin
  2508. Id := GetState(4);
  2509. end;
  2510. var
  2511. W: TWrapper;
  2512. Begin
  2513. W.Id := 2;
  2514. W.x := 3;
  2515. W.y := 4;
  2516. W.GetState(5);
  2517. End.
  2518. </pre>
  2519. </td>
  2520. <td>
  2521. <pre>rtl.module("program",
  2522. ["System"],
  2523. function(){
  2524. var $mod = this;
  2525. rtl.createClass($mod, "TWrapper", pas.System.TObject, function () {
  2526. this.DoIt = function(){
  2527. this.$Id = this.$Handle.GetState(4);
  2528. };
  2529. });
  2530. this.W = null;
  2531. $mod.$main = function(){
  2532. $mod.W.$Id = 2;
  2533. $mod.W[0] = 3;
  2534. $mod.W["A B"] = 4;
  2535. $mod.W.$Handle.GetState(5);
  2536. };
  2537. },
  2538. []);
  2539. </pre>
  2540. </td>
  2541. </tr>
  2542. </tbody>
  2543. </table>
  2544. <ul>
  2545. <li>Non identifiers like "0" or "A B" must be enclosed in brackets.</li>
  2546. </ul>
  2547. </div>
  2548. <div class="section">
  2549. <h2 id="externalclass">External classes</h2>
  2550. pas2js introduces a new class modifier "<i>external name</i>", which makes
  2551. the whole class external.
  2552. External classes allow to easily declare Pascal wrappers for JavaScript
  2553. objects and function objects.<br>
  2554. They need the modeswitch <b>externalclass</b> in front of the class.<br>
  2555. An external class is not a TObject and has none of its methods.<br>
  2556. All members are external. If you omit the <i>external</i> modifier the
  2557. external name is the member name. Keep in mind that JS is case sensitive.<br>
  2558. Destructors are not allowed.<br>
  2559. Constructors are only allowed with the name <i>New</i> and a call
  2560. translates to <i>new ExtClass(params)</i>.
  2561. Properties work the same as with Pascal classes, i.e. are replaced by Getter/Setter.<br>
  2562. <table class="sample">
  2563. <tbody>
  2564. <tr>
  2565. <th>Pascal</th>
  2566. <th>JavaScript</th>
  2567. </tr>
  2568. <tr>
  2569. <td>
  2570. <pre>Program MyModule;
  2571. {$modeswitch externalclass}
  2572. type
  2573. TJSDate = class external name 'Date'
  2574. private
  2575. function getYear: NativeInt;
  2576. procedure setYear(const AValue: NativeInt);
  2577. public
  2578. constructor New;
  2579. constructor New(const MilliSecsSince1970: NativeInt);
  2580. class function now: NativeInt;
  2581. property Year: NativeInt read getYear write setYear;
  2582. end;
  2583. var
  2584. d: TJSDate;
  2585. Begin
  2586. d:=TJSDate.New;
  2587. d.Year:=d.Year+1;
  2588. End.
  2589. </pre>
  2590. </td>
  2591. <td>
  2592. <pre>rtl.module("program",["System"],function () {
  2593. var $mod = this;
  2594. this.d = null;
  2595. $mod.$main = function () {
  2596. $mod.d = new Date();
  2597. $mod.d.setYear($mod.d.getYear() + 1);
  2598. };
  2599. });
  2600. </pre>
  2601. </td>
  2602. </tr>
  2603. </tbody>
  2604. </table>
  2605. Notes:
  2606. <ul>
  2607. <li>Any class instance can be type casted to any root class.</li>
  2608. <li>A Pascal class can descend from an external class.</li>
  2609. <li>You can define a class-of external class and the <b>is</b> and <b>as</b>
  2610. operators work similar.</li>
  2611. <li>Class variables work as in JavaScript. That means, each descendant and each
  2612. instance can have its own value. For example <i>TExtA.Value</i> might be
  2613. different from <i>InstanceExtA.Value</i>. Setting <i>InstanceExtA.Value</i>
  2614. does not change <i>TExtA.Value</i>.</li>
  2615. <li>Const with an expression are replaced by the expression.</li>
  2616. <li>Const without an expression are treated as a readonly variable.</li>
  2617. <li>Class functions and class procedures are allowed, but can only be called via the class, not via an instance.<br>
  2618. For example you can call the class function <i>TJSString.fromCharCode()</i>, but you cannot
  2619. call <i>aJSString.fromCharCode()</i>.</li>
  2620. <li>An external class can descend from another external class.</li>
  2621. <li>Since class types are JS objects it is possible to typecast a class type
  2622. to the JS Object, e.g. TJSObject(TObject)</li>
  2623. <li>You can typecast function addresses and function references to JS
  2624. function, e.g. <i>TJSFunction(@SomeProc)</i>, <i>TJSFunction(OnClick)</i>.
  2625. Keep in mind that typecasting a method address creates a function wrapper
  2626. to bind the Self argument.</li>
  2627. </ul>
  2628. </div>
  2629. <div class="section">
  2630. <h2 id="externalclassancestor">External class as ancestor</h2>
  2631. A Pascal class can descend from an external class.<br>
  2632. The methods <i>AfterConstruction</i> and <i>BeforeDestruction</i>
  2633. are called if they exist.<br>
  2634. New instances are created by default with <i>Object.create(ancestorclass)</i>.<br>
  2635. You can override this, by providing a<br>
  2636. <b>class function NewInstance(fnname: string; const paramsarray): TPasClass; virtual;</b>.
  2637. This method is called to create a new instance and before calling the constructor.
  2638. The name is arbitrary, but the function must be the first non private,
  2639. non external, virtual class function with the class as result type.<br>
  2640. <table class="sample">
  2641. <tbody>
  2642. <tr>
  2643. <th>Pascal</th>
  2644. <th>JavaScript</th>
  2645. </tr>
  2646. <tr>
  2647. <td>
  2648. <pre>Program MyModule;
  2649. {$modeswitch externalclass}
  2650. type
  2651. TExtA = class external name 'ExtA'
  2652. end;
  2653. TMyB = class(TExtA)
  2654. protected
  2655. class function NewInstance(fnname: string; const paramarray): TMyB; virtual;
  2656. end;
  2657. class function TMyB.NewInstance(fnname: string; const paramarray): TMyB;
  2658. Begin
  2659. asm
  2660. Result = Object.create(ExtA);
  2661. end;
  2662. End;
  2663. Begin
  2664. End.
  2665. </pre>
  2666. </td>
  2667. <td>
  2668. <pre>rtl.module("program",["System"],function () {
  2669. var $mod = this;
  2670. rtl.createClassExt($mod, "TMyB", ExtA, "NewInstance", function () {
  2671. this.$init = function () {
  2672. };
  2673. this.$final = function () {
  2674. };
  2675. this.NewInstance = function (fnname, paramarray) {
  2676. var Result = null;
  2677. Result = Object.create(ExtA);
  2678. return Result;
  2679. };
  2680. });
  2681. $mod.$main = function () {
  2682. };
  2683. });
  2684. </pre>
  2685. </td>
  2686. </tr>
  2687. </tbody>
  2688. </table>
  2689. </div>
  2690. <div class="section">
  2691. <h2 id="jsvalue">The JSValue type</h2>
  2692. Pas2js introduces a new type <b>JSValue</b>, which works similar to a JS variable.
  2693. You can assign almost any value to it and it can be type casted to many types.
  2694. JSValue is useful for JS wrappers, when a variable can have multiple types.
  2695. And it can be used for containers storing arbitrary data, e.g. a list of JSValue.<br>
  2696. Key features:<br>
  2697. <ul>
  2698. <li>A JSValue variable initial value is undefined.</li>
  2699. <li>Operators: =, &lt;&gt;</li>
  2700. <li>type casting a <i>JSValue</i> to ...
  2701. <ul>
  2702. <li><i>Integer: Math.floor(aJSValue)</i> Note: may return <i>NaN</i></li>
  2703. <li><i>Boolean: !(aJSValue == false)</i> Note: works for numbers too, <i>0==false</i></li>
  2704. <li><i>Double: rtl.getNumber(aJSValue)</i> Note: <i>typeof(n)=="number"?n:NaN;</i></li>
  2705. <li><i>String: ""+aJSValue</i></li>
  2706. <li><i>Char: rtl.getChar(aJSValue)</i> Note: <i>((typeof(c)!="string") && (c.length==1)) ? c : ""</i></li>
  2707. <li>class instance or class-of: <i>rtl.getObject()</i> Note: checks for type <i>"object"</i></li>
  2708. <li>enum type</li>
  2709. <li>pointer</li>
  2710. </ul>
  2711. </li>
  2712. <li>A JSValue in a conditional expressions <i>If aJSValue then, while aJSValue do,
  2713. repeat until aJSValue</i> has the same meaning as in JS: the condition is
  2714. true, if the value is not <i>undefined, false, null, NaN, 0, ''</i>.
  2715. Note that <i>new Boolean(false)</i> is not <i>null</i> and the condition is true.
  2716. </li>
  2717. <li><i>function Assigned(V: jsvalue): boolean</i> returns true if<br>
  2718. <i>(V!=undefined) && (V!=null) && (!rtl.isArray(V) || (V.length > 0))</i></li>
  2719. <li><i>function StrictEqual(const A: jsvalue; const B): boolean</i></li>
  2720. <li><i>function StrictInequal(const A: jsvalue; const B): boolean</i></li>
  2721. <li>Any array can be assigned to an <i>array of jsvalue</i>.</li>
  2722. <li>is-operator: <i>jsvalue is class-type</i>, <i>jsvalue is class-of-type</i><br>
  2723. <li>The unit JS provides many utility functions for JSValue, like <i>hasString,
  2724. hasValue, isBoolean, isNumber, isInteger, isObject, isClass, isClassInstance, etc..</i></li>
  2725. </ul>
  2726. </div>
  2727. <div class="section">
  2728. <h2 id="bracketaccessor">Accessing JS object properties with the bracket accessor</h2>
  2729. Pas2js allows to define index properties that map directly to the JS object properties.
  2730. For example the default property of TJSObject allows to get and set the
  2731. properties of an object. For example <i>TJSObject(AnObject)['Name']:=Value;</i><br>
  2732. Another example is the default property of TJSArray, that allows access via integers
  2733. <i>aTJSArray[3]:=Value;</i><br>
  2734. To define your own bracket accessor define a normal index property and define
  2735. the getter/setter as <i>external name '[]'</i>.<br>
  2736. Here is an example for a read only accessor:
  2737. <table class="sample">
  2738. <tbody>
  2739. <tr>
  2740. <th>Pascal</th>
  2741. <th>JavaScript</th>
  2742. </tr>
  2743. <tr>
  2744. <td>
  2745. <pre>Program MyModule;
  2746. {$modeswitch externalclass}
  2747. type
  2748. TExtA = class external name 'ExtA'
  2749. private
  2750. function GetItems(Index: integer): String; external name '[]';
  2751. public
  2752. property Items[Index: integer]: String read GetItems; default;
  2753. end;
  2754. var
  2755. Obj: TExtA;
  2756. s: String;
  2757. Begin
  2758. ... get Obj from somewhere ...
  2759. s:=Obj[2];
  2760. End.
  2761. </pre>
  2762. </td>
  2763. <td>
  2764. <pre>rtl.module("program",["System"],function () {
  2765. var $mod = this;
  2766. this.Obj = undefined;
  2767. this.s = "";
  2768. $mod.$main = function () {
  2769. $mod.s = Obj[2];
  2770. };
  2771. });
  2772. </pre>
  2773. </td>
  2774. </tr>
  2775. </tbody>
  2776. </table>
  2777. Notes:
  2778. <ul>
  2779. <li>A property can have a mix of normal accessor and bracket accessor.
  2780. For example a bracket accessor as getter and a normal function as setter.</li>
  2781. </ul>
  2782. </div>
  2783. <div class="section">
  2784. <h2 id="rtti">RTTI - Run Time Type Information</h2>
  2785. The RTTI provides access to the type data of all published properties,
  2786. fields and methods. The type data provides similar information as Delphi/FPC,
  2787. but the internals are very different. Delphi/FPC uses pointers,
  2788. variant records and fake static arrays, which have no equivalent in JS.
  2789. Instead pas2js uses external classes. For example:
  2790. <pre>
  2791. TTypeInfo = class external name 'rtl.tTypeInfo'
  2792. public
  2793. Name: String external name 'name';
  2794. Kind: TTypeKind external name 'kind';
  2795. end;
  2796. TTypeInfoClass = class of TTypeInfo;
  2797. TTypeInfoInteger = class external name 'rtl.tTypeInfoInteger'(TTypeInfo)
  2798. public
  2799. MinValue: NativeInt external name 'minvalue';
  2800. MaxValue: NativeInt external name 'maxvalue';
  2801. OrdType : TOrdType external name 'ordtype';
  2802. end;
  2803. </pre>
  2804. The <b>typeinfo</b> function works on type, var, const and property identifiers.
  2805. By default it returns a <i>pointer</i>. If the typinfo unit is used it returns the
  2806. appropiate <i>TTypeInfo</i>. For instance <i>typeinfo(integer)</i> returns
  2807. a <i>TTypeInfoInteger</i>.<br>
  2808. <i>Typeinfo</i> of a <i>var</i> or <i>const</i> returns the typeinfo of its
  2809. type, not of its current runtime value. The exception is a class and class-of instance
  2810. variable (e.g. <i>var o: TObject; ... typeinfo(o)</i>), which returns the
  2811. typeinfo of the current runtime value.
  2812. If <i>o</i> is <i>null</i> it will give a JS error.<br>
  2813. Local types (i.e. inside a procedure) do not have typeinfo.<br>
  2814. Open array parameters are not yet supported.<br>
  2815. </div>
  2816. <div class="section">
  2817. <h2 id="compilerdirectives">Compiler directives</h2>
  2818. In config files:
  2819. <ul>
  2820. <li>#IFDEF macroname</li>
  2821. <li>#IFNDEF macroname</li>
  2822. <li>#IF expression - same as $if, except only defines</li>
  2823. <li>#ELSEIF</li>
  2824. <li>#ELSE</li>
  2825. <li>#ENDIF</li>
  2826. <li>#ERROR text</li>
  2827. </ul>
  2828. In source files:
  2829. <ul>
  2830. <li>{$Define <i>MacroName</i>}: defines macro <i>MacroName</i> with value '1'.</li>
  2831. <li>{$Define <i>MacroName:=value</i>}: defines macro <i>MacroName</i> with custom value.</li>
  2832. <li>{$Undef <i>MacroName</i>}: undefines macro <i>MacroName</i>.</li>
  2833. <li>{$IfDef <i>MacroName</i>}: if <i>MacroName</i> is not defined, skip to next $Else or $EndIf. Can be nested.</li>
  2834. <li>{$IfNDef <i>MacroName</i>}: as $IfDef, except negated.</li>
  2835. <li>{$If <i>boolean expression</i>}: if <i>expression</i> evaluates to true
  2836. (not '0'), skip to next $Else or $EndIf. Can be nested.<br>
  2837. Supported functions and operators:<br>
  2838. <ul>
  2839. <li>macro - replaced by its value, a simple define has value '1'</li>
  2840. <li>defined(macro) - '1' if defined, '0' otherwise</li>
  2841. <li>undefined(macro) - as <i>not defined(macro)</i></li>
  2842. <li>option(letter) - same as <i>{$IFOpt letter+}</i></li>
  2843. <li>not - first level of precedence</li>
  2844. <li>*, /, div, mod, and, shl, shr - second level of precedence</li>
  2845. <li>+, -, or, xor - third level of precedence</li>
  2846. <li>=, &lt;&gt;, &lt;, &gt;, &lt;=, &gt;= - fourth level of precedence</li>
  2847. <li>If the operands can be converted to numbers they are combined as numbers, otherwise as strings.</li>
  2848. </ul>
  2849. Not supported functions and operators:<br>
  2850. <ul>
  2851. <li>defined(Pascal identifier), undefined(Pascal identifier)</li>
  2852. <li>declared(Pascal identifier)</li>
  2853. <li>in operator</li>
  2854. </ul>
  2855. </li>
  2856. <li>{$IfOpt <i>Letter+,-</i>}: if <i>expression</i> evaluates to true (not '0'), skip to next $Else or $EndIf. Can be nested.</li>
  2857. <li>{$Else}: If previous $IfDef, $If or $IfOpt was skipped, execute next block, otherwise skip.</li>
  2858. <li>{$ElseIf <i>boolean expression</i>}: As $Else, except with an extra expression like $if to test. There can be multiple $elseif.</li>
  2859. <li>{$EndIf}: ends an $IfDef block</li>
  2860. <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>
  2861. <li>{$modeswitch externalclass}: allow declaring external classes</li>
  2862. <li>{$modeswitch arrayoperators}: allow + operator to concatenate arrays, default in mode delphi</li>
  2863. <li>{$macro on|off} enables macro replacements. Only macros with a value are replaced. Macros are never replaced inside directives.</li>
  2864. <li>{$I filename} or {$include filename} - insert include file</li>
  2865. <li>{$I %param%}:
  2866. <ul>
  2867. <li>%date%: current date as string literal, '[yyyy/mm/dd]'</li>
  2868. <li>%time%: current time as string literal, 'hh:mm:ss'. Note that the
  2869. inclusion of %date% and %time% will not cause the compiler to
  2870. recompile the unit every time it is used:
  2871. the date and time will be the date and time when the unit was last compiled.</li>
  2872. <li>%file%: current source filename as string literal, e.g. <i>'unit1.pas'</i></li>
  2873. <li>%line%: current source line number as string literal, e.g. <i>'123'</i></li>
  2874. <li>%linenum%: current source line number as integer, e.g. <i>123</i></li>
  2875. <li>%currentroutine%: name of current routine as string literal</li>
  2876. <li>%pas2jstarget%, %pas2jstargetos%, %fpctarget%, %fpctargetos%: target os as string literal, e.g. 'Browser'</li>
  2877. <li>%pas2jstargetcpu%, %fpctargetcpu%: target cpu as string literal, e.g. 'ECMAScript5'</li>
  2878. <li>%pas2jsversion%, %fpcversion%: compiler version as strnig literal, e.g. '1.0.2'</li>
  2879. <li>If param is none of the above it will use the environment variable.
  2880. Keep in mind that depending on the platform the name may be case sensitive.
  2881. If there is no such variable an empty string <i>''</i> is inserted.</li>
  2882. </ul>
  2883. </li>
  2884. <li>{$Warnings on|off}</li>
  2885. <li>{$Notes on|off}</li>
  2886. <li>{$Hints on|off}</li>
  2887. <li>{$Error text} : emit an error</li>
  2888. <li>{$Warning text} : emit a warning</li>
  2889. <li>{$Note text} : emit a note</li>
  2890. <li>{$Hint text} : emit a hint</li>
  2891. <li>{$Message hint-text} : emit a hint</li>
  2892. <li>{$Message hint|note|warn|error|fatal text} : emit a message</li>
  2893. <li>{$Warn identifier on|off|default|error} : enable or disable a specific hint.<br>
  2894. 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>
  2895. Identifier can be a message number as written by -vq or one of the following case insensitive:<br>
  2896. <ul>
  2897. <li>CONSTRUCTING_ABSTRACT: Constructing an instance of a class with abstract methods.</li>
  2898. <li>IMPLICIT_VARIANTS: Implicit use of the variants unit.</li>
  2899. <li>NO_RETVAL: Function result is not set</li>
  2900. <li>SYMBOL_DEPRECATED: Deprecated symbol.</li>
  2901. <li>SYMBOL_EXPERIMENTAL: Experimental symbol</li>
  2902. <li>SYMBOL_LIBRARY</li>
  2903. <li>SYMBOL_PLATFORM: Platform-dependent symbol.</li>
  2904. <li>SYMBOL_UNIMPLEMENTED: Unimplemented symbol.</li>
  2905. <li>HIDDEN_VIRTUAL: method hides virtual method of ancestor</li>
  2906. <li>GARBAGE: text after final end.</li>
  2907. <li>BOUNDS_ERROR: range check errors</li>
  2908. <li>MESSAGE_DIRECTIVE: user defined $message</li>
  2909. </ul>
  2910. </li>
  2911. <li>{$M+}, {$TypeInfo on}: switches default visibility for class members from public to published</li>
  2912. <li>{$ScopedEnums on|off} disabled(default): propagate enums to global scope, enable: needs fqn e.g. TEnumType.EnumValue.</li>
  2913. <li>{$C+} generate code for assertions</li>
  2914. <li>{$H+}, but not {$H-}</li>
  2915. <li>{$J-}, {$WriteableConst off}: Typed const become readonly. For example <i>const i:byte=3; ... i:=4</i> creates a compile time error.</li>
  2916. <li>{$M+} : allow published members
  2917. <li>{$Q+} : not yet supported, ignored
  2918. <li>{$R+}, {$RangeChecks on}: compile time range check hints become errors
  2919. and add runtime range checks for assignments.</li>
  2920. <li>{$ObjectChecks on|off}:
  2921. <ul>
  2922. <li>Verify method calls, i.e. check at runtime in every method if <i>Self</i> is a descendant class.</li>
  2923. <li>Check type casts, e.g. <i>TBird(AnObject)</i> becomes <i>AnObject as TBird</i></li>
  2924. </ul>
  2925. </li>
  2926. </ul>
  2927. Defines:
  2928. <ul>
  2929. <li>PASJS</li>
  2930. <li>PAS2JS_FULLVERSION - major*1000+minor*100+release, e.g. 1.2.3 = 10203</li>
  2931. <li>Target platform: Browser, NodeJS, Pas2JSTargetOS=&lt;value&gt;</li>
  2932. <li>Target processor: ECMAScript5, ECMAScript6, ECMAScript=5, Pas2JSTargetCPU=&lt;value&gt;</li>
  2933. <li>Mode: DELPHI, OBJFPC</li>
  2934. </ul>
  2935. </div>
  2936. <div class="section">
  2937. <h2 id="numbers">Numbers</h2>
  2938. JavaScript only supports double. All Pascal number types and enum values
  2939. are mapped to this. A double supports integers from<br>
  2940. MinInteger = -$10000000000000;<br>
  2941. MaxInteger = $fffffffffffff;<br>
  2942. MinDouble = 5.0e-324;<br>
  2943. MaxDouble = 1.7e+308;<br>
  2944. <br>
  2945. Intrinsic integer types:
  2946. <ul>
  2947. <li>Byte - unsigned 8-bit</li>
  2948. <li>ShortInt - signed 8-bit</li>
  2949. <li>Word - unsigned 16-bit</li>
  2950. <li>SmallInt - signed 16-bit</li>
  2951. <li>LongWord - unsigned 32-bit</li>
  2952. <li>LongInt - signed 32-bit</li>
  2953. <li>NativeUInt - unsigned 53-bit</li>
  2954. <li>NativeInt - signed 54-bit</li>
  2955. </ul>
  2956. Notes:
  2957. <ul>
  2958. <li>Division by zero does not raise an exception. 0/0 results in NaN, positive/0 is Infinity, negative/0 is -Infinity.</li>
  2959. <li>NaN&lt;&gt;NaN</li>
  2960. <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>
  2961. <li>Math.isNan(double) tests for NaN. Otherwise false. isNan(Infinity)=false.</li>
  2962. <li>Math.isFinite(double) tests if not NaN, positive or negative infinity.</li>
  2963. <li>Math.isInfinite(double) tests if positive or negative infinity.</li>
  2964. <li>For more functions see unit Math.</li>
  2965. <li>To make porting easier Single is defined in the system unit as alias of
  2966. double, but gives a warning. Since using higher precision might give
  2967. unexpected results you should check every place.</li>
  2968. </ul>
  2969. </div>
  2970. <div class="section">
  2971. <h2 id="othersupportedelements">Other supported Pascal elements</h2>
  2972. <ul>
  2973. <li><b>break</b>, <b>continue</b>, <b>exit</b>, <b>exit()</b></li>
  2974. <li><b>chr</b>, <b>ord</b></li>
  2975. <li>alias type and type alias type</li>
  2976. <li>inc()/dec() to += -=</li>
  2977. <li>Converts "a div b" to "Math.floor(a / b)"</li>
  2978. <li>and, or, xor, not: logical and bitwise</li>
  2979. <li>Name conflicts with JS identifiers are automatically fixed by changing case.
  2980. For example a Pascal function "<i>apply"</i> is renamed to "<i>Apply</i>".</li>
  2981. <li>uses unitname in 'filename'.
  2982. In <i>$mode delphi</i> the in-filenames are only allowed in the program
  2983. and the unitname must fit the filename,
  2984. e.g. <i>uses unit1 in 'sub/Unit1.pas'</i>.<br>
  2985. In <i>$mode objfpc</i> units can use in-filenames too and
  2986. alias are allowed, e.g. <i>uses foo in 'bar.pas'</i>.</li>
  2987. <li>The intrinsic procedure <b>str</b> works with boolean, integer, float and enumvalue.<br>
  2988. Additionally there is <b>str</b> function, that takes an arbitrary number of
  2989. arguments and returns a concatenated string. It supports string as parameter too.
  2990. For example s:=str(i,' ',d:1:5).<br>
  2991. Width and precision is supported. str(i:10) will add spaces to the left to fill up to 10 characters.</b>
  2992. str(aDouble:1:5) returns a string in decimal format with 5 digits for the fraction.</li>
  2993. <li>Intrinsic procedure WriteStr(out s: string; params...)</li>
  2994. <li><i>Debugger;</i> converts to <i>debugger;</i>. If a debugger is running
  2995. it will break on this line just like a break point.</li>
  2996. <li><i>function concat(string1,string2,...): string</i> since 1.3</li>
  2997. <li><i>$mode delphi: function lo|hi(integer): byte</i> since 1.3</li>
  2998. <li><i>$mode objfpc: function lo|hi(integer): byte|word|longword</i> since 1.3</li>
  2999. </ul>
  3000. </div>
  3001. <div class="section">
  3002. <h2 id="notsupportedelements">Not supported elements</h2>
  3003. <ul>
  3004. <li>Class destructor</li>
  3005. <li>Enums with custom values</li>
  3006. <li>Generics</li>
  3007. <li>Global properties</li>
  3008. <li>Futures</li>
  3009. <li>Inline</li>
  3010. <li>Library</li>
  3011. <li>Objects</li>
  3012. <li>Operator overloading</li>
  3013. <li>Pointer arithmetic</li>
  3014. <li>Package</li>
  3015. <li>Resources</li>
  3016. <li>RTTI extended, $RTTI</li>
  3017. <li>Variant records</li>
  3018. <li>Variants</li>
  3019. </ul>
  3020. </div>
  3021. <div class="section">
  3022. <h2 id="targetprocessor">JavaScript Version</h2>
  3023. Code generation depending on -P option:
  3024. <ul>
  3025. <li>ECMAScript5</li>
  3026. <li>ECMAScript6: using 0b for binary literals, and 0o for octal literals</li>
  3027. </ul>
  3028. </div>
  3029. <div class="section">
  3030. <h2 id="sourcemaps">Creating source maps</h2>
  3031. Source maps are files telling the browser what JavaScript comes from which
  3032. original source (e.g. Pascal file), similar to debug information in FPC/Delphi.<br>
  3033. In 2017 FireFox and Chrome supports source maps.<br>
  3034. You can enable generating source map files by using the <i>-Jm</i> option.<br>
  3035. The compiler generates one module.js.map file for every generated module.js file.
  3036. The last line of the .js file contains the line<br>
  3037. <i>//# sourceMappingURL=module.js.map</i><br>
  3038. telling the browser where to find the source map.<br>
  3039. The source map contains references to the Pascal files and included .js
  3040. files (e.g. -Jirtl.js) relative to the location of the source map.
  3041. Note that if the Pascal file lies in a parent directory, the relativ path
  3042. contains '../'. You can change the base directory of the relative paths by using
  3043. the option <i>-Jmbasedir=&lt;x&gt;</i>. For example <i>-JmC:\www\pas</i>
  3044. creates paths relative to C:\www\pas.<br>
  3045. You can set the base URL, where the browser finds the Pascal sources, by passing
  3046. the <i>-Jmsourceroot=&lt;x&gt;</i> option. For example
  3047. <i>-Jmsourceroot=http://www.yoursite.com/pas/</i>. The browser prepends this
  3048. to the source map filenames when downloading the original source files
  3049. (e.g. the .pas files).<br>
  3050. You can include the whole Pascal sources in the source map using the option
  3051. <i>-Jminclude</i>.<br>
  3052. <br>
  3053. To show the generated mapping for each line you can use the tool fpc/packages/fcl-js/examples/srcmapdump.<br>
  3054. <li>Option -JmXSSIHeader: According to the specifications sourcemap
  3055. should start with the XSSI (cross site script inclusion) protection header
  3056. <i>)]}'</i>. If your browser does not support that,
  3057. disable it with <i>-JmXSSIHeader-</i>. See here the specs:
  3058. https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.h7yy76c5il9v
  3059. </li>
  3060. </div>
  3061. <div id="footer">
  3062. </div>
  3063. </body>
  3064. </html>