C-
C MINUS是C语言的一个子集,该语言的语法在《编译原理与实践》第九章附录中有详细的介绍。
Lexical Conventions
- 关键字
else if int return void while - 专用符号
+ - * / < <= > >= == != = ; , ( ) [ ] { } /* */ -
标识符ID和整数NUM,通过下列正则表达式定义:
ID=letter letter*
NUM=digit digit*
letter = a|...|z|A|...|Z
digit = 0|...|9 - 注释用
/*...*/表示,可以超过一行。注释不能嵌套。
/*...*/
思考
- 识别C-语言Token的DFA设计
- note that: [, ], 和 [] 是三种不同的tokens。[]用于声明数组类型,[]中间不得有空格。
Syntax
- program → declaration-list
-
declaration-list → declaration-list declaration declaration -
declaration → var-declaration fun-declaration -
var-declaration → type-specifier ID;type-specifier ID[NUM]; -
type-specifier → intvoid - fun-declaration → type-specifier
ID(params)compound-stmt -
params → param-list void -
param-list→ param-list , param param -
param → type-specifier IDtype-specifier ID[] - compound-stmt →
{local-declarations statement-list} -
local-declarations → local-declarations var-declaration empty -
statement-list → statement-list statement empty -
statement → expression-stmt compound-stmt selection-stmt iteration-stmt return-stmt -
expression-stmt → expression ; ; -
selection-stmt → if(expression)statementif(expression)statementelsestatement - iteration-stmt →
while(expression)statement -
return-stmt → return;returnexpression ; -
expression → var =expressionsimple-expression -
var → IDID[expression] -
simple-expression → additive-expression relop additive- expression additive-expression -
relop → <=<>>===!= -
additive-expression → additive-expression addop term term -
addop → +- -
term → term mulop factor factor -
mulop → */ -
factor → (expression)var call NUM - call →
ID(args) -
args → arg-list empty -
arg-list → arg-list , expression expression
思考:
- C-语言语法的特点,它的CFG
Sample Programs of C-
int gcd (int u, int v) { /* calculate the gcd of u and v */
if (v == 0) return u;
else return gcd(v, u - u / v * v); /* v,u-u/v*v is equals to u mod v*/
}
int main() {
int x; int y; int temp;
x = 72;
y = 18;
if (x<y) {
temp = x;
x = y;
y = temp;
}
gcd(x,y);
return 0;
}