Path: blob/main/contrib/llvm-project/clang/lib/Frontend/Rewrite/RewriteMacros.cpp
35266 views
//===--- RewriteMacros.cpp - Rewrite macros into their expansions ---------===//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 code rewrites macro invocations into their expansions. This gives you9// a macro expanded file that retains comments and #includes.10//11//===----------------------------------------------------------------------===//1213#include "clang/Rewrite/Frontend/Rewriters.h"14#include "clang/Basic/SourceManager.h"15#include "clang/Lex/Preprocessor.h"16#include "clang/Rewrite/Core/Rewriter.h"17#include "llvm/Support/Path.h"18#include "llvm/Support/raw_ostream.h"19#include <cstdio>20#include <memory>2122using namespace clang;2324/// isSameToken - Return true if the two specified tokens start have the same25/// content.26static bool isSameToken(Token &RawTok, Token &PPTok) {27// If two tokens have the same kind and the same identifier info, they are28// obviously the same.29if (PPTok.getKind() == RawTok.getKind() &&30PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())31return true;3233// Otherwise, if they are different but have the same identifier info, they34// are also considered to be the same. This allows keywords and raw lexed35// identifiers with the same name to be treated the same.36if (PPTok.getIdentifierInfo() &&37PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo())38return true;3940return false;41}424344/// GetNextRawTok - Return the next raw token in the stream, skipping over45/// comments if ReturnComment is false.46static const Token &GetNextRawTok(const std::vector<Token> &RawTokens,47unsigned &CurTok, bool ReturnComment) {48assert(CurTok < RawTokens.size() && "Overran eof!");4950// If the client doesn't want comments and we have one, skip it.51if (!ReturnComment && RawTokens[CurTok].is(tok::comment))52++CurTok;5354return RawTokens[CurTok++];55}565758/// LexRawTokensFromMainFile - Lets all the raw tokens from the main file into59/// the specified vector.60static void LexRawTokensFromMainFile(Preprocessor &PP,61std::vector<Token> &RawTokens) {62SourceManager &SM = PP.getSourceManager();6364// Create a lexer to lex all the tokens of the main file in raw mode. Even65// though it is in raw mode, it will not return comments.66llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(SM.getMainFileID());67Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());6869// Switch on comment lexing because we really do want them.70RawLex.SetCommentRetentionState(true);7172Token RawTok;73do {74RawLex.LexFromRawLexer(RawTok);7576// If we have an identifier with no identifier info for our raw token, look77// up the identifier info. This is important for equality comparison of78// identifier tokens.79if (RawTok.is(tok::raw_identifier))80PP.LookUpIdentifierInfo(RawTok);8182RawTokens.push_back(RawTok);83} while (RawTok.isNot(tok::eof));84}858687/// RewriteMacrosInInput - Implement -rewrite-macros mode.88void clang::RewriteMacrosInInput(Preprocessor &PP, raw_ostream *OS) {89SourceManager &SM = PP.getSourceManager();9091Rewriter Rewrite;92Rewrite.setSourceMgr(SM, PP.getLangOpts());93RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID());9495std::vector<Token> RawTokens;96LexRawTokensFromMainFile(PP, RawTokens);97unsigned CurRawTok = 0;98Token RawTok = GetNextRawTok(RawTokens, CurRawTok, false);99100101// Get the first preprocessing token.102PP.EnterMainSourceFile();103Token PPTok;104PP.Lex(PPTok);105106// Preprocess the input file in parallel with raw lexing the main file. Ignore107// all tokens that are preprocessed from a file other than the main file (e.g.108// a header). If we see tokens that are in the preprocessed file but not the109// lexed file, we have a macro expansion. If we see tokens in the lexed file110// that aren't in the preprocessed view, we have macros that expand to no111// tokens, or macro arguments etc.112while (RawTok.isNot(tok::eof) || PPTok.isNot(tok::eof)) {113SourceLocation PPLoc = SM.getExpansionLoc(PPTok.getLocation());114115// If PPTok is from a different source file, ignore it.116if (!SM.isWrittenInMainFile(PPLoc)) {117PP.Lex(PPTok);118continue;119}120121// If the raw file hits a preprocessor directive, they will be extra tokens122// in the raw file that don't exist in the preprocsesed file. However, we123// choose to preserve them in the output file and otherwise handle them124// specially.125if (RawTok.is(tok::hash) && RawTok.isAtStartOfLine()) {126// If this is a #warning directive or #pragma mark (GNU extensions),127// comment the line out.128if (RawTokens[CurRawTok].is(tok::identifier)) {129const IdentifierInfo *II = RawTokens[CurRawTok].getIdentifierInfo();130if (II->getName() == "warning") {131// Comment out #warning.132RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//");133} else if (II->getName() == "pragma" &&134RawTokens[CurRawTok+1].is(tok::identifier) &&135(RawTokens[CurRawTok+1].getIdentifierInfo()->getName() ==136"mark")) {137// Comment out #pragma mark.138RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//");139}140}141142// Otherwise, if this is a #include or some other directive, just leave it143// in the file by skipping over the line.144RawTok = GetNextRawTok(RawTokens, CurRawTok, false);145while (!RawTok.isAtStartOfLine() && RawTok.isNot(tok::eof))146RawTok = GetNextRawTok(RawTokens, CurRawTok, false);147continue;148}149150// Okay, both tokens are from the same file. Get their offsets from the151// start of the file.152unsigned PPOffs = SM.getFileOffset(PPLoc);153unsigned RawOffs = SM.getFileOffset(RawTok.getLocation());154155// If the offsets are the same and the token kind is the same, ignore them.156if (PPOffs == RawOffs && isSameToken(RawTok, PPTok)) {157RawTok = GetNextRawTok(RawTokens, CurRawTok, false);158PP.Lex(PPTok);159continue;160}161162// If the PP token is farther along than the raw token, something was163// deleted. Comment out the raw token.164if (RawOffs <= PPOffs) {165// Comment out a whole run of tokens instead of bracketing each one with166// comments. Add a leading space if RawTok didn't have one.167bool HasSpace = RawTok.hasLeadingSpace();168RB.InsertTextAfter(RawOffs, &" /*"[HasSpace]);169unsigned EndPos;170171do {172EndPos = RawOffs+RawTok.getLength();173174RawTok = GetNextRawTok(RawTokens, CurRawTok, true);175RawOffs = SM.getFileOffset(RawTok.getLocation());176177if (RawTok.is(tok::comment)) {178// Skip past the comment.179RawTok = GetNextRawTok(RawTokens, CurRawTok, false);180break;181}182183} while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() &&184(PPOffs != RawOffs || !isSameToken(RawTok, PPTok)));185186RB.InsertTextBefore(EndPos, "*/");187continue;188}189190// Otherwise, there was a replacement an expansion. Insert the new token191// in the output buffer. Insert the whole run of new tokens at once to get192// them in the right order.193unsigned InsertPos = PPOffs;194std::string Expansion;195while (PPOffs < RawOffs) {196Expansion += ' ' + PP.getSpelling(PPTok);197PP.Lex(PPTok);198PPLoc = SM.getExpansionLoc(PPTok.getLocation());199PPOffs = SM.getFileOffset(PPLoc);200}201Expansion += ' ';202RB.InsertTextBefore(InsertPos, Expansion);203}204205// Get the buffer corresponding to MainFileID. If we haven't changed it, then206// we are done.207if (const RewriteBuffer *RewriteBuf =208Rewrite.getRewriteBufferFor(SM.getMainFileID())) {209//printf("Changed:\n");210*OS << std::string(RewriteBuf->begin(), RewriteBuf->end());211} else {212fprintf(stderr, "No changes\n");213}214OS->flush();215}216217218