-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathPPDirectives.cpp
4047 lines (3559 loc) · 155 KB
/
PPDirectives.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
//===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
//
// 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
/// Implements # directive processing for the Preprocessor.
///
//===----------------------------------------------------------------------===//
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Basic/Attributes.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/DirectoryEntry.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TokenKinds.h"
#include "clang/Lex/CodeCompletionHandler.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/LiteralSupport.h"
#include "clang/Lex/MacroInfo.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/ModuleMap.h"
#include "clang/Lex/PPCallbacks.h"
#include "clang/Lex/Pragma.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/Token.h"
#include "clang/Lex/VariadicMacroSupport.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <optional>
#include <string>
#include <utility>
using namespace clang;
//===----------------------------------------------------------------------===//
// Utility Methods for Preprocessor Directive Handling.
//===----------------------------------------------------------------------===//
MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
static_assert(std::is_trivially_destructible_v<MacroInfo>, "");
return new (BP) MacroInfo(L);
}
DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
SourceLocation Loc) {
return new (BP) DefMacroDirective(MI, Loc);
}
UndefMacroDirective *
Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
return new (BP) UndefMacroDirective(UndefLoc);
}
VisibilityMacroDirective *
Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
bool isPublic) {
return new (BP) VisibilityMacroDirective(Loc, isPublic);
}
/// Read and discard all tokens remaining on the current line until
/// the tok::eod token is found.
SourceRange Preprocessor::DiscardUntilEndOfDirective(Token &Tmp) {
SourceRange Res;
LexUnexpandedToken(Tmp);
Res.setBegin(Tmp.getLocation());
while (Tmp.isNot(tok::eod)) {
assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
LexUnexpandedToken(Tmp);
}
Res.setEnd(Tmp.getLocation());
return Res;
}
/// Enumerates possible cases of #define/#undef a reserved identifier.
enum MacroDiag {
MD_NoWarn, //> Not a reserved identifier
MD_KeywordDef, //> Macro hides keyword, enabled by default
MD_ReservedMacro, //> #define of #undef reserved id, disabled by default
MD_ReservedAttributeIdentifier
};
/// Enumerates possible %select values for the pp_err_elif_after_else and
/// pp_err_elif_without_if diagnostics.
enum PPElifDiag {
PED_Elif,
PED_Elifdef,
PED_Elifndef
};
static bool isFeatureTestMacro(StringRef MacroName) {
// list from:
// * https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html
// * https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt?view=msvc-160
// * man 7 feature_test_macros
// The list must be sorted for correct binary search.
static constexpr StringRef ReservedMacro[] = {
"_ATFILE_SOURCE",
"_BSD_SOURCE",
"_CRT_NONSTDC_NO_WARNINGS",
"_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES",
"_CRT_SECURE_NO_WARNINGS",
"_FILE_OFFSET_BITS",
"_FORTIFY_SOURCE",
"_GLIBCXX_ASSERTIONS",
"_GLIBCXX_CONCEPT_CHECKS",
"_GLIBCXX_DEBUG",
"_GLIBCXX_DEBUG_PEDANTIC",
"_GLIBCXX_PARALLEL",
"_GLIBCXX_PARALLEL_ASSERTIONS",
"_GLIBCXX_SANITIZE_VECTOR",
"_GLIBCXX_USE_CXX11_ABI",
"_GLIBCXX_USE_DEPRECATED",
"_GNU_SOURCE",
"_ISOC11_SOURCE",
"_ISOC95_SOURCE",
"_ISOC99_SOURCE",
"_LARGEFILE64_SOURCE",
"_POSIX_C_SOURCE",
"_REENTRANT",
"_SVID_SOURCE",
"_THREAD_SAFE",
"_XOPEN_SOURCE",
"_XOPEN_SOURCE_EXTENDED",
"__STDCPP_WANT_MATH_SPEC_FUNCS__",
"__STDC_FORMAT_MACROS",
};
return std::binary_search(std::begin(ReservedMacro), std::end(ReservedMacro),
MacroName);
}
static bool isLanguageDefinedBuiltin(const SourceManager &SourceMgr,
const MacroInfo *MI,
const StringRef MacroName) {
// If this is a macro with special handling (like __LINE__) then it's language
// defined.
if (MI->isBuiltinMacro())
return true;
// Builtin macros are defined in the builtin file
if (!SourceMgr.isWrittenInBuiltinFile(MI->getDefinitionLoc()))
return false;
// C defines macros starting with __STDC, and C++ defines macros starting with
// __STDCPP
if (MacroName.starts_with("__STDC"))
return true;
// C++ defines the __cplusplus macro
if (MacroName == "__cplusplus")
return true;
// C++ defines various feature-test macros starting with __cpp
if (MacroName.starts_with("__cpp"))
return true;
// Anything else isn't language-defined
return false;
}
static bool isReservedCXXAttributeName(Preprocessor &PP, IdentifierInfo *II) {
const LangOptions &Lang = PP.getLangOpts();
if (Lang.CPlusPlus &&
hasAttribute(AttributeCommonInfo::AS_CXX11, /* Scope*/ nullptr, II,
PP.getTargetInfo(), Lang, /*CheckPlugins*/ false) > 0) {
AttributeCommonInfo::AttrArgsInfo AttrArgsInfo =
AttributeCommonInfo::getCXX11AttrArgsInfo(II);
if (AttrArgsInfo == AttributeCommonInfo::AttrArgsInfo::Required)
return PP.isNextPPTokenLParen();
return !PP.isNextPPTokenLParen() ||
AttrArgsInfo == AttributeCommonInfo::AttrArgsInfo::Optional;
}
return false;
}
static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
const LangOptions &Lang = PP.getLangOpts();
StringRef Text = II->getName();
if (isReservedInAllContexts(II->isReserved(Lang)))
return isFeatureTestMacro(Text) ? MD_NoWarn : MD_ReservedMacro;
if (II->isKeyword(Lang))
return MD_KeywordDef;
if (Lang.CPlusPlus11 && (Text == "override" || Text == "final"))
return MD_KeywordDef;
if (isReservedCXXAttributeName(PP, II))
return MD_ReservedAttributeIdentifier;
return MD_NoWarn;
}
static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
const LangOptions &Lang = PP.getLangOpts();
// Do not warn on keyword undef. It is generally harmless and widely used.
if (isReservedInAllContexts(II->isReserved(Lang)))
return MD_ReservedMacro;
if (isReservedCXXAttributeName(PP, II))
return MD_ReservedAttributeIdentifier;
return MD_NoWarn;
}
// Return true if we want to issue a diagnostic by default if we
// encounter this name in a #include with the wrong case. For now,
// this includes the standard C and C++ headers, Posix headers,
// and Boost headers. Improper case for these #includes is a
// potential portability issue.
static bool warnByDefaultOnWrongCase(StringRef Include) {
// If the first component of the path is "boost", treat this like a standard header
// for the purposes of diagnostics.
if (::llvm::sys::path::begin(Include)->equals_insensitive("boost"))
return true;
// "condition_variable" is the longest standard header name at 18 characters.
// If the include file name is longer than that, it can't be a standard header.
static const size_t MaxStdHeaderNameLen = 18u;
if (Include.size() > MaxStdHeaderNameLen)
return false;
// Lowercase and normalize the search string.
SmallString<32> LowerInclude{Include};
for (char &Ch : LowerInclude) {
// In the ASCII range?
if (static_cast<unsigned char>(Ch) > 0x7f)
return false; // Can't be a standard header
// ASCII lowercase:
if (Ch >= 'A' && Ch <= 'Z')
Ch += 'a' - 'A';
// Normalize path separators for comparison purposes.
else if (::llvm::sys::path::is_separator(Ch))
Ch = '/';
}
// The standard C/C++ and Posix headers
return llvm::StringSwitch<bool>(LowerInclude)
// C library headers
.Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
.Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
.Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
.Cases("stdatomic.h", "stdbool.h", "stdckdint.h", "stddef.h", true)
.Cases("stdint.h", "stdio.h", "stdlib.h", "stdnoreturn.h", true)
.Cases("string.h", "tgmath.h", "threads.h", "time.h", "uchar.h", true)
.Cases("wchar.h", "wctype.h", true)
// C++ headers for C library facilities
.Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
.Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
.Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
.Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
.Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
.Case("cwctype", true)
// C++ library headers
.Cases("algorithm", "fstream", "list", "regex", "thread", true)
.Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
.Cases("atomic", "future", "map", "set", "type_traits", true)
.Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
.Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
.Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
.Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
.Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
.Cases("deque", "istream", "queue", "string", "valarray", true)
.Cases("exception", "iterator", "random", "strstream", "vector", true)
.Cases("forward_list", "limits", "ratio", "system_error", true)
// POSIX headers (which aren't also C headers)
.Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
.Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
.Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
.Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
.Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
.Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
.Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
.Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
.Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
.Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
.Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
.Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
.Default(false);
}
/// Find a similar string in `Candidates`.
///
/// \param LHS a string for a similar string in `Candidates`
///
/// \param Candidates the candidates to find a similar string.
///
/// \returns a similar string if exists. If no similar string exists,
/// returns std::nullopt.
static std::optional<StringRef>
findSimilarStr(StringRef LHS, const std::vector<StringRef> &Candidates) {
// We need to check if `Candidates` has the exact case-insensitive string
// because the Levenshtein distance match does not care about it.
for (StringRef C : Candidates) {
if (LHS.equals_insensitive(C)) {
return C;
}
}
// Keep going with the Levenshtein distance match.
// If the LHS size is less than 3, use the LHS size minus 1 and if not,
// use the LHS size divided by 3.
size_t Length = LHS.size();
size_t MaxDist = Length < 3 ? Length - 1 : Length / 3;
std::optional<std::pair<StringRef, size_t>> SimilarStr;
for (StringRef C : Candidates) {
size_t CurDist = LHS.edit_distance(C, true);
if (CurDist <= MaxDist) {
if (!SimilarStr) {
// The first similar string found.
SimilarStr = {C, CurDist};
} else if (CurDist < SimilarStr->second) {
// More similar string found.
SimilarStr = {C, CurDist};
}
}
}
if (SimilarStr) {
return SimilarStr->first;
} else {
return std::nullopt;
}
}
bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
bool *ShadowFlag) {
// Missing macro name?
if (MacroNameTok.is(tok::eod))
return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
if (!II)
return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
if (II->isCPlusPlusOperatorKeyword()) {
// C++ 2.5p2: Alternative tokens behave the same as its primary token
// except for their spellings.
Diag(MacroNameTok, getLangOpts().MicrosoftExt
? diag::ext_pp_operator_used_as_macro_name
: diag::err_pp_operator_used_as_macro_name)
<< II << MacroNameTok.getKind();
// Allow #defining |and| and friends for Microsoft compatibility or
// recovery when legacy C headers are included in C++.
}
if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
// Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
return Diag(MacroNameTok, diag::err_defined_macro_name);
}
// If defining/undefining reserved identifier or a keyword, we need to issue
// a warning.
SourceLocation MacroNameLoc = MacroNameTok.getLocation();
if (ShadowFlag)
*ShadowFlag = false;
if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
(SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
MacroDiag D = MD_NoWarn;
if (isDefineUndef == MU_Define) {
D = shouldWarnOnMacroDef(*this, II);
}
else if (isDefineUndef == MU_Undef)
D = shouldWarnOnMacroUndef(*this, II);
if (D == MD_KeywordDef) {
// We do not want to warn on some patterns widely used in configuration
// scripts. This requires analyzing next tokens, so do not issue warnings
// now, only inform caller.
if (ShadowFlag)
*ShadowFlag = true;
}
if (D == MD_ReservedMacro)
Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
if (D == MD_ReservedAttributeIdentifier)
Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_attribute_id)
<< II->getName();
}
// Okay, we got a good identifier.
return false;
}
/// Lex and validate a macro name, which occurs after a
/// \#define or \#undef.
///
/// This sets the token kind to eod and discards the rest of the macro line if
/// the macro name is invalid.
///
/// \param MacroNameTok Token that is expected to be a macro name.
/// \param isDefineUndef Context in which macro is used.
/// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
bool *ShadowFlag) {
// Read the token, don't allow macro expansion on it.
LexUnexpandedToken(MacroNameTok);
if (MacroNameTok.is(tok::code_completion)) {
if (CodeComplete)
CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
setCodeCompletionReached();
LexUnexpandedToken(MacroNameTok);
}
if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
return;
// Invalid macro name, read and discard the rest of the line and set the
// token kind to tok::eod if necessary.
if (MacroNameTok.isNot(tok::eod)) {
MacroNameTok.setKind(tok::eod);
DiscardUntilEndOfDirective();
}
}
/// Ensure that the next token is a tok::eod token.
///
/// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
/// true, then we consider macros that expand to zero tokens as being ok.
///
/// Returns the location of the end of the directive.
SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
bool EnableMacros) {
Token Tmp;
// Lex unexpanded tokens for most directives: macros might expand to zero
// tokens, causing us to miss diagnosing invalid lines. Some directives (like
// #line) allow empty macros.
if (EnableMacros)
Lex(Tmp);
else
LexUnexpandedToken(Tmp);
// There should be no tokens after the directive, but we allow them as an
// extension.
while (Tmp.is(tok::comment)) // Skip comments in -C mode.
LexUnexpandedToken(Tmp);
if (Tmp.is(tok::eod))
return Tmp.getLocation();
// Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
// or if this is a macro-style preprocessing directive, because it is more
// trouble than it is worth to insert /**/ and check that there is no /**/
// in the range also.
FixItHint Hint;
if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
!CurTokenLexer)
Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
return DiscardUntilEndOfDirective().getEnd();
}
void Preprocessor::SuggestTypoedDirective(const Token &Tok,
StringRef Directive) const {
// If this is a `.S` file, treat unknown # directives as non-preprocessor
// directives.
if (getLangOpts().AsmPreprocessor) return;
std::vector<StringRef> Candidates = {
"if", "ifdef", "ifndef", "elif", "else", "endif"
};
if (LangOpts.C23 || LangOpts.CPlusPlus23)
Candidates.insert(Candidates.end(), {"elifdef", "elifndef"});
if (std::optional<StringRef> Sugg = findSimilarStr(Directive, Candidates)) {
// Directive cannot be coming from macro.
assert(Tok.getLocation().isFileID());
CharSourceRange DirectiveRange = CharSourceRange::getCharRange(
Tok.getLocation(),
Tok.getLocation().getLocWithOffset(Directive.size()));
StringRef SuggValue = *Sugg;
auto Hint = FixItHint::CreateReplacement(DirectiveRange, SuggValue);
Diag(Tok, diag::warn_pp_invalid_directive) << 1 << SuggValue << Hint;
}
}
/// SkipExcludedConditionalBlock - We just read a \#if or related directive and
/// decided that the subsequent tokens are in the \#if'd out portion of the
/// file. Lex the rest of the file, until we see an \#endif. If
/// FoundNonSkipPortion is true, then we have already emitted code for part of
/// this \#if directive, so \#else/\#elif blocks should never be entered.
/// If ElseOk is true, then \#else directives are ok, if not, then we have
/// already seen one so a \#else directive is a duplicate. When this returns,
/// the caller can lex the first valid token.
void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
SourceLocation IfTokenLoc,
bool FoundNonSkipPortion,
bool FoundElse,
SourceLocation ElseLoc) {
// In SkippingRangeStateTy we are depending on SkipExcludedConditionalBlock()
// not getting called recursively by storing the RecordedSkippedRanges
// DenseMap lookup pointer (field SkipRangePtr). SkippingRangeStateTy expects
// that RecordedSkippedRanges won't get modified and SkipRangePtr won't be
// invalidated. If this changes and there is a need to call
// SkipExcludedConditionalBlock() recursively, SkippingRangeStateTy should
// change to do a second lookup in endLexPass function instead of reusing the
// lookup pointer.
assert(!SkippingExcludedConditionalBlock &&
"calling SkipExcludedConditionalBlock recursively");
llvm::SaveAndRestore SARSkipping(SkippingExcludedConditionalBlock, true);
++NumSkipped;
assert(!CurTokenLexer && "Conditional PP block cannot appear in a macro!");
assert(CurPPLexer && "Conditional PP block must be in a file!");
assert(CurLexer && "Conditional PP block but no current lexer set!");
if (PreambleConditionalStack.reachedEOFWhileSkipping())
PreambleConditionalStack.clearSkipInfo();
else
CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
FoundNonSkipPortion, FoundElse);
// Enter raw mode to disable identifier lookup (and thus macro expansion),
// disabling warnings, etc.
CurPPLexer->LexingRawMode = true;
Token Tok;
SourceLocation endLoc;
/// Keeps track and caches skipped ranges and also retrieves a prior skipped
/// range if the same block is re-visited.
struct SkippingRangeStateTy {
Preprocessor &PP;
const char *BeginPtr = nullptr;
unsigned *SkipRangePtr = nullptr;
SkippingRangeStateTy(Preprocessor &PP) : PP(PP) {}
void beginLexPass() {
if (BeginPtr)
return; // continue skipping a block.
// Initiate a skipping block and adjust the lexer if we already skipped it
// before.
BeginPtr = PP.CurLexer->getBufferLocation();
SkipRangePtr = &PP.RecordedSkippedRanges[BeginPtr];
if (*SkipRangePtr) {
PP.CurLexer->seek(PP.CurLexer->getCurrentBufferOffset() + *SkipRangePtr,
/*IsAtStartOfLine*/ true);
}
}
void endLexPass(const char *Hashptr) {
if (!BeginPtr) {
// Not doing normal lexing.
assert(PP.CurLexer->isDependencyDirectivesLexer());
return;
}
// Finished skipping a block, record the range if it's first time visited.
if (!*SkipRangePtr) {
*SkipRangePtr = Hashptr - BeginPtr;
}
assert(*SkipRangePtr == unsigned(Hashptr - BeginPtr));
BeginPtr = nullptr;
SkipRangePtr = nullptr;
}
} SkippingRangeState(*this);
while (true) {
if (CurLexer->isDependencyDirectivesLexer()) {
CurLexer->LexDependencyDirectiveTokenWhileSkipping(Tok);
} else {
SkippingRangeState.beginLexPass();
while (true) {
CurLexer->Lex(Tok);
if (Tok.is(tok::code_completion)) {
setCodeCompletionReached();
if (CodeComplete)
CodeComplete->CodeCompleteInConditionalExclusion();
continue;
}
// If this is the end of the buffer, we have an error.
if (Tok.is(tok::eof)) {
// We don't emit errors for unterminated conditionals here,
// Lexer::LexEndOfFile can do that properly.
// Just return and let the caller lex after this #include.
if (PreambleConditionalStack.isRecording())
PreambleConditionalStack.SkipInfo.emplace(HashTokenLoc, IfTokenLoc,
FoundNonSkipPortion,
FoundElse, ElseLoc);
break;
}
// If this token is not a preprocessor directive, just skip it.
if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
continue;
break;
}
}
if (Tok.is(tok::eof))
break;
// We just parsed a # character at the start of a line, so we're in
// directive mode. Tell the lexer this so any newlines we see will be
// converted into an EOD token (this terminates the macro).
CurPPLexer->ParsingPreprocessorDirective = true;
if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
assert(Tok.is(tok::hash));
const char *Hashptr = CurLexer->getBufferLocation() - Tok.getLength();
assert(CurLexer->getSourceLocation(Hashptr) == Tok.getLocation());
// Read the next token, the directive flavor.
LexUnexpandedToken(Tok);
// If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
// something bogus), skip it.
if (Tok.isNot(tok::raw_identifier)) {
CurPPLexer->ParsingPreprocessorDirective = false;
// Restore comment saving mode.
if (CurLexer) CurLexer->resetExtendedTokenMode();
continue;
}
// If the first letter isn't i or e, it isn't intesting to us. We know that
// this is safe in the face of spelling differences, because there is no way
// to spell an i/e in a strange way that is another letter. Skipping this
// allows us to avoid looking up the identifier info for #define/#undef and
// other common directives.
StringRef RI = Tok.getRawIdentifier();
char FirstChar = RI[0];
if (FirstChar >= 'a' && FirstChar <= 'z' &&
FirstChar != 'i' && FirstChar != 'e') {
CurPPLexer->ParsingPreprocessorDirective = false;
// Restore comment saving mode.
if (CurLexer) CurLexer->resetExtendedTokenMode();
continue;
}
// Get the identifier name without trigraphs or embedded newlines. Note
// that we can't use Tok.getIdentifierInfo() because its lookup is disabled
// when skipping.
char DirectiveBuf[20];
StringRef Directive;
if (!Tok.needsCleaning() && RI.size() < 20) {
Directive = RI;
} else {
std::string DirectiveStr = getSpelling(Tok);
size_t IdLen = DirectiveStr.size();
if (IdLen >= 20) {
CurPPLexer->ParsingPreprocessorDirective = false;
// Restore comment saving mode.
if (CurLexer) CurLexer->resetExtendedTokenMode();
continue;
}
memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
Directive = StringRef(DirectiveBuf, IdLen);
}
if (Directive.starts_with("if")) {
StringRef Sub = Directive.substr(2);
if (Sub.empty() || // "if"
Sub == "def" || // "ifdef"
Sub == "ndef") { // "ifndef"
// We know the entire #if/#ifdef/#ifndef block will be skipped, don't
// bother parsing the condition.
DiscardUntilEndOfDirective();
CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
/*foundnonskip*/false,
/*foundelse*/false);
} else {
SuggestTypoedDirective(Tok, Directive);
}
} else if (Directive[0] == 'e') {
StringRef Sub = Directive.substr(1);
if (Sub == "ndif") { // "endif"
PPConditionalInfo CondInfo;
CondInfo.WasSkipping = true; // Silence bogus warning.
bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
(void)InCond; // Silence warning in no-asserts mode.
assert(!InCond && "Can't be skipping if not in a conditional!");
// If we popped the outermost skipping block, we're done skipping!
if (!CondInfo.WasSkipping) {
SkippingRangeState.endLexPass(Hashptr);
// Restore the value of LexingRawMode so that trailing comments
// are handled correctly, if we've reached the outermost block.
CurPPLexer->LexingRawMode = false;
endLoc = CheckEndOfDirective("endif");
CurPPLexer->LexingRawMode = true;
if (Callbacks)
Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
break;
} else {
DiscardUntilEndOfDirective();
}
} else if (Sub == "lse") { // "else".
// #else directive in a skipping conditional. If not in some other
// skipping conditional, and if #else hasn't already been seen, enter it
// as a non-skipping conditional.
PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
if (!CondInfo.WasSkipping)
SkippingRangeState.endLexPass(Hashptr);
// If this is a #else with a #else before it, report the error.
if (CondInfo.FoundElse)
Diag(Tok, diag::pp_err_else_after_else);
// Note that we've seen a #else in this conditional.
CondInfo.FoundElse = true;
// If the conditional is at the top level, and the #if block wasn't
// entered, enter the #else block now.
if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
CondInfo.FoundNonSkip = true;
// Restore the value of LexingRawMode so that trailing comments
// are handled correctly.
CurPPLexer->LexingRawMode = false;
endLoc = CheckEndOfDirective("else");
CurPPLexer->LexingRawMode = true;
if (Callbacks)
Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
break;
} else {
DiscardUntilEndOfDirective(); // C99 6.10p4.
}
} else if (Sub == "lif") { // "elif".
PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
if (!CondInfo.WasSkipping)
SkippingRangeState.endLexPass(Hashptr);
// If this is a #elif with a #else before it, report the error.
if (CondInfo.FoundElse)
Diag(Tok, diag::pp_err_elif_after_else) << PED_Elif;
// If this is in a skipping block or if we're already handled this #if
// block, don't bother parsing the condition.
if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
// FIXME: We should probably do at least some minimal parsing of the
// condition to verify that it is well-formed. The current state
// allows #elif* directives with completely malformed (or missing)
// conditions.
DiscardUntilEndOfDirective();
} else {
// Restore the value of LexingRawMode so that identifiers are
// looked up, etc, inside the #elif expression.
assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
CurPPLexer->LexingRawMode = false;
IdentifierInfo *IfNDefMacro = nullptr;
DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
// Stop if Lexer became invalid after hitting code completion token.
if (!CurPPLexer)
return;
const bool CondValue = DER.Conditional;
CurPPLexer->LexingRawMode = true;
if (Callbacks) {
Callbacks->Elif(
Tok.getLocation(), DER.ExprRange,
(CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
CondInfo.IfLoc);
}
// If this condition is true, enter it!
if (CondValue) {
CondInfo.FoundNonSkip = true;
break;
}
}
} else if (Sub == "lifdef" || // "elifdef"
Sub == "lifndef") { // "elifndef"
bool IsElifDef = Sub == "lifdef";
PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
Token DirectiveToken = Tok;
if (!CondInfo.WasSkipping)
SkippingRangeState.endLexPass(Hashptr);
// Warn if using `#elifdef` & `#elifndef` in not C23 & C++23 mode even
// if this branch is in a skipping block.
unsigned DiagID;
if (LangOpts.CPlusPlus)
DiagID = LangOpts.CPlusPlus23 ? diag::warn_cxx23_compat_pp_directive
: diag::ext_cxx23_pp_directive;
else
DiagID = LangOpts.C23 ? diag::warn_c23_compat_pp_directive
: diag::ext_c23_pp_directive;
Diag(Tok, DiagID) << (IsElifDef ? PED_Elifdef : PED_Elifndef);
// If this is a #elif with a #else before it, report the error.
if (CondInfo.FoundElse)
Diag(Tok, diag::pp_err_elif_after_else)
<< (IsElifDef ? PED_Elifdef : PED_Elifndef);
// If this is in a skipping block or if we're already handled this #if
// block, don't bother parsing the condition.
if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
// FIXME: We should probably do at least some minimal parsing of the
// condition to verify that it is well-formed. The current state
// allows #elif* directives with completely malformed (or missing)
// conditions.
DiscardUntilEndOfDirective();
} else {
// Restore the value of LexingRawMode so that identifiers are
// looked up, etc, inside the #elif[n]def expression.
assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
CurPPLexer->LexingRawMode = false;
Token MacroNameTok;
ReadMacroName(MacroNameTok);
CurPPLexer->LexingRawMode = true;
// If the macro name token is tok::eod, there was an error that was
// already reported.
if (MacroNameTok.is(tok::eod)) {
// Skip code until we get to #endif. This helps with recovery by
// not emitting an error when the #endif is reached.
continue;
}
emitMacroExpansionWarnings(MacroNameTok);
CheckEndOfDirective(IsElifDef ? "elifdef" : "elifndef");
IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
auto MD = getMacroDefinition(MII);
MacroInfo *MI = MD.getMacroInfo();
if (Callbacks) {
if (IsElifDef) {
Callbacks->Elifdef(DirectiveToken.getLocation(), MacroNameTok,
MD);
} else {
Callbacks->Elifndef(DirectiveToken.getLocation(), MacroNameTok,
MD);
}
}
// If this condition is true, enter it!
if (static_cast<bool>(MI) == IsElifDef) {
CondInfo.FoundNonSkip = true;
break;
}
}
} else {
SuggestTypoedDirective(Tok, Directive);
}
} else {
SuggestTypoedDirective(Tok, Directive);
}
CurPPLexer->ParsingPreprocessorDirective = false;
// Restore comment saving mode.
if (CurLexer) CurLexer->resetExtendedTokenMode();
}
// Finally, if we are out of the conditional (saw an #endif or ran off the end
// of the file, just stop skipping and return to lexing whatever came after
// the #if block.
CurPPLexer->LexingRawMode = false;
// The last skipped range isn't actually skipped yet if it's truncated
// by the end of the preamble; we'll resume parsing after the preamble.
if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
Callbacks->SourceRangeSkipped(
SourceRange(HashTokenLoc, endLoc.isValid()
? endLoc
: CurPPLexer->getSourceLocation()),
Tok.getLocation());
}
Module *Preprocessor::getModuleForLocation(SourceLocation Loc,
bool AllowTextual) {
if (!SourceMgr.isInMainFile(Loc)) {
// Try to determine the module of the include directive.
// FIXME: Look into directly passing the FileEntry from LookupFile instead.
FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
if (auto EntryOfIncl = SourceMgr.getFileEntryRefForID(IDOfIncl)) {
// The include comes from an included file.
return HeaderInfo.getModuleMap()
.findModuleForHeader(*EntryOfIncl, AllowTextual)
.getModule();
}
}
// This is either in the main file or not in a file at all. It belongs
// to the current module, if there is one.
return getLangOpts().CurrentModule.empty()
? nullptr
: HeaderInfo.lookupModule(getLangOpts().CurrentModule, Loc);
}
OptionalFileEntryRef
Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
SourceLocation Loc) {
Module *IncM = getModuleForLocation(
IncLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
// Walk up through the include stack, looking through textual headers of M
// until we hit a non-textual header that we can #include. (We assume textual
// headers of a module with non-textual headers aren't meant to be used to
// import entities from the module.)
auto &SM = getSourceManager();
while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
auto FE = SM.getFileEntryRefForID(ID);
if (!FE)
break;
// We want to find all possible modules that might contain this header, so
// search all enclosing directories for module maps and load them.
HeaderInfo.hasModuleMap(FE->getName(), /*Root*/ nullptr,
SourceMgr.isInSystemHeader(Loc));
bool InPrivateHeader = false;
for (auto Header : HeaderInfo.findAllModulesForHeader(*FE)) {
if (!Header.isAccessibleFrom(IncM)) {
// It's in a private header; we can't #include it.
// FIXME: If there's a public header in some module that re-exports it,
// then we could suggest including that, but it's not clear that's the
// expected way to make this entity visible.
InPrivateHeader = true;
continue;
}
// Don't suggest explicitly excluded headers.
if (Header.getRole() == ModuleMap::ExcludedHeader)
continue;
// We'll suggest including textual headers below if they're
// include-guarded.
if (Header.getRole() & ModuleMap::TextualHeader)
continue;
// If we have a module import syntax, we shouldn't include a header to
// make a particular module visible. Let the caller know they should
// suggest an import instead.
if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules)
return std::nullopt;
// If this is an accessible, non-textual header of M's top-level module
// that transitively includes the given location and makes the
// corresponding module visible, this is the thing to #include.
return *FE;
}
// FIXME: If we're bailing out due to a private header, we shouldn't suggest
// an import either.
if (InPrivateHeader)
return std::nullopt;
// If the header is includable and has an include guard, assume the
// intended way to expose its contents is by #include, not by importing a
// module that transitively includes it.
if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(*FE))
return *FE;
Loc = SM.getIncludeLoc(ID);
}
return std::nullopt;
}
OptionalFileEntryRef Preprocessor::LookupFile(
SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
ConstSearchDirIterator FromDir, const FileEntry *FromFile,
ConstSearchDirIterator *CurDirArg, SmallVectorImpl<char> *SearchPath,
SmallVectorImpl<char> *RelativePath,
ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
bool *IsFrameworkFound, bool SkipCache, bool OpenFile, bool CacheFailures) {
ConstSearchDirIterator CurDirLocal = nullptr;
ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
Module *RequestingModule = getModuleForLocation(
FilenameLoc, LangOpts.ModulesValidateTextualHeaderIncludes);
// If the header lookup mechanism may be relative to the current inclusion
// stack, record the parent #includes.
SmallVector<std::pair<OptionalFileEntryRef, DirectoryEntryRef>, 16> Includers;
bool BuildSystemModule = false;
if (!FromDir && !FromFile) {
FileID FID = getCurrentFileLexer()->getFileID();
OptionalFileEntryRef FileEnt = SourceMgr.getFileEntryRefForID(FID);
// If there is no file entry associated with this file, it must be the
// predefines buffer or the module includes buffer. Any other file is not
// lexed with a normal lexer, so it won't be scanned for preprocessor
// directives.
//
// If we have the predefines buffer, resolve #include references (which come