-
Notifications
You must be signed in to change notification settings - Fork 91
/
luaparse.js
2744 lines (2339 loc) · 80.4 KB
/
luaparse.js
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
/* global exports:true, module:true, require:true, define:true, global:true */
(function (root, name, factory) {
'use strict';
// Used to determine if values are of the language type `Object`
var objectTypes = {
'function': true
, 'object': true
}
// Detect free variable `exports`
, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports
// Detect free variable `module`
, freeModule = objectTypes[typeof module] && module && !module.nodeType && module
// Detect free variable `global`, from Node.js or Browserified code, and
// use it as `window`
, freeGlobal = freeExports && freeModule && typeof global === 'object' && global
// Detect the popular CommonJS extension `module.exports`
, moduleExports = freeModule && freeModule.exports === freeExports && freeExports;
/* istanbul ignore else */
if (freeGlobal && (freeGlobal.global === freeGlobal ||
/* istanbul ignore next */ freeGlobal.window === freeGlobal ||
/* istanbul ignore next */ freeGlobal.self === freeGlobal)) {
root = freeGlobal;
}
// Some AMD build optimizers, like r.js, check for specific condition
// patterns like the following:
/* istanbul ignore if */
if (typeof define === 'function' &&
/* istanbul ignore next */ typeof define.amd === 'object' &&
/* istanbul ignore next */ define.amd) {
// defined as an anonymous module.
define(['exports'], factory);
// In case the source has been processed and wrapped in a define module use
// the supplied `exports` object.
if (freeExports && moduleExports) factory(freeModule.exports);
}
// check for `exports` after `define` in case a build optimizer adds an
// `exports` object
else /* istanbul ignore else */ if (freeExports && freeModule) {
// in Node.js or RingoJS v0.8.0+
/* istanbul ignore else */
if (moduleExports) factory(freeModule.exports);
// in RingoJS v0.7.0-
else factory(freeExports);
}
// in a browser or Rhino
else {
factory((root[name] = {}));
}
}(this, 'luaparse', function (exports) {
'use strict';
exports.version = "0.3.1";
var input, options, length, features, encodingMode;
// Options can be set either globally on the parser object through
// defaultOptions, or during the parse call.
var defaultOptions = exports.defaultOptions = {
// Explicitly tell the parser when the input ends.
wait: false
// Store comments as an array in the chunk object.
, comments: true
// Track identifier scopes by adding an isLocal attribute to each
// identifier-node.
, scope: false
// Store location information on each syntax node as
// `loc: { start: { line, column }, end: { line, column } }`.
, locations: false
// Store the start and end character locations on each syntax node as
// `range: [start, end]`.
, ranges: false
// A callback which will be invoked when a syntax node has been completed.
// The node which has been created will be passed as the only parameter.
, onCreateNode: null
// A callback which will be invoked when a new scope is created.
, onCreateScope: null
// A callback which will be invoked when the current scope is destroyed.
, onDestroyScope: null
// A callback which will be invoked when a local variable is declared in the current scope.
// The variable's name will be passed as the only parameter
, onLocalDeclaration: null
// The version of Lua targeted by the parser (string; allowed values are
// '5.1', '5.2', '5.3').
, luaVersion: '5.1'
// Encoding mode: how to interpret code units higher than U+007F in input
, encodingMode: 'none'
};
function encodeUTF8(codepoint, highMask) {
highMask = highMask || 0;
if (codepoint < 0x80) {
return String.fromCharCode(codepoint);
} else if (codepoint < 0x800) {
return String.fromCharCode(
highMask | 0xc0 | (codepoint >> 6) ,
highMask | 0x80 | ( codepoint & 0x3f)
);
} else if (codepoint < 0x10000) {
return String.fromCharCode(
highMask | 0xe0 | (codepoint >> 12) ,
highMask | 0x80 | ((codepoint >> 6) & 0x3f),
highMask | 0x80 | ( codepoint & 0x3f)
);
} else /* istanbul ignore else */ if (codepoint < 0x110000) {
return String.fromCharCode(
highMask | 0xf0 | (codepoint >> 18) ,
highMask | 0x80 | ((codepoint >> 12) & 0x3f),
highMask | 0x80 | ((codepoint >> 6) & 0x3f),
highMask | 0x80 | ( codepoint & 0x3f)
);
} else {
// TODO: Lua 5.4 allows up to six-byte sequences, as in UTF-8:1993
return null;
}
}
function toHex(num, digits) {
var result = num.toString(16);
while (result.length < digits)
result = '0' + result;
return result;
}
function checkChars(rx) {
return function (s) {
var m = rx.exec(s);
if (!m)
return s;
raise(null, errors.invalidCodeUnit, toHex(m[0].charCodeAt(0), 4).toUpperCase());
};
}
var encodingModes = {
// `pseudo-latin1` encoding mode: assume the input was decoded with the latin1 encoding
// WARNING: latin1 does **NOT** mean cp1252 here like in the bone-headed WHATWG standard;
// it means true ISO/IEC 8859-1 identity-mapped to Basic Latin and Latin-1 Supplement blocks
'pseudo-latin1': {
fixup: checkChars(/[^\x00-\xff]/),
encodeByte: function (value) {
if (value === null)
return '';
return String.fromCharCode(value);
},
encodeUTF8: function (codepoint) {
return encodeUTF8(codepoint);
},
},
// `x-user-defined` encoding mode: assume the input was decoded with the WHATWG `x-user-defined` encoding
'x-user-defined': {
fixup: checkChars(/[^\x00-\x7f\uf780-\uf7ff]/),
encodeByte: function (value) {
if (value === null)
return '';
if (value >= 0x80)
return String.fromCharCode(value | 0xf700);
return String.fromCharCode(value);
},
encodeUTF8: function (codepoint) {
return encodeUTF8(codepoint, 0xf700);
}
},
// `none` encoding mode: disregard intrepretation of string literals, leave identifiers as-is
'none': {
discardStrings: true,
fixup: function (s) {
return s;
},
encodeByte: function (value) {
return '';
},
encodeUTF8: function (codepoint) {
return '';
}
}
};
// The available tokens expressed as enum flags so they can be checked with
// bitwise operations.
var EOF = 1, StringLiteral = 2, Keyword = 4, Identifier = 8
, NumericLiteral = 16, Punctuator = 32, BooleanLiteral = 64
, NilLiteral = 128, VarargLiteral = 256;
exports.tokenTypes = { EOF: EOF, StringLiteral: StringLiteral
, Keyword: Keyword, Identifier: Identifier, NumericLiteral: NumericLiteral
, Punctuator: Punctuator, BooleanLiteral: BooleanLiteral
, NilLiteral: NilLiteral, VarargLiteral: VarargLiteral
};
// As this parser is a bit different from luas own, the error messages
// will be different in some situations.
var errors = exports.errors = {
unexpected: 'unexpected %1 \'%2\' near \'%3\''
, unexpectedEOF: 'unexpected symbol near \'<eof>\''
, expected: '\'%1\' expected near \'%2\''
, expectedToken: '%1 expected near \'%2\''
, unfinishedString: 'unfinished string near \'%1\''
, malformedNumber: 'malformed number near \'%1\''
, decimalEscapeTooLarge: 'decimal escape too large near \'%1\''
, invalidEscape: 'invalid escape sequence near \'%1\''
, hexadecimalDigitExpected: 'hexadecimal digit expected near \'%1\''
, braceExpected: 'missing \'%1\' near \'%2\''
, tooLargeCodepoint: 'UTF-8 value too large near \'%1\''
, unfinishedLongString: 'unfinished long string (starting at line %1) near \'%2\''
, unfinishedLongComment: 'unfinished long comment (starting at line %1) near \'%2\''
, ambiguousSyntax: 'ambiguous syntax (function call x new statement) near \'%1\''
, noLoopToBreak: 'no loop to break near \'%1\''
, labelAlreadyDefined: 'label \'%1\' already defined on line %2'
, labelNotVisible: 'no visible label \'%1\' for <goto>'
, gotoJumpInLocalScope: '<goto %1> jumps into the scope of local \'%2\''
, cannotUseVararg: 'cannot use \'...\' outside a vararg function near \'%1\''
, invalidCodeUnit: 'code unit U+%1 is not allowed in the current encoding mode'
};
// ### Abstract Syntax Tree
//
// The default AST structure is inspired by the Mozilla Parser API but can
// easily be customized by overriding these functions.
var ast = exports.ast = {
labelStatement: function(label) {
return {
type: 'LabelStatement'
, label: label
};
}
, breakStatement: function() {
return {
type: 'BreakStatement'
};
}
, gotoStatement: function(label) {
return {
type: 'GotoStatement'
, label: label
};
}
, returnStatement: function(args) {
return {
type: 'ReturnStatement'
, 'arguments': args
};
}
, ifStatement: function(clauses) {
return {
type: 'IfStatement'
, clauses: clauses
};
}
, ifClause: function(condition, body) {
return {
type: 'IfClause'
, condition: condition
, body: body
};
}
, elseifClause: function(condition, body) {
return {
type: 'ElseifClause'
, condition: condition
, body: body
};
}
, elseClause: function(body) {
return {
type: 'ElseClause'
, body: body
};
}
, whileStatement: function(condition, body) {
return {
type: 'WhileStatement'
, condition: condition
, body: body
};
}
, doStatement: function(body) {
return {
type: 'DoStatement'
, body: body
};
}
, repeatStatement: function(condition, body) {
return {
type: 'RepeatStatement'
, condition: condition
, body: body
};
}
, localStatement: function(variables, init) {
return {
type: 'LocalStatement'
, variables: variables
, init: init
};
}
, assignmentStatement: function(variables, init) {
return {
type: 'AssignmentStatement'
, variables: variables
, init: init
};
}
, callStatement: function(expression) {
return {
type: 'CallStatement'
, expression: expression
};
}
, functionStatement: function(identifier, parameters, isLocal, body) {
return {
type: 'FunctionDeclaration'
, identifier: identifier
, isLocal: isLocal
, parameters: parameters
, body: body
};
}
, forNumericStatement: function(variable, start, end, step, body) {
return {
type: 'ForNumericStatement'
, variable: variable
, start: start
, end: end
, step: step
, body: body
};
}
, forGenericStatement: function(variables, iterators, body) {
return {
type: 'ForGenericStatement'
, variables: variables
, iterators: iterators
, body: body
};
}
, chunk: function(body) {
return {
type: 'Chunk'
, body: body
};
}
, identifier: function(name) {
return {
type: 'Identifier'
, name: name
};
}
, literal: function(type, value, raw) {
type = (type === StringLiteral) ? 'StringLiteral'
: (type === NumericLiteral) ? 'NumericLiteral'
: (type === BooleanLiteral) ? 'BooleanLiteral'
: (type === NilLiteral) ? 'NilLiteral'
: 'VarargLiteral';
return {
type: type
, value: value
, raw: raw
};
}
, tableKey: function(key, value) {
return {
type: 'TableKey'
, key: key
, value: value
};
}
, tableKeyString: function(key, value) {
return {
type: 'TableKeyString'
, key: key
, value: value
};
}
, tableValue: function(value) {
return {
type: 'TableValue'
, value: value
};
}
, tableConstructorExpression: function(fields) {
return {
type: 'TableConstructorExpression'
, fields: fields
};
}
, binaryExpression: function(operator, left, right) {
var type = ('and' === operator || 'or' === operator) ?
'LogicalExpression' :
'BinaryExpression';
return {
type: type
, operator: operator
, left: left
, right: right
};
}
, unaryExpression: function(operator, argument) {
return {
type: 'UnaryExpression'
, operator: operator
, argument: argument
};
}
, memberExpression: function(base, indexer, identifier) {
return {
type: 'MemberExpression'
, indexer: indexer
, identifier: identifier
, base: base
};
}
, indexExpression: function(base, index) {
return {
type: 'IndexExpression'
, base: base
, index: index
};
}
, callExpression: function(base, args) {
return {
type: 'CallExpression'
, base: base
, 'arguments': args
};
}
, tableCallExpression: function(base, args) {
return {
type: 'TableCallExpression'
, base: base
, 'arguments': args
, argument: args
};
}
, stringCallExpression: function(base, argument) {
return {
type: 'StringCallExpression'
, base: base
, argument: argument
};
}
, comment: function(value, raw) {
return {
type: 'Comment'
, value: value
, raw: raw
};
}
};
// Wrap up the node object.
function finishNode(node) {
// Pop a `Marker` off the location-array and attach its location data.
if (trackLocations) {
var location = locations.pop();
location.complete();
location.bless(node);
}
if (options.onCreateNode) options.onCreateNode(node);
return node;
}
// Helpers
// -------
var slice = Array.prototype.slice
, toString = Object.prototype.toString
;
var indexOf = /* istanbul ignore next */ function (array, element) {
for (var i = 0, length = array.length; i < length; ++i) {
if (array[i] === element) return i;
}
return -1;
};
/* istanbul ignore else */
if (Array.prototype.indexOf)
indexOf = function (array, element) {
return array.indexOf(element);
};
// Iterate through an array of objects and return the index of an object
// with a matching property.
function indexOfObject(array, property, element) {
for (var i = 0, length = array.length; i < length; ++i) {
if (array[i][property] === element) return i;
}
return -1;
}
// A sprintf implementation using %index (beginning at 1) to input
// arguments in the format string.
//
// Example:
//
// // Unexpected function in token
// sprintf('Unexpected %2 in %1.', 'token', 'function');
function sprintf(format) {
var args = slice.call(arguments, 1);
format = format.replace(/%(\d)/g, function (match, index) {
return '' + args[index - 1] || /* istanbul ignore next */ '';
});
return format;
}
// Polyfill for `Object.assign`.
var assign = /* istanbul ignore next */ function (dest) {
var args = slice.call(arguments, 1)
, src, prop;
for (var i = 0, length = args.length; i < length; ++i) {
src = args[i];
for (prop in src)
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(src, prop)) {
dest[prop] = src[prop];
}
}
return dest;
};
/* istanbul ignore else */
if (Object.assign)
assign = Object.assign;
// ### Error functions
exports.SyntaxError = SyntaxError;
// XXX: Eliminate this function and change the error type to be different from SyntaxError.
// This will unfortunately be a breaking change, because some downstream users depend
// on the error thrown being an instance of SyntaxError. For example, the Ace editor:
// <https://github.com/ajaxorg/ace/blob/4c7e5eb3f5d5ca9434847be51834a4e41661b852/lib/ace/mode/lua_worker.js#L55>
function fixupError(e) {
/* istanbul ignore if */
if (!Object.create)
return e;
return Object.create(e, {
'line': { 'writable': true, value: e.line },
'index': { 'writable': true, value: e.index },
'column': { 'writable': true, value: e.column }
});
}
// #### Raise an exception.
//
// Raise an exception by passing a token, a string format and its paramters.
//
// The passed tokens location will automatically be added to the error
// message if it exists, if not it will default to the lexers current
// position.
//
// Example:
//
// // [1:0] expected [ near (
// raise(token, "expected %1 near %2", '[', token.value);
function raise(token) {
var message = sprintf.apply(null, slice.call(arguments, 1))
, error, col;
if (token === null || typeof token.line === 'undefined') {
col = index - lineStart + 1;
error = fixupError(new SyntaxError(sprintf('[%1:%2] %3', line, col, message)));
error.index = index;
error.line = line;
error.column = col;
} else {
col = token.range[0] - token.lineStart;
error = fixupError(new SyntaxError(sprintf('[%1:%2] %3', token.line, col, message)));
error.line = token.line;
error.index = token.range[0];
error.column = col;
}
throw error;
}
function tokenValue(token) {
var raw = input.slice(token.range[0], token.range[1]);
if (raw)
return raw;
return token.value;
}
// #### Raise an unexpected token error.
//
// Example:
//
// // expected <name> near '0'
// raiseUnexpectedToken('<name>', token);
function raiseUnexpectedToken(type, token) {
raise(token, errors.expectedToken, type, tokenValue(token));
}
// #### Raise a general unexpected error
//
// Usage should pass either a token object or a symbol string which was
// expected. We can also specify a nearby token such as <eof>, this will
// default to the currently active token.
//
// Example:
//
// // Unexpected symbol 'end' near '<eof>'
// unexpected(token);
//
// If there's no token in the buffer it means we have reached <eof>.
function unexpected(found) {
var near = tokenValue(lookahead);
if ('undefined' !== typeof found.type) {
var type;
switch (found.type) {
case StringLiteral: type = 'string'; break;
case Keyword: type = 'keyword'; break;
case Identifier: type = 'identifier'; break;
case NumericLiteral: type = 'number'; break;
case Punctuator: type = 'symbol'; break;
case BooleanLiteral: type = 'boolean'; break;
case NilLiteral:
return raise(found, errors.unexpected, 'symbol', 'nil', near);
case EOF:
return raise(found, errors.unexpectedEOF);
}
return raise(found, errors.unexpected, type, tokenValue(found), near);
}
return raise(found, errors.unexpected, 'symbol', found, near);
}
// Lexer
// -----
//
// The lexer, or the tokenizer reads the input string character by character
// and derives a token left-right. To be as efficient as possible the lexer
// prioritizes the common cases such as identifiers. It also works with
// character codes instead of characters as string comparisons was the
// biggest bottleneck of the parser.
//
// If `options.comments` is enabled, all comments encountered will be stored
// in an array which later will be appended to the chunk object. If disabled,
// they will simply be disregarded.
//
// When the lexer has derived a valid token, it will be returned as an object
// containing its value and as well as its position in the input string (this
// is always enabled to provide proper debug messages).
//
// `lex()` starts lexing and returns the following token in the stream.
var index
, token
, previousToken
, lookahead
, comments
, tokenStart
, line
, lineStart;
exports.lex = lex;
function lex() {
skipWhiteSpace();
// Skip comments beginning with --
while (45 === input.charCodeAt(index) &&
45 === input.charCodeAt(index + 1)) {
scanComment();
skipWhiteSpace();
}
if (index >= length) return {
type : EOF
, value: '<eof>'
, line: line
, lineStart: lineStart
, range: [index, index]
};
var charCode = input.charCodeAt(index)
, next = input.charCodeAt(index + 1);
// Memorize the range index where the token begins.
tokenStart = index;
if (isIdentifierStart(charCode)) return scanIdentifierOrKeyword();
switch (charCode) {
case 39: case 34: // '"
return scanStringLiteral();
case 48: case 49: case 50: case 51: case 52: case 53:
case 54: case 55: case 56: case 57: // 0-9
return scanNumericLiteral();
case 46: // .
// If the dot is followed by a digit it's a float.
if (isDecDigit(next)) return scanNumericLiteral();
if (46 === next) {
if (46 === input.charCodeAt(index + 2)) return scanVarargLiteral();
return scanPunctuator('..');
}
return scanPunctuator('.');
case 61: // =
if (61 === next) return scanPunctuator('==');
return scanPunctuator('=');
case 62: // >
if (features.bitwiseOperators)
if (62 === next) return scanPunctuator('>>');
if (61 === next) return scanPunctuator('>=');
return scanPunctuator('>');
case 60: // <
if (features.bitwiseOperators)
if (60 === next) return scanPunctuator('<<');
if (61 === next) return scanPunctuator('<=');
return scanPunctuator('<');
case 126: // ~
if (61 === next) return scanPunctuator('~=');
if (!features.bitwiseOperators)
break;
return scanPunctuator('~');
case 58: // :
if (features.labels)
if (58 === next) return scanPunctuator('::');
return scanPunctuator(':');
case 91: // [
// Check for a multiline string, they begin with [= or [[
if (91 === next || 61 === next) return scanLongStringLiteral();
return scanPunctuator('[');
case 47: // /
// Check for integer division op (//)
if (features.integerDivision)
if (47 === next) return scanPunctuator('//');
return scanPunctuator('/');
case 38: case 124: // & |
if (!features.bitwiseOperators)
break;
/* fall through */
case 42: case 94: case 37: case 44: case 123: case 125:
case 93: case 40: case 41: case 59: case 35: case 45:
case 43: // * ^ % , { } ] ( ) ; # - +
return scanPunctuator(input.charAt(index));
}
return unexpected(input.charAt(index));
}
// Whitespace has no semantic meaning in lua so simply skip ahead while
// tracking the encounted newlines. Any kind of eol sequence is counted as a
// single line.
function consumeEOL() {
var charCode = input.charCodeAt(index)
, peekCharCode = input.charCodeAt(index + 1);
if (isLineTerminator(charCode)) {
// Count \n\r and \r\n as one newline.
if (10 === charCode && 13 === peekCharCode) ++index;
if (13 === charCode && 10 === peekCharCode) ++index;
++line;
lineStart = ++index;
return true;
}
return false;
}
function skipWhiteSpace() {
while (index < length) {
var charCode = input.charCodeAt(index);
if (isWhiteSpace(charCode)) {
++index;
} else if (!consumeEOL()) {
break;
}
}
}
// Identifiers, keywords, booleans and nil all look the same syntax wise. We
// simply go through them one by one and defaulting to an identifier if no
// previous case matched.
function scanIdentifierOrKeyword() {
var value, type;
// Slicing the input string is prefered before string concatenation in a
// loop for performance reasons.
while (isIdentifierPart(input.charCodeAt(++index)));
value = encodingMode.fixup(input.slice(tokenStart, index));
// Decide on the token type and possibly cast the value.
if (isKeyword(value)) {
type = Keyword;
} else if ('true' === value || 'false' === value) {
type = BooleanLiteral;
value = ('true' === value);
} else if ('nil' === value) {
type = NilLiteral;
value = null;
} else {
type = Identifier;
}
return {
type: type
, value: value
, line: line
, lineStart: lineStart
, range: [tokenStart, index]
};
}
// Once a punctuator reaches this function it should already have been
// validated so we simply return it as a token.
function scanPunctuator(value) {
index += value.length;
return {
type: Punctuator
, value: value
, line: line
, lineStart: lineStart
, range: [tokenStart, index]
};
}
// A vararg literal consists of three dots.
function scanVarargLiteral() {
index += 3;
return {
type: VarargLiteral
, value: '...'
, line: line
, lineStart: lineStart
, range: [tokenStart, index]
};
}
// Find the string literal by matching the delimiter marks used.
function scanStringLiteral() {
var delimiter = input.charCodeAt(index++)
, beginLine = line
, beginLineStart = lineStart
, stringStart = index
, string = encodingMode.discardStrings ? null : ''
, charCode;
for (;;) {
charCode = input.charCodeAt(index++);
if (delimiter === charCode) break;
// EOF or `\n` terminates a string literal. If we haven't found the
// ending delimiter by now, raise an exception.
if (index > length || isLineTerminator(charCode)) {
string += input.slice(stringStart, index - 1);
raise(null, errors.unfinishedString, input.slice(tokenStart, index - 1));
}
if (92 === charCode) { // backslash
if (!encodingMode.discardStrings) {
var beforeEscape = input.slice(stringStart, index - 1);
string += encodingMode.fixup(beforeEscape);
}
var escapeValue = readEscapeSequence();
if (!encodingMode.discardStrings)
string += escapeValue;
stringStart = index;
}
}
if (!encodingMode.discardStrings) {
string += encodingMode.encodeByte(null);
string += encodingMode.fixup(input.slice(stringStart, index - 1));
}
return {
type: StringLiteral
, value: string
, line: beginLine
, lineStart: beginLineStart
, lastLine: line
, lastLineStart: lineStart
, range: [tokenStart, index]
};
}
// Expect a multiline string literal and return it as a regular string
// literal, if it doesn't validate into a valid multiline string, throw an
// exception.
function scanLongStringLiteral() {
var beginLine = line
, beginLineStart = lineStart
, string = readLongString(false);
// Fail if it's not a multiline literal.
if (false === string) raise(token, errors.expected, '[', tokenValue(token));
return {
type: StringLiteral
, value: encodingMode.discardStrings ? null : encodingMode.fixup(string)
, line: beginLine
, lineStart: beginLineStart
, lastLine: line
, lastLineStart: lineStart
, range: [tokenStart, index]
};
}
// Numeric literals will be returned as floating-point numbers instead of
// strings. The raw value should be retrieved from slicing the input string
// later on in the process.
//
// If a hexadecimal number is encountered, it will be converted.
function scanNumericLiteral() {
var character = input.charAt(index)
, next = input.charAt(index + 1);
var literal = ('0' === character && 'xX'.indexOf(next || null) >= 0) ?
readHexLiteral() : readDecLiteral();
var foundImaginaryUnit = readImaginaryUnitSuffix()
, foundInt64Suffix = readInt64Suffix();
if (foundInt64Suffix && (foundImaginaryUnit || literal.hasFractionPart)) {
raise(null, errors.malformedNumber, input.slice(tokenStart, index));
}
return {
type: NumericLiteral
, value: literal.value
, line: line
, lineStart: lineStart
, range: [tokenStart, index]
};
}
function readImaginaryUnitSuffix() {
if (!features.imaginaryNumbers) return;
// Imaginary unit number suffix is optional.
// See http://luajit.org/ext_ffi_api.html#literals
if ('iI'.indexOf(input.charAt(index) || null) >= 0) {
++index;
return true;
} else {
return false;
}
}
function readInt64Suffix() {
if (!features.integerSuffixes) return;
// Int64/uint64 number suffix is optional.