-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathjs-runtime.el
2158 lines (1905 loc) · 77.7 KB
/
js-runtime.el
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
;;; js-runtime.el -- runtime support for ECMAScript interpreter
;; Author: Steve Yegge ([email protected])
;; Version: 2008.10.30
;; Keywords: javascript languages
;; This program is free software; you can redistribute it and/or
;; modify it under the terms of the GNU General Public License as
;; published by the Free Software Foundation; either version 2 of
;; the License, or (at your option) any later version.
;; This program is distributed in the hope that it will be
;; useful, but WITHOUT ANY WARRANTY; without even the implied
;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;; PURPOSE. See the GNU General Public License for more details.
;; You should have received a copy of the GNU General Public
;; License along with this program; if not, write to the Free
;; Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
;; MA 02111-1307 USA
;;; Commentary:
;;
;; This package implements the runtime support described by the
;; ECMA-262 specification, 3rd edition, available at this URL:
;; http://www.ecma-international.org/publications/standards/Ecma-262.htm
;; The parser and interpreter are in separate packages.
;;
;; This package has no features for Emacs users; it is a library for use
;; by Emacs-JavaScript applications such as `js-console'.
;;
;; Some of the algorithms are borrowed from SpiderMonkey and Rhino.
;;
;; Emacs Compatibility:
;;
;; This package only works in GNU Emacs >= 22, for various reasons
;; that include multibyte/utf-8/unicode support. I have no plans to
;; support older versions of Emacs.
;;
;; ECMA Extensions:
;;
;; This runtime library implements several features not in ECMA-262,
;; including some JavaScript 1.5/1.6 features and a few SpiderMonkey
;; extensions. The goal is to evolve towards 1.7 compatibility. I'm
;; not particularly worried about security (this is an editor, not a
;; web browser) so __defineProperty__ is always available.
;;
;; Extensions implemented:
;; - toSource() method
;; - get/set syntax for getters/setters in object initializers
;; - __defineGetter__, __defineSetter__
;; - __lookupGetter__, __lookupSetter__
;; - __proto__, __parent__
;; - __noSuchMethod__
;; - __defineProperty__ (SpiderMonkey)
;; - array indexing of strings, e.g. "foobar"[3] => 'b'
;; - Array: every, indexOf, filter, forEach, lastIndexOf, map, some
;;
;; Interpreters:
;;
;; You can fire up multiple JavaScript interpreters per Emacs session.
;; However, you can only have one intepreter per buffer, as the
;; interpreter uses buffer-local variables for storing the state of
;; the parser, interpreter, and runtime.
;;
;; Primitive Types:
;;
;; The JavaScript primitive types and values are mapped as follows:
;;
;; true -> t or 'true
;; false -> nil or 'false
;; null -> nil, 'null or "null".
;; undefined -> 'undefined or "undefined"
;; string -> primitive lisp string
;; number -> lisp floating-point value
;; NaN -> 0.0e+NaN
;; +Infinity -> 1.0e+INF
;; -Infinity -> -1.0e+INF
;;
;; Whenever possible, Lisp nil is used for false/null/undefined, and t
;; for true. The symbols 'null, 'false or 'undefined (or their string
;; representations) are generally only used for disambiguation.
;;
;; Numeric Representation:
;;
;; Emacs integers are 29-bit signed values; i.e., -2**28 to 2**28 - 1.
;; Emacs floating-point numbers are C doubles, hence 64 bits on most
;; machines these days. We can't achieve ECMA compliance with Emacs
;; integers, but we might do so with Emacs floats.
;;
;; AFAICT, the bitwise and shift operators all work with 32-bit ints
;; in SpiderMonkey/Rhino, and overflow or return nonsense when used
;; with integral values that require greater precision. The other
;; arithmetic operators all seem to operate with 64-bit precision.
;; Hence, if we represent Numbers and numeric values internally as
;; floats, and do range checks before bitwise/shift ops, we should see
;; reasonable results, possibly excepting overflow/underflow
;; scenarios, but I can live with that.
;;
;; NaN, +Infinity and -Infinity are represented internally by the
;; Emacs floating-point values 0.0e+NaN, 1.0e+INF and -1.0e+INF.
;; -1.0e+INF is not equal/eql/eq/= to either of the other two. Sadly,
;; 0.0e+NaN and 1.0e+INF are `equal', `eql', `=', and they format the
;; same when printed as strings. They are both not `eq' to themselves
;; or each other. Each is '>' than the other. In a nutshell, there
;; is no combination of equality predicates or other operators than
;; can distinguish the two values. The only way to distinguish them
;; that I am aware of is to use `format' with "%f" or "%g". I've made
;; utility functions to smooth over this as much as possible.
;;
;; Emacs does not distinguish +/- zero, so this implementation ignores
;; sections of Ecma-262 that deal specially with -0, always treating it
;; as +0 instead.
;;
;; Built-In Constructors:
;;
;; The built-in classes Object, Function, Array, String, Boolean, etc.
;; are represented as defstructs. Each has a table of internal
;; methods and properties (a "vtable" of type `js-Internal'). The
;; vtable and Ecma-262 [[Class]] property are stored as symbol props
;; on the cl-struct tags. The constructors are all initialized on
;; construction of a new interpreter.
;;; TODO:
;; - finish Number.prototype.toString (section 9.8.1)
;; - arguments.caller and exception stack traces
;; (http://examples.oreilly.com/jscript3/text/7-3.txt)
;; - SpiderMonkey unit-test suite
;; - JS regex engine (just port the Rhino code - easiest)
;; - debugger (and add `debugger' keyword)
;; - E4X
;; - Emacs host objects
;; - unicode identifiers (in SpiderMonkey but not Rhino)
;; - warn on identifiers that are future reserved words
;; - strict-mode
;;; BUGS:
;; - bitwise and shift operators fail for sufficiently large integers
;; - mismatched quotes in console, e.g. "foobar' => lisp eval error
;;; PERFORMANCE:
;; - cache MRU prop name/val in a new slot on js-Object
;;; Code:
(require 'js-parse)
(require 'help-fns) ; for setting length prop on native functions
(require 'js-util)
(defconst js-obj-plist-type 'hybrid
"Data structure to use for JS object property lists.
Currently supported types are `alist', `hybrid', and `splay'.
A value of `alist' always uses alists for any number of properties.
A value of `splay' uses a splay tree to hold an object's properties.
A value of `hybrid' uses an alist up to a certain size, then converts
to a hashtable for that object.")
(case js-obj-plist-type
(hybrid
(load "js-obj-hybrid"))
(alist
(load "js-obj-alist"))
(splay
(load "js-obj-splay"))
(t
(error "Unknown backing store type: %s" js-obj-plist-type)))
(eval-and-compile
(require 'cl)) ; need at runtime, e.g. for most-positive-float
(eval-when-compile
(defun js-exec (n) nil))
(defvar js-current-context nil
"Current buffer-local JavaScript Execution Context.
An execution context is associated with each buffer running a script.
Each time a new context is entered, we dynamically bind this variable
with `let', creating a context stack that unwinds with the lisp
execution stack.")
;(make-variable-buffer-local 'js-current-context)
;;; Number parsing
(defsubst js-radix-chars (radix)
"Return the list of valid chars for RADIX.
Returns the ascii char codes, including upper/lowercase."
(if (<= radix 10)
(loop for i from ?0 to (+ ?0 radix -1) collect i)
(append
(loop for i from ?0 to ?9 collect i)
(loop for i from ?a to (+ ?a (- radix 11)) collect i)
(loop for i from ?A to (+ ?A (- radix 11)) collect i))))
(defun js-parse-int (string &optional radix)
"JavaScript global parseInt function. ECMA 15.1.2.2.
Returns a lisp integer or integral float value."
;; NOTE: parseInt("Infinity") => NaN (rhino/squarefree)
(let ((s (js-to-string string))
(sign 1)
(i 0)
chars )
;; trim leading/trailing whitespace
(if (string-match "^\\s-+\\(.+?\\)\\s-*" s)
(setq s (match-string 1 s)))
;; strip +/- and set sign
(when (plusp (length s))
(if (eq (aref s 0) ?-)
(setq sign -1))
(if (memq (aref s 0) '(?- ?+))
(setq s (substring s 1))))
;; determine radix
(setq radix (if radix
(truncate (js-to-int32 radix))
10))
(cond
((string-match "^0[xX]" s)
(setq s (substring s 2))
(setq radix 16))
((string-match "^0." s)
(setq radix 8)))
;; trivial rejects
(if (or (string= s "")
(not (numberp radix))
(< radix 2)
(> radix 36))
0.0e+NaN
;; strip trailing bad chars
(setq chars (js-radix-chars radix))
(setq s (apply 'string (loop for c across s
until (not (memq c chars))
collect c)))
(cond
((string= s "")
0.0e+NaN)
;; js-parse-int-internal handles radixes <= 16, but Emacs
;; is likely to be faster and more accurate for large numbers.
((<= radix 16)
(condition-case nil
(string-to-number s) ; call emacs to parse it
(error 0.0e+NaN)))
(t
(js-parse-int-internal s radix sign))))))
(defun js-parse-int-internal (s radix sign)
"Parse int from S with RADIX and SIGN. S must be well-formed."
(let ((digit-max ?9)
(lcBound ?a)
(ucBound ?A)
(len (length s))
(end 0)
(sum 0.0))
(cond
((< radix 10)
(setq digit-max (+ ?0 radix -1)))
((> radix 10)
(setq lcBound (+ ?a radix -10))
(setq ucBound (+ ?A radix -10))))
(catch 'break
(loop with new-digit = 0
for c across s do
(cond
((and (<= ?0 c) (<= c digit-max))
(setq new-digit (- c ?0)))
((and (<= ?a c) (< c lcBound))
(setq new-digit (+ c (- ?a) 10)))
((and (<= ?A c) (< c ucBound))
(setq new-digit (+ c (- ?A) 10)))
(t
(throw 'break nil)))
(incf end)
(setq sum (+ (* sum radix) new-digit))))
;; Rhino has some special handling for rounding inaccuracies in
;; the basic algorithm when applied to very large numbers. I'll
;; punt on that for now.
(if (zerop end)
0.0e+NaN
sum)))
(defconst js-plus-minus-fp-regexp
(concat "^\\([+-]?" js-fp-regexp "\\)")
"Matches +/- floating-point numbers, but not integers.")
(defconst js-plus-minus-int-regexp
(concat "^\\([+-]?" js-int-regexp "\\)")
"Matches +/- JavaScript integers.")
(defun js-parse-float (val)
"Parse a string as a decimal literal. ECMA 15.1.2.3.
Currently limited by the capabilities of `string-to-number' and
other problems with Elisp's numeric precision."
(let ((s (js-to-string val)))
(if (string-match "^\\s-+\\(.+\\)" s) ; strip leading spaces
(setq s (match-string 1 s)))
(if (string-match js-plus-minus-fp-regexp s)
(string-to-number (match-string 1 s))
(if (string-match js-plus-minus-int-regexp s)
(js-parse-int (match-string 1 s))
0.0e+NaN))))
;;; js2-runtime proper starts here
(defsubst js-bool (expr)
"Convert a Lisp boolean expression to a JavaScript boolean value.
Turns non-nil to 'true and nil to 'false"
(if expr 'true 'false))
(defsubst aref-safe (array idx)
"Return element of ARRAY at index IDX.
Returns nil if IDX is out of bounds, so be careful to use it only
when you know there are no nils in ARRAY. IDX starts at zero."
(if (or (minusp idx) (>= idx (length array)))
nil
(aref array idx)))
(defsubst js-primitive-p (value)
(or (memq value '(undefined null true false))
(stringp value)
(symbolp value) ; e.g. property names
(numberp value)))
(defsubst js-null-p (val)
"Return t if VAL is nil or JavaScript null or undefined."
(or (null val)
(member val '(undefined null))))
(defsubst js-boolean-p (val)
"Return t if VAL is a primitive boolean or a Boolean object."
(or (memq val '(t true false))
(js-Boolean-p val)))
(defsubst js-number-p (val)
"Return t if VAL is a primitive number or a Number object."
(or (numberp val) ; includes 1.0e+INF 0.0e+NaN -1.0e+INF
(js-Number-p val)))
(defsubst js-string-p (val)
"Return t if VAL is a primitive string or a String object."
(or (stringp val)
(js-String-p val)))
;;; Structs for each of the native object types.
;;
;; These structs hold per-instance data for JavaScript objects.
;; They exist primarily to yield fast access for frequently-accessed
;; internal properties such as an object's prototype or parent scope.
;;
;; These are -not- the same as the built-in type constructors.
;; For example, "Object", a built-in native constructor for objects
;; of type Object, is actually a js-Function, because it's callable
;; (and newable.) The built-in type constructors typically create
;; an instance of the corresponding struct when invoked with "new".
(defstruct js-Object
"JavaScript Object object instance"
proto ; prototype link
scope ; parent scope
props) ; property list
(defstruct (js-Function (:include js-Object))
"JavaScript Function object instance"
call-slot ; if nil, defaults to the vtable version
construct-slot ; ditto
builtin-p ; t for built-in function objects (no AST, etc.)
node) ; AST node with params and body
(defstruct (js-Array (:include js-Object))
"JavaScript Array object instance")
(defstruct (js-String (:include js-Object))
"JavaScript String object instance"
value) ; the lisp string object
(defstruct (js-Boolean (:include js-Object))
"JavaScript Boolean object instance"
value)
(defstruct (js-Number (:include js-Object))
"JavaScript Number object instance"
value)
(defstruct (js-Math (:include js-Object))
"JavaScript Math object")
(defstruct (js-Date (:include js-Object))
"JavaScript Date object instance"
value) ; time in millis since Epoch
(defstruct (js-RegExp (:include js-Function))
"JavaScript RegExp object instance"
pattern ; regexp source
flags ; regexp flags (bit field)
compiled ; jsre-compiled-re (byte-compiled regexp)
elisp) ; elisp translation of the pattern string
(defstruct (js-Error (:include js-Object))
"JavaScript Error instance"
(name "Error"))
(defstruct (js-EvalError
(:include js-Error (name "EvalError" :read-only t)))
"ECMA-262 15.11.6.1")
(defstruct (js-RangeError
(:include js-Error (name "RangeError" :read-only t)))
"ECMA-262 15.11.6.2")
(defstruct (js-ReferenceError
(:include js-Error (name "ReferenceError" :read-only t)))
"ECMA-262 15.11.6.3")
(defstruct (js-SyntaxError
(:include js-Error (name "SyntaxError" :read-only t)))
"ECMA-262 15.11.6.4")
(defstruct (js-TypeError
(:include js-Error (name "TypeError" :read-only t)))
"ECMA-262 15.11.6.5")
(defstruct (js-URIError
(:include js-Error (name "URIError" :read-only t)))
"ECMA-262 15.11.6.6")
(put 'cl-struct-js-EvalError 'js-class 'Error)
(put 'cl-struct-js-RangeError 'js-class 'Error)
(put 'cl-struct-js-ReferenceError 'js-class 'Error)
(put 'cl-struct-js-SyntaxError 'js-class 'Error)
(put 'cl-struct-js-TypeError 'js-class 'Error)
(put 'cl-struct-js-URIError 'js-class 'Error)
;; `defstruct' gives us a unique tag per struct, which we'll use to
;; store class-related information for each Native and Host constructor.
(put 'cl-struct-js-Object 'js-class 'Object)
(put 'cl-struct-js-Function 'js-class 'Function)
(put 'cl-struct-js-Array 'js-class 'Array)
(put 'cl-struct-js-String 'js-class 'String)
(put 'cl-struct-js-Boolean 'js-class 'Boolean)
(put 'cl-struct-js-Number 'js-class 'Number)
(put 'cl-struct-js-Math 'js-class 'Math)
(put 'cl-struct-js-Date 'js-class 'Date)
(put 'cl-struct-js-RegExp 'js-class 'RegExp)
(put 'cl-struct-js-Error 'js-class 'Error)
(defstruct js-Internal
"A virtual method table for JavaScript internal methods.
The default values of the slots are the functions implementing
the corresponding internal methods for Object. Native and Host
objects provide their own js-Internal table as a property on the
constructor symbol called `js-vtable'."
(get 'js-default--get--) ; [[Get]]
(put 'js-default--put--) ; [[Put]]
(can-put 'js-default--can-put--) ; [[CanPut]]
(has-property 'js-default--has-property--) ; [[HasProperty]]
(delete 'js-default--delete--) ; [[Delete]]
(default-value 'js-default--default-value--) ; [[DefaultValue]]
(construct 'js-default--construct--) ; [[Construct]]
(call 'js-default--call--) ; [[Call]]
(has-instance 'js-default--has-instance--)) ; [[HasInstance]]
;; Most of the built-in types don't override the standard internal
;; properties and methods.
(let ((shared-vtable (make-js-Internal)))
(dolist (sym '(String Boolean Number Math Date RegExp
Error EvalError RangeError ReferenceError
SyntaxError TypeError URIError))
(put (intern (concat "cl-struct-js-"
(symbol-name sym)))
'js-vtable
shared-vtable)))
(defstruct js-Context
"A JavaScript execution context."
type
this
caller
callee
arguments
scope
(result 'undefined)
target)
(defun js-init-scope (obj &optional scope)
(setf (js-Object-scope obj)
(or scope
(if js-current-context
(js-Context-scope js-current-context)
(error "No execution context")))))
(defsubst js-init-proto (obj &optional proto)
(setf (js-Object-proto obj)
(or proto (js-get-Object-prototype
(js-Object-scope obj)))))
(defun js-make-object (&optional scope proto)
"Create a new JavaScript native Object.
SCOPE is the parent scope for this object, and must be a valid
JavaScript Object. If omitted, it is set to the Global object from
the current execution context, which is the buffer-local value of
`js-current-context'. If there is no current context, an error will
be signaled.
PROTO is the Prototype of this object. If omitted, it will
default to Object.prototype, which is found by traversing the
scope chain from SCOPE to the root Global object."
(let ((obj (make-js-Object)))
(js-init-scope obj scope)
(js-init-proto obj proto)
obj))
(defalias 'js-object-p 'js-Object-p
"Return t if OBJ appears to be a valid JavaScript native Object.
Return nil if OBJ is a JavaScript primitive or any other lisp type.")
(defalias 'js-prototype 'js-Object-proto
"Return the prototype for OBJ. Returns nil if the prototype is null.")
(defsubst js-class (obj)
"Return the [[Class]] internal property of OBJ."
;; Stored on the cl-struct-js-Foo tag of the vector, for now.
;; Wanted a place to put it that was per-class, not per-instance.
(get (aref obj 0) 'js-class))
(defsubst js-vtable (obj)
"Return the table of internal method pointers for OBJ."
(get (aref obj 0) 'js-vtable))
(defun js-printobj (obj)
"Debugging function - print JavaScript object OBJ.
Return value is a string representation of OBJ suitable for
display in a JavaScript debugging console."
(let ((s
(cond
;; don't want dependency on js-exec, but need js-reference-p:
((and (vectorp obj)
(eq (aref obj 0) 'js-ref-tag))
;; An internal reference is [js-ref-tag BASE NAME NODE].
;; BASE is often the global object. Would be nice to have
;; smarter printing of the BASE object.
(format "%s" (aref obj 2)))
(t
(js-to-source obj)))))
(if (string= s "[object Unknown]")
(setq s (format "%s" obj)))
(if (> (length s) 80)
(concat (substring s 0 77) "...")
s)))
;;; ECMA 8.6.2 -- default implementations of Internal methods.
(defsubst js-call-internal (method obj &rest args)
"Call an internal method on OBJ, passing ARGS.
METHOD must be a valid slot accessor for `js-Internals' structs.
OBJ must be a `js-Object', and ARGS are the arguments to the method."
;; Functions can have `call' or `construct' instance slots that
;; override their vtable entry.
(cond
((and (eq method 'js-Internal-call)
(js-Function-p obj)
(js-Function-call-slot obj))
(funcall (js-Function-call-slot obj) obj args))
((and (eq method 'js-Internal-construct)
(js-Function-p obj)
(js-Function-construct-slot obj))
(funcall (js-Function-construct-slot obj) obj args))
(t
(apply (funcall method (js-vtable obj)) obj args))))
(defsubst js-get (obj name)
"Utility for calling the [[Get]] method on OBJ for property NAME.
NAME can be any object, and will be converted to a string by the
actual method definition. Returns 'undefined if NAME is not found
on OBJ or its prototype chain."
(cond
((js-null-p obj)
'undefined)
;; The __proto__ and __parent__ virtual properties can't go through
;; the normal lookup chain. Rhino handles them by creating a subclass
;; of Ref called SpecialRef, created in the IRFactory when the parser
;; determines that the name is "__proto__" or "__parent__". This is
;; probably a good long-term solution for us, but since elisp has no
;; virtual methods or polymorphic dispatch, we'll have to build our
;; own for references. For now, we just detect special names here
;; and in js-put.
((equal name "__proto__")
(js-Object-proto obj))
((equal name "__parent__")
(js-Object-scope obj))
(t
(js-call-internal 'js-Internal-get obj name))))
;; `js-default--get--' recursively traverses up the prototype chain.
;; If it finds a getter, it calls it. Unfortunately, we need to call
;; the getter on the original object, not the current object. Example:
;; var x = {}; x.__proto__ => walks up to Object.prototype, finds the
;; getter for __proto__. If it calls it on Object.prototype, it returns
;; null, since Object.prototype has no prototype. Need to call on x!
;; Rhino handles this by requiring a 'start' parameter to get() as part
;; of the public API, which is pretty confusing. Even Norris couldn't
;; remember why it was there. A better solution is to tuck the start
;; object away in a thread-local (or in Emacs' case, buffer-local)
;; variable and check it on each recursion step. This is that variable:
(defvar js-get-base-obj nil)
;(make-variable-buffer-local 'js-get-base-obj)
(defun js-default--get-- (obj name)
"Lisp-level [[Get]] implementation for Object, 8.6.2.1.
OBJ must be a js-Object, and NAME must be a lisp string or lisp symbol.
Returns the value of the property named NAME, searching the prototype
chain. If not found, returns the symbol `undefined'."
(let ((cell (js-get-prop-cell obj name))
(js-get-base-obj (or js-get-base-obj obj))
getter result)
(cond
((null cell)
;; recurse up prototype chain to look for result
(setq result (js-get (js-prototype obj) name))
(if (neq result 'undefined)
result
;; Rhino seems to permit calling certain Object builtins even
;; if the target object's __proto__ link is null. For these
;; we'll fetch the value from Object.prototype.
(if (and (null (js-Object-proto obj))
(member name '("toSource" "toString"
"__lookupGetter__"
"__lookupSetter__"
"__defineGetter__"
"__defineSetter__"
"__defineProperty__"))) ; others?
(js-global-get name)
'undefined)))
((js-getter-setter-p cell)
(if (setq getter (caar cell))
(js-Function-call getter js-get-base-obj nil)
'undefined))
(t
(first cell)))))
(defsubst js-can-put (obj name)
"Utility for calling the [[CanPut]] method on OBJ, a js-Object.
NAME can be any object, and will be converted to a string by the
actual method implementation, e.g. `js-Object--can-put--'."
(if (js-null-p obj)
nil
(js-call-internal 'js-Internal-can-put obj name)))
(defun js-default--can-put-- (obj name)
"Lisp-level implementation of [[CanPut]] for Object, 8.6.2.2.
OBJ must be a js-Object, and NAME must be a lisp string or symbol.
Return t if a `js-put' of NAME on OBJ will succeed, else nil.
Note that this method returns Lisp t/nil, not JavaScript true/false.
Host and Native objects that override it should do the same."
(let ((cell (js-get-prop-cell obj name))
proto)
(if cell
(not (js-prop-read-only-p cell))
(setq proto (js-prototype obj))
(if (null proto)
t ; no read-only version in prototype chain => t
(js-can-put proto name)))))
(defsubst js-put (obj name value)
"Utility for calling the [[Put]] method on OBJ.
NAME can be any object, and will be converted to a string by the
actual method implementation, e.g. `js-Object--put--'. VALUE must be
a valid JavaScript value to associate with NAME in OBJ."
(cond
((js-null-p obj)
(js-type-error (js-format "%s has no properties" obj)))
;; See comments about __proto__/__parent__ in `js-put'.
((equal name "__proto__")
(js-Object-setProto obj value))
((equal name "__parent__")
(js-Object-setParent obj value))
(t
(js-call-internal 'js-Internal-put obj name value))))
(defun js-default--put-- (obj name value)
"Lisp-level [[Put]] implementation for Object, 8.6.2.2.
Tries to set local property NAME to value VALUE on object OBJ.
If OBJ has a setter function for NAME, the setter is invoked with
VALUE. If OBJ has a getter for NAME but no setter, an error is
signaled. Otherwise, the property is set in the object's property
list.
Excepting setter invocations, the property always goes into the
local plist for OBJ, even if NAME is defined somewhere up the
prototype chain. Has no effect if the property is declared
read-only, including up the prototype chain. NAME must be a
symbol or string."
(let ((setter (js-Object-lookupSetter obj (list name))))
(if setter
(js-Function-call setter obj (list value))
(if (js-can-put obj name)
(js-define obj name value 'keep-flags)))))
(defsubst js-has-property (obj name)
"Utility for calling the [[HasProperty]] method on OBJ.
NAME can be any object, and will be converted to a string by the
actual method implementation, e.g. `js-default--has-property--'.
This method returns Lisp t/nil rather than JavaScript true/false."
(if (js-null-p obj)
nil
(js-call-internal 'js-Internal-has-property obj name)))
(defun js-default--has-property-- (obj name)
"Lisp-level [[HasProperty]] implementation for Object, 8.6.2.4.
If OBJ or its prototype chain has property named NAME, return t,
Otherwise return nil. OBJ must be a js-Object, and NAME must be a
lisp string or symbol."
;; As long as the object has an entry for that property, even if the
;; value is undefined, the object is considered to have the property.
(if (js-get-prop-cell obj name)
t
(js-has-property (js-prototype obj) name)))
(defsubst js-delete (obj name)
"Utility to call [[Delete]] method for OBJ.
If NAME is deleted (or not found), returns the symbol `true',
else returns the symbol `false'. Native and Host objects that
override this method should also return JavaScript true/false values."
(if (js-null-p obj)
'false
(js-call-internal 'js-Internal-delete obj name)))
(defun js-default--delete-- (obj name)
"Lisp-level [[Delete]] implementation for Object, 8.6.2.5.
OBJ must be a js-Object, and NAME must be a lisp string or symbol.
This method tries to delete the property named NAME from OBJ.
Note that the [[Delete]] method does not search the prototype chain.
If the property has the `permanent' flag set, or OBJ has no property
named NAME, returns 'false. Otherwise deletes it and returns 'true."
(js-prop-delete obj name))
(defsubst js-default-value (obj &optional hint)
"Utility for calling the [[DefaultValue]] method on OBJ.
Always returns a JavaScript primitive value, or throws a TypeError.
HINT is a symbol such as 'String or 'Number."
(if (null obj)
(error "nil is not a JavaScript object") ; coding error
(js-call-internal 'js-Internal-default-value obj hint)))
(defun js-default--default-value-- (obj &optional hint)
"Lisp-level implementation of [[DefaultValue]] on Object, 8.6.2.6.
Always returns a primitive value for the object. Host objects that
implement their own default-value method must also return primitives.
If provided, hint must be the symbol 'String or 'Number."
(if (null hint)
(setq hint (if (js-Date-p obj)
'String
'Number)))
(let ((method1 (if (eq hint 'Number) "valueOf" "toString"))
(method2 (if (eq hint 'Number) "toString" "valueOf"))
val)
(loop for m in (list method1 method2)
for fun = (js-get obj m)
if (and (js-Function-p fun)
(js-primitive-p
(setq val (js-Function-call fun obj nil))))
return val
finally do
(js-type-error
(js-format "No default value for %s, hint %s" obj hint)))))
(defun js-default--construct-- (ctor args)
"Lisp-level implementation of [[Call]] for non-Function objects."
(js-type-error (js-format "%s is not a constructor" ctor)))
(defun js-default--call-- (obj args)
"Lisp-level implementation of [[Call]] for non-Function objects."
(js-type-error (js-format "%s is not a function" obj)))
(defun js-default--has-instance-- (obj value)
"Lisp-level implementation of [[HasInstance]] on Object, 11.8.6.
Always throws a TypeError. This method is overridden by js-Function."
(js-type-error
(js-format "%s is not a valid 'instanceof' operand" obj)))
(defsubst js-instanceof (obj ctor)
"Return t if CTOR [[HasInstance]] OBJ, else nil. ECMA 11.8.6."
(if (js-object-p ctor)
(js-call-internal 'js-Internal-has-instance ctor obj)
(js-type-error
(js-format "invalid 'instanceof' operand: %s" ctor))))
(defsubst js-in (val obj)
"Return 'true if VAL is in OBJ, else 'false. ECMA 11.8.7."
(unless (js-object-p obj)
(js-type-error
(js-format "invalid 'in' operand: %s" obj)))
(js-bool (js-has-property obj (js-to-string val))))
(defun js-property-is-enumerable (obj v)
"Return t if OBJ has a local enumerable property named V, else nil.
This method does not consider objects in the prototype chain."
(if (or (null obj) (null v))
nil
(let ((cell (js-get-prop-cell obj (js-to-string v))))
(if (null cell)
nil
(not (js-prop-dont-enum-p cell))))))
;;; 9 -- Type Conversion (plus a few type predicates)
(defconst js-NaN-string (format "%f" 0.0e+NaN))
(defconst js-pos-INF-string (format "%f" 1.0e+INF))
(defconst js-neg-INF-string (format "%f" -1.0e+INF))
(defconst js-nonbroken-NaN-p (eql 0.0e+NaN 0.0e+NaN)
"Some C libraries don't let NaN compare `eql' to itself.")
(defun js-NaN-p (val)
"Return t if VAL is the Number/number NaN (but not +/- Infinity).
VAL can be any lisp object."
(if (js-Number-p val)
(setq val (js-Number-value val)))
(if js-nonbroken-NaN-p
(eql val 0.0e+NaN)
(and (eql val 1.0e+INF) ; fast reject for all but NaN/Infinity
(string= (format "%f" val) ; distinguish from 1.0e+INF
js-NaN-string))))
(defun js-infinity-p (val)
"Return t if VAL is the Number/number Infinity (not -Infinity/NaN).
VAL can be any lisp object."
(if (js-Number-p val)
(setq val (js-Number-value val)))
(if js-nonbroken-NaN-p
(eql val 1.0e+INF)
(and (eql val 1.0e+INF) ; fast reject for all but NaN/Infinity
(string= (format "%f" val) ; distinguish from 0.0e+NaN
js-pos-INF-string))))
(defun js-minus-infinity-p (val)
"Return t if VAL is the Number/number -Infinity (not Infinity/NaN).
VAL can be any lisp object."
(if (js-Number-p val)
(setq val (js-Number-value val)))
(if js-nonbroken-NaN-p
(eql val -1.0e+INF)
(and (eql -1.0e+INF val)
(string= (format "%f" val) js-neg-INF-string))))
(defun js-infinite-p (val)
"Return t if VAL is the Number/number +/-Infinity (but not NaN).
VAL can be any lisp object."
(if (js-Number-p val)
(setq val (js-Number-value val)))
(and (or (eql val -1.0e+INF)
(eql val 1.0e+INF)) ; fast reject for most values
(or js-nonbroken-NaN-p
(not (string= (format "%f" val)
js-NaN-string)))))
(defun js-finite-p (val)
"Return t if VAL is a finite Number/number (not +/-Infinity/NaN).
VAL can be any lisp object."
(if (js-Number-p val)
(setq val (js-Number-value val)))
(and (numberp val)
(not (member val '(1.0e+INF -1.0e+INF 0.0e+NaN)))))
(defun js-Nanfinity-p (val)
"Return t if VAL is the Number/number NaN or +/- Infinity.
VAL can be any lisp object."
(and (numberp val)
(not (js-finite-p val))))
(defun js-integer-p (val)
"Return t if VAL is an integral Number or primitive number.
VAL can be any lisp object. Returns nil for Nan or +/-Infinity."
(if (js-Number-p val)
(setq val (js-Number-value val)))
(or (integerp val)
(and (floatp val)
(not (js-Nanfinity-p val)) ; or `ffloor' will barf
(= val (ffloor val)))))
(defun js-typeof (val)
"Implementation of the typeof operator. ECMA 11.4.3.
Returns a string representing the type of VAL."
(cond
((memq val '(undefined nil))
"undefined")
((eq val 'null)
"object")
((js-Function-p val)
"function")
((js-object-p val)
"object")
((js-boolean-p val)
"boolean")
((js-number-p val)
"number")
((js-string-p val)
"string")
(t
;; implementation-dependent, needs EmacsConnect spec
(format "[Elisp: %s]" val))))
(defsubst js-to-primitive (value &optional preferred-type)
"Operator to convert VALUE (an Object) to a non-Object type.
If an object is capable of converting to more than one primitive type,
it may use the optional PREFERRED-TYPE to favor that type."
(if (js-primitive-p value)
value
(js-default-value value preferred-type)))
(defun js-to-boolean (val)
"The ToBoolean operator (9.2) converts VAL to type Boolean.
Returns either 'true or 'false."
(cond
((memq val '(nil undefined null false))
'false)
((memq val '(t true)) 'true)
((js-Boolean-p val)
(js-bool (js-Boolean-value val)))
((numberp val)
(if (js-Number-p val)
(setq val (js-Number-value val)))
(js-bool (not (or (zerop val)
(js-NaN-p val)))))
((stringp val)
(if (js-String-p val)
(setq val (js-String-value val)))
(js-bool (not (zerop (length val)))))
((js-object-p val)
'true)
(t
'true))) ; punt on host objects and native elisp thingies
(defsubst js-not (val)
"Convert 'true to 'false and vice-versa."
(if (eq val 'true)
'false
'true))
(defsubst js-test (val)
"Convert a JavaScript boolean value to a Lisp boolean value.
Returns t if `js-to-boolean' of VAL is true, else nil."
(eq 'true (js-to-primitive (js-to-boolean val))))
(defsubst js-and (x y)
"Return 'true or 'false based on converting X and Y to boolean"
(let ((a (js-to-primitive (js-to-boolean x)))
(b (js-to-primitive (js-to-boolean y))))
(js-bool (and (eq a 'true) (eq b 'true)))))
(defsubst js-or (x y)
"Return 'true or 'false based on converting X and Y to boolean"
(let ((a (js-to-primitive (js-to-boolean x)))
(b (js-to-primitive (js-to-boolean y))))
(js-bool (or (eq a 'true) (eq b 'true)))))
(defsubst js-xor (x y)
"Return 'true or 'false based on converting X and Y to boolean"
(let ((a (js-to-primitive (js-to-boolean x)))
(b (js-to-primitive (js-to-boolean y))))
(js-bool (neq a b))))
(defun js-format-number (num)
"Format NUM, a primitive number, for script output.
Returns a string that represents the number in JavaScript. For
instance, turns integral floats into ints, and Lisp NaN/infinity
representations into NaN and Infinity."
(cond
((js-Number-p num)
(js-format-number (js-Number-value num)))
((not (numberp num))
"NaN")
((js-NaN-p num)
"NaN")
((js-infinity-p num)
"Infinity")
((js-minus-infinity-p num)
"-Infinity")
((js-integer-p num)
(let ((s (number-to-string num)))
(if (string-match "\\(.+\\)\\.0+" s)
(match-string 1 s)
s)))
(t
(number-to-string num))))
(defun js-parse-number (val)
"Return VAL parsed as a Number. VAL is a lisp string.
Follows the rules in 9.3.1 of Ecma-262. Returns a primitive
number value."
;; Uses Lisp parsing and some heuristics. Needs work.
(cond
((string= val "NaN")
0.0e+NaN)
((string= val "Infinity")