1

我必须解析一个看起来像这样的文件:

versioninfo
{
    "editorversion" "400"
    "editorbuild" "4715"
}
visgroups
{
}
world
{
    "id" "1"
    "mapversion" "525"
    "classname" "worldspawn"
    solid
    {
        "id" "2"
        side
        {
            "id" "1"
            "plane" "(-544 -400 0) (-544 -240 0) (-272 -240 0)"
        }
        side
        {
            "id" "2"
            "plane" "(-544 -240 -16) (-544 -400 -16) (-272 -400 -16)"
        }
    }
}

我有一个从头开始编写的解析器,但它有一些我无法追踪的错误,我想如果将来格式发生变化,它会很难维护。我决定改用 GOLD 解析系统来生成解析器。我的语法如下所示:

"Start Symbol" = <SectionList>

! SETS

{Section Chars} = {AlphaNumeric} + [_]
{Property Chars} = {Printable} - ["]

! TERMINALS

SectionName = {Section Chars}+ 
PropertyPart = '"' {Property Chars}* '"'

! RULES

<SectionList> ::= <Section>
               |  <Section> <SectionList>

<SectionBody> ::= <PropertyList>
               |  <SectionList>
               |  <PropertyList> <SectionList>

<Section> ::= SectionName '{' '}'
           |  SectionName '{' <SectionBody> '}'

<PropertyList> ::= <Property>
                |  <Property> <PropertyList>

<Property> ::= PropertyPart PropertyPart

没有错误,它可以很好地解析我的 2000 行测试文件。但是,这是我第一次编写自定义语法,所以我不确定我是否做得正确。

我可以对上面的语法进行任何改进吗?

4

1 回答 1

4

below are some changes i would request to change for better performance

1) make the grammar left recursive rules. this is better in terms of making shift reduce operations as gold parser is a shift reduce LR parser.

SectionList ::= Section

           |   SectionList Section

PropertyList ::= Property

            | PropertyList Property

2) third rule in below section forces you to have propertylist only before sectionlist but not between different 's. make sure its as per requirement

SectionBody ::= PropertyList

           |  SectionList

           |  PropertyList SectionList

i can help you better if required and if you let me know the language saying " it should accept this , shouldn't accept this" rather than a sample input which will not give 100% picture of your language. or let me know the bugs you felt from which we can define the language description also.

Regards, V M Rakesh (rakesh.vm@gmail.com)

于 2011-04-26T18:48:55.390 回答