blob: c3d7738afe0df5fc917340fe541b6e80c9058dd8 [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"
17#include "clang/Basic/Diagnostic.h"
18using namespace clang;
19
20/// MacroArgs ctor function - This destroys the vector passed in.
21MacroArgs *MacroArgs::create(const MacroInfo *MI,
22 const Token *UnexpArgTokens,
23 unsigned NumToks, bool VarargsElided) {
24 assert(MI->isFunctionLike() &&
25 "Can't have args for an object-like macro!");
Chris Lattner7c351222009-01-26 04:33:10 +000026
Chris Lattnere5c8ffe2008-03-09 02:55:12 +000027 // Allocate memory for the MacroArgs object with the lexer tokens at the end.
28 MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) +
29 NumToks*sizeof(Token));
30 // Construct the macroargs object.
31 new (Result) MacroArgs(NumToks, VarargsElided);
32
33 // Copy the actual unexpanded tokens to immediately after the result ptr.
34 if (NumToks)
35 memcpy(const_cast<Token*>(Result->getUnexpArgument(0)),
36 UnexpArgTokens, NumToks*sizeof(Token));
37
38 return Result;
39}
40
41/// destroy - Destroy and deallocate the memory for this object.
42///
43void MacroArgs::destroy() {
44 // Run the dtor to deallocate the vectors.
45 this->~MacroArgs();
46 // Release the memory for the object.
47 free(this);
48}
49
50
51/// getArgLength - Given a pointer to an expanded or unexpanded argument,
52/// return the number of tokens, not counting the EOF, that make up the
53/// argument.
54unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
55 unsigned NumArgTokens = 0;
56 for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
57 ++NumArgTokens;
58 return NumArgTokens;
59}
60
61
62/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
63///
64const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
65 // The unexpanded argument tokens start immediately after the MacroArgs object
66 // in memory.
67 const Token *Start = (const Token *)(this+1);
68 const Token *Result = Start;
69 // Scan to find Arg.
70 for (; Arg; ++Result) {
71 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
72 if (Result->is(tok::eof))
73 --Arg;
74 }
75 return Result;
76}
77
78
79/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
80/// by pre-expansion, return false. Otherwise, conservatively return true.
81bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
82 Preprocessor &PP) const {
83 // If there are no identifiers in the argument list, or if the identifiers are
84 // known to not be macros, pre-expansion won't modify it.
85 for (; ArgTok->isNot(tok::eof); ++ArgTok)
86 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
87 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled())
88 // Return true even though the macro could be a function-like macro
89 // without a following '(' token.
90 return true;
91 }
92 return false;
93}
94
95/// getPreExpArgument - Return the pre-expanded form of the specified
96/// argument.
97const std::vector<Token> &
98MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) {
99 assert(Arg < NumUnexpArgTokens && "Invalid argument number!");
100
101 // If we have already computed this, return it.
102 if (PreExpArgTokens.empty())
103 PreExpArgTokens.resize(NumUnexpArgTokens);
104
105 std::vector<Token> &Result = PreExpArgTokens[Arg];
106 if (!Result.empty()) return Result;
107
108 const Token *AT = getUnexpArgument(Arg);
109 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
110
111 // Otherwise, we have to pre-expand this argument, populating Result. To do
112 // this, we set up a fake TokenLexer to lex from the unexpanded argument
113 // list. With this installed, we lex expanded tokens until we hit the EOF
114 // token at the end of the unexp list.
Chris Lattner6b884502008-03-10 06:06:04 +0000115 PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
116 false /*owns tokens*/);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000117
118 // Lex all of the macro-expanded tokens into Result.
119 do {
120 Result.push_back(Token());
Chris Lattner7c351222009-01-26 04:33:10 +0000121 Token &Tok = Result.back();
122 PP.Lex(Tok);
123
124 // Eagerly resolve instantiation ID's to their spelling location. This
125 // makes it so we only have to get the spelling loc once per macro argument
126 // preexpansion instead of once per each time the token is expanded.
127 if (!Tok.getLocation().isFileID())
128 Tok.setLocation(PP.getSourceManager().getSpellingLoc(Tok.getLocation()));
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000129 } while (Result.back().isNot(tok::eof));
130
131 // Pop the token stream off the top of the stack. We know that the internal
132 // pointer inside of it is to the "end" of the token stream, but the stack
133 // will not otherwise be popped until the next token is lexed. The problem is
134 // that the token may be lexed sometime after the vector of tokens itself is
135 // destroyed, which would be badness.
136 PP.RemoveTopOfLexerStack();
137 return Result;
138}
139
140
141/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
142/// tokens into the literal string token that should be produced by the C #
143/// preprocessor operator. If Charify is true, then it should be turned into
144/// a character literal for the Microsoft charize (#@) extension.
145///
146Token MacroArgs::StringifyArgument(const Token *ArgToks,
147 Preprocessor &PP, bool Charify) {
148 Token Tok;
149 Tok.startToken();
150 Tok.setKind(tok::string_literal);
151
152 const Token *ArgTokStart = ArgToks;
153
154 // Stringify all the tokens.
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000155 llvm::SmallString<128> Result;
156 Result += "\"";
157
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000158 bool isFirst = true;
159 for (; ArgToks->isNot(tok::eof); ++ArgToks) {
160 const Token &Tok = *ArgToks;
161 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
162 Result += ' ';
163 isFirst = false;
164
165 // If this is a string or character constant, escape the token as specified
166 // by 6.10.3.2p2.
167 if (Tok.is(tok::string_literal) || // "foo"
168 Tok.is(tok::wide_string_literal) || // L"foo"
169 Tok.is(tok::char_constant)) { // 'x' and L'x'.
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000170 std::string Str = Lexer::Stringify(PP.getSpelling(Tok));
171 Result.append(Str.begin(), Str.end());
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000172 } else {
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000173 // Otherwise, just append the token. Do some gymnastics to get the token
174 // in place and avoid copies where possible.
175 unsigned CurStrLen = Result.size();
176 Result.resize(CurStrLen+Tok.getLength());
177 const char *BufPtr = &Result[CurStrLen];
178 unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr);
179
180 // If getSpelling returned a pointer to an already uniqued version of the
181 // string instead of filling in BufPtr, memcpy it onto our string.
182 if (BufPtr != &Result[CurStrLen])
183 memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
184
185 // If the token was dirty, the spelling may be shorter than the token.
186 if (ActualTokLen != Tok.getLength())
187 Result.resize(CurStrLen+ActualTokLen);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000188 }
189 }
190
191 // If the last character of the string is a \, and if it isn't escaped, this
192 // is an invalid string literal, diagnose it as specified in C99.
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000193 if (Result.back() == '\\') {
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000194 // Count the number of consequtive \ characters. If even, then they are
195 // just escaped backslashes, otherwise it's an error.
196 unsigned FirstNonSlash = Result.size()-2;
197 // Guaranteed to find the starting " if nothing else.
198 while (Result[FirstNonSlash] == '\\')
199 --FirstNonSlash;
200 if ((Result.size()-1-FirstNonSlash) & 1) {
201 // Diagnose errors for things like: #define F(X) #X / F(\)
202 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000203 Result.pop_back(); // remove one of the \'s.
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000204 }
205 }
206 Result += '"';
207
208 // If this is the charify operation and the result is not a legal character
209 // constant, diagnose it.
210 if (Charify) {
211 // First step, turn double quotes into single quotes:
212 Result[0] = '\'';
213 Result[Result.size()-1] = '\'';
214
215 // Check for bogus character.
216 bool isBad = false;
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000217 if (Result.size() == 3)
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000218 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
Chris Lattnerc19e8a22009-01-05 23:04:18 +0000219 else
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000220 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000221
222 if (isBad) {
223 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
224 Result = "' '"; // Use something arbitrary, but legal.
225 }
226 }
227
Chris Lattner47246be2009-01-26 19:29:26 +0000228 PP.CreateString(&Result[0], Result.size(), Tok);
Chris Lattnere5c8ffe2008-03-09 02:55:12 +0000229 return Tok;
230}
231
232/// getStringifiedArgument - Compute, cache, and return the specified argument
233/// that has been 'stringified' as required by the # operator.
234const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
235 Preprocessor &PP) {
236 assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
237 if (StringifiedArgs.empty()) {
238 StringifiedArgs.resize(getNumArguments());
239 memset(&StringifiedArgs[0], 0,
240 sizeof(StringifiedArgs[0])*getNumArguments());
241 }
242 if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
243 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP);
244 return StringifiedArgs[ArgNo];
245}