使用 yacc 的模态解析器

Modal parser using yacc

我正在用 yacc 编写我的第一个解析器。我想解析一个包含 3 "modes":

的文件

我希望我的解析器以语句模式启动,然后当它看到由减号组成的行时,切换到 table 标题模式。当它看到另一行减号时,切换到 table 行模式,最后当它看到第三组减号时切换到语句模式:

statement...
statement...
statement...
----
table heading
----
table row
table row
table row
----
statement
statement
statement

我想到的一件事是,我可以在 line feed loop 中切换 3 个单独的语法。但是,我不知道如何在一个 .y 文件中创建多个语法。

另一个似乎可行的方法是使用 "Lexical Tie-ins"(遗憾的是,您必须在文档中搜索该字符串)。然而,yacc 教程的作者并没有真正告诉我关于这些 "lexical tie-ins" 的任何信息,除了 "This kind of ``backdoor'' approach can be elaborated to a noxious degree. Nevertheless, it represents a way of doing some things that are difficult, if not impossible, to do otherwise." 这一点并不令人鼓舞。

我已经通过创建使用词法分析器插入的伪符号解决了这个问题:

line
    : TABLE_HEADING sentences ',' table_heading_columns ',' sentences
    {
      fmt.Println("TABLE_HEADING")
    }
    | TABLE_BODY table_body_columns
    {
      fmt.Println("TABLE_BODY")
    }
    | STATEMENT sentences
    {
      fmt.Println("STATEMENT")
    }
    ;