Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 1 | //===--- MacroExpander.cpp - Lex from a macro expansion -------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file was developed by Chris Lattner and is distributed under |
| 6 | // the University of Illinois Open Source License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements the MacroExpander interface. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "clang/Lex/MacroExpander.h" |
| 15 | #include "clang/Lex/MacroInfo.h" |
| 16 | #include "clang/Lex/Preprocessor.h" |
| 17 | #include "clang/Basic/SourceManager.h" |
| 18 | #include "clang/Basic/Diagnostic.h" |
| 19 | #include "llvm/ADT/SmallVector.h" |
| 20 | using namespace clang; |
| 21 | |
| 22 | //===----------------------------------------------------------------------===// |
| 23 | // MacroArgs Implementation |
| 24 | //===----------------------------------------------------------------------===// |
| 25 | |
| 26 | /// MacroArgs ctor function - This destroys the vector passed in. |
| 27 | MacroArgs *MacroArgs::create(const MacroInfo *MI, |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 28 | const Token *UnexpArgTokens, |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 29 | unsigned NumToks, bool VarargsElided) { |
| 30 | assert(MI->isFunctionLike() && |
| 31 | "Can't have args for an object-like macro!"); |
| 32 | |
| 33 | // Allocate memory for the MacroArgs object with the lexer tokens at the end. |
| 34 | MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) + |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 35 | NumToks*sizeof(Token)); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 36 | // Construct the macroargs object. |
| 37 | new (Result) MacroArgs(NumToks, VarargsElided); |
| 38 | |
| 39 | // Copy the actual unexpanded tokens to immediately after the result ptr. |
| 40 | if (NumToks) |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 41 | memcpy(const_cast<Token*>(Result->getUnexpArgument(0)), |
| 42 | UnexpArgTokens, NumToks*sizeof(Token)); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 43 | |
| 44 | return Result; |
| 45 | } |
| 46 | |
| 47 | /// destroy - Destroy and deallocate the memory for this object. |
| 48 | /// |
| 49 | void MacroArgs::destroy() { |
| 50 | // Run the dtor to deallocate the vectors. |
| 51 | this->~MacroArgs(); |
| 52 | // Release the memory for the object. |
| 53 | free(this); |
| 54 | } |
| 55 | |
| 56 | |
| 57 | /// getArgLength - Given a pointer to an expanded or unexpanded argument, |
| 58 | /// return the number of tokens, not counting the EOF, that make up the |
| 59 | /// argument. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 60 | unsigned MacroArgs::getArgLength(const Token *ArgPtr) { |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 61 | unsigned NumArgTokens = 0; |
| 62 | for (; ArgPtr->getKind() != tok::eof; ++ArgPtr) |
| 63 | ++NumArgTokens; |
| 64 | return NumArgTokens; |
| 65 | } |
| 66 | |
| 67 | |
| 68 | /// getUnexpArgument - Return the unexpanded tokens for the specified formal. |
| 69 | /// |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 70 | const Token *MacroArgs::getUnexpArgument(unsigned Arg) const { |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 71 | // The unexpanded argument tokens start immediately after the MacroArgs object |
| 72 | // in memory. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 73 | const Token *Start = (const Token *)(this+1); |
| 74 | const Token *Result = Start; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 75 | // Scan to find Arg. |
| 76 | for (; Arg; ++Result) { |
| 77 | assert(Result < Start+NumUnexpArgTokens && "Invalid arg #"); |
| 78 | if (Result->getKind() == tok::eof) |
| 79 | --Arg; |
| 80 | } |
| 81 | return Result; |
| 82 | } |
| 83 | |
| 84 | |
| 85 | /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected |
| 86 | /// by pre-expansion, return false. Otherwise, conservatively return true. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 87 | bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok) const { |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 88 | // If there are no identifiers in the argument list, or if the identifiers are |
| 89 | // known to not be macros, pre-expansion won't modify it. |
| 90 | for (; ArgTok->getKind() != tok::eof; ++ArgTok) |
| 91 | if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) { |
| 92 | if (II->getMacroInfo() && II->getMacroInfo()->isEnabled()) |
| 93 | // Return true even though the macro could be a function-like macro |
| 94 | // without a following '(' token. |
| 95 | return true; |
| 96 | } |
| 97 | return false; |
| 98 | } |
| 99 | |
| 100 | /// getPreExpArgument - Return the pre-expanded form of the specified |
| 101 | /// argument. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 102 | const std::vector<Token> & |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 103 | MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) { |
| 104 | assert(Arg < NumUnexpArgTokens && "Invalid argument number!"); |
| 105 | |
| 106 | // If we have already computed this, return it. |
| 107 | if (PreExpArgTokens.empty()) |
| 108 | PreExpArgTokens.resize(NumUnexpArgTokens); |
| 109 | |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 110 | std::vector<Token> &Result = PreExpArgTokens[Arg]; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 111 | if (!Result.empty()) return Result; |
| 112 | |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 113 | const Token *AT = getUnexpArgument(Arg); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 114 | unsigned NumToks = getArgLength(AT)+1; // Include the EOF. |
| 115 | |
| 116 | // Otherwise, we have to pre-expand this argument, populating Result. To do |
| 117 | // this, we set up a fake MacroExpander to lex from the unexpanded argument |
| 118 | // list. With this installed, we lex expanded tokens until we hit the EOF |
| 119 | // token at the end of the unexp list. |
| 120 | PP.EnterTokenStream(AT, NumToks); |
| 121 | |
| 122 | // Lex all of the macro-expanded tokens into Result. |
| 123 | do { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 124 | Result.push_back(Token()); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 125 | PP.Lex(Result.back()); |
| 126 | } while (Result.back().getKind() != tok::eof); |
| 127 | |
| 128 | // Pop the token stream off the top of the stack. We know that the internal |
| 129 | // pointer inside of it is to the "end" of the token stream, but the stack |
| 130 | // will not otherwise be popped until the next token is lexed. The problem is |
| 131 | // that the token may be lexed sometime after the vector of tokens itself is |
| 132 | // destroyed, which would be badness. |
| 133 | PP.RemoveTopOfLexerStack(); |
| 134 | return Result; |
| 135 | } |
| 136 | |
| 137 | |
| 138 | /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of |
| 139 | /// tokens into the literal string token that should be produced by the C # |
| 140 | /// preprocessor operator. |
| 141 | /// |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 142 | static Token StringifyArgument(const Token *ArgToks, |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 143 | Preprocessor &PP, bool Charify = false) { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 144 | Token Tok; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 145 | Tok.startToken(); |
| 146 | Tok.setKind(tok::string_literal); |
| 147 | |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 148 | const Token *ArgTokStart = ArgToks; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 149 | |
| 150 | // Stringify all the tokens. |
| 151 | std::string Result = "\""; |
| 152 | // FIXME: Optimize this loop to not use std::strings. |
| 153 | bool isFirst = true; |
| 154 | for (; ArgToks->getKind() != tok::eof; ++ArgToks) { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 155 | const Token &Tok = *ArgToks; |
Chris Lattner | 2b64fdc | 2007-07-19 16:11:58 +0000 | [diff] [blame] | 156 | if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine())) |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 157 | Result += ' '; |
| 158 | isFirst = false; |
| 159 | |
| 160 | // If this is a string or character constant, escape the token as specified |
| 161 | // by 6.10.3.2p2. |
| 162 | if (Tok.getKind() == tok::string_literal || // "foo" |
| 163 | Tok.getKind() == tok::wide_string_literal || // L"foo" |
| 164 | Tok.getKind() == tok::char_constant) { // 'x' and L'x'. |
| 165 | Result += Lexer::Stringify(PP.getSpelling(Tok)); |
| 166 | } else { |
| 167 | // Otherwise, just append the token. |
| 168 | Result += PP.getSpelling(Tok); |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | // If the last character of the string is a \, and if it isn't escaped, this |
| 173 | // is an invalid string literal, diagnose it as specified in C99. |
| 174 | if (Result[Result.size()-1] == '\\') { |
| 175 | // Count the number of consequtive \ characters. If even, then they are |
| 176 | // just escaped backslashes, otherwise it's an error. |
| 177 | unsigned FirstNonSlash = Result.size()-2; |
| 178 | // Guaranteed to find the starting " if nothing else. |
| 179 | while (Result[FirstNonSlash] == '\\') |
| 180 | --FirstNonSlash; |
| 181 | if ((Result.size()-1-FirstNonSlash) & 1) { |
| 182 | // Diagnose errors for things like: #define F(X) #X / F(\) |
| 183 | PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal); |
| 184 | Result.erase(Result.end()-1); // remove one of the \'s. |
| 185 | } |
| 186 | } |
| 187 | Result += '"'; |
| 188 | |
| 189 | // If this is the charify operation and the result is not a legal character |
| 190 | // constant, diagnose it. |
| 191 | if (Charify) { |
| 192 | // First step, turn double quotes into single quotes: |
| 193 | Result[0] = '\''; |
| 194 | Result[Result.size()-1] = '\''; |
| 195 | |
| 196 | // Check for bogus character. |
| 197 | bool isBad = false; |
| 198 | if (Result.size() == 3) { |
| 199 | isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above. |
| 200 | } else { |
| 201 | isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x' |
| 202 | } |
| 203 | |
| 204 | if (isBad) { |
| 205 | PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify); |
| 206 | Result = "' '"; // Use something arbitrary, but legal. |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | Tok.setLength(Result.size()); |
| 211 | Tok.setLocation(PP.CreateString(&Result[0], Result.size())); |
| 212 | return Tok; |
| 213 | } |
| 214 | |
| 215 | /// getStringifiedArgument - Compute, cache, and return the specified argument |
| 216 | /// that has been 'stringified' as required by the # operator. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 217 | const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo, |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 218 | Preprocessor &PP) { |
| 219 | assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!"); |
| 220 | if (StringifiedArgs.empty()) { |
| 221 | StringifiedArgs.resize(getNumArguments()); |
| 222 | memset(&StringifiedArgs[0], 0, |
| 223 | sizeof(StringifiedArgs[0])*getNumArguments()); |
| 224 | } |
| 225 | if (StringifiedArgs[ArgNo].getKind() != tok::string_literal) |
| 226 | StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP); |
| 227 | return StringifiedArgs[ArgNo]; |
| 228 | } |
| 229 | |
| 230 | //===----------------------------------------------------------------------===// |
| 231 | // MacroExpander Implementation |
| 232 | //===----------------------------------------------------------------------===// |
| 233 | |
| 234 | /// Create a macro expander for the specified macro with the specified actual |
| 235 | /// arguments. Note that this ctor takes ownership of the ActualArgs pointer. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 236 | void MacroExpander::Init(Token &Tok, MacroArgs *Actuals) { |
Chris Lattner | 9594acf | 2007-07-15 00:25:26 +0000 | [diff] [blame] | 237 | // If the client is reusing a macro expander, make sure to free any memory |
| 238 | // associated with it. |
| 239 | destroy(); |
| 240 | |
| 241 | Macro = Tok.getIdentifierInfo()->getMacroInfo(); |
| 242 | ActualArgs = Actuals; |
| 243 | CurToken = 0; |
| 244 | InstantiateLoc = Tok.getLocation(); |
| 245 | AtStartOfLine = Tok.isAtStartOfLine(); |
| 246 | HasLeadingSpace = Tok.hasLeadingSpace(); |
Chris Lattner | c215bd6 | 2007-07-14 22:11:41 +0000 | [diff] [blame] | 247 | MacroTokens = &*Macro->tokens_begin(); |
Chris Lattner | 9c68306 | 2007-07-22 01:16:55 +0000 | [diff] [blame^] | 248 | OwnsMacroTokens = false; |
Chris Lattner | c215bd6 | 2007-07-14 22:11:41 +0000 | [diff] [blame] | 249 | NumMacroTokens = Macro->tokens_end()-Macro->tokens_begin(); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 250 | |
| 251 | // If this is a function-like macro, expand the arguments and change |
| 252 | // MacroTokens to point to the expanded tokens. |
| 253 | if (Macro->isFunctionLike() && Macro->getNumArgs()) |
| 254 | ExpandFunctionArguments(); |
| 255 | |
| 256 | // Mark the macro as currently disabled, so that it is not recursively |
| 257 | // expanded. The macro must be disabled only after argument pre-expansion of |
| 258 | // function-like macro arguments occurs. |
| 259 | Macro->DisableMacro(); |
| 260 | } |
| 261 | |
Chris Lattner | 9594acf | 2007-07-15 00:25:26 +0000 | [diff] [blame] | 262 | |
| 263 | |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 264 | /// Create a macro expander for the specified token stream. This does not |
| 265 | /// take ownership of the specified token vector. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 266 | void MacroExpander::Init(const Token *TokArray, unsigned NumToks) { |
Chris Lattner | 9594acf | 2007-07-15 00:25:26 +0000 | [diff] [blame] | 267 | // If the client is reusing a macro expander, make sure to free any memory |
| 268 | // associated with it. |
| 269 | destroy(); |
| 270 | |
| 271 | Macro = 0; |
| 272 | ActualArgs = 0; |
| 273 | MacroTokens = TokArray; |
Chris Lattner | 9c68306 | 2007-07-22 01:16:55 +0000 | [diff] [blame^] | 274 | OwnsMacroTokens = false; |
Chris Lattner | 9594acf | 2007-07-15 00:25:26 +0000 | [diff] [blame] | 275 | NumMacroTokens = NumToks; |
| 276 | CurToken = 0; |
| 277 | InstantiateLoc = SourceLocation(); |
| 278 | AtStartOfLine = false; |
| 279 | HasLeadingSpace = false; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 280 | |
| 281 | // Set HasLeadingSpace/AtStartOfLine so that the first token will be |
| 282 | // returned unmodified. |
| 283 | if (NumToks != 0) { |
| 284 | AtStartOfLine = TokArray[0].isAtStartOfLine(); |
| 285 | HasLeadingSpace = TokArray[0].hasLeadingSpace(); |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | |
Chris Lattner | 9594acf | 2007-07-15 00:25:26 +0000 | [diff] [blame] | 290 | void MacroExpander::destroy() { |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 291 | // If this was a function-like macro that actually uses its arguments, delete |
| 292 | // the expanded tokens. |
Chris Lattner | 9c68306 | 2007-07-22 01:16:55 +0000 | [diff] [blame^] | 293 | if (OwnsMacroTokens) { |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 294 | delete [] MacroTokens; |
Chris Lattner | 9c68306 | 2007-07-22 01:16:55 +0000 | [diff] [blame^] | 295 | MacroTokens = 0; |
| 296 | } |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 297 | |
| 298 | // MacroExpander owns its formal arguments. |
| 299 | if (ActualArgs) ActualArgs->destroy(); |
| 300 | } |
| 301 | |
| 302 | /// Expand the arguments of a function-like macro so that we can quickly |
| 303 | /// return preexpanded tokens from MacroTokens. |
| 304 | void MacroExpander::ExpandFunctionArguments() { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 305 | llvm::SmallVector<Token, 128> ResultToks; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 306 | |
| 307 | // Loop through the MacroTokens tokens, expanding them into ResultToks. Keep |
| 308 | // track of whether we change anything. If not, no need to keep them. If so, |
| 309 | // we install the newly expanded sequence as MacroTokens. |
| 310 | bool MadeChange = false; |
| 311 | |
| 312 | // NextTokGetsSpace - When this is true, the next token appended to the |
| 313 | // output list will get a leading space, regardless of whether it had one to |
| 314 | // begin with or not. This is used for placemarker support. |
| 315 | bool NextTokGetsSpace = false; |
| 316 | |
| 317 | for (unsigned i = 0, e = NumMacroTokens; i != e; ++i) { |
| 318 | // If we found the stringify operator, get the argument stringified. The |
| 319 | // preprocessor already verified that the following token is a macro name |
| 320 | // when the #define was parsed. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 321 | const Token &CurTok = MacroTokens[i]; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 322 | if (CurTok.getKind() == tok::hash || CurTok.getKind() == tok::hashat) { |
| 323 | int ArgNo = Macro->getArgumentNum(MacroTokens[i+1].getIdentifierInfo()); |
| 324 | assert(ArgNo != -1 && "Token following # is not an argument?"); |
| 325 | |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 326 | Token Res; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 327 | if (CurTok.getKind() == tok::hash) // Stringify |
| 328 | Res = ActualArgs->getStringifiedArgument(ArgNo, PP); |
| 329 | else { |
| 330 | // 'charify': don't bother caching these. |
| 331 | Res = StringifyArgument(ActualArgs->getUnexpArgument(ArgNo), PP, true); |
| 332 | } |
| 333 | |
| 334 | // The stringified/charified string leading space flag gets set to match |
| 335 | // the #/#@ operator. |
| 336 | if (CurTok.hasLeadingSpace() || NextTokGetsSpace) |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 337 | Res.setFlag(Token::LeadingSpace); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 338 | |
| 339 | ResultToks.push_back(Res); |
| 340 | MadeChange = true; |
| 341 | ++i; // Skip arg name. |
| 342 | NextTokGetsSpace = false; |
| 343 | continue; |
| 344 | } |
| 345 | |
| 346 | // Otherwise, if this is not an argument token, just add the token to the |
| 347 | // output buffer. |
| 348 | IdentifierInfo *II = CurTok.getIdentifierInfo(); |
| 349 | int ArgNo = II ? Macro->getArgumentNum(II) : -1; |
| 350 | if (ArgNo == -1) { |
| 351 | // This isn't an argument, just add it. |
| 352 | ResultToks.push_back(CurTok); |
| 353 | |
| 354 | if (NextTokGetsSpace) { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 355 | ResultToks.back().setFlag(Token::LeadingSpace); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 356 | NextTokGetsSpace = false; |
| 357 | } |
| 358 | continue; |
| 359 | } |
| 360 | |
| 361 | // An argument is expanded somehow, the result is different than the |
| 362 | // input. |
| 363 | MadeChange = true; |
| 364 | |
| 365 | // Otherwise, this is a use of the argument. Find out if there is a paste |
| 366 | // (##) operator before or after the argument. |
| 367 | bool PasteBefore = |
| 368 | !ResultToks.empty() && ResultToks.back().getKind() == tok::hashhash; |
| 369 | bool PasteAfter = i+1 != e && MacroTokens[i+1].getKind() == tok::hashhash; |
| 370 | |
| 371 | // If it is not the LHS/RHS of a ## operator, we must pre-expand the |
| 372 | // argument and substitute the expanded tokens into the result. This is |
| 373 | // C99 6.10.3.1p1. |
| 374 | if (!PasteBefore && !PasteAfter) { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 375 | const Token *ResultArgToks; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 376 | |
| 377 | // Only preexpand the argument if it could possibly need it. This |
| 378 | // avoids some work in common cases. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 379 | const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 380 | if (ActualArgs->ArgNeedsPreexpansion(ArgTok)) |
| 381 | ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0]; |
| 382 | else |
| 383 | ResultArgToks = ArgTok; // Use non-preexpanded tokens. |
| 384 | |
| 385 | // If the arg token expanded into anything, append it. |
| 386 | if (ResultArgToks->getKind() != tok::eof) { |
| 387 | unsigned FirstResult = ResultToks.size(); |
| 388 | unsigned NumToks = MacroArgs::getArgLength(ResultArgToks); |
| 389 | ResultToks.append(ResultArgToks, ResultArgToks+NumToks); |
| 390 | |
| 391 | // If any tokens were substituted from the argument, the whitespace |
| 392 | // before the first token should match the whitespace of the arg |
| 393 | // identifier. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 394 | ResultToks[FirstResult].setFlagValue(Token::LeadingSpace, |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 395 | CurTok.hasLeadingSpace() || |
| 396 | NextTokGetsSpace); |
| 397 | NextTokGetsSpace = false; |
| 398 | } else { |
| 399 | // If this is an empty argument, and if there was whitespace before the |
| 400 | // formal token, make sure the next token gets whitespace before it. |
| 401 | NextTokGetsSpace = CurTok.hasLeadingSpace(); |
| 402 | } |
| 403 | continue; |
| 404 | } |
| 405 | |
| 406 | // Okay, we have a token that is either the LHS or RHS of a paste (##) |
| 407 | // argument. It gets substituted as its non-pre-expanded tokens. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 408 | const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 409 | unsigned NumToks = MacroArgs::getArgLength(ArgToks); |
| 410 | if (NumToks) { // Not an empty argument? |
| 411 | ResultToks.append(ArgToks, ArgToks+NumToks); |
| 412 | |
| 413 | // If the next token was supposed to get leading whitespace, ensure it has |
| 414 | // it now. |
| 415 | if (NextTokGetsSpace) { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 416 | ResultToks[ResultToks.size()-NumToks].setFlag(Token::LeadingSpace); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 417 | NextTokGetsSpace = false; |
| 418 | } |
| 419 | continue; |
| 420 | } |
| 421 | |
| 422 | // If an empty argument is on the LHS or RHS of a paste, the standard (C99 |
| 423 | // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur. We |
| 424 | // implement this by eating ## operators when a LHS or RHS expands to |
| 425 | // empty. |
| 426 | NextTokGetsSpace |= CurTok.hasLeadingSpace(); |
| 427 | if (PasteAfter) { |
| 428 | // Discard the argument token and skip (don't copy to the expansion |
| 429 | // buffer) the paste operator after it. |
| 430 | NextTokGetsSpace |= MacroTokens[i+1].hasLeadingSpace(); |
| 431 | ++i; |
| 432 | continue; |
| 433 | } |
| 434 | |
| 435 | // If this is on the RHS of a paste operator, we've already copied the |
| 436 | // paste operator to the ResultToks list. Remove it. |
| 437 | assert(PasteBefore && ResultToks.back().getKind() == tok::hashhash); |
| 438 | NextTokGetsSpace |= ResultToks.back().hasLeadingSpace(); |
| 439 | ResultToks.pop_back(); |
| 440 | |
| 441 | // If this is the __VA_ARGS__ token, and if the argument wasn't provided, |
| 442 | // and if the macro had at least one real argument, and if the token before |
| 443 | // the ## was a comma, remove the comma. |
| 444 | if ((unsigned)ArgNo == Macro->getNumArgs()-1 && // is __VA_ARGS__ |
| 445 | ActualArgs->isVarargsElidedUse() && // Argument elided. |
| 446 | !ResultToks.empty() && ResultToks.back().getKind() == tok::comma) { |
| 447 | // Never add a space, even if the comma, ##, or arg had a space. |
| 448 | NextTokGetsSpace = false; |
| 449 | ResultToks.pop_back(); |
| 450 | } |
| 451 | continue; |
| 452 | } |
| 453 | |
| 454 | // If anything changed, install this as the new MacroTokens list. |
| 455 | if (MadeChange) { |
| 456 | // This is deleted in the dtor. |
| 457 | NumMacroTokens = ResultToks.size(); |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 458 | Token *Res = new Token[ResultToks.size()]; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 459 | if (NumMacroTokens) |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 460 | memcpy(Res, &ResultToks[0], NumMacroTokens*sizeof(Token)); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 461 | MacroTokens = Res; |
Chris Lattner | 9c68306 | 2007-07-22 01:16:55 +0000 | [diff] [blame^] | 462 | OwnsMacroTokens = true; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 463 | } |
| 464 | } |
| 465 | |
| 466 | /// Lex - Lex and return a token from this macro stream. |
| 467 | /// |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 468 | void MacroExpander::Lex(Token &Tok) { |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 469 | // Lexing off the end of the macro, pop this macro off the expansion stack. |
| 470 | if (isAtEnd()) { |
| 471 | // If this is a macro (not a token stream), mark the macro enabled now |
| 472 | // that it is no longer being expanded. |
| 473 | if (Macro) Macro->EnableMacro(); |
| 474 | |
| 475 | // Pop this context off the preprocessors lexer stack and get the next |
| 476 | // token. This will delete "this" so remember the PP instance var. |
| 477 | Preprocessor &PPCache = PP; |
| 478 | if (PP.HandleEndOfMacro(Tok)) |
| 479 | return; |
| 480 | |
| 481 | // HandleEndOfMacro may not return a token. If it doesn't, lex whatever is |
| 482 | // next. |
| 483 | return PPCache.Lex(Tok); |
| 484 | } |
| 485 | |
| 486 | // If this is the first token of the expanded result, we inherit spacing |
| 487 | // properties later. |
| 488 | bool isFirstToken = CurToken == 0; |
| 489 | |
| 490 | // Get the next token to return. |
| 491 | Tok = MacroTokens[CurToken++]; |
| 492 | |
| 493 | // If this token is followed by a token paste (##) operator, paste the tokens! |
| 494 | if (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash) |
| 495 | PasteTokens(Tok); |
| 496 | |
| 497 | // The token's current location indicate where the token was lexed from. We |
| 498 | // need this information to compute the spelling of the token, but any |
| 499 | // diagnostics for the expanded token should appear as if they came from |
| 500 | // InstantiationLoc. Pull this information together into a new SourceLocation |
| 501 | // that captures all of this. |
| 502 | if (InstantiateLoc.isValid()) { // Don't do this for token streams. |
| 503 | SourceManager &SrcMgr = PP.getSourceManager(); |
Chris Lattner | abca2bb | 2007-07-15 06:35:27 +0000 | [diff] [blame] | 504 | Tok.setLocation(SrcMgr.getInstantiationLoc(Tok.getLocation(), |
| 505 | InstantiateLoc)); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 506 | } |
| 507 | |
| 508 | // If this is the first token, set the lexical properties of the token to |
| 509 | // match the lexical properties of the macro identifier. |
| 510 | if (isFirstToken) { |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 511 | Tok.setFlagValue(Token::StartOfLine , AtStartOfLine); |
| 512 | Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 513 | } |
| 514 | |
| 515 | // Handle recursive expansion! |
| 516 | if (Tok.getIdentifierInfo()) |
| 517 | return PP.HandleIdentifier(Tok); |
| 518 | |
| 519 | // Otherwise, return a normal token. |
| 520 | } |
| 521 | |
| 522 | /// PasteTokens - Tok is the LHS of a ## operator, and CurToken is the ## |
| 523 | /// operator. Read the ## and RHS, and paste the LHS/RHS together. If there |
| 524 | /// are is another ## after it, chomp it iteratively. Return the result as Tok. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 525 | void MacroExpander::PasteTokens(Token &Tok) { |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 526 | llvm::SmallVector<char, 128> Buffer; |
| 527 | do { |
| 528 | // Consume the ## operator. |
| 529 | SourceLocation PasteOpLoc = MacroTokens[CurToken].getLocation(); |
| 530 | ++CurToken; |
| 531 | assert(!isAtEnd() && "No token on the RHS of a paste operator!"); |
| 532 | |
| 533 | // Get the RHS token. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 534 | const Token &RHS = MacroTokens[CurToken]; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 535 | |
| 536 | bool isInvalid = false; |
| 537 | |
| 538 | // Allocate space for the result token. This is guaranteed to be enough for |
| 539 | // the two tokens and a null terminator. |
| 540 | Buffer.resize(Tok.getLength() + RHS.getLength() + 1); |
| 541 | |
| 542 | // Get the spelling of the LHS token in Buffer. |
| 543 | const char *BufPtr = &Buffer[0]; |
| 544 | unsigned LHSLen = PP.getSpelling(Tok, BufPtr); |
| 545 | if (BufPtr != &Buffer[0]) // Really, we want the chars in Buffer! |
| 546 | memcpy(&Buffer[0], BufPtr, LHSLen); |
| 547 | |
| 548 | BufPtr = &Buffer[LHSLen]; |
| 549 | unsigned RHSLen = PP.getSpelling(RHS, BufPtr); |
| 550 | if (BufPtr != &Buffer[LHSLen]) // Really, we want the chars in Buffer! |
| 551 | memcpy(&Buffer[LHSLen], BufPtr, RHSLen); |
| 552 | |
| 553 | // Add null terminator. |
| 554 | Buffer[LHSLen+RHSLen] = '\0'; |
| 555 | |
| 556 | // Trim excess space. |
| 557 | Buffer.resize(LHSLen+RHSLen+1); |
| 558 | |
| 559 | // Plop the pasted result (including the trailing newline and null) into a |
| 560 | // scratch buffer where we can lex it. |
| 561 | SourceLocation ResultTokLoc = PP.CreateString(&Buffer[0], Buffer.size()); |
| 562 | |
| 563 | // Lex the resultant pasted token into Result. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 564 | Token Result; |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 565 | |
| 566 | // Avoid testing /*, as the lexer would think it is the start of a comment |
| 567 | // and emit an error that it is unterminated. |
| 568 | if (Tok.getKind() == tok::slash && RHS.getKind() == tok::star) { |
| 569 | isInvalid = true; |
| 570 | } else if (Tok.getKind() == tok::identifier && |
| 571 | RHS.getKind() == tok::identifier) { |
| 572 | // Common paste case: identifier+identifier = identifier. Avoid creating |
| 573 | // a lexer and other overhead. |
| 574 | PP.IncrementPasteCounter(true); |
| 575 | Result.startToken(); |
| 576 | Result.setKind(tok::identifier); |
| 577 | Result.setLocation(ResultTokLoc); |
| 578 | Result.setLength(LHSLen+RHSLen); |
| 579 | } else { |
| 580 | PP.IncrementPasteCounter(false); |
| 581 | |
| 582 | // Make a lexer to lex this string from. |
| 583 | SourceManager &SourceMgr = PP.getSourceManager(); |
| 584 | const char *ResultStrData = SourceMgr.getCharacterData(ResultTokLoc); |
| 585 | |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 586 | // Make a lexer object so that we lex and expand the paste result. |
Chris Lattner | 25bdb51 | 2007-07-20 16:52:03 +0000 | [diff] [blame] | 587 | Lexer *TL = new Lexer(ResultTokLoc, PP, ResultStrData, |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 588 | ResultStrData+LHSLen+RHSLen /*don't include null*/); |
| 589 | |
| 590 | // Lex a token in raw mode. This way it won't look up identifiers |
| 591 | // automatically, lexing off the end will return an eof token, and |
| 592 | // warnings are disabled. This returns true if the result token is the |
| 593 | // entire buffer. |
| 594 | bool IsComplete = TL->LexRawToken(Result); |
| 595 | |
| 596 | // If we got an EOF token, we didn't form even ONE token. For example, we |
| 597 | // did "/ ## /" to get "//". |
| 598 | IsComplete &= Result.getKind() != tok::eof; |
| 599 | isInvalid = !IsComplete; |
| 600 | |
| 601 | // We're now done with the temporary lexer. |
| 602 | delete TL; |
| 603 | } |
| 604 | |
| 605 | // If pasting the two tokens didn't form a full new token, this is an error. |
| 606 | // This occurs with "x ## +" and other stuff. Return with Tok unmodified |
| 607 | // and with RHS as the next token to lex. |
| 608 | if (isInvalid) { |
| 609 | // If not in assembler language mode. |
| 610 | PP.Diag(PasteOpLoc, diag::err_pp_bad_paste, |
| 611 | std::string(Buffer.begin(), Buffer.end()-1)); |
| 612 | return; |
| 613 | } |
| 614 | |
| 615 | // Turn ## into 'other' to avoid # ## # from looking like a paste operator. |
| 616 | if (Result.getKind() == tok::hashhash) |
| 617 | Result.setKind(tok::unknown); |
| 618 | // FIXME: Turn __VARRGS__ into "not a token"? |
| 619 | |
| 620 | // Transfer properties of the LHS over the the Result. |
Chris Lattner | d217773 | 2007-07-20 16:59:19 +0000 | [diff] [blame] | 621 | Result.setFlagValue(Token::StartOfLine , Tok.isAtStartOfLine()); |
| 622 | Result.setFlagValue(Token::LeadingSpace, Tok.hasLeadingSpace()); |
Reid Spencer | 5f016e2 | 2007-07-11 17:01:13 +0000 | [diff] [blame] | 623 | |
| 624 | // Finally, replace LHS with the result, consume the RHS, and iterate. |
| 625 | ++CurToken; |
| 626 | Tok = Result; |
| 627 | } while (!isAtEnd() && MacroTokens[CurToken].getKind() == tok::hashhash); |
| 628 | |
| 629 | // Now that we got the result token, it will be subject to expansion. Since |
| 630 | // token pasting re-lexes the result token in raw mode, identifier information |
| 631 | // isn't looked up. As such, if the result is an identifier, look up id info. |
| 632 | if (Tok.getKind() == tok::identifier) { |
| 633 | // Look up the identifier info for the token. We disabled identifier lookup |
| 634 | // by saying we're skipping contents, so we need to do this manually. |
| 635 | Tok.setIdentifierInfo(PP.LookUpIdentifierInfo(Tok)); |
| 636 | } |
| 637 | } |
| 638 | |
| 639 | /// isNextTokenLParen - If the next token lexed will pop this macro off the |
| 640 | /// expansion stack, return 2. If the next unexpanded token is a '(', return |
| 641 | /// 1, otherwise return 0. |
| 642 | unsigned MacroExpander::isNextTokenLParen() const { |
| 643 | // Out of tokens? |
| 644 | if (isAtEnd()) |
| 645 | return 2; |
| 646 | return MacroTokens[CurToken].getKind() == tok::l_paren; |
| 647 | } |