forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileCheck.cpp
2834 lines (2490 loc) · 107 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/FileCheck/FileCheck.h"
#include "FileCheckImpl.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/CheckedArithmetic.h"
#include "llvm/Support/FormatVariadic.h"
#include <cstdint>
#include <list>
#include <set>
#include <tuple>
#include <utility>
using namespace llvm;
StringRef ExpressionFormat::toString() const {
switch (Value) {
case Kind::NoFormat:
return StringRef("<none>");
case Kind::Unsigned:
return StringRef("%u");
case Kind::Signed:
return StringRef("%d");
case Kind::HexUpper:
return StringRef("%X");
case Kind::HexLower:
return StringRef("%x");
}
llvm_unreachable("unknown expression format");
}
Expected<std::string> ExpressionFormat::getWildcardRegex() const {
StringRef AlternateFormPrefix = AlternateForm ? StringRef("0x") : StringRef();
auto CreatePrecisionRegex = [&](StringRef S) {
return (Twine(AlternateFormPrefix) + S + Twine('{') + Twine(Precision) +
"}")
.str();
};
switch (Value) {
case Kind::Unsigned:
if (Precision)
return CreatePrecisionRegex("([1-9][0-9]*)?[0-9]");
return std::string("[0-9]+");
case Kind::Signed:
if (Precision)
return CreatePrecisionRegex("-?([1-9][0-9]*)?[0-9]");
return std::string("-?[0-9]+");
case Kind::HexUpper:
if (Precision)
return CreatePrecisionRegex("([1-9A-F][0-9A-F]*)?[0-9A-F]");
return (Twine(AlternateFormPrefix) + Twine("[0-9A-F]+")).str();
case Kind::HexLower:
if (Precision)
return CreatePrecisionRegex("([1-9a-f][0-9a-f]*)?[0-9a-f]");
return (Twine(AlternateFormPrefix) + Twine("[0-9a-f]+")).str();
default:
return createStringError(std::errc::invalid_argument,
"trying to match value with invalid format");
}
}
Expected<std::string>
ExpressionFormat::getMatchingString(ExpressionValue IntegerValue) const {
uint64_t AbsoluteValue;
StringRef SignPrefix = IntegerValue.isNegative() ? "-" : "";
if (Value == Kind::Signed) {
Expected<int64_t> SignedValue = IntegerValue.getSignedValue();
if (!SignedValue)
return SignedValue.takeError();
if (*SignedValue < 0)
AbsoluteValue = cantFail(IntegerValue.getAbsolute().getUnsignedValue());
else
AbsoluteValue = *SignedValue;
} else {
Expected<uint64_t> UnsignedValue = IntegerValue.getUnsignedValue();
if (!UnsignedValue)
return UnsignedValue.takeError();
AbsoluteValue = *UnsignedValue;
}
std::string AbsoluteValueStr;
switch (Value) {
case Kind::Unsigned:
case Kind::Signed:
AbsoluteValueStr = utostr(AbsoluteValue);
break;
case Kind::HexUpper:
case Kind::HexLower:
AbsoluteValueStr = utohexstr(AbsoluteValue, Value == Kind::HexLower);
break;
default:
return createStringError(std::errc::invalid_argument,
"trying to match value with invalid format");
}
StringRef AlternateFormPrefix = AlternateForm ? StringRef("0x") : StringRef();
if (Precision > AbsoluteValueStr.size()) {
unsigned LeadingZeros = Precision - AbsoluteValueStr.size();
return (Twine(SignPrefix) + Twine(AlternateFormPrefix) +
std::string(LeadingZeros, '0') + AbsoluteValueStr)
.str();
}
return (Twine(SignPrefix) + Twine(AlternateFormPrefix) + AbsoluteValueStr)
.str();
}
Expected<ExpressionValue>
ExpressionFormat::valueFromStringRepr(StringRef StrVal,
const SourceMgr &SM) const {
bool ValueIsSigned = Value == Kind::Signed;
// Both the FileCheck utility and library only call this method with a valid
// value in StrVal. This is guaranteed by the regex returned by
// getWildcardRegex() above. Only underflow and overflow errors can thus
// occur. However new uses of this method could be added in the future so
// the error message does not make assumptions about StrVal.
StringRef IntegerParseErrorStr = "unable to represent numeric value";
if (ValueIsSigned) {
int64_t SignedValue;
if (StrVal.getAsInteger(10, SignedValue))
return ErrorDiagnostic::get(SM, StrVal, IntegerParseErrorStr);
return ExpressionValue(SignedValue);
}
bool Hex = Value == Kind::HexUpper || Value == Kind::HexLower;
uint64_t UnsignedValue;
bool MissingFormPrefix = AlternateForm && !StrVal.consume_front("0x");
if (StrVal.getAsInteger(Hex ? 16 : 10, UnsignedValue))
return ErrorDiagnostic::get(SM, StrVal, IntegerParseErrorStr);
// Error out for a missing prefix only now that we know we have an otherwise
// valid integer. For example, "-0x18" is reported above instead.
if (MissingFormPrefix)
return ErrorDiagnostic::get(SM, StrVal, "missing alternate form prefix");
return ExpressionValue(UnsignedValue);
}
static int64_t getAsSigned(uint64_t UnsignedValue) {
// Use memcpy to reinterpret the bitpattern in Value since casting to
// signed is implementation-defined if the unsigned value is too big to be
// represented in the signed type and using an union violates type aliasing
// rules.
int64_t SignedValue;
memcpy(&SignedValue, &UnsignedValue, sizeof(SignedValue));
return SignedValue;
}
Expected<int64_t> ExpressionValue::getSignedValue() const {
if (Negative)
return getAsSigned(Value);
if (Value > (uint64_t)std::numeric_limits<int64_t>::max())
return make_error<OverflowError>();
// Value is in the representable range of int64_t so we can use cast.
return static_cast<int64_t>(Value);
}
Expected<uint64_t> ExpressionValue::getUnsignedValue() const {
if (Negative)
return make_error<OverflowError>();
return Value;
}
ExpressionValue ExpressionValue::getAbsolute() const {
if (!Negative)
return *this;
int64_t SignedValue = getAsSigned(Value);
int64_t MaxInt64 = std::numeric_limits<int64_t>::max();
// Absolute value can be represented as int64_t.
if (SignedValue >= -MaxInt64)
return ExpressionValue(-getAsSigned(Value));
// -X == -(max int64_t + Rem), negate each component independently.
SignedValue += MaxInt64;
uint64_t RemainingValueAbsolute = -SignedValue;
return ExpressionValue(MaxInt64 + RemainingValueAbsolute);
}
Expected<ExpressionValue> llvm::operator+(const ExpressionValue &LeftOperand,
const ExpressionValue &RightOperand) {
if (LeftOperand.isNegative() && RightOperand.isNegative()) {
int64_t LeftValue = cantFail(LeftOperand.getSignedValue());
int64_t RightValue = cantFail(RightOperand.getSignedValue());
Optional<int64_t> Result = checkedAdd<int64_t>(LeftValue, RightValue);
if (!Result)
return make_error<OverflowError>();
return ExpressionValue(*Result);
}
// (-A) + B == B - A.
if (LeftOperand.isNegative())
return RightOperand - LeftOperand.getAbsolute();
// A + (-B) == A - B.
if (RightOperand.isNegative())
return LeftOperand - RightOperand.getAbsolute();
// Both values are positive at this point.
uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
Optional<uint64_t> Result =
checkedAddUnsigned<uint64_t>(LeftValue, RightValue);
if (!Result)
return make_error<OverflowError>();
return ExpressionValue(*Result);
}
Expected<ExpressionValue> llvm::operator-(const ExpressionValue &LeftOperand,
const ExpressionValue &RightOperand) {
// Result will be negative and thus might underflow.
if (LeftOperand.isNegative() && !RightOperand.isNegative()) {
int64_t LeftValue = cantFail(LeftOperand.getSignedValue());
uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
// Result <= -1 - (max int64_t) which overflows on 1- and 2-complement.
if (RightValue > (uint64_t)std::numeric_limits<int64_t>::max())
return make_error<OverflowError>();
Optional<int64_t> Result =
checkedSub(LeftValue, static_cast<int64_t>(RightValue));
if (!Result)
return make_error<OverflowError>();
return ExpressionValue(*Result);
}
// (-A) - (-B) == B - A.
if (LeftOperand.isNegative())
return RightOperand.getAbsolute() - LeftOperand.getAbsolute();
// A - (-B) == A + B.
if (RightOperand.isNegative())
return LeftOperand + RightOperand.getAbsolute();
// Both values are positive at this point.
uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
if (LeftValue >= RightValue)
return ExpressionValue(LeftValue - RightValue);
else {
uint64_t AbsoluteDifference = RightValue - LeftValue;
uint64_t MaxInt64 = std::numeric_limits<int64_t>::max();
// Value might underflow.
if (AbsoluteDifference > MaxInt64) {
AbsoluteDifference -= MaxInt64;
int64_t Result = -MaxInt64;
int64_t MinInt64 = std::numeric_limits<int64_t>::min();
// Underflow, tested by:
// abs(Result + (max int64_t)) > abs((min int64_t) + (max int64_t))
if (AbsoluteDifference > static_cast<uint64_t>(-(MinInt64 - Result)))
return make_error<OverflowError>();
Result -= static_cast<int64_t>(AbsoluteDifference);
return ExpressionValue(Result);
}
return ExpressionValue(-static_cast<int64_t>(AbsoluteDifference));
}
}
Expected<ExpressionValue> llvm::operator*(const ExpressionValue &LeftOperand,
const ExpressionValue &RightOperand) {
// -A * -B == A * B
if (LeftOperand.isNegative() && RightOperand.isNegative())
return LeftOperand.getAbsolute() * RightOperand.getAbsolute();
// A * -B == -B * A
if (RightOperand.isNegative())
return RightOperand * LeftOperand;
assert(!RightOperand.isNegative() && "Unexpected negative operand!");
// Result will be negative and can underflow.
if (LeftOperand.isNegative()) {
auto Result = LeftOperand.getAbsolute() * RightOperand.getAbsolute();
if (!Result)
return Result;
return ExpressionValue(0) - *Result;
}
// Result will be positive and can overflow.
uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
Optional<uint64_t> Result =
checkedMulUnsigned<uint64_t>(LeftValue, RightValue);
if (!Result)
return make_error<OverflowError>();
return ExpressionValue(*Result);
}
Expected<ExpressionValue> llvm::operator/(const ExpressionValue &LeftOperand,
const ExpressionValue &RightOperand) {
// -A / -B == A / B
if (LeftOperand.isNegative() && RightOperand.isNegative())
return LeftOperand.getAbsolute() / RightOperand.getAbsolute();
// Check for divide by zero.
if (RightOperand == ExpressionValue(0))
return make_error<OverflowError>();
// Result will be negative and can underflow.
if (LeftOperand.isNegative() || RightOperand.isNegative())
return ExpressionValue(0) -
cantFail(LeftOperand.getAbsolute() / RightOperand.getAbsolute());
uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
return ExpressionValue(LeftValue / RightValue);
}
Expected<ExpressionValue> llvm::max(const ExpressionValue &LeftOperand,
const ExpressionValue &RightOperand) {
if (LeftOperand.isNegative() && RightOperand.isNegative()) {
int64_t LeftValue = cantFail(LeftOperand.getSignedValue());
int64_t RightValue = cantFail(RightOperand.getSignedValue());
return ExpressionValue(std::max(LeftValue, RightValue));
}
if (!LeftOperand.isNegative() && !RightOperand.isNegative()) {
uint64_t LeftValue = cantFail(LeftOperand.getUnsignedValue());
uint64_t RightValue = cantFail(RightOperand.getUnsignedValue());
return ExpressionValue(std::max(LeftValue, RightValue));
}
if (LeftOperand.isNegative())
return RightOperand;
return LeftOperand;
}
Expected<ExpressionValue> llvm::min(const ExpressionValue &LeftOperand,
const ExpressionValue &RightOperand) {
if (cantFail(max(LeftOperand, RightOperand)) == LeftOperand)
return RightOperand;
return LeftOperand;
}
Expected<ExpressionValue> NumericVariableUse::eval() const {
Optional<ExpressionValue> Value = Variable->getValue();
if (Value)
return *Value;
return make_error<UndefVarError>(getExpressionStr());
}
Expected<ExpressionValue> BinaryOperation::eval() const {
Expected<ExpressionValue> LeftOp = LeftOperand->eval();
Expected<ExpressionValue> RightOp = RightOperand->eval();
// Bubble up any error (e.g. undefined variables) in the recursive
// evaluation.
if (!LeftOp || !RightOp) {
Error Err = Error::success();
if (!LeftOp)
Err = joinErrors(std::move(Err), LeftOp.takeError());
if (!RightOp)
Err = joinErrors(std::move(Err), RightOp.takeError());
return std::move(Err);
}
return EvalBinop(*LeftOp, *RightOp);
}
Expected<ExpressionFormat>
BinaryOperation::getImplicitFormat(const SourceMgr &SM) const {
Expected<ExpressionFormat> LeftFormat = LeftOperand->getImplicitFormat(SM);
Expected<ExpressionFormat> RightFormat = RightOperand->getImplicitFormat(SM);
if (!LeftFormat || !RightFormat) {
Error Err = Error::success();
if (!LeftFormat)
Err = joinErrors(std::move(Err), LeftFormat.takeError());
if (!RightFormat)
Err = joinErrors(std::move(Err), RightFormat.takeError());
return std::move(Err);
}
if (*LeftFormat != ExpressionFormat::Kind::NoFormat &&
*RightFormat != ExpressionFormat::Kind::NoFormat &&
*LeftFormat != *RightFormat)
return ErrorDiagnostic::get(
SM, getExpressionStr(),
"implicit format conflict between '" + LeftOperand->getExpressionStr() +
"' (" + LeftFormat->toString() + ") and '" +
RightOperand->getExpressionStr() + "' (" + RightFormat->toString() +
"), need an explicit format specifier");
return *LeftFormat != ExpressionFormat::Kind::NoFormat ? *LeftFormat
: *RightFormat;
}
Expected<std::string> NumericSubstitution::getResult() const {
assert(ExpressionPointer->getAST() != nullptr &&
"Substituting empty expression");
Expected<ExpressionValue> EvaluatedValue =
ExpressionPointer->getAST()->eval();
if (!EvaluatedValue)
return EvaluatedValue.takeError();
ExpressionFormat Format = ExpressionPointer->getFormat();
return Format.getMatchingString(*EvaluatedValue);
}
Expected<std::string> StringSubstitution::getResult() const {
// Look up the value and escape it so that we can put it into the regex.
Expected<StringRef> VarVal = Context->getPatternVarValue(FromStr);
if (!VarVal)
return VarVal.takeError();
return Regex::escape(*VarVal);
}
bool Pattern::isValidVarNameStart(char C) { return C == '_' || isAlpha(C); }
Expected<Pattern::VariableProperties>
Pattern::parseVariable(StringRef &Str, const SourceMgr &SM) {
if (Str.empty())
return ErrorDiagnostic::get(SM, Str, "empty variable name");
size_t I = 0;
bool IsPseudo = Str[0] == '@';
// Global vars start with '$'.
if (Str[0] == '$' || IsPseudo)
++I;
if (!isValidVarNameStart(Str[I++]))
return ErrorDiagnostic::get(SM, Str, "invalid variable name");
for (size_t E = Str.size(); I != E; ++I)
// Variable names are composed of alphanumeric characters and underscores.
if (Str[I] != '_' && !isAlnum(Str[I]))
break;
StringRef Name = Str.take_front(I);
Str = Str.substr(I);
return VariableProperties {Name, IsPseudo};
}
// StringRef holding all characters considered as horizontal whitespaces by
// FileCheck input canonicalization.
constexpr StringLiteral 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;
}
char OverflowError::ID = 0;
char UndefVarError::ID = 0;
char ErrorDiagnostic::ID = 0;
char NotFoundError::ID = 0;
char ErrorReported::ID = 0;
Expected<NumericVariable *> Pattern::parseNumericVariableDefinition(
StringRef &Expr, FileCheckPatternContext *Context,
Optional<size_t> LineNumber, ExpressionFormat ImplicitFormat,
const SourceMgr &SM) {
Expected<VariableProperties> ParseVarResult = parseVariable(Expr, SM);
if (!ParseVarResult)
return ParseVarResult.takeError();
StringRef Name = ParseVarResult->Name;
if (ParseVarResult->IsPseudo)
return ErrorDiagnostic::get(
SM, Name, "definition of pseudo numeric variable unsupported");
// Detect collisions between string and numeric variables when the latter
// is created later than the former.
if (Context->DefinedVariableTable.find(Name) !=
Context->DefinedVariableTable.end())
return ErrorDiagnostic::get(
SM, Name, "string variable with name '" + Name + "' already exists");
Expr = Expr.ltrim(SpaceChars);
if (!Expr.empty())
return ErrorDiagnostic::get(
SM, Expr, "unexpected characters after numeric variable name");
NumericVariable *DefinedNumericVariable;
auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
if (VarTableIter != Context->GlobalNumericVariableTable.end()) {
DefinedNumericVariable = VarTableIter->second;
if (DefinedNumericVariable->getImplicitFormat() != ImplicitFormat)
return ErrorDiagnostic::get(
SM, Expr, "format different from previous variable definition");
} else
DefinedNumericVariable =
Context->makeNumericVariable(Name, ImplicitFormat, LineNumber);
return DefinedNumericVariable;
}
Expected<std::unique_ptr<NumericVariableUse>> Pattern::parseNumericVariableUse(
StringRef Name, bool IsPseudo, Optional<size_t> LineNumber,
FileCheckPatternContext *Context, const SourceMgr &SM) {
if (IsPseudo && !Name.equals("@LINE"))
return ErrorDiagnostic::get(
SM, Name, "invalid pseudo numeric variable '" + Name + "'");
// Numeric variable definitions and uses are parsed in the order in which
// they appear in the CHECK patterns. For each definition, the pointer to the
// class instance of the corresponding numeric variable definition is stored
// in GlobalNumericVariableTable in parsePattern. Therefore, if the pointer
// we get below is null, it means no such variable was defined before. When
// that happens, we create a dummy variable so that parsing can continue. All
// uses of undefined variables, whether string or numeric, are then diagnosed
// in printNoMatch() after failing to match.
auto VarTableIter = Context->GlobalNumericVariableTable.find(Name);
NumericVariable *NumericVariable;
if (VarTableIter != Context->GlobalNumericVariableTable.end())
NumericVariable = VarTableIter->second;
else {
NumericVariable = Context->makeNumericVariable(
Name, ExpressionFormat(ExpressionFormat::Kind::Unsigned));
Context->GlobalNumericVariableTable[Name] = NumericVariable;
}
Optional<size_t> DefLineNumber = NumericVariable->getDefLineNumber();
if (DefLineNumber && LineNumber && *DefLineNumber == *LineNumber)
return ErrorDiagnostic::get(
SM, Name,
"numeric variable '" + Name +
"' defined earlier in the same CHECK directive");
return std::make_unique<NumericVariableUse>(Name, NumericVariable);
}
Expected<std::unique_ptr<ExpressionAST>> Pattern::parseNumericOperand(
StringRef &Expr, AllowedOperand AO, bool MaybeInvalidConstraint,
Optional<size_t> LineNumber, FileCheckPatternContext *Context,
const SourceMgr &SM) {
if (Expr.startswith("(")) {
if (AO != AllowedOperand::Any)
return ErrorDiagnostic::get(
SM, Expr, "parenthesized expression not permitted here");
return parseParenExpr(Expr, LineNumber, Context, SM);
}
if (AO == AllowedOperand::LineVar || AO == AllowedOperand::Any) {
// Try to parse as a numeric variable use.
Expected<Pattern::VariableProperties> ParseVarResult =
parseVariable(Expr, SM);
if (ParseVarResult) {
// Try to parse a function call.
if (Expr.ltrim(SpaceChars).startswith("(")) {
if (AO != AllowedOperand::Any)
return ErrorDiagnostic::get(SM, ParseVarResult->Name,
"unexpected function call");
return parseCallExpr(Expr, ParseVarResult->Name, LineNumber, Context,
SM);
}
return parseNumericVariableUse(ParseVarResult->Name,
ParseVarResult->IsPseudo, LineNumber,
Context, SM);
}
if (AO == AllowedOperand::LineVar)
return ParseVarResult.takeError();
// Ignore the error and retry parsing as a literal.
consumeError(ParseVarResult.takeError());
}
// Otherwise, parse it as a literal.
int64_t SignedLiteralValue;
uint64_t UnsignedLiteralValue;
StringRef SaveExpr = Expr;
// Accept both signed and unsigned literal, default to signed literal.
if (!Expr.consumeInteger((AO == AllowedOperand::LegacyLiteral) ? 10 : 0,
UnsignedLiteralValue))
return std::make_unique<ExpressionLiteral>(SaveExpr.drop_back(Expr.size()),
UnsignedLiteralValue);
Expr = SaveExpr;
if (AO == AllowedOperand::Any && !Expr.consumeInteger(0, SignedLiteralValue))
return std::make_unique<ExpressionLiteral>(SaveExpr.drop_back(Expr.size()),
SignedLiteralValue);
return ErrorDiagnostic::get(
SM, Expr,
Twine("invalid ") +
(MaybeInvalidConstraint ? "matching constraint or " : "") +
"operand format");
}
Expected<std::unique_ptr<ExpressionAST>>
Pattern::parseParenExpr(StringRef &Expr, Optional<size_t> LineNumber,
FileCheckPatternContext *Context, const SourceMgr &SM) {
Expr = Expr.ltrim(SpaceChars);
assert(Expr.startswith("("));
// Parse right operand.
Expr.consume_front("(");
Expr = Expr.ltrim(SpaceChars);
if (Expr.empty())
return ErrorDiagnostic::get(SM, Expr, "missing operand in expression");
// Note: parseNumericOperand handles nested opening parentheses.
Expected<std::unique_ptr<ExpressionAST>> SubExprResult = parseNumericOperand(
Expr, AllowedOperand::Any, /*MaybeInvalidConstraint=*/false, LineNumber,
Context, SM);
Expr = Expr.ltrim(SpaceChars);
while (SubExprResult && !Expr.empty() && !Expr.startswith(")")) {
StringRef OrigExpr = Expr;
SubExprResult = parseBinop(OrigExpr, Expr, std::move(*SubExprResult), false,
LineNumber, Context, SM);
Expr = Expr.ltrim(SpaceChars);
}
if (!SubExprResult)
return SubExprResult;
if (!Expr.consume_front(")")) {
return ErrorDiagnostic::get(SM, Expr,
"missing ')' at end of nested expression");
}
return SubExprResult;
}
Expected<std::unique_ptr<ExpressionAST>>
Pattern::parseBinop(StringRef Expr, StringRef &RemainingExpr,
std::unique_ptr<ExpressionAST> LeftOp,
bool IsLegacyLineExpr, Optional<size_t> LineNumber,
FileCheckPatternContext *Context, const SourceMgr &SM) {
RemainingExpr = RemainingExpr.ltrim(SpaceChars);
if (RemainingExpr.empty())
return std::move(LeftOp);
// Check if this is a supported operation and select a function to perform
// it.
SMLoc OpLoc = SMLoc::getFromPointer(RemainingExpr.data());
char Operator = popFront(RemainingExpr);
binop_eval_t EvalBinop;
switch (Operator) {
case '+':
EvalBinop = operator+;
break;
case '-':
EvalBinop = operator-;
break;
default:
return ErrorDiagnostic::get(
SM, OpLoc, Twine("unsupported operation '") + Twine(Operator) + "'");
}
// Parse right operand.
RemainingExpr = RemainingExpr.ltrim(SpaceChars);
if (RemainingExpr.empty())
return ErrorDiagnostic::get(SM, RemainingExpr,
"missing operand in expression");
// The second operand in a legacy @LINE expression is always a literal.
AllowedOperand AO =
IsLegacyLineExpr ? AllowedOperand::LegacyLiteral : AllowedOperand::Any;
Expected<std::unique_ptr<ExpressionAST>> RightOpResult =
parseNumericOperand(RemainingExpr, AO, /*MaybeInvalidConstraint=*/false,
LineNumber, Context, SM);
if (!RightOpResult)
return RightOpResult;
Expr = Expr.drop_back(RemainingExpr.size());
return std::make_unique<BinaryOperation>(Expr, EvalBinop, std::move(LeftOp),
std::move(*RightOpResult));
}
Expected<std::unique_ptr<ExpressionAST>>
Pattern::parseCallExpr(StringRef &Expr, StringRef FuncName,
Optional<size_t> LineNumber,
FileCheckPatternContext *Context, const SourceMgr &SM) {
Expr = Expr.ltrim(SpaceChars);
assert(Expr.startswith("("));
auto OptFunc = StringSwitch<Optional<binop_eval_t>>(FuncName)
.Case("add", operator+)
.Case("div", operator/)
.Case("max", max)
.Case("min", min)
.Case("mul", operator*)
.Case("sub", operator-)
.Default(None);
if (!OptFunc)
return ErrorDiagnostic::get(
SM, FuncName, Twine("call to undefined function '") + FuncName + "'");
Expr.consume_front("(");
Expr = Expr.ltrim(SpaceChars);
// Parse call arguments, which are comma separated.
SmallVector<std::unique_ptr<ExpressionAST>, 4> Args;
while (!Expr.empty() && !Expr.startswith(")")) {
if (Expr.startswith(","))
return ErrorDiagnostic::get(SM, Expr, "missing argument");
// Parse the argument, which is an arbitary expression.
StringRef OuterBinOpExpr = Expr;
Expected<std::unique_ptr<ExpressionAST>> Arg = parseNumericOperand(
Expr, AllowedOperand::Any, /*MaybeInvalidConstraint=*/false, LineNumber,
Context, SM);
while (Arg && !Expr.empty()) {
Expr = Expr.ltrim(SpaceChars);
// Have we reached an argument terminator?
if (Expr.startswith(",") || Expr.startswith(")"))
break;
// Arg = Arg <op> <expr>
Arg = parseBinop(OuterBinOpExpr, Expr, std::move(*Arg), false, LineNumber,
Context, SM);
}
// Prefer an expression error over a generic invalid argument message.
if (!Arg)
return Arg.takeError();
Args.push_back(std::move(*Arg));
// Have we parsed all available arguments?
Expr = Expr.ltrim(SpaceChars);
if (!Expr.consume_front(","))
break;
Expr = Expr.ltrim(SpaceChars);
if (Expr.startswith(")"))
return ErrorDiagnostic::get(SM, Expr, "missing argument");
}
if (!Expr.consume_front(")"))
return ErrorDiagnostic::get(SM, Expr,
"missing ')' at end of call expression");
const unsigned NumArgs = Args.size();
if (NumArgs == 2)
return std::make_unique<BinaryOperation>(Expr, *OptFunc, std::move(Args[0]),
std::move(Args[1]));
// TODO: Support more than binop_eval_t.
return ErrorDiagnostic::get(SM, FuncName,
Twine("function '") + FuncName +
Twine("' takes 2 arguments but ") +
Twine(NumArgs) + " given");
}
Expected<std::unique_ptr<Expression>> Pattern::parseNumericSubstitutionBlock(
StringRef Expr, Optional<NumericVariable *> &DefinedNumericVariable,
bool IsLegacyLineExpr, Optional<size_t> LineNumber,
FileCheckPatternContext *Context, const SourceMgr &SM) {
std::unique_ptr<ExpressionAST> ExpressionASTPointer = nullptr;
StringRef DefExpr = StringRef();
DefinedNumericVariable = None;
ExpressionFormat ExplicitFormat = ExpressionFormat();
unsigned Precision = 0;
// Parse format specifier (NOTE: ',' is also an argument seperator).
size_t FormatSpecEnd = Expr.find(',');
size_t FunctionStart = Expr.find('(');
if (FormatSpecEnd != StringRef::npos && FormatSpecEnd < FunctionStart) {
StringRef FormatExpr = Expr.take_front(FormatSpecEnd);
Expr = Expr.drop_front(FormatSpecEnd + 1);
FormatExpr = FormatExpr.trim(SpaceChars);
if (!FormatExpr.consume_front("%"))
return ErrorDiagnostic::get(
SM, FormatExpr,
"invalid matching format specification in expression");
// Parse alternate form flag.
SMLoc AlternateFormFlagLoc = SMLoc::getFromPointer(FormatExpr.data());
bool AlternateForm = FormatExpr.consume_front("#");
// Parse precision.
if (FormatExpr.consume_front(".")) {
if (FormatExpr.consumeInteger(10, Precision))
return ErrorDiagnostic::get(SM, FormatExpr,
"invalid precision in format specifier");
}
if (!FormatExpr.empty()) {
// Check for unknown matching format specifier and set matching format in
// class instance representing this expression.
SMLoc FmtLoc = SMLoc::getFromPointer(FormatExpr.data());
switch (popFront(FormatExpr)) {
case 'u':
ExplicitFormat =
ExpressionFormat(ExpressionFormat::Kind::Unsigned, Precision);
break;
case 'd':
ExplicitFormat =
ExpressionFormat(ExpressionFormat::Kind::Signed, Precision);
break;
case 'x':
ExplicitFormat = ExpressionFormat(ExpressionFormat::Kind::HexLower,
Precision, AlternateForm);
break;
case 'X':
ExplicitFormat = ExpressionFormat(ExpressionFormat::Kind::HexUpper,
Precision, AlternateForm);
break;
default:
return ErrorDiagnostic::get(SM, FmtLoc,
"invalid format specifier in expression");
}
}
if (AlternateForm && ExplicitFormat != ExpressionFormat::Kind::HexLower &&
ExplicitFormat != ExpressionFormat::Kind::HexUpper)
return ErrorDiagnostic::get(
SM, AlternateFormFlagLoc,
"alternate form only supported for hex values");
FormatExpr = FormatExpr.ltrim(SpaceChars);
if (!FormatExpr.empty())
return ErrorDiagnostic::get(
SM, FormatExpr,
"invalid matching format specification in expression");
}
// Save variable definition expression if any.
size_t DefEnd = Expr.find(':');
if (DefEnd != StringRef::npos) {
DefExpr = Expr.substr(0, DefEnd);
Expr = Expr.substr(DefEnd + 1);
}
// Parse matching constraint.
Expr = Expr.ltrim(SpaceChars);
bool HasParsedValidConstraint = false;
if (Expr.consume_front("=="))
HasParsedValidConstraint = true;
// Parse the expression itself.
Expr = Expr.ltrim(SpaceChars);
if (Expr.empty()) {
if (HasParsedValidConstraint)
return ErrorDiagnostic::get(
SM, Expr, "empty numeric expression should not have a constraint");
} else {
Expr = Expr.rtrim(SpaceChars);
StringRef OuterBinOpExpr = Expr;
// The first operand in a legacy @LINE expression is always the @LINE
// pseudo variable.
AllowedOperand AO =
IsLegacyLineExpr ? AllowedOperand::LineVar : AllowedOperand::Any;
Expected<std::unique_ptr<ExpressionAST>> ParseResult = parseNumericOperand(
Expr, AO, !HasParsedValidConstraint, LineNumber, Context, SM);
while (ParseResult && !Expr.empty()) {
ParseResult = parseBinop(OuterBinOpExpr, Expr, std::move(*ParseResult),
IsLegacyLineExpr, LineNumber, Context, SM);
// Legacy @LINE expressions only allow 2 operands.
if (ParseResult && IsLegacyLineExpr && !Expr.empty())
return ErrorDiagnostic::get(
SM, Expr,
"unexpected characters at end of expression '" + Expr + "'");
}
if (!ParseResult)
return ParseResult.takeError();
ExpressionASTPointer = std::move(*ParseResult);
}
// Select format of the expression, i.e. (i) its explicit format, if any,
// otherwise (ii) its implicit format, if any, otherwise (iii) the default
// format (unsigned). Error out in case of conflicting implicit format
// without explicit format.
ExpressionFormat Format;
if (ExplicitFormat)
Format = ExplicitFormat;
else if (ExpressionASTPointer) {
Expected<ExpressionFormat> ImplicitFormat =
ExpressionASTPointer->getImplicitFormat(SM);
if (!ImplicitFormat)
return ImplicitFormat.takeError();
Format = *ImplicitFormat;
}
if (!Format)
Format = ExpressionFormat(ExpressionFormat::Kind::Unsigned, Precision);
std::unique_ptr<Expression> ExpressionPointer =
std::make_unique<Expression>(std::move(ExpressionASTPointer), Format);
// Parse the numeric variable definition.
if (DefEnd != StringRef::npos) {
DefExpr = DefExpr.ltrim(SpaceChars);
Expected<NumericVariable *> ParseResult = parseNumericVariableDefinition(
DefExpr, Context, LineNumber, ExpressionPointer->getFormat(), SM);
if (!ParseResult)
return ParseResult.takeError();
DefinedNumericVariable = *ParseResult;
}
return std::move(ExpressionPointer);
}
bool Pattern::parsePattern(StringRef PatternStr, StringRef Prefix,
SourceMgr &SM, const FileCheckRequest &Req) {
bool MatchFullLinesHere = Req.MatchFullLines && CheckTy != Check::CheckNot;
IgnoreCase = Req.IgnoreCase;
PatternLoc = SMLoc::getFromPointer(PatternStr.data());
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;
}
// If literal check, set fixed string.
if (CheckTy.isLiteralMatch()) {
FixedStr = PatternStr;
return false;
}
// Check to see if this is a fixed string, or if it has regex pieces.
if (!MatchFullLinesHere &&
(PatternStr.size() < 2 ||
(!PatternStr.contains("{{") && !PatternStr.contains("[[")))) {
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;
}