二十五、 clang插件

Clang插件

LLVM下載

由于國(guó)內(nèi)的網(wǎng)絡(luò)限制,我們需要借助鏡像下載LLVM的源碼

https://mirror.tuna.tsinghua.edu.cn/help/llvm/

  • 下載llvm項(xiàng)目

git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/llvm.git

  • 在LLVM的tools目錄下下載Clang

cd llvm/tools
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/clang.git

  • 在 LLVM 的 projects 目錄下下載 compiler-rt, libcxx, libcxxabi

cd ../projects
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/compiler-rt.g it
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/libcxx.git
git clone https://mirrors.tuna.tsinghua.edu.cn/git/llvm/libcxxabi.git

  • 在Clang的tools下安裝extra工具

cd ../tools/clang/tools
git clone https://mirrors.tuna.tsinghua.edu.cn/git/LLvm/cLang-tooLs-e xtra.git

LLVM編譯

由于最新的LLVM只支持c make來(lái)編譯了,我們還需要安裝c make。

安裝cmake

  • 查看brew是否安裝cmake如果有就跳過(guò)下面步驟

brew list

  • 通過(guò)brew安裝cmake

brew install cmake

編譯LLVM

通過(guò)xcode編譯LLVM

  • cmake編譯成Xcode項(xiàng)目

mkdir build_xcode
cd build_xcode
cmake -G Xcode ../llvm

  • 使用Xcode編譯Clang。
    • 選擇自動(dòng)創(chuàng)建Schemes


      自動(dòng)創(chuàng)建Schemes.png
    • 編譯,選擇ALL_BUILD Secheme進(jìn)行編譯,預(yù)計(jì)1+小時(shí)。


      選擇編譯.png

我們這里只需要手動(dòng)編譯,選擇clangclangTooLing

手動(dòng)編譯選擇.png

創(chuàng)建插件

目標(biāo): 在聲明屬性時(shí),該用copy的地方,沒有使用copy,給予提示

  • 在/llvm/tools/clang/tools 目錄下新建插件 HKPlugin


    新建插件目錄.png
  • 修改/llvm/tools/clang/tools 目錄下的 CMakeLists.txt 文件,新增 add_clang_subdirectory(HKPlugin)

    添加插件命令.png

  • 在HKPlugin目錄下新建一個(gè)名為HKPlugin.cpp的文件和CMakeLists.txt的文件。在CMakeLists.txt中寫上

add_llvm_library( HKPlugin MODULE BUILDTREE_ONLY
HKPlugin.cpp
)
接下來(lái)利用cmake重新生成一下Xcode項(xiàng)目,在build_xcode中cmake -g Xcode ../llvm

  • 最后可以在LLVM的Xcode項(xiàng)目中可以看到Loadable modules目錄下有自己 的Plugin目錄了。我們可以在里面編寫插件代碼。
添加插件模塊.png

添加下自己的插件,等下編譯

#include <iostream>
#include "clang/AST/AST.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
using    namespace    clang;
using    namespace    std;
using    namespace    llvm;
using    namespace    clang::ast_matchers;

namespace HKPlugin {
    class HKConsumer: public ASTConsumer {
    public:
        //解析一個(gè)頂級(jí)的聲明就回調(diào)一次
        bool HandleTopLevelDecl(DeclGroupRef D) {
            cout<<"正在解析..."<<endl;
            return true;
        }
        
        //整個(gè)文件都解析完成的回調(diào)
        void HandleTranslationUnit(ASTContext &Ctx) {
            cout << "文件解析完畢" << endl;
        }
    };

    //繼承PluginASTAction 實(shí)現(xiàn)我們自定義的Action
    class HKASTAction:public PluginASTAction{
    public:
        //重寫
        bool ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &arg){
            return true;
        }
        
        std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
            return unique_ptr<HKConsumer>(new HKConsumer);
        }
    };
}
//注冊(cè)插件

static FrontendPluginRegistry::Add<HKPlugin::HKASTAction> HK("HKPlugin","this is HKPlugin");

先簡(jiǎn)單寫些測(cè)試代碼,然后編譯生成dylib


生成dylib.png
int sum(int a);
int a;
int sum(int a){
    int b = 10;
    return 10 + b;
}
int sum2(int a,int b){
    int c = 10;
    return a + b + c;
}

寫些測(cè)試代碼

自己編譯的 clang 文件路徑 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/ -Xclang -load -Xclang 自己編譯的 clang 文件路徑 -Xclang -add-plugin -Xclang 自己編譯的 clang 文件路徑 -c 自己編譯的 clang 文件路徑

例: /Users/xxx/Desktop/LLVMENV/build_xcode/Debug/bin/clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk/ -Xclang -load -Xclang /Users/xxx/Desktop/LLVMENV/build_xcode/Debug/lib/HKPlugin.dylib -Xclang -add-plugin -Xclang HKPlugin -c ./hello.m
注:iPhoneSimulator13.5.sdk換成自己目錄下的sdk版本

正在解析...
正在解析...
正在解析...
正在解析...
文件解析完畢

現(xiàn)在在viewController中聲明屬性

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic, strong) NSDictionary* dict;
@property(nonatomic, strong) NSArray* arr;
@property(nonatomic, strong) NSString* name;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}
@end

然后通過(guò)語(yǔ)法分析,查看抽象語(yǔ)法樹

clang -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator13.5.sdk -fmodules -fsyntax-only -Xclang -ast-dump ViewController.m

TranslationUnitDecl 0x7f9e57000008 <<invalid sloc>> <invalid sloc> <undeserialized declarations>
|-TypedefDecl 0x7f9e570008a0 <<invalid sloc>> <invalid sloc> implicit __int128_t '__int128'
| `-BuiltinType 0x7f9e570005a0 '__int128'
|-TypedefDecl 0x7f9e57000910 <<invalid sloc>> <invalid sloc> implicit __uint128_t 'unsigned __int128'
| `-BuiltinType 0x7f9e570005c0 'unsigned __int128'
|-TypedefDecl 0x7f9e570009b0 <<invalid sloc>> <invalid sloc> implicit SEL 'SEL *'
| `-PointerType 0x7f9e57000970 'SEL *' imported
|   `-BuiltinType 0x7f9e57000800 'SEL'
|-TypedefDecl 0x7f9e57000a98 <<invalid sloc>> <invalid sloc> implicit id 'id'
| `-ObjCObjectPointerType 0x7f9e57000a40 'id' imported
|   `-ObjCObjectType 0x7f9e57000a10 'id' imported
|-TypedefDecl 0x7f9e57000b78 <<invalid sloc>> <invalid sloc> implicit Class 'Class'
| `-ObjCObjectPointerType 0x7f9e57000b20 'Class' imported
|   `-ObjCObjectType 0x7f9e57000af0 'Class' imported
|-ObjCInterfaceDecl 0x7f9e57000bd0 <<invalid sloc>> <invalid sloc> implicit Protocol
|-TypedefDecl 0x7f9e57000f48 <<invalid sloc>> <invalid sloc> implicit __NSConstantString 'struct __NSConstantString_tag'
| `-RecordType 0x7f9e57000d40 'struct __NSConstantString_tag'
|   `-Record 0x7f9e57000ca0 '__NSConstantString_tag'
|-TypedefDecl 0x7f9e58008400 <<invalid sloc>> <invalid sloc> implicit __builtin_ms_va_list 'char *'
| `-PointerType 0x7f9e57000fa0 'char *'
|   `-BuiltinType 0x7f9e570000a0 'char'
|-TypedefDecl 0x7f9e580086e8 <<invalid sloc>> <invalid sloc> implicit __builtin_va_list 'struct __va_list_tag [1]'
| `-ConstantArrayType 0x7f9e58008690 'struct __va_list_tag [1]' 1 
|   `-RecordType 0x7f9e580084f0 'struct __va_list_tag'
|     `-Record 0x7f9e58008458 '__va_list_tag'
|-ImportDecl 0x7f9e5852bc18 <./ViewController.h:9:1> col:1 implicit UIKit
|-ObjCInterfaceDecl 0x7f9e58541e00 <line:11:1, line:14:2> line:11:12 ViewController
| |-super ObjCInterface 0x7f9e5852be78 'UIViewController'
| `-ObjCImplementation 0x7f9e5857f460 'ViewController'
|-ObjCCategoryDecl 0x7f9e58541f30 <ViewController.m:11:1, line:15:2> line:11:12
| |-ObjCInterface 0x7f9e58541e00 'ViewController'
| |-ObjCPropertyDecl 0x7f9e58548a00 <line:12:1, col:44> col:44 dict 'NSDictionary *' readwrite nonatomic strong
| |-ObjCMethodDecl 0x7f9e58548a80 <col:44> col:44 implicit - dict 'NSDictionary *'
| |-ObjCMethodDecl 0x7f9e58548c28 <col:44> col:44 implicit - setDict: 'void'
| | `-ParmVarDecl 0x7f9e58548cb0 <col:44> col:44 dict 'NSDictionary *'
| |-ObjCPropertyDecl 0x7f9e58551cd0 <line:13:1, col:39> col:39 arr 'NSArray *' readwrite nonatomic strong
| |-ObjCMethodDecl 0x7f9e58551d50 <col:39> col:39 implicit - arr 'NSArray *'
| |-ObjCMethodDecl 0x7f9e58551ea8 <col:39> col:39 implicit - setArr: 'void'
| | `-ParmVarDecl 0x7f9e58551f30 <col:39> col:39 arr 'NSArray *'
| |-ObjCPropertyDecl 0x7f9e585650d0 <line:14:1, col:40> col:40 name 'NSString *' readwrite nonatomic strong
| |-ObjCMethodDecl 0x7f9e58565150 <col:40> col:40 implicit - name 'NSString *'
| `-ObjCMethodDecl 0x7f9e585652a8 <col:40> col:40 implicit - setName: 'void'
|   `-ParmVarDecl 0x7f9e58565330 <col:40> col:40 name 'NSString *'
`-ObjCImplementationDecl 0x7f9e5857f460 <line:17:1, line:25:1> line:17:17 ViewController
  |-ObjCInterface 0x7f9e58541e00 'ViewController'
  |-ObjCMethodDecl 0x7f9e5857f580 <line:19:1, line:22:1> line:19:1 - viewDidLoad 'void'
  | |-ImplicitParamDecl 0x7f9e585c9c08 <<invalid sloc>> <invalid sloc> implicit self 'ViewController *'
  | |-ImplicitParamDecl 0x7f9e585c9c70 <<invalid sloc>> <invalid sloc> implicit _cmd 'SEL':'SEL *'
  | `-CompoundStmt 0x7f9e585cf2b8 <col:21, line:22:1>
  |   `-ObjCMessageExpr 0x7f9e585c9cd8 <line:20:5, col:23> 'void' selector=viewDidLoad super (instance)
  |-ObjCIvarDecl 0x7f9e585c8168 <line:12:44> col:44 implicit _dict 'NSDictionary *' synthesize private
  |-ObjCPropertyImplDecl 0x7f9e585c81c8 <<invalid sloc>, col:44> <invalid sloc> dict synthesize
  | |-ObjCProperty 0x7f9e58548a00 'dict'
  | `-ObjCIvar 0x7f9e585c8168 '_dict' 'NSDictionary *'
  |-ObjCIvarDecl 0x7f9e585c84e0 <line:13:39> col:39 implicit _arr 'NSArray *' synthesize private
  |-ObjCPropertyImplDecl 0x7f9e585c8540 <<invalid sloc>, col:39> <invalid sloc> arr synthesize
  | |-ObjCProperty 0x7f9e58551cd0 'arr'
  | `-ObjCIvar 0x7f9e585c84e0 '_arr' 'NSArray *'
  |-ObjCIvarDecl 0x7f9e585c9890 <line:14:40> col:40 implicit _name 'NSString *' synthesize private
  |-ObjCPropertyImplDecl 0x7f9e585c98f0 <<invalid sloc>, col:40> <invalid sloc> name synthesize
  | |-ObjCProperty 0x7f9e585650d0 'name'
  | `-ObjCIvar 0x7f9e585c9890 '_name' 'NSString *'
  |-ObjCMethodDecl 0x7f9e585c82f8 <line:12:44> col:44 implicit - dict 'NSDictionary *'
  |-ObjCMethodDecl 0x7f9e585c8450 <col:44> col:44 implicit - setDict: 'void'
  | `-ParmVarDecl 0x7f9e58548cb0 <col:44> col:44 dict 'NSDictionary *'
  |-ObjCMethodDecl 0x7f9e585c8670 <line:13:39> col:39 implicit - arr 'NSArray *'
  |-ObjCMethodDecl 0x7f9e585c9800 <col:39> col:39 implicit - setArr: 'void'
  | `-ParmVarDecl 0x7f9e58551f30 <col:39> col:39 arr 'NSArray *'
  |-ObjCMethodDecl 0x7f9e585c9a20 <line:14:40> col:40 implicit - name 'NSString *'
  `-ObjCMethodDecl 0x7f9e585c9b78 <col:40> col:40 implicit - setName: 'void'
    `-ParmVarDecl 0x7f9e58565330 <col:40> col:40 name 'NSString *'

我們可以找到其中的屬性節(jié)點(diǎn)和他的修飾符

| |-ObjCPropertyDecl 0x7f9e585650d0 <line:14:1, col:40> col:40 name 'NSString *' readwrite nonatomic strong

完整代碼如下

#include <iostream>
#include "clang/AST/AST.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/Frontend/FrontendPluginRegistry.h"
using    namespace    clang;
using    namespace    std;
using    namespace    llvm;
using    namespace    clang::ast_matchers;

namespace HKPlugin {

    class HKMatchCallback:public MatchFinder::MatchCallback{
    private:
        CompilerInstance &CI;
        
        bool isUserSourceCode(const string fileName){
            if (fileName.empty()) return false;
            //非xcode中的源碼都認(rèn)為是用戶的
            if(fileName.find("/Applications/Xcode.app/") == 0)return false;
            return true;
        }
        
        //判斷是否應(yīng)該用copy修飾
        bool isShouldUseCopy(const string typeStr){
            if (typeStr.find("NSString") != string::npos ||
                typeStr.find("NSArray") != string::npos ||
                typeStr.find("NSDictionary") != string::npos ) {
                return true;
            }
            return false;
        }
    public:
        HKMatchCallback(CompilerInstance &CI):CI(CI){}
        void run(const MatchFinder::MatchResult &Result) {
            //通過(guò)Result獲得節(jié)點(diǎn)
            //之前綁定的標(biāo)識(shí)
            const ObjCPropertyDecl * propertyDecl =  Result.Nodes.getNodeAs<ObjCPropertyDecl>("objcPropertyDecl");
            

            //獲取文件名稱
            string fileName = CI.getSourceManager().getFilename(propertyDecl-> getSourceRange().getBegin()).str();

            //判斷節(jié)點(diǎn)有值并且是用戶文件
            if (propertyDecl && isUserSourceCode(fileName)) {
                //節(jié)點(diǎn)類型轉(zhuǎn)為字符串
                string typeStr = propertyDecl->getType().getAsString();
                //拿到及誒單的描述信息
                ObjCPropertyDecl::PropertyAttributeKind attrKind = propertyDecl->getPropertyAttributes();
                //判斷應(yīng)該使用copy但是沒有使用copy
                if (isShouldUseCopy(typeStr) && !(attrKind & clang::ObjCPropertyDecl::OBJC_PR_copy)) {
                    cout << typeStr << "應(yīng)該用copy修飾!但你沒有" << endl;
                    //診斷引擎
                    DiagnosticsEngine &diag = CI.getDiagnostics();
                    //Report 報(bào)告
                    diag.Report(propertyDecl->getBeginLoc(),diag.getCustomDiagID(DiagnosticsEngine::Warning, "--- %0    這個(gè)地方推薦使用copy"))<<typeStr
                }
//                cout<<"--拿到了:"<<typeStr<<"---屬于文件:"<<fileName<<endl;
                
            }
        }
    };

    class HKConsumer: public ASTConsumer {
    private:
        //AST節(jié)點(diǎn)的查找過(guò)濾器
        MatchFinder matcher;
        HKMatchCallback callback;
    public:
        HKConsumer(CompilerInstance &CI):callback(CI){
            //添加一個(gè)MatchFinder去匹配objcPropertyDecl節(jié)點(diǎn)
            //回調(diào)在HKMatchCallback里面run方法
            
            matcher.addMatcher(objcPropertyDecl().bind("objcPropertyDecl"), &callback);
        }
        //解析一個(gè)頂級(jí)的聲明就回調(diào)一次
        bool HandleTopLevelDecl(DeclGroupRef D) {
            cout<<"正在解析..."<<endl;
            return true;
        }
        
        //整個(gè)文件都解析完成的回調(diào)
        void HandleTranslationUnit(ASTContext &Ctx) {
            cout << "文件解析完畢" << endl;
            matcher.matchAST(Ctx);//將語(yǔ)法樹交給過(guò)濾器
        }
    };

    //繼承PluginASTAction 實(shí)現(xiàn)我們自定義的Action
    class HKASTAction:public PluginASTAction{
    public:
        //重寫
        bool ParseArgs(const CompilerInstance &CI, const std::vector<std::string> &arg){
            return true;
        }
        
        std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
            //ASTConsumer是一個(gè)抽象類,這里返回一個(gè)自定義的類來(lái)繼承
            return unique_ptr<HKConsumer>(new HKConsumer(CI));
        }
    };
}
//注冊(cè)插件

static FrontendPluginRegistry::Add<HKPlugin::HKASTAction> HK("HKPlugin","this is HKPlugin");

編譯完成.在xcode中加載插件


加載插件.png

-Xclang -load -Xclang (.dylib)動(dòng)態(tài)庫(kù)路徑 -Xclang -add-plugin -Xclang HKPlugin

由于Clang插件需要使用對(duì)應(yīng)的版本去加載,如果版本不一致則會(huì)導(dǎo)致編譯 錯(cuò)誤,會(huì)出現(xiàn)如下圖所示


編譯錯(cuò)誤.png

在Build Settings欄目中新增兩項(xiàng)用戶定義的設(shè)置


新增用戶設(shè)置.png
  • 分別是CC和CXX
    CC對(duì)應(yīng)的是自己編譯的clang的絕對(duì)路徑
    CXX對(duì)應(yīng)的是自己編譯的clang++的絕對(duì)路徑。


    CC&CXX.png

接下來(lái)在 Build Settings 欄目中搜索 index,將 Enable Index-Wihle-Building Functionality 的 D efault 改為 NO。


command+B編譯下程序。
現(xiàn)在ViewController中就會(huì)出現(xiàn)提示。
提示.png

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容