forked from mooz/js2-mode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
js2-mode.el
12883 lines (11556 loc) · 498 KB
/
js2-mode.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
;;; js2-mode.el --- Improved JavaScript editing mode
;; Copyright (C) 2009, 2011-2017 Free Software Foundation, Inc.
;; Author: Steve Yegge <[email protected]>
;; mooz <[email protected]>
;; Dmitry Gutov <[email protected]>
;; URL: https://github.com/mooz/js2-mode/
;; http://code.google.com/p/js2-mode/
;; Version: 20170116
;; Keywords: languages, javascript
;; Package-Requires: ((emacs "24.1") (cl-lib "0.5"))
;; This file is part of GNU Emacs.
;; GNU Emacs 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 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs 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 GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; This JavaScript editing mode supports:
;; - strict recognition of the Ecma-262 language standard
;; - support for most Rhino and SpiderMonkey extensions from 1.5 and up
;; - parsing support for ECMAScript for XML (E4X, ECMA-357)
;; - accurate syntax highlighting using a recursive-descent parser
;; - on-the-fly reporting of syntax errors and strict-mode warnings
;; - undeclared-variable warnings using a configurable externs framework
;; - "bouncing" line indentation to choose among alternate indentation points
;; - smart line-wrapping within comments and strings
;; - code folding:
;; - show some or all function bodies as {...}
;; - show some or all block comments as /*...*/
;; - context-sensitive menu bar and popup menus
;; - code browsing using the `imenu' package
;; - many customization options
;; Installation:
;;
;; To install it as your major mode for JavaScript editing:
;; (add-to-list 'auto-mode-alist '("\\.js\\'" . js2-mode))
;; Alternatively, to install it as a minor mode just for JavaScript linting,
;; you must add it to the appropriate major-mode hook. Normally this would be:
;; (add-hook 'js-mode-hook 'js2-minor-mode)
;; You may also want to hook it in for shell scripts running via node.js:
;; (add-to-list 'interpreter-mode-alist '("node" . js2-mode))
;; Support for JSX is available via the derived mode `js2-jsx-mode'. If you
;; also want JSX support, use that mode instead:
;; (add-to-list 'auto-mode-alist '("\\.jsx?\\'" . js2-jsx-mode))
;; (add-to-list 'interpreter-mode-alist '("node" . js2-jsx-mode))
;; To customize how it works:
;; M-x customize-group RET js2-mode RET
;; Notes:
;; This mode includes a port of Mozilla Rhino's scanner, parser and
;; symbol table. Ideally it should stay in sync with Rhino, keeping
;; `js2-mode' current as the EcmaScript language standard evolves.
;; Unlike cc-engine based language modes, js2-mode's line-indentation is not
;; customizable. It is a surprising amount of work to support customizable
;; indentation. The current compromise is that the tab key lets you cycle among
;; various likely indentation points, similar to the behavior of python-mode.
;; This mode does not yet work with "multi-mode" modes such as `mmm-mode'
;; and `mumamo', although it could be made to do so with some effort.
;; This means that `js2-mode' is currently only useful for editing JavaScript
;; files, and not for editing JavaScript within <script> tags or templates.
;; The project page on GitHub is used for development and issue tracking.
;; The original homepage at Google Code has outdated information and is mostly
;; unmaintained.
;;; Code:
(require 'cl-lib)
(require 'imenu)
(require 'js)
(require 'etags)
(eval-and-compile
(if (version< emacs-version "25.0")
(require 'js2-old-indent)
(defvaralias 'js2-basic-offset 'js-indent-level nil)
(defalias 'js2-proper-indentation 'js--proper-indentation)
(defalias 'js2-jsx-indent-line 'js-jsx-indent-line)
(defalias 'js2-indent-line 'js-indent-line)
(defalias 'js2-re-search-forward 'js--re-search-forward)))
;;; Externs (variables presumed to be defined by the host system)
(defvar js2-ecma-262-externs
(mapcar 'symbol-name
'(Array Boolean Date Error EvalError Function Infinity JSON
Math NaN Number Object RangeError ReferenceError RegExp
String SyntaxError TypeError URIError
decodeURI decodeURIComponent encodeURI
encodeURIComponent escape eval isFinite isNaN
parseFloat parseInt undefined unescape))
"Ecma-262 externs. Never highlighted as undeclared variables.")
(defvar js2-browser-externs
(mapcar 'symbol-name
'(;; DOM level 1
Attr CDATASection CharacterData Comment DOMException
DOMImplementation Document DocumentFragment
DocumentType Element Entity EntityReference
ExceptionCode NamedNodeMap Node NodeList Notation
ProcessingInstruction Text
;; DOM level 2
HTMLAnchorElement HTMLAppletElement HTMLAreaElement
HTMLBRElement HTMLBaseElement HTMLBaseFontElement
HTMLBodyElement HTMLButtonElement HTMLCollection
HTMLDListElement HTMLDirectoryElement HTMLDivElement
HTMLDocument HTMLElement HTMLFieldSetElement
HTMLFontElement HTMLFormElement HTMLFrameElement
HTMLFrameSetElement HTMLHRElement HTMLHeadElement
HTMLHeadingElement HTMLHtmlElement HTMLIFrameElement
HTMLImageElement HTMLInputElement HTMLIsIndexElement
HTMLLIElement HTMLLabelElement HTMLLegendElement
HTMLLinkElement HTMLMapElement HTMLMenuElement
HTMLMetaElement HTMLModElement HTMLOListElement
HTMLObjectElement HTMLOptGroupElement
HTMLOptionElement HTMLOptionsCollection
HTMLParagraphElement HTMLParamElement HTMLPreElement
HTMLQuoteElement HTMLScriptElement HTMLSelectElement
HTMLStyleElement HTMLTableCaptionElement
HTMLTableCellElement HTMLTableColElement
HTMLTableElement HTMLTableRowElement
HTMLTableSectionElement HTMLTextAreaElement
HTMLTitleElement HTMLUListElement
;; DOM level 3
DOMConfiguration DOMError DOMException
DOMImplementationList DOMImplementationSource
DOMLocator DOMStringList NameList TypeInfo
UserDataHandler
;; Window
window alert confirm document java navigator prompt screen
self top requestAnimationFrame cancelAnimationFrame
;; W3C CSS
CSSCharsetRule CSSFontFace CSSFontFaceRule
CSSImportRule CSSMediaRule CSSPageRule
CSSPrimitiveValue CSSProperties CSSRule CSSRuleList
CSSStyleDeclaration CSSStyleRule CSSStyleSheet
CSSValue CSSValueList Counter DOMImplementationCSS
DocumentCSS DocumentStyle ElementCSSInlineStyle
LinkStyle MediaList RGBColor Rect StyleSheet
StyleSheetList ViewCSS
;; W3C Event
EventListener EventTarget Event DocumentEvent UIEvent
MouseEvent MutationEvent KeyboardEvent
;; W3C Range
DocumentRange Range RangeException
;; W3C XML
XPathResult XMLHttpRequest
;; console object. Provided by at least Chrome and Firefox.
console))
"Browser externs.
You can cause these to be included or excluded with the custom
variable `js2-include-browser-externs'.")
(defvar js2-rhino-externs
(mapcar 'symbol-name
'(Packages importClass importPackage com org java
;; Global object (shell) externs.
defineClass deserialize doctest gc help load
loadClass print quit readFile readUrl runCommand seal
serialize spawn sync toint32 version))
"Mozilla Rhino externs.
Set `js2-include-rhino-externs' to t to include them.")
(defvar js2-node-externs
(mapcar 'symbol-name
'(__dirname __filename Buffer clearInterval clearTimeout require
console exports global module process setInterval setTimeout
querystring setImmediate clearImmediate))
"Node.js externs.
Set `js2-include-node-externs' to t to include them.")
(defvar js2-typed-array-externs
(mapcar 'symbol-name
'(ArrayBuffer Uint8ClampedArray DataView
Int8Array Uint8Array Int16Array Uint16Array Int32Array Uint32Array
Float32Array Float64Array))
"Khronos typed array externs. Available in most modern browsers and
in node.js >= 0.6. If `js2-include-node-externs' or `js2-include-browser-externs'
are enabled, these will also be included.")
(defvar js2-harmony-externs
(mapcar 'symbol-name
'(Map Promise Proxy Reflect Set Symbol WeakMap WeakSet))
"ES6 externs. If `js2-include-browser-externs' is enabled and
`js2-language-version' is sufficiently high, these will be included.")
;;; Variables
(defcustom js2-ignored-warnings nil
"A list of warning message types that will not be reported.
Possible values are the keys of `js2-message-table'."
:group 'js2-mode
:type '(repeat string))
(defcustom js2-highlight-level 2
"Amount of syntax highlighting to perform.
0 or a negative value means none.
1 adds basic syntax highlighting.
2 adds highlighting of some Ecma built-in properties.
3 adds highlighting of many Ecma built-in functions."
:group 'js2-mode
:type '(choice (const :tag "None" 0)
(const :tag "Basic" 1)
(const :tag "Include Properties" 2)
(const :tag "Include Functions" 3)))
(defvar js2-mode-dev-mode-p nil
"Non-nil if running in development mode. Normally nil.")
(defgroup js2-mode nil
"An improved JavaScript mode."
:group 'languages)
(defcustom js2-idle-timer-delay 0.2
"Delay in secs before re-parsing after user makes changes.
Multiplied by `js2-dynamic-idle-timer-adjust', which see."
:type 'number
:group 'js2-mode)
(make-variable-buffer-local 'js2-idle-timer-delay)
(defcustom js2-dynamic-idle-timer-adjust 0
"Positive to adjust `js2-idle-timer-delay' based on file size.
The idea is that for short files, parsing is faster so we can be
more responsive to user edits without interfering with editing.
The buffer length in characters (typically bytes) is divided by
this value and used to multiply `js2-idle-timer-delay' for the
buffer. For example, a 21k file and 10k adjust yields 21k/10k
== 2, so js2-idle-timer-delay is multiplied by 2.
If `js2-dynamic-idle-timer-adjust' is 0 or negative,
`js2-idle-timer-delay' is not dependent on the file size."
:type 'number
:group 'js2-mode)
(defcustom js2-concat-multiline-strings t
"When non-nil, `js2-line-break' in mid-string will make it a
string concatenation. When `eol', the '+' will be inserted at the
end of the line, otherwise, at the beginning of the next line."
:type '(choice (const t) (const eol) (const nil))
:group 'js2-mode)
(defcustom js2-mode-show-parse-errors t
"True to highlight parse errors."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-assume-strict nil
"Non-nil to start files in strict mode automatically."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-show-strict-warnings t
"Non-nil to emit Ecma strict-mode warnings.
Some of the warnings can be individually disabled by other flags,
even if this flag is non-nil."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-trailing-comma-warning t
"Non-nil to warn about trailing commas in array literals.
Ecma-262-5.1 allows them, but older versions of IE raise an error."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-missing-semi-warning t
"Non-nil to warn about semicolon auto-insertion after statement.
Technically this is legal per Ecma-262, but some style guides disallow
depending on it."
:type 'boolean
:group 'js2-mode)
(defcustom js2-missing-semi-one-line-override nil
"Non-nil to permit missing semicolons in one-line functions.
In one-liner functions such as `function identity(x) {return x}'
people often omit the semicolon for a cleaner look. If you are
such a person, you can suppress the missing-semicolon warning
by setting this variable to t."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-inconsistent-return-warning t
"Non-nil to warn about mixing returns with value-returns.
It's perfectly legal to have a `return' and a `return foo' in the
same function, but it's often an indicator of a bug, and it also
interferes with type inference (in systems that support it.)"
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-cond-assign-warning t
"Non-nil to warn about expressions like if (a = b).
This often should have been '==' instead of '='. If the warning
is enabled, you can suppress it on a per-expression basis by
parenthesizing the expression, e.g. if ((a = b)) ..."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-var-redeclaration-warning t
"Non-nil to warn about redeclaring variables in a script or function."
:type 'boolean
:group 'js2-mode)
(defcustom js2-strict-var-hides-function-arg-warning t
"Non-nil to warn about a var decl hiding a function argument."
:type 'boolean
:group 'js2-mode)
(defcustom js2-skip-preprocessor-directives nil
"Non-nil to treat lines beginning with # as comments.
Useful for viewing Mozilla JavaScript source code."
:type 'boolean
:group 'js2-mode)
(defcustom js2-language-version 200
"Configures what JavaScript language version to recognize.
Currently versions 150, 160, 170, 180 and 200 are supported,
corresponding to JavaScript 1.5, 1.6, 1.7, 1.8 and 2.0 (Harmony),
respectively. In a nutshell, 1.6 adds E4X support, 1.7 adds let,
yield, and Array comprehensions, and 1.8 adds function closures."
:type 'integer
:group 'js2-mode)
(defcustom js2-instanceof-has-side-effects nil
"If non-nil, treats the instanceof operator as having side effects.
This is useful for xulrunner apps."
:type 'boolean
:group 'js2-mode)
(defcustom js2-getprop-has-side-effects nil
"If non-nil, treats the getprop operator as having side effects.
This is useful for testing libraries with nontrivial getters and for
compilers that use empty getprops to declare interface properties."
:type 'boolean
:group 'js2-mode)
(defcustom js2-move-point-on-right-click t
"Non-nil to move insertion point when you right-click.
This makes right-click context menu behavior a bit more intuitive,
since menu operations generally apply to the point. The exception
is if there is a region selection, in which case the point does -not-
move, so cut/copy/paste can work properly.
Note that IntelliJ moves the point, and Eclipse leaves it alone,
so this behavior is customizable."
:group 'js2-mode
:type 'boolean)
(defcustom js2-allow-rhino-new-expr-initializer t
"Non-nil to support a Rhino's experimental syntactic construct.
Rhino supports the ability to follow a `new' expression with an object
literal, which is used to set additional properties on the new object
after calling its constructor. Syntax:
new <expr> [ ( arglist ) ] [initializer]
Hence, this expression:
new Object {a: 1, b: 2}
results in an Object with properties a=1 and b=2. This syntax is
apparently not configurable in Rhino - it's currently always enabled,
as of Rhino version 1.7R2."
:type 'boolean
:group 'js2-mode)
(defcustom js2-allow-member-expr-as-function-name nil
"Non-nil to support experimental Rhino syntax for function names.
Rhino supports an experimental syntax configured via the Rhino Context
setting `allowMemberExprAsFunctionName'. The experimental syntax is:
function <member-expr> ( [ arg-list ] ) { <body> }
Where member-expr is a non-parenthesized 'member expression', which
is anything at the grammar level of a new-expression or lower, meaning
any expression that does not involve infix or unary operators.
When <member-expr> is not a simple identifier, then it is syntactic
sugar for assigning the anonymous function to the <member-expr>. Hence,
this code:
function a.b().c[2] (x, y) { ... }
is rewritten as:
a.b().c[2] = function(x, y) {...}
which doesn't seem particularly useful, but Rhino permits it."
:type 'boolean
:group 'js2-mode)
;; scanner variables
(defmacro js2-deflocal (name value &optional comment)
"Define a buffer-local variable NAME with VALUE and COMMENT."
(declare (debug defvar) (doc-string 3))
`(progn
(defvar ,name ,value ,comment)
(make-variable-buffer-local ',name)))
(defvar js2-EOF_CHAR -1
"Represents end of stream. Distinct from js2-EOF token type.")
;; I originally used symbols to represent tokens, but Rhino uses
;; ints and then sets various flag bits in them, so ints it is.
;; The upshot is that we need a `js2-' prefix in front of each name.
(defvar js2-ERROR -1)
(defvar js2-EOF 0)
(defvar js2-EOL 1)
(defvar js2-ENTERWITH 2) ; begin interpreter bytecodes
(defvar js2-LEAVEWITH 3)
(defvar js2-RETURN 4)
(defvar js2-GOTO 5)
(defvar js2-IFEQ 6)
(defvar js2-IFNE 7)
(defvar js2-SETNAME 8)
(defvar js2-BITOR 9)
(defvar js2-BITXOR 10)
(defvar js2-BITAND 11)
(defvar js2-EQ 12)
(defvar js2-NE 13)
(defvar js2-LT 14)
(defvar js2-LE 15)
(defvar js2-GT 16)
(defvar js2-GE 17)
(defvar js2-LSH 18)
(defvar js2-RSH 19)
(defvar js2-URSH 20)
(defvar js2-ADD 21) ; infix plus
(defvar js2-SUB 22) ; infix minus
(defvar js2-MUL 23)
(defvar js2-DIV 24)
(defvar js2-MOD 25)
(defvar js2-NOT 26)
(defvar js2-BITNOT 27)
(defvar js2-POS 28) ; unary plus
(defvar js2-NEG 29) ; unary minus
(defvar js2-NEW 30)
(defvar js2-DELPROP 31)
(defvar js2-TYPEOF 32)
(defvar js2-GETPROP 33)
(defvar js2-GETPROPNOWARN 34)
(defvar js2-SETPROP 35)
(defvar js2-GETELEM 36)
(defvar js2-SETELEM 37)
(defvar js2-CALL 38)
(defvar js2-NAME 39) ; an identifier
(defvar js2-NUMBER 40)
(defvar js2-STRING 41)
(defvar js2-NULL 42)
(defvar js2-THIS 43)
(defvar js2-FALSE 44)
(defvar js2-TRUE 45)
(defvar js2-SHEQ 46) ; shallow equality (===)
(defvar js2-SHNE 47) ; shallow inequality (!==)
(defvar js2-REGEXP 48)
(defvar js2-BINDNAME 49)
(defvar js2-THROW 50)
(defvar js2-RETHROW 51) ; rethrow caught exception: catch (e if ) uses it
(defvar js2-IN 52)
(defvar js2-INSTANCEOF 53)
(defvar js2-LOCAL_LOAD 54)
(defvar js2-GETVAR 55)
(defvar js2-SETVAR 56)
(defvar js2-CATCH_SCOPE 57)
(defvar js2-ENUM_INIT_KEYS 58) ; FIXME: what are these?
(defvar js2-ENUM_INIT_VALUES 59)
(defvar js2-ENUM_INIT_ARRAY 60)
(defvar js2-ENUM_NEXT 61)
(defvar js2-ENUM_ID 62)
(defvar js2-THISFN 63)
(defvar js2-RETURN_RESULT 64) ; to return previously stored return result
(defvar js2-ARRAYLIT 65) ; array literal
(defvar js2-OBJECTLIT 66) ; object literal
(defvar js2-GET_REF 67) ; *reference
(defvar js2-SET_REF 68) ; *reference = something
(defvar js2-DEL_REF 69) ; delete reference
(defvar js2-REF_CALL 70) ; f(args) = something or f(args)++
(defvar js2-REF_SPECIAL 71) ; reference for special properties like __proto
(defvar js2-YIELD 72) ; JS 1.7 yield pseudo keyword
;; XML support
(defvar js2-DEFAULTNAMESPACE 73)
(defvar js2-ESCXMLATTR 74)
(defvar js2-ESCXMLTEXT 75)
(defvar js2-REF_MEMBER 76) ; Reference for x.@y, x..y etc.
(defvar js2-REF_NS_MEMBER 77) ; Reference for x.ns::y, x..ns::y etc.
(defvar js2-REF_NAME 78) ; Reference for @y, @[y] etc.
(defvar js2-REF_NS_NAME 79) ; Reference for ns::y, @ns::y@[y] etc.
(defvar js2-first-bytecode js2-ENTERWITH)
(defvar js2-last-bytecode js2-REF_NS_NAME)
(defvar js2-TRY 80)
(defvar js2-SEMI 81) ; semicolon
(defvar js2-LB 82) ; left and right brackets
(defvar js2-RB 83)
(defvar js2-LC 84) ; left and right curly-braces
(defvar js2-RC 85)
(defvar js2-LP 86) ; left and right parens
(defvar js2-RP 87)
(defvar js2-COMMA 88) ; comma operator
(defvar js2-ASSIGN 89) ; simple assignment (=)
(defvar js2-ASSIGN_BITOR 90) ; |=
(defvar js2-ASSIGN_BITXOR 91) ; ^=
(defvar js2-ASSIGN_BITAND 92) ; &=
(defvar js2-ASSIGN_LSH 93) ; <<=
(defvar js2-ASSIGN_RSH 94) ; >>=
(defvar js2-ASSIGN_URSH 95) ; >>>=
(defvar js2-ASSIGN_ADD 96) ; +=
(defvar js2-ASSIGN_SUB 97) ; -=
(defvar js2-ASSIGN_MUL 98) ; *=
(defvar js2-ASSIGN_DIV 99) ; /=
(defvar js2-ASSIGN_MOD 100) ; %=
(defvar js2-ASSIGN_EXPON 101)
(defvar js2-first-assign js2-ASSIGN)
(defvar js2-last-assign js2-ASSIGN_EXPON)
(defvar js2-COLON 102)
(defvar js2-OR 103) ; logical or (||)
(defvar js2-AND 104) ; logical and (&&)
(defvar js2-INC 105) ; increment/decrement (++ --)
(defvar js2-DEC 106)
(defvar js2-DOT 107) ; member operator (.)
(defvar js2-FUNCTION 108) ; function keyword
(defvar js2-EXPORT 109) ; export keyword
(defvar js2-IMPORT 110) ; import keyword
(defvar js2-IF 111) ; if keyword
(defvar js2-ELSE 112) ; else keyword
(defvar js2-SWITCH 113) ; switch keyword
(defvar js2-CASE 114) ; case keyword
(defvar js2-DEFAULT 115) ; default keyword
(defvar js2-WHILE 116) ; while keyword
(defvar js2-DO 117) ; do keyword
(defvar js2-FOR 118) ; for keyword
(defvar js2-BREAK 119) ; break keyword
(defvar js2-CONTINUE 120) ; continue keyword
(defvar js2-VAR 121) ; var keyword
(defvar js2-WITH 122) ; with keyword
(defvar js2-CATCH 123) ; catch keyword
(defvar js2-FINALLY 124) ; finally keyword
(defvar js2-VOID 125) ; void keyword
(defvar js2-RESERVED 126) ; reserved keywords
(defvar js2-EMPTY 127)
;; Types used for the parse tree - never returned by scanner.
(defvar js2-BLOCK 128) ; statement block
(defvar js2-LABEL 129) ; label
(defvar js2-TARGET 130)
(defvar js2-LOOP 131)
(defvar js2-EXPR_VOID 132) ; expression statement in functions
(defvar js2-EXPR_RESULT 133) ; expression statement in scripts
(defvar js2-JSR 134)
(defvar js2-SCRIPT 135) ; top-level node for entire script
(defvar js2-TYPEOFNAME 136) ; for typeof(simple-name)
(defvar js2-USE_STACK 137)
(defvar js2-SETPROP_OP 138) ; x.y op= something
(defvar js2-SETELEM_OP 139) ; x[y] op= something
(defvar js2-LOCAL_BLOCK 140)
(defvar js2-SET_REF_OP 141) ; *reference op= something
;; For XML support:
(defvar js2-DOTDOT 142) ; member operator (..)
(defvar js2-COLONCOLON 143) ; namespace::name
(defvar js2-XML 144) ; XML type
(defvar js2-DOTQUERY 145) ; .() -- e.g., x.emps.emp.(name == "terry")
(defvar js2-XMLATTR 146) ; @
(defvar js2-XMLEND 147)
;; Optimizer-only tokens
(defvar js2-TO_OBJECT 148)
(defvar js2-TO_DOUBLE 149)
(defvar js2-GET 150) ; JS 1.5 get pseudo keyword
(defvar js2-SET 151) ; JS 1.5 set pseudo keyword
(defvar js2-LET 152) ; JS 1.7 let pseudo keyword
(defvar js2-CONST 153)
(defvar js2-SETCONST 154)
(defvar js2-SETCONSTVAR 155)
(defvar js2-ARRAYCOMP 156)
(defvar js2-LETEXPR 157)
(defvar js2-WITHEXPR 158)
(defvar js2-DEBUGGER 159)
(defvar js2-COMMENT 160)
(defvar js2-TRIPLEDOT 161) ; for rest parameter
(defvar js2-ARROW 162) ; function arrow (=>)
(defvar js2-CLASS 163)
(defvar js2-EXTENDS 164)
(defvar js2-SUPER 165)
(defvar js2-TEMPLATE_HEAD 166) ; part of template literal before substitution
(defvar js2-NO_SUBS_TEMPLATE 167) ; template literal without substitutions
(defvar js2-TAGGED_TEMPLATE 168) ; tagged template literal
(defvar js2-AWAIT 169) ; await (pseudo keyword)
(defvar js2-HOOK 170) ; conditional (?:)
(defvar js2-EXPON 171)
(defconst js2-num-tokens (1+ js2-EXPON))
(defconst js2-debug-print-trees nil)
;; Rhino accepts any string or stream as input. Emacs character
;; processing works best in buffers, so we'll assume the input is a
;; buffer. JavaScript strings can be copied into temp buffers before
;; scanning them.
;; Buffer-local variables yield much cleaner code than using `defstruct'.
;; They're the Emacs equivalent of instance variables, more or less.
(js2-deflocal js2-ts-dirty-line nil
"Token stream buffer-local variable.
Indicates stuff other than whitespace since start of line.")
(js2-deflocal js2-ts-hit-eof nil
"Token stream buffer-local variable.")
;; FIXME: Unused.
(js2-deflocal js2-ts-line-start 0
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-lineno 1
"Token stream buffer-local variable.")
;; FIXME: Unused.
(js2-deflocal js2-ts-line-end-char -1
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-cursor 1 ; emacs buffers are 1-indexed
"Token stream buffer-local variable.
Current scan position.")
;; FIXME: Unused.
(js2-deflocal js2-ts-is-xml-attribute nil
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-xml-is-tag-content nil
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-xml-open-tags-count 0
"Token stream buffer-local variable.")
(js2-deflocal js2-ts-string-buffer nil
"Token stream buffer-local variable.
List of chars built up while scanning various tokens.")
(cl-defstruct (js2-token
(:constructor nil)
(:constructor make-js2-token (beg)))
"Value returned from the token stream."
(type js2-EOF)
(beg 1)
(end -1)
(string "")
number
number-base
number-legacy-octal-p
regexp-flags
comment-type
follows-eol-p)
;; Have to call `js2-init-scanner' to initialize the values.
(js2-deflocal js2-ti-tokens nil)
(js2-deflocal js2-ti-tokens-cursor nil)
(js2-deflocal js2-ti-lookahead nil)
(cl-defstruct (js2-ts-state
(:constructor make-js2-ts-state (&key (lineno js2-ts-lineno)
(cursor js2-ts-cursor)
(tokens (copy-sequence js2-ti-tokens))
(tokens-cursor js2-ti-tokens-cursor)
(lookahead js2-ti-lookahead))))
lineno
cursor
tokens
tokens-cursor
lookahead)
;;; Parser variables
(js2-deflocal js2-parsed-errors nil
"List of errors produced during scanning/parsing.")
(js2-deflocal js2-parsed-warnings nil
"List of warnings produced during scanning/parsing.")
(js2-deflocal js2-recover-from-parse-errors t
"Non-nil to continue parsing after a syntax error.
In recovery mode, the AST will be built in full, and any error
nodes will be flagged with appropriate error information. If
this flag is nil, a syntax error will result in an error being
signaled.
The variable is automatically buffer-local, because different
modes that use the parser will need different settings.")
(js2-deflocal js2-parse-hook nil
"List of callbacks for receiving parsing progress.")
(defvar js2-parse-finished-hook nil
"List of callbacks to notify when parsing finishes.
Not called if parsing was interrupted.")
(js2-deflocal js2-is-eval-code nil
"True if we're evaluating code in a string.
If non-nil, the tokenizer will record the token text, and the AST nodes
will record their source text. Off by default for IDE modes, since the
text is available in the buffer.")
(defvar js2-parse-ide-mode t
"Non-nil if the parser is being used for `js2-mode'.
If non-nil, the parser will set text properties for fontification
and the syntax table. The value should be nil when using the
parser as a frontend to an interpreter or byte compiler.")
;;; Parser instance variables (buffer-local vars for js2-parse)
(defconst js2-ti-after-eol (lsh 1 16)
"Flag: first token of the source line.")
;; Inline Rhino's CompilerEnvirons vars as buffer-locals.
(js2-deflocal js2-compiler-generate-debug-info t)
(js2-deflocal js2-compiler-use-dynamic-scope nil)
(js2-deflocal js2-compiler-reserved-keywords-as-identifier nil)
(js2-deflocal js2-compiler-xml-available t)
(js2-deflocal js2-compiler-optimization-level 0)
(js2-deflocal js2-compiler-generating-source t)
(js2-deflocal js2-compiler-strict-mode nil)
(js2-deflocal js2-compiler-report-warning-as-error nil)
(js2-deflocal js2-compiler-generate-observer-count nil)
(js2-deflocal js2-compiler-activation-names nil)
;; SKIP: sourceURI
;; There's a compileFunction method in Context.java - may need it.
(js2-deflocal js2-called-by-compile-function nil
"True if `js2-parse' was called by `js2-compile-function'.
Will only be used when we finish implementing the interpreter.")
;; SKIP: ts (we just call `js2-init-scanner' and use its vars)
;; SKIP: node factory - we're going to just call functions directly,
;; and eventually go to a unified AST format.
(js2-deflocal js2-nesting-of-function 0)
(js2-deflocal js2-recorded-identifiers nil
"Tracks identifiers found during parsing.")
(js2-deflocal js2-is-in-destructuring nil
"True while parsing destructuring expression.")
(js2-deflocal js2-in-use-strict-directive nil
"True while inside a script or function under strict mode.")
(defcustom js2-global-externs nil
"A list of any extern names you'd like to consider always declared.
This list is global and is used by all `js2-mode' files.
You can create buffer-local externs list using `js2-additional-externs'."
:type 'list
:group 'js2-mode)
(defcustom js2-include-browser-externs t
"Non-nil to include browser externs in the master externs list.
If you work on JavaScript files that are not intended for browsers,
such as Mozilla Rhino server-side JavaScript, set this to nil.
See `js2-additional-externs' for more information about externs."
:type 'boolean
:group 'js2-mode)
(defcustom js2-include-rhino-externs nil
"Non-nil to include Mozilla Rhino externs in the master externs list.
See `js2-additional-externs' for more information about externs."
:type 'boolean
:group 'js2-mode)
(defcustom js2-include-node-externs nil
"Non-nil to include Node.js externs in the master externs list.
See `js2-additional-externs' for more information about externs."
:type 'boolean
:group 'js2-mode)
(js2-deflocal js2-additional-externs nil
"A buffer-local list of additional external declarations.
It is used to decide whether variables are considered undeclared
for purposes of highlighting. See `js2-highlight-undeclared-vars'.
Each entry is a Lisp string. The string should be the fully qualified
name of an external entity. All externs should be added to this list,
so that as js2-mode's processing improves it can take advantage of them.
You may want to declare your externs in three ways.
First, you can add externs that are valid for all your JavaScript files.
You should probably do this by adding them to `js2-global-externs', which
is a global list used for all js2-mode files.
Next, you can add a function to `js2-init-hook' that adds additional
externs appropriate for the specific file, perhaps based on its path.
These should go in `js2-additional-externs', which is buffer-local.
Third, you can use JSLint's global declaration, as long as
`js2-include-jslint-globals' is non-nil, which see.
Finally, you can add a function to `js2-post-parse-callbacks',
which is called after parsing completes, and `js2-mode-ast' is bound to
the root of the parse tree. At this stage you can set up an AST
node visitor using `js2-visit-ast' and examine the parse tree
for specific import patterns that may imply the existence of
other externs, possibly tied to your build system. These should also
be added to `js2-additional-externs'.
Your post-parse callback may of course also use the simpler and
faster (but perhaps less robust) approach of simply scanning the
buffer text for your imports, using regular expressions.")
;; SKIP: decompiler
;; SKIP: encoded-source
;;; The following variables are per-function and should be saved/restored
;;; during function parsing...
(js2-deflocal js2-current-script-or-fn nil)
(js2-deflocal js2-current-scope nil)
(js2-deflocal js2-nesting-of-with 0)
(js2-deflocal js2-label-set nil
"An alist mapping label names to nodes.")
(js2-deflocal js2-loop-set nil)
(js2-deflocal js2-loop-and-switch-set nil)
(js2-deflocal js2-has-return-value nil)
(js2-deflocal js2-end-flags 0)
;;; ...end of per function variables
;; These flags enumerate the possible ways a statement/function can
;; terminate. These flags are used by endCheck() and by the Parser to
;; detect inconsistent return usage.
;;
;; END_UNREACHED is reserved for code paths that are assumed to always be
;; able to execute (example: throw, continue)
;;
;; END_DROPS_OFF indicates if the statement can transfer control to the
;; next one. Statement such as return dont. A compound statement may have
;; some branch that drops off control to the next statement.
;;
;; END_RETURNS indicates that the statement can return (without arguments)
;; END_RETURNS_VALUE indicates that the statement can return a value.
;;
;; A compound statement such as
;; if (condition) {
;; return value;
;; }
;; Will be detected as (END_DROPS_OFF | END_RETURN_VALUE) by endCheck()
(defconst js2-end-unreached #x0)
(defconst js2-end-drops-off #x1)
(defconst js2-end-returns #x2)
(defconst js2-end-returns-value #x4)
;; Rhino awkwardly passes a statementLabel parameter to the
;; statementHelper() function, the main statement parser, which
;; is then used by quite a few of the sub-parsers. We just make
;; it a buffer-local variable and make sure it's cleaned up properly.
(js2-deflocal js2-labeled-stmt nil) ; type `js2-labeled-stmt-node'
;; Similarly, Rhino passes an inForInit boolean through about half
;; the expression parsers. We use a dynamically-scoped variable,
;; which makes it easier to funcall the parsers individually without
;; worrying about whether they take the parameter or not.
(js2-deflocal js2-in-for-init nil)
(js2-deflocal js2-temp-name-counter 0)
(js2-deflocal js2-parse-stmt-count 0)
(defsubst js2-get-next-temp-name ()
(format "$%d" (cl-incf js2-temp-name-counter)))
(defvar js2-parse-interruptable-p t
"Set this to nil to force parse to continue until finished.
This will mostly be useful for interpreters.")
(defvar js2-statements-per-pause 50
"Pause after this many statements to check for user input.
If user input is pending, stop the parse and discard the tree.
This makes for a smoother user experience for large files.
You may have to wait a second or two before the highlighting
and error-reporting appear, but you can always type ahead if
you wish. This appears to be more or less how Eclipse, IntelliJ
and other editors work.")
(js2-deflocal js2-record-comments t
"Instructs the scanner to record comments in `js2-scanned-comments'.")
(js2-deflocal js2-scanned-comments nil
"List of all comments from the current parse.")
(defcustom js2-mode-indent-inhibit-undo nil
"Non-nil to disable collection of Undo information when indenting lines.
Some users have requested this behavior. It's nil by default because
other Emacs modes don't work this way."
:type 'boolean
:group 'js2-mode)
(defcustom js2-mode-indent-ignore-first-tab nil
"If non-nil, ignore first TAB keypress if we look indented properly.
It's fairly common for users to navigate to an already-indented line
and press TAB for reassurance that it's been indented. For this class
of users, we want the first TAB press on a line to be ignored if the
line is already indented to one of the precomputed alternatives.
This behavior is only partly implemented. If you TAB-indent a line,
navigate to another line, and then navigate back, it fails to clear
the last-indented variable, so it thinks you've already hit TAB once,
and performs the indent. A full solution would involve getting on the
point-motion hooks for the entire buffer. If we come across another
use cases that requires watching point motion, I'll consider doing it.
If you set this variable to nil, then the TAB key will always change
the indentation of the current line, if more than one alternative
indentation spot exists."
:type 'boolean
:group 'js2-mode)
(defvar js2-indent-hook nil
"A hook for user-defined indentation rules.
Functions on this hook should expect two arguments: (LIST INDEX)
The LIST argument is the list of computed indentation points for
the current line. INDEX is the list index of the indentation point
that `js2-bounce-indent' plans to use. If INDEX is nil, then the
indent function is not going to change the current line indentation.
If a hook function on this list returns a non-nil value, then
`js2-bounce-indent' assumes the hook function has performed its own
indentation, and will do nothing. If all hook functions on the list
return nil, then `js2-bounce-indent' will use its computed indentation
and reindent the line.
When hook functions on this hook list are called, the variable
`js2-mode-ast' may or may not be set, depending on whether the
parse tree is available. If the variable is nil, you can pass a
callback to `js2-mode-wait-for-parse', and your callback will be
called after the new parse tree is built. This can take some time
in large files.")
(defface js2-warning
`((((class color) (background light))
(:underline "orange"))
(((class color) (background dark))
(:underline "orange"))
(t (:underline t)))
"Face for JavaScript warnings."
:group 'js2-mode)
(defface js2-error
`((((class color) (background light))
(:foreground "red"))
(((class color) (background dark))
(:foreground "red"))
(t (:foreground "red")))