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