気を付けたこと
- kotlinでは複数のクラスを一つのファイルにまとめることが出来るのでまとめた
- while((text = reader.readLine())の書き方はエラーがでるのでforeachを使った
- program.txtはサンプルファイルからとってパスを確認する
- すぐに初期化しない変数はlateinitを使っても良いがnullエラーになる場合がある
import java.io.BufferedReader
import java.io.FileReader
import java.lang.Exception
import java.lang.NumberFormatException
import java.util.*
fun main(args: Array<String>) {
try {
val reader = BufferedReader(FileReader("program.txt"))
var text = reader.readLines()
text.forEach{line ->
println("text = \"${line}\"")
val node = ProgramNode()
node.parse(Context(line))
println("node = ${node}")
}
reader.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
abstract class Node {
abstract fun parse(context:Context)
}
class ProgramNode:Node(){
lateinit private var commandListNode:Node
override fun parse(context: Context) {
context.skipToken("program")
commandListNode = CommandListNode()
commandListNode.parse(context)
}
override fun toString(): String {
return "[program ${commandListNode} ]"
}
}
class CommandListNode : Node() {
private val list = arrayListOf<Node>()
override fun parse(context: Context) {
while (true) {
if (context.currentToken() == null) {
throw ParseException("Missing end")
}else if (context.currentToken().equals("end")) {
context.skipToken("end")
break
} else {
val commandNode = CommandNode()
commandNode.parse(context)
list.add(commandNode)
}
}
}
override fun toString(): String {
return list.toString()
}
}
class CommandNode : Node() {
lateinit private var node:Node
override fun parse(context: Context) {
if (context.currentToken().equals("repeat")) {
node = RepeatCommandNode()
node.parse(context)
} else {
node = PrimitiveCommandNode()
node.parse(context)
}
}
override fun toString(): String {
return node.toString()
}
}
class RepeatCommandNode : Node() {
private var number:Int = 0
private lateinit var commandListNode: Node
override fun parse(context: Context) {
context.skipToken("repeat")
number = context.currentNumber()
context.nextToken()
commandListNode = CommandListNode()
commandListNode.parse(context)
}
override fun toString(): String {
return "[reapeat ${number} ${commandListNode} ]"
}
}
class PrimitiveCommandNode : Node() {
private lateinit var name: String
override fun parse(context: Context) {
name = context.currentToken()
context.skipToken(name)
if (!name.equals("go") && !name.equals("right") && !name.equals("left")) {
throw ParseException("${name} is undefined")
}
}
override fun toString(): String {
return name
}
}
class Context(text:String){
private val tokenizer = StringTokenizer(text)
private lateinit var currentToken:String
init {
nextToken()
}
fun nextToken():String {
if (tokenizer.hasMoreTokens()) {
currentToken = tokenizer.nextToken()
} else {
currentToken = ""
}
return currentToken
}
fun currentToken():String {
return currentToken
}
fun skipToken(token: String) {
if (!token.equals(currentToken)) {
throw ParseException("Warning: ${token} is expected, but ${currentToken} is found.")
}
nextToken()
}
fun currentNumber(): Int {
var number = 0
try {
number = currentToken.toInt()
} catch (e: NumberFormatException) {
throw ParseException("Warning: ${e}")
}
return number
}
}
class ParseException(msg:String) : Exception(msg)
元のコードは以下の本からの引用です。サンプルコードは著者さんのサイトで配布されています。リンクはAmazonアソシエイトを使用しています。
ライセンス表記
Copyright (C) 2001,2004 Hiroshi Yuki.
hyuki@hyuki.com Java言語で学ぶデザインパターン入門 第3版結城浩『Java言語で学ぶデザインパターン入門 ...
This software is provided ‘as-is’, without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution.
コメント