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/Basic/SourceManager.h"
39 #include "clang/Basic/FileManager.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "llvm/ADT/APFloat.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/Support/MemoryBuffer.h"
44 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
46 
47 //===----------------------------------------------------------------------===//
48 ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
49 
50 Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
51                            const TargetInfo &target, SourceManager &SM,
52                            HeaderSearch &Headers,
53                            IdentifierInfoLookup* IILookup,
54                            bool OwnsHeaders)
55   : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
56     SourceMgr(SM), HeaderInfo(Headers), ExternalSource(0),
57     Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
58     CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
59     CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
60     MICache(0) {
61   ScratchBuf = new ScratchBuffer(SourceMgr);
62   CounterValue = 0; // __COUNTER__ starts at 0.
63   OwnsHeaderSearch = OwnsHeaders;
64 
65   // Clear stats.
66   NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
67   NumIf = NumElse = NumEndif = 0;
68   NumEnteredSourceFiles = 0;
69   NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
70   NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
71   MaxIncludeStackDepth = 0;
72   NumSkipped = 0;
73 
74   // Default to discarding comments.
75   KeepComments = false;
76   KeepMacroComments = false;
77 
78   // Macro expansion is enabled.
79   DisableMacroExpansion = false;
80   InMacroArgs = false;
81   NumCachedTokenLexers = 0;
82 
83   CachedLexPos = 0;
84 
85   // We haven't read anything from the external source.
86   ReadMacrosFromExternalSource = false;
87 
88   // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
89   // This gets unpoisoned where it is allowed.
90   (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
91 
92   // Initialize the pragma handlers.
93   PragmaHandlers = new PragmaNamespace(llvm::StringRef());
94   RegisterBuiltinPragmas();
95 
96   // Initialize builtin macros like __LINE__ and friends.
97   RegisterBuiltinMacros();
98 }
99 
100 Preprocessor::~Preprocessor() {
101   assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
102 
103   while (!IncludeMacroStack.empty()) {
104     delete IncludeMacroStack.back().TheLexer;
105     delete IncludeMacroStack.back().TheTokenLexer;
106     IncludeMacroStack.pop_back();
107   }
108 
109   // Free any macro definitions.
110   for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
111     I->MI.Destroy();
112 
113   // Free any cached macro expanders.
114   for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
115     delete TokenLexerCache[i];
116 
117   // Free any cached MacroArgs.
118   for (MacroArgs *ArgList = MacroArgCache; ArgList; )
119     ArgList = ArgList->deallocate();
120 
121   // Release pragma information.
122   delete PragmaHandlers;
123 
124   // Delete the scratch buffer info.
125   delete ScratchBuf;
126 
127   // Delete the header search info, if we own it.
128   if (OwnsHeaderSearch)
129     delete &HeaderInfo;
130 
131   delete Callbacks;
132 }
133 
134 void Preprocessor::setPTHManager(PTHManager* pm) {
135   PTH.reset(pm);
136   FileMgr.addStatCache(PTH->createStatCache());
137 }
138 
139 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
140   llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
141                << getSpelling(Tok) << "'";
142 
143   if (!DumpFlags) return;
144 
145   llvm::errs() << "\t";
146   if (Tok.isAtStartOfLine())
147     llvm::errs() << " [StartOfLine]";
148   if (Tok.hasLeadingSpace())
149     llvm::errs() << " [LeadingSpace]";
150   if (Tok.isExpandDisabled())
151     llvm::errs() << " [ExpandDisabled]";
152   if (Tok.needsCleaning()) {
153     const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
154     llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength())
155                  << "']";
156   }
157 
158   llvm::errs() << "\tLoc=<";
159   DumpLocation(Tok.getLocation());
160   llvm::errs() << ">";
161 }
162 
163 void Preprocessor::DumpLocation(SourceLocation Loc) const {
164   Loc.dump(SourceMgr);
165 }
166 
167 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
168   llvm::errs() << "MACRO: ";
169   for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
170     DumpToken(MI.getReplacementToken(i));
171     llvm::errs() << "  ";
172   }
173   llvm::errs() << "\n";
174 }
175 
176 void Preprocessor::PrintStats() {
177   llvm::errs() << "\n*** Preprocessor Stats:\n";
178   llvm::errs() << NumDirectives << " directives found:\n";
179   llvm::errs() << "  " << NumDefined << " #define.\n";
180   llvm::errs() << "  " << NumUndefined << " #undef.\n";
181   llvm::errs() << "  #include/#include_next/#import:\n";
182   llvm::errs() << "    " << NumEnteredSourceFiles << " source files entered.\n";
183   llvm::errs() << "    " << MaxIncludeStackDepth << " max include stack depth\n";
184   llvm::errs() << "  " << NumIf << " #if/#ifndef/#ifdef.\n";
185   llvm::errs() << "  " << NumElse << " #else/#elif.\n";
186   llvm::errs() << "  " << NumEndif << " #endif.\n";
187   llvm::errs() << "  " << NumPragma << " #pragma.\n";
188   llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
189 
190   llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
191              << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
192              << NumFastMacroExpanded << " on the fast path.\n";
193   llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
194              << " token paste (##) operations performed, "
195              << NumFastTokenPaste << " on the fast path.\n";
196 }
197 
198 Preprocessor::macro_iterator
199 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
200   if (IncludeExternalMacros && ExternalSource &&
201       !ReadMacrosFromExternalSource) {
202     ReadMacrosFromExternalSource = true;
203     ExternalSource->ReadDefinedMacros();
204   }
205 
206   return Macros.begin();
207 }
208 
209 Preprocessor::macro_iterator
210 Preprocessor::macro_end(bool IncludeExternalMacros) const {
211   if (IncludeExternalMacros && ExternalSource &&
212       !ReadMacrosFromExternalSource) {
213     ReadMacrosFromExternalSource = true;
214     ExternalSource->ReadDefinedMacros();
215   }
216 
217   return Macros.end();
218 }
219 
220 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
221                                           unsigned TruncateAtLine,
222                                           unsigned TruncateAtColumn) {
223   using llvm::MemoryBuffer;
224 
225   CodeCompletionFile = File;
226 
227   // Okay to clear out the code-completion point by passing NULL.
228   if (!CodeCompletionFile)
229     return false;
230 
231   // Load the actual file's contents.
232   bool Invalid = false;
233   const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
234   if (Invalid)
235     return true;
236 
237   // Find the byte position of the truncation point.
238   const char *Position = Buffer->getBufferStart();
239   for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
240     for (; *Position; ++Position) {
241       if (*Position != '\r' && *Position != '\n')
242         continue;
243 
244       // Eat \r\n or \n\r as a single line.
245       if ((Position[1] == '\r' || Position[1] == '\n') &&
246           Position[0] != Position[1])
247         ++Position;
248       ++Position;
249       break;
250     }
251   }
252 
253   Position += TruncateAtColumn - 1;
254 
255   // Truncate the buffer.
256   if (Position < Buffer->getBufferEnd()) {
257     llvm::StringRef Data(Buffer->getBufferStart(),
258                          Position-Buffer->getBufferStart());
259     MemoryBuffer *TruncatedBuffer
260       = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
261     SourceMgr.overrideFileContents(File, TruncatedBuffer);
262   }
263 
264   return false;
265 }
266 
267 bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
268   return CodeCompletionFile && FileLoc.isFileID() &&
269     SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
270       == CodeCompletionFile;
271 }
272 
273 void Preprocessor::CodeCompleteNaturalLanguage() {
274   SetCodeCompletionPoint(0, 0, 0);
275   getDiagnostics().setSuppressAllDiagnostics(true);
276   if (CodeComplete)
277     CodeComplete->CodeCompleteNaturalLanguage();
278 }
279 
280 //===----------------------------------------------------------------------===//
281 // Token Spelling
282 //===----------------------------------------------------------------------===//
283 
284 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
285 /// token are the characters used to represent the token in the source file
286 /// after trigraph expansion and escaped-newline folding.  In particular, this
287 /// wants to get the true, uncanonicalized, spelling of things like digraphs
288 /// UCNs, etc.
289 std::string Preprocessor::getSpelling(const Token &Tok,
290                                       const SourceManager &SourceMgr,
291                                       const LangOptions &Features,
292                                       bool *Invalid) {
293   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
294 
295   // If this token contains nothing interesting, return it directly.
296   bool CharDataInvalid = false;
297   const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
298                                                     &CharDataInvalid);
299   if (Invalid)
300     *Invalid = CharDataInvalid;
301   if (CharDataInvalid)
302     return std::string();
303 
304   if (!Tok.needsCleaning())
305     return std::string(TokStart, TokStart+Tok.getLength());
306 
307   std::string Result;
308   Result.reserve(Tok.getLength());
309 
310   // Otherwise, hard case, relex the characters into the string.
311   for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
312        Ptr != End; ) {
313     unsigned CharSize;
314     Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
315     Ptr += CharSize;
316   }
317   assert(Result.size() != unsigned(Tok.getLength()) &&
318          "NeedsCleaning flag set on something that didn't need cleaning!");
319   return Result;
320 }
321 
322 /// getSpelling() - Return the 'spelling' of this token.  The spelling of a
323 /// token are the characters used to represent the token in the source file
324 /// after trigraph expansion and escaped-newline folding.  In particular, this
325 /// wants to get the true, uncanonicalized, spelling of things like digraphs
326 /// UCNs, etc.
327 std::string Preprocessor::getSpelling(const Token &Tok, bool *Invalid) const {
328   return getSpelling(Tok, SourceMgr, Features, Invalid);
329 }
330 
331 /// getSpelling - This method is used to get the spelling of a token into a
332 /// preallocated buffer, instead of as an std::string.  The caller is required
333 /// to allocate enough space for the token, which is guaranteed to be at least
334 /// Tok.getLength() bytes long.  The actual length of the token is returned.
335 ///
336 /// Note that this method may do two possible things: it may either fill in
337 /// the buffer specified with characters, or it may *change the input pointer*
338 /// to point to a constant buffer with the data already in it (avoiding a
339 /// copy).  The caller is not allowed to modify the returned buffer pointer
340 /// if an internal buffer is returned.
341 unsigned Preprocessor::getSpelling(const Token &Tok,
342                                    const char *&Buffer, bool *Invalid) const {
343   assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
344 
345   // If this token is an identifier, just return the string from the identifier
346   // table, which is very quick.
347   if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
348     Buffer = II->getNameStart();
349     return II->getLength();
350   }
351 
352   // Otherwise, compute the start of the token in the input lexer buffer.
353   const char *TokStart = 0;
354 
355   if (Tok.isLiteral())
356     TokStart = Tok.getLiteralData();
357 
358   if (TokStart == 0) {
359     bool CharDataInvalid = false;
360     TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
361     if (Invalid)
362       *Invalid = CharDataInvalid;
363     if (CharDataInvalid) {
364       Buffer = "";
365       return 0;
366     }
367   }
368 
369   // If this token contains nothing interesting, return it directly.
370   if (!Tok.needsCleaning()) {
371     Buffer = TokStart;
372     return Tok.getLength();
373   }
374 
375   // Otherwise, hard case, relex the characters into the string.
376   char *OutBuf = const_cast<char*>(Buffer);
377   for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
378        Ptr != End; ) {
379     unsigned CharSize;
380     *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
381     Ptr += CharSize;
382   }
383   assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
384          "NeedsCleaning flag set on something that didn't need cleaning!");
385 
386   return OutBuf-Buffer;
387 }
388 
389 /// getSpelling - This method is used to get the spelling of a token into a
390 /// SmallVector. Note that the returned StringRef may not point to the
391 /// supplied buffer if a copy can be avoided.
392 llvm::StringRef Preprocessor::getSpelling(const Token &Tok,
393                                           llvm::SmallVectorImpl<char> &Buffer,
394                                           bool *Invalid) const {
395   // Try the fast path.
396   if (const IdentifierInfo *II = Tok.getIdentifierInfo())
397     return II->getName();
398 
399   // Resize the buffer if we need to copy into it.
400   if (Tok.needsCleaning())
401     Buffer.resize(Tok.getLength());
402 
403   const char *Ptr = Buffer.data();
404   unsigned Len = getSpelling(Tok, Ptr, Invalid);
405   return llvm::StringRef(Ptr, Len);
406 }
407 
408 /// CreateString - Plop the specified string into a scratch buffer and return a
409 /// location for it.  If specified, the source location provides a source
410 /// location for the token.
411 void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
412                                 SourceLocation InstantiationLoc) {
413   Tok.setLength(Len);
414 
415   const char *DestPtr;
416   SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
417 
418   if (InstantiationLoc.isValid())
419     Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
420                                            InstantiationLoc, Len);
421   Tok.setLocation(Loc);
422 
423   // If this is a literal token, set the pointer data.
424   if (Tok.isLiteral())
425     Tok.setLiteralData(DestPtr);
426 }
427 
428 
429 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
430 /// token, return a new location that specifies a character within the token.
431 SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
432                                                      unsigned CharNo) {
433   // Figure out how many physical characters away the specified instantiation
434   // character is.  This needs to take into consideration newlines and
435   // trigraphs.
436   bool Invalid = false;
437   const char *TokPtr = SourceMgr.getCharacterData(TokStart, &Invalid);
438 
439   // If they request the first char of the token, we're trivially done.
440   if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
441     return TokStart;
442 
443   unsigned PhysOffset = 0;
444 
445   // The usual case is that tokens don't contain anything interesting.  Skip
446   // over the uninteresting characters.  If a token only consists of simple
447   // chars, this method is extremely fast.
448   while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
449     if (CharNo == 0)
450       return TokStart.getFileLocWithOffset(PhysOffset);
451     ++TokPtr, --CharNo, ++PhysOffset;
452   }
453 
454   // If we have a character that may be a trigraph or escaped newline, use a
455   // lexer to parse it correctly.
456   for (; CharNo; --CharNo) {
457     unsigned Size;
458     Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
459     TokPtr += Size;
460     PhysOffset += Size;
461   }
462 
463   // Final detail: if we end up on an escaped newline, we want to return the
464   // location of the actual byte of the token.  For example foo\<newline>bar
465   // advanced by 3 should return the location of b, not of \\.  One compounding
466   // detail of this is that the escape may be made by a trigraph.
467   if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
468     PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
469 
470   return TokStart.getFileLocWithOffset(PhysOffset);
471 }
472 
473 SourceLocation Preprocessor::getLocForEndOfToken(SourceLocation Loc,
474                                                  unsigned Offset) {
475   if (Loc.isInvalid() || !Loc.isFileID())
476     return SourceLocation();
477 
478   unsigned Len = Lexer::MeasureTokenLength(Loc, getSourceManager(), Features);
479   if (Len > Offset)
480     Len = Len - Offset;
481   else
482     return Loc;
483 
484   return AdvanceToTokenCharacter(Loc, Len);
485 }
486 
487 
488 
489 //===----------------------------------------------------------------------===//
490 // Preprocessor Initialization Methods
491 //===----------------------------------------------------------------------===//
492 
493 
494 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
495 /// which implicitly adds the builtin defines etc.
496 void Preprocessor::EnterMainSourceFile() {
497   // We do not allow the preprocessor to reenter the main file.  Doing so will
498   // cause FileID's to accumulate information from both runs (e.g. #line
499   // information) and predefined macros aren't guaranteed to be set properly.
500   assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
501   FileID MainFileID = SourceMgr.getMainFileID();
502 
503   // Enter the main file source buffer.
504   EnterSourceFile(MainFileID, 0, SourceLocation());
505 
506   // If we've been asked to skip bytes in the main file (e.g., as part of a
507   // precompiled preamble), do so now.
508   if (SkipMainFilePreamble.first > 0)
509     CurLexer->SkipBytes(SkipMainFilePreamble.first,
510                         SkipMainFilePreamble.second);
511 
512   // Tell the header info that the main file was entered.  If the file is later
513   // #imported, it won't be re-entered.
514   if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
515     HeaderInfo.IncrementIncludeCount(FE);
516 
517   // Preprocess Predefines to populate the initial preprocessor state.
518   llvm::MemoryBuffer *SB =
519     llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
520   assert(SB && "Cannot create predefined source buffer");
521   FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
522   assert(!FID.isInvalid() && "Could not create FileID for predefines?");
523 
524   // Start parsing the predefines.
525   EnterSourceFile(FID, 0, SourceLocation());
526 }
527 
528 void Preprocessor::EndSourceFile() {
529   // Notify the client that we reached the end of the source file.
530   if (Callbacks)
531     Callbacks->EndOfMainFile();
532 }
533 
534 //===----------------------------------------------------------------------===//
535 // Lexer Event Handling.
536 //===----------------------------------------------------------------------===//
537 
538 /// LookUpIdentifierInfo - Given a tok::identifier token, look up the
539 /// identifier information for the token and install it into the token.
540 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
541                                                    const char *BufPtr) const {
542   assert(Identifier.is(tok::identifier) && "Not an identifier!");
543   assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
544 
545   // Look up this token, see if it is a macro, or if it is a language keyword.
546   IdentifierInfo *II;
547   if (BufPtr && !Identifier.needsCleaning()) {
548     // No cleaning needed, just use the characters from the lexed buffer.
549     II = getIdentifierInfo(llvm::StringRef(BufPtr, Identifier.getLength()));
550   } else {
551     // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
552     llvm::SmallString<64> IdentifierBuffer;
553     llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
554     II = getIdentifierInfo(CleanedStr);
555   }
556   Identifier.setIdentifierInfo(II);
557   return II;
558 }
559 
560 
561 /// HandleIdentifier - This callback is invoked when the lexer reads an
562 /// identifier.  This callback looks up the identifier in the map and/or
563 /// potentially macro expands it or turns it into a named token (like 'for').
564 ///
565 /// Note that callers of this method are guarded by checking the
566 /// IdentifierInfo's 'isHandleIdentifierCase' bit.  If this method changes, the
567 /// IdentifierInfo methods that compute these properties will need to change to
568 /// match.
569 void Preprocessor::HandleIdentifier(Token &Identifier) {
570   assert(Identifier.getIdentifierInfo() &&
571          "Can't handle identifiers without identifier info!");
572 
573   IdentifierInfo &II = *Identifier.getIdentifierInfo();
574 
575   // If this identifier was poisoned, and if it was not produced from a macro
576   // expansion, emit an error.
577   if (II.isPoisoned() && CurPPLexer) {
578     if (&II != Ident__VA_ARGS__)   // We warn about __VA_ARGS__ with poisoning.
579       Diag(Identifier, diag::err_pp_used_poisoned_id);
580     else
581       Diag(Identifier, diag::ext_pp_bad_vaargs_use);
582   }
583 
584   // If this is a macro to be expanded, do it.
585   if (MacroInfo *MI = getMacroInfo(&II)) {
586     if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
587       if (MI->isEnabled()) {
588         if (!HandleMacroExpandedIdentifier(Identifier, MI))
589           return;
590       } else {
591         // C99 6.10.3.4p2 says that a disabled macro may never again be
592         // expanded, even if it's in a context where it could be expanded in the
593         // future.
594         Identifier.setFlag(Token::DisableExpand);
595       }
596     }
597   }
598 
599   // C++ 2.11p2: If this is an alternative representation of a C++ operator,
600   // then we act as if it is the actual operator and not the textual
601   // representation of it.
602   if (II.isCPlusPlusOperatorKeyword())
603     Identifier.setIdentifierInfo(0);
604 
605   // If this is an extension token, diagnose its use.
606   // We avoid diagnosing tokens that originate from macro definitions.
607   // FIXME: This warning is disabled in cases where it shouldn't be,
608   // like "#define TY typeof", "TY(1) x".
609   if (II.isExtensionToken() && !DisableMacroExpansion)
610     Diag(Identifier, diag::ext_token_used);
611 }
612 
613 void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
614   assert(Handler && "NULL comment handler");
615   assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
616          CommentHandlers.end() && "Comment handler already registered");
617   CommentHandlers.push_back(Handler);
618 }
619 
620 void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
621   std::vector<CommentHandler *>::iterator Pos
622   = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
623   assert(Pos != CommentHandlers.end() && "Comment handler not registered");
624   CommentHandlers.erase(Pos);
625 }
626 
627 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
628   bool AnyPendingTokens = false;
629   for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
630        HEnd = CommentHandlers.end();
631        H != HEnd; ++H) {
632     if ((*H)->HandleComment(*this, Comment))
633       AnyPendingTokens = true;
634   }
635   if (!AnyPendingTokens || getCommentRetentionState())
636     return false;
637   Lex(result);
638   return true;
639 }
640 
641 CommentHandler::~CommentHandler() { }
642 
643 CodeCompletionHandler::~CodeCompletionHandler() { }
644 
645 void Preprocessor::createPreprocessingRecord() {
646   if (Record)
647     return;
648 
649   Record = new PreprocessingRecord;
650   addPPCallbacks(Record);
651 }
652