clang  6.0.0svn
MacroArgs.cpp
Go to the documentation of this file.
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"
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.
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  }
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 ///
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.
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 // This function assumes that the variadic arguments are the tokens
139 // corresponding to the last parameter (ellipsis) - and since tokens are
140 // separated by the 'eof' token, if that is the only token corresponding to that
141 // last parameter, we know no variadic arguments were supplied.
143  if (!MI->isVariadic())
144  return false;
145  const int VariadicArgIndex = getNumMacroArguments() - 1;
146  return getUnexpArgument(VariadicArgIndex)->isNot(tok::eof);
147 }
148 
149 /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
150 /// by pre-expansion, return false. Otherwise, conservatively return true.
152  Preprocessor &PP) const {
153  // If there are no identifiers in the argument list, or if the identifiers are
154  // known to not be macros, pre-expansion won't modify it.
155  for (; ArgTok->isNot(tok::eof); ++ArgTok)
156  if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
157  if (II->hasMacroDefinition())
158  // Return true even though the macro could be a function-like macro
159  // without a following '(' token, or could be disabled, or not visible.
160  return true;
161  return false;
162 }
163 
164 /// getPreExpArgument - Return the pre-expanded form of the specified
165 /// argument.
166 const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,
167  Preprocessor &PP) {
168  assert(Arg < getNumMacroArguments() && "Invalid argument number!");
169 
170  // If we have already computed this, return it.
171  if (PreExpArgTokens.size() < getNumMacroArguments())
172  PreExpArgTokens.resize(getNumMacroArguments());
173 
174  std::vector<Token> &Result = PreExpArgTokens[Arg];
175  if (!Result.empty()) return Result;
176 
177  SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
178 
179  const Token *AT = getUnexpArgument(Arg);
180  unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
181 
182  // Otherwise, we have to pre-expand this argument, populating Result. To do
183  // this, we set up a fake TokenLexer to lex from the unexpanded argument
184  // list. With this installed, we lex expanded tokens until we hit the EOF
185  // token at the end of the unexp list.
186  PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
187  false /*owns tokens*/);
188 
189  // Lex all of the macro-expanded tokens into Result.
190  do {
191  Result.push_back(Token());
192  Token &Tok = Result.back();
193  PP.Lex(Tok);
194  } while (Result.back().isNot(tok::eof));
195 
196  // Pop the token stream off the top of the stack. We know that the internal
197  // pointer inside of it is to the "end" of the token stream, but the stack
198  // will not otherwise be popped until the next token is lexed. The problem is
199  // that the token may be lexed sometime after the vector of tokens itself is
200  // destroyed, which would be badness.
201  if (PP.InCachingLexMode())
202  PP.ExitCachingLexMode();
204  return Result;
205 }
206 
207 
208 /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
209 /// tokens into the literal string token that should be produced by the C #
210 /// preprocessor operator. If Charify is true, then it should be turned into
211 /// a character literal for the Microsoft charize (#@) extension.
212 ///
214  Preprocessor &PP, bool Charify,
215  SourceLocation ExpansionLocStart,
216  SourceLocation ExpansionLocEnd) {
217  Token Tok;
218  Tok.startToken();
219  Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
220 
221  const Token *ArgTokStart = ArgToks;
222 
223  // Stringify all the tokens.
225  Result += "\"";
226 
227  bool isFirst = true;
228  for (; ArgToks->isNot(tok::eof); ++ArgToks) {
229  const Token &Tok = *ArgToks;
230  if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
231  Result += ' ';
232  isFirst = false;
233 
234  // If this is a string or character constant, escape the token as specified
235  // by 6.10.3.2p2.
236  if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
237  Tok.is(tok::char_constant) || // 'x'
238  Tok.is(tok::wide_char_constant) || // L'x'.
239  Tok.is(tok::utf8_char_constant) || // u8'x'.
240  Tok.is(tok::utf16_char_constant) || // u'x'.
241  Tok.is(tok::utf32_char_constant)) { // U'x'.
242  bool Invalid = false;
243  std::string TokStr = PP.getSpelling(Tok, &Invalid);
244  if (!Invalid) {
245  std::string Str = Lexer::Stringify(TokStr);
246  Result.append(Str.begin(), Str.end());
247  }
248  } else if (Tok.is(tok::code_completion)) {
250  } else {
251  // Otherwise, just append the token. Do some gymnastics to get the token
252  // in place and avoid copies where possible.
253  unsigned CurStrLen = Result.size();
254  Result.resize(CurStrLen+Tok.getLength());
255  const char *BufPtr = Result.data() + CurStrLen;
256  bool Invalid = false;
257  unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
258 
259  if (!Invalid) {
260  // If getSpelling returned a pointer to an already uniqued version of
261  // the string instead of filling in BufPtr, memcpy it onto our string.
262  if (ActualTokLen && BufPtr != &Result[CurStrLen])
263  memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
264 
265  // If the token was dirty, the spelling may be shorter than the token.
266  if (ActualTokLen != Tok.getLength())
267  Result.resize(CurStrLen+ActualTokLen);
268  }
269  }
270  }
271 
272  // If the last character of the string is a \, and if it isn't escaped, this
273  // is an invalid string literal, diagnose it as specified in C99.
274  if (Result.back() == '\\') {
275  // Count the number of consequtive \ characters. If even, then they are
276  // just escaped backslashes, otherwise it's an error.
277  unsigned FirstNonSlash = Result.size()-2;
278  // Guaranteed to find the starting " if nothing else.
279  while (Result[FirstNonSlash] == '\\')
280  --FirstNonSlash;
281  if ((Result.size()-1-FirstNonSlash) & 1) {
282  // Diagnose errors for things like: #define F(X) #X / F(\)
283  PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
284  Result.pop_back(); // remove one of the \'s.
285  }
286  }
287  Result += '"';
288 
289  // If this is the charify operation and the result is not a legal character
290  // constant, diagnose it.
291  if (Charify) {
292  // First step, turn double quotes into single quotes:
293  Result[0] = '\'';
294  Result[Result.size()-1] = '\'';
295 
296  // Check for bogus character.
297  bool isBad = false;
298  if (Result.size() == 3)
299  isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
300  else
301  isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
302 
303  if (isBad) {
304  PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
305  Result = "' '"; // Use something arbitrary, but legal.
306  }
307  }
308 
309  PP.CreateString(Result, Tok,
310  ExpansionLocStart, ExpansionLocEnd);
311  return Tok;
312 }
313 
314 /// getStringifiedArgument - Compute, cache, and return the specified argument
315 /// that has been 'stringified' as required by the # operator.
317  Preprocessor &PP,
318  SourceLocation ExpansionLocStart,
319  SourceLocation ExpansionLocEnd) {
320  assert(ArgNo < getNumMacroArguments() && "Invalid argument number!");
321  if (StringifiedArgs.empty())
322  StringifiedArgs.resize(getNumMacroArguments(), {});
323 
324  if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
325  StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
326  /*Charify=*/false,
327  ExpansionLocStart,
328  ExpansionLocEnd);
329  return StringifiedArgs[ArgNo];
330 }
bool invokedWithVariadicArgument(const MacroInfo *const MI) const
Returns true if the macro was defined with a variadic (ellipsis) parameter AND was invoked with at le...
Definition: MacroArgs.cpp:142
bool ArgNeedsPreexpansion(const Token *ArgTok, Preprocessor &PP) const
ArgNeedsPreexpansion - If we can prove that the argument won&#39;t be affected by pre-expansion, return false.
Definition: MacroArgs.cpp:151
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:95
Defines the clang::MacroInfo and clang::MacroDirective classes.
virtual void clear()
bool isVariadic() const
Definition: MacroInfo.h:208
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token...
Definition: TokenKinds.h:79
tok::TokenKind getKind() const
Definition: Token.h:90
One of these records is kept for each identifier that is lexed.
Token - This structure provides full information about a lexed token.
Definition: Token.h:35
void setKind(tok::TokenKind K)
Definition: Token.h:91
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the &#39;spelling&#39; of the token at the given location; does not go up to the spelling location or ...
const FormatToken & Tok
void destroy(Preprocessor &PP)
destroy - Destroy and deallocate the memory for this object.
Definition: MacroArgs.cpp:78
const Token & getStringifiedArgument(unsigned ArgNo, Preprocessor &PP, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd)
getStringifiedArgument - Compute, cache, and return the specified argument that has been &#39;stringified...
Definition: MacroArgs.cpp:316
static Token StringifyArgument(const Token *ArgToks, Preprocessor &PP, bool Charify, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd)
StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of tokens into the literal string...
Definition: MacroArgs.cpp:213
unsigned getNumParams() const
Definition: MacroInfo.h:183
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition: MacroArgs.h:30
Defines the clang::Preprocessor interface.
The result type of a method or function.
MacroArgs * deallocate()
deallocate - This should only be called by the Preprocessor when managing its freelist.
Definition: MacroArgs.cpp:93
Encodes a location in the source.
IdentifierInfo * getIdentifierInfo() const
Definition: Token.h:177
void Lex(Token &Result)
Lex the next token for this preprocessor.
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:266
bool isNot(tok::TokenKind K) const
Definition: Token.h:96
Dataflow Directional Tag Classes.
bool isFunctionLike() const
Definition: MacroInfo.h:200
const std::vector< Token > & getPreExpArgument(unsigned Arg, Preprocessor &PP)
getPreExpArgument - Return the pre-expanded form of the specified argument.
Definition: MacroArgs.cpp:166
static unsigned getArgLength(const Token *ArgPtr)
getArgLength - Given a pointer to an expanded or unexpanded argument, return the number of tokens...
Definition: MacroArgs.cpp:110
void CodeCompleteNaturalLanguage()
Hook used by the lexer to invoke the "natural language" code completion point.
unsigned getLength() const
Definition: Token.h:127
unsigned getNumMacroArguments() const
getNumMacroArguments - Return the number of arguments the invoked macro expects.
Definition: MacroArgs.h:106
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:40
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token&#39;s location and length to ...
static MacroArgs * create(const MacroInfo *MI, ArrayRef< Token > UnexpArgTokens, bool VarargsElided, Preprocessor &PP)
MacroArgs ctor function - Create a new MacroArgs object with the specified macro and argument info...
Definition: MacroArgs.cpp:25
void RemoveTopOfLexerStack()
Pop the current lexer/macro exp off the top of the lexer stack.
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition: Token.h:270
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
const Token * getUnexpArgument(unsigned Arg) const
getUnexpArgument - Return a pointer to the first token of the unexpanded token list for the specified...
Definition: MacroArgs.cpp:120
void startToken()
Reset all flags to cleared.
Definition: Token.h:169
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping &#39;\&#39; and " characters and ii) ...
Definition: Lexer.cpp:246
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:127