編譯原理:TINY語言的語法、詞法單元與文法的最全總結

下面是一段YINY語言源代碼:

{ Sample program
  in TINY language -
  computes factorial
}
read x; { input an integer }
if 0 < x then { don't compute if x <= 0 }
  fact := 1;
  repeat
    fact := fact * x;
    x := x - 1
  until x = 0;
  write fact  { output factorial of x }
end

在學習編譯原理時,由於網上沒有對TINY詞法與文法的總結,這一塊自己摸索很久。現在分享給大家,這裏是喬卿的博客。下面對TINY語言的語法、詞法單元與文法進行總結,涉及到編譯原理中的詞法分析、語法分析。

TINY語言的語法爲:

  1. 註釋:放在一對大括號內,不能嵌套;
  2. 關鍵字:read write if end repeat until else;
  3. 類型:只支持整型和布爾型;
  4. 運算符:+ - * / ( ) < = :=,其中:=爲賦值運算,=爲判斷。沒有>和<=和>=。

TINY的詞法單元爲:

詞法單元類型

詞法單元

詞素(例)

關鍵字

(預定義符)

IF

if

THEN

then

ELSE

else

END

end

REPEAT

repeat

UNTIL

until

READ

read

WRITE

write

自定義符

ID

myName

NUM

123

運算符

ASSIGN

:=

EQ

=

LT

<

PLUS

+

MINUS

-

TIMES

*

OVER

/

LPAREN

(

RPAREN

)

SEMI

;

錯誤

ERROR

>=

TINY的文法爲:

非終結符

含義

展開

program

程序

stmt_seq

stmt_seq

若干條語句

stmt_seq SEMI stmt | stmt

stmt

單條語句

if_stmt | repeat_stmt | assign_stmt | read_stmt | write_stmt | error

if_stmt

判斷語句

IF exp THEN stmt_seq END | IF exp THEN stmt_seq ELSE stmt_seq END

repeat_stmt

循環語句

REPEAT stmt_seq UNTIL exp

assign_stmt

賦值語句

ID ASSIGN exp

read_stmt

輸入語句

READ ID

write_stmt

輸出語句

WRITE exp

exp

判斷表達式

simple_exp LT simple_exp | simple_exp EQ simple_exp| simple_exp

simple_exp

加減表達式

simple_exp PLUS term | simple_exp MINUS term | term

term

乘除表達式

term TIMES factor | term OVER factor | factor

factor

括號表達式

LPAREN exp RPAREN | NUM | ID | error

即:

program->stmt_seq
stmt_seq->stmt_seq;stmt
stmt_seq->stmt
stmt->if_stmt
stmt->repeat_stmt
stmt->assign_stmt
stmt->read_stmt
stmt->write_stmt
stmt->error
if_stmt->IF exp THEN stmt_seq END
if_stmt->IF exp THEN stmt_seq ELSE stmt_seq END
repeat_stmt->REPEAT stmt_seq UNTIL exp
assign_stmt->ID:=exp
read_stmt->READ ID
write_stmt->WRITE exp
exp->simple_exp<simple_exp
exp->simple_exp=simple_exp
simple_exp->simple_exp+term
simple_exp->simple_exp-term
term->term*factor
term->term/factor
factor->(exp)
factor->NUM
factor->ID
factor->error

如果這篇文章對你有幫助,請給博主點個贊吧!

版權聲明:本文爲博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/qq_41112170/article/details/106880776
本文作者:喬卿

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章