Chris Lattner | a3b605e | 2008-03-09 03:13:06 +0000 | [diff] [blame] | 1 | //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===// |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 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 # directive processing for the Preprocessor. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "clang/Lex/Preprocessor.h" |
| 15 | #include "clang/Lex/HeaderSearch.h" |
| 16 | #include "clang/Lex/MacroInfo.h" |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 17 | #include "clang/Basic/Diagnostic.h" |
| 18 | #include "clang/Basic/SourceManager.h" |
| 19 | using namespace clang; |
| 20 | |
| 21 | //===----------------------------------------------------------------------===// |
| 22 | // Utility Methods for Preprocessor Directive Handling. |
| 23 | //===----------------------------------------------------------------------===// |
| 24 | |
| 25 | /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the |
| 26 | /// current line until the tok::eom token is found. |
| 27 | void Preprocessor::DiscardUntilEndOfDirective() { |
| 28 | Token Tmp; |
| 29 | do { |
| 30 | LexUnexpandedToken(Tmp); |
| 31 | } while (Tmp.isNot(tok::eom)); |
| 32 | } |
| 33 | |
| 34 | /// isCXXNamedOperator - Returns "true" if the token is a named operator in C++. |
| 35 | static bool isCXXNamedOperator(const std::string &Spelling) { |
| 36 | return Spelling == "and" || Spelling == "bitand" || Spelling == "bitor" || |
| 37 | Spelling == "compl" || Spelling == "not" || Spelling == "not_eq" || |
| 38 | Spelling == "or" || Spelling == "xor"; |
| 39 | } |
| 40 | |
| 41 | /// ReadMacroName - Lex and validate a macro name, which occurs after a |
| 42 | /// #define or #undef. This sets the token kind to eom and discards the rest |
| 43 | /// of the macro line if the macro name is invalid. isDefineUndef is 1 if |
| 44 | /// this is due to a a #define, 2 if #undef directive, 0 if it is something |
| 45 | /// else (e.g. #ifdef). |
| 46 | void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) { |
| 47 | // Read the token, don't allow macro expansion on it. |
| 48 | LexUnexpandedToken(MacroNameTok); |
| 49 | |
| 50 | // Missing macro name? |
Chris Lattner | 3692b09 | 2008-11-18 07:59:24 +0000 | [diff] [blame] | 51 | if (MacroNameTok.is(tok::eom)) { |
| 52 | Diag(MacroNameTok, diag::err_pp_missing_macro_name); |
| 53 | return; |
| 54 | } |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 55 | |
| 56 | IdentifierInfo *II = MacroNameTok.getIdentifierInfo(); |
| 57 | if (II == 0) { |
| 58 | std::string Spelling = getSpelling(MacroNameTok); |
| 59 | if (isCXXNamedOperator(Spelling)) |
| 60 | // C++ 2.5p2: Alternative tokens behave the same as its primary token |
| 61 | // except for their spellings. |
Chris Lattner | 56b05c8 | 2008-11-18 08:02:48 +0000 | [diff] [blame] | 62 | Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 63 | else |
| 64 | Diag(MacroNameTok, diag::err_pp_macro_not_identifier); |
| 65 | // Fall through on error. |
| 66 | } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) { |
| 67 | // Error if defining "defined": C99 6.10.8.4. |
| 68 | Diag(MacroNameTok, diag::err_defined_macro_name); |
| 69 | } else if (isDefineUndef && II->hasMacroDefinition() && |
| 70 | getMacroInfo(II)->isBuiltinMacro()) { |
| 71 | // Error if defining "__LINE__" and other builtins: C99 6.10.8.4. |
| 72 | if (isDefineUndef == 1) |
| 73 | Diag(MacroNameTok, diag::pp_redef_builtin_macro); |
| 74 | else |
| 75 | Diag(MacroNameTok, diag::pp_undef_builtin_macro); |
| 76 | } else { |
| 77 | // Okay, we got a good identifier node. Return it. |
| 78 | return; |
| 79 | } |
| 80 | |
| 81 | // Invalid macro name, read and discard the rest of the line. Then set the |
| 82 | // token kind to tok::eom. |
| 83 | MacroNameTok.setKind(tok::eom); |
| 84 | return DiscardUntilEndOfDirective(); |
| 85 | } |
| 86 | |
| 87 | /// CheckEndOfDirective - Ensure that the next token is a tok::eom token. If |
| 88 | /// not, emit a diagnostic and consume up until the eom. |
| 89 | void Preprocessor::CheckEndOfDirective(const char *DirType) { |
| 90 | Token Tmp; |
| 91 | // Lex unexpanded tokens: macros might expand to zero tokens, causing us to |
| 92 | // miss diagnosing invalid lines. |
| 93 | LexUnexpandedToken(Tmp); |
| 94 | |
| 95 | // There should be no tokens after the directive, but we allow them as an |
| 96 | // extension. |
| 97 | while (Tmp.is(tok::comment)) // Skip comments in -C mode. |
| 98 | LexUnexpandedToken(Tmp); |
| 99 | |
| 100 | if (Tmp.isNot(tok::eom)) { |
Chris Lattner | 56b05c8 | 2008-11-18 08:02:48 +0000 | [diff] [blame] | 101 | Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 102 | DiscardUntilEndOfDirective(); |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | |
| 107 | |
| 108 | /// SkipExcludedConditionalBlock - We just read a #if or related directive and |
| 109 | /// decided that the subsequent tokens are in the #if'd out portion of the |
| 110 | /// file. Lex the rest of the file, until we see an #endif. If |
| 111 | /// FoundNonSkipPortion is true, then we have already emitted code for part of |
| 112 | /// this #if directive, so #else/#elif blocks should never be entered. If ElseOk |
| 113 | /// is true, then #else directives are ok, if not, then we have already seen one |
| 114 | /// so a #else directive is a duplicate. When this returns, the caller can lex |
| 115 | /// the first valid token. |
| 116 | void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc, |
| 117 | bool FoundNonSkipPortion, |
| 118 | bool FoundElse) { |
| 119 | ++NumSkipped; |
Ted Kremenek | f6452c5 | 2008-11-18 01:04:47 +0000 | [diff] [blame] | 120 | assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?"); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 121 | |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 122 | CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false, |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 123 | FoundNonSkipPortion, FoundElse); |
| 124 | |
| 125 | // Enter raw mode to disable identifier lookup (and thus macro expansion), |
| 126 | // disabling warnings, etc. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 127 | CurPPLexer->LexingRawMode = true; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 128 | Token Tok; |
| 129 | while (1) { |
Ted Kremenek | f6452c5 | 2008-11-18 01:04:47 +0000 | [diff] [blame] | 130 | if (CurLexer) |
| 131 | CurLexer->Lex(Tok); |
| 132 | else |
| 133 | CurPTHLexer->Lex(Tok); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 134 | |
| 135 | // If this is the end of the buffer, we have an error. |
| 136 | if (Tok.is(tok::eof)) { |
| 137 | // Emit errors for each unterminated conditional on the stack, including |
| 138 | // the current one. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 139 | while (!CurPPLexer->ConditionalStack.empty()) { |
| 140 | Diag(CurPPLexer->ConditionalStack.back().IfLoc, |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 141 | diag::err_pp_unterminated_conditional); |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 142 | CurPPLexer->ConditionalStack.pop_back(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 143 | } |
| 144 | |
| 145 | // Just return and let the caller lex after this #include. |
| 146 | break; |
| 147 | } |
| 148 | |
| 149 | // If this token is not a preprocessor directive, just skip it. |
| 150 | if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) |
| 151 | continue; |
| 152 | |
| 153 | // We just parsed a # character at the start of a line, so we're in |
| 154 | // directive mode. Tell the lexer this so any newlines we see will be |
| 155 | // converted into an EOM token (this terminates the macro). |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 156 | CurPPLexer->ParsingPreprocessorDirective = true; |
Ted Kremenek | ac6b06d | 2008-11-18 00:43:07 +0000 | [diff] [blame] | 157 | if (CurLexer) CurLexer->SetCommentRetentionState(false); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 158 | |
| 159 | |
| 160 | // Read the next token, the directive flavor. |
| 161 | LexUnexpandedToken(Tok); |
| 162 | |
| 163 | // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or |
| 164 | // something bogus), skip it. |
| 165 | if (Tok.isNot(tok::identifier)) { |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 166 | CurPPLexer->ParsingPreprocessorDirective = false; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 167 | // Restore comment saving mode. |
Ted Kremenek | ac6b06d | 2008-11-18 00:43:07 +0000 | [diff] [blame] | 168 | if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 169 | continue; |
| 170 | } |
| 171 | |
| 172 | // If the first letter isn't i or e, it isn't intesting to us. We know that |
| 173 | // this is safe in the face of spelling differences, because there is no way |
| 174 | // to spell an i/e in a strange way that is another letter. Skipping this |
| 175 | // allows us to avoid looking up the identifier info for #define/#undef and |
| 176 | // other common directives. |
| 177 | const char *RawCharData = SourceMgr.getCharacterData(Tok.getLocation()); |
| 178 | char FirstChar = RawCharData[0]; |
| 179 | if (FirstChar >= 'a' && FirstChar <= 'z' && |
| 180 | FirstChar != 'i' && FirstChar != 'e') { |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 181 | CurPPLexer->ParsingPreprocessorDirective = false; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 182 | // Restore comment saving mode. |
Ted Kremenek | ac6b06d | 2008-11-18 00:43:07 +0000 | [diff] [blame] | 183 | if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 184 | continue; |
| 185 | } |
| 186 | |
| 187 | // Get the identifier name without trigraphs or embedded newlines. Note |
| 188 | // that we can't use Tok.getIdentifierInfo() because its lookup is disabled |
| 189 | // when skipping. |
| 190 | // TODO: could do this with zero copies in the no-clean case by using |
| 191 | // strncmp below. |
| 192 | char Directive[20]; |
| 193 | unsigned IdLen; |
| 194 | if (!Tok.needsCleaning() && Tok.getLength() < 20) { |
| 195 | IdLen = Tok.getLength(); |
| 196 | memcpy(Directive, RawCharData, IdLen); |
| 197 | Directive[IdLen] = 0; |
| 198 | } else { |
| 199 | std::string DirectiveStr = getSpelling(Tok); |
| 200 | IdLen = DirectiveStr.size(); |
| 201 | if (IdLen >= 20) { |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 202 | CurPPLexer->ParsingPreprocessorDirective = false; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 203 | // Restore comment saving mode. |
Ted Kremenek | ac6b06d | 2008-11-18 00:43:07 +0000 | [diff] [blame] | 204 | if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 205 | continue; |
| 206 | } |
| 207 | memcpy(Directive, &DirectiveStr[0], IdLen); |
| 208 | Directive[IdLen] = 0; |
| 209 | } |
| 210 | |
| 211 | if (FirstChar == 'i' && Directive[1] == 'f') { |
| 212 | if ((IdLen == 2) || // "if" |
| 213 | (IdLen == 5 && !strcmp(Directive+2, "def")) || // "ifdef" |
| 214 | (IdLen == 6 && !strcmp(Directive+2, "ndef"))) { // "ifndef" |
| 215 | // We know the entire #if/#ifdef/#ifndef block will be skipped, don't |
| 216 | // bother parsing the condition. |
| 217 | DiscardUntilEndOfDirective(); |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 218 | CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true, |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 219 | /*foundnonskip*/false, |
| 220 | /*fnddelse*/false); |
| 221 | } |
| 222 | } else if (FirstChar == 'e') { |
| 223 | if (IdLen == 5 && !strcmp(Directive+1, "ndif")) { // "endif" |
| 224 | CheckEndOfDirective("#endif"); |
| 225 | PPConditionalInfo CondInfo; |
| 226 | CondInfo.WasSkipping = true; // Silence bogus warning. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 227 | bool InCond = CurPPLexer->popConditionalLevel(CondInfo); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 228 | InCond = InCond; // Silence warning in no-asserts mode. |
| 229 | assert(!InCond && "Can't be skipping if not in a conditional!"); |
| 230 | |
| 231 | // If we popped the outermost skipping block, we're done skipping! |
| 232 | if (!CondInfo.WasSkipping) |
| 233 | break; |
| 234 | } else if (IdLen == 4 && !strcmp(Directive+1, "lse")) { // "else". |
| 235 | // #else directive in a skipping conditional. If not in some other |
| 236 | // skipping conditional, and if #else hasn't already been seen, enter it |
| 237 | // as a non-skipping conditional. |
| 238 | CheckEndOfDirective("#else"); |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 239 | PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 240 | |
| 241 | // If this is a #else with a #else before it, report the error. |
| 242 | if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else); |
| 243 | |
| 244 | // Note that we've seen a #else in this conditional. |
| 245 | CondInfo.FoundElse = true; |
| 246 | |
| 247 | // If the conditional is at the top level, and the #if block wasn't |
| 248 | // entered, enter the #else block now. |
| 249 | if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) { |
| 250 | CondInfo.FoundNonSkip = true; |
| 251 | break; |
| 252 | } |
| 253 | } else if (IdLen == 4 && !strcmp(Directive+1, "lif")) { // "elif". |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 254 | PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 255 | |
| 256 | bool ShouldEnter; |
| 257 | // If this is in a skipping block or if we're already handled this #if |
| 258 | // block, don't bother parsing the condition. |
| 259 | if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) { |
| 260 | DiscardUntilEndOfDirective(); |
| 261 | ShouldEnter = false; |
| 262 | } else { |
| 263 | // Restore the value of LexingRawMode so that identifiers are |
| 264 | // looked up, etc, inside the #elif expression. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 265 | assert(CurPPLexer->LexingRawMode && "We have to be skipping here!"); |
| 266 | CurPPLexer->LexingRawMode = false; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 267 | IdentifierInfo *IfNDefMacro = 0; |
| 268 | ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro); |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 269 | CurPPLexer->LexingRawMode = true; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 270 | } |
| 271 | |
| 272 | // If this is a #elif with a #else before it, report the error. |
| 273 | if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else); |
| 274 | |
| 275 | // If this condition is true, enter it! |
| 276 | if (ShouldEnter) { |
| 277 | CondInfo.FoundNonSkip = true; |
| 278 | break; |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 283 | CurPPLexer->ParsingPreprocessorDirective = false; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 284 | // Restore comment saving mode. |
Ted Kremenek | ac6b06d | 2008-11-18 00:43:07 +0000 | [diff] [blame] | 285 | if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 286 | } |
| 287 | |
| 288 | // Finally, if we are out of the conditional (saw an #endif or ran off the end |
| 289 | // of the file, just stop skipping and return to lexing whatever came after |
| 290 | // the #if block. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 291 | CurPPLexer->LexingRawMode = false; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 292 | } |
| 293 | |
Chris Lattner | 1072509 | 2008-03-09 04:17:44 +0000 | [diff] [blame] | 294 | /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file, |
| 295 | /// return null on failure. isAngled indicates whether the file reference is |
| 296 | /// for system #include's or not (i.e. using <> instead of ""). |
| 297 | const FileEntry *Preprocessor::LookupFile(const char *FilenameStart, |
| 298 | const char *FilenameEnd, |
| 299 | bool isAngled, |
| 300 | const DirectoryLookup *FromDir, |
| 301 | const DirectoryLookup *&CurDir) { |
| 302 | // If the header lookup mechanism may be relative to the current file, pass in |
| 303 | // info about where the current file is. |
| 304 | const FileEntry *CurFileEnt = 0; |
| 305 | if (!FromDir) { |
| 306 | SourceLocation FileLoc = getCurrentFileLexer()->getFileLoc(); |
| 307 | CurFileEnt = SourceMgr.getFileEntryForLoc(FileLoc); |
| 308 | } |
| 309 | |
| 310 | // Do a standard file entry lookup. |
| 311 | CurDir = CurDirLookup; |
| 312 | const FileEntry *FE = |
| 313 | HeaderInfo.LookupFile(FilenameStart, FilenameEnd, |
| 314 | isAngled, FromDir, CurDir, CurFileEnt); |
| 315 | if (FE) return FE; |
| 316 | |
| 317 | // Otherwise, see if this is a subframework header. If so, this is relative |
| 318 | // to one of the headers on the #include stack. Walk the list of the current |
| 319 | // headers on the #include stack and pass them to HeaderInfo. |
| 320 | if (CurLexer && !CurLexer->Is_PragmaLexer) { |
| 321 | if ((CurFileEnt = SourceMgr.getFileEntryForLoc(CurLexer->getFileLoc()))) |
| 322 | if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, FilenameEnd, |
| 323 | CurFileEnt))) |
| 324 | return FE; |
| 325 | } |
| 326 | |
| 327 | for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) { |
| 328 | IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1]; |
| 329 | if (ISEntry.TheLexer && !ISEntry.TheLexer->Is_PragmaLexer) { |
| 330 | if ((CurFileEnt = |
| 331 | SourceMgr.getFileEntryForLoc(ISEntry.TheLexer->getFileLoc()))) |
| 332 | if ((FE = HeaderInfo.LookupSubframeworkHeader(FilenameStart, |
| 333 | FilenameEnd, CurFileEnt))) |
| 334 | return FE; |
| 335 | } |
| 336 | } |
| 337 | |
| 338 | // Otherwise, we really couldn't find the file. |
| 339 | return 0; |
| 340 | } |
| 341 | |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 342 | |
| 343 | //===----------------------------------------------------------------------===// |
| 344 | // Preprocessor Directive Handling. |
| 345 | //===----------------------------------------------------------------------===// |
| 346 | |
| 347 | /// HandleDirective - This callback is invoked when the lexer sees a # token |
| 348 | /// at the start of a line. This consumes the directive, modifies the |
| 349 | /// lexer/preprocessor state, and advances the lexer(s) so that the next token |
| 350 | /// read is the correct one. |
| 351 | void Preprocessor::HandleDirective(Token &Result) { |
| 352 | // FIXME: Traditional: # with whitespace before it not recognized by K&R? |
| 353 | |
| 354 | // We just parsed a # character at the start of a line, so we're in directive |
| 355 | // mode. Tell the lexer this so any newlines we see will be converted into an |
| 356 | // EOM token (which terminates the directive). |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 357 | CurPPLexer->ParsingPreprocessorDirective = true; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 358 | |
| 359 | ++NumDirectives; |
| 360 | |
| 361 | // We are about to read a token. For the multiple-include optimization FA to |
| 362 | // work, we have to remember if we had read any tokens *before* this |
| 363 | // pp-directive. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 364 | bool ReadAnyTokensBeforeDirective = CurPPLexer->MIOpt.getHasReadAnyTokensVal(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 365 | |
| 366 | // Read the next token, the directive flavor. This isn't expanded due to |
| 367 | // C99 6.10.3p8. |
| 368 | LexUnexpandedToken(Result); |
| 369 | |
| 370 | // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.: |
| 371 | // #define A(x) #x |
| 372 | // A(abc |
| 373 | // #warning blah |
| 374 | // def) |
| 375 | // If so, the user is relying on non-portable behavior, emit a diagnostic. |
| 376 | if (InMacroArgs) |
| 377 | Diag(Result, diag::ext_embedded_directive); |
| 378 | |
| 379 | TryAgain: |
| 380 | switch (Result.getKind()) { |
| 381 | case tok::eom: |
| 382 | return; // null directive. |
| 383 | case tok::comment: |
| 384 | // Handle stuff like "# /*foo*/ define X" in -E -C mode. |
| 385 | LexUnexpandedToken(Result); |
| 386 | goto TryAgain; |
| 387 | |
| 388 | case tok::numeric_constant: |
| 389 | // FIXME: implement # 7 line numbers! |
| 390 | DiscardUntilEndOfDirective(); |
| 391 | return; |
| 392 | default: |
| 393 | IdentifierInfo *II = Result.getIdentifierInfo(); |
| 394 | if (II == 0) break; // Not an identifier. |
| 395 | |
| 396 | // Ask what the preprocessor keyword ID is. |
| 397 | switch (II->getPPKeywordID()) { |
| 398 | default: break; |
| 399 | // C99 6.10.1 - Conditional Inclusion. |
| 400 | case tok::pp_if: |
| 401 | return HandleIfDirective(Result, ReadAnyTokensBeforeDirective); |
| 402 | case tok::pp_ifdef: |
| 403 | return HandleIfdefDirective(Result, false, true/*not valid for miopt*/); |
| 404 | case tok::pp_ifndef: |
| 405 | return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective); |
| 406 | case tok::pp_elif: |
| 407 | return HandleElifDirective(Result); |
| 408 | case tok::pp_else: |
| 409 | return HandleElseDirective(Result); |
| 410 | case tok::pp_endif: |
| 411 | return HandleEndifDirective(Result); |
| 412 | |
| 413 | // C99 6.10.2 - Source File Inclusion. |
| 414 | case tok::pp_include: |
| 415 | return HandleIncludeDirective(Result); // Handle #include. |
| 416 | |
| 417 | // C99 6.10.3 - Macro Replacement. |
| 418 | case tok::pp_define: |
| 419 | return HandleDefineDirective(Result); |
| 420 | case tok::pp_undef: |
| 421 | return HandleUndefDirective(Result); |
| 422 | |
| 423 | // C99 6.10.4 - Line Control. |
| 424 | case tok::pp_line: |
| 425 | // FIXME: implement #line |
| 426 | DiscardUntilEndOfDirective(); |
| 427 | return; |
| 428 | |
| 429 | // C99 6.10.5 - Error Directive. |
| 430 | case tok::pp_error: |
| 431 | return HandleUserDiagnosticDirective(Result, false); |
| 432 | |
| 433 | // C99 6.10.6 - Pragma Directive. |
| 434 | case tok::pp_pragma: |
| 435 | return HandlePragmaDirective(); |
| 436 | |
| 437 | // GNU Extensions. |
| 438 | case tok::pp_import: |
| 439 | return HandleImportDirective(Result); |
| 440 | case tok::pp_include_next: |
| 441 | return HandleIncludeNextDirective(Result); |
| 442 | |
| 443 | case tok::pp_warning: |
| 444 | Diag(Result, diag::ext_pp_warning_directive); |
| 445 | return HandleUserDiagnosticDirective(Result, true); |
| 446 | case tok::pp_ident: |
| 447 | return HandleIdentSCCSDirective(Result); |
| 448 | case tok::pp_sccs: |
| 449 | return HandleIdentSCCSDirective(Result); |
| 450 | case tok::pp_assert: |
| 451 | //isExtension = true; // FIXME: implement #assert |
| 452 | break; |
| 453 | case tok::pp_unassert: |
| 454 | //isExtension = true; // FIXME: implement #unassert |
| 455 | break; |
| 456 | } |
| 457 | break; |
| 458 | } |
| 459 | |
| 460 | // If we reached here, the preprocessing token is not valid! |
| 461 | Diag(Result, diag::err_pp_invalid_directive); |
| 462 | |
| 463 | // Read the rest of the PP line. |
| 464 | DiscardUntilEndOfDirective(); |
| 465 | |
| 466 | // Okay, we're done parsing the directive. |
| 467 | } |
| 468 | |
| 469 | void Preprocessor::HandleUserDiagnosticDirective(Token &Tok, |
| 470 | bool isWarning) { |
| 471 | // Read the rest of the line raw. We do this because we don't want macros |
| 472 | // to be expanded and we don't require that the tokens be valid preprocessing |
| 473 | // tokens. For example, this is allowed: "#warning ` 'foo". GCC does |
| 474 | // collapse multiple consequtive white space between tokens, but this isn't |
| 475 | // specified by the standard. |
| 476 | std::string Message = CurLexer->ReadToEndOfLine(); |
| 477 | |
| 478 | unsigned DiagID = isWarning ? diag::pp_hash_warning : diag::err_pp_hash_error; |
Chris Lattner | 56b05c8 | 2008-11-18 08:02:48 +0000 | [diff] [blame] | 479 | Diag(Tok, DiagID) << Message; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 480 | } |
| 481 | |
| 482 | /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive. |
| 483 | /// |
| 484 | void Preprocessor::HandleIdentSCCSDirective(Token &Tok) { |
| 485 | // Yes, this directive is an extension. |
| 486 | Diag(Tok, diag::ext_pp_ident_directive); |
| 487 | |
| 488 | // Read the string argument. |
| 489 | Token StrTok; |
| 490 | Lex(StrTok); |
| 491 | |
| 492 | // If the token kind isn't a string, it's a malformed directive. |
| 493 | if (StrTok.isNot(tok::string_literal) && |
Chris Lattner | 3692b09 | 2008-11-18 07:59:24 +0000 | [diff] [blame] | 494 | StrTok.isNot(tok::wide_string_literal)) { |
| 495 | Diag(StrTok, diag::err_pp_malformed_ident); |
| 496 | return; |
| 497 | } |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 498 | |
| 499 | // Verify that there is nothing after the string, other than EOM. |
| 500 | CheckEndOfDirective("#ident"); |
| 501 | |
| 502 | if (Callbacks) |
| 503 | Callbacks->Ident(Tok.getLocation(), getSpelling(StrTok)); |
| 504 | } |
| 505 | |
| 506 | //===----------------------------------------------------------------------===// |
| 507 | // Preprocessor Include Directive Handling. |
| 508 | //===----------------------------------------------------------------------===// |
| 509 | |
| 510 | /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully |
| 511 | /// checked and spelled filename, e.g. as an operand of #include. This returns |
| 512 | /// true if the input filename was in <>'s or false if it were in ""'s. The |
| 513 | /// caller is expected to provide a buffer that is large enough to hold the |
| 514 | /// spelling of the filename, but is also expected to handle the case when |
| 515 | /// this method decides to use a different buffer. |
| 516 | bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc, |
| 517 | const char *&BufStart, |
| 518 | const char *&BufEnd) { |
| 519 | // Get the text form of the filename. |
| 520 | assert(BufStart != BufEnd && "Can't have tokens with empty spellings!"); |
| 521 | |
| 522 | // Make sure the filename is <x> or "x". |
| 523 | bool isAngled; |
| 524 | if (BufStart[0] == '<') { |
| 525 | if (BufEnd[-1] != '>') { |
| 526 | Diag(Loc, diag::err_pp_expects_filename); |
| 527 | BufStart = 0; |
| 528 | return true; |
| 529 | } |
| 530 | isAngled = true; |
| 531 | } else if (BufStart[0] == '"') { |
| 532 | if (BufEnd[-1] != '"') { |
| 533 | Diag(Loc, diag::err_pp_expects_filename); |
| 534 | BufStart = 0; |
| 535 | return true; |
| 536 | } |
| 537 | isAngled = false; |
| 538 | } else { |
| 539 | Diag(Loc, diag::err_pp_expects_filename); |
| 540 | BufStart = 0; |
| 541 | return true; |
| 542 | } |
| 543 | |
| 544 | // Diagnose #include "" as invalid. |
| 545 | if (BufEnd-BufStart <= 2) { |
| 546 | Diag(Loc, diag::err_pp_empty_filename); |
| 547 | BufStart = 0; |
| 548 | return ""; |
| 549 | } |
| 550 | |
| 551 | // Skip the brackets. |
| 552 | ++BufStart; |
| 553 | --BufEnd; |
| 554 | return isAngled; |
| 555 | } |
| 556 | |
| 557 | /// ConcatenateIncludeName - Handle cases where the #include name is expanded |
| 558 | /// from a macro as multiple tokens, which need to be glued together. This |
| 559 | /// occurs for code like: |
| 560 | /// #define FOO <a/b.h> |
| 561 | /// #include FOO |
| 562 | /// because in this case, "<a/b.h>" is returned as 7 tokens, not one. |
| 563 | /// |
| 564 | /// This code concatenates and consumes tokens up to the '>' token. It returns |
| 565 | /// false if the > was found, otherwise it returns true if it finds and consumes |
| 566 | /// the EOM marker. |
| 567 | static bool ConcatenateIncludeName(llvm::SmallVector<char, 128> &FilenameBuffer, |
| 568 | Preprocessor &PP) { |
| 569 | Token CurTok; |
| 570 | |
| 571 | PP.Lex(CurTok); |
| 572 | while (CurTok.isNot(tok::eom)) { |
| 573 | // Append the spelling of this token to the buffer. If there was a space |
| 574 | // before it, add it now. |
| 575 | if (CurTok.hasLeadingSpace()) |
| 576 | FilenameBuffer.push_back(' '); |
| 577 | |
| 578 | // Get the spelling of the token, directly into FilenameBuffer if possible. |
| 579 | unsigned PreAppendSize = FilenameBuffer.size(); |
| 580 | FilenameBuffer.resize(PreAppendSize+CurTok.getLength()); |
| 581 | |
| 582 | const char *BufPtr = &FilenameBuffer[PreAppendSize]; |
| 583 | unsigned ActualLen = PP.getSpelling(CurTok, BufPtr); |
| 584 | |
| 585 | // If the token was spelled somewhere else, copy it into FilenameBuffer. |
| 586 | if (BufPtr != &FilenameBuffer[PreAppendSize]) |
| 587 | memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen); |
| 588 | |
| 589 | // Resize FilenameBuffer to the correct size. |
| 590 | if (CurTok.getLength() != ActualLen) |
| 591 | FilenameBuffer.resize(PreAppendSize+ActualLen); |
| 592 | |
| 593 | // If we found the '>' marker, return success. |
| 594 | if (CurTok.is(tok::greater)) |
| 595 | return false; |
| 596 | |
| 597 | PP.Lex(CurTok); |
| 598 | } |
| 599 | |
| 600 | // If we hit the eom marker, emit an error and return true so that the caller |
| 601 | // knows the EOM has been read. |
| 602 | PP.Diag(CurTok.getLocation(), diag::err_pp_expects_filename); |
| 603 | return true; |
| 604 | } |
| 605 | |
| 606 | /// HandleIncludeDirective - The "#include" tokens have just been read, read the |
| 607 | /// file to be included from the lexer, then include it! This is a common |
| 608 | /// routine with functionality shared between #include, #include_next and |
Chris Lattner | 7218183 | 2008-09-26 20:12:23 +0000 | [diff] [blame] | 609 | /// #import. LookupFrom is set when this is a #include_next directive, it |
| 610 | /// specifies the file to start searching from. |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 611 | void Preprocessor::HandleIncludeDirective(Token &IncludeTok, |
| 612 | const DirectoryLookup *LookupFrom, |
| 613 | bool isImport) { |
| 614 | |
| 615 | Token FilenameTok; |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 616 | CurPPLexer->LexIncludeFilename(FilenameTok); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 617 | |
| 618 | // Reserve a buffer to get the spelling. |
| 619 | llvm::SmallVector<char, 128> FilenameBuffer; |
| 620 | const char *FilenameStart, *FilenameEnd; |
| 621 | |
| 622 | switch (FilenameTok.getKind()) { |
| 623 | case tok::eom: |
| 624 | // If the token kind is EOM, the error has already been diagnosed. |
| 625 | return; |
| 626 | |
| 627 | case tok::angle_string_literal: |
| 628 | case tok::string_literal: { |
| 629 | FilenameBuffer.resize(FilenameTok.getLength()); |
| 630 | FilenameStart = &FilenameBuffer[0]; |
| 631 | unsigned Len = getSpelling(FilenameTok, FilenameStart); |
| 632 | FilenameEnd = FilenameStart+Len; |
| 633 | break; |
| 634 | } |
| 635 | |
| 636 | case tok::less: |
| 637 | // This could be a <foo/bar.h> file coming from a macro expansion. In this |
| 638 | // case, glue the tokens together into FilenameBuffer and interpret those. |
| 639 | FilenameBuffer.push_back('<'); |
| 640 | if (ConcatenateIncludeName(FilenameBuffer, *this)) |
| 641 | return; // Found <eom> but no ">"? Diagnostic already emitted. |
| 642 | FilenameStart = &FilenameBuffer[0]; |
| 643 | FilenameEnd = &FilenameBuffer[FilenameBuffer.size()]; |
| 644 | break; |
| 645 | default: |
| 646 | Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename); |
| 647 | DiscardUntilEndOfDirective(); |
| 648 | return; |
| 649 | } |
| 650 | |
| 651 | bool isAngled = GetIncludeFilenameSpelling(FilenameTok.getLocation(), |
| 652 | FilenameStart, FilenameEnd); |
| 653 | // If GetIncludeFilenameSpelling set the start ptr to null, there was an |
| 654 | // error. |
| 655 | if (FilenameStart == 0) { |
| 656 | DiscardUntilEndOfDirective(); |
| 657 | return; |
| 658 | } |
| 659 | |
| 660 | // Verify that there is nothing after the filename, other than EOM. Use the |
| 661 | // preprocessor to lex this in case lexing the filename entered a macro. |
| 662 | CheckEndOfDirective("#include"); |
| 663 | |
| 664 | // Check that we don't have infinite #include recursion. |
Chris Lattner | 3692b09 | 2008-11-18 07:59:24 +0000 | [diff] [blame] | 665 | if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) { |
| 666 | Diag(FilenameTok, diag::err_pp_include_too_deep); |
| 667 | return; |
| 668 | } |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 669 | |
| 670 | // Search include directories. |
| 671 | const DirectoryLookup *CurDir; |
| 672 | const FileEntry *File = LookupFile(FilenameStart, FilenameEnd, |
| 673 | isAngled, LookupFrom, CurDir); |
Chris Lattner | 3692b09 | 2008-11-18 07:59:24 +0000 | [diff] [blame] | 674 | if (File == 0) { |
| 675 | Diag(FilenameTok, diag::err_pp_file_not_found) |
| 676 | << std::string(FilenameStart, FilenameEnd); |
| 677 | return; |
| 678 | } |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 679 | |
Chris Lattner | 7218183 | 2008-09-26 20:12:23 +0000 | [diff] [blame] | 680 | // Ask HeaderInfo if we should enter this #include file. If not, #including |
| 681 | // this file will have no effect. |
| 682 | if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 683 | return; |
Chris Lattner | 7218183 | 2008-09-26 20:12:23 +0000 | [diff] [blame] | 684 | |
| 685 | // The #included file will be considered to be a system header if either it is |
| 686 | // in a system include directory, or if the #includer is a system include |
| 687 | // header. |
Chris Lattner | 9d72851 | 2008-10-27 01:19:25 +0000 | [diff] [blame] | 688 | SrcMgr::CharacteristicKind FileCharacter = |
Chris Lattner | 0b9e736 | 2008-09-26 21:18:42 +0000 | [diff] [blame] | 689 | std::max(HeaderInfo.getFileDirFlavor(File), |
| 690 | SourceMgr.getFileCharacteristic(getCurrentFileLexer()->getFileLoc())); |
Chris Lattner | 7218183 | 2008-09-26 20:12:23 +0000 | [diff] [blame] | 691 | |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 692 | // Look up the file, create a File ID for it. |
Nico Weber | 7bfaaae | 2008-08-10 19:59:06 +0000 | [diff] [blame] | 693 | unsigned FileID = SourceMgr.createFileID(File, FilenameTok.getLocation(), |
Chris Lattner | 7218183 | 2008-09-26 20:12:23 +0000 | [diff] [blame] | 694 | FileCharacter); |
Chris Lattner | 56b05c8 | 2008-11-18 08:02:48 +0000 | [diff] [blame] | 695 | if (FileID == 0) { |
| 696 | Diag(FilenameTok, diag::err_pp_file_not_found) |
| 697 | << std::string(FilenameStart, FilenameEnd); |
| 698 | return; |
| 699 | } |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 700 | |
| 701 | // Finally, if all is good, enter the new file! |
| 702 | EnterSourceFile(FileID, CurDir); |
| 703 | } |
| 704 | |
| 705 | /// HandleIncludeNextDirective - Implements #include_next. |
| 706 | /// |
| 707 | void Preprocessor::HandleIncludeNextDirective(Token &IncludeNextTok) { |
| 708 | Diag(IncludeNextTok, diag::ext_pp_include_next_directive); |
| 709 | |
| 710 | // #include_next is like #include, except that we start searching after |
| 711 | // the current found directory. If we can't do this, issue a |
| 712 | // diagnostic. |
| 713 | const DirectoryLookup *Lookup = CurDirLookup; |
| 714 | if (isInPrimaryFile()) { |
| 715 | Lookup = 0; |
| 716 | Diag(IncludeNextTok, diag::pp_include_next_in_primary); |
| 717 | } else if (Lookup == 0) { |
| 718 | Diag(IncludeNextTok, diag::pp_include_next_absolute_path); |
| 719 | } else { |
| 720 | // Start looking up in the next directory. |
| 721 | ++Lookup; |
| 722 | } |
| 723 | |
| 724 | return HandleIncludeDirective(IncludeNextTok, Lookup); |
| 725 | } |
| 726 | |
| 727 | /// HandleImportDirective - Implements #import. |
| 728 | /// |
| 729 | void Preprocessor::HandleImportDirective(Token &ImportTok) { |
| 730 | Diag(ImportTok, diag::ext_pp_import_directive); |
| 731 | |
| 732 | return HandleIncludeDirective(ImportTok, 0, true); |
| 733 | } |
| 734 | |
| 735 | //===----------------------------------------------------------------------===// |
| 736 | // Preprocessor Macro Directive Handling. |
| 737 | //===----------------------------------------------------------------------===// |
| 738 | |
| 739 | /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro |
| 740 | /// definition has just been read. Lex the rest of the arguments and the |
| 741 | /// closing ), updating MI with what we learn. Return true if an error occurs |
| 742 | /// parsing the arg list. |
| 743 | bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) { |
| 744 | llvm::SmallVector<IdentifierInfo*, 32> Arguments; |
| 745 | |
| 746 | Token Tok; |
| 747 | while (1) { |
| 748 | LexUnexpandedToken(Tok); |
| 749 | switch (Tok.getKind()) { |
| 750 | case tok::r_paren: |
| 751 | // Found the end of the argument list. |
| 752 | if (Arguments.empty()) { // #define FOO() |
| 753 | MI->setArgumentList(Arguments.begin(), Arguments.end()); |
| 754 | return false; |
| 755 | } |
| 756 | // Otherwise we have #define FOO(A,) |
| 757 | Diag(Tok, diag::err_pp_expected_ident_in_arg_list); |
| 758 | return true; |
| 759 | case tok::ellipsis: // #define X(... -> C99 varargs |
| 760 | // Warn if use of C99 feature in non-C99 mode. |
| 761 | if (!Features.C99) Diag(Tok, diag::ext_variadic_macro); |
| 762 | |
| 763 | // Lex the token after the identifier. |
| 764 | LexUnexpandedToken(Tok); |
| 765 | if (Tok.isNot(tok::r_paren)) { |
| 766 | Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); |
| 767 | return true; |
| 768 | } |
| 769 | // Add the __VA_ARGS__ identifier as an argument. |
| 770 | Arguments.push_back(Ident__VA_ARGS__); |
| 771 | MI->setIsC99Varargs(); |
| 772 | MI->setArgumentList(Arguments.begin(), Arguments.end()); |
| 773 | return false; |
| 774 | case tok::eom: // #define X( |
| 775 | Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); |
| 776 | return true; |
| 777 | default: |
| 778 | // Handle keywords and identifiers here to accept things like |
| 779 | // #define Foo(for) for. |
| 780 | IdentifierInfo *II = Tok.getIdentifierInfo(); |
| 781 | if (II == 0) { |
| 782 | // #define X(1 |
| 783 | Diag(Tok, diag::err_pp_invalid_tok_in_arg_list); |
| 784 | return true; |
| 785 | } |
| 786 | |
| 787 | // If this is already used as an argument, it is used multiple times (e.g. |
| 788 | // #define X(A,A. |
| 789 | if (std::find(Arguments.begin(), Arguments.end(), II) != |
| 790 | Arguments.end()) { // C99 6.10.3p6 |
Chris Lattner | 56b05c8 | 2008-11-18 08:02:48 +0000 | [diff] [blame] | 791 | Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II->getName(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 792 | return true; |
| 793 | } |
| 794 | |
| 795 | // Add the argument to the macro info. |
| 796 | Arguments.push_back(II); |
| 797 | |
| 798 | // Lex the token after the identifier. |
| 799 | LexUnexpandedToken(Tok); |
| 800 | |
| 801 | switch (Tok.getKind()) { |
| 802 | default: // #define X(A B |
| 803 | Diag(Tok, diag::err_pp_expected_comma_in_arg_list); |
| 804 | return true; |
| 805 | case tok::r_paren: // #define X(A) |
| 806 | MI->setArgumentList(Arguments.begin(), Arguments.end()); |
| 807 | return false; |
| 808 | case tok::comma: // #define X(A, |
| 809 | break; |
| 810 | case tok::ellipsis: // #define X(A... -> GCC extension |
| 811 | // Diagnose extension. |
| 812 | Diag(Tok, diag::ext_named_variadic_macro); |
| 813 | |
| 814 | // Lex the token after the identifier. |
| 815 | LexUnexpandedToken(Tok); |
| 816 | if (Tok.isNot(tok::r_paren)) { |
| 817 | Diag(Tok, diag::err_pp_missing_rparen_in_macro_def); |
| 818 | return true; |
| 819 | } |
| 820 | |
| 821 | MI->setIsGNUVarargs(); |
| 822 | MI->setArgumentList(Arguments.begin(), Arguments.end()); |
| 823 | return false; |
| 824 | } |
| 825 | } |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | /// HandleDefineDirective - Implements #define. This consumes the entire macro |
| 830 | /// line then lets the caller lex the next real token. |
| 831 | void Preprocessor::HandleDefineDirective(Token &DefineTok) { |
| 832 | ++NumDefined; |
| 833 | |
| 834 | Token MacroNameTok; |
| 835 | ReadMacroName(MacroNameTok, 1); |
| 836 | |
| 837 | // Error reading macro name? If so, diagnostic already issued. |
| 838 | if (MacroNameTok.is(tok::eom)) |
| 839 | return; |
| 840 | |
| 841 | // If we are supposed to keep comments in #defines, reenable comment saving |
| 842 | // mode. |
Ted Kremenek | ac6b06d | 2008-11-18 00:43:07 +0000 | [diff] [blame] | 843 | if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 844 | |
| 845 | // Create the new macro. |
| 846 | MacroInfo *MI = new MacroInfo(MacroNameTok.getLocation()); |
| 847 | |
| 848 | Token Tok; |
| 849 | LexUnexpandedToken(Tok); |
| 850 | |
| 851 | // If this is a function-like macro definition, parse the argument list, |
| 852 | // marking each of the identifiers as being used as macro arguments. Also, |
| 853 | // check other constraints on the first token of the macro body. |
| 854 | if (Tok.is(tok::eom)) { |
| 855 | // If there is no body to this macro, we have no special handling here. |
| 856 | } else if (Tok.is(tok::l_paren) && !Tok.hasLeadingSpace()) { |
| 857 | // This is a function-like macro definition. Read the argument list. |
| 858 | MI->setIsFunctionLike(); |
| 859 | if (ReadMacroDefinitionArgList(MI)) { |
| 860 | // Forget about MI. |
| 861 | delete MI; |
| 862 | // Throw away the rest of the line. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 863 | if (CurPPLexer->ParsingPreprocessorDirective) |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 864 | DiscardUntilEndOfDirective(); |
| 865 | return; |
| 866 | } |
| 867 | |
| 868 | // Read the first token after the arg list for down below. |
| 869 | LexUnexpandedToken(Tok); |
| 870 | } else if (!Tok.hasLeadingSpace()) { |
| 871 | // C99 requires whitespace between the macro definition and the body. Emit |
| 872 | // a diagnostic for something like "#define X+". |
| 873 | if (Features.C99) { |
| 874 | Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name); |
| 875 | } else { |
| 876 | // FIXME: C90/C++ do not get this diagnostic, but it does get a similar |
| 877 | // one in some cases! |
| 878 | } |
| 879 | } else { |
| 880 | // This is a normal token with leading space. Clear the leading space |
| 881 | // marker on the first token to get proper expansion. |
| 882 | Tok.clearFlag(Token::LeadingSpace); |
| 883 | } |
| 884 | |
| 885 | // If this is a definition of a variadic C99 function-like macro, not using |
| 886 | // the GNU named varargs extension, enabled __VA_ARGS__. |
| 887 | |
| 888 | // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. |
| 889 | // This gets unpoisoned where it is allowed. |
| 890 | assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!"); |
| 891 | if (MI->isC99Varargs()) |
| 892 | Ident__VA_ARGS__->setIsPoisoned(false); |
| 893 | |
| 894 | // Read the rest of the macro body. |
| 895 | if (MI->isObjectLike()) { |
| 896 | // Object-like macros are very simple, just read their body. |
| 897 | while (Tok.isNot(tok::eom)) { |
| 898 | MI->AddTokenToBody(Tok); |
| 899 | // Get the next token of the macro. |
| 900 | LexUnexpandedToken(Tok); |
| 901 | } |
| 902 | |
| 903 | } else { |
| 904 | // Otherwise, read the body of a function-like macro. This has to validate |
| 905 | // the # (stringize) operator. |
| 906 | while (Tok.isNot(tok::eom)) { |
| 907 | MI->AddTokenToBody(Tok); |
| 908 | |
| 909 | // Check C99 6.10.3.2p1: ensure that # operators are followed by macro |
| 910 | // parameters in function-like macro expansions. |
| 911 | if (Tok.isNot(tok::hash)) { |
| 912 | // Get the next token of the macro. |
| 913 | LexUnexpandedToken(Tok); |
| 914 | continue; |
| 915 | } |
| 916 | |
| 917 | // Get the next token of the macro. |
| 918 | LexUnexpandedToken(Tok); |
| 919 | |
| 920 | // Not a macro arg identifier? |
| 921 | if (!Tok.getIdentifierInfo() || |
| 922 | MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) { |
| 923 | Diag(Tok, diag::err_pp_stringize_not_parameter); |
| 924 | delete MI; |
| 925 | |
| 926 | // Disable __VA_ARGS__ again. |
| 927 | Ident__VA_ARGS__->setIsPoisoned(true); |
| 928 | return; |
| 929 | } |
| 930 | |
| 931 | // Things look ok, add the param name token to the macro. |
| 932 | MI->AddTokenToBody(Tok); |
| 933 | |
| 934 | // Get the next token of the macro. |
| 935 | LexUnexpandedToken(Tok); |
| 936 | } |
| 937 | } |
| 938 | |
| 939 | |
| 940 | // Disable __VA_ARGS__ again. |
| 941 | Ident__VA_ARGS__->setIsPoisoned(true); |
| 942 | |
| 943 | // Check that there is no paste (##) operator at the begining or end of the |
| 944 | // replacement list. |
| 945 | unsigned NumTokens = MI->getNumTokens(); |
| 946 | if (NumTokens != 0) { |
| 947 | if (MI->getReplacementToken(0).is(tok::hashhash)) { |
| 948 | Diag(MI->getReplacementToken(0), diag::err_paste_at_start); |
| 949 | delete MI; |
| 950 | return; |
| 951 | } |
| 952 | if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) { |
| 953 | Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end); |
| 954 | delete MI; |
| 955 | return; |
| 956 | } |
| 957 | } |
| 958 | |
| 959 | // If this is the primary source file, remember that this macro hasn't been |
| 960 | // used yet. |
| 961 | if (isInPrimaryFile()) |
| 962 | MI->setIsUsed(false); |
| 963 | |
| 964 | // Finally, if this identifier already had a macro defined for it, verify that |
| 965 | // the macro bodies are identical and free the old definition. |
| 966 | if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) { |
| 967 | if (!OtherMI->isUsed()) |
| 968 | Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used); |
| 969 | |
| 970 | // Macros must be identical. This means all tokes and whitespace separation |
| 971 | // must be the same. C99 6.10.3.2. |
| 972 | if (!MI->isIdenticalTo(*OtherMI, *this)) { |
Chris Lattner | 204b2fe | 2008-11-18 21:48:13 +0000 | [diff] [blame^] | 973 | Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef) |
| 974 | << MacroNameTok.getIdentifierInfo()->getName(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 975 | Diag(OtherMI->getDefinitionLoc(), diag::ext_pp_macro_redef2); |
| 976 | } |
| 977 | delete OtherMI; |
| 978 | } |
| 979 | |
| 980 | setMacroInfo(MacroNameTok.getIdentifierInfo(), MI); |
| 981 | } |
| 982 | |
| 983 | /// HandleUndefDirective - Implements #undef. |
| 984 | /// |
| 985 | void Preprocessor::HandleUndefDirective(Token &UndefTok) { |
| 986 | ++NumUndefined; |
| 987 | |
| 988 | Token MacroNameTok; |
| 989 | ReadMacroName(MacroNameTok, 2); |
| 990 | |
| 991 | // Error reading macro name? If so, diagnostic already issued. |
| 992 | if (MacroNameTok.is(tok::eom)) |
| 993 | return; |
| 994 | |
| 995 | // Check to see if this is the last token on the #undef line. |
| 996 | CheckEndOfDirective("#undef"); |
| 997 | |
| 998 | // Okay, we finally have a valid identifier to undef. |
| 999 | MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo()); |
| 1000 | |
| 1001 | // If the macro is not defined, this is a noop undef, just return. |
| 1002 | if (MI == 0) return; |
| 1003 | |
| 1004 | if (!MI->isUsed()) |
| 1005 | Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used); |
| 1006 | |
| 1007 | // Free macro definition. |
| 1008 | delete MI; |
| 1009 | setMacroInfo(MacroNameTok.getIdentifierInfo(), 0); |
| 1010 | } |
| 1011 | |
| 1012 | |
| 1013 | //===----------------------------------------------------------------------===// |
| 1014 | // Preprocessor Conditional Directive Handling. |
| 1015 | //===----------------------------------------------------------------------===// |
| 1016 | |
| 1017 | /// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is |
| 1018 | /// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true |
| 1019 | /// if any tokens have been returned or pp-directives activated before this |
| 1020 | /// #ifndef has been lexed. |
| 1021 | /// |
| 1022 | void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef, |
| 1023 | bool ReadAnyTokensBeforeDirective) { |
| 1024 | ++NumIf; |
| 1025 | Token DirectiveTok = Result; |
| 1026 | |
| 1027 | Token MacroNameTok; |
| 1028 | ReadMacroName(MacroNameTok); |
| 1029 | |
| 1030 | // Error reading macro name? If so, diagnostic already issued. |
| 1031 | if (MacroNameTok.is(tok::eom)) { |
| 1032 | // Skip code until we get to #endif. This helps with recovery by not |
| 1033 | // emitting an error when the #endif is reached. |
| 1034 | SkipExcludedConditionalBlock(DirectiveTok.getLocation(), |
| 1035 | /*Foundnonskip*/false, /*FoundElse*/false); |
| 1036 | return; |
| 1037 | } |
| 1038 | |
| 1039 | // Check to see if this is the last token on the #if[n]def line. |
| 1040 | CheckEndOfDirective(isIfndef ? "#ifndef" : "#ifdef"); |
| 1041 | |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1042 | if (CurPPLexer->getConditionalStackDepth() == 0) { |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1043 | // If the start of a top-level #ifdef, inform MIOpt. |
| 1044 | if (!ReadAnyTokensBeforeDirective) { |
| 1045 | assert(isIfndef && "#ifdef shouldn't reach here"); |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1046 | CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MacroNameTok.getIdentifierInfo()); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1047 | } else |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1048 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1049 | } |
| 1050 | |
| 1051 | IdentifierInfo *MII = MacroNameTok.getIdentifierInfo(); |
| 1052 | MacroInfo *MI = getMacroInfo(MII); |
| 1053 | |
| 1054 | // If there is a macro, process it. |
| 1055 | if (MI) // Mark it used. |
| 1056 | MI->setIsUsed(true); |
| 1057 | |
| 1058 | // Should we include the stuff contained by this directive? |
| 1059 | if (!MI == isIfndef) { |
| 1060 | // Yes, remember that we are inside a conditional, then lex the next token. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1061 | CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(), /*wasskip*/false, |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1062 | /*foundnonskip*/true, /*foundelse*/false); |
| 1063 | } else { |
| 1064 | // No, skip the contents of this block and return the first token after it. |
| 1065 | SkipExcludedConditionalBlock(DirectiveTok.getLocation(), |
| 1066 | /*Foundnonskip*/false, |
| 1067 | /*FoundElse*/false); |
| 1068 | } |
| 1069 | } |
| 1070 | |
| 1071 | /// HandleIfDirective - Implements the #if directive. |
| 1072 | /// |
| 1073 | void Preprocessor::HandleIfDirective(Token &IfToken, |
| 1074 | bool ReadAnyTokensBeforeDirective) { |
| 1075 | ++NumIf; |
| 1076 | |
| 1077 | // Parse and evaluation the conditional expression. |
| 1078 | IdentifierInfo *IfNDefMacro = 0; |
| 1079 | bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro); |
| 1080 | |
Nuno Lopes | 0049db6 | 2008-06-01 18:31:24 +0000 | [diff] [blame] | 1081 | |
| 1082 | // If this condition is equivalent to #ifndef X, and if this is the first |
| 1083 | // directive seen, handle it for the multiple-include optimization. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1084 | if (CurPPLexer->getConditionalStackDepth() == 0) { |
Nuno Lopes | 0049db6 | 2008-06-01 18:31:24 +0000 | [diff] [blame] | 1085 | if (!ReadAnyTokensBeforeDirective && IfNDefMacro) |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1086 | CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro); |
Nuno Lopes | 0049db6 | 2008-06-01 18:31:24 +0000 | [diff] [blame] | 1087 | else |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1088 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
Nuno Lopes | 0049db6 | 2008-06-01 18:31:24 +0000 | [diff] [blame] | 1089 | } |
| 1090 | |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1091 | // Should we include the stuff contained by this directive? |
| 1092 | if (ConditionalTrue) { |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1093 | // Yes, remember that we are inside a conditional, then lex the next token. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1094 | CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false, |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1095 | /*foundnonskip*/true, /*foundelse*/false); |
| 1096 | } else { |
| 1097 | // No, skip the contents of this block and return the first token after it. |
| 1098 | SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false, |
| 1099 | /*FoundElse*/false); |
| 1100 | } |
| 1101 | } |
| 1102 | |
| 1103 | /// HandleEndifDirective - Implements the #endif directive. |
| 1104 | /// |
| 1105 | void Preprocessor::HandleEndifDirective(Token &EndifToken) { |
| 1106 | ++NumEndif; |
| 1107 | |
| 1108 | // Check that this is the whole directive. |
| 1109 | CheckEndOfDirective("#endif"); |
| 1110 | |
| 1111 | PPConditionalInfo CondInfo; |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1112 | if (CurPPLexer->popConditionalLevel(CondInfo)) { |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1113 | // No conditionals on the stack: this is an #endif without an #if. |
Chris Lattner | 3692b09 | 2008-11-18 07:59:24 +0000 | [diff] [blame] | 1114 | Diag(EndifToken, diag::err_pp_endif_without_if); |
| 1115 | return; |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1116 | } |
| 1117 | |
| 1118 | // If this the end of a top-level #endif, inform MIOpt. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1119 | if (CurPPLexer->getConditionalStackDepth() == 0) |
| 1120 | CurPPLexer->MIOpt.ExitTopLevelConditional(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1121 | |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1122 | assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode && |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1123 | "This code should only be reachable in the non-skipping case!"); |
| 1124 | } |
| 1125 | |
| 1126 | |
| 1127 | void Preprocessor::HandleElseDirective(Token &Result) { |
| 1128 | ++NumElse; |
| 1129 | |
| 1130 | // #else directive in a non-skipping conditional... start skipping. |
| 1131 | CheckEndOfDirective("#else"); |
| 1132 | |
| 1133 | PPConditionalInfo CI; |
Chris Lattner | 3692b09 | 2008-11-18 07:59:24 +0000 | [diff] [blame] | 1134 | if (CurPPLexer->popConditionalLevel(CI)) { |
| 1135 | Diag(Result, diag::pp_err_else_without_if); |
| 1136 | return; |
| 1137 | } |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1138 | |
| 1139 | // If this is a top-level #else, inform the MIOpt. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1140 | if (CurPPLexer->getConditionalStackDepth() == 0) |
| 1141 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1142 | |
| 1143 | // If this is a #else with a #else before it, report the error. |
| 1144 | if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else); |
| 1145 | |
| 1146 | // Finally, skip the rest of the contents of this block and return the first |
| 1147 | // token after it. |
| 1148 | return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, |
| 1149 | /*FoundElse*/true); |
| 1150 | } |
| 1151 | |
| 1152 | void Preprocessor::HandleElifDirective(Token &ElifToken) { |
| 1153 | ++NumElse; |
| 1154 | |
| 1155 | // #elif directive in a non-skipping conditional... start skipping. |
| 1156 | // We don't care what the condition is, because we will always skip it (since |
| 1157 | // the block immediately before it was included). |
| 1158 | DiscardUntilEndOfDirective(); |
| 1159 | |
| 1160 | PPConditionalInfo CI; |
Chris Lattner | 3692b09 | 2008-11-18 07:59:24 +0000 | [diff] [blame] | 1161 | if (CurPPLexer->popConditionalLevel(CI)) { |
| 1162 | Diag(ElifToken, diag::pp_err_elif_without_if); |
| 1163 | return; |
| 1164 | } |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1165 | |
| 1166 | // If this is a top-level #elif, inform the MIOpt. |
Ted Kremenek | 60e45d4 | 2008-11-18 00:34:22 +0000 | [diff] [blame] | 1167 | if (CurPPLexer->getConditionalStackDepth() == 0) |
| 1168 | CurPPLexer->MIOpt.EnterTopLevelConditional(); |
Chris Lattner | 141e71f | 2008-03-09 01:54:53 +0000 | [diff] [blame] | 1169 | |
| 1170 | // If this is a #elif with a #else before it, report the error. |
| 1171 | if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else); |
| 1172 | |
| 1173 | // Finally, skip the rest of the contents of this block and return the first |
| 1174 | // token after it. |
| 1175 | return SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true, |
| 1176 | /*FoundElse*/CI.FoundElse); |
| 1177 | } |
| 1178 | |