第七章语义剖析和中间代码生成.ppt
文本预览下载声明
t1 := -c t2 := b* t1 t3 := -c t4 := b* t3 t5 := t2+t4 a := t5 assign a + * b c uminus * uminus c b a:=b*-c+b*-c 产生赋值语句三地址代码的翻译模式 S→id:=E {p:=lookup(id.name); if pnil then emit(p:= E.place)else error} E→E1+E2 {E.place=newtemp; emit(E.place:=E1.place+E2.place)} E→E1*E2 {E.place=newtemp; emit(E.place:=E1.place*E2.place)} E →-E { E.place:=newtemp; emit(E.place ′ := ′ ′uminus′E1.place} E→(E1) {E.place:=E1.place} E→id {p:=lookup(id.name); if pnil then E.place:=p else error} 7.4 布尔表达式的翻译 布尔表达式: 用布尔运算符号(and,or,not)作用到布尔变量或关系表达式上而组成。 布尔表达式的作用: 1. 用作计算逻辑值 2. 用作控制流语句如if-then,if-then-else和 while-do等之中的条件表达式 ◆一个布尔表达式的值的计算 方法一:用数值表示真和假,从而对布尔表达式的求值,可以象对算术表达式的求值那样一步一步地来计算 方法二:优化的方法。 A or B 解释成 if A then true else B A and B 解释成 if A then B else false not A 解释成 if A then false else true 7.4.1 数值表示法的翻译 (用作计算逻辑值) 用1表示真,0表示假来实现布尔表达式的翻译 例如,布尔表达式:a or b and not c 翻译成三地址代码序列: 100 : t1:=not c 101 : t2:=b and t1 102 : t3:=a or t1 or a and b c not 关系表达式: ab 等价于if ab then 1 else 0 翻译成三地址代码序列: 100 : if a<b goto l03 101 : t:=0 102 : goto l04 103 : t:=1 104: 关于布尔表达式的数值表示法的翻译模式 E→E1 or E2 {E.place:=newtemp; emit(E.place ‘:=‘ E1.place ‘or’ E2.place)} E→E1 and E2 {E.place:=newtemp; emit(E.place:=E1.placeand’ E2.place)} E→not E1 {E.place:=newtemp; emit(E.place:= not E1.place)} E→id1 relop id2 注: relop是关系运算符 { E.place:=newtemp; emit(if id1.place relop.op id2.place goto nextstat+3); emit(E.place:=0); emit(gotonextstat+2); emit(E.place:=‘ 1)} E→ture {E.place:=newtemp; emit(E.place:= 1)} E→false {E.place:=newtemp; emit(E.place:= 0)} ab 的翻译: 100 : if a<b goto
显示全部