1 //===--- TokenLexer.cpp - Lex from a token stream -------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the TokenLexer interface.
12 //===----------------------------------------------------------------------===//
14 #include "MacroArgs.h"
15 #include "clang/Lex/MacroInfo.h"
16 #include "clang/Lex/Preprocessor.h"
17 #include "clang/Lex/LexDiagnostic.h"
18 using namespace clang
;
20 /// MacroArgs ctor function - This destroys the vector passed in.
21 MacroArgs
*MacroArgs::create(const MacroInfo
*MI
,
22 const Token
*UnexpArgTokens
,
23 unsigned NumToks
, bool VarargsElided
,
25 assert(MI
->isFunctionLike() &&
26 "Can't have args for an object-like macro!");
27 MacroArgs
**ResultEnt
= 0;
28 unsigned ClosestMatch
= ~0U;
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
)
34 if ((*Entry
)->NumUnexpArgTokens
>= NumToks
&&
35 (*Entry
)->NumUnexpArgTokens
< ClosestMatch
) {
38 // If we have an exact match, use it.
39 if ((*Entry
)->NumUnexpArgTokens
== NumToks
)
41 // Otherwise, use the best fit.
42 ClosestMatch
= (*Entry
)->NumUnexpArgTokens
;
47 // 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
);
53 // Unlink this node from the preprocessors singly linked list.
54 *ResultEnt
= Result
->ArgCache
;
55 Result
->NumUnexpArgTokens
= NumToks
;
56 Result
->VarargsElided
= VarargsElided
;
59 // Copy the actual unexpanded tokens to immediately after the result ptr.
61 memcpy(const_cast<Token
*>(Result
->getUnexpArgument(0)),
62 UnexpArgTokens
, NumToks
*sizeof(Token
));
67 /// destroy - Destroy and deallocate the memory for this object.
69 void MacroArgs::destroy(Preprocessor
&PP
) {
70 StringifiedArgs
.clear();
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();
77 // Add this to the preprocessor's free list.
78 ArgCache
= PP
.MacroArgCache
;
79 PP
.MacroArgCache
= this;
82 /// deallocate - This should only be called by the Preprocessor when managing
84 MacroArgs
*MacroArgs::deallocate() {
85 MacroArgs
*Next
= ArgCache
;
87 // Run the dtor to deallocate the vectors.
89 // Release the memory for the object.
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
99 unsigned MacroArgs::getArgLength(const Token
*ArgPtr
) {
100 unsigned NumArgTokens
= 0;
101 for (; ArgPtr
->isNot(tok::eof
); ++ArgPtr
)
107 /// getUnexpArgument - Return the unexpanded tokens for the specified formal.
109 const Token
*MacroArgs::getUnexpArgument(unsigned Arg
) const {
110 // The unexpanded argument tokens start immediately after the MacroArgs object
112 const Token
*Start
= (const Token
*)(this+1);
113 const Token
*Result
= Start
;
115 for (; Arg
; ++Result
) {
116 assert(Result
< Start
+NumUnexpArgTokens
&& "Invalid arg #");
117 if (Result
->is(tok::eof
))
120 assert(Result
< Start
+NumUnexpArgTokens
&& "Invalid arg #");
125 /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
126 /// by pre-expansion, return false. Otherwise, conservatively return true.
127 bool 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.
141 /// getPreExpArgument - Return the pre-expanded form of the specified
143 const std::vector
<Token
> &
144 MacroArgs::getPreExpArgument(unsigned Arg
, const MacroInfo
*MI
,
146 assert(Arg
< MI
->getNumArgs() && "Invalid argument number!");
148 // If we have already computed this, return it.
149 if (PreExpArgTokens
.size() < MI
->getNumArgs())
150 PreExpArgTokens
.resize(MI
->getNumArgs());
152 std::vector
<Token
> &Result
= PreExpArgTokens
[Arg
];
153 if (!Result
.empty()) return Result
;
155 const Token
*AT
= getUnexpArgument(Arg
);
156 unsigned NumToks
= getArgLength(AT
)+1; // Include the EOF.
158 // 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.
162 PP
.EnterTokenStream(AT
, NumToks
, false /*disable expand*/,
163 false /*owns tokens*/);
165 // Lex all of the macro-expanded tokens into Result.
167 Result
.push_back(Token());
168 Token
&Tok
= Result
.back();
170 } while (Result
.back().isNot(tok::eof
));
172 // 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();
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.
187 Token
MacroArgs::StringifyArgument(const Token
*ArgToks
,
188 Preprocessor
&PP
, bool Charify
) {
191 Tok
.setKind(Charify
? tok::char_constant
: tok::string_literal
);
193 const Token
*ArgTokStart
= ArgToks
;
195 // Stringify all the tokens.
196 llvm::SmallString
<128> Result
;
200 for (; ArgToks
->isNot(tok::eof
); ++ArgToks
) {
201 const Token
&Tok
= *ArgToks
;
202 if (!isFirst
&& (Tok
.hasLeadingSpace() || Tok
.isAtStartOfLine()))
206 // If this is a string or character constant, escape the token as specified
208 if (Tok
.is(tok::string_literal
) || // "foo"
209 Tok
.is(tok::wide_string_literal
) || // L"foo"
210 Tok
.is(tok::char_constant
)) { // 'x' and L'x'.
211 bool Invalid
= false;
212 std::string TokStr
= PP
.getSpelling(Tok
, &Invalid
);
214 std::string Str
= Lexer::Stringify(TokStr
);
215 Result
.append(Str
.begin(), Str
.end());
218 // Otherwise, just append the token. Do some gymnastics to get the token
219 // in place and avoid copies where possible.
220 unsigned CurStrLen
= Result
.size();
221 Result
.resize(CurStrLen
+Tok
.getLength());
222 const char *BufPtr
= &Result
[CurStrLen
];
223 bool Invalid
= false;
224 unsigned ActualTokLen
= PP
.getSpelling(Tok
, BufPtr
, &Invalid
);
227 // If getSpelling returned a pointer to an already uniqued version of
228 // the string instead of filling in BufPtr, memcpy it onto our string.
229 if (BufPtr
!= &Result
[CurStrLen
])
230 memcpy(&Result
[CurStrLen
], BufPtr
, ActualTokLen
);
232 // If the token was dirty, the spelling may be shorter than the token.
233 if (ActualTokLen
!= Tok
.getLength())
234 Result
.resize(CurStrLen
+ActualTokLen
);
239 // If the last character of the string is a \, and if it isn't escaped, this
240 // is an invalid string literal, diagnose it as specified in C99.
241 if (Result
.back() == '\\') {
242 // Count the number of consequtive \ characters. If even, then they are
243 // just escaped backslashes, otherwise it's an error.
244 unsigned FirstNonSlash
= Result
.size()-2;
245 // Guaranteed to find the starting " if nothing else.
246 while (Result
[FirstNonSlash
] == '\\')
248 if ((Result
.size()-1-FirstNonSlash
) & 1) {
249 // Diagnose errors for things like: #define F(X) #X / F(\)
250 PP
.Diag(ArgToks
[-1], diag::pp_invalid_string_literal
);
251 Result
.pop_back(); // remove one of the \'s.
256 // If this is the charify operation and the result is not a legal character
257 // constant, diagnose it.
259 // First step, turn double quotes into single quotes:
261 Result
[Result
.size()-1] = '\'';
263 // Check for bogus character.
265 if (Result
.size() == 3)
266 isBad
= Result
[1] == '\''; // ''' is not legal. '\' already fixed above.
268 isBad
= (Result
.size() != 4 || Result
[1] != '\\'); // Not '\x'
271 PP
.Diag(ArgTokStart
[0], diag::err_invalid_character_to_charify
);
272 Result
= "' '"; // Use something arbitrary, but legal.
276 PP
.CreateString(&Result
[0], Result
.size(), Tok
);
280 /// getStringifiedArgument - Compute, cache, and return the specified argument
281 /// that has been 'stringified' as required by the # operator.
282 const Token
&MacroArgs::getStringifiedArgument(unsigned ArgNo
,
284 assert(ArgNo
< NumUnexpArgTokens
&& "Invalid argument number!");
285 if (StringifiedArgs
.empty()) {
286 StringifiedArgs
.resize(getNumArguments());
287 memset(&StringifiedArgs
[0], 0,
288 sizeof(StringifiedArgs
[0])*getNumArguments());
290 if (StringifiedArgs
[ArgNo
].isNot(tok::string_literal
))
291 StringifiedArgs
[ArgNo
] = StringifyArgument(getUnexpArgument(ArgNo
), PP
);
292 return StringifiedArgs
[ArgNo
];