这是一个简单的项目,我的设计思路是原理算法分析、数据结构设计、状态机设计、方法函数详细设计、代码实现。

原理算法分析

单一字符分析 + 状态机切换
以解析 int age = 45 为例说明
这里我们有 4 种 Token : Int 定义 , 变量定义, 等于号, 数字 构建词法分析器 - 图1

数据结构设计

  • token类型

根据项目的目标我们的脚本解释器,主要功能是可以看做是一个简单的四则运算器。需要解析的 Token 如下定义

  1. type Type int
  2. const (
  3. Plus Type = iota // +
  4. Minus // -
  5. Star // *
  6. Slash // /
  7. SemiColon // ;
  8. LeftParen // (
  9. RightParen // )
  10. Assignment // =
  11. Int
  12. Identifier // 标识符
  13. IntLiteral // 整型字面量
  14. )
  • Token 接口 ```go type Token interface { Type() Type Value() string }

type BuildToken func(Type, string) Token


- TokenReader 接口
```go
type TokenReader interface {
    Read() Token
    Peek() Token
    UnRead()
    Position() int
    SetPosition(position int)
}

type BuildReader func([]Token) TokenReader
  • 状态机结构 ```go type Type int

const ( Initial Type = iota

Plus             // +
Minus             // -
Star              // *
Slash             // /

SemiColon  // ;
LeftParen  // (
RightParen // )
Assignment // =

Int 
IdInt1
IdInt2
IdInt3

Id  // 标识符
IntLiteral  // 字面量

)


- 其他  方便构造接口和方法
```go
// Tokens token存储数组
type Tokens []token

// lexer 词法解析器
type lexer struct {
    state state.Type // 存储当前解析状态

    tokens     []token.Token // 存储 Token 数组
    tokenValue string        // 存储临时 token

    rawScript string // 原始的脚本值
}

状态机设计

int 与 标识符判断

构建词法分析器 - 图2

数字字面量

构建词法分析器 - 图3

其他符号判断

构建词法分析器 - 图4

方法函数和结构体设计

下面每个方法都尽量保证功能的单一性。

辅助函数

  • IsNumber(c uint8) bool

判断字符是否为 0-9 之间的值

  • IsAlphabet(c uint8) bool

判断字符是否为 字母

SimpleToken

type SimpleToken struct {
    t     Type
    value string
}

实现了 Token 接口, 并提供 New函数方便构建此结构体

SimpleReader

type SimpleReader struct {
    position int
    tokens   []Token
}

实现了 TokenReader 接口, 并提供 New函数方便构建此结构体

lexer

type lexer struct {
    state state.Type // 存储当前解析状态

    tokens     []token.Token // 存储 Token 数组
    tokenValue string        // 存储临时 token

    rawScript string // 原始的脚本值

    readerBuilder token.BuildReader
    tokenBuilder  token.BuildToken
}

将 builder 再次提取出来, 将 lexer 和 simple结构解耦。实现 所有都是面向接口的编程。