Compare commits

..
23 changed files with 535 additions and 62 deletions

No files matched your search

+1
View File
@@ -14,3 +14,4 @@ xcuserdata
.gigaide .gigaide
/kotlin-js-store/yarn.lock /kotlin-js-store/yarn.lock
/test.lyng /test.lyng
/sample_texts/1.txt.gz
+4 -2
View File
@@ -7,12 +7,14 @@ Important thing is that maps can't contain `null`: it is used to return from mis
Constructed map instance is of class `Map` and implements `Collection` (and therefore `Iterable`) Constructed map instance is of class `Map` and implements `Collection` (and therefore `Iterable`)
val map = Map( ["foo", 1], ["bar", "buzz"] ) val map = Map( "foo" => 1, "bar" => "buzz" )
assert(map is Map) assert(map is Map)
assert(map.size == 2) assert(map.size == 2)
assert(map is Iterable) assert(map is Iterable)
>>> void >>> void
Notice usage of the `=>` operator that creates `MapEntry`, which implements also [Collection] of
two items, first, at index zero, is a key, second, at index 1, is the value. You can use lists too.
Map keys could be any objects (hashable, e.g. with reasonable hashCode, most of standard types are). You can access elements with indexing operator: Map keys could be any objects (hashable, e.g. with reasonable hashCode, most of standard types are). You can access elements with indexing operator:
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] ) val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
@@ -31,7 +33,7 @@ To remove item from the collection. use `remove`. It returns last removed item o
hold nulls in the map - this is not a recommended practice when using `remove` returned value. `clear()` hold nulls in the map - this is not a recommended practice when using `remove` returned value. `clear()`
removes all. removes all.
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] ) val map = Map( "foo" => 1, "bar" => "buzz", [42, "answer"] )
assertEquals( 1, map.remove("foo") ) assertEquals( 1, map.remove("foo") )
assert( map.getOrNull("foo") == null) assert( map.getOrNull("foo") == null)
assert( map.size == 2 ) assert( map.size == 2 )
+1 -1
View File
@@ -4,7 +4,7 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.JvmTarget
group = "net.sergeych" group = "net.sergeych"
version = "0.7.4-SNAPSHOT" version = "0.8.0-SNAPSHOT"
buildscript { buildscript {
repositories { repositories {
@@ -2,6 +2,7 @@ package net.sergeych.lyng
import net.sergeych.lyng.obj.Obj import net.sergeych.lyng.obj.Obj
import net.sergeych.lyng.obj.ObjList import net.sergeych.lyng.obj.ObjList
import net.sergeych.lyng.obj.ObjRecord
/** /**
* List of argument declarations in the __definition__ of the lambda, class constructor, * List of argument declarations in the __definition__ of the lambda, class constructor,
@@ -22,17 +23,20 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
} }
/** /**
* parse args and create local vars in a given context * parse args and create local vars in a given context properly interpreting
* ellipsis args and default values
*/ */
suspend fun assignToContext( suspend fun assignToContext(
scope: Scope, scope: Scope,
arguments: Arguments = scope.args, arguments: Arguments = scope.args,
defaultAccessType: AccessType = AccessType.Var, defaultAccessType: AccessType = AccessType.Var,
defaultVisibility: Visibility = Visibility.Public defaultVisibility: Visibility = Visibility.Public,
defaultRecordType: ObjRecord.Type = ObjRecord.Type.ConstructorField
) { ) {
fun assign(a: Item, value: Obj) { fun assign(a: Item, value: Obj) {
scope.addItem(a.name, (a.accessType ?: defaultAccessType).isMutable, value, scope.addItem(a.name, (a.accessType ?: defaultAccessType).isMutable, value,
a.visibility ?: defaultVisibility) a.visibility ?: defaultVisibility,
recordType = defaultRecordType)
} }
// will be used with last lambda arg fix // will be used with last lambda arg fix
@@ -1122,7 +1122,7 @@ class Compiler(
thisObj thisObj
} }
// inheritance must alter this code: // inheritance must alter this code:
val newClass = ObjClass(className).apply { val newClass = ObjInstanceClass(className).apply {
instanceConstructor = constructorCode instanceConstructor = constructorCode
constructorMeta = constructorArgsDeclaration constructorMeta = constructorArgsDeclaration
} }
@@ -1630,7 +1630,7 @@ class Compiler(
// create a separate copy: // create a separate copy:
val initValue = initialExpression?.execute(context)?.byValueCopy() ?: ObjNull val initValue = initialExpression?.execute(context)?.byValueCopy() ?: ObjNull
context.addItem(name, isMutable, initValue, visibility) context.addItem(name, isMutable, initValue, visibility, recordType = ObjRecord.Type.Field)
initValue initValue
} }
} }
@@ -116,9 +116,10 @@ open class Scope(
name: String, name: String,
isMutable: Boolean, isMutable: Boolean,
value: Obj, value: Obj,
visibility: Visibility = Visibility.Public visibility: Visibility = Visibility.Public,
recordType: ObjRecord.Type = ObjRecord.Type.Other
): ObjRecord { ): ObjRecord {
return ObjRecord(value, isMutable, visibility).also { objects[name] = it } return ObjRecord(value, isMutable, visibility,type = recordType).also { objects[name] = it }
} }
fun getOrCreateNamespace(name: String): ObjClass { fun getOrCreateNamespace(name: String): ObjClass {
@@ -131,6 +131,12 @@ class Script(
if( a.compareTo(this, b) != 0 ) if( a.compareTo(this, b) != 0 )
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect()} == ${b.inspect()}")) raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect()} == ${b.inspect()}"))
} }
addVoidFn("assertNotEquals") {
val a = requiredArg<Obj>(0)
val b = requiredArg<Obj>(1)
if( a.compareTo(this, b) == 0 )
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect()} != ${b.inspect()}"))
}
addFn("assertThrows") { addFn("assertThrows") {
val code = requireOnlyArg<Statement>() val code = requireOnlyArg<Statement>()
val result =try { val result =try {
@@ -57,13 +57,20 @@ open class Obj {
args: Arguments = Arguments.EMPTY args: Arguments = Arguments.EMPTY
): T = invokeInstanceMethod(scope, name, args) as T ): T = invokeInstanceMethod(scope, name, args) as T
/**
* Invoke a method of the object if exists
* it [onNotFoundResult] is not null, it returns it when symbol is not found
* otherwise throws [ObjSymbolNotDefinedException] object exception
*/
open suspend fun invokeInstanceMethod( open suspend fun invokeInstanceMethod(
scope: Scope, scope: Scope,
name: String, name: String,
args: Arguments = Arguments.EMPTY args: Arguments = Arguments.EMPTY,
onNotFoundResult: Obj?=null
): Obj = ): Obj =
// note that getInstanceMember traverses the hierarchy objClass.getInstanceMemberOrNull(name)?.value?.invoke(scope, this, args)
objClass.getInstanceMember(scope.pos, name).value.invoke(scope, this, args) ?: onNotFoundResult
?: scope.raiseSymbolNotFound(name)
open suspend fun getInstanceMethod( open suspend fun getInstanceMethod(
scope: Scope, scope: Scope,
@@ -341,7 +348,7 @@ object ObjNull : Obj() {
scope.raiseNPE() scope.raiseNPE()
} }
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments): Obj { override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments, onNotFoundResult: Obj?): Obj {
scope.raiseNPE() scope.raiseNPE()
} }
@@ -366,6 +373,7 @@ object ObjNull : Obj() {
override suspend fun lynonType(): LynonType { override suspend fun lynonType(): LynonType {
return LynonType.Null return LynonType.Null
} }
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) { override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
if (lynonType == null) { if (lynonType == null) {
encoder.putBit(0) encoder.putBit(0)
@@ -82,9 +82,7 @@ open class ObjBuffer(val byteArray: UByteArray) : Obj() {
override suspend fun lynonType(): LynonType = LynonType.Buffer override suspend fun lynonType(): LynonType = LynonType.Buffer
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) { override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
encoder.encodeCached(byteArray) { encoder.encodeCachedBytes(byteArray.asByteArray())
bout.compress(byteArray.asByteArray())
}
} }
companion object { companion object {
@@ -11,6 +11,8 @@ open class ObjClass(
vararg parents: ObjClass, vararg parents: ObjClass,
) : Obj() { ) : Obj() {
val classNameObj by lazy { ObjString(className) }
var constructorMeta: ArgsDeclaration? = null var constructorMeta: ArgsDeclaration? = null
var instanceConstructor: Statement? = null var instanceConstructor: Statement? = null
@@ -95,11 +97,14 @@ open class ObjClass(
return super.readField(scope, name) return super.readField(scope, name)
} }
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments): Obj { override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments,
return classMembers[name]?.value?.invoke(scope, this, args) ?: super.invokeInstanceMethod(scope, name, args) onNotFoundResult: Obj?): Obj {
return classMembers[name]?.value?.invoke(scope, this, args)
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
} }
open suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj = scope.raiseNotImplemented() open suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj = scope.raiseNotImplemented()
} }
@@ -2,6 +2,7 @@ package net.sergeych.lyng.obj
import net.sergeych.lyng.Arguments import net.sergeych.lyng.Arguments
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
import net.sergeych.lynon.LynonDecoder
import net.sergeych.lynon.LynonEncoder import net.sergeych.lynon.LynonEncoder
import net.sergeych.lynon.LynonType import net.sergeych.lynon.LynonType
@@ -29,14 +30,15 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
} ?: super.writeField(scope, name, newValue) } ?: super.writeField(scope, name, newValue)
} }
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments): Obj = override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments,
onNotFoundResult: Obj?): Obj =
instanceScope[name]?.let { instanceScope[name]?.let {
if (it.visibility.isPublic) if (it.visibility.isPublic)
it.value.invoke(scope, this, args) it.value.invoke(scope, this, args)
else else
scope.raiseError(ObjAccessException(scope, "can't invoke non-public method $name")) scope.raiseError(ObjAccessException(scope, "can't invoke non-public method $name"))
} }
?: super.invokeInstanceMethod(scope, name, args) ?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
private val publicFields: Map<String, ObjRecord> private val publicFields: Map<String, ObjRecord>
get() = instanceScope.objects.filter { it.value.visibility.isPublic } get() = instanceScope.objects.filter { it.value.visibility.isPublic }
@@ -49,19 +51,51 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) { override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
val meta = objClass.constructorMeta val meta = objClass.constructorMeta
?: scope.raiseError("can't serialize non-serializable object (no constructor meta)") ?: scope.raiseError("can't serialize non-serializable object (no constructor meta)")
for( p in meta.params) { // actual constructor can vary, for example, adding new fields with default
val r = readField(scope, p.name) // values, so we save size of the construction:
println("serialize ${p.name}=${r.value}")
TODO() // using objlist allow for some optimizations:
// encoder.encodeObj(scope, r.value) val params = meta.params.map { readField(scope, it.name).value }
encoder.encodeAnyList(scope, params)
serializeStateVars(scope, encoder)
}
protected val instanceVars: Map<String, ObjRecord> by lazy {
instanceScope.objects.filter { it.value.type.serializable }
}
protected suspend fun serializeStateVars(scope: Scope,encoder: LynonEncoder) {
val vars = instanceVars.values.map { it.value }
if( vars.isNotEmpty()) {
encoder.encodeAnyList(scope, vars)
println("serialized state vars $vars")
}
}
internal suspend fun deserializeStateVars(scope: Scope, decoder: LynonDecoder) {
val localVars = instanceVars.values.toList()
if( localVars.isNotEmpty() ) {
println("gonna read vars")
val vars = decoder.decodeAnyList(scope)
if (vars.size > instanceVars.size)
scope.raiseIllegalArgument("serialized vars has bigger size than instance vars")
println("deser state vars $vars")
for ((i, v) in vars.withIndex()) {
localVars[i].value = vars[i]
}
}
}
protected val comparableVars: Map<String, ObjRecord> by lazy {
instanceScope.objects.filter {
it.value.type.comparable
} }
// todo: possible vars?
} }
override suspend fun compareTo(scope: Scope, other: Obj): Int { override suspend fun compareTo(scope: Scope, other: Obj): Int {
if (other !is ObjInstance) return -1 if (other !is ObjInstance) return -1
if (other.objClass != objClass) return -1 if (other.objClass != objClass) return -1
for (f in publicFields) { for (f in comparableVars) {
val a = f.value.value val a = f.value.value
val b = other.instanceScope[f.key]!!.value val b = other.instanceScope[f.key]!!.value
val d = a.compareTo(scope, b) val d = a.compareTo(scope, b)
@@ -0,0 +1,28 @@
package net.sergeych.lyng.obj
import net.sergeych.lyng.Arguments
import net.sergeych.lyng.Scope
import net.sergeych.lynon.LynonDecoder
import net.sergeych.lynon.LynonType
/**
* Special variant of [ObjClass] to be used in [ObjInstance], e.g. for Lyng compiled classes
*/
class ObjInstanceClass(val name: String) : ObjClass(name) {
// val onDeserilaized =
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
val args = decoder.decodeAnyList(scope)
println("deserializing constructor $name, $args params")
val actualSize = constructorMeta?.params?.size ?: 0
if( args.size > actualSize )
scope.raiseIllegalArgument("constructor $name has only $actualSize but serialized version has ${args.size}")
val newScope = scope.copy(args = Arguments(args))
return (callOn(newScope) as ObjInstance).apply {
deserializeStateVars(scope,decoder)
invokeInstanceMethod(scope, "onDeserialized", onNotFoundResult = ObjVoid)
}
}
}
@@ -117,6 +117,7 @@ class ObjInt(var value: Long, override val isConst: Boolean = false) : Obj(), Nu
LynonType.Int0 -> {} LynonType.Int0 -> {}
LynonType.IntPositive -> encoder.encodeUnsigned(value.toULong()) LynonType.IntPositive -> encoder.encodeUnsigned(value.toULong())
LynonType.IntNegative -> encoder.encodeUnsigned((-value).toULong()) LynonType.IntNegative -> encoder.encodeUnsigned((-value).toULong())
LynonType.IntSigned -> encoder.encodeSigned(value)
else -> scope.raiseIllegalArgument("Unsupported lynon type code for Int: $lynonType") else -> scope.raiseIllegalArgument("Unsupported lynon type code for Int: $lynonType")
} }
} }
@@ -131,6 +132,7 @@ class ObjInt(var value: Long, override val isConst: Boolean = false) : Obj(), Nu
LynonType.Int0 -> Zero LynonType.Int0 -> Zero
LynonType.IntPositive -> ObjInt(decoder.unpackUnsigned().toLong()) LynonType.IntPositive -> ObjInt(decoder.unpackUnsigned().toLong())
LynonType.IntNegative -> ObjInt(-decoder.unpackUnsigned().toLong()) LynonType.IntNegative -> ObjInt(-decoder.unpackUnsigned().toLong())
LynonType.IntSigned -> ObjInt(decoder.unpackSigned())
else -> scope.raiseIllegalState("illegal type code for Int: $lynonType") else -> scope.raiseIllegalState("illegal type code for Int: $lynonType")
} }
} }
@@ -2,6 +2,9 @@ package net.sergeych.lyng.obj
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
import net.sergeych.lyng.statement import net.sergeych.lyng.statement
import net.sergeych.lynon.LynonDecoder
import net.sergeych.lynon.LynonEncoder
import net.sergeych.lynon.LynonType
class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() { class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
@@ -125,9 +128,18 @@ class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
return list == other.list return list == other.list
} }
companion object { override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
val type = ObjClass("List", ObjArray).apply { encoder.encodeAnyList(scope,list)
}
override suspend fun lynonType(): LynonType = LynonType.List
companion object {
val type = object : ObjClass("List", ObjArray) {
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
return ObjList(decoder.decodeAnyList(scope))
}
}.apply {
createField("size", createField("size",
statement { statement {
(thisObj as ObjList).list.size.toObj() (thisObj as ObjList).list.size.toObj()
@@ -2,6 +2,9 @@ package net.sergeych.lyng.obj
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
import net.sergeych.lyng.Statement import net.sergeych.lyng.Statement
import net.sergeych.lynon.LynonDecoder
import net.sergeych.lynon.LynonEncoder
import net.sergeych.lynon.LynonType
class ObjMapEntry(val key: Obj, val value: Obj) : Obj() { class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
@@ -12,6 +15,14 @@ class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
return value.compareTo(scope, other.value) return value.compareTo(scope, other.value)
} }
override fun hashCode(): Int {
return key.hashCode() + value.hashCode()
}
override fun equals(other: Any?): Boolean {
return other is ObjMapEntry && key == other.key && value == other.value
}
override suspend fun getAt(scope: Scope, index: Obj): Obj = when (index.toInt()) { override suspend fun getAt(scope: Scope, index: Obj): Obj = when (index.toInt()) {
0 -> key 0 -> key
1 -> value 1 -> value
@@ -24,11 +35,23 @@ class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
override val objClass = type override val objClass = type
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
encoder.encodeAny(scope,key)
encoder.encodeAny(scope,value)
}
companion object { companion object {
val type = object : ObjClass("MapEntry", ObjArray) { val type = object : ObjClass("MapEntry", ObjArray) {
override suspend fun callOn(scope: Scope): Obj { override suspend fun callOn(scope: Scope): Obj {
return ObjMapEntry(scope.requiredArg<Obj>(0), scope.requiredArg<Obj>(1)) return ObjMapEntry(scope.requiredArg<Obj>(0), scope.requiredArg<Obj>(1))
} }
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
return ObjMapEntry(
decoder.decodeAny(scope),
decoder.decodeAny(scope)
)
}
}.apply { }.apply {
addFn("key") { thisAs<ObjMapEntry>().key } addFn("key") { thisAs<ObjMapEntry>().key }
addFn("value") { thisAs<ObjMapEntry>().value } addFn("value") { thisAs<ObjMapEntry>().value }
@@ -71,6 +94,15 @@ class ObjMap(val map: MutableMap<Obj, Obj> = mutableMapOf()) : Obj() {
return map == other.map return map == other.map
} }
override suspend fun lynonType(): LynonType = LynonType.Map
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
val keys = map.keys.map { it.toObj() }
val values = map.values.map { it.toObj() }
encoder.encodeAnyList(scope, keys)
encoder.encodeAnyList(scope, values, fixedSize = true)
}
companion object { companion object {
suspend fun listToMap(scope: Scope, list: List<Obj>): MutableMap<Obj, Obj> { suspend fun listToMap(scope: Scope, list: List<Obj>): MutableMap<Obj, Obj> {
@@ -98,6 +130,13 @@ class ObjMap(val map: MutableMap<Obj, Obj> = mutableMapOf()) : Obj() {
override suspend fun callOn(scope: Scope): Obj { override suspend fun callOn(scope: Scope): Obj {
return ObjMap(listToMap(scope, scope.args.list)) return ObjMap(listToMap(scope, scope.args.list))
} }
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
val keys = decoder.decodeAnyList(scope)
val values = decoder.decodeAnyList(scope,fixedSize = keys.size)
if( keys.size != values.size) scope.raiseIllegalArgument("map keys and values should be same size")
return ObjMap(keys.zip(values).toMap().toMutableMap())
}
}.apply { }.apply {
addFn("getOrNull") { addFn("getOrNull") {
val key = args.firstAndOnly(pos) val key = args.firstAndOnly(pos)
@@ -10,8 +10,17 @@ data class ObjRecord(
var value: Obj, var value: Obj,
val isMutable: Boolean, val isMutable: Boolean,
val visibility: Visibility = Visibility.Public, val visibility: Visibility = Visibility.Public,
var importedFrom: Scope? = null var importedFrom: Scope? = null,
val isTransient: Boolean = false,
val type: Type = Type.Other
) { ) {
enum class Type(val comparable: Boolean = false,val serializable: Boolean = false) {
Field(true, true),
@Suppress("unused")
Fun,
ConstructorField(true, true),
Other
}
@Suppress("unused") @Suppress("unused")
fun qualifiedName(name: String): String = fun qualifiedName(name: String): String =
"${importedFrom?.packageName ?: "anonymous"}.$name" "${importedFrom?.packageName ?: "anonymous"}.$name"
@@ -1,6 +1,9 @@
package net.sergeych.lyng.obj package net.sergeych.lyng.obj
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
import net.sergeych.lynon.LynonDecoder
import net.sergeych.lynon.LynonEncoder
import net.sergeych.lynon.LynonType
class ObjSet(val set: MutableSet<Obj> = mutableSetOf()) : Obj() { class ObjSet(val set: MutableSet<Obj> = mutableSetOf()) : Obj() {
@@ -80,6 +83,12 @@ class ObjSet(val set: MutableSet<Obj> = mutableSetOf()) : Obj() {
return set == other.set return set == other.set
} }
override suspend fun lynonType(): LynonType = LynonType.Set
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
encoder.encodeAnyList(scope, set.toList())
}
companion object { companion object {
@@ -87,6 +96,9 @@ class ObjSet(val set: MutableSet<Obj> = mutableSetOf()) : Obj() {
override suspend fun callOn(scope: Scope): Obj { override suspend fun callOn(scope: Scope): Obj {
return ObjSet(scope.args.list.toMutableSet()) return ObjSet(scope.args.list.toMutableSet())
} }
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
ObjSet(decoder.decodeAnyList(scope).toMutableSet())
}.apply { }.apply {
addFn("size") { addFn("size") {
thisAs<ObjSet>().set.size.toObj() thisAs<ObjSet>().set.size.toObj()
@@ -84,17 +84,13 @@ data class ObjString(val value: String) : Obj() {
override suspend fun lynonType(): LynonType = LynonType.String override suspend fun lynonType(): LynonType = LynonType.String
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) { override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
val data = value.encodeToByteArray() encoder.encodeBinaryData(value.encodeToByteArray())
encoder.encodeCached(data) { encoder.encodeBinaryData(data) }
} }
companion object { companion object {
val type = object : ObjClass("String") { val type = object : ObjClass("String") {
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj = override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
decoder.decodeCached {
ObjString(decoder.unpackBinaryData().decodeToString()) ObjString(decoder.unpackBinaryData().decodeToString())
}
}.apply { }.apply {
addFn("toInt") { addFn("toInt") {
ObjInt(thisAs<ObjString>().value.toLong()) ObjInt(thisAs<ObjString>().value.toLong())
@@ -3,6 +3,7 @@ package net.sergeych.lynon
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
import net.sergeych.lyng.obj.Obj import net.sergeych.lyng.obj.Obj
import net.sergeych.lyng.obj.ObjClass import net.sergeych.lyng.obj.ObjClass
import net.sergeych.lyng.obj.ObjString
open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSettings.default) { open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSettings.default) {
@@ -17,10 +18,11 @@ open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSe
val cache = mutableListOf<Any>() val cache = mutableListOf<Any>()
inline fun <T : Any>decodeCached(f: LynonDecoder.() -> T): T { inline fun <reified T : Any> decodeCached(f: LynonDecoder.() -> T): T {
return if (bin.getBit() == 0) { return if (bin.getBit() == 0) {
// unpack and cache // unpack and cache
f().also { f().also {
// println("decode: cache miss: ${cache.size}: $it:${it::class.simpleName}")
if (settings.shouldCache(it)) cache.add(it) if (settings.shouldCache(it)) cache.add(it)
} }
} else { } else {
@@ -29,18 +31,55 @@ open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSe
val id = bin.getBitsOrNull(size)?.toInt() val id = bin.getBitsOrNull(size)?.toInt()
?: throw RuntimeException("Invalid object id: unexpected end of stream") ?: throw RuntimeException("Invalid object id: unexpected end of stream")
if (id >= cache.size) throw RuntimeException("Invalid object id: $id should be in 0..<${cache.size}") if (id >= cache.size) throw RuntimeException("Invalid object id: $id should be in 0..<${cache.size}")
@Suppress("UNCHECKED_CAST") // println("decode: cache hit ${id}: ${cache[id]}:${cache[id]::class.simpleName}")
// @Suppress("UNCHECKED_CAST")
cache[id] as T cache[id] as T
} }
} }
suspend fun decodeAny(scope: Scope): Obj = decodeCached { suspend fun decodeAny(scope: Scope): Obj = decodeCached {
val type = LynonType.entries[bin.getBits(4).toInt()] val type = LynonType.entries[bin.getBits(4).toInt()]
if (type != LynonType.Other) {
type.objClass.deserialize(scope, this, type) type.objClass.deserialize(scope, this, type)
} else {
decodeClassObj(scope).deserialize(scope, this, null)
}
} }
suspend fun decodeObject(scope: Scope, type: ObjClass): Obj { private suspend fun decodeClassObj(scope: Scope): ObjClass {
return decodeCached { type.deserialize(scope, this, null) } val className = decodeObject(scope, ObjString.type, null) as ObjString
println("expected class name $className")
return scope.get(className.value)?.value?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
it
} ?: scope.raiseSymbolNotFound("can't deserialize: not found type $className")
}
suspend fun decodeAnyList(scope: Scope,fixedSize: Int?=null): MutableList<Obj> {
return if (bin.getBit() == 1) {
// homogenous
val type = LynonType.entries[getBitsAsInt(4)]
val list = mutableListOf<Obj>()
val objClass = if (type == LynonType.Other)
decodeClassObj(scope).also { println("detected class obj: $it") }
else type.objClass
val size = fixedSize ?: bin.unpackUnsigned().toInt()
println("detected homogenous list type $type, $size items")
for (i in 0..<size) {
list += decodeObject(scope, objClass, type).also {
println("decoded: $it")
}
}
list
} else {
val size = fixedSize ?: unpackUnsigned().toInt()
(0..<size).map { decodeAny(scope) }.toMutableList()
}
}
suspend fun decodeObject(scope: Scope, type: ObjClass, overrideType: LynonType? = null): Obj {
return decodeCached { type.deserialize(scope, this, overrideType) }
} }
fun unpackBinaryData(): ByteArray = bin.decompress() fun unpackBinaryData(): ByteArray = bin.decompress()
@@ -9,6 +9,7 @@ enum class LynonType(val objClass: ObjClass,val defaultFrequency: Int = 1) {
Int0(ObjInt.type, 70), Int0(ObjInt.type, 70),
IntNegative(ObjInt.type, 50), IntNegative(ObjInt.type, 50),
IntPositive(ObjInt.type, 100), IntPositive(ObjInt.type, 100),
IntSigned(ObjInt.type, 30),
String(ObjString.type, 100), String(ObjString.type, 100),
Real(ObjReal.type), Real(ObjReal.type),
Bool(ObjBool.type, 80), Bool(ObjBool.type, 80),
@@ -19,6 +20,29 @@ enum class LynonType(val objClass: ObjClass,val defaultFrequency: Int = 1) {
Instant(ObjInstant.type, 30), Instant(ObjInstant.type, 30),
Duration(ObjDuration.type), Duration(ObjDuration.type),
Other(Obj.rootObjectType, 60); Other(Obj.rootObjectType, 60);
fun generalizeTo(other: LynonType): LynonType? {
if (this == other) return this
return (if (this.isInt && other.isInt) {
when {
this == Int0 -> other // upgrade 0 to some other int
other == Int0 -> this // 0 is member of our class, ignore
// different signum propagate to signed
else -> IntSigned
}
} else
// impossible to generalize
null
).also { println("Gen $this + $other -> $it") }
}
val isInt by lazy {
when (this) {
Int0, IntSigned, IntPositive, IntNegative -> true
else -> false
}
}
} }
open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = LynonSettings.default) { open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = LynonSettings.default) {
@@ -29,14 +53,20 @@ open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = Lynon
suspend fun serializeAndCache(key: Any = item) { suspend fun serializeAndCache(key: Any = item) {
cache[key]?.let { cacheId -> cache[key]?.let { cacheId ->
// println("encode: Cache hit: ${cacheId}: $item: ${item::class.simpleName}")
val size = sizeInBits(cache.size) val size = sizeInBits(cache.size)
bout.putBit(1) bout.putBit(1)
bout.putBits(cacheId.toULong(), size) bout.putBits(cacheId.toULong(), size)
} ?: run { } ?: run {
bout.putBit(0) bout.putBit(0)
if (settings.shouldCache(item)) if (settings.shouldCache(item)) {
cache[key] = cache.size // println("encode add cache: ${cache.size}: $item: ${item::class.simpleName}")
packer() packer()
cache[key] = cache.size
} else {
// println("encode but not cache $item")
packer()
}
} }
} }
@@ -53,21 +83,77 @@ open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = Lynon
* *
* Caching is used automatically. * Caching is used automatically.
*/ */
suspend fun encodeAny(scope: Scope, value: Obj) { suspend fun encodeAny(scope: Scope, obj: Obj) {
encodeCached(value) { encodeCached(obj) {
val type = value.lynonType() val type = putTypeRecord(scope, obj, obj.lynonType())
putType(type) obj.serialize(scope, this, type)
value.serialize(scope, this, type)
} }
} }
private suspend fun putTypeRecord(scope: Scope, obj: Obj, type: LynonType): LynonType {
putType(type)
if( type == LynonType.Other) {
encodeObject(scope, obj.objClass.classNameObj)
}
return type
}
private fun putType(type: LynonType) { private fun putType(type: LynonType) {
bout.putBits(type.ordinal.toULong(), 4) bout.putBits(type.ordinal.toULong(), 4)
} }
suspend fun encodeObject(scope: Scope, obj: Obj) { /**
* AnyList could be homogenous (first bit=1) and heterogeneous (first bit=0). Homogenous list
* has a single type record that precedes the list, heterogeneous hash typed record
* for each item.
*
*/
suspend fun encodeAnyList(scope: Scope, list: List<Obj>,fixedSize: Boolean = false) {
if( list.isEmpty()) {
// any-typed, empty, save space
putBit(0)
encodeUnsigned(0u)
}
else {
val objClass = list[0].objClass
var type = list[0].lynonType()
var isHomogeneous = true
for (i in list.drop(1))
if (i.objClass != objClass) {
isHomogeneous = false
break
} else {
// same class but type might need generalization
type = type.generalizeTo(i.lynonType())
?: scope.raiseError("inner error: can't generalize lynon type $type to ${i.lynonType()}")
}
if (isHomogeneous) {
putBit(1)
putTypeRecord(scope, list[0], type)
if (!fixedSize)
encodeUnsigned(list.size.toULong())
for (i in list) encodeObject(scope, i, type)
} else {
putBit(0)
if (!fixedSize)
encodeUnsigned(list.size.toULong())
for (i in list) encodeAny(scope, i)
}
}
}
/**
* Write object _with no type record_: type is known
*/
suspend fun encodeObject(scope: Scope, obj: Obj,overrideType: LynonType? = null) {
encodeCached(obj) { encodeCached(obj) {
obj.serialize(scope, this, null) obj.serialize(scope, this, overrideType)
}
}
suspend fun encodeCachedBytes(bytes: ByteArray) {
encodeCached(bytes) {
bout.compress(bytes)
} }
} }
@@ -2242,6 +2242,14 @@ class ScriptTest {
) )
} }
@Test
fun testSet2() = runTest {
eval("""
assertEquals( Set( ...[1,2,3]), Set(1,2,3) )
assertEquals( Set( ...[1,false,"ok"]), Set("ok", 1, false) )
""".trimIndent())
}
@Test @Test
fun testLet() = runTest { fun testLet() = runTest {
eval( eval(
@@ -50,4 +50,27 @@ class TypesTest {
""".trimIndent()) """.trimIndent())
} }
@Test
fun testUserClassCompareTo() = runTest {
eval("""
class Point(val a,b)
assertEquals(Point(0,1), Point(0,1) )
assertNotEquals(Point(0,1), Point(1,1) )
""".trimIndent())
}
@Test
fun testUserClassCompareTo2() = runTest {
eval("""
class Point(val a,b) {
var c = 0
}
assertEquals(Point(0,1), Point(0,1) )
assertEquals(Point(0,1).apply { c = 2 }, Point(0,1).apply { c = 2 } )
assertNotEquals(Point(0,1), Point(1,1) )
assertNotEquals(Point(0,1), Point(0,1).apply { c = 1 } )
""".trimIndent())
}
} }
+173 -13
View File
@@ -1,4 +1,5 @@
import junit.framework.TestCase.* import junit.framework.TestCase.assertNotSame
import junit.framework.TestCase.assertSame
import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.runTest
import net.sergeych.bintools.encodeToHex import net.sergeych.bintools.encodeToHex
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
@@ -9,6 +10,9 @@ import java.nio.file.Files
import java.nio.file.Path import java.nio.file.Path
import kotlin.test.Test import kotlin.test.Test
import kotlin.test.assertContentEquals import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class LynonTests { class LynonTests {
@Test @Test
@@ -53,6 +57,7 @@ class LynonTests {
assertEquals(1, bin.getBit()) assertEquals(1, bin.getBit())
assertEquals(null, bin.getBitOrNull()) assertEquals(null, bin.getBitOrNull())
} }
@Test @Test
fun testBitOutputMedium() { fun testBitOutputMedium() {
val bout = MemoryBitOutput() val bout = MemoryBitOutput()
@@ -144,6 +149,15 @@ class LynonTests {
assertEquals(1471792L, bin.unpackSigned()) assertEquals(1471792L, bin.unpackSigned())
} }
@Test
fun testObjStringAndStringKeys() = runTest {
val s = "foo"
val sobj = ObjString("foo")
val map = mutableMapOf(s to 1, sobj to 2)
assertEquals(1, map[s])
assertEquals(2, map[sobj])
}
@Test @Test
fun testCache1() = runTest { fun testCache1() = runTest {
val bout = MemoryBitOutput() val bout = MemoryBitOutput()
@@ -231,6 +245,7 @@ class LynonTests {
assertEquals(ObjReal(Double.MIN_VALUE), decoder.decodeObject(scope, ObjReal.type)) assertEquals(ObjReal(Double.MIN_VALUE), decoder.decodeObject(scope, ObjReal.type))
assertEquals(ObjReal(Double.MAX_VALUE), decoder.decodeObject(scope, ObjReal.type)) assertEquals(ObjReal(Double.MAX_VALUE), decoder.decodeObject(scope, ObjReal.type))
} }
@Test @Test
fun testUnpackInt() = runTest { fun testUnpackInt() = runTest {
val scope = Scope() val scope = Scope()
@@ -273,10 +288,12 @@ class LynonTests {
@Test @Test
fun testEncodeNullsAndInts() = runTest { fun testEncodeNullsAndInts() = runTest {
testScope().eval(""" testScope().eval(
"""
testEncode(null) testEncode(null)
testEncode(0) testEncode(0)
""".trimIndent()) """.trimIndent()
)
} }
@Test @Test
@@ -290,7 +307,9 @@ class LynonTests {
} }
suspend fun testScope() = suspend fun testScope() =
Scope().apply { eval(""" Scope().apply {
eval(
"""
import lyng.serialization import lyng.serialization
fun testEncode(value) { fun testEncode(value) {
val encoded = Lynon.encode(value) val encoded = Lynon.encode(value)
@@ -298,21 +317,25 @@ class LynonTests {
println("Encoded size %d: %s"(encoded.size, value)) println("Encoded size %d: %s"(encoded.size, value))
assertEquals( value, Lynon.decode(encoded) ) assertEquals( value, Lynon.decode(encoded) )
} }
""".trimIndent()) """.trimIndent()
)
} }
@Test @Test
fun testUnaryMinus() = runTest { fun testUnaryMinus() = runTest {
eval(""" eval(
"""
assertEquals( -1 * π, 0 - π ) assertEquals( -1 * π, 0 - π )
assertEquals( -1 * π, -π ) assertEquals( -1 * π, -π )
""".trimIndent()) """.trimIndent()
)
} }
@Test @Test
fun testSimpleTypes() = runTest { fun testSimpleTypes() = runTest {
testScope().eval(""" testScope().eval(
"""
testEncode(null) testEncode(null)
testEncode(0) testEncode(0)
testEncode(47) testEncode(47)
@@ -330,7 +353,8 @@ class LynonTests {
testEncode("Hello, world".encodeUtf8()) testEncode("Hello, world".encodeUtf8())
testEncode("Hello, world") testEncode("Hello, world")
""".trimIndent()) """.trimIndent()
)
} }
@Test @Test
@@ -398,14 +422,12 @@ class LynonTests {
val alphabet = object : Huffman.Alphabet<LynonType> { val alphabet = object : Huffman.Alphabet<LynonType> {
override val maxOrdinal = LynonType.entries.size override val maxOrdinal = LynonType.entries.size
// val bitSize = sizeInBits(maxOrdinal)
override fun decodeOrdinalTo(bout: BitOutput, ordinal: Int) { override fun decodeOrdinalTo(bout: BitOutput, ordinal: Int) {
TODO("Not yet implemented") throw NotImplementedError()
} }
override fun get(ordinal: Int): LynonType { override fun get(ordinal: Int): LynonType {
TODO("Not yet implemented") return LynonType.entries[ordinal]
} }
override fun ordinalOf(value: LynonType): Int = value.ordinal override fun ordinalOf(value: LynonType): Int = value.ordinal
@@ -474,5 +496,143 @@ class LynonTests {
assertEquals(src3, bin.decompressString()) assertEquals(src3, bin.decompressString())
} }
@Test
fun testIntList() = runTest {
testScope().eval(
"""
testEncode([1,2,3])
testEncode([-1,-2,-3])
testEncode([1,-2,-3])
testEncode([0,1])
testEncode([0,0,0])
testEncode(["the", "the", "wall", "the", "wall", "wall"])
testEncode([1,2,3, "the", "wall", "wall"])
testEncode([false, false, false, true,true])
testEncode([])
""".trimIndent()
)
} }
@Test
fun testNamedObject() = runTest {
val s = testScope()
val x = s.eval("""5 => 6""")
assert(x is ObjMapEntry)
val bout = MemoryBitOutput()
val e = LynonEncoder(bout)
e.encodeAny(s, x)
val bin = bout.toBitInput()
val d = LynonDecoder(bin)
val x2 = d.decodeAny(s)
println(x)
println(x2)
assertTrue { x.compareTo(s, x2) == 0}
assertEquals(x, x2)
s.eval("""
testEncode( 1 => "one" )
testEncode( [1 => "one", 1 => "one"] )
testEncode( [1 => "one", 1 => "one", "foo" => "MapEntry"] )
""".trimIndent())
}
@Test
fun testHomogenousMap() = runTest {
val s = testScope()
s.eval("""
testEncode( Map("one" => 1, "two" => 2) )
testEncode( Map() )
""".trimIndent())
}
@Test
fun testHeterogeneousMap() = runTest {
val s = testScope()
s.eval("""
testEncode(["one", 2])
testEncode([1, "2"])
testEncode( Map("one" => 1, 2 => 2) )
testEncode( Map("one" => 1, 2 => "2") )
""".trimIndent())
}
@Test
fun testSetSerialization() = runTest {
testScope().eval("""
testEncode( Set("one", "two") )
testEncode( Set() )
testEncode( Set(1, "one", false) )
testEncode( Set(true, true, false) )
""".trimIndent())
}
@Test
fun testClassSerializationNoInstanceVars() = runTest {
testScope().eval("""
import lyng.serialization
class Point(x,y)
// println( Lynon.encode(Point(0,0)).toDump() )
testEncode(Point(0,0))
testEncode(Point(10,11))
testEncode(Point(-1,2))
testEncode(Point(-1,-2))
testEncode(Point("point!",-2))
""".trimIndent())
}
@Test
fun testClassSerializationWithInstanceVars() = runTest {
testScope().eval("""
import lyng.serialization
class Point(x=0) {
var y = 0
}
testEncode(Point())
testEncode(Point(1))
testEncode(Point(1).apply { y = 2 })
testEncode(Point(10).also { it.y = 11 })
""".trimIndent())
}
@Test
fun testClassSerializationWithInstanceVars2() = runTest {
testScope().eval("""
import lyng.serialization
var onInitComment = null
class Point(x=0) {
var y = 0
var comment = null
fun onDeserialized() {
onInitComment = comment
}
}
testEncode(Point())
testEncode(Point(1))
testEncode(Point(1).apply { y = 2 })
testEncode(Point(10).also { it.y = 11 })
// important: class init is called before setting non-constructor fields
// this is decessary, so deserialized fields are only available
// after onDeserialized() call (if exists):
// deserialized:
testEncode(Point(10).also { it.y = 11; it.comment = "comment" })
println("-- on init comment "+onInitComment)
assertEquals("comment", onInitComment)
""".trimIndent())
}
}