开始

你需要首先在你的项目中导入 kiot-lexer:

allprojects {
	repositories {
		maven("https://jitpack.io")
	}
}

dependencies {
	implementation("com.github.KiotLand.kiot-lexer:kiot-lexer:1.0.6.1")
	// kiot-lexer-js and kiot-lexer-jvm are also alternatives.
}

完成!接下来让我们看看下面的示例:

import org.kiot.automaton.CharClass
import org.kiot.automaton.NFABuilder
import org.kiot.lexer.Lexer
import org.kiot.util.intListOf

// IntList 是 MutableList<Int> 的优化实现
val data = LexerData.buildSimple {
	NFABuilder.from(' ') action 1
	NFABuilder.from(CharClass.digit).oneOrMore() action 2
	NFABuilder.from(CharClass.letter).oneOrMore() action 3
}
// 上面的代码可能对你来说理解尚为困难... 但这能很快地带你熟悉 kiot-lexer
// 下面这段代码和上面的是等价的,只不过我们使用了正则表达式作为匹配串
/*
	val data = LexerData.buildSimple {
		" " action 1
		"\\d+" action 2
		"\\w+" action 3
	}
*/

// ... 现在我们来到了词法分析部分

class SimpleLexer(chars: CharSequence): Lexer<Int>(data, chars) {
	override fun onAction(action: Int) {
		returnValue(action)
	}
}

SimpleLexer("i have 2 ideas").lexAll()
// ret = [3, 1, 3, 1, 2, 1, 3]

SimpleLexer("!!").lex()
// Crashes: Mismatch in [0, 0]

正如你所看见的,在 kiot-lexer 中,词法分析器是通过 LexerData.buildSimpleLexerData.build 创建的。它们的不同在于 LexerData.buildSimple 只有一个默认的状态,而 LexerData.build 支持多个不同状态,详细信息将在 后面的文章 给出。

下面是 LexerData.buildSimple 的普遍使用方式:

LexerData.buildSimple {
    [匹配串] action []
    // [动作] 可以为 "ignore",届时这个匹配串会被词法分析器接受,但并不会激活任何动作
    // 以及更多这样的东西...
}

Last updated

Was this helpful?