blob: 968c15e3c27b59872da7c40cfee7e0a177ba74bf [file] [log] [blame]
Chris Lattnere5c8ffe2008-03-09 02:55:12 +00001//===--- TokenLexer.cpp - Lex from a token stream -------------------------===//
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 TokenLexer interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MacroArgs.h"
15#include "clang/Lex/MacroInfo.h"
16#include "clang/Lex/Preprocessor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000017#include "clang/Lex/LexDiagnostic.h"
Chris Lattnere5c8ffe2008-03-09 02:55:12 +000018using namespace clang;
19
20/// MacroArgs ctor function - This destroys the vector passed in.
21MacroArgs *MacroArgs::create(const MacroInfo *MI,
22 const Token *UnexpArgTokens,
Chris Lattner561395b2009-12-14 22:12:52 +000023 unsigned NumToks, bool VarargsElided,
24 Preprocessor &PP) {
Chris Lattnere5c8ffe2008-03-09 02:55:12 +000025 assert(MI->isFunctionLike() &&
26 "Can't have args for an object-like macro!");
Chris Lattner4fe739f2009-12-28 06:36:46 +000027 MacroArgs **ResultEnt = 0;
28 unsigned ClosestMatch = ~0U;
Chris Lattner46084592009-12-15 20:48:12 +000029
30 // See if we have an entry with a big enough argument list to reuse on the
31 // free list. If so, reuse it.
32 for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
33 Entry = &(*Entry)->ArgCache)
Chris Lattner4fe739f2009-12-28 06:36:46 +000034 if ((*Entry)->NumUnexpArgTokens >= NumToks &&
35 (*Entry)->NumUnexpArgTokens < ClosestMatch) {
36 ResultEnt = Entry;
37
38 // If we have an exact match, use it.
39 if ((*Entry)->NumUnexpArgTokens == NumToks)
40 break;
41 // Otherwise, use the best fit.
42 ClosestMatch = (*Entry)->NumUnexpArgTokens;
Chris Lattner46084592009-12-15 20:48:12 +000043 }
44
Chris Lattner4fe739f2009-12-28 06:36:46 +000045 MacroArgs *Result;
46 if (ResultEnt == 0) {
Chris Lattner46084592009-12-15 20:48:12 +000047 // Allocate memory for a MacroArgs object with the lexer tokens at the end.
48 Result = (MacroArgs*)malloc(sizeof(MacroArgs) + NumToks*sizeof(Token));
49 // Construct the MacroArgs object.
50 new (Result) MacroArgs(NumToks, VarargsElided);
51 } else {
Chris Lattner4fe739f2009-12-28 06:36:46 +000052 Result = *ResultEnt;
53 // Unlink this node from the preprocessors singly linked list.
54 *ResultEnt = Result->ArgCache;
Chris Lattner46084592009-12-15 20:48:12 +000055 Result->NumUnexpArgTokens = NumToks;
56 Result->VarargsElided = VarargsElided;
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattnere5c8ffe2008-03-09 02:55:12 +000059 // Copy the actual unexpanded tokens to immediately after the result ptr.
60 if (NumToks)
61 memcpy(const_cast<Token*>(Result->getUnexpArgument(0)),
62 UnexpArgTokens, NumToks*sizeof(Token));
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattnere5c8ffe2008-03-09 02:55:12 +000064 return Result;
65}
66
67/// destroy - Destroy and deallocate the memory for this object.
68///
Chris Lattner561395b2009-12-14 22:12:52 +000069void MacroArgs::destroy(Preprocessor &PP) {
Chris Lattner46084592009-12-15 20:48:12 +000070 StringifiedArgs.clear();
71
72 // Don't clear PreExpArgTokens, just clear the entries. Clearing the entries
73 // would deallocate the element vectors.
74 for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)
75 PreExpArgTokens[i].clear();
76
77 // Add this to the preprocessor's free list.
78 ArgCache = PP.MacroArgCache;
79 PP.MacroArgCache = this;
Chris Lattnere5c8ffe2008-03-09 02:55:12 +000080}
81
Chris Lattner23f77e52009-12-15 01:51:03 +000082/// deallocate - This should only be called by the Preprocessor when managing
83/// its freelist.
84MacroArgs *MacroArgs::deallocate() {
85 MacroArgs *Next = ArgCache;
86
87 // Run the dtor to deallocate the vectors.
88 this->~MacroArgs();
89 // Release the memory for the object.
90 free(this);
91
92 return Next;
93}
94
Chris Lattnere5c8ffe2008-03-09 02:55:12 +000095
96/// getArgLength - Given a pointer to an expanded or unexpanded argument,
97/// return the number of tokens, not counting the EOF, that make up the
98/// argument.
99unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
100 unsigned NumArgTokens = 0;
101 for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
102 ++NumArgTokens;
103 return NumArgTokens;
104}
105
106
107/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
108///
109const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
110 // The unexpanded argument tokens start immediately after the MacroArgs object
111 // in memory.
112 const Token *Start = (const Token *)(this+1);
113 const Token *Result = Start;
114 // Scan to find Arg.
115 for (; Arg; ++Result) {
116 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
117 if (Result->is(tok::eof))
118 --Arg;
119 }
Chris Lattner9fc9e772009-05-13 00:55:26 +0000120 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000121 return Result;
122}
123
124
125/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
126/// by pre-expansion, return false. Otherwise, conservatively return true.
127bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
128 Preprocessor &PP) const {
129 // If there are no identifiers in the argument list, or if the identifiers are
130 // known to not be macros, pre-expansion won't modify it.
131 for (; ArgTok->isNot(tok::eof); ++ArgTok)
132 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
133 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled())
134 // Return true even though the macro could be a function-like macro
135 // without a following '(' token.
136 return true;
137 }
138 return false;
139}
140
141/// getPreExpArgument - Return the pre-expanded form of the specified
142/// argument.
143const std::vector<Token> &
Chris Lattnerf5809a72009-12-28 06:17:16 +0000144MacroArgs::getPreExpArgument(unsigned Arg, const MacroInfo *MI,
145 Preprocessor &PP) {
146 assert(Arg < MI->getNumArgs() && "Invalid argument number!");
Mike Stump1eb44332009-09-09 15:08:12 +0000147
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000148 // If we have already computed this, return it.
Chris Lattnerf5809a72009-12-28 06:17:16 +0000149 if (PreExpArgTokens.size() < MI->getNumArgs())
150 PreExpArgTokens.resize(MI->getNumArgs());
151
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000152 std::vector<Token> &Result = PreExpArgTokens[Arg];
153 if (!Result.empty()) return Result;
154
155 const Token *AT = getUnexpArgument(Arg);
156 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000158 // Otherwise, we have to pre-expand this argument, populating Result. To do
159 // this, we set up a fake TokenLexer to lex from the unexpanded argument
160 // list. With this installed, we lex expanded tokens until we hit the EOF
161 // token at the end of the unexp list.
Mike Stump1eb44332009-09-09 15:08:12 +0000162 PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
Chris Lattner6b884502008-03-10 06:06:04 +0000163 false /*owns tokens*/);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000164
165 // Lex all of the macro-expanded tokens into Result.
166 do {
167 Result.push_back(Token());
Chris Lattner7c351222009-01-26 04:33:10 +0000168 Token &Tok = Result.back();
169 PP.Lex(Tok);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000170 } while (Result.back().isNot(tok::eof));
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000172 // Pop the token stream off the top of the stack. We know that the internal
173 // pointer inside of it is to the "end" of the token stream, but the stack
174 // will not otherwise be popped until the next token is lexed. The problem is
175 // that the token may be lexed sometime after the vector of tokens itself is
176 // destroyed, which would be badness.
177 PP.RemoveTopOfLexerStack();
178 return Result;
179}
180
181
182/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
183/// tokens into the literal string token that should be produced by the C #
184/// preprocessor operator. If Charify is true, then it should be turned into
185/// a character literal for the Microsoft charize (#@) extension.
186///
187Token MacroArgs::StringifyArgument(const Token *ArgToks,
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +0000188 Preprocessor &PP, bool Charify,
189 SourceLocation hashInstLoc) {
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000190 Token Tok;
191 Tok.startToken();
Chris Lattner66335222009-12-23 19:15:27 +0000192 Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000193
194 const Token *ArgTokStart = ArgToks;
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000196 // Stringify all the tokens.
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000197 llvm::SmallString<128> Result;
198 Result += "\"";
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000200 bool isFirst = true;
201 for (; ArgToks->isNot(tok::eof); ++ArgToks) {
202 const Token &Tok = *ArgToks;
203 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
204 Result += ' ';
205 isFirst = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000207 // If this is a string or character constant, escape the token as specified
208 // by 6.10.3.2p2.
209 if (Tok.is(tok::string_literal) || // "foo"
210 Tok.is(tok::wide_string_literal) || // L"foo"
211 Tok.is(tok::char_constant)) { // 'x' and L'x'.
Douglas Gregor453091c2010-03-16 22:30:13 +0000212 bool Invalid = false;
213 std::string TokStr = PP.getSpelling(Tok, &Invalid);
214 if (!Invalid) {
215 std::string Str = Lexer::Stringify(TokStr);
216 Result.append(Str.begin(), Str.end());
217 }
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000218 } else {
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000219 // Otherwise, just append the token. Do some gymnastics to get the token
220 // in place and avoid copies where possible.
221 unsigned CurStrLen = Result.size();
222 Result.resize(CurStrLen+Tok.getLength());
223 const char *BufPtr = &Result[CurStrLen];
Douglas Gregor453091c2010-03-16 22:30:13 +0000224 bool Invalid = false;
225 unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
Mike Stump1eb44332009-09-09 15:08:12 +0000226
Douglas Gregor453091c2010-03-16 22:30:13 +0000227 if (!Invalid) {
228 // If getSpelling returned a pointer to an already uniqued version of
229 // the string instead of filling in BufPtr, memcpy it onto our string.
230 if (BufPtr != &Result[CurStrLen])
231 memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
Mike Stump1eb44332009-09-09 15:08:12 +0000232
Douglas Gregor453091c2010-03-16 22:30:13 +0000233 // If the token was dirty, the spelling may be shorter than the token.
234 if (ActualTokLen != Tok.getLength())
235 Result.resize(CurStrLen+ActualTokLen);
236 }
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000237 }
238 }
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000240 // If the last character of the string is a \, and if it isn't escaped, this
241 // is an invalid string literal, diagnose it as specified in C99.
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000242 if (Result.back() == '\\') {
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000243 // Count the number of consequtive \ characters. If even, then they are
244 // just escaped backslashes, otherwise it's an error.
245 unsigned FirstNonSlash = Result.size()-2;
246 // Guaranteed to find the starting " if nothing else.
247 while (Result[FirstNonSlash] == '\\')
248 --FirstNonSlash;
249 if ((Result.size()-1-FirstNonSlash) & 1) {
250 // Diagnose errors for things like: #define F(X) #X / F(\)
251 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000252 Result.pop_back(); // remove one of the \'s.
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000253 }
254 }
255 Result += '"';
Mike Stump1eb44332009-09-09 15:08:12 +0000256
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000257 // If this is the charify operation and the result is not a legal character
258 // constant, diagnose it.
259 if (Charify) {
260 // First step, turn double quotes into single quotes:
261 Result[0] = '\'';
262 Result[Result.size()-1] = '\'';
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000264 // Check for bogus character.
265 bool isBad = false;
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000266 if (Result.size() == 3)
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000267 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000268 else
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000269 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
Mike Stump1eb44332009-09-09 15:08:12 +0000270
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000271 if (isBad) {
272 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
273 Result = "' '"; // Use something arbitrary, but legal.
274 }
275 }
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +0000277 PP.CreateString(&Result[0], Result.size(), Tok, hashInstLoc);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000278 return Tok;
279}
280
281/// getStringifiedArgument - Compute, cache, and return the specified argument
282/// that has been 'stringified' as required by the # operator.
283const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +0000284 Preprocessor &PP,
285 SourceLocation hashInstLoc) {
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000286 assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
287 if (StringifiedArgs.empty()) {
288 StringifiedArgs.resize(getNumArguments());
Chandler Carruth75c40642011-04-28 08:19:45 +0000289 memset((void*)&StringifiedArgs[0], 0,
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000290 sizeof(StringifiedArgs[0])*getNumArguments());
291 }
292 if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
Argyrios Kyrtzidisb73377e2011-07-07 03:40:34 +0000293 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
294 /*Charify=*/false, hashInstLoc);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000295 return StringifiedArgs[ArgNo];
296}