Grammar.parse似乎永远循环并使用100%的CPU

转自 the #perl6 IRC channel,by jkramer,with permission

我正在玩语法并试图解析一个ini风格的文件,但不知何故,Grammar.parse似乎永远循环并使用100%的cpu.任何想法在这里有什么问题?

grammar Format {
  token TOP {
    [
      <comment>*
      [
        <section>
        [ <line> | <comment> ]*
      ]*
    ]*
  }

  rule section {
    '[' <identifier> <subsection>? ']'
  }

  rule subsection {
    '"' <identifier> '"'
  }

  rule identifier {
    <[A..Za..z]> <[A..Za..z0..9_-]>+
  }

  rule comment {
    <[";]> .*? $$
  }

  rule line {
    <key> '=' <value>
  }

  rule key {
    <identifier>
  }

  rule value {
    .*? $$
  }
}

Format.parse('lol.conf'.IO.slurp)

解决方法

Token TOP在subregex上具有可以解析空字符串的*量词(因为< comment>和包含< section>的组都有自己的*量词).

如果内部子规则匹配空字符串,它可以无限次地执行,而不会使光标前进.目前,Perl 6没有针对此类错误的保护.

在我看来,你可以简化你的代码

token TOP {
  <comment>*
  [
    <section>
    [ <line> | <comment> ]*
  ]*
}

(不需要[…] *的外部组,因为最后的< comment>也匹配部分之前的注释.

相关文章

1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(...
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据...
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,...
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了...
在实际生产环境中,常常需要从后台日志中截取报文,报文的形...
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让...