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