คิดว่าจะสนุกถ้าหยุด practical content พักคราว โชว์ Ruby party trick หน่อย
ก่อน Ruby รันโปรแกรม ต้อง parse ก่อน Parser เป็น state machine และมี command line flag น้อยคนรู้ ให้ Ruby log ทุกอย่างที่ state machine ทำ
ตัวอย่าง:
a = 1 + 2
รันด้วย flag -y ได้ output:
$ ruby -y sample.rb
Starting parse
Entering state 0
Reducing stack by rule 1 (line 903):
-> $$ = nterm $@1 ()
Stack now 0
Entering state 2
Reading a token:
Next token is token tIDENTIFIER ()
Shifting token tIDENTIFIER ()
Entering state 35
Reading a token:
Next token is token '=' ()
Reducing stack by rule 509 (line 4417):
$1 = token tIDENTIFIER ()
-> $$ = nterm user_variable ()
Stack now 0 2
Entering state 113
Next token is token '=' ()
Reducing stack by rule 100 (line 1764):
$1 = nterm user_variable ()
-> $$ = nterm lhs ()
Stack now 0 2
... 140 more lines
สิ่งที่เห็น: Ruby parser cycle แต่ละ token ในไฟล์ ทำ operations:
- เพิ่ม token เข้า stack
- เปรียบเทียบ stack กับ rule list
- ถ้า token match rule ทำ state transition
- ถ้าไม่ match เพิ่ม token อีกตัวเข้า stack ลองใหม่
States และ rules ทั้งหมด defined ใน parse.y ไฟล์ที่ bison parser generator process เพื่อ generate parser จริงใน C