forked from synopse/mORMot2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmormot.lib.quickjs.pas
More file actions
3645 lines (3012 loc) · 106 KB
/
Copy pathmormot.lib.quickjs.pas
File metadata and controls
3645 lines (3012 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// low-level access to the QuickJS Engine
// - this unit is a part of the Open Source Synopse mORMot framework 2,
// licensed under a MPL/GPL/LGPL three license - see LICENSE.md
unit mormot.lib.quickjs;
{
*****************************************************************************
Cross-Platform and Cross-Compiler JavaScript Interpreter
- QuickJS to Pascal Wrappers
- QuickJS Low-Level Constants and Types
- QuickJS Functions API
*****************************************************************************
}
interface
{$I ..\mormot.defines.inc}
{
QuickJS is a small and embeddable Javascript engine.
It supports the ES2020 specification including modules, asynchronous
generators, proxies and BigInt.
Copyright 2017-2020 Fabrice Bellard and Charlie Gordon - MIT License
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation files
(the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
{$ifdef LIBQUICKJSSTATIC}
// we embedd https://github.com/c-smile/quickjspp fork statics
// - 64-bit JSValue on all platforms, JSX, debugger, no quickjs-libc
// - amalgamation file patched for pascal static linking (malloc, assert)
// - see res/static/libquickjs for source and build instructions
{$define JS_STRICT_NAN_BOXING}
{$define LIBQUICKJS}
{$endif LIBQUICKJSSTATIC}
{$ifdef LIBQUICKJS}
uses
sysutils,
classes,
math,
mormot.core.base,
mormot.core.os,
mormot.core.unicode,
mormot.core.text,
mormot.core.json,
mormot.core.datetime,
mormot.core.data,
mormot.core.variants;
{$ifdef JS_STRICT_NAN_BOXING}
// on 32+64-bit, JSValue is an 64-bit with double NAN bits used as tag
{$define JS_ANY_NAN_BOXING}
{$else}
// on 32-bit, JSValue is an 64-bit with double NAN bits used as tag
// on 64-bit, JSValue is a 128-bit struct of explicit value + tag
{$ifdef CPU32}
{$define JS_NAN_BOXING}
{$define JS_ANY_NAN_BOXING}
{$endif CPU32}
{$endif JS_STRICT_NAN_BOXING}
{ ************ QuickJS to Pascal Wrappers }
type
{$A-} { packet object not allowed since Delphi 2009 :( }
// some definitions ahead of low-level QuickJS API to allow pointer wrapping
{$ifdef JS_ANY_NAN_BOXING}
{$ifdef CPU64}
{$define JS_ANY_NAN_BOXING_CPU64}
{$endif CPU64}
/// JSValue as stored in a 64-bit integer (one or two registers)
// - mandatory for the proper values marshalling over QuickJS API calls
// - don't use this low-level type, but the high-level JSValue wrapper
JSValueRaw = UInt64;
{$else}
/// JSValue as stored in a 128-bit structure (two registers)
// - mandatory for the proper values marshalling over QuickJS API calls
// - don't use this low-level type, but the high-level JSValue wrapper
JSValueRaw = record
union, tag: Int64;
end;
{$endif JS_ANY_NAN_BOXING}
/// wrapper object to the QuickJS JSValueRaw opaque type
// - you can use e.g. JSValue(somejsvaluevariable).IsObject or JSValue.Raw
// - JSValueRaw is the low-level type mandatory for QuickJS API calls: using
// JSValue to call the QuickJS library fails to use registers, so trigger GPF
// - number above MAX_SAFE_JS_INTEGER (53-bit) would be stored as double
{$ifdef USERECORDWITHMETHODS}
JSValue = record
{$else}
JSValue = object
{$endif USERECORDWITHMETHODS}
private
u: record
case byte of
0:
(i32,
tag: integer);
1:
(f64: Double);
2:
(ptr: pointer);
3:
(u64: UInt64);
end;
{$ifndef JS_ANY_NAN_BOXING}
UnboxedTag: Int64;
{$endif JS_ANY_NAN_BOXING}
/// return the tag of this value - won't detect JS_TAG_FLOAT64
function TagNotFloat: PtrInt;
{$ifdef HASINLINE} inline; {$endif}
/// get the value as expected by the raw QuickJS API
function GetRaw: JSValueRaw;
{$ifdef HASINLINE} inline; {$endif}
procedure SetRaw(const value: JSValueRaw);
{$ifdef HASINLINE} inline; {$endif}
public
/// set the tag bits - should be called before setting u.f64/ptr/u64 (i32 ok)
procedure SetTag(newtag: PtrInt);
{$ifdef HASINLINE} inline; {$endif}
/// get the tag of this value, normalizing floats to JS_TAG_FLOAT64
function NormTag: PtrInt;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_NULL
function IsNull: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_UNDEFINED
function IsUndefined: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_UNINITIALIZED
function IsUninitialized: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_STRING
function IsString: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_OBJECT
function IsObject: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_EXCEPTION
function IsException: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_SYMBOL
function IsSymbol: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_INT
function IsInt32: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_FLOAT64
function IsFloat: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_INT or JS_TAG_FLOAT64
function IsNumber: boolean;
/// detect NaN/+Inf/-Inf special values
function IsNan: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_BIG_INT
function IsBigInt: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_BIG_FLOAT
function IsBigFloat: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect JS_TAG_BIG_DECIMAL
function IsBigDecimal: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// detect reference-counted values
function IsRefCounted: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// extract the JS_TAG_INT value
function Int32: integer;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// extract the JS_TAG_INT or JS_TAG_FLOAT64 value as an 53-bit integer
function Int64: Int64;
/// extract the JS_TAG_BOOL value
function Bool: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// extract the JS_TAG_FLOAT64 value
function F64: double;
/// may be JSObject or JSString
function Ptr: pointer;
{$ifdef HASINLINE} inline; {$endif}
/// used internally by Duplicate/DuplicateRaw
procedure IncRefCnt;
{$ifdef HASINLINE} inline; {$endif}
/// used internally e.g. by TJSContext.Free
function DecRefCnt: boolean;
{$ifdef HASINLINE} inline; {$endif}
/// retrieve or change the value as expected by the raw QuickJS API
property Raw: JSValueRaw
read GetRaw write SetRaw;
/// return a copy of this value, incrementing the refcount if needed
function Duplicate: JSValue;
/// return a copy of this value, without incrementing the refcount
function DuplicateRaw: JSValueRaw;
/// compare two JS values at binary level
function Equals(const another: JSValue): boolean;
{$ifdef HASINLINE} inline; {$endif}
/// set to a JS_TAG_UNINITIALIZED value
procedure Empty;
{$ifdef HASINLINE} inline; {$endif}
/// set a value from its tag and 32-bit content
procedure Fill(newtag, val: integer); overload;
{$ifdef HASINLINE} inline; {$endif}
/// set a pointer value - may be JSObject or JSString
procedure Fill(newtag: integer; val: pointer); overload;
{$ifndef JS_ANY_NAN_BOXING_CPU64}{$ifdef HASINLINE}inline;{$endif}{$endif}
/// create a JS_TAG_BOOL
procedure From(val: boolean);
{$ifdef HASINLINE} inline; {$endif}
/// create a JS_TAG_INT
procedure From32(val: integer);
{$ifdef HASINLINE} inline; {$endif}
/// create a JS_TAG_INT if possible, JS_TAG_FLOAT64 otherwise
procedure From64(val: Int64);
{$ifdef HASINLINE} inline; {$endif}
/// create a JS_TAG_INT if possible, JS_TAG_FLOAT64 otherwise
procedure FromNum(val: double);
/// create a JS_TAG_FLOAT64
procedure FromFloat(val: double);
end;
{$A+}
{$ifdef FPC}
{$packrecords C}
{$endif FPC}
PJSValueRaw = ^JSValueRaw;
PJSValue = ^JSValue;
JSValues = array[0..(MaxInt div SizeOf(JSValue)) - 1] of JSValue;
PJSValues = ^JSValues;
JSValueDynArray = array of JSValue;
type
JSRuntime = ^TJSRuntime;
JSContext = ^TJSContext;
JSFunction = function(ctx: JSContext; this_val: JSValueRaw; argc: integer;
argv: PJSValues): JSValueRaw; cdecl;
/// wrapper object to the QuickJS JSRuntime abstract pointer type
// - JSRuntime is a pointer to this opaque object
// - only a single
{$ifdef USERECORDWITHMETHODS}
TJSRuntime = record
{$else}
TJSRuntime = object
{$endif USERECORDWITHMETHODS}
public
/// create a new execution context for this Runtime
function New: JSContext;
/// just a wrapper around JS_FreeRuntime(@self)
procedure Done;
/// just a wrapper around Done with exception/signal tracking
// - EQuickJS panic exception may occur if the GC detected some leak
function DoneSafe: string;
end;
/// wrapper object to the QuickJS JSContext abstract pointer type
// - JSContext is a pointer to this opaque object
{$ifdef USERECORDWITHMETHODS}
TJSContext = record
{$else}
TJSContext = object
{$endif USERECORDWITHMETHODS}
public
/// just a wrapper around JS_FreeContext(@self)
procedure Done;
/// release the memory used by a JSValueRaw - JS_FreeValue() alternative
procedure FreeInlined(v: PJSValue);
{$ifdef HASSAFEINLINE} inline; {$endif}
/// release the memory used by a JSValue - JS_FreeValue() alternative
// - won't be inlined so may be used when performance matters less
procedure Free(var v: JSValue);
/// retrieve a property of the global object
// - caller should make cx.Free(val) once done with this value
function GetValue(prop: PAnsiChar; out val: JSValue;
raiseIfNotFound: boolean = false): boolean; overload;
/// retrieve a property of a given object
// - caller should make cx.Free(val) once done with this value
function GetValue(obj: JSValue; prop: PAnsiChar; out val: JSValue;
raiseIfNotFound: boolean = false): boolean; overload;
/// retrieve a property of a given object, and free the object
// - caller should make cx.Free(val) once done with this value
function GetValueFree(obj: JSValue; prop: PAnsiChar; out val: JSValue;
raiseIfNotFound: boolean = false): boolean; overload;
/// retrieve a property value from its cascaded names
// - caller should make cx.Free(val) once done with this value
// - if parent is defined, it will store the previous prop[] object
// - GetValue([], glob) will return the global object
function GetValue(const prop: array of PAnsiChar; out val: JSValue;
parent: PJSValue = nil; raiseIfNotFound: boolean = false): boolean; overload;
/// assign a value to an object property by name
procedure SetValue(obj: JSValue; prop: PAnsiChar; val: JSValue);
/// assign a function to an object property by name
procedure SetFunction(obj: JSValue; prop: PAnsiChar;
func: JSFunction; args: integer); overload;
/// assign a function to an object property by cascaded names
// - will resolve the object path from the first obj[] name
// - SetFunction([], 'funcname',...) will set a global function
procedure SetFunction(const obj: array of PAnsiChar; prop: PAnsiChar;
func: JSFunction; args: integer); overload;
/// raise an EQuickJS exception if an API call result returned FALSE (0)
procedure Check(res: integer; caller: PAnsiChar);
{$ifdef HASINLINE} inline; {$endif}
/// returns the current error message, after JSValue.IsException=true
// - by default will get the exception from JS_GetException(), but you
// can optionally specify the error reason/exception
procedure ErrorMessage(stacktrace: boolean; var msg: RawUtf8;
reason: PJSValue = nil);
/// output ErrorMessage() text into the current error stream
// - is the StdErr console by default, but may be redirected e.g. to a log
procedure ErrorDump(stacktrace: boolean; reason: PJSValue = nil);
/// compute a JS_EXCEPTION from an object pascal exception instance
function ThrowInternalError(E: Exception): JSValueRaw;
/// raw execution of some JavaScript code
function Eval(const code, fn: RawUtf8; flags: integer; out err: RawUtf8): JSValue;
/// execute some JavaScript code in the global context
// - returns '' on success, or an error message if compilation failed
function EvalGlobal(const code: RawUtf8; const filename: RawUtf8 = ''): RawUtf8;
/// execute some JavaScript code as a module
// - returns '' on success, or an error message if compilation failed
function EvalModule(const code, filename: RawUtf8): RawUtf8;
/// raw execution of a JavaScript function
// - if objectname='', the Global object will be used
// - will release the supplied args[] values when leaving
function CallRaw(const objectname, funcname: RawUtf8;
var args: JSValueDynArray): JSValueRaw; overload;
/// raw execution of a JavaScript function from a JS Object
// - will release the supplied args[] values when leaving
function CallRaw(obj: JSValue; const funcname: RawUtf8;
var args: JSValueDynArray): JSValueRaw; overload;
/// raw execution of a JavaScript function from a JS Object and Function
function CallRaw(obj, fun: JSValue;
const args: JSValueDynArray): JSValueRaw; overload;
/// execution of a JavaScript function with direct parameters provided
// - if objectname='', the Global object will be used
// - caller should make cx.Free(result) once done
function Call(const objectname, funcname: RawUtf8;
const args: array of const): JSValue; overload;
/// variant-oriented execution of a JavaScript function
// - if objectname='', the Global object will be used
function CallVariant(const objectname, funcname: RawUtf8;
const args: array of variant): variant; overload;
/// variant-oriented execution of a JavaScript function from a JS object
function CallVariant(obj: JSValue; const funcname: RawUtf8;
const args: array of variant): variant; overload;
/// convert a JSValue into its RawUtf8 text
// - a JS_TAG_OBJECT returns its JSON serialization unless noJson is set
procedure ToUtf8(v: JSValue; var s: RawUtf8; noJson: boolean = false); overload;
/// convert a JSValue into its RawUtf8 text
function ToUtf8(const v: JSValue; noJson: boolean = false): RawUtf8; overload;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// convert a JSValue into its RawUtf8 text and free the value
function ToUtf8Free(var v: JSValue; noJson: boolean = false): RawUtf8;
/// convert a JSValue into an UTF-8 text buffer
procedure ToUtf8(const v: JSValue; var temp: TSynTempBuffer); overload;
/// append a JSValue as text
procedure AddUtf8(const v: JSValue; var s: RawUtf8; const sep: RawUtf8 = '');
/// convert a JSValue into a variant
// - convert into varNull, varBoolean, varInt, varInt64, varDouble, varString
// or TDocVariant (after JsonStringify for JS_TAG_OBJECT) and returns true
// - unhandled kinds return false
function ToVariant(var v: JSValue; var res: variant): boolean;
/// convert a JSValue into a variant and free the value
function ToVariantFree(var v: JSValue; var res: variant): boolean;
/// create a JS_TAG_STRING from UTF-8 buffer
function From(P: PUtf8Char; Len: PtrInt): JSValue; overload;
/// create a JS_TAG_STRING from UTF-16 buffer
function FromW(P: PWideChar; Len: PtrInt): JSValue; overload;
/// create a JS_TAG_STRING from UTF-8 string
function From(const val: RawUtf8): JSValue; overload;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// create a JS_TAG_STRING from UTF-16 string
function FromW(const val: SynUnicode): JSValue; overload;
{$ifdef HASSAFEINLINE} inline; {$endif}
/// create a JS value from an "array of const" value
procedure FromVarRec(const val: TVarRec; out result: JSValue);
/// create a JS value from a variant value
procedure FromVariant(const val: variant; out result: JSValue);
/// create a JS_TAG_OBJECT from a class instance published properties
procedure FromClass(instance: TObject; out result: JSValue);
/// create a JS Value by unserializing JSON - maybe creating a JS_TAG_OBJECT
procedure FromJson(const json: RawUtf8; out result: JSValue;
exceptonerror: boolean = true);
/// create a Date object value from its Unix MS timestamp
procedure FromUnixMSTime(val: TUnixMSTime; out result: JSValue);
/// create a Date object value from a TDateTime value
procedure FromDate(val: TDateTime; out result: JSValue);
end;
type
/// exception raised by this unit on QuickJS panic
// - mainly if assert() - aka pas_assert() - failed in the C code
EQuickJS = class(ESynException)
public
/// create a message with the current JSContext exception information
constructor Create(ctx: pointer; caller: PAnsiChar;
stacktrace: boolean = true); overload;
/// create a message with the current JSContext exception information
// and free the supplied value
// - typical use is
// ! if result.IsException then
// ! raise EQuickJS.Create(@self, 'methodname', result);
constructor Create(ctx: pointer; caller: PAnsiChar; var tofree: JSValue;
stacktrace: boolean = true); overload;
end;
{ ************ QuickJS Low-Level Constants and Types }
const
{$ifdef JS_STRICT_NAN_BOXING}
// https://github.com/c-smile/quickjspp encoding = always 64-bit
JS_TAG_UNINITIALIZED = 0;
JS_TAG_INT = 1;
JS_TAG_BOOL = 2;
JS_TAG_NULL = 3;
JS_TAG_UNDEFINED = 4;
JS_TAG_CATCH_OFFSET = 5;
JS_TAG_EXCEPTION = 6;
JS_TAG_FLOAT64 = 7;
// all tags with a reference count have (NormTag and $fff8) = $0008
JS_TAG_OBJECT = 8;
JS_TAG_FUNCTION_BYTECODE = 9; // internal use
JS_TAG_MODULE = 10; // internal use
JS_TAG_STRING = 11;
JS_TAG_SYMBOL = 12;
JS_TAG_BIG_FLOAT = 13;
JS_TAG_BIG_INT = 14;
JS_TAG_BIG_DECIMAL = 15;
JS_TAG_MASK = $000fffffffffffff;
JS_NAN_MASK = $7ff00000;
JS_NAN = UInt64(JS_TAG_FLOAT64) shl 48 + 0;
JS_INFINITY_NEGATIVE = UInt64(JS_TAG_FLOAT64) shl 48 + 1;
JS_INFINITY_POSITIVE = UInt64(JS_TAG_FLOAT64) shl 48 + 2;
{$else}
// regular https://github.com/bellard/quickjs encoding (buggy on Windows)
JS_TAG_FIRST = -11; // first negative tag
JS_TAG_BIG_DECIMAL = -11;
JS_TAG_BIG_INT = -10;
JS_TAG_BIG_FLOAT = -9;
JS_TAG_SYMBOL = -8;
JS_TAG_STRING = -7;
JS_TAG_MODULE = -3; // internal use
JS_TAG_FUNCTION_BYTECODE = -2; // internal use
JS_TAG_OBJECT = -1;
// all tags with a reference count are negative
JS_TAG_INT = 0;
JS_TAG_BOOL = 1;
JS_TAG_NULL = 2;
JS_TAG_UNDEFINED = 3;
JS_TAG_UNINITIALIZED = 4;
JS_TAG_CATCH_OFFSET = 5;
JS_TAG_EXCEPTION = 6;
JS_TAG_FLOAT64 = 7;
// any tag larger than FLOAT64 needs to be handled as JS_NAN_BOXING
{$ifdef JS_NAN_BOXING}
JS_FLOAT64_TAG_ADDEND = $7ff80000 - JS_TAG_FIRST + 1; // quiet NaN encoding
JS_NAN = UInt64($7ff8000000000000 - (JS_FLOAT64_TAG_ADDEND shl 32));
{$else}
var
JS_NAN: JSValueRaw;
{$endif JS_NAN_BOXING}
{$endif JS_STRICT_NAN_BOXING}
const
JS_FLOAT64_NAN: double = NaN;
JS_FLOAT64_POSINF: double = Infinity;
JS_FLOAT64_NEGINF: double = NegInfinity;
{$ifdef CPU64}
// any 64-bit pointer can be truncated to 48-bit on Intel/AMD CPUs
JS_PTR64_MASK = $0000ffffffffffff;
{$endif CPU64}
const
// flags for object properties
JS_PROP_CONFIGURABLE = 1 shl 0;
JS_PROP_WRITABLE = 1 shl 1;
JS_PROP_ENUMERABLE = 1 shl 2;
JS_PROP_C_W_E = JS_PROP_CONFIGURABLE or
JS_PROP_WRITABLE or
JS_PROP_ENUMERABLE;
JS_PROP_LENGTH = 1 shl 3; // used internally in Arrays
JS_PROP_TMASK = 3 shl 4; // mask for NORMAL, GETSET, VARREF, AUTOINIT
JS_PROP_NORMAL = 0 shl 4;
JS_PROP_GETSET = 1 shl 4;
JS_PROP_VARREF = 2 shl 4; // internal use
JS_PROP_AUTOINIT = 3 shl 4; // internal use
// flags for JS_DefineProperty
JS_PROP_HAS_SHIFT = 1 shl 3;
JS_PROP_HAS_CONFIGURABLE = 1 shl 8;
JS_PROP_HAS_WRITABLE = 1 shl 9;
JS_PROP_HAS_ENUMERABLE = 1 shl 10;
JS_PROP_HAS_GET = 1 shl 11;
JS_PROP_HAS_SET = 1 shl 12;
JS_PROP_HAS_VALUE = 1 shl 13;
// throw an exception if false would be returned JS_DefineProperty/JS_SetProperty
JS_PROP_THROW = 1 shl 14;
// throw an exception if false would be returned in strict mode JS_SetProperty
JS_PROP_THROW_STRICT = 1 shl 15;
JS_PROP_NO_ADD = 1 shl 16; // internal use
JS_PROP_NO_EXOTIC = 1 shl 17; // internal use
JS_DEFAULT_STACK_SIZE = 256 * 1024;
// JS_Eval flags
JS_EVAL_TYPE_GLOBAL = 0 shl 0; // global code default
JS_EVAL_TYPE_MODULE = 1 shl 0; // module code
JS_EVAL_TYPE_DIRECT = 2 shl 0; // direct call internal use
JS_EVAL_TYPE_INDIRECT = 3 shl 0; // indirect call internal use
JS_EVAL_TYPE_MASK = 3 shl 0;
JS_EVAL_FLAG_STRICT = 1 shl 3; // force 'strict' mode
JS_EVAL_FLAG_STRIP = 1 shl 4; // force 'strip' mode
// compile but do not run. The result is an object with a
// JS_TAG_FUNCTION_BYTECODE or JS_TAG_MODULE tag. It can be executed
// with JS_EvalFunction.
JS_EVAL_FLAG_COMPILE_ONLY = 1 shl 5; // internal use
JS_EVAL_FLAG_MODULE_COMPILE_ONLY = JS_EVAL_TYPE_MODULE or
JS_EVAL_FLAG_COMPILE_ONLY;
// don't include the stack frames before this eval in the Error backtraces
JS_EVAL_FLAG_BACKTRACE_BARRIER = 1 shl 6;
// Object Writer/Reader currently only used to handle precompiled code
JS_WRITE_OBJ_BYTECODE = 1 shl 0; // allow function/module
JS_WRITE_OBJ_BSWAP = 1 shl 1; // byte swapped output
JS_READ_OBJ_BYTECODE = 1 shl 0; // allow function/module
JS_READ_OBJ_ROM_DATA = 1 shl 1; // avoid duplicating 'buf' data
// C property definition
JS_DEF_CFUNC = 0;
JS_DEF_CGETSET = 1;
JS_DEF_CGETSET_MAGIC = 2;
JS_DEF_PROP_STRING = 3;
JS_DEF_PROP_INT32 = 4;
JS_DEF_PROP_INT64 = 5;
JS_DEF_PROP_DOUBLE = 6;
JS_DEF_PROP_UNDEFINED = 7;
JS_DEF_OBJECT = 8;
JS_DEF_ALIAS = 9;
// C function definition
// JSCFunctionEnum
JS_CFUNC_generic = 0;
JS_CFUNC_generic_magic = 1;
JS_CFUNC_constructor = 2;
JS_CFUNC_constructor_magic = 3;
JS_CFUNC_constructor_or_func = 4;
JS_CFUNC_constructor_or_func_magic = 5;
JS_CFUNC_f_f = 6;
JS_CFUNC_f_f_f = 7;
JS_CFUNC_getter = 8;
JS_CFUNC_setter = 9;
JS_CFUNC_getter_magic = 10;
JS_CFUNC_setter_magic = 11;
JS_CFUNC_iterator_next = 12;
JS_GPN_STRING_MASK = 1 shl 0;
JS_GPN_SYMBOL_MASK = 1 shl 1;
JS_GPN_PRIVATE_MASK = 1 shl 2;
// only include the enumerable properties
JS_GPN_ENUM_ONLY = 1 shl 4;
// set theJSPropertyEnum.is_enumerable field
JS_GPN_SET_ENUM = 1 shl 5;
// C Call Flags
JS_CALL_FLAG_CONSTRUCTOR = 1 shl 0;
type
PJSContext = ^JSContext;
JSObject = pointer;
JSClass = pointer;
JSModuleDef = pointer;
JS_BOOL = LongBool;
JSString = ^pointer;
JSClassID = cardinal;
PJSClassID = ^JSClassID;
JSAtom = cardinal;
JSCFunctionEnum = integer;
JSGCObjectHeader = pointer;
JSValueConst = JSValueRaw;
PJSValueConst = ^JSValueConst;
JSValueConstArr = array[0..(MaxInt div SizeOf(JSValueConst)) - 1] of JSValueConst;
PJSValueConstArr = ^JSValueConstArr;
type
JSMallocState = record
malloc_count, malloc_size, malloc_limit: PtrUInt;
opaque: pointer;
end;
PJSMallocState = ^JSMallocState;
JSMallocFunctions = record
js_malloc: function(s: PJSMallocState; size: PtrUInt): pointer; cdecl;
js_free: procedure(s: PJSMallocState; Ptr: pointer); cdecl;
js_realloc: function(s: PJSMallocState; Ptr: pointer; size: PtrUInt): pointer; cdecl;
js_malloc_usable_size: function(Ptr: pointer): PtrUInt; cdecl;
end;
PJSMallocFunctions = ^JSMallocFunctions;
JSMemoryUsage = record
malloc_size,
malloc_limit,
memory_used_size,
malloc_count,
memory_used_count,
atom_count,
atom_size,
str_count,
str_size,
obj_count,
obj_size,
prop_count,
prop_size,
shape_count,
shape_size,
js_func_count,
js_func_size,
js_func_code_size,
js_func_pc2line_count,
js_func_pc2line_size,
c_func_count,
array_count,
fast_array_count,
fast_array_elements,
binary_object_count,
binary_object_size: Int64;
end;
PJSMemoryUsage = ^JSMemoryUsage;
JSCFunction = function(ctx: JSContext; this_val: JSValueConst; argc: integer;
argv: PJSValueConstArr): JSValueRaw; cdecl;
PJSCFunction = ^JSCFunction;
JSCFunctionMagic = function(ctx: JSContext; this_val: JSValueConst;
argc: integer; argv: PJSValueConst; magic: integer): JSValueRaw; cdecl;
PJSCFunctionMagic = ^JSCFunctionMagic;
JSCFunctionData = function(ctx: JSContext; this_val: JSValueConst;
argc: integer; argv: PJSValueConst; magic: integer;
func_data: PJSValueRaw): JSValueRaw; cdecl;
PJSCFunctionData = ^JSCFunctionData;
JS_MarkFunc = procedure(rt: JSRuntime; gp: JSGCObjectHeader); cdecl;
PJS_MarkFunc = ^JS_MarkFunc;
JSClassFinalizer = procedure(rt: JSRuntime; val: JSValueRaw); cdecl;
PJSClassFinalizer = ^JSClassFinalizer;
JSClassGCMark = procedure(rt: JSRuntime; val: JSValueConst;
mark_func: PJS_MarkFunc); cdecl;
PJSClassGCMark = ^JSClassGCMark;
JSClassCall = function(ctx: JSContext; func_obj: JSValueConst;
this_val: JSValueConst; argc: integer; argv: PJSValueConst;
flags: integer): JSValueRaw; cdecl;
PJSClassCall = ^JSClassCall;
JSFreeArrayBufferDataFunc = procedure(rt: JSRuntime;
opaque, Ptr: pointer); cdecl;
PJSFreeArrayBufferDataFunc = ^JSFreeArrayBufferDataFunc;
// return != 0 if the JS code needs to be interrupted
JSInterruptHandler = function(rt: JSRuntime; opaque: pointer): integer; cdecl;
PJSInterruptHandler = ^JSInterruptHandler;
// return the module specifier (allocated with js_malloc()) or nil if exception
JSModuleNormalizeFunc = function(ctx: JSContext; const module_base_name,
module_name: PAnsiChar; opaque: pointer): PAnsiChar; cdecl;
PJSModuleNormalizeFunc = ^JSModuleNormalizeFunc;
JSModuleLoaderFunc = function(ctx: JSContext; module_name: PAnsiChar;
opaque: pointer): JSModuleDef; cdecl;
PJSModuleLoaderFunc = ^JSModuleLoaderFunc;
// JS Job support
JSJobFunc = function(ctx: JSContext; argc: integer;
argv: PJSValueConst): JSValueRaw; cdecl;
PJSJobFunc = ^JSJobFunc;
// C module definition
JSModuleInitFunc = function(ctx: JSContext; m: JSModuleDef): integer; cdecl;
PJSModuleInitFunc = ^JSModuleInitFunc;
// Promises RejectionTracker CallBack
// is_handled = true means that the rejection is handled
JSHostPromiseRejectionTracker = procedure(ctx: JSContext;
promise, reason: JSValueConst; is_handled: JS_BOOL; opaque: pointer); cdecl;
PJSHostPromiseRejectionTracker = ^JSHostPromiseRejectionTracker;
// object class support
JSPropertyEnum = record
is_enumerable: JS_BOOL;
atom: JSAtom;
end;
PJSPropertyEnum = ^JSPropertyEnum;
PPJSPropertyEnum = ^PJSPropertyEnum;
JSPropertyDescriptor = record
flags: integer;
value, getter, setter: JSValueRaw;
end;
PJSPropertyDescriptor = ^JSPropertyDescriptor;
JSClassExoticMethods = record
// Return -1 if exception (can only happen in case of Proxy object),
// 0 if the property does not exists, true if it exists. If 1 is
// returned, the property descriptor 'desc' is filled if != nil.
get_own_property: function(ctx: JSContext; desc: PJSPropertyDescriptor;
obj: JSValueConst; prop: JSAtom): integer; cdecl;
// '*ptab' should hold the '*plen' property keys. Return 0 if OK,
// -1 if exception. The 'is_enumerable' field is ignored.
get_own_property_names: function(ctx: JSContext; ptab: PPJSPropertyEnum;
plen: PCardinal; obj: JSValueConst): integer; cdecl;
// return < 0 if exception, or true/false
delete_property: function(ctx: JSContext; obj: JSValueConst;
prop: JSAtom): integer; cdecl;
// return < 0 if exception or true/false
define_own_property: function(ctx: JSContext; this_obj: JSValueConst;
prop: JSAtom; val: JSValueConst; getter: JSValueConst;
setter: JSValueConst; flags: integer): integer; cdecl;
// The following methods can be emulated with the previous ones,
// so they are usually not needed
// return < 0 if exception or true/false
has_property: function(ctx: JSContext; obj: JSValueConst;
atom: JSAtom): integer; cdecl;
get_property: function(ctx: JSContext; obj: JSValueConst; atom: JSAtom;
receiver: JSValueConst): JSValueRaw; cdecl;
set_property: function(ctx: JSContext; obj: JSValueConst; atom: JSAtom;
value: JSValueConst; receiver: JSValueConst; flags: integer): integer; cdecl;
end;
PJSClassExoticMethods = ^JSClassExoticMethods;
JSClassDef = record
class_name: PAnsiChar;
finalizer: PJSClassFinalizer;
gc_mark: PJSClassGCMark;
// if call != nil, the object is a function.
// If (flags and JS_CALL_FLAG_CONSTRUCTOR) <> 0, the function is called as a
// constructor. In this case, 'this_val' is new.target. A
// constructor call only happens if the object constructor bit is
// set (see JS_SetConstructorBit())
call: PJSClassCall;
// XXX: suppress this indirection ? It is here only to save memory
// because only a few classes need these methods
exotic: PJSClassExoticMethods;
end;
PJSClassDef = ^JSClassDef;
// C function definition
constructor_magic_func = function(ctx: JSContext; new_target: JSValueConst;
argc: integer; argv: PJSValueConst; magic: integer): JSValueRaw; cdecl;
f_f_func = function(_para1: double): double cdecl;
f_f_f_func = function(_para1: double; _para2: double): double; cdecl;
Getter_func = function(ctx: JSContext; this_val: JSValueConst): JSValueRaw; cdecl;
Setter_func = function(ctx: JSContext; this_val: JSValueConst;
val: JSValueConst): JSValueRaw; cdecl;
getter_magic_func = function(ctx: JSContext; this_val: JSValueConst;
magic: integer): JSValueRaw; cdecl;
setter_magic_func = function(ctx: JSContext; this_val: JSValueConst;
val: JSValueConst; magic: integer): JSValueRaw; cdecl;
iterator_next_func = function(ctx: JSContext; this_val: JSValueConst;
argc: integer; argv: PJSValueConst; pdone: PInteger;
magic: integer): JSValueRaw; cdecl;
JSCFunctionType = record
case integer of
0: (generic: JSCFunction);
1: (generic_magic: JSCFunctionMagic);
2: (constructor_: JSCFunction);
3: (constructor_magic: constructor_magic_func);
4: (constructor_or_func: JSCFunction);
5: (f_f: f_f_func);
6: (f_f_f: f_f_f_func);
7: (getter: Getter_func);
8: (setter: Setter_func);
9: (getter_magic: getter_magic_func);
10: (setter_magic: setter_magic_func);
11: (iterator_next: iterator_next_func);
end;
PJSCFunctionType = ^JSCFunctionType;
// C property definition
PJSCFunctionListEntry = ^JSCFunctionListEntry;
JSCFunctionListEntry = record
name: PAnsiChar;
prop_flags: byte;
def_type: byte;
magic: SmallInt;
u: record
case integer of
0:
(func: record
length: byte; // XXX: should move outside union
cproto: byte; // XXX: should move outside union
cfunc: JSCFunctionType;
end);
1:
(getset: record
get: JSCFunctionType;
_set: JSCFunctionType;
end);
2:
(alias_: record
name: PAnsiChar;
base: integer;
end);
3:
(prop_list: record
tab: PJSCFunctionListEntry;
len: integer;
end);
4:
(str: PAnsiChar);
5:
(i32: integer);
6:
(i64: Int64);
7:
(f64: double);
end;
end;
{ ************ QuickJS Functions API }
{$ifdef LIBQUICKJSSTATIC}
{$define QUICKJSDEBUGGER}
{$undef QJSDLL}
{$else}
// Windows (and Delphi) doesn't support well gcc compiled binaries
{$define QJSDLL}
const
{$ifdef OSWINDOWS}
{$ifdef WIN64}
QJ = 'quickjs64.dll';
{$else}
QJ = 'quickjs32.dll';
{$endif WIN64}
{$else}
QJ = 'libquickjs.o';
{$endif OSWINDOWS}
{$endif LIBQUICKJSSTATIC}
function JS_NewRuntime: JSRuntime;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
// info must remain at least as long as rt
procedure JS_SetRuntimeInfo(rt: JSRuntime; const info: PAnsiChar);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_SetMemoryLimit(rt: JSRuntime; limit: PtrUInt);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_SetGCThreshold(rt: JSRuntime; gc_threshold: PtrUInt);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_SetMaxStackSize(ctx: JSContext; stack_size: PtrUInt);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_NewRuntime2(const mf: PJSMallocFunctions;
opaque: pointer): JSRuntime;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_FreeRuntime(rt: JSRuntime);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_GetRuntimeOpaque(rt: JSRuntime): pointer;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_SetRuntimeOpaque(rt: JSRuntime; opaque: pointer);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_MarkValue(rt: JSRuntime; val: JSValueConst;
mark_func: PJS_MarkFunc);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_RunGC(rt: JSRuntime);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_IsLiveObject(rt: JSRuntime; obj: JSValueConst): JS_BOOL;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
// {REMOVED} function JS_IsInGCSweep(rt: JSRuntime): JS_BOOL;
// cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_NewContext(rt: JSRuntime): JSContext;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_FreeContext(s: JSContext);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_DupContext(ctx: JSContext): JSContext;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_GetContextOpaque(ctx: JSContext): pointer;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_SetContextOpaque(ctx: JSContext; opaque: pointer);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_GetRuntime(ctx: JSContext): JSRuntime;
cdecl; external {$ifdef QJSDLL}QJ{$endif};
procedure JS_SetClassProto(ctx: JSContext; class_id: JSClassID; obj: JSValueRaw);
cdecl; external {$ifdef QJSDLL}QJ{$endif};
function JS_GetClassProto(ctx: JSContext; class_id: JSClassID): JSValueRaw;