1*7330f729Sjoerg //===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//
2*7330f729Sjoerg //
3*7330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*7330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
5*7330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*7330f729Sjoerg //
7*7330f729Sjoerg //===----------------------------------------------------------------------===//
8*7330f729Sjoerg //
9*7330f729Sjoerg // This file implements the MacroArgs interface.
10*7330f729Sjoerg //
11*7330f729Sjoerg //===----------------------------------------------------------------------===//
12*7330f729Sjoerg
13*7330f729Sjoerg #include "clang/Lex/MacroArgs.h"
14*7330f729Sjoerg #include "clang/Lex/LexDiagnostic.h"
15*7330f729Sjoerg #include "clang/Lex/MacroInfo.h"
16*7330f729Sjoerg #include "clang/Lex/Preprocessor.h"
17*7330f729Sjoerg #include "llvm/ADT/SmallString.h"
18*7330f729Sjoerg #include "llvm/Support/SaveAndRestore.h"
19*7330f729Sjoerg #include <algorithm>
20*7330f729Sjoerg
21*7330f729Sjoerg using namespace clang;
22*7330f729Sjoerg
23*7330f729Sjoerg /// MacroArgs ctor function - This destroys the vector passed in.
create(const MacroInfo * MI,ArrayRef<Token> UnexpArgTokens,bool VarargsElided,Preprocessor & PP)24*7330f729Sjoerg MacroArgs *MacroArgs::create(const MacroInfo *MI,
25*7330f729Sjoerg ArrayRef<Token> UnexpArgTokens,
26*7330f729Sjoerg bool VarargsElided, Preprocessor &PP) {
27*7330f729Sjoerg assert(MI->isFunctionLike() &&
28*7330f729Sjoerg "Can't have args for an object-like macro!");
29*7330f729Sjoerg MacroArgs **ResultEnt = nullptr;
30*7330f729Sjoerg unsigned ClosestMatch = ~0U;
31*7330f729Sjoerg
32*7330f729Sjoerg // See if we have an entry with a big enough argument list to reuse on the
33*7330f729Sjoerg // free list. If so, reuse it.
34*7330f729Sjoerg for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
35*7330f729Sjoerg Entry = &(*Entry)->ArgCache) {
36*7330f729Sjoerg if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
37*7330f729Sjoerg (*Entry)->NumUnexpArgTokens < ClosestMatch) {
38*7330f729Sjoerg ResultEnt = Entry;
39*7330f729Sjoerg
40*7330f729Sjoerg // If we have an exact match, use it.
41*7330f729Sjoerg if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
42*7330f729Sjoerg break;
43*7330f729Sjoerg // Otherwise, use the best fit.
44*7330f729Sjoerg ClosestMatch = (*Entry)->NumUnexpArgTokens;
45*7330f729Sjoerg }
46*7330f729Sjoerg }
47*7330f729Sjoerg MacroArgs *Result;
48*7330f729Sjoerg if (!ResultEnt) {
49*7330f729Sjoerg // Allocate memory for a MacroArgs object with the lexer tokens at the end,
50*7330f729Sjoerg // and construct the MacroArgs object.
51*7330f729Sjoerg Result = new (
52*7330f729Sjoerg llvm::safe_malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))
53*7330f729Sjoerg MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());
54*7330f729Sjoerg } else {
55*7330f729Sjoerg Result = *ResultEnt;
56*7330f729Sjoerg // Unlink this node from the preprocessors singly linked list.
57*7330f729Sjoerg *ResultEnt = Result->ArgCache;
58*7330f729Sjoerg Result->NumUnexpArgTokens = UnexpArgTokens.size();
59*7330f729Sjoerg Result->VarargsElided = VarargsElided;
60*7330f729Sjoerg Result->NumMacroArgs = MI->getNumParams();
61*7330f729Sjoerg }
62*7330f729Sjoerg
63*7330f729Sjoerg // Copy the actual unexpanded tokens to immediately after the result ptr.
64*7330f729Sjoerg if (!UnexpArgTokens.empty()) {
65*7330f729Sjoerg static_assert(std::is_trivial<Token>::value,
66*7330f729Sjoerg "assume trivial copyability if copying into the "
67*7330f729Sjoerg "uninitialized array (as opposed to reusing a cached "
68*7330f729Sjoerg "MacroArgs)");
69*7330f729Sjoerg std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
70*7330f729Sjoerg Result->getTrailingObjects<Token>());
71*7330f729Sjoerg }
72*7330f729Sjoerg
73*7330f729Sjoerg return Result;
74*7330f729Sjoerg }
75*7330f729Sjoerg
76*7330f729Sjoerg /// destroy - Destroy and deallocate the memory for this object.
77*7330f729Sjoerg ///
destroy(Preprocessor & PP)78*7330f729Sjoerg void MacroArgs::destroy(Preprocessor &PP) {
79*7330f729Sjoerg // Don't clear PreExpArgTokens, just clear the entries. Clearing the entries
80*7330f729Sjoerg // would deallocate the element vectors.
81*7330f729Sjoerg for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)
82*7330f729Sjoerg PreExpArgTokens[i].clear();
83*7330f729Sjoerg
84*7330f729Sjoerg // Add this to the preprocessor's free list.
85*7330f729Sjoerg ArgCache = PP.MacroArgCache;
86*7330f729Sjoerg PP.MacroArgCache = this;
87*7330f729Sjoerg }
88*7330f729Sjoerg
89*7330f729Sjoerg /// deallocate - This should only be called by the Preprocessor when managing
90*7330f729Sjoerg /// its freelist.
deallocate()91*7330f729Sjoerg MacroArgs *MacroArgs::deallocate() {
92*7330f729Sjoerg MacroArgs *Next = ArgCache;
93*7330f729Sjoerg
94*7330f729Sjoerg // Run the dtor to deallocate the vectors.
95*7330f729Sjoerg this->~MacroArgs();
96*7330f729Sjoerg // Release the memory for the object.
97*7330f729Sjoerg static_assert(std::is_trivially_destructible<Token>::value,
98*7330f729Sjoerg "assume trivially destructible and forego destructors");
99*7330f729Sjoerg free(this);
100*7330f729Sjoerg
101*7330f729Sjoerg return Next;
102*7330f729Sjoerg }
103*7330f729Sjoerg
104*7330f729Sjoerg
105*7330f729Sjoerg /// getArgLength - Given a pointer to an expanded or unexpanded argument,
106*7330f729Sjoerg /// return the number of tokens, not counting the EOF, that make up the
107*7330f729Sjoerg /// argument.
getArgLength(const Token * ArgPtr)108*7330f729Sjoerg unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
109*7330f729Sjoerg unsigned NumArgTokens = 0;
110*7330f729Sjoerg for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
111*7330f729Sjoerg ++NumArgTokens;
112*7330f729Sjoerg return NumArgTokens;
113*7330f729Sjoerg }
114*7330f729Sjoerg
115*7330f729Sjoerg
116*7330f729Sjoerg /// getUnexpArgument - Return the unexpanded tokens for the specified formal.
117*7330f729Sjoerg ///
getUnexpArgument(unsigned Arg) const118*7330f729Sjoerg const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
119*7330f729Sjoerg
120*7330f729Sjoerg assert(Arg < getNumMacroArguments() && "Invalid arg #");
121*7330f729Sjoerg // The unexpanded argument tokens start immediately after the MacroArgs object
122*7330f729Sjoerg // in memory.
123*7330f729Sjoerg const Token *Start = getTrailingObjects<Token>();
124*7330f729Sjoerg const Token *Result = Start;
125*7330f729Sjoerg
126*7330f729Sjoerg // Scan to find Arg.
127*7330f729Sjoerg for (; Arg; ++Result) {
128*7330f729Sjoerg assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
129*7330f729Sjoerg if (Result->is(tok::eof))
130*7330f729Sjoerg --Arg;
131*7330f729Sjoerg }
132*7330f729Sjoerg assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
133*7330f729Sjoerg return Result;
134*7330f729Sjoerg }
135*7330f729Sjoerg
invokedWithVariadicArgument(const MacroInfo * const MI,Preprocessor & PP)136*7330f729Sjoerg bool MacroArgs::invokedWithVariadicArgument(const MacroInfo *const MI,
137*7330f729Sjoerg Preprocessor &PP) {
138*7330f729Sjoerg if (!MI->isVariadic())
139*7330f729Sjoerg return false;
140*7330f729Sjoerg const int VariadicArgIndex = getNumMacroArguments() - 1;
141*7330f729Sjoerg return getPreExpArgument(VariadicArgIndex, PP).front().isNot(tok::eof);
142*7330f729Sjoerg }
143*7330f729Sjoerg
144*7330f729Sjoerg /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
145*7330f729Sjoerg /// by pre-expansion, return false. Otherwise, conservatively return true.
ArgNeedsPreexpansion(const Token * ArgTok,Preprocessor & PP) const146*7330f729Sjoerg bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
147*7330f729Sjoerg Preprocessor &PP) const {
148*7330f729Sjoerg // If there are no identifiers in the argument list, or if the identifiers are
149*7330f729Sjoerg // known to not be macros, pre-expansion won't modify it.
150*7330f729Sjoerg for (; ArgTok->isNot(tok::eof); ++ArgTok)
151*7330f729Sjoerg if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
152*7330f729Sjoerg if (II->hasMacroDefinition())
153*7330f729Sjoerg // Return true even though the macro could be a function-like macro
154*7330f729Sjoerg // without a following '(' token, or could be disabled, or not visible.
155*7330f729Sjoerg return true;
156*7330f729Sjoerg return false;
157*7330f729Sjoerg }
158*7330f729Sjoerg
159*7330f729Sjoerg /// getPreExpArgument - Return the pre-expanded form of the specified
160*7330f729Sjoerg /// argument.
getPreExpArgument(unsigned Arg,Preprocessor & PP)161*7330f729Sjoerg const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,
162*7330f729Sjoerg Preprocessor &PP) {
163*7330f729Sjoerg assert(Arg < getNumMacroArguments() && "Invalid argument number!");
164*7330f729Sjoerg
165*7330f729Sjoerg // If we have already computed this, return it.
166*7330f729Sjoerg if (PreExpArgTokens.size() < getNumMacroArguments())
167*7330f729Sjoerg PreExpArgTokens.resize(getNumMacroArguments());
168*7330f729Sjoerg
169*7330f729Sjoerg std::vector<Token> &Result = PreExpArgTokens[Arg];
170*7330f729Sjoerg if (!Result.empty()) return Result;
171*7330f729Sjoerg
172*7330f729Sjoerg SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
173*7330f729Sjoerg
174*7330f729Sjoerg const Token *AT = getUnexpArgument(Arg);
175*7330f729Sjoerg unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
176*7330f729Sjoerg
177*7330f729Sjoerg // Otherwise, we have to pre-expand this argument, populating Result. To do
178*7330f729Sjoerg // this, we set up a fake TokenLexer to lex from the unexpanded argument
179*7330f729Sjoerg // list. With this installed, we lex expanded tokens until we hit the EOF
180*7330f729Sjoerg // token at the end of the unexp list.
181*7330f729Sjoerg PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
182*7330f729Sjoerg false /*owns tokens*/, false /*is reinject*/);
183*7330f729Sjoerg
184*7330f729Sjoerg // Lex all of the macro-expanded tokens into Result.
185*7330f729Sjoerg do {
186*7330f729Sjoerg Result.push_back(Token());
187*7330f729Sjoerg Token &Tok = Result.back();
188*7330f729Sjoerg PP.Lex(Tok);
189*7330f729Sjoerg } while (Result.back().isNot(tok::eof));
190*7330f729Sjoerg
191*7330f729Sjoerg // Pop the token stream off the top of the stack. We know that the internal
192*7330f729Sjoerg // pointer inside of it is to the "end" of the token stream, but the stack
193*7330f729Sjoerg // will not otherwise be popped until the next token is lexed. The problem is
194*7330f729Sjoerg // that the token may be lexed sometime after the vector of tokens itself is
195*7330f729Sjoerg // destroyed, which would be badness.
196*7330f729Sjoerg if (PP.InCachingLexMode())
197*7330f729Sjoerg PP.ExitCachingLexMode();
198*7330f729Sjoerg PP.RemoveTopOfLexerStack();
199*7330f729Sjoerg return Result;
200*7330f729Sjoerg }
201*7330f729Sjoerg
202*7330f729Sjoerg
203*7330f729Sjoerg /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
204*7330f729Sjoerg /// tokens into the literal string token that should be produced by the C #
205*7330f729Sjoerg /// preprocessor operator. If Charify is true, then it should be turned into
206*7330f729Sjoerg /// a character literal for the Microsoft charize (#@) extension.
207*7330f729Sjoerg ///
StringifyArgument(const Token * ArgToks,Preprocessor & PP,bool Charify,SourceLocation ExpansionLocStart,SourceLocation ExpansionLocEnd)208*7330f729Sjoerg Token MacroArgs::StringifyArgument(const Token *ArgToks,
209*7330f729Sjoerg Preprocessor &PP, bool Charify,
210*7330f729Sjoerg SourceLocation ExpansionLocStart,
211*7330f729Sjoerg SourceLocation ExpansionLocEnd) {
212*7330f729Sjoerg Token Tok;
213*7330f729Sjoerg Tok.startToken();
214*7330f729Sjoerg Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
215*7330f729Sjoerg
216*7330f729Sjoerg const Token *ArgTokStart = ArgToks;
217*7330f729Sjoerg
218*7330f729Sjoerg // Stringify all the tokens.
219*7330f729Sjoerg SmallString<128> Result;
220*7330f729Sjoerg Result += "\"";
221*7330f729Sjoerg
222*7330f729Sjoerg bool isFirst = true;
223*7330f729Sjoerg for (; ArgToks->isNot(tok::eof); ++ArgToks) {
224*7330f729Sjoerg const Token &Tok = *ArgToks;
225*7330f729Sjoerg if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
226*7330f729Sjoerg Result += ' ';
227*7330f729Sjoerg isFirst = false;
228*7330f729Sjoerg
229*7330f729Sjoerg // If this is a string or character constant, escape the token as specified
230*7330f729Sjoerg // by 6.10.3.2p2.
231*7330f729Sjoerg if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
232*7330f729Sjoerg Tok.is(tok::char_constant) || // 'x'
233*7330f729Sjoerg Tok.is(tok::wide_char_constant) || // L'x'.
234*7330f729Sjoerg Tok.is(tok::utf8_char_constant) || // u8'x'.
235*7330f729Sjoerg Tok.is(tok::utf16_char_constant) || // u'x'.
236*7330f729Sjoerg Tok.is(tok::utf32_char_constant)) { // U'x'.
237*7330f729Sjoerg bool Invalid = false;
238*7330f729Sjoerg std::string TokStr = PP.getSpelling(Tok, &Invalid);
239*7330f729Sjoerg if (!Invalid) {
240*7330f729Sjoerg std::string Str = Lexer::Stringify(TokStr);
241*7330f729Sjoerg Result.append(Str.begin(), Str.end());
242*7330f729Sjoerg }
243*7330f729Sjoerg } else if (Tok.is(tok::code_completion)) {
244*7330f729Sjoerg PP.CodeCompleteNaturalLanguage();
245*7330f729Sjoerg } else {
246*7330f729Sjoerg // Otherwise, just append the token. Do some gymnastics to get the token
247*7330f729Sjoerg // in place and avoid copies where possible.
248*7330f729Sjoerg unsigned CurStrLen = Result.size();
249*7330f729Sjoerg Result.resize(CurStrLen+Tok.getLength());
250*7330f729Sjoerg const char *BufPtr = Result.data() + CurStrLen;
251*7330f729Sjoerg bool Invalid = false;
252*7330f729Sjoerg unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
253*7330f729Sjoerg
254*7330f729Sjoerg if (!Invalid) {
255*7330f729Sjoerg // If getSpelling returned a pointer to an already uniqued version of
256*7330f729Sjoerg // the string instead of filling in BufPtr, memcpy it onto our string.
257*7330f729Sjoerg if (ActualTokLen && BufPtr != &Result[CurStrLen])
258*7330f729Sjoerg memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
259*7330f729Sjoerg
260*7330f729Sjoerg // If the token was dirty, the spelling may be shorter than the token.
261*7330f729Sjoerg if (ActualTokLen != Tok.getLength())
262*7330f729Sjoerg Result.resize(CurStrLen+ActualTokLen);
263*7330f729Sjoerg }
264*7330f729Sjoerg }
265*7330f729Sjoerg }
266*7330f729Sjoerg
267*7330f729Sjoerg // If the last character of the string is a \, and if it isn't escaped, this
268*7330f729Sjoerg // is an invalid string literal, diagnose it as specified in C99.
269*7330f729Sjoerg if (Result.back() == '\\') {
270*7330f729Sjoerg // Count the number of consecutive \ characters. If even, then they are
271*7330f729Sjoerg // just escaped backslashes, otherwise it's an error.
272*7330f729Sjoerg unsigned FirstNonSlash = Result.size()-2;
273*7330f729Sjoerg // Guaranteed to find the starting " if nothing else.
274*7330f729Sjoerg while (Result[FirstNonSlash] == '\\')
275*7330f729Sjoerg --FirstNonSlash;
276*7330f729Sjoerg if ((Result.size()-1-FirstNonSlash) & 1) {
277*7330f729Sjoerg // Diagnose errors for things like: #define F(X) #X / F(\)
278*7330f729Sjoerg PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
279*7330f729Sjoerg Result.pop_back(); // remove one of the \'s.
280*7330f729Sjoerg }
281*7330f729Sjoerg }
282*7330f729Sjoerg Result += '"';
283*7330f729Sjoerg
284*7330f729Sjoerg // If this is the charify operation and the result is not a legal character
285*7330f729Sjoerg // constant, diagnose it.
286*7330f729Sjoerg if (Charify) {
287*7330f729Sjoerg // First step, turn double quotes into single quotes:
288*7330f729Sjoerg Result[0] = '\'';
289*7330f729Sjoerg Result[Result.size()-1] = '\'';
290*7330f729Sjoerg
291*7330f729Sjoerg // Check for bogus character.
292*7330f729Sjoerg bool isBad = false;
293*7330f729Sjoerg if (Result.size() == 3)
294*7330f729Sjoerg isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
295*7330f729Sjoerg else
296*7330f729Sjoerg isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
297*7330f729Sjoerg
298*7330f729Sjoerg if (isBad) {
299*7330f729Sjoerg PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
300*7330f729Sjoerg Result = "' '"; // Use something arbitrary, but legal.
301*7330f729Sjoerg }
302*7330f729Sjoerg }
303*7330f729Sjoerg
304*7330f729Sjoerg PP.CreateString(Result, Tok,
305*7330f729Sjoerg ExpansionLocStart, ExpansionLocEnd);
306*7330f729Sjoerg return Tok;
307*7330f729Sjoerg }
308