-
Notifications
You must be signed in to change notification settings - Fork 594
/
LexPerl.cxx
1851 lines (1778 loc) · 58 KB
/
LexPerl.cxx
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
// Scintilla source code edit control
/** @file LexPerl.cxx
** Lexer for Perl.
** Converted to lexer object by "Udo Lechner" <dlchnr(at)gmx(dot)net>
**/
// Copyright 1998-2008 by Neil Hodgson <neilh@scintilla.org>
// Lexical analysis fixes by Kein-Hong Man <mkh@pl.jaring.my>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>
#include <string>
#include <string_view>
#include <map>
#include <functional>
#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"
#include "WordList.h"
#include "LexAccessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"
#include "OptionSet.h"
#include "DefaultLexer.h"
using namespace Scintilla;
using namespace Lexilla;
// Info for HERE document handling from perldata.pod (reformatted):
// ----------------------------------------------------------------
// A line-oriented form of quoting is based on the shell ``here-doc'' syntax.
// Following a << you specify a string to terminate the quoted material, and
// all lines following the current line down to the terminating string are
// the value of the item.
// Prefixing the terminating string with a "~" specifies that you want to
// use "Indented Here-docs" (see below).
// * The terminating string may be either an identifier (a word), or some
// quoted text.
// * If quoted, the type of quotes you use determines the treatment of the
// text, just as in regular quoting.
// * An unquoted identifier works like double quotes.
// * There must be no space between the << and the identifier.
// (If you put a space it will be treated as a null identifier,
// which is valid, and matches the first empty line.)
// (This is deprecated, -w warns of this syntax)
// * The terminating string must appear by itself (unquoted and
// with no surrounding whitespace) on the terminating line.
//
// Indented Here-docs
// ------------------
// The here-doc modifier "~" allows you to indent your here-docs to
// make the code more readable.
// The delimiter is used to determine the exact whitespace to remove
// from the beginning of each line. All lines must have at least the
// same starting whitespace (except lines only containing a newline)
// or perl will croak. Tabs and spaces can be mixed, but are matched
// exactly. One tab will not be equal to 8 spaces!
// Additional beginning whitespace (beyond what preceded the
// delimiter) will be preserved.
#define HERE_DELIM_MAX 256 // maximum length of HERE doc delimiter
#define PERLNUM_BINARY 1 // order is significant: 1-3 cannot have a dot
#define PERLNUM_OCTAL 2
#define PERLNUM_FLOAT_EXP 3 // exponent part only
#define PERLNUM_HEX 4 // may be a hex float
#define PERLNUM_DECIMAL 5 // 1-5 are numbers; 6-7 are strings
#define PERLNUM_VECTOR 6
#define PERLNUM_V_VECTOR 7
#define PERLNUM_BAD 8
#define BACK_NONE 0 // lookback state for bareword disambiguation:
#define BACK_OPERATOR 1 // whitespace/comments are insignificant
#define BACK_KEYWORD 2 // operators/keywords are needed for disambiguation
#define SUB_BEGIN 0 // states for subroutine prototype scan:
#define SUB_HAS_PROTO 1 // only 'prototype' attribute allows prototypes
#define SUB_HAS_ATTRIB 2 // other attributes can exist leftward
#define SUB_HAS_MODULE 3 // sub name can have a ::identifier part
#define SUB_HAS_SUB 4 // 'sub' keyword
// all interpolated styles are different from their parent styles by a constant difference
// we also assume SCE_PL_STRING_VAR is the interpolated style with the smallest value
#define INTERPOLATE_SHIFT (SCE_PL_STRING_VAR - SCE_PL_STRING)
static bool isPerlKeyword(Sci_PositionU start, Sci_PositionU end, WordList &keywords, LexAccessor &styler) {
// old-style keyword matcher; needed because GetCurrent() needs
// current segment to be committed, but we may abandon early...
char s[100];
Sci_PositionU i, len = end - start;
if (len > 30) { len = 30; }
for (i = 0; i < len; i++, start++) s[i] = styler[start];
s[i] = '\0';
return keywords.InList(s);
}
static int disambiguateBareword(LexAccessor &styler, Sci_PositionU bk, Sci_PositionU fw,
int backFlag, Sci_PositionU backPos, Sci_PositionU endPos) {
// identifiers are recognized by Perl as barewords under some
// conditions, the following attempts to do the disambiguation
// by looking backward and forward; result in 2 LSB
int result = 0;
bool moreback = false; // true if passed newline/comments
bool brace = false; // true if opening brace found
// if BACK_NONE, neither operator nor keyword, so skip test
if (backFlag == BACK_NONE)
return result;
// first look backwards past whitespace/comments to set EOL flag
// (some disambiguation patterns must be on a single line)
if (backPos <= static_cast<Sci_PositionU>(styler.LineStart(styler.GetLine(bk))))
moreback = true;
// look backwards at last significant lexed item for disambiguation
bk = backPos - 1;
int ch = static_cast<unsigned char>(styler.SafeGetCharAt(bk));
if (ch == '{' && !moreback) {
// {bareword: possible variable spec
brace = true;
} else if ((ch == '&' && styler.SafeGetCharAt(bk - 1) != '&')
// &bareword: subroutine call
|| styler.Match(bk - 1, "->")
// ->bareword: part of variable spec
|| styler.Match(bk - 1, "::")
// ::bareword: part of module spec
|| styler.Match(bk - 2, "sub")) {
// sub bareword: subroutine declaration
// (implied BACK_KEYWORD, no keywords end in 'sub'!)
result |= 1;
}
// next, scan forward after word past tab/spaces only;
// if ch isn't one of '[{(,' we can skip the test
if ((ch == '{' || ch == '(' || ch == '['|| ch == ',')
&& fw < endPos) {
while (IsASpaceOrTab(ch = static_cast<unsigned char>(styler.SafeGetCharAt(fw)))
&& fw < endPos) {
fw++;
}
if ((ch == '}' && brace)
// {bareword}: variable spec
|| styler.Match(fw, "=>")) {
// [{(, bareword=>: hash literal
result |= 2;
}
}
return result;
}
static void skipWhitespaceComment(LexAccessor &styler, Sci_PositionU &p) {
// when backtracking, we need to skip whitespace and comments
while (p > 0) {
const int style = styler.StyleAt(p);
if (style != SCE_PL_DEFAULT && style != SCE_PL_COMMENTLINE)
break;
p--;
}
}
static int findPrevLexeme(LexAccessor &styler, Sci_PositionU &bk, int &style) {
// scan backward past whitespace and comments to find a lexeme
skipWhitespaceComment(styler, bk);
if (bk == 0)
return 0;
int sz = 1;
style = styler.StyleAt(bk);
while (bk > 0) { // find extent of lexeme
if (styler.StyleAt(bk - 1) == style) {
bk--; sz++;
} else
break;
}
return sz;
}
static int styleBeforeBracePair(LexAccessor &styler, Sci_PositionU bk) {
// backtrack to find open '{' corresponding to a '}', balanced
// return significant style to be tested for '/' disambiguation
int braceCount = 1;
if (bk == 0)
return SCE_PL_DEFAULT;
while (--bk > 0) {
if (styler.StyleAt(bk) == SCE_PL_OPERATOR) {
int bkch = static_cast<unsigned char>(styler.SafeGetCharAt(bk));
if (bkch == ';') { // early out
break;
} else if (bkch == '}') {
braceCount++;
} else if (bkch == '{') {
if (--braceCount == 0) break;
}
}
}
if (bk > 0 && braceCount == 0) {
// balanced { found, bk > 0, skip more whitespace/comments
bk--;
skipWhitespaceComment(styler, bk);
return styler.StyleAt(bk);
}
return SCE_PL_DEFAULT;
}
static int styleCheckIdentifier(LexAccessor &styler, Sci_PositionU bk) {
// backtrack to classify sub-styles of identifier under test
// return sub-style to be tested for '/' disambiguation
if (styler.SafeGetCharAt(bk) == '>') // inputsymbol, like <foo>
return 1;
// backtrack to check for possible "->" or "::" before identifier
while (bk > 0 && styler.StyleAt(bk) == SCE_PL_IDENTIFIER) {
bk--;
}
while (bk > 0) {
int bkstyle = styler.StyleAt(bk);
if (bkstyle == SCE_PL_DEFAULT
|| bkstyle == SCE_PL_COMMENTLINE) {
// skip whitespace, comments
} else if (bkstyle == SCE_PL_OPERATOR) {
// test for "->" and "::"
if (styler.Match(bk - 1, "->") || styler.Match(bk - 1, "::"))
return 2;
} else
return 3; // bare identifier
bk--;
}
return 0;
}
static int podLineScan(LexAccessor &styler, Sci_PositionU &pos, Sci_PositionU endPos) {
// forward scan the current line to classify line for POD style
int state = -1;
while (pos < endPos) {
int ch = static_cast<unsigned char>(styler.SafeGetCharAt(pos));
if (ch == '\n' || ch == '\r') {
if (ch == '\r' && styler.SafeGetCharAt(pos + 1) == '\n') pos++;
break;
}
if (IsASpaceOrTab(ch)) { // whitespace, take note
if (state == -1)
state = SCE_PL_DEFAULT;
} else if (state == SCE_PL_DEFAULT) { // verbatim POD line
state = SCE_PL_POD_VERB;
} else if (state != SCE_PL_POD_VERB) { // regular POD line
state = SCE_PL_POD;
}
pos++;
}
if (state == -1)
state = SCE_PL_DEFAULT;
return state;
}
static bool styleCheckSubPrototype(LexAccessor &styler, Sci_PositionU bk) {
// backtrack to identify if we're starting a subroutine prototype
// we also need to ignore whitespace/comments, format is like:
// sub abc::pqr :const :prototype(...)
// lexemes are tested in pairs, e.g. '::'+'pqr', ':'+'const', etc.
// and a state machine generates legal subroutine syntax matches
styler.Flush();
int state = SUB_BEGIN;
do {
// find two lexemes, lexeme 2 follows lexeme 1
int style2 = SCE_PL_DEFAULT;
Sci_PositionU pos2 = bk;
int len2 = findPrevLexeme(styler, pos2, style2);
int style1 = SCE_PL_DEFAULT;
Sci_PositionU pos1 = pos2;
if (pos1 > 0) pos1--;
int len1 = findPrevLexeme(styler, pos1, style1);
if (len1 == 0 || len2 == 0) // lexeme pair must exist
break;
// match parts of syntax, if invalid subroutine syntax, break off
if (style1 == SCE_PL_OPERATOR && len1 == 1 &&
styler.SafeGetCharAt(pos1) == ':') { // ':'
if (style2 == SCE_PL_IDENTIFIER || style2 == SCE_PL_WORD) {
if (len2 == 9 && styler.Match(pos2, "prototype")) { // ':' 'prototype'
if (state == SUB_BEGIN) {
state = SUB_HAS_PROTO;
} else
break;
} else { // ':' <attribute>
if (state == SUB_HAS_PROTO || state == SUB_HAS_ATTRIB) {
state = SUB_HAS_ATTRIB;
} else
break;
}
} else
break;
} else if (style1 == SCE_PL_OPERATOR && len1 == 2 &&
styler.Match(pos1, "::")) { // '::'
if (style2 == SCE_PL_IDENTIFIER) { // '::' <identifier>
state = SUB_HAS_MODULE;
} else
break;
} else if (style1 == SCE_PL_WORD && len1 == 3 &&
styler.Match(pos1, "sub")) { // 'sub'
if (style2 == SCE_PL_IDENTIFIER) { // 'sub' <identifier>
state = SUB_HAS_SUB;
} else
break;
} else
break;
bk = pos1; // set position for finding next lexeme pair
if (bk > 0) bk--;
} while (state != SUB_HAS_SUB);
return (state == SUB_HAS_SUB);
}
static int actualNumStyle(int numberStyle) {
if (numberStyle == PERLNUM_VECTOR || numberStyle == PERLNUM_V_VECTOR) {
return SCE_PL_STRING;
} else if (numberStyle == PERLNUM_BAD) {
return SCE_PL_ERROR;
}
return SCE_PL_NUMBER;
}
static int opposite(int ch) {
if (ch == '(') return ')';
if (ch == '[') return ']';
if (ch == '{') return '}';
if (ch == '<') return '>';
return ch;
}
static bool IsCommentLine(Sci_Position line, LexAccessor &styler) {
Sci_Position pos = styler.LineStart(line);
Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
for (Sci_Position i = pos; i < eol_pos; i++) {
char ch = styler[i];
int style = styler.StyleAt(i);
if (ch == '#' && style == SCE_PL_COMMENTLINE)
return true;
else if (!IsASpaceOrTab(ch))
return false;
}
return false;
}
static bool IsPackageLine(Sci_Position line, LexAccessor &styler) {
Sci_Position pos = styler.LineStart(line);
int style = styler.StyleAt(pos);
if (style == SCE_PL_WORD && styler.Match(pos, "package")) {
return true;
}
return false;
}
static int PodHeadingLevel(Sci_Position pos, LexAccessor &styler) {
int lvl = static_cast<unsigned char>(styler.SafeGetCharAt(pos + 5));
if (lvl >= '1' && lvl <= '4') {
return lvl - '0';
}
return 0;
}
// An individual named option for use in an OptionSet
// Options used for LexerPerl
struct OptionsPerl {
bool fold;
bool foldComment;
bool foldCompact;
// Custom folding of POD and packages
bool foldPOD; // fold.perl.pod
// Enable folding Pod blocks when using the Perl lexer.
bool foldPackage; // fold.perl.package
// Enable folding packages when using the Perl lexer.
bool foldCommentExplicit;
bool foldAtElse;
OptionsPerl() {
fold = false;
foldComment = false;
foldCompact = true;
foldPOD = true;
foldPackage = true;
foldCommentExplicit = true;
foldAtElse = false;
}
};
static const char *const perlWordListDesc[] = {
"Keywords",
0
};
struct OptionSetPerl : public OptionSet<OptionsPerl> {
OptionSetPerl() {
DefineProperty("fold", &OptionsPerl::fold);
DefineProperty("fold.comment", &OptionsPerl::foldComment);
DefineProperty("fold.compact", &OptionsPerl::foldCompact);
DefineProperty("fold.perl.pod", &OptionsPerl::foldPOD,
"Set to 0 to disable folding Pod blocks when using the Perl lexer.");
DefineProperty("fold.perl.package", &OptionsPerl::foldPackage,
"Set to 0 to disable folding packages when using the Perl lexer.");
DefineProperty("fold.perl.comment.explicit", &OptionsPerl::foldCommentExplicit,
"Set to 0 to disable explicit folding.");
DefineProperty("fold.perl.at.else", &OptionsPerl::foldAtElse,
"This option enables Perl folding on a \"} else {\" line of an if statement.");
DefineWordListSets(perlWordListDesc);
}
};
class LexerPerl : public DefaultLexer {
CharacterSet setWordStart;
CharacterSet setWord;
CharacterSet setSpecialVar;
CharacterSet setControlVar;
WordList keywords;
OptionsPerl options;
OptionSetPerl osPerl;
public:
LexerPerl() :
DefaultLexer("perl", SCLEX_PERL),
setWordStart(CharacterSet::setAlpha, "_", 0x80, true),
setWord(CharacterSet::setAlphaNum, "_", 0x80, true),
setSpecialVar(CharacterSet::setNone, "\"$;<>&`'+,./\\%:=~!?@[]"),
setControlVar(CharacterSet::setNone, "ACDEFHILMNOPRSTVWX") {
}
virtual ~LexerPerl() {
}
void SCI_METHOD Release() override {
delete this;
}
int SCI_METHOD Version() const override {
return lvRelease5;
}
const char *SCI_METHOD PropertyNames() override {
return osPerl.PropertyNames();
}
int SCI_METHOD PropertyType(const char *name) override {
return osPerl.PropertyType(name);
}
const char *SCI_METHOD DescribeProperty(const char *name) override {
return osPerl.DescribeProperty(name);
}
Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
const char * SCI_METHOD PropertyGet(const char *key) override {
return osPerl.PropertyGet(key);
}
const char *SCI_METHOD DescribeWordListSets() override {
return osPerl.DescribeWordListSets();
}
Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;
void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;
void *SCI_METHOD PrivateCall(int, void *) override {
return 0;
}
static ILexer5 *LexerFactoryPerl() {
return new LexerPerl();
}
int InputSymbolScan(StyleContext &sc);
void InterpolateSegment(StyleContext &sc, int maxSeg, bool isPattern=false);
};
Sci_Position SCI_METHOD LexerPerl::PropertySet(const char *key, const char *val) {
if (osPerl.PropertySet(&options, key, val)) {
return 0;
}
return -1;
}
Sci_Position SCI_METHOD LexerPerl::WordListSet(int n, const char *wl) {
WordList *wordListN = 0;
switch (n) {
case 0:
wordListN = &keywords;
break;
}
Sci_Position firstModification = -1;
if (wordListN) {
WordList wlNew;
wlNew.Set(wl);
if (*wordListN != wlNew) {
wordListN->Set(wl);
firstModification = 0;
}
}
return firstModification;
}
int LexerPerl::InputSymbolScan(StyleContext &sc) {
// forward scan for matching > on same line; file handles
int c, sLen = 0;
while ((c = sc.GetRelativeCharacter(++sLen)) != 0) {
if (c == '\r' || c == '\n') {
return 0;
} else if (c == '>') {
if (sc.Match("<=>")) // '<=>' case
return 0;
return sLen;
}
}
return 0;
}
void LexerPerl::InterpolateSegment(StyleContext &sc, int maxSeg, bool isPattern) {
// interpolate a segment (with no active backslashes or delimiters within)
// switch in or out of an interpolation style or continue current style
// commit variable patterns if found, trim segment, repeat until done
while (maxSeg > 0) {
bool isVar = false;
int sLen = 0;
if ((maxSeg > 1) && (sc.ch == '$' || sc.ch == '@')) {
// $#[$]*word [$@][$]*word (where word or {word} is always present)
bool braces = false;
sLen = 1;
if (sc.ch == '$' && sc.chNext == '#') { // starts with $#
sLen++;
}
while ((maxSeg > sLen) && (sc.GetRelativeCharacter(sLen) == '$')) // >0 $ dereference within
sLen++;
if ((maxSeg > sLen) && (sc.GetRelativeCharacter(sLen) == '{')) { // { start for {word}
sLen++;
braces = true;
}
if (maxSeg > sLen) {
int c = sc.GetRelativeCharacter(sLen);
if (setWordStart.Contains(c)) { // word (various)
sLen++;
isVar = true;
while (maxSeg > sLen) {
if (!setWord.Contains(sc.GetRelativeCharacter(sLen)))
break;
sLen++;
}
} else if (braces && IsADigit(c) && (sLen == 2)) { // digit for ${digit}
sLen++;
isVar = true;
}
}
if (braces) {
if ((maxSeg > sLen) && (sc.GetRelativeCharacter(sLen) == '}')) { // } end for {word}
sLen++;
} else
isVar = false;
}
}
if (!isVar && (maxSeg > 1)) { // $- or @-specific variable patterns
int c = sc.chNext;
if (sc.ch == '$') {
sLen = 1;
if (IsADigit(c)) { // $[0-9] and slurp trailing digits
sLen++;
isVar = true;
while ((maxSeg > sLen) && IsADigit(sc.GetRelativeCharacter(sLen)))
sLen++;
} else if (setSpecialVar.Contains(c)) { // $ special variables
sLen++;
isVar = true;
} else if (!isPattern && ((c == '(') || (c == ')') || (c == '|'))) { // $ additional
sLen++;
isVar = true;
} else if (c == '^') { // $^A control-char style
sLen++;
if ((maxSeg > sLen) && setControlVar.Contains(sc.GetRelativeCharacter(sLen))) {
sLen++;
isVar = true;
}
}
} else if (sc.ch == '@') {
sLen = 1;
if (!isPattern && ((c == '+') || (c == '-'))) { // @ specials non-pattern
sLen++;
isVar = true;
}
}
}
if (isVar) { // commit as interpolated variable or normal character
if (sc.state < SCE_PL_STRING_VAR)
sc.SetState(sc.state + INTERPOLATE_SHIFT);
sc.Forward(sLen);
maxSeg -= sLen;
} else {
if (sc.state >= SCE_PL_STRING_VAR)
sc.SetState(sc.state - INTERPOLATE_SHIFT);
sc.Forward();
maxSeg--;
}
}
if (sc.state >= SCE_PL_STRING_VAR)
sc.SetState(sc.state - INTERPOLATE_SHIFT);
}
void SCI_METHOD LexerPerl::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) {
LexAccessor styler(pAccess);
// keywords that forces /PATTERN/ at all times; should track vim's behaviour
WordList reWords;
reWords.Set("elsif if split while");
// charset classes
CharacterSet setSingleCharOp(CharacterSet::setNone, "rwxoRWXOezsfdlpSbctugkTBMAC");
// lexing of "%*</" operators is non-trivial; these are missing in the set below
CharacterSet setPerlOperator(CharacterSet::setNone, "^&\\()-+=|{}[]:;>,?!.~");
CharacterSet setQDelim(CharacterSet::setNone, "qrwx");
CharacterSet setModifiers(CharacterSet::setAlpha);
CharacterSet setPreferRE(CharacterSet::setNone, "*/<%");
// setArray and setHash also accepts chars for special vars like $_,
// which are then truncated when the next char does not match setVar
CharacterSet setVar(CharacterSet::setAlphaNum, "#$_'", 0x80, true);
CharacterSet setArray(CharacterSet::setAlpha, "#$_+-", 0x80, true);
CharacterSet setHash(CharacterSet::setAlpha, "#$_!^+-", 0x80, true);
CharacterSet &setPOD = setModifiers;
CharacterSet setNonHereDoc(CharacterSet::setDigits, "=$@");
CharacterSet setHereDocDelim(CharacterSet::setAlphaNum, "_");
CharacterSet setSubPrototype(CharacterSet::setNone, "\\[$@%&*+];_ \t");
CharacterSet setRepetition(CharacterSet::setDigits, ")\"'");
// for format identifiers
CharacterSet setFormatStart(CharacterSet::setAlpha, "_=");
CharacterSet &setFormat = setHereDocDelim;
// Lexer for perl often has to backtrack to start of current style to determine
// which characters are being used as quotes, how deeply nested is the
// start position and what the termination string is for HERE documents.
class HereDocCls { // Class to manage HERE doc sequence
public:
int State;
// 0: '<<' encountered
// 1: collect the delimiter
// 2: here doc text (lines after the delimiter)
int Quote; // the char after '<<'
bool Quoted; // true if Quote in ('\'','"','`')
bool StripIndent; // true if '<<~' requested to strip leading whitespace
int DelimiterLength; // strlen(Delimiter)
char Delimiter[HERE_DELIM_MAX]; // the Delimiter
HereDocCls() {
State = 0;
Quote = 0;
Quoted = false;
StripIndent = false;
DelimiterLength = 0;
Delimiter[0] = '\0';
}
void Append(int ch) {
Delimiter[DelimiterLength++] = static_cast<char>(ch);
Delimiter[DelimiterLength] = '\0';
}
~HereDocCls() {
}
};
HereDocCls HereDoc; // TODO: FIFO for stacked here-docs
class QuoteCls { // Class to manage quote pairs
public:
int Rep;
int Count;
int Up, Down;
QuoteCls() {
New(1);
}
void New(int r = 1) {
Rep = r;
Count = 0;
Up = '\0';
Down = '\0';
}
void Open(int u) {
Count++;
Up = u;
Down = opposite(Up);
}
};
QuoteCls Quote;
// additional state for number lexing
int numState = PERLNUM_DECIMAL;
int dotCount = 0;
Sci_PositionU endPos = startPos + length;
// Backtrack to beginning of style if required...
// If in a long distance lexical state, backtrack to find quote characters.
// Includes strings (may be multi-line), numbers (additional state), format
// bodies, as well as POD sections.
if (initStyle == SCE_PL_HERE_Q
|| initStyle == SCE_PL_HERE_QQ
|| initStyle == SCE_PL_HERE_QX
|| initStyle == SCE_PL_FORMAT
|| initStyle == SCE_PL_HERE_QQ_VAR
|| initStyle == SCE_PL_HERE_QX_VAR
) {
// backtrack through multiple styles to reach the delimiter start
int delim = (initStyle == SCE_PL_FORMAT) ? SCE_PL_FORMAT_IDENT:SCE_PL_HERE_DELIM;
while ((startPos > 1) && (styler.StyleAt(startPos) != delim)) {
startPos--;
}
startPos = styler.LineStart(styler.GetLine(startPos));
initStyle = styler.StyleAt(startPos - 1);
}
if (initStyle == SCE_PL_STRING
|| initStyle == SCE_PL_STRING_QQ
|| initStyle == SCE_PL_BACKTICKS
|| initStyle == SCE_PL_STRING_QX
|| initStyle == SCE_PL_REGEX
|| initStyle == SCE_PL_STRING_QR
|| initStyle == SCE_PL_REGSUBST
|| initStyle == SCE_PL_STRING_VAR
|| initStyle == SCE_PL_STRING_QQ_VAR
|| initStyle == SCE_PL_BACKTICKS_VAR
|| initStyle == SCE_PL_STRING_QX_VAR
|| initStyle == SCE_PL_REGEX_VAR
|| initStyle == SCE_PL_STRING_QR_VAR
|| initStyle == SCE_PL_REGSUBST_VAR
) {
// for interpolation, must backtrack through a mix of two different styles
int otherStyle = (initStyle >= SCE_PL_STRING_VAR) ?
initStyle - INTERPOLATE_SHIFT : initStyle + INTERPOLATE_SHIFT;
while (startPos > 1) {
int st = styler.StyleAt(startPos - 1);
if ((st != initStyle) && (st != otherStyle))
break;
startPos--;
}
initStyle = SCE_PL_DEFAULT;
} else if (initStyle == SCE_PL_STRING_Q
|| initStyle == SCE_PL_STRING_QW
|| initStyle == SCE_PL_XLAT
|| initStyle == SCE_PL_CHARACTER
|| initStyle == SCE_PL_NUMBER
|| initStyle == SCE_PL_IDENTIFIER
|| initStyle == SCE_PL_ERROR
|| initStyle == SCE_PL_SUB_PROTOTYPE
) {
while ((startPos > 1) && (styler.StyleAt(startPos - 1) == initStyle)) {
startPos--;
}
initStyle = SCE_PL_DEFAULT;
} else if (initStyle == SCE_PL_POD
|| initStyle == SCE_PL_POD_VERB
) {
// POD backtracking finds preceding blank lines and goes back past them
Sci_Position ln = styler.GetLine(startPos);
if (ln > 0) {
initStyle = styler.StyleAt(styler.LineStart(--ln));
if (initStyle == SCE_PL_POD || initStyle == SCE_PL_POD_VERB) {
while (ln > 0 && styler.GetLineState(ln) == SCE_PL_DEFAULT)
ln--;
}
startPos = styler.LineStart(++ln);
initStyle = styler.StyleAt(startPos - 1);
} else {
startPos = 0;
initStyle = SCE_PL_DEFAULT;
}
}
// backFlag, backPos are additional state to aid identifier corner cases.
// Look backwards past whitespace and comments in order to detect either
// operator or keyword. Later updated as we go along.
int backFlag = BACK_NONE;
Sci_PositionU backPos = startPos;
if (backPos > 0) {
backPos--;
skipWhitespaceComment(styler, backPos);
if (styler.StyleAt(backPos) == SCE_PL_OPERATOR)
backFlag = BACK_OPERATOR;
else if (styler.StyleAt(backPos) == SCE_PL_WORD)
backFlag = BACK_KEYWORD;
backPos++;
}
StyleContext sc(startPos, endPos - startPos, initStyle, styler);
for (; sc.More(); sc.Forward()) {
// Determine if the current state should terminate.
switch (sc.state) {
case SCE_PL_OPERATOR:
sc.SetState(SCE_PL_DEFAULT);
backFlag = BACK_OPERATOR;
backPos = sc.currentPos;
break;
case SCE_PL_IDENTIFIER: // identifier, bareword, inputsymbol
if ((!setWord.Contains(sc.ch) && sc.ch != '\'')
|| sc.Match('.', '.')
|| sc.chPrev == '>') { // end of inputsymbol
sc.SetState(SCE_PL_DEFAULT);
}
break;
case SCE_PL_WORD: // keyword, plus special cases
if (!setWord.Contains(sc.ch)) {
char s[100];
sc.GetCurrent(s, sizeof(s));
if ((strcmp(s, "__DATA__") == 0) || (strcmp(s, "__END__") == 0)) {
sc.ChangeState(SCE_PL_DATASECTION);
} else {
if ((strcmp(s, "format") == 0)) {
sc.SetState(SCE_PL_FORMAT_IDENT);
HereDoc.State = 0;
} else {
sc.SetState(SCE_PL_DEFAULT);
}
backFlag = BACK_KEYWORD;
backPos = sc.currentPos;
}
}
break;
case SCE_PL_SCALAR:
case SCE_PL_ARRAY:
case SCE_PL_HASH:
case SCE_PL_SYMBOLTABLE:
if (sc.Match(':', ':')) { // skip ::
sc.Forward();
} else if (!setVar.Contains(sc.ch)) {
if (sc.LengthCurrent() == 1) {
// Special variable: $(, $_ etc.
sc.Forward();
}
sc.SetState(SCE_PL_DEFAULT);
}
break;
case SCE_PL_NUMBER:
// if no early break, number style is terminated at "(go through)"
if (sc.ch == '.') {
if (sc.chNext == '.') {
// double dot is always an operator (go through)
} else if (numState <= PERLNUM_FLOAT_EXP) {
// non-decimal number or float exponent, consume next dot
sc.SetState(SCE_PL_OPERATOR);
break;
} else { // decimal or vectors allows dots
dotCount++;
if (numState == PERLNUM_DECIMAL) {
if (dotCount <= 1) // number with one dot in it
break;
if (IsADigit(sc.chNext)) { // really a vector
numState = PERLNUM_VECTOR;
break;
}
// number then dot (go through)
} else if (numState == PERLNUM_HEX) {
if (dotCount <= 1 && IsADigit(sc.chNext, 16)) {
break; // hex with one dot is a hex float
} else {
sc.SetState(SCE_PL_OPERATOR);
break;
}
// hex then dot (go through)
} else if (IsADigit(sc.chNext)) // vectors
break;
// vector then dot (go through)
}
} else if (sc.ch == '_') {
// permissive underscoring for number and vector literals
break;
} else if (numState == PERLNUM_DECIMAL) {
if (sc.ch == 'E' || sc.ch == 'e') { // exponent, sign
numState = PERLNUM_FLOAT_EXP;
if (sc.chNext == '+' || sc.chNext == '-') {
sc.Forward();
}
break;
} else if (IsADigit(sc.ch))
break;
// number then word (go through)
} else if (numState == PERLNUM_HEX) {
if (sc.ch == 'P' || sc.ch == 'p') { // hex float exponent, sign
numState = PERLNUM_FLOAT_EXP;
if (sc.chNext == '+' || sc.chNext == '-') {
sc.Forward();
}
break;
} else if (IsADigit(sc.ch, 16))
break;
// hex or hex float then word (go through)
} else if (numState == PERLNUM_VECTOR || numState == PERLNUM_V_VECTOR) {
if (IsADigit(sc.ch)) // vector
break;
if (setWord.Contains(sc.ch) && dotCount == 0) { // change to word
sc.ChangeState(SCE_PL_IDENTIFIER);
break;
}
// vector then word (go through)
} else if (IsADigit(sc.ch)) {
if (numState == PERLNUM_FLOAT_EXP) {
break;
} else if (numState == PERLNUM_OCTAL) {
if (sc.ch <= '7') break;
} else if (numState == PERLNUM_BINARY) {
if (sc.ch <= '1') break;
}
// mark invalid octal, binary numbers (go through)
numState = PERLNUM_BAD;
break;
}
// complete current number or vector
sc.ChangeState(actualNumStyle(numState));
sc.SetState(SCE_PL_DEFAULT);
break;
case SCE_PL_COMMENTLINE:
if (sc.atLineStart) {
sc.SetState(SCE_PL_DEFAULT);
}
break;
case SCE_PL_HERE_DELIM:
if (HereDoc.State == 0) { // '<<' encountered
int delim_ch = sc.chNext;
Sci_Position ws_skip = 0;
HereDoc.State = 1; // pre-init HERE doc class
HereDoc.Quote = sc.chNext;
HereDoc.Quoted = false;
HereDoc.StripIndent = false;
HereDoc.DelimiterLength = 0;
HereDoc.Delimiter[HereDoc.DelimiterLength] = '\0';
if (delim_ch == '~') { // was actually '<<~'
sc.Forward();
HereDoc.StripIndent = true;
HereDoc.Quote = delim_ch = sc.chNext;
}
if (IsASpaceOrTab(delim_ch)) {
// skip whitespace; legal only for quoted delimiters
Sci_PositionU i = sc.currentPos + 1;
while ((i < endPos) && IsASpaceOrTab(delim_ch)) {
i++;
delim_ch = static_cast<unsigned char>(styler.SafeGetCharAt(i));
}
ws_skip = i - sc.currentPos - 1;
}
if (delim_ch == '\'' || delim_ch == '"' || delim_ch == '`') {
// a quoted here-doc delimiter; skip any whitespace
sc.Forward(ws_skip + 1);
HereDoc.Quote = delim_ch;
HereDoc.Quoted = true;
} else if ((ws_skip == 0 && setNonHereDoc.Contains(sc.chNext))
|| ws_skip > 0) {
// left shift << or <<= operator cases
// restore position if operator
sc.ChangeState(SCE_PL_OPERATOR);
sc.ForwardSetState(SCE_PL_DEFAULT);
backFlag = BACK_OPERATOR;
backPos = sc.currentPos;
HereDoc.State = 0;
} else {
// specially handle initial '\' for identifier
if (ws_skip == 0 && HereDoc.Quote == '\\')
sc.Forward();
// an unquoted here-doc delimiter, no special handling
// (cannot be prefixed by spaces/tabs), or
// symbols terminates; deprecated zero-length delimiter
}
} else if (HereDoc.State == 1) { // collect the delimiter
backFlag = BACK_NONE;
if (HereDoc.Quoted) { // a quoted here-doc delimiter
if (sc.ch == HereDoc.Quote) { // closing quote => end of delimiter
sc.ForwardSetState(SCE_PL_DEFAULT);
} else if (!sc.atLineEnd) {
if (sc.Match('\\', static_cast<char>(HereDoc.Quote))) { // escaped quote
sc.Forward();
}
if (sc.ch != '\r') { // skip CR if CRLF
int i = 0; // else append char, possibly an extended char
while (i < sc.width) {
HereDoc.Append(static_cast<unsigned char>(styler.SafeGetCharAt(sc.currentPos + i)));
i++;
}
}
}
} else { // an unquoted here-doc delimiter, no extended charsets
if (setHereDocDelim.Contains(sc.ch)) {
HereDoc.Append(sc.ch);
} else {
sc.SetState(SCE_PL_DEFAULT);
}
}
if (HereDoc.DelimiterLength >= HERE_DELIM_MAX - 1) {
sc.SetState(SCE_PL_ERROR);
HereDoc.State = 0;
}
}
break;
case SCE_PL_HERE_Q:
case SCE_PL_HERE_QQ:
case SCE_PL_HERE_QX:
// also implies HereDoc.State == 2
sc.Complete();
if (HereDoc.StripIndent) {
// skip whitespace
while (IsASpaceOrTab(sc.ch) && !sc.atLineEnd)
sc.Forward();
}