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