Compare commits

...
14 Commits
28 changed files with 945 additions and 237 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 )
+42 -1
View File
@@ -147,7 +147,7 @@ In many cases it is necessary to implement custom comparison and `toString`, sti
each class is provided with default implementations: each class is provided with default implementations:
- default toString outputs class name and its _public_ fields. - default toString outputs class name and its _public_ fields.
- default comparison compares compares all public fields in order of appearance. - default comparison compares all fields in order of appearance.
For example, for our class Point: For example, for our class Point:
@@ -160,6 +160,47 @@ For example, for our class Point:
Point(1,1+1) Point(1,1+1)
>>> Point(x=1,y=2) >>> Point(x=1,y=2)
## Statics: class fields and class methods
You can mark a field or a method as static. This is borrowed from Java as more plain version of a kotlin's companion object or Scala's object. Static field and functions is one for a class, not for an instance. From inside the class, e.g. from the class method, it is a regular var. From outside, it is accessible as `ClassName.field` or method:
class Value(x) {
static var foo = Value("foo")
static fun exclamation() {
// here foo is a regular var:
foo.x + "!"
}
}
assertEquals( Value.foo.x, "foo" )
assertEquals( "foo!", Value.exclamation() )
// we can access foo from outside like this:
Value.foo = Value("bar")
assertEquals( "bar!", Value.exclamation() )
>>> void
As usual, private statics are not accessible from the outside:
class Test {
// private, inacessible from outside protected data:
private static var data = null
// the interface to access and change it:
static fun getData() { data }
static fun setData(value) { data = value }
}
// no direct access:
assertThrows { Test.data }
// accessible with the interface:
assertEquals( null, Test.getData() )
Test.setData("fubar")
assertEquals("fubar", Test.getData() )
>>> void
# Extending classes # Extending classes
It sometimes happen that the class is missing some particular functionality that can be _added to it_ without rewriting its inner logic and using its private state. In this case _extension methods_ could be used, for example. we want to create an extension method It sometimes happen that the class is missing some particular functionality that can be _added to it_ without rewriting its inner logic and using its private state. In this case _extension methods_ could be used, for example. we want to create an extension method
+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.1-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
@@ -17,6 +17,16 @@ class Compiler(
class Settings class Settings
private val initStack = mutableListOf<MutableList<Statement>>()
val currentInitScope: MutableList<Statement>
get() =
initStack.lastOrNull() ?: cc.syntaxError("no initialization scope exists here")
private fun pushInitScope(): MutableList<Statement> = mutableListOf<Statement>().also { initStack.add(it) }
private fun popInitScope(): MutableList<Statement> = initStack.removeLast()
private suspend fun parseScript(): Script { private suspend fun parseScript(): Script {
val statements = mutableListOf<Statement>() val statements = mutableListOf<Statement>()
val start = cc.currentPos() val start = cc.currentPos()
@@ -823,6 +833,8 @@ class Compiler(
val isExtern = cc.skipId("extern") val isExtern = cc.skipId("extern")
when { when {
cc.matchQualifiers("fun", "private") -> parseFunctionDeclaration(Visibility.Private, isExtern) cc.matchQualifiers("fun", "private") -> parseFunctionDeclaration(Visibility.Private, isExtern)
cc.matchQualifiers("fun", "private", "static") -> parseFunctionDeclaration(Visibility.Private, isExtern, isStatic = true)
cc.matchQualifiers("fun", "static") -> parseFunctionDeclaration(Visibility.Public, isExtern, isStatic = true)
cc.matchQualifiers("fn", "private") -> parseFunctionDeclaration(Visibility.Private, isExtern) cc.matchQualifiers("fn", "private") -> parseFunctionDeclaration(Visibility.Private, isExtern)
cc.matchQualifiers("fun", "open") -> parseFunctionDeclaration(isOpen = true, isExtern = isExtern) cc.matchQualifiers("fun", "open") -> parseFunctionDeclaration(isOpen = true, isExtern = isExtern)
cc.matchQualifiers("fn", "open") -> parseFunctionDeclaration(isOpen = true, isExtern = isExtern) cc.matchQualifiers("fn", "open") -> parseFunctionDeclaration(isOpen = true, isExtern = isExtern)
@@ -830,7 +842,21 @@ class Compiler(
cc.matchQualifiers("fun") -> parseFunctionDeclaration(isOpen = false, isExtern = isExtern) cc.matchQualifiers("fun") -> parseFunctionDeclaration(isOpen = false, isExtern = isExtern)
cc.matchQualifiers("fn") -> parseFunctionDeclaration(isOpen = false, isExtern = isExtern) cc.matchQualifiers("fn") -> parseFunctionDeclaration(isOpen = false, isExtern = isExtern)
cc.matchQualifiers("val", "private", "static") -> parseVarDeclaration(
false,
Visibility.Private,
isStatic = true
)
cc.matchQualifiers("val", "static") -> parseVarDeclaration(false, Visibility.Public, isStatic = true)
cc.matchQualifiers("val", "private") -> parseVarDeclaration(false, Visibility.Private) cc.matchQualifiers("val", "private") -> parseVarDeclaration(false, Visibility.Private)
cc.matchQualifiers("var", "static") -> parseVarDeclaration(true, Visibility.Public, isStatic = true)
cc.matchQualifiers("var", "static", "private") -> parseVarDeclaration(
true,
Visibility.Private,
isStatic = true
)
cc.matchQualifiers("var", "private") -> parseVarDeclaration(true, Visibility.Private) cc.matchQualifiers("var", "private") -> parseVarDeclaration(true, Visibility.Private)
cc.matchQualifiers("val", "open") -> parseVarDeclaration(false, Visibility.Private, true) cc.matchQualifiers("val", "open") -> parseVarDeclaration(false, Visibility.Private, true)
cc.matchQualifiers("var", "open") -> parseVarDeclaration(true, Visibility.Private, true) cc.matchQualifiers("var", "open") -> parseVarDeclaration(true, Visibility.Private, true)
@@ -1090,6 +1116,8 @@ class Compiler(
cc.skipTokenOfType(Token.Type.NEWLINE, isOptional = true) cc.skipTokenOfType(Token.Type.NEWLINE, isOptional = true)
val t = cc.next() val t = cc.next()
pushInitScope()
val bodyInit: Statement? = if (t.type == Token.Type.LBRACE) { val bodyInit: Statement? = if (t.type == Token.Type.LBRACE) {
// parse body // parse body
parseScript().also { parseScript().also {
@@ -1100,6 +1128,8 @@ class Compiler(
null null
} }
val initScope = popInitScope()
// create class // create class
val className = nameToken.value val className = nameToken.value
@@ -1122,7 +1152,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
} }
@@ -1131,6 +1161,13 @@ class Compiler(
// the main statement should create custom ObjClass instance with field // the main statement should create custom ObjClass instance with field
// accessors, constructor registration, etc. // accessors, constructor registration, etc.
addItem(className, false, newClass) addItem(className, false, newClass)
if (initScope.isNotEmpty()) {
val classScope = copy(newThisObj = newClass)
newClass.classScope = classScope
for (s in initScope)
s.execute(classScope)
.also { println("executed, ${classScope.objects}") }
}
newClass newClass
} }
} }
@@ -1506,7 +1543,8 @@ class Compiler(
private suspend fun parseFunctionDeclaration( private suspend fun parseFunctionDeclaration(
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
@Suppress("UNUSED_PARAMETER") isOpen: Boolean = false, @Suppress("UNUSED_PARAMETER") isOpen: Boolean = false,
isExtern: Boolean = false isExtern: Boolean = false,
isStatic: Boolean = false,
): Statement { ): Statement {
var t = cc.next() var t = cc.next()
val start = t.pos val start = t.pos
@@ -1559,7 +1597,7 @@ class Compiler(
} }
fnStatements.execute(context) fnStatements.execute(context)
} }
return statement(start) { context -> val fnCreatestatement = statement(start) { context ->
// we added fn in the context. now we must save closure // we added fn in the context. now we must save closure
// for the function // for the function
closure = context closure = context
@@ -1577,6 +1615,11 @@ class Compiler(
// saved the proper context in the closure // saved the proper context in the closure
fnBody fnBody
} }
return if (isStatic) {
currentInitScope += fnCreatestatement
NopStatement
} else
fnCreatestatement
} }
private suspend fun parseBlock(skipLeadingBrace: Boolean = false): Statement { private suspend fun parseBlock(skipLeadingBrace: Boolean = false): Statement {
@@ -1600,7 +1643,8 @@ class Compiler(
private suspend fun parseVarDeclaration( private suspend fun parseVarDeclaration(
isMutable: Boolean, isMutable: Boolean,
visibility: Visibility, visibility: Visibility,
@Suppress("UNUSED_PARAMETER") isOpen: Boolean = false @Suppress("UNUSED_PARAMETER") isOpen: Boolean = false,
isStatic: Boolean = false
): Statement { ): Statement {
val nameToken = cc.next() val nameToken = cc.next()
val start = nameToken.pos val start = nameToken.pos
@@ -1622,6 +1666,21 @@ class Compiler(
val initialExpression = if (setNull) null else parseStatement(true) val initialExpression = if (setNull) null else parseStatement(true)
?: throw ScriptError(eqToken.pos, "Expected initializer expression") ?: throw ScriptError(eqToken.pos, "Expected initializer expression")
if (isStatic) {
// find objclass instance: this is tricky: this code executes in object initializer,
// when creating instance, but we need to execute it in the class initializer which
// is missing as for now. Add it to the compiler context?
// add there
// return
currentInitScope += statement {
val initValue = initialExpression?.execute(this)?.byValueCopy() ?: ObjNull
(thisObj as ObjClass).createClassField(name, initValue, isMutable, visibility, pos)
addItem(name, isMutable, initValue, visibility, ObjRecord.Type.Field)
ObjVoid
}
return NopStatement
}
return statement(nameToken.pos) { context -> return statement(nameToken.pos) { context ->
if (context.containsLocal(name)) if (context.containsLocal(name))
throw ScriptError(nameToken.pos, "Variable $name is already defined") throw ScriptError(nameToken.pos, "Variable $name is already defined")
@@ -1630,7 +1689,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
} }
} }
@@ -49,6 +49,10 @@ class CompilerContext(val tokens: List<Token>) {
throw ScriptError(at, message) throw ScriptError(at, message)
} }
fun syntaxError(message: String = "Syntax error"): Nothing {
throw ScriptError(currentPos(), message)
}
fun currentPos(): Pos = tokens[currentIndex].pos fun currentPos(): Pos = tokens[currentIndex].pos
/** /**
@@ -50,6 +50,9 @@ open class Scope(
fun raiseIllegalState(message: String = "Illegal argument error"): Nothing = fun raiseIllegalState(message: String = "Illegal argument error"): Nothing =
raiseError(ObjIllegalStateException(this, message)) raiseError(ObjIllegalStateException(this, message))
fun raiseIllegalAssignment(message: String): Nothing =
raiseError(ObjIllegalAssignmentException(this, message))
@Suppress("unused") @Suppress("unused")
fun raiseNoSuchElement(message: String = "No such element"): Nothing = fun raiseNoSuchElement(message: String = "No such element"): Nothing =
raiseError(ObjIllegalArgumentException(this, message)) raiseError(ObjIllegalArgumentException(this, message))
@@ -116,9 +119,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,9 +11,21 @@ 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
/**
* the scope for class methods, initialize class vars, etc.
*
* Important notice. When create a user class, e.g. from Lyng source, it should
* be set to a scope by compiler, so it could access local closure, etc. Otherwise,
* it will be initialized to default scope on first necessity, e.g. when used in
* external, kotlin classes with [addClassConst] and [addClassFn], etc.
*/
var classScope: Scope? = null
val allParentsSet: Set<ObjClass> = val allParentsSet: Set<ObjClass> =
parents.flatMap { parents.flatMap {
listOf(it) + it.allParentsSet listOf(it) + it.allParentsSet
@@ -21,9 +33,10 @@ open class ObjClass(
override val objClass: ObjClass by lazy { ObjClassType } override val objClass: ObjClass by lazy { ObjClassType }
// members: fields most often /**
* members: fields most often. These are called with [ObjInstance] withs ths [ObjInstance.objClass]
*/
private val members = mutableMapOf<String, ObjRecord>() private val members = mutableMapOf<String, ObjRecord>()
private val classMembers = mutableMapOf<String, ObjRecord>()
override fun toString(): String = className override fun toString(): String = className
@@ -38,6 +51,7 @@ open class ObjClass(
return instance return instance
} }
fun createField( fun createField(
name: String, name: String,
initialValue: Obj, initialValue: Obj,
@@ -51,6 +65,11 @@ open class ObjClass(
members[name] = ObjRecord(initialValue, isMutable, visibility) members[name] = ObjRecord(initialValue, isMutable, visibility)
} }
private fun initClassScope(): Scope {
if( classScope == null ) classScope = Scope()
return classScope!!
}
fun createClassField( fun createClassField(
name: String, name: String,
initialValue: Obj, initialValue: Obj,
@@ -58,10 +77,11 @@ open class ObjClass(
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
pos: Pos = Pos.builtIn pos: Pos = Pos.builtIn
) { ) {
val existing = classMembers[name] initClassScope()
val existing = classScope!!.objects[name]
if( existing != null) if( existing != null)
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes") throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
classMembers[name] = ObjRecord(initialValue, isMutable, visibility) classScope!!.addItem(name, isMutable, initialValue, visibility)
} }
fun addFn(name: String, isOpen: Boolean = false, code: suspend Scope.() -> Obj) { fun addFn(name: String, isOpen: Boolean = false, code: suspend Scope.() -> Obj) {
@@ -89,17 +109,28 @@ open class ObjClass(
?: throw ScriptError(atPos, "symbol doesn't exist: $name") ?: throw ScriptError(atPos, "symbol doesn't exist: $name")
override suspend fun readField(scope: Scope, name: String): ObjRecord { override suspend fun readField(scope: Scope, name: String): ObjRecord {
classMembers[name]?.let { classScope?.objects?.get(name)?.let {
return it if( it.visibility.isPublic ) return it
} }
return super.readField(scope, name) return super.readField(scope, name)
} }
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments): Obj { override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
return classMembers[name]?.value?.invoke(scope, this, args) ?: super.invokeInstanceMethod(scope, name, args) initClassScope().objects[name]?.let {
if( it.isMutable) it.value = newValue
else scope.raiseIllegalAssignment("can't assign $name is not mutable")
}
?: super.writeField(scope, name, newValue)
}
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments,
onNotFoundResult: Obj?): Obj {
return classScope?.objects?.get(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 = v
}
}
}
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,26 @@
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) {
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,21 +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?) {
if( lynonType == null ) encoder.encodeBinaryData(value.encodeToByteArray())
encoder.encodeCached(this) { encoder.encodeBinaryData(value.encodeToByteArray()) }
else
encoder.encodeBinaryData(value.encodeToByteArray())
} }
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 =
if( lynonType == null ) ObjString(decoder.unpackBinaryData().decodeToString())
decoder.decodeCached {
ObjString(decoder.unpackBinaryData().decodeToString())
}
else ObjString(decoder.unpackBinaryData().decodeToString())
}.apply { }.apply {
addFn("toInt") { addFn("toInt") {
ObjInt(thisAs<ObjString>().value.toLong()) ObjInt(thisAs<ObjString>().value.toLong())
@@ -2,12 +2,16 @@ package net.sergeych.lyng
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.ObjVoid
fun String.toSource(name: String = "eval"): Source = Source(name, this) fun String.toSource(name: String = "eval"): Source = Source(name, this)
sealed class ObjType { sealed class ObjType {
object Any : ObjType() object Any : ObjType()
object Int : ObjType() object Void: ObjType()
companion object {
}
} }
@@ -62,4 +66,8 @@ fun statement(isStaticConst: Boolean = false, isConst: Boolean = false, f: suspe
override suspend fun execute(scope: Scope): Obj = f(scope) override suspend fun execute(scope: Scope): Obj = f(scope)
} }
object NopStatement: Statement(true, true, ObjType.Void) {
override val pos: Pos = Pos.builtIn
override suspend fun execute(scope: Scope): Obj = ObjVoid
}
@@ -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,19 +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()]
type.objClass.deserialize(scope, this, type) if (type != LynonType.Other) {
type.objClass.deserialize(scope, this, type)
} else {
decodeClassObj(scope).deserialize(scope, this, null)
}
} }
// todo: rewrite/remove? private suspend fun decodeClassObj(scope: Scope): ObjClass {
suspend fun unpackObject(scope: Scope, type: ObjClass): Obj { val className = decodeObject(scope, ObjString.type, null) as ObjString
return type.deserialize(scope, this, null) 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()
@@ -4,21 +4,45 @@ import net.sergeych.bintools.ByteChunk
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
import net.sergeych.lyng.obj.* import net.sergeych.lyng.obj.*
enum class LynonType(val objClass: ObjClass) { enum class LynonType(val objClass: ObjClass, val defaultFrequency: Int = 1) {
Null(ObjNull.objClass), Null(ObjNull.objClass, 80),
Int0(ObjInt.type), Int0(ObjInt.type, 70),
IntNegative(ObjInt.type), IntNegative(ObjInt.type, 50),
IntPositive(ObjInt.type), IntPositive(ObjInt.type, 100),
String(ObjString.type), IntSigned(ObjInt.type, 30),
String(ObjString.type, 100),
Real(ObjReal.type), Real(ObjReal.type),
Bool(ObjBool.type), Bool(ObjBool.type, 80),
List(ObjList.type), List(ObjList.type, 70),
Map(ObjMap.type), Map(ObjMap.type, 40),
Set(ObjSet.type), Set(ObjSet.type),
Buffer(ObjBuffer.type), Buffer(ObjBuffer.type, 50),
Instant(ObjInstant.type), Instant(ObjInstant.type, 30),
Duration(ObjDuration.type), Duration(ObjDuration.type),
Other(Obj.rootObjectType); 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)) {
// println("encode add cache: ${cache.size}: $item: ${item::class.simpleName}")
packer()
cache[key] = cache.size cache[key] = cache.size
packer() } else {
// println("encode but not cache $item")
packer()
}
} }
} }
@@ -53,20 +83,78 @@ 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 encodeObj(scope: Scope, obj: Obj) { /**
obj.serialize(scope, this, null) * 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) {
obj.serialize(scope, this, overrideType)
}
}
suspend fun encodeCachedBytes(bytes: ByteArray) {
encodeCached(bytes) {
bout.compress(bytes)
}
} }
fun encodeBinaryData(data: ByteArray) { fun encodeBinaryData(data: ByteArray) {
@@ -1,38 +1,68 @@
package net.sergeych.lynon package net.sergeych.lynon
import net.sergeych.collections.SortedList import net.sergeych.collections.SortedList
import net.sergeych.lynon.Huffman.Alphabet
/** /**
* Experimental, reference implementation of Huffman trees and encoding. * Generic huffman encoding implementation using bits input/output and abstract [Alphabet].
*
* This is a reference huffman encoding implementation not yet ready;
* it was used to experiment with LZW, at the moment, LZW won the competition
* for compressed module format for its speed and sufficiently small size/
*
* This is byte-based compressor which makes it not too interesting.
*
* TODO: convert to use various source dictionary
*
* reason: version thant compress bytes is not too interesting; particular alphabets
* are often longer than byte bits and are often sparse, that requires another
* codes serialization implementation
*/ */
object Huffman { object Huffman {
/**
* Alphabet interface: source can be variable bit size codes, not just bytes,
* so the Huffman encoding is not limited to bytes. It works with any alphabet
* using its _ordinals_; encoding between source symbols and ordinals are
* performed by the alphabet. See [byteAlphabet] for example.
*/
interface Alphabet<T> {
val maxOrdinal: Int
/**
* Write correct symbol for the [ordinal] to the [bout]. This is
* the inverse of [ordinalOf] but as [T] could be variable bit size,
* we provide output bit stream.
*/
fun decodeOrdinalTo(bout: BitOutput, ordinal: Int)
/**
* Find the ordinal of the source symbol
*/
fun ordinalOf(value: T): Int
operator fun get(ordinal: Int): T
}
/**
* Alphabet for unsigned bytes, allows to encode bytes easily
*/
val byteAlphabet = object : Alphabet<UByte> {
override val maxOrdinal: Int
get() = 256
override fun decodeOrdinalTo(bout: BitOutput, ordinal: Int) {
bout.putBits(ordinal, 8)
}
override fun ordinalOf(value: UByte): Int = value.toInt()
override operator fun get(ordinal: Int): UByte = ordinal.toUByte()
}
sealed class Node(val freq: Int) : Comparable<Node> { sealed class Node(val freq: Int) : Comparable<Node> {
override fun compareTo(other: Node): Int { override fun compareTo(other: Node): Int {
return freq.compareTo(other.freq) return freq.compareTo(other.freq)
} }
abstract fun decode(bin: BitInput): Int? abstract fun decodeOrdinal(bin: BitInput): Int?
class Leaf(val value: Int, freq: Int) : Node(freq) { class Leaf(val ordinal: Int, freq: Int) : Node(freq) {
override fun toString(): String { override fun toString(): String {
return "[$value:$freq]" return "[$ordinal:$freq]"
} }
override fun decode(bin: BitInput): Int { override fun decodeOrdinal(bin: BitInput): Int {
return value//.also { println(": ${Char(value)}") } return ordinal//.also { println(": ${Char(value)}") }
} }
} }
@@ -41,33 +71,33 @@ object Huffman {
return "[${left.freq}<- :<$freq>: ->${right.freq}]" return "[${left.freq}<- :<$freq>: ->${right.freq}]"
} }
override fun decode(bin: BitInput): Int? { override fun decodeOrdinal(bin: BitInput): Int? {
return when (bin.getBitOrNull().also { print("$it") }) { return when (bin.getBitOrNull().also { print("$it") }) {
1 -> left.decode(bin) 1 -> left.decodeOrdinal(bin)
0 -> right.decode(bin) 0 -> right.decodeOrdinal(bin)
else -> null else -> null
} }
} }
} }
} }
data class Code(val symbol: Int, val bits: TinyBits) { data class Code(val ordinal: Int, val bits: TinyBits) {
val size by bits::size val size by bits::size
override fun toString(): String { override fun toString(): String {
return "[${Char(symbol)}:$size:$bits]" return "[$ordinal:$size:$bits]"
} }
} }
private fun generateCanonicCodes(tree: Node): List<Code?> { private fun generateCanonicCodes(tree: Node, alphabet: Alphabet<*>): List<Code?> {
val codes = MutableList<Code?>(256) { null } val codes = MutableList<Code?>(alphabet.maxOrdinal) { null }
fun traverse(node: Node, code: TinyBits) { fun traverse(node: Node, code: TinyBits) {
when (node) { when (node) {
is Node.Leaf -> is Node.Leaf ->
codes[node.value] = (Code(node.value, code)) codes[node.ordinal] = (Code(node.ordinal, code))
is Node.Internal -> { is Node.Internal -> {
traverse(node.left, code.insertBit(1)) traverse(node.left, code.insertBit(1))
@@ -77,17 +107,17 @@ object Huffman {
} }
traverse(tree, TinyBits()) traverse(tree, TinyBits())
return makeCanonical(codes) return makeCanonical(codes, alphabet)
} }
private fun makeCanonical(source: List<Code?>): List<Code?> { private fun makeCanonical(source: List<Code?>,alphabet: Alphabet<*>): List<Code?> {
val sorted = source.filterNotNull().sortedWith(canonicComparator) val sorted = source.filterNotNull().sortedWith(canonicComparator)
val canonical = MutableList<Code?>(256) { null } val canonical = MutableList<Code?>(alphabet.maxOrdinal) { null }
val first = sorted[0] val first = sorted[0]
val prevValue = first.copy(bits = TinyBits(0UL, first.bits.size)) val prevValue = first.copy(bits = TinyBits(0UL, first.bits.size))
canonical[first.symbol] = prevValue canonical[first.ordinal] = prevValue
var prev = prevValue.bits var prev = prevValue.bits
for (i in 1..<sorted.size) { for (i in 1..<sorted.size) {
@@ -96,7 +126,7 @@ object Huffman {
while (code.bits.size > bits.size) { while (code.bits.size > bits.size) {
bits = bits.insertBit(0) bits = bits.insertBit(0)
} }
canonical[code.symbol] = code.copy(bits = bits)//.also { println("$it") } canonical[code.ordinal] = code.copy(bits = bits)//.also { println("$it") }
prev = bits prev = bits
} }
return canonical return canonical
@@ -104,18 +134,21 @@ object Huffman {
private val canonicComparator = { a: Code, b: Code -> private val canonicComparator = { a: Code, b: Code ->
if (a.bits.size == b.bits.size) { if (a.bits.size == b.bits.size) {
a.symbol.compareTo(b.symbol) a.ordinal.compareTo(b.ordinal)
} else { } else {
a.bits.size.compareTo(b.bits.size) a.bits.size.compareTo(b.bits.size)
} }
} }
private fun buildTree(data: UByteArray): Node { private fun buildTree(data: Iterable<Int>,alphabet: Alphabet<*>): Node {
// println(data.toDump()) val frequencies = buildFrequencies(alphabet, data)
val frequencies = Array(256) { 0 } return buildTree(frequencies)
data.forEach { frequencies[it.toInt()]++ } }
val list = SortedList<Node>(*frequencies.mapIndexed { index, i -> Node.Leaf(index, i) }.filter { it.freq > 0 } private fun buildTree(frequencies: Array<Int>): Node {
// println(data.toDump())
val list: SortedList<Node> = SortedList(*frequencies.mapIndexed { index, frequency -> Node.Leaf(index, frequency) }.filter { it.freq > 0 }
.toTypedArray()) .toTypedArray())
// build the tree // build the tree
@@ -127,8 +160,18 @@ object Huffman {
return list[0] return list[0]
} }
fun decompressUsingCodes(bin: BitInput, codes: List<Code?>): UByteArray { private fun buildFrequencies(
val result = mutableListOf<UByte>() alphabet: Alphabet<*>,
data: Iterable<Int>
): Array<Int> {
val maxOrdinal = alphabet.maxOrdinal
val frequencies = Array(maxOrdinal) { 0 }
data.forEach { frequencies[it]++ }
return frequencies
}
fun decompressUsingCodes(bin: BitInput, codes: List<Code?>, alphabet: Alphabet<*>): BitArray {
val result = MemoryBitOutput()
val table = codes.filterNotNull().associateBy { it.bits } val table = codes.filterNotNull().associateBy { it.bits }
outer@ while (true) { outer@ while (true) {
@@ -139,12 +182,12 @@ object Huffman {
val data = table[input] val data = table[input]
if (data != null) { if (data != null) {
// println("Code found: ${data.bits} -> [${data.symbol.toChar()}]") // println("Code found: ${data.bits} -> [${data.symbol.toChar()}]")
result.add(data.symbol.toUByte()) alphabet.decodeOrdinalTo(result,data.ordinal)
break break
} }
} }
} }
return result.toUByteArray() return result.toBitArray()
} }
private fun serializeCanonicCodes(bout: BitOutput, codes: List<Code?>) { private fun serializeCanonicCodes(bout: BitOutput, codes: List<Code?>) {
@@ -167,11 +210,11 @@ object Huffman {
} }
} }
fun deserializeCanonicCodes(bin: BitInput): List<Code?> { fun deserializeCanonicCodes(bin: BitInput, alphabet: Alphabet<*>): List<Code?> {
val minSize = bin.unpackUnsigned().toInt() val minSize = bin.unpackUnsigned().toInt()
val sizeInBits = bin.unpackUnsigned().toInt() val sizeInBits = bin.unpackUnsigned().toInt()
val sorted = mutableListOf<Code>().also { codes -> val sorted = mutableListOf<Code>().also { codes ->
for (i in 0..<256) { for (i in 0..<alphabet.maxOrdinal) {
val s = bin.getBits(sizeInBits).toInt() val s = bin.getBits(sizeInBits).toInt()
if (s > 0) { if (s > 0) {
codes.add(Code(i, TinyBits(0U, s - 1 + minSize))) codes.add(Code(i, TinyBits(0U, s - 1 + minSize)))
@@ -179,66 +222,53 @@ object Huffman {
} }
}.sortedWith(canonicComparator) }.sortedWith(canonicComparator)
val result = MutableList<Code?>(256) { null } val result = MutableList<Code?>(alphabet.maxOrdinal) { null }
var prev = sorted[0].copy(bits = TinyBits(0U, sorted[0].bits.size)) var prev = sorted[0].copy(bits = TinyBits(0U, sorted[0].bits.size))
result[prev.symbol] = prev result[prev.ordinal] = prev
for (i in 1..<sorted.size) { for (i in 1..<sorted.size) {
val code = sorted[i] val code = sorted[i]
var bits = TinyBits(prev.bits.value + 1u, prev.bits.size) var bits = TinyBits(prev.bits.value + 1u, prev.bits.size)
while (bits.size < code.bits.size) bits = bits.insertBit(0) while (bits.size < code.bits.size) bits = bits.insertBit(0)
result[code.symbol] = code.copy(bits = bits).also { result[code.ordinal] = code.copy(bits = bits).also {
prev = it prev = it
} }
} }
return result return result
} }
fun compress(data: UByteArray): BitArray { // fun generateCanonicalCodes(frequencies: Iterable<Int>): List<Code?> {
//
// }
val root = buildTree(data) fun generateCanonicalCodes(frequencies: Array<Int>,alphabet: Alphabet<*>): List<Code?> =
generateCanonicCodes(buildTree(frequencies), alphabet)
val codes = generateCanonicCodes(root) fun <T>compress(plain: Iterable<T>,alphabet: Alphabet<T>): BitArray {
val source = plain.map { alphabet.ordinalOf(it) }
val root = buildTree(source,alphabet)
val codes = generateCanonicCodes(root, alphabet)
// serializa table // serializa table
// test encode: // test encode:
val bout = MemoryBitOutput() val bout = MemoryBitOutput()
serializeCanonicCodes(bout, codes) serializeCanonicCodes(bout, codes)
for (i in data) { for (i in source) {
val code = codes[i.toInt()]!! val code = codes[i]!!
// println(">> $code") // println(">> $code")
bout.putBits(code.bits) bout.putBits(code.bits)
} }
// println(bout.toBitArray().bytes.toDump()) // println(bout.toBitArray().bytes.toDump())
val compressed = bout.toBitArray() val compressed = bout.toBitArray()
// println("Size: ${compressed.bytes.size / data.size.toDouble() }")
// println("compression ratio: ${compressed.bytes.size / data.size.toDouble() }")
// test decompress
// val bin = MemoryBitInput(compressed)
// val codes2 = deserializeCanonicCodes(bin)
// for ((a, b) in codes.zip(codes2)) {
// if (a != b) {
// println("Codes mismatch: $a != $b")
// break
// }
// }
// require(codes == codes2)
// val result = decompressUsingCodes(bin, codes2)
//
//// println(result.toUByteArray().toDump())
// check(data contentEquals result.toUByteArray())
// if( !(data contentEquals result.toUByteArray()) )
// throw RuntimeException("Data mismatch")
// println(data.toDump())
//
return compressed return compressed
} }
fun decompress(bin: BitInput): UByteArray { fun <T>decompress(bin: BitInput,alphabet: Alphabet<T>): UByteArray {
val codes = deserializeCanonicCodes(bin) val codes = deserializeCanonicCodes(bin, alphabet)
return decompressUsingCodes(bin, codes) return decompressUsingCodes(bin, codes, alphabet).asUbyteArray()
} }
} }
+46
View File
@@ -0,0 +1,46 @@
import kotlinx.coroutines.test.runTest
import net.sergeych.lyng.eval
import kotlin.test.Test
class OOTest {
@Test
fun testClassProps() = runTest {
eval("""
import lyng.time
class Point(x,y) {
static val origin = Point(0,0)
static var center = origin
}
assertEquals(Point(0,0), Point.origin)
assertEquals(Point(0,0), Point.center)
Point.center = Point(1,2)
assertEquals(Point(0,0), Point.origin)
assertEquals(Point(1,2), Point.center)
""".trimIndent())
}
@Test
fun testClassMethods() = runTest {
eval("""
import lyng.time
class Point(x,y) {
private static var data = null
static fun getData() { data }
static fun setData(value) {
data = value
callFrom()
}
static fun callFrom() {
data = data + "!"
}
}
assertEquals(Point(0,0), Point(0,0) )
assertEquals(null, Point.getData() )
Point.setData("foo")
assertEquals( "foo!", Point.getData() )
""".trimIndent())
}
}
@@ -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())
}
} }
+266 -83
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()
@@ -60,8 +65,8 @@ class LynonTests {
bout.putBit(1) bout.putBit(1)
bout.putBit(0) bout.putBit(0)
bout.putBit(1) bout.putBit(1)
bout.putBits( 0, 7) bout.putBits(0, 7)
bout.putBits( 3, 2) bout.putBits(3, 2)
val x = bout.toBitArray() val x = bout.toBitArray()
assertEquals(1, x[0]) assertEquals(1, x[0])
assertEquals(1, x[1]) assertEquals(1, x[1])
@@ -144,34 +149,43 @@ 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()
val encoder = LynonEncoder(bout) val encoder = LynonEncoder(bout)
val s = "Hello, World!".toObj() val s = "Hello, World!".toObj()
val scope = Scope() val scope = Scope()
encoder.encodeObj(scope, s) // 1 encoder.encodeObject(scope, s) // 1
encoder.encodeObj(scope, s) encoder.encodeObject(scope, s)
encoder.encodeObj(scope, s) encoder.encodeObject(scope, s)
encoder.encodeObj(scope, s) encoder.encodeObject(scope, s)
encoder.encodeObj(scope, s) encoder.encodeObject(scope, s)
encoder.encodeObj(scope, s) encoder.encodeObject(scope, s)
encoder.encodeObj(scope, s) encoder.encodeObject(scope, s)
encoder.encodeObj(scope, s) // 8 encoder.encodeObject(scope, s) // 8
val decoder = LynonDecoder(MemoryBitInput(bout)) val decoder = LynonDecoder(MemoryBitInput(bout))
val s1 = decoder.unpackObject(scope, ObjString.type) // 1 val s1 = decoder.decodeObject(scope, ObjString.type) // 1
assertEquals(s, s1) assertEquals(s, s1)
assertNotSame(s, s1) assertNotSame(s, s1)
val s2 = decoder.unpackObject(scope, ObjString.type) val s2 = decoder.decodeObject(scope, ObjString.type)
assertEquals(s, s2) assertEquals(s, s2)
assertSame(s1, s2) assertSame(s1, s2)
assertSame(s1, decoder.unpackObject(scope, ObjString.type)) assertSame(s1, decoder.decodeObject(scope, ObjString.type))
assertSame(s1, decoder.unpackObject(scope, ObjString.type)) assertSame(s1, decoder.decodeObject(scope, ObjString.type))
assertSame(s1, decoder.unpackObject(scope, ObjString.type)) assertSame(s1, decoder.decodeObject(scope, ObjString.type))
assertSame(s1, decoder.unpackObject(scope, ObjString.type)) assertSame(s1, decoder.decodeObject(scope, ObjString.type))
assertSame(s1, decoder.unpackObject(scope, ObjString.type)) assertSame(s1, decoder.decodeObject(scope, ObjString.type))
assertSame(s1, decoder.unpackObject(scope, ObjString.type)) // 8 assertSame(s1, decoder.decodeObject(scope, ObjString.type)) // 8
} }
@Test @Test
@@ -182,12 +196,12 @@ class LynonTests {
val encoder = LynonPacker() val encoder = LynonPacker()
val scope = Scope() val scope = Scope()
for (s in source) { for (s in source) {
encoder.encodeObj(scope, s) encoder.encodeObject(scope, s)
} }
val decoder = LynonUnpacker(encoder) val decoder = LynonUnpacker(encoder)
val restored = mutableListOf<Obj>() val restored = mutableListOf<Obj>()
for (i in source.indices) { for (i in source.indices) {
restored.add(decoder.unpackObject(scope, ObjString.type)) restored.add(decoder.decodeObject(scope, ObjString.type))
} }
assertEquals(restored, source) assertEquals(restored, source)
} }
@@ -196,58 +210,59 @@ class LynonTests {
fun testUnpackBoolean() = runTest { fun testUnpackBoolean() = runTest {
val scope = Scope() val scope = Scope()
val decoder = LynonUnpacker(LynonPacker().apply { val decoder = LynonUnpacker(LynonPacker().apply {
encodeObj(scope, ObjBool(true)) encodeObject(scope, ObjBool(true))
encodeObj(scope, ObjBool(false)) encodeObject(scope, ObjBool(false))
encodeObj(scope, ObjBool(true)) encodeObject(scope, ObjBool(true))
encodeObj(scope, ObjBool(true)) encodeObject(scope, ObjBool(true))
}) })
assertEquals(ObjTrue, decoder.unpackObject(scope, ObjBool.type)) assertEquals(ObjTrue, decoder.decodeObject(scope, ObjBool.type))
assertEquals(ObjFalse, decoder.unpackObject(scope, ObjBool.type)) assertEquals(ObjFalse, decoder.decodeObject(scope, ObjBool.type))
assertEquals(ObjTrue, decoder.unpackObject(scope, ObjBool.type)) assertEquals(ObjTrue, decoder.decodeObject(scope, ObjBool.type))
assertEquals(ObjTrue, decoder.unpackObject(scope, ObjBool.type)) assertEquals(ObjTrue, decoder.decodeObject(scope, ObjBool.type))
} }
@Test @Test
fun testUnpackReal() = runTest { fun testUnpackReal() = runTest {
val scope = Scope() val scope = Scope()
val decoder = LynonUnpacker(LynonPacker().apply { val decoder = LynonUnpacker(LynonPacker().apply {
encodeObj(scope, ObjReal(-Math.PI)) encodeObject(scope, ObjReal(-Math.PI))
encodeObj(scope, ObjReal(Math.PI)) encodeObject(scope, ObjReal(Math.PI))
encodeObj(scope, ObjReal(-Math.PI)) encodeObject(scope, ObjReal(-Math.PI))
encodeObj(scope, ObjReal(Math.PI)) encodeObject(scope, ObjReal(Math.PI))
encodeObj(scope, ObjReal(Double.NaN)) encodeObject(scope, ObjReal(Double.NaN))
encodeObj(scope, ObjReal(Double.NEGATIVE_INFINITY)) encodeObject(scope, ObjReal(Double.NEGATIVE_INFINITY))
encodeObj(scope, ObjReal(Double.POSITIVE_INFINITY)) encodeObject(scope, ObjReal(Double.POSITIVE_INFINITY))
encodeObj(scope, ObjReal(Double.MIN_VALUE)) encodeObject(scope, ObjReal(Double.MIN_VALUE))
encodeObj(scope, ObjReal(Double.MAX_VALUE)) encodeObject(scope, ObjReal(Double.MAX_VALUE))
}) })
assertEquals(ObjReal(-Math.PI), decoder.unpackObject(scope, ObjReal.type)) assertEquals(ObjReal(-Math.PI), decoder.decodeObject(scope, ObjReal.type))
assertEquals(ObjReal(Math.PI), decoder.unpackObject(scope, ObjReal.type)) assertEquals(ObjReal(Math.PI), decoder.decodeObject(scope, ObjReal.type))
assertEquals(ObjReal(-Math.PI), decoder.unpackObject(scope, ObjReal.type)) assertEquals(ObjReal(-Math.PI), decoder.decodeObject(scope, ObjReal.type))
assertEquals(ObjReal(Math.PI), decoder.unpackObject(scope, ObjReal.type)) assertEquals(ObjReal(Math.PI), decoder.decodeObject(scope, ObjReal.type))
assert((decoder.unpackObject(scope, ObjReal.type)).toDouble().isNaN()) assert((decoder.decodeObject(scope, ObjReal.type)).toDouble().isNaN())
assertEquals(ObjReal(Double.NEGATIVE_INFINITY), decoder.unpackObject(scope, ObjReal.type)) assertEquals(ObjReal(Double.NEGATIVE_INFINITY), decoder.decodeObject(scope, ObjReal.type))
assertEquals(ObjReal(Double.POSITIVE_INFINITY), decoder.unpackObject(scope, ObjReal.type)) assertEquals(ObjReal(Double.POSITIVE_INFINITY), decoder.decodeObject(scope, ObjReal.type))
assertEquals(ObjReal(Double.MIN_VALUE), decoder.unpackObject(scope, ObjReal.type)) assertEquals(ObjReal(Double.MIN_VALUE), decoder.decodeObject(scope, ObjReal.type))
assertEquals(ObjReal(Double.MAX_VALUE), decoder.unpackObject(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()
val decoder = LynonUnpacker(LynonPacker().apply { val decoder = LynonUnpacker(LynonPacker().apply {
encodeObj(scope, ObjInt(0)) encodeObject(scope, ObjInt(0))
encodeObj(scope, ObjInt(-1)) encodeObject(scope, ObjInt(-1))
encodeObj(scope, ObjInt(23)) encodeObject(scope, ObjInt(23))
encodeObj(scope, ObjInt(Long.MIN_VALUE)) encodeObject(scope, ObjInt(Long.MIN_VALUE))
encodeObj(scope, ObjInt(Long.MAX_VALUE)) encodeObject(scope, ObjInt(Long.MAX_VALUE))
encodeObj(scope, ObjInt(Long.MAX_VALUE)) encodeObject(scope, ObjInt(Long.MAX_VALUE))
}) })
assertEquals(ObjInt(0), decoder.unpackObject(scope, ObjInt.type)) assertEquals(ObjInt(0), decoder.decodeObject(scope, ObjInt.type))
assertEquals(ObjInt(-1), decoder.unpackObject(scope, ObjInt.type)) assertEquals(ObjInt(-1), decoder.decodeObject(scope, ObjInt.type))
assertEquals(ObjInt(23), decoder.unpackObject(scope, ObjInt.type)) assertEquals(ObjInt(23), decoder.decodeObject(scope, ObjInt.type))
assertEquals(ObjInt(Long.MIN_VALUE), decoder.unpackObject(scope, ObjInt.type)) assertEquals(ObjInt(Long.MIN_VALUE), decoder.decodeObject(scope, ObjInt.type))
assertEquals(ObjInt(Long.MAX_VALUE), decoder.unpackObject(scope, ObjInt.type)) assertEquals(ObjInt(Long.MAX_VALUE), decoder.decodeObject(scope, ObjInt.type))
assertEquals(ObjInt(Long.MAX_VALUE), decoder.unpackObject(scope, ObjInt.type)) assertEquals(ObjInt(Long.MAX_VALUE), decoder.decodeObject(scope, ObjInt.type))
} }
@Test @Test
@@ -272,15 +287,17 @@ class LynonTests {
val original = Files.readString(Path.of("../sample_texts/dikkens_hard_times.txt")) val original = Files.readString(Path.of("../sample_texts/dikkens_hard_times.txt"))
@Test @Test
fun testEncodeNullsAndInts() = runTest{ fun testEncodeNullsAndInts() = runTest {
testScope().eval(""" testScope().eval(
"""
testEncode(null) testEncode(null)
testEncode(0) testEncode(0)
""".trimIndent()) """.trimIndent()
)
} }
@Test @Test
fun testBufferEncoderInterop() = runTest{ fun testBufferEncoderInterop() = runTest {
val bout = MemoryBitOutput() val bout = MemoryBitOutput()
bout.putBits(0, 1) bout.putBits(0, 1)
bout.putBits(1, 4) bout.putBits(1, 4)
@@ -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
@@ -371,7 +395,7 @@ class LynonTests {
assertEquals("011101", a0.toString()) assertEquals("011101", a0.toString())
val bin = MemoryBitInput(MemoryBitOutput().apply { putBits(a0) }) val bin = MemoryBitInput(MemoryBitOutput().apply { putBits(a0) })
var result = TinyBits() var result = TinyBits()
for( i in a0.indices) result = result.insertBit(bin.getBit()) for (i in a0.indices) result = result.insertBit(bin.getBit())
assertEquals(a0, result) assertEquals(a0, result)
} }
@@ -382,32 +406,53 @@ class LynonTests {
println("Original : ${x.size}") println("Original : ${x.size}")
val lzw = LZW.compress(x).bytes val lzw = LZW.compress(x).bytes
println("LZW : ${lzw.size}") println("LZW : ${lzw.size}")
val ba = Huffman.compress(x) val ba = Huffman.compress(x, Huffman.byteAlphabet)
val huff = ba.bytes val huff = ba.bytes
println("Huffman : ${huff.size}") println("Huffman : ${huff.size}")
val lzwhuff = Huffman.compress(lzw).bytes val lzwhuff = Huffman.compress(lzw, Huffman.byteAlphabet).bytes
println("LZW+HUFF : ${lzwhuff.size}") println("LZW+HUFF : ${lzwhuff.size}")
val compressed = Huffman.compress(x) val compressed = Huffman.compress(x, Huffman.byteAlphabet)
val decompressed = Huffman.decompress(compressed.toBitInput()) val decompressed = Huffman.decompress(compressed.toBitInput(), Huffman.byteAlphabet)
assertContentEquals(x, decompressed) assertContentEquals(x, decompressed)
} }
@Test
fun testGenerateCanonicalHuffmanCodes() {
val frequencies = LynonType.entries.map { it.defaultFrequency }.toTypedArray()
val alphabet = object : Huffman.Alphabet<LynonType> {
override val maxOrdinal = LynonType.entries.size
override fun decodeOrdinalTo(bout: BitOutput, ordinal: Int) {
throw NotImplementedError()
}
override fun get(ordinal: Int): LynonType {
return LynonType.entries[ordinal]
}
override fun ordinalOf(value: LynonType): Int = value.ordinal
}
for (code in Huffman.generateCanonicalCodes(frequencies, alphabet)) {
println("${code?.bits}: ${code?.ordinal?.let { LynonType.entries[it] }}")
}
}
@Test @Test
fun testBitListSmall() { fun testBitListSmall() {
var t = TinyBits() var t = TinyBits()
for( i in listOf(1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1) ) for (i in listOf(1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1))
t = t.insertBit(i) t = t.insertBit(i)
assertEquals(1, t[0]) assertEquals(1, t[0])
assertEquals(1, t[1]) assertEquals(1, t[1])
assertEquals(0, t[2]) assertEquals(0, t[2])
assertEquals("1101000111101",t.toString()) assertEquals("1101000111101", t.toString())
t[0] = 0 t[0] = 0
t[1] = 0 t[1] = 0
t[2] = 1 t[2] = 1
assertEquals("0011000111101",t.toString()) assertEquals("0011000111101", t.toString())
t[12] = 0 t[12] = 0
t[11] = 1 t[11] = 1
assertEquals("0011000111110",t.toString()) assertEquals("0011000111110", t.toString())
} }
@Test @Test
@@ -416,10 +461,10 @@ class LynonTests {
val bout = MemoryBitOutput() val bout = MemoryBitOutput()
assertEquals("1101", bitListOf(1, 1, 0, 1).toString()) assertEquals("1101", bitListOf(1, 1, 0, 1).toString())
bout.putBits(bitListOf(1, 1, 0, 1)) bout.putBits(bitListOf(1, 1, 0, 1))
bout.putBits(bitListOf( 0, 0)) bout.putBits(bitListOf(0, 0))
bout.putBits(bitListOf( 0, 1, 1, 1, 1, 0, 1)) bout.putBits(bitListOf(0, 1, 1, 1, 1, 0, 1))
val x = bout.toBitArray() val x = bout.toBitArray()
assertEquals("1101000111101",x.toString()) assertEquals("1101000111101", x.toString())
} }
@@ -451,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())
}
} }