FormatTokenLexer.cpp
39.1 KB
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
//===--- FormatTokenLexer.cpp - Lex FormatTokens -------------*- C++ ----*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// This file implements FormatTokenLexer, which tokenizes a source file
/// into a FormatToken stream suitable for ClangFormat.
///
//===----------------------------------------------------------------------===//
#include "FormatTokenLexer.h"
#include "FormatToken.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Format/Format.h"
#include "llvm/Support/Regex.h"
namespace clang {
namespace format {
FormatTokenLexer::FormatTokenLexer(
const SourceManager &SourceMgr, FileID ID, unsigned Column,
const FormatStyle &Style, encoding::Encoding Encoding,
llvm::SpecificBumpPtrAllocator<FormatToken> &Allocator,
IdentifierTable &IdentTable)
: FormatTok(nullptr), IsFirstToken(true), StateStack({LexerState::NORMAL}),
Column(Column), TrailingWhitespace(0), SourceMgr(SourceMgr), ID(ID),
Style(Style), IdentTable(IdentTable), Keywords(IdentTable),
Encoding(Encoding), Allocator(Allocator), FirstInLineIndex(0),
FormattingDisabled(false), MacroBlockBeginRegex(Style.MacroBlockBegin),
MacroBlockEndRegex(Style.MacroBlockEnd) {
Lex.reset(new Lexer(ID, SourceMgr.getBuffer(ID), SourceMgr,
getFormattingLangOpts(Style)));
Lex->SetKeepWhitespaceMode(true);
for (const std::string &ForEachMacro : Style.ForEachMacros)
Macros.insert({&IdentTable.get(ForEachMacro), TT_ForEachMacro});
for (const std::string &AttributeMacro : Style.AttributeMacros)
Macros.insert({&IdentTable.get(AttributeMacro), TT_AttributeMacro});
for (const std::string &StatementMacro : Style.StatementMacros)
Macros.insert({&IdentTable.get(StatementMacro), TT_StatementMacro});
for (const std::string &TypenameMacro : Style.TypenameMacros)
Macros.insert({&IdentTable.get(TypenameMacro), TT_TypenameMacro});
for (const std::string &NamespaceMacro : Style.NamespaceMacros)
Macros.insert({&IdentTable.get(NamespaceMacro), TT_NamespaceMacro});
for (const std::string &WhitespaceSensitiveMacro :
Style.WhitespaceSensitiveMacros) {
Macros.insert(
{&IdentTable.get(WhitespaceSensitiveMacro), TT_UntouchableMacroFunc});
}
}
ArrayRef<FormatToken *> FormatTokenLexer::lex() {
assert(Tokens.empty());
assert(FirstInLineIndex == 0);
do {
Tokens.push_back(getNextToken());
if (Style.Language == FormatStyle::LK_JavaScript) {
tryParseJSRegexLiteral();
handleTemplateStrings();
}
if (Style.Language == FormatStyle::LK_TextProto)
tryParsePythonComment();
tryMergePreviousTokens();
if (Style.isCSharp())
// This needs to come after tokens have been merged so that C#
// string literals are correctly identified.
handleCSharpVerbatimAndInterpolatedStrings();
if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
FirstInLineIndex = Tokens.size() - 1;
} while (Tokens.back()->Tok.isNot(tok::eof));
return Tokens;
}
void FormatTokenLexer::tryMergePreviousTokens() {
if (tryMerge_TMacro())
return;
if (tryMergeConflictMarkers())
return;
if (tryMergeLessLess())
return;
if (tryMergeForEach())
return;
if (Style.isCpp() && tryTransformTryUsageForC())
return;
if (Style.isCSharp()) {
if (tryMergeCSharpKeywordVariables())
return;
if (tryMergeCSharpStringLiteral())
return;
if (tryMergeCSharpDoubleQuestion())
return;
if (tryMergeCSharpNullConditional())
return;
if (tryTransformCSharpForEach())
return;
static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
return;
}
if (tryMergeNSStringLiteral())
return;
if (Style.Language == FormatStyle::LK_JavaScript) {
static const tok::TokenKind JSIdentity[] = {tok::equalequal, tok::equal};
static const tok::TokenKind JSNotIdentity[] = {tok::exclaimequal,
tok::equal};
static const tok::TokenKind JSShiftEqual[] = {tok::greater, tok::greater,
tok::greaterequal};
static const tok::TokenKind JSRightArrow[] = {tok::equal, tok::greater};
static const tok::TokenKind JSExponentiation[] = {tok::star, tok::star};
static const tok::TokenKind JSExponentiationEqual[] = {tok::star,
tok::starequal};
static const tok::TokenKind JSNullPropagatingOperator[] = {tok::question,
tok::period};
static const tok::TokenKind JSNullishOperator[] = {tok::question,
tok::question};
// FIXME: Investigate what token type gives the correct operator priority.
if (tryMergeTokens(JSIdentity, TT_BinaryOperator))
return;
if (tryMergeTokens(JSNotIdentity, TT_BinaryOperator))
return;
if (tryMergeTokens(JSShiftEqual, TT_BinaryOperator))
return;
if (tryMergeTokens(JSRightArrow, TT_JsFatArrow))
return;
if (tryMergeTokens(JSExponentiation, TT_JsExponentiation))
return;
if (tryMergeTokens(JSExponentiationEqual, TT_JsExponentiationEqual)) {
Tokens.back()->Tok.setKind(tok::starequal);
return;
}
if (tryMergeTokens(JSNullishOperator, TT_JsNullishCoalescingOperator)) {
// Treat like the "||" operator (as opposed to the ternary ?).
Tokens.back()->Tok.setKind(tok::pipepipe);
return;
}
if (tryMergeTokens(JSNullPropagatingOperator,
TT_JsNullPropagatingOperator)) {
// Treat like a regular "." access.
Tokens.back()->Tok.setKind(tok::period);
return;
}
if (tryMergeJSPrivateIdentifier())
return;
}
if (Style.Language == FormatStyle::LK_Java) {
static const tok::TokenKind JavaRightLogicalShiftAssign[] = {
tok::greater, tok::greater, tok::greaterequal};
if (tryMergeTokens(JavaRightLogicalShiftAssign, TT_BinaryOperator))
return;
}
}
bool FormatTokenLexer::tryMergeNSStringLiteral() {
if (Tokens.size() < 2)
return false;
auto &At = *(Tokens.end() - 2);
auto &String = *(Tokens.end() - 1);
if (!At->is(tok::at) || !String->is(tok::string_literal))
return false;
At->Tok.setKind(tok::string_literal);
At->TokenText = StringRef(At->TokenText.begin(),
String->TokenText.end() - At->TokenText.begin());
At->ColumnWidth += String->ColumnWidth;
At->setType(TT_ObjCStringLiteral);
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
// Merges #idenfier into a single identifier with the text #identifier
// but the token tok::identifier.
if (Tokens.size() < 2)
return false;
auto &Hash = *(Tokens.end() - 2);
auto &Identifier = *(Tokens.end() - 1);
if (!Hash->is(tok::hash) || !Identifier->is(tok::identifier))
return false;
Hash->Tok.setKind(tok::identifier);
Hash->TokenText =
StringRef(Hash->TokenText.begin(),
Identifier->TokenText.end() - Hash->TokenText.begin());
Hash->ColumnWidth += Identifier->ColumnWidth;
Hash->setType(TT_JsPrivateIdentifier);
Tokens.erase(Tokens.end() - 1);
return true;
}
// Search for verbatim or interpolated string literals @"ABC" or
// $"aaaaa{abc}aaaaa" i and mark the token as TT_CSharpStringLiteral, and to
// prevent splitting of @, $ and ".
// Merging of multiline verbatim strings with embedded '"' is handled in
// handleCSharpVerbatimAndInterpolatedStrings with lower-level lexing.
bool FormatTokenLexer::tryMergeCSharpStringLiteral() {
if (Tokens.size() < 2)
return false;
// Interpolated strings could contain { } with " characters inside.
// $"{x ?? "null"}"
// should not be split into $"{x ?? ", null, "}" but should treated as a
// single string-literal.
//
// We opt not to try and format expressions inside {} within a C#
// interpolated string. Formatting expressions within an interpolated string
// would require similar work as that done for JavaScript template strings
// in `handleTemplateStrings()`.
auto &CSharpInterpolatedString = *(Tokens.end() - 2);
if (CSharpInterpolatedString->getType() == TT_CSharpStringLiteral &&
(CSharpInterpolatedString->TokenText.startswith(R"($")") ||
CSharpInterpolatedString->TokenText.startswith(R"($@")"))) {
int UnmatchedOpeningBraceCount = 0;
auto TokenTextSize = CSharpInterpolatedString->TokenText.size();
for (size_t Index = 0; Index < TokenTextSize; ++Index) {
char C = CSharpInterpolatedString->TokenText[Index];
if (C == '{') {
// "{{" inside an interpolated string is an escaped '{' so skip it.
if (Index + 1 < TokenTextSize &&
CSharpInterpolatedString->TokenText[Index + 1] == '{') {
++Index;
continue;
}
++UnmatchedOpeningBraceCount;
} else if (C == '}') {
// "}}" inside an interpolated string is an escaped '}' so skip it.
if (Index + 1 < TokenTextSize &&
CSharpInterpolatedString->TokenText[Index + 1] == '}') {
++Index;
continue;
}
--UnmatchedOpeningBraceCount;
}
}
if (UnmatchedOpeningBraceCount > 0) {
auto &NextToken = *(Tokens.end() - 1);
CSharpInterpolatedString->TokenText =
StringRef(CSharpInterpolatedString->TokenText.begin(),
NextToken->TokenText.end() -
CSharpInterpolatedString->TokenText.begin());
CSharpInterpolatedString->ColumnWidth += NextToken->ColumnWidth;
Tokens.erase(Tokens.end() - 1);
return true;
}
}
// Look for @"aaaaaa" or $"aaaaaa".
auto &String = *(Tokens.end() - 1);
if (!String->is(tok::string_literal))
return false;
auto &At = *(Tokens.end() - 2);
if (!(At->is(tok::at) || At->TokenText == "$"))
return false;
if (Tokens.size() > 2 && At->is(tok::at)) {
auto &Dollar = *(Tokens.end() - 3);
if (Dollar->TokenText == "$") {
// This looks like $@"aaaaa" so we need to combine all 3 tokens.
Dollar->Tok.setKind(tok::string_literal);
Dollar->TokenText =
StringRef(Dollar->TokenText.begin(),
String->TokenText.end() - Dollar->TokenText.begin());
Dollar->ColumnWidth += (At->ColumnWidth + String->ColumnWidth);
Dollar->setType(TT_CSharpStringLiteral);
Tokens.erase(Tokens.end() - 2);
Tokens.erase(Tokens.end() - 1);
return true;
}
}
// Convert back into just a string_literal.
At->Tok.setKind(tok::string_literal);
At->TokenText = StringRef(At->TokenText.begin(),
String->TokenText.end() - At->TokenText.begin());
At->ColumnWidth += String->ColumnWidth;
At->setType(TT_CSharpStringLiteral);
Tokens.erase(Tokens.end() - 1);
return true;
}
// Valid C# attribute targets:
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/attributes/#attribute-targets
const llvm::StringSet<> FormatTokenLexer::CSharpAttributeTargets = {
"assembly", "module", "field", "event", "method",
"param", "property", "return", "type",
};
bool FormatTokenLexer::tryMergeCSharpDoubleQuestion() {
if (Tokens.size() < 2)
return false;
auto &FirstQuestion = *(Tokens.end() - 2);
auto &SecondQuestion = *(Tokens.end() - 1);
if (!FirstQuestion->is(tok::question) || !SecondQuestion->is(tok::question))
return false;
FirstQuestion->Tok.setKind(tok::question); // no '??' in clang tokens.
FirstQuestion->TokenText = StringRef(FirstQuestion->TokenText.begin(),
SecondQuestion->TokenText.end() -
FirstQuestion->TokenText.begin());
FirstQuestion->ColumnWidth += SecondQuestion->ColumnWidth;
FirstQuestion->setType(TT_CSharpNullCoalescing);
Tokens.erase(Tokens.end() - 1);
return true;
}
// Merge '?[' and '?.' pairs into single tokens.
bool FormatTokenLexer::tryMergeCSharpNullConditional() {
if (Tokens.size() < 2)
return false;
auto &Question = *(Tokens.end() - 2);
auto &PeriodOrLSquare = *(Tokens.end() - 1);
if (!Question->is(tok::question) ||
!PeriodOrLSquare->isOneOf(tok::l_square, tok::period))
return false;
Question->TokenText =
StringRef(Question->TokenText.begin(),
PeriodOrLSquare->TokenText.end() - Question->TokenText.begin());
Question->ColumnWidth += PeriodOrLSquare->ColumnWidth;
if (PeriodOrLSquare->is(tok::l_square)) {
Question->Tok.setKind(tok::question); // no '?[' in clang tokens.
Question->setType(TT_CSharpNullConditionalLSquare);
} else {
Question->Tok.setKind(tok::question); // no '?.' in clang tokens.
Question->setType(TT_CSharpNullConditional);
}
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryMergeCSharpKeywordVariables() {
if (Tokens.size() < 2)
return false;
auto &At = *(Tokens.end() - 2);
auto &Keyword = *(Tokens.end() - 1);
if (!At->is(tok::at))
return false;
if (!Keywords.isCSharpKeyword(*Keyword))
return false;
At->Tok.setKind(tok::identifier);
At->TokenText = StringRef(At->TokenText.begin(),
Keyword->TokenText.end() - At->TokenText.begin());
At->ColumnWidth += Keyword->ColumnWidth;
At->setType(Keyword->getType());
Tokens.erase(Tokens.end() - 1);
return true;
}
// In C# transform identifier foreach into kw_foreach
bool FormatTokenLexer::tryTransformCSharpForEach() {
if (Tokens.size() < 1)
return false;
auto &Identifier = *(Tokens.end() - 1);
if (!Identifier->is(tok::identifier))
return false;
if (Identifier->TokenText != "foreach")
return false;
Identifier->setType(TT_ForEachMacro);
Identifier->Tok.setKind(tok::kw_for);
return true;
}
bool FormatTokenLexer::tryMergeForEach() {
if (Tokens.size() < 2)
return false;
auto &For = *(Tokens.end() - 2);
auto &Each = *(Tokens.end() - 1);
if (!For->is(tok::kw_for))
return false;
if (!Each->is(tok::identifier))
return false;
if (Each->TokenText != "each")
return false;
For->setType(TT_ForEachMacro);
For->Tok.setKind(tok::kw_for);
For->TokenText = StringRef(For->TokenText.begin(),
Each->TokenText.end() - For->TokenText.begin());
For->ColumnWidth += Each->ColumnWidth;
Tokens.erase(Tokens.end() - 1);
return true;
}
bool FormatTokenLexer::tryTransformTryUsageForC() {
if (Tokens.size() < 2)
return false;
auto &Try = *(Tokens.end() - 2);
if (!Try->is(tok::kw_try))
return false;
auto &Next = *(Tokens.end() - 1);
if (Next->isOneOf(tok::l_brace, tok::colon, tok::hash, tok::comment))
return false;
if (Tokens.size() > 2) {
auto &At = *(Tokens.end() - 3);
if (At->is(tok::at))
return false;
}
Try->Tok.setKind(tok::identifier);
return true;
}
bool FormatTokenLexer::tryMergeLessLess() {
// Merge X,less,less,Y into X,lessless,Y unless X or Y is less.
if (Tokens.size() < 3)
return false;
bool FourthTokenIsLess = false;
if (Tokens.size() > 3)
FourthTokenIsLess = (Tokens.end() - 4)[0]->is(tok::less);
auto First = Tokens.end() - 3;
if (First[2]->is(tok::less) || First[1]->isNot(tok::less) ||
First[0]->isNot(tok::less) || FourthTokenIsLess)
return false;
// Only merge if there currently is no whitespace between the two "<".
if (First[1]->WhitespaceRange.getBegin() !=
First[1]->WhitespaceRange.getEnd())
return false;
First[0]->Tok.setKind(tok::lessless);
First[0]->TokenText = "<<";
First[0]->ColumnWidth += 1;
Tokens.erase(Tokens.end() - 2);
return true;
}
bool FormatTokenLexer::tryMergeTokens(ArrayRef<tok::TokenKind> Kinds,
TokenType NewType) {
if (Tokens.size() < Kinds.size())
return false;
SmallVectorImpl<FormatToken *>::const_iterator First =
Tokens.end() - Kinds.size();
if (!First[0]->is(Kinds[0]))
return false;
unsigned AddLength = 0;
for (unsigned i = 1; i < Kinds.size(); ++i) {
if (!First[i]->is(Kinds[i]) || First[i]->WhitespaceRange.getBegin() !=
First[i]->WhitespaceRange.getEnd())
return false;
AddLength += First[i]->TokenText.size();
}
Tokens.resize(Tokens.size() - Kinds.size() + 1);
First[0]->TokenText = StringRef(First[0]->TokenText.data(),
First[0]->TokenText.size() + AddLength);
First[0]->ColumnWidth += AddLength;
First[0]->setType(NewType);
return true;
}
// Returns \c true if \p Tok can only be followed by an operand in JavaScript.
bool FormatTokenLexer::precedesOperand(FormatToken *Tok) {
// NB: This is not entirely correct, as an r_paren can introduce an operand
// location in e.g. `if (foo) /bar/.exec(...);`. That is a rare enough
// corner case to not matter in practice, though.
return Tok->isOneOf(tok::period, tok::l_paren, tok::comma, tok::l_brace,
tok::r_brace, tok::l_square, tok::semi, tok::exclaim,
tok::colon, tok::question, tok::tilde) ||
Tok->isOneOf(tok::kw_return, tok::kw_do, tok::kw_case, tok::kw_throw,
tok::kw_else, tok::kw_new, tok::kw_delete, tok::kw_void,
tok::kw_typeof, Keywords.kw_instanceof, Keywords.kw_in) ||
Tok->isBinaryOperator();
}
bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken *Prev) {
if (!Prev)
return true;
// Regex literals can only follow after prefix unary operators, not after
// postfix unary operators. If the '++' is followed by a non-operand
// introducing token, the slash here is the operand and not the start of a
// regex.
// `!` is an unary prefix operator, but also a post-fix operator that casts
// away nullability, so the same check applies.
if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
// The previous token must introduce an operand location where regex
// literals can occur.
if (!precedesOperand(Prev))
return false;
return true;
}
// Tries to parse a JavaScript Regex literal starting at the current token,
// if that begins with a slash and is in a location where JavaScript allows
// regex literals. Changes the current token to a regex literal and updates
// its text if successful.
void FormatTokenLexer::tryParseJSRegexLiteral() {
FormatToken *RegexToken = Tokens.back();
if (!RegexToken->isOneOf(tok::slash, tok::slashequal))
return;
FormatToken *Prev = nullptr;
for (auto I = Tokens.rbegin() + 1, E = Tokens.rend(); I != E; ++I) {
// NB: Because previous pointers are not initialized yet, this cannot use
// Token.getPreviousNonComment.
if ((*I)->isNot(tok::comment)) {
Prev = *I;
break;
}
}
if (!canPrecedeRegexLiteral(Prev))
return;
// 'Manually' lex ahead in the current file buffer.
const char *Offset = Lex->getBufferLocation();
const char *RegexBegin = Offset - RegexToken->TokenText.size();
StringRef Buffer = Lex->getBuffer();
bool InCharacterClass = false;
bool HaveClosingSlash = false;
for (; !HaveClosingSlash && Offset != Buffer.end(); ++Offset) {
// Regular expressions are terminated with a '/', which can only be
// escaped using '\' or a character class between '[' and ']'.
// See http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.5.
switch (*Offset) {
case '\\':
// Skip the escaped character.
++Offset;
break;
case '[':
InCharacterClass = true;
break;
case ']':
InCharacterClass = false;
break;
case '/':
if (!InCharacterClass)
HaveClosingSlash = true;
break;
}
}
RegexToken->setType(TT_RegexLiteral);
// Treat regex literals like other string_literals.
RegexToken->Tok.setKind(tok::string_literal);
RegexToken->TokenText = StringRef(RegexBegin, Offset - RegexBegin);
RegexToken->ColumnWidth = RegexToken->TokenText.size();
resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
}
void FormatTokenLexer::handleCSharpVerbatimAndInterpolatedStrings() {
FormatToken *CSharpStringLiteral = Tokens.back();
if (CSharpStringLiteral->getType() != TT_CSharpStringLiteral)
return;
// Deal with multiline strings.
if (!(CSharpStringLiteral->TokenText.startswith(R"(@")") ||
CSharpStringLiteral->TokenText.startswith(R"($@")")))
return;
const char *StrBegin =
Lex->getBufferLocation() - CSharpStringLiteral->TokenText.size();
const char *Offset = StrBegin;
if (CSharpStringLiteral->TokenText.startswith(R"(@")"))
Offset += 2;
else // CSharpStringLiteral->TokenText.startswith(R"($@")")
Offset += 3;
// Look for a terminating '"' in the current file buffer.
// Make no effort to format code within an interpolated or verbatim string.
for (; Offset != Lex->getBuffer().end(); ++Offset) {
if (Offset[0] == '"') {
// "" within a verbatim string is an escaped double quote: skip it.
if (Offset + 1 < Lex->getBuffer().end() && Offset[1] == '"')
++Offset;
else
break;
}
}
// Make no attempt to format code properly if a verbatim string is
// unterminated.
if (Offset == Lex->getBuffer().end())
return;
StringRef LiteralText(StrBegin, Offset - StrBegin + 1);
CSharpStringLiteral->TokenText = LiteralText;
// Adjust width for potentially multiline string literals.
size_t FirstBreak = LiteralText.find('\n');
StringRef FirstLineText = FirstBreak == StringRef::npos
? LiteralText
: LiteralText.substr(0, FirstBreak);
CSharpStringLiteral->ColumnWidth = encoding::columnWidthWithTabs(
FirstLineText, CSharpStringLiteral->OriginalColumn, Style.TabWidth,
Encoding);
size_t LastBreak = LiteralText.rfind('\n');
if (LastBreak != StringRef::npos) {
CSharpStringLiteral->IsMultiline = true;
unsigned StartColumn = 0;
CSharpStringLiteral->LastLineColumnWidth = encoding::columnWidthWithTabs(
LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
Style.TabWidth, Encoding);
}
SourceLocation loc = Offset < Lex->getBuffer().end()
? Lex->getSourceLocation(Offset + 1)
: SourceMgr.getLocForEndOfFile(ID);
resetLexer(SourceMgr.getFileOffset(loc));
}
void FormatTokenLexer::handleTemplateStrings() {
FormatToken *BacktickToken = Tokens.back();
if (BacktickToken->is(tok::l_brace)) {
StateStack.push(LexerState::NORMAL);
return;
}
if (BacktickToken->is(tok::r_brace)) {
if (StateStack.size() == 1)
return;
StateStack.pop();
if (StateStack.top() != LexerState::TEMPLATE_STRING)
return;
// If back in TEMPLATE_STRING, fallthrough and continue parsing the
} else if (BacktickToken->is(tok::unknown) &&
BacktickToken->TokenText == "`") {
StateStack.push(LexerState::TEMPLATE_STRING);
} else {
return; // Not actually a template
}
// 'Manually' lex ahead in the current file buffer.
const char *Offset = Lex->getBufferLocation();
const char *TmplBegin = Offset - BacktickToken->TokenText.size(); // at "`"
for (; Offset != Lex->getBuffer().end(); ++Offset) {
if (Offset[0] == '`') {
StateStack.pop();
break;
}
if (Offset[0] == '\\') {
++Offset; // Skip the escaped character.
} else if (Offset + 1 < Lex->getBuffer().end() && Offset[0] == '$' &&
Offset[1] == '{') {
// '${' introduces an expression interpolation in the template string.
StateStack.push(LexerState::NORMAL);
++Offset;
break;
}
}
StringRef LiteralText(TmplBegin, Offset - TmplBegin + 1);
BacktickToken->setType(TT_TemplateString);
BacktickToken->Tok.setKind(tok::string_literal);
BacktickToken->TokenText = LiteralText;
// Adjust width for potentially multiline string literals.
size_t FirstBreak = LiteralText.find('\n');
StringRef FirstLineText = FirstBreak == StringRef::npos
? LiteralText
: LiteralText.substr(0, FirstBreak);
BacktickToken->ColumnWidth = encoding::columnWidthWithTabs(
FirstLineText, BacktickToken->OriginalColumn, Style.TabWidth, Encoding);
size_t LastBreak = LiteralText.rfind('\n');
if (LastBreak != StringRef::npos) {
BacktickToken->IsMultiline = true;
unsigned StartColumn = 0; // The template tail spans the entire line.
BacktickToken->LastLineColumnWidth = encoding::columnWidthWithTabs(
LiteralText.substr(LastBreak + 1, LiteralText.size()), StartColumn,
Style.TabWidth, Encoding);
}
SourceLocation loc = Offset < Lex->getBuffer().end()
? Lex->getSourceLocation(Offset + 1)
: SourceMgr.getLocForEndOfFile(ID);
resetLexer(SourceMgr.getFileOffset(loc));
}
void FormatTokenLexer::tryParsePythonComment() {
FormatToken *HashToken = Tokens.back();
if (!HashToken->isOneOf(tok::hash, tok::hashhash))
return;
// Turn the remainder of this line into a comment.
const char *CommentBegin =
Lex->getBufferLocation() - HashToken->TokenText.size(); // at "#"
size_t From = CommentBegin - Lex->getBuffer().begin();
size_t To = Lex->getBuffer().find_first_of('\n', From);
if (To == StringRef::npos)
To = Lex->getBuffer().size();
size_t Len = To - From;
HashToken->setType(TT_LineComment);
HashToken->Tok.setKind(tok::comment);
HashToken->TokenText = Lex->getBuffer().substr(From, Len);
SourceLocation Loc = To < Lex->getBuffer().size()
? Lex->getSourceLocation(CommentBegin + Len)
: SourceMgr.getLocForEndOfFile(ID);
resetLexer(SourceMgr.getFileOffset(Loc));
}
bool FormatTokenLexer::tryMerge_TMacro() {
if (Tokens.size() < 4)
return false;
FormatToken *Last = Tokens.back();
if (!Last->is(tok::r_paren))
return false;
FormatToken *String = Tokens[Tokens.size() - 2];
if (!String->is(tok::string_literal) || String->IsMultiline)
return false;
if (!Tokens[Tokens.size() - 3]->is(tok::l_paren))
return false;
FormatToken *Macro = Tokens[Tokens.size() - 4];
if (Macro->TokenText != "_T")
return false;
const char *Start = Macro->TokenText.data();
const char *End = Last->TokenText.data() + Last->TokenText.size();
String->TokenText = StringRef(Start, End - Start);
String->IsFirst = Macro->IsFirst;
String->LastNewlineOffset = Macro->LastNewlineOffset;
String->WhitespaceRange = Macro->WhitespaceRange;
String->OriginalColumn = Macro->OriginalColumn;
String->ColumnWidth = encoding::columnWidthWithTabs(
String->TokenText, String->OriginalColumn, Style.TabWidth, Encoding);
String->NewlinesBefore = Macro->NewlinesBefore;
String->HasUnescapedNewline = Macro->HasUnescapedNewline;
Tokens.pop_back();
Tokens.pop_back();
Tokens.pop_back();
Tokens.back() = String;
return true;
}
bool FormatTokenLexer::tryMergeConflictMarkers() {
if (Tokens.back()->NewlinesBefore == 0 && Tokens.back()->isNot(tok::eof))
return false;
// Conflict lines look like:
// <marker> <text from the vcs>
// For example:
// >>>>>>> /file/in/file/system at revision 1234
//
// We merge all tokens in a line that starts with a conflict marker
// into a single token with a special token type that the unwrapped line
// parser will use to correctly rebuild the underlying code.
FileID ID;
// Get the position of the first token in the line.
unsigned FirstInLineOffset;
std::tie(ID, FirstInLineOffset) = SourceMgr.getDecomposedLoc(
Tokens[FirstInLineIndex]->getStartOfNonWhitespace());
StringRef Buffer = SourceMgr.getBuffer(ID)->getBuffer();
// Calculate the offset of the start of the current line.
auto LineOffset = Buffer.rfind('\n', FirstInLineOffset);
if (LineOffset == StringRef::npos) {
LineOffset = 0;
} else {
++LineOffset;
}
auto FirstSpace = Buffer.find_first_of(" \n", LineOffset);
StringRef LineStart;
if (FirstSpace == StringRef::npos) {
LineStart = Buffer.substr(LineOffset);
} else {
LineStart = Buffer.substr(LineOffset, FirstSpace - LineOffset);
}
TokenType Type = TT_Unknown;
if (LineStart == "<<<<<<<" || LineStart == ">>>>") {
Type = TT_ConflictStart;
} else if (LineStart == "|||||||" || LineStart == "=======" ||
LineStart == "====") {
Type = TT_ConflictAlternative;
} else if (LineStart == ">>>>>>>" || LineStart == "<<<<") {
Type = TT_ConflictEnd;
}
if (Type != TT_Unknown) {
FormatToken *Next = Tokens.back();
Tokens.resize(FirstInLineIndex + 1);
// We do not need to build a complete token here, as we will skip it
// during parsing anyway (as we must not touch whitespace around conflict
// markers).
Tokens.back()->setType(Type);
Tokens.back()->Tok.setKind(tok::kw___unknown_anytype);
Tokens.push_back(Next);
return true;
}
return false;
}
FormatToken *FormatTokenLexer::getStashedToken() {
// Create a synthesized second '>' or '<' token.
Token Tok = FormatTok->Tok;
StringRef TokenText = FormatTok->TokenText;
unsigned OriginalColumn = FormatTok->OriginalColumn;
FormatTok = new (Allocator.Allocate()) FormatToken;
FormatTok->Tok = Tok;
SourceLocation TokLocation =
FormatTok->Tok.getLocation().getLocWithOffset(Tok.getLength() - 1);
FormatTok->Tok.setLocation(TokLocation);
FormatTok->WhitespaceRange = SourceRange(TokLocation, TokLocation);
FormatTok->TokenText = TokenText;
FormatTok->ColumnWidth = 1;
FormatTok->OriginalColumn = OriginalColumn + 1;
return FormatTok;
}
FormatToken *FormatTokenLexer::getNextToken() {
if (StateStack.top() == LexerState::TOKEN_STASHED) {
StateStack.pop();
return getStashedToken();
}
FormatTok = new (Allocator.Allocate()) FormatToken;
readRawToken(*FormatTok);
SourceLocation WhitespaceStart =
FormatTok->Tok.getLocation().getLocWithOffset(-TrailingWhitespace);
FormatTok->IsFirst = IsFirstToken;
IsFirstToken = false;
// Consume and record whitespace until we find a significant token.
unsigned WhitespaceLength = TrailingWhitespace;
while (FormatTok->Tok.is(tok::unknown)) {
StringRef Text = FormatTok->TokenText;
auto EscapesNewline = [&](int pos) {
// A '\r' here is just part of '\r\n'. Skip it.
if (pos >= 0 && Text[pos] == '\r')
--pos;
// See whether there is an odd number of '\' before this.
// FIXME: This is wrong. A '\' followed by a newline is always removed,
// regardless of whether there is another '\' before it.
// FIXME: Newlines can also be escaped by a '?' '?' '/' trigraph.
unsigned count = 0;
for (; pos >= 0; --pos, ++count)
if (Text[pos] != '\\')
break;
return count & 1;
};
// FIXME: This miscounts tok:unknown tokens that are not just
// whitespace, e.g. a '`' character.
for (int i = 0, e = Text.size(); i != e; ++i) {
switch (Text[i]) {
case '\n':
++FormatTok->NewlinesBefore;
FormatTok->HasUnescapedNewline = !EscapesNewline(i - 1);
FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
Column = 0;
break;
case '\r':
FormatTok->LastNewlineOffset = WhitespaceLength + i + 1;
Column = 0;
break;
case '\f':
case '\v':
Column = 0;
break;
case ' ':
++Column;
break;
case '\t':
Column +=
Style.TabWidth - (Style.TabWidth ? Column % Style.TabWidth : 0);
break;
case '\\':
if (i + 1 == e || (Text[i + 1] != '\r' && Text[i + 1] != '\n'))
FormatTok->setType(TT_ImplicitStringLiteral);
break;
default:
FormatTok->setType(TT_ImplicitStringLiteral);
break;
}
if (FormatTok->getType() == TT_ImplicitStringLiteral)
break;
}
if (FormatTok->is(TT_ImplicitStringLiteral))
break;
WhitespaceLength += FormatTok->Tok.getLength();
readRawToken(*FormatTok);
}
// JavaScript and Java do not allow to escape the end of the line with a
// backslash. Backslashes are syntax errors in plain source, but can occur in
// comments. When a single line comment ends with a \, it'll cause the next
// line of code to be lexed as a comment, breaking formatting. The code below
// finds comments that contain a backslash followed by a line break, truncates
// the comment token at the backslash, and resets the lexer to restart behind
// the backslash.
if ((Style.Language == FormatStyle::LK_JavaScript ||
Style.Language == FormatStyle::LK_Java) &&
FormatTok->is(tok::comment) && FormatTok->TokenText.startswith("//")) {
size_t BackslashPos = FormatTok->TokenText.find('\\');
while (BackslashPos != StringRef::npos) {
if (BackslashPos + 1 < FormatTok->TokenText.size() &&
FormatTok->TokenText[BackslashPos + 1] == '\n') {
const char *Offset = Lex->getBufferLocation();
Offset -= FormatTok->TokenText.size();
Offset += BackslashPos + 1;
resetLexer(SourceMgr.getFileOffset(Lex->getSourceLocation(Offset)));
FormatTok->TokenText = FormatTok->TokenText.substr(0, BackslashPos + 1);
FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
FormatTok->TokenText, FormatTok->OriginalColumn, Style.TabWidth,
Encoding);
break;
}
BackslashPos = FormatTok->TokenText.find('\\', BackslashPos + 1);
}
}
// In case the token starts with escaped newlines, we want to
// take them into account as whitespace - this pattern is quite frequent
// in macro definitions.
// FIXME: Add a more explicit test.
while (FormatTok->TokenText.size() > 1 && FormatTok->TokenText[0] == '\\') {
unsigned SkippedWhitespace = 0;
if (FormatTok->TokenText.size() > 2 &&
(FormatTok->TokenText[1] == '\r' && FormatTok->TokenText[2] == '\n'))
SkippedWhitespace = 3;
else if (FormatTok->TokenText[1] == '\n')
SkippedWhitespace = 2;
else
break;
++FormatTok->NewlinesBefore;
WhitespaceLength += SkippedWhitespace;
FormatTok->LastNewlineOffset = SkippedWhitespace;
Column = 0;
FormatTok->TokenText = FormatTok->TokenText.substr(SkippedWhitespace);
}
FormatTok->WhitespaceRange = SourceRange(
WhitespaceStart, WhitespaceStart.getLocWithOffset(WhitespaceLength));
FormatTok->OriginalColumn = Column;
TrailingWhitespace = 0;
if (FormatTok->Tok.is(tok::comment)) {
// FIXME: Add the trimmed whitespace to Column.
StringRef UntrimmedText = FormatTok->TokenText;
FormatTok->TokenText = FormatTok->TokenText.rtrim(" \t\v\f");
TrailingWhitespace = UntrimmedText.size() - FormatTok->TokenText.size();
} else if (FormatTok->Tok.is(tok::raw_identifier)) {
IdentifierInfo &Info = IdentTable.get(FormatTok->TokenText);
FormatTok->Tok.setIdentifierInfo(&Info);
FormatTok->Tok.setKind(Info.getTokenID());
if (Style.Language == FormatStyle::LK_Java &&
FormatTok->isOneOf(tok::kw_struct, tok::kw_union, tok::kw_delete,
tok::kw_operator)) {
FormatTok->Tok.setKind(tok::identifier);
FormatTok->Tok.setIdentifierInfo(nullptr);
} else if (Style.Language == FormatStyle::LK_JavaScript &&
FormatTok->isOneOf(tok::kw_struct, tok::kw_union,
tok::kw_operator)) {
FormatTok->Tok.setKind(tok::identifier);
FormatTok->Tok.setIdentifierInfo(nullptr);
}
} else if (FormatTok->Tok.is(tok::greatergreater)) {
FormatTok->Tok.setKind(tok::greater);
FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
++Column;
StateStack.push(LexerState::TOKEN_STASHED);
} else if (FormatTok->Tok.is(tok::lessless)) {
FormatTok->Tok.setKind(tok::less);
FormatTok->TokenText = FormatTok->TokenText.substr(0, 1);
++Column;
StateStack.push(LexerState::TOKEN_STASHED);
}
// Now FormatTok is the next non-whitespace token.
StringRef Text = FormatTok->TokenText;
size_t FirstNewlinePos = Text.find('\n');
if (FirstNewlinePos == StringRef::npos) {
// FIXME: ColumnWidth actually depends on the start column, we need to
// take this into account when the token is moved.
FormatTok->ColumnWidth =
encoding::columnWidthWithTabs(Text, Column, Style.TabWidth, Encoding);
Column += FormatTok->ColumnWidth;
} else {
FormatTok->IsMultiline = true;
// FIXME: ColumnWidth actually depends on the start column, we need to
// take this into account when the token is moved.
FormatTok->ColumnWidth = encoding::columnWidthWithTabs(
Text.substr(0, FirstNewlinePos), Column, Style.TabWidth, Encoding);
// The last line of the token always starts in column 0.
// Thus, the length can be precomputed even in the presence of tabs.
FormatTok->LastLineColumnWidth = encoding::columnWidthWithTabs(
Text.substr(Text.find_last_of('\n') + 1), 0, Style.TabWidth, Encoding);
Column = FormatTok->LastLineColumnWidth;
}
if (Style.isCpp()) {
auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
tok::pp_define) &&
it != Macros.end()) {
FormatTok->setType(it->second);
} else if (FormatTok->is(tok::identifier)) {
if (MacroBlockBeginRegex.match(Text)) {
FormatTok->setType(TT_MacroBlockBegin);
} else if (MacroBlockEndRegex.match(Text)) {
FormatTok->setType(TT_MacroBlockEnd);
}
}
}
return FormatTok;
}
void FormatTokenLexer::readRawToken(FormatToken &Tok) {
Lex->LexFromRawLexer(Tok.Tok);
Tok.TokenText = StringRef(SourceMgr.getCharacterData(Tok.Tok.getLocation()),
Tok.Tok.getLength());
// For formatting, treat unterminated string literals like normal string
// literals.
if (Tok.is(tok::unknown)) {
if (!Tok.TokenText.empty() && Tok.TokenText[0] == '"') {
Tok.Tok.setKind(tok::string_literal);
Tok.IsUnterminatedLiteral = true;
} else if (Style.Language == FormatStyle::LK_JavaScript &&
Tok.TokenText == "''") {
Tok.Tok.setKind(tok::string_literal);
}
}
if ((Style.Language == FormatStyle::LK_JavaScript ||
Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) &&
Tok.is(tok::char_constant)) {
Tok.Tok.setKind(tok::string_literal);
}
if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format on" ||
Tok.TokenText == "/* clang-format on */")) {
FormattingDisabled = false;
}
Tok.Finalized = FormattingDisabled;
if (Tok.is(tok::comment) && (Tok.TokenText == "// clang-format off" ||
Tok.TokenText == "/* clang-format off */")) {
FormattingDisabled = true;
}
}
void FormatTokenLexer::resetLexer(unsigned Offset) {
StringRef Buffer = SourceMgr.getBufferData(ID);
Lex.reset(new Lexer(SourceMgr.getLocForStartOfFile(ID),
getFormattingLangOpts(Style), Buffer.begin(),
Buffer.begin() + Offset, Buffer.end()));
Lex->SetKeepWhitespaceMode(true);
TrailingWhitespace = 0;
}
} // namespace format
} // namespace clang