Compare commits

..
13 changed files with 327 additions and 21 deletions

No files matched your search

@@ -0,0 +1,28 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Tests in 'lyng.lynglib.jvmTest'" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings>
<option name="executionName" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="externalSystemIdString" value="GRADLE" />
<option name="scriptParameters" value="" />
<option name="taskDescriptions">
<list />
</option>
<option name="taskNames">
<list>
<option value=":lynglib:cleanJvmTest" />
<option value=":lynglib:jvmTest" />
</list>
</option>
<option name="vmOptions" />
</ExternalSystemSettings>
<ExternalSystemDebugServerProcess>false</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<ExternalSystemDebugDisabled>false</ExternalSystemDebugDisabled>
<DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>true</RunAsTest>
<GradleProfilingDisabled>false</GradleProfilingDisabled>
<GradleCoverageDisabled>false</GradleCoverageDisabled>
<method v="2" />
</configuration>
</component>
@@ -1,3 +1,20 @@
<!--
~ Copyright 2025 Sergey S. Chernov real.sergeych@gmail.com
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<component name="ProjectRunConfigurationManager"> <component name="ProjectRunConfigurationManager">
<configuration default="false" name="lyng:site [jsBrowserDevelopmentRun]" type="GradleRunConfiguration" factoryName="Gradle"> <configuration default="false" name="lyng:site [jsBrowserDevelopmentRun]" type="GradleRunConfiguration" factoryName="Gradle">
<ExternalSystemSettings> <ExternalSystemSettings>
@@ -17,8 +34,11 @@
</ExternalSystemSettings> </ExternalSystemSettings>
<ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess> <ExternalSystemDebugServerProcess>true</ExternalSystemDebugServerProcess>
<ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess> <ExternalSystemReattachDebugProcess>true</ExternalSystemReattachDebugProcess>
<ExternalSystemDebugDisabled>false</ExternalSystemDebugDisabled>
<DebugAllEnabled>false</DebugAllEnabled> <DebugAllEnabled>false</DebugAllEnabled>
<RunAsTest>false</RunAsTest> <RunAsTest>false</RunAsTest>
<GradleProfilingDisabled>true</GradleProfilingDisabled>
<GradleCoverageDisabled>true</GradleCoverageDisabled>
<method v="2" /> <method v="2" />
</configuration> </configuration>
</component> </component>
+14
View File
@@ -68,6 +68,20 @@ These, again, does the thing:
>>> void >>> void
## map and mapNotNull
Used to transform either the whole iterable stream or also skipping som elements from it:
val source = [1,2,3,4]
// transform every element to string or null:
assertEquals(["n1", "n2", null, "n4"], source.map { if( it == 3 ) null else "n"+it } )
// transform every element to stirng, skipping 3:
assertEquals(["n1", "n2", "n4"], source.mapNotNull { if( it == 3 ) null else "n"+it } )
>>> void
## Instance methods: ## Instance methods:
| fun/method | description | | fun/method | description |
+66
View File
@@ -0,0 +1,66 @@
### Lynon class-name resolution: current behavior and roadmap for fully-qualified names
#### Current behavior (as of Dec 2025)
- The Lynon encoder writes the class name for user-defined objects as a simple name taken from `obj.objClass.classNameObj` (e.g., `"Vault"`). It does not encode the fully-qualified path (e.g., `"ns.sub.Vault"`).
- During decoding, `LynonDecoder.decodeClassObj` must resolve this simple name to an `ObjClass` using the provided `Scope`.
- Historically, `decodeClassObj` relied only on `scope.get(name)`. In some scopes this missed symbols that were import-visible at compile time, while `scope.eval(name)` could still find them. This mismatch caused occasional failures such as:
- `scope.eval("Vault")` ← returns `ObjClass`
- `scope.get("Vault")` ← returns `null`
To address this, the decoder now uses a robust, import-aware resolution strategy:
1) Try `scope.get(name)`
2) Try `scope.chainLookupWithMembers(name)`
3) Find the nearest `ModuleScope` and check its locals and its parent/root locals/members
4) Check `scope.currentImportProvider.rootScope` globals (e.g., stdlib)
5) As a last resort, try `scope.eval(name)` and validate the result is an `ObjClass`
This resolves the previously observed mismatch, including simple names like `"Vault"` defined in modules or visible via imports.
Notes:
- Tests confirm that the simple-name path is stable after this change.
- Tests for fully qualified names were avoided because the encoder does not currently emit qualified names, and runtime namespaces (like a value-bound `ns`) are not guaranteed to exist for `eval("ns.sub.Vault")` in all scopes.
#### Limitations
- Decoder receives only simple names. If two different classes with the same simple name exist in different packages/modules, decoding could be ambiguous unless the surrounding scope makes the intended one discoverable.
- Using `eval` as last fallback implies compilation at decode-time in rare cases. While this is robust, a purely structural resolution is preferable for determinism and performance.
#### Roadmap: support fully-qualified class names
If/when we decide to encode fully-qualified names, we should implement both encoder and decoder changes in lockstep.
Proposed plan:
1) Encoder changes
- When serializing a user-defined object, emit the fully-qualified class path (e.g., `"ns.sub.Vault"`) alongside or instead of the simple class name.
- Consider a feature flag or versioning in Lynon type records to maintain backward compatibility with existing streams that carry only the simple name.
2) Decoder changes
- If the encoded name contains dots, treat it as a dotted path. Implement a path resolver that:
- Splits the name by `.` into segments: `[ns, sub, Vault]`.
- Resolves the first segment with the same multi-scope strategy used today for simple names (steps 1–4 above), without relying on `eval`.
- For remaining segments, traverse members/namespace tables:
- If the current object is an `ObjNamespace` or similar container, look up the next segment in its members map.
- If the current object is an `ObjClass`, look up the next segment with `getInstanceMemberOrNull` (for nested classes or class-level members), if applicable.
- Continue until the final segment is reached; verify the target is an `ObjClass`.
- If this structural path resolution fails, optionally fall back to `scope.eval(fullyQualifiedName)` in development modes, but prefer to avoid it in production for determinism.
3) Runtime namespace objects (optional but recommended)
- Introduce or formalize an `ObjNamespace` (or reuse existing) that represents packages/modules at runtime and can be placed in scope bindings, enabling deterministic traversal of `ns.sub` without compiling code.
- Ensure imports or `package` declarations materialize such namespace objects in accessible scopes when required, so dotted paths can be resolved purely structurally by the decoder.
4) Backward compatibility and migration
- Maintain decoding support for simple names for older data.
- Prefer fully-qualified names when writing new data once the feature is available.
- Provide configuration to control which form to emit.
5) Testing strategy
- Add tests that:
- Encode/decode with simple names (legacy) and confirm existing behavior.
- Encode/decode with fully-qualified names (new) and confirm dotted-path traversal works without `eval`.
- Cover ambiguity resolution when same simple name exists in multiple namespaces.
#### Summary
Today, Lynon encodes and decodes class names using simple names only. The decoder’s name resolution was strengthened to be import-aware and robust, fixing cases where `eval` sees a class that `get` does not. To support fully-qualified names in the future, we plan to emit dotted class paths and implement a structural dotted-path resolver in the decoder (with optional runtime namespace objects) to avoid relying on `eval` and to keep decoding deterministic and unambiguous.
@@ -173,31 +173,44 @@ class Script(
val a = requiredArg<Obj>(0) val a = requiredArg<Obj>(0)
val b = requiredArg<Obj>(1) val b = requiredArg<Obj>(1)
if (a.compareTo(this, b) != 0) if (a.compareTo(this, b) != 0)
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect(this)} == ${b.inspect(this)}")) raiseError(
ObjAssertionFailedException(
this,
"Assertion failed: ${a.inspect(this)} == ${b.inspect(this)}"
)
)
} }
// alias used in tests // alias used in tests
addVoidFn("assertEqual") { addVoidFn("assertEqual") {
val a = requiredArg<Obj>(0) val a = requiredArg<Obj>(0)
val b = requiredArg<Obj>(1) val b = requiredArg<Obj>(1)
if (a.compareTo(this, b) != 0) if (a.compareTo(this, b) != 0)
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect(this)} == ${b.inspect(this)}")) raiseError(
ObjAssertionFailedException(
this,
"Assertion failed: ${a.inspect(this)} == ${b.inspect(this)}"
)
)
} }
addVoidFn("assertNotEquals") { addVoidFn("assertNotEquals") {
val a = requiredArg<Obj>(0) val a = requiredArg<Obj>(0)
val b = requiredArg<Obj>(1) val b = requiredArg<Obj>(1)
if (a.compareTo(this, b) == 0) if (a.compareTo(this, b) == 0)
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect(this)} != ${b.inspect(this)}")) raiseError(
ObjAssertionFailedException(
this,
"Assertion failed: ${a.inspect(this)} != ${b.inspect(this)}"
)
)
} }
addFn("assertThrows") { addFn("assertThrows") {
val code = requireOnlyArg<Statement>() val code = requireOnlyArg<Statement>()
val result = try { val result = try {
code.execute(this) code.execute(this)
null null
} } catch (e: ExecutionError) {
catch( e: ExecutionError ) {
e.errorObject e.errorObject
} } catch (_: ScriptError) {
catch (_: ScriptError) {
ObjNull ObjNull
} }
result ?: raiseError(ObjAssertionFailedException(this, "Expected exception but nothing was thrown")) result ?: raiseError(ObjAssertionFailedException(this, "Expected exception but nothing was thrown"))
@@ -131,7 +131,7 @@ object CompletionEngineLight {
} }
is MiniClassDecl -> add(CompletionItem(d.name, Kind.Class_)) is MiniClassDecl -> add(CompletionItem(d.name, Kind.Class_))
is MiniValDecl -> add(CompletionItem(d.name, Kind.Value, typeText = typeOf(d.type))) is MiniValDecl -> add(CompletionItem(d.name, Kind.Value, typeText = typeOf(d.type)))
else -> add(CompletionItem(d.name, Kind.Value)) // else -> add(CompletionItem(d.name, Kind.Value))
} }
} }
@@ -197,9 +197,20 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
!it.key.contains("::") && it.value.visibility.isPublic && it.value.type.serializable !it.key.contains("::") && it.value.visibility.isPublic && it.value.type.serializable
} }
override fun toString(): String { override suspend fun toString(scope: Scope, calledFromLyng: Boolean): ObjString {
val fields = publicFields.map { "${it.key}=${it.value.value}" }.joinToString(",") return ObjString(buildString {
return "${objClass.className}($fields)" append("${objClass.className}(")
var first = true
for ((name, value) in publicFields) {
if (first) first = false else append(",")
append("$name=${value.value.toString(scope)}")
}
append(")")
})
}
override suspend fun inspect(scope: Scope): String {
return toString(scope).value
} }
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) { override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
@@ -158,6 +158,23 @@ val ObjIterable by lazy {
ObjList(result) ObjList(result)
} }
addFnDoc(
name = "mapNotNull",
doc = "Transform elements by applying the given lambda unless it returns null.",
params = listOf(ParamDoc("transform")),
returns = type("lyng.List"),
isOpen = true,
moduleName = "lyng.stdlib"
) {
val fn = requiredArg<Statement>(0)
val result = mutableListOf<Obj>()
thisObj.toFlow(this).collect {
val transformed = fn.call(this, it)
if( transformed != ObjNull) result += transformed
}
ObjList(result)
}
addFnDoc( addFnDoc(
name = "take", name = "take",
doc = "Take the first N elements and return them as a list.", doc = "Take the first N elements and return them as a list.",
@@ -198,6 +198,18 @@ class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
return JsonArray(list.map { it.toJson(scope) }) return JsonArray(list.map { it.toJson(scope) })
} }
override suspend fun toString(scope: Scope, calledFromLyng: Boolean): ObjString {
return ObjString(buildString {
append("[")
var first = true
for (v in list) {
if (first) first = false else append(",")
append(v.toString(scope).value)
}
append("]")
})
}
companion object { companion object {
val type = object : ObjClass("List", ObjArray) { val type = object : ObjClass("List", ObjArray) {
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj { override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
@@ -52,8 +52,8 @@ class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
else -> scope.raiseIndexOutOfBounds() else -> scope.raiseIndexOutOfBounds()
} }
override fun toString(): String { override suspend fun toString(scope: Scope, calledFromLyng: Boolean): ObjString {
return "$key=>$value" return ObjString("(${key.toString(scope).value} => ${value.toString(scope).value})")
} }
override val objClass = type override val objClass = type
@@ -1625,7 +1625,7 @@ class ListLiteralRef(private val entries: List<ListEntry>) : ObjRef {
when (elements) { when (elements) {
is ObjList -> { is ObjList -> {
// Grow underlying array once when possible // Grow underlying array once when possible
if (list is ArrayList) list.ensureCapacity(list.size + elements.list.size) list.ensureCapacity(list.size + elements.list.size)
list.addAll(elements.list) list.addAll(elements.list)
} }
else -> scope.raiseError("Spread element must be list") else -> scope.raiseError("Spread element must be list")
@@ -78,11 +78,72 @@ open class LynonDecoder(val bin: BitInput, val settings: LynonSettings = LynonSe
private suspend fun decodeClassObj(scope: Scope): ObjClass { private suspend fun decodeClassObj(scope: Scope): ObjClass {
val className = decodeObject(scope, ObjString.type, null) as ObjString val className = decodeObject(scope, ObjString.type, null) as ObjString
return scope.get(className.value)?.value?.let { val name = className.value
// 1) Try direct lookup in this scope (locals/parents/this members)
scope.get(name)?.value?.let {
if (it !is ObjClass) if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}") scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
it return it
} ?: scope.raiseSymbolNotFound("can't deserialize: not found type $className") }
// 2) Try ancestry lookup including instance/class members, but without invoking overridden get
scope.chainLookupWithMembers(name)?.value?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
return it
}
// 3) Try to find nearest ModuleScope and check its locals and its parent (root) locals
run {
var s: Scope? = scope
val visited = HashSet<Long>(4)
while (s != null) {
if (!visited.add(s.frameId)) break
if (s is net.sergeych.lyng.ModuleScope) {
s.objects[name]?.value?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
return it
}
s.localBindings[name]?.value?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
return it
}
s.parent?.let { p ->
p.objects[name]?.value?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
return it
}
p.localBindings[name]?.value?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
return it
}
p.thisObj.objClass.getInstanceMemberOrNull(name)?.value?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
return it
}
}
break
}
s = s.parent
}
}
// 4) Try ImportProvider root scope globals (e.g., stdlib)
runCatching { scope.currentImportProvider.rootScope.objects[name]?.value }.getOrNull()?.let {
if (it !is ObjClass)
scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
return it
}
// // 5) As a final fallback, try to evaluate the name in this scope using the compiler
// runCatching { scope.eval(name) }.getOrNull()?.let {
// if (it !is ObjClass)
// scope.raiseClassCastError("Expected obj class but got ${it::class.simpleName}")
// return it
// }
// If everything failed, raise an informative error
scope.raiseSymbolNotFound("can't deserialize: not found type ${className}")
} }
suspend fun decodeAnyList(scope: Scope, fixedSize: Int? = null): MutableList<Obj> { suspend fun decodeAnyList(scope: Scope, fixedSize: Int? = null): MutableList<Obj> {
+68 -4
View File
@@ -25,10 +25,7 @@ import net.sergeych.lyng.obj.*
import net.sergeych.lynon.* import net.sergeych.lynon.*
import java.nio.file.Files import java.nio.file.Files
import java.nio.file.Path import java.nio.file.Path
import kotlin.test.Test import kotlin.test.*
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class LynonTests { class LynonTests {
@@ -44,6 +41,73 @@ class LynonTests {
assertEquals(3, sizeInTetrades(257u)) assertEquals(3, sizeInTetrades(257u))
} }
@Ignore("This is not yet implemented")
@Test
fun decodeClassObj_shouldResolveDottedQualifiedNames() = runTest {
// Define nested namespaces and a class with a qualified name via eval
val module = net.sergeych.lyng.Script.defaultImportManager.newModule()
module.eval(
"""
package ns.sub
class Vault() { fun toString() { "ns.sub.Vault" } }
""".trimIndent()
)
val child = module.createChildScope(module.pos)
// Sanity: eval resolves both qualified and unqualified in the same module context
val qualified = child.eval("ns.sub.Vault")
assertTrue(qualified is ObjClass)
val inst = child.eval("ns.sub.Vault()")
assertTrue(inst is ObjInstance)
// Encode and decode instance; decoder should resolve class by its encoded name
val bout = MemoryBitOutput()
val enc = LynonEncoder(bout)
enc.encodeAny(child, inst)
val bin = MemoryBitInput(bout.toBitArray())
val dec = LynonDecoder(bin)
val decoded = dec.decodeAny(child)
assertTrue(decoded is ObjInstance)
val decObj = decoded as ObjInstance
assertEquals("Vault", decObj.objClass.className)
}
@Test
fun decodeClassObj_shouldResolveWhenEvalFindsButGetMisses() = runTest {
// Build a module scope and define a class there via eval (simulating imported/user code)
val module = net.sergeych.lyng.Script.defaultImportManager.newModule()
module.eval("class Vault() { fun toString() { \"Vault\" } }")
// Build a child scope where local bindings do not include the class name explicitly
val child = module.createChildScope(module.pos)
// Sanity: eval in the child must resolve the class by name
val evalResolved = child.eval("Vault")
assertTrue(evalResolved is ObjClass)
// Create an instance so that encoder will write type Other + class name and constructor args
val inst = child.eval("Vault()")
assertTrue(inst is ObjInstance)
// Encode the instance and then decode it with our decoder that contains robust class lookup
val bout = MemoryBitOutput()
val enc = LynonEncoder(bout)
enc.encodeAny(child, inst)
val bin = MemoryBitInput(bout.toBitArray())
val dec = LynonDecoder(bin)
val decoded = dec.decodeAny(child)
assertTrue(decoded is ObjInstance)
// Class should be resolvable and preserved
val instObj = inst as ObjInstance
val decObj = decoded as ObjInstance
assertEquals(instObj.objClass.className, decObj.objClass.className)
assertEquals("Vault", decObj.objClass.className)
}
@Test @Test
fun testSizeInBits() { fun testSizeInBits() {
assertEquals(1, sizeInBits(0u)) assertEquals(1, sizeInBits(0u))