【问题标题】:Function body identification in programmatically以编程方式识别功能体
【发布时间】:2014-10-09 12:02:40
【问题描述】:

我正在尝试创建自动化工具以在函数体上方插入注释行。想法是,我将 .CPP 文件作为文本读取并找到函数体。在 .CPP 文件中找到函数体后,我会将函数头放在函数体上方。

文件的读写与普通文本文件类似,但我想知道通用的函数体定义。 IE。我将如何以编程方式在 .CPP 文件中找到函数体。否则还有其他方法可以将函数头放在函数体之上。

谢谢。

【问题讨论】:

  • 可能挂在某些 C++ 解析器中(例如 clang)?
  • @Niall:感谢您的回复,但您能否提供一些关于您所说的解析器的想法。我是自动化方面的新手。:)
  • 您可以确定{} 的位置,如果它前面没有使用它的其他东西,例如iffor 或其他什么,那么它就是一个函数身体?
  • 另外,您能否编辑一个示例来说明您要实现的目标。就我个人而言,我很难理解你的目标。
  • clang.llvm.org/docs/Tooling.html 是一个不错的起点,然后可能是 clang 格式化程序的代码作为示例?

标签: c# c++ function visual-c++ automation


【解决方案1】:

这是一个想法:

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

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);
}

【讨论】:

  • for 循环呢?或while 循环。或if。还是因为{我喜欢它}而{大括号}和它{几乎做同样的事情}?我知道有人在每一行代码上都加上括号,因为他不知道更好。一切都在该行的范围内,但编译的怪物。
  • 好吧,我想第一个花括号将属于函数体的开头。此外,它匹配的花括号将是函数体的结尾......
  • 假设你只想匹配文件中的一个函数。
  • @Yann4 请检查源代码和解释。注意“匹配的右大括号”。
  • 我并没有完全遵循goout = true 上面的内容,所以你可能是对的。
猜你喜欢
  • 1970-01-01
  • 2012-03-13
  • 2010-10-02
  • 2011-08-02
  • 1970-01-01
  • 2015-03-05
  • 1970-01-01
  • 2019-09-06
  • 2017-10-15
相关资源
最近更新 更多