Compare commits
12
Commits
12b209c724
...
0.8.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de71c7c8ec | ||
|
|
be370dfdef | ||
|
|
53a6a88924 | ||
|
|
2c2dae4d85 | ||
|
|
63b2808109 | ||
|
|
4165da5e81 | ||
|
|
af463163bb | ||
|
|
6df06a6911 | ||
|
|
f805e1ee82 | ||
|
|
790cce0d24 | ||
|
|
2339130241 | ||
|
|
d7bd159fcb |
No files matched your search
@@ -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
@@ -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
@@ -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
|
||||||
|
|||||||
@@ -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,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())
|
||||||
|
|||||||
@@ -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,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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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())
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference in new issue
Block a user