-
Notifications
You must be signed in to change notification settings - Fork 3
/
StateMachineLexerImpl.kt
65 lines (56 loc) · 2.35 KB
/
StateMachineLexerImpl.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package dev.vinayshetty.stateart.lexer
import dev.vinayshetty.stateart.datastructure.StateMachine
class StateMachineLexerImpl(private val stateMachineTokenizer: StateMachineTokenizer) : StateMachineLexer {
private companion object {
private val stateMatcherRegex = ".*state(\\<|\\()(.*?)(\\>|\\)).*".toRegex()
private val eventMatcherRegex = ".*\\s+on(\\<|\\()(.*?)(\\>|\\)).*".toRegex()
private val transitionToMatcherRegex = ".*transitionTo\\((.*?)(,|\\)).*".toRegex()
private val doNotTransitionMatcherRegex = ".*dontTransition\\((.*?)\\).*".toRegex()
}
override fun lex(stateMachineString: String): StateMachine {
stateMachineString.split("\n").forEach { lexLine(it) }
return stateMachineTokenizer.stateMachine()
}
private fun lexLine(line: String) {
if (line.matches(stateMatcherRegex)) {
val matchResult = stateMatcherRegex.find(line)
matchResult?.let {
val (_, state, _) = it.destructured
val shortName = shortenName(state)
stateMachineTokenizer.state(shortName)
}
}
if (line.matches(doNotTransitionMatcherRegex)) {
val matchResult = doNotTransitionMatcherRegex.find(line)
matchResult?.let {
stateMachineTokenizer.doNotTransition()
}
}
if (line.matches(eventMatcherRegex)) {
val matchResult = eventMatcherRegex.find(line)
matchResult?.let {
val (_, event, _) = it.destructured
val shortName = shortenName(event)
stateMachineTokenizer.event(shortName)
}
}
if (line.matches(transitionToMatcherRegex)) {
val matchResult = transitionToMatcherRegex.find(line)
matchResult?.let {
val (toState) = it.destructured
val shortName = shortenName(toState)
stateMachineTokenizer.transition(shortName)
}
}
}
private fun shortenName(name: String): String {
return when {
name.contains("(") -> {
val nameWithoutBraces = name.split("(").first()
return nameWithoutBraces.split(".").last()
}
name.contains(".") -> return name.split(".").last()
else -> name
}
}
}