Sign in Join
Wiki copytemporary

pas2js: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: pas2js

OldNewLine
1+## Pas2js : What is it ?
2+
3+### Compiler
4+
5+Pas2js is an open source [[Pascal]] to [[JavaScript]] transpiler. It parses Object Pascal and emits JavaScript. The JavaScript is currently of level ECMAScript 5 and should run in any browser or in Node.js (target "nodejs"). It is available in 5 forms:
6+
7+- as a library
8+- as a command-line program
9+- as a webserver
10+- as a node.js program
11+- as a program running in the browser.
12+
13+It transpiles from actual Pascal source, it has no intermediate .ppu files. That means all sources must always be available.
14+
15+Through external class definitions, the compiler can use JavaScript classes:
16+
17+- All classes available in the JavaScript runtime, and in the browser are available\
18+ through import units (comparable to the windows or unix units for the native compiler).
19+- For Node.js, basic support for the nodejs runtime environment is available.
20+- An import unit for jQuery is available (libjquery)
21+
22+As a non commercial open source project we are always searching for helping hands. If you want to contribute see [[Pas2js How to contribute|here]].
23+
24+This project is **not** related to a similar named project on github.
25+
26+### RTL
27+
28+For the generated code to work, a small JavaScript file is needed: rtl.js. It defines an object rtl. This object will start the Object Pascal code if you include a call to rtl.run() in the [[HTML]] page.
29+
30+```html4strict
31+<script type="application/javascript">
32+ rtl.run()
33+</script>
34+```
35+
36+pas2js can automatically include this file in the generated output, like this:
37+
38+ pas2js -Jc -Jirtl.js -Tbrowser hello.pas
39+
40+For nodejs, the compiler will insert the call to rtl.run() automatically at the end of the generated Javascript file.
41+
42+There is a basic Object Pascal RTL, several units from the FPC Packages are also available
43+
44+- system
45+- sysutils
46+- Math
47+- strutils
48+- rtlconst
49+- classes
50+- contnrs
51+- DB (yes, TDataset)
52+- fpcunit testsuite
53+- custapp
54+- restconnection
55+- js (javascript system objects)
56+- web (browser provided objects)
57+- libjquery (jquery is available too)
58+- nodejs (basic node runtime environment)
59+- typinfo
60+- objpas
61+- browserconsole (support writeln)
62+- dateutils
63+- browserapp
64+- nodejsapp
65+
66+## Where to get it
67+
68+The pas2js compiler and RTL are - naturally - open source and can be downloaded and used freely.
69+
70+### Releases
71+
72+The releases contain binaries for **Windows (32 and 64bit), Linux (64 bit) and macOS**.
73+
74+Installation procedure:
75+
76+1\. Download pas2js from:
77+
78+- <https://getpas2js.freepascal.org/>
79+
80+
81+Every version has a directory with the version number.
82+
83+A list of changes can be found on the changelog page [[Pas2JS Version Changes]]
84+
85+2\. Unpack it in folder of your choice. The example below uses **C:\lazarus\pas2js\**. The release contains three folders:
86+
87+- bin - contains the compiler as executable (pas2js or pas2js.exe), a pas2js.cfg, a library and some utilities.
88+- demo - lots of examples
89+- packages - the Pascal units of the RTL and other packages.
90+- tools - html2form - HTML to pascal code converter program
91+- utils - A script to create a pas2js.cfg: createconfig.pp
92+
93+
94+![](/wiki-images/f/fa/Pas2js-folder.png)
95+
96+3\. To use pas2js into Lazarus IDE see: <https://wiki.freepascal.org/lazarus_pas2js_integration>
97+
98+### GIT
99+
100+The sources are available on gitlab, and a read-only mirror exists on github.
101+
102+The makefile expects the sources of FPC to be present under the compiler directory. You can copy/clone the FPC sources there or set enviroment variable FPCDIR. Note that a symlink to the FPC sources will not work.
103+
104+Cloning pas2js and fpc git repos:
105+
106+``` bash
107+git clone https://gitlab.com/freepascal.org/fpc/pas2js.git pas2js
108+cd pas2js
109+git config --local pull.rebase true
110+git clone https://gitlab.com/freepascal.org/fpc/source.git compiler
111+cd compiler
112+git config --local pull.rebase true
113+```
114+
115+Updating local git repos:
116+
117+``` bash
118+cd pas2js
119+git pull
120+cd compiler
121+git pull
122+```
123+
124+Switching to the fixes branch:
125+
126+``` bash
127+cd pas2js
128+git checkout fixes_3_0
129+cd compiler
130+git checkout pas2js/fixes_3_0
131+```
132+
133+### Building on Linux/macOS
134+
135+Change to the directory and build it with:
136+
137+``` bash
138+make clean all
139+```
140+
141+This creates *bin/\$(TargetCPU)-\$(TargetOS)/pas2js* (Windows: pas2js.exe). For example on Linux 64bit it creates *bin/x86_64-linux/pas2js*, while under Windows 64bit it creates *bin\x86_64-win\pas2js.exe*. And a basic config file *bin/x86_64-linux/pas2js.cfg*.
142+
143+### Building on Windows
144+
145+Make sure that you use the *make.exe* from fpc, not the one from Delphi by setting the **PATH**: For example if you installed the 32-bit version of fpc in *C:\YourPathOfFPC\3.2.2*:
146+
147+``` bash
148+set PATH=C:\YourPathOfFPC\3.2.2\bin\i386-win32;%PATH%
149+```
150+
151+If you installed the 64-bit version of fpc in C:\YourPathOfFPC\3.2.2 use
152+
153+``` bash
154+set PATH=C:\YourPathOfFPC\3.2.2\bin\x86-64-win64;%PATH%
155+```
156+
157+Then build with
158+
159+``` bash
160+make clean all
161+```
162+
163+If you see "Error makefile ... Command syntax error" your "set PATH" was not correct. When make all has succesfully finished it created with a 32-bit fpc the executable *bin/i386-win32/pas2js.exe* and a basic config file *bin/i386-win32/pas2js.cfg*.
164+
165+### pas2js.cfg
166+
167+When you built via **make**, it creates a **pas2js.cfg** in *bin/\$(TargetCPU)-\$(TargetOS)/*.
168+
169+You can create a basic pas2js.cfg yourself by either using *tools/createconfig/createconfig* or manually:
170+
171+For more about pas2js.cfg see here: [[pas2js.cfg]]
172+
173+## How to use pas2js
174+
175+The command-line arguments are kept mostly the same as the FPC command-line arguments. Error messages are also in the same format.
176+
177+The compiler needs access to all sources, and so you need to specify the path to the sources of all used units.
178+
179+As for the FPC compiler, a configuration file is supported, which has the same syntax as the FPC config file. Note that the snapshots and svn version already contains a default pas2js.cfg with unit search paths (-Fu) for the rtl and fcl. See here how for details about the [[pas2js.cfg]].
180+
181+Basically, the command is the same as any FPC command line. The only thing that is different is the target: *-Tbrowser* or *-Tnodeejs*
182+
183+Here is the complete list of [[pas2js command line arguments|command line arguments]].
184+
185+### for the browser
186+
187+Consider the classical:
188+
189+``` pascal
190+program hello;
191+
192+begin
193+ Writeln('Hello, world!');
194+end.
195+```
196+
197+Yes, writeln is supported. Here is how to compile it:
198+
199+ pas2js -Jc -Jirtl.js -Tbrowser hello.pas
200+
201+When compiled succesfully, the code can be run in the browser by opening a html file in the browser with the following content:
202+
203+```html4strict
204+<html>
205+ <head>
206+ <meta charset="utf-8"/>
207+ <script type="application/javascript" src="hello.js"></script>
208+ </head>
209+ <body>
210+ <script type="application/javascript">
211+ rtl.run();
212+ </script>
213+ </body>
214+</html>
215+```
216+
217+The files that are needed are:
218+
219+- hello.html
220+- hello.js
221+
222+Whether hello.html is opened by double-clicking it in the explorer or put on a server and opened with an URL, is not relevant for the functioning.
223+
224+The output is visible in the browser's web developer console. By including the browserconsole unit, it will be visible in the browser page:
225+
226+``` pascal
227+program hello;
228+
229+uses browserconsole;
230+
231+begin
232+ Writeln('Hello, world!');
233+end.
234+```
235+
236+### for NodeJS
237+
238+ pas2js -Tnodejs hello.pas
239+
240+When compiled succesfully, the code can be run in node using the following command.
241+
242+ nodejs hello.js
243+
244+### for modules
245+
246+Pas2js supports compiling modules:
247+
248+ pas2js -Tmodule mymodule.pas
249+
250+When compiled succesfully, the code can be used in a web page using the following tag:
251+
252+ <script type="module" src="mymodule.js"><script>
253+
254+More info can be found on the [[pas2js modules|Modules page]]
255+
256+## Supported syntax elements
257+
258+A significant amount of Object Pascal syntax is supported, including RTTI. A more detailed list can be found in the [[Pas2js Transpiler]] file in the sources.
259+
260+- [[Mode Delphi|Delphi]] and [[Mode ObjFPC|ObjFPC]] mode
261+- [[Program]], [[Unit|Units]], namespaces
262+- [[pas2js modules|Library]] since 2.1.0
263+- unit initialization, but not finalization
264+- [[Var]], [[Const]], [[Type]]
265+- string (unicodestring), char (widechar), [[Boolean]], [[Double]], [[Byte]], [[Shortint]], [[Word]], [[Smallint]], longword, [[Longint]], nativeint(int53), nativeuint(int52), currency
266+- resourcestrings
267+- [[Pointer]] (as a reference to a class, array, record, pointer of record, interface, but no pointer arithmetic)
268+- [[Record]] (but no variant records), advanced records (since 1.3)
269+- [[Function|Functions]], [[Procedure|Procedures]], nested, anonymous functions (since 1.1)
270+- function types, of object, reference to (closures)
271+- function arguments: default, const, var, out
272+- [[If]]-then-else
273+- [[For]]-do
274+- [[Repeat]]-until
275+- [[While]]-do
276+- [[With]]-do
277+- try-finally
278+- try-except
279+- enums
280+- sets
281+- arrays static, dynamic, open, multi dimensionals, array of const
282+- String like array operations: *a:=\[1,2,3\]+\[1,1\];*
283+- class type, visibility, virtual, override, abstract, overload, properties, class properties, class var, class const, constructor, destructor, class constructor (since 1.5)
284+- class-of
285+- nested classes
286+- interfaces: CORBA, COM, delegations, method resolution, reference counting, TVirtualInterface
287+- external classes, vars, const
288+- class helpers, record helpers, type helpers (since 1.3)
289+- Enumeration for..in..do
290+- Type alias, e.g. type TTranslateString = type string;
291+- RTTI
292+- asm block for embedding JavaScript directly
293+- compiler directives (e.g. \$ifdef, \$if, \$define, \$modeswitch, \$R+)
294+- compile time and run time range checking. Overflow checking since 1.5.
295+- attributes (since 1.5)
296+- [[pas2js modules|$linklib]] directive to link [[pas2js modules|modules]].
297+- [[pas2js Generics|generics]] (since 1.5)
298+- [[pas2js resources|Resources]] (since 1.5)
299+
300+There are some constructs that are naturally not supported and will never be supported:
301+
302+- Anything involving memory pointers and pointer arithmetic.
303+- Variant records
304+
305+And there are some extra constructs unique to pas2js:
306+
307+- **JSValue** - a base type representing a JavaScript value.
308+- function Str(X\[,Y,Z...\]): string - same as procedure Str, except as a function
309+- [[pas2js AsyncAWait|async/await]]
310+
311+## Planned language features
312+
313+Basically, the idea is to get the pas2js transpiler up to the same level as FPC or Delphi. That means the following needs to be added:
314+
315+- Extended RTTI
316+- Operator Overloading
317+- anonymous records, e.g. *var a: array of record w: word; end;*
318+- [[Pas2js Package|Packages]]
319+
320+Needless to say, anything requiring direct memory access is not going to be supported.
321+
322+## Other unimplemented features
323+
324+- Array of interface
325+- Enums with custom values
326+- Finalization sections, class destructors
327+- Futures
328+- Global properties
329+- Inline
330+- Library
331+- Objects
332+- Pointer arithmetic
333+- Record field interface
334+- Variants
335+
336+## Lazarus integration of pas2js
337+
338+Lazarus understands the concept of external classes as used by pas2js, so code completion will work.
339+
340+Since Lazarus 1.9 the IDE can use pas2js.exe as a normal compiler.
341+
342+The integration is described here: [[lazarus pas2js integration]]. It is still under construction, but deep integration with lazarus is planned.
343+
344+## Importing Javascript classes
345+
346+To import a javascript class, one writes a normal class definition that mimics the Javascript class. It is possible to use properties. Many examples can be found in the JS, web, nodejs and libjquery units.
347+
348+Here is a simple example:
349+
350+``` pascal
351+ TJSFunction = class external name 'Function'(TJSObject)
352+ private
353+ Flength: NativeInt external name 'length';
354+ Fprototyp: TJSFunction external name 'prototyp';
355+ public
356+ name: String;
357+ property prototyp: TJSFunction read Fprototyp;
358+ property length: NativeInt read Flength;
359+ function apply(thisArg: TJSObject; const ArgArray: TJSValueDynArray): JSValue; varargs;
360+ function bind(thisArg: TJSObject): JSValue; varargs;
361+ function call(thisArg: TJSObject): JSValue; varargs;
362+ end;
363+```
364+
365+This declares the `TJSFunction` object : in Javascript, functions are objects.
366+
367+- The "`external name 'Function'`" means that you declare a Javascript class where the Javascript name of the class is 'Function'.
368+- The `(TJSObject)` means it descends from `TJSObject` also an external class. There does not need to be an ancestor type.
369+- Fields are declared just as in Pascal.
370+- To declare read-only fields, a trick can be used: declare the field using an external name "thename" modifier, and declare a read-only property with the same name.\
371+ (see the length declaration)
372+- `Varargs` can be used to indicate that a function accepts any number of arguments.
373+- `JSValue` can be used to indicate an unknown type.\
374+ It is more or less equivalent to a Variant.
375+
376+## Create simple JS objects with the new function
377+
378+Some JS-framework functions expect an JS object as parameter. Here is how to do that in Pascal using the *new* function from unit *JS*:
379+
380+``` javascript
381+// JavaScript:
382+DoIt({name:"Fred", id:3, size:4.3});
383+```
384+
385+``` pascal
386+// Pascal;
387+DoIt(new(['name','Fred', 'id',3, 'size',4.3]));
388+```
389+
390+You can nest it to create sub objects:
391+
392+``` javascript
393+// JavaScript:
394+DoIt({name:"Fred", size:{width:3,height:2}});
395+```
396+
397+``` pascal
398+// Pascal;
399+DoIt(new(['name','Fred', 'size',new(['width',3, 'height',2])]));
400+```
401+
402+You can use TJSArray._of to create JS arrays on the fly:
403+
404+``` javascript
405+// JavaScript:
406+DoIt({numbers:[1,2,3]});
407+```
408+
409+``` pascal
410+// Pascal;
411+DoIt(new(['numbers',TJSArray._of(1,2,3)]));
412+```
413+
414+## Resource strings
415+
416+The pas2js transpiler can generate a JSON file (extension *.jrs*) with all the resource strings in your program.
417+
418+This is a quite simple file. A JSON object exists for every unit, with each json property a resource string.
419+
420+ {
421+ "trs2" : {
422+ "ResUsed" : "This resourcestring is used",
423+ "ResUnUsed" : "This resourcestring is not used",
424+ "ImplResUsed" : "This implementation resourcestring is used"
425+ },
426+ "trs1" : {
427+ "MyString" : "The very nice string we will need to translate"
428+ }
429+ }
430+
431+This file can be translated, and the translation file can be loaded using the **rstranslate** unit, part of the rtl. There are demo programs which demonstrate the use of this feature.
432+
433+The generating of this file is controlled by the **-Jr** option. It can take 3 possible arguments:
434+
435+1. *none* This is the default, no file is generated.
436+2. *unit* one file per compiled unit will be generated. This file will contain all resource strings of the unit.
437+3. *program* one file is generated for the main file. This fill will contain all used resource strings for the main file and all the units it uses.
438+
439+If you compile a program, then the *program* option will generate a file with all the used resource strings in your program.
440+
441+The above example was generated using the command:
442+
443+ pas2js -Jrprogram trs1.pp -B
444+
445+Note that the format is different from the format used by FPC:
446+
447+- Identifiers in the file are case sensitive: the names must be typed as they appear in the source file.
448+- The strings are grouped per unit, this allows to load them fasters
449+- The hash and bytes parts are missing, they make little sense in a Javascript context.
450+
451+## Exceptions
452+
453+Exceptions are translated to actual Javascript exceptions. The rtl.js has several mechanisms to deal with uncaught exceptions. The basic mechanism is setting the *showUncaughtExceptions* to true before calling rtl.run() in your html file:
454+
455+ <script type="application/javascript">
456+ rtl.showUncaughtExceptions=true;
457+ rtl.run();
458+ </script>
459+
460+the browser will then use a *window.alert()* to show uncaught exceptions.
461+
462+More explanations can be found in [[pas2js exceptions]]
463+
464+## Debugging
465+
466+The generated Javascript source code is of course visible and debuggable in the browser.
467+
468+Moreover, the transpiler can generate a source map, which means that you will be able to see and debug the Pascal code in the browser. (not everything will work, but many things do. This depends on the browser too.)
469+
470+A source map can be generated using the command-line parameter:
471+
472+ -Jm
473+
474+The easiest is to include the Pascal sources in the source map:
475+
476+ -Jminclude
477+
478+By default all source filenames are relative to .js.map. You can tell the compiler to store all file names relative to a specific local base directory:
479+
480+ -Jmbasedir=DirName
481+
482+And you can store an URL in the map, so the browser will use URL/above-relative-file-name to get the source:
483+
484+ -Jmsourceroot=URL
485+
486+## Porting from FPC/Delphi
487+
488+See [[Porting from FPC/Delphi to pas2js|here]] for tips and traps porting code from FPC and Delphi.
489+
490+Delphi cannot parse some of the constructs that exist in *pas2js* (namely: external classes). You can create stub declarations suitable for the Delphi parser with the [[pas2js makestub|stub creator]].
491+
492+## Bugs
493+
494+Please report bugs in the [FPC Bug Tracker](https://bugs.freepascal.org) with category *pas2js*.
495+
496+## Examples
497+
498+- Time Tracking Application: <https://www.devstructor.com/demos/pas2js-time/source.zip> (sources: <https://www.devstructor.com/demos/pas2js-time/source.zip>)
499+- Drawing and animation on canvas: <http://ragnemalm.se/images/santa/santa.html> (sources: <http://ragnemalm.se/images/santa/>)
500+- WebGL: <https://github.com/genericptr/Pas2JS-WebGL#pas2js-webgl>
501+- Allegro Web Game: <https://lainz.github.io/AllegroPas2JS-Demo-Game/index.html> (sources: <https://github.com/lainz/AllegroPas2JS-Demo-Game>)
502+- Pas2JS (freepascal) Compiler Tutorials on RetroNick's Programming Channel: <https://youtube.com/playlist?list=PLdLUbKp49uouo9UMrBDvXIoJx6j084_ef>
503+
504+## Lazarus Widgetset
505+
506+The ultimate goal is of course to have the LCL running in the web. Discussions on this topic are delegated to a separate page. [[pas2js widgetsets]]
507+
508+## FAQ
509+
510+### Why is a simple hello world program so big?
511+
512+This is mainly due to the used rtl.js. The rtl.js contains code for Pascal modules, classes, RTTI, sets, range checks, etc and is written with big WebApps in mind, not for scripts with a few lines of code.
513+
514+1. You can use a Javascript [[pas2js minifier|minifier]] to reduce the created Javascript
515+2. You can create your own minified rtl.js by removing all functions you don't need. Eventually this will be done automatically by pas2js.
516+
517+### Why are asm blocks bad?
518+
519+Asm blocks are useful for things you cannot do with pas2js. But there are some downsides: pas2js does not parse the JS. Neither does it check the syntax, nor does it know what Pascal identifiers the code is referencing. That means any identifier only accessed by the asm block will be removed by the pas2js' optimizer.
520+
521+Therefore always try to do it in Pascal. Remember you can typecast values to JSValue, objects to TJSObject, arrays to TJSArray, strings to TJSString, etc to use almost all JS features.
522+
523+### Why not parse asm blocks?
524+
525+Any compiletime JS parser can only do a syntax check and parse only simple JS. But since simple JS can be better written in Pascal, it is somewhat pointless and has therefore low priority.
526+
527+### What about optimization X?
528+
529+See here for [[Pas2js optimizations]]
530+
531+## See also
532+
533+- [[pas2js html2form]] - a small tool that converts an HTML file to a Pascal class.
534+
535+---
536+*From the Free Pascal wiki, page "pas2js", as it stood on 2024-02-21 after a change by Michael, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history