多个状态的词法分析

你可能会需要在你的词法分析器中添加多个状态,例如字符串中的状态和函数体中的状态。我们可以像这样切换状态:

import org.kiot.lexer.Lexer

val data = LexerData.build {
	// 默认的状态总是 0
	state(default) {
		": " action 1
		"\\w+" action 2
	}
	state(1) {
		".+" action 3
	}
}

class SimpleLexer(chars: CharSequence) : Lexer<Nothing>(data, chars) {
	override fun onAction(action: Int) {
		when (action) {
			1 -> switchState(1)
			2 -> println("word: ${string()}")
			3 -> println("definition: ${string()}")
		}
	}
}

lexer.lex("KiotLand: A land where Kotlin lovers gather.")

你可能认为用数字来代表词法分析器的状态并不是一个好想法。kiot-lexer 中提供了 LexerState 来解决这个问题:

import org.kiot.lexer.LexerState
import org.kiot.lexer.Lexer

enum class MyState : LexerState {
    DEFINITION
}

// ...

class SimpleLexer(chars: CharSequence) : Lexer<Nothing>(data, chars) {
	override fun onAction(action: Int) {
		when (action) {
			1 -> switchState(MyState.DEFINITION)
			2 -> println("word: ${string()}")
			3 -> println("definition: ${string()}")
		}
	}
}

Last updated

Was this helpful?