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