• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- Rewrite.cpp --------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang-c/Rewrite.h"
10 #include "CXSourceLocation.h"
11 #include "CXTranslationUnit.h"
12 #include "clang/Basic/SourceManager.h"
13 #include "clang/Frontend/ASTUnit.h"
14 #include "clang/Rewrite/Core/Rewriter.h"
15 
clang_CXRewriter_create(CXTranslationUnit TU)16 CXRewriter clang_CXRewriter_create(CXTranslationUnit TU) {
17   if (clang::cxtu::isNotUsableTU(TU)) {
18     LOG_BAD_TU(TU);
19     return {};
20   }
21   clang::ASTUnit *AU = clang::cxtu::getASTUnit(TU);
22   assert(AU);
23   return reinterpret_cast<CXRewriter>(
24       new clang::Rewriter(AU->getSourceManager(), AU->getLangOpts()));
25 }
26 
clang_CXRewriter_insertTextBefore(CXRewriter Rew,CXSourceLocation Loc,const char * Insert)27 void clang_CXRewriter_insertTextBefore(CXRewriter Rew, CXSourceLocation Loc,
28                             const char *Insert) {
29   assert(Rew);
30   clang::Rewriter &R = *reinterpret_cast<clang::Rewriter *>(Rew);
31   R.InsertTextBefore(clang::cxloc::translateSourceLocation(Loc), Insert);
32 }
33 
clang_CXRewriter_replaceText(CXRewriter Rew,CXSourceRange ToBeReplaced,const char * Replacement)34 void clang_CXRewriter_replaceText(CXRewriter Rew, CXSourceRange ToBeReplaced,
35                        const char *Replacement) {
36   assert(Rew);
37   clang::Rewriter &R = *reinterpret_cast<clang::Rewriter *>(Rew);
38   R.ReplaceText(clang::cxloc::translateCXRangeToCharRange(ToBeReplaced),
39                 Replacement);
40 }
41 
clang_CXRewriter_removeText(CXRewriter Rew,CXSourceRange ToBeRemoved)42 void clang_CXRewriter_removeText(CXRewriter Rew, CXSourceRange ToBeRemoved) {
43   assert(Rew);
44   clang::Rewriter &R = *reinterpret_cast<clang::Rewriter *>(Rew);
45   R.RemoveText(clang::cxloc::translateCXRangeToCharRange(ToBeRemoved));
46 }
47 
clang_CXRewriter_overwriteChangedFiles(CXRewriter Rew)48 int clang_CXRewriter_overwriteChangedFiles(CXRewriter Rew) {
49   assert(Rew);
50   clang::Rewriter &R = *reinterpret_cast<clang::Rewriter *>(Rew);
51   return R.overwriteChangedFiles();
52 }
53 
clang_CXRewriter_writeMainFileToStdOut(CXRewriter Rew)54 void clang_CXRewriter_writeMainFileToStdOut(CXRewriter Rew) {
55   assert(Rew);
56   clang::Rewriter &R = *reinterpret_cast<clang::Rewriter *>(Rew);
57   R.getEditBuffer(R.getSourceMgr().getMainFileID()).write(llvm::outs());
58 }
59 
clang_CXRewriter_dispose(CXRewriter Rew)60 void clang_CXRewriter_dispose(CXRewriter Rew) {
61   if (Rew)
62     delete reinterpret_cast<clang::Rewriter *>(Rew);
63 }
64