translation.html 89 KB

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