以编程方式识别中的函数体

Function body identification in programmatically

本文关键字:函数体 识别 编程 方式      更新时间:2023-10-16

我正在尝试创建一个自动化工具,在函数体上方插入注释行。想法是,我将以文本形式阅读.CPP文件,并找到函数体。一旦在.CPP文件中找到函数体,我就会把函数头放在函数体上面。

文件的读取和写入将类似于普通文本文件,但我想知道广义函数体的定义。也就是说,我将如何以编程方式在.CPP文件中找到函数体。除此之外,还有其他选择,可以将函数头放在函数体之上。

谢谢。

以下是想法:

查找第一个大括号{。然后找到匹配的右大括号。重复

public List<string> FindFunctions(string str)
{
    var ret = new List<string>();
    var position = 0;
    var goout = false;
    while (!goout)
    {
        position = str.IndexOf("{", position);
        if (position == -1)
            break;
        var str1 = GetBracedString(str.Substring(position), '{', '}','"');
        position += str1.Length;
        ret.Add(str1);
    }
    return ret;
}


public String GetBracedString(string str, char openB, char closeB, char quoteChar)
{
    int i = 0;
    var goout = false;
    int index = -1;
    var isUnpairedQoute = new Func<string, char, bool>((s, q) => s.Count(x => x == q)%2 == 1);
    var braceMatch = new Func<string, char, char, bool>((s,o,c) => s.Count(x => x == o) == s.Count(x => x == c));
    while (!goout)
    {
        index = str.IndexOf(closeB, index + 1);
        var testS = str.Substring(0, index + 1);
        index = isUnpairedQoute(testS,quoteChar) ? str.IndexOf(quoteChar, index) : index;
        testS = str.Substring(0, index + 1);
        testS = Regex.Replace(testS, String.Format("{0}.*?[{1}{2}]+?.*?{0}", quoteChar, openB, closeB),match => new string('#', match.Value.Length));
        goout = braceMatch(testS,openB,closeB);
    }
    return str.Substring(0, index + 1);
}