1 //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Preprocessor interface.
12 //===----------------------------------------------------------------------===//
14 // Options to support:
15 // -H - Print the name of each header file used.
16 // -d[DNI] - Dump various things.
17 // -fworking-directory - #line's with preprocessor's working dir.
19 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
24 // "Multiple include guards may be useful for:\n"
26 //===----------------------------------------------------------------------===//
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/CodeCompletionHandler.h"
33 #include "clang/Lex/ExternalPreprocessorSource.h"
34 #include "clang/Lex/HeaderSearch.h"
35 #include "clang/Lex/LexDiagnostic.h"
36 #include "clang/Lex/LiteralSupport.h"
37 #include "clang/Lex/MacroArgs.h"
38 #include "clang/Lex/MacroInfo.h"
39 #include "clang/Lex/ModuleLoader.h"
40 #include "clang/Lex/Pragma.h"
41 #include "clang/Lex/PreprocessingRecord.h"
42 #include "clang/Lex/PreprocessorOptions.h"
43 #include "clang/Lex/ScratchBuffer.h"
44 #include "llvm/ADT/APFloat.h"
45 #include "llvm/ADT/STLExtras.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/StringExtras.h"
48 #include "llvm/Support/Capacity.h"
49 #include "llvm/Support/ConvertUTF.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/raw_ostream.h"
52 using namespace clang;
54 //===----------------------------------------------------------------------===//
55 ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
57 Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
58 DiagnosticsEngine &diags, LangOptions &opts,
59 SourceManager &SM, HeaderSearch &Headers,
60 ModuleLoader &TheModuleLoader,
61 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
62 TranslationUnitKind TUKind)
63 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
64 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
65 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
66 Identifiers(opts, IILookup), IncrementalProcessing(false), TUKind(TUKind),
67 CodeComplete(nullptr), CodeCompletionFile(nullptr),
68 CodeCompletionOffset(0), LastTokenWasAt(false),
69 ModuleImportExpectsIdentifier(false), CodeCompletionReached(0),
70 SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
71 CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr),
72 Callbacks(nullptr), MacroArgCache(nullptr), Record(nullptr),
73 MIChainHead(nullptr), MICache(nullptr), DeserialMIChainHead(nullptr) {
74 OwnsHeaderSearch = OwnsHeaders;
76 ScratchBuf = new ScratchBuffer(SourceMgr);
77 CounterValue = 0; // __COUNTER__ starts at 0.
80 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
81 NumIf = NumElse = NumEndif = 0;
82 NumEnteredSourceFiles = 0;
83 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
84 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
85 MaxIncludeStackDepth = 0;
88 // Default to discarding comments.
90 KeepMacroComments = false;
91 SuppressIncludeNotFoundError = false;
93 // Macro expansion is enabled.
94 DisableMacroExpansion = false;
95 MacroExpansionInDirectivesOverride = false;
97 InMacroArgPreExpansion = false;
98 NumCachedTokenLexers = 0;
99 PragmasEnabled = true;
100 ParsingIfOrElifDirective = false;
101 PreprocessedOutput = false;
105 // We haven't read anything from the external source.
106 ReadMacrosFromExternalSource = false;
108 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
109 // This gets unpoisoned where it is allowed.
110 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
111 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
113 // Initialize the pragma handlers.
114 PragmaHandlers = new PragmaNamespace(StringRef());
115 RegisterBuiltinPragmas();
117 // Initialize builtin macros like __LINE__ and friends.
118 RegisterBuiltinMacros();
120 if(LangOpts.Borland) {
121 Ident__exception_info = getIdentifierInfo("_exception_info");
122 Ident___exception_info = getIdentifierInfo("__exception_info");
123 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
124 Ident__exception_code = getIdentifierInfo("_exception_code");
125 Ident___exception_code = getIdentifierInfo("__exception_code");
126 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
127 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
128 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
129 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
131 Ident__exception_info = Ident__exception_code = nullptr;
132 Ident__abnormal_termination = Ident___exception_info = nullptr;
133 Ident___exception_code = Ident___abnormal_termination = nullptr;
134 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
135 Ident_AbnormalTermination = nullptr;
139 Preprocessor::~Preprocessor() {
140 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
142 IncludeMacroStack.clear();
144 // Free any macro definitions.
145 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
148 // Free any cached macro expanders.
149 // This populates MacroArgCache, so all TokenLexers need to be destroyed
150 // before the code below that frees up the MacroArgCache list.
151 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
152 delete TokenLexerCache[i];
153 CurTokenLexer.reset();
155 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next)
158 // Free any cached MacroArgs.
159 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
160 ArgList = ArgList->deallocate();
162 // Release pragma information.
163 delete PragmaHandlers;
165 // Delete the scratch buffer info.
168 // Delete the header search info, if we own it.
169 if (OwnsHeaderSearch)
175 void Preprocessor::Initialize(const TargetInfo &Target) {
176 assert((!this->Target || this->Target == &Target) &&
177 "Invalid override of target information");
178 this->Target = &Target;
180 // Initialize information about built-ins.
181 BuiltinInfo.InitializeTarget(Target);
182 HeaderInfo.setTarget(Target);
185 void Preprocessor::setPTHManager(PTHManager* pm) {
187 FileMgr.addStatCache(PTH->createStatCache());
190 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
191 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
192 << getSpelling(Tok) << "'";
194 if (!DumpFlags) return;
196 llvm::errs() << "\t";
197 if (Tok.isAtStartOfLine())
198 llvm::errs() << " [StartOfLine]";
199 if (Tok.hasLeadingSpace())
200 llvm::errs() << " [LeadingSpace]";
201 if (Tok.isExpandDisabled())
202 llvm::errs() << " [ExpandDisabled]";
203 if (Tok.needsCleaning()) {
204 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
205 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
209 llvm::errs() << "\tLoc=<";
210 DumpLocation(Tok.getLocation());
214 void Preprocessor::DumpLocation(SourceLocation Loc) const {
218 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
219 llvm::errs() << "MACRO: ";
220 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
221 DumpToken(MI.getReplacementToken(i));
224 llvm::errs() << "\n";
227 void Preprocessor::PrintStats() {
228 llvm::errs() << "\n*** Preprocessor Stats:\n";
229 llvm::errs() << NumDirectives << " directives found:\n";
230 llvm::errs() << " " << NumDefined << " #define.\n";
231 llvm::errs() << " " << NumUndefined << " #undef.\n";
232 llvm::errs() << " #include/#include_next/#import:\n";
233 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
234 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
235 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
236 llvm::errs() << " " << NumElse << " #else/#elif.\n";
237 llvm::errs() << " " << NumEndif << " #endif.\n";
238 llvm::errs() << " " << NumPragma << " #pragma.\n";
239 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
241 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
242 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
243 << NumFastMacroExpanded << " on the fast path.\n";
244 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
245 << " token paste (##) operations performed, "
246 << NumFastTokenPaste << " on the fast path.\n";
248 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
250 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
251 llvm::errs() << "\n Macro Expanded Tokens: "
252 << llvm::capacity_in_bytes(MacroExpandedTokens);
253 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
254 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
255 llvm::errs() << "\n #pragma push_macro Info: "
256 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
257 llvm::errs() << "\n Poison Reasons: "
258 << llvm::capacity_in_bytes(PoisonReasons);
259 llvm::errs() << "\n Comment Handlers: "
260 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
263 Preprocessor::macro_iterator
264 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
265 if (IncludeExternalMacros && ExternalSource &&
266 !ReadMacrosFromExternalSource) {
267 ReadMacrosFromExternalSource = true;
268 ExternalSource->ReadDefinedMacros();
271 return Macros.begin();
274 size_t Preprocessor::getTotalMemory() const {
275 return BP.getTotalMemory()
276 + llvm::capacity_in_bytes(MacroExpandedTokens)
277 + Predefines.capacity() /* Predefines buffer. */
278 + llvm::capacity_in_bytes(Macros)
279 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
280 + llvm::capacity_in_bytes(PoisonReasons)
281 + llvm::capacity_in_bytes(CommentHandlers);
284 Preprocessor::macro_iterator
285 Preprocessor::macro_end(bool IncludeExternalMacros) const {
286 if (IncludeExternalMacros && ExternalSource &&
287 !ReadMacrosFromExternalSource) {
288 ReadMacrosFromExternalSource = true;
289 ExternalSource->ReadDefinedMacros();
295 /// \brief Compares macro tokens with a specified token value sequence.
296 static bool MacroDefinitionEquals(const MacroInfo *MI,
297 ArrayRef<TokenValue> Tokens) {
298 return Tokens.size() == MI->getNumTokens() &&
299 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
302 StringRef Preprocessor::getLastMacroWithSpelling(
304 ArrayRef<TokenValue> Tokens) const {
305 SourceLocation BestLocation;
306 StringRef BestSpelling;
307 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
309 if (!I->second->getMacroInfo()->isObjectLike())
311 const MacroDirective::DefInfo
312 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
315 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
317 SourceLocation Location = Def.getLocation();
318 // Choose the macro defined latest.
319 if (BestLocation.isInvalid() ||
320 (Location.isValid() &&
321 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
322 BestLocation = Location;
323 BestSpelling = I->first->getName();
329 void Preprocessor::recomputeCurLexerKind() {
331 CurLexerKind = CLK_Lexer;
332 else if (CurPTHLexer)
333 CurLexerKind = CLK_PTHLexer;
334 else if (CurTokenLexer)
335 CurLexerKind = CLK_TokenLexer;
337 CurLexerKind = CLK_CachingLexer;
340 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
341 unsigned CompleteLine,
342 unsigned CompleteColumn) {
344 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
345 assert(!CodeCompletionFile && "Already set");
347 using llvm::MemoryBuffer;
349 // Load the actual file's contents.
350 bool Invalid = false;
351 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
355 // Find the byte position of the truncation point.
356 const char *Position = Buffer->getBufferStart();
357 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
358 for (; *Position; ++Position) {
359 if (*Position != '\r' && *Position != '\n')
362 // Eat \r\n or \n\r as a single line.
363 if ((Position[1] == '\r' || Position[1] == '\n') &&
364 Position[0] != Position[1])
371 Position += CompleteColumn - 1;
373 // Insert '\0' at the code-completion point.
374 if (Position < Buffer->getBufferEnd()) {
375 CodeCompletionFile = File;
376 CodeCompletionOffset = Position - Buffer->getBufferStart();
378 MemoryBuffer *NewBuffer =
379 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
380 Buffer->getBufferIdentifier());
381 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
382 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
384 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
385 SourceMgr.overrideFileContents(File, NewBuffer);
391 void Preprocessor::CodeCompleteNaturalLanguage() {
393 CodeComplete->CodeCompleteNaturalLanguage();
394 setCodeCompletionReached();
397 /// getSpelling - This method is used to get the spelling of a token into a
398 /// SmallVector. Note that the returned StringRef may not point to the
399 /// supplied buffer if a copy can be avoided.
400 StringRef Preprocessor::getSpelling(const Token &Tok,
401 SmallVectorImpl<char> &Buffer,
402 bool *Invalid) const {
403 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
404 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
405 // Try the fast path.
406 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
407 return II->getName();
410 // Resize the buffer if we need to copy into it.
411 if (Tok.needsCleaning())
412 Buffer.resize(Tok.getLength());
414 const char *Ptr = Buffer.data();
415 unsigned Len = getSpelling(Tok, Ptr, Invalid);
416 return StringRef(Ptr, Len);
419 /// CreateString - Plop the specified string into a scratch buffer and return a
420 /// location for it. If specified, the source location provides a source
421 /// location for the token.
422 void Preprocessor::CreateString(StringRef Str, Token &Tok,
423 SourceLocation ExpansionLocStart,
424 SourceLocation ExpansionLocEnd) {
425 Tok.setLength(Str.size());
428 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
430 if (ExpansionLocStart.isValid())
431 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
432 ExpansionLocEnd, Str.size());
433 Tok.setLocation(Loc);
435 // If this is a raw identifier or a literal token, set the pointer data.
436 if (Tok.is(tok::raw_identifier))
437 Tok.setRawIdentifierData(DestPtr);
438 else if (Tok.isLiteral())
439 Tok.setLiteralData(DestPtr);
442 Module *Preprocessor::getCurrentModule() {
443 if (getLangOpts().CurrentModule.empty())
446 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
449 //===----------------------------------------------------------------------===//
450 // Preprocessor Initialization Methods
451 //===----------------------------------------------------------------------===//
454 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
455 /// which implicitly adds the builtin defines etc.
456 void Preprocessor::EnterMainSourceFile() {
457 // We do not allow the preprocessor to reenter the main file. Doing so will
458 // cause FileID's to accumulate information from both runs (e.g. #line
459 // information) and predefined macros aren't guaranteed to be set properly.
460 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
461 FileID MainFileID = SourceMgr.getMainFileID();
463 // If MainFileID is loaded it means we loaded an AST file, no need to enter
465 if (!SourceMgr.isLoadedFileID(MainFileID)) {
466 // Enter the main file source buffer.
467 EnterSourceFile(MainFileID, nullptr, SourceLocation());
469 // If we've been asked to skip bytes in the main file (e.g., as part of a
470 // precompiled preamble), do so now.
471 if (SkipMainFilePreamble.first > 0)
472 CurLexer->SkipBytes(SkipMainFilePreamble.first,
473 SkipMainFilePreamble.second);
475 // Tell the header info that the main file was entered. If the file is later
476 // #imported, it won't be re-entered.
477 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
478 HeaderInfo.IncrementIncludeCount(FE);
481 // Preprocess Predefines to populate the initial preprocessor state.
482 llvm::MemoryBuffer *SB =
483 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
484 assert(SB && "Cannot create predefined source buffer");
485 FileID FID = SourceMgr.createFileID(SB);
486 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
487 setPredefinesFileID(FID);
489 // Start parsing the predefines.
490 EnterSourceFile(FID, nullptr, SourceLocation());
493 void Preprocessor::EndSourceFile() {
494 // Notify the client that we reached the end of the source file.
496 Callbacks->EndOfMainFile();
499 //===----------------------------------------------------------------------===//
500 // Lexer Event Handling.
501 //===----------------------------------------------------------------------===//
503 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
504 /// identifier information for the token and install it into the token,
505 /// updating the token kind accordingly.
506 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
507 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
509 // Look up this token, see if it is a macro, or if it is a language keyword.
511 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
512 // No cleaning needed, just use the characters from the lexed buffer.
513 II = getIdentifierInfo(Identifier.getRawIdentifier());
515 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
516 SmallString<64> IdentifierBuffer;
517 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
519 if (Identifier.hasUCN()) {
520 SmallString<64> UCNIdentifierBuffer;
521 expandUCNs(UCNIdentifierBuffer, CleanedStr);
522 II = getIdentifierInfo(UCNIdentifierBuffer);
524 II = getIdentifierInfo(CleanedStr);
528 // Update the token info (identifier info and appropriate token kind).
529 Identifier.setIdentifierInfo(II);
530 Identifier.setKind(II->getTokenID());
535 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
536 PoisonReasons[II] = DiagID;
539 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
540 assert(Ident__exception_code && Ident__exception_info);
541 assert(Ident___exception_code && Ident___exception_info);
542 Ident__exception_code->setIsPoisoned(Poison);
543 Ident___exception_code->setIsPoisoned(Poison);
544 Ident_GetExceptionCode->setIsPoisoned(Poison);
545 Ident__exception_info->setIsPoisoned(Poison);
546 Ident___exception_info->setIsPoisoned(Poison);
547 Ident_GetExceptionInfo->setIsPoisoned(Poison);
548 Ident__abnormal_termination->setIsPoisoned(Poison);
549 Ident___abnormal_termination->setIsPoisoned(Poison);
550 Ident_AbnormalTermination->setIsPoisoned(Poison);
553 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
554 assert(Identifier.getIdentifierInfo() &&
555 "Can't handle identifiers without identifier info!");
556 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
557 PoisonReasons.find(Identifier.getIdentifierInfo());
558 if(it == PoisonReasons.end())
559 Diag(Identifier, diag::err_pp_used_poisoned_id);
561 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
564 /// HandleIdentifier - This callback is invoked when the lexer reads an
565 /// identifier. This callback looks up the identifier in the map and/or
566 /// potentially macro expands it or turns it into a named token (like 'for').
568 /// Note that callers of this method are guarded by checking the
569 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
570 /// IdentifierInfo methods that compute these properties will need to change to
572 bool Preprocessor::HandleIdentifier(Token &Identifier) {
573 assert(Identifier.getIdentifierInfo() &&
574 "Can't handle identifiers without identifier info!");
576 IdentifierInfo &II = *Identifier.getIdentifierInfo();
578 // If the information about this identifier is out of date, update it from
579 // the external source.
580 // We have to treat __VA_ARGS__ in a special way, since it gets
581 // serialized with isPoisoned = true, but our preprocessor may have
582 // unpoisoned it if we're defining a C99 macro.
583 if (II.isOutOfDate()) {
584 bool CurrentIsPoisoned = false;
585 if (&II == Ident__VA_ARGS__)
586 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
588 ExternalSource->updateOutOfDateIdentifier(II);
589 Identifier.setKind(II.getTokenID());
591 if (&II == Ident__VA_ARGS__)
592 II.setIsPoisoned(CurrentIsPoisoned);
595 // If this identifier was poisoned, and if it was not produced from a macro
596 // expansion, emit an error.
597 if (II.isPoisoned() && CurPPLexer) {
598 HandlePoisonedIdentifier(Identifier);
601 // If this is a macro to be expanded, do it.
602 if (MacroDirective *MD = getMacroDirective(&II)) {
603 MacroInfo *MI = MD->getMacroInfo();
604 if (!DisableMacroExpansion) {
605 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
606 // C99 6.10.3p10: If the preprocessing token immediately after the
607 // macro name isn't a '(', this macro should not be expanded.
608 if (!MI->isFunctionLike() || isNextPPTokenLParen())
609 return HandleMacroExpandedIdentifier(Identifier, MD);
611 // C99 6.10.3.4p2 says that a disabled macro may never again be
612 // expanded, even if it's in a context where it could be expanded in the
614 Identifier.setFlag(Token::DisableExpand);
615 if (MI->isObjectLike() || isNextPPTokenLParen())
616 Diag(Identifier, diag::pp_disabled_macro_expansion);
621 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
622 // we're not considering macro expansion, since this identifier might be the
624 // FIXME: This warning is disabled in cases where it shouldn't be, like
625 // "#define constexpr constexpr", "int constexpr;"
626 if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
627 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
628 // Don't diagnose this keyword again in this translation unit.
629 II.setIsCXX11CompatKeyword(false);
632 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
633 // then we act as if it is the actual operator and not the textual
634 // representation of it.
635 if (II.isCPlusPlusOperatorKeyword())
636 Identifier.setIdentifierInfo(nullptr);
638 // If this is an extension token, diagnose its use.
639 // We avoid diagnosing tokens that originate from macro definitions.
640 // FIXME: This warning is disabled in cases where it shouldn't be,
641 // like "#define TY typeof", "TY(1) x".
642 if (II.isExtensionToken() && !DisableMacroExpansion)
643 Diag(Identifier, diag::ext_token_used);
645 // If this is the 'import' contextual keyword following an '@', note
646 // that the next token indicates a module name.
648 // Note that we do not treat 'import' as a contextual
649 // keyword when we're in a caching lexer, because caching lexers only get
650 // used in contexts where import declarations are disallowed.
651 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
652 !DisableMacroExpansion && getLangOpts().Modules &&
653 CurLexerKind != CLK_CachingLexer) {
654 ModuleImportLoc = Identifier.getLocation();
655 ModuleImportPath.clear();
656 ModuleImportExpectsIdentifier = true;
657 CurLexerKind = CLK_LexAfterModuleImport;
662 void Preprocessor::Lex(Token &Result) {
663 // We loop here until a lex function retuns a token; this avoids recursion.
666 switch (CurLexerKind) {
668 ReturnedToken = CurLexer->Lex(Result);
671 ReturnedToken = CurPTHLexer->Lex(Result);
674 ReturnedToken = CurTokenLexer->Lex(Result);
676 case CLK_CachingLexer:
678 ReturnedToken = true;
680 case CLK_LexAfterModuleImport:
681 LexAfterModuleImport(Result);
682 ReturnedToken = true;
685 } while (!ReturnedToken);
687 LastTokenWasAt = Result.is(tok::at);
691 /// \brief Lex a token following the 'import' contextual keyword.
693 void Preprocessor::LexAfterModuleImport(Token &Result) {
694 // Figure out what kind of lexer we actually have.
695 recomputeCurLexerKind();
697 // Lex the next token.
700 // The token sequence
702 // import identifier (. identifier)*
704 // indicates a module import directive. We already saw the 'import'
705 // contextual keyword, so now we're looking for the identifiers.
706 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
707 // We expected to see an identifier here, and we did; continue handling
709 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
710 Result.getLocation()));
711 ModuleImportExpectsIdentifier = false;
712 CurLexerKind = CLK_LexAfterModuleImport;
716 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
717 // see the next identifier.
718 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
719 ModuleImportExpectsIdentifier = true;
720 CurLexerKind = CLK_LexAfterModuleImport;
724 // If we have a non-empty module path, load the named module.
725 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
726 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
728 Module::MacrosVisible,
729 /*IsIncludeDirective=*/false);
731 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
735 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
736 const char *DiagnosticTag,
737 bool AllowMacroExpansion) {
738 // We need at least one string literal.
739 if (Result.isNot(tok::string_literal)) {
740 Diag(Result, diag::err_expected_string_literal)
741 << /*Source='in...'*/0 << DiagnosticTag;
745 // Lex string literal tokens, optionally with macro expansion.
746 SmallVector<Token, 4> StrToks;
748 StrToks.push_back(Result);
750 if (Result.hasUDSuffix())
751 Diag(Result, diag::err_invalid_string_udl);
753 if (AllowMacroExpansion)
756 LexUnexpandedToken(Result);
757 } while (Result.is(tok::string_literal));
759 // Concatenate and parse the strings.
760 StringLiteralParser Literal(StrToks, *this);
761 assert(Literal.isAscii() && "Didn't allow wide strings in");
763 if (Literal.hadError)
766 if (Literal.Pascal) {
767 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
768 << /*Source='in...'*/0 << DiagnosticTag;
772 String = Literal.GetString();
776 bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
777 assert(Tok.is(tok::numeric_constant));
778 SmallString<8> IntegerBuffer;
779 bool NumberInvalid = false;
780 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
783 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
784 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
786 llvm::APInt APVal(64, 0);
787 if (Literal.GetIntegerValue(APVal))
790 Value = APVal.getLimitedValue();
794 void Preprocessor::addCommentHandler(CommentHandler *Handler) {
795 assert(Handler && "NULL comment handler");
796 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
797 CommentHandlers.end() && "Comment handler already registered");
798 CommentHandlers.push_back(Handler);
801 void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
802 std::vector<CommentHandler *>::iterator Pos
803 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
804 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
805 CommentHandlers.erase(Pos);
808 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
809 bool AnyPendingTokens = false;
810 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
811 HEnd = CommentHandlers.end();
813 if ((*H)->HandleComment(*this, Comment))
814 AnyPendingTokens = true;
816 if (!AnyPendingTokens || getCommentRetentionState())
822 ModuleLoader::~ModuleLoader() { }
824 CommentHandler::~CommentHandler() { }
826 CodeCompletionHandler::~CodeCompletionHandler() { }
828 void Preprocessor::createPreprocessingRecord() {
832 Record = new PreprocessingRecord(getSourceManager());
833 addPPCallbacks(Record);