### 习题课三--作业题和实验问题讲解

```作业和实验问题讲解

%left + *
exp->// 设立原表达式属性str，求导后dstr
exp * exp \$\$.str=\$1.str*\$2.str ; \$\$.dstr=(\$1.dstr)*\$2.str+\$2.dstr*\$1.str ;
exp + exp \$\$.str=\$1.str+\$2.str ;\$\$.dstr=\$1.dstr+\$2.dstr;
X
\$\$.str=x;\$\$.dstr=1;
Num
\$\$.str=num;\$\$.dstr=0;
( exp )
\$\$.str=(\$1.str);\$\$.dstr=(\$1.dstr);

%left +
%right =
S->E
E->
E =E \$\$.isl=0;if(\$1.isl==0) {printf(“error”);exit(0);}
E+E \$\$.isl=0;
(E) \$\$.isl=\$2.isl;
Id
\$\$.isl=1;

a.声明了多少个id b.翻译方案，嵌套深度
(b)%left ;

D->D;D
D->Id:T printf(“%s,%d”,\$1,depth);
D->
{depth++;}
Proc id;D;S
{depth--;}

a.声明了多少个id b.翻译方案，嵌套深度
(b)%left ; //设定属性值整型dep
D->{\$2.dep=\$4.dep=\$\$.dep;}D;D
D->Id:T printf(“%s,%d”,\$1,\$\$.dep);
D->
{\$5.dep=\$\$.dep+1;}
Proc id;D;S

D(node p)
{T(p->T);p->L->in=p->T->type;L(p->L);}
L (node p)
{if(p->kind==1)
}

1.不要太担心文档，也不要太不担心文档好坏：文档写的

2.细心很重要，也许你拓展的很好，可是老师基本的对程

Mid-rule
1.中间规则的行为用到的\$n,只能涉及行为之前的符号，故\$\$不能用
2.中间规则行为看作一个符号，用\$<…>n给予属性
3. -Wmidrule-value ：the midrule-value warnings are enabled
stmt:
"let" '(' var ')'
{
\$<context>let = push_context ();
declare_variable (\$3);
}[let]
initistmtates error
stmt
recovery in ，
{
need a ？？
\$\$ = \$6;
pop_context (\$<context>let);
}
%type <context> let
%destructor { pop_context (\$\$); } let
%%
stmt:
let stmt
{
\$\$ = \$2;
pop_context (\$let);
};
let:
"let" '(' var ')'
{
\$let = push_context ();
declare_variable (\$3);
};
compound:
‘{’ declarations statements ‘}’
| ‘{’ statements ‘}’
;

compound:
{ prepare_for_local_variables (); }
'{' declarations statements '}'
| '{' statements '}'

compound:
{ prepare_for_local_variables (); }
‘{’ declarations statements ‘}’
| { prepare_for_local_variables (); }
‘{’ statements ‘}’;

compound:
‘{’ { prepare_for_local_variables (); }
declarations statements ‘}’
| ‘{’ statements ‘}’;

subroutine:
%empty { prepare_for_local_variables (); };
compound:
subroutine '{' declarations statements '}'
| subroutine '{' statements '}'
;

Bison用自下而上的方法分析，对于没有归约的符号，

Bison的定位方法

@n，表示第n个的符号的位置信息

1.你能用YYLTYPE的宏来定义自己的location类型，如果不指

typedef struct YYLTYPE
{
int first_line;
int first_column;
int last_line;
int last_column;
} YYLTYPE;
Location的计算
YYLLOC_DEFAULT定义了每次一个规则被匹配时的处理location信息的步骤，默认的
# define YYLLOC_DEFAULT(Cur, Rhs, N)
\
do
\
if (N)
\
{
\
(Cur).first_line = YYRHSLOC(Rhs, 1).first_line; \
(Cur).first_column = YYRHSLOC(Rhs, 1).first_column; \
(Cur).last_line = YYRHSLOC(Rhs, N).last_line; \
(Cur).last_column = YYRHSLOC(Rhs, N).last_column; \
}
\
else
\
{
\
(Cur).first_line = (Cur).last_line =
\
YYRHSLOC(Rhs, 0).last_line;
\
(Cur).first_column = (Cur).last_column =
\
YYRHSLOC(Rhs, 0).last_column;
\
}
\
while (0)

That is all！
```