1 //===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the MacroArgs interface.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/MacroArgs.h"
15 #include "clang/Lex/LexDiagnostic.h"
16 #include "clang/Lex/MacroInfo.h"
17 #include "clang/Lex/Preprocessor.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Support/SaveAndRestore.h"
22 using namespace clang;
24 /// MacroArgs ctor function - This destroys the vector passed in.
25 MacroArgs *MacroArgs::create(const MacroInfo *MI,
26 ArrayRef<Token> UnexpArgTokens,
27 bool VarargsElided, Preprocessor &PP) {
28 assert(MI->isFunctionLike() &&
29 "Can't have args for an object-like macro!");
30 MacroArgs **ResultEnt = nullptr;
31 unsigned ClosestMatch = ~0U;
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;
36 Entry = &(*Entry)->ArgCache)
37 if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
38 (*Entry)->NumUnexpArgTokens < ClosestMatch) {
41 // If we have an exact match, use it.
42 if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
44 // Otherwise, use the best fit.
45 ClosestMatch = (*Entry)->NumUnexpArgTokens;
50 // Allocate memory for a MacroArgs object with the lexer tokens at the end.
51 Result = (MacroArgs *)malloc(sizeof(MacroArgs) +
52 UnexpArgTokens.size() * sizeof(Token));
53 // Construct the MacroArgs object.
55 MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());
58 // Unlink this node from the preprocessors singly linked list.
59 *ResultEnt = Result->ArgCache;
60 Result->NumUnexpArgTokens = UnexpArgTokens.size();
61 Result->VarargsElided = VarargsElided;
62 Result->NumMacroArgs = MI->getNumParams();
65 // Copy the actual unexpanded tokens to immediately after the result ptr.
66 if (!UnexpArgTokens.empty())
67 std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
68 const_cast<Token*>(Result->getUnexpArgument(0)));
73 /// destroy - Destroy and deallocate the memory for this object.
75 void MacroArgs::destroy(Preprocessor &PP) {
76 StringifiedArgs.clear();
78 // Don't clear PreExpArgTokens, just clear the entries. Clearing the entries
79 // would deallocate the element vectors.
80 for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)
81 PreExpArgTokens[i].clear();
83 // Add this to the preprocessor's free list.
84 ArgCache = PP.MacroArgCache;
85 PP.MacroArgCache = this;
88 /// deallocate - This should only be called by the Preprocessor when managing
90 MacroArgs *MacroArgs::deallocate() {
91 MacroArgs *Next = ArgCache;
93 // Run the dtor to deallocate the vectors.
95 // Release the memory for the object.
102 /// getArgLength - Given a pointer to an expanded or unexpanded argument,
103 /// return the number of tokens, not counting the EOF, that make up the
105 unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
106 unsigned NumArgTokens = 0;
107 for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
113 /// getUnexpArgument - Return the unexpanded tokens for the specified formal.
115 const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
116 // The unexpanded argument tokens start immediately after the MacroArgs object
118 const Token *Start = (const Token *)(this+1);
119 const Token *Result = Start;
121 for (; Arg; ++Result) {
122 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
123 if (Result->is(tok::eof))
126 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
131 /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
132 /// by pre-expansion, return false. Otherwise, conservatively return true.
133 bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
134 Preprocessor &PP) const {
135 // If there are no identifiers in the argument list, or if the identifiers are
136 // known to not be macros, pre-expansion won't modify it.
137 for (; ArgTok->isNot(tok::eof); ++ArgTok)
138 if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
139 if (II->hasMacroDefinition())
140 // Return true even though the macro could be a function-like macro
141 // without a following '(' token, or could be disabled, or not visible.
146 /// getPreExpArgument - Return the pre-expanded form of the specified
148 const std::vector<Token> &
149 MacroArgs::getPreExpArgument(unsigned Arg, const MacroInfo *MI,
151 assert(Arg < MI->getNumParams() && "Invalid argument number!");
153 // If we have already computed this, return it.
154 if (PreExpArgTokens.size() < MI->getNumParams())
155 PreExpArgTokens.resize(MI->getNumParams());
157 std::vector<Token> &Result = PreExpArgTokens[Arg];
158 if (!Result.empty()) return Result;
160 SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
162 const Token *AT = getUnexpArgument(Arg);
163 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
165 // Otherwise, we have to pre-expand this argument, populating Result. To do
166 // this, we set up a fake TokenLexer to lex from the unexpanded argument
167 // list. With this installed, we lex expanded tokens until we hit the EOF
168 // token at the end of the unexp list.
169 PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
170 false /*owns tokens*/);
172 // Lex all of the macro-expanded tokens into Result.
174 Result.push_back(Token());
175 Token &Tok = Result.back();
177 } while (Result.back().isNot(tok::eof));
179 // Pop the token stream off the top of the stack. We know that the internal
180 // pointer inside of it is to the "end" of the token stream, but the stack
181 // will not otherwise be popped until the next token is lexed. The problem is
182 // that the token may be lexed sometime after the vector of tokens itself is
183 // destroyed, which would be badness.
184 if (PP.InCachingLexMode())
185 PP.ExitCachingLexMode();
186 PP.RemoveTopOfLexerStack();
191 /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
192 /// tokens into the literal string token that should be produced by the C #
193 /// preprocessor operator. If Charify is true, then it should be turned into
194 /// a character literal for the Microsoft charize (#@) extension.
196 Token MacroArgs::StringifyArgument(const Token *ArgToks,
197 Preprocessor &PP, bool Charify,
198 SourceLocation ExpansionLocStart,
199 SourceLocation ExpansionLocEnd) {
202 Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
204 const Token *ArgTokStart = ArgToks;
206 // Stringify all the tokens.
207 SmallString<128> Result;
211 for (; ArgToks->isNot(tok::eof); ++ArgToks) {
212 const Token &Tok = *ArgToks;
213 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
217 // If this is a string or character constant, escape the token as specified
219 if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
220 Tok.is(tok::char_constant) || // 'x'
221 Tok.is(tok::wide_char_constant) || // L'x'.
222 Tok.is(tok::utf8_char_constant) || // u8'x'.
223 Tok.is(tok::utf16_char_constant) || // u'x'.
224 Tok.is(tok::utf32_char_constant)) { // U'x'.
225 bool Invalid = false;
226 std::string TokStr = PP.getSpelling(Tok, &Invalid);
228 std::string Str = Lexer::Stringify(TokStr);
229 Result.append(Str.begin(), Str.end());
231 } else if (Tok.is(tok::code_completion)) {
232 PP.CodeCompleteNaturalLanguage();
234 // Otherwise, just append the token. Do some gymnastics to get the token
235 // in place and avoid copies where possible.
236 unsigned CurStrLen = Result.size();
237 Result.resize(CurStrLen+Tok.getLength());
238 const char *BufPtr = Result.data() + CurStrLen;
239 bool Invalid = false;
240 unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
243 // If getSpelling returned a pointer to an already uniqued version of
244 // the string instead of filling in BufPtr, memcpy it onto our string.
245 if (ActualTokLen && BufPtr != &Result[CurStrLen])
246 memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
248 // If the token was dirty, the spelling may be shorter than the token.
249 if (ActualTokLen != Tok.getLength())
250 Result.resize(CurStrLen+ActualTokLen);
255 // If the last character of the string is a \, and if it isn't escaped, this
256 // is an invalid string literal, diagnose it as specified in C99.
257 if (Result.back() == '\\') {
258 // Count the number of consequtive \ characters. If even, then they are
259 // just escaped backslashes, otherwise it's an error.
260 unsigned FirstNonSlash = Result.size()-2;
261 // Guaranteed to find the starting " if nothing else.
262 while (Result[FirstNonSlash] == '\\')
264 if ((Result.size()-1-FirstNonSlash) & 1) {
265 // Diagnose errors for things like: #define F(X) #X / F(\)
266 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
267 Result.pop_back(); // remove one of the \'s.
272 // If this is the charify operation and the result is not a legal character
273 // constant, diagnose it.
275 // First step, turn double quotes into single quotes:
277 Result[Result.size()-1] = '\'';
279 // Check for bogus character.
281 if (Result.size() == 3)
282 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
284 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
287 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
288 Result = "' '"; // Use something arbitrary, but legal.
292 PP.CreateString(Result, Tok,
293 ExpansionLocStart, ExpansionLocEnd);
297 /// getStringifiedArgument - Compute, cache, and return the specified argument
298 /// that has been 'stringified' as required by the # operator.
299 const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
301 SourceLocation ExpansionLocStart,
302 SourceLocation ExpansionLocEnd) {
303 assert(ArgNo < getNumMacroArguments() && "Invalid argument number!");
304 if (StringifiedArgs.empty())
305 StringifiedArgs.resize(getNumMacroArguments(), {});
307 if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
308 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
312 return StringifiedArgs[ArgNo];