Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Last active July 30, 2019 19:43
Show Gist options
  • Select an option

  • Save thomasnield/92e4fb26f8dd63141a9fea03e17e8bc1 to your computer and use it in GitHub Desktop.

Select an option

Save thomasnield/92e4fb26f8dd63141a9fea03e17e8bc1 to your computer and use it in GitHub Desktop.
Simple Language Interpreter
fun main() {
val testCode = """
x = 3
print(x)
"""
val program = compile(testCode)
program.execute()
}
fun compile(code: String): CompiledProgram {
val compiledProgram = CompiledProgram()
code.lineSequence()
.filter { it.isNotBlank() }
.map { it.trim() }
.forEach { line ->
compiledProgram.instructions += Token.values().first { it.pattern.matches(line) }.compileFunction(line, compiledProgram)
}
return compiledProgram
}
class CompiledProgram {
val variables = mutableMapOf<String,Int>()
val instructions = mutableListOf<() -> Unit>()
fun execute() {
instructions.forEach { it() }
}
}
enum class Token(val pattern: Regex) {
VARIABLE_ASSIGN(Regex("[a-z][0-9a-z]* = [0-9]+")) {
val extractVariableName = Regex("[a-z][0-9a-z]*(?= =[0-9]+)")
val extractVariableValue = Regex("(?<== )[0-9]+")
override fun compileFunction(subCode: String, compiledProgram: CompiledProgram): () -> Unit {
return {
val variableName = extractVariableName.find(subCode)?.value!!
val variableValue = extractVariableValue.find(subCode)?.value!!.toInt()
compiledProgram.variables[variableName] = variableValue
}
}
},
PRINT(Regex("print\\([0-9a-z]+\\)")) {
val extractPrintStr = Regex("(?<=print\\()[0-9a-z]+(?=\\))")
override fun compileFunction(subCode: String, compiledProgram: CompiledProgram): () -> Unit {
return { println(extractPrintStr.find(subCode)?.value) }
}
},
VARIABLE_GET(Regex("[a-z][0-9a-z]*")) {
}
;/*,
IF(Regex("if\\(.+\\)")),
PLUS(Regex("[0-9a-z]+ \\+ [0-9a-z]+"))*/
abstract fun compileFunction(subCode: String, compiledProgram: CompiledProgram): () -> Unit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment