Context free grammar in Java

BNF and context-free grammar

What is a grammar ? A grammar is a model of a language, or a language of a language. We can use finite grammar rules to generate infinite sentences of a language. The general method we describe a grammar is called BNF. For example, we describe a context-free grammar (CFG) using 4-tuple:

  1. A set of terminal symbols.
  2. A set of non-terminal symbols.
  3. A set of rules known as productions (or production rules) which can transform each non-terminal symbol to a sequence of non-terminal and/or terminal symbols.
  4. A start symbol or goal symbol, also called sentence in English.

A production example :

S -> aS;
S -> abc;

Maybe you know another grammar called context sensitive grammar. Then, what’s the differences between context free grammar and context sensitive grammar ? The most important difference is production rules : the left hand side of a context free grammar production is non-terminal symbol , but the left hand side of a context sensitive grammar contains not-termianl and terminal symbols.

More information can be found in Chomsky hierarchy. We can get the grammars’ relationship below.

Lexical grammar and syntactic grammar

Java is a programming language using context free grammar to define lexical grammar and syntactic grammar.

For example, the lexical grammar in Java contains the production:

BooleanLiteral :
        t r u e
        f a l s e

BooleanLiteral is a non-terminal symbol in the left hand side of the production, true or false is the right hand side sequence.

The syntactic grammar for the Java programming language has tokens defined by the lexical grammar as its terminal symbols.

For example , The syntactic production :

IfThenStatement: 
    if ( Expression ) Statement

IfThenStatement is a non-termianl symbol , which represents the token if which is a token defined by the lexical grammar, followed by a left parenthesis token, followed by an Expression, followed by a right parenthesis token, followed by a Statement.

References

  1. https://www.quora.com/What-is-a-context-free-grammar/answer/Yuval-Feinstein
  2. http://classes.engineering.wustl.edu/cse425s/resources/bnf/
  3. https://en.wikipedia.org/wiki/Context-free_grammar
  4. https://www.zhihu.com/question/21833944/answer/40689967
  5. https://docs.oracle.com/javase/specs/jls/se7/html/jls-2.html
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • ️#青蛙打卡#B1刘文华8月25日江西19/100 【百日目标】 1.23:00/7:00 2.【阅读3/12+运...
    Twinkle_L阅读 485评论 0 2
  • 我记得以前跟这句话产生过共鸣:痛苦,本质上是对自己无能的愤怒。而今天看到书里说,痛苦主要源于自身的各种情结,这种情...
    希可人儿阅读 189评论 0 0
  • 01 手输概算,弄清原理 上周末本打算看书、收拾房间的,结果领导安排我接手项目资金控制。单位目前的在建工程分布在...
    七云舒阅读 980评论 6 16
  • 39号武丽娟9月11日 感恩白桦老师给我一整天的辅导,从早上八点45到下午5点20整整微信语音7个多小时,午饭都没...
    花布鱼阅读 129评论 0 0