blob: a201d16590735f828ed8ef3959c4a6d3bddc8c33 [file] [log] [blame]
Nico Webera7d16192014-05-09 00:39:59 +00001//===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//
Chris Lattner7ff66fb2008-03-09 02:55:12 +00002//
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//
Nico Weber33b2d712014-05-09 00:42:08 +000010// This file implements the MacroArgs interface.
Chris Lattner7ff66fb2008-03-09 02:55:12 +000011//
12//===----------------------------------------------------------------------===//
13
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +000014#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Lex/LexDiagnostic.h"
Chris Lattner7ff66fb2008-03-09 02:55:12 +000016#include "clang/Lex/MacroInfo.h"
17#include "clang/Lex/Preprocessor.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000018#include "llvm/ADT/SmallString.h"
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +000019#include "llvm/Support/SaveAndRestore.h"
David Blaikie319b7382011-09-22 02:03:12 +000020#include <algorithm>
21
Chris Lattner7ff66fb2008-03-09 02:55:12 +000022using namespace clang;
23
24/// MacroArgs ctor function - This destroys the vector passed in.
25MacroArgs *MacroArgs::create(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000026 ArrayRef<Token> UnexpArgTokens,
David Blaikie319b7382011-09-22 02:03:12 +000027 bool VarargsElided, Preprocessor &PP) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +000028 assert(MI->isFunctionLike() &&
29 "Can't have args for an object-like macro!");
Craig Topperd2d442c2014-05-17 23:10:59 +000030 MacroArgs **ResultEnt = nullptr;
Chris Lattner9e0005f2009-12-28 06:36:46 +000031 unsigned ClosestMatch = ~0U;
Chris Lattner13162492009-12-15 20:48:12 +000032
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)
David Blaikie319b7382011-09-22 02:03:12 +000037 if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
Chris Lattner9e0005f2009-12-28 06:36:46 +000038 (*Entry)->NumUnexpArgTokens < ClosestMatch) {
39 ResultEnt = Entry;
40
41 // If we have an exact match, use it.
David Blaikie319b7382011-09-22 02:03:12 +000042 if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
Chris Lattner9e0005f2009-12-28 06:36:46 +000043 break;
44 // Otherwise, use the best fit.
45 ClosestMatch = (*Entry)->NumUnexpArgTokens;
Chris Lattner13162492009-12-15 20:48:12 +000046 }
Erich Keane8691d6e2017-06-14 23:09:01 +000047
Chris Lattner9e0005f2009-12-28 06:36:46 +000048 MacroArgs *Result;
Craig Topperd2d442c2014-05-17 23:10:59 +000049 if (!ResultEnt) {
Chris Lattner13162492009-12-15 20:48:12 +000050 // Allocate memory for a MacroArgs object with the lexer tokens at the end.
Erich Keane8691d6e2017-06-14 23:09:01 +000051 Result = (MacroArgs *)malloc(sizeof(MacroArgs) +
52 UnexpArgTokens.size() * sizeof(Token));
Chris Lattner13162492009-12-15 20:48:12 +000053 // Construct the MacroArgs object.
Erich Keane8691d6e2017-06-14 23:09:01 +000054 new (Result)
55 MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumArgs());
Chris Lattner13162492009-12-15 20:48:12 +000056 } else {
Chris Lattner9e0005f2009-12-28 06:36:46 +000057 Result = *ResultEnt;
58 // Unlink this node from the preprocessors singly linked list.
59 *ResultEnt = Result->ArgCache;
David Blaikie319b7382011-09-22 02:03:12 +000060 Result->NumUnexpArgTokens = UnexpArgTokens.size();
Chris Lattner13162492009-12-15 20:48:12 +000061 Result->VarargsElided = VarargsElided;
Erich Keane8691d6e2017-06-14 23:09:01 +000062 Result->NumMacroArgs = MI->getNumArgs();
Chris Lattner13162492009-12-15 20:48:12 +000063 }
Mike Stump11289f42009-09-09 15:08:12 +000064
Chris Lattner7ff66fb2008-03-09 02:55:12 +000065 // Copy the actual unexpanded tokens to immediately after the result ptr.
David Blaikie319b7382011-09-22 02:03:12 +000066 if (!UnexpArgTokens.empty())
67 std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
68 const_cast<Token*>(Result->getUnexpArgument(0)));
Mike Stump11289f42009-09-09 15:08:12 +000069
Chris Lattner7ff66fb2008-03-09 02:55:12 +000070 return Result;
71}
72
73/// destroy - Destroy and deallocate the memory for this object.
74///
Chris Lattnerffbf2de2009-12-14 22:12:52 +000075void MacroArgs::destroy(Preprocessor &PP) {
Chris Lattner13162492009-12-15 20:48:12 +000076 StringifiedArgs.clear();
77
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();
82
83 // Add this to the preprocessor's free list.
84 ArgCache = PP.MacroArgCache;
85 PP.MacroArgCache = this;
Chris Lattner7ff66fb2008-03-09 02:55:12 +000086}
87
Chris Lattnerd19564b2009-12-15 01:51:03 +000088/// deallocate - This should only be called by the Preprocessor when managing
89/// its freelist.
90MacroArgs *MacroArgs::deallocate() {
91 MacroArgs *Next = ArgCache;
92
93 // Run the dtor to deallocate the vectors.
94 this->~MacroArgs();
95 // Release the memory for the object.
96 free(this);
97
98 return Next;
99}
100
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000101
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
104/// argument.
105unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
106 unsigned NumArgTokens = 0;
107 for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
108 ++NumArgTokens;
109 return NumArgTokens;
110}
111
112
113/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
114///
115const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
116 // The unexpanded argument tokens start immediately after the MacroArgs object
117 // in memory.
118 const Token *Start = (const Token *)(this+1);
119 const Token *Result = Start;
120 // Scan to find Arg.
121 for (; Arg; ++Result) {
122 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
123 if (Result->is(tok::eof))
124 --Arg;
125 }
Chris Lattnerf160b5f2009-05-13 00:55:26 +0000126 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000127 return Result;
128}
129
130
131/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
132/// by pre-expansion, return false. Otherwise, conservatively return true.
133bool 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)
Richard Smith20e883e2015-04-29 23:20:19 +0000138 if (IdentifierInfo *II = ArgTok->getIdentifierInfo())
139 if (II->hasMacroDefinition())
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000140 // Return true even though the macro could be a function-like macro
Richard Smith20e883e2015-04-29 23:20:19 +0000141 // without a following '(' token, or could be disabled, or not visible.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000142 return true;
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000143 return false;
144}
145
146/// getPreExpArgument - Return the pre-expanded form of the specified
147/// argument.
148const std::vector<Token> &
Chris Lattner394f5892009-12-28 06:17:16 +0000149MacroArgs::getPreExpArgument(unsigned Arg, const MacroInfo *MI,
150 Preprocessor &PP) {
151 assert(Arg < MI->getNumArgs() && "Invalid argument number!");
Mike Stump11289f42009-09-09 15:08:12 +0000152
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000153 // If we have already computed this, return it.
Chris Lattner394f5892009-12-28 06:17:16 +0000154 if (PreExpArgTokens.size() < MI->getNumArgs())
155 PreExpArgTokens.resize(MI->getNumArgs());
156
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000157 std::vector<Token> &Result = PreExpArgTokens[Arg];
158 if (!Result.empty()) return Result;
159
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000160 SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
161
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000162 const Token *AT = getUnexpArgument(Arg);
163 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Mike Stump11289f42009-09-09 15:08:12 +0000164
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000165 // 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.
Mike Stump11289f42009-09-09 15:08:12 +0000169 PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
Chris Lattner3e468322008-03-10 06:06:04 +0000170 false /*owns tokens*/);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000171
172 // Lex all of the macro-expanded tokens into Result.
173 do {
174 Result.push_back(Token());
Chris Lattnerad13cf42009-01-26 04:33:10 +0000175 Token &Tok = Result.back();
176 PP.Lex(Tok);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000177 } while (Result.back().isNot(tok::eof));
Mike Stump11289f42009-09-09 15:08:12 +0000178
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000179 // 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.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000184 if (PP.InCachingLexMode())
185 PP.ExitCachingLexMode();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000186 PP.RemoveTopOfLexerStack();
187 return Result;
188}
189
190
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.
195///
196Token MacroArgs::StringifyArgument(const Token *ArgToks,
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000197 Preprocessor &PP, bool Charify,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000198 SourceLocation ExpansionLocStart,
199 SourceLocation ExpansionLocEnd) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000200 Token Tok;
201 Tok.startToken();
Chris Lattner3859c742009-12-23 19:15:27 +0000202 Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000203
204 const Token *ArgTokStart = ArgToks;
Mike Stump11289f42009-09-09 15:08:12 +0000205
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000206 // Stringify all the tokens.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000207 SmallString<128> Result;
Chris Lattner933d5ff2009-01-05 23:04:18 +0000208 Result += "\"";
Mike Stump11289f42009-09-09 15:08:12 +0000209
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000210 bool isFirst = true;
211 for (; ArgToks->isNot(tok::eof); ++ArgToks) {
212 const Token &Tok = *ArgToks;
213 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
214 Result += ' ';
215 isFirst = false;
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000217 // If this is a string or character constant, escape the token as specified
218 // by 6.10.3.2p2.
Richard Smithc98bb4e2013-03-09 23:30:15 +0000219 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'.
Richard Smith3e3a7052014-11-08 06:08:42 +0000222 Tok.is(tok::utf8_char_constant) || // u8'x'.
Richard Smithc98bb4e2013-03-09 23:30:15 +0000223 Tok.is(tok::utf16_char_constant) || // u'x'.
224 Tok.is(tok::utf32_char_constant)) { // U'x'.
Douglas Gregordc970f02010-03-16 22:30:13 +0000225 bool Invalid = false;
226 std::string TokStr = PP.getSpelling(Tok, &Invalid);
227 if (!Invalid) {
228 std::string Str = Lexer::Stringify(TokStr);
229 Result.append(Str.begin(), Str.end());
230 }
Argyrios Kyrtzidisb914e3b2011-09-04 03:32:19 +0000231 } else if (Tok.is(tok::code_completion)) {
232 PP.CodeCompleteNaturalLanguage();
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000233 } else {
Chris Lattner933d5ff2009-01-05 23:04:18 +0000234 // 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());
David Majnemerd3c3e782014-10-25 11:40:40 +0000238 const char *BufPtr = Result.data() + CurStrLen;
Douglas Gregordc970f02010-03-16 22:30:13 +0000239 bool Invalid = false;
240 unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Douglas Gregordc970f02010-03-16 22:30:13 +0000242 if (!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.
David Majnemerd3c3e782014-10-25 11:40:40 +0000245 if (ActualTokLen && BufPtr != &Result[CurStrLen])
Douglas Gregordc970f02010-03-16 22:30:13 +0000246 memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000247
Douglas Gregordc970f02010-03-16 22:30:13 +0000248 // If the token was dirty, the spelling may be shorter than the token.
249 if (ActualTokLen != Tok.getLength())
250 Result.resize(CurStrLen+ActualTokLen);
251 }
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000252 }
253 }
Mike Stump11289f42009-09-09 15:08:12 +0000254
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000255 // 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.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000257 if (Result.back() == '\\') {
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000258 // 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] == '\\')
263 --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);
Chris Lattner933d5ff2009-01-05 23:04:18 +0000267 Result.pop_back(); // remove one of the \'s.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000268 }
269 }
270 Result += '"';
Mike Stump11289f42009-09-09 15:08:12 +0000271
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000272 // If this is the charify operation and the result is not a legal character
273 // constant, diagnose it.
274 if (Charify) {
275 // First step, turn double quotes into single quotes:
276 Result[0] = '\'';
277 Result[Result.size()-1] = '\'';
Mike Stump11289f42009-09-09 15:08:12 +0000278
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000279 // Check for bogus character.
280 bool isBad = false;
Chris Lattner933d5ff2009-01-05 23:04:18 +0000281 if (Result.size() == 3)
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000282 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000283 else
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000284 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000286 if (isBad) {
287 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
288 Result = "' '"; // Use something arbitrary, but legal.
289 }
290 }
Mike Stump11289f42009-09-09 15:08:12 +0000291
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000292 PP.CreateString(Result, Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000293 ExpansionLocStart, ExpansionLocEnd);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000294 return Tok;
295}
296
297/// getStringifiedArgument - Compute, cache, and return the specified argument
298/// that has been 'stringified' as required by the # operator.
299const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000300 Preprocessor &PP,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000301 SourceLocation ExpansionLocStart,
302 SourceLocation ExpansionLocEnd) {
Erich Keane8691d6e2017-06-14 23:09:01 +0000303 assert(ArgNo < getNumMacroArguments() && "Invalid argument number!");
304 if (StringifiedArgs.empty())
305 StringifiedArgs.resize(getNumMacroArguments(), {});
306
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000307 if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
Argyrios Kyrtzidis41fb2d92011-07-07 03:40:34 +0000308 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000309 /*Charify=*/false,
310 ExpansionLocStart,
311 ExpansionLocEnd);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000312 return StringifiedArgs[ArgNo];
313}