1 //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Preprocessor interface.
12 //===----------------------------------------------------------------------===//
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.
19 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
24 // "Multiple include guards may be useful for:\n"
26 //===----------------------------------------------------------------------===//
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Lex/PreprocessorOptions.h"
30 #include "MacroArgs.h"
31 #include "clang/Lex/ExternalPreprocessorSource.h"
32 #include "clang/Lex/HeaderSearch.h"
33 #include "clang/Lex/MacroInfo.h"
34 #include "clang/Lex/Pragma.h"
35 #include "clang/Lex/PreprocessingRecord.h"
36 #include "clang/Lex/ScratchBuffer.h"
37 #include "clang/Lex/LexDiagnostic.h"
38 #include "clang/Lex/CodeCompletionHandler.h"
39 #include "clang/Lex/ModuleLoader.h"
40 #include "clang/Basic/SourceManager.h"
41 #include "clang/Basic/FileManager.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "llvm/ADT/APFloat.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/raw_ostream.h"
47 #include "llvm/Support/Capacity.h"
48 using namespace clang;
50 //===----------------------------------------------------------------------===//
51 ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
53 PPMutationListener::~PPMutationListener() { }
55 Preprocessor::Preprocessor(llvm::IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
56 DiagnosticsEngine &diags, LangOptions &opts,
57 const TargetInfo *target, SourceManager &SM,
58 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
59 IdentifierInfoLookup* IILookup,
61 bool DelayInitialization,
63 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(target),
64 FileMgr(Headers.getFileMgr()),
65 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
66 ExternalSource(0), Identifiers(opts, IILookup),
67 IncrementalProcessing(IncrProcessing), CodeComplete(0),
68 CodeCompletionFile(0), CodeCompletionOffset(0), CodeCompletionReached(0),
69 SkipMainFilePreamble(0, true), CurPPLexer(0),
70 CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0), Listener(0),
71 MacroArgCache(0), Record(0), MIChainHead(0), MICache(0)
73 OwnsHeaderSearch = OwnsHeaders;
75 ScratchBuf = new ScratchBuffer(SourceMgr);
76 CounterValue = 0; // __COUNTER__ starts at 0.
79 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
80 NumIf = NumElse = NumEndif = 0;
81 NumEnteredSourceFiles = 0;
82 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
83 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
84 MaxIncludeStackDepth = 0;
87 // Default to discarding comments.
89 KeepMacroComments = false;
90 SuppressIncludeNotFoundError = false;
92 // Macro expansion is enabled.
93 DisableMacroExpansion = false;
94 MacroExpansionInDirectivesOverride = false;
96 InMacroArgPreExpansion = false;
97 NumCachedTokenLexers = 0;
98 PragmasEnabled = true;
102 // We haven't read anything from the external source.
103 ReadMacrosFromExternalSource = false;
105 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
106 // This gets unpoisoned where it is allowed.
107 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
108 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
110 // Initialize the pragma handlers.
111 PragmaHandlers = new PragmaNamespace(StringRef());
112 RegisterBuiltinPragmas();
114 // Initialize builtin macros like __LINE__ and friends.
115 RegisterBuiltinMacros();
117 if(LangOpts.Borland) {
118 Ident__exception_info = getIdentifierInfo("_exception_info");
119 Ident___exception_info = getIdentifierInfo("__exception_info");
120 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
121 Ident__exception_code = getIdentifierInfo("_exception_code");
122 Ident___exception_code = getIdentifierInfo("__exception_code");
123 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
124 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
125 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
126 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
128 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
129 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
130 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
133 if (!DelayInitialization) {
134 assert(Target && "Must provide target information for PP initialization");
139 Preprocessor::~Preprocessor() {
140 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
142 while (!IncludeMacroStack.empty()) {
143 delete IncludeMacroStack.back().TheLexer;
144 delete IncludeMacroStack.back().TheTokenLexer;
145 IncludeMacroStack.pop_back();
148 // Free any macro definitions.
149 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
152 // Free any cached macro expanders.
153 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
154 delete TokenLexerCache[i];
156 // Free any cached MacroArgs.
157 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
158 ArgList = ArgList->deallocate();
160 // Release pragma information.
161 delete PragmaHandlers;
163 // Delete the scratch buffer info.
166 // Delete the header search info, if we own it.
167 if (OwnsHeaderSearch)
173 void Preprocessor::Initialize(const TargetInfo &Target) {
174 assert((!this->Target || this->Target == &Target) &&
175 "Invalid override of target information");
176 this->Target = &Target;
178 // Initialize information about built-ins.
179 BuiltinInfo.InitializeTarget(Target);
180 HeaderInfo.setTarget(Target);
183 void Preprocessor::setPTHManager(PTHManager* pm) {
185 FileMgr.addStatCache(PTH->createStatCache());
188 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
189 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
190 << getSpelling(Tok) << "'";
192 if (!DumpFlags) return;
194 llvm::errs() << "\t";
195 if (Tok.isAtStartOfLine())
196 llvm::errs() << " [StartOfLine]";
197 if (Tok.hasLeadingSpace())
198 llvm::errs() << " [LeadingSpace]";
199 if (Tok.isExpandDisabled())
200 llvm::errs() << " [ExpandDisabled]";
201 if (Tok.needsCleaning()) {
202 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
203 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
207 llvm::errs() << "\tLoc=<";
208 DumpLocation(Tok.getLocation());
212 void Preprocessor::DumpLocation(SourceLocation Loc) const {
216 void Preprocessor::DumpMacro(const MacroInfo &MI) const {
217 llvm::errs() << "MACRO: ";
218 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
219 DumpToken(MI.getReplacementToken(i));
222 llvm::errs() << "\n";
225 void Preprocessor::PrintStats() {
226 llvm::errs() << "\n*** Preprocessor Stats:\n";
227 llvm::errs() << NumDirectives << " directives found:\n";
228 llvm::errs() << " " << NumDefined << " #define.\n";
229 llvm::errs() << " " << NumUndefined << " #undef.\n";
230 llvm::errs() << " #include/#include_next/#import:\n";
231 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
232 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
233 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
234 llvm::errs() << " " << NumElse << " #else/#elif.\n";
235 llvm::errs() << " " << NumEndif << " #endif.\n";
236 llvm::errs() << " " << NumPragma << " #pragma.\n";
237 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
239 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
240 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
241 << NumFastMacroExpanded << " on the fast path.\n";
242 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
243 << " token paste (##) operations performed, "
244 << NumFastTokenPaste << " on the fast path.\n";
246 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
248 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
249 llvm::errs() << "\n Macro Expanded Tokens: "
250 << llvm::capacity_in_bytes(MacroExpandedTokens);
251 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
252 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
253 llvm::errs() << "\n #pragma push_macro Info: "
254 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
255 llvm::errs() << "\n Poison Reasons: "
256 << llvm::capacity_in_bytes(PoisonReasons);
257 llvm::errs() << "\n Comment Handlers: "
258 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
261 Preprocessor::macro_iterator
262 Preprocessor::macro_begin(bool IncludeExternalMacros) const {
263 if (IncludeExternalMacros && ExternalSource &&
264 !ReadMacrosFromExternalSource) {
265 ReadMacrosFromExternalSource = true;
266 ExternalSource->ReadDefinedMacros();
269 return Macros.begin();
272 size_t Preprocessor::getTotalMemory() const {
273 return BP.getTotalMemory()
274 + llvm::capacity_in_bytes(MacroExpandedTokens)
275 + Predefines.capacity() /* Predefines buffer. */
276 + llvm::capacity_in_bytes(Macros)
277 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
278 + llvm::capacity_in_bytes(PoisonReasons)
279 + llvm::capacity_in_bytes(CommentHandlers);
282 Preprocessor::macro_iterator
283 Preprocessor::macro_end(bool IncludeExternalMacros) const {
284 if (IncludeExternalMacros && ExternalSource &&
285 !ReadMacrosFromExternalSource) {
286 ReadMacrosFromExternalSource = true;
287 ExternalSource->ReadDefinedMacros();
293 /// \brief Compares macro tokens with a specified token value sequence.
294 static bool MacroDefinitionEquals(const MacroInfo *MI,
295 llvm::ArrayRef<TokenValue> Tokens) {
296 return Tokens.size() == MI->getNumTokens() &&
297 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
300 StringRef Preprocessor::getLastMacroWithSpelling(
302 ArrayRef<TokenValue> Tokens) const {
303 SourceLocation BestLocation;
304 StringRef BestSpelling;
305 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
307 if (!I->second->isObjectLike())
309 const MacroInfo *MI = I->second->findDefinitionAtLoc(Loc, SourceMgr);
312 if (!MacroDefinitionEquals(MI, Tokens))
314 SourceLocation Location = I->second->getDefinitionLoc();
315 // Choose the macro defined latest.
316 if (BestLocation.isInvalid() ||
317 (Location.isValid() &&
318 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
319 BestLocation = Location;
320 BestSpelling = I->first->getName();
326 void Preprocessor::recomputeCurLexerKind() {
328 CurLexerKind = CLK_Lexer;
329 else if (CurPTHLexer)
330 CurLexerKind = CLK_PTHLexer;
331 else if (CurTokenLexer)
332 CurLexerKind = CLK_TokenLexer;
334 CurLexerKind = CLK_CachingLexer;
337 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
338 unsigned CompleteLine,
339 unsigned CompleteColumn) {
341 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
342 assert(!CodeCompletionFile && "Already set");
344 using llvm::MemoryBuffer;
346 // Load the actual file's contents.
347 bool Invalid = false;
348 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
352 // Find the byte position of the truncation point.
353 const char *Position = Buffer->getBufferStart();
354 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
355 for (; *Position; ++Position) {
356 if (*Position != '\r' && *Position != '\n')
359 // Eat \r\n or \n\r as a single line.
360 if ((Position[1] == '\r' || Position[1] == '\n') &&
361 Position[0] != Position[1])
368 Position += CompleteColumn - 1;
370 // Insert '\0' at the code-completion point.
371 if (Position < Buffer->getBufferEnd()) {
372 CodeCompletionFile = File;
373 CodeCompletionOffset = Position - Buffer->getBufferStart();
375 MemoryBuffer *NewBuffer =
376 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
377 Buffer->getBufferIdentifier());
378 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
379 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
381 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
382 SourceMgr.overrideFileContents(File, NewBuffer);
388 void Preprocessor::CodeCompleteNaturalLanguage() {
390 CodeComplete->CodeCompleteNaturalLanguage();
391 setCodeCompletionReached();
394 /// getSpelling - This method is used to get the spelling of a token into a
395 /// SmallVector. Note that the returned StringRef may not point to the
396 /// supplied buffer if a copy can be avoided.
397 StringRef Preprocessor::getSpelling(const Token &Tok,
398 SmallVectorImpl<char> &Buffer,
399 bool *Invalid) const {
400 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
401 if (Tok.isNot(tok::raw_identifier)) {
402 // Try the fast path.
403 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
404 return II->getName();
407 // Resize the buffer if we need to copy into it.
408 if (Tok.needsCleaning())
409 Buffer.resize(Tok.getLength());
411 const char *Ptr = Buffer.data();
412 unsigned Len = getSpelling(Tok, Ptr, Invalid);
413 return StringRef(Ptr, Len);
416 /// CreateString - Plop the specified string into a scratch buffer and return a
417 /// location for it. If specified, the source location provides a source
418 /// location for the token.
419 void Preprocessor::CreateString(StringRef Str, Token &Tok,
420 SourceLocation ExpansionLocStart,
421 SourceLocation ExpansionLocEnd) {
422 Tok.setLength(Str.size());
425 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
427 if (ExpansionLocStart.isValid())
428 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
429 ExpansionLocEnd, Str.size());
430 Tok.setLocation(Loc);
432 // If this is a raw identifier or a literal token, set the pointer data.
433 if (Tok.is(tok::raw_identifier))
434 Tok.setRawIdentifierData(DestPtr);
435 else if (Tok.isLiteral())
436 Tok.setLiteralData(DestPtr);
439 Module *Preprocessor::getCurrentModule() {
440 if (getLangOpts().CurrentModule.empty())
443 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
446 //===----------------------------------------------------------------------===//
447 // Preprocessor Initialization Methods
448 //===----------------------------------------------------------------------===//
451 /// EnterMainSourceFile - Enter the specified FileID as the main source file,
452 /// which implicitly adds the builtin defines etc.
453 void Preprocessor::EnterMainSourceFile() {
454 // We do not allow the preprocessor to reenter the main file. Doing so will
455 // cause FileID's to accumulate information from both runs (e.g. #line
456 // information) and predefined macros aren't guaranteed to be set properly.
457 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
458 FileID MainFileID = SourceMgr.getMainFileID();
460 // If MainFileID is loaded it means we loaded an AST file, no need to enter
462 if (!SourceMgr.isLoadedFileID(MainFileID)) {
463 // Enter the main file source buffer.
464 EnterSourceFile(MainFileID, 0, SourceLocation());
466 // If we've been asked to skip bytes in the main file (e.g., as part of a
467 // precompiled preamble), do so now.
468 if (SkipMainFilePreamble.first > 0)
469 CurLexer->SkipBytes(SkipMainFilePreamble.first,
470 SkipMainFilePreamble.second);
472 // Tell the header info that the main file was entered. If the file is later
473 // #imported, it won't be re-entered.
474 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
475 HeaderInfo.IncrementIncludeCount(FE);
478 // Preprocess Predefines to populate the initial preprocessor state.
479 llvm::MemoryBuffer *SB =
480 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
481 assert(SB && "Cannot create predefined source buffer");
482 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
483 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
485 // Start parsing the predefines.
486 EnterSourceFile(FID, 0, SourceLocation());
489 void Preprocessor::EndSourceFile() {
490 // Notify the client that we reached the end of the source file.
492 Callbacks->EndOfMainFile();
495 //===----------------------------------------------------------------------===//
496 // Lexer Event Handling.
497 //===----------------------------------------------------------------------===//
499 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
500 /// identifier information for the token and install it into the token,
501 /// updating the token kind accordingly.
502 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
503 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
505 // Look up this token, see if it is a macro, or if it is a language keyword.
507 if (!Identifier.needsCleaning()) {
508 // No cleaning needed, just use the characters from the lexed buffer.
509 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
510 Identifier.getLength()));
512 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
513 SmallString<64> IdentifierBuffer;
514 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
515 II = getIdentifierInfo(CleanedStr);
518 // Update the token info (identifier info and appropriate token kind).
519 Identifier.setIdentifierInfo(II);
520 Identifier.setKind(II->getTokenID());
525 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
526 PoisonReasons[II] = DiagID;
529 void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
530 assert(Ident__exception_code && Ident__exception_info);
531 assert(Ident___exception_code && Ident___exception_info);
532 Ident__exception_code->setIsPoisoned(Poison);
533 Ident___exception_code->setIsPoisoned(Poison);
534 Ident_GetExceptionCode->setIsPoisoned(Poison);
535 Ident__exception_info->setIsPoisoned(Poison);
536 Ident___exception_info->setIsPoisoned(Poison);
537 Ident_GetExceptionInfo->setIsPoisoned(Poison);
538 Ident__abnormal_termination->setIsPoisoned(Poison);
539 Ident___abnormal_termination->setIsPoisoned(Poison);
540 Ident_AbnormalTermination->setIsPoisoned(Poison);
543 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
544 assert(Identifier.getIdentifierInfo() &&
545 "Can't handle identifiers without identifier info!");
546 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
547 PoisonReasons.find(Identifier.getIdentifierInfo());
548 if(it == PoisonReasons.end())
549 Diag(Identifier, diag::err_pp_used_poisoned_id);
551 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
554 /// HandleIdentifier - This callback is invoked when the lexer reads an
555 /// identifier. This callback looks up the identifier in the map and/or
556 /// potentially macro expands it or turns it into a named token (like 'for').
558 /// Note that callers of this method are guarded by checking the
559 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
560 /// IdentifierInfo methods that compute these properties will need to change to
562 void Preprocessor::HandleIdentifier(Token &Identifier) {
563 assert(Identifier.getIdentifierInfo() &&
564 "Can't handle identifiers without identifier info!");
566 IdentifierInfo &II = *Identifier.getIdentifierInfo();
568 // If the information about this identifier is out of date, update it from
569 // the external source.
570 // We have to treat __VA_ARGS__ in a special way, since it gets
571 // serialized with isPoisoned = true, but our preprocessor may have
572 // unpoisoned it if we're defining a C99 macro.
573 if (II.isOutOfDate()) {
574 bool CurrentIsPoisoned = false;
575 if (&II == Ident__VA_ARGS__)
576 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
578 ExternalSource->updateOutOfDateIdentifier(II);
579 Identifier.setKind(II.getTokenID());
581 if (&II == Ident__VA_ARGS__)
582 II.setIsPoisoned(CurrentIsPoisoned);
585 // If this identifier was poisoned, and if it was not produced from a macro
586 // expansion, emit an error.
587 if (II.isPoisoned() && CurPPLexer) {
588 HandlePoisonedIdentifier(Identifier);
591 // If this is a macro to be expanded, do it.
592 if (MacroInfo *MI = getMacroInfo(&II)) {
593 if (!DisableMacroExpansion) {
594 if (Identifier.isExpandDisabled()) {
595 Diag(Identifier, diag::pp_disabled_macro_expansion);
596 } else if (MI->isEnabled()) {
597 if (!HandleMacroExpandedIdentifier(Identifier, MI))
600 // C99 6.10.3.4p2 says that a disabled macro may never again be
601 // expanded, even if it's in a context where it could be expanded in the
603 Identifier.setFlag(Token::DisableExpand);
604 Diag(Identifier, diag::pp_disabled_macro_expansion);
609 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
610 // we're not considering macro expansion, since this identifier might be the
612 // FIXME: This warning is disabled in cases where it shouldn't be, like
613 // "#define constexpr constexpr", "int constexpr;"
614 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
615 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
616 // Don't diagnose this keyword again in this translation unit.
617 II.setIsCXX11CompatKeyword(false);
620 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
621 // then we act as if it is the actual operator and not the textual
622 // representation of it.
623 if (II.isCPlusPlusOperatorKeyword())
624 Identifier.setIdentifierInfo(0);
626 // If this is an extension token, diagnose its use.
627 // We avoid diagnosing tokens that originate from macro definitions.
628 // FIXME: This warning is disabled in cases where it shouldn't be,
629 // like "#define TY typeof", "TY(1) x".
630 if (II.isExtensionToken() && !DisableMacroExpansion)
631 Diag(Identifier, diag::ext_token_used);
633 // If this is the '__experimental_modules_import' contextual keyword, note
634 // that the next token indicates a module name.
636 // Note that we do not treat '__experimental_modules_import' as a contextual
637 // keyword when we're in a caching lexer, because caching lexers only get
638 // used in contexts where import declarations are disallowed.
639 if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion &&
640 getLangOpts().Modules && CurLexerKind != CLK_CachingLexer) {
641 ModuleImportLoc = Identifier.getLocation();
642 ModuleImportPath.clear();
643 ModuleImportExpectsIdentifier = true;
644 CurLexerKind = CLK_LexAfterModuleImport;
648 /// \brief Lex a token following the 'import' contextual keyword.
650 void Preprocessor::LexAfterModuleImport(Token &Result) {
651 // Figure out what kind of lexer we actually have.
652 recomputeCurLexerKind();
654 // Lex the next token.
657 // The token sequence
659 // import identifier (. identifier)*
661 // indicates a module import directive. We already saw the 'import'
662 // contextual keyword, so now we're looking for the identifiers.
663 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
664 // We expected to see an identifier here, and we did; continue handling
666 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
667 Result.getLocation()));
668 ModuleImportExpectsIdentifier = false;
669 CurLexerKind = CLK_LexAfterModuleImport;
673 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
674 // see the next identifier.
675 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
676 ModuleImportExpectsIdentifier = true;
677 CurLexerKind = CLK_LexAfterModuleImport;
681 // If we have a non-empty module path, load the named module.
682 if (!ModuleImportPath.empty()) {
683 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
685 Module::MacrosVisible,
686 /*IsIncludeDirective=*/false);
688 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
692 void Preprocessor::addCommentHandler(CommentHandler *Handler) {
693 assert(Handler && "NULL comment handler");
694 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
695 CommentHandlers.end() && "Comment handler already registered");
696 CommentHandlers.push_back(Handler);
699 void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
700 std::vector<CommentHandler *>::iterator Pos
701 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
702 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
703 CommentHandlers.erase(Pos);
706 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
707 bool AnyPendingTokens = false;
708 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
709 HEnd = CommentHandlers.end();
711 if ((*H)->HandleComment(*this, Comment))
712 AnyPendingTokens = true;
714 if (!AnyPendingTokens || getCommentRetentionState())
720 ModuleLoader::~ModuleLoader() { }
722 CommentHandler::~CommentHandler() { }
724 CodeCompletionHandler::~CodeCompletionHandler() { }
726 void Preprocessor::createPreprocessingRecord(bool RecordConditionalDirectives) {
730 Record = new PreprocessingRecord(getSourceManager(),
731 RecordConditionalDirectives);
732 addPPCallbacks(Record);