blob: 5aa4679fad4626eadf5a961f1e82ef7090009dea [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner7ff66fb2008-03-09 02:55:12 +00006//
7//===----------------------------------------------------------------------===//
8//
Nico Weber33b2d712014-05-09 00:42:08 +00009// This file implements the MacroArgs interface.
Chris Lattner7ff66fb2008-03-09 02:55:12 +000010//
11//===----------------------------------------------------------------------===//
12
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +000013#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Lex/LexDiagnostic.h"
Chris Lattner7ff66fb2008-03-09 02:55:12 +000015#include "clang/Lex/MacroInfo.h"
16#include "clang/Lex/Preprocessor.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000017#include "llvm/ADT/SmallString.h"
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +000018#include "llvm/Support/SaveAndRestore.h"
David Blaikie319b7382011-09-22 02:03:12 +000019#include <algorithm>
20
Chris Lattner7ff66fb2008-03-09 02:55:12 +000021using namespace clang;
22
23/// MacroArgs ctor function - This destroys the vector passed in.
24MacroArgs *MacroArgs::create(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000025 ArrayRef<Token> UnexpArgTokens,
David Blaikie319b7382011-09-22 02:03:12 +000026 bool VarargsElided, Preprocessor &PP) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +000027 assert(MI->isFunctionLike() &&
28 "Can't have args for an object-like macro!");
Craig Topperd2d442c2014-05-17 23:10:59 +000029 MacroArgs **ResultEnt = nullptr;
Chris Lattner9e0005f2009-12-28 06:36:46 +000030 unsigned ClosestMatch = ~0U;
Fangrui Song6907ce22018-07-30 19:24:48 +000031
Chris Lattner13162492009-12-15 20:48:12 +000032 // See if we have an entry with a big enough argument list to reuse on the
33 // free list. If so, reuse it.
34 for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
Faisal Vali02d8dde2017-09-28 01:50:23 +000035 Entry = &(*Entry)->ArgCache) {
David Blaikie319b7382011-09-22 02:03:12 +000036 if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
Chris Lattner9e0005f2009-12-28 06:36:46 +000037 (*Entry)->NumUnexpArgTokens < ClosestMatch) {
38 ResultEnt = Entry;
Fangrui Song6907ce22018-07-30 19:24:48 +000039
Chris Lattner9e0005f2009-12-28 06:36:46 +000040 // If we have an exact match, use it.
David Blaikie319b7382011-09-22 02:03:12 +000041 if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
Chris Lattner9e0005f2009-12-28 06:36:46 +000042 break;
43 // Otherwise, use the best fit.
44 ClosestMatch = (*Entry)->NumUnexpArgTokens;
Chris Lattner13162492009-12-15 20:48:12 +000045 }
Faisal Vali02d8dde2017-09-28 01:50:23 +000046 }
Chris Lattner9e0005f2009-12-28 06:36:46 +000047 MacroArgs *Result;
Craig Topperd2d442c2014-05-17 23:10:59 +000048 if (!ResultEnt) {
Faisal Vali02d8dde2017-09-28 01:50:23 +000049 // Allocate memory for a MacroArgs object with the lexer tokens at the end,
50 // and construct the MacroArgs object.
Serge Pavlov52525732018-02-21 02:02:39 +000051 Result = new (
52 llvm::safe_malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))
Faisal Valiac506d72017-07-17 17:18:43 +000053 MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());
Chris Lattner13162492009-12-15 20:48:12 +000054 } else {
Chris Lattner9e0005f2009-12-28 06:36:46 +000055 Result = *ResultEnt;
56 // Unlink this node from the preprocessors singly linked list.
57 *ResultEnt = Result->ArgCache;
David Blaikie319b7382011-09-22 02:03:12 +000058 Result->NumUnexpArgTokens = UnexpArgTokens.size();
Chris Lattner13162492009-12-15 20:48:12 +000059 Result->VarargsElided = VarargsElided;
Faisal Valiac506d72017-07-17 17:18:43 +000060 Result->NumMacroArgs = MI->getNumParams();
Chris Lattner13162492009-12-15 20:48:12 +000061 }
Mike Stump11289f42009-09-09 15:08:12 +000062
Chris Lattner7ff66fb2008-03-09 02:55:12 +000063 // Copy the actual unexpanded tokens to immediately after the result ptr.
Faisal Vali02d8dde2017-09-28 01:50:23 +000064 if (!UnexpArgTokens.empty()) {
Benjamin Kramer32c99822017-09-28 08:50:30 +000065 static_assert(std::is_trivial<Token>::value,
Faisal Vali02d8dde2017-09-28 01:50:23 +000066 "assume trivial copyability if copying into the "
67 "uninitialized array (as opposed to reusing a cached "
68 "MacroArgs)");
Benjamin Kramer32c99822017-09-28 08:50:30 +000069 std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
Faisal Vali02d8dde2017-09-28 01:50:23 +000070 Result->getTrailingObjects<Token>());
71 }
Mike Stump11289f42009-09-09 15:08:12 +000072
Chris Lattner7ff66fb2008-03-09 02:55:12 +000073 return Result;
74}
75
76/// destroy - Destroy and deallocate the memory for this object.
77///
Chris Lattnerffbf2de2009-12-14 22:12:52 +000078void MacroArgs::destroy(Preprocessor &PP) {
Chris Lattner13162492009-12-15 20:48:12 +000079 StringifiedArgs.clear();
80
81 // Don't clear PreExpArgTokens, just clear the entries. Clearing the entries
82 // would deallocate the element vectors.
83 for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)
84 PreExpArgTokens[i].clear();
Fangrui Song6907ce22018-07-30 19:24:48 +000085
Chris Lattner13162492009-12-15 20:48:12 +000086 // Add this to the preprocessor's free list.
87 ArgCache = PP.MacroArgCache;
88 PP.MacroArgCache = this;
Chris Lattner7ff66fb2008-03-09 02:55:12 +000089}
90
Chris Lattnerd19564b2009-12-15 01:51:03 +000091/// deallocate - This should only be called by the Preprocessor when managing
92/// its freelist.
93MacroArgs *MacroArgs::deallocate() {
94 MacroArgs *Next = ArgCache;
Fangrui Song6907ce22018-07-30 19:24:48 +000095
Chris Lattnerd19564b2009-12-15 01:51:03 +000096 // Run the dtor to deallocate the vectors.
97 this->~MacroArgs();
98 // Release the memory for the object.
Faisal Valic5fa1f12017-09-28 02:00:40 +000099 static_assert(std::is_trivially_destructible<Token>::value,
Faisal Vali02d8dde2017-09-28 01:50:23 +0000100 "assume trivially destructible and forego destructors");
Chris Lattnerd19564b2009-12-15 01:51:03 +0000101 free(this);
Fangrui Song6907ce22018-07-30 19:24:48 +0000102
Chris Lattnerd19564b2009-12-15 01:51:03 +0000103 return Next;
104}
105
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000106
107/// getArgLength - Given a pointer to an expanded or unexpanded argument,
108/// return the number of tokens, not counting the EOF, that make up the
109/// argument.
110unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
111 unsigned NumArgTokens = 0;
112 for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
113 ++NumArgTokens;
114 return NumArgTokens;
115}
116
117
118/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
119///
120const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
Faisal Vali7ae3c3f2017-09-30 19:34:27 +0000121
122 assert(Arg < getNumMacroArguments() && "Invalid arg #");
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000123 // The unexpanded argument tokens start immediately after the MacroArgs object
124 // in memory.
Faisal Vali02d8dde2017-09-28 01:50:23 +0000125 const Token *Start = getTrailingObjects<Token>();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000126 const Token *Result = Start;
Fangrui Song6907ce22018-07-30 19:24:48 +0000127
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000128 // Scan to find Arg.
129 for (; Arg; ++Result) {
130 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
131 if (Result->is(tok::eof))
132 --Arg;
133 }
Chris Lattnerf160b5f2009-05-13 00:55:26 +0000134 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000135 return Result;
136}
137
Richard Smithcb1beee2019-05-04 06:46:18 +0000138bool MacroArgs::invokedWithVariadicArgument(const MacroInfo *const MI,
139 Preprocessor &PP) {
Faisal Vali18268422017-10-15 01:26:26 +0000140 if (!MI->isVariadic())
141 return false;
142 const int VariadicArgIndex = getNumMacroArguments() - 1;
Richard Smithcb1beee2019-05-04 06:46:18 +0000143 return getPreExpArgument(VariadicArgIndex, PP).front().isNot(tok::eof);
Faisal Vali18268422017-10-15 01:26:26 +0000144}
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000145
146/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
147/// by pre-expansion, return false. Otherwise, conservatively return true.
148bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
149 Preprocessor &PP) const {
150 // If there are no identifiers in the argument list, or if the identifiers are
151 // known to not be macros, pre-expansion won't modify it.
152 for (; ArgTok->isNot(tok::eof); ++ArgTok)
Richard Smith20e883e2015-04-29 23:20:19 +0000153 if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
154 if (II->hasMacroDefinition())
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000155 // Return true even though the macro could be a function-like macro
Richard Smith20e883e2015-04-29 23:20:19 +0000156 // without a following '(' token, or could be disabled, or not visible.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000157 return true;
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000158 return false;
159}
160
161/// getPreExpArgument - Return the pre-expanded form of the specified
162/// argument.
Faisal Vali333133e2017-09-30 13:58:38 +0000163const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,
164 Preprocessor &PP) {
165 assert(Arg < getNumMacroArguments() && "Invalid argument number!");
Mike Stump11289f42009-09-09 15:08:12 +0000166
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000167 // If we have already computed this, return it.
Faisal Vali333133e2017-09-30 13:58:38 +0000168 if (PreExpArgTokens.size() < getNumMacroArguments())
169 PreExpArgTokens.resize(getNumMacroArguments());
Fangrui Song6907ce22018-07-30 19:24:48 +0000170
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000171 std::vector<Token> &Result = PreExpArgTokens[Arg];
172 if (!Result.empty()) return Result;
173
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000174 SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
175
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000176 const Token *AT = getUnexpArgument(Arg);
177 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Mike Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000179 // Otherwise, we have to pre-expand this argument, populating Result. To do
180 // this, we set up a fake TokenLexer to lex from the unexpanded argument
181 // list. With this installed, we lex expanded tokens until we hit the EOF
182 // token at the end of the unexp list.
Mike Stump11289f42009-09-09 15:08:12 +0000183 PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
Ilya Biryukov929af672019-05-17 09:32:05 +0000184 false /*owns tokens*/, false /*is reinject*/);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000185
186 // Lex all of the macro-expanded tokens into Result.
187 do {
188 Result.push_back(Token());
Chris Lattnerad13cf42009-01-26 04:33:10 +0000189 Token &Tok = Result.back();
190 PP.Lex(Tok);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000191 } while (Result.back().isNot(tok::eof));
Mike Stump11289f42009-09-09 15:08:12 +0000192
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000193 // Pop the token stream off the top of the stack. We know that the internal
194 // pointer inside of it is to the "end" of the token stream, but the stack
195 // will not otherwise be popped until the next token is lexed. The problem is
196 // that the token may be lexed sometime after the vector of tokens itself is
197 // destroyed, which would be badness.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000198 if (PP.InCachingLexMode())
199 PP.ExitCachingLexMode();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000200 PP.RemoveTopOfLexerStack();
201 return Result;
202}
203
204
205/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
206/// tokens into the literal string token that should be produced by the C #
207/// preprocessor operator. If Charify is true, then it should be turned into
208/// a character literal for the Microsoft charize (#@) extension.
209///
210Token MacroArgs::StringifyArgument(const Token *ArgToks,
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000211 Preprocessor &PP, bool Charify,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000212 SourceLocation ExpansionLocStart,
213 SourceLocation ExpansionLocEnd) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000214 Token Tok;
215 Tok.startToken();
Chris Lattner3859c742009-12-23 19:15:27 +0000216 Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000217
218 const Token *ArgTokStart = ArgToks;
Mike Stump11289f42009-09-09 15:08:12 +0000219
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000220 // Stringify all the tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000221 SmallString<128> Result;
Chris Lattner933d5ff2009-01-05 23:04:18 +0000222 Result += "\"";
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000224 bool isFirst = true;
225 for (; ArgToks->isNot(tok::eof); ++ArgToks) {
226 const Token &Tok = *ArgToks;
227 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
228 Result += ' ';
229 isFirst = false;
Mike Stump11289f42009-09-09 15:08:12 +0000230
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000231 // If this is a string or character constant, escape the token as specified
232 // by 6.10.3.2p2.
Richard Smithc98bb4e2013-03-09 23:30:15 +0000233 if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
234 Tok.is(tok::char_constant) || // 'x'
235 Tok.is(tok::wide_char_constant) || // L'x'.
Richard Smith3e3a7052014-11-08 06:08:42 +0000236 Tok.is(tok::utf8_char_constant) || // u8'x'.
Richard Smithc98bb4e2013-03-09 23:30:15 +0000237 Tok.is(tok::utf16_char_constant) || // u'x'.
238 Tok.is(tok::utf32_char_constant)) { // U'x'.
Douglas Gregordc970f02010-03-16 22:30:13 +0000239 bool Invalid = false;
240 std::string TokStr = PP.getSpelling(Tok, &Invalid);
241 if (!Invalid) {
242 std::string Str = Lexer::Stringify(TokStr);
243 Result.append(Str.begin(), Str.end());
244 }
Argyrios Kyrtzidisb914e3b2011-09-04 03:32:19 +0000245 } else if (Tok.is(tok::code_completion)) {
246 PP.CodeCompleteNaturalLanguage();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000247 } else {
Chris Lattner933d5ff2009-01-05 23:04:18 +0000248 // Otherwise, just append the token. Do some gymnastics to get the token
249 // in place and avoid copies where possible.
250 unsigned CurStrLen = Result.size();
251 Result.resize(CurStrLen+Tok.getLength());
David Majnemerd3c3e782014-10-25 11:40:40 +0000252 const char *BufPtr = Result.data() + CurStrLen;
Douglas Gregordc970f02010-03-16 22:30:13 +0000253 bool Invalid = false;
254 unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
Mike Stump11289f42009-09-09 15:08:12 +0000255
Douglas Gregordc970f02010-03-16 22:30:13 +0000256 if (!Invalid) {
257 // If getSpelling returned a pointer to an already uniqued version of
258 // the string instead of filling in BufPtr, memcpy it onto our string.
David Majnemerd3c3e782014-10-25 11:40:40 +0000259 if (ActualTokLen && BufPtr != &Result[CurStrLen])
Douglas Gregordc970f02010-03-16 22:30:13 +0000260 memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000261
Douglas Gregordc970f02010-03-16 22:30:13 +0000262 // If the token was dirty, the spelling may be shorter than the token.
263 if (ActualTokLen != Tok.getLength())
264 Result.resize(CurStrLen+ActualTokLen);
265 }
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000266 }
267 }
Mike Stump11289f42009-09-09 15:08:12 +0000268
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000269 // If the last character of the string is a \, and if it isn't escaped, this
270 // is an invalid string literal, diagnose it as specified in C99.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000271 if (Result.back() == '\\') {
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000272 // Count the number of consecutive \ characters. If even, then they are
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000273 // just escaped backslashes, otherwise it's an error.
274 unsigned FirstNonSlash = Result.size()-2;
275 // Guaranteed to find the starting " if nothing else.
276 while (Result[FirstNonSlash] == '\\')
277 --FirstNonSlash;
278 if ((Result.size()-1-FirstNonSlash) & 1) {
279 // Diagnose errors for things like: #define F(X) #X / F(\)
280 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattner933d5ff2009-01-05 23:04:18 +0000281 Result.pop_back(); // remove one of the \'s.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000282 }
283 }
284 Result += '"';
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000286 // If this is the charify operation and the result is not a legal character
287 // constant, diagnose it.
288 if (Charify) {
289 // First step, turn double quotes into single quotes:
290 Result[0] = '\'';
291 Result[Result.size()-1] = '\'';
Mike Stump11289f42009-09-09 15:08:12 +0000292
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000293 // Check for bogus character.
294 bool isBad = false;
Chris Lattner933d5ff2009-01-05 23:04:18 +0000295 if (Result.size() == 3)
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000296 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000297 else
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000298 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
Mike Stump11289f42009-09-09 15:08:12 +0000299
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000300 if (isBad) {
301 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
302 Result = "' '"; // Use something arbitrary, but legal.
303 }
304 }
Mike Stump11289f42009-09-09 15:08:12 +0000305
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000306 PP.CreateString(Result, Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000307 ExpansionLocStart, ExpansionLocEnd);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000308 return Tok;
309}
310
311/// getStringifiedArgument - Compute, cache, and return the specified argument
312/// that has been 'stringified' as required by the # operator.
313const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000314 Preprocessor &PP,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000315 SourceLocation ExpansionLocStart,
316 SourceLocation ExpansionLocEnd) {
Erich Keane8691d6e2017-06-14 23:09:01 +0000317 assert(ArgNo < getNumMacroArguments() && "Invalid argument number!");
318 if (StringifiedArgs.empty())
319 StringifiedArgs.resize(getNumMacroArguments(), {});
320
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000321 if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000322 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000323 /*Charify=*/false,
324 ExpansionLocStart,
325 ExpansionLocEnd);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000326 return StringifiedArgs[ArgNo];
327}