模态解析器使用yacc

huangapple go评论81阅读模式
英文:

Modal parser using yacc

问题

我正在使用yacc编写我的第一个解析器。我想解析一个包含3个“模式”的文件:

  • 语句模式
  • 表头模式
  • 表行模式

我希望我的解析器一开始处于语句模式,当它看到由连字符组成的行时,切换到表头模式。当它看到另一行连字符时,切换到表行模式,最后当它看到第三组连字符时,切换回语句模式:

语句...
语句...
语句...
----
表头
----
表行
表行
表行
----
语句
语句
语句

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

另一种可能性是使用“词法绑定”(Lexical Tie-ins)(不幸的是,你需要在文档中搜索该字符串)。然而,yacc教程的作者并没有告诉我关于这些“词法绑定”的任何信息,除了“这种“后门”方法可以被详细阐述到令人讨厌的程度。尽管如此,它代表了一种做一些其他方式难以做到甚至不可能做到的事情的方法。”这几乎没有什么鼓励性的内容。

英文:

I am writing my first parser in yacc. I would like to parse a file that has 3 "modes":

  • Statement mode
  • Table heading mode
  • Table row mode

I would like my parser to start out in statement mode, then when it sees a line consisting of minus signs, switch to table heading mode. When it sees another line of minus signs, switch to table row mode, and finally when it sees a third set of minus signs switch to statement mode:

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

One thing that occures to me, is that I could have 3 separate grammars which I would switch between in my line feed loop. However, I don't know how to create multiple grammars in one .y file.

The other thing that seems like a possibility is using "Lexical Tie-ins" (unfortunately, you'll have to search for that string in the document). However, the author of the yacc tutorial doesn't really tell me anything about these "lexical tie-ins" other than that "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." Which is hardly encouraging.

答案1

得分: 0

我通过使用词法分析器插入伪符号来解决了这个问题:

line
    : TABLE_HEADING sentences ',' table_heading_columns ',' sentences
    {
      fmt.Println("表头")
    }
    | TABLE_BODY table_body_columns
    {
      fmt.Println("表体")
    }
    | STATEMENT sentences
    {
      fmt.Println("语句")
    }
    ;
英文:

I have solved the problem by creating pseudo-symbols which I insert using the lexer:

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

huangapple
  • 本文由 发表于 2016年6月8日 03:17:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/37687582.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定