Yacc/Bison语法用于语句序列 [英] Yacc/Bison grammar for sequence of statements

查看:77
本文介绍了Yacc/Bison语法用于语句序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下规则来解析语句序列:语句必须由至少一个换行符分隔,并且该序列可以由至少零个换行符填充.例如

I'm trying to parse a sequence of statements, with the following rule: statements must be separated by at least one newline, and the sequence may be padded with at least zero newlines. For example,

\n
stmt\n
stmt\n
\n
stmt

到目前为止,我已经提出了这个Yacc语法,

So far I've come up with this Yacc grammar,

stmt_list:
    %empty
|   stmt_list stmt seps
;

seps:
    sep
| seps sep
;

但是它与我的示例不匹配,因为我的语法期望结尾处有换行符.有解析此内容的标准方法吗?谢谢.

but it doesn't match my example since my grammar expects a newline at the end. Is there are standard way of parsing this? Thanks.

推荐答案

一种简单(传统)的解决方案是允许使用空语句:

A simple (and traditional) solution is to allow empty statements:

program  : statement
         | program '\n' statement

statement: %empty
         | statement_type_1
         | ...

那并不能提供相同的分析树,因为它会迫使您忽略一个空语句:)但它具有简单的优点.

That doesn't quite provide the same parse tree, since it forces you to ignore an empty statement :) But it has the virtue of being simple.

否则,您将遇到类似问题:

Otherwise, you're stuck with something like:

program       : statement_list opt_newlines

statement_list: opt_newlines
              | statement_list newlines statement

opt_newlines  : %empty
              | opt_newlines '\n'

newlines      : '\n' opt_newlines

这篇关于Yacc/Bison语法用于语句序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆