- 1、本文档共29页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
ChapterContext-FreeGrammarandLanguages
5.4 Ambiguity in Grammars and Languages Context free languages provide a convenient notation for recursive description of languages. The original goal of formalizing the structure of natural languages is still elusive, but CFGs are now the universally accepted formalism for definition of (the syntax of) programming languages. Writing parsers has become an almost fully automated process thanks to this theory. Conventions: Example: The language of balanced parentheses is context-free. It is generated by the following grammar: G = ( V={S}, T={(,)}, P={ S→ε, S→SS, S→(S) }, S ) V = {Expression, Term, Factor, Identifier} T = {+, *, (, ), x, y, z, …} P = { Expression → Term Expression → Expression + Term Term → Factor Term → Term * Factor Factor→ Identifer Factor → ( Expression ) Identifier → x Identifier → y Identifier → z Identifier → … } S = Expression Note, however, that the fact L=L(G1) is not totally obvious. We need to prove set inclusion both ways. Example: Consider the grammar G3: S → AS |ε A → 0A1 | A1 | 01 5.2 Parse Tree Formal definition: The Yield , Y(?) of a parse tree ? is the string over V∪T inductively defined as follows: (1) If ? is a leaf, then Y(?) is its label; (2) If ?1, …, ?k are subtrees of ? rooted at the children of the root of ? (in the order from left to right), then Y(?)=Y (?1) … Y(?k); ?Thus, Y(?) is the string obtained by reading the labels of leaves during the left (“inorder”) traversal of ?. 5.4 Ambiguity in Grammars and Languages If a grammar for arithmetic expressions contains productions E→ (E) | E+E | E*E | 1 | 2 | 3 | … , then 1+2*3 has two parse trees. The grammar for balanced parentheses we used at the beginning: S → SS | (S) | ε is also ambiguous. We saw one leftmost derivation for the string (())(). S ? SS ? (S)S ? ((S))S ? (())S ? (())(S) ? (())() Here is another: S ? SS ? SSS ? (S)SS ? ((S))SS ? (())SS ? (())(S)S ? (())()S ? (())() Even if a grammar G for a context-f
文档评论(0)