如何使用正则表达式查找 C 文件中的所有数组声明?

2 c c++ regex grep

我正在尝试分析一些第三方代码,并且我对在给定源(.c 和 .h)中声明+定义的所有数组感兴趣。了解在移植到嵌入式系统时是否浪费了一些内存很有趣。

我可以假设只使用标准类型,即 char、int、long、float、double。

这是我想要查找的示例:

char message[100];
int tag[MY_PERSONAL_TAG_SIZE];
double vald[2]   ={1.0,1.1}; 
Run Code Online (Sandbox Code Playgroud)

在同事的大力支持下,我尝试了以下方法,但出现了一些误报:

egrep -e '(char|int|long|short|float|double)[ \t]*[^ \t)]+[ \t]*\[[^ \t]+\]' *
Run Code Online (Sandbox Code Playgroud)

这也发现(它不应该):

wordTable  = &intTable[0];
MyFunction (MyPointer* foo, int *bar, int code[4], int add[4], char *Mystring[4]) {
Run Code Online (Sandbox Code Playgroud)

我猜正则表达式还会发现一些其他误报,并且可能会错过它应该找到的一些定义。所以我很乐意听到任何建议。谢谢。

Alp*_*per 5

我建议clang-query作为regex. 这里有一个例子来展示clang-query可以做什么。

两个文件test.htest.cpp类似的问题。

$ cat ~/CPP/test.h
 1  int x[10], y, z[10];

$ cat ~/CPP/test.cpp
 1  #include "test.h"
 2  
 3  #define MY_PERSONAL_TAG_SIZE 10
 4  
 5  struct MyPointer;
 6  
 7  void MyFunction (MyPointer* foo, int *bar, int code[4], int add[4], char *Mystring[4])
 8  {
 9  }
10   
11  int main()
12  {
13      char message[100];
14      int tag[MY_PERSONAL_TAG_SIZE];
15      double vald[2]   ={1.0,1.1}; 
16      int a[10], b, c[30];
17  
18      return 0;
19  }
Run Code Online (Sandbox Code Playgroud)

运行clang-querytest.cpp和查询数组声明。

$ ./clang-query ~/CPP/test.cpp --
clang-query> help
Available commands:

  match MATCHER, m MATCHER      Match the loaded ASTs against the given matcher.
  set bind-root (true|false)    Set whether to bind the root matcher to "root".
  set output (diag|print|dump)  Set whether to print bindings as diagnostics,
                                AST pretty prints or AST dumps.

clang-query> match varDecl(hasType(arrayType()))

Match #1:

~/CPP/test.h:1:1: note: "root" binds here
int x[10], y, z[10];
^~~~~~~~~

Match #2:

~/CPP/test.h:1:1: note: "root" binds here
int x[10], y, z[10];
^~~~~~~~~~~~~~~~~~~

Match #3:

~/CPP/test.cpp:13:5: note: "root" binds here
    char message[100];
    ^~~~~~~~~~~~~~~~~

Match #4:

~/CPP/test.cpp:14:5: note: "root" binds here
    int tag[MY_PERSONAL_TAG_SIZE];
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Match #5:

~/CPP/test.cpp:15:5: note: "root" binds here
    double vald[2]   ={1.0,1.1}; 
    ^~~~~~~~~~~~~~~~~~~~~~~~~~~

Match #6:

~/CPP/test.cpp:16:5: note: "root" binds here
    int a[10], b, c[30];
    ^~~~~~~~~

Match #7:

~/CPP/test.cpp:16:5: note: "root" binds here
    int a[10], b, c[30];
    ^~~~~~~~~~~~~~~~~~~
7 matches.
clang-query> 
Run Code Online (Sandbox Code Playgroud)