Compare commits

..
4 Commits
Author SHA1 Message Date
sergeych 323c455a50 v.0.2.0: classes, lambdas, arrays, ellipsis, splats, etc. 2025-06-10 00:57:47 +04:00
sergeych 370d8cf605 better readme 2025-06-10 00:55:46 +04:00
sergeych f338c54632 public class methods 2025-06-10 00:09:53 +04:00
sergeych 3ef80616d8 public class methods 2025-06-10 00:07:48 +04:00
8 changed files with 94 additions and 44 deletions

No files matched your search

+35 -8
View File
@@ -1,14 +1,32 @@
# Lyng: scripting lang for kotlin multiplatform
# Lyng: modern scripting for kotlin multiplatform
in the form of multiplatform library. Key benefits:
A KMP library and a standalone interpreter
- async and multithreaded (on JVM and native) out of the box
- easy and efficient kotlin integration
- dynamic types yet with good checks
- simple, compact, intuitive and elegant modern code style:
__current state of implementation and docs__:
```
class Point(x,y) {
fun dist() { sqrt(x*x + y*y) }
}
Point(3,4).dist() //< 5
```
- [introduction and tutorial](docs/tutorial.md)
- extremely simple Kotlin integration on any platform
- 100% secure: no access to any API you didn't explicitly provide
- 100% coroutines! Every function/script is a coroutine, it does not block the thread, no async/await/suspend keyword garbage:
```
delay(1.5) // coroutine is delayed for 1.5s, thread is not blocked!
```
and it is multithreaded on platforms supporting it (automatically, no code changes required, just
`launch` more coroutines and they will be executed concurrently if possible)/
- functional style and OOP together, multiple inheritance, implementing interfaces for existing classes, writing extensions.
- Any unicode letters can be used as identifiers: `assert( sin(π/2) == 1 )`.
## Resources:
- [introduction and tutorial](docs/tutorial.md) - start here please
- [Samples directory](docs/samples)
## Integration in Kotlin multiplatform
@@ -31,6 +49,7 @@ Script is executed over some `Context`. Create instance of the context,
add your specific vars and functions to it, an call over it:
```kotlin
// simple function
val context = Context().apply {
addFn("addArgs") {
var sum = 0.0
@@ -38,8 +57,16 @@ val context = Context().apply {
ObjReal(sum)
}
addConst("LIGHT_SPEED", ObjReal(299_792_458.0))
}
// callback back to kotlin to some suspend fn, for example::
// suspend fun doSomeWork(text: String): Int
addFn("doSomeWork") {
// this _is_ a suspend lambda, we can call suspend function,
// and it won't consume the thread:
doSomeWork(args[0].toString()).toObj()
}
}
// adding constant:
context.eval("addArgs(1,2,3)") // <- 6
```
Note that the context stores all changes in it so you can make calls on a single context to preserve state between calls.
+1 -1
View File
@@ -11,7 +11,7 @@ plugins {
}
group = "net.sergeych"
version = "0.0.5-SNAPSHOT"
version = "0.2.0-SNAPSHOT"
kotlin {
jvm()
@@ -402,7 +402,9 @@ class Compiler(
}
enum class AccessType(val isMutable: Boolean) {
Val(false), Var(true), Initialization(false)
Val(false), Var(true),
@Suppress("unused")
Initialization(false)
}
enum class Visibility {
@@ -713,7 +715,6 @@ class Compiler(
cc.skipTokenOfType(Token.Type.NEWLINE, isOptional = true)
val t = cc.next()
var extraInit: Statement? = null
val bodyInit: Statement? = if (t.type == Token.Type.LBRACE) {
// parse body
parseScript(t.pos, cc).also {
@@ -726,10 +727,9 @@ class Compiler(
// create class
val className = nameToken.value
lateinit var classContext: Context
val defaultAccess = if (isStruct) AccessType.Var else AccessType.Initialization
val defaultVisibility = Visibility.Public
@Suppress("UNUSED_VARIABLE") val defaultAccess = if (isStruct) AccessType.Var else AccessType.Initialization
@Suppress("UNUSED_VARIABLE") val defaultVisibility = Visibility.Public
// create instance constructor
// create custom objClass with all fields and instance constructor
@@ -741,14 +741,11 @@ class Compiler(
// the context now is a "class creation context", we must use its args to initialize
// fields. Note that 'this' is already set by class
constructorArgsDeclaration?.let { cad ->
cad.assignToContext(this)
// note that accessors are created in ObjClass instance, not during instance
// initialization (not here)
}
constructorArgsDeclaration?.assignToContext(this)
bodyInit?.execute(this)
// export public
for( (name,record) in objects ) {
println("-- $name $record")
when(record.visibility) {
Visibility.Public -> {
thisObj.publicFields += name
@@ -27,6 +27,7 @@ class Context(
fun raiseClassCastError(msg: String): Nothing = raiseError(ObjClassCastError(this, msg))
@Suppress("unused")
fun raiseSymbolNotFound(name: String): Nothing = raiseError(ObjSymbolNotDefinedError(this, "symbol is not defined: $name"))
fun raiseError(message: String): Nothing {
@@ -78,7 +79,7 @@ class Context(
fun getOrCreateNamespace(name: String): ObjClass {
val ns = objects.getOrPut(name) { ObjRecord(ObjNamespace(name), isMutable = false) }.value
return ns!!.objClass
return ns.objClass
}
inline fun addVoidFn(vararg names: String, crossinline fn: suspend Context.() -> Unit) {
@@ -69,7 +69,7 @@ open class Obj {
args: Arguments = Arguments.EMPTY
): T = invokeInstanceMethod(context, name, args) as T
suspend fun invokeInstanceMethod(
open suspend fun invokeInstanceMethod(
context: Context,
name: String,
args: Arguments = Arguments.EMPTY
@@ -46,7 +46,7 @@ class ObjClass(
) {
if (name in members || allParentsSet.any { name in it.members } == true)
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
members[name] = ObjRecord(initialValue, isMutable)
members[name] = ObjRecord(initialValue, isMutable, visibility)
}
fun addFn(name: String, isOpen: Boolean = false, code: suspend Context.() -> Obj) {
@@ -151,25 +151,3 @@ val ObjArray by lazy {
}
}
class ObjInstance(override val objClass: ObjClass) : Obj() {
internal val publicFields = mutableSetOf<String>()
internal val protectedFields = mutableSetOf<String>()
internal lateinit var instanceContext: Context
override suspend fun readField(context: Context, name: String): ObjRecord {
return if( name in publicFields ) instanceContext[name]!!
else super.readField(context, name)
}
override suspend fun writeField(context: Context, name: String, newValue: Obj) {
if( name in publicFields ) {
val f = instanceContext[name]!!
if( !f.isMutable ) ObjIllegalAssignmentError(context, "can't reassign val $name").raise()
if( f.value.assign(context, newValue) == null)
f.value = newValue
}
else super.writeField(context, name, newValue)
}
}
@@ -0,0 +1,29 @@
package net.sergeych.lyng
class ObjInstance(override val objClass: ObjClass) : Obj() {
internal val publicFields = mutableSetOf<String>()
internal val protectedFields = mutableSetOf<String>()
internal lateinit var instanceContext: Context
override suspend fun readField(context: Context, name: String): ObjRecord {
return if( name in publicFields ) instanceContext[name]!!
else super.readField(context, name)
}
override suspend fun writeField(context: Context, name: String, newValue: Obj) {
if( name in publicFields ) {
val f = instanceContext[name]!!
if( !f.isMutable ) ObjIllegalAssignmentError(context, "can't reassign val $name").raise()
if( f.value.assign(context, newValue) == null)
f.value = newValue
}
else super.writeField(context, name, newValue)
}
override suspend fun invokeInstanceMethod(context: Context, name: String, args: Arguments): Obj {
if( name in publicFields ) return instanceContext[name]!!.value.invoke(context, this, args)
return super.invokeInstanceMethod(context, name, args)
}
}
@@ -1435,4 +1435,22 @@ class ScriptTest {
assert( p.length == 5 )
""".trimIndent())
}
@Test
fun testStructBodyFun() = runTest {
val c = Context()
c.eval("""
struct Point(x,y) {
fun length() {
sqrt(x*x+y*y)
}
var foo = "zero"
}
val p = Point(3,4)
assertEquals(5, p.length())
p.y = 10
println(p.length())
assertEquals(sqrt(109), p.length())
""".trimIndent())
}
}