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