【问题标题】:extract arguments from function with scripting使用脚本从函数中提取参数
【发布时间】:2011-03-21 12:07:25
【问题描述】:

我有一个这样的函数原型文件:

int func1(type1 arg, int x);

type2 funct2(int z, char* buffer);

我想创建一个可以打印的脚本(bash、sed、awk 等等)

function = func1 // first argument type = type1// second argument type = int
function = func1 // first argument type = int// second argument type = char*

换句话说,标记每一行并打印函数名称和参数。此外,我想将这些标记作为变量保存以便稍后打印它们,例如echo $4

【问题讨论】:

    标签: linux bash scripting sed


    【解决方案1】:

    另一种方法是使用“-g”进行编译并读取调试信息。
    This answer 可以帮助您读取调试信息并找出函数参数(它是 Python,而不是 bash,但我会建议使用 Python 或 Perl 而不是 bash)。

    由此产生的解决方案将比任何基于文本解析的解决方案更加强大。它将处理定义函数的所有不同方式,甚至处理诸如在宏中定义的函数之类的疯狂事物。

    为了更好地说服您(或者如果您不相信,可以帮助您做对),这里列出了可能会破坏您的解析的测试用例:

    // Many lines
    const
    char
    *
    
    f
    (
    int
    x
    )
    {
    }
    
    // Count parenthesis!
    void f(void (*f)(void *f)) {}
    
    // Old style
    void f(a, b)
    int a;
    char *b
    {
    }
    
    // Not a function
    int f=sizeof(int);
    
    // Nesting
    int f() {
        int g() { return 1; }
        return g();
    }
    
    // Just one
    void f(int x /*, int y */) { }
    
    // what if?
    void (int x
    #ifdef ALSO_Y
         , int y
    #endif
    ) { }
    
    // A function called __attribute__?
    static int __attribute__((always_inline)) f(int x) {}
    

    【讨论】:

      【解决方案2】:

      这是一个开始。

      #!/bin/bash
      #bash 3.2+
      while read -r line
      do
        line="${line#* }"
        [[ $line =~ "^(.*)\((.*)\)" ]]
        echo  "function: ${BASH_REMATCH[1]}"
        echo  "args: ${BASH_REMATCH[2]}"
        ARGS=${BASH_REMATCH[2]}
        FUNCTION=${BASH_REMATCH[1]}
        # break down the arguments further.
        set -- $ARGS
        echo "first arg type:$1 , second arg type: $2"
      done <"file"
      

      输出

      $ ./shell.sh
      function: func1
      args: type1 arg, int x
      first arg type:type1 , second arg type: arg,
      function: funct2
      args: int z, char* buffer
      first arg type:int , second arg type: z,
      

      【讨论】:

      • 如何将反向引用存储在 sed 中?例如回声“abcd”| sed 's/ab(.*)/\1/' 这将打印“cd”。如何将 cd 存储在变量中?
      • var=$(echo "abcd" | sed 's/ab(.*)/\1/')
      • 快到了。我有“int func(struct type1* tp, TYPE1 *name, TYPE2 *name2);”这一行。我想将 TYPE1 和 TYPE2 存储在一个变量中,然后打印出来
      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 2022-01-22
      • 2013-03-30
      • 2016-04-24
      • 2022-01-26
      • 2022-01-13
      • 2011-02-10
      • 2020-02-19
      相关资源
      最近更新 更多