Compare commits
17
Commits
0.5.1
...
e0bb183929
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e0bb183929 | ||
|
|
b961296425 | ||
|
|
bd2b6bf06e | ||
|
|
253480e32a | ||
|
|
eb8110cbf0 | ||
|
|
8c6a1979ed | ||
|
|
185aa4e0cf | ||
|
|
ef266b73a2 | ||
|
|
89427de5cd | ||
|
|
cfb2f7f128 | ||
|
|
be4f2c7f45 | ||
|
|
7cc80e2433 | ||
|
|
dacdcd7faa | ||
|
|
59a76efdce | ||
|
|
bb862e6cb5 | ||
|
|
aea819b89a | ||
|
|
88974e0f2d |
No files matched your search
@@ -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
@@ -0,0 +1,3 @@
|
|||||||
|
#!/usr/bin/env lyng
|
||||||
|
|
||||||
|
println("Hello from lyng!")
|
||||||
@@ -87,3 +87,27 @@ Lambda functions remember their scopes, so it will work the same as previous:
|
|||||||
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
|
||||||
|
|
||||||
|
,
|
||||||
@@ -81,6 +81,22 @@ to catch all exceptions to, then you can write it even shorter:
|
|||||||
You can even check the type of the `it` and create more convenient and sophisticated processing logic. Such approach is
|
You can even check the type of the `it` and create more convenient and sophisticated processing logic. Such approach is
|
||||||
used, for example, in Scala.
|
used, for example, in Scala.
|
||||||
|
|
||||||
|
## finally block
|
||||||
|
|
||||||
|
If `finally` block present, it will be executed after body (until first exception)
|
||||||
|
and catch block, if any will match. finally statement is executed even if the
|
||||||
|
exception will be thrown and not caught locally. It does not alter try/catch block result:
|
||||||
|
|
||||||
|
try {
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
println("called finally")
|
||||||
|
}
|
||||||
|
>>> called finally
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
- and yes, there could be try-finally block, no catching, but perform some guaranteed cleanup.
|
||||||
|
|
||||||
# Conveying data with exceptions
|
# Conveying data with exceptions
|
||||||
|
|
||||||
The simplest way is to provide exception string and `Exception` class:
|
The simplest way is to provide exception string and `Exception` class:
|
||||||
@@ -115,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 | |
|
||||||
|
|||||||
@@ -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:
|
||||||
@@ -552,6 +597,89 @@ Or, more neat:
|
|||||||
>>> just 3
|
>>> just 3
|
||||||
>>> void
|
>>> void
|
||||||
|
|
||||||
|
## When
|
||||||
|
|
||||||
|
It is very much like the kotlin's:
|
||||||
|
|
||||||
|
fun type(x) {
|
||||||
|
when(x) {
|
||||||
|
in 'a'..'z', in 'A'..'Z' -> "letter"
|
||||||
|
in '0'..'9' -> "digit"
|
||||||
|
'$' -> "dollar"
|
||||||
|
"EUR" -> "crap"
|
||||||
|
in ['@', '#', '^'] -> "punctuation1"
|
||||||
|
in "*&.," -> "punctuation2"
|
||||||
|
else -> "unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("digit", type('3'))
|
||||||
|
assertEquals("dollar", type('$'))
|
||||||
|
assertEquals("crap", type("EUR"))
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Notice, several conditions can be grouped with a comma.
|
||||||
|
Also, you can check the type too:
|
||||||
|
|
||||||
|
fun type(x) {
|
||||||
|
when(x) {
|
||||||
|
"42", 42 -> "answer to the great question"
|
||||||
|
is Real, is Int -> "number"
|
||||||
|
is String -> {
|
||||||
|
for( d in x ) {
|
||||||
|
if( d !in '0'..'9' )
|
||||||
|
break "unknown"
|
||||||
|
}
|
||||||
|
else "number"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("number", type(5))
|
||||||
|
assertEquals("number", type("153"))
|
||||||
|
assertEquals("number", type(π/2))
|
||||||
|
assertEquals("unknown", type("12%"))
|
||||||
|
assertEquals("answer to the great question", type(42))
|
||||||
|
assertEquals("answer to the great question", type("42"))
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
### supported when conditions:
|
||||||
|
|
||||||
|
#### Contains:
|
||||||
|
|
||||||
|
You can thest that _when expression_ is _contained_, or not contained, in some object using `in container` and `!in container`. The container is any object that provides `contains` method, otherwise the runtime exception will be thrown.
|
||||||
|
|
||||||
|
Typical builtin types that are containers (e.g. support `conain`):
|
||||||
|
|
||||||
|
| class | notes |
|
||||||
|
|------------|--------------------------------------------|
|
||||||
|
| Collection | contains an element (1) |
|
||||||
|
| Array | faster maybe that Collection's |
|
||||||
|
| List | faster than Array's |
|
||||||
|
| String | character in string or substring in string |
|
||||||
|
| Range | object is included in the range (2) |
|
||||||
|
|
||||||
|
(1)
|
||||||
|
: Iterable is not the container as it can be infinite
|
||||||
|
|
||||||
|
(2)
|
||||||
|
: Depending on the inclusivity and open/closed range parameters. BE careful here: String range is allowed, but it is usually not what you expect of it:
|
||||||
|
|
||||||
|
assert( "more" in "a".."z") // string range ok
|
||||||
|
assert( 'x' !in "a".."z") // char in string range: probably error
|
||||||
|
assert( 'x' in 'a'..'z') // character range: ok
|
||||||
|
assert( "x" !in 'a'..'z') // string in character range: could be error
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
So we recommend not to mix characters and string ranges; use `ch in str` that works
|
||||||
|
as expected:
|
||||||
|
|
||||||
|
"foo" in "foobar"
|
||||||
|
>>> true
|
||||||
|
|
||||||
|
and also character inclusion:
|
||||||
|
|
||||||
|
'o' in "foobar"
|
||||||
|
>>> true
|
||||||
|
|
||||||
## while
|
## while
|
||||||
|
|
||||||
Regular pre-condition while loop, as expression, loop returns the last expression as everything else:
|
Regular pre-condition while loop, as expression, loop returns the last expression as everything else:
|
||||||
|
|||||||
@@ -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
|
|
||||||
|
|
||||||
*/
|
|
||||||
@@ -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 {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|
||||||
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.5.1-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)
|
|
||||||
//}
|
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
+232
-87
@@ -39,13 +39,6 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Token.Type.PRIVATE, Token.Type.PROTECTED -> {
|
|
||||||
if (cc.nextIdValue() in setOf("var", "val", "class", "fun", "fn")) {
|
|
||||||
continue
|
|
||||||
} else
|
|
||||||
throw ScriptError(t.pos, "unexpected keyword ${t.value}")
|
|
||||||
}
|
|
||||||
|
|
||||||
Token.Type.PLUS2, Token.Type.MINUS2 -> {
|
Token.Type.PLUS2, Token.Type.MINUS2 -> {
|
||||||
cc.previous()
|
cc.previous()
|
||||||
parseExpression(cc)
|
parseExpression(cc)
|
||||||
@@ -128,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
|
||||||
@@ -145,19 +139,24 @@ 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
|
||||||
val lambda =
|
val lambda =
|
||||||
parseExpression(cc) ?: throw ScriptError(t.pos, "expected valid lambda here")
|
parseExpression(cc) ?: throw ScriptError(t.pos, "expected valid lambda here")
|
||||||
@@ -166,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
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -181,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
|
||||||
@@ -212,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")
|
||||||
@@ -344,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -458,17 +473,14 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
|
|
||||||
Token.Type.NEWLINE -> {}
|
Token.Type.NEWLINE -> {}
|
||||||
Token.Type.PROTECTED, Token.Type.PRIVATE -> {
|
|
||||||
if (!isClassDeclaration) {
|
|
||||||
cc.restorePos(startPos); return null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Token.Type.ID -> {
|
Token.Type.ID -> {
|
||||||
// visibility
|
// visibility
|
||||||
val visibility = if (isClassDeclaration)
|
val visibility = if (isClassDeclaration && t.value == "private") {
|
||||||
cc.getVisibility(Visibility.Public)
|
t = cc.next()
|
||||||
else Visibility.Public
|
Visibility.Private
|
||||||
|
} else Visibility.Public
|
||||||
|
|
||||||
// val/var?
|
// val/var?
|
||||||
val access = when (t.value) {
|
val access = when (t.value) {
|
||||||
"val" -> {
|
"val" -> {
|
||||||
@@ -600,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) {
|
||||||
@@ -617,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,
|
||||||
@@ -660,7 +678,7 @@ class Compiler(
|
|||||||
"void" -> Accessor { ObjVoid.asReadonly }
|
"void" -> Accessor { ObjVoid.asReadonly }
|
||||||
"null" -> Accessor { ObjNull.asReadonly }
|
"null" -> Accessor { ObjNull.asReadonly }
|
||||||
"true" -> Accessor { ObjBool(true).asReadonly }
|
"true" -> Accessor { ObjBool(true).asReadonly }
|
||||||
"false" -> Accessor { ObjBool(false).asReadonly }
|
"false" -> Accessor { ObjFalse.asReadonly }
|
||||||
else -> {
|
else -> {
|
||||||
Accessor({
|
Accessor({
|
||||||
it.pos = t.pos
|
it.pos = t.pos
|
||||||
@@ -707,8 +725,8 @@ class Compiler(
|
|||||||
* @return parsed statement or null if, for example. [id] is not among keywords
|
* @return parsed statement or null if, for example. [id] is not among keywords
|
||||||
*/
|
*/
|
||||||
private fun parseKeywordStatement(id: Token, cc: CompilerContext): Statement? = when (id.value) {
|
private fun parseKeywordStatement(id: Token, cc: CompilerContext): Statement? = when (id.value) {
|
||||||
"val" -> parseVarDeclaration(id.value, false, cc)
|
"val" -> parseVarDeclaration(false, Visibility.Public, cc)
|
||||||
"var" -> parseVarDeclaration(id.value, true, cc)
|
"var" -> parseVarDeclaration(true, Visibility.Public, cc)
|
||||||
"while" -> parseWhileStatement(cc)
|
"while" -> parseWhileStatement(cc)
|
||||||
"do" -> parseDoWhileStatement(cc)
|
"do" -> parseDoWhileStatement(cc)
|
||||||
"for" -> parseForStatement(cc)
|
"for" -> parseForStatement(cc)
|
||||||
@@ -719,16 +737,141 @@ class Compiler(
|
|||||||
"class" -> parseClassDeclaration(cc, false)
|
"class" -> parseClassDeclaration(cc, false)
|
||||||
"try" -> parseTryStatement(cc)
|
"try" -> parseTryStatement(cc)
|
||||||
"throw" -> parseThrowStatement(cc)
|
"throw" -> parseThrowStatement(cc)
|
||||||
else -> null
|
"when" -> parseWhenStatement(cc)
|
||||||
|
else -> {
|
||||||
|
// triples
|
||||||
|
cc.previous()
|
||||||
|
when {
|
||||||
|
cc.matchQualifiers("fun", "private") -> parseFunctionDeclaration(cc, Visibility.Private)
|
||||||
|
cc.matchQualifiers("fn", "private") -> parseFunctionDeclaration(cc, Visibility.Private)
|
||||||
|
cc.matchQualifiers("fun", "open") -> parseFunctionDeclaration(cc, isOpen = true)
|
||||||
|
cc.matchQualifiers("fn", "open") -> parseFunctionDeclaration(cc, isOpen = true)
|
||||||
|
cc.matchQualifiers("val", "private") -> parseVarDeclaration(false, Visibility.Private, cc)
|
||||||
|
cc.matchQualifiers("var", "private") -> parseVarDeclaration(true, Visibility.Private, cc)
|
||||||
|
cc.matchQualifiers("val", "open") -> parseVarDeclaration(false, Visibility.Private, cc, true)
|
||||||
|
cc.matchQualifiers("var", "open") -> parseVarDeclaration(true, Visibility.Private, cc, true)
|
||||||
|
else -> {
|
||||||
|
cc.next()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
data class WhenCase(val condition: Statement, val block: Statement)
|
||||||
|
|
||||||
|
private fun parseWhenStatement(cc: CompilerContext): Statement {
|
||||||
|
// has a value, when(value) ?
|
||||||
|
var t = cc.skipWsTokens()
|
||||||
|
return if (t.type == Token.Type.LPAREN) {
|
||||||
|
// when(value)
|
||||||
|
val value = parseStatement(cc) ?: throw ScriptError(cc.currentPos(), "when(value) expected")
|
||||||
|
cc.skipTokenOfType(Token.Type.RPAREN)
|
||||||
|
t = cc.next()
|
||||||
|
if (t.type != Token.Type.LBRACE) throw ScriptError(t.pos, "when { ... } expected")
|
||||||
|
val cases = mutableListOf<WhenCase>()
|
||||||
|
var elseCase: Statement? = null
|
||||||
|
lateinit var whenValue: Obj
|
||||||
|
|
||||||
|
// there could be 0+ then clauses
|
||||||
|
// condition could be a value, in and is clauses:
|
||||||
|
// parse several conditions for one then clause
|
||||||
|
|
||||||
|
// loop cases
|
||||||
|
outer@ while (true) {
|
||||||
|
|
||||||
|
var skipParseBody = false
|
||||||
|
val currentCondition = mutableListOf<Statement>()
|
||||||
|
|
||||||
|
// loop conditions
|
||||||
|
while (true) {
|
||||||
|
t = cc.skipWsTokens()
|
||||||
|
|
||||||
|
when (t.type) {
|
||||||
|
Token.Type.IN,
|
||||||
|
Token.Type.NOTIN -> {
|
||||||
|
// we need a copy in the closure:
|
||||||
|
val isIn = t.type == Token.Type.IN
|
||||||
|
val container = parseExpression(cc) ?: throw ScriptError(cc.currentPos(), "type expected")
|
||||||
|
currentCondition += statement {
|
||||||
|
val r = container.execute(this).contains(this, whenValue)
|
||||||
|
ObjBool(if (isIn) r else !r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Token.Type.IS, Token.Type.NOTIS -> {
|
||||||
|
// we need a copy in the closure:
|
||||||
|
val isIn = t.type == Token.Type.IS
|
||||||
|
val caseType = parseExpression(cc) ?: throw ScriptError(cc.currentPos(), "type expected")
|
||||||
|
currentCondition += statement {
|
||||||
|
val r = whenValue.isInstanceOf(caseType.execute(this))
|
||||||
|
ObjBool(if (isIn) r else !r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Token.Type.COMMA ->
|
||||||
|
continue
|
||||||
|
|
||||||
|
Token.Type.ARROW ->
|
||||||
|
break
|
||||||
|
|
||||||
|
Token.Type.RBRACE ->
|
||||||
|
break@outer
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
if (t.value == "else") {
|
||||||
|
cc.skipTokens(Token.Type.ARROW)
|
||||||
|
if (elseCase != null) throw ScriptError(
|
||||||
|
cc.currentPos(),
|
||||||
|
"when else block already defined"
|
||||||
|
)
|
||||||
|
elseCase =
|
||||||
|
parseStatement(cc) ?: throw ScriptError(cc.currentPos(), "when else block expected")
|
||||||
|
skipParseBody = true
|
||||||
|
} else {
|
||||||
|
cc.previous()
|
||||||
|
val x = parseExpression(cc)
|
||||||
|
?: throw ScriptError(cc.currentPos(), "when case condition expected")
|
||||||
|
currentCondition += statement {
|
||||||
|
ObjBool(x.execute(this).compareTo(this, whenValue) == 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// parsed conditions?
|
||||||
|
if (!skipParseBody) {
|
||||||
|
val block = parseStatement(cc) ?: throw ScriptError(cc.currentPos(), "when case block expected")
|
||||||
|
for (c in currentCondition) cases += WhenCase(c, block)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
statement {
|
||||||
|
var result: Obj = ObjVoid
|
||||||
|
// in / is and like uses whenValue from closure:
|
||||||
|
whenValue = value.execute(this)
|
||||||
|
var found = false
|
||||||
|
for (c in cases)
|
||||||
|
if (c.condition.execute(this).toBool()) {
|
||||||
|
result = c.block.execute(this)
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if (!found && elseCase != null) result = elseCase.execute(this)
|
||||||
|
result
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// when { cond -> ... }
|
||||||
|
TODO("when without object is not yet implemented")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseThrowStatement(cc: CompilerContext): Statement {
|
private fun parseThrowStatement(cc: CompilerContext): Statement {
|
||||||
val throwStatement = parseStatement(cc) ?: throw ScriptError(cc.currentPos(), "throw object expected")
|
val throwStatement = parseStatement(cc) ?: throw ScriptError(cc.currentPos(), "throw object expected")
|
||||||
return statement {
|
return statement {
|
||||||
var errorObject = throwStatement.execute(this)
|
var errorObject = throwStatement.execute(this)
|
||||||
if( errorObject is ObjString )
|
if (errorObject is ObjString)
|
||||||
errorObject = ObjException(this, errorObject.value)
|
errorObject = ObjException(this, errorObject.value)
|
||||||
if( errorObject is ObjException )
|
if (errorObject is ObjException)
|
||||||
raiseError(errorObject)
|
raiseError(errorObject)
|
||||||
else raiseError("this is not an exception object: $errorObject")
|
else raiseError("this is not an exception object: $errorObject")
|
||||||
}
|
}
|
||||||
@@ -745,7 +888,7 @@ class Compiler(
|
|||||||
val catches = mutableListOf<CatchBlockData>()
|
val catches = mutableListOf<CatchBlockData>()
|
||||||
cc.skipTokens(Token.Type.NEWLINE)
|
cc.skipTokens(Token.Type.NEWLINE)
|
||||||
var t = cc.next()
|
var t = cc.next()
|
||||||
while( t.value == "catch" ) {
|
while (t.value == "catch") {
|
||||||
|
|
||||||
if (cc.skipTokenOfType(Token.Type.LPAREN, isOptional = true)) {
|
if (cc.skipTokenOfType(Token.Type.LPAREN, isOptional = true)) {
|
||||||
t = cc.next()
|
t = cc.next()
|
||||||
@@ -785,45 +928,47 @@ class Compiler(
|
|||||||
} else {
|
} else {
|
||||||
// no (e: Exception) block: should be shortest variant `catch { ... }`
|
// no (e: Exception) block: should be shortest variant `catch { ... }`
|
||||||
cc.skipTokenOfType(Token.Type.LBRACE, "expected catch(...) or catch { ... } here")
|
cc.skipTokenOfType(Token.Type.LBRACE, "expected catch(...) or catch { ... } here")
|
||||||
catches += CatchBlockData(Token("it", cc.currentPos(), Token.Type.ID), listOf("Exception"),
|
catches += CatchBlockData(
|
||||||
parseBlock(cc,true))
|
Token("it", cc.currentPos(), Token.Type.ID), listOf("Exception"),
|
||||||
|
parseBlock(cc, true)
|
||||||
|
)
|
||||||
t = cc.next()
|
t = cc.next()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if( catches.isEmpty() )
|
val finallyClause = if (t.value == "finally") {
|
||||||
throw ScriptError(cc.currentPos(), "try block must have at least one catch clause")
|
|
||||||
val finallyClause = if( t.value == "finally" ) {
|
|
||||||
parseBlock(cc)
|
parseBlock(cc)
|
||||||
} else {
|
} else {
|
||||||
cc.previous()
|
cc.previous()
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (catches.isEmpty() && finallyClause == null)
|
||||||
|
throw ScriptError(cc.currentPos(), "try block must have either catch or finally clause or both")
|
||||||
|
|
||||||
return statement {
|
return statement {
|
||||||
var result: Obj = ObjVoid
|
var result: Obj = ObjVoid
|
||||||
try {
|
try {
|
||||||
// body is a parsed block, it already has separate context
|
// body is a parsed block, it already has separate context
|
||||||
result = body.execute(this)
|
result = body.execute(this)
|
||||||
}
|
} catch (e: Exception) {
|
||||||
catch (e: Exception) {
|
|
||||||
// convert to appropriate exception
|
// convert to appropriate exception
|
||||||
val objException = when(e) {
|
val objException = when (e) {
|
||||||
is ExecutionError -> e.errorObject
|
is ExecutionError -> e.errorObject
|
||||||
else -> ObjUnknownException(this, e.message ?: e.toString())
|
else -> ObjUnknownException(this, e.message ?: e.toString())
|
||||||
}
|
}
|
||||||
// let's see if we should catch it:
|
// let's see if we should catch it:
|
||||||
var isCaught = false
|
var isCaught = false
|
||||||
for( cdata in catches ) {
|
for (cdata in catches) {
|
||||||
var exceptionObject: ObjException? = null
|
var exceptionObject: ObjException? = null
|
||||||
for (exceptionClassName in cdata.classNames) {
|
for (exceptionClassName in cdata.classNames) {
|
||||||
val exObj = ObjException.getErrorClass(exceptionClassName)
|
val exObj = ObjException.getErrorClass(exceptionClassName)
|
||||||
?: raiseSymbolNotFound("error clas not exists: $exceptionClassName")
|
?: raiseSymbolNotFound("error clas not exists: $exceptionClassName")
|
||||||
if( objException.isInstanceOf(exObj) ) {
|
if (objException.isInstanceOf(exObj)) {
|
||||||
exceptionObject = objException
|
exceptionObject = objException
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if( exceptionObject != null ) {
|
if (exceptionObject != null) {
|
||||||
val catchContext = this.copy(pos = cdata.catchVar.pos)
|
val catchContext = this.copy(pos = cdata.catchVar.pos)
|
||||||
catchContext.addItem(cdata.catchVar.value, false, objException)
|
catchContext.addItem(cdata.catchVar.value, false, objException)
|
||||||
result = cdata.block.execute(catchContext)
|
result = cdata.block.execute(catchContext)
|
||||||
@@ -832,10 +977,9 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// rethrow if not caught this exception
|
// rethrow if not caught this exception
|
||||||
if( !isCaught )
|
if (!isCaught)
|
||||||
throw e
|
throw e
|
||||||
}
|
} finally {
|
||||||
finally {
|
|
||||||
// finally clause does not alter result!
|
// finally clause does not alter result!
|
||||||
finallyClause?.execute(this)
|
finallyClause?.execute(this)
|
||||||
}
|
}
|
||||||
@@ -1080,8 +1224,8 @@ class Compiler(
|
|||||||
cc.skipTokens(Token.Type.NEWLINE)
|
cc.skipTokens(Token.Type.NEWLINE)
|
||||||
|
|
||||||
val t = cc.next()
|
val t = cc.next()
|
||||||
if( t.type != Token.Type.ID && t.value != "while" )
|
if (t.type != Token.Type.ID && t.value != "while")
|
||||||
cc.skipTokenOfType(Token.Type.LPAREN, "expected '(' here")
|
cc.skipTokenOfType(Token.Type.LPAREN, "expected '(' here")
|
||||||
|
|
||||||
val conditionStart = ensureLparen(cc)
|
val conditionStart = ensureLparen(cc)
|
||||||
val condition =
|
val condition =
|
||||||
@@ -1105,10 +1249,9 @@ class Compiler(
|
|||||||
doContext = it.copy().apply { skipContextCreation = true }
|
doContext = it.copy().apply { skipContextCreation = true }
|
||||||
try {
|
try {
|
||||||
result = body.execute(doContext)
|
result = body.execute(doContext)
|
||||||
}
|
} catch (e: LoopBreakContinueException) {
|
||||||
catch( e: LoopBreakContinueException) {
|
if (e.label == label || e.label == null) {
|
||||||
if( e.label == label || e.label == null ) {
|
if (e.doContinue) continue
|
||||||
if( e.doContinue ) continue
|
|
||||||
else {
|
else {
|
||||||
result = e.result
|
result = e.result
|
||||||
wasBroken = true
|
wasBroken = true
|
||||||
@@ -1117,8 +1260,8 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
throw e
|
throw e
|
||||||
}
|
}
|
||||||
} while( condition.execute(doContext).toBool() )
|
} while (condition.execute(doContext).toBool())
|
||||||
if( !wasBroken ) elseStatement?.let { s -> result = s.execute(it) }
|
if (!wasBroken) elseStatement?.let { s -> result = s.execute(it) }
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1272,9 +1415,11 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseFunctionDeclaration(tokens: CompilerContext): Statement {
|
private fun parseFunctionDeclaration(
|
||||||
val visibility = tokens.getVisibility()
|
tokens: CompilerContext,
|
||||||
|
visibility: Visibility = Visibility.Public,
|
||||||
|
@Suppress("UNUSED_PARAMETER") isOpen: Boolean = false
|
||||||
|
): Statement {
|
||||||
var t = tokens.next()
|
var t = tokens.next()
|
||||||
val start = t.pos
|
val start = t.pos
|
||||||
val name = if (t.type != Token.Type.ID)
|
val name = if (t.type != Token.Type.ID)
|
||||||
@@ -1328,7 +1473,7 @@ class Compiler(
|
|||||||
val block = parseScript(startPos, cc)
|
val block = parseScript(startPos, cc)
|
||||||
return statement(startPos) {
|
return statement(startPos) {
|
||||||
// block run on inner context:
|
// block run on inner context:
|
||||||
block.execute(if( it.skipContextCreation ) it else it.copy(startPos))
|
block.execute(if (it.skipContextCreation) it else it.copy(startPos))
|
||||||
}.also {
|
}.also {
|
||||||
val t1 = cc.next()
|
val t1 = cc.next()
|
||||||
if (t1.type != Token.Type.RBRACE)
|
if (t1.type != Token.Type.RBRACE)
|
||||||
@@ -1336,26 +1481,22 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseVarDeclaration(kind: String, mutable: Boolean, tokens: CompilerContext): Statement {
|
private fun parseVarDeclaration(
|
||||||
// we are just after var/val, visibility if exists is 2 steps behind
|
isMutable: Boolean,
|
||||||
val visibility = when (tokens.atOffset(-2)?.type) {
|
visibility: Visibility,
|
||||||
Token.Type.PRIVATE ->
|
tokens: CompilerContext,
|
||||||
Visibility.Private
|
@Suppress("UNUSED_PARAMETER") isOpen: Boolean = false
|
||||||
|
): Statement {
|
||||||
Token.Type.PROTECTED -> Visibility.Protected
|
|
||||||
else -> Visibility.Public
|
|
||||||
}
|
|
||||||
|
|
||||||
val nameToken = tokens.next()
|
val nameToken = tokens.next()
|
||||||
val start = nameToken.pos
|
val start = nameToken.pos
|
||||||
if (nameToken.type != Token.Type.ID)
|
if (nameToken.type != Token.Type.ID)
|
||||||
throw ScriptError(nameToken.pos, "Expected identifier after '$kind'")
|
throw ScriptError(nameToken.pos, "Expected identifier here")
|
||||||
val name = nameToken.value
|
val name = nameToken.value
|
||||||
|
|
||||||
val eqToken = tokens.next()
|
val eqToken = tokens.next()
|
||||||
var setNull = false
|
var setNull = false
|
||||||
if (eqToken.type != Token.Type.ASSIGN) {
|
if (eqToken.type != Token.Type.ASSIGN) {
|
||||||
if (!mutable)
|
if (!isMutable)
|
||||||
throw ScriptError(start, "val must be initialized")
|
throw ScriptError(start, "val must be initialized")
|
||||||
else {
|
else {
|
||||||
tokens.previous()
|
tokens.previous()
|
||||||
@@ -1374,7 +1515,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, mutable, initValue, visibility)
|
context.addItem(name, isMutable, initValue, visibility)
|
||||||
initValue
|
initValue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1487,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())
|
||||||
@@ -1518,7 +1662,8 @@ class Compiler(
|
|||||||
/**
|
/**
|
||||||
* The keywords that stop processing of expression term
|
* The keywords that stop processing of expression term
|
||||||
*/
|
*/
|
||||||
val stopKeywords = setOf("do", "break", "continue", "return", "if", "when", "do", "while", "for", "class", "struct")
|
val stopKeywords =
|
||||||
|
setOf("do", "break", "continue", "return", "if", "when", "do", "while", "for", "class", "struct")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
+39
-28
@@ -21,7 +21,11 @@ internal class CompilerContext(val tokens: List<Token>) {
|
|||||||
|
|
||||||
fun hasNext() = currentIndex < tokens.size
|
fun hasNext() = currentIndex < tokens.size
|
||||||
fun hasPrevious() = currentIndex > 0
|
fun hasPrevious() = currentIndex > 0
|
||||||
fun next() = tokens.getOrElse(currentIndex) { throw IllegalStateException("No next token") }.also { currentIndex++ }
|
fun next() =
|
||||||
|
if( currentIndex < tokens.size ) tokens[currentIndex++]
|
||||||
|
else Token("", tokens.last().pos, Token.Type.EOF)
|
||||||
|
// throw IllegalStateException("No more tokens")
|
||||||
|
|
||||||
fun previous() = if (!hasPrevious()) throw IllegalStateException("No previous token") else tokens[--currentIndex]
|
fun previous() = if (!hasPrevious()) throw IllegalStateException("No previous token") else tokens[--currentIndex]
|
||||||
|
|
||||||
fun savePos() = currentIndex
|
fun savePos() = currentIndex
|
||||||
@@ -47,9 +51,7 @@ internal class CompilerContext(val tokens: List<Token>) {
|
|||||||
throw ScriptError(at, message)
|
throw ScriptError(at, message)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun currentPos() =
|
fun currentPos(): Pos = tokens[currentIndex].pos
|
||||||
if (hasNext()) next().pos.also { previous() }
|
|
||||||
else previous().pos.also { next() }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Skips next token if its type is `tokenType`, returns `true` if so.
|
* Skips next token if its type is `tokenType`, returns `true` if so.
|
||||||
@@ -94,6 +96,7 @@ internal class CompilerContext(val tokens: List<Token>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Suppress("NOTHING_TO_INLINE")
|
||||||
inline fun addBreak() {
|
inline fun addBreak() {
|
||||||
breakFound = true
|
breakFound = true
|
||||||
}
|
}
|
||||||
@@ -102,6 +105,7 @@ internal class CompilerContext(val tokens: List<Token>) {
|
|||||||
* Return value of the next token if it is an identifier, null otherwise.
|
* Return value of the next token if it is an identifier, null otherwise.
|
||||||
* Does not change position.
|
* Does not change position.
|
||||||
*/
|
*/
|
||||||
|
@Suppress("unused")
|
||||||
fun nextIdValue(): String? {
|
fun nextIdValue(): String? {
|
||||||
return if (hasNext()) {
|
return if (hasNext()) {
|
||||||
val nt = tokens[currentIndex]
|
val nt = tokens[currentIndex]
|
||||||
@@ -117,36 +121,43 @@ internal class CompilerContext(val tokens: List<Token>) {
|
|||||||
/**
|
/**
|
||||||
* If the token at current position plus offset (could be negative) exists, returns it, otherwise returns null.
|
* If the token at current position plus offset (could be negative) exists, returns it, otherwise returns null.
|
||||||
*/
|
*/
|
||||||
|
@Suppress("unused")
|
||||||
fun atOffset(offset: Int): Token? =
|
fun atOffset(offset: Int): Token? =
|
||||||
if (currentIndex + offset in tokens.indices) tokens[currentIndex + offset] else null
|
if (currentIndex + offset in tokens.indices) tokens[currentIndex + offset] else null
|
||||||
|
|
||||||
/**
|
fun matchQualifiers(keyword: String, vararg qualifiers: String): Boolean {
|
||||||
* Scan backwards as deep as specified looking for visibility token. Does not change position.
|
val pos = savePos()
|
||||||
*/
|
var count = 0
|
||||||
fun getVisibility(default: Visibility = Visibility.Public, depths: Int = 2): Visibility {
|
while( count < qualifiers.size) {
|
||||||
for( i in -depths .. -1) {
|
val t = next()
|
||||||
when( atOffset(i)?.type) {
|
when(t.type) {
|
||||||
Token.Type.PROTECTED -> return Visibility.Protected
|
Token.Type.ID -> {
|
||||||
Token.Type.PRIVATE -> return Visibility.Private
|
if( t.value in qualifiers ) count++
|
||||||
else -> {}
|
else { restorePos(pos); return false }
|
||||||
|
}
|
||||||
|
Token.Type.MULTILINE_COMMENT, Token.Type.SINLGE_LINE_COMMENT, Token.Type.NEWLINE -> {}
|
||||||
|
else -> { restorePos(pos); return false }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return default
|
val t = next()
|
||||||
|
if( t.type == Token.Type.ID && t.value == keyword ) {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
restorePos(pos)
|
||||||
|
return false
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// fun expectKeyword(vararg keyword: String): String {
|
/**
|
||||||
// val t = next()
|
* Skip newlines and comments. Returns (and reads) first non-whitespace token.
|
||||||
// if (t.type != Token.Type.ID && t.value !in keyword) {
|
* Note that [Token.Type.EOF] is not considered a whitespace token.
|
||||||
// throw ScriptError(t.pos, "expected one of ${keyword.joinToString()}")
|
*/
|
||||||
//
|
fun skipWsTokens(): Token {
|
||||||
// }
|
while( current().type in wstokens ) next()
|
||||||
|
return next()
|
||||||
// data class ReturnScope(val needCatch: Boolean = false)
|
}
|
||||||
|
|
||||||
// private val
|
|
||||||
|
|
||||||
// fun startReturnScope(): ReturnScope {
|
|
||||||
// return ReturnScope()
|
|
||||||
// }
|
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val wstokens = setOf(Token.Type.NEWLINE, Token.Type.MULTILINE_COMMENT, Token.Type.SINLGE_LINE_COMMENT)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
+1
-1
@@ -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 =
|
||||||
File renamed without changes.
File renamed without changes.
+23
-3
@@ -89,7 +89,7 @@ open class Obj {
|
|||||||
}
|
}
|
||||||
|
|
||||||
open suspend fun contains(context: Context, other: Obj): Boolean {
|
open suspend fun contains(context: Context, other: Obj): Boolean {
|
||||||
context.raiseNotImplemented()
|
return invokeInstanceMethod(context, "contains", other).toBool()
|
||||||
}
|
}
|
||||||
|
|
||||||
open val asStr: ObjString by lazy {
|
open val asStr: ObjString by lazy {
|
||||||
@@ -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)
|
||||||
File renamed without changes.
File renamed without changes.
+24
-2
@@ -42,7 +42,8 @@ open class ObjClass(
|
|||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
pos: Pos = Pos.builtIn
|
pos: Pos = Pos.builtIn
|
||||||
) {
|
) {
|
||||||
if (name in members || allParentsSet.any { name in it.members })
|
val existing = members[name] ?: allParentsSet.firstNotNullOfOrNull { it.members[name] }
|
||||||
|
if( existing?.isMutable == false)
|
||||||
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")
|
||||||
members[name] = ObjRecord(initialValue, isMutable, visibility)
|
members[name] = ObjRecord(initialValue, isMutable, visibility)
|
||||||
}
|
}
|
||||||
@@ -97,7 +98,19 @@ val ObjIterable by lazy {
|
|||||||
*/
|
*/
|
||||||
val ObjCollection by lazy {
|
val ObjCollection by lazy {
|
||||||
val i: ObjClass = ObjIterable
|
val i: ObjClass = ObjIterable
|
||||||
ObjClass("Collection", i)
|
ObjClass("Collection", i).apply {
|
||||||
|
// it is not effective, but it is open:
|
||||||
|
addFn("contains", isOpen = true) {
|
||||||
|
val obj = args.firstAndOnly()
|
||||||
|
val it = thisObj.invokeInstanceMethod(this, "iterator")
|
||||||
|
while (it.invokeInstanceMethod(this, "hasNext").toBool()) {
|
||||||
|
if( obj.compareTo(this, it.invokeInstanceMethod(this, "next")) == 0 )
|
||||||
|
return@addFn ObjTrue
|
||||||
|
}
|
||||||
|
ObjFalse
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val ObjIterator by lazy { ObjClass("Iterator") }
|
val ObjIterator by lazy { ObjClass("Iterator") }
|
||||||
@@ -145,6 +158,15 @@ val ObjArray by lazy {
|
|||||||
addFn("iterator") {
|
addFn("iterator") {
|
||||||
ObjArrayIterator(thisObj).also { it.init(this) }
|
ObjArrayIterator(thisObj).also { it.init(this) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addFn("contains", isOpen = true) {
|
||||||
|
val obj = args.firstAndOnly()
|
||||||
|
for( i in 0..< thisObj.invokeInstanceMethod(this, "size").toInt()) {
|
||||||
|
if( thisObj.getAt(this, i).compareTo(this, obj) == 0 ) return@addFn ObjTrue
|
||||||
|
}
|
||||||
|
ObjFalse
|
||||||
|
}
|
||||||
|
|
||||||
addFn("isample") { "ok".toObj() }
|
addFn("isample") { "ok".toObj() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
File renamed without changes.
File renamed without changes.
+4
@@ -75,6 +75,10 @@ class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
return this
|
return this
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun contains(context: Context, other: Obj): Boolean {
|
||||||
|
return list.contains(other)
|
||||||
|
}
|
||||||
|
|
||||||
override val objClass: ObjClass
|
override val objClass: ObjClass
|
||||||
get() = type
|
get() = type
|
||||||
|
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+8
@@ -31,6 +31,14 @@ data class ObjString(val value: String) : Obj() {
|
|||||||
return ObjChar(value[index])
|
return ObjChar(value[index])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun contains(context: Context, other: Obj): Boolean {
|
||||||
|
return if (other is ObjString)
|
||||||
|
value.contains(other.value)
|
||||||
|
else if (other is ObjChar)
|
||||||
|
value.contains(other.value)
|
||||||
|
else context.raiseArgumentError("String.contains can't take $other")
|
||||||
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val type = ObjClass("String").apply {
|
val type = ObjClass("String").apply {
|
||||||
addConst("startsWith",
|
addConst("startsWith",
|
||||||
+38
-18
@@ -137,14 +137,20 @@ private class Parser(fromPos: Pos) {
|
|||||||
if (currentChar == '.') {
|
if (currentChar == '.') {
|
||||||
pos.advance()
|
pos.advance()
|
||||||
// .. already parsed:
|
// .. already parsed:
|
||||||
if (currentChar == '.') {
|
when (currentChar) {
|
||||||
pos.advance()
|
'.' -> {
|
||||||
Token("...", from, Token.Type.ELLIPSIS)
|
pos.advance()
|
||||||
} else if (currentChar == '<') {
|
Token("...", from, Token.Type.ELLIPSIS)
|
||||||
pos.advance()
|
}
|
||||||
Token("..<", from, Token.Type.DOTDOTLT)
|
|
||||||
} else {
|
'<' -> {
|
||||||
Token("..", from, Token.Type.DOTDOT)
|
pos.advance()
|
||||||
|
Token("..<", from, Token.Type.DOTDOTLT)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
Token("..", from, Token.Type.DOTDOT)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else
|
} else
|
||||||
Token(".", from, Token.Type.DOT)
|
Token(".", from, Token.Type.DOT)
|
||||||
@@ -153,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
|
||||||
@@ -236,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)
|
||||||
@@ -261,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!
|
||||||
@@ -280,8 +301,6 @@ private class Parser(fromPos: Pos) {
|
|||||||
when (text) {
|
when (text) {
|
||||||
"in" -> Token("in", from, Token.Type.IN)
|
"in" -> Token("in", from, Token.Type.IN)
|
||||||
"is" -> Token("is", from, Token.Type.IS)
|
"is" -> Token("is", from, Token.Type.IS)
|
||||||
"protected" -> Token("protected", from, Token.Type.PROTECTED)
|
|
||||||
"private" -> Token("private", from, Token.Type.PRIVATE)
|
|
||||||
else -> Token(text, from, Token.Type.ID)
|
else -> Token(text, from, Token.Type.ID)
|
||||||
}
|
}
|
||||||
} else
|
} else
|
||||||
@@ -293,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 == '+')
|
||||||
@@ -338,7 +357,7 @@ private class Parser(fromPos: Pos) {
|
|||||||
// could be integer, also hex:
|
// could be integer, also hex:
|
||||||
if (currentChar == 'x' && p1 == "0") {
|
if (currentChar == 'x' && p1 == "0") {
|
||||||
pos.advance()
|
pos.advance()
|
||||||
Token(loadChars({ it in hexDigits }), start, Token.Type.HEX).also {
|
Token(loadChars { it in hexDigits }, start, Token.Type.HEX).also {
|
||||||
if (currentChar.isLetter())
|
if (currentChar.isLetter())
|
||||||
raise("invalid hex literal")
|
raise("invalid hex literal")
|
||||||
}
|
}
|
||||||
@@ -351,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 != '"') {
|
||||||
+1
@@ -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)
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+5
-1
@@ -17,11 +17,15 @@ data class Token(val value: String, val pos: Pos, val type: Type) {
|
|||||||
AND, BITAND, OR, BITOR, NOT, BITNOT, DOT, ARROW, QUESTION, COLONCOLON,
|
AND, BITAND, OR, BITOR, NOT, BITNOT, DOT, ARROW, QUESTION, COLONCOLON,
|
||||||
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
||||||
LABEL, ATLABEL, // label@ at@label
|
LABEL, ATLABEL, // label@ at@label
|
||||||
PRIVATE, PROTECTED,
|
|
||||||
//PUBLIC, PROTECTED, INTERNAL, EXPORT, OPEN, INLINE, OVERRIDE, ABSTRACT, SEALED, EXTERNAL, VAL, VAR, CONST, TYPE, FUN, CLASS, INTERFACE, ENUM, OBJECT, TRAIT, THIS,
|
//PUBLIC, PROTECTED, INTERNAL, EXPORT, OPEN, INLINE, OVERRIDE, ABSTRACT, SEALED, EXTERNAL, VAL, VAR, CONST, TYPE, FUN, CLASS, INTERFACE, ENUM, OBJECT, TRAIT, THIS,
|
||||||
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()
|
||||||
|
}
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
+337
-37
@@ -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() {
|
||||||
@@ -298,9 +298,9 @@ class ScriptTest {
|
|||||||
@Test
|
@Test
|
||||||
fun eqNeqTest() = runTest {
|
fun eqNeqTest() = runTest {
|
||||||
assertEquals(ObjBool(true), eval("val x = 2; x == 2"))
|
assertEquals(ObjBool(true), eval("val x = 2; x == 2"))
|
||||||
assertEquals(ObjBool(false), eval("val x = 3; x == 2"))
|
assertEquals(ObjFalse, eval("val x = 3; x == 2"))
|
||||||
assertEquals(ObjBool(true), eval("val x = 3; x != 2"))
|
assertEquals(ObjBool(true), eval("val x = 3; x != 2"))
|
||||||
assertEquals(ObjBool(false), eval("val x = 3; x != 3"))
|
assertEquals(ObjFalse, eval("val x = 3; x != 3"))
|
||||||
|
|
||||||
assertTrue { eval("1 == 1").toBool() }
|
assertTrue { eval("1 == 1").toBool() }
|
||||||
assertTrue { eval("true == true").toBool() }
|
assertTrue { eval("true == true").toBool() }
|
||||||
@@ -313,17 +313,17 @@ class ScriptTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun logicTest() = runTest {
|
fun logicTest() = runTest {
|
||||||
assertEquals(ObjBool(false), eval("true && false"))
|
assertEquals(ObjFalse, eval("true && false"))
|
||||||
assertEquals(ObjBool(false), eval("false && false"))
|
assertEquals(ObjFalse, eval("false && false"))
|
||||||
assertEquals(ObjBool(false), eval("false && true"))
|
assertEquals(ObjFalse, eval("false && true"))
|
||||||
assertEquals(ObjBool(true), eval("true && true"))
|
assertEquals(ObjBool(true), eval("true && true"))
|
||||||
|
|
||||||
assertEquals(ObjBool(true), eval("true || false"))
|
assertEquals(ObjBool(true), eval("true || false"))
|
||||||
assertEquals(ObjBool(false), eval("false || false"))
|
assertEquals(ObjFalse, eval("false || false"))
|
||||||
assertEquals(ObjBool(true), eval("false || true"))
|
assertEquals(ObjBool(true), eval("false || true"))
|
||||||
assertEquals(ObjBool(true), eval("true || true"))
|
assertEquals(ObjBool(true), eval("true || true"))
|
||||||
|
|
||||||
assertEquals(ObjBool(false), eval("!true"))
|
assertEquals(ObjFalse, eval("!true"))
|
||||||
assertEquals(ObjBool(true), eval("!false"))
|
assertEquals(ObjBool(true), eval("!false"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1750,8 +1750,9 @@ class ScriptTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testThrowExisting()= runTest {
|
fun testThrowExisting() = runTest {
|
||||||
eval("""
|
eval(
|
||||||
|
"""
|
||||||
val x = IllegalArgumentException("test")
|
val x = IllegalArgumentException("test")
|
||||||
assert( x is Exception )
|
assert( x is Exception )
|
||||||
|
|
||||||
@@ -1773,12 +1774,14 @@ class ScriptTest {
|
|||||||
}
|
}
|
||||||
assertEquals(3, t)
|
assertEquals(3, t)
|
||||||
assert(finallyCaught)
|
assert(finallyCaught)
|
||||||
""".trimIndent())
|
""".trimIndent()
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testCatchShort1()= runTest {
|
fun testCatchShort1() = runTest {
|
||||||
eval("""
|
eval(
|
||||||
|
"""
|
||||||
val x = IllegalArgumentException("test")
|
val x = IllegalArgumentException("test")
|
||||||
var t = 0
|
var t = 0
|
||||||
var finallyCaught = false
|
var finallyCaught = false
|
||||||
@@ -1795,12 +1798,14 @@ class ScriptTest {
|
|||||||
}
|
}
|
||||||
assertEquals(31, t)
|
assertEquals(31, t)
|
||||||
assert(finallyCaught)
|
assert(finallyCaught)
|
||||||
""".trimIndent())
|
""".trimIndent()
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testCatchShort2()= runTest {
|
fun testCatchShort2() = runTest {
|
||||||
eval("""
|
eval(
|
||||||
|
"""
|
||||||
val x = IllegalArgumentException("test")
|
val x = IllegalArgumentException("test")
|
||||||
var caught = null
|
var caught = null
|
||||||
try {
|
try {
|
||||||
@@ -1810,12 +1815,14 @@ class ScriptTest {
|
|||||||
caught = it
|
caught = it
|
||||||
}
|
}
|
||||||
assert( caught is IllegalArgumentException )
|
assert( caught is IllegalArgumentException )
|
||||||
""".trimIndent())
|
""".trimIndent()
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testAccessEHData() = runTest {
|
fun testAccessEHData() = runTest {
|
||||||
eval("""
|
eval(
|
||||||
|
"""
|
||||||
val x = IllegalArgumentException("test")
|
val x = IllegalArgumentException("test")
|
||||||
val m = try {
|
val m = try {
|
||||||
throw x
|
throw x
|
||||||
@@ -1830,7 +1837,300 @@ class ScriptTest {
|
|||||||
}
|
}
|
||||||
println(m)
|
println(m)
|
||||||
assert( m == "test" )
|
assert( m == "test" )
|
||||||
""".trimIndent())
|
""".trimIndent()
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testTryFinally() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
assertFails {
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
var resource = "used"
|
||||||
|
try {
|
||||||
|
throw "test"
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
resource = "freed"
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
assertEquals("freed", resource)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testThrowFromKotlin() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
c.addFn("callThrow") {
|
||||||
|
raiseArgumentError("fromKotlin")
|
||||||
|
}
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
val result = try {
|
||||||
|
callThrow()
|
||||||
|
"fail"
|
||||||
|
}
|
||||||
|
catch(e) {
|
||||||
|
println("caught:"+e)
|
||||||
|
println(e.message)
|
||||||
|
assert( e is IllegalArgumentException )
|
||||||
|
assertEquals("fromKotlin", e.message)
|
||||||
|
"ok"
|
||||||
|
}
|
||||||
|
assertEquals(result, "ok")
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReturnValue1() = runTest {
|
||||||
|
val r = eval(
|
||||||
|
"""
|
||||||
|
class Point(x,y) {
|
||||||
|
println("1")
|
||||||
|
fun length() { sqrt(d2()) }
|
||||||
|
println("2")
|
||||||
|
private fun d2() {x*x + y*y}
|
||||||
|
println("3")
|
||||||
|
}
|
||||||
|
println("Helluva")
|
||||||
|
val p = Point(3,4)
|
||||||
|
// assertEquals( 5, p.length() )
|
||||||
|
// assertThrows { p.d2() }
|
||||||
|
"111"
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
assertEquals("111", r.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun doWhileValuesTest() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var count = 0
|
||||||
|
val result = do {
|
||||||
|
count++
|
||||||
|
if( count < 10 )
|
||||||
|
continue
|
||||||
|
if( count % 2 == 1 )
|
||||||
|
break "found "+count
|
||||||
|
} while(count < 100)
|
||||||
|
else "no"
|
||||||
|
assertEquals("found 11", result)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var count = 0
|
||||||
|
val result = do {
|
||||||
|
count++
|
||||||
|
if( count < 10 )
|
||||||
|
continue
|
||||||
|
if( count % 2 == 1 )
|
||||||
|
break "found "+count
|
||||||
|
} while(count < 5)
|
||||||
|
else "no"
|
||||||
|
assertEquals("no", result)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var count = 0
|
||||||
|
val result = do {
|
||||||
|
count++
|
||||||
|
if( count % 2 == 3 )
|
||||||
|
break "found "+count
|
||||||
|
"proc "+count
|
||||||
|
} while(count < 5)
|
||||||
|
assertEquals("proc 5", result)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun doWhileValuesLabelTest() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var count = 0
|
||||||
|
var count2 = 0
|
||||||
|
var count3 = 0
|
||||||
|
val result = outer@ do {
|
||||||
|
count2++
|
||||||
|
count = 0
|
||||||
|
do {
|
||||||
|
count++
|
||||||
|
if( count < 10 || count2 < 5 ) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if( count % 2 == 1 )
|
||||||
|
break@outer "found "+count + "/" + count2
|
||||||
|
} while(count < 14)
|
||||||
|
count3++
|
||||||
|
} while( count2 < 100 )
|
||||||
|
else "no"
|
||||||
|
assertEquals("found 11/5", result)
|
||||||
|
assertEquals( 4, count3)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSimpleWhen() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var result = when("a") {
|
||||||
|
"a" -> "ok"
|
||||||
|
else -> "fail"
|
||||||
|
}
|
||||||
|
assertEquals(result, "ok")
|
||||||
|
result = when(5) {
|
||||||
|
3 -> "fail1"
|
||||||
|
4 -> "fail2"
|
||||||
|
else -> "ok2"
|
||||||
|
}
|
||||||
|
assert(result == "ok2")
|
||||||
|
result = when(5) {
|
||||||
|
3 -> "fail"
|
||||||
|
4 -> "fail2"
|
||||||
|
}
|
||||||
|
assert(result == void)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testWhenIs() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var result = when("a") {
|
||||||
|
is Int -> "fail2"
|
||||||
|
is String -> "ok"
|
||||||
|
else -> "fail"
|
||||||
|
}
|
||||||
|
assertEquals(result, "ok")
|
||||||
|
result = when(5) {
|
||||||
|
3 -> "fail1"
|
||||||
|
4 -> "fail2"
|
||||||
|
else -> "ok2"
|
||||||
|
}
|
||||||
|
assert(result == "ok2")
|
||||||
|
result = when(5) {
|
||||||
|
3 -> "fail"
|
||||||
|
4 -> "fail2"
|
||||||
|
}
|
||||||
|
assert(result == void)
|
||||||
|
result = when(5) {
|
||||||
|
!is String -> "ok"
|
||||||
|
4 -> "fail2"
|
||||||
|
}
|
||||||
|
assert(result == "ok")
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testWhenIn() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var result = when('e') {
|
||||||
|
in 'a'..'c' -> "fail2"
|
||||||
|
in 'a'..'z' -> "ok"
|
||||||
|
else -> "fail"
|
||||||
|
}
|
||||||
|
// assertEquals(result, "ok")
|
||||||
|
result = when(5) {
|
||||||
|
in [1,2,3,4,6] -> "fail1"
|
||||||
|
in [7, 0, 9] -> "fail2"
|
||||||
|
else -> "ok2"
|
||||||
|
}
|
||||||
|
assert(result == "ok2")
|
||||||
|
result = when(5) {
|
||||||
|
in [1,2,3,4,6] -> "fail1"
|
||||||
|
in [7, 0, 9] -> "fail2"
|
||||||
|
in [-1, 5, 11] -> "ok3"
|
||||||
|
else -> "fail3"
|
||||||
|
}
|
||||||
|
assert(result == "ok3")
|
||||||
|
result = when(5) {
|
||||||
|
!in [1,2,3,4,6, 5] -> "fail1"
|
||||||
|
!in [7, 0, 9, 5] -> "fail2"
|
||||||
|
!in [-1, 15, 11] -> "ok4"
|
||||||
|
else -> "fail3"
|
||||||
|
}
|
||||||
|
assert(result == "ok4")
|
||||||
|
result = when(5) {
|
||||||
|
in [1,3] -> "fail"
|
||||||
|
in 2..4 -> "fail2"
|
||||||
|
}
|
||||||
|
assert(result == void)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testWhenSample1() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun type(x) {
|
||||||
|
when(x) {
|
||||||
|
in 'a'..'z', in 'A'..'Z' -> "letter"
|
||||||
|
in '0'..'9' -> "digit"
|
||||||
|
in "$%&" -> "hate char"
|
||||||
|
else -> "unknown"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("digit", type('3'))
|
||||||
|
assertEquals("letter", type('E'))
|
||||||
|
assertEquals("hate char", type('%'))
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testWhenSample2() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun type(x) {
|
||||||
|
when(x) {
|
||||||
|
"42", 42 -> "answer to the great question"
|
||||||
|
is Real, is Int -> "number"
|
||||||
|
is String -> {
|
||||||
|
for( d in x ) {
|
||||||
|
if( d !in '0'..'9' )
|
||||||
|
break "unknown"
|
||||||
|
}
|
||||||
|
else "number"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals("number", type(5))
|
||||||
|
""".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())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
File renamed without changes.
File renamed without changes.
+1
-1
@@ -18,5 +18,5 @@ dependencyResolutionManagement {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rootProject.name = "lyng"
|
rootProject.name = "lyng"
|
||||||
include(":library")
|
include(":lynglib")
|
||||||
include(":lyng")
|
include(":lyng")
|
||||||
Reference in new issue
Block a user