Debian Codegraph @

scintilla/lexilla/lexers/LexPython.cxx

raw
1 // Scintilla source code edit control
2 /** @file LexPython.cxx
3 ** Lexer for Python.
4 **/
5 // Copyright 1998-2002 by Neil Hodgson <[email protected]>
6 // The License.txt file describes the conditions under which this software may be distributed.
7
8 #include <cstdlib>
9 #include <cassert>
10 #include <cstring>
11
12 #include <string>
13 #include <string_view>
14 #include <vector>
15 #include <map>
16 #include <algorithm>
17 #include <functional>
18
19 #include "ILexer.h"
20 #include "Scintilla.h"
21 #include "SciLexer.h"
22
23 #include "WordList.h"
24 #include "LexAccessor.h"
25 #include "Accessor.h"
26 #include "StyleContext.h"
27 #include "CharacterSet.h"
28 #include "CharacterCategory.h"
29 #include "LexerModule.h"
30 #include "OptionSet.h"
31 #include "SubStyles.h"
32 #include "DefaultLexer.h"
33
34 using namespace Scintilla;
35 using namespace Lexilla;
36
37 namespace {
38 // Use an unnamed namespace to protect the functions and classes from name conflicts
39
40 /* Notes on f-strings: f-strings are strings prefixed with f (e.g. f'') that may
41 have arbitrary expressions in {}. The tokens in the expressions are lexed as if
42 they were outside of any string. Expressions may contain { and } characters as
43 long as there is a closing } for every {, may be 2+ lines in a triple quoted
44 string, and may have a formatting specifier following a ! or :, but both !
45 and : are valid inside of a bracketed expression and != is a valid
46 expression token even outside of a bracketed expression.
47
48 When in an f-string expression, the lexer keeps track of the state value of
49 the f-string and the nesting count for the expression (# of [, (, { seen - # of
50 }, ), ] seen). f-strings may be nested (e.g. f'{ a + f"{1+2}"') so a stack of
51 states and nesting counts is kept. If a f-string expression continues beyond
52 the end of a line, this stack is saved in a std::map that maps a line number to
53 the stack at the end of that line. std::vector is used for the stack.
54
55 The PEP for f-strings is at https://www.python.org/dev/peps/pep-0498/
56 */
57 struct SingleFStringExpState {
58 int state;
59 int nestingCount;
60 };
61
62 /* kwCDef, kwCTypeName only used for Cython */
63 enum kwType { kwOther, kwClass, kwDef, kwImport, kwCDef, kwCTypeName, kwCPDef };
64
65 enum literalsAllowed { litNone = 0, litU = 1, litB = 2, litF = 4 };
66
67 constexpr int indicatorWhitespace = 1;
68
69 bool IsPyComment(Accessor &styler, Sci_Position pos, Sci_Position len) {
70 return len > 0 && styler[pos] == '#';
71 }
72
73 constexpr bool IsPyStringTypeChar(int ch, literalsAllowed allowed) noexcept {
74 return
75 ((allowed & litB) && (ch == 'b' || ch == 'B')) ||
76 ((allowed & litU) && (ch == 'u' || ch == 'U')) ||
77 ((allowed & litF) && (ch == 'f' || ch == 'F'));
78 }
79
80 constexpr bool IsQuote(int ch) {
81 return AnyOf(ch, '"', '\'');
82 }
83
84 constexpr bool IsRawPrefix(int ch) {
85 return AnyOf(ch, 'r', 'R');
86 }
87
88 bool IsPyStringStart(int ch, int chNext, int chNext2, literalsAllowed allowed) noexcept {
89 // To cover both python2 and python3 lex character prefixes as --
90 // ur'' is a string, but ru'' is not
91 // fr'', rf'', br'', rb'' are all strings
92 if (IsQuote(ch))
93 return true;
94 if (IsPyStringTypeChar(ch, allowed)) {
95 if (IsQuote(chNext))
96 return true;
97 if (IsRawPrefix(chNext) && IsQuote(chNext2))
98 return true;
99 }
100 if (IsRawPrefix(ch)) {
101 if (IsQuote(chNext))
102 return true;
103 if (IsPyStringTypeChar(chNext, allowed) && !AnyOf(chNext, 'u', 'U') && IsQuote(chNext2))
104 return true;
105 }
106
107 return false;
108 }
109
110 constexpr bool IsPyFStringState(int st) noexcept {
111 return AnyOf(st, SCE_P_FCHARACTER, SCE_P_FSTRING, SCE_P_FTRIPLE, SCE_P_FTRIPLEDOUBLE);
112 }
113
114 constexpr bool IsPySingleQuoteStringState(int st) noexcept {
115 return AnyOf(st, SCE_P_CHARACTER, SCE_P_STRING, SCE_P_FCHARACTER, SCE_P_FSTRING);
116 }
117
118 constexpr bool IsPyTripleQuoteStringState(int st) noexcept {
119 return AnyOf(st, SCE_P_TRIPLE, SCE_P_TRIPLEDOUBLE, SCE_P_FTRIPLE, SCE_P_FTRIPLEDOUBLE);
120 }
121
122 char GetPyStringQuoteChar(int st) noexcept {
123 if (AnyOf(st, SCE_P_CHARACTER, SCE_P_FCHARACTER, SCE_P_TRIPLE, SCE_P_FTRIPLE))
124 return '\'';
125 if (AnyOf(st, SCE_P_STRING, SCE_P_FSTRING, SCE_P_TRIPLEDOUBLE, SCE_P_FTRIPLEDOUBLE))
126 return '"';
127
128 return '\0';
129 }
130
131 void PushStateToStack(int state, std::vector<SingleFStringExpState> &stack, SingleFStringExpState *&currentFStringExp) {
132 const SingleFStringExpState single = {state, 0};
133 stack.push_back(single);
134
135 currentFStringExp = &stack.back();
136 }
137
138 int PopFromStateStack(std::vector<SingleFStringExpState> &stack, SingleFStringExpState *&currentFStringExp) noexcept {
139 int state = 0;
140
141 if (!stack.empty()) {
142 state = stack.back().state;
143 stack.pop_back();
144 }
145
146 if (stack.empty()) {
147 currentFStringExp = nullptr;
148 } else {
149 currentFStringExp = &stack.back();
150 }
151
152 return state;
153 }
154
155 /* Return the state to use for the string starting at i; *nextIndex will be set to the first index following the quote(s) */
156 int GetPyStringState(Accessor &styler, Sci_Position i, Sci_PositionU *nextIndex, literalsAllowed allowed) {
157 char ch = styler.SafeGetCharAt(i);
158 char chNext = styler.SafeGetCharAt(i + 1);
159 bool isFString = false;
160
161 // Advance beyond r, a type char, or both (in either order)
162 // Note that this depends on IsPyStringStart to enforce ru'' not being a string
163 if (IsRawPrefix(ch)) {
164 i++;
165 if (IsPyStringTypeChar(chNext, allowed)) {
166 if (AnyOf(chNext, 'f', 'F'))
167 isFString = true;
168 i++;
169 }
170 ch = styler.SafeGetCharAt(i);
171 chNext = styler.SafeGetCharAt(i + 1);
172 } else if (IsPyStringTypeChar(ch, allowed)) {
173 if (AnyOf(ch, 'f', 'F'))
174 isFString = true;
175 if (IsRawPrefix(chNext))
176 i += 2;
177 else
178 i += 1;
179 ch = styler.SafeGetCharAt(i);
180 chNext = styler.SafeGetCharAt(i + 1);
181 }
182
183 // ch and i will be the first quote
184 if (!IsQuote(ch)) {
185 *nextIndex = i + 1;
186 return SCE_P_DEFAULT;
187 }
188
189 if (ch == chNext && ch == styler.SafeGetCharAt(i + 2)) {
190 *nextIndex = i + 3;
191
192 if (ch == '"')
193 return (isFString ? SCE_P_FTRIPLEDOUBLE : SCE_P_TRIPLEDOUBLE);
194 else
195 return (isFString ? SCE_P_FTRIPLE : SCE_P_TRIPLE);
196 } else {
197 *nextIndex = i + 1;
198
199 if (ch == '"')
200 return (isFString ? SCE_P_FSTRING : SCE_P_STRING);
201 else
202 return (isFString ? SCE_P_FCHARACTER : SCE_P_CHARACTER);
203 }
204 }
205
206 bool IsAWordChar(int ch, bool unicodeIdentifiers) noexcept {
207 if (IsASCII(ch))
208 return (IsAlphaNumeric(ch) || ch == '.' || ch == '_');
209
210 if (!unicodeIdentifiers)
211 return false;
212
213 // Python uses the XID_Continue set from Unicode data
214 return IsXidContinue(ch);
215 }
216
217 bool IsAWordStart(int ch, bool unicodeIdentifiers) noexcept {
218 if (IsASCII(ch))
219 return (IsUpperOrLowerCase(ch) || ch == '_');
220
221 if (!unicodeIdentifiers)
222 return false;
223
224 // Python uses the XID_Start set from Unicode data
225 return IsXidStart(ch);
226 }
227
228 bool IsFirstNonWhitespace(Sci_Position pos, Accessor &styler) {
229 const Sci_Position line = styler.GetLine(pos);
230 const Sci_Position start_pos = styler.LineStart(line);
231 for (Sci_Position i = start_pos; i < pos; i++) {
232 const char ch = styler[i];
233 if (!IsASpaceOrTab(ch))
234 return false;
235 }
236 return true;
237 }
238
239 unsigned char GetNextNonWhitespaceChar(Accessor &styler, Sci_PositionU pos, Sci_PositionU maxPos, Sci_PositionU *charPosPtr = nullptr) {
240 while (pos < maxPos) {
241 const unsigned char ch = styler.SafeGetCharAt(pos, '\0');
242 if (!AnyOf(ch, ' ', '\t', '\n', '\r')) {
243 if (charPosPtr != nullptr) {
244 *charPosPtr = pos;
245 }
246 return ch;
247 }
248 pos++;
249 }
250
251 return '\0';
252 }
253
254 // Returns whether symbol is "match" or "case" and it is an identifier &
255 // not a keyword. Does not require the line to end with : so "match\n"
256 // and "match (x)\n" return false because match could be a keyword once
257 // more text is added
258 bool IsMatchOrCaseIdentifier(const StyleContext &sc, Accessor &styler, const char *symbol) {
259 if (strcmp(symbol, "match") != 0 && strcmp(symbol, "case") != 0) {
260 return false;
261 }
262
263 if (!IsFirstNonWhitespace(sc.currentPos - strlen(symbol), styler)) {
264 return true;
265 }
266
267 // The match keyword can be followed by an expression; the case keyword
268 // is a bit more restrictive but not much. Here, we look for the next
269 // char and return false if the char cannot start an expression; for '.'
270 // we look at the following char to see if it's a digit because .1 is a
271 // number
272 Sci_PositionU nextCharPos = 0;
273 const unsigned char nextChar = GetNextNonWhitespaceChar(styler, sc.currentPos, sc.lineEnd, &nextCharPos);
274 if (nextChar == '=' || nextChar == '#') {
275 return true;
276 }
277 if (nextChar == '.' && nextCharPos >= sc.currentPos) {
278 const unsigned char followingChar = GetNextNonWhitespaceChar(styler, nextCharPos+1, sc.lineEnd);
279 if (!IsADigit(followingChar)) {
280 return true;
281 }
282 }
283
284 return false;
285 }
286
287 // Options used for LexerPython
288 struct OptionsPython {
289 int whingeLevel = 0;
290 bool base2or8Literals = true;
291 bool stringsU = true;
292 bool stringsB = true;
293 bool stringsF = true;
294 bool stringsOverNewline = false;
295 bool keywords2NoSubIdentifiers = false;
296 bool fold = false;
297 bool foldQuotes = false;
298 bool foldCompact = false;
299 bool unicodeIdentifiers = true;
300 int identifierAttributes = 0;
301 int decoratorAttributes = 0;
302 bool pep701StringsF = true;
303
304 [[nodiscard]] literalsAllowed AllowedLiterals() const noexcept {
305 literalsAllowed allowedLiterals = stringsU ? litU : litNone;
306 if (stringsB)
307 allowedLiterals = static_cast<literalsAllowed>(allowedLiterals | litB);
308 if (stringsF)
309 allowedLiterals = static_cast<literalsAllowed>(allowedLiterals | litF);
310 return allowedLiterals;
311 }
312 };
313
314 const char *const pythonWordListDesc[] = {
315 "Keywords",
316 "Highlighted identifiers",
317 nullptr
318 };
319
320 struct OptionSetPython : public OptionSet<OptionsPython> {
321 OptionSetPython() {
322 DefineProperty("tab.timmy.whinge.level", &OptionsPython::whingeLevel,
323 "For Python code, checks whether indenting is consistent. "
324 "The default, 0 turns off indentation checking, "
325 "1 checks whether each line is potentially inconsistent with the previous line, "
326 "2 checks whether any space characters occur before a tab character in the indentation, "
327 "3 checks whether any spaces are in the indentation, and "
328 "4 checks for any tab characters in the indentation. "
329 "1 is a good level to use.");
330
331 DefineProperty("lexer.python.literals.binary", &OptionsPython::base2or8Literals,
332 "Set to 0 to not recognise Python 3 binary and octal literals: 0b1011 0o712.");
333
334 DefineProperty("lexer.python.strings.u", &OptionsPython::stringsU,
335 "Set to 0 to not recognise Python Unicode literals u\"x\" as used before Python 3.");
336
337 DefineProperty("lexer.python.strings.b", &OptionsPython::stringsB,
338 "Set to 0 to not recognise Python 3 bytes literals b\"x\".");
339
340 DefineProperty("lexer.python.strings.f", &OptionsPython::stringsF,
341 "Set to 0 to not recognise Python 3.6 f-string literals f\"var={var}\".");
342
343 DefineProperty("lexer.python.strings.f.pep.701", &OptionsPython::pep701StringsF,
344 "Set to 0 to use pre-PEP 701 / Python 3.12 f-string lexing.");
345
346 DefineProperty("lexer.python.strings.over.newline", &OptionsPython::stringsOverNewline,
347 "Set to 1 to allow strings to span newline characters.");
348
349 DefineProperty("lexer.python.keywords2.no.sub.identifiers", &OptionsPython::keywords2NoSubIdentifiers,
350 "When enabled, it will not style keywords2 items that are used as a sub-identifier. "
351 "Example: when set, will not highlight \"foo.open\" when \"open\" is a keywords2 item.");
352
353 DefineProperty("fold", &OptionsPython::fold);
354
355 DefineProperty("fold.quotes.python", &OptionsPython::foldQuotes,
356 "This option enables folding multi-line quoted strings when using the Python lexer.");
357
358 DefineProperty("fold.compact", &OptionsPython::foldCompact);
359
360 DefineProperty("lexer.python.unicode.identifiers", &OptionsPython::unicodeIdentifiers,
361 "Set to 0 to not recognise Python 3 Unicode identifiers.");
362
363 DefineProperty("lexer.python.identifier.attributes", &OptionsPython::identifierAttributes,
364 "Set to 1 to recognise Python identifier attributes.");
365
366 DefineProperty("lexer.python.decorator.attributes", &OptionsPython::decoratorAttributes,
367 "Set to 1 to recognise Python decorator attributes.");
368
369 DefineWordListSets(pythonWordListDesc);
370 }
371 };
372
373 const char styleSubable[] = { SCE_P_IDENTIFIER, 0 };
374
375 const LexicalClass lexicalClasses[] = {
376 // Lexer Python SCLEX_PYTHON SCE_P_:
377 0, "SCE_P_DEFAULT", "default", "White space",
378 1, "SCE_P_COMMENTLINE", "comment line", "Comment",
379 2, "SCE_P_NUMBER", "literal numeric", "Number",
380 3, "SCE_P_STRING", "literal string", "String",
381 4, "SCE_P_CHARACTER", "literal string", "Single quoted string",
382 5, "SCE_P_WORD", "keyword", "Keyword",
383 6, "SCE_P_TRIPLE", "literal string", "Triple quotes",
384 7, "SCE_P_TRIPLEDOUBLE", "literal string", "Triple double quotes",
385 8, "SCE_P_CLASSNAME", "identifier", "Class name definition",
386 9, "SCE_P_DEFNAME", "identifier", "Function or method name definition",
387 10, "SCE_P_OPERATOR", "operator", "Operators",
388 11, "SCE_P_IDENTIFIER", "identifier", "Identifiers",
389 12, "SCE_P_COMMENTBLOCK", "comment", "Comment-blocks",
390 13, "SCE_P_STRINGEOL", "error literal string", "End of line where string is not closed",
391 14, "SCE_P_WORD2", "identifier", "Highlighted identifiers",
392 15, "SCE_P_DECORATOR", "preprocessor", "Decorators",
393 16, "SCE_P_FSTRING", "literal string interpolated", "F-String",
394 17, "SCE_P_FCHARACTER", "literal string interpolated", "Single quoted f-string",
395 18, "SCE_P_FTRIPLE", "literal string interpolated", "Triple quoted f-string",
396 19, "SCE_P_FTRIPLEDOUBLE", "literal string interpolated", "Triple double quoted f-string",
397 20, "SCE_P_ATTRIBUTE", "identifier", "Attribute of identifier",
398 };
399
400 class LexerPython : public DefaultLexer {
401 WordList keywords;
402 WordList keywords2;
403 OptionsPython options;
404 OptionSetPython osPython;
405 enum { ssIdentifier };
406 SubStyles subStyles{styleSubable};
407 std::map<Sci_Position, std::vector<SingleFStringExpState> > ftripleStateAtEol;
408 public:
409 explicit LexerPython() :
410 DefaultLexer("python", SCLEX_PYTHON, lexicalClasses, std::size(lexicalClasses)) {
411 }
412 ~LexerPython() override = default;
413 void SCI_METHOD Release() override {
414 delete this;
415 }
416 int SCI_METHOD Version() const override {
417 return lvRelease5;
418 }
419 const char *SCI_METHOD PropertyNames() override {
420 return osPython.PropertyNames();
421 }
422 int SCI_METHOD PropertyType(const char *name) override {
423 return osPython.PropertyType(name);
424 }
425 const char *SCI_METHOD DescribeProperty(const char *name) override {
426 return osPython.DescribeProperty(name);
427 }
428 Sci_Position SCI_METHOD PropertySet(const char *key, const char *val) override;
429 const char *SCI_METHOD PropertyGet(const char *key) override {
430 return osPython.PropertyGet(key);
431 }
432 const char *SCI_METHOD DescribeWordListSets() override {
433 return osPython.DescribeWordListSets();
434 }
435 Sci_Position SCI_METHOD WordListSet(int n, const char *wl) override;
436 void SCI_METHOD Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;
437 void SCI_METHOD Fold(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) override;
438
439 void *SCI_METHOD PrivateCall(int, void *) override {
440 return nullptr;
441 }
442
443 int SCI_METHOD LineEndTypesSupported() override {
444 return SC_LINE_END_TYPE_UNICODE;
445 }
446
447 int SCI_METHOD AllocateSubStyles(int styleBase, int numberStyles) override {
448 return subStyles.Allocate(styleBase, numberStyles);
449 }
450 int SCI_METHOD SubStylesStart(int styleBase) override {
451 return subStyles.Start(styleBase);
452 }
453 int SCI_METHOD SubStylesLength(int styleBase) override {
454 return subStyles.Length(styleBase);
455 }
456 int SCI_METHOD StyleFromSubStyle(int subStyle) override {
457 const int styleBase = subStyles.BaseStyle(subStyle);
458 return styleBase;
459 }
460 int SCI_METHOD PrimaryStyleFromStyle(int style) override {
461 return style;
462 }
463 void SCI_METHOD FreeSubStyles() override {
464 subStyles.Free();
465 }
466 void SCI_METHOD SetIdentifiers(int style, const char *identifiers) override {
467 subStyles.SetIdentifiers(style, identifiers);
468 }
469 int SCI_METHOD DistanceToSecondaryStyles() override {
470 return 0;
471 }
472 const char *SCI_METHOD GetSubStyleBases() override {
473 return styleSubable;
474 }
475
476 static ILexer5 *LexerFactoryPython() {
477 return new LexerPython();
478 }
479
480 private:
481 void ProcessLineEnd(StyleContext &sc, std::vector<SingleFStringExpState> &fstringStateStack, SingleFStringExpState *&currentFStringExp, bool &inContinuedString);
482 };
483
484 Sci_Position SCI_METHOD LexerPython::PropertySet(const char *key, const char *val) {
485 if (osPython.PropertySet(&options, key, val)) {
486 return 0;
487 }
488 return -1;
489 }
490
491 Sci_Position SCI_METHOD LexerPython::WordListSet(int n, const char *wl) {
492 WordList *wordListN = nullptr;
493 switch (n) {
494 case 0:
495 wordListN = &keywords;
496 break;
497 case 1:
498 wordListN = &keywords2;
499 break;
500 default:
501 break;
502 }
503 Sci_Position firstModification = -1;
504 if (wordListN) {
505 if (wordListN->Set(wl)) {
506 firstModification = 0;
507 }
508 }
509 return firstModification;
510 }
511
512 void LexerPython::ProcessLineEnd(StyleContext &sc, std::vector<SingleFStringExpState> &fstringStateStack, SingleFStringExpState *&currentFStringExp, bool &inContinuedString) {
513 // Before pep 701 single quote f-string's could not continue to a 2nd+ line
514 // Post pep 701, they can continue both with a trailing \ and if a { field is
515 // not ended with a }
516 if (!options.pep701StringsF) {
517 long deepestSingleStateIndex = -1;
518 unsigned long i;
519
520 // Find the deepest single quote state because that string will end; no \ continuation in f-string
521 for (i = 0; i < fstringStateStack.size(); i++) {
522 if (IsPySingleQuoteStringState(fstringStateStack[i].state)) {
523 deepestSingleStateIndex = i;
524 break;
525 }
526 }
527
528 if (deepestSingleStateIndex != -1) {
529 sc.SetState(fstringStateStack[deepestSingleStateIndex].state);
530 while (fstringStateStack.size() > static_cast<unsigned long>(deepestSingleStateIndex)) {
531 PopFromStateStack(fstringStateStack, currentFStringExp);
532 }
533 }
534 }
535
536 if (!fstringStateStack.empty()) {
537 std::pair<Sci_Position, std::vector<SingleFStringExpState> > val;
538 val.first = sc.currentLine;
539 val.second = fstringStateStack;
540
541 ftripleStateAtEol.insert(val);
542 }
543
544 if ((sc.state == SCE_P_DEFAULT)
545 || IsPyTripleQuoteStringState(sc.state)) {
546 // Perform colourisation of white space and triple quoted strings at end of each line to allow
547 // tab marking to work inside white space and triple quoted strings
548 sc.SetState(sc.state);
549 }
550 if (IsPySingleQuoteStringState(sc.state)) {
551 if (inContinuedString || options.stringsOverNewline) {
552 inContinuedString = false;
553 } else {
554 sc.ChangeState(SCE_P_STRINGEOL);
555 sc.ForwardSetState(SCE_P_DEFAULT);
556 }
557 }
558 }
559
560 void SCI_METHOD LexerPython::Lex(Sci_PositionU startPos, Sci_Position length, int initStyle, IDocument *pAccess) {
561 Accessor styler(pAccess, nullptr);
562
563 // Track whether in f-string expression; vector is used for a stack to
564 // handle nested f-strings such as f"""{f'''{f"{f'{1}'}"}'''}"""
565 std::vector<SingleFStringExpState> fstringStateStack;
566 SingleFStringExpState *currentFStringExp = nullptr;
567
568 const Sci_Position endPos = startPos + length;
569
570 // Backtrack to previous line in case need to fix its tab whinging
571 Sci_Position lineCurrent = styler.GetLine(startPos);
572 if (startPos > 0) {
573 if (lineCurrent > 0) {
574 lineCurrent--;
575 // Look for backslash-continued lines
576 while (lineCurrent > 0) {
577 const Sci_Position eolPos = styler.LineStart(lineCurrent) - 1;
578 const int eolStyle = styler.StyleIndexAt(eolPos);
579 if (AnyOf(eolStyle, SCE_P_STRING, SCE_P_CHARACTER, SCE_P_STRINGEOL)) {
580 lineCurrent -= 1;
581 } else {
582 break;
583 }
584 }
585 startPos = styler.LineStart(lineCurrent);
586 }
587 initStyle = startPos == 0 ? SCE_P_DEFAULT : styler.StyleIndexAt(startPos - 1);
588 }
589
590 const literalsAllowed allowedLiterals = options.AllowedLiterals();
591
592 if (initStyle == SCE_P_STRINGEOL) {
593 initStyle = SCE_P_DEFAULT;
594 }
595
596 // Set up fstate stack from last line and remove any subsequent ftriple at eol states
597 std::map<Sci_Position, std::vector<SingleFStringExpState> >::iterator it;
598 it = ftripleStateAtEol.find(lineCurrent - 1);
599 if (it != ftripleStateAtEol.end() && !it->second.empty()) {
600 fstringStateStack = it->second;
601 currentFStringExp = &fstringStateStack.back();
602 }
603 it = ftripleStateAtEol.lower_bound(lineCurrent);
604 if (it != ftripleStateAtEol.end()) {
605 ftripleStateAtEol.erase(it, ftripleStateAtEol.end());
606 }
607
608 kwType kwLast = kwOther;
609 int spaceFlags = 0;
610 styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
611 bool base_n_number = false;
612
613 const WordClassifier &classifierIdentifiers = subStyles.Classifier(SCE_P_IDENTIFIER);
614
615 StyleContext sc(startPos, endPos - startPos, initStyle, styler);
616
617 bool indentGood = true;
618 Sci_Position startIndicator = sc.currentPos;
619 bool inContinuedString = false;
620
621 for (; sc.More(); sc.Forward()) {
622
623 if (sc.atLineStart) {
624 styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
625 indentGood = true;
626 if (options.whingeLevel == 1) {
627 indentGood = (spaceFlags & wsInconsistent) == 0;
628 } else if (options.whingeLevel == 2) {
629 indentGood = (spaceFlags & wsSpaceTab) == 0;
630 } else if (options.whingeLevel == 3) {
631 indentGood = (spaceFlags & wsSpace) == 0;
632 } else if (options.whingeLevel == 4) {
633 indentGood = (spaceFlags & wsTab) == 0;
634 }
635 if (!indentGood) {
636 styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 0);
637 startIndicator = sc.currentPos;
638 }
639 }
640
641 if (sc.atLineEnd) {
642 ProcessLineEnd(sc, fstringStateStack, currentFStringExp, inContinuedString);
643 lineCurrent++;
644 if (!sc.More())
645 break;
646 }
647
648 bool needEOLCheck = false;
649
650
651 if (sc.state == SCE_P_OPERATOR) {
652 kwLast = kwOther;
653 sc.SetState(SCE_P_DEFAULT);
654 } else if (sc.state == SCE_P_NUMBER) {
655 if (!IsAWordChar(sc.ch, false) &&
656 !(!base_n_number && ((sc.ch == '+' || sc.ch == '-') && (sc.chPrev == 'e' || sc.chPrev == 'E')))) {
657 sc.SetState(SCE_P_DEFAULT);
658 }
659 } else if (sc.state == SCE_P_IDENTIFIER) {
660 if ((sc.ch == '.') || (!IsAWordChar(sc.ch, options.unicodeIdentifiers))) {
661 char identifier[100];
662 sc.GetCurrent(identifier, sizeof(identifier));
663 int style = SCE_P_IDENTIFIER;
664 if ((kwLast == kwImport) && (strcmp(identifier, "as") == 0)) {
665 style = SCE_P_WORD;
666 } else if (keywords.InList(identifier) && !IsMatchOrCaseIdentifier(sc, styler, identifier)) {
667 style = SCE_P_WORD;
668 } else if (kwLast == kwClass) {
669 style = SCE_P_CLASSNAME;
670 } else if (kwLast == kwDef) {
671 style = SCE_P_DEFNAME;
672 } else if (kwLast == kwCDef || kwLast == kwCPDef) {
673 Sci_Position pos = sc.currentPos;
674 unsigned char ch = styler.SafeGetCharAt(pos, '\0');
675 while (ch != '\0') {
676 if (ch == '(') {
677 style = SCE_P_DEFNAME;
678 break;
679 } else if (ch == ':') {
680 style = SCE_P_CLASSNAME;
681 break;
682 } else if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') {
683 pos++;
684 ch = styler.SafeGetCharAt(pos, '\0');
685 } else {
686 break;
687 }
688 }
689 } else if (keywords2.InList(identifier)) {
690 if (options.keywords2NoSubIdentifiers) {
691 // We don't want to highlight keywords2
692 // that are used as a sub-identifier,
693 // i.e. not open in "foo.open".
694 const Sci_Position pos = styler.GetStartSegment() - 1;
695 if (pos < 0 || (styler.SafeGetCharAt(pos, '\0') != '.'))
696 style = SCE_P_WORD2;
697 } else {
698 style = SCE_P_WORD2;
699 }
700 } else {
701 const int subStyle = classifierIdentifiers.ValueFor(identifier);
702 if (subStyle >= 0) {
703 style = subStyle;
704 }
705 if (options.identifierAttributes > 0 || options.decoratorAttributes > 0) {
706 // Does the user even want attributes styled?
707 Sci_Position pos = styler.GetStartSegment() - 1;
708 unsigned char ch = styler.SafeGetCharAt(pos, '\0');
709 while (ch != '\0' && (ch == '.' || ch == ' ' || ch == '\\' || ch == '\t' || ch == '\n' || ch == '\r')) {
710 // Backwards search for a . while only allowing certain valid characters
711 if (IsAWordChar(ch, options.unicodeIdentifiers)) {
712 break;
713 }
714 pos--;
715 ch = styler.SafeGetCharAt(pos, '\0');
716 }
717 if (pos < 0 || ch == '.') {
718 // Is this an attribute we could style? if it is, do as asked
719 bool isComment = false;
720 bool isDecoratorAttribute = false;
721 const Sci_Position attrLine = styler.GetLine(pos);
722 for (Sci_Position i = styler.LineStart(attrLine); i < pos; i++) {
723 const char attrCh = styler[i];
724 if (attrCh == '@')
725 isDecoratorAttribute = true;
726 if (attrCh == '#')
727 isComment = true;
728 // Detect if this attribute belongs to a decorator
729 if (!IsASpaceOrTab(ch))
730 break;
731 }
732 if (((isDecoratorAttribute) && (!isComment)) && (((options.decoratorAttributes == 1) && (style == SCE_P_IDENTIFIER)) || (options.decoratorAttributes == 2))) {
733 // Style decorator attributes as decorators but respect already styled identifiers (unless requested to ignore already styled identifiers)
734 style = SCE_P_DECORATOR;
735 }
736 if (((!isDecoratorAttribute) && (!isComment)) && (((options.identifierAttributes == 1) && (style == SCE_P_IDENTIFIER)) || (options.identifierAttributes == 2))) {
737 // Style attributes and ignore decorator attributes but respect already styled identifiers (unless requested to ignore already styled identifiers)
738 style = SCE_P_ATTRIBUTE;
739 }
740 }
741 }
742 }
743 sc.ChangeState(style);
744 sc.SetState(SCE_P_DEFAULT);
745 if (style == SCE_P_WORD) {
746 if (0 == strcmp(identifier, "class"))
747 kwLast = kwClass;
748 else if (0 == strcmp(identifier, "def"))
749 kwLast = kwDef;
750 else if (0 == strcmp(identifier, "import"))
751 kwLast = kwImport;
752 else if (0 == strcmp(identifier, "cdef"))
753 kwLast = kwCDef;
754 else if (0 == strcmp(identifier, "cpdef"))
755 kwLast = kwCPDef;
756 else if (0 == strcmp(identifier, "cimport"))
757 kwLast = kwImport;
758 else if (kwLast != kwCDef && kwLast != kwCPDef)
759 kwLast = kwOther;
760 } else if (kwLast != kwCDef && kwLast != kwCPDef) {
761 kwLast = kwOther;
762 }
763 }
764 } else if ((sc.state == SCE_P_COMMENTLINE) || (sc.state == SCE_P_COMMENTBLOCK)) {
765 if (sc.ch == '\r' || sc.ch == '\n') {
766 sc.SetState(SCE_P_DEFAULT);
767 }
768 } else if (sc.state == SCE_P_DECORATOR) {
769 if (!IsAWordStart(sc.ch, options.unicodeIdentifiers)) {
770 sc.SetState(SCE_P_DEFAULT);
771 }
772 } else if (IsPySingleQuoteStringState(sc.state)) {
773 if (sc.ch == '\\') {
774 if ((sc.chNext == '\r') && (sc.GetRelative(2) == '\n')) {
775 sc.Forward();
776 }
777 if (sc.chNext == '\n' || sc.chNext == '\r') {
778 inContinuedString = true;
779 } else {
780 // Don't roll over the newline.
781 sc.Forward();
782 }
783 } else if (sc.ch == GetPyStringQuoteChar(sc.state)) {
784 sc.ForwardSetState(SCE_P_DEFAULT);
785 needEOLCheck = true;
786 }
787 } else if ((sc.state == SCE_P_TRIPLE) || (sc.state == SCE_P_FTRIPLE)) {
788 if (sc.ch == '\\') {
789 sc.Forward();
790 } else if (sc.Match(R"(''')")) {
791 sc.Forward();
792 sc.Forward();
793 sc.ForwardSetState(SCE_P_DEFAULT);
794 needEOLCheck = true;
795 }
796 } else if ((sc.state == SCE_P_TRIPLEDOUBLE) || (sc.state == SCE_P_FTRIPLEDOUBLE)) {
797 if (sc.ch == '\\') {
798 sc.Forward();
799 } else if (sc.Match(R"(""")")) {
800 sc.Forward();
801 sc.Forward();
802 sc.ForwardSetState(SCE_P_DEFAULT);
803 needEOLCheck = true;
804 }
805 }
806
807 // Note if used and not if else because string states also match
808 // some of the above clauses
809 if (IsPyFStringState(sc.state) && sc.ch == '{') {
810 if (sc.chNext == '{') {
811 sc.Forward();
812 } else {
813 PushStateToStack(sc.state, fstringStateStack, currentFStringExp);
814 sc.ForwardSetState(SCE_P_DEFAULT);
815 }
816 needEOLCheck = true;
817 }
818
819 // If in an f-string expression and pre pep 701 lexing is used,
820 // check for the ending quote(s) and end f-string to handle
821 // syntactically incorrect cases like f'{' and f"""{""". Post
822 // pep 701, a quote may appear in a { } field so cases like
823 // f"n = {":".join(seq)}" is valid
824 if (!options.pep701StringsF && !fstringStateStack.empty() && IsQuote(sc.ch)) {
825 long matching_stack_i = -1;
826 for (unsigned long stack_i = 0; stack_i < fstringStateStack.size() && matching_stack_i == -1; stack_i++) {
827 const int stack_state = fstringStateStack[stack_i].state;
828 const char quote = GetPyStringQuoteChar(stack_state);
829 if (sc.ch == quote) {
830 if (IsPySingleQuoteStringState(stack_state)) {
831 matching_stack_i = stack_i;
832 } else if (quote == '"' ? sc.Match(R"(""")") : sc.Match("'''")) {
833 matching_stack_i = stack_i;
834 }
835 }
836 }
837
838 if (matching_stack_i != -1) {
839 sc.SetState(fstringStateStack[matching_stack_i].state);
840 if (IsPyTripleQuoteStringState(fstringStateStack[matching_stack_i].state)) {
841 sc.Forward();
842 sc.Forward();
843 }
844 sc.ForwardSetState(SCE_P_DEFAULT);
845 needEOLCheck = true;
846
847 while (fstringStateStack.size() > static_cast<unsigned long>(matching_stack_i)) {
848 PopFromStateStack(fstringStateStack, currentFStringExp);
849 }
850 }
851 }
852 // End of code to find the end of a state
853
854 if (!indentGood && !IsASpaceOrTab(sc.ch)) {
855 styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 1);
856 startIndicator = sc.currentPos;
857 indentGood = true;
858 }
859
860 // One cdef or cpdef line, clear kwLast only at end of line
861 if ((kwLast == kwCDef || kwLast == kwCPDef) && sc.atLineEnd) {
862 kwLast = kwOther;
863 }
864
865 // State exit code may have moved on to end of line
866 if (needEOLCheck && sc.atLineEnd) {
867 ProcessLineEnd(sc, fstringStateStack, currentFStringExp, inContinuedString);
868 lineCurrent++;
869 styler.IndentAmount(lineCurrent, &spaceFlags, IsPyComment);
870 if (!sc.More())
871 break;
872 }
873
874 // If in f-string expression, check for }, :, ! to resume f-string state or update nesting count
875 if (currentFStringExp && !IsPySingleQuoteStringState(sc.state) && !IsPyTripleQuoteStringState(sc.state)) {
876 if (currentFStringExp->nestingCount == 0 && (sc.ch == '}' || sc.ch == ':' || (sc.ch == '!' && sc.chNext != '='))) {
877 sc.SetState(PopFromStateStack(fstringStateStack, currentFStringExp));
878 } else {
879 if (sc.ch == '{' || sc.ch == '[' || sc.ch == '(') {
880 currentFStringExp->nestingCount++;
881 } else if (sc.ch == '}' || sc.ch == ']' || sc.ch == ')') {
882 currentFStringExp->nestingCount--;
883 }
884 }
885 }
886
887 // Check for a new state starting character
888 if (sc.state == SCE_P_DEFAULT) {
889 if (IsADigit(sc.ch) || (sc.ch == '.' && IsADigit(sc.chNext))) {
890 if (sc.ch == '0' && (sc.chNext == 'x' || sc.chNext == 'X')) {
891 base_n_number = true;
892 sc.SetState(SCE_P_NUMBER);
893 } else if (sc.ch == '0' &&
894 (sc.chNext == 'o' || sc.chNext == 'O' || sc.chNext == 'b' || sc.chNext == 'B')) {
895 if (options.base2or8Literals) {
896 base_n_number = true;
897 sc.SetState(SCE_P_NUMBER);
898 } else {
899 sc.SetState(SCE_P_NUMBER);
900 sc.ForwardSetState(SCE_P_IDENTIFIER);
901 }
902 } else {
903 base_n_number = false;
904 sc.SetState(SCE_P_NUMBER);
905 }
906 } else if (isoperator(sc.ch) || sc.ch == '`') {
907 sc.SetState(SCE_P_OPERATOR);
908 } else if (sc.ch == '#') {
909 sc.SetState(sc.chNext == '#' ? SCE_P_COMMENTBLOCK : SCE_P_COMMENTLINE);
910 } else if (sc.ch == '@') {
911 if (IsFirstNonWhitespace(sc.currentPos, styler))
912 sc.SetState(SCE_P_DECORATOR);
913 else
914 sc.SetState(SCE_P_OPERATOR);
915 } else if (IsPyStringStart(sc.ch, sc.chNext, sc.GetRelative(2), allowedLiterals)) {
916 Sci_PositionU nextIndex = 0;
917 sc.SetState(GetPyStringState(styler, sc.currentPos, &nextIndex, allowedLiterals));
918 while (nextIndex > (sc.currentPos + 1) && sc.More()) {
919 sc.Forward();
920 }
921 } else if (IsAWordStart(sc.ch, options.unicodeIdentifiers)) {
922 sc.SetState(SCE_P_IDENTIFIER);
923 }
924 }
925 }
926 styler.IndicatorFill(startIndicator, sc.currentPos, indicatorWhitespace, 0);
927 sc.Complete();
928 }
929
930 bool IsCommentLine(Sci_Position line, Accessor &styler) {
931 const Sci_Position pos = styler.LineStart(line);
932 const Sci_Position eol_pos = styler.LineStart(line + 1) - 1;
933 for (Sci_Position i = pos; i < eol_pos; i++) {
934 const char ch = styler[i];
935 if (ch == '#')
936 return true;
937 if (!IsASpaceOrTab(ch))
938 return false;
939 }
940 return false;
941 }
942
943 bool IsQuoteLine(Sci_Position line, const Accessor &styler) {
944 const int style = styler.StyleIndexAt(styler.LineStart(line));
945 return IsPyTripleQuoteStringState(style);
946 }
947
948
949 void SCI_METHOD LexerPython::Fold(Sci_PositionU startPos, Sci_Position length, int /*initStyle - unused*/, IDocument *pAccess) {
950 if (!options.fold)
951 return;
952
953 Accessor styler(pAccess, nullptr);
954
955 const Sci_Position maxPos = startPos + length;
956 const Sci_Position maxLines = (maxPos == styler.Length()) ? styler.GetLine(maxPos) : styler.GetLine(maxPos - 1); // Requested last line
957 const Sci_Position docLines = styler.GetLine(styler.Length()); // Available last line
958
959 // Backtrack to previous non-blank line so we can determine indent level
960 // for any white space lines (needed esp. within triple quoted strings)
961 // and so we can fix any preceding fold level (which is why we go back
962 // at least one line in all cases)
963 int spaceFlags = 0;
964 Sci_Position lineCurrent = styler.GetLine(startPos);
965 int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, nullptr);
966 while (lineCurrent > 0) {
967 lineCurrent--;
968 indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, nullptr);
969 if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG) &&
970 (!IsCommentLine(lineCurrent, styler)) &&
971 (!IsQuoteLine(lineCurrent, styler)))
972 break;
973 }
974 int indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
975
976 // Set up initial loop state
977 startPos = styler.LineStart(lineCurrent);
978 int prev_state = SCE_P_DEFAULT;
979 if (lineCurrent >= 1)
980 prev_state = styler.StyleIndexAt(startPos - 1);
981 int prevQuote = options.foldQuotes && IsPyTripleQuoteStringState(prev_state);
982
983 // Process all characters to end of requested range or end of any triple quote
984 //that hangs over the end of the range. Cap processing in all cases
985 // to end of document (in case of unclosed quote at end).
986 while ((lineCurrent <= docLines) && ((lineCurrent <= maxLines) || prevQuote)) {
987
988 // Gather info
989 int lev = indentCurrent;
990 Sci_Position lineNext = lineCurrent + 1;
991 int indentNext = indentCurrent;
992 int quote = false;
993 if (lineNext <= docLines) {
994 // Information about next line is only available if not at end of document
995 indentNext = styler.IndentAmount(lineNext, &spaceFlags, nullptr);
996 const Sci_Position lookAtPos = (styler.LineStart(lineNext) == styler.Length()) ? styler.Length() - 1 : styler.LineStart(lineNext);
997 const int style = styler.StyleIndexAt(lookAtPos);
998 quote = options.foldQuotes && IsPyTripleQuoteStringState(style);
999 }
1000 const bool quote_start = (quote && !prevQuote);
1001 const bool quote_continue = (quote && prevQuote);
1002 if (!quote || !prevQuote)
1003 indentCurrentLevel = indentCurrent & SC_FOLDLEVELNUMBERMASK;
1004 if (quote)
1005 indentNext = indentCurrentLevel;
1006 if (indentNext & SC_FOLDLEVELWHITEFLAG)
1007 indentNext = SC_FOLDLEVELWHITEFLAG | indentCurrentLevel;
1008
1009 if (quote_start) {
1010 // Place fold point at start of triple quoted string
1011 lev |= SC_FOLDLEVELHEADERFLAG;
1012 } else if (quote_continue || prevQuote) {
1013 // Add level to rest of lines in the string
1014 lev = lev + 1;
1015 }
1016
1017 // Skip past any blank lines for next indent level info; we skip also
1018 // comments (all comments, not just those starting in column 0)
1019 // which effectively folds them into surrounding code rather
1020 // than screwing up folding. If comments end file, use the min
1021 // comment indent as the level after
1022
1023 int minCommentLevel = indentCurrentLevel;
1024 while (!quote &&
1025 (lineNext < docLines) &&
1026 ((indentNext & SC_FOLDLEVELWHITEFLAG) || (IsCommentLine(lineNext, styler)))) {
1027
1028 if (IsCommentLine(lineNext, styler) && indentNext < minCommentLevel) {
1029 minCommentLevel = indentNext;
1030 }
1031
1032 lineNext++;
1033 indentNext = styler.IndentAmount(lineNext, &spaceFlags, nullptr);
1034 }
1035
1036 const int levelAfterComments = ((lineNext < docLines) ? indentNext & SC_FOLDLEVELNUMBERMASK : minCommentLevel);
1037 const int levelBeforeComments = std::max(indentCurrentLevel, levelAfterComments);
1038
1039 // Now set all the indent levels on the lines we skipped
1040 // Do this from end to start. Once we encounter one line
1041 // which is indented more than the line after the end of
1042 // the comment-block, use the level of the block before
1043
1044 Sci_Position skipLine = lineNext;
1045 int skipLevel = levelAfterComments;
1046
1047 while (--skipLine > lineCurrent) {
1048 const int skipLineIndent = styler.IndentAmount(skipLine, &spaceFlags, nullptr);
1049
1050 if (options.foldCompact) {
1051 if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments)
1052 skipLevel = levelBeforeComments;
1053
1054 const int whiteFlag = skipLineIndent & SC_FOLDLEVELWHITEFLAG;
1055
1056 styler.SetLevel(skipLine, skipLevel | whiteFlag);
1057 } else {
1058 if ((skipLineIndent & SC_FOLDLEVELNUMBERMASK) > levelAfterComments &&
1059 !(skipLineIndent & SC_FOLDLEVELWHITEFLAG) &&
1060 !IsCommentLine(skipLine, styler))
1061 skipLevel = levelBeforeComments;
1062
1063 styler.SetLevel(skipLine, skipLevel);
1064 }
1065 }
1066
1067 // Set fold header on non-quote line
1068 if (!quote && !(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
1069 if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))
1070 lev |= SC_FOLDLEVELHEADERFLAG;
1071 }
1072
1073 // Keep track of triple quote state of previous line
1074 prevQuote = quote;
1075
1076 // Set fold level for this line and move to next line
1077 styler.SetLevel(lineCurrent, options.foldCompact ? lev : lev & ~SC_FOLDLEVELWHITEFLAG);
1078 indentCurrent = indentNext;
1079 lineCurrent = lineNext;
1080 }
1081
1082 // NOTE: Cannot set level of last line here because indentCurrent doesn't have
1083 // header flag set; the loop above is crafted to take care of this case!
1084 //styler.SetLevel(lineCurrent, indentCurrent);
1085 }
1086
1087 }
1088
1089 extern const LexerModule lmPython(SCLEX_PYTHON, LexerPython::LexerFactoryPython, "python",
1090 pythonWordListDesc);