translation.html 81 KB

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