【问题标题】:PEG rule to identify function protoype识别函数原型的 PEG 规则
【发布时间】:2019-05-14 17:57:43
【问题描述】:

我正在尝试创建一个可以解析 C 代码的解析器。我的用例解析可能包含函数原型的缓冲区。我想将此函数名称推送到符号表中。我是 Spirit 和 PEG 的新手,我正在尝试弄清楚如何编写可以识别函数原型的规则。

这是我当前的实现:

auto nameRule = x3::alpha >> *x3::alnum;
auto fcnPrototypeRule = nameRule >> *nameRule;
auto fcnRule = fcnPrototypeRule >> space >> x3::char_('(') >> -(nameRule % ',') >> x3::char_(');');

这是我的应用程序代码:

class Parser {   

    public:
    std::string functionParser(const std::string& input) {
        std::string output;
        x3::phrase_parse(input.begin(), input.end(), fcnRule, space, output);
        return output;
    }
};

输入为 = "extern void myFunction();" 输出是一个空字符串。我想得到函数原型。

【问题讨论】:

  • 提升? class?这不是 C,而是 C++。
  • 它是一个分析 C 代码的 C++ 程序。

标签: c++ compiler-construction boost-spirit


【解决方案1】:

看起来');' 应该是“);”?

此外,由于您有一个船长(x3::space 在对 phrase_parse 的调用中),因此没有多大意义:

  • 还在解析器表达式中指定space(它永远不会匹配)
  • 不要将nameRule 包装在lexemenoskip 指令中。另见Boost spirit skipper issues

所以首先尝试让它发挥作用:

std::string functionParser(const std::string& input) {
    namespace x3 = boost::spirit::x3;

    auto nameRule = x3::lexeme [x3::alpha >> *x3::alnum];
    auto fcnPrototypeRule = nameRule >> *nameRule;
    auto fcnRule = fcnPrototypeRule >> x3::char_('(') >> -(nameRule % ',') >> x3::char_(");");
    std::string output;
    x3::phrase_parse(input.begin(), input.end(), fcnRule, x3::space, output);
    return output;
}

但是,您会注意到它返回 ndn() (Live On Coliru)。

我认为这基本上是由于您的 AS (std::string) 与语法不太匹配造成的。我会说你的意思是“匹配”而不是“解析”,我会使用 x3::raw 来公开原始匹配:

Live On Colriu

#include <boost/spirit/home/x3.hpp>
#include <iostream>
#include <iomanip>

std::string functionParser(const std::string& input) {
    namespace x3 = boost::spirit::x3;

    auto nameRule = x3::lexeme [x3::alpha >> *x3::alnum];
    auto fcnPrototypeRule = nameRule >> *nameRule;
    auto fcnRule = x3::raw[ fcnPrototypeRule >> '(' >> -(nameRule % ',') >> ')' >> ';' ];
    std::string output;
    x3::phrase_parse(input.begin(), input.end(), fcnRule, x3::space, output);
    return output;
}

int main() {
    for (auto s : {
        "extern void myFunction();",
        })
    {
        std::cout << std::quoted(s) << " -> " << std::quoted(functionParser(s)) << "\n";
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    相关资源
    最近更新 更多