1193326Sed//===--- TokenLexer.cpp - Lex from a token stream -------------------------===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file implements the TokenLexer interface.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14251662Sdim#include "clang/Lex/MacroArgs.h"
15249423Sdim#include "clang/Lex/LexDiagnostic.h"
16193326Sed#include "clang/Lex/MacroInfo.h"
17193326Sed#include "clang/Lex/Preprocessor.h"
18234353Sdim#include "llvm/ADT/SmallString.h"
19234353Sdim#include "llvm/Support/SaveAndRestore.h"
20226633Sdim#include <algorithm>
21226633Sdim
22193326Sedusing namespace clang;
23193326Sed
24193326Sed/// MacroArgs ctor function - This destroys the vector passed in.
25193326SedMacroArgs *MacroArgs::create(const MacroInfo *MI,
26249423Sdim                             ArrayRef<Token> UnexpArgTokens,
27226633Sdim                             bool VarargsElided, Preprocessor &PP) {
28193326Sed  assert(MI->isFunctionLike() &&
29193326Sed         "Can't have args for an object-like macro!");
30201361Srdivacky  MacroArgs **ResultEnt = 0;
31201361Srdivacky  unsigned ClosestMatch = ~0U;
32201361Srdivacky
33201361Srdivacky  // See if we have an entry with a big enough argument list to reuse on the
34201361Srdivacky  // free list.  If so, reuse it.
35201361Srdivacky  for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
36201361Srdivacky       Entry = &(*Entry)->ArgCache)
37226633Sdim    if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
38201361Srdivacky        (*Entry)->NumUnexpArgTokens < ClosestMatch) {
39201361Srdivacky      ResultEnt = Entry;
40201361Srdivacky
41201361Srdivacky      // If we have an exact match, use it.
42226633Sdim      if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
43201361Srdivacky        break;
44201361Srdivacky      // Otherwise, use the best fit.
45201361Srdivacky      ClosestMatch = (*Entry)->NumUnexpArgTokens;
46201361Srdivacky    }
47201361Srdivacky
48201361Srdivacky  MacroArgs *Result;
49201361Srdivacky  if (ResultEnt == 0) {
50201361Srdivacky    // Allocate memory for a MacroArgs object with the lexer tokens at the end.
51226633Sdim    Result = (MacroArgs*)malloc(sizeof(MacroArgs) +
52226633Sdim                                UnexpArgTokens.size() * sizeof(Token));
53201361Srdivacky    // Construct the MacroArgs object.
54226633Sdim    new (Result) MacroArgs(UnexpArgTokens.size(), VarargsElided);
55201361Srdivacky  } else {
56201361Srdivacky    Result = *ResultEnt;
57201361Srdivacky    // Unlink this node from the preprocessors singly linked list.
58201361Srdivacky    *ResultEnt = Result->ArgCache;
59226633Sdim    Result->NumUnexpArgTokens = UnexpArgTokens.size();
60201361Srdivacky    Result->VarargsElided = VarargsElided;
61201361Srdivacky  }
62198092Srdivacky
63193326Sed  // Copy the actual unexpanded tokens to immediately after the result ptr.
64226633Sdim  if (!UnexpArgTokens.empty())
65226633Sdim    std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),
66226633Sdim              const_cast<Token*>(Result->getUnexpArgument(0)));
67198092Srdivacky
68193326Sed  return Result;
69193326Sed}
70193326Sed
71193326Sed/// destroy - Destroy and deallocate the memory for this object.
72193326Sed///
73200583Srdivackyvoid MacroArgs::destroy(Preprocessor &PP) {
74201361Srdivacky  StringifiedArgs.clear();
75201361Srdivacky
76201361Srdivacky  // Don't clear PreExpArgTokens, just clear the entries.  Clearing the entries
77201361Srdivacky  // would deallocate the element vectors.
78201361Srdivacky  for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)
79201361Srdivacky    PreExpArgTokens[i].clear();
80201361Srdivacky
81201361Srdivacky  // Add this to the preprocessor's free list.
82201361Srdivacky  ArgCache = PP.MacroArgCache;
83201361Srdivacky  PP.MacroArgCache = this;
84193326Sed}
85193326Sed
86200583Srdivacky/// deallocate - This should only be called by the Preprocessor when managing
87200583Srdivacky/// its freelist.
88200583SrdivackyMacroArgs *MacroArgs::deallocate() {
89200583Srdivacky  MacroArgs *Next = ArgCache;
90200583Srdivacky
91200583Srdivacky  // Run the dtor to deallocate the vectors.
92200583Srdivacky  this->~MacroArgs();
93200583Srdivacky  // Release the memory for the object.
94200583Srdivacky  free(this);
95200583Srdivacky
96200583Srdivacky  return Next;
97200583Srdivacky}
98193326Sed
99200583Srdivacky
100193326Sed/// getArgLength - Given a pointer to an expanded or unexpanded argument,
101193326Sed/// return the number of tokens, not counting the EOF, that make up the
102193326Sed/// argument.
103193326Sedunsigned MacroArgs::getArgLength(const Token *ArgPtr) {
104193326Sed  unsigned NumArgTokens = 0;
105193326Sed  for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
106193326Sed    ++NumArgTokens;
107193326Sed  return NumArgTokens;
108193326Sed}
109193326Sed
110193326Sed
111193326Sed/// getUnexpArgument - Return the unexpanded tokens for the specified formal.
112193326Sed///
113193326Sedconst Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
114193326Sed  // The unexpanded argument tokens start immediately after the MacroArgs object
115193326Sed  // in memory.
116193326Sed  const Token *Start = (const Token *)(this+1);
117193326Sed  const Token *Result = Start;
118193326Sed  // Scan to find Arg.
119193326Sed  for (; Arg; ++Result) {
120193326Sed    assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
121193326Sed    if (Result->is(tok::eof))
122193326Sed      --Arg;
123193326Sed  }
124193326Sed  assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
125193326Sed  return Result;
126193326Sed}
127193326Sed
128193326Sed
129193326Sed/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
130193326Sed/// by pre-expansion, return false.  Otherwise, conservatively return true.
131193326Sedbool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
132193326Sed                                     Preprocessor &PP) const {
133193326Sed  // If there are no identifiers in the argument list, or if the identifiers are
134193326Sed  // known to not be macros, pre-expansion won't modify it.
135193326Sed  for (; ArgTok->isNot(tok::eof); ++ArgTok)
136193326Sed    if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
137193326Sed      if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled())
138193326Sed        // Return true even though the macro could be a function-like macro
139193326Sed        // without a following '(' token.
140193326Sed        return true;
141193326Sed    }
142193326Sed  return false;
143193326Sed}
144193326Sed
145193326Sed/// getPreExpArgument - Return the pre-expanded form of the specified
146193326Sed/// argument.
147193326Sedconst std::vector<Token> &
148201361SrdivackyMacroArgs::getPreExpArgument(unsigned Arg, const MacroInfo *MI,
149201361Srdivacky                             Preprocessor &PP) {
150201361Srdivacky  assert(Arg < MI->getNumArgs() && "Invalid argument number!");
151198092Srdivacky
152193326Sed  // If we have already computed this, return it.
153201361Srdivacky  if (PreExpArgTokens.size() < MI->getNumArgs())
154201361Srdivacky    PreExpArgTokens.resize(MI->getNumArgs());
155201361Srdivacky
156193326Sed  std::vector<Token> &Result = PreExpArgTokens[Arg];
157193326Sed  if (!Result.empty()) return Result;
158193326Sed
159234353Sdim  SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
160234353Sdim
161193326Sed  const Token *AT = getUnexpArgument(Arg);
162193326Sed  unsigned NumToks = getArgLength(AT)+1;  // Include the EOF.
163198092Srdivacky
164193326Sed  // Otherwise, we have to pre-expand this argument, populating Result.  To do
165193326Sed  // this, we set up a fake TokenLexer to lex from the unexpanded argument
166193326Sed  // list.  With this installed, we lex expanded tokens until we hit the EOF
167193326Sed  // token at the end of the unexp list.
168198092Srdivacky  PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
169193326Sed                      false /*owns tokens*/);
170193326Sed
171193326Sed  // Lex all of the macro-expanded tokens into Result.
172193326Sed  do {
173193326Sed    Result.push_back(Token());
174193326Sed    Token &Tok = Result.back();
175193326Sed    PP.Lex(Tok);
176193326Sed  } while (Result.back().isNot(tok::eof));
177198092Srdivacky
178193326Sed  // Pop the token stream off the top of the stack.  We know that the internal
179193326Sed  // pointer inside of it is to the "end" of the token stream, but the stack
180193326Sed  // will not otherwise be popped until the next token is lexed.  The problem is
181193326Sed  // that the token may be lexed sometime after the vector of tokens itself is
182193326Sed  // destroyed, which would be badness.
183234353Sdim  if (PP.InCachingLexMode())
184234353Sdim    PP.ExitCachingLexMode();
185193326Sed  PP.RemoveTopOfLexerStack();
186193326Sed  return Result;
187193326Sed}
188193326Sed
189193326Sed
190193326Sed/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
191193326Sed/// tokens into the literal string token that should be produced by the C #
192193326Sed/// preprocessor operator.  If Charify is true, then it should be turned into
193193326Sed/// a character literal for the Microsoft charize (#@) extension.
194193326Sed///
195193326SedToken MacroArgs::StringifyArgument(const Token *ArgToks,
196224145Sdim                                   Preprocessor &PP, bool Charify,
197226633Sdim                                   SourceLocation ExpansionLocStart,
198226633Sdim                                   SourceLocation ExpansionLocEnd) {
199193326Sed  Token Tok;
200193326Sed  Tok.startToken();
201201361Srdivacky  Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
202193326Sed
203193326Sed  const Token *ArgTokStart = ArgToks;
204198092Srdivacky
205193326Sed  // Stringify all the tokens.
206234353Sdim  SmallString<128> Result;
207193326Sed  Result += "\"";
208198092Srdivacky
209193326Sed  bool isFirst = true;
210193326Sed  for (; ArgToks->isNot(tok::eof); ++ArgToks) {
211193326Sed    const Token &Tok = *ArgToks;
212193326Sed    if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
213193326Sed      Result += ' ';
214193326Sed    isFirst = false;
215198092Srdivacky
216193326Sed    // If this is a string or character constant, escape the token as specified
217193326Sed    // by 6.10.3.2p2.
218249423Sdim    if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
219249423Sdim        Tok.is(tok::char_constant) ||          // 'x'
220249423Sdim        Tok.is(tok::wide_char_constant) ||     // L'x'.
221249423Sdim        Tok.is(tok::utf16_char_constant) ||    // u'x'.
222249423Sdim        Tok.is(tok::utf32_char_constant)) {    // U'x'.
223205408Srdivacky      bool Invalid = false;
224205408Srdivacky      std::string TokStr = PP.getSpelling(Tok, &Invalid);
225205408Srdivacky      if (!Invalid) {
226205408Srdivacky        std::string Str = Lexer::Stringify(TokStr);
227205408Srdivacky        Result.append(Str.begin(), Str.end());
228205408Srdivacky      }
229226633Sdim    } else if (Tok.is(tok::code_completion)) {
230226633Sdim      PP.CodeCompleteNaturalLanguage();
231193326Sed    } else {
232193326Sed      // Otherwise, just append the token.  Do some gymnastics to get the token
233193326Sed      // in place and avoid copies where possible.
234193326Sed      unsigned CurStrLen = Result.size();
235193326Sed      Result.resize(CurStrLen+Tok.getLength());
236193326Sed      const char *BufPtr = &Result[CurStrLen];
237205408Srdivacky      bool Invalid = false;
238205408Srdivacky      unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
239198092Srdivacky
240205408Srdivacky      if (!Invalid) {
241205408Srdivacky        // If getSpelling returned a pointer to an already uniqued version of
242205408Srdivacky        // the string instead of filling in BufPtr, memcpy it onto our string.
243205408Srdivacky        if (BufPtr != &Result[CurStrLen])
244205408Srdivacky          memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
245198092Srdivacky
246205408Srdivacky        // If the token was dirty, the spelling may be shorter than the token.
247205408Srdivacky        if (ActualTokLen != Tok.getLength())
248205408Srdivacky          Result.resize(CurStrLen+ActualTokLen);
249205408Srdivacky      }
250193326Sed    }
251193326Sed  }
252198092Srdivacky
253193326Sed  // If the last character of the string is a \, and if it isn't escaped, this
254193326Sed  // is an invalid string literal, diagnose it as specified in C99.
255193326Sed  if (Result.back() == '\\') {
256193326Sed    // Count the number of consequtive \ characters.  If even, then they are
257193326Sed    // just escaped backslashes, otherwise it's an error.
258193326Sed    unsigned FirstNonSlash = Result.size()-2;
259193326Sed    // Guaranteed to find the starting " if nothing else.
260193326Sed    while (Result[FirstNonSlash] == '\\')
261193326Sed      --FirstNonSlash;
262193326Sed    if ((Result.size()-1-FirstNonSlash) & 1) {
263193326Sed      // Diagnose errors for things like: #define F(X) #X   /   F(\)
264193326Sed      PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
265193326Sed      Result.pop_back();  // remove one of the \'s.
266193326Sed    }
267193326Sed  }
268193326Sed  Result += '"';
269198092Srdivacky
270193326Sed  // If this is the charify operation and the result is not a legal character
271193326Sed  // constant, diagnose it.
272193326Sed  if (Charify) {
273193326Sed    // First step, turn double quotes into single quotes:
274193326Sed    Result[0] = '\'';
275193326Sed    Result[Result.size()-1] = '\'';
276198092Srdivacky
277193326Sed    // Check for bogus character.
278193326Sed    bool isBad = false;
279193326Sed    if (Result.size() == 3)
280193326Sed      isBad = Result[1] == '\'';   // ''' is not legal. '\' already fixed above.
281193326Sed    else
282193326Sed      isBad = (Result.size() != 4 || Result[1] != '\\');  // Not '\x'
283198092Srdivacky
284193326Sed    if (isBad) {
285193326Sed      PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
286193326Sed      Result = "' '";  // Use something arbitrary, but legal.
287193326Sed    }
288193326Sed  }
289198092Srdivacky
290243830Sdim  PP.CreateString(Result, Tok,
291226633Sdim                  ExpansionLocStart, ExpansionLocEnd);
292193326Sed  return Tok;
293193326Sed}
294193326Sed
295193326Sed/// getStringifiedArgument - Compute, cache, and return the specified argument
296193326Sed/// that has been 'stringified' as required by the # operator.
297193326Sedconst Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
298224145Sdim                                               Preprocessor &PP,
299226633Sdim                                               SourceLocation ExpansionLocStart,
300226633Sdim                                               SourceLocation ExpansionLocEnd) {
301193326Sed  assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
302193326Sed  if (StringifiedArgs.empty()) {
303193326Sed    StringifiedArgs.resize(getNumArguments());
304221345Sdim    memset((void*)&StringifiedArgs[0], 0,
305193326Sed           sizeof(StringifiedArgs[0])*getNumArguments());
306193326Sed  }
307193326Sed  if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
308224145Sdim    StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
309226633Sdim                                               /*Charify=*/false,
310226633Sdim                                               ExpansionLocStart,
311226633Sdim                                               ExpansionLocEnd);
312193326Sed  return StringifiedArgs[ArgNo];
313193326Sed}
314