-
Notifications
You must be signed in to change notification settings - Fork 71
/
MethodScriptCompiler.java
3183 lines (3019 loc) · 119 KB
/
MethodScriptCompiler.java
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
package com.laytonsmith.core;
import com.laytonsmith.PureUtilities.Common.FileUtil;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.PureUtilities.SimpleVersion;
import com.laytonsmith.PureUtilities.SmartComment;
import com.laytonsmith.annotations.OperatorPreferred;
import com.laytonsmith.annotations.breakable;
import com.laytonsmith.annotations.nolinking;
import com.laytonsmith.annotations.unbreakable;
import com.laytonsmith.core.Optimizable.OptimizationOption;
import com.laytonsmith.core.compiler.BranchStatement;
import com.laytonsmith.core.compiler.CompilerEnvironment;
import com.laytonsmith.core.compiler.CompilerWarning;
import com.laytonsmith.core.compiler.EarlyBindingKeyword;
import com.laytonsmith.core.compiler.FileOptions;
import com.laytonsmith.core.compiler.FileOptions.SuppressWarning;
import com.laytonsmith.core.compiler.Keyword;
import com.laytonsmith.core.compiler.KeywordList;
import com.laytonsmith.core.compiler.LateBindingKeyword;
import com.laytonsmith.core.compiler.TokenStream;
import com.laytonsmith.core.compiler.analysis.StaticAnalysis;
import com.laytonsmith.core.constructs.CBareString;
import com.laytonsmith.core.constructs.CClassType;
import com.laytonsmith.core.constructs.CDecimal;
import com.laytonsmith.core.constructs.CDouble;
import com.laytonsmith.core.constructs.CFunction;
import com.laytonsmith.core.constructs.CInt;
import com.laytonsmith.core.constructs.CKeyword;
import com.laytonsmith.core.constructs.CLabel;
import com.laytonsmith.core.constructs.CNull;
import com.laytonsmith.core.constructs.CPreIdentifier;
import com.laytonsmith.core.constructs.CSemicolon;
import com.laytonsmith.core.constructs.CSlice;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.CSymbol;
import com.laytonsmith.core.constructs.CVoid;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.IVariable;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.constructs.Token;
import com.laytonsmith.core.constructs.Token.TType;
import com.laytonsmith.core.constructs.Variable;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.CRE.CRECastException;
import com.laytonsmith.core.exceptions.CRE.CRERangeException;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigCompileGroupException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.extensions.ExtensionManager;
import com.laytonsmith.core.extensions.ExtensionTracker;
import com.laytonsmith.core.functions.Compiler;
import com.laytonsmith.core.functions.Compiler.__autoconcat__;
import com.laytonsmith.core.functions.Compiler.__cbrace__;
import com.laytonsmith.core.functions.Compiler.__smart_string__;
import com.laytonsmith.core.functions.Compiler.__statements__;
import com.laytonsmith.core.functions.Compiler.p;
import com.laytonsmith.core.functions.ControlFlow;
import com.laytonsmith.core.functions.DataHandling;
import com.laytonsmith.core.functions.Function;
import com.laytonsmith.core.functions.FunctionBase;
import com.laytonsmith.core.functions.FunctionList;
import com.laytonsmith.core.functions.ArrayHandling.array_get;
import com.laytonsmith.core.functions.Math.neg;
import com.laytonsmith.core.functions.StringHandling;
import com.laytonsmith.core.natives.interfaces.Mixed;
import com.laytonsmith.persistence.DataSourceException;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EmptyStackException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.Stack;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
/**
* The MethodScriptCompiler class handles the various stages of compilation and provides helper methods for execution of
* the compiled trees.
*/
public final class MethodScriptCompiler {
private static final EnumSet<Optimizable.OptimizationOption> NO_OPTIMIZATIONS = EnumSet.noneOf(Optimizable.OptimizationOption.class);
private MethodScriptCompiler() {
}
private static final Pattern VAR_PATTERN = Pattern.compile("\\$[\\p{L}0-9_]+");
private static final Pattern IVAR_PATTERN = Pattern.compile(IVariable.VARIABLE_NAME_REGEX);
/**
* Lexes the script, and turns it into a token stream.This looks through the script character by character.
*
* @param script The script to lex
* @param env The environment.
* @param file The file this script came from, or potentially null if the code is from a dynamic source
* @param inPureMScript If the script is in pure MethodScript, this should be true. Pure MethodScript is defined as
* code that doesn't have command alias wrappers.
* @return A stream of tokens
* @throws ConfigCompileException If compilation fails due to bad syntax
*/
public static TokenStream lex(String script, Environment env, File file, boolean inPureMScript)
throws ConfigCompileException {
return lex(script, env, file, inPureMScript, false);
}
/**
* Lexes the script, and turns it into a token stream. This looks through the script character by character.
*
* @param script The script to lex
* @param env
* @param file The file this script came from, or potentially null if the code is from a dynamic source
* @param inPureMScript If the script is in pure MethodScript, this should be true. Pure MethodScript is defined as
* code that doesn't have command alias wrappers.
* @param saveAllTokens If this script is planning to be compiled, then this value should always be false, however,
* if the calling code needs all tokens for informational purposes (and doesn't plan on actually compiling the code)
* then this can be true. If true, all tokens are saved, including comments and (some) whitespace. Given this lexing
* stream, the exact source code could be re-constructed.
*
* A note on whitespace: The whitespace tokens are not guaranteed to be accurate, however, the column information
* is. If you have two tokens t1 and t2, each with a value of length 1, where the columns are 1 and 5, then that
* means there are 4 spaces between the two.
* @return A stream of tokens
* @throws ConfigCompileException If compilation fails due to bad syntax
*/
@SuppressWarnings({"null", "UnnecessaryContinue"})
public static TokenStream lex(String script, Environment env, File file,
boolean inPureMScript, boolean saveAllTokens) throws ConfigCompileException {
if(env == null) {
// We MUST have a CompilerEnvironment, but it doesn't need to be used, but we have to create it at this
// stage.
env = Environment.createEnvironment(new CompilerEnvironment());
}
if(!env.hasEnv(CompilerEnvironment.class)) {
env = env.cloneAndAdd(new CompilerEnvironment());
}
if(script.isEmpty()) {
return new TokenStream(new LinkedList<>(), "", new HashMap<>());
}
if(script.charAt(0) == 65279) {
// Remove the UTF-8 Byte Order Mark, if present.
script = script.substring(1);
}
final StringBuilder fileOptions = new StringBuilder();
/**
* May be null if the file options aren't parsed yet, but if they have been, they will be parsed and put in
* this variable, to allow the lexer to make use of the file options already.
*/
FileOptions builtFileOptions = null;
script = script.replaceAll("\r\n", "\n");
script = script + "\n";
final Set<String> keywords = KeywordList.getKeywordNames();
final TokenStream tokenList = new TokenStream();
// Set our state variables.
boolean stateInQuote = false;
int quoteLineNumberStart = 1;
boolean inSmartQuote = false;
int smartQuoteLineNumberStart = 1;
boolean inComment = false;
int commentLineNumberStart = 1;
boolean commentIsBlock = false;
boolean inOptVar = false;
boolean inCommand = (!inPureMScript);
boolean inMultiline = false;
boolean inSmartComment = false;
boolean inFileOptions = false;
boolean inAnnotation = false;
int fileOptionsLineNumberStart = 1;
StringBuilder buf = new StringBuilder();
int lineNum = 1;
int column = 1;
int lastColumn = 0;
Target target = Target.UNKNOWN;
// Lex the script character by character.
for(int i = 0; i < script.length(); i++) {
char c = script.charAt(i);
char c2 = '\0';
char c3 = '\0';
if(i < script.length() - 1) {
c2 = script.charAt(i + 1);
}
if(i < script.length() - 2) {
c3 = script.charAt(i + 2);
}
column += i - lastColumn;
lastColumn = i;
if(c == '\n') {
lineNum++;
column = 0;
if(!inMultiline && !inPureMScript) {
inCommand = true;
}
}
if(buf.length() == 0) {
target = new Target(lineNum, file, column);
}
// If we are in file options, add the character to the buffer if it's not a file options end character.
if(inFileOptions) {
// For a '>' character outside of a comment, '\>' would have to be used in file options.
// Other characters than '>'cannot be escaped.
// If support for more escaped characters would be desired in the future, it could be added here.
switch(c) {
case '\\': {
if(c2 == '>') { // "\>".
fileOptions.append('>');
i++;
continue;
}
break;
}
case '>': {
if(saveAllTokens) {
tokenList.add(new Token(TType.FILE_OPTIONS_STRING,
fileOptions.toString(), target));
tokenList.add(new Token(TType.FILE_OPTIONS_END, ">", target));
}
inFileOptions = false;
builtFileOptions = TokenStream.parseFileOptions(fileOptions.toString(), new HashMap<>());
continue;
}
}
fileOptions.append(c);
continue;
}
// Comment handling. This is bypassed if we are in a string.
if(!stateInQuote && !inSmartQuote) {
switch(c) {
// Block comments start (/* and /**) and Double slash line comment start (//).
case '/': {
if(c2 == '*') { // "/*" or "/**".
if(inComment && commentIsBlock) {
// This compiler warning can be removed and the nested comment blocks implemented in 3.3.6
// or later.
CompilerWarning warning = new CompilerWarning("Nested comment blocks are being"
+ " added to a future version, where this code will suddenly cause an unclosed"
+ " comment block. You can remove this block comment open symbol now, or add a "
+ " new block comment close when this feature is implemented (it will likely"
+ " cause an obvious compile error), and optionally suppress this warning.",
target, SuppressWarning.FutureNestedCommentChange);
env.getEnv(CompilerEnvironment.class).addCompilerWarning(builtFileOptions, warning);
}
if(!inComment) {
buf.append("/*");
inComment = true;
commentIsBlock = true;
if(i + 2 < script.length() && script.charAt(i + 2) == '*'
&& (i + 3 >= script.length() || script.charAt(i + 3) != '/')) { // "/**".
inSmartComment = true;
buf.append("*");
i++;
}
commentLineNumberStart = lineNum;
i++;
continue;
}
} else if(c2 == '/') { // "//".
if(!inComment) {
buf.append("//");
inComment = true;
i++;
continue;
}
}
break;
}
// Line comment start (#).
case '#': {
if(!inComment) { // "#".
buf.append("#");
inComment = true;
continue;
}
break;
}
// Block comment end (*/).
case '*': {
if(inComment && commentIsBlock && c2 == '/') { // "*/".
if(saveAllTokens || inSmartComment) {
buf.append("*/");
validateTerminatedBidiSequence(buf.toString(), target);
tokenList.add(new Token(inSmartComment ? TType.SMART_COMMENT : TType.COMMENT,
buf.toString(), target));
}
buf = new StringBuilder();
target = new Target(lineNum, file, column);
inComment = false;
commentIsBlock = false;
inSmartComment = false;
i++;
continue;
}
break;
}
// Line comment end (\n).
case '\n': {
if(inComment && !commentIsBlock) { // "\n".
inComment = false;
if(saveAllTokens) {
validateTerminatedBidiSequence(buf.toString(), target);
tokenList.add(new Token(TType.COMMENT, buf.toString(), target));
tokenList.add(new Token(TType.NEWLINE, "\n", new Target(lineNum + 1, file, 0)));
}
buf = new StringBuilder();
target = new Target(lineNum, file, column);
continue;
}
break;
}
}
}
// If we are in a comment, add the character to the buffer.
if(inComment || (inAnnotation && c != '}')) {
buf.append(c);
continue;
}
// Handle non-comment non-quoted characters.
if(!stateInQuote) {
// We're not in a comment or quoted string, handle: +=, -=, *=, /=, .=, ->, ++, --, %, **, *, +, -, /,
// >=, <=, <<<, >>>, <, >, ===, !==, ==, !=, &&&, |||, &&, ||, !, {, }, .., ., ::, [, =, ], :, comma,
// (, ), ;, and whitespace.
matched:
{
Token token;
switch(c) {
case '+': {
if(c2 == '=') { // "+=".
token = new Token(TType.PLUS_ASSIGNMENT, "+=", target.copy());
i++;
} else if(c2 == '+') { // "++".
token = new Token(TType.INCREMENT, "++", target.copy());
i++;
} else { // "+".
token = new Token(TType.PLUS, "+", target.copy());
}
break;
}
case '-': {
if(c2 == '=') { // "-=".
token = new Token(TType.MINUS_ASSIGNMENT, "-=", target.copy());
i++;
} else if(c2 == '-') { // "--".
token = new Token(TType.DECREMENT, "--", target.copy());
i++;
} else if(c2 == '>') { // "->".
token = new Token(TType.DEREFERENCE, "->", target.copy());
i++;
} else { // "-".
token = new Token(TType.MINUS, "-", target.copy());
}
break;
}
case '*': {
if(c2 == '=') { // "*=".
token = new Token(TType.MULTIPLICATION_ASSIGNMENT, "*=", target.copy());
i++;
} else if(c2 == '*') { // "**".
token = new Token(TType.EXPONENTIAL, "**", target.copy());
i++;
} else { // "*".
token = new Token(TType.MULTIPLICATION, "*", target.copy());
}
break;
}
case '/': {
if(c2 == '=') { // "/=".
token = new Token(TType.DIVISION_ASSIGNMENT, "/=", target.copy());
i++;
} else { // "/".
// Protect against matching commands.
if(Character.isLetter(c2)) {
break matched; // Pretend that division didn't match.
}
token = new Token(TType.DIVISION, "/", target.copy());
}
break;
}
case '.': {
if(c2 == '=') { // ".=".
token = new Token(TType.CONCAT_ASSIGNMENT, ".=", target.copy());
i++;
} else if(c2 == '.' && c3 == '.') {
token = new Token(TType.VARARGS, "...", target.copy());
i += 2;
} else if(c2 == '.') { // "..".
token = new Token(TType.SLICE, "..", target.copy());
i++;
} else { // ".".
token = new Token(TType.DOT, ".", target.copy());
}
break;
}
case '%': {
token = new Token(TType.MODULO, "%", target.copy());
break;
}
case '>': {
if(c2 == '=') { // ">=".
token = new Token(TType.GTE, ">=", target.copy());
i++;
} else if(c2 == '>' && i < script.length() - 2 && script.charAt(i + 2) == '>') { // ">>>".
token = new Token(TType.MULTILINE_START, ">>>", target.copy());
inMultiline = true;
i += 2;
} else { // ">".
token = new Token(TType.GT, ">", target.copy());
}
break;
}
case '<': {
if(c2 == '!') { // "<!".
if(buf.length() > 0) {
tokenList.add(new Token(TType.UNKNOWN, buf.toString(), target));
buf = new StringBuilder();
target = new Target(lineNum, file, column);
}
if(saveAllTokens) {
tokenList.add(new Token(TType.FILE_OPTIONS_START, "<!", target.copy()));
}
inFileOptions = true;
fileOptionsLineNumberStart = lineNum;
i++;
continue;
} else if(c2 == '=') { // "<=".
token = new Token(TType.LTE, "<=", target.copy());
i++;
} else if(c2 == '<' && i < script.length() - 2 && script.charAt(i + 2) == '<') { // "<<<".
token = new Token(TType.MULTILINE_END, "<<<", target.copy());
inMultiline = false;
i += 2;
} else { // "<".
token = new Token(TType.LT, "<", target.copy());
}
break;
}
case '=': {
if(c2 == '=') {
if(i < script.length() - 2 && script.charAt(i + 2) == '=') { // "===".
token = new Token(TType.STRICT_EQUALS, "===", target.copy());
i += 2;
} else { // "==".
token = new Token(TType.EQUALS, "==", target.copy());
i++;
}
} else { // "=".
if(inCommand) {
if(inOptVar) {
token = new Token(TType.OPT_VAR_ASSIGN, "=", target.copy());
} else {
token = new Token(TType.ALIAS_END, "=", target.copy());
inCommand = false;
}
} else {
token = new Token(TType.ASSIGNMENT, "=", target.copy());
}
}
break;
}
case '!': {
if(c2 == '=') {
if(i < script.length() - 2 && script.charAt(i + 2) == '=') { // "!==".
token = new Token(TType.STRICT_NOT_EQUALS, "!==", target.copy());
i += 2;
} else { // "!=".
token = new Token(TType.NOT_EQUALS, "!=", target.copy());
i++;
}
} else { // "!".
token = new Token(TType.LOGICAL_NOT, "!", target.copy());
}
break;
}
case '&': {
if(c2 == '&') {
if(i < script.length() - 2 && script.charAt(i + 2) == '&') { // "&&&".
token = new Token(TType.DEFAULT_AND, "&&&", target.copy());
i += 2;
} else { // "&&".
token = new Token(TType.LOGICAL_AND, "&&", target.copy());
i++;
}
} else { // "&".
// Bitwise symbols are not used yet.
break matched; // Pretend that bitwise AND didn't match.
// token = new Token(TType.BIT_AND, "&", target);
}
break;
}
case '|': {
if(c2 == '|') {
if(i < script.length() - 2 && script.charAt(i + 2) == '|') { // "|||".
token = new Token(TType.DEFAULT_OR, "|||", target.copy());
i += 2;
} else { // "||".
token = new Token(TType.LOGICAL_OR, "||", target.copy());
i++;
}
} else { // "|".
// Bitwise symbols are not used yet.
break matched; // Pretend that bitwise OR didn't match.
// token = new Token(TType.BIT_OR, "|", target);
}
break;
}
// Bitwise symbols are not used yet.
// case '^': {
// token = new Token(TType.BIT_XOR, "^", target);
// break;
// }
case ':': {
if(c2 == ':') { // "::".
token = new Token(TType.DEREFERENCE, "::", target.copy());
i++;
} else { // ":".
token = new Token(TType.LABEL, ":", target.copy());
}
break;
}
case '{': {
token = new Token(TType.LCURLY_BRACKET, "{", target.copy());
break;
}
case '}': {
if(inAnnotation) {
// Eventually, this will no longer be a comment type, but for now, we just want
// to totally ignore annotations, as if they were comments.
inAnnotation = false;
token = new Token(/*TType.ANNOTATION*/TType.COMMENT, "@{" + buf.toString() + "}", target);
buf = new StringBuilder();
break;
}
token = new Token(TType.RCURLY_BRACKET, "}", target.copy());
break;
}
case '[': {
token = new Token(TType.LSQUARE_BRACKET, "[", target.copy());
inOptVar = true;
break;
}
case ']': {
token = new Token(TType.RSQUARE_BRACKET, "]", target.copy());
inOptVar = false;
break;
}
case ',': {
token = new Token(TType.COMMA, ",", target.copy());
break;
}
case ';': {
token = new Token(TType.SEMICOLON, ";", target.copy());
break;
}
case '(': {
token = new Token(TType.FUNC_START, "(", target.copy());
// Handle the buffer or previous token, with the knowledge that a FUNC_START follows.
if(buf.length() > 0) {
// In this case, we need to check for keywords first, because we want to go ahead
// and convert into that stage. In the future, we might want to do this
// unconditionally, but for now, just go ahead and only do it if saveAllTokens is
// true, because we know that won't be used by the compiler.
if(saveAllTokens && KeywordList.getKeywordByName(buf.toString()) != null) {
// It's a keyword.
tokenList.add(new Token(TType.KEYWORD, buf.toString(), target));
} else {
// It's not a keyword, but a normal function.
String funcName = buf.toString();
if(funcName.matches("[_a-zA-Z0-9]+")) {
tokenList.add(new Token(TType.FUNC_NAME, funcName, target));
} else {
tokenList.add(new Token(TType.UNKNOWN, funcName, target));
}
}
buf = new StringBuilder();
target = new Target(lineNum, file, column);
} else {
// The previous token, if unknown, should be changed to a FUNC_NAME. If it's not
// unknown, we may be doing standalone parenthesis, so auto tack on the __autoconcat__
// function.
try {
int count = 0;
Iterator<Token> it = tokenList.descendingIterator();
Token t;
while((t = it.next()).type == TType.WHITESPACE) {
count++;
}
if(t.type == TType.UNKNOWN) {
t.type = TType.FUNC_NAME;
// Go ahead and remove the whitespace here too, they break things.
count--;
for(int a = 0; a < count; a++) {
tokenList.removeLast();
}
}
} catch (NoSuchElementException e) {
// This is the first element on the list, so, it's another autoconcat.
}
}
break;
}
case ')': {
token = new Token(TType.FUNC_END, ")", target.copy());
break;
}
case ' ': { // Whitespace case #1.
token = new Token(TType.WHITESPACE, " ", target.copy());
break;
}
case '\t': { // Whitespace case #2 (TAB).
token = new Token(TType.WHITESPACE, "\t", target.copy());
break;
}
case '@': {
if(c2 == '{') {
inAnnotation = true;
i++;
continue;
}
break matched;
}
default: {
// No match was found at this point, so continue matching below.
break matched;
}
}
// Add previous characters as UNKNOWN token.
if(buf.length() > 0) {
tokenList.add(new Token(TType.UNKNOWN, buf.toString(), target));
buf = new StringBuilder();
target = new Target(lineNum, file, column);
}
// Add the new token to the token list.
tokenList.add(token);
// Continue lexing.
continue;
}
}
// Handle non-comment characters that might start or stop a quoted string.
switch(c) {
case '\'': {
if(stateInQuote && !inSmartQuote) {
validateTerminatedBidiSequence(buf.toString(), target);
tokenList.add(new Token(TType.STRING, buf.toString(), target));
buf = new StringBuilder();
target = new Target(lineNum, file, column);
stateInQuote = false;
continue;
} else if(!stateInQuote) {
stateInQuote = true;
quoteLineNumberStart = lineNum;
inSmartQuote = false;
if(buf.length() > 0) {
tokenList.add(new Token(TType.UNKNOWN, buf.toString(), target));
buf = new StringBuilder();
target = new Target(lineNum, file, column);
}
continue;
} else {
// We're in a smart quote.
buf.append("'");
}
break;
}
case '"': {
if(stateInQuote && inSmartQuote) {
validateTerminatedBidiSequence(buf.toString(), target);
tokenList.add(new Token(TType.SMART_STRING, buf.toString(), target));
buf = new StringBuilder();
target = new Target(lineNum, file, column);
stateInQuote = false;
inSmartQuote = false;
continue;
} else if(!stateInQuote) {
stateInQuote = true;
inSmartQuote = true;
smartQuoteLineNumberStart = lineNum;
if(buf.length() > 0) {
tokenList.add(new Token(TType.UNKNOWN, buf.toString(), target));
buf = new StringBuilder();
target = new Target(lineNum, file, column);
}
continue;
} else {
// We're in normal quotes.
buf.append('"');
}
break;
}
case '\n': {
// Append a newline to the buffer if it's quoted.
if(stateInQuote) {
buf.append(c);
} else {
// Newline is not quoted. Move the buffer to an UNKNOWN token and add a NEWLINE token.
if(buf.length() > 0) {
tokenList.add(new Token(TType.UNKNOWN, buf.toString(), target));
buf = new StringBuilder();
target = new Target(lineNum, file, column);
}
tokenList.add(new Token(TType.NEWLINE, "\n", target));
}
continue;
}
case '\\': {
// Handle escaped characters in quotes or a single "\" seperator token otherwise.
// Handle backslash character outside of quotes.
if(!stateInQuote) {
tokenList.add(new Token(TType.SEPERATOR, "\\", target));
break;
}
// Handle an escape sign in a quote.
switch(c2) {
case '\\':
if(inSmartQuote) {
// Escaping of '@' and '\' is handled within __smart_string__.
buf.append('\\');
}
buf.append('\\');
break;
case '\'':
case '"':
buf.append(c2);
break;
case 'n':
buf.append('\n');
break;
case 'r':
buf.append('\r');
break;
case 't':
buf.append('\t');
break;
case '0':
buf.append('\0');
break;
case 'f':
buf.append('\f');
break; // Form feed.
case 'v':
buf.append('\u000B');
break; // Vertical TAB.
case 'a':
buf.append('\u0007');
break; // Alarm.
case 'b':
buf.append('\u0008');
break; // Backspace.
case 'u': { // Unicode (4 characters).
// Grab the next 4 characters, and check to see if they are numbers.
if(i + 5 >= script.length()) {
throw new ConfigCompileException("Unrecognized unicode escape sequence", target);
}
String unicode = script.substring(i + 2, i + 6);
int unicodeNum;
try {
unicodeNum = Integer.parseInt(unicode, 16);
} catch (NumberFormatException e) {
throw new ConfigCompileException(
"Unrecognized unicode escape sequence: \\u" + unicode, target);
}
buf.append(Character.toChars(unicodeNum));
i += 4;
break;
}
case 'U': { // Unicode (8 characters).
// Grab the next 8 characters and check to see if they are numbers.
if(i + 9 >= script.length()) {
throw new ConfigCompileException("Unrecognized unicode escape sequence", target);
}
String unicode = script.substring(i + 2, i + 10);
int unicodeNum;
try {
unicodeNum = Integer.parseInt(unicode, 16);
} catch (NumberFormatException e) {
throw new ConfigCompileException(
"Unrecognized unicode escape sequence: \\u" + unicode, target);
}
buf.append(Character.toChars(unicodeNum));
i += 8;
break;
}
case '@': {
if(!inSmartQuote) {
throw new ConfigCompileException("The escape sequence \\@ is not"
+ " a recognized escape sequence in a non-smart string", target);
}
buf.append("\\@");
break;
}
default: {
// Since we might expand this list later, don't let them use unescaped backslashes.
throw new ConfigCompileException(
"The escape sequence \\" + c2 + " is not a recognized escape sequence", target);
}
}
i++;
continue;
}
default: {
// At this point, only non-comment and non-escaped characters that are not part of a
// quote start/end are left.
// Disallow Non-Breaking Space Characters.
if(!stateInQuote && c == '\u00A0'/*nbsp*/) {
throw new ConfigCompileException("NBSP character in script", target);
}
// Add the characters that didn't match anything to the buffer.
buf.append(c);
continue;
}
}
} // End of lexing.
// Handle unended file options.
if(inFileOptions) {
throw new ConfigCompileException("Unended file options. You started the the file options on line "
+ fileOptionsLineNumberStart, target);
}
// Handle unended string literals.
if(stateInQuote) {
if(inSmartQuote) {
throw new ConfigCompileException("Unended string literal. You started the last double quote on line "
+ smartQuoteLineNumberStart, target);
} else {
throw new ConfigCompileException("Unended string literal. You started the last single quote on line "
+ quoteLineNumberStart, target);
}
}
// Handle unended comment blocks. Since a newline is added to the end of the script, line comments are ended.
if(inComment || commentIsBlock) {
throw new ConfigCompileException("Unended block comment. You started the comment on line "
+ commentLineNumberStart, target);
}
// Look at the tokens and get meaning from them. Also, look for improper symbol locations
// and go ahead and absorb unary +- into the token.
ListIterator<Token> it = tokenList.listIterator(0);
while(it.hasNext()) {
Token t = it.next();
// Combine whitespace tokens into one.
if(t.type == TType.WHITESPACE && it.hasNext()) {
Token next;
if((next = it.next()).type == TType.WHITESPACE) {
t.value += next.val();
it.remove(); // Remove 'next'.
} else {
it.previous(); // Select 'next' <--.
}
it.previous(); // Select 't' <--.
it.next(); // Select 't' -->.
}
// Convert "-" + number to -number if allowed.
it.previous(); // Select 't' <--.
if(it.hasPrevious() && t.type == TType.UNKNOWN) {
Token prev1 = it.previous(); // Select 'prev1' <--.
if(prev1.type.isPlusMinus()) {
// Find the first non-whitespace token before the '-'.
Token prevNonWhitespace = null;
while(it.hasPrevious()) {
if(it.previous().type != TType.WHITESPACE) {
prevNonWhitespace = it.next();
break;
}
}
while(it.next() != prev1) { // Skip until selection is at 'prev1 -->'.
}
if(prevNonWhitespace != null) {
// Convert "±UNKNOWN" if the '±' is used as a sign (and not an add/subtract operation).
if(!prevNonWhitespace.type.isIdentifier() // Don't convert "number/string/var ± ...".
&& prevNonWhitespace.type != TType.FUNC_END // Don't convert "func() ± ...".
&& prevNonWhitespace.type != TType.RSQUARE_BRACKET // Don't convert "] ± ..." (arrays).
&& !IVAR_PATTERN.matcher(t.val()).matches() // Don't convert "± @var".
&& !VAR_PATTERN.matcher(t.val()).matches()) { // Don't convert "± $var".
// It is a negative/positive number: Absorb the sign.
t.value = prev1.value + t.value;
it.remove(); // Remove 'prev1'.
}
}
} else {
it.next(); // Select 'prev1' -->.
}
}
it.next(); // Select 't' -->.
// Assign a type to all UNKNOWN tokens.
if(t.type == TType.UNKNOWN) {
if(t.val().charAt(0) == '/' && t.val().length() > 1) {
t.type = TType.COMMAND;
} else if(t.val().equals("$")) {
t.type = TType.FINAL_VAR;
} else if(VAR_PATTERN.matcher(t.val()).matches()) {
t.type = TType.VARIABLE;
} else if(IVAR_PATTERN.matcher(t.val()).matches()) {
t.type = TType.IVARIABLE;
} else if(t.val().charAt(0) == '@') {
throw new ConfigCompileException("IVariables must match the regex: " + IVAR_PATTERN, t.getTarget());
} else if(keywords.contains(t.val())) {
t.type = TType.KEYWORD;
} else if(t.val().matches("[\t ]*")) {
t.type = TType.WHITESPACE;
} else {
t.type = TType.LIT;
}
}
// Skip this check if we're not in pure mscript.
if(inPureMScript) {
if(it.hasNext()) {
Token next = it.next(); // Select 'next' -->.
it.previous(); // Select 'next' <--.
it.previous(); // Select 't' <--.
if(t.type.isSymbol() && !t.type.isUnary() && !next.type.isUnary()) {
if(it.hasPrevious()) {
Token prev1 = it.previous(); // Select 'prev1' <--.
if(prev1.type.equals(TType.FUNC_START) || prev1.type.equals(TType.COMMA)
|| next.type.equals(TType.FUNC_END) || next.type.equals(TType.COMMA)
|| prev1.type.isSymbol() || next.type.isSymbol()) {
throw new ConfigCompileException("Unexpected symbol (" + t.val() + ")", t.getTarget());
}
it.next(); // Select 'prev1' -->.
}
}
it.next(); // Select 't' -->.
}
}
}
// Set file options
{
Map<String, String> defaults = new HashMap<>();
List<File> dirs = new ArrayList<>();
if(file != null) {
File f = file.getParentFile();
while(true) {
if(f == null) {
break;
}
File fileOptionDefaults = new File(f, ".msfileoptions");
if(fileOptionDefaults.exists()) {
dirs.add(fileOptionDefaults);
}
f = f.getParentFile();
}
}
Collections.reverse(dirs);
for(File d : dirs) {
try {
defaults.putAll(TokenStream.parseFileOptions(FileUtil.read(d), defaults).getRawOptions());
} catch (IOException ex) {
throw new ConfigCompileException("Cannot read " + d.getAbsolutePath(), Target.UNKNOWN, ex);
}
}
tokenList.setFileOptions(fileOptions.toString(), defaults);
}
// Make sure that the file options are the first non-comment code in the file
{
boolean foundCode = false;
for(Token t : tokenList) {