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