blob: 3b6e2dc2411a035c7cdf8f96d98885e88c900c69 [file] [log] [blame]
Nico Webera7d16192014-05-09 00:39:59 +00001//===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//
Chris Lattner7ff66fb2008-03-09 02:55:12 +00002//
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//
Nico Weber33b2d712014-05-09 00:42:08 +000010// This file implements the MacroArgs interface.
Chris Lattner7ff66fb2008-03-09 02:55:12 +000011//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +000014#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Lex/LexDiagnostic.h"
Chris Lattner7ff66fb2008-03-09 02:55:12 +000016#include "clang/Lex/MacroInfo.h"
17#include "clang/Lex/Preprocessor.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000018#include "llvm/ADT/SmallString.h"
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +000019#include "llvm/Support/SaveAndRestore.h"
David Blaikie319b7382011-09-22 02:03:12 +000020#include <algorithm>
21
Chris Lattner7ff66fb2008-03-09 02:55:12 +000022using namespace clang;
23
24/// MacroArgs ctor function - This destroys the vector passed in.
25MacroArgs *MacroArgs::create(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000026 ArrayRef<Token> UnexpArgTokens,
David Blaikie319b7382011-09-22 02:03:12 +000027 bool VarargsElided, Preprocessor &PP) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +000028 assert(MI->isFunctionLike() &&
29 "Can't have args for an object-like macro!");
Craig Topperd2d442c2014-05-17 23:10:59 +000030 MacroArgs **ResultEnt = nullptr;
Chris Lattner9e0005f2009-12-28 06:36:46 +000031 unsigned ClosestMatch = ~0U;
Chris Lattner13162492009-12-15 20:48:12 +000032
33 // See if we have an entry with a big enough argument list to reuse on the
34 // free list. If so, reuse it.
35 for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
Faisal Vali02d8dde2017-09-28 01:50:23 +000036 Entry = &(*Entry)->ArgCache) {
David Blaikie319b7382011-09-22 02:03:12 +000037 if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
Chris Lattner9e0005f2009-12-28 06:36:46 +000038 (*Entry)->NumUnexpArgTokens < ClosestMatch) {
39 ResultEnt = Entry;
40
41 // If we have an exact match, use it.
David Blaikie319b7382011-09-22 02:03:12 +000042 if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
Chris Lattner9e0005f2009-12-28 06:36:46 +000043 break;
44 // Otherwise, use the best fit.
45 ClosestMatch = (*Entry)->NumUnexpArgTokens;
Chris Lattner13162492009-12-15 20:48:12 +000046 }
Faisal Vali02d8dde2017-09-28 01:50:23 +000047 }
Chris Lattner9e0005f2009-12-28 06:36:46 +000048 MacroArgs *Result;
Craig Topperd2d442c2014-05-17 23:10:59 +000049 if (!ResultEnt) {
Faisal Vali02d8dde2017-09-28 01:50:23 +000050 // Allocate memory for a MacroArgs object with the lexer tokens at the end,
51 // and construct the MacroArgs object.
Serge Pavlov52525732018-02-21 02:02:39 +000052 Result = new (
53 llvm::safe_malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))
Faisal Valiac506d72017-07-17 17:18:43 +000054 MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());
Chris Lattner13162492009-12-15 20:48:12 +000055 } else {
Chris Lattner9e0005f2009-12-28 06:36:46 +000056 Result = *ResultEnt;
57 // Unlink this node from the preprocessors singly linked list.
58 *ResultEnt = Result->ArgCache;
David Blaikie319b7382011-09-22 02:03:12 +000059 Result->NumUnexpArgTokens = UnexpArgTokens.size();
Chris Lattner13162492009-12-15 20:48:12 +000060 Result->VarargsElided = VarargsElided;
Faisal Valiac506d72017-07-17 17:18:43 +000061 Result->NumMacroArgs = MI->getNumParams();
Chris Lattner13162492009-12-15 20:48:12 +000062 }
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner7ff66fb2008-03-09 02:55:12 +000064 // Copy the actual unexpanded tokens to immediately after the result ptr.
Faisal Vali02d8dde2017-09-28 01:50:23 +000065 if (!UnexpArgTokens.empty()) {
Benjamin Kramer32c99822017-09-28 08:50:30 +000066 static_assert(std::is_trivial<Token>::value,
Faisal Vali02d8dde2017-09-28 01:50:23 +000067 "assume trivial copyability if copying into the "
68 "uninitialized array (as opposed to reusing a cached "
69 "MacroArgs)");
Benjamin Kramer32c99822017-09-28 08:50:30 +000070 std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
Faisal Vali02d8dde2017-09-28 01:50:23 +000071 Result->getTrailingObjects<Token>());
72 }
Mike Stump11289f42009-09-09 15:08:12 +000073
Chris Lattner7ff66fb2008-03-09 02:55:12 +000074 return Result;
75}
76
77/// destroy - Destroy and deallocate the memory for this object.
78///
Chris Lattnerffbf2de2009-12-14 22:12:52 +000079void MacroArgs::destroy(Preprocessor &PP) {
Chris Lattner13162492009-12-15 20:48:12 +000080 StringifiedArgs.clear();
81
82 // Don't clear PreExpArgTokens, just clear the entries. Clearing the entries
83 // would deallocate the element vectors.
84 for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)
85 PreExpArgTokens[i].clear();
86
87 // Add this to the preprocessor's free list.
88 ArgCache = PP.MacroArgCache;
89 PP.MacroArgCache = this;
Chris Lattner7ff66fb2008-03-09 02:55:12 +000090}
91
Chris Lattnerd19564b2009-12-15 01:51:03 +000092/// deallocate - This should only be called by the Preprocessor when managing
93/// its freelist.
94MacroArgs *MacroArgs::deallocate() {
95 MacroArgs *Next = ArgCache;
96
97 // Run the dtor to deallocate the vectors.
98 this->~MacroArgs();
99 // Release the memory for the object.
Faisal Valic5fa1f12017-09-28 02:00:40 +0000100 static_assert(std::is_trivially_destructible<Token>::value,
Faisal Vali02d8dde2017-09-28 01:50:23 +0000101 "assume trivially destructible and forego destructors");
Chris Lattnerd19564b2009-12-15 01:51:03 +0000102 free(this);
103
104 return Next;
105}
106
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000107
108/// getArgLength - Given a pointer to an expanded or unexpanded argument,
109/// return the number of tokens, not counting the EOF, that make up the
110/// argument.
111unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
112 unsigned NumArgTokens = 0;
113 for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
114 ++NumArgTokens;
115 return NumArgTokens;
116}
117
118
119/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
120///
121const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
Faisal Vali7ae3c3f2017-09-30 19:34:27 +0000122
123 assert(Arg < getNumMacroArguments() && "Invalid arg #");
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000124 // The unexpanded argument tokens start immediately after the MacroArgs object
125 // in memory.
Faisal Vali02d8dde2017-09-28 01:50:23 +0000126 const Token *Start = getTrailingObjects<Token>();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000127 const Token *Result = Start;
Faisal Vali7ae3c3f2017-09-30 19:34:27 +0000128
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000129 // Scan to find Arg.
130 for (; Arg; ++Result) {
131 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
132 if (Result->is(tok::eof))
133 --Arg;
134 }
Chris Lattnerf160b5f2009-05-13 00:55:26 +0000135 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000136 return Result;
137}
138
Faisal Vali18268422017-10-15 01:26:26 +0000139// This function assumes that the variadic arguments are the tokens
140// corresponding to the last parameter (ellipsis) - and since tokens are
141// separated by the 'eof' token, if that is the only token corresponding to that
142// last parameter, we know no variadic arguments were supplied.
143bool MacroArgs::invokedWithVariadicArgument(const MacroInfo *const MI) const {
144 if (!MI->isVariadic())
145 return false;
146 const int VariadicArgIndex = getNumMacroArguments() - 1;
147 return getUnexpArgument(VariadicArgIndex)->isNot(tok::eof);
148}
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000149
150/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
151/// by pre-expansion, return false. Otherwise, conservatively return true.
152bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
153 Preprocessor &PP) const {
154 // If there are no identifiers in the argument list, or if the identifiers are
155 // known to not be macros, pre-expansion won't modify it.
156 for (; ArgTok->isNot(tok::eof); ++ArgTok)
Richard Smith20e883e2015-04-29 23:20:19 +0000157 if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
158 if (II->hasMacroDefinition())
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000159 // Return true even though the macro could be a function-like macro
Richard Smith20e883e2015-04-29 23:20:19 +0000160 // without a following '(' token, or could be disabled, or not visible.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000161 return true;
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000162 return false;
163}
164
165/// getPreExpArgument - Return the pre-expanded form of the specified
166/// argument.
Faisal Vali333133e2017-09-30 13:58:38 +0000167const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,
168 Preprocessor &PP) {
169 assert(Arg < getNumMacroArguments() && "Invalid argument number!");
Mike Stump11289f42009-09-09 15:08:12 +0000170
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000171 // If we have already computed this, return it.
Faisal Vali333133e2017-09-30 13:58:38 +0000172 if (PreExpArgTokens.size() < getNumMacroArguments())
173 PreExpArgTokens.resize(getNumMacroArguments());
Chris Lattner394f5892009-12-28 06:17:16 +0000174
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000175 std::vector<Token> &Result = PreExpArgTokens[Arg];
176 if (!Result.empty()) return Result;
177
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000178 SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
179
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000180 const Token *AT = getUnexpArgument(Arg);
181 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Mike Stump11289f42009-09-09 15:08:12 +0000182
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000183 // Otherwise, we have to pre-expand this argument, populating Result. To do
184 // this, we set up a fake TokenLexer to lex from the unexpanded argument
185 // list. With this installed, we lex expanded tokens until we hit the EOF
186 // token at the end of the unexp list.
Mike Stump11289f42009-09-09 15:08:12 +0000187 PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
Chris Lattner3e468322008-03-10 06:06:04 +0000188 false /*owns tokens*/);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000189
190 // Lex all of the macro-expanded tokens into Result.
191 do {
192 Result.push_back(Token());
Chris Lattnerad13cf42009-01-26 04:33:10 +0000193 Token &Tok = Result.back();
194 PP.Lex(Tok);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000195 } while (Result.back().isNot(tok::eof));
Mike Stump11289f42009-09-09 15:08:12 +0000196
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000197 // Pop the token stream off the top of the stack. We know that the internal
198 // pointer inside of it is to the "end" of the token stream, but the stack
199 // will not otherwise be popped until the next token is lexed. The problem is
200 // that the token may be lexed sometime after the vector of tokens itself is
201 // destroyed, which would be badness.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000202 if (PP.InCachingLexMode())
203 PP.ExitCachingLexMode();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000204 PP.RemoveTopOfLexerStack();
205 return Result;
206}
207
208
209/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
210/// tokens into the literal string token that should be produced by the C #
211/// preprocessor operator. If Charify is true, then it should be turned into
212/// a character literal for the Microsoft charize (#@) extension.
213///
214Token MacroArgs::StringifyArgument(const Token *ArgToks,
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000215 Preprocessor &PP, bool Charify,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000216 SourceLocation ExpansionLocStart,
217 SourceLocation ExpansionLocEnd) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000218 Token Tok;
219 Tok.startToken();
Chris Lattner3859c742009-12-23 19:15:27 +0000220 Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000221
222 const Token *ArgTokStart = ArgToks;
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000224 // Stringify all the tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000225 SmallString<128> Result;
Chris Lattner933d5ff2009-01-05 23:04:18 +0000226 Result += "\"";
Mike Stump11289f42009-09-09 15:08:12 +0000227
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000228 bool isFirst = true;
229 for (; ArgToks->isNot(tok::eof); ++ArgToks) {
230 const Token &Tok = *ArgToks;
231 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
232 Result += ' ';
233 isFirst = false;
Mike Stump11289f42009-09-09 15:08:12 +0000234
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000235 // If this is a string or character constant, escape the token as specified
236 // by 6.10.3.2p2.
Richard Smithc98bb4e2013-03-09 23:30:15 +0000237 if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
238 Tok.is(tok::char_constant) || // 'x'
239 Tok.is(tok::wide_char_constant) || // L'x'.
Richard Smith3e3a7052014-11-08 06:08:42 +0000240 Tok.is(tok::utf8_char_constant) || // u8'x'.
Richard Smithc98bb4e2013-03-09 23:30:15 +0000241 Tok.is(tok::utf16_char_constant) || // u'x'.
242 Tok.is(tok::utf32_char_constant)) { // U'x'.
Douglas Gregordc970f02010-03-16 22:30:13 +0000243 bool Invalid = false;
244 std::string TokStr = PP.getSpelling(Tok, &Invalid);
245 if (!Invalid) {
246 std::string Str = Lexer::Stringify(TokStr);
247 Result.append(Str.begin(), Str.end());
248 }
Argyrios Kyrtzidisb914e3b2011-09-04 03:32:19 +0000249 } else if (Tok.is(tok::code_completion)) {
250 PP.CodeCompleteNaturalLanguage();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000251 } else {
Chris Lattner933d5ff2009-01-05 23:04:18 +0000252 // Otherwise, just append the token. Do some gymnastics to get the token
253 // in place and avoid copies where possible.
254 unsigned CurStrLen = Result.size();
255 Result.resize(CurStrLen+Tok.getLength());
David Majnemerd3c3e782014-10-25 11:40:40 +0000256 const char *BufPtr = Result.data() + CurStrLen;
Douglas Gregordc970f02010-03-16 22:30:13 +0000257 bool Invalid = false;
258 unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
Mike Stump11289f42009-09-09 15:08:12 +0000259
Douglas Gregordc970f02010-03-16 22:30:13 +0000260 if (!Invalid) {
261 // If getSpelling returned a pointer to an already uniqued version of
262 // the string instead of filling in BufPtr, memcpy it onto our string.
David Majnemerd3c3e782014-10-25 11:40:40 +0000263 if (ActualTokLen && BufPtr != &Result[CurStrLen])
Douglas Gregordc970f02010-03-16 22:30:13 +0000264 memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000265
Douglas Gregordc970f02010-03-16 22:30:13 +0000266 // If the token was dirty, the spelling may be shorter than the token.
267 if (ActualTokLen != Tok.getLength())
268 Result.resize(CurStrLen+ActualTokLen);
269 }
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000270 }
271 }
Mike Stump11289f42009-09-09 15:08:12 +0000272
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000273 // If the last character of the string is a \, and if it isn't escaped, this
274 // is an invalid string literal, diagnose it as specified in C99.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000275 if (Result.back() == '\\') {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000276 // Count the number of consecutive \ characters. If even, then they are
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000277 // just escaped backslashes, otherwise it's an error.
278 unsigned FirstNonSlash = Result.size()-2;
279 // Guaranteed to find the starting " if nothing else.
280 while (Result[FirstNonSlash] == '\\')
281 --FirstNonSlash;
282 if ((Result.size()-1-FirstNonSlash) & 1) {
283 // Diagnose errors for things like: #define F(X) #X / F(\)
284 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattner933d5ff2009-01-05 23:04:18 +0000285 Result.pop_back(); // remove one of the \'s.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000286 }
287 }
288 Result += '"';
Mike Stump11289f42009-09-09 15:08:12 +0000289
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000290 // If this is the charify operation and the result is not a legal character
291 // constant, diagnose it.
292 if (Charify) {
293 // First step, turn double quotes into single quotes:
294 Result[0] = '\'';
295 Result[Result.size()-1] = '\'';
Mike Stump11289f42009-09-09 15:08:12 +0000296
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000297 // Check for bogus character.
298 bool isBad = false;
Chris Lattner933d5ff2009-01-05 23:04:18 +0000299 if (Result.size() == 3)
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000300 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000301 else
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000302 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
Mike Stump11289f42009-09-09 15:08:12 +0000303
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000304 if (isBad) {
305 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
306 Result = "' '"; // Use something arbitrary, but legal.
307 }
308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000310 PP.CreateString(Result, Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000311 ExpansionLocStart, ExpansionLocEnd);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000312 return Tok;
313}
314
315/// getStringifiedArgument - Compute, cache, and return the specified argument
316/// that has been 'stringified' as required by the # operator.
317const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000318 Preprocessor &PP,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000319 SourceLocation ExpansionLocStart,
320 SourceLocation ExpansionLocEnd) {
Erich Keane8691d6e2017-06-14 23:09:01 +0000321 assert(ArgNo < getNumMacroArguments() && "Invalid argument number!");
322 if (StringifiedArgs.empty())
323 StringifiedArgs.resize(getNumMacroArguments(), {});
324
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000325 if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000326 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000327 /*Charify=*/false,
328 ExpansionLocStart,
329 ExpansionLocEnd);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000330 return StringifiedArgs[ArgNo];
331}