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