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