简体   繁体   English

使用循环语句的BNF语法

[英]BNF grammar using loop statements

Write a simple BNF grammar for a subset of C that supports multiple statements including assignment, if-else, and while statements without block statements. 为C的子集编写一个简单的BNF语法,该语法支持多个语句,包括赋值,if-else和while语句而没有block语句。 Use meaningful names for your nonterminals (vs. cryptic letters). 为您的非终结符使用有意义的名称(与隐含字母相对)。 Assume variables are represented by single letters and are integers. 假设变量用单个字母表示,并且是整数。 Assume that the standard precedence rules apply for the operators *, /, +, -, and parentheses. 假定标准优先级规则适用于运算符*,/,+,-和括号。 Make sure to include relational operators (==, !=, <, >, >=, and <=). 确保包括关系运算符(==,!=,<,>,> =和<=)。 The following is a valid program for your grammar: 以下是您的语法的有效程序:

 a = -35;while (b > a);a = a + b;if (a >= 10);c = a;else c = b;

Can you expand your BNF to properly handle a C block statement as part of a while or if or else? 您能否在一段时间内(如果有的话)扩展BNF以正确处理C块语句? Revise your productions to support: while (b > a) a = a + b; 修改产品以支持:(b> a)a = a + b; printf(“in loop”); printf(“循环中”);

using the above grammar I came up with 使用上面的语法我想出了

<statement> ::=  a=-35
<while> ::= while (b>a)
<assign>::= a = a + b;
<if>::= if (a >= 10) 
<assign> ::= c=a;
<else> 
<assign> ::= c = b;

<while>::= while (b>a)
<assign>:= a = a + b;
<statement>::= printf ("in loop");

Is this a valid bnf grammar ? 这是有效的bnf语法吗?

No. What you are writting are more examples than a grammar. 不。您写的不是语法而是更多的例子。 A grammar explains how to produce all the valid constructs of the language. 语法说明了如何产生语言的所有有效构造。

For example 例如

 <while> ::= while <expression> <block>

Then, you define <expression> in a way that allows to write any expression in the language, and <block> as a block of statements (a simple statement or several statement grouped by brackets). 然后,以允许以该语言编写任何表达式的方式定义<expression> ,并定义<block>作为语句块(一个简单的语句或由方括号分组的多个语句)。

http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form http://en.wikipedia.org/wiki/Backus%E2%80%93Naur_Form

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM