Tiny语言编译器开发之词法分析

本文详细解析了Tiny语言编写的样例程序,通过词法分析过程,逐行解析并标记程序的关键字、标识符及数字,展示了如何使用DFA进行词法分析,最终实现对程序源代码的正确理解与执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  对于Tiny语言编写的Sample程序源代码如下:

{ 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

 

词法分析采用手工构造DFA的方式进行,词法分析主要为后面的各个阶段提供方法getToken;

经过词法分析后每行的关键字、标识符以及数字如下:

   1: { Sample program
   2:   in TINY language -
   3:   computes factorial
   4: }
   5: read x; { input an integer }
        5: reserved word: read
        5: ID, name=x
        5: ;
   6: if 0 < x then { don't compute if x <= 0 }
        6: reserved word: if
        6: NUM, val= 0
        6: <
        6: ID, name=x
        6: reserved word: then
   7:   fact := 1;
        7: ID, name=fact
        7: :=
        7: NUM, val= 1
        7: ;
   8:   repeat
        8: reserved word: repeat
   9:     fact := fact * x;
        9: ID, name=fact
        9: :=
        9: ID, name=fact
        9: *
        9: ID, name=x
        9: ;
  10:     x := x - 1
        10: ID, name=x
        10: :=
        10: ID, name=x
        10: -
        10: NUM, val= 1
  11:   until x = 0;
        11: reserved word: until
        11: ID, name=x
        11: =
        11: NUM, val= 0
        11: ;
  12:   write fact  { output factorial of x }
        12: reserved word: write
        12: ID, name=fact
  13: end
        13: reserved word: end
        14: EOF

 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值