"syntax" VS "semantics"

本文探讨了语言中句子的有效性由语法结构和词汇符号的意义共同决定。通过例子说明了语法正确但语义上不合理的情况,并介绍了如何在ANTLR语法中应用语义规则。
A language is a set of valid sentences. What makes a sentence valid? You can break validity down into two things: syntax and semantics. The term syntax refers to grammatical structure whereas the term semantics refers to the meaning of the vocabulary symbols arranged with that structure. Grammatical (syntactically valid) does not imply sensible (semantically valid), however. For example, the grammatical sentence "cows flow supremely" is grammatically ok (subject verb adverb) in English, but makes no sense. Similarly, in a programming language, your grammar (syntax rules) may allow ID EQUALS ID but the language may only allow the sentence if the text matched for ID does not represent a type name (a semantic rule).

When you write an ANTLR grammar, you are specifying the set of syntax rules obeyed by your language. ANTLR uses this to generate a recognizer for sentences in that language. To apply semantic rules, you must add actions or semantic predicates to the grammar. The actions test the "value" of the various tokens and their relationships to determine semantic validity. For example, if you look up a type name in a symbol table to ensure it's a type not a variable, you are applying a semantic rule.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值