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