-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLexNWScript.cpp
1113 lines (1050 loc) · 38.3 KB
/
LexNWScript.cpp
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
//:://////////////////////////////////////////////////////////////////////////////////////////////////////
/** NWScript custom Lexer
** @file LexNWScript.cpp
** previous filename: LexCPP.cpp
**
** Further folding features and configuration properties added by "Udo Lechner" <dlchnr(at)gmx(dot)net>
** Added extensions of NWScript language, changed name and class by "Leonardo Silva"
**/
// Copyright 1998-2005 by Neil Hodgson <neilh@scintilla.org>
// The License.txt file describes the conditions under which this software may be distributed.
//:://///////////////////////////////////////////////////////////////////////////////////////////////////
//:: Patched by Leonardo Silva
//:: File patched in Feb-2022 to adapt lexer for NWScript language
//:://///////////////////////////////////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "LexNWScript.h"
/*
*
* Implementations of LexNWScript class
*
*/
Sci_Position SCI_METHOD LexerNWScript::PropertySet(const char *key, const char *val) {
if (osNWScript.PropertySet(&options, key, val)) {
if (strcmp(key, "lexer.nwscript.allow.dollars") == 0) {
setWord = CharacterSet(CharacterSet::setAlphaNum, "._", 0x80, true);
if (options.identifiersAllowDollars) {
setWord.Add('$');
}
}
return 0;
}
return -1;
}
const char * SCI_METHOD LexerNWScript::PropertyGet(const char *key) {
return osNWScript.PropertyGet(key);
}
Sci_Position SCI_METHOD LexerNWScript::WordListSet(int n, const char *wl) {
WordList *wordListN = nullptr;
// All keywordClass(es) from LexNWScript.xml
switch (n) {
case 0:
wordListN = &keywordsInstructions; // instre1
break;
// case 1:
// wordListN = &keywordsInstr2; // instre2 - this list is unused by this lexer. Kept from original file
// break;
case 2:
wordListN = &keywordsCommonTypes; // type1
break;
case 3:
wordListN = &keywordsEngineTypes; // type2
break;
case 4:
wordListN = &keywordsObjectTypes; // type3
break;
case 5:
wordListN = &keywordsEngineConstants; // type4
break;
case 6:
wordListN = &keywordsUserConstants; // type5
break;
case 7:
wordListN = &keywordsEngineFunctions; // type6
break;
case 8:
wordListN = &keywordsUserFunctions; // type7
break;
}
Sci_Position firstModification = -1;
if (wordListN) {
WordList wlNew;
wlNew.Set(wl);
if (*wordListN != wlNew) {
wordListN->Set(wl);
firstModification = 0;
}
}
return firstModification;
}
void SCI_METHOD LexerNWScript::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) {
LexAccessor styler(pAccess);
CharacterSet setOKBeforeRE(CharacterSet::setNone, "([{=,:;!%^&*|?~+-");
CharacterSet setCouldBePostOp(CharacterSet::setNone, "+-");
CharacterSet setDoxygen(CharacterSet::setAlpha, "$@\\&<>#{}[]");
setWordStart = CharacterSet(CharacterSet::setAlpha, "_", 0x80, true);
CharacterSet setInvalidRawFirst(CharacterSet::setNone, " )\\\t\v\f\n");
if (options.identifiersAllowDollars) {
setWordStart.Add('$');
}
int chPrevNonWhite = ' ';
int visibleChars = 0;
bool lastWordWasUUID = false;
int styleBeforeDCKeyword = SCE_C_DEFAULT;
int styleBeforeTaskMarker = SCE_C_DEFAULT;
bool continuationLine = false;
bool isIncludePreprocessor = false;
bool isStringInPreprocessor = false;
bool inRERange = false;
bool seenDocKeyBrace = false;
Sci_Position lineCurrent = styler.GetLine(startPos);
if ((MaskActive(initStyle) == SCE_C_PREPROCESSOR) ||
(MaskActive(initStyle) == SCE_C_COMMENTLINE) ||
(MaskActive(initStyle) == SCE_C_COMMENTLINEDOC)) {
// Set continuationLine if last character of previous line is '\'
if (lineCurrent > 0) {
const Sci_Position endLinePrevious = styler.LineEnd(lineCurrent - 1);
if (endLinePrevious > 0) {
continuationLine = styler.SafeGetCharAt(endLinePrevious-1) == '\\';
}
}
}
// look back to set chPrevNonWhite properly for better regex colouring
if (startPos > 0) {
Sci_Position back = startPos;
while (--back && IsSpaceEquiv(MaskActive(styler.StyleAt(back))))
;
if (MaskActive(styler.StyleAt(back)) == SCE_C_OPERATOR) {
chPrevNonWhite = styler.SafeGetCharAt(back);
}
}
StyleContext sc(startPos, length, initStyle, styler);
LinePPState preproc = vlls.ForLine(lineCurrent);
bool definitionsChanged = false;
// Truncate ppDefineHistory before current line
if (!options.updatePreprocessor)
ppDefineHistory.clear();
std::vector<PPDefinition>::iterator itInvalid = std::find_if(ppDefineHistory.begin(), ppDefineHistory.end(),
[lineCurrent](const PPDefinition &p) noexcept { return p.line >= lineCurrent; });
if (itInvalid != ppDefineHistory.end()) {
ppDefineHistory.erase(itInvalid, ppDefineHistory.end());
definitionsChanged = true;
}
SymbolTable preprocessorDefinitions = preprocessorDefinitionsStart;
for (const PPDefinition &ppDef : ppDefineHistory) {
if (ppDef.isUndef)
preprocessorDefinitions.erase(ppDef.key);
else
preprocessorDefinitions[ppDef.key] = SymbolValue(ppDef.value, ppDef.arguments);
}
std::string rawStringTerminator = rawStringTerminators.ValueAt(lineCurrent-1);
SparseState<std::string> rawSTNew(lineCurrent);
int activitySet = preproc.ActiveState();
const WordClassifier &classifierIdentifiers = subStyles.Classifier(SCE_C_IDENTIFIER);
const WordClassifier &classifierDocKeyWords = subStyles.Classifier(SCE_C_COMMENTDOCKEYWORD);
Sci_PositionU lineEndNext = styler.LineEnd(lineCurrent);
for (; sc.More();) {
if (sc.atLineStart) {
// Using MaskActive() is not needed in the following statement.
// Inside inactive preprocessor declaration, state will be reset anyway at the end of this block.
if ((sc.state == SCE_C_STRING) || (sc.state == SCE_C_CHARACTER)) {
// Prevent SCE_C_STRINGEOL from leaking back to previous line which
// ends with a line continuation by locking in the state up to this position.
sc.SetState(sc.state);
}
if ((MaskActive(sc.state) == SCE_C_PREPROCESSOR) && (!continuationLine)) {
sc.SetState(SCE_C_DEFAULT|activitySet);
}
// reset states to beginning of colourise so no surprises
// if different sets of lines lexed.
visibleChars = 0;
lastWordWasUUID = false;
isIncludePreprocessor = false;
inRERange = false;
if (preproc.IsInactive()) {
activitySet = inactiveFlag;
sc.SetState(sc.state | activitySet);
}
}
if (sc.atLineEnd) {
lineCurrent++;
lineEndNext = styler.LineEnd(lineCurrent);
vlls.Add(lineCurrent, preproc);
if (rawStringTerminator != "") {
rawSTNew.Set(lineCurrent-1, rawStringTerminator);
}
}
// Handle line continuation generically.
if (sc.ch == '\\') {
if ((sc.currentPos+1) >= lineEndNext) {
lineCurrent++;
lineEndNext = styler.LineEnd(lineCurrent);
vlls.Add(lineCurrent, preproc);
if (rawStringTerminator != "") {
rawSTNew.Set(lineCurrent-1, rawStringTerminator);
}
sc.Forward();
if (sc.ch == '\r' && sc.chNext == '\n') {
// Even in UTF-8, \r and \n are separate
sc.Forward();
}
continuationLine = true;
sc.Forward();
continue;
}
}
const bool atLineEndBeforeSwitch = sc.atLineEnd;
// Determine if the current state should terminate.
switch (MaskActive(sc.state)) {
case SCE_C_OPERATOR:
sc.SetState(SCE_C_DEFAULT|activitySet);
break;
case SCE_C_NUMBER:
// We accept almost anything because of hex. and number suffixes
if (sc.ch == '_') {
sc.ChangeState(SCE_C_USERLITERAL|activitySet);
} else if (!(setWord.Contains(sc.ch)
|| (sc.ch == '\'')
|| ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E' ||
sc.chPrev == 'p' || sc.chPrev == 'P')))) {
sc.SetState(SCE_C_DEFAULT|activitySet);
}
break;
case SCE_C_USERLITERAL:
if (!(setWord.Contains(sc.ch)))
sc.SetState(SCE_C_DEFAULT|activitySet);
break;
case SCE_C_IDENTIFIER:
if (sc.atLineStart || sc.atLineEnd || !setWord.Contains(sc.ch) || (sc.ch == '.')) {
char s[1000];
if (caseSensitive) {
sc.GetCurrent(s, sizeof(s));
} else {
sc.GetCurrentLowered(s, sizeof(s));
}
if (keywordsInstructions.InList(s)) { // instre1 stylers.xml keywordClass from notepad++
lastWordWasUUID = strcmp(s, "uuid") == 0;
sc.ChangeState(SCE_C_WORD|activitySet);
} else if (keywordsInstr2.InList(s) || keywordsCommonTypes.InList(s)) { // notepad's instre2 or type1 (shared between langs)
sc.ChangeState(SCE_C_WORD2|activitySet);
} else if (keywordsEngineTypes.InList(s)) { // type2
sc.ChangeState(SCE_C_ENGINETYPE|activitySet);
} else if (keywordsObjectTypes.InList(s)) { // type3
sc.ChangeState(SCE_C_OBJECTTYPE|activitySet);
} else if (keywordsEngineConstants.InList(s)) { // type4
sc.ChangeState(SCE_C_ENGINECONSTANT|activitySet);
} else if (keywordsUserConstants.InList(s)) { // type5
sc.ChangeState(SCE_C_USERCONSTANT|activitySet);
} else if (keywordsEngineFunctions.InList(s)) { // type6
sc.ChangeState(SCE_C_ENGINEFUNCTION|activitySet);
} else if (keywordsUserFunctions.InList(s)) { // type7
sc.ChangeState(SCE_C_USERFUNCTION|activitySet);
} else {
int subStyle = classifierIdentifiers.ValueFor(s);
if (subStyle >= 0) {
sc.ChangeState(subStyle|activitySet);
}
}
const bool literalString = sc.ch == '\"';
if (literalString || sc.ch == '\'') {
size_t lenS = strlen(s);
const bool raw = literalString && sc.chPrev == 'R' && !setInvalidRawFirst.Contains(sc.chNext);
if (raw)
s[lenS--] = '\0';
const bool valid =
(lenS == 0) ||
((lenS == 1) && ((s[0] == 'L') || (s[0] == 'u') || (s[0] == 'U'))) ||
((lenS == 2) && literalString && (s[0] == 'u') && (s[1] == '8'));
if (valid) {
if (literalString) {
if (raw) {
// Set the style of the string prefix to SCE_C_STRINGRAW but then change to
// SCE_C_DEFAULT as that allows the raw string start code to run.
sc.ChangeState(SCE_C_STRINGRAW|activitySet);
sc.SetState(SCE_C_DEFAULT|activitySet);
} else {
sc.ChangeState(SCE_C_STRING|activitySet);
}
} else {
sc.ChangeState(SCE_C_CHARACTER|activitySet);
}
} else {
sc.SetState(SCE_C_DEFAULT | activitySet);
}
} else {
sc.SetState(SCE_C_DEFAULT|activitySet);
}
}
break;
case SCE_C_PREPROCESSOR:
if (options.stylingWithinPreprocessor) {
if (IsASpace(sc.ch) || (sc.ch == '(')) {
sc.SetState(SCE_C_DEFAULT|activitySet);
}
} else if (isStringInPreprocessor && (sc.Match('>') || sc.Match('\"') || sc.atLineEnd)) {
isStringInPreprocessor = false;
} else if (!isStringInPreprocessor) {
if ((isIncludePreprocessor && sc.Match('<')) || sc.Match('\"')) {
isStringInPreprocessor = true;
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) {
sc.SetState(SCE_C_PREPROCESSORCOMMENTDOC|activitySet);
} else {
sc.SetState(SCE_C_PREPROCESSORCOMMENT|activitySet);
}
sc.Forward(); // Eat the *
} else if (sc.Match('/', '/')) {
sc.SetState(SCE_C_DEFAULT|activitySet);
}
}
break;
case SCE_C_PREPROCESSORCOMMENT:
case SCE_C_PREPROCESSORCOMMENTDOC:
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_PREPROCESSOR|activitySet);
continue; // Without advancing in case of '\'.
}
break;
case SCE_C_COMMENT:
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
} else {
styleBeforeTaskMarker = SCE_C_COMMENT;
highlightTaskMarker(sc, styler, activitySet, markerList, caseSensitive);
}
break;
case SCE_C_COMMENTDOC:
if (sc.Match('*', '/')) {
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
} else if (sc.ch == '@' || sc.ch == '\\') { // JavaDoc and Doxygen support
// Verify that we have the conditions to mark a comment-doc-keyword
if ((IsASpace(sc.chPrev) || sc.chPrev == '*') && (!IsASpace(sc.chNext))) {
styleBeforeDCKeyword = SCE_C_COMMENTDOC;
sc.SetState(SCE_C_COMMENTDOCKEYWORD|activitySet);
}
}
break;
case SCE_C_COMMENTLINE:
if (sc.atLineStart && !continuationLine) {
sc.SetState(SCE_C_DEFAULT|activitySet);
} else {
styleBeforeTaskMarker = SCE_C_COMMENTLINE;
highlightTaskMarker(sc, styler, activitySet, markerList, caseSensitive);
}
break;
case SCE_C_COMMENTLINEDOC:
if (sc.atLineStart && !continuationLine) {
sc.SetState(SCE_C_DEFAULT|activitySet);
} else if (sc.ch == '@' || sc.ch == '\\') { // JavaDoc and Doxygen support
// Verify that we have the conditions to mark a comment-doc-keyword
if ((IsASpace(sc.chPrev) || sc.chPrev == '/' || sc.chPrev == '!') && (!IsASpace(sc.chNext))) {
styleBeforeDCKeyword = SCE_C_COMMENTLINEDOC;
sc.SetState(SCE_C_COMMENTDOCKEYWORD|activitySet);
}
}
break;
case SCE_C_COMMENTDOCKEYWORD:
if ((styleBeforeDCKeyword == SCE_C_COMMENTDOC) && sc.Match('*', '/')) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR);
sc.Forward();
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
seenDocKeyBrace = false;
} else if (sc.ch == '[' || sc.ch == '{') {
seenDocKeyBrace = true;
} else if (!setDoxygen.Contains(sc.ch)
&& !(seenDocKeyBrace && (sc.ch == ',' || sc.ch == '.'))) {
char s[100];
if (caseSensitive) {
sc.GetCurrent(s, sizeof(s));
} else {
sc.GetCurrentLowered(s, sizeof(s));
}
if (!(IsASpace(sc.ch) || (sc.ch == 0))) {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR|activitySet);
} else if (!keywordsCommonTypes.InList(s + 1)) {
int subStyleCDKW = classifierDocKeyWords.ValueFor(s+1);
if (subStyleCDKW >= 0) {
sc.ChangeState(subStyleCDKW|activitySet);
} else {
sc.ChangeState(SCE_C_COMMENTDOCKEYWORDERROR|activitySet);
}
}
sc.SetState(styleBeforeDCKeyword|activitySet);
seenDocKeyBrace = false;
}
break;
case SCE_C_STRING:
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL|activitySet);
} else if (isIncludePreprocessor) {
if (sc.ch == '>') {
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
isIncludePreprocessor = false;
}
} else if (sc.ch == '\\') {
if (options.escapeSequence) {
sc.SetState(SCE_C_ESCAPESEQUENCE|activitySet);
escapeSeq.resetEscapeState(sc.chNext);
}
sc.Forward(); // Skip all characters after the backslash
} else if (sc.ch == '\"') {
if (sc.chNext == '_') {
sc.ChangeState(SCE_C_USERLITERAL|activitySet);
} else {
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
}
}
break;
case SCE_C_ESCAPESEQUENCE:
escapeSeq.consumeDigit();
if (!escapeSeq.atEscapeEnd(sc.ch)) {
break;
}
if (sc.ch == '"') {
sc.SetState(SCE_C_STRING|activitySet);
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
} else if (sc.ch == '\\') {
escapeSeq.resetEscapeState(sc.chNext);
sc.Forward();
} else {
sc.SetState(SCE_C_STRING|activitySet);
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL|activitySet);
}
}
break;
case SCE_C_HASHQUOTEDSTRING:
if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\"') {
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
}
break;
case SCE_C_STRINGRAW:
if (sc.Match(rawStringTerminator.c_str())) {
for (size_t termPos=rawStringTerminator.size(); termPos; termPos--)
sc.Forward();
sc.SetState(SCE_C_DEFAULT|activitySet);
rawStringTerminator = "";
}
break;
case SCE_C_CHARACTER:
if (sc.atLineEnd) {
sc.ChangeState(SCE_C_STRINGEOL|activitySet);
} else if (sc.ch == '\\') {
if (sc.chNext == '\"' || sc.chNext == '\'' || sc.chNext == '\\') {
sc.Forward();
}
} else if (sc.ch == '\'') {
if (sc.chNext == '_') {
sc.ChangeState(SCE_C_USERLITERAL|activitySet);
} else {
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
}
}
break;
case SCE_C_REGEX:
if (sc.atLineStart) {
sc.SetState(SCE_C_DEFAULT|activitySet);
} else if (!inRERange && sc.ch == '/') {
sc.Forward();
while (IsLowerCase(sc.ch))
sc.Forward(); // gobble regex flags
sc.SetState(SCE_C_DEFAULT|activitySet);
} else if (sc.ch == '\\' && ((sc.currentPos+1) < lineEndNext)) {
// Gobble up the escaped character
sc.Forward();
} else if (sc.ch == '[') {
inRERange = true;
} else if (sc.ch == ']') {
inRERange = false;
}
break;
case SCE_C_STRINGEOL:
if (sc.atLineStart) {
sc.SetState(SCE_C_DEFAULT|activitySet);
}
break;
case SCE_C_VERBATIM:
if (options.verbatimStringsAllowEscapes && (sc.ch == '\\')) {
sc.Forward(); // Skip all characters after the backslash
} else if (sc.ch == '\"') {
if (sc.chNext == '\"') {
sc.Forward();
} else {
sc.ForwardSetState(SCE_C_DEFAULT|activitySet);
}
}
break;
case SCE_C_TRIPLEVERBATIM:
if (sc.Match(R"(""")")) {
while (sc.Match('"')) {
sc.Forward();
}
sc.SetState(SCE_C_DEFAULT|activitySet);
}
break;
case SCE_C_UUID:
if (sc.atLineEnd || sc.ch == ')') {
sc.SetState(SCE_C_DEFAULT|activitySet);
}
break;
case SCE_C_TASKMARKER:
if (isoperator(sc.ch) || IsASpace(sc.ch)) {
sc.SetState(styleBeforeTaskMarker|activitySet);
styleBeforeTaskMarker = SCE_C_DEFAULT;
}
}
if (sc.atLineEnd && !atLineEndBeforeSwitch) {
// State exit processing consumed characters up to end of line.
lineCurrent++;
lineEndNext = styler.LineEnd(lineCurrent);
vlls.Add(lineCurrent, preproc);
}
// Determine if a new state should be entered.
if (MaskActive(sc.state) == SCE_C_DEFAULT) {
if (sc.Match('@', '\"')) {
sc.SetState(SCE_C_VERBATIM|activitySet);
sc.Forward();
} else if (options.triplequotedStrings && sc.Match(R"(""")")) {
sc.SetState(SCE_C_TRIPLEVERBATIM|activitySet);
sc.Forward(2);
} else if (options.hashquotedStrings && sc.Match('#', '\"')) {
sc.SetState(SCE_C_HASHQUOTEDSTRING|activitySet);
sc.Forward();
} else if (options.backQuotedStrings && sc.Match('`')) {
sc.SetState(SCE_C_STRINGRAW|activitySet);
rawStringTerminator = "`";
} else if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID|activitySet);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_NUMBER|activitySet);
}
} else if (!sc.atLineEnd && (setWordStart.Contains(sc.ch) || (sc.ch == '@'))) {
if (lastWordWasUUID) {
sc.SetState(SCE_C_UUID|activitySet);
lastWordWasUUID = false;
} else {
sc.SetState(SCE_C_IDENTIFIER|activitySet);
}
} else if (sc.Match('/', '*')) {
if (sc.Match("/**") || sc.Match("/*!")) { // Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTDOC|activitySet);
} else {
sc.SetState(SCE_C_COMMENT|activitySet);
}
sc.Forward(); // Eat the * so it isn't used for the end of the comment
} else if (sc.Match('/', '/')) {
if ((sc.Match("///") && !sc.Match("////")) || sc.Match("//!"))
// Support of Qt/Doxygen doc. style
sc.SetState(SCE_C_COMMENTLINEDOC|activitySet);
else
sc.SetState(SCE_C_COMMENTLINE|activitySet);
} else if (sc.ch == '/'
&& (setOKBeforeRE.Contains(chPrevNonWhite)
|| followsReturnKeyword(sc, styler))
&& (!setCouldBePostOp.Contains(chPrevNonWhite)
|| !FollowsPostfixOperator(sc, styler))) {
sc.SetState(SCE_C_REGEX|activitySet); // JavaScript's RegEx
inRERange = false;
} else if (sc.ch == '\"') {
if (sc.chPrev == 'R') {
styler.Flush();
if (MaskActive(styler.StyleAt(sc.currentPos - 1)) == SCE_C_STRINGRAW) {
sc.SetState(SCE_C_STRINGRAW|activitySet);
rawStringTerminator = ")";
for (Sci_Position termPos = sc.currentPos + 1;; termPos++) {
const char chTerminator = styler.SafeGetCharAt(termPos, '(');
if (chTerminator == '(')
break;
rawStringTerminator += chTerminator;
}
rawStringTerminator += '\"';
} else {
sc.SetState(SCE_C_STRING|activitySet);
}
} else {
sc.SetState(SCE_C_STRING|activitySet);
}
isIncludePreprocessor = false; // ensure that '>' won't end the string
} else if (isIncludePreprocessor && sc.ch == '<') {
sc.SetState(SCE_C_STRING|activitySet);
} else if (sc.ch == '\'') {
sc.SetState(SCE_C_CHARACTER|activitySet);
} else if (sc.ch == '#' && visibleChars == 0) {
// Preprocessor commands are alone on their line
sc.SetState(SCE_C_PREPROCESSOR|activitySet);
// Skip whitespace between # and preprocessor word
do {
sc.Forward();
} while ((sc.ch == ' ' || sc.ch == '\t') && sc.More());
if (sc.atLineEnd) {
sc.SetState(SCE_C_DEFAULT|activitySet);
} else if (sc.Match("include")) {
isIncludePreprocessor = true;
} else {
if (options.trackPreprocessor) {
// If #if is nested too deeply (>31 levels) the active/inactive appearance
// will stop reflecting the code.
if (sc.Match("ifdef") || sc.Match("ifndef")) {
const bool isIfDef = sc.Match("ifdef");
const int startRest = isIfDef ? 5 : 6;
std::string restOfLine = GetRestOfLine(styler, sc.currentPos + startRest + 1, false);
bool foundDef = preprocessorDefinitions.find(restOfLine) != preprocessorDefinitions.end();
preproc.StartSection(isIfDef == foundDef);
} else if (sc.Match("if")) {
std::string restOfLine = GetRestOfLine(styler, sc.currentPos + 2, true);
const bool ifGood = EvaluateExpression(restOfLine, preprocessorDefinitions);
preproc.StartSection(ifGood);
} else if (sc.Match("else")) {
// #else is shown as active if either preceding or following section is active
// as that means that it contributed to the result.
if (!preproc.CurrentIfTaken()) {
// Inactive, may become active if parent scope active
assert(sc.state == (SCE_C_PREPROCESSOR|inactiveFlag));
preproc.InvertCurrentLevel();
activitySet = preproc.ActiveState();
// If following is active then show "else" as active
if (!activitySet)
sc.ChangeState(SCE_C_PREPROCESSOR);
} else if (preproc.IsActive()) {
// Active -> inactive
assert(sc.state == SCE_C_PREPROCESSOR);
preproc.InvertCurrentLevel();
activitySet = preproc.ActiveState();
// Continue to show "else" as active as it ends active section.
}
} else if (sc.Match("elif")) {
// Ensure only one chosen out of #if .. #elif .. #elif .. #else .. #endif
// #elif is shown as active if either preceding or following section is active
// as that means that it contributed to the result.
if (!preproc.CurrentIfTaken()) {
// Inactive, if expression true then may become active if parent scope active
assert(sc.state == (SCE_C_PREPROCESSOR|inactiveFlag));
// Similar to #if
std::string restOfLine = GetRestOfLine(styler, sc.currentPos + 4, true);
const bool ifGood = EvaluateExpression(restOfLine, preprocessorDefinitions);
if (ifGood) {
preproc.InvertCurrentLevel();
activitySet = preproc.ActiveState();
if (!activitySet)
sc.ChangeState(SCE_C_PREPROCESSOR);
}
} else if (preproc.IsActive()) {
// Active -> inactive
assert(sc.state == SCE_C_PREPROCESSOR);
preproc.InvertCurrentLevel();
activitySet = preproc.ActiveState();
// Continue to show "elif" as active as it ends active section.
}
} else if (sc.Match("endif")) {
preproc.EndSection();
activitySet = preproc.ActiveState();
sc.ChangeState(SCE_C_PREPROCESSOR|activitySet);
} else if (sc.Match("define")) {
if (options.updatePreprocessor && preproc.IsActive()) {
std::string restOfLine = GetRestOfLine(styler, sc.currentPos + 6, true);
size_t startName = 0;
while ((startName < restOfLine.length()) && IsSpaceOrTab(restOfLine[startName]))
startName++;
size_t endName = startName;
while ((endName < restOfLine.length()) && setWord.Contains(restOfLine[endName]))
endName++;
std::string key = restOfLine.substr(startName, endName-startName);
if ((endName < restOfLine.length()) && (restOfLine.at(endName) == '(')) {
// Macro
size_t endArgs = endName;
while ((endArgs < restOfLine.length()) && (restOfLine[endArgs] != ')'))
endArgs++;
std::string args = restOfLine.substr(endName + 1, endArgs - endName - 1);
size_t startValue = endArgs+1;
while ((startValue < restOfLine.length()) && IsSpaceOrTab(restOfLine[startValue]))
startValue++;
std::string value;
if (startValue < restOfLine.length())
value = restOfLine.substr(startValue);
preprocessorDefinitions[key] = SymbolValue(value, args);
ppDefineHistory.push_back(PPDefinition(lineCurrent, key, value, false, args));
definitionsChanged = true;
} else {
// Value
size_t startValue = endName;
while ((startValue < restOfLine.length()) && IsSpaceOrTab(restOfLine[startValue]))
startValue++;
std::string value = restOfLine.substr(startValue);
if (OnlySpaceOrTab(value))
value = "1"; // No value defaults to 1
preprocessorDefinitions[key] = value;
ppDefineHistory.push_back(PPDefinition(lineCurrent, key, value));
definitionsChanged = true;
}
}
} else if (sc.Match("undef")) {
if (options.updatePreprocessor && preproc.IsActive()) {
const std::string restOfLine = GetRestOfLine(styler, sc.currentPos + 5, false);
std::vector<std::string> tokens = Tokenize(restOfLine);
if (tokens.size() >= 1) {
const std::string key = tokens[0];
preprocessorDefinitions.erase(key);
ppDefineHistory.push_back(PPDefinition(lineCurrent, key, "", true));
definitionsChanged = true;
}
}
}
}
}
} else if (isoperator(sc.ch)) {
sc.SetState(SCE_C_OPERATOR|activitySet);
}
}
if (!IsASpace(sc.ch) && !IsSpaceEquiv(MaskActive(sc.state))) {
chPrevNonWhite = sc.ch;
visibleChars++;
}
continuationLine = false;
sc.Forward();
}
const bool rawStringsChanged = rawStringTerminators.Merge(rawSTNew, lineCurrent);
if (definitionsChanged || rawStringsChanged)
styler.ChangeLexerState(startPos, startPos + length);
sc.Complete();
}
// Store both the current line's fold level and the next lines in the
// level store to make it easy to pick up with each increment
// and to make it possible to fiddle the current level for "} else {".
void SCI_METHOD LexerNWScript::Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) {
if (!options.fold)
return;
LexAccessor styler(pAccess);
const Sci_PositionU endPos = startPos + length;
int visibleChars = 0;
bool inLineComment = false;
Sci_Position lineCurrent = styler.GetLine(startPos);
int levelCurrent = SC_FOLDLEVELBASE;
if (lineCurrent > 0)
levelCurrent = styler.LevelAt(lineCurrent-1) >> 16;
Sci_PositionU lineStartNext = styler.LineStart(lineCurrent+1);
int levelMinCurrent = levelCurrent;
int levelNext = levelCurrent;
char chNext = styler[startPos];
int styleNext = MaskActive(styler.StyleAt(startPos));
int style = MaskActive(initStyle);
const bool userDefinedFoldMarkers = !options.foldExplicitStart.empty() && !options.foldExplicitEnd.empty();
for (Sci_PositionU i = startPos; i < endPos; i++) {
const char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
const int stylePrev = style;
style = styleNext;
styleNext = MaskActive(styler.StyleAt(i + 1));
const bool atEOL = i == (lineStartNext-1);
if ((style == SCE_C_COMMENTLINE) || (style == SCE_C_COMMENTLINEDOC))
inLineComment = true;
if (options.foldComment && options.foldCommentMultiline && IsStreamCommentStyle(style) && !inLineComment) {
if (!IsStreamCommentStyle(stylePrev)) {
levelNext++;
} else if (!IsStreamCommentStyle(styleNext) && !atEOL) {
// Comments don't end at end of line and the next character may be unstyled.
levelNext--;
}
}
if (options.foldComment && options.foldCommentExplicit && ((style == SCE_C_COMMENTLINE) || options.foldExplicitAnywhere)) {
if (userDefinedFoldMarkers) {
if (styler.Match(i, options.foldExplicitStart.c_str())) {
levelNext++;
} else if (styler.Match(i, options.foldExplicitEnd.c_str())) {
levelNext--;
}
} else {
if ((ch == '/') && (chNext == '/')) {
const char chNext2 = styler.SafeGetCharAt(i + 2);
if (chNext2 == '{') {
levelNext++;
} else if (chNext2 == '}') {
levelNext--;
}
}
}
}
if (options.foldPreprocessor && (style == SCE_C_PREPROCESSOR)) {
if (ch == '#') {
Sci_PositionU j = i + 1;
while ((j < endPos) && IsASpaceOrTab(styler.SafeGetCharAt(j))) {
j++;
}
if (styler.Match(j, "region") || styler.Match(j, "if")) {
levelNext++;
} else if (styler.Match(j, "end")) {
levelNext--;
}
if (options.foldPreprocessorAtElse && (styler.Match(j, "else") || styler.Match(j, "elif"))) {
levelMinCurrent--;
}
}
}
if (options.foldSyntaxBased && (style == SCE_C_OPERATOR)) {
if (ch == '{' || ch == '[' || ch == '(') {
// Measure the minimum before a '{' to allow
// folding on "} else {"
if (options.foldAtElse && levelMinCurrent > levelNext) {
levelMinCurrent = levelNext;
}
levelNext++;
} else if (ch == '}' || ch == ']' || ch == ')') {
levelNext--;
}
}
if (!IsASpace(ch))
visibleChars++;
if (atEOL || (i == endPos-1)) {
int levelUse = levelCurrent;
if ((options.foldSyntaxBased && options.foldAtElse) ||
(options.foldPreprocessor && options.foldPreprocessorAtElse)
) {
levelUse = levelMinCurrent;
}
int lev = levelUse | levelNext << 16;
if (visibleChars == 0 && options.foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if (levelUse < levelNext)
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
lineStartNext = styler.LineStart(lineCurrent+1);
levelCurrent = levelNext;
levelMinCurrent = levelCurrent;
if (atEOL && (i == static_cast<Sci_PositionU>(styler.Length()-1))) {
// There is an empty line at end of file so give it same level and empty
styler.SetLevel(lineCurrent, (levelCurrent | levelCurrent << 16) | SC_FOLDLEVELWHITEFLAG);
}
visibleChars = 0;
inLineComment = false;
}
}
}
void LexerNWScript::EvaluateTokens(std::vector<std::string> &tokens, const SymbolTable &preprocessorDefinitions) {
// Remove whitespace tokens
tokens.erase(std::remove_if(tokens.begin(), tokens.end(), OnlySpaceOrTab), tokens.end());
// Evaluate defined statements to either 0 or 1
for (size_t i=0; (i+1)<tokens.size();) {
if (tokens[i] == "defined") {
const char *val = "0";
if (tokens[i+1] == "(") {
if (((i + 2)<tokens.size()) && (tokens[i + 2] == ")")) {
// defined()
tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 3);
} else if (((i+3)<tokens.size()) && (tokens[i+3] == ")")) {
// defined(<identifier>)
SymbolTable::const_iterator it = preprocessorDefinitions.find(tokens[i+2]);
if (it != preprocessorDefinitions.end()) {
val = "1";
}
tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 4);
} else {
// Spurious '(' so erase as more likely to result in false
tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 2);
}
} else {
// defined <identifier>
SymbolTable::const_iterator it = preprocessorDefinitions.find(tokens[i+1]);
if (it != preprocessorDefinitions.end()) {
val = "1";
}
tokens.erase(tokens.begin() + i + 1, tokens.begin() + i + 2);
}
tokens[i] = val;
} else {
i++;
}
}
// Evaluate identifiers
constexpr size_t maxIterations = 100;
size_t iterations = 0; // Limit number of iterations in case there is a recursive macro.
for (size_t i = 0; (i<tokens.size()) && (iterations < maxIterations);) {
iterations++;
if (setWordStart.Contains(tokens[i][0])) {
SymbolTable::const_iterator it = preprocessorDefinitions.find(tokens[i]);
if (it != preprocessorDefinitions.end()) {
// Tokenize value
std::vector<std::string> macroTokens = Tokenize(it->second.value);
if (it->second.IsMacro()) {
if ((i + 1 < tokens.size()) && (tokens.at(i + 1) == "(")) {
// Create map of argument name to value
std::vector<std::string> argumentNames = StringSplit(it->second.arguments, ',');
std::map<std::string, std::string> arguments;
size_t arg = 0;
size_t tok = i+2;
while ((tok < tokens.size()) && (arg < argumentNames.size()) && (tokens.at(tok) != ")")) {
if (tokens.at(tok) != ",") {
arguments[argumentNames.at(arg)] = tokens.at(tok);
arg++;
}
tok++;
}
// Remove invocation
tokens.erase(tokens.begin() + i, tokens.begin() + tok + 1);
// Substitute values into macro
macroTokens.erase(std::remove_if(macroTokens.begin(), macroTokens.end(), OnlySpaceOrTab), macroTokens.end());
for (size_t iMacro = 0; iMacro < macroTokens.size();) {
if (setWordStart.Contains(macroTokens[iMacro][0])) {
std::map<std::string, std::string>::const_iterator itFind = arguments.find(macroTokens[iMacro]);
if (itFind != arguments.end()) {
macroTokens[iMacro] = itFind->second;
}
}
iMacro++;
}
// Insert results back into tokens
tokens.insert(tokens.begin() + i, macroTokens.begin(), macroTokens.end());
} else {
i++;
}
} else {
// Remove invocation
tokens.erase(tokens.begin() + i);
// Insert results back into tokens
tokens.insert(tokens.begin() + i, macroTokens.begin(), macroTokens.end());
}
} else {
// Identifier not found and value defaults to zero
tokens[i] = "0";
}
} else {
i++;
}
}
// Find bracketed subexpressions and recurse on them
BracketPair bracketPair = FindBracketPair(tokens);
while (bracketPair.itBracket != tokens.end()) {
std::vector<std::string> inBracket(bracketPair.itBracket + 1, bracketPair.itEndBracket);
EvaluateTokens(inBracket, preprocessorDefinitions);
// The insertion is done before the removal because there were failures with the opposite approach
tokens.insert(bracketPair.itBracket, inBracket.begin(), inBracket.end());
bracketPair = FindBracketPair(tokens);
tokens.erase(bracketPair.itBracket, bracketPair.itEndBracket + 1);
bracketPair = FindBracketPair(tokens);
}
// Evaluate logical negations
for (size_t j=0; (j+1)<tokens.size();) {
if (setNegationOp.Contains(tokens[j][0])) {
int isTrue = atoi(tokens[j+1].c_str());
if (tokens[j] == "!")
isTrue = ~isTrue; // TEST: Changed to bitwise
std::vector<std::string>::iterator itInsert =
tokens.erase(tokens.begin() + j, tokens.begin() + j + 2);
tokens.insert(itInsert, isTrue ? "1" : "0");
} else {
j++;