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