简体   繁体   English

试图了解C语法

[英]Trying to understand C Grammar

I started my journey into recursive parsers, and was looking into C Grammar, trying to understand how it works to replicate it in my code. 我开始了递归解析器的旅程,并一直在研究C语法,试图了解它如何在我的代码中复制它。

Then I saw this: 然后我看到了:

assignmentExpression
:   conditionalExpression
|   unaryExpression assignmentOperator assignmentExpression
|   DigitSequence // for
;

and this part in particular: 特别是这部分:

unaryExpression assignmentOperator assignmentExpression

With my (poor and probably wrong) understanding, a unary expression can be a Constant (if you follow the rest of the grammar), then it looks like this 1 = 1 is valid, which is obviously wrong. 根据我的理解(较差,可能是错误的),一元表达式可以是一个常数(如果遵循语法的其余部分),则看起来这是1 = 1是有效的,这显然是错误的。 I searched for C parsers, even the GCC source code, and the assignmentExpression functions never really have any code related to the unaryExpression part. 我搜索了C解析器,甚至是GCC源代码,而assignmentExpression函数从没有真正与unaryExpression部分相关的代码。

So I'm really confused; 所以我真的很困惑。 I'm probably missing something very important here. 我可能在这里错过了一些非常重要的东西。

C is not completely described by its grammar; C的语法没有完全描述。 a valid C program must conform to the grammar, but it also must conform to many other rules, eg rules relating to the type system. 有效的C程序必须符合语法,但还必须符合许多其他规则,例如与类型系统有关的规则。

So, you're right: 1 = 1 conforms to the rule you've quoted, but it's invalid anyway, because the left-hand-side is not an lvalue. 因此,您是对的: 1 = 1符合您引用的规则,但是无论如何都是无效的,因为左侧不是左值。

(Note that some compilers may actually treat 1 = 1 as a syntax error, because they may roll some of these other restrictions into the grammar that they apply. That's allowed; the spec gives compilers a lot of flexibility in how they implement things, as long as they handle valid programs correctly.) (请注意,有些编译器实际上可能将1 = 1视为语法错误,因为它们可能会将其他一些限制纳入适用的语法中。这是允许的;规范为编译器在实现事情上提供了很大的灵活性,例如只要他们能够正确处理有效程序。)

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

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