1. 基本思路


目标词法
*实数是科学计数法的前缀

目标词法 *实数是科学计数法的前缀

我们要实现的最终目标:识别字符串 $s$ 中符合某种词法单元模式的所有词素

直接实现这个目标非常复杂,因此我们首先要将实现拆分为若干步:

Untitled

2. 具体实现


首先我们将词素分成从易到难的三类

  1. $\rm ws~if~else~id~int$

    Lookahead 1 char

  2. $\rm rel~op$

    Lookahead 2 chars

  3. $\rm real~sci$

    Lookahead $k$ chars. 在循环中持续匹配,直到可以判断

第一类:Lookahead 1 Character

空白符

空白符

标识符

标识符

整数

整数

识别字符串 $s$ 中符合某种词法单元模式的前缀词素。

合并三个 FA 中的状态 22, 12, 9 (初始状态),根据下一个字符即可判断词法单元的类型;否则, 调用错误处理模块 (对应 other), 报告该字符有误, 并忽略该字符。

<aside> 💡 Recognition of Reserved Words

There are two approaches to handling reserved words:

  1. Initialize the symbol table with the reserved words. The getToken function checks the symbol table entry for the found lexeme and returns the token name indicated by the symbol table.
  2. Create separate transition diagrams for each keyword. </aside>

第二类:Lookahead 2 Character