Path: blob/main/contrib/llvm-project/clang/lib/Lex/TokenConcatenation.cpp
35233 views
//===--- TokenConcatenation.cpp - Token Concatenation Avoidance -----------===//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 TokenConcatenation class.9//10//===----------------------------------------------------------------------===//1112#include "clang/Lex/TokenConcatenation.h"13#include "clang/Basic/CharInfo.h"14#include "clang/Lex/Preprocessor.h"15#include "llvm/Support/ErrorHandling.h"16using namespace clang;171819/// IsStringPrefix - Return true if Str is a string prefix.20/// 'L', 'u', 'U', or 'u8'. Including raw versions.21static bool IsStringPrefix(StringRef Str, bool CPlusPlus11) {2223if (Str[0] == 'L' ||24(CPlusPlus11 && (Str[0] == 'u' || Str[0] == 'U' || Str[0] == 'R'))) {2526if (Str.size() == 1)27return true; // "L", "u", "U", and "R"2829// Check for raw flavors. Need to make sure the first character wasn't30// already R. Need CPlusPlus11 check for "LR".31if (Str[1] == 'R' && Str[0] != 'R' && Str.size() == 2 && CPlusPlus11)32return true; // "LR", "uR", "UR"3334// Check for "u8" and "u8R"35if (Str[0] == 'u' && Str[1] == '8') {36if (Str.size() == 2) return true; // "u8"37if (Str.size() == 3 && Str[2] == 'R') return true; // "u8R"38}39}4041return false;42}4344/// IsIdentifierStringPrefix - Return true if the spelling of the token45/// is literally 'L', 'u', 'U', or 'u8'. Including raw versions.46bool TokenConcatenation::IsIdentifierStringPrefix(const Token &Tok) const {47const LangOptions &LangOpts = PP.getLangOpts();4849if (!Tok.needsCleaning()) {50if (Tok.getLength() < 1 || Tok.getLength() > 3)51return false;52SourceManager &SM = PP.getSourceManager();53const char *Ptr = SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation()));54return IsStringPrefix(StringRef(Ptr, Tok.getLength()),55LangOpts.CPlusPlus11);56}5758if (Tok.getLength() < 256) {59char Buffer[256];60const char *TokPtr = Buffer;61unsigned length = PP.getSpelling(Tok, TokPtr);62return IsStringPrefix(StringRef(TokPtr, length), LangOpts.CPlusPlus11);63}6465return IsStringPrefix(StringRef(PP.getSpelling(Tok)), LangOpts.CPlusPlus11);66}6768TokenConcatenation::TokenConcatenation(const Preprocessor &pp) : PP(pp) {69memset(TokenInfo, 0, sizeof(TokenInfo));7071// These tokens have custom code in AvoidConcat.72TokenInfo[tok::identifier ] |= aci_custom;73TokenInfo[tok::numeric_constant] |= aci_custom_firstchar;74TokenInfo[tok::period ] |= aci_custom_firstchar;75TokenInfo[tok::amp ] |= aci_custom_firstchar;76TokenInfo[tok::plus ] |= aci_custom_firstchar;77TokenInfo[tok::minus ] |= aci_custom_firstchar;78TokenInfo[tok::slash ] |= aci_custom_firstchar;79TokenInfo[tok::less ] |= aci_custom_firstchar;80TokenInfo[tok::greater ] |= aci_custom_firstchar;81TokenInfo[tok::pipe ] |= aci_custom_firstchar;82TokenInfo[tok::percent ] |= aci_custom_firstchar;83TokenInfo[tok::colon ] |= aci_custom_firstchar;84TokenInfo[tok::hash ] |= aci_custom_firstchar;85TokenInfo[tok::arrow ] |= aci_custom_firstchar;8687// These tokens have custom code in C++11 mode.88if (PP.getLangOpts().CPlusPlus11) {89TokenInfo[tok::string_literal ] |= aci_custom;90TokenInfo[tok::wide_string_literal ] |= aci_custom;91TokenInfo[tok::utf8_string_literal ] |= aci_custom;92TokenInfo[tok::utf16_string_literal] |= aci_custom;93TokenInfo[tok::utf32_string_literal] |= aci_custom;94TokenInfo[tok::char_constant ] |= aci_custom;95TokenInfo[tok::wide_char_constant ] |= aci_custom;96TokenInfo[tok::utf16_char_constant ] |= aci_custom;97TokenInfo[tok::utf32_char_constant ] |= aci_custom;98}99100// These tokens have custom code in C++17 mode.101if (PP.getLangOpts().CPlusPlus17)102TokenInfo[tok::utf8_char_constant] |= aci_custom;103104// These tokens have custom code in C++2a mode.105if (PP.getLangOpts().CPlusPlus20)106TokenInfo[tok::lessequal ] |= aci_custom_firstchar;107108// These tokens change behavior if followed by an '='.109TokenInfo[tok::amp ] |= aci_avoid_equal; // &=110TokenInfo[tok::plus ] |= aci_avoid_equal; // +=111TokenInfo[tok::minus ] |= aci_avoid_equal; // -=112TokenInfo[tok::slash ] |= aci_avoid_equal; // /=113TokenInfo[tok::less ] |= aci_avoid_equal; // <=114TokenInfo[tok::greater ] |= aci_avoid_equal; // >=115TokenInfo[tok::pipe ] |= aci_avoid_equal; // |=116TokenInfo[tok::percent ] |= aci_avoid_equal; // %=117TokenInfo[tok::star ] |= aci_avoid_equal; // *=118TokenInfo[tok::exclaim ] |= aci_avoid_equal; // !=119TokenInfo[tok::lessless ] |= aci_avoid_equal; // <<=120TokenInfo[tok::greatergreater] |= aci_avoid_equal; // >>=121TokenInfo[tok::caret ] |= aci_avoid_equal; // ^=122TokenInfo[tok::equal ] |= aci_avoid_equal; // ==123}124125/// GetFirstChar - Get the first character of the token \arg Tok,126/// avoiding calls to getSpelling where possible.127static char GetFirstChar(const Preprocessor &PP, const Token &Tok) {128if (IdentifierInfo *II = Tok.getIdentifierInfo()) {129// Avoid spelling identifiers, the most common form of token.130return II->getNameStart()[0];131} else if (!Tok.needsCleaning()) {132if (Tok.isLiteral() && Tok.getLiteralData()) {133return *Tok.getLiteralData();134} else {135SourceManager &SM = PP.getSourceManager();136return *SM.getCharacterData(SM.getSpellingLoc(Tok.getLocation()));137}138} else if (Tok.getLength() < 256) {139char Buffer[256];140const char *TokPtr = Buffer;141PP.getSpelling(Tok, TokPtr);142return TokPtr[0];143} else {144return PP.getSpelling(Tok)[0];145}146}147148/// AvoidConcat - If printing PrevTok immediately followed by Tok would cause149/// the two individual tokens to be lexed as a single token, return true150/// (which causes a space to be printed between them). This allows the output151/// of -E mode to be lexed to the same token stream as lexing the input152/// directly would.153///154/// This code must conservatively return true if it doesn't want to be 100%155/// accurate. This will cause the output to include extra space characters,156/// but the resulting output won't have incorrect concatenations going on.157/// Examples include "..", which we print with a space between, because we158/// don't want to track enough to tell "x.." from "...".159bool TokenConcatenation::AvoidConcat(const Token &PrevPrevTok,160const Token &PrevTok,161const Token &Tok) const {162// Conservatively assume that every annotation token that has a printable163// form requires whitespace.164if (PrevTok.isAnnotation())165return true;166167// First, check to see if the tokens were directly adjacent in the original168// source. If they were, it must be okay to stick them together: if there169// were an issue, the tokens would have been lexed differently.170SourceManager &SM = PP.getSourceManager();171SourceLocation PrevSpellLoc = SM.getSpellingLoc(PrevTok.getLocation());172SourceLocation SpellLoc = SM.getSpellingLoc(Tok.getLocation());173if (PrevSpellLoc.getLocWithOffset(PrevTok.getLength()) == SpellLoc)174return false;175176tok::TokenKind PrevKind = PrevTok.getKind();177if (!PrevTok.isAnnotation() && PrevTok.getIdentifierInfo())178PrevKind = tok::identifier; // Language keyword or named operator.179180// Look up information on when we should avoid concatenation with prevtok.181unsigned ConcatInfo = TokenInfo[PrevKind];182183// If prevtok never causes a problem for anything after it, return quickly.184if (ConcatInfo == 0) return false;185186if (ConcatInfo & aci_avoid_equal) {187// If the next token is '=' or '==', avoid concatenation.188if (Tok.isOneOf(tok::equal, tok::equalequal))189return true;190ConcatInfo &= ~aci_avoid_equal;191}192if (Tok.isAnnotation()) {193// Modules annotation can show up when generated automatically for includes.194assert(Tok.isOneOf(tok::annot_module_include, tok::annot_module_begin,195tok::annot_module_end, tok::annot_embed) &&196"unexpected annotation in AvoidConcat");197198ConcatInfo = 0;199if (Tok.is(tok::annot_embed))200return true;201}202203if (ConcatInfo == 0)204return false;205206// Basic algorithm: we look at the first character of the second token, and207// determine whether it, if appended to the first token, would form (or208// would contribute) to a larger token if concatenated.209char FirstChar = 0;210if (ConcatInfo & aci_custom) {211// If the token does not need to know the first character, don't get it.212} else {213FirstChar = GetFirstChar(PP, Tok);214}215216switch (PrevKind) {217default:218llvm_unreachable("InitAvoidConcatTokenInfo built wrong");219220case tok::raw_identifier:221llvm_unreachable("tok::raw_identifier in non-raw lexing mode!");222223case tok::string_literal:224case tok::wide_string_literal:225case tok::utf8_string_literal:226case tok::utf16_string_literal:227case tok::utf32_string_literal:228case tok::char_constant:229case tok::wide_char_constant:230case tok::utf8_char_constant:231case tok::utf16_char_constant:232case tok::utf32_char_constant:233if (!PP.getLangOpts().CPlusPlus11)234return false;235236// In C++11, a string or character literal followed by an identifier is a237// single token.238if (Tok.getIdentifierInfo())239return true;240241// A ud-suffix is an identifier. If the previous token ends with one, treat242// it as an identifier.243if (!PrevTok.hasUDSuffix())244return false;245[[fallthrough]];246case tok::identifier: // id+id or id+number or id+L"foo".247// id+'.'... will not append.248if (Tok.is(tok::numeric_constant))249return GetFirstChar(PP, Tok) != '.';250251if (Tok.getIdentifierInfo() ||252Tok.isOneOf(tok::wide_string_literal, tok::utf8_string_literal,253tok::utf16_string_literal, tok::utf32_string_literal,254tok::wide_char_constant, tok::utf8_char_constant,255tok::utf16_char_constant, tok::utf32_char_constant))256return true;257258// If this isn't identifier + string, we're done.259if (Tok.isNot(tok::char_constant) && Tok.isNot(tok::string_literal))260return false;261262// Otherwise, this is a narrow character or string. If the *identifier*263// is a literal 'L', 'u8', 'u' or 'U', avoid pasting L "foo" -> L"foo".264return IsIdentifierStringPrefix(PrevTok);265266case tok::numeric_constant:267return isPreprocessingNumberBody(FirstChar) ||268FirstChar == '+' || FirstChar == '-';269case tok::period: // ..., .*, .1234270return (FirstChar == '.' && PrevPrevTok.is(tok::period)) ||271isDigit(FirstChar) ||272(PP.getLangOpts().CPlusPlus && FirstChar == '*');273case tok::amp: // &&274return FirstChar == '&';275case tok::plus: // ++276return FirstChar == '+';277case tok::minus: // --, ->, ->*278return FirstChar == '-' || FirstChar == '>';279case tok::slash: //, /*, //280return FirstChar == '*' || FirstChar == '/';281case tok::less: // <<, <<=, <:, <%282return FirstChar == '<' || FirstChar == ':' || FirstChar == '%';283case tok::greater: // >>, >>=284return FirstChar == '>';285case tok::pipe: // ||286return FirstChar == '|';287case tok::percent: // %>, %:288return FirstChar == '>' || FirstChar == ':';289case tok::colon: // ::, :>290return FirstChar == '>' ||291(PP.getLangOpts().CPlusPlus && FirstChar == ':');292case tok::hash: // ##, #@, %:%:293return FirstChar == '#' || FirstChar == '@' || FirstChar == '%';294case tok::arrow: // ->*295return PP.getLangOpts().CPlusPlus && FirstChar == '*';296case tok::lessequal: // <=> (C++2a)297return PP.getLangOpts().CPlusPlus20 && FirstChar == '>';298}299}300301302