Path: blob/main/contrib/llvm-project/clang/lib/Lex/MacroArgs.cpp
35234 views
//===--- MacroArgs.cpp - Formal argument info for Macros ------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the MacroArgs interface.9//10//===----------------------------------------------------------------------===//1112#include "clang/Lex/MacroArgs.h"13#include "clang/Lex/LexDiagnostic.h"14#include "clang/Lex/MacroInfo.h"15#include "clang/Lex/Preprocessor.h"16#include "llvm/ADT/SmallString.h"17#include "llvm/Support/SaveAndRestore.h"18#include <algorithm>1920using namespace clang;2122/// MacroArgs ctor function - This destroys the vector passed in.23MacroArgs *MacroArgs::create(const MacroInfo *MI,24ArrayRef<Token> UnexpArgTokens,25bool VarargsElided, Preprocessor &PP) {26assert(MI->isFunctionLike() &&27"Can't have args for an object-like macro!");28MacroArgs **ResultEnt = nullptr;29unsigned ClosestMatch = ~0U;3031// See if we have an entry with a big enough argument list to reuse on the32// free list. If so, reuse it.33for (MacroArgs **Entry = &PP.MacroArgCache; *Entry;34Entry = &(*Entry)->ArgCache) {35if ((*Entry)->NumUnexpArgTokens >= UnexpArgTokens.size() &&36(*Entry)->NumUnexpArgTokens < ClosestMatch) {37ResultEnt = Entry;3839// If we have an exact match, use it.40if ((*Entry)->NumUnexpArgTokens == UnexpArgTokens.size())41break;42// Otherwise, use the best fit.43ClosestMatch = (*Entry)->NumUnexpArgTokens;44}45}46MacroArgs *Result;47if (!ResultEnt) {48// Allocate memory for a MacroArgs object with the lexer tokens at the end,49// and construct the MacroArgs object.50Result = new (51llvm::safe_malloc(totalSizeToAlloc<Token>(UnexpArgTokens.size())))52MacroArgs(UnexpArgTokens.size(), VarargsElided, MI->getNumParams());53} else {54Result = *ResultEnt;55// Unlink this node from the preprocessors singly linked list.56*ResultEnt = Result->ArgCache;57Result->NumUnexpArgTokens = UnexpArgTokens.size();58Result->VarargsElided = VarargsElided;59Result->NumMacroArgs = MI->getNumParams();60}6162// Copy the actual unexpanded tokens to immediately after the result ptr.63if (!UnexpArgTokens.empty()) {64static_assert(std::is_trivial_v<Token>,65"assume trivial copyability if copying into the "66"uninitialized array (as opposed to reusing a cached "67"MacroArgs)");68std::copy(UnexpArgTokens.begin(), UnexpArgTokens.end(),69Result->getTrailingObjects<Token>());70}7172return Result;73}7475/// destroy - Destroy and deallocate the memory for this object.76///77void MacroArgs::destroy(Preprocessor &PP) {78// Don't clear PreExpArgTokens, just clear the entries. Clearing the entries79// would deallocate the element vectors.80for (unsigned i = 0, e = PreExpArgTokens.size(); i != e; ++i)81PreExpArgTokens[i].clear();8283// Add this to the preprocessor's free list.84ArgCache = PP.MacroArgCache;85PP.MacroArgCache = this;86}8788/// deallocate - This should only be called by the Preprocessor when managing89/// its freelist.90MacroArgs *MacroArgs::deallocate() {91MacroArgs *Next = ArgCache;9293// Run the dtor to deallocate the vectors.94this->~MacroArgs();95// Release the memory for the object.96static_assert(std::is_trivially_destructible_v<Token>,97"assume trivially destructible and forego destructors");98free(this);99100return Next;101}102103104/// getArgLength - Given a pointer to an expanded or unexpanded argument,105/// return the number of tokens, not counting the EOF, that make up the106/// argument.107unsigned MacroArgs::getArgLength(const Token *ArgPtr) {108unsigned NumArgTokens = 0;109for (; ArgPtr->isNot(tok::eof); ++ArgPtr)110++NumArgTokens;111return NumArgTokens;112}113114115/// getUnexpArgument - Return the unexpanded tokens for the specified formal.116///117const Token *MacroArgs::getUnexpArgument(unsigned Arg) const {118119assert(Arg < getNumMacroArguments() && "Invalid arg #");120// The unexpanded argument tokens start immediately after the MacroArgs object121// in memory.122const Token *Start = getTrailingObjects<Token>();123const Token *Result = Start;124125// Scan to find Arg.126for (; Arg; ++Result) {127assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");128if (Result->is(tok::eof))129--Arg;130}131assert(Result < Start+NumUnexpArgTokens && "Invalid arg #");132return Result;133}134135bool MacroArgs::invokedWithVariadicArgument(const MacroInfo *const MI,136Preprocessor &PP) {137if (!MI->isVariadic())138return false;139const int VariadicArgIndex = getNumMacroArguments() - 1;140return getPreExpArgument(VariadicArgIndex, PP).front().isNot(tok::eof);141}142143/// ArgNeedsPreexpansion - If we can prove that the argument won't be affected144/// by pre-expansion, return false. Otherwise, conservatively return true.145bool MacroArgs::ArgNeedsPreexpansion(const Token *ArgTok,146Preprocessor &PP) const {147// If there are no identifiers in the argument list, or if the identifiers are148// known to not be macros, pre-expansion won't modify it.149for (; ArgTok->isNot(tok::eof); ++ArgTok)150if (IdentifierInfo *II = ArgTok->getIdentifierInfo())151if (II->hasMacroDefinition())152// Return true even though the macro could be a function-like macro153// without a following '(' token, or could be disabled, or not visible.154return true;155return false;156}157158/// getPreExpArgument - Return the pre-expanded form of the specified159/// argument.160const std::vector<Token> &MacroArgs::getPreExpArgument(unsigned Arg,161Preprocessor &PP) {162assert(Arg < getNumMacroArguments() && "Invalid argument number!");163164// If we have already computed this, return it.165if (PreExpArgTokens.size() < getNumMacroArguments())166PreExpArgTokens.resize(getNumMacroArguments());167168std::vector<Token> &Result = PreExpArgTokens[Arg];169if (!Result.empty()) return Result;170171SaveAndRestore PreExpandingMacroArgs(PP.InMacroArgPreExpansion, true);172173const Token *AT = getUnexpArgument(Arg);174unsigned NumToks = getArgLength(AT)+1; // Include the EOF.175176// Otherwise, we have to pre-expand this argument, populating Result. To do177// this, we set up a fake TokenLexer to lex from the unexpanded argument178// list. With this installed, we lex expanded tokens until we hit the EOF179// token at the end of the unexp list.180PP.EnterTokenStream(AT, NumToks, false /*disable expand*/,181false /*owns tokens*/, false /*is reinject*/);182183// Lex all of the macro-expanded tokens into Result.184do {185Result.push_back(Token());186Token &Tok = Result.back();187PP.Lex(Tok);188} while (Result.back().isNot(tok::eof));189190// Pop the token stream off the top of the stack. We know that the internal191// pointer inside of it is to the "end" of the token stream, but the stack192// will not otherwise be popped until the next token is lexed. The problem is193// that the token may be lexed sometime after the vector of tokens itself is194// destroyed, which would be badness.195if (PP.InCachingLexMode())196PP.ExitCachingLexMode();197PP.RemoveTopOfLexerStack();198return Result;199}200201202/// StringifyArgument - Implement C99 6.10.3.2p2, converting a sequence of203/// tokens into the literal string token that should be produced by the C #204/// preprocessor operator. If Charify is true, then it should be turned into205/// a character literal for the Microsoft charize (#@) extension.206///207Token MacroArgs::StringifyArgument(const Token *ArgToks,208Preprocessor &PP, bool Charify,209SourceLocation ExpansionLocStart,210SourceLocation ExpansionLocEnd) {211Token Tok;212Tok.startToken();213Tok.setKind(Charify ? tok::char_constant : tok::string_literal);214215const Token *ArgTokStart = ArgToks;216217// Stringify all the tokens.218SmallString<128> Result;219Result += "\"";220221bool isFirst = true;222for (; ArgToks->isNot(tok::eof); ++ArgToks) {223const Token &Tok = *ArgToks;224if (!isFirst && (Tok.hasLeadingSpace() || Tok.isAtStartOfLine()))225Result += ' ';226isFirst = false;227228// If this is a string or character constant, escape the token as specified229// by 6.10.3.2p2.230if (tok::isStringLiteral(Tok.getKind()) || // "foo", u8R"x(foo)x"_bar, etc.231Tok.is(tok::char_constant) || // 'x'232Tok.is(tok::wide_char_constant) || // L'x'.233Tok.is(tok::utf8_char_constant) || // u8'x'.234Tok.is(tok::utf16_char_constant) || // u'x'.235Tok.is(tok::utf32_char_constant)) { // U'x'.236bool Invalid = false;237std::string TokStr = PP.getSpelling(Tok, &Invalid);238if (!Invalid) {239std::string Str = Lexer::Stringify(TokStr);240Result.append(Str.begin(), Str.end());241}242} else if (Tok.is(tok::code_completion)) {243PP.CodeCompleteNaturalLanguage();244} else {245// Otherwise, just append the token. Do some gymnastics to get the token246// in place and avoid copies where possible.247unsigned CurStrLen = Result.size();248Result.resize(CurStrLen+Tok.getLength());249const char *BufPtr = Result.data() + CurStrLen;250bool Invalid = false;251unsigned ActualTokLen = PP.getSpelling(Tok, BufPtr, &Invalid);252253if (!Invalid) {254// If getSpelling returned a pointer to an already uniqued version of255// the string instead of filling in BufPtr, memcpy it onto our string.256if (ActualTokLen && BufPtr != &Result[CurStrLen])257memcpy(&Result[CurStrLen], BufPtr, ActualTokLen);258259// If the token was dirty, the spelling may be shorter than the token.260if (ActualTokLen != Tok.getLength())261Result.resize(CurStrLen+ActualTokLen);262}263}264}265266// If the last character of the string is a \, and if it isn't escaped, this267// is an invalid string literal, diagnose it as specified in C99.268if (Result.back() == '\\') {269// Count the number of consecutive \ characters. If even, then they are270// just escaped backslashes, otherwise it's an error.271unsigned FirstNonSlash = Result.size()-2;272// Guaranteed to find the starting " if nothing else.273while (Result[FirstNonSlash] == '\\')274--FirstNonSlash;275if ((Result.size()-1-FirstNonSlash) & 1) {276// Diagnose errors for things like: #define F(X) #X / F(\)277PP.Diag(ArgToks[-1], diag::pp_invalid_string_literal);278Result.pop_back(); // remove one of the \'s.279}280}281Result += '"';282283// If this is the charify operation and the result is not a legal character284// constant, diagnose it.285if (Charify) {286// First step, turn double quotes into single quotes:287Result[0] = '\'';288Result[Result.size()-1] = '\'';289290// Check for bogus character.291bool isBad = false;292if (Result.size() == 3)293isBad = Result[1] == '\''; // ''' is not legal. '\' already fixed above.294else295isBad = (Result.size() != 4 || Result[1] != '\\'); // Not '\x'296297if (isBad) {298PP.Diag(ArgTokStart[0], diag::err_invalid_character_to_charify);299Result = "' '"; // Use something arbitrary, but legal.300}301}302303PP.CreateString(Result, Tok,304ExpansionLocStart, ExpansionLocEnd);305return Tok;306}307308309