Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1 | //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===// |
| 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 top level handling of macro expasion for the |
| 11 | // preprocessor. |
| 12 | // |
| 13 | //===----------------------------------------------------------------------===// |
| 14 | |
| 15 | #include "clang/Lex/Preprocessor.h" |
| 16 | #include "MacroArgs.h" |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 17 | #include "clang/Basic/FileManager.h" |
Chandler Carruth | 3a02247 | 2012-12-04 09:13:33 +0000 | [diff] [blame] | 18 | #include "clang/Basic/SourceManager.h" |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 19 | #include "clang/Basic/TargetInfo.h" |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 20 | #include "clang/Lex/CodeCompletionHandler.h" |
| 21 | #include "clang/Lex/ExternalPreprocessorSource.h" |
Chandler Carruth | 3a02247 | 2012-12-04 09:13:33 +0000 | [diff] [blame] | 22 | #include "clang/Lex/LexDiagnostic.h" |
| 23 | #include "clang/Lex/MacroInfo.h" |
| 24 | #include "llvm/ADT/STLExtras.h" |
Andy Gibbs | 58905d2 | 2012-11-17 19:15:38 +0000 | [diff] [blame] | 25 | #include "llvm/ADT/SmallString.h" |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 26 | #include "llvm/ADT/StringSwitch.h" |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 27 | #include "llvm/Config/llvm-config.h" |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 28 | #include "llvm/Support/ErrorHandling.h" |
Dmitri Gribenko | ae07f72 | 2012-09-24 20:56:28 +0000 | [diff] [blame] | 29 | #include "llvm/Support/Format.h" |
Chandler Carruth | 3a02247 | 2012-12-04 09:13:33 +0000 | [diff] [blame] | 30 | #include "llvm/Support/raw_ostream.h" |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 31 | #include <cstdio> |
| 32 | #include <ctime> |
| 33 | using namespace clang; |
| 34 | |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 35 | MacroDirective * |
| 36 | Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const { |
Alexander Kornienko | 1d26c02 | 2012-09-25 17:18:14 +0000 | [diff] [blame] | 37 | assert(II->hadMacroDefinition() && "Identifier has not been not a macro!"); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 38 | |
| 39 | macro_iterator Pos = Macros.find(II); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 40 | assert(Pos != Macros.end() && "Identifier macro info is missing!"); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 41 | return Pos->second; |
| 42 | } |
| 43 | |
| 44 | /// setMacroInfo - Specify a macro for this identifier. |
| 45 | /// |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 46 | void Preprocessor::setMacroDirective(IdentifierInfo *II, MacroInfo *MI, |
| 47 | SourceLocation Loc, bool isImported) { |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 48 | assert(MI && "MacroInfo should be non-zero!"); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 49 | |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 50 | MacroDirective *MD = AllocateMacroDirective(MI, Loc, isImported); |
| 51 | MacroDirective *&StoredMD = Macros[II]; |
| 52 | MD->setPrevious(StoredMD); |
| 53 | StoredMD = MD; |
| 54 | II->setHasMacroDefinition(true); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 55 | if (II->isFromAST()) |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 56 | II->setChangedSinceDeserialization(); |
| 57 | } |
| 58 | |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 59 | void Preprocessor::addLoadedMacroInfo(IdentifierInfo *II, MacroDirective *MD, |
| 60 | MacroDirective *Hint) { |
| 61 | assert(MD && "Missing macro?"); |
| 62 | assert(MD->isImported() && "Macro is not from an AST?"); |
| 63 | assert(!MD->getPrevious() && "Macro already in chain?"); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 64 | |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 65 | MacroDirective *&StoredMD = Macros[II]; |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 66 | |
| 67 | // Easy case: this is the first macro definition for this macro. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 68 | if (!StoredMD) { |
| 69 | StoredMD = MD; |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 70 | |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 71 | if (MD->isDefined()) |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 72 | II->setHasMacroDefinition(true); |
| 73 | return; |
| 74 | } |
| 75 | |
| 76 | // If this macro is a definition and this identifier has been neither |
| 77 | // defined nor undef'd in the current translation unit, add this macro |
| 78 | // to the end of the chain of definitions. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 79 | if (MD->isDefined() && StoredMD->isImported()) { |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 80 | // Simple case: if this is the first actual definition, just put it at |
| 81 | // th beginning. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 82 | if (!StoredMD->isDefined()) { |
| 83 | MD->setPrevious(StoredMD); |
| 84 | StoredMD = MD; |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 85 | |
| 86 | II->setHasMacroDefinition(true); |
| 87 | return; |
| 88 | } |
| 89 | |
| 90 | // Find the end of the definition chain. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 91 | MacroDirective *Prev; |
| 92 | MacroDirective *PrevPrev = StoredMD; |
| 93 | bool Ambiguous = StoredMD->isAmbiguous(); |
Douglas Gregor | 5968b1b | 2012-10-11 21:07:39 +0000 | [diff] [blame] | 94 | bool MatchedOther = false; |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 95 | do { |
Douglas Gregor | cfa46a8 | 2012-10-12 00:16:50 +0000 | [diff] [blame] | 96 | Prev = PrevPrev; |
| 97 | |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 98 | // If the macros are not identical, we have an ambiguity. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 99 | if (!Prev->getInfo()->isIdenticalTo(*MD->getInfo(), *this)) { |
Douglas Gregor | 5968b1b | 2012-10-11 21:07:39 +0000 | [diff] [blame] | 100 | if (!Ambiguous) { |
| 101 | Ambiguous = true; |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 102 | StoredMD->setAmbiguous(true); |
Douglas Gregor | 5968b1b | 2012-10-11 21:07:39 +0000 | [diff] [blame] | 103 | } |
| 104 | } else { |
| 105 | MatchedOther = true; |
| 106 | } |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 107 | } while ((PrevPrev = Prev->getPrevious()) && |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 108 | PrevPrev->isDefined()); |
| 109 | |
Douglas Gregor | 5968b1b | 2012-10-11 21:07:39 +0000 | [diff] [blame] | 110 | // If there are ambiguous definitions, and we didn't match any other |
| 111 | // definition, then mark us as ambiguous. |
| 112 | if (Ambiguous && !MatchedOther) |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 113 | MD->setAmbiguous(true); |
Douglas Gregor | 0634737 | 2012-10-11 00:48:48 +0000 | [diff] [blame] | 114 | |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 115 | // Wire this macro information into the chain. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 116 | MD->setPrevious(Prev->getPrevious()); |
| 117 | Prev->setPrevious(MD); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 118 | return; |
| 119 | } |
| 120 | |
| 121 | // The macro is not a definition; put it at the end of the list. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 122 | MacroDirective *Prev = Hint? Hint : StoredMD; |
| 123 | while (Prev->getPrevious()) |
| 124 | Prev = Prev->getPrevious(); |
| 125 | Prev->setPrevious(MD); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 126 | } |
| 127 | |
| 128 | void Preprocessor::makeLoadedMacroInfoVisible(IdentifierInfo *II, |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 129 | MacroDirective *MD) { |
| 130 | assert(MD->isImported() && "Macro must be from the AST"); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 131 | |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 132 | MacroDirective *&StoredMD = Macros[II]; |
| 133 | if (StoredMD == MD) { |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 134 | // Easy case: this is the first macro anyway. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 135 | II->setHasMacroDefinition(MD->isDefined()); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 136 | return; |
| 137 | } |
| 138 | |
| 139 | // Go find the macro and pull it out of the list. |
Douglas Gregor | cfa46a8 | 2012-10-12 00:16:50 +0000 | [diff] [blame] | 140 | // FIXME: Yes, this is O(N), and making a pile of macros visible or hidden |
| 141 | // would be quadratic, but it's extremely rare. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 142 | MacroDirective *Prev = StoredMD; |
| 143 | while (Prev->getPrevious() != MD) |
| 144 | Prev = Prev->getPrevious(); |
| 145 | Prev->setPrevious(MD->getPrevious()); |
| 146 | MD->setPrevious(0); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 147 | |
| 148 | // Add the macro back to the list. |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 149 | addLoadedMacroInfo(II, MD); |
Douglas Gregor | cfa46a8 | 2012-10-12 00:16:50 +0000 | [diff] [blame] | 150 | |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 151 | II->setHasMacroDefinition(StoredMD->isDefined()); |
Douglas Gregor | cfa46a8 | 2012-10-12 00:16:50 +0000 | [diff] [blame] | 152 | if (II->isFromAST()) |
| 153 | II->setChangedSinceDeserialization(); |
Douglas Gregor | 5a4649b | 2012-10-11 00:46:49 +0000 | [diff] [blame] | 154 | } |
| 155 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 156 | /// \brief Undefine a macro for this identifier. |
| 157 | void Preprocessor::clearMacroInfo(IdentifierInfo *II) { |
| 158 | assert(II->hasMacroDefinition() && "Macro is not defined!"); |
| 159 | assert(Macros[II]->getUndefLoc().isValid() && "Macro is still defined!"); |
| 160 | II->setHasMacroDefinition(false); |
| 161 | if (II->isFromAST()) |
| 162 | II->setChangedSinceDeserialization(); |
| 163 | } |
| 164 | |
| 165 | /// RegisterBuiltinMacro - Register the specified identifier in the identifier |
| 166 | /// table and mark it as a builtin macro to be expanded. |
| 167 | static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ |
| 168 | // Get the identifier. |
| 169 | IdentifierInfo *Id = PP.getIdentifierInfo(Name); |
| 170 | |
| 171 | // Mark it as being a macro that is builtin. |
| 172 | MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); |
| 173 | MI->setIsBuiltinMacro(); |
Argyrios Kyrtzidis | 09c9e81 | 2013-02-20 00:54:57 +0000 | [diff] [blame] | 174 | PP.setMacroDirective(Id, MI); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 175 | return Id; |
| 176 | } |
| 177 | |
| 178 | |
| 179 | /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the |
| 180 | /// identifier table. |
| 181 | void Preprocessor::RegisterBuiltinMacros() { |
| 182 | Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); |
| 183 | Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); |
| 184 | Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); |
| 185 | Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); |
| 186 | Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); |
| 187 | Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); |
| 188 | |
| 189 | // GCC Extensions. |
| 190 | Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); |
| 191 | Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); |
| 192 | Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); |
| 193 | |
| 194 | // Clang Extensions. |
| 195 | Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); |
| 196 | Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension"); |
| 197 | Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); |
| 198 | Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute"); |
| 199 | Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); |
| 200 | Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); |
| 201 | Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning"); |
| 202 | |
Douglas Gregor | c83de30 | 2012-09-25 15:44:52 +0000 | [diff] [blame] | 203 | // Modules. |
| 204 | if (LangOpts.Modules) { |
| 205 | Ident__building_module = RegisterBuiltinMacro(*this, "__building_module"); |
| 206 | |
| 207 | // __MODULE__ |
| 208 | if (!LangOpts.CurrentModule.empty()) |
| 209 | Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__"); |
| 210 | else |
| 211 | Ident__MODULE__ = 0; |
| 212 | } else { |
| 213 | Ident__building_module = 0; |
| 214 | Ident__MODULE__ = 0; |
| 215 | } |
| 216 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 217 | // Microsoft Extensions. |
| 218 | if (LangOpts.MicrosoftExt) |
| 219 | Ident__pragma = RegisterBuiltinMacro(*this, "__pragma"); |
| 220 | else |
| 221 | Ident__pragma = 0; |
| 222 | } |
| 223 | |
| 224 | /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token |
| 225 | /// in its expansion, currently expands to that token literally. |
| 226 | static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, |
| 227 | const IdentifierInfo *MacroIdent, |
| 228 | Preprocessor &PP) { |
| 229 | IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); |
| 230 | |
| 231 | // If the token isn't an identifier, it's always literally expanded. |
| 232 | if (II == 0) return true; |
| 233 | |
| 234 | // If the information about this identifier is out of date, update it from |
| 235 | // the external source. |
| 236 | if (II->isOutOfDate()) |
| 237 | PP.getExternalSource()->updateOutOfDateIdentifier(*II); |
| 238 | |
| 239 | // If the identifier is a macro, and if that macro is enabled, it may be |
| 240 | // expanded so it's not a trivial expansion. |
| 241 | if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() && |
| 242 | // Fast expanding "#define X X" is ok, because X would be disabled. |
| 243 | II != MacroIdent) |
| 244 | return false; |
| 245 | |
| 246 | // If this is an object-like macro invocation, it is safe to trivially expand |
| 247 | // it. |
| 248 | if (MI->isObjectLike()) return true; |
| 249 | |
| 250 | // If this is a function-like macro invocation, it's safe to trivially expand |
| 251 | // as long as the identifier is not a macro argument. |
| 252 | for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); |
| 253 | I != E; ++I) |
| 254 | if (*I == II) |
| 255 | return false; // Identifier is a macro argument. |
| 256 | |
| 257 | return true; |
| 258 | } |
| 259 | |
| 260 | |
| 261 | /// isNextPPTokenLParen - Determine whether the next preprocessor token to be |
| 262 | /// lexed is a '('. If so, consume the token and return true, if not, this |
| 263 | /// method should have no observable side-effect on the lexed tokens. |
| 264 | bool Preprocessor::isNextPPTokenLParen() { |
| 265 | // Do some quick tests for rejection cases. |
| 266 | unsigned Val; |
| 267 | if (CurLexer) |
| 268 | Val = CurLexer->isNextPPTokenLParen(); |
| 269 | else if (CurPTHLexer) |
| 270 | Val = CurPTHLexer->isNextPPTokenLParen(); |
| 271 | else |
| 272 | Val = CurTokenLexer->isNextTokenLParen(); |
| 273 | |
| 274 | if (Val == 2) { |
| 275 | // We have run off the end. If it's a source file we don't |
| 276 | // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the |
| 277 | // macro stack. |
| 278 | if (CurPPLexer) |
| 279 | return false; |
| 280 | for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { |
| 281 | IncludeStackInfo &Entry = IncludeMacroStack[i-1]; |
| 282 | if (Entry.TheLexer) |
| 283 | Val = Entry.TheLexer->isNextPPTokenLParen(); |
| 284 | else if (Entry.ThePTHLexer) |
| 285 | Val = Entry.ThePTHLexer->isNextPPTokenLParen(); |
| 286 | else |
| 287 | Val = Entry.TheTokenLexer->isNextTokenLParen(); |
| 288 | |
| 289 | if (Val != 2) |
| 290 | break; |
| 291 | |
| 292 | // Ran off the end of a source file? |
| 293 | if (Entry.ThePPLexer) |
| 294 | return false; |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // Okay, if we know that the token is a '(', lex it and return. Otherwise we |
| 299 | // have found something that isn't a '(' or we found the end of the |
| 300 | // translation unit. In either case, return false. |
| 301 | return Val == 1; |
| 302 | } |
| 303 | |
| 304 | /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be |
| 305 | /// expanded as a macro, handle it and return the next token as 'Identifier'. |
| 306 | bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, |
| 307 | MacroInfo *MI) { |
| 308 | // If this is a macro expansion in the "#if !defined(x)" line for the file, |
| 309 | // then the macro could expand to different things in other contexts, we need |
| 310 | // to disable the optimization in this case. |
| 311 | if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); |
| 312 | |
| 313 | // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. |
| 314 | if (MI->isBuiltinMacro()) { |
| 315 | if (Callbacks) Callbacks->MacroExpands(Identifier, MI, |
| 316 | Identifier.getLocation()); |
| 317 | ExpandBuiltinMacro(Identifier); |
| 318 | return false; |
| 319 | } |
| 320 | |
| 321 | /// Args - If this is a function-like macro expansion, this contains, |
| 322 | /// for each macro argument, the list of tokens that were provided to the |
| 323 | /// invocation. |
| 324 | MacroArgs *Args = 0; |
| 325 | |
| 326 | // Remember where the end of the expansion occurred. For an object-like |
| 327 | // macro, this is the identifier. For a function-like macro, this is the ')'. |
| 328 | SourceLocation ExpansionEnd = Identifier.getLocation(); |
| 329 | |
| 330 | // If this is a function-like macro, read the arguments. |
| 331 | if (MI->isFunctionLike()) { |
| 332 | // C99 6.10.3p10: If the preprocessing token immediately after the macro |
| 333 | // name isn't a '(', this macro should not be expanded. |
| 334 | if (!isNextPPTokenLParen()) |
| 335 | return true; |
| 336 | |
| 337 | // Remember that we are now parsing the arguments to a macro invocation. |
| 338 | // Preprocessor directives used inside macro arguments are not portable, and |
| 339 | // this enables the warning. |
| 340 | InMacroArgs = true; |
| 341 | Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd); |
| 342 | |
| 343 | // Finished parsing args. |
| 344 | InMacroArgs = false; |
| 345 | |
| 346 | // If there was an error parsing the arguments, bail out. |
| 347 | if (Args == 0) return false; |
| 348 | |
| 349 | ++NumFnMacroExpanded; |
| 350 | } else { |
| 351 | ++NumMacroExpanded; |
| 352 | } |
| 353 | |
| 354 | // Notice that this macro has been used. |
| 355 | markMacroAsUsed(MI); |
| 356 | |
| 357 | // Remember where the token is expanded. |
| 358 | SourceLocation ExpandLoc = Identifier.getLocation(); |
| 359 | SourceRange ExpansionRange(ExpandLoc, ExpansionEnd); |
| 360 | |
| 361 | if (Callbacks) { |
| 362 | if (InMacroArgs) { |
| 363 | // We can have macro expansion inside a conditional directive while |
| 364 | // reading the function macro arguments. To ensure, in that case, that |
| 365 | // MacroExpands callbacks still happen in source order, queue this |
| 366 | // callback to have it happen after the function macro callback. |
| 367 | DelayedMacroExpandsCallbacks.push_back( |
| 368 | MacroExpandsInfo(Identifier, MI, ExpansionRange)); |
| 369 | } else { |
| 370 | Callbacks->MacroExpands(Identifier, MI, ExpansionRange); |
| 371 | if (!DelayedMacroExpandsCallbacks.empty()) { |
| 372 | for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) { |
| 373 | MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i]; |
| 374 | Callbacks->MacroExpands(Info.Tok, Info.MI, Info.Range); |
| 375 | } |
| 376 | DelayedMacroExpandsCallbacks.clear(); |
| 377 | } |
| 378 | } |
| 379 | } |
Douglas Gregor | 5968b1b | 2012-10-11 21:07:39 +0000 | [diff] [blame] | 380 | |
Argyrios Kyrtzidis | 1ffbc3a | 2013-01-23 18:21:56 +0000 | [diff] [blame] | 381 | // FIXME: Temporarily disable this warning that is currently bogus with a PCH |
| 382 | // that redefined a macro without undef'ing it first (test/PCH/macro-redef.c). |
| 383 | #if 0 |
Douglas Gregor | 5968b1b | 2012-10-11 21:07:39 +0000 | [diff] [blame] | 384 | // If the macro definition is ambiguous, complain. |
| 385 | if (MI->isAmbiguous()) { |
| 386 | Diag(Identifier, diag::warn_pp_ambiguous_macro) |
| 387 | << Identifier.getIdentifierInfo(); |
| 388 | Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen) |
| 389 | << Identifier.getIdentifierInfo(); |
| 390 | for (MacroInfo *PrevMI = MI->getPreviousDefinition(); |
| 391 | PrevMI && PrevMI->isDefined(); |
| 392 | PrevMI = PrevMI->getPreviousDefinition()) { |
| 393 | if (PrevMI->isAmbiguous()) { |
| 394 | Diag(PrevMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other) |
| 395 | << Identifier.getIdentifierInfo(); |
| 396 | } |
| 397 | } |
| 398 | } |
Argyrios Kyrtzidis | 1ffbc3a | 2013-01-23 18:21:56 +0000 | [diff] [blame] | 399 | #endif |
Douglas Gregor | 5968b1b | 2012-10-11 21:07:39 +0000 | [diff] [blame] | 400 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 401 | // If we started lexing a macro, enter the macro expansion body. |
| 402 | |
| 403 | // If this macro expands to no tokens, don't bother to push it onto the |
| 404 | // expansion stack, only to take it right back off. |
| 405 | if (MI->getNumTokens() == 0) { |
| 406 | // No need for arg info. |
| 407 | if (Args) Args->destroy(*this); |
| 408 | |
| 409 | // Ignore this macro use, just return the next token in the current |
| 410 | // buffer. |
| 411 | bool HadLeadingSpace = Identifier.hasLeadingSpace(); |
| 412 | bool IsAtStartOfLine = Identifier.isAtStartOfLine(); |
| 413 | |
| 414 | Lex(Identifier); |
| 415 | |
| 416 | // If the identifier isn't on some OTHER line, inherit the leading |
| 417 | // whitespace/first-on-a-line property of this token. This handles |
| 418 | // stuff like "! XX," -> "! ," and " XX," -> " ,", when XX is |
| 419 | // empty. |
| 420 | if (!Identifier.isAtStartOfLine()) { |
| 421 | if (IsAtStartOfLine) Identifier.setFlag(Token::StartOfLine); |
| 422 | if (HadLeadingSpace) Identifier.setFlag(Token::LeadingSpace); |
| 423 | } |
| 424 | Identifier.setFlag(Token::LeadingEmptyMacro); |
| 425 | ++NumFastMacroExpanded; |
| 426 | return false; |
| 427 | |
| 428 | } else if (MI->getNumTokens() == 1 && |
| 429 | isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), |
| 430 | *this)) { |
| 431 | // Otherwise, if this macro expands into a single trivially-expanded |
| 432 | // token: expand it now. This handles common cases like |
| 433 | // "#define VAL 42". |
| 434 | |
| 435 | // No need for arg info. |
| 436 | if (Args) Args->destroy(*this); |
| 437 | |
| 438 | // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro |
| 439 | // identifier to the expanded token. |
| 440 | bool isAtStartOfLine = Identifier.isAtStartOfLine(); |
| 441 | bool hasLeadingSpace = Identifier.hasLeadingSpace(); |
| 442 | |
| 443 | // Replace the result token. |
| 444 | Identifier = MI->getReplacementToken(0); |
| 445 | |
| 446 | // Restore the StartOfLine/LeadingSpace markers. |
| 447 | Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); |
| 448 | Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); |
| 449 | |
| 450 | // Update the tokens location to include both its expansion and physical |
| 451 | // locations. |
| 452 | SourceLocation Loc = |
| 453 | SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc, |
| 454 | ExpansionEnd,Identifier.getLength()); |
| 455 | Identifier.setLocation(Loc); |
| 456 | |
| 457 | // If this is a disabled macro or #define X X, we must mark the result as |
| 458 | // unexpandable. |
| 459 | if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) { |
| 460 | if (MacroInfo *NewMI = getMacroInfo(NewII)) |
| 461 | if (!NewMI->isEnabled() || NewMI == MI) { |
| 462 | Identifier.setFlag(Token::DisableExpand); |
Douglas Gregor | 1a347f7 | 2013-01-30 23:10:17 +0000 | [diff] [blame] | 463 | // Don't warn for "#define X X" like "#define bool bool" from |
| 464 | // stdbool.h. |
| 465 | if (NewMI != MI || MI->isFunctionLike()) |
| 466 | Diag(Identifier, diag::pp_disabled_macro_expansion); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 467 | } |
| 468 | } |
| 469 | |
| 470 | // Since this is not an identifier token, it can't be macro expanded, so |
| 471 | // we're done. |
| 472 | ++NumFastMacroExpanded; |
| 473 | return false; |
| 474 | } |
| 475 | |
| 476 | // Start expanding the macro. |
| 477 | EnterMacro(Identifier, ExpansionEnd, MI, Args); |
| 478 | |
| 479 | // Now that the macro is at the top of the include stack, ask the |
| 480 | // preprocessor to read the next token from it. |
| 481 | Lex(Identifier); |
| 482 | return false; |
| 483 | } |
| 484 | |
| 485 | /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next |
| 486 | /// token is the '(' of the macro, this method is invoked to read all of the |
| 487 | /// actual arguments specified for the macro invocation. This returns null on |
| 488 | /// error. |
| 489 | MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, |
| 490 | MacroInfo *MI, |
| 491 | SourceLocation &MacroEnd) { |
| 492 | // The number of fixed arguments to parse. |
| 493 | unsigned NumFixedArgsLeft = MI->getNumArgs(); |
| 494 | bool isVariadic = MI->isVariadic(); |
| 495 | |
| 496 | // Outer loop, while there are more arguments, keep reading them. |
| 497 | Token Tok; |
| 498 | |
| 499 | // Read arguments as unexpanded tokens. This avoids issues, e.g., where |
| 500 | // an argument value in a macro could expand to ',' or '(' or ')'. |
| 501 | LexUnexpandedToken(Tok); |
| 502 | assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); |
| 503 | |
| 504 | // ArgTokens - Build up a list of tokens that make up each argument. Each |
| 505 | // argument is separated by an EOF token. Use a SmallVector so we can avoid |
| 506 | // heap allocations in the common case. |
| 507 | SmallVector<Token, 64> ArgTokens; |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 508 | bool ContainsCodeCompletionTok = false; |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 509 | |
| 510 | unsigned NumActuals = 0; |
| 511 | while (Tok.isNot(tok::r_paren)) { |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 512 | if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod))) |
| 513 | break; |
| 514 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 515 | assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) && |
| 516 | "only expect argument separators here"); |
| 517 | |
| 518 | unsigned ArgTokenStart = ArgTokens.size(); |
| 519 | SourceLocation ArgStartLoc = Tok.getLocation(); |
| 520 | |
| 521 | // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note |
| 522 | // that we already consumed the first one. |
| 523 | unsigned NumParens = 0; |
| 524 | |
| 525 | while (1) { |
| 526 | // Read arguments as unexpanded tokens. This avoids issues, e.g., where |
| 527 | // an argument value in a macro could expand to ',' or '(' or ')'. |
| 528 | LexUnexpandedToken(Tok); |
| 529 | |
| 530 | if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n" |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 531 | if (!ContainsCodeCompletionTok) { |
| 532 | Diag(MacroName, diag::err_unterm_macro_invoc); |
| 533 | Diag(MI->getDefinitionLoc(), diag::note_macro_here) |
| 534 | << MacroName.getIdentifierInfo(); |
| 535 | // Do not lose the EOF/EOD. Return it to the client. |
| 536 | MacroName = Tok; |
| 537 | return 0; |
| 538 | } else { |
Argyrios Kyrtzidis | 9fd1571 | 2012-12-22 04:48:10 +0000 | [diff] [blame] | 539 | // Do not lose the EOF/EOD. |
| 540 | Token *Toks = new Token[1]; |
| 541 | Toks[0] = Tok; |
| 542 | EnterTokenStream(Toks, 1, true, true); |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 543 | break; |
| 544 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 545 | } else if (Tok.is(tok::r_paren)) { |
| 546 | // If we found the ) token, the macro arg list is done. |
| 547 | if (NumParens-- == 0) { |
| 548 | MacroEnd = Tok.getLocation(); |
| 549 | break; |
| 550 | } |
| 551 | } else if (Tok.is(tok::l_paren)) { |
| 552 | ++NumParens; |
Nico Weber | dd9602f | 2012-09-26 08:19:01 +0000 | [diff] [blame] | 553 | } else if (Tok.is(tok::comma) && NumParens == 0) { |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 554 | // Comma ends this argument if there are more fixed arguments expected. |
| 555 | // However, if this is a variadic macro, and this is part of the |
| 556 | // variadic part, then the comma is just an argument token. |
| 557 | if (!isVariadic) break; |
| 558 | if (NumFixedArgsLeft > 1) |
| 559 | break; |
| 560 | } else if (Tok.is(tok::comment) && !KeepMacroComments) { |
| 561 | // If this is a comment token in the argument list and we're just in |
| 562 | // -C mode (not -CC mode), discard the comment. |
| 563 | continue; |
| 564 | } else if (Tok.getIdentifierInfo() != 0) { |
| 565 | // Reading macro arguments can cause macros that we are currently |
| 566 | // expanding from to be popped off the expansion stack. Doing so causes |
| 567 | // them to be reenabled for expansion. Here we record whether any |
| 568 | // identifiers we lex as macro arguments correspond to disabled macros. |
| 569 | // If so, we mark the token as noexpand. This is a subtle aspect of |
| 570 | // C99 6.10.3.4p2. |
| 571 | if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) |
| 572 | if (!MI->isEnabled()) |
| 573 | Tok.setFlag(Token::DisableExpand); |
| 574 | } else if (Tok.is(tok::code_completion)) { |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 575 | ContainsCodeCompletionTok = true; |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 576 | if (CodeComplete) |
| 577 | CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(), |
| 578 | MI, NumActuals); |
| 579 | // Don't mark that we reached the code-completion point because the |
| 580 | // parser is going to handle the token and there will be another |
| 581 | // code-completion callback. |
| 582 | } |
| 583 | |
| 584 | ArgTokens.push_back(Tok); |
| 585 | } |
| 586 | |
| 587 | // If this was an empty argument list foo(), don't add this as an empty |
| 588 | // argument. |
| 589 | if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) |
| 590 | break; |
| 591 | |
| 592 | // If this is not a variadic macro, and too many args were specified, emit |
| 593 | // an error. |
| 594 | if (!isVariadic && NumFixedArgsLeft == 0) { |
| 595 | if (ArgTokens.size() != ArgTokenStart) |
| 596 | ArgStartLoc = ArgTokens[ArgTokenStart].getLocation(); |
| 597 | |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 598 | if (!ContainsCodeCompletionTok) { |
| 599 | // Emit the diagnostic at the macro name in case there is a missing ). |
| 600 | // Emitting it at the , could be far away from the macro name. |
| 601 | Diag(ArgStartLoc, diag::err_too_many_args_in_macro_invoc); |
| 602 | Diag(MI->getDefinitionLoc(), diag::note_macro_here) |
| 603 | << MacroName.getIdentifierInfo(); |
| 604 | return 0; |
| 605 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 606 | } |
| 607 | |
| 608 | // Empty arguments are standard in C99 and C++0x, and are supported as an extension in |
| 609 | // other modes. |
| 610 | if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99) |
Richard Smith | 2bf7fdb | 2013-01-02 11:42:31 +0000 | [diff] [blame] | 611 | Diag(Tok, LangOpts.CPlusPlus11 ? |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 612 | diag::warn_cxx98_compat_empty_fnmacro_arg : |
| 613 | diag::ext_empty_fnmacro_arg); |
| 614 | |
| 615 | // Add a marker EOF token to the end of the token list for this argument. |
| 616 | Token EOFTok; |
| 617 | EOFTok.startToken(); |
| 618 | EOFTok.setKind(tok::eof); |
| 619 | EOFTok.setLocation(Tok.getLocation()); |
| 620 | EOFTok.setLength(0); |
| 621 | ArgTokens.push_back(EOFTok); |
| 622 | ++NumActuals; |
Argyrios Kyrtzidis | fb70380 | 2013-02-22 22:28:58 +0000 | [diff] [blame^] | 623 | if (!ContainsCodeCompletionTok || NumFixedArgsLeft != 0) { |
| 624 | assert(NumFixedArgsLeft != 0 && "Too many arguments parsed"); |
| 625 | --NumFixedArgsLeft; |
| 626 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 627 | } |
| 628 | |
| 629 | // Okay, we either found the r_paren. Check to see if we parsed too few |
| 630 | // arguments. |
| 631 | unsigned MinArgsExpected = MI->getNumArgs(); |
| 632 | |
| 633 | // See MacroArgs instance var for description of this. |
| 634 | bool isVarargsElided = false; |
| 635 | |
Argyrios Kyrtzidis | d4635d4 | 2012-12-21 01:51:12 +0000 | [diff] [blame] | 636 | if (ContainsCodeCompletionTok) { |
| 637 | // Recover from not-fully-formed macro invocation during code-completion. |
| 638 | Token EOFTok; |
| 639 | EOFTok.startToken(); |
| 640 | EOFTok.setKind(tok::eof); |
| 641 | EOFTok.setLocation(Tok.getLocation()); |
| 642 | EOFTok.setLength(0); |
| 643 | for (; NumActuals < MinArgsExpected; ++NumActuals) |
| 644 | ArgTokens.push_back(EOFTok); |
| 645 | } |
| 646 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 647 | if (NumActuals < MinArgsExpected) { |
| 648 | // There are several cases where too few arguments is ok, handle them now. |
| 649 | if (NumActuals == 0 && MinArgsExpected == 1) { |
| 650 | // #define A(X) or #define A(...) ---> A() |
| 651 | |
| 652 | // If there is exactly one argument, and that argument is missing, |
| 653 | // then we have an empty "()" argument empty list. This is fine, even if |
| 654 | // the macro expects one argument (the argument is just empty). |
| 655 | isVarargsElided = MI->isVariadic(); |
| 656 | } else if (MI->isVariadic() && |
| 657 | (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) |
| 658 | (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() |
| 659 | // Varargs where the named vararg parameter is missing: OK as extension. |
| 660 | // #define A(x, ...) |
| 661 | // A("blah") |
Eli Friedman | 14d3c79 | 2012-11-14 02:18:46 +0000 | [diff] [blame] | 662 | // |
| 663 | // If the macro contains the comma pasting extension, the diagnostic |
| 664 | // is suppressed; we know we'll get another diagnostic later. |
| 665 | if (!MI->hasCommaPasting()) { |
| 666 | Diag(Tok, diag::ext_missing_varargs_arg); |
| 667 | Diag(MI->getDefinitionLoc(), diag::note_macro_here) |
| 668 | << MacroName.getIdentifierInfo(); |
| 669 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 670 | |
| 671 | // Remember this occurred, allowing us to elide the comma when used for |
| 672 | // cases like: |
| 673 | // #define A(x, foo...) blah(a, ## foo) |
| 674 | // #define B(x, ...) blah(a, ## __VA_ARGS__) |
| 675 | // #define C(...) blah(a, ## __VA_ARGS__) |
| 676 | // A(x) B(x) C() |
| 677 | isVarargsElided = true; |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 678 | } else if (!ContainsCodeCompletionTok) { |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 679 | // Otherwise, emit the error. |
| 680 | Diag(Tok, diag::err_too_few_args_in_macro_invoc); |
Argyrios Kyrtzidis | 164fdb6 | 2012-12-14 18:53:47 +0000 | [diff] [blame] | 681 | Diag(MI->getDefinitionLoc(), diag::note_macro_here) |
| 682 | << MacroName.getIdentifierInfo(); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 683 | return 0; |
| 684 | } |
| 685 | |
| 686 | // Add a marker EOF token to the end of the token list for this argument. |
| 687 | SourceLocation EndLoc = Tok.getLocation(); |
| 688 | Tok.startToken(); |
| 689 | Tok.setKind(tok::eof); |
| 690 | Tok.setLocation(EndLoc); |
| 691 | Tok.setLength(0); |
| 692 | ArgTokens.push_back(Tok); |
| 693 | |
| 694 | // If we expect two arguments, add both as empty. |
| 695 | if (NumActuals == 0 && MinArgsExpected == 2) |
| 696 | ArgTokens.push_back(Tok); |
| 697 | |
Argyrios Kyrtzidis | c1d9a67 | 2012-12-21 01:17:20 +0000 | [diff] [blame] | 698 | } else if (NumActuals > MinArgsExpected && !MI->isVariadic() && |
| 699 | !ContainsCodeCompletionTok) { |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 700 | // Emit the diagnostic at the macro name in case there is a missing ). |
| 701 | // Emitting it at the , could be far away from the macro name. |
| 702 | Diag(MacroName, diag::err_too_many_args_in_macro_invoc); |
Argyrios Kyrtzidis | 164fdb6 | 2012-12-14 18:53:47 +0000 | [diff] [blame] | 703 | Diag(MI->getDefinitionLoc(), diag::note_macro_here) |
| 704 | << MacroName.getIdentifierInfo(); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 705 | return 0; |
| 706 | } |
| 707 | |
| 708 | return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this); |
| 709 | } |
| 710 | |
| 711 | /// \brief Keeps macro expanded tokens for TokenLexers. |
| 712 | // |
| 713 | /// Works like a stack; a TokenLexer adds the macro expanded tokens that is |
| 714 | /// going to lex in the cache and when it finishes the tokens are removed |
| 715 | /// from the end of the cache. |
| 716 | Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer, |
| 717 | ArrayRef<Token> tokens) { |
| 718 | assert(tokLexer); |
| 719 | if (tokens.empty()) |
| 720 | return 0; |
| 721 | |
| 722 | size_t newIndex = MacroExpandedTokens.size(); |
| 723 | bool cacheNeedsToGrow = tokens.size() > |
| 724 | MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); |
| 725 | MacroExpandedTokens.append(tokens.begin(), tokens.end()); |
| 726 | |
| 727 | if (cacheNeedsToGrow) { |
| 728 | // Go through all the TokenLexers whose 'Tokens' pointer points in the |
| 729 | // buffer and update the pointers to the (potential) new buffer array. |
| 730 | for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) { |
| 731 | TokenLexer *prevLexer; |
| 732 | size_t tokIndex; |
| 733 | llvm::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i]; |
| 734 | prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex; |
| 735 | } |
| 736 | } |
| 737 | |
| 738 | MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex)); |
| 739 | return MacroExpandedTokens.data() + newIndex; |
| 740 | } |
| 741 | |
| 742 | void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() { |
| 743 | assert(!MacroExpandingLexersStack.empty()); |
| 744 | size_t tokIndex = MacroExpandingLexersStack.back().second; |
| 745 | assert(tokIndex < MacroExpandedTokens.size()); |
| 746 | // Pop the cached macro expanded tokens from the end. |
| 747 | MacroExpandedTokens.resize(tokIndex); |
| 748 | MacroExpandingLexersStack.pop_back(); |
| 749 | } |
| 750 | |
| 751 | /// ComputeDATE_TIME - Compute the current time, enter it into the specified |
| 752 | /// scratch buffer, then return DATELoc/TIMELoc locations with the position of |
| 753 | /// the identifier tokens inserted. |
| 754 | static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, |
| 755 | Preprocessor &PP) { |
| 756 | time_t TT = time(0); |
| 757 | struct tm *TM = localtime(&TT); |
| 758 | |
| 759 | static const char * const Months[] = { |
| 760 | "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" |
| 761 | }; |
| 762 | |
Dmitri Gribenko | ae07f72 | 2012-09-24 20:56:28 +0000 | [diff] [blame] | 763 | { |
| 764 | SmallString<32> TmpBuffer; |
| 765 | llvm::raw_svector_ostream TmpStream(TmpBuffer); |
| 766 | TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon], |
| 767 | TM->tm_mday, TM->tm_year + 1900); |
Dmitri Gribenko | ae07f72 | 2012-09-24 20:56:28 +0000 | [diff] [blame] | 768 | Token TmpTok; |
| 769 | TmpTok.startToken(); |
Dmitri Gribenko | b8e9e75 | 2012-09-24 21:07:17 +0000 | [diff] [blame] | 770 | PP.CreateString(TmpStream.str(), TmpTok); |
Dmitri Gribenko | ae07f72 | 2012-09-24 20:56:28 +0000 | [diff] [blame] | 771 | DATELoc = TmpTok.getLocation(); |
| 772 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 773 | |
Dmitri Gribenko | ae07f72 | 2012-09-24 20:56:28 +0000 | [diff] [blame] | 774 | { |
| 775 | SmallString<32> TmpBuffer; |
| 776 | llvm::raw_svector_ostream TmpStream(TmpBuffer); |
| 777 | TmpStream << llvm::format("\"%02d:%02d:%02d\"", |
| 778 | TM->tm_hour, TM->tm_min, TM->tm_sec); |
Dmitri Gribenko | ae07f72 | 2012-09-24 20:56:28 +0000 | [diff] [blame] | 779 | Token TmpTok; |
| 780 | TmpTok.startToken(); |
Dmitri Gribenko | b8e9e75 | 2012-09-24 21:07:17 +0000 | [diff] [blame] | 781 | PP.CreateString(TmpStream.str(), TmpTok); |
Dmitri Gribenko | ae07f72 | 2012-09-24 20:56:28 +0000 | [diff] [blame] | 782 | TIMELoc = TmpTok.getLocation(); |
| 783 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 784 | } |
| 785 | |
| 786 | |
| 787 | /// HasFeature - Return true if we recognize and implement the feature |
| 788 | /// specified by the identifier as a standard language feature. |
| 789 | static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { |
| 790 | const LangOptions &LangOpts = PP.getLangOpts(); |
| 791 | StringRef Feature = II->getName(); |
| 792 | |
| 793 | // Normalize the feature name, __foo__ becomes foo. |
| 794 | if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4) |
| 795 | Feature = Feature.substr(2, Feature.size() - 4); |
| 796 | |
| 797 | return llvm::StringSwitch<bool>(Feature) |
Will Dietz | f54319c | 2013-01-18 11:30:38 +0000 | [diff] [blame] | 798 | .Case("address_sanitizer", LangOpts.Sanitize.Address) |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 799 | .Case("attribute_analyzer_noreturn", true) |
| 800 | .Case("attribute_availability", true) |
| 801 | .Case("attribute_availability_with_message", true) |
| 802 | .Case("attribute_cf_returns_not_retained", true) |
| 803 | .Case("attribute_cf_returns_retained", true) |
| 804 | .Case("attribute_deprecated_with_message", true) |
| 805 | .Case("attribute_ext_vector_type", true) |
| 806 | .Case("attribute_ns_returns_not_retained", true) |
| 807 | .Case("attribute_ns_returns_retained", true) |
| 808 | .Case("attribute_ns_consumes_self", true) |
| 809 | .Case("attribute_ns_consumed", true) |
| 810 | .Case("attribute_cf_consumed", true) |
| 811 | .Case("attribute_objc_ivar_unused", true) |
| 812 | .Case("attribute_objc_method_family", true) |
| 813 | .Case("attribute_overloadable", true) |
| 814 | .Case("attribute_unavailable_with_message", true) |
| 815 | .Case("attribute_unused_on_fields", true) |
| 816 | .Case("blocks", LangOpts.Blocks) |
| 817 | .Case("cxx_exceptions", LangOpts.Exceptions) |
| 818 | .Case("cxx_rtti", LangOpts.RTTI) |
| 819 | .Case("enumerator_attributes", true) |
Will Dietz | f54319c | 2013-01-18 11:30:38 +0000 | [diff] [blame] | 820 | .Case("memory_sanitizer", LangOpts.Sanitize.Memory) |
| 821 | .Case("thread_sanitizer", LangOpts.Sanitize.Thread) |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 822 | // Objective-C features |
| 823 | .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE? |
| 824 | .Case("objc_arc", LangOpts.ObjCAutoRefCount) |
| 825 | .Case("objc_arc_weak", LangOpts.ObjCARCWeak) |
| 826 | .Case("objc_default_synthesize_properties", LangOpts.ObjC2) |
| 827 | .Case("objc_fixed_enum", LangOpts.ObjC2) |
| 828 | .Case("objc_instancetype", LangOpts.ObjC2) |
| 829 | .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules) |
| 830 | .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile()) |
Ted Kremenek | dae8f9f | 2013-01-04 19:04:44 +0000 | [diff] [blame] | 831 | .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword? |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 832 | .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport()) |
| 833 | .Case("ownership_holds", true) |
| 834 | .Case("ownership_returns", true) |
| 835 | .Case("ownership_takes", true) |
| 836 | .Case("objc_bool", true) |
| 837 | .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile()) |
| 838 | .Case("objc_array_literals", LangOpts.ObjC2) |
| 839 | .Case("objc_dictionary_literals", LangOpts.ObjC2) |
| 840 | .Case("objc_boxed_expressions", LangOpts.ObjC2) |
| 841 | .Case("arc_cf_code_audited", true) |
| 842 | // C11 features |
| 843 | .Case("c_alignas", LangOpts.C11) |
| 844 | .Case("c_atomic", LangOpts.C11) |
| 845 | .Case("c_generic_selections", LangOpts.C11) |
| 846 | .Case("c_static_assert", LangOpts.C11) |
| 847 | // C++11 features |
Richard Smith | 2bf7fdb | 2013-01-02 11:42:31 +0000 | [diff] [blame] | 848 | .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11) |
| 849 | .Case("cxx_alias_templates", LangOpts.CPlusPlus11) |
| 850 | .Case("cxx_alignas", LangOpts.CPlusPlus11) |
| 851 | .Case("cxx_atomic", LangOpts.CPlusPlus11) |
| 852 | .Case("cxx_attributes", LangOpts.CPlusPlus11) |
| 853 | .Case("cxx_auto_type", LangOpts.CPlusPlus11) |
| 854 | .Case("cxx_constexpr", LangOpts.CPlusPlus11) |
| 855 | .Case("cxx_decltype", LangOpts.CPlusPlus11) |
| 856 | .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11) |
| 857 | .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11) |
| 858 | .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11) |
| 859 | .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11) |
| 860 | .Case("cxx_deleted_functions", LangOpts.CPlusPlus11) |
| 861 | .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11) |
| 862 | .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11) |
| 863 | .Case("cxx_implicit_moves", LangOpts.CPlusPlus11) |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 864 | //.Case("cxx_inheriting_constructors", false) |
Richard Smith | 2bf7fdb | 2013-01-02 11:42:31 +0000 | [diff] [blame] | 865 | .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11) |
| 866 | .Case("cxx_lambdas", LangOpts.CPlusPlus11) |
| 867 | .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11) |
| 868 | .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11) |
| 869 | .Case("cxx_noexcept", LangOpts.CPlusPlus11) |
| 870 | .Case("cxx_nullptr", LangOpts.CPlusPlus11) |
| 871 | .Case("cxx_override_control", LangOpts.CPlusPlus11) |
| 872 | .Case("cxx_range_for", LangOpts.CPlusPlus11) |
| 873 | .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11) |
| 874 | .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11) |
| 875 | .Case("cxx_rvalue_references", LangOpts.CPlusPlus11) |
| 876 | .Case("cxx_strong_enums", LangOpts.CPlusPlus11) |
| 877 | .Case("cxx_static_assert", LangOpts.CPlusPlus11) |
| 878 | .Case("cxx_trailing_return", LangOpts.CPlusPlus11) |
| 879 | .Case("cxx_unicode_literals", LangOpts.CPlusPlus11) |
| 880 | .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11) |
| 881 | .Case("cxx_user_literals", LangOpts.CPlusPlus11) |
| 882 | .Case("cxx_variadic_templates", LangOpts.CPlusPlus11) |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 883 | // Type traits |
| 884 | .Case("has_nothrow_assign", LangOpts.CPlusPlus) |
| 885 | .Case("has_nothrow_copy", LangOpts.CPlusPlus) |
| 886 | .Case("has_nothrow_constructor", LangOpts.CPlusPlus) |
| 887 | .Case("has_trivial_assign", LangOpts.CPlusPlus) |
| 888 | .Case("has_trivial_copy", LangOpts.CPlusPlus) |
| 889 | .Case("has_trivial_constructor", LangOpts.CPlusPlus) |
| 890 | .Case("has_trivial_destructor", LangOpts.CPlusPlus) |
| 891 | .Case("has_virtual_destructor", LangOpts.CPlusPlus) |
| 892 | .Case("is_abstract", LangOpts.CPlusPlus) |
| 893 | .Case("is_base_of", LangOpts.CPlusPlus) |
| 894 | .Case("is_class", LangOpts.CPlusPlus) |
| 895 | .Case("is_convertible_to", LangOpts.CPlusPlus) |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 896 | .Case("is_empty", LangOpts.CPlusPlus) |
| 897 | .Case("is_enum", LangOpts.CPlusPlus) |
| 898 | .Case("is_final", LangOpts.CPlusPlus) |
| 899 | .Case("is_literal", LangOpts.CPlusPlus) |
| 900 | .Case("is_standard_layout", LangOpts.CPlusPlus) |
| 901 | .Case("is_pod", LangOpts.CPlusPlus) |
| 902 | .Case("is_polymorphic", LangOpts.CPlusPlus) |
| 903 | .Case("is_trivial", LangOpts.CPlusPlus) |
| 904 | .Case("is_trivially_assignable", LangOpts.CPlusPlus) |
| 905 | .Case("is_trivially_constructible", LangOpts.CPlusPlus) |
| 906 | .Case("is_trivially_copyable", LangOpts.CPlusPlus) |
| 907 | .Case("is_union", LangOpts.CPlusPlus) |
| 908 | .Case("modules", LangOpts.Modules) |
| 909 | .Case("tls", PP.getTargetInfo().isTLSSupported()) |
| 910 | .Case("underlying_type", LangOpts.CPlusPlus) |
| 911 | .Default(false); |
| 912 | } |
| 913 | |
| 914 | /// HasExtension - Return true if we recognize and implement the feature |
| 915 | /// specified by the identifier, either as an extension or a standard language |
| 916 | /// feature. |
| 917 | static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) { |
| 918 | if (HasFeature(PP, II)) |
| 919 | return true; |
| 920 | |
| 921 | // If the use of an extension results in an error diagnostic, extensions are |
| 922 | // effectively unavailable, so just return false here. |
| 923 | if (PP.getDiagnostics().getExtensionHandlingBehavior() == |
| 924 | DiagnosticsEngine::Ext_Error) |
| 925 | return false; |
| 926 | |
| 927 | const LangOptions &LangOpts = PP.getLangOpts(); |
| 928 | StringRef Extension = II->getName(); |
| 929 | |
| 930 | // Normalize the extension name, __foo__ becomes foo. |
| 931 | if (Extension.startswith("__") && Extension.endswith("__") && |
| 932 | Extension.size() >= 4) |
| 933 | Extension = Extension.substr(2, Extension.size() - 4); |
| 934 | |
| 935 | // Because we inherit the feature list from HasFeature, this string switch |
| 936 | // must be less restrictive than HasFeature's. |
| 937 | return llvm::StringSwitch<bool>(Extension) |
| 938 | // C11 features supported by other languages as extensions. |
| 939 | .Case("c_alignas", true) |
| 940 | .Case("c_atomic", true) |
| 941 | .Case("c_generic_selections", true) |
| 942 | .Case("c_static_assert", true) |
| 943 | // C++0x features supported by other languages as extensions. |
| 944 | .Case("cxx_atomic", LangOpts.CPlusPlus) |
| 945 | .Case("cxx_deleted_functions", LangOpts.CPlusPlus) |
| 946 | .Case("cxx_explicit_conversions", LangOpts.CPlusPlus) |
| 947 | .Case("cxx_inline_namespaces", LangOpts.CPlusPlus) |
| 948 | .Case("cxx_local_type_template_args", LangOpts.CPlusPlus) |
| 949 | .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus) |
| 950 | .Case("cxx_override_control", LangOpts.CPlusPlus) |
| 951 | .Case("cxx_range_for", LangOpts.CPlusPlus) |
| 952 | .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus) |
| 953 | .Case("cxx_rvalue_references", LangOpts.CPlusPlus) |
| 954 | .Default(false); |
| 955 | } |
| 956 | |
| 957 | /// HasAttribute - Return true if we recognize and implement the attribute |
| 958 | /// specified by the given identifier. |
| 959 | static bool HasAttribute(const IdentifierInfo *II) { |
| 960 | StringRef Name = II->getName(); |
| 961 | // Normalize the attribute name, __foo__ becomes foo. |
| 962 | if (Name.startswith("__") && Name.endswith("__") && Name.size() >= 4) |
| 963 | Name = Name.substr(2, Name.size() - 4); |
| 964 | |
| 965 | // FIXME: Do we need to handle namespaces here? |
| 966 | return llvm::StringSwitch<bool>(Name) |
| 967 | #include "clang/Lex/AttrSpellings.inc" |
| 968 | .Default(false); |
| 969 | } |
| 970 | |
| 971 | /// EvaluateHasIncludeCommon - Process a '__has_include("path")' |
| 972 | /// or '__has_include_next("path")' expression. |
| 973 | /// Returns true if successful. |
| 974 | static bool EvaluateHasIncludeCommon(Token &Tok, |
| 975 | IdentifierInfo *II, Preprocessor &PP, |
| 976 | const DirectoryLookup *LookupFrom) { |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 977 | // Save the location of the current token. If a '(' is later found, use |
Aaron Ballman | 5cb2411 | 2013-01-15 21:59:46 +0000 | [diff] [blame] | 978 | // that location. If not, use the end of this location instead. |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 979 | SourceLocation LParenLoc = Tok.getLocation(); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 980 | |
Aaron Ballman | 6ce0000 | 2013-01-16 19:32:21 +0000 | [diff] [blame] | 981 | // These expressions are only allowed within a preprocessor directive. |
| 982 | if (!PP.isParsingIfOrElifDirective()) { |
| 983 | PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName(); |
| 984 | return false; |
| 985 | } |
| 986 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 987 | // Get '('. |
| 988 | PP.LexNonComment(Tok); |
| 989 | |
| 990 | // Ensure we have a '('. |
| 991 | if (Tok.isNot(tok::l_paren)) { |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 992 | // No '(', use end of last token. |
| 993 | LParenLoc = PP.getLocForEndOfToken(LParenLoc); |
| 994 | PP.Diag(LParenLoc, diag::err_pp_missing_lparen) << II->getName(); |
| 995 | // If the next token looks like a filename or the start of one, |
| 996 | // assume it is and process it as such. |
| 997 | if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) && |
| 998 | !Tok.is(tok::less)) |
| 999 | return false; |
| 1000 | } else { |
| 1001 | // Save '(' location for possible missing ')' message. |
| 1002 | LParenLoc = Tok.getLocation(); |
| 1003 | |
Eli Friedman | ec94b61 | 2013-01-09 02:20:00 +0000 | [diff] [blame] | 1004 | if (PP.getCurrentLexer()) { |
| 1005 | // Get the file name. |
| 1006 | PP.getCurrentLexer()->LexIncludeFilename(Tok); |
| 1007 | } else { |
| 1008 | // We're in a macro, so we can't use LexIncludeFilename; just |
| 1009 | // grab the next token. |
| 1010 | PP.Lex(Tok); |
| 1011 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1012 | } |
| 1013 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1014 | // Reserve a buffer to get the spelling. |
| 1015 | SmallString<128> FilenameBuffer; |
| 1016 | StringRef Filename; |
| 1017 | SourceLocation EndLoc; |
| 1018 | |
| 1019 | switch (Tok.getKind()) { |
| 1020 | case tok::eod: |
| 1021 | // If the token kind is EOD, the error has already been diagnosed. |
| 1022 | return false; |
| 1023 | |
| 1024 | case tok::angle_string_literal: |
| 1025 | case tok::string_literal: { |
| 1026 | bool Invalid = false; |
| 1027 | Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); |
| 1028 | if (Invalid) |
| 1029 | return false; |
| 1030 | break; |
| 1031 | } |
| 1032 | |
| 1033 | case tok::less: |
| 1034 | // This could be a <foo/bar.h> file coming from a macro expansion. In this |
| 1035 | // case, glue the tokens together into FilenameBuffer and interpret those. |
| 1036 | FilenameBuffer.push_back('<'); |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 1037 | if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) { |
| 1038 | // Let the caller know a <eod> was found by changing the Token kind. |
| 1039 | Tok.setKind(tok::eod); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1040 | return false; // Found <eod> but no ">"? Diagnostic already emitted. |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 1041 | } |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1042 | Filename = FilenameBuffer.str(); |
| 1043 | break; |
| 1044 | default: |
| 1045 | PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); |
| 1046 | return false; |
| 1047 | } |
| 1048 | |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 1049 | SourceLocation FilenameLoc = Tok.getLocation(); |
| 1050 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1051 | // Get ')'. |
| 1052 | PP.LexNonComment(Tok); |
| 1053 | |
| 1054 | // Ensure we have a trailing ). |
| 1055 | if (Tok.isNot(tok::r_paren)) { |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 1056 | PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_missing_rparen) |
| 1057 | << II->getName(); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1058 | PP.Diag(LParenLoc, diag::note_matching) << "("; |
| 1059 | return false; |
| 1060 | } |
| 1061 | |
| 1062 | bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); |
| 1063 | // If GetIncludeFilenameSpelling set the start ptr to null, there was an |
| 1064 | // error. |
| 1065 | if (Filename.empty()) |
| 1066 | return false; |
| 1067 | |
| 1068 | // Search include directories. |
| 1069 | const DirectoryLookup *CurDir; |
| 1070 | const FileEntry *File = |
| 1071 | PP.LookupFile(Filename, isAngled, LookupFrom, CurDir, NULL, NULL, NULL); |
| 1072 | |
| 1073 | // Get the result value. A result of true means the file exists. |
| 1074 | return File != 0; |
| 1075 | } |
| 1076 | |
| 1077 | /// EvaluateHasInclude - Process a '__has_include("path")' expression. |
| 1078 | /// Returns true if successful. |
| 1079 | static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, |
| 1080 | Preprocessor &PP) { |
| 1081 | return EvaluateHasIncludeCommon(Tok, II, PP, NULL); |
| 1082 | } |
| 1083 | |
| 1084 | /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. |
| 1085 | /// Returns true if successful. |
| 1086 | static bool EvaluateHasIncludeNext(Token &Tok, |
| 1087 | IdentifierInfo *II, Preprocessor &PP) { |
| 1088 | // __has_include_next is like __has_include, except that we start |
| 1089 | // searching after the current found directory. If we can't do this, |
| 1090 | // issue a diagnostic. |
| 1091 | const DirectoryLookup *Lookup = PP.GetCurDirLookup(); |
| 1092 | if (PP.isInPrimaryFile()) { |
| 1093 | Lookup = 0; |
| 1094 | PP.Diag(Tok, diag::pp_include_next_in_primary); |
| 1095 | } else if (Lookup == 0) { |
| 1096 | PP.Diag(Tok, diag::pp_include_next_absolute_path); |
| 1097 | } else { |
| 1098 | // Start looking up in the next directory. |
| 1099 | ++Lookup; |
| 1100 | } |
| 1101 | |
| 1102 | return EvaluateHasIncludeCommon(Tok, II, PP, Lookup); |
| 1103 | } |
| 1104 | |
Douglas Gregor | c83de30 | 2012-09-25 15:44:52 +0000 | [diff] [blame] | 1105 | /// \brief Process __building_module(identifier) expression. |
| 1106 | /// \returns true if we are building the named module, false otherwise. |
| 1107 | static bool EvaluateBuildingModule(Token &Tok, |
| 1108 | IdentifierInfo *II, Preprocessor &PP) { |
| 1109 | // Get '('. |
| 1110 | PP.LexNonComment(Tok); |
| 1111 | |
| 1112 | // Ensure we have a '('. |
| 1113 | if (Tok.isNot(tok::l_paren)) { |
| 1114 | PP.Diag(Tok.getLocation(), diag::err_pp_missing_lparen) << II->getName(); |
| 1115 | return false; |
| 1116 | } |
| 1117 | |
| 1118 | // Save '(' location for possible missing ')' message. |
| 1119 | SourceLocation LParenLoc = Tok.getLocation(); |
| 1120 | |
| 1121 | // Get the module name. |
| 1122 | PP.LexNonComment(Tok); |
| 1123 | |
| 1124 | // Ensure that we have an identifier. |
| 1125 | if (Tok.isNot(tok::identifier)) { |
| 1126 | PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module); |
| 1127 | return false; |
| 1128 | } |
| 1129 | |
| 1130 | bool Result |
| 1131 | = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule; |
| 1132 | |
| 1133 | // Get ')'. |
| 1134 | PP.LexNonComment(Tok); |
| 1135 | |
| 1136 | // Ensure we have a trailing ). |
| 1137 | if (Tok.isNot(tok::r_paren)) { |
| 1138 | PP.Diag(Tok.getLocation(), diag::err_pp_missing_rparen) << II->getName(); |
| 1139 | PP.Diag(LParenLoc, diag::note_matching) << "("; |
| 1140 | return false; |
| 1141 | } |
| 1142 | |
| 1143 | return Result; |
| 1144 | } |
| 1145 | |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1146 | /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded |
| 1147 | /// as a builtin macro, handle it and return the next token as 'Tok'. |
| 1148 | void Preprocessor::ExpandBuiltinMacro(Token &Tok) { |
| 1149 | // Figure out which token this is. |
| 1150 | IdentifierInfo *II = Tok.getIdentifierInfo(); |
| 1151 | assert(II && "Can't be a macro without id info!"); |
| 1152 | |
| 1153 | // If this is an _Pragma or Microsoft __pragma directive, expand it, |
| 1154 | // invoke the pragma handler, then lex the token after it. |
| 1155 | if (II == Ident_Pragma) |
| 1156 | return Handle_Pragma(Tok); |
| 1157 | else if (II == Ident__pragma) // in non-MS mode this is null |
| 1158 | return HandleMicrosoft__pragma(Tok); |
| 1159 | |
| 1160 | ++NumBuiltinMacroExpanded; |
| 1161 | |
| 1162 | SmallString<128> TmpBuffer; |
| 1163 | llvm::raw_svector_ostream OS(TmpBuffer); |
| 1164 | |
| 1165 | // Set up the return result. |
| 1166 | Tok.setIdentifierInfo(0); |
| 1167 | Tok.clearFlag(Token::NeedsCleaning); |
| 1168 | |
| 1169 | if (II == Ident__LINE__) { |
| 1170 | // C99 6.10.8: "__LINE__: The presumed line number (within the current |
| 1171 | // source file) of the current source line (an integer constant)". This can |
| 1172 | // be affected by #line. |
| 1173 | SourceLocation Loc = Tok.getLocation(); |
| 1174 | |
| 1175 | // Advance to the location of the first _, this might not be the first byte |
| 1176 | // of the token if it starts with an escaped newline. |
| 1177 | Loc = AdvanceToTokenCharacter(Loc, 0); |
| 1178 | |
| 1179 | // One wrinkle here is that GCC expands __LINE__ to location of the *end* of |
| 1180 | // a macro expansion. This doesn't matter for object-like macros, but |
| 1181 | // can matter for a function-like macro that expands to contain __LINE__. |
| 1182 | // Skip down through expansion points until we find a file loc for the |
| 1183 | // end of the expansion history. |
| 1184 | Loc = SourceMgr.getExpansionRange(Loc).second; |
| 1185 | PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); |
| 1186 | |
| 1187 | // __LINE__ expands to a simple numeric value. |
| 1188 | OS << (PLoc.isValid()? PLoc.getLine() : 1); |
| 1189 | Tok.setKind(tok::numeric_constant); |
| 1190 | } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { |
| 1191 | // C99 6.10.8: "__FILE__: The presumed name of the current source file (a |
| 1192 | // character string literal)". This can be affected by #line. |
| 1193 | PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); |
| 1194 | |
| 1195 | // __BASE_FILE__ is a GNU extension that returns the top of the presumed |
| 1196 | // #include stack instead of the current file. |
| 1197 | if (II == Ident__BASE_FILE__ && PLoc.isValid()) { |
| 1198 | SourceLocation NextLoc = PLoc.getIncludeLoc(); |
| 1199 | while (NextLoc.isValid()) { |
| 1200 | PLoc = SourceMgr.getPresumedLoc(NextLoc); |
| 1201 | if (PLoc.isInvalid()) |
| 1202 | break; |
| 1203 | |
| 1204 | NextLoc = PLoc.getIncludeLoc(); |
| 1205 | } |
| 1206 | } |
| 1207 | |
| 1208 | // Escape this filename. Turn '\' -> '\\' '"' -> '\"' |
| 1209 | SmallString<128> FN; |
| 1210 | if (PLoc.isValid()) { |
| 1211 | FN += PLoc.getFilename(); |
| 1212 | Lexer::Stringify(FN); |
| 1213 | OS << '"' << FN.str() << '"'; |
| 1214 | } |
| 1215 | Tok.setKind(tok::string_literal); |
| 1216 | } else if (II == Ident__DATE__) { |
| 1217 | if (!DATELoc.isValid()) |
| 1218 | ComputeDATE_TIME(DATELoc, TIMELoc, *this); |
| 1219 | Tok.setKind(tok::string_literal); |
| 1220 | Tok.setLength(strlen("\"Mmm dd yyyy\"")); |
| 1221 | Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(), |
| 1222 | Tok.getLocation(), |
| 1223 | Tok.getLength())); |
| 1224 | return; |
| 1225 | } else if (II == Ident__TIME__) { |
| 1226 | if (!TIMELoc.isValid()) |
| 1227 | ComputeDATE_TIME(DATELoc, TIMELoc, *this); |
| 1228 | Tok.setKind(tok::string_literal); |
| 1229 | Tok.setLength(strlen("\"hh:mm:ss\"")); |
| 1230 | Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(), |
| 1231 | Tok.getLocation(), |
| 1232 | Tok.getLength())); |
| 1233 | return; |
| 1234 | } else if (II == Ident__INCLUDE_LEVEL__) { |
| 1235 | // Compute the presumed include depth of this token. This can be affected |
| 1236 | // by GNU line markers. |
| 1237 | unsigned Depth = 0; |
| 1238 | |
| 1239 | PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); |
| 1240 | if (PLoc.isValid()) { |
| 1241 | PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); |
| 1242 | for (; PLoc.isValid(); ++Depth) |
| 1243 | PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); |
| 1244 | } |
| 1245 | |
| 1246 | // __INCLUDE_LEVEL__ expands to a simple numeric value. |
| 1247 | OS << Depth; |
| 1248 | Tok.setKind(tok::numeric_constant); |
| 1249 | } else if (II == Ident__TIMESTAMP__) { |
| 1250 | // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be |
| 1251 | // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. |
| 1252 | |
| 1253 | // Get the file that we are lexing out of. If we're currently lexing from |
| 1254 | // a macro, dig into the include stack. |
| 1255 | const FileEntry *CurFile = 0; |
| 1256 | PreprocessorLexer *TheLexer = getCurrentFileLexer(); |
| 1257 | |
| 1258 | if (TheLexer) |
| 1259 | CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); |
| 1260 | |
| 1261 | const char *Result; |
| 1262 | if (CurFile) { |
| 1263 | time_t TT = CurFile->getModificationTime(); |
| 1264 | struct tm *TM = localtime(&TT); |
| 1265 | Result = asctime(TM); |
| 1266 | } else { |
| 1267 | Result = "??? ??? ?? ??:??:?? ????\n"; |
| 1268 | } |
| 1269 | // Surround the string with " and strip the trailing newline. |
| 1270 | OS << '"' << StringRef(Result, strlen(Result)-1) << '"'; |
| 1271 | Tok.setKind(tok::string_literal); |
| 1272 | } else if (II == Ident__COUNTER__) { |
| 1273 | // __COUNTER__ expands to a simple numeric value. |
| 1274 | OS << CounterValue++; |
| 1275 | Tok.setKind(tok::numeric_constant); |
| 1276 | } else if (II == Ident__has_feature || |
| 1277 | II == Ident__has_extension || |
| 1278 | II == Ident__has_builtin || |
| 1279 | II == Ident__has_attribute) { |
| 1280 | // The argument to these builtins should be a parenthesized identifier. |
| 1281 | SourceLocation StartLoc = Tok.getLocation(); |
| 1282 | |
| 1283 | bool IsValid = false; |
| 1284 | IdentifierInfo *FeatureII = 0; |
| 1285 | |
| 1286 | // Read the '('. |
Andy Gibbs | d41d094 | 2012-11-17 19:18:27 +0000 | [diff] [blame] | 1287 | LexUnexpandedToken(Tok); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1288 | if (Tok.is(tok::l_paren)) { |
| 1289 | // Read the identifier |
Andy Gibbs | d41d094 | 2012-11-17 19:18:27 +0000 | [diff] [blame] | 1290 | LexUnexpandedToken(Tok); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1291 | if (Tok.is(tok::identifier) || Tok.is(tok::kw_const)) { |
| 1292 | FeatureII = Tok.getIdentifierInfo(); |
| 1293 | |
| 1294 | // Read the ')'. |
Andy Gibbs | d41d094 | 2012-11-17 19:18:27 +0000 | [diff] [blame] | 1295 | LexUnexpandedToken(Tok); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1296 | if (Tok.is(tok::r_paren)) |
| 1297 | IsValid = true; |
| 1298 | } |
| 1299 | } |
| 1300 | |
| 1301 | bool Value = false; |
| 1302 | if (!IsValid) |
| 1303 | Diag(StartLoc, diag::err_feature_check_malformed); |
| 1304 | else if (II == Ident__has_builtin) { |
| 1305 | // Check for a builtin is trivial. |
| 1306 | Value = FeatureII->getBuiltinID() != 0; |
| 1307 | } else if (II == Ident__has_attribute) |
| 1308 | Value = HasAttribute(FeatureII); |
| 1309 | else if (II == Ident__has_extension) |
| 1310 | Value = HasExtension(*this, FeatureII); |
| 1311 | else { |
| 1312 | assert(II == Ident__has_feature && "Must be feature check"); |
| 1313 | Value = HasFeature(*this, FeatureII); |
| 1314 | } |
| 1315 | |
| 1316 | OS << (int)Value; |
| 1317 | if (IsValid) |
| 1318 | Tok.setKind(tok::numeric_constant); |
| 1319 | } else if (II == Ident__has_include || |
| 1320 | II == Ident__has_include_next) { |
| 1321 | // The argument to these two builtins should be a parenthesized |
| 1322 | // file name string literal using angle brackets (<>) or |
| 1323 | // double-quotes (""). |
| 1324 | bool Value; |
| 1325 | if (II == Ident__has_include) |
| 1326 | Value = EvaluateHasInclude(Tok, II, *this); |
| 1327 | else |
| 1328 | Value = EvaluateHasIncludeNext(Tok, II, *this); |
| 1329 | OS << (int)Value; |
Richard Trieu | da03198 | 2012-10-22 20:28:48 +0000 | [diff] [blame] | 1330 | if (Tok.is(tok::r_paren)) |
| 1331 | Tok.setKind(tok::numeric_constant); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1332 | } else if (II == Ident__has_warning) { |
| 1333 | // The argument should be a parenthesized string literal. |
| 1334 | // The argument to these builtins should be a parenthesized identifier. |
| 1335 | SourceLocation StartLoc = Tok.getLocation(); |
| 1336 | bool IsValid = false; |
| 1337 | bool Value = false; |
| 1338 | // Read the '('. |
Andy Gibbs | 58905d2 | 2012-11-17 19:15:38 +0000 | [diff] [blame] | 1339 | LexUnexpandedToken(Tok); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1340 | do { |
Andy Gibbs | 58905d2 | 2012-11-17 19:15:38 +0000 | [diff] [blame] | 1341 | if (Tok.isNot(tok::l_paren)) { |
| 1342 | Diag(StartLoc, diag::err_warning_check_malformed); |
| 1343 | break; |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1344 | } |
Andy Gibbs | 58905d2 | 2012-11-17 19:15:38 +0000 | [diff] [blame] | 1345 | |
| 1346 | LexUnexpandedToken(Tok); |
| 1347 | std::string WarningName; |
| 1348 | SourceLocation StrStartLoc = Tok.getLocation(); |
Andy Gibbs | a8df57a | 2012-11-17 19:16:52 +0000 | [diff] [blame] | 1349 | if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'", |
| 1350 | /*MacroExpansion=*/false)) { |
Andy Gibbs | 58905d2 | 2012-11-17 19:15:38 +0000 | [diff] [blame] | 1351 | // Eat tokens until ')'. |
Andy Gibbs | b5b30c4 | 2012-11-17 22:17:28 +0000 | [diff] [blame] | 1352 | while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) && |
| 1353 | Tok.isNot(tok::eof)) |
Andy Gibbs | 58905d2 | 2012-11-17 19:15:38 +0000 | [diff] [blame] | 1354 | LexUnexpandedToken(Tok); |
| 1355 | break; |
| 1356 | } |
| 1357 | |
| 1358 | // Is the end a ')'? |
| 1359 | if (!(IsValid = Tok.is(tok::r_paren))) { |
| 1360 | Diag(StartLoc, diag::err_warning_check_malformed); |
| 1361 | break; |
| 1362 | } |
| 1363 | |
| 1364 | if (WarningName.size() < 3 || WarningName[0] != '-' || |
| 1365 | WarningName[1] != 'W') { |
| 1366 | Diag(StrStartLoc, diag::warn_has_warning_invalid_option); |
| 1367 | break; |
| 1368 | } |
| 1369 | |
| 1370 | // Finally, check if the warning flags maps to a diagnostic group. |
| 1371 | // We construct a SmallVector here to talk to getDiagnosticIDs(). |
| 1372 | // Although we don't use the result, this isn't a hot path, and not |
| 1373 | // worth special casing. |
Dmitri Gribenko | f857950 | 2013-01-12 19:30:44 +0000 | [diff] [blame] | 1374 | SmallVector<diag::kind, 10> Diags; |
Andy Gibbs | 58905d2 | 2012-11-17 19:15:38 +0000 | [diff] [blame] | 1375 | Value = !getDiagnostics().getDiagnosticIDs()-> |
| 1376 | getDiagnosticsInGroup(WarningName.substr(2), Diags); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1377 | } while (false); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1378 | |
| 1379 | OS << (int)Value; |
Andy Gibbs | f591982b | 2012-11-17 19:14:53 +0000 | [diff] [blame] | 1380 | if (IsValid) |
| 1381 | Tok.setKind(tok::numeric_constant); |
Douglas Gregor | c83de30 | 2012-09-25 15:44:52 +0000 | [diff] [blame] | 1382 | } else if (II == Ident__building_module) { |
| 1383 | // The argument to this builtin should be an identifier. The |
| 1384 | // builtin evaluates to 1 when that identifier names the module we are |
| 1385 | // currently building. |
| 1386 | OS << (int)EvaluateBuildingModule(Tok, II, *this); |
| 1387 | Tok.setKind(tok::numeric_constant); |
| 1388 | } else if (II == Ident__MODULE__) { |
| 1389 | // The current module as an identifier. |
| 1390 | OS << getLangOpts().CurrentModule; |
| 1391 | IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule); |
| 1392 | Tok.setIdentifierInfo(ModuleII); |
| 1393 | Tok.setKind(ModuleII->getTokenID()); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1394 | } else { |
| 1395 | llvm_unreachable("Unknown identifier!"); |
| 1396 | } |
Dmitri Gribenko | b8e9e75 | 2012-09-24 21:07:17 +0000 | [diff] [blame] | 1397 | CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation()); |
Joao Matos | c0d4c1b | 2012-08-31 21:34:27 +0000 | [diff] [blame] | 1398 | } |
| 1399 | |
| 1400 | void Preprocessor::markMacroAsUsed(MacroInfo *MI) { |
| 1401 | // If the 'used' status changed, and the macro requires 'unused' warning, |
| 1402 | // remove its SourceLocation from the warn-for-unused-macro locations. |
| 1403 | if (MI->isWarnIfUnused() && !MI->isUsed()) |
| 1404 | WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); |
| 1405 | MI->setIsUsed(true); |
| 1406 | } |