clang API Documentation

MacroArgs.cpp
Go to the documentation of this file.
00001 //===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the MacroArgs interface.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Lex/MacroArgs.h"
00015 #include "clang/Lex/LexDiagnostic.h"
00016 #include "clang/Lex/MacroInfo.h"
00017 #include "clang/Lex/Preprocessor.h"
00018 #include "llvm/ADT/SmallString.h"
00019 #include "llvm/Support/SaveAndRestore.h"
00020 #include <algorithm>
00021 
00022 using namespace clang;
00023 
00024 /// MacroArgs ctor function - This destroys the vector passed in.
00025 MacroArgs *MacroArgs::create(const MacroInfo *MI,
00026                              ArrayRef<Token> UnexpArgTokens,
00027                              bool VarargsElided, Preprocessor &PP) {
00028   assert(MI->isFunctionLike() &&
00029          "Can't have args for an object-like macro!");
00030   MacroArgs **ResultEnt = nullptr;
00031   unsigned ClosestMatch = ~0U;
00032   
00033   // See if we have an entry with a big enough argument list to reuse on the
00034   // free list.  If so, reuse it.
00035   for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;
00036        Entry = &(*Entry)->ArgCache)
00037     if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&
00038         (*Entry)->NumUnexpArgTokens < ClosestMatch) {
00039       ResultEnt = Entry;
00040       
00041       // If we have an exact match, use it.
00042       if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())
00043         break;
00044       // Otherwise, use the best fit.
00045       ClosestMatch = (*Entry)->NumUnexpArgTokens;
00046     }
00047   
00048   MacroArgs *Result;
00049   if (!ResultEnt) {
00050     // Allocate memory for a MacroArgs object with the lexer tokens at the end.
00051     Result = (MacroArgs*)malloc(sizeof(MacroArgs) + 
00052                                 UnexpArgTokens.size() * sizeof(Token));
00053     // Construct the MacroArgs object.
00054     new (Result) MacroArgs(UnexpArgTokens.size(), VarargsElided);
00055   } else {
00056     Result = *ResultEnt;
00057     // Unlink this node from the preprocessors singly linked list.
00058     *ResultEnt = Result->ArgCache;
00059     Result->NumUnexpArgTokens = UnexpArgTokens.size();
00060     Result->VarargsElided = VarargsElided;
00061   }
00062 
00063   // Copy the actual unexpanded tokens to immediately after the result ptr.
00064   if (!UnexpArgTokens.empty())
00065     std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(), 
00066               const_cast<Token*>(Result->getUnexpArgument(0)));
00067 
00068   return Result;
00069 }
00070 
00071 /// destroy - Destroy and deallocate the memory for this object.
00072 ///
00073 void MacroArgs::destroy(Preprocessor &PP) {
00074   StringifiedArgs.clear();
00075 
00076   // Don't clear PreExpArgTokens, just clear the entries.  Clearing the entries
00077   // would deallocate the element vectors.
00078   for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)
00079     PreExpArgTokens[i].clear();
00080   
00081   // Add this to the preprocessor's free list.
00082   ArgCache = PP.MacroArgCache;
00083   PP.MacroArgCache = this;
00084 }
00085 
00086 /// deallocate - This should only be called by the Preprocessor when managing
00087 /// its freelist.
00088 MacroArgs *MacroArgs::deallocate() {
00089   MacroArgs *Next = ArgCache;
00090   
00091   // Run the dtor to deallocate the vectors.
00092   this->~MacroArgs();
00093   // Release the memory for the object.
00094   free(this);
00095   
00096   return Next;
00097 }
00098 
00099 
00100 /// getArgLength - Given a pointer to an expanded or unexpanded argument,
00101 /// return the number of tokens, not counting the EOF, that make up the
00102 /// argument.
00103 unsigned MacroArgs::getArgLength(const Token *ArgPtr) {
00104   unsigned NumArgTokens = 0;
00105   for (; ArgPtr->isNot(tok::eof); ++ArgPtr)
00106     ++NumArgTokens;
00107   return NumArgTokens;
00108 }
00109 
00110 
00111 /// getUnexpArgument - Return the unexpanded tokens for the specified formal.
00112 ///
00113 const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {
00114   // The unexpanded argument tokens start immediately after the MacroArgs object
00115   // in memory.
00116   const Token *Start = (const Token *)(this+1);
00117   const Token *Result = Start;
00118   // Scan to find Arg.
00119   for (; Arg; ++Result) {
00120     assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
00121     if (Result->is(tok::eof))
00122       --Arg;
00123   }
00124   assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");
00125   return Result;
00126 }
00127 
00128 
00129 /// ArgNeedsPreexpansion - If we can prove that the argument won't be affected
00130 /// by pre-expansion, return false.  Otherwise, conservatively return true.
00131 bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,
00132                                      Preprocessor &PP) const {
00133   // If there are no identifiers in the argument list, or if the identifiers are
00134   // known to not be macros, pre-expansion won't modify it.
00135   for (; ArgTok->isNot(tok::eof); ++ArgTok)
00136     if (IdentifierInfo *II = ArgTok->getIdentifierInfo()) {
00137       if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled())
00138         // Return true even though the macro could be a function-like macro
00139         // without a following '(' token.
00140         return true;
00141     }
00142   return false;
00143 }
00144 
00145 /// getPreExpArgument - Return the pre-expanded form of the specified
00146 /// argument.
00147 const std::vector<Token> &
00148 MacroArgs::getPreExpArgument(unsigned Arg, const MacroInfo *MI, 
00149                              Preprocessor &PP) {
00150   assert(Arg < MI->getNumArgs() && "Invalid argument number!");
00151 
00152   // If we have already computed this, return it.
00153   if (PreExpArgTokens.size() < MI->getNumArgs())
00154     PreExpArgTokens.resize(MI->getNumArgs());
00155   
00156   std::vector<Token> &Result = PreExpArgTokens[Arg];
00157   if (!Result.empty()) return Result;
00158 
00159   SaveAndRestore<bool> PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);
00160 
00161   const Token *AT = getUnexpArgument(Arg);
00162   unsigned NumToks = getArgLength(AT)+1;  // Include the EOF.
00163 
00164   // Otherwise, we have to pre-expand this argument, populating Result.  To do
00165   // this, we set up a fake TokenLexer to lex from the unexpanded argument
00166   // list.  With this installed, we lex expanded tokens until we hit the EOF
00167   // token at the end of the unexp list.
00168   PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,
00169                       false /*owns tokens*/);
00170 
00171   // Lex all of the macro-expanded tokens into Result.
00172   do {
00173     Result.push_back(Token());
00174     Token &Tok = Result.back();
00175     PP.Lex(Tok);
00176   } while (Result.back().isNot(tok::eof));
00177 
00178   // Pop the token stream off the top of the stack.  We know that the internal
00179   // pointer inside of it is to the "end" of the token stream, but the stack
00180   // will not otherwise be popped until the next token is lexed.  The problem is
00181   // that the token may be lexed sometime after the vector of tokens itself is
00182   // destroyed, which would be badness.
00183   if (PP.InCachingLexMode())
00184     PP.ExitCachingLexMode();
00185   PP.RemoveTopOfLexerStack();
00186   return Result;
00187 }
00188 
00189 
00190 /// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of
00191 /// tokens into the literal string token that should be produced by the C #
00192 /// preprocessor operator.  If Charify is true, then it should be turned into
00193 /// a character literal for the Microsoft charize (#@) extension.
00194 ///
00195 Token MacroArgs::StringifyArgument(const Token *ArgToks,
00196                                    Preprocessor &PP, bool Charify,
00197                                    SourceLocation ExpansionLocStart,
00198                                    SourceLocation ExpansionLocEnd) {
00199   Token Tok;
00200   Tok.startToken();
00201   Tok.setKind(Charify ? tok::char_constant : tok::string_literal);
00202 
00203   const Token *ArgTokStart = ArgToks;
00204 
00205   // Stringify all the tokens.
00206   SmallString<128> Result;
00207   Result += "\"";
00208 
00209   bool isFirst = true;
00210   for (; ArgToks->isNot(tok::eof); ++ArgToks) {
00211     const Token &Tok = *ArgToks;
00212     if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))
00213       Result += ' ';
00214     isFirst = false;
00215 
00216     // If this is a string or character constant, escape the token as specified
00217     // by 6.10.3.2p2.
00218     if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.
00219         Tok.is(tok::char_constant) ||          // 'x'
00220         Tok.is(tok::wide_char_constant) ||     // L'x'.
00221         Tok.is(tok::utf8_char_constant) ||     // u8'x'.
00222         Tok.is(tok::utf16_char_constant) ||    // u'x'.
00223         Tok.is(tok::utf32_char_constant)) {    // U'x'.
00224       bool Invalid = false;
00225       std::string TokStr = PP.getSpelling(Tok, &Invalid);
00226       if (!Invalid) {
00227         std::string Str = Lexer::Stringify(TokStr);
00228         Result.append(Str.begin(), Str.end());
00229       }
00230     } else if (Tok.is(tok::code_completion)) {
00231       PP.CodeCompleteNaturalLanguage();
00232     } else {
00233       // Otherwise, just append the token.  Do some gymnastics to get the token
00234       // in place and avoid copies where possible.
00235       unsigned CurStrLen = Result.size();
00236       Result.resize(CurStrLen+Tok.getLength());
00237       const char *BufPtr = Result.data() + CurStrLen;
00238       bool Invalid = false;
00239       unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);
00240 
00241       if (!Invalid) {
00242         // If getSpelling returned a pointer to an already uniqued version of
00243         // the string instead of filling in BufPtr, memcpy it onto our string.
00244         if (ActualTokLen && BufPtr != &Result[CurStrLen])
00245           memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);
00246 
00247         // If the token was dirty, the spelling may be shorter than the token.
00248         if (ActualTokLen != Tok.getLength())
00249           Result.resize(CurStrLen+ActualTokLen);
00250       }
00251     }
00252   }
00253 
00254   // If the last character of the string is a \, and if it isn't escaped, this
00255   // is an invalid string literal, diagnose it as specified in C99.
00256   if (Result.back() == '\\') {
00257     // Count the number of consequtive \ characters.  If even, then they are
00258     // just escaped backslashes, otherwise it's an error.
00259     unsigned FirstNonSlash = Result.size()-2;
00260     // Guaranteed to find the starting " if nothing else.
00261     while (Result[FirstNonSlash] == '\\')
00262       --FirstNonSlash;
00263     if ((Result.size()-1-FirstNonSlash) & 1) {
00264       // Diagnose errors for things like: #define F(X) #X   /   F(\)
00265       PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);
00266       Result.pop_back();  // remove one of the \'s.
00267     }
00268   }
00269   Result += '"';
00270 
00271   // If this is the charify operation and the result is not a legal character
00272   // constant, diagnose it.
00273   if (Charify) {
00274     // First step, turn double quotes into single quotes:
00275     Result[0] = '\'';
00276     Result[Result.size()-1] = '\'';
00277 
00278     // Check for bogus character.
00279     bool isBad = false;
00280     if (Result.size() == 3)
00281       isBad = Result[1] == '\'';   // ''' is not legal. '\' already fixed above.
00282     else
00283       isBad = (Result.size() != 4 || Result[1] != '\\');  // Not '\x'
00284 
00285     if (isBad) {
00286       PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);
00287       Result = "' '";  // Use something arbitrary, but legal.
00288     }
00289   }
00290 
00291   PP.CreateString(Result, Tok,
00292                   ExpansionLocStart, ExpansionLocEnd);
00293   return Tok;
00294 }
00295 
00296 /// getStringifiedArgument - Compute, cache, and return the specified argument
00297 /// that has been 'stringified' as required by the # operator.
00298 const Token &MacroArgs::getStringifiedArgument(unsigned ArgNo,
00299                                                Preprocessor &PP,
00300                                                SourceLocation ExpansionLocStart,
00301                                                SourceLocation ExpansionLocEnd) {
00302   assert(ArgNo < NumUnexpArgTokens && "Invalid argument number!");
00303   if (StringifiedArgs.empty()) {
00304     StringifiedArgs.resize(getNumArguments());
00305     memset((void*)&StringifiedArgs[0], 0,
00306            sizeof(StringifiedArgs[0])*getNumArguments());
00307   }
00308   if (StringifiedArgs[ArgNo].isNot(tok::string_literal))
00309     StringifiedArgs[ArgNo] = StringifyArgument(getUnexpArgument(ArgNo), PP,
00310                                                /*Charify=*/false,
00311                                                ExpansionLocStart,
00312                                                ExpansionLocEnd);
00313   return StringifiedArgs[ArgNo];
00314 }