Compare commits

..
12 Commits
Author SHA1 Message Date
sergeych dcde11d722 Merge remote-tracking branch 'origin/master'
# Conflicts:
#	lyng/src/nativeMain/kotlin/Common.native.kt
2025-06-14 01:21:44 +04:00
sergeych 83e79f47c7 lyng CLI: support for shebang, started shell KMP code 2025-06-14 01:20:26 +04:00
sergeych e0bb183929 lyng CLI: support for shebang, started shell KMP code 2025-06-14 01:20:00 +04:00
sergeych b961296425 fix #19 set of null-coalesce operators 2025-06-13 22:25:18 +04:00
sergeych bd2b6bf06e readme actualized 2025-06-13 21:20:45 +04:00
sergeych 253480e32a readme actualized 2025-06-13 20:15:39 +04:00
sergeych eb8110cbf0 removed unnecessary 2025-06-13 19:12:51 +04:00
sergeych 8c6a1979ed published to our maven 2025-06-13 19:11:28 +04:00
sergeych 185aa4e0cf better docs/2 2025-06-13 18:40:14 +04:00
sergeych ef266b73a2 better docs/2 2025-06-13 18:03:51 +04:00
sergeych 89427de5cd better docs 2025-06-13 18:02:34 +04:00
sergeych cfb2f7f128 more docs, fixed parsing of an empty string 2025-06-13 17:59:40 +04:00
47 changed files with 450 additions and 186 deletions

No files matched your search

+78 -17
View File
@@ -9,6 +9,10 @@ class Point(x,y) {
fun dist() { sqrt(x*x + y*y) } fun dist() { sqrt(x*x + y*y) }
} }
Point(3,4).dist() //< 5 Point(3,4).dist() //< 5
fun swapEnds(first, args..., last, f) {
f( last, ...args, first)
}
``` ```
- extremely simple Kotlin integration on any platform - extremely simple Kotlin integration on any platform
@@ -31,16 +35,42 @@ and it is multithreaded on platforms supporting it (automatically, no code chang
## Integration in Kotlin multiplatform ## Integration in Kotlin multiplatform
### Add library ### Add dependency to your project
TBD ```kotlin
// update to current please:
val lyngVersion = "0.6.1-SNAPSHOT"
repositories {
// ...
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
}
```
And add dependency to the proper place in your project, it could look like:
```kotlin
comminMain by getting {
dependencies {
// ...
implementation("net.sergeych:lynglib:$lyngVersion")
}
}
```
Now you can import lyng and use it:
### Execute script: ### Execute script:
```kotlin ```kotlin
assertEquals("hello, world", eval(""" import net.sergeyh.lyng.*
"hello, " + "world"
""").toString()) // we need a coroutine to start, as Lyng
// is a coroutine based language, async topdown
runBlocking {
assert(5 == eval(""" 3*3 - 4 """).toInt())
eval(""" println("Hello, Lyng!") """)
}
``` ```
### Exchanging information ### Exchanging information
@@ -49,6 +79,8 @@ Script is executed over some `Context`. Create instance of the context,
add your specific vars and functions to it, an call over it: add your specific vars and functions to it, an call over it:
```kotlin ```kotlin
import new.sergeych.lyng.*
// simple function // simple function
val context = Context().apply { val context = Context().apply {
addFn("addArgs") { addFn("addArgs") {
@@ -83,22 +115,51 @@ Designed to add scripting to kotlin multiplatform application in easy and effici
# Language # Language
- dynamic - Javascript, WasmJS, native, JVM, android - batteries included.
- async - dynamic types in most elegant and concise way
- multithreaded (coroutines could be dispatched using threads on appropriate platforms, automatically) - async, 100% coroutines, supports multiple cores where platofrm supports thread
- good for functional an object-oriented style
## By-stage # Language Roadmap
Here are plans to develop it: ## v1.0.0
### First stage Planned autumn 2025. Complete dynamic language with sufficient standard library:
Interpreted, precompiled into threaded code, actually. Dynamic types. Ready features:
### Second stage - [x] Language platform and independent command-line launcher
- [x] Integral types and user classes, variables and constants, functions
- [x] lambdas and closures, coroutines for all callables
- [x] while-else, do-while-else, for-else loops with break-continue returning values and labels support
- [x] ranges, lists, strings, interfaces: Iterable, Iterator, Collection, Array
- [x] when(value), if-then-else
- [x] exception handling: throw, try-catch-finally, exception classes.
- [x] multiplatform maven publication
- [x] documentation for the current state
Will add: Under way:
- optimizations - [ ] maps, sets and sequences (flows?)
- p-code serialization - [ ] regular exceptions
- static typing - [ ] modules
- [ ] string interpolation and more string tools
- [ ] multiple inheritance for user classes
- [ ] launch, deferred, coroutineScope, mutex, etc.
- [ ] site with integrated interpreter to give a try
- [ ] kotlin part public API good docs, integration focused
- [ ] better stack reporting
## v1.1+
Planned features.
- [ ] type specifications
- [ ] source docs and maybe lyng.md to a standard
- [ ] moacro-style kotlin integration or something else to simplify it
Further
- [ ] client with GUI support based on compose multiplatform somehow
- [ ] notebook - style workbooks with graphs, formulaes, etc.
- [ ] language server or compose-based lyng-aware editor
Executable
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env lyng
println("Hello from lyng!")
+25 -1
View File
@@ -86,4 +86,28 @@ Lambda functions remember their scopes, so it will work the same as previous:
val c = createLambda() val c = createLambda()
println(c) println(c)
>> 1 >> 1
>> void >> void
# Elements of functional programming
With ellipsis and splats you can create partial functions, manipulate
arguments list in almost arbitrary ways. For example:
// Swap first and last arguments for call
fun swap_args(first, others..., last, f) {
f(last, ...others, first)
}
fun glue(args...) {
var result = ""
for( a in args ) result += a
}
assertEquals(
"4231",
swap_args( 1, 2, 3, 4, glue)
)
>>> void
,
+1 -1
View File
@@ -131,7 +131,7 @@ _this functionality is not yet released_
| class | notes | | class | notes |
|----------------------------|-------------------------------------------------------| |----------------------------|-------------------------------------------------------|
| Exception | root of al throwable objects | | Exception | root of al throwable objects |
| NullPointerException | | | NullReferenceException | |
| AssertionFailedException | | | AssertionFailedException | |
| ClassCastException | | | ClassCastException | |
| IndexOutOfBoundsException | | | IndexOutOfBoundsException | |
+45
View File
@@ -118,6 +118,51 @@ These operators return rvalue, unmodifiable.
## Assignment return r-value! ## Assignment return r-value!
Naturally, assignment returns its value:
var x
x = 11
>>> 11
rvalue means you cant assign the result if the assignment
var x
assertThrows { (x = 11) = 5 }
void
>>> void
This also prevents chain assignments so use parentheses:
var x
var y
x = (y = 1)
>>> 1
## Nullability
When the value is `null`, it might throws `NullReferenceException`, the name is somewhat a tradition. To avoid it
one can check it against null or use _null coalescing_. The null coalescing means, if the operand (left) is null,
the operation won't be performed and the result will be null. Here is the difference:
val ref = null
assertThrows { ref.field }
assertThrows { ref.method() }
assertThrows { ref.array[1] }
assertThrows { ref[1] }
assertThrows { ref() }
assert( ref?.field == null )
assert( ref?.method() == null )
assert( ref?.array?[1] == null )
assert( ref?[1] == null )
assert( ref?() == null )
>>> void
There is also "elvis operator", null-coalesce infix operator '?:' that returns rvalue if lvalue is `null`:
null ?: "nothing"
>>> "nothing"
## Math ## Math
It is rather simple, like everywhere else: It is rather simple, like everywhere else:
-11
View File
@@ -1,11 +0,0 @@
count = 0
for n1 in range(10):
for n2 in range(10):
for n3 in range(10):
for n4 in range(10):
for n5 in range(10):
for n6 in range(10):
if n1 + n2 + n3 == n4 + n5 + n6:
count += 1
print(count)
@@ -1,13 +0,0 @@
package net.sergeych.lyng
class Symbols(
unitType: UnitType,
val name: String,
val x: TypeDecl
) {
enum class UnitType {
Module, Function, Lambda
}
}
@@ -1,21 +0,0 @@
package net.sergeych.lyng
sealed class TypeDecl {
// ??
data class Fn(val argTypes: List<ArgsDeclaration.Item>, val retType: TypeDecl) : TypeDecl()
object Obj : TypeDecl()
}
/*
To use in the compiler, we need symbol information when:
- declaring a class: the only way to export its public/protected symbols is to know it in compiler time
- importing a module: actually, we cam try to do it in a more efficient way.
Importing module:
The moudule is efficiently a statement, that initializes it with all its symbols modifying some context.
The thing is, we need only
*/
+9 -3
View File
@@ -29,11 +29,11 @@ kotlin {
sourceSets { sourceSets {
val commonMain by getting { val commonMain by getting {
dependencies { dependencies {
implementation(project(":library")) implementation(kotlin("stdlib-common"))
implementation(project(":lynglib"))
implementation(libs.okio) implementation(libs.okio)
implementation(libs.clikt) implementation(libs.clikt)
implementation(kotlin("stdlib-common"))
// optional support for rendering markdown in help messages // optional support for rendering markdown in help messages
// implementation(libs.clikt.markdown) // implementation(libs.clikt.markdown)
} }
@@ -42,9 +42,15 @@ kotlin {
dependencies { dependencies {
implementation(kotlin("test-common")) implementation(kotlin("test-common"))
implementation(kotlin("test-annotations-common")) implementation(kotlin("test-annotations-common"))
implementation(libs.kotlinx.coroutines.core)
implementation(libs.okio.fakefilesystem) implementation(libs.okio.fakefilesystem)
} }
} }
// val nativeMain by getting {
// dependencies {
// implementation(kotlin("stdlib-common"))
// }
// }
val linuxX64Main by getting { val linuxX64Main by getting {
} }
+23 -1
View File
@@ -17,11 +17,28 @@ import okio.use
expect fun exit(code: Int) expect fun exit(code: Int)
expect class ShellCommandExecutor {
fun executeCommand(command: String): CommandResult
companion object {
fun create(): ShellCommandExecutor
}
}
data class CommandResult(
val exitCode: Int,
val output: String,
val error: String
)
val baseContext = Context().apply { val baseContext = Context().apply {
addFn("exit") { addFn("exit") {
exit(requireOnlyArg<ObjInt>().toInt()) exit(requireOnlyArg<ObjInt>().toInt())
ObjVoid ObjVoid
} }
// ObjString.type.addFn("shell") {
//
// }
} }
class Lyng(val launcher: (suspend () -> Unit) -> Unit) : CliktCommand() { class Lyng(val launcher: (suspend () -> Unit) -> Unit) : CliktCommand() {
@@ -90,11 +107,16 @@ class Lyng(val launcher: (suspend () -> Unit) -> Unit) : CliktCommand() {
} }
suspend fun executeFile(fileName: String) { suspend fun executeFile(fileName: String) {
val text = FileSystem.SYSTEM.source(fileName.toPath()).use { fileSource -> var text = FileSystem.SYSTEM.source(fileName.toPath()).use { fileSource ->
fileSource.buffer().use { bs -> fileSource.buffer().use { bs ->
bs.readUtf8() bs.readUtf8()
} }
} }
if( text.startsWith("#!") ) {
// skip shebang
val pos = text.indexOf('\n')
text = text.substring(pos + 1)
}
processErrors { processErrors {
Compiler().compile(Source(fileName, text)).execute(baseContext) Compiler().compile(Source(fileName, text)).execute(baseContext)
} }
+21
View File
@@ -0,0 +1,21 @@
package net.sergeych
// Alternative implementation for native targets
actual class ShellCommandExecutor() {
actual fun executeCommand(command: String): CommandResult {
val process = ProcessBuilder("/bin/sh", "-c", command).start()
val exitCode = process.waitFor()
val output = process.inputStream.bufferedReader().readText()
val error = process.errorStream.bufferedReader().readText()
return CommandResult(
exitCode = exitCode,
output = output.trim(),
error = error.trim()
)
}
actual companion object {
actual fun create(): ShellCommandExecutor = ShellCommandExecutor()
}
}
@@ -1,7 +1,48 @@
@file:OptIn(ExperimentalForeignApi::class, ExperimentalForeignApi::class, ExperimentalForeignApi::class)
package net.sergeych package net.sergeych
import kotlinx.cinterop.*
import platform.posix.fgets
import platform.posix.pclose
import platform.posix.popen
import kotlin.system.exitProcess import kotlin.system.exitProcess
actual class ShellCommandExecutor() {
actual fun executeCommand(command: String): CommandResult {
val outputBuilder = StringBuilder()
val errorBuilder = StringBuilder()
val fp = popen(command, "r") ?: return CommandResult(
exitCode = -1,
output = "",
error = "Failed to execute command"
)
val buffer = ByteArray(4096)
while (true) {
val bytesRead = buffer.usePinned { pinned ->
fgets(pinned.addressOf(0), buffer.size.convert(), fp)
}
if (bytesRead == null) break
outputBuilder.append(bytesRead.toKString())
}
val status = pclose(fp)
val exitCode = if (status == 0) 0 else 1
return CommandResult(
exitCode = exitCode,
output = outputBuilder.toString().trim(),
error = errorBuilder.toString().trim()
)
}
actual companion object {
actual fun create(): ShellCommandExecutor = ShellCommandExecutor()
}
}
actual fun exit(code: Int) { actual fun exit(code: Int) {
exitProcess(code) exitProcess(code)
} }
@@ -1,11 +1,10 @@
import com.codingfeline.buildkonfig.compiler.FieldSpec.Type.STRING import com.codingfeline.buildkonfig.compiler.FieldSpec.Type.STRING
import com.vanniktech.maven.publish.SonatypeHost
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl 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.6.0-SNAPSHOT" version = "0.6.-SNAPSHOT"
buildscript { buildscript {
repositories { repositories {
@@ -20,9 +19,10 @@ buildscript {
plugins { plugins {
alias(libs.plugins.kotlinMultiplatform) alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidLibrary) alias(libs.plugins.androidLibrary)
alias(libs.plugins.vanniktech.mavenPublish) // alias(libs.plugins.vanniktech.mavenPublish)
kotlin("plugin.serialization") version "2.1.20" kotlin("plugin.serialization") version "2.1.20"
id("com.codingfeline.buildkonfig") version "0.17.1" id("com.codingfeline.buildkonfig") version "0.17.1"
`maven-publish`
} }
buildkonfig { buildkonfig {
@@ -62,7 +62,7 @@ kotlin {
sourceSets { sourceSets {
all { all {
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi") languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
languageSettings.optIn("kotlin.contracts.ExperimentalContracts::class") languageSettings.optIn("kotlin.contracts.ExperimentalContracts")
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes") languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
languageSettings.optIn("kotlin.coroutines.DelicateCoroutinesApi") languageSettings.optIn("kotlin.coroutines.DelicateCoroutinesApi")
} }
@@ -101,73 +101,54 @@ dependencies {
implementation(libs.firebase.crashlytics.buildtools) implementation(libs.firebase.crashlytics.buildtools)
} }
mavenPublishing { publishing {
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL) val mavenToken by lazy {
File("${System.getProperty("user.home")}/.gitea_token").readText()
signAllPublications() }
repositories {
coordinates(group.toString(), "library", version.toString()) maven {
credentials(HttpHeaderCredentials::class) {
pom { name = "Authorization"
name = "Lyng language" value = mavenToken
description = "Kotlin-bound scripting loanguage"
inceptionYear = "2025"
// url = "https://sergeych.net"
licenses {
license {
name = "XXX"
url = "YYY"
distribution = "ZZZ"
} }
} url = uri("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
developers { authentication {
developer { create("Authorization", HttpHeaderAuthentication::class)
id = "XXX"
name = "YYY"
url = "ZZZ"
} }
} }
scm {
url = "XXX"
connection = "YYY"
developerConnection = "ZZZ"
}
} }
} }
//mavenPublishing {
// publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
// //
//val projectVersion by project.extra(provider { // signAllPublications()
// // Compute value lazily
// (version as String)
//})
// //
//val generateBuildConfig by tasks.registering { // coordinates(group.toString(), "library", version.toString())
// // Declare outputs safely
// val outputDir = layout.buildDirectory.dir("generated/buildConfig/commonMain/kotlin")
// outputs.dir(outputDir)
// //
// val version = projectVersion.get() // pom {
// // name = "Lyng language"
// // Inputs: Version is tracked as an input // description = "Kotlin-bound scripting loanguage"
// inputs.property("version", version) // inceptionYear = "2025"
// //// url = "https://sergeych.net"
// doLast { // licenses {
// val packageName = "net.sergeych.lyng.buildconfig" // license {
// val packagePath = packageName.replace('.', '/') // name = "XXX"
// val buildConfigFile = outputDir.get().file("$packagePath/BuildConfig.kt").asFile // url = "YYY"
// // distribution = "ZZZ"
// buildConfigFile.parentFile?.mkdirs() // }
// buildConfigFile.writeText( // }
// """ // developers {
// |package $packageName // developer {
// | // id = "XXX"
// |object BuildConfig { // name = "YYY"
// | const val VERSION = "$version" // url = "ZZZ"
// |} // }
// """.trimMargin() // }
// ) // scm {
// url = "XXX"
// connection = "YYY"
// developerConnection = "ZZZ"
// }
// } // }
//} //}
//
//tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
// dependsOn(generateBuildConfig)
//}
@@ -121,7 +121,8 @@ class Compiler(
operand = Accessor { op.getter(it).value.logicalNot(it).asReadonly } operand = Accessor { op.getter(it).value.logicalNot(it).asReadonly }
} }
Token.Type.DOT -> { Token.Type.DOT, Token.Type.NULL_COALESCE -> {
var isOptional = t.type == Token.Type.NULL_COALESCE
operand?.let { left -> operand?.let { left ->
// dotcall: calling method on the operand, if next is ID, "(" // dotcall: calling method on the operand, if next is ID, "("
var isCall = false var isCall = false
@@ -138,17 +139,22 @@ class Compiler(
operand = Accessor { context -> operand = Accessor { context ->
context.pos = next.pos context.pos = next.pos
val v = left.getter(context).value val v = left.getter(context).value
ObjRecord( if (v == ObjNull && isOptional)
v.invokeInstanceMethod( ObjNull.asReadonly
context, else
next.value, ObjRecord(
args.toArguments(context, false) v.invokeInstanceMethod(
), isMutable = false context,
) next.value,
args.toArguments(context, false)
), isMutable = false
)
} }
} }
Token.Type.LBRACE -> {
Token.Type.LBRACE, Token.Type.NULL_COALESCE_BLOCKINVOKE -> {
isOptional = nt.type == Token.Type.NULL_COALESCE_BLOCKINVOKE
// single lambda arg, like assertTrows { ... } // single lambda arg, like assertTrows { ... }
cc.next() cc.next()
isCall = true isCall = true
@@ -159,13 +165,16 @@ class Compiler(
operand = Accessor { context -> operand = Accessor { context ->
context.pos = next.pos context.pos = next.pos
val v = left.getter(context).value val v = left.getter(context).value
ObjRecord( if (v == ObjNull && isOptional)
v.invokeInstanceMethod( ObjNull.asReadonly
context, else
next.value, ObjRecord(
Arguments(listOf(lambda), true) v.invokeInstanceMethod(
), isMutable = false context,
) next.value,
Arguments(listOf(lambda), true)
), isMutable = false
)
} }
} }
@@ -174,25 +183,30 @@ class Compiler(
} }
if (!isCall) { if (!isCall) {
operand = Accessor({ context -> operand = Accessor({ context ->
left.getter(context).value.readField(context, next.value) val x = left.getter(context).value
if (x == ObjNull && isOptional) ObjNull.asReadonly
else x.readField(context, next.value)
}) { cc, newValue -> }) { cc, newValue ->
left.getter(cc).value.writeField(cc, next.value, newValue) left.getter(cc).value.writeField(cc, next.value, newValue)
} }
} }
} ?: throw ScriptError(t.pos, "Expecting expression before dot") }
?: throw ScriptError(t.pos, "Expecting expression before dot")
} }
Token.Type.COLONCOLON -> { Token.Type.COLONCOLON -> {
operand = parseScopeOperator(operand, cc) operand = parseScopeOperator(operand, cc)
} }
Token.Type.LPAREN -> { Token.Type.LPAREN, Token.Type.NULL_COALESCE_INVOKE -> {
operand?.let { left -> operand?.let { left ->
// this is function call from <left> // this is function call from <left>
operand = parseFunctionCall( operand = parseFunctionCall(
cc, cc,
left, left,
false, false,
t.type == Token.Type.NULL_COALESCE_INVOKE
) )
} ?: run { } ?: run {
// Expression in parentheses // Expression in parentheses
@@ -205,15 +219,18 @@ class Compiler(
} }
} }
Token.Type.LBRACKET -> { Token.Type.LBRACKET, Token.Type.NULL_COALESCE_INDEX -> {
operand?.let { left -> operand?.let { left ->
// array access // array access
val isOptional = t.type == Token.Type.NULL_COALESCE_INDEX
val index = parseStatement(cc) ?: throw ScriptError(t.pos, "Expecting index expression") val index = parseStatement(cc) ?: throw ScriptError(t.pos, "Expecting index expression")
cc.skipTokenOfType(Token.Type.RBRACKET, "missing ']' at the end of the list literal") cc.skipTokenOfType(Token.Type.RBRACKET, "missing ']' at the end of the list literal")
operand = Accessor({ cxt -> operand = Accessor({ cxt ->
val i = (index.execute(cxt) as? ObjInt)?.value?.toInt() val i = (index.execute(cxt) as? ObjInt)?.value?.toInt()
?: cxt.raiseError("index must be integer") ?: cxt.raiseError("index must be integer")
left.getter(cxt).value.getAt(cxt, i).asMutable val x = left.getter(cxt).value
if( x == ObjNull && isOptional) ObjNull.asReadonly
else x.getAt(cxt, i).asMutable
}) { cxt, newValue -> }) { cxt, newValue ->
val i = (index.execute(cxt) as? ObjInt)?.value?.toInt() val i = (index.execute(cxt) as? ObjInt)?.value?.toInt()
?: cxt.raiseError("index must be integer") ?: cxt.raiseError("index must be integer")
@@ -337,10 +354,15 @@ class Compiler(
} }
} }
Token.Type.LBRACE -> { Token.Type.LBRACE, Token.Type.NULL_COALESCE_BLOCKINVOKE -> {
operand = operand?.let { left -> operand = operand?.let { left ->
cc.previous() cc.previous()
parseFunctionCall(cc, left, blockArgument = true) parseFunctionCall(
cc,
left,
blockArgument = true,
t.type == Token.Type.NULL_COALESCE_BLOCKINVOKE
)
} ?: parseLambdaExpression(cc) } ?: parseLambdaExpression(cc)
} }
@@ -590,7 +612,12 @@ class Compiler(
} }
private fun parseFunctionCall(cc: CompilerContext, left: Accessor, blockArgument: Boolean): Accessor { private fun parseFunctionCall(
cc: CompilerContext,
left: Accessor,
blockArgument: Boolean,
isOptional: Boolean
): Accessor {
// insofar, functions always return lvalue // insofar, functions always return lvalue
var detectedBlockArgument = blockArgument var detectedBlockArgument = blockArgument
val args = if (blockArgument) { val args = if (blockArgument) {
@@ -607,6 +634,7 @@ class Compiler(
return Accessor { context -> return Accessor { context ->
val v = left.getter(context) val v = left.getter(context)
if (v.value == ObjNull && isOptional) return@Accessor v.value.asReadonly
v.value.callOn( v.value.callOn(
context.copy( context.copy(
context.pos, context.pos,
@@ -1600,6 +1628,9 @@ class Compiler(
Operator.simple(Token.Type.NOTIN, lastPrty) { c, a, b -> ObjBool(!b.contains(c, a)) }, Operator.simple(Token.Type.NOTIN, lastPrty) { c, a, b -> ObjBool(!b.contains(c, a)) },
Operator.simple(Token.Type.IS, lastPrty) { c, a, b -> ObjBool(a.isInstanceOf(b)) }, Operator.simple(Token.Type.IS, lastPrty) { c, a, b -> ObjBool(a.isInstanceOf(b)) },
Operator.simple(Token.Type.NOTIS, lastPrty) { c, a, b -> ObjBool(!a.isInstanceOf(b)) }, Operator.simple(Token.Type.NOTIS, lastPrty) { c, a, b -> ObjBool(!a.isInstanceOf(b)) },
Operator.simple(Token.Type.ELVIS, ++lastPrty) { c, a, b -> if( a == ObjNull) b else a },
// shuttle <=> 6 // shuttle <=> 6
Operator.simple(Token.Type.SHUTTLE, ++lastPrty) { c, a, b -> Operator.simple(Token.Type.SHUTTLE, ++lastPrty) { c, a, b ->
ObjInt(a.compareTo(c, b).toLong()) ObjInt(a.compareTo(c, b).toLong())
@@ -96,6 +96,7 @@ internal class CompilerContext(val tokens: List<Token>) {
} }
} }
@Suppress("NOTHING_TO_INLINE")
inline fun addBreak() { inline fun addBreak() {
breakFound = true breakFound = true
} }
@@ -16,7 +16,7 @@ class Context(
fun raiseNotImplemented(what: String = "operation"): Nothing = raiseError("$what is not implemented") fun raiseNotImplemented(what: String = "operation"): Nothing = raiseError("$what is not implemented")
@Suppress("unused") @Suppress("unused")
fun raiseNPE(): Nothing = raiseError(ObjNullPointerException(this)) fun raiseNPE(): Nothing = raiseError(ObjNullReferenceException(this))
@Suppress("unused") @Suppress("unused")
fun raiseIndexOutOfBounds(message: String = "Index out of bounds"): Nothing = fun raiseIndexOutOfBounds(message: String = "Index out of bounds"): Nothing =
@@ -289,6 +289,26 @@ object ObjNull : Obj() {
return other is ObjNull || other == null return other is ObjNull || other == null
} }
override suspend fun readField(context: Context, name: String): ObjRecord {
context.raiseNPE()
}
override suspend fun invokeInstanceMethod(context: Context, name: String, args: Arguments): Obj {
context.raiseNPE()
}
override suspend fun getAt(context: Context, index: Int): Obj {
context.raiseNPE()
}
override suspend fun putAt(context: Context, index: Int, newValue: Obj) {
context.raiseNPE()
}
override suspend fun callOn(context: Context): Obj {
context.raiseNPE()
}
override fun toString(): String = "null" override fun toString(): String = "null"
} }
@@ -383,7 +403,7 @@ open class ObjException(exceptionClass: ExceptionClass, val context: Context, va
context.addConst("Exception", Root) context.addConst("Exception", Root)
existingErrorClasses["Exception"] = Root existingErrorClasses["Exception"] = Root
for (name in listOf( for (name in listOf(
"NullPointerException", "NullReferenceException",
"AssertionFailedException", "AssertionFailedException",
"ClassCastException", "ClassCastException",
"IndexOutOfBoundsException", "IndexOutOfBoundsException",
@@ -400,7 +420,7 @@ open class ObjException(exceptionClass: ExceptionClass, val context: Context, va
} }
} }
class ObjNullPointerException(context: Context) : ObjException("NullPointerException", context, "object is null") class ObjNullReferenceException(context: Context) : ObjException("NullReferenceException", context, "object is null")
class ObjAssertionFailedException(context: Context, message: String) : class ObjAssertionFailedException(context: Context, message: String) :
ObjException("AssertionFailedException", context, message) ObjException("AssertionFailedException", context, message)
@@ -142,10 +142,12 @@ private class Parser(fromPos: Pos) {
pos.advance() pos.advance()
Token("...", from, Token.Type.ELLIPSIS) Token("...", from, Token.Type.ELLIPSIS)
} }
'<' -> { '<' -> {
pos.advance() pos.advance()
Token("..<", from, Token.Type.DOTDOTLT) Token("..<", from, Token.Type.DOTDOTLT)
} }
else -> { else -> {
Token("..", from, Token.Type.DOTDOT) Token("..", from, Token.Type.DOTDOT)
} }
@@ -157,11 +159,10 @@ private class Parser(fromPos: Pos) {
'<' -> { '<' -> {
if (currentChar == '=') { if (currentChar == '=') {
pos.advance() pos.advance()
if( currentChar == '>' ) { if (currentChar == '>') {
pos.advance() pos.advance()
Token("<=>", from, Token.Type.SHUTTLE) Token("<=>", from, Token.Type.SHUTTLE)
} } else {
else {
Token("<=", from, Token.Type.LTE) Token("<=", from, Token.Type.LTE)
} }
} else } else
@@ -240,6 +241,7 @@ private class Parser(fromPos: Pos) {
} }
'"' -> loadStringToken() '"' -> loadStringToken()
in digitsSet -> { in digitsSet -> {
pos.back() pos.back()
decodeNumber(loadChars(digits), from) decodeNumber(loadChars(digits), from)
@@ -265,6 +267,21 @@ private class Parser(fromPos: Pos) {
Token(value.toString(), start, Token.Type.CHAR) Token(value.toString(), start, Token.Type.CHAR)
} }
'?' -> {
when(currentChar.also { pos.advance() }) {
':' -> Token("??", from, Token.Type.ELVIS)
'?' -> Token("??", from, Token.Type.ELVIS)
'.' -> Token("?.", from, Token.Type.NULL_COALESCE)
'[' -> Token("?(", from, Token.Type.NULL_COALESCE_INDEX)
'(' -> Token("?(", from, Token.Type.NULL_COALESCE_INVOKE)
'{' -> Token("?{", from, Token.Type.NULL_COALESCE_BLOCKINVOKE)
else -> {
pos.back()
Token("?", from, Token.Type.QUESTION)
}
}
}
else -> { else -> {
// text infix operators: // text infix operators:
// Labels processing is complicated! // Labels processing is complicated!
@@ -295,7 +312,7 @@ private class Parser(fromPos: Pos) {
private fun decodeNumber(p1: String, start: Pos): Token = private fun decodeNumber(p1: String, start: Pos): Token =
if (pos.end) if (pos.end)
Token(p1, start, Token.Type.INT) Token(p1, start, Token.Type.INT)
else if( currentChar == 'e' || currentChar == 'E' ) { else if (currentChar == 'e' || currentChar == 'E') {
pos.advance() pos.advance()
var negative = false var negative = false
if (currentChar == '+') if (currentChar == '+')
@@ -353,10 +370,11 @@ private class Parser(fromPos: Pos) {
private val currentChar: Char get() = pos.currentChar private val currentChar: Char get() = pos.currentChar
private fun loadStringToken(): Token { private fun loadStringToken(): Token {
var start = currentPos val start = currentPos
if (currentChar == '"') pos.advance() // if (currentChar == '"') pos.advance()
else start = start.back() // else start = start.back()
// start = start.back()
val sb = StringBuilder() val sb = StringBuilder()
while (currentChar != '"') { while (currentChar != '"') {
@@ -5,6 +5,7 @@ data class Pos(val source: Source, val line: Int, val column: Int) {
return "${source.fileName}:${line+1}:${column}" return "${source.fileName}:${line+1}:${column}"
} }
@Suppress("unused")
fun back(): Pos = fun back(): Pos =
if( column > 0) Pos(source, line, column-1) if( column > 0) Pos(source, line, column-1)
else if( line > 0) Pos(source, line-1, source.lines[line-1].length - 1) else if( line > 0) Pos(source, line-1, source.lines[line-1].length - 1)
@@ -21,6 +21,11 @@ data class Token(val value: String, val pos: Pos, val type: Type) {
ELLIPSIS, DOTDOT, DOTDOTLT, ELLIPSIS, DOTDOT, DOTDOTLT,
NEWLINE, NEWLINE,
EOF, EOF,
NULL_COALESCE,
ELVIS,
NULL_COALESCE_INDEX,
NULL_COALESCE_INVOKE,
NULL_COALESCE_BLOCKINVOKE,
} }
companion object { companion object {
@@ -0,0 +1,9 @@
package net.sergeych.lyng
// this is highly experimental and subject to complete redesign
// very soon
sealed class TypeDecl {
// ??
// data class Fn(val argTypes: List<ArgsDeclaration.Item>, val retType: TypeDecl) : TypeDecl()
object Obj : TypeDecl()
}
@@ -111,25 +111,25 @@ class ScriptTest {
assertEquals(Token("label", src.posAt(0, 12), Token.Type.ATLABEL), tt[2]) assertEquals(Token("label", src.posAt(0, 12), Token.Type.ATLABEL), tt[2])
} }
@Test // @Test
fun parse0Test() { // fun parse0Test() {
val src = """ // val src = """
println("Hello") // println("Hello")
println( "world" ) // println( "world" )
""".trimIndent().toSource() // """.trimIndent().toSource()
//
val p = parseLyng(src).listIterator() // val p = parseLyng(src).listIterator()
//
assertEquals(Token("println", src.posAt(0, 0), Token.Type.ID), p.next()) // assertEquals(Token("println", src.posAt(0, 0), Token.Type.ID), p.next())
assertEquals(Token("(", src.posAt(0, 7), Token.Type.LPAREN), p.next()) // assertEquals(Token("(", src.posAt(0, 7), Token.Type.LPAREN), p.next())
assertEquals(Token("Hello", src.posAt(0, 8), Token.Type.STRING), p.next()) // assertEquals(Token("Hello", src.posAt(0, 9), Token.Type.STRING), p.next())
assertEquals(Token(")", src.posAt(0, 15), Token.Type.RPAREN), p.next()) // assertEquals(Token(")", src.posAt(0, 15), Token.Type.RPAREN), p.next())
assertEquals(Token("\n", src.posAt(0, 16), Token.Type.NEWLINE), p.next()) // assertEquals(Token("\n", src.posAt(0, 16), Token.Type.NEWLINE), p.next())
assertEquals(Token("println", src.posAt(1, 0), Token.Type.ID), p.next()) // assertEquals(Token("println", src.posAt(1, 0), Token.Type.ID), p.next())
assertEquals(Token("(", src.posAt(1, 7), Token.Type.LPAREN), p.next()) // assertEquals(Token("(", src.posAt(1, 7), Token.Type.LPAREN), p.next())
assertEquals(Token("world", src.posAt(1, 9), Token.Type.STRING), p.next()) // assertEquals(Token("world", src.posAt(1, 9), Token.Type.STRING), p.next())
assertEquals(Token(")", src.posAt(1, 17), Token.Type.RPAREN), p.next()) // assertEquals(Token(")", src.posAt(1, 17), Token.Type.RPAREN), p.next())
} // }
@Test @Test
fun parse1Test() { fun parse1Test() {
@@ -2113,4 +2113,24 @@ class ScriptTest {
""".trimIndent() """.trimIndent()
) )
} }
@Test
fun testNull1() = runTest {
eval("""
var s = null
assertThrows { s.length }
assertThrows { s.size() }
assertEquals( null, s?.size() )
assertEquals( null, s?.length )
assertEquals( null, s?.length ?{ "test" } )
assertEquals( null, s?[1] )
assertEquals( null, s ?{ "test" } )
assertEquals( null, s.test ?{ "test" } )
s = "xx"
assert(s.lower().size == 2)
assert(s.length == 2)
""".trimIndent())
}
} }
+1 -1
View File
@@ -18,5 +18,5 @@ dependencyResolutionManagement {
} }
rootProject.name = "lyng" rootProject.name = "lyng"
include(":library") include(":lynglib")
include(":lyng") include(":lyng")