forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileCheck.cpp
1902 lines (1653 loc) · 68.8 KB
/
FileCheck.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- FileCheck.cpp - Check that File's Contents match what is expected --===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// FileCheck does a line-by line check of a file that validates whether it
// contains the expected content. This is useful for regression tests etc.
//
// This file implements most of the API that will be used by the FileCheck utility
// as well as various unittests.
//===----------------------------------------------------------------------===//
#include "llvm/Support/FileCheck.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/FormatVariadic.h"
#include <cstdint>
#include <list>
#include <map>
#include <tuple>
#include <utility>
using namespace llvm;
bool FileCheckNumericVariable::setValue(uint64_t NewValue) {
if (Value)
return true;
Value = NewValue;
return false;
}
bool FileCheckNumericVariable::clearValue() {
if (!Value)
return true;
Value = None;
return false;
}
Optional<uint64_t> FileCheckNumExpr::eval() const {
assert(LeftOp && "Evaluating an empty numeric expression");
Optional<uint64_t> LeftOpValue = LeftOp->getValue();
// Variable is undefined.
if (!LeftOpValue)
return None;
return EvalBinop(*LeftOpValue, RightOp);
}
StringRef FileCheckNumExpr::getUndefVarName() const {
if (!LeftOp->getValue())
return LeftOp->getName();
return StringRef();
}
Optional<std::string> FileCheckNumericSubstitution::getResult() const {
Optional<uint64_t> EvaluatedValue = NumExpr->eval();
if (!EvaluatedValue)
return None;
return utostr(*EvaluatedValue);
}
Optional<std::string> FileCheckStringSubstitution::getResult() const {
// Look up the value and escape it so that we can put it into the regex.
Optional<StringRef> VarVal = Context->getPatternVarValue(FromStr);
if (!VarVal)
return None;
return Regex::escape(*VarVal);
}
StringRef FileCheckNumericSubstitution::getUndefVarName() const {
// Although a use of an undefined numeric variable is detected at parse
// time, a numeric variable can be undefined later by ClearLocalVariables.
return NumExpr->getUndefVarName();
}
StringRef FileCheckStringSubstitution::getUndefVarName() const {
if (!Context->getPatternVarValue(FromStr))
return FromStr;
return StringRef();
}
bool FileCheckPattern::isValidVarNameStart(char C) {
return C == '_' || isalpha(C);
}
bool FileCheckPattern::parseVariable(StringRef &Str, StringRef &Name,
bool &IsPseudo) {
if (Str.empty())
return true;
bool ParsedOneChar = false;
unsigned I = 0;
IsPseudo = Str[0] == '@';
// Global vars start with '$'.
if (Str[0] == '$' || IsPseudo)
++I;
for (unsigned E = Str.size(); I != E; ++I) {
if (!ParsedOneChar && !isValidVarNameStart(Str[I]))
return true;
// Variable names are composed of alphanumeric characters and underscores.
if (Str[I] != '_' && !isalnum(Str[I]))
break;
ParsedOneChar = true;
}
Name = Str.take_front(I);
Str = Str.substr(I);
return false;
}
// StringRef holding all characters considered as horizontal whitespaces by
// FileCheck input canonicalization.
StringRef SpaceChars = " \t";
// Parsing helper function that strips the first character in S and returns it.
static char popFront(StringRef &S) {
char C = S.front();
S = S.drop_front();
return C;
}
bool FileCheckPattern::parseNumericVariableDefinition(
StringRef &Expr, StringRef &Name, FileCheckPatternContext *Context,
const SourceMgr &SM) {
bool IsPseudo;
if (parseVariable(Expr, Name, IsPseudo)) {
SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
"invalid variable name");
return true;
}
if (IsPseudo) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
"definition of pseudo numeric variable unsupported");
return true;
}
// Detect collisions between string and numeric variables when the latter
// is created later than the former.
if (Context->DefinedVariableTable.find(Name) !=
Context->DefinedVariableTable.end()) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
"string variable with name '" + Name + "' already exists");
return true;
}
return false;
}
FileCheckNumericVariable *
FileCheckPattern::parseNumericVariableUse(StringRef &Expr,
const SourceMgr &SM) const {
bool IsPseudo;
StringRef Name;
if (parseVariable(Expr, Name, IsPseudo)) {
SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
"invalid variable name");
return nullptr;
}
if (IsPseudo && !Name.equals("@LINE")) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
"invalid pseudo numeric variable '" + Name + "'");
return nullptr;
}
// This method is indirectly called from parsePattern for all numeric
// variable definitions and uses in the order in which they appear in the
// CHECK pattern. For each definition, the pointer to the class instance of
// the corresponding numeric variable definition is stored in
// GlobalNumericVariableTable. Therefore, the pointer we get below is for the
// class instance corresponding to the last definition of this variable use.
auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
if (VarTableIter == Context->GlobalNumericVariableTable.end()) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
"using undefined numeric variable '" + Name + "'");
return nullptr;
}
FileCheckNumericVariable *NumericVariable = VarTableIter->second;
if (!IsPseudo && NumericVariable->getDefLineNumber() == LineNumber) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
"numeric variable '" + Name +
"' defined on the same line as used");
return nullptr;
}
return NumericVariable;
}
static uint64_t add(uint64_t LeftOp, uint64_t RightOp) {
return LeftOp + RightOp;
}
static uint64_t sub(uint64_t LeftOp, uint64_t RightOp) {
return LeftOp - RightOp;
}
FileCheckNumExpr *FileCheckPattern::parseBinop(StringRef &Expr,
const SourceMgr &SM) const {
FileCheckNumericVariable *LeftOp = parseNumericVariableUse(Expr, SM);
if (!LeftOp) {
// Error reporting done in parseNumericVariableUse().
return nullptr;
}
// Check if this is a supported operation and select a function to perform
// it.
Expr = Expr.ltrim(SpaceChars);
if (Expr.empty())
return Context->makeNumExpr(add, LeftOp, 0);
SMLoc OpLoc = SMLoc::getFromPointer(Expr.data());
char Operator = popFront(Expr);
binop_eval_t EvalBinop;
switch (Operator) {
case '+':
EvalBinop = add;
break;
case '-':
EvalBinop = sub;
break;
default:
SM.PrintMessage(OpLoc, SourceMgr::DK_Error,
Twine("unsupported numeric operation '") + Twine(Operator) +
"'");
return nullptr;
}
// Parse right operand.
Expr = Expr.ltrim(SpaceChars);
if (Expr.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
"missing operand in numeric expression");
return nullptr;
}
uint64_t RightOp;
if (Expr.consumeInteger(10, RightOp)) {
SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
"invalid offset in numeric expression '" + Expr + "'");
return nullptr;
}
Expr = Expr.ltrim(SpaceChars);
if (!Expr.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(Expr.data()), SourceMgr::DK_Error,
"unexpected characters at end of numeric expression '" +
Expr + "'");
return nullptr;
}
return Context->makeNumExpr(EvalBinop, LeftOp, RightOp);
}
FileCheckNumExpr *FileCheckPattern::parseNumericSubstitutionBlock(
StringRef Expr, FileCheckNumericVariable *&DefinedNumericVariable,
const SourceMgr &SM) const {
// Parse the numeric variable definition.
DefinedNumericVariable = nullptr;
size_t DefEnd = Expr.find(':');
if (DefEnd != StringRef::npos) {
StringRef DefExpr = Expr.substr(0, DefEnd);
StringRef UseExpr = Expr = Expr.substr(DefEnd + 1);
DefExpr = DefExpr.ltrim(SpaceChars);
StringRef Name;
if (parseNumericVariableDefinition(DefExpr, Name, Context, SM)) {
// Invalid variable definition. Error reporting done in parsing function.
return nullptr;
}
DefinedNumericVariable =
Context->makeNumericVariable(this->LineNumber, Name);
DefExpr = DefExpr.ltrim(SpaceChars);
if (!DefExpr.empty()) {
SM.PrintMessage(SMLoc::getFromPointer(DefExpr.data()),
SourceMgr::DK_Error,
"invalid numeric variable definition");
return nullptr;
}
UseExpr = UseExpr.ltrim(SpaceChars);
if (!UseExpr.empty()) {
SM.PrintMessage(
SMLoc::getFromPointer(UseExpr.data()), SourceMgr::DK_Error,
"unexpected string after variable definition: '" + UseExpr + "'");
return nullptr;
}
return Context->makeNumExpr(add, nullptr, 0);
}
// Parse the numeric expression itself.
Expr = Expr.ltrim(SpaceChars);
return parseBinop(Expr, SM);
}
bool FileCheckPattern::parsePattern(StringRef PatternStr, StringRef Prefix,
SourceMgr &SM,
const FileCheckRequest &Req) {
bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
PatternLoc = SMLoc::getFromPointer(PatternStr.data());
// Create fake @LINE pseudo variable definition.
StringRef LinePseudo = "@LINE";
uint64_t LineNumber64 = LineNumber;
FileCheckNumericVariable *LinePseudoVar =
Context->makeNumericVariable(LinePseudo, LineNumber64);
Context->GlobalNumericVariableTable[LinePseudo] = LinePseudoVar;
if (!(Req.NoCanonicalizeWhiteSpace && Req.MatchFullLines))
// Ignore trailing whitespace.
while (!PatternStr.empty() &&
(PatternStr.back() == ' ' || PatternStr.back() == '\t'))
PatternStr = PatternStr.substr(0, PatternStr.size() - 1);
// Check that there is something on the line.
if (PatternStr.empty() && CheckTy != Check::CheckEmpty) {
SM.PrintMessage(PatternLoc, SourceMgr::DK_Error,
"found empty check string with prefix '" + Prefix + ":'");
return true;
}
if (!PatternStr.empty() && CheckTy == Check::CheckEmpty) {
SM.PrintMessage(
PatternLoc, SourceMgr::DK_Error,
"found non-empty check string for empty check with prefix '" + Prefix +
":'");
return true;
}
if (CheckTy == Check::CheckEmpty) {
RegExStr = "(\n$)";
return false;
}
// Check to see if this is a fixed string, or if it has regex pieces.
if (!MatchFullLinesHere &&
(PatternStr.size() < 2 || (PatternStr.find("{{") == StringRef::npos &&
PatternStr.find("[[") == StringRef::npos))) {
FixedStr = PatternStr;
return false;
}
if (MatchFullLinesHere) {
RegExStr += '^';
if (!Req.NoCanonicalizeWhiteSpace)
RegExStr += " *";
}
// Paren value #0 is for the fully matched string. Any new parenthesized
// values add from there.
unsigned CurParen = 1;
// Otherwise, there is at least one regex piece. Build up the regex pattern
// by escaping scary characters in fixed strings, building up one big regex.
while (!PatternStr.empty()) {
// RegEx matches.
if (PatternStr.startswith("{{")) {
// This is the start of a regex match. Scan for the }}.
size_t End = PatternStr.find("}}");
if (End == StringRef::npos) {
SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
SourceMgr::DK_Error,
"found start of regex string with no end '}}'");
return true;
}
// Enclose {{}} patterns in parens just like [[]] even though we're not
// capturing the result for any purpose. This is required in case the
// expression contains an alternation like: CHECK: abc{{x|z}}def. We
// want this to turn into: "abc(x|z)def" not "abcx|zdef".
RegExStr += '(';
++CurParen;
if (AddRegExToRegEx(PatternStr.substr(2, End - 2), CurParen, SM))
return true;
RegExStr += ')';
PatternStr = PatternStr.substr(End + 2);
continue;
}
// String and numeric substitution blocks. String substitution blocks come
// in two forms: [[foo:.*]] and [[foo]]. The former matches .* (or some
// other regex) and assigns it to the string variable 'foo'. The latter
// substitutes foo's value. Numeric substitution blocks work the same way
// as string ones, but start with a '#' sign after the double brackets.
// Both string and numeric variable names must satisfy the regular
// expression "[a-zA-Z_][0-9a-zA-Z_]*" to be valid, as this helps catch
// some common errors.
if (PatternStr.startswith("[[")) {
StringRef UnparsedPatternStr = PatternStr.substr(2);
// Find the closing bracket pair ending the match. End is going to be an
// offset relative to the beginning of the match string.
size_t End = FindRegexVarEnd(UnparsedPatternStr, SM);
StringRef MatchStr = UnparsedPatternStr.substr(0, End);
bool IsNumBlock = MatchStr.consume_front("#");
if (End == StringRef::npos) {
SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
SourceMgr::DK_Error,
"Invalid substitution block, no ]] found");
return true;
}
// Strip the substitution block we are parsing. End points to the start
// of the "]]" closing the expression so account for it in computing the
// index of the first unparsed character.
PatternStr = UnparsedPatternStr.substr(End + 2);
bool IsDefinition = false;
StringRef DefName;
StringRef SubstStr;
StringRef MatchRegexp;
size_t SubstInsertIdx = RegExStr.size();
// Parse string variable or legacy numeric expression.
if (!IsNumBlock) {
size_t VarEndIdx = MatchStr.find(":");
size_t SpacePos = MatchStr.substr(0, VarEndIdx).find_first_of(" \t");
if (SpacePos != StringRef::npos) {
SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data() + SpacePos),
SourceMgr::DK_Error, "unexpected whitespace");
return true;
}
// Get the name (e.g. "foo") and verify it is well formed.
bool IsPseudo;
StringRef Name;
StringRef OrigMatchStr = MatchStr;
if (parseVariable(MatchStr, Name, IsPseudo)) {
SM.PrintMessage(SMLoc::getFromPointer(MatchStr.data()),
SourceMgr::DK_Error, "invalid variable name");
return true;
}
IsDefinition = (VarEndIdx != StringRef::npos);
if (IsDefinition) {
if ((IsPseudo || !MatchStr.consume_front(":"))) {
SM.PrintMessage(SMLoc::getFromPointer(Name.data()),
SourceMgr::DK_Error,
"invalid name in string variable definition");
return true;
}
// Detect collisions between string and numeric variables when the
// former is created later than the latter.
if (Context->GlobalNumericVariableTable.find(Name) !=
Context->GlobalNumericVariableTable.end()) {
SM.PrintMessage(
SMLoc::getFromPointer(Name.data()), SourceMgr::DK_Error,
"numeric variable with name '" + Name + "' already exists");
return true;
}
DefName = Name;
MatchRegexp = MatchStr;
} else {
if (IsPseudo) {
MatchStr = OrigMatchStr;
IsNumBlock = true;
} else
SubstStr = Name;
}
}
// Parse numeric substitution block.
FileCheckNumExpr *NumExpr;
FileCheckNumericVariable *DefinedNumericVariable;
if (IsNumBlock) {
NumExpr =
parseNumericSubstitutionBlock(MatchStr, DefinedNumericVariable, SM);
if (NumExpr == nullptr)
return true;
if (DefinedNumericVariable) {
IsDefinition = true;
DefName = DefinedNumericVariable->getName();
MatchRegexp = StringRef("[0-9]+");
} else
SubstStr = MatchStr;
}
// Handle substitutions: [[foo]] and [[#<foo expr>]].
if (!IsDefinition) {
// Handle substitution of string variables that were defined earlier on
// the same line by emitting a backreference. Numeric expressions do
// not support substituting a numeric variable defined on the same
// line.
if (!IsNumBlock && VariableDefs.find(SubstStr) != VariableDefs.end()) {
unsigned CaptureParenGroup = VariableDefs[SubstStr];
if (CaptureParenGroup < 1 || CaptureParenGroup > 9) {
SM.PrintMessage(SMLoc::getFromPointer(SubstStr.data()),
SourceMgr::DK_Error,
"Can't back-reference more than 9 variables");
return true;
}
AddBackrefToRegEx(CaptureParenGroup);
} else {
// Handle substitution of string variables ([[<var>]]) defined in
// previous CHECK patterns, and substitution of numeric expressions.
FileCheckSubstitution *Substitution =
IsNumBlock
? Context->makeNumericSubstitution(SubstStr, NumExpr,
SubstInsertIdx)
: Context->makeStringSubstitution(SubstStr, SubstInsertIdx);
Substitutions.push_back(Substitution);
}
continue;
}
// Handle variable definitions: [[<def>:(...)]] and
// [[#(...)<def>:(...)]].
if (IsNumBlock) {
FileCheckNumExprMatch NumExprDef = {DefinedNumericVariable, CurParen};
NumericVariableDefs[DefName] = NumExprDef;
// This store is done here rather than in match() to allow
// parseNumericVariableUse() to get the pointer to the class instance
// of the right variable definition corresponding to a given numeric
// variable use.
Context->GlobalNumericVariableTable[DefName] = DefinedNumericVariable;
} else {
VariableDefs[DefName] = CurParen;
// Mark the string variable as defined to detect collisions between
// string and numeric variables in parseNumericVariableUse() and
// DefineCmdlineVariables() when the latter is created later than the
// former. We cannot reuse GlobalVariableTable for this by populating
// it with an empty string since we would then lose the ability to
// detect the use of an undefined variable in match().
Context->DefinedVariableTable[DefName] = true;
}
RegExStr += '(';
++CurParen;
if (AddRegExToRegEx(MatchRegexp, CurParen, SM))
return true;
RegExStr += ')';
}
// Handle fixed string matches.
// Find the end, which is the start of the next regex.
size_t FixedMatchEnd = PatternStr.find("{{");
FixedMatchEnd = std::min(FixedMatchEnd, PatternStr.find("[["));
RegExStr += Regex::escape(PatternStr.substr(0, FixedMatchEnd));
PatternStr = PatternStr.substr(FixedMatchEnd);
}
if (MatchFullLinesHere) {
if (!Req.NoCanonicalizeWhiteSpace)
RegExStr += " *";
RegExStr += '$';
}
return false;
}
bool FileCheckPattern::AddRegExToRegEx(StringRef RS, unsigned &CurParen, SourceMgr &SM) {
Regex R(RS);
std::string Error;
if (!R.isValid(Error)) {
SM.PrintMessage(SMLoc::getFromPointer(RS.data()), SourceMgr::DK_Error,
"invalid regex: " + Error);
return true;
}
RegExStr += RS.str();
CurParen += R.getNumMatches();
return false;
}
void FileCheckPattern::AddBackrefToRegEx(unsigned BackrefNum) {
assert(BackrefNum >= 1 && BackrefNum <= 9 && "Invalid backref number");
std::string Backref = std::string("\\") + std::string(1, '0' + BackrefNum);
RegExStr += Backref;
}
size_t FileCheckPattern::match(StringRef Buffer, size_t &MatchLen,
const SourceMgr &SM) const {
// If this is the EOF pattern, match it immediately.
if (CheckTy == Check::CheckEOF) {
MatchLen = 0;
return Buffer.size();
}
// If this is a fixed string pattern, just match it now.
if (!FixedStr.empty()) {
MatchLen = FixedStr.size();
return Buffer.find(FixedStr);
}
// Regex match.
// If there are substitutions, we need to create a temporary string with the
// actual value.
StringRef RegExToMatch = RegExStr;
std::string TmpStr;
if (!Substitutions.empty()) {
TmpStr = RegExStr;
size_t InsertOffset = 0;
// Substitute all string variables and numeric expressions whose values are
// only now known. Use of string variables defined on the same line are
// handled by back-references.
for (const auto &Substitution : Substitutions) {
// Substitute and check for failure (e.g. use of undefined variable).
Optional<std::string> Value = Substitution->getResult();
if (!Value)
return StringRef::npos;
// Plop it into the regex at the adjusted offset.
TmpStr.insert(TmpStr.begin() + Substitution->getIndex() + InsertOffset,
Value->begin(), Value->end());
InsertOffset += Value->size();
}
// Match the newly constructed regex.
RegExToMatch = TmpStr;
}
SmallVector<StringRef, 4> MatchInfo;
if (!Regex(RegExToMatch, Regex::Newline).match(Buffer, &MatchInfo))
return StringRef::npos;
// Successful regex match.
assert(!MatchInfo.empty() && "Didn't get any match");
StringRef FullMatch = MatchInfo[0];
// If this defines any string variables, remember their values.
for (const auto &VariableDef : VariableDefs) {
assert(VariableDef.second < MatchInfo.size() && "Internal paren error");
Context->GlobalVariableTable[VariableDef.first] =
MatchInfo[VariableDef.second];
}
// If this defines any numeric variables, remember their values.
for (const auto &NumericVariableDef : NumericVariableDefs) {
const FileCheckNumExprMatch &NumericVariableMatch =
NumericVariableDef.getValue();
unsigned CaptureParenGroup = NumericVariableMatch.CaptureParenGroup;
assert(CaptureParenGroup < MatchInfo.size() && "Internal paren error");
FileCheckNumericVariable *DefinedNumericVariable =
NumericVariableMatch.DefinedNumericVariable;
StringRef MatchedValue = MatchInfo[CaptureParenGroup];
uint64_t Val;
if (MatchedValue.getAsInteger(10, Val)) {
SM.PrintMessage(SMLoc::getFromPointer(MatchedValue.data()),
SourceMgr::DK_Error, "Unable to represent numeric value");
}
if (DefinedNumericVariable->setValue(Val))
assert(false && "Numeric variable redefined");
}
// Like CHECK-NEXT, CHECK-EMPTY's match range is considered to start after
// the required preceding newline, which is consumed by the pattern in the
// case of CHECK-EMPTY but not CHECK-NEXT.
size_t MatchStartSkip = CheckTy == Check::CheckEmpty;
MatchLen = FullMatch.size() - MatchStartSkip;
return FullMatch.data() - Buffer.data() + MatchStartSkip;
}
unsigned FileCheckPattern::computeMatchDistance(StringRef Buffer) const {
// Just compute the number of matching characters. For regular expressions, we
// just compare against the regex itself and hope for the best.
//
// FIXME: One easy improvement here is have the regex lib generate a single
// example regular expression which matches, and use that as the example
// string.
StringRef ExampleString(FixedStr);
if (ExampleString.empty())
ExampleString = RegExStr;
// Only compare up to the first line in the buffer, or the string size.
StringRef BufferPrefix = Buffer.substr(0, ExampleString.size());
BufferPrefix = BufferPrefix.split('\n').first;
return BufferPrefix.edit_distance(ExampleString);
}
void FileCheckPattern::printSubstitutions(const SourceMgr &SM, StringRef Buffer,
SMRange MatchRange) const {
// Print what we know about substitutions.
if (!Substitutions.empty()) {
for (const auto &Substitution : Substitutions) {
SmallString<256> Msg;
raw_svector_ostream OS(Msg);
Optional<std::string> MatchedValue = Substitution->getResult();
// Substitution failed or is not known at match time, print the undefined
// variable it uses.
if (!MatchedValue) {
StringRef UndefVarName = Substitution->getUndefVarName();
if (UndefVarName.empty())
continue;
OS << "uses undefined variable \"";
OS.write_escaped(UndefVarName) << "\"";
} else {
// Substitution succeeded. Print substituted value.
OS << "with \"";
OS.write_escaped(Substitution->getFromString()) << "\" equal to \"";
OS.write_escaped(*MatchedValue) << "\"";
}
if (MatchRange.isValid())
SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note, OS.str(),
{MatchRange});
else
SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
SourceMgr::DK_Note, OS.str());
}
}
}
static SMRange ProcessMatchResult(FileCheckDiag::MatchType MatchTy,
const SourceMgr &SM, SMLoc Loc,
Check::FileCheckType CheckTy,
StringRef Buffer, size_t Pos, size_t Len,
std::vector<FileCheckDiag> *Diags,
bool AdjustPrevDiag = false) {
SMLoc Start = SMLoc::getFromPointer(Buffer.data() + Pos);
SMLoc End = SMLoc::getFromPointer(Buffer.data() + Pos + Len);
SMRange Range(Start, End);
if (Diags) {
if (AdjustPrevDiag)
Diags->rbegin()->MatchTy = MatchTy;
else
Diags->emplace_back(SM, CheckTy, Loc, MatchTy, Range);
}
return Range;
}
void FileCheckPattern::printFuzzyMatch(
const SourceMgr &SM, StringRef Buffer,
std::vector<FileCheckDiag> *Diags) const {
// Attempt to find the closest/best fuzzy match. Usually an error happens
// because some string in the output didn't exactly match. In these cases, we
// would like to show the user a best guess at what "should have" matched, to
// save them having to actually check the input manually.
size_t NumLinesForward = 0;
size_t Best = StringRef::npos;
double BestQuality = 0;
// Use an arbitrary 4k limit on how far we will search.
for (size_t i = 0, e = std::min(size_t(4096), Buffer.size()); i != e; ++i) {
if (Buffer[i] == '\n')
++NumLinesForward;
// Patterns have leading whitespace stripped, so skip whitespace when
// looking for something which looks like a pattern.
if (Buffer[i] == ' ' || Buffer[i] == '\t')
continue;
// Compute the "quality" of this match as an arbitrary combination of the
// match distance and the number of lines skipped to get to this match.
unsigned Distance = computeMatchDistance(Buffer.substr(i));
double Quality = Distance + (NumLinesForward / 100.);
if (Quality < BestQuality || Best == StringRef::npos) {
Best = i;
BestQuality = Quality;
}
}
// Print the "possible intended match here" line if we found something
// reasonable and not equal to what we showed in the "scanning from here"
// line.
if (Best && Best != StringRef::npos && BestQuality < 50) {
SMRange MatchRange =
ProcessMatchResult(FileCheckDiag::MatchFuzzy, SM, getLoc(),
getCheckTy(), Buffer, Best, 0, Diags);
SM.PrintMessage(MatchRange.Start, SourceMgr::DK_Note,
"possible intended match here");
// FIXME: If we wanted to be really friendly we would show why the match
// failed, as it can be hard to spot simple one character differences.
}
}
Optional<StringRef>
FileCheckPatternContext::getPatternVarValue(StringRef VarName) {
auto VarIter = GlobalVariableTable.find(VarName);
if (VarIter == GlobalVariableTable.end())
return None;
return VarIter->second;
}
FileCheckNumExpr *
FileCheckPatternContext::makeNumExpr(binop_eval_t EvalBinop,
FileCheckNumericVariable *OperandLeft,
uint64_t OperandRight) {
NumExprs.push_back(llvm::make_unique<FileCheckNumExpr>(EvalBinop, OperandLeft,
OperandRight));
return NumExprs.back().get();
}
template <class... Types>
FileCheckNumericVariable *
FileCheckPatternContext::makeNumericVariable(Types... args) {
NumericVariables.push_back(
llvm::make_unique<FileCheckNumericVariable>(args...));
return NumericVariables.back().get();
}
FileCheckSubstitution *
FileCheckPatternContext::makeStringSubstitution(StringRef VarName,
size_t InsertIdx) {
Substitutions.push_back(
llvm::make_unique<FileCheckStringSubstitution>(this, VarName, InsertIdx));
return Substitutions.back().get();
}
FileCheckSubstitution *FileCheckPatternContext::makeNumericSubstitution(
StringRef Expr, FileCheckNumExpr *NumExpr, size_t InsertIdx) {
Substitutions.push_back(llvm::make_unique<FileCheckNumericSubstitution>(
this, Expr, NumExpr, InsertIdx));
return Substitutions.back().get();
}
size_t FileCheckPattern::FindRegexVarEnd(StringRef Str, SourceMgr &SM) {
// Offset keeps track of the current offset within the input Str
size_t Offset = 0;
// [...] Nesting depth
size_t BracketDepth = 0;
while (!Str.empty()) {
if (Str.startswith("]]") && BracketDepth == 0)
return Offset;
if (Str[0] == '\\') {
// Backslash escapes the next char within regexes, so skip them both.
Str = Str.substr(2);
Offset += 2;
} else {
switch (Str[0]) {
default:
break;
case '[':
BracketDepth++;
break;
case ']':
if (BracketDepth == 0) {
SM.PrintMessage(SMLoc::getFromPointer(Str.data()),
SourceMgr::DK_Error,
"missing closing \"]\" for regex variable");
exit(1);
}
BracketDepth--;
break;
}
Str = Str.substr(1);
Offset++;
}
}
return StringRef::npos;
}
StringRef FileCheck::CanonicalizeFile(MemoryBuffer &MB,
SmallVectorImpl<char> &OutputBuffer) {
OutputBuffer.reserve(MB.getBufferSize());
for (const char *Ptr = MB.getBufferStart(), *End = MB.getBufferEnd();
Ptr != End; ++Ptr) {
// Eliminate trailing dosish \r.
if (Ptr <= End - 2 && Ptr[0] == '\r' && Ptr[1] == '\n') {
continue;
}
// If current char is not a horizontal whitespace or if horizontal
// whitespace canonicalization is disabled, dump it to output as is.
if (Req.NoCanonicalizeWhiteSpace || (*Ptr != ' ' && *Ptr != '\t')) {
OutputBuffer.push_back(*Ptr);
continue;
}
// Otherwise, add one space and advance over neighboring space.
OutputBuffer.push_back(' ');
while (Ptr + 1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t'))
++Ptr;
}
// Add a null byte and then return all but that byte.
OutputBuffer.push_back('\0');
return StringRef(OutputBuffer.data(), OutputBuffer.size() - 1);
}
FileCheckDiag::FileCheckDiag(const SourceMgr &SM,
const Check::FileCheckType &CheckTy,
SMLoc CheckLoc, MatchType MatchTy,
SMRange InputRange)
: CheckTy(CheckTy), MatchTy(MatchTy) {
auto Start = SM.getLineAndColumn(InputRange.Start);
auto End = SM.getLineAndColumn(InputRange.End);
InputStartLine = Start.first;
InputStartCol = Start.second;
InputEndLine = End.first;
InputEndCol = End.second;
Start = SM.getLineAndColumn(CheckLoc);
CheckLine = Start.first;
CheckCol = Start.second;
}
static bool IsPartOfWord(char c) {
return (isalnum(c) || c == '-' || c == '_');
}
Check::FileCheckType &Check::FileCheckType::setCount(int C) {
assert(Count > 0 && "zero and negative counts are not supported");
assert((C == 1 || Kind == CheckPlain) &&
"count supported only for plain CHECK directives");
Count = C;
return *this;
}
std::string Check::FileCheckType::getDescription(StringRef Prefix) const {
switch (Kind) {
case Check::CheckNone:
return "invalid";
case Check::CheckPlain:
if (Count > 1)
return Prefix.str() + "-COUNT";
return Prefix;
case Check::CheckNext:
return Prefix.str() + "-NEXT";
case Check::CheckSame:
return Prefix.str() + "-SAME";
case Check::CheckNot:
return Prefix.str() + "-NOT";
case Check::CheckDAG:
return Prefix.str() + "-DAG";
case Check::CheckLabel:
return Prefix.str() + "-LABEL";
case Check::CheckEmpty:
return Prefix.str() + "-EMPTY";
case Check::CheckEOF:
return "implicit EOF";
case Check::CheckBadNot:
return "bad NOT";
case Check::CheckBadCount:
return "bad COUNT";
}
llvm_unreachable("unknown FileCheckType");
}
static std::pair<Check::FileCheckType, StringRef>
FindCheckType(StringRef Buffer, StringRef Prefix) {
if (Buffer.size() <= Prefix.size())
return {Check::CheckNone, StringRef()};
char NextChar = Buffer[Prefix.size()];
StringRef Rest = Buffer.drop_front(Prefix.size() + 1);
// Verify that the : is present after the prefix.
if (NextChar == ':')
return {Check::CheckPlain, Rest};
if (NextChar != '-')
return {Check::CheckNone, StringRef()};
if (Rest.consume_front("COUNT-")) {
int64_t Count;
if (Rest.consumeInteger(10, Count))
// Error happened in parsing integer.
return {Check::CheckBadCount, Rest};
if (Count <= 0 || Count > INT32_MAX)
return {Check::CheckBadCount, Rest};
if (!Rest.consume_front(":"))
return {Check::CheckBadCount, Rest};
return {Check::FileCheckType(Check::CheckPlain).setCount(Count), Rest};
}
if (Rest.consume_front("NEXT:"))
return {Check::CheckNext, Rest};
if (Rest.consume_front("SAME:"))
return {Check::CheckSame, Rest};
if (Rest.consume_front("NOT:"))
return {Check::CheckNot, Rest};
if (Rest.consume_front("DAG:"))
return {Check::CheckDAG, Rest};
if (Rest.consume_front("LABEL:"))
return {Check::CheckLabel, Rest};
if (Rest.consume_front("EMPTY:"))
return {Check::CheckEmpty, Rest};
// You can't combine -NOT with another suffix.
if (Rest.startswith("DAG-NOT:") || Rest.startswith("NOT-DAG:") ||
Rest.startswith("NEXT-NOT:") || Rest.startswith("NOT-NEXT:") ||
Rest.startswith("SAME-NOT:") || Rest.startswith("NOT-SAME:") ||
Rest.startswith("EMPTY-NOT:") || Rest.startswith("NOT-EMPTY:"))
return {Check::CheckBadNot, Rest};
return {Check::CheckNone, Rest};
}