Parser 2

Ambiguous Grammar

A grammar is ambiguous if it can derive a sentence with two different parse trees. For example, using the grammar below we can derive two different parse tree with the sentence of 1+2*3.


ambiguous grammar
1+2*3 or (1+2)*3?

Ambiguous grammars are problematic for compiling since it can derive different meanings. Actually, we can usually eliminate ambiguity by transforming the grammar as shown below.


Grammar 1

Predictive Parsing

Some grammar are easy to use a simple algorithm as recursive-descent.
A recursive-descent parser for this language has one function for each non-
terminal and one clause for each production. We illustrate this by writing a recursive-descent parser for grammar below.


enum token {IF, THEN, ELSE, BEGIN, END, PRINT, SEMI, NUM, EQ};
extern enum token getToken(void);
enum token tok;
void advance() {tok=getToken();}
void eat(enum token t) {if (tok==t) advance(); else error();}
void S(void) {switch(tok) {
case IF: eat(IF); E(); eat(THEN); S();
eat(ELSE); S(); break;
case BEGIN: eat(BEGIN); S(); L(); break;
case PRINT: eat(PRINT); E(); break;
default: error();
}}
void L(void) {switch(tok) {
case END: eat(END); break;
case SEMI: eat(SEMI); S(); L(); break;
default: error();
}}
void E(void) { eat(NUM); eat(EQ); eat(NUM); }

However, this method will fail if using the umbiguous grammar above.

 void S(void) { E(); eat(EOF); }
void E(void) {switch (tok) {
case ?: E(); eat(PLUS); T(); break;
case ?: E(); eat(MINUS); T(); break;
case ?: T(); break;
default: error();
}}
void T(void) {switch (tok) {
case ?: T(); eat(TIMES); F(); break;
case ?: T(); eat(DIV); F(); break;
case ?: F(); break;
default: error();
}}

There is a conflict here: the E function has no way to know which production to use. That means the recursive-descent parsing works only on grammars where the first terminal symbol of each subexpression provides enough information to choose which production to use. So how can we use predictive parsing working on more complicated grammar?
This is how we do to parse the grammar below.


image.png

1. Calculate the First and Follow sets of all terminals in grammar.

FIRST(r) is the set of all terminals that can begin any string derived from r. For example, let r= T*F, thus FIRST(r) = { id , num , ( }.
Notice: If two different production X->r1 and X->r2 have the same left-hand-side symbol(X) and their right hand side have overlapping FIRST sets, then the grammar cannot be parsed using the predictive parsing. if FIRST(r1)=FIRST(r2)=I, then the X function in parser will not know what to do if the input token = I.
FOLLOW(X) is the set of terminals that can immediately follow X.
Then use the algorithm below to calculate.

for each terminal symbol Z
  FIRST[Z]←{Z}
repeat
  for each production X → Y1Y2 ··· Yk
    for each i from 1 to k, each j from i + 1 to k,
      if all the Yi are nullable
        then nullable[X] ← true
      if Y1 ··· Yi−1 are all nullable
        then FIRST[X] ← FIRST[X] ∪ FIRST[Yi]
      if Yi+1 ··· Yk are all nullable
        then FOLLOW[Yi] ← FOLLOW[Yi] ∪ FOLLOW[X]
      if Yi+1 ··· Yj−1 are all nullable
        then FOLLOW[Yi] ← FOLLOW[Yi] ∪ FIRST[Yj]
until FIRST, FOLLOW, and nullable did not change in this iteration.
image.png

2. Build the Parsing table.

To construct this table, enter production X → γ in row X, column T of the table for each T ∈ FIRST(γ ). Also, if γ is nullable, enter the production
in row X, column T for each T ∈ FOLLOW[X].


image.png

The presence of duplicate entries means that predictive parsing will not work.
Also this is grammar is ambiguous and ambiguous grammar will always lead to duplicate entries in the predictive parsing table.

3. Use recursive-decent parser to implement it based on the production for each (X,T) in parsing table.

LL(1)

What we talk about above actually is the LL(1), standing for Left-to-right parse, Leftmost-derivation,1-symbol lookahead.
We can generalize the notion of FIRST sets to describe the first k tokens of a string, and to make an LL(k) parsing table whose rows columns are every sequence of k terminals. This is not efficient since the table are so large.

Eliminating Left Recursion

Suppose we build a predictive parser for that ambiguous grammar (Grammar 1)



These two productions are certain to cause duplicate entries in the LL(1) parsing table, since any token in FIRST(T ) will also be in FIRST(E + T ). The problem is that E appears as the first right-hand-side symbol in an E-production; this is called left recursion. Grammars with left recursion cannot be LL(1).
To eliminate left recursion, we will rewrite using right recursion. We introduce
a new nonterminal E', and write


image.png

This derives the same set of strings (on T and +) as the original two productions, but now there is no left recursion. So we can reconstruct the grammar and build the LL(1) parser.


Left Factoring

We have solved Left Recursive problem, but there is one another problem when two production for the same nonterminal start with the same symbols.Like
S → if E then S else S
S → if E then S

We can solve that by left factoring the grammar, like below.
S → if E then S X
X →
X → else S

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,285评论 0 10
  • 男孩:丫头 如果我要离开 你会等我吗? 女孩:会啊,你要去哪 男孩:我要去英国了 这是一个难得的学习机会 女孩:...
    候鸟飞鱼阅读 315评论 0 0
  • 深夜我还不能睡,我擦完泪水,趴在床上,决定用文字记录,不然我会疯。 我们有三天没有说话了,我去你的宿舍五六次,都不...
    你打伞了吗阅读 330评论 1 0
  • 冬韵冬阳入画中,风轻云淡古今同。 碧池倒影更柔美,咏物抒情诗意浓。
    荷塘月色131419阅读 183评论 0 3
  • 首先感谢我的家人对我的支持,今天来到现场的三位都是我挚爱的家人,老公,儿子,婆婆,感谢他们对我工作的支持,一开始我...
    连夫人阅读 795评论 0 0