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