translation.html 85 KB

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