blob: a621854814fbc4a49738f11d3da83b8bf9efce1a [file] [log] [blame]
Chris Lattner7ff66fb2008-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 Lattner60f36222009-01-29 05:15:15 +000017#include "clang/Lex/LexDiagnostic.h"
Chris Lattner7ff66fb2008-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 Lattnerffbf2de2009-12-14 22:12:52 +000023 unsigned NumToks, bool VarargsElided,
24 Preprocessor &PP) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +000025 assert(MI->isFunctionLike() &&
26 "Can't have args for an object-like macro!");
Mike Stump11289f42009-09-09 15:08:12 +000027
Chris Lattner7ff66fb2008-03-09 02:55:12 +000028 // Allocate memory for the MacroArgs object with the lexer tokens at the end.
29 MacroArgs *Result = (MacroArgs*)malloc(sizeof(MacroArgs) +
30 NumToks*sizeof(Token));
31 // Construct the macroargs object.
32 new (Result) MacroArgs(NumToks, VarargsElided);
Mike Stump11289f42009-09-09 15:08:12 +000033
Chris Lattner7ff66fb2008-03-09 02:55:12 +000034 // Copy the actual unexpanded tokens to immediately after the result ptr.
35 if (NumToks)
36 memcpy(const_cast<Token*>(Result->getUnexpArgument(0)),
37 UnexpArgTokens, NumToks*sizeof(Token));
Mike Stump11289f42009-09-09 15:08:12 +000038
Chris Lattner7ff66fb2008-03-09 02:55:12 +000039 return Result;
40}
41
42/// destroy - Destroy and deallocate the memory for this object.
43///
Chris Lattnerffbf2de2009-12-14 22:12:52 +000044void MacroArgs::destroy(Preprocessor &PP) {
Chris Lattner7ff66fb2008-03-09 02:55:12 +000045 // Run the dtor to deallocate the vectors.
46 this->~MacroArgs();
47 // Release the memory for the object.
48 free(this);
49}
50
51
52/// getArgLength - Given a pointer to an expanded or unexpanded argument,
53/// return the number of tokens, not counting the EOF, that make up the
54/// argument.
55unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
56 unsigned NumArgTokens = 0;
57 for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
58 ++NumArgTokens;
59 return NumArgTokens;
60}
61
62
63/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
64///
65const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
66 // The unexpanded argument tokens start immediately after the MacroArgs object
67 // in memory.
68 const Token *Start = (const Token *)(this+1);
69 const Token *Result = Start;
70 // Scan to find Arg.
71 for (; Arg; ++Result) {
72 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
73 if (Result->is(tok::eof))
74 --Arg;
75 }
Chris Lattnerf160b5f2009-05-13 00:55:26 +000076 assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
Chris Lattner7ff66fb2008-03-09 02:55:12 +000077 return Result;
78}
79
80
81/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
82/// by pre-expansion, return false. Otherwise, conservatively return true.
83bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
84 Preprocessor &PP) const {
85 // If there are no identifiers in the argument list, or if the identifiers are
86 // known to not be macros, pre-expansion won't modify it.
87 for (; ArgTok->isNot(tok::eof); ++ArgTok)
88 if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
89 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled())
90 // Return true even though the macro could be a function-like macro
91 // without a following '(' token.
92 return true;
93 }
94 return false;
95}
96
97/// getPreExpArgument - Return the pre-expanded form of the specified
98/// argument.
99const std::vector<Token> &
100MacroArgs::getPreExpArgument(unsigned Arg, Preprocessor &PP) {
101 assert(Arg < NumUnexpArgTokens && "Invalid argument number!");
Mike Stump11289f42009-09-09 15:08:12 +0000102
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000103 // If we have already computed this, return it.
104 if (PreExpArgTokens.empty())
105 PreExpArgTokens.resize(NumUnexpArgTokens);
106
107 std::vector<Token> &Result = PreExpArgTokens[Arg];
108 if (!Result.empty()) return Result;
109
110 const Token *AT = getUnexpArgument(Arg);
111 unsigned NumToks = getArgLength(AT)+1; // Include the EOF.
Mike Stump11289f42009-09-09 15:08:12 +0000112
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000113 // Otherwise, we have to pre-expand this argument, populating Result. To do
114 // this, we set up a fake TokenLexer to lex from the unexpanded argument
115 // list. With this installed, we lex expanded tokens until we hit the EOF
116 // token at the end of the unexp list.
Mike Stump11289f42009-09-09 15:08:12 +0000117 PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
Chris Lattner3e468322008-03-10 06:06:04 +0000118 false /*owns tokens*/);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000119
120 // Lex all of the macro-expanded tokens into Result.
121 do {
122 Result.push_back(Token());
Chris Lattnerad13cf42009-01-26 04:33:10 +0000123 Token &Tok = Result.back();
124 PP.Lex(Tok);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000125 } while (Result.back().isNot(tok::eof));
Mike Stump11289f42009-09-09 15:08:12 +0000126
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000127 // Pop the token stream off the top of the stack. We know that the internal
128 // pointer inside of it is to the "end" of the token stream, but the stack
129 // will not otherwise be popped until the next token is lexed. The problem is
130 // that the token may be lexed sometime after the vector of tokens itself is
131 // destroyed, which would be badness.
132 PP.RemoveTopOfLexerStack();
133 return Result;
134}
135
136
137/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
138/// tokens into the literal string token that should be produced by the C #
139/// preprocessor operator. If Charify is true, then it should be turned into
140/// a character literal for the Microsoft charize (#@) extension.
141///
142Token MacroArgs::StringifyArgument(const Token *ArgToks,
143 Preprocessor &PP, bool Charify) {
144 Token Tok;
145 Tok.startToken();
146 Tok.setKind(tok::string_literal);
147
148 const Token *ArgTokStart = ArgToks;
Mike Stump11289f42009-09-09 15:08:12 +0000149
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000150 // Stringify all the tokens.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000151 llvm::SmallString<128> Result;
152 Result += "\"";
Mike Stump11289f42009-09-09 15:08:12 +0000153
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000154 bool isFirst = true;
155 for (; ArgToks->isNot(tok::eof); ++ArgToks) {
156 const Token &Tok = *ArgToks;
157 if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
158 Result += ' ';
159 isFirst = false;
Mike Stump11289f42009-09-09 15:08:12 +0000160
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000161 // If this is a string or character constant, escape the token as specified
162 // by 6.10.3.2p2.
163 if (Tok.is(tok::string_literal) || // "foo"
164 Tok.is(tok::wide_string_literal) || // L"foo"
165 Tok.is(tok::char_constant)) { // 'x' and L'x'.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000166 std::string Str = Lexer::Stringify(PP.getSpelling(Tok));
167 Result.append(Str.begin(), Str.end());
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000168 } else {
Chris Lattner933d5ff2009-01-05 23:04:18 +0000169 // Otherwise, just append the token. Do some gymnastics to get the token
170 // in place and avoid copies where possible.
171 unsigned CurStrLen = Result.size();
172 Result.resize(CurStrLen+Tok.getLength());
173 const char *BufPtr = &Result[CurStrLen];
174 unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000175
Chris Lattner933d5ff2009-01-05 23:04:18 +0000176 // If getSpelling returned a pointer to an already uniqued version of the
177 // string instead of filling in BufPtr, memcpy it onto our string.
178 if (BufPtr != &Result[CurStrLen])
179 memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
Mike Stump11289f42009-09-09 15:08:12 +0000180
Chris Lattner933d5ff2009-01-05 23:04:18 +0000181 // If the token was dirty, the spelling may be shorter than the token.
182 if (ActualTokLen != Tok.getLength())
183 Result.resize(CurStrLen+ActualTokLen);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000184 }
185 }
Mike Stump11289f42009-09-09 15:08:12 +0000186
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000187 // If the last character of the string is a \, and if it isn't escaped, this
188 // is an invalid string literal, diagnose it as specified in C99.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000189 if (Result.back() == '\\') {
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000190 // Count the number of consequtive \ characters. If even, then they are
191 // just escaped backslashes, otherwise it's an error.
192 unsigned FirstNonSlash = Result.size()-2;
193 // Guaranteed to find the starting " if nothing else.
194 while (Result[FirstNonSlash] == '\\')
195 --FirstNonSlash;
196 if ((Result.size()-1-FirstNonSlash) & 1) {
197 // Diagnose errors for things like: #define F(X) #X / F(\)
198 PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
Chris Lattner933d5ff2009-01-05 23:04:18 +0000199 Result.pop_back(); // remove one of the \'s.
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000200 }
201 }
202 Result += '"';
Mike Stump11289f42009-09-09 15:08:12 +0000203
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000204 // If this is the charify operation and the result is not a legal character
205 // constant, diagnose it.
206 if (Charify) {
207 // First step, turn double quotes into single quotes:
208 Result[0] = '\'';
209 Result[Result.size()-1] = '\'';
Mike Stump11289f42009-09-09 15:08:12 +0000210
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000211 // Check for bogus character.
212 bool isBad = false;
Chris Lattner933d5ff2009-01-05 23:04:18 +0000213 if (Result.size() == 3)
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000214 isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.
Chris Lattner933d5ff2009-01-05 23:04:18 +0000215 else
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000216 isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'
Mike Stump11289f42009-09-09 15:08:12 +0000217
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000218 if (isBad) {
219 PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
220 Result = "' '"; // Use something arbitrary, but legal.
221 }
222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223
Chris Lattner5a7971e2009-01-26 19:29:26 +0000224 PP.CreateString(&Result[0], Result.size(), Tok);
Chris Lattner7ff66fb2008-03-09 02:55:12 +0000225 return Tok;
226}
227
228/// getStringifiedArgument - Compute, cache, and return the specified argument
229/// that has been 'stringified' as required by the # operator.
230const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
231 Preprocessor &PP) {
232 assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
233 if (StringifiedArgs.empty()) {
234 StringifiedArgs.resize(getNumArguments());
235 memset(&StringifiedArgs[0], 0,
236 sizeof(StringifiedArgs[0])*getNumArguments());
237 }
238 if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
239 StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP);
240 return StringifiedArgs[ArgNo];
241}