Upload
austen-sutton
View
245
Download
3
Embed Size (px)
Citation preview
Chapter Syntax-Directed Translation
5.1 Attributes and attribute grammars5.1 Attributes and attribute grammars
5.2 Algorithms for attribute computation5.2 Algorithms for attribute computation
5.3 5.3 翻译模式翻译模式
55
● ● Purpose Purpose 目的目的compute compute additional informationadditional information needed for compilation needed for compilation that is beyond the capabilities of context-free grammars that is beyond the capabilities of context-free grammars and standard parsing algorithms;and standard parsing algorithms;
● ● Static semantic analysis Static semantic analysis 静态语义分析 静态语义分析
● ● Classification Classification 分类分类
analysis of a programanalysis of a program required by the rules of the program required by the rules of the programming language to establish its correctness and to guarantee prming language to establish its correctness and to guarantee proper execution;oper execution; analysis performed by a compileranalysis performed by a compiler to enhance the efficiency to enhance the efficiency of execution of the translated program of execution of the translated program
Take place Take place prior to executionprior to execution (Such as building a symbol (Such as building a symbol tabletable 、、 performing type inference and type checking) ;performing type inference and type checking) ;
5.1 Attributes and attribute grammars 5.1 Attributes and attribute grammars 属性和属性文法属性和属性文法
● ● Attributes Attributes 属性属性any propertyany property of of a programming language constructa programming language construct such as such as
The data type of a variableThe data type of a variable The value of an expressionThe value of an expression The location of a variable in memoryThe location of a variable in memory The object code of a procedureThe object code of a procedure The number of significant digits in a number The number of significant digits in a number 数的有数的有
效位数效位数
the time the time during the compilation/execution processduring the compilation/execution process when the when the binding of an attribute occurs. binding of an attribute occurs.
● ● Binding timeBinding time 联编时间联编时间
● ● Binding of the attribute Binding of the attribute 属性的联编属性的联编the process of the process of computing an attributecomputing an attribute and associating its and associating its computed value with the language construct in question. computed value with the language construct in question.
5.1 Attributes and attribute grammars 5.1 Attributes and attribute grammars 属性和属性文法属性和属性文法
● ● Static attributes / Dynamic attributes Static attributes / Dynamic attributes
Based on the difference of the binding time, attributes is Based on the difference of the binding time, attributes is divided into divided into Static attributesStatic attributes ( be bound ( be bound prior toprior to execution) execution) and and Dynamic attributesDynamic attributes (be bound (be bound duringduring execution). execution).
◆ ◆ type checker type checker 类型检查器 类型检查器 ◆◆ the values of expressionsthe values of expressions 表达式的值表达式的值 usually dynamic and the be computed during execution; but sometime cusually dynamic and the be computed during execution; but sometime c
an also be evaluated during compilation(constant folding an also be evaluated during compilation(constant folding 常量合并常量合并 ). ).
◆ ◆ The allocation of a variable The allocation of a variable 变量的分配变量的分配 either static or dynamiceither static or dynamic ,, sometimes it is a mixture of static and dynamsometimes it is a mixture of static and dynam
ic depending on the language and properties of the variable itself.ic depending on the language and properties of the variable itself.
◆ ◆ Object code of a procedureObject code of a procedure 程序的目标代码程序的目标代码 a static attribute, which is computed by the code generator.a static attribute, which is computed by the code generator.
◆ ◆ Number of significant digits in a numberNumber of significant digits in a number 数的有效位数数的有效位数 often not explicitly treated during compilation. often not explicitly treated during compilation.
● ● ExampleExample
5.1.1 Attribute grammars 5.1.1 Attribute grammars 属性文法属性文法
● ● syntax-directed semantics syntax-directed semantics 语法制导语义语法制导语义
X.aX.a means the value of a associated to X (X is a means the value of a associated to X (X is a grammar grammar symbolsymbol and a is an and a is an attributeattribute associated to X). associated to X).
attributes are associated directly with the grammar symbolattributes are associated directly with the grammar symbols of the language. Given a collection of attributes as of the language. Given a collection of attributes a11,…,a,…,akk, it , it
implies that for each grammar rule implies that for each grammar rule XX00XX11XX22…X…Xnn (X (X00 is a n is a n
onterminal), the values of the attributes onterminal), the values of the attributes XXii.a.ajj of each gram of each gram
mar symbol Xmar symbol Xii are related to the values of the attributes of are related to the values of the attributes of
the other symbols in the rule.the other symbols in the rule.
5.1.1 Attribute grammars 5.1.1 Attribute grammars 属性文法属性文法
An attribute grammar for attributes aAn attribute grammar for attributes a11, a, a
22, … , a, … , akk is the coll is the coll
ection of all attribute equations or semantic rules of the follection of all attribute equations or semantic rules of the following form, for all the grammar rules of the language.owing form, for all the grammar rules of the language.XXi.i.aajj = f = f
ijij(X(X00.a.a11,…,X,…,X
00.a.akk, …, X, …, X11.a.all, …, X, …, X
n-1n-1.a.a11, …X, …Xnn.a.akk))
Where fWhere fijij is a mathematical function of its arguments is a mathematical function of its arguments
● ● attribute equations or semantic rules attribute equations or semantic rules 属性等式或语义规则属性等式或语义规则
Grammar Rule Semantic RulesGrammar Rule Semantic Rules Rule 1 Associated attribute equationsRule 1 Associated attribute equations
.. .. .. .. Rule n Associated attribute equationsRule n Associated attribute equations
● ● attribute grammars attribute grammars 属性文法属性文法
1) 1) 已知无符号数文法如下,请改写成值属性文法,并对已知无符号数文法如下,请改写成值属性文法,并对 345345进行语义分析。进行语义分析。 number number number digit | digit number digit | digit
digit digit 0|1|2|3|4|5|6|7|8|9 0|1|2|3|4|5|6|7|8|9
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesnumbernumber11numbernumber22digitdigit numbernumber11.val = number.val = number22.val*10+digit.val.val*10+digit.val
number number digit number.val= digit.val digit number.val= digit.valdigit digit 0 digit.val = 0 0 digit.val = 0digit digit 1 digit.val = 1 1 digit.val = 1digit digit 2 digit.val = 2 2 digit.val = 2digit digit 3 digit.val = 3 3 digit.val = 3digit digit 4 digit.val = 4 4 digit.val = 4digit digit 5 digit.val = 5 5 digit.val = 5digit digit 6 digit.val = 6 6 digit.val = 6digit digit 7 digit.val = 7 7 digit.val = 7digit digit 8 digit.val = 8 8 digit.val = 8digit digit 9 digit.val = 9 9 digit.val = 9
解:解:
numbernumber(val=3*10+4=34)(val=3*10+4=34)
numbernumber(val=3)(val=3)
digitdigit(val=4)(val=4)
numbernumber(val=34*10+5=345)(val=34*10+5=345)
digitdigit(val=5)(val=5)
digitdigit(val=3)(val=3)
33
44
55
the parse tree showing attribute computations for the number 345the parse tree showing attribute computations for the number 345
2) 2) 已知简单的整数算术表达式文法如下,请改写成值属性文已知简单的整数算术表达式文法如下,请改写成值属性文法,并对 法,并对 (34-3)*42 (34-3)*42 进行语义分析。进行语义分析。exp exp exp + term | exp-term | term exp + term | exp-term | termterm term term*factor | factor term*factor | factorfactor factor (exp) | number (exp) | number
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesexpexp11 exp exp22+term exp+term exp11.val=exp.val=exp22.val+term.val.val+term.val
expexp11 exp exp22-term exp-term exp11.val=exp.val=exp22.val-erm.val.val-erm.val
exp exp term exp.val= term.val term exp.val= term.valtermterm11 term term22*factor *factor term term11.val=term.val=term22.val*factor.val .val*factor.val
term term factor term.val=factor.val factor term.val=factor.val factor factor (exp) factor.val=exp.val (exp) factor.val=exp.val factor factor number factor.val=number.val number factor.val=number.val
解:解:
termterm(val = 31) (val = 31)
factorfactor(val = 31)(val = 31)
))
termterm(val = 31*42=1302)(val = 31*42=1302)
factorfactor(val = 42) (val = 42)
expexp(val = 34-3=31) (val = 34-3=31)
--
((
numbernumber(val = 42)(val = 42)
the parse tree (34-3)*42 the parse tree (34-3)*42 expexp
(val = 1302)(val = 1302)
**
expexp(val = 34) (val = 34)
termterm(val = 34) (val = 34)
factorfactor(val = 34) (val = 34)
termterm(val = 3) (val = 3)
factorfactor(val =3) (val =3)
numbernumber(val = 3) (val = 3)
numbernumber(val = 34) (val = 34)
3) 3) 已知变量声明文法如下,请对已知变量声明文法如下,请对 float x, yfloat x, y 进行语义分析。进行语义分析。decl decl type var-list type var-listtypetypeint|floatint|floatvar-listvar-listid,var-list|id id,var-list|id
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesdecldecltype var-list var-list.dtype = type.dtypetype var-list var-list.dtype = type.dtypetypetypeint type.dtype = integerint type.dtype = integertypetype float type.dtype = real float type.dtype = realvar-listvar-list11id,var-listid,var-list2 2 id.dtype = var-list id.dtype = var-list11.dtype.dtype
var-listvar-list22.dtype= var-list.dtype= var-list11.dtype .dtype
var-listvar-listid id.dtype = var-list.dtypeid id.dtype = var-list.dtype
解:解:
typetype(dtype = real) (dtype = real)
float float idid(x)(x)
(dtype = real) (dtype = real)
decl decl
var-listvar-list(dtype = real) (dtype = real)
var-listvar-list(dtype = real) (dtype = real)
idid(y)(y)
(dtype = real) (dtype = real)
,,
the parse tree (float x,y)the parse tree (float x,y)
4) 4) 已知数文法如下,请对已知数文法如下,请对 345o345o 进行语义分析。进行语义分析。based-num based-num num basechar num basecharbasechar basechar o|d o|dnum num num digit | digit num digit | digit digit digit 0|1|2|3|4|5|6|7|8|9 0|1|2|3|4|5|6|7|8|9
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesbased-numbased-numnum basechar based-num.val = num.valnum basechar based-num.val = num.val num.base = basechar.basenum.base = basechar.basebasechar basechar o basechar.base = 8o basechar.base = 8basecharbasechar d basechar.base = 10 d basechar.base = 10numnum11numnum22 digit num digit num11.val =.val =
if if digit.val = error or numdigit.val = error or num22.val = error.val = error
then errorthen error else numelse num22.val*num.val*num11.base+digit.val.base+digit.val
numnum22.base = num.base = num11.base.base
digit.base = numdigit.base = num11.base.base
解:解:
4) 4) 已知数文法如下,请对已知数文法如下,请对 345o345o 进行语义分析。进行语义分析。based-num based-num num basechar num basecharbasechar basechar o|d o|dnum num num digit | digit num digit | digit digit digit 0|1|2|3|4|5|6|7|8|9 0|1|2|3|4|5|6|7|8|9
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesnum num digit num.val = digit.val digit num.val = digit.val digit.base = num.basedigit.base = num.basedigit digit 0 digit.val = 00 digit.val = 0digit digit 1 digit.val = 11 digit.val = 1… …… …digit digit 7 digit.val = 77 digit.val = 7digit digit 8 digit.val = if digit.base = 8 then error else 88 digit.val = if digit.base = 8 then error else 8digit digit 9 digit.val = if digit.base = 8 then error else 99 digit.val = if digit.base = 8 then error else 9
解:解:
numnum(val = 28*8+5=229) (base = 8)(val = 28*8+5=229) (base = 8)
numnum (val = 3*8+4=28)(base=8)(val = 3*8+4=28)(base=8)
digitdigit(val = 5) (base = 8) (val = 5) (base = 8)
based-numbased-num(val = 229) (val = 229)
basecharbasechar(base = 8) (base = 8)
numnum(val = 3)(base = 8) (val = 3)(base = 8)
33
55
oo
the parse tree showing attribute computations for the number the parse tree showing attribute computations for the number 345o345o
digitdigit(val = 4) (base = 8) (val = 4) (base = 8)
44digitdigit
(val = 3) (base = 8) (val = 3) (base = 8)
5.2 Algorithms for attribute computation 5.2 Algorithms for attribute computation 属性计算方法属性计算方法
5.2.1 dependency graphs and evaluation order5.2.1 dependency graphs and evaluation order 相关图和赋值顺序相关图和赋值顺序
dependency graphdependency graph of the string is the union of the dependency of the string is the union of the dependency graphs of the grammar rule choices representing each node(nographs of the grammar rule choices representing each node(nonleaf) of the parse tree of the string.nleaf) of the parse tree of the string.XXi.i.aajj = f = f
ijij(…, X(…, Xmm.a.akk, …), …)
An edge from each node XAn edge from each node Xmm.a.akk to X to X
i.i.aajj the node expressing the d the node expressing the d
ependency of Xependency of Xi.i.aajj on X on X
mm.a.akk..
1) 1) 已知无符号数属性文法,请画出属性等式及已知无符号数属性文法,请画出属性等式及 345345 的依赖图的依赖图。。
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesnumbernumber11numbernumber22digitdigit numbernumber11.val = number.val = number22.val*10+digit.val.val*10+digit.val
number number digit number.val= digit.val digit number.val= digit.val
解:属性等式解:属性等式 numbernumber11.val = number.val = number22.val*10+digit.val.val*10+digit.val
文法规则文法规则 numbernumber11numbernumber22digit digit 的依赖图:的依赖图:
numbernumber2 2 .val.val
numbernumber1 1 .val.val
digit.valdigit.val
属性等式属性等式 number.val = digit.valnumber.val = digit.val文法规则文法规则 numbernumberdigit digit 的依赖图:的依赖图:
numbernumber .val.val
digit.valdigit.val
字符串字符串 345345 对应的语法树的依赖图:对应的语法树的依赖图:
number.valnumber.val
number.valnumber.val digit.valdigit.val
number.valnumber.val
digit.valdigit.val
digit.valdigit.val
2) 2) 已知声明属性文法,请画出属性等式及已知声明属性文法,请画出属性等式及 float x,yfloat x,y 的依赖图。的依赖图。●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesdecldecltype var-list var-list.dtype = type.dtypetype var-list var-list.dtype = type.dtypetypetypeint type.dtype = integerint type.dtype = integertypetype float type.dtype = real float type.dtype = realvar-listvar-list11id,var-listid,var-list2 2 id.dtype = var-list id.dtype = var-list11.dtype.dtype
var-listvar-list22.dtype= var-list.dtype= var-list11.dtype .dtype
var-listvar-listid id.dtype = var-list.dtypeid id.dtype = var-list.dtype
解:属性等式解:属性等式 id.dtype = var-listid.dtype = var-list11.dtype.dtype
var-listvar-list22.dtype= var-list.dtype= var-list11.dtype.dtype
文法规则文法规则 var-listvar-list11id,var-listid,var-list22 的依赖图:的依赖图:
id.dtypeid.dtype
var-listvar-list11.dtype.dtype
var-listvar-list11.dtype.dtype
属性等式属性等式 id.dtype = var-list.dtypeid.dtype = var-list.dtype文法规则文法规则 var-listvar-listidid 的依赖图:的依赖图:
id.dtypeid.dtype
var-list.dtypevar-list.dtype
属性等式属性等式 var-list.dtype = type.dtypevar-list.dtype = type.dtype文法规则文法规则 decldecltype var-list type var-list 的依赖图:的依赖图:
type type dtypedtype
decl decl
dtypedtype var-list var-list
字符串字符串 float x,yfloat x,y 的依赖图:的依赖图:
type type dtypedtype
float float dtypedtype id id(x)(x)
decl decl
dtypedtype var-list var-list
dtypedtype var-list var-list
dtype dtype id id(y)(y)
,,
●● exampleexample 3) 3) 已知无符号数属性文法,请画出属性等式及已知无符号数属性文法,请画出属性等式及 345o345o 的依赖图。的依赖图。grammar rulegrammar rule semantic rulessemantic rulesbased-numbased-numnum basechar based-num.val = num. valnum basechar based-num.val = num. val num.base = basechar.basenum.base = basechar.basebasechar basechar o basechar.base = 8o basechar.base = 8basecharbasechar d basechar.base = 10 d basechar.base = 10numnum11numnum22 digit num digit num11.val =.val =
if if digit.val = error or numdigit.val = error or num22.val = error.val = error
then errorthen error else numelse num22.val*num.val*num11.base+digit.val.base+digit.val
numnum22.base = num.base = num11.base.base
digit.base = numdigit.base = num11.base.base
num num digit digit num.val = digit.valnum.val = digit.val digit.base = num.basedigit.base = num.basedigit digit 0 0 digit.val = 0digit.val = 0digit digit 1 1 digit.val = 1digit.val = 1… … … …digit digit 7 7 digit.val = 7digit.val = 7digit digit 8 8 digit.val = if digit.base = 8 then error else 8digit.val = if digit.base = 8 then error else 8digit digit 9 9 digit.val = if digit.base = 8 then error else 9digit.val = if digit.base = 8 then error else 9
解:属性等式解:属性等式 based-num.val = num.valbased-num.val = num.val num.base = basechar.basenum.base = basechar.base 文法规则文法规则 based-numbased-numnum basecharnum basechar 的依赖图:的依赖图:
basebase num num valval
based-num based-num valval
basechar basechar basebase
basebase num num valval
basebase num num valval basebase digit digit valval
属性等式属性等式 numnum11.val = if digit.val = error or num.val = if digit.val = error or num22.val = error.val = error
then errorthen error else numelse num22.val*num.val*num11.base+digit.val.base+digit.val
numnum22.base = num.base = num11.base.base
digit.base = numdigit.base = num11.base.base
文法规则文法规则 numnum11numnum22 digit digit 的依赖图:的依赖图:
basebase num num valval
basebase digit digit valval
属性等式属性等式 num.val = digit.valnum.val = digit.val digit.base = num.basedigit.base = num.base文法规则文法规则 numnumdigit digit 的依赖图:的依赖图:
basebase digit digit valval
99
属性等式属性等式 digit.val = if digit.base = 8 then error else 9digit.val = if digit.base = 8 then error else 9文法规则文法规则 digit digit 99 的依赖图:的依赖图:
basebase num num valval
basebase num num valval basebase digit digit valval
based-num based-num valval
basechar basechar basebase
basebase num num valval
33
55
oo
字符串字符串 345o345o 的依赖图:的依赖图:
basebase digit digit valval
44basebase digit digit valval
● ● topological sort topological sort 拓扑排序拓扑排序
● ● directed acyclic graphs. or dags directed acyclic graphs. or dags 确定非循环图确定非循环图 (( 有向无环图有向无环图 ))
4) 4) 已知依赖图是一个已知依赖图是一个 dag dag ,请计算其属性值。,请计算其属性值。●● exampleexample
basebase num num valval
basebase num num valval basebase digit digit valval
based-num based-num valval
basechar basechar basebase
basebase num num valval
33
55
oo
basebase digit digit valval
44basebase digit digit valval
1122
33
44
55 66
77 88 99
1010 1111 1212
1313
1414
5.2.2 Synthesized and inherited attributes 5.2.2 Synthesized and inherited attributes 综合和继承属性综合和继承属性
● ● Classification of the attributes Classification of the attributes 属性的分类属性的分类1. synthesized attributes 1. synthesized attributes 合成属性(综合属性)合成属性(综合属性)2. Inherited attributes 2. Inherited attributes 继承属性继承属性
An attribute is An attribute is synthesizedsynthesized if all its if all its dependencies pointdependencies point form form child to parentchild to parent in the parse tree. Equivalently, an attribute a in the parse tree. Equivalently, an attribute a is synthesized if, given a grammar ruleAis synthesized if, given a grammar ruleAXX11XX22… X… Xnn, the onl, the onl
y associated attribute equation with an a on the left-hand sidy associated attribute equation with an a on the left-hand side is of the form:e is of the form:A.a = f(XA.a = f(X11.a.a11,…X,…X11.a.akk,…X,…Xnn.a.a11,… X,… Xnn.a.akk))
● ● synthesized attributes synthesized attributes
An attribute grammar in which all the attributes are An attribute grammar in which all the attributes are synthesized is called an S-attributed grammar. synthesized is called an S-attributed grammar.
1) 1) 无符号数属性文法为无符号数属性文法为 SS 属性文法,其中属性文法,其中 valval 属性为综合属性属性为综合属性。。
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesnumbernumber11numbernumber22digitdigit numbernumber11.val = number.val = number22.val*10+digit.val.val*10+digit.val
number number digit number.val= digit.val digit number.val= digit.valdigit digit 0 digit.val = 0 0 digit.val = 0digit digit 1 digit.val = 1 1 digit.val = 1digit digit 2 digit.val = 2 2 digit.val = 2digit digit 3 digit.val = 3 3 digit.val = 3digit digit 4 digit.val = 4 4 digit.val = 4digit digit 5 digit.val = 5 5 digit.val = 5digit digit 6 digit.val = 6 6 digit.val = 6digit digit 7 digit.val = 7 7 digit.val = 7digit digit 8 digit.val = 8 8 digit.val = 8digit digit 9 digit.val = 9 9 digit.val = 9
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesexpexp11 exp exp22+term exp+term exp11.val=exp.val=exp22.val+term.val.val+term.val
expexp11 exp exp22-term exp-term exp11.val=exp.val=exp22.val-erm.val.val-erm.val
exp exp term exp.val= term.val term exp.val= term.valtermterm11 term term22*factor *factor term term11.val=term.val=term22.val*factor.val .val*factor.val
term term factor term.val=factor.val factor term.val=factor.val factor factor (exp) factor.val=exp.val (exp) factor.val=exp.val factor factor number factor.val=number.val number factor.val=number.val
2) 2) 简单的整数算术表达式属性文法为简单的整数算术表达式属性文法为 SS 属性文法,其中属性文法,其中 valval属性为综合属性。属性为综合属性。
The attribute values of an The attribute values of an S-attributed grammarS-attributed grammar can be can be computed by a signal computed by a signal bottom-upbottom-up, or , or post-orderpost-order, traversal , traversal of the parse or syntax tree. Just as follows:of the parse or syntax tree. Just as follows:
Procedure PostEval (T : treenode);Procedure PostEval (T : treenode);Begin Begin
For each child C of T doFor each child C of T doPostEval(C);PostEval(C);Compute all synthesized attributes of T;Compute all synthesized attributes of T;
EndEnd
◆◆ 综合综合属性值的计算属性值的计算
Typedef enum {Plus, Minus,Times} opkind;Typedef enum {Plus, Minus,Times} opkind;
Typedef enum {opkind, constkind} expkind;Typedef enum {opkind, constkind} expkind;
Typedef struct streenodeTypedef struct streenode
{ expkind kind;{ expkind kind;
opkind op;opkind op;
struct streenode *lchild, *rchild;struct streenode *lchild, *rchild;
int val;int val;
} Streenode;} Streenode;
typedef Streenode *Syntaxtree;typedef Streenode *Syntaxtree;
◆◆ The structure for a syntax treeThe structure for a syntax tree 语法树的结构语法树的结构
void postEval(Syntaxtree t)void postEval(Syntaxtree t){ int temp;{ int temp; if (t->kind == opkind)if (t->kind == opkind) { postEval(t->lchild);{ postEval(t->lchild); postEval(t_rchild);postEval(t_rchild);
switch (t->op)switch (t->op){ case Plus:{ case Plus:
t->val = t->lchild->val + t->rchild->val;t->val = t->lchild->val + t->rchild->val;break;break;
case Minus:case Minus:t->val = t->lchild->val - t->rchild->val;t->val = t->lchild->val - t->rchild->val;break;break;
case Times:case Times:t->val = t->lchild->val * t->rchild->val;t->val = t->lchild->val * t->rchild->val;break;break;
} } }}}}
◆◆ the PostEval pseudocode the PostEval pseudocode 后序属性赋值后序属性赋值
● ● inherited attributeinherited attribute
An attribute that is not synthesized is called an inherited An attribute that is not synthesized is called an inherited attribute. attribute.
● ● two basic kinds of dependency of inherited attributestwo basic kinds of dependency of inherited attributes
aa AA
aa aaBB CC
AA
aa aaBB CC
Inheritance form Inheritance form parent to siblings parent to siblings
inheritance from inheritance from sibling to sibling sibling to sibling
● ● sibling inheritance via sibling pointers sibling inheritance via sibling pointers 同属指针的同属继承同属指针的同属继承AA
aa aaBB CC
3) 3) 变量声明属性文法,其中变量声明属性文法,其中 dtypedtype 属性为继承属性。属性为继承属性。
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesdecldecltype var-list var-list.dtype = type.dtypetype var-list var-list.dtype = type.dtypetypetypeint type.dtype = integerint type.dtype = integertypetype float type.dtype = real float type.dtype = realvar-listvar-list11id,var-listid,var-list2 2 id.dtype = var-list id.dtype = var-list11.dtype.dtype
var-listvar-list22.dtype= var-list.dtype= var-list11.dtype .dtype
var-listvar-listid id.dtype = var-list.dtypeid id.dtype = var-list.dtype
Inherited attributesInherited attributes can be computed by a can be computed by a preorder preorder travetraversal , or rsal , or combined preorder/inordercombined preorder/inorder traversal of the parse traversal of the parse or syntax tree, represented by the following pseudocode:or syntax tree, represented by the following pseudocode:
Procedure PreEval(T: treenode);Procedure PreEval(T: treenode);BeginBegin
For each child C of T doFor each child C of T doCompute all inherited attributes of C;Compute all inherited attributes of C;PreEval(C);PreEval(C);
End;End;
◆◆ 继承继承属性值的计算属性值的计算
Procedure EvalType(T: treenode);Procedure EvalType(T: treenode);Begin Begin
Case nodekind of T ofCase nodekind of T ofDecl:Decl:
EvalType(type child of T);EvalType(type child of T);Assign dtype of type child of T to var-list child of T;Assign dtype of type child of T to var-list child of T;EvalType(var-list child of T);EvalType(var-list child of T);
Type:Type:If child of T = int then T.dtype := integerIf child of T = int then T.dtype := integerElse T.dtype :=real;Else T.dtype :=real;
Var-list:Var-list:Assign T.dtype to first child of T;Assign T.dtype to first child of T;If third child of T is not nil then If third child of T is not nil then
Assign T.dtype to third child;Assign T.dtype to third child;EvalType(third child of T);EvalType(third child of T);
End case;End case;End EvalType;End EvalType;
◆◆ dtypedtype 属性的递归程序属性的递归程序 In the procedure above, pIn the procedure above, preorder and inorder operareorder and inorder operations are mixed.tions are mixed.Inorder: decl nodeInorder: decl nodePreorder: var-list nodePreorder: var-list node
字符串字符串 float x,yfloat x,y 的依赖图:的依赖图:
type type dtypedtype
float float dtypedtype id id(x)(x)
decl decl
dtypedtype var-list var-list
dtypedtype var-list var-list
dtype dtype id id(y)(y)
,,
11 22
33 44
55
Typedef enum {decl, type,id} nodekind;Typedef enum {decl, type,id} nodekind;
Typedef enum {integer, real} typekind;Typedef enum {integer, real} typekind;
Typedef struct treenodeTypedef struct treenode
{nodekind kind;{nodekind kind;
struct treenode *lchild, *rchild , * sibling;struct treenode *lchild, *rchild , * sibling;
typekind dtype;typekind dtype;
char *name;char *name;
} *Syntaxtree;} *Syntaxtree;
◆◆ The syntax tree structure The syntax tree structure 语法树的结构(语法树的结构( CC 语言)语言)
float float idid
decl decl
idid
void evaltype (syntaxtree t)void evaltype (syntaxtree t){{ switch (t->kind)switch (t->kind)
{case decl:{case decl:t->rchild->dtype = t->lchild->dtypet->rchild->dtype = t->lchild->dtypeevaltype(t->rchild);evaltype(t->rchild);break;break;
case id:case id:if(t->sibling != NULL)if(t->sibling != NULL){{ t->sibling->dtype = t->dtype;t->sibling->dtype = t->dtype;
evaltype(t->sibling);evaltype(t->sibling);}}break;break;
}}}}
◆◆ The EvalType procedure The EvalType procedure (( CC 语言)语言)
void evaltype(syntaxtree t)void evaltype(syntaxtree t)
{{ if(t->kind = = decl)if(t->kind = = decl)
{{ syntaxtree p = t->rchild;syntaxtree p = t->rchild;
p->dtype = t->lchlild->dtype;p->dtype = t->lchlild->dtype;
while (p->sibling !=NULL)while (p->sibling !=NULL)
{ p->sibling->dtype = p->dtype;{ p->sibling->dtype = p->dtype;
p = p->sibling;p = p->sibling;
}}
}}
}}
◆◆ The EvalType nonrecursive procedure The EvalType nonrecursive procedure (( CC 语言)语言)
●● exampleexample 3)3) 无符号数属性文法,其中无符号数属性文法,其中 valval 属性为综合属性,属性为综合属性, basebase 为继承属性为继承属性。。 grammar rulegrammar rule semantic rulessemantic rules
based-numbased-numnum basechar based-num.val = num. valnum basechar based-num.val = num. val num.base = basechar.basenum.base = basechar.basebasechar basechar o basechar.base = 8o basechar.base = 8basecharbasechar d basechar.base = 10 d basechar.base = 10numnum11numnum22 digit num digit num11.val =.val =
if if digit.val = error or numdigit.val = error or num22.val = error.val = error
then errorthen error else numelse num22.val*num.val*num11.base+digit.val.base+digit.val
numnum22.base = num.base = num11.base.base
digit.base = numdigit.base = num11.base.base
num num digit digit num.val = digit.valnum.val = digit.val digit.base = num.basedigit.base = num.basedigit digit 0 0 digit.val = 0digit.val = 0digit digit 1 1 digit.val = 1digit.val = 1… … … …digit digit 7 7 digit.val = 7digit.val = 7digit digit 8 8 digit.val = if digit.base = 8 then error else 8digit.val = if digit.base = 8 then error else 8digit digit 9 9 digit.val = if digit.base = 8 then error else 9digit.val = if digit.base = 8 then error else 9
Procedure EvalWithBase(T: treenode);Procedure EvalWithBase(T: treenode);
BeginBegin
Case nodekind of T of Case nodekind of T of
Based-num:Based-num:
EvalWithBase(right child of T);EvalWithBase(right child of T);
Assign base of right child of T to base of left child;Assign base of right child of T to base of left child;
EvalWithBase (left child of T);EvalWithBase (left child of T);
Assign val of left child of T to T.val;Assign val of left child of T to T.val;
Num:Num:
Assign T.base to base of left child of T;Assign T.base to base of left child of T;
EvalWith Base(left child of T);EvalWith Base(left child of T);
◆◆ val , btypeval , btype 属性的计算程序属性的计算程序Base is computed in pBase is computed in preorder and val in posreorder and val in postorder during a single torder during a single pass as follows. pass as follows.
If right child of T is not nil thenIf right child of T is not nil thenAssign T.base to base of right child of T;Assign T.base to base of right child of T;EvalWithBase(right child of T);EvalWithBase(right child of T);If vals of left and right children != error thenIf vals of left and right children != error then T.val :=T.base*(val of left child)T.val :=T.base*(val of left child)
+val of right child+val of right childElse T.val := error;Else T.val := error;
Else T.val := val of left child;Else T.val := val of left child; Basechar:Basechar:
If child of T = o then T.base :=8;If child of T = o then T.base :=8;Else T.base :=10;Else T.base :=10;
Digit:Digit:If T.base=8 and child of T=8 or 9 then T.val := errorIf T.base=8 and child of T=8 or 9 then T.val := errorElse T.val :=numbal(child of T);Else T.val :=numbal(child of T);
End case;End case;End EvalWithBase;End EvalWithBase;
To compute all the attributes in a single pass over the To compute all the attributes in a single pass over the parse or syntax tree, the inherited attributes shouldn’t depend parse or syntax tree, the inherited attributes shouldn’t depend on any synthesized attributes, the synthesized attributes could on any synthesized attributes, the synthesized attributes could depend on the inherited attributes (as well as other synthesized depend on the inherited attributes (as well as other synthesized attributes).attributes).
◆◆
Procedure CombinedEval(T:treenode);Procedure CombinedEval(T:treenode);Begin Begin
For each child C of T doFor each child C of T doCompute all inherited attributes of C;Compute all inherited attributes of C;CombinedEval(C);CombinedEval(C);
Compute all synthesized attributes of T.Compute all synthesized attributes of T.End;End;
4) consider the following simple version of an expression gram4) consider the following simple version of an expression grammar: Expmar: Expexp/exp | num | num.num exp/exp | num | num.num
●● exampleexample
Operations may be interpreted differently depending on whOperations may be interpreted differently depending on whether they are floating-point or strictly integer operations. ether they are floating-point or strictly integer operations. For instance: 5/2/2.0 = 1.25 For instance: 5/2/2.0 = 1.25 5/2/2 = 15/2/2 = 1
the attributes needed to express the corresponding semantic:the attributes needed to express the corresponding semantic:1.1. isFloat : boolean, indicates if any part of an expression haisFloat : boolean, indicates if any part of an expression has a floating-point value (synthesized)s a floating-point value (synthesized)2.2. etype: gives the type of each subexpression and depends oetype: gives the type of each subexpression and depends on isFloat (inherited), here is int or floatn isFloat (inherited), here is int or float3.3. val : gives the numeric value of each subexpression , depeval : gives the numeric value of each subexpression , depends on etype.nds on etype.
grammar rulegrammar rule semantic rulessemantic rulesSSexp exp.etype = if exp.isFloat then float else intexp exp.etype = if exp.isFloat then float else int
S.val = exp.valS.val = exp.valExpExp11expexp22/exp/exp33 exp exp11.isFloat = exp.isFloat = exp22.isFloat or exp.isFloat or exp33.isFloat.isFloat
ExpExp22.etype = exp.etype = exp11.etype.etype
ExpExp33.etype = exp.etype = exp11.etype.etype
ExpExp11.val = .val =
if expif exp11.etype=int then exp.etype=int then exp22.val div exp.val div exp33.val.val
else expelse exp22.val / exp.val / exp33.val.val
expexpnumnum exp.isFloat = false exp.isFloat = false exp.val = exp.val = if exp.etype = int then num.val if exp.etype = int then num.val
else Float(num.val)else Float(num.val)expexpnum.num exp.isFloat = truenum.num exp.isFloat = true exp.val = num.num.valexp.val = num.num.val
5.2.3 Attributes as parameters and returned value5.2.3 Attributes as parameters and returned values s 作为参数和返回值的属性作为参数和返回值的属性
Many attributes are the same or are only used temporarily to Many attributes are the same or are only used temporarily to compute other attribute values, needn’t be stored as fields in compute other attribute values, needn’t be stored as fields in a syntax tree record structure.a syntax tree record structure.
inherited attributesinherited attributes: be computed in : be computed in preorderpreorder, often be treate, often be treated as d as parameters parameters of the call.of the call.Synthesized attributesSynthesized attributes: be computed in : be computed in postorderpostorder, often be tr, often be treated as eated as returned valuesreturned values of the call. of the call.
●● exampleexample
Function EvalWithBase(T: treenode; base:integer):integer;Function EvalWithBase(T: treenode; base:integer):integer;Var temp, temp2 : integer;Var temp, temp2 : integer;Begin Begin
Case nodekind of T ofCase nodekind of T ofBased-num:Based-num:
Temp := EvalWithBase(right child of T);Temp := EvalWithBase(right child of T);Return EvalWithBase(left child of T, temp);Return EvalWithBase(left child of T, temp);
Num:Num:Temp:= EvalWithBase(left child of T, base);Temp:= EvalWithBase(left child of T, base);If right child of T is not nil thenIf right child of T is not nil then Temp2 := EvalWithBase(right child of T, base);Temp2 := EvalWithBase(right child of T, base); If temp != error and temp2 !=error thenIf temp != error and temp2 !=error then
Return base*temp + temp2Return base*temp + temp2Else return error;Else return error;
Else return temp;Else return temp;
1) consider the recursive procedure EvalWithBase of example, 1) consider the recursive procedure EvalWithBase of example, we can turn we can turn basebase into a into a parameterparameter and and val val into a into a returned valreturned val. .
Basechar:Basechar:If child of T = o then retur 8If child of T = o then retur 8Else return 10;Else return 10;
Digit:Digit:If base = 8 and child of T = 8 or 9 then return errorIf base = 8 and child of T = 8 or 9 then return errorElse return numbal(child of T);Else return numbal(child of T);
End case;End case;End EvalWithBase;End EvalWithBase;
To start the computation, one would have to make a call such as To start the computation, one would have to make a call such as
EvalWithBase(rootnode, 0)EvalWithBase(rootnode, 0)
To distinguish three cases, it’s more national to write three separTo distinguish three cases, it’s more national to write three separate procedures as follows:ate procedures as follows:
Function EvalBasedNum(T: treenode) : integer;Function EvalBasedNum(T: treenode) : integer;(/*only called on root node */)(/*only called on root node */)begin begin
return EvalNum(left child of T, EvalBase(right child of T));return EvalNum(left child of T, EvalBase(right child of T));end ;end ; function EvalBase(T: treenode) : integer;function EvalBase(T: treenode) : integer;(/*only called on basechar node*/)(/*only called on basechar node*/)begin begin
if child of T = o then return 8if child of T = o then return 8else return 10;else return 10;
endend
function EvalNum(T:treenode; base: integer) : integer;function EvalNum(T:treenode; base: integer) : integer;var temp, temp2: integer;var temp, temp2: integer;begin begin
case nodekond of T ofcase nodekond of T ofNum:Num:
Temp:= EvalWithBase(left child of T, base);Temp:= EvalWithBase(left child of T, base);If right child of T is not nil thenIf right child of T is not nil then Temp2 := EvalWithBase(right child of T, base);Temp2 := EvalWithBase(right child of T, base); If temp != error and temp2 !=error thenIf temp != error and temp2 !=error then
Return base*temp + temp2Return base*temp + temp2 Else return error;Else return error;Else return temp;Else return temp;
Digit:Digit:If base = 8 and child of T = 8 or 9 then return errorIf base = 8 and child of T = 8 or 9 then return errorElse return numbal(child of T);Else return numbal(child of T);
End case;End case;End.End.
5.2.4 The use of external data structures to store attr5.2.4 The use of external data structures to store attributes values ibutes values 使用扩展数据结构存储属性值使用扩展数据结构存储属性值
● ● applicabilityapplicability
When not suitable to the method of parameters and returned When not suitable to the method of parameters and returned values( particularly when the attribute values have significant values( particularly when the attribute values have significant structure and may be needed at arbitrary points during structure and may be needed at arbitrary points during translation), and not reasonable to be stored in the syntax tree translation), and not reasonable to be stored in the syntax tree nodes. nodes. ● ● WaysWays
Use external data structures such as table, graphs and other Use external data structures such as table, graphs and other data structures to store the corresponding attribute values; (one data structures to store the corresponding attribute values; (one of the prime examples is the symbol table) of the prime examples is the symbol table) Replace attribute equations by calls to procedures representing Replace attribute equations by calls to procedures representing operations on the appropriate data structure used to maintain operations on the appropriate data structure used to maintain the attribute values.the attribute values.
1) EvalWithBase1) EvalWithBase
●● exampleexample
function EvaWithBase(T:treenode) : integer;function EvaWithBase(T:treenode) : integer;var temp, temp2: integer;var temp, temp2: integer;begin begin
case nodekond of T ofcase nodekond of T ofbased-num:based-num:
SetBase( right child of T);SetBase( right child of T);Return EvalWithBase(left child of T);Return EvalWithBase(left child of T);
Num:Num:Temp:= EvalWithBase(left child of T);Temp:= EvalWithBase(left child of T);If right child of T is not nil thenIf right child of T is not nil then Temp2 := EvalWithBase(right child of T);Temp2 := EvalWithBase(right child of T); If temp != error and temp2 !=error thenIf temp != error and temp2 !=error then
Return base*temp + temp2Return base*temp + temp2Else return error;Else return error;
Else return temp;Else return temp;
1) EvalWithBase1) EvalWithBase
●● exampleexample
Digit:Digit: If base=8 and child of T = 8 or 9 then return errorIf base=8 and child of T = 8 or 9 then return error Else return numval(child of T);Else return numval(child of T);End case;End case;
End.End. Procedure SetBase(T:treenode);Procedure SetBase(T:treenode);BeginBegin
If child of T = o then base :=8If child of T = o then base :=8Else base :=10Else base :=10
EndEnd
grammar rulegrammar rule semantic rulessemantic rulesbased-numbased-numnum basechar based-num.val = num.bvalnum basechar based-num.val = num.bvalbasechar basechar o base = 8o base = 8basecharbasechar d base = 10 d base = 10numnum11numnum22 digit num digit num11.val =.val =
if digit.val=error or numif digit.val=error or num22.val=error.val=error
then errorthen error else numelse num22.val* base+digit.val.val* base+digit.val
etc. etc.etc. etc.
2) consider the attribute grammar of simple declarations, treat 2) consider the attribute grammar of simple declarations, treat the dtype as a nonlocal variable, use symbol table to store the dthe dtype as a nonlocal variable, use symbol table to store the dtype values.type values.
●● exampleexample
grammar rulegrammar rule semantic rulessemantic rulesdecldecltype var-list type var-list typetypeint dtype = integerint dtype = integertypetype float dtype = real float dtype = realvar-list1var-list1id,var-list2 insert(id.name, dtype)id,var-list2 insert(id.name, dtype)var-listvar-listid insert(id.name, dtype)id insert(id.name, dtype)
procedure insert(name:string; dtype: typekind) is a functioprocedure insert(name:string; dtype: typekind) is a function which store the identifier name together with its declared n which store the identifier name together with its declared data type into the symbol table.data type into the symbol table.
●● exampleexample
The corresponding pseudocode for an attribute evaluation pThe corresponding pseudocode for an attribute evaluation procedure EvalType is as follows:rocedure EvalType is as follows:Procedure EvalType(T: treenode);Procedure EvalType(T: treenode);BeginBegin
Case nodekind of T ofCase nodekind of T ofDecl:Decl:
EvalType(type child of T)EvalType(type child of T)EvalType(var-list child of T)EvalType(var-list child of T)
Type:Type:If child of T = int then dtype := integer;If child of T = int then dtype := integer;Else dtype :=real;Else dtype :=real;
Var-list:Var-list:Insert (name of first child of T, dtype)Insert (name of first child of T, dtype)If third child of T is not nil thenIf third child of T is not nil then
EvalType(third child of T);EvalType(third child of T);End caseEnd caseEnd End
5.2.5 The computation of attributes during parsin5.2.5 The computation of attributes during parsing g 语法分析时属性的计算语法分析时属性的计算
● ● L-attributed L-L-attributed L- 属性属性
An attribute grammar for attribute aAn attribute grammar for attribute a11, …, a, …, akk is L-attributed i is L-attributed if , for each inherited attribute af , for each inherited attribute ajj and each grammar rule: and each grammar rule:
XX00 X X11XX22…X…Xnn
The associated equations for aj are all of the form:The associated equations for aj are all of the form:XXi.i.aajj = f = f
ijij(X(X00.a.a11,…,X,…,X
00.a.akk, …, X, …, X11.a.all, …, X, …, X
i-1i-1.a.a11, …X, …Xi-1i-1.a.akk))
That is , the value of aThat is , the value of ajj at X at Xii can only depend on attribute of t can only depend on attribute of the symbols Xhe symbols X00, … X, … Xi-1i-1 that occur to that occur to the left of Xthe left of Xii in the gram in the grammar rule.mar rule.
对于对于 A-> XA-> X11XX22…X…Xnn, Xj, Xj 的每个继承属性只依赖于左边的每个继承属性只依赖于左边符号的属性和符号的属性和 AA 的继承属性的继承属性
S-attributed grammar is L-attributed grammar.S-attributed grammar is L-attributed grammar.
表表 6.6 6.6 是否为是否为 L-L- 属性的语法制导定义?属性的语法制导定义?
产生式产生式 语义规则语义规则
ALM
A QR
L.i:=l(A.i)M.i:=m(L.s)A.s:=f(M.s)
R.i:=r(A.i)Q.i:=q(R.s)A.s:=f(Q.s)
解:解:表表 6.66.6 的语法制导定义不是的语法制导定义不是 L-L- 属性定义属性定义文法符号文法符号 QQ 的继承属性依赖于它右边文法符号的继承属性依赖于它右边文法符号 RR 的属性的属性
Given an L-attributed grammar in which the inherited Given an L-attributed grammar in which the inherited attributes do not depend on the synthesized attributes:attributes do not depend on the synthesized attributes:
Top-down parserTop-down parser: a recursive-descent parser can evaluate all : a recursive-descent parser can evaluate all the attributes by turning the inherited attributes into the attributes by turning the inherited attributes into parameters and synthesized attributes into returned values. parameters and synthesized attributes into returned values.
Bottom-up parserBottom-up parser: LR parsers are suited to handling : LR parsers are suited to handling primarily synthesized attributes, but are difficult for primarily synthesized attributes, but are difficult for inherited attributes.inherited attributes.
●● computing synthesized attributes during LR parsingcomputing synthesized attributes during LR parsing
1)1) exampleexample :: ambiguous grammar: ambiguous grammar: exp exp exp + exp|exp – exp|exp * exp|(exp)|number exp + exp|exp – exp|exp * exp|(exp)|number
grammar rulegrammar rule semantic rulessemantic rules
expexp11expexp22+exp+exp33 exp exp11.val=exp.val=exp22.val+exp.val+exp33.val.val
expexp11expexp22-exp-exp33 exp exp11.val=exp.val=exp22.val-exp.val-exp33.val.val
expexp11expexp22*exp*exp33 exp exp11.val=exp.val=exp22.val*exp.val*exp33.val.val
expexp11(exp(exp22) exp) exp11.val=exp.val=exp22.val .val
expexpnumber exp.val=number.valnumber exp.val=number.val
解:解:
●● computing synthesized attributes during LR parsingcomputing synthesized attributes during LR parsing解:解:
grammar rulegrammar rule semantic rulessemantic rules
expexp11expexp22+exp+exp33 exp exp11.val=exp.val=exp22.val+exp.val+exp33.val.val
expexp11expexp22-exp-exp33 exp exp11.val=exp.val=exp22.val-exp.val-exp33.val.val
expexp11expexp22*exp*exp33 exp exp11.val=exp.val=exp22.val*exp.val*exp33.val.val
expexp11(exp(exp22) exp) exp11.val=exp.val=exp22.val .val
expexpnumber exp.val=number.valnumber exp.val=number.val
Parsing stack input parsing action value stack semantic actionParsing stack input parsing action value stack semantic action11 $$ 3*4+5$3*4+5$ ShiftShift $ $ 22 $n$n *4+5$*4+5$ Reduce EReduce Enn $n$n E.val = n.valE.val = n.val33 $E$E *4+5$*4+5$ ShiftShift $3 $3 44 $E*$E* 4+5$4+5$ ShiftShift $3* $3* 55 $E*n$E*n +5$+5$ Reduce EReduce Enn $3*n$3*n E.val =n.valE.val =n.val66 $E*E$E*E +5$+5$ Reduce EReduce EE*EE*E $3*4$3*4 E1.val=E2.val*E3.val E1.val=E2.val*E3.val 77 $E$E +5$+5$ ShiftShift $12$12 88 $E+$E+ 5$5$ ShiftShift $12+ $12+ 99 $E+n$E+n $$ Reduce EReduce Enn $12+n$12+n E.val = n.valE.val = n.val1010 $E+E$E+E $$ Reduce EReduce EE+EE+E $12+5$12+5 E1.val=E2.val +E3.valE1.val=E2.val +E3.val1111 $E$E $$ $17$17
5.2.6 The dependence of attributes computation o5.2.6 The dependence of attributes computation on the syntax n the syntax 语法中属性计算的相关性语法中属性计算的相关性
●● TheoremTheorem
(from Knuth [1968]). Given an attribute grammar , all (from Knuth [1968]). Given an attribute grammar , all
inherited attributed attributes can be changed into synthesinherited attributed attributes can be changed into synthes
ized attributes by suitable modification of the grammar, wized attributes by suitable modification of the grammar, w
ithout changing the language of the grammar.ithout changing the language of the grammar.
给定一个属性文法,通过适当地修改文法,而无须改给定一个属性文法,通过适当地修改文法,而无须改变文法的语言,所有的继承属性可以改变成合成属性。变文法的语言,所有的继承属性可以改变成合成属性。
5.35.3 翻译模式翻译模式
翻译模式是语法制导定义的一种便于翻译的书写形式。翻译模式是语法制导定义的一种便于翻译的书写形式。其中属性与文法符号相对应,其中属性与文法符号相对应,语义规则语义规则或或语义动作语义动作用花括号用花括号{ }括起来,可被插入到产生式右部的任何合适的位置上。{ }括起来,可被插入到产生式右部的任何合适的位置上。
这是一种语法分析和语义动作交错的表示法,它表达在这是一种语法分析和语义动作交错的表示法,它表达在按按深度优先遍历深度优先遍历分析树的过程中何时执行语义动作。分析树的过程中何时执行语义动作。
翻译模式给出了使用语义规则进行计算的顺序。可看成翻译模式给出了使用语义规则进行计算的顺序。可看成是分析过程中翻译的注释。是分析过程中翻译的注释。
例:一个简单的翻译模式例:一个简单的翻译模式 , 9-5+2, 9-5+2 的结果。的结果。 E→TR R→addop T {print(addop.lexeme)} R1|ε T→num {print(num.val)}
EE
TT
99 TTPt(´9´)Pt(´9´) RRPt(´-´)Pt(´-´)
Pt(´+´)Pt(´+´)
RR
--
55 Pt(´5´)Pt(´5´) ++ TT
22 Pt(´2´)Pt(´2´)
RR
图: 图: 9-5+29-5+2 的带语义动作的分析树的带语义动作的分析树E→TR R→addop T {print(addop.lexeme)}R1|ε T→num {print(num.val)}
深度优先遍历输出: 9 5 - 2 +输入表达式 9-5+2 的后缀式。
1. 1. 只需要综合属性的情况:只需要综合属性的情况:
为每一个语义规则建立一个包含赋值的动作,并把这个动作放在相应的产生式右边右边的末尾末尾。
解: TT1*F {Tval:=T1 val*F val}
● ● 设计翻译模式设计翻译模式
条件:语法制导定义是条件:语法制导定义是 L-L- 属性定义属性定义 保证语义动作不会引用还没有计算的属性值。保证语义动作不会引用还没有计算的属性值。
例:语法和语义规则如下,请写出其翻译模式: TT1*F Tval:=T1 val*F val
2. 2. 既有综合属性又有继承属性既有综合属性又有继承属性
● ● 产生式产生式右边右边的符号的的符号的继承继承属性必须在这个符号属性必须在这个符号以前以前的动作中计算出来。的动作中计算出来。
● ● 一个动作一个动作不能引用不能引用这个动作这个动作右边右边符号的符号的综合综合属性。属性。
● ● 产生式产生式左边左边非终结符号的非终结符号的综合综合属性只有在它所引用的所有属性都计算属性只有在它所引用的所有属性都计算出来以后才能计算。计算这种属性的动作通常可放在出来以后才能计算。计算这种属性的动作通常可放在产生式右端的未产生式右端的未尾尾。。
● ● 设计翻译模式设计翻译模式
例:
E→T {Ri:=T val} R { E val:=R s }
例:语法和语义规则如下: E→TR Ri:=T val E val:=R s 其翻译模式: E→T {Ri:=T val} R { E val:=R s }
例例 : : 带左递归的文法的翻译模式构造方法带左递归的文法的翻译模式构造方法
(( 对于一个翻译模式,若采用自顶向下分析,必须消除左递归必须消除左递归和提取左公因子提取左公因子,在改写基本文法时考虑属性值的计算。 )
产生式 语义规则E E EE11+T E +T E val := Eval := E11 val+T val+T val val
E E T E T E val := T val := T val val
T T TT11*F T *F T val := Tval := T11 val*F val*F val val
T T F T F T val := F val := F val val
F F (E) F (E) F val := Eval := E val val
F F digit F digit F val := digitval := digitlexvallexval
●● exampleexample
E E1+T { E val:=E1val+T val}
E E1-T { E val:=E1 val-T val }
E T {E.val:=T val}
T (E) { T val:=E val }
T num { T val:=num val}
● ● 带左递归的文法的翻译模式带左递归的文法的翻译模式
● ● 经过转换的带有右递归文法的翻译模式经过转换的带有右递归文法的翻译模式
E→T {Ri:=T val} R { E val:=R s } R→ + T { R1i:=R.i+T. val} R1 { R. s:=R1 s} R→- T { R1 i:=R i-Tval} R1 { R s:=R1 s} R→ε { R s:=R i} T→ ( E ) { T val:=E.val} T→num {T val:=num val}
EEEE11+T +T
E E E E11-T -T
E E T T T T (E) (E) T T num num
E E TR TRRR(+T|-T)R| ε(+T|-T)R| εT T (E) (E) T T num num
● ● 产生式产生式右边右边的符号的的符号的继承继承属性必须在这个符号属性必须在这个符号以前以前的动作中计算出来。的动作中计算出来。● ● 一个动作一个动作不能引用不能引用这个动作这个动作右边右边符号的符号的综合综合属性。属性。● ● 产生式产生式左边左边非终结符号的非终结符号的综合综合属性只有在它所引用的所有属性都计算出来属性只有在它所引用的所有属性都计算出来以后才能计算。计算这种属性的动作通常可放在以后才能计算。计算这种属性的动作通常可放在产生式右端的未尾产生式右端的未尾。。
E val=6
Tval=9
R i=9; R s= 6
9– T val=
5
5
R i=4; R s= 6
+ T val=2
R i=6; R s= 62
表达式表达式 9-5+29-5+2 的计算的计算 E→T {RE→T {Ri:=T i:=T val} val} R{E R{E val:=R val:=R s} s} R→+T{RR→+T{R11i:=R.i+T. i:=R.i+T. vv
al} al} RR11{R. {R. s:=Rs:=R11 s} s}
R→-T{RR→-T{R11 i:=R i:=R i-T i-Tvv
al} al} RR11{R {R s:=Rs:=R11 s} s}
R→εR→ε {{ R R s:=R s:=R i} i} T→(E){T T→(E){T val:=E.val:=E.val} val} T→T→num {Tnum {Tval:=num val:=num val} val}
Tval=9
R i=9
T val=5 R i=4
T val=2 R i=6R s= 6
R s= 6
R s= 6
E val=6
◆ 关于左递归翻译模式更一般化的讨论•左递归翻译模式 A→A1Y { A.a:=g(A1.a,Y.y)} A→X { A.a:=f(X.x)} ( 5.2 )
每一个文法符号都有一个综合属性,用相应的小写字母表示, g 和 f 是任意函数。
•消除左递归,文法转换成 A→X R R→Y R|ε ( 5.3 ) •再考虑语义动作,翻译模式变为: A→X { Ri:=f(X x)} R { A. a:=R. s} R→Y { R1 i:=g ( R i,Y y ) } R1 { R s:=R1 s} R→ε { R s:=R i} ( 5.4 ) 经过转换的翻译模式,使用 R 的继承属性 i 和综合属性 s 。
Chapter Syntax-Directed Translation
5.1 Attributes and attribute grammars5.1 Attributes and attribute grammars
5.2 Algorithms for attribute computation5.2 Algorithms for attribute computation
5.3 5.3 翻译模式翻译模式
55
ENDEND
Class ProblemClass ProblemClassify each error as lexical, syntax, or semantic?Classify each error as lexical, syntax, or semantic?
int a;int a;a = 1.0;a = 1.0;
int a; bint a; bb = a;b = a;
{ int a;{ int a; a = 1;a = 1;}}{ a = 2;{ a = 2;}}
in a;in a;a = 1;a = 1;
int foo(int a)int foo(int a){{ foo = 3;foo = 3;}}