【问题标题】:Bison zero or one occurrences in grammar file野牛在语法文件中出现零次或一次
【发布时间】:2017-07-31 11:46:15
【问题描述】:

我需要解析类似 JSON 的对象 {"f": 1, "i": 2, "g": 5, ...},但与常规 JSON 对象不同,输入可以在对象中出现零次或一次...

所以,这是错误的对象{"f": 1, "f": 1, "i": 2, ...},因为它有键“f 两次”。

而且,这个对象很好{"i": 2},因为它只有键“i”并且不会出现多次。

这是我尝试过的。我知道它不起作用,但我不知道如何设置它是正确的。

RuleMemberList
    : RuleMember
        {{$$ = {}; $$[$1[0]] = $1[1];}}
    | RuleMemberList ',' RuleMember
        {$$ = $1; $1[$3[0]] = $3[1];}
    ;

RuleMember
    : I ':' RuleString
          {$$ = [$1, $3];}
    | G ':' RuleString
          {$$ = [$1, $3];}
    | F ':' RuleFinder
          {$$ = [$1, $3];}
    | A ':' RuleAction
          {$$ = [$1, $3];}
    | T ':' RuleTarget
          {$$ = [$1, $3];}
    | P ':' RuleNumber
          {$$ = [$1, $3];}
    | C ':' RuleChance
          {$$ = [$1, $3];}
    | L ':' RuleLayers
          {$$ = [$1, $3];}
    | R ':' RuleString
          {$$ = [$1, $3];}
    | E ':' RuleEvents
          {$$ = [$1, $3];}
    | B ':' RuleBinds
          {$$ = [$1, $3];}
    ;

我能以某种方式将其定义为 0 次或 1 次吗?

【问题讨论】:

    标签: parsing compiler-construction bison


    【解决方案1】:

    向地图添加元素时检查重复项。比如:

    | RuleMemberList ',' RuleMember
        { $$ = $1;
          if ($3[0] in $1)
            error("duplicate key ", $3[0], " in map");
          else
            $1[$3[0]] = $3[1];}
    ;
    

    【讨论】:

    • 看起来不错,但是没有名为“error”的函数。你熟悉另一个我可以用来返回错误的函数吗?
    • 找到解决方案:抛出“消息”工作正常。使用 JISON (zaa.ch/jison)
    猜你喜欢
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-17
    相关资源
    最近更新 更多