package egg
class Value<T> <: Object {
var value: T
public init(value: T) {
this.value = value
}
}
class Utils {
public static func ensureNumber(value: Object, operationName: String): Float64 {
if (value is Value<Float64>) {
let temp = (value as Value<Float64>).getOrThrow({=> Exception("操作符 ${operationName} 需要数字类型参数")})
return temp.value
} else if (value is Value<Int64>) {
let temp = (value as Value<Int64>).getOrThrow({=> Exception("操作符 ${operationName} 需要数字类型参数")})
return Float64(temp.value)
} else {
throw Exception("操作符 ${operationName} 需要数字类型参数")
}
}
/**
* 将数组转换为字符串表示
*/
private static func arrayToString(array: Value<Array<Object>>): String {
var result = "["
for (i in 0..array.value.size) {
result += convertObjectToString(array.value[i])
if (i != array.value.size - 1) {
result += ", "
}
}
result += "]"
return result
}
/**
* 将 Egg 的内部值转换为适合打印的字符串表示。
* @param value 要转换的值
* @return 值的字符串表示
*/
public static func convertObjectToString(value: Object): String {
try {
match (value) {
case str: Value<String> => "${str.value}"
case num: Value<Float64> => "${num.value}"
case num: Value<Int64> => "${num.value}"
case bool: Value<Bool> => "${bool.value}"
case array: Value<Array<Object>> => arrayToString(array)
case _: UserDefinedFunction => "UserDefinedFunction"
case _: EggFunction => "EggFunction"
case _: SpecialForm => "SpecialForm"
case expr: Expression => expr.toString()
case _ => "unknown"
}
} catch (e: Exception) {
throw Exception("对象转换为字符串时发生错误: ${e.message}")
}
}
// 跳过空格、制表符、换行符和回车符
public static func isWhitespace(c: UInt8): Bool {
return c == 32 || c == 9 || c == 10 || c == 13 // 空格、制表符、换行符、回车符
}
public static func isBank(value: String): Bool {
if (value.isEmpty()) {
return true
}
for (c in value) {
if (Utils.isWhitespace(c) == false) {
return false
}
}
return true
}
}