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 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     : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(target),
64       FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
65       TheModuleLoader(TheModuleLoader), ExternalSource(0),
66       Identifiers(opts, IILookup), IncrementalProcessing(IncrProcessing),
67       CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0),
68       CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
69       CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0),
70       MacroArgCache(0), Record(0), MIChainHead(0), MICache(0) {
71   OwnsHeaderSearch = OwnsHeaders;
72 
73   ScratchBuf = new ScratchBuffer(SourceMgr);
74   CounterValue = 0; // __COUNTER__ starts at 0.
75 
76   // Clear stats.
77   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
78   NumIf = NumElse = NumEndif = 0;
79   NumEnteredSourceFiles = 0;
80   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
81   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
82   MaxIncludeStackDepth = 0;
83   NumSkipped = 0;
84 
85   // Default to discarding comments.
86   KeepComments = false;
87   KeepMacroComments = false;
88   SuppressIncludeNotFoundError = false;
89 
90   // Macro expansion is enabled.
91   DisableMacroExpansion = false;
92   MacroExpansionInDirectivesOverride = false;
93   InMacroArgs = false;
94   InMacroArgPreExpansion = false;
95   NumCachedTokenLexers = 0;
96   PragmasEnabled = true;
97   ParsingIfOrElifDirective = false;
98   PreprocessedOutput = false;
99 
100   CachedLexPos = 0;
101 
102   // We haven't read anything from the external source.
103   ReadMacrosFromExternalSource = false;
104 
105   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
106   // This gets unpoisoned where it is allowed.
107   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
108   SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
109 
110   // Initialize the pragma handlers.
111   PragmaHandlers = new PragmaNamespace(StringRef());
112   RegisterBuiltinPragmas();
113 
114   // Initialize builtin macros like __LINE__ and friends.
115   RegisterBuiltinMacros();
116 
117   if(LangOpts.Borland) {
118     Ident__exception_info        = getIdentifierInfo("_exception_info");
119     Ident___exception_info       = getIdentifierInfo("__exception_info");
120     Ident_GetExceptionInfo       = getIdentifierInfo("GetExceptionInformation");
121     Ident__exception_code        = getIdentifierInfo("_exception_code");
122     Ident___exception_code       = getIdentifierInfo("__exception_code");
123     Ident_GetExceptionCode       = getIdentifierInfo("GetExceptionCode");
124     Ident__abnormal_termination  = getIdentifierInfo("_abnormal_termination");
125     Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
126     Ident_AbnormalTermination    = getIdentifierInfo("AbnormalTermination");
127   } else {
128     Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
129     Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
130     Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
131   }
132 
133   if (!DelayInitialization) {
134     assert(Target && "Must provide target information for PP initialization");
135     Initialize(*Target);
136   }
137 }
138 
139 Preprocessor::~Preprocessor() {
140   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
141 
142   while (!IncludeMacroStack.empty()) {
143     delete IncludeMacroStack.back().TheLexer;
144     delete IncludeMacroStack.back().TheTokenLexer;
145     IncludeMacroStack.pop_back();
146   }
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   // Free any cached MacroArgs.
157   for (MacroArgs *ArgList = MacroArgCache; ArgList; )
158     ArgList = ArgList->deallocate();
159 
160   // Release pragma information.
161   delete PragmaHandlers;
162 
163   // Delete the scratch buffer info.
164   delete ScratchBuf;
165 
166   // Delete the header search info, if we own it.
167   if (OwnsHeaderSearch)
168     delete &HeaderInfo;
169 
170   delete Callbacks;
171 }
172 
173 void Preprocessor::Initialize(const TargetInfo &Target) {
174   assert((!this->Target || this->Target == &Target) &&
175          "Invalid override of target information");
176   this->Target = &Target;
177 
178   // Initialize information about built-ins.
179   BuiltinInfo.InitializeTarget(Target);
180   HeaderInfo.setTarget(Target);
181 }
182 
183 void Preprocessor::setPTHManager(PTHManager* pm) {
184   PTH.reset(pm);
185   FileMgr.addStatCache(PTH->createStatCache());
186 }
187 
188 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
189   llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
190                << getSpelling(Tok) << "'";
191 
192   if (!DumpFlags) return;
193 
194   llvm::errs() << "\t";
195   if (Tok.isAtStartOfLine())
196     llvm::errs() << " [StartOfLine]";
197   if (Tok.hasLeadingSpace())
198     llvm::errs() << " [LeadingSpace]";
199   if (Tok.isExpandDisabled())
200     llvm::errs() << " [ExpandDisabled]";
201   if (Tok.needsCleaning()) {
202     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
203     llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
204                  << "']";
205   }
206 
207   llvm::errs() << "\tLoc=<";
208   DumpLocation(Tok.getLocation());
209   llvm::errs() << ">";
210 }
211 
212 void Preprocessor::DumpLocation(SourceLocation Loc) const {
213   Loc.dump(SourceMgr);
214 }
215 
216 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
217   llvm::errs() << "MACRO: ";
218   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
219     DumpToken(MI.getReplacementToken(i));
220     llvm::errs() << "  ";
221   }
222   llvm::errs() << "\n";
223 }
224 
225 void Preprocessor::PrintStats() {
226   llvm::errs() << "\n*** Preprocessor Stats:\n";
227   llvm::errs() << NumDirectives << " directives found:\n";
228   llvm::errs() << "  " << NumDefined << " #define.\n";
229   llvm::errs() << "  " << NumUndefined << " #undef.\n";
230   llvm::errs() << "  #include/#include_next/#import:\n";
231   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
232   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
233   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
234   llvm::errs() << "  " << NumElse << " #else/#elif.\n";
235   llvm::errs() << "  " << NumEndif << " #endif.\n";
236   llvm::errs() << "  " << NumPragma << " #pragma.\n";
237   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
238 
239   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
240              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
241              << NumFastMacroExpanded << " on the fast path.\n";
242   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
243              << " token paste (##) operations performed, "
244              << NumFastTokenPaste << " on the fast path.\n";
245 
246   llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
247 
248   llvm::errs() << "\n  BumpPtr: " << BP.getTotalMemory();
249   llvm::errs() << "\n  Macro Expanded Tokens: "
250                << llvm::capacity_in_bytes(MacroExpandedTokens);
251   llvm::errs() << "\n  Predefines Buffer: " << Predefines.capacity();
252   llvm::errs() << "\n  Macros: " << llvm::capacity_in_bytes(Macros);
253   llvm::errs() << "\n  #pragma push_macro Info: "
254                << llvm::capacity_in_bytes(PragmaPushMacroInfo);
255   llvm::errs() << "\n  Poison Reasons: "
256                << llvm::capacity_in_bytes(PoisonReasons);
257   llvm::errs() << "\n  Comment Handlers: "
258                << llvm::capacity_in_bytes(CommentHandlers) << "\n";
259 }
260 
261 Preprocessor::macro_iterator
262 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
263   if (IncludeExternalMacros && ExternalSource &&
264       !ReadMacrosFromExternalSource) {
265     ReadMacrosFromExternalSource = true;
266     ExternalSource->ReadDefinedMacros();
267   }
268 
269   return Macros.begin();
270 }
271 
272 size_t Preprocessor::getTotalMemory() const {
273   return BP.getTotalMemory()
274     + llvm::capacity_in_bytes(MacroExpandedTokens)
275     + Predefines.capacity() /* Predefines buffer. */
276     + llvm::capacity_in_bytes(Macros)
277     + llvm::capacity_in_bytes(PragmaPushMacroInfo)
278     + llvm::capacity_in_bytes(PoisonReasons)
279     + llvm::capacity_in_bytes(CommentHandlers);
280 }
281 
282 Preprocessor::macro_iterator
283 Preprocessor::macro_end(bool IncludeExternalMacros) const {
284   if (IncludeExternalMacros && ExternalSource &&
285       !ReadMacrosFromExternalSource) {
286     ReadMacrosFromExternalSource = true;
287     ExternalSource->ReadDefinedMacros();
288   }
289 
290   return Macros.end();
291 }
292 
293 /// \brief Compares macro tokens with a specified token value sequence.
294 static bool MacroDefinitionEquals(const MacroInfo *MI,
295                                   ArrayRef<TokenValue> Tokens) {
296   return Tokens.size() == MI->getNumTokens() &&
297       std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
298 }
299 
300 StringRef Preprocessor::getLastMacroWithSpelling(
301                                     SourceLocation Loc,
302                                     ArrayRef<TokenValue> Tokens) const {
303   SourceLocation BestLocation;
304   StringRef BestSpelling;
305   for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
306        I != E; ++I) {
307     if (!I->second->getMacroInfo()->isObjectLike())
308       continue;
309     const MacroDirective::DefInfo
310       Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
311     if (!Def)
312       continue;
313     if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
314       continue;
315     SourceLocation Location = Def.getLocation();
316     // Choose the macro defined latest.
317     if (BestLocation.isInvalid() ||
318         (Location.isValid() &&
319          SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
320       BestLocation = Location;
321       BestSpelling = I->first->getName();
322     }
323   }
324   return BestSpelling;
325 }
326 
327 void Preprocessor::recomputeCurLexerKind() {
328   if (CurLexer)
329     CurLexerKind = CLK_Lexer;
330   else if (CurPTHLexer)
331     CurLexerKind = CLK_PTHLexer;
332   else if (CurTokenLexer)
333     CurLexerKind = CLK_TokenLexer;
334   else
335     CurLexerKind = CLK_CachingLexer;
336 }
337 
338 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
339                                           unsigned CompleteLine,
340                                           unsigned CompleteColumn) {
341   assert(File);
342   assert(CompleteLine && CompleteColumn && "Starts from 1:1");
343   assert(!CodeCompletionFile && "Already set");
344 
345   using llvm::MemoryBuffer;
346 
347   // Load the actual file's contents.
348   bool Invalid = false;
349   const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
350   if (Invalid)
351     return true;
352 
353   // Find the byte position of the truncation point.
354   const char *Position = Buffer->getBufferStart();
355   for (unsigned Line = 1; Line < CompleteLine; ++Line) {
356     for (; *Position; ++Position) {
357       if (*Position != '\r' && *Position != '\n')
358         continue;
359 
360       // Eat \r\n or \n\r as a single line.
361       if ((Position[1] == '\r' || Position[1] == '\n') &&
362           Position[0] != Position[1])
363         ++Position;
364       ++Position;
365       break;
366     }
367   }
368 
369   Position += CompleteColumn - 1;
370 
371   // Insert '\0' at the code-completion point.
372   if (Position < Buffer->getBufferEnd()) {
373     CodeCompletionFile = File;
374     CodeCompletionOffset = Position - Buffer->getBufferStart();
375 
376     MemoryBuffer *NewBuffer =
377         MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
378                                             Buffer->getBufferIdentifier());
379     char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
380     char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
381     *NewPos = '\0';
382     std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
383     SourceMgr.overrideFileContents(File, NewBuffer);
384   }
385 
386   return false;
387 }
388 
389 void Preprocessor::CodeCompleteNaturalLanguage() {
390   if (CodeComplete)
391     CodeComplete->CodeCompleteNaturalLanguage();
392   setCodeCompletionReached();
393 }
394 
395 /// getSpelling - This method is used to get the spelling of a token into a
396 /// SmallVector. Note that the returned StringRef may not point to the
397 /// supplied buffer if a copy can be avoided.
398 StringRef Preprocessor::getSpelling(const Token &Tok,
399                                           SmallVectorImpl<char> &Buffer,
400                                           bool *Invalid) const {
401   // NOTE: this has to be checked *before* testing for an IdentifierInfo.
402   if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
403     // Try the fast path.
404     if (const IdentifierInfo *II = Tok.getIdentifierInfo())
405       return II->getName();
406   }
407 
408   // Resize the buffer if we need to copy into it.
409   if (Tok.needsCleaning())
410     Buffer.resize(Tok.getLength());
411 
412   const char *Ptr = Buffer.data();
413   unsigned Len = getSpelling(Tok, Ptr, Invalid);
414   return StringRef(Ptr, Len);
415 }
416 
417 /// CreateString - Plop the specified string into a scratch buffer and return a
418 /// location for it.  If specified, the source location provides a source
419 /// location for the token.
420 void Preprocessor::CreateString(StringRef Str, Token &Tok,
421                                 SourceLocation ExpansionLocStart,
422                                 SourceLocation ExpansionLocEnd) {
423   Tok.setLength(Str.size());
424 
425   const char *DestPtr;
426   SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
427 
428   if (ExpansionLocStart.isValid())
429     Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
430                                        ExpansionLocEnd, Str.size());
431   Tok.setLocation(Loc);
432 
433   // If this is a raw identifier or a literal token, set the pointer data.
434   if (Tok.is(tok::raw_identifier))
435     Tok.setRawIdentifierData(DestPtr);
436   else if (Tok.isLiteral())
437     Tok.setLiteralData(DestPtr);
438 }
439 
440 Module *Preprocessor::getCurrentModule() {
441   if (getLangOpts().CurrentModule.empty())
442     return 0;
443 
444   return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
445 }
446 
447 //===----------------------------------------------------------------------===//
448 // Preprocessor Initialization Methods
449 //===----------------------------------------------------------------------===//
450 
451 
452 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
453 /// which implicitly adds the builtin defines etc.
454 void Preprocessor::EnterMainSourceFile() {
455   // We do not allow the preprocessor to reenter the main file.  Doing so will
456   // cause FileID's to accumulate information from both runs (e.g. #line
457   // information) and predefined macros aren't guaranteed to be set properly.
458   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
459   FileID MainFileID = SourceMgr.getMainFileID();
460 
461   // If MainFileID is loaded it means we loaded an AST file, no need to enter
462   // a main file.
463   if (!SourceMgr.isLoadedFileID(MainFileID)) {
464     // Enter the main file source buffer.
465     EnterSourceFile(MainFileID, 0, SourceLocation());
466 
467     // If we've been asked to skip bytes in the main file (e.g., as part of a
468     // precompiled preamble), do so now.
469     if (SkipMainFilePreamble.first > 0)
470       CurLexer->SkipBytes(SkipMainFilePreamble.first,
471                           SkipMainFilePreamble.second);
472 
473     // Tell the header info that the main file was entered.  If the file is later
474     // #imported, it won't be re-entered.
475     if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
476       HeaderInfo.IncrementIncludeCount(FE);
477   }
478 
479   // Preprocess Predefines to populate the initial preprocessor state.
480   llvm::MemoryBuffer *SB =
481     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
482   assert(SB && "Cannot create predefined source buffer");
483   FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
484   assert(!FID.isInvalid() && "Could not create FileID for predefines?");
485   setPredefinesFileID(FID);
486 
487   // Start parsing the predefines.
488   EnterSourceFile(FID, 0, SourceLocation());
489 }
490 
491 void Preprocessor::EndSourceFile() {
492   // Notify the client that we reached the end of the source file.
493   if (Callbacks)
494     Callbacks->EndOfMainFile();
495 }
496 
497 //===----------------------------------------------------------------------===//
498 // Lexer Event Handling.
499 //===----------------------------------------------------------------------===//
500 
501 static void appendCodePoint(unsigned Codepoint,
502                             llvm::SmallVectorImpl<char> &Str) {
503   char ResultBuf[4];
504   char *ResultPtr = ResultBuf;
505   bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
506   (void)Res;
507   assert(Res && "Unexpected conversion failure");
508   Str.append(ResultBuf, ResultPtr);
509 }
510 
511 static void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
512   for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
513     if (*I != '\\') {
514       Buf.push_back(*I);
515       continue;
516     }
517 
518     ++I;
519     assert(*I == 'u' || *I == 'U');
520 
521     unsigned NumHexDigits;
522     if (*I == 'u')
523       NumHexDigits = 4;
524     else
525       NumHexDigits = 8;
526 
527     assert(I + NumHexDigits <= E);
528 
529     uint32_t CodePoint = 0;
530     for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
531       unsigned Value = llvm::hexDigitValue(*I);
532       assert(Value != -1U);
533 
534       CodePoint <<= 4;
535       CodePoint += Value;
536     }
537 
538     appendCodePoint(CodePoint, Buf);
539     --I;
540   }
541 }
542 
543 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
544 /// identifier information for the token and install it into the token,
545 /// updating the token kind accordingly.
546 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
547   assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
548 
549   // Look up this token, see if it is a macro, or if it is a language keyword.
550   IdentifierInfo *II;
551   if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
552     // No cleaning needed, just use the characters from the lexed buffer.
553     II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
554                                      Identifier.getLength()));
555   } else {
556     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
557     SmallString<64> IdentifierBuffer;
558     StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
559 
560     if (Identifier.hasUCN()) {
561       SmallString<64> UCNIdentifierBuffer;
562       expandUCNs(UCNIdentifierBuffer, CleanedStr);
563       II = getIdentifierInfo(UCNIdentifierBuffer);
564     } else {
565       II = getIdentifierInfo(CleanedStr);
566     }
567   }
568 
569   // Update the token info (identifier info and appropriate token kind).
570   Identifier.setIdentifierInfo(II);
571   Identifier.setKind(II->getTokenID());
572 
573   return II;
574 }
575 
576 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
577   PoisonReasons[II] = DiagID;
578 }
579 
580 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
581   assert(Ident__exception_code && Ident__exception_info);
582   assert(Ident___exception_code && Ident___exception_info);
583   Ident__exception_code->setIsPoisoned(Poison);
584   Ident___exception_code->setIsPoisoned(Poison);
585   Ident_GetExceptionCode->setIsPoisoned(Poison);
586   Ident__exception_info->setIsPoisoned(Poison);
587   Ident___exception_info->setIsPoisoned(Poison);
588   Ident_GetExceptionInfo->setIsPoisoned(Poison);
589   Ident__abnormal_termination->setIsPoisoned(Poison);
590   Ident___abnormal_termination->setIsPoisoned(Poison);
591   Ident_AbnormalTermination->setIsPoisoned(Poison);
592 }
593 
594 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
595   assert(Identifier.getIdentifierInfo() &&
596          "Can't handle identifiers without identifier info!");
597   llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
598     PoisonReasons.find(Identifier.getIdentifierInfo());
599   if(it == PoisonReasons.end())
600     Diag(Identifier, diag::err_pp_used_poisoned_id);
601   else
602     Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
603 }
604 
605 /// HandleIdentifier - This callback is invoked when the lexer reads an
606 /// identifier.  This callback looks up the identifier in the map and/or
607 /// potentially macro expands it or turns it into a named token (like 'for').
608 ///
609 /// Note that callers of this method are guarded by checking the
610 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
611 /// IdentifierInfo methods that compute these properties will need to change to
612 /// match.
613 void Preprocessor::HandleIdentifier(Token &Identifier) {
614   assert(Identifier.getIdentifierInfo() &&
615          "Can't handle identifiers without identifier info!");
616 
617   IdentifierInfo &II = *Identifier.getIdentifierInfo();
618 
619   // If the information about this identifier is out of date, update it from
620   // the external source.
621   // We have to treat __VA_ARGS__ in a special way, since it gets
622   // serialized with isPoisoned = true, but our preprocessor may have
623   // unpoisoned it if we're defining a C99 macro.
624   if (II.isOutOfDate()) {
625     bool CurrentIsPoisoned = false;
626     if (&II == Ident__VA_ARGS__)
627       CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
628 
629     ExternalSource->updateOutOfDateIdentifier(II);
630     Identifier.setKind(II.getTokenID());
631 
632     if (&II == Ident__VA_ARGS__)
633       II.setIsPoisoned(CurrentIsPoisoned);
634   }
635 
636   // If this identifier was poisoned, and if it was not produced from a macro
637   // expansion, emit an error.
638   if (II.isPoisoned() && CurPPLexer) {
639     HandlePoisonedIdentifier(Identifier);
640   }
641 
642   // If this is a macro to be expanded, do it.
643   if (MacroDirective *MD = getMacroDirective(&II)) {
644     MacroInfo *MI = MD->getMacroInfo();
645     if (!DisableMacroExpansion) {
646       if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
647         if (!HandleMacroExpandedIdentifier(Identifier, MD))
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