Compare commits
180
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f7f020f4d6 | ||
|
|
0f54e2f845 | ||
|
|
19f8b6605b | ||
|
|
de71c7c8ec | ||
|
|
be370dfdef | ||
|
|
53a6a88924 | ||
|
|
2c2dae4d85 | ||
|
|
63b2808109 | ||
|
|
4165da5e81 | ||
|
|
af463163bb | ||
|
|
6df06a6911 | ||
|
|
f805e1ee82 | ||
|
|
790cce0d24 | ||
|
|
2339130241 | ||
|
|
d7bd159fcb | ||
|
|
12b209c724 | ||
|
|
20181c63a1 | ||
|
|
405ff2ec2b | ||
|
|
a9f65bdbe3 | ||
|
|
6ab438b1f6 | ||
|
|
cffe4eaffc | ||
|
|
7aee25ffef | ||
|
|
f3d766d1b1 | ||
|
|
34bc7297bd | ||
|
|
23dafff453 | ||
|
|
77f9191387 | ||
|
|
f26ee7cd7c | ||
|
|
d969993997 | ||
|
|
987b80e44d | ||
|
|
5848adca61 | ||
|
|
f1ae4b2d23 | ||
|
|
30b6ef235b | ||
|
|
9771b40c98 | ||
|
|
230cb0a067 | ||
|
|
732d8f3877 | ||
|
|
23006b5caa | ||
|
|
26282d3e22 | ||
|
|
ce4ed5c819 | ||
|
|
612c0fb7b9 | ||
|
|
ef6bc5c468 | ||
|
|
1e2cb5e420 | ||
|
|
868379ce22 | ||
|
|
f37354f382 | ||
|
|
ddbcbf9e4e | ||
|
|
6cf99fbd13 | ||
|
|
950e8301c3 | ||
|
|
ea2cf1f373 | ||
|
|
eee6d75587 | ||
|
|
a8067d0a6b | ||
|
|
75a6f20150 | ||
|
|
d969d6d572 | ||
|
|
2d4c4d345d | ||
|
|
f9416105ec | ||
|
|
c002204420 | ||
|
|
a4448ab2ff | ||
|
|
8a4363bd84 | ||
|
|
19eae213ec | ||
|
|
1db1f12be3 | ||
|
|
dcde11d722 | ||
|
|
83e79f47c7 | ||
|
|
e0bb183929 | ||
|
|
b961296425 | ||
|
|
bd2b6bf06e | ||
|
|
253480e32a | ||
|
|
eb8110cbf0 | ||
|
|
8c6a1979ed | ||
|
|
185aa4e0cf | ||
|
|
ef266b73a2 | ||
|
|
89427de5cd | ||
|
|
cfb2f7f128 | ||
|
|
be4f2c7f45 | ||
|
|
7cc80e2433 | ||
|
|
dacdcd7faa | ||
|
|
59a76efdce | ||
|
|
bb862e6cb5 | ||
|
|
aea819b89a | ||
|
|
88974e0f2d | ||
|
|
0981d8370e | ||
|
|
c4122e8243 | ||
|
|
c3bf536bab | ||
|
|
5ed8b2f123 | ||
|
|
6c71f0a2e6 | ||
|
|
95aae0b231 | ||
|
|
b3f08b4cac | ||
|
|
badeea9b28 | ||
|
|
a1267c4395 | ||
|
|
55fd3ea716 | ||
|
|
697bafdcee | ||
|
|
28b83f9892 | ||
|
|
194fc8aca6 | ||
|
|
382532e0e1 | ||
|
|
c0eba1ecf0 | ||
|
|
b253eed032 | ||
|
|
d482401b15 | ||
|
|
88b355c40d | ||
|
|
652e1d3af4 | ||
|
|
2a93e6f7da | ||
|
|
20c81dbf2e | ||
|
|
fffa3d31bb | ||
|
|
323c455a50 | ||
|
|
370d8cf605 | ||
|
|
f338c54632 | ||
|
|
3ef80616d8 | ||
|
|
961228ca0b | ||
|
|
56e0d2fd63 | ||
|
|
33fdb0934a | ||
|
|
60384060bf | ||
|
|
d3f23be7fe | ||
|
|
397dcaae92 | ||
|
|
2b87845a40 | ||
|
|
5591a66af3 | ||
|
|
9a08da0dfd | ||
|
|
71a2933066 | ||
|
|
4dc73b91c2 | ||
|
|
c0cf190452 | ||
|
|
306a7f26ef | ||
|
|
823e9a6498 | ||
|
|
aba122c3e6 | ||
|
|
75d90d7228 | ||
|
|
b331f4edaa | ||
|
|
148d1b6d24 | ||
|
|
953e0e696b | ||
|
|
7b76b7d80f | ||
|
|
512dda5984 | ||
|
|
53eb1bc5e7 | ||
|
|
1323f93923 | ||
|
|
c167ebe6a8 | ||
|
|
29c643eed2 | ||
|
|
4a597886e6 | ||
|
|
3cd2786ef0 | ||
|
|
25ace7370b | ||
|
|
d1b6ec03f7 | ||
|
|
f40c28504d | ||
|
|
f18038f9ca | ||
|
|
19a2a1d909 | ||
|
|
2344e19857 | ||
|
|
dae09f0dc9 | ||
|
|
e13dde68b5 | ||
|
|
6ef94fff65 | ||
|
|
939e391a20 | ||
|
|
c65f711ee3 | ||
|
|
698d169612 | ||
|
|
86d59abfbc | ||
|
|
d2c732ceef | ||
|
|
dcab60b7bb | ||
|
|
2b3b0b298c | ||
|
|
b82a97ed20 | ||
|
|
3908b8ee9f | ||
|
|
f7b35c7576 | ||
|
|
f3b3ebbb52 | ||
|
|
7288de4ea8 | ||
|
|
3a7a0c34c6 | ||
|
|
f4a3ad4c19 | ||
|
|
1479df4426 | ||
|
|
b56b5c521d | ||
|
|
c18345823b | ||
|
|
f881faf89f | ||
|
|
ca93d73b9c | ||
|
|
ff03f3066d | ||
|
|
9a9f712cec | ||
|
|
72f637e7de | ||
|
|
2130974929 | ||
|
|
47c061d2b4 | ||
|
|
f885300d18 | ||
|
|
d21544ca5d | ||
|
|
361c1d5b13 | ||
|
|
eba29aedb7 | ||
|
|
baf9eab3ba | ||
|
|
9ae9752634 | ||
|
|
758f49603f | ||
|
|
ebeed385e9 | ||
|
|
22fbd5584b | ||
|
|
0569be3b21 | ||
|
|
0e065e0d7c | ||
|
|
60db9f3b95 | ||
|
|
95e68d6e2a | ||
|
|
07a4c4c8d0 | ||
|
|
3dd98131e7 | ||
|
|
166b1fa0d5 | ||
|
|
408543d191 |
No files matched your search
+3
-1
@@ -12,4 +12,6 @@ xcuserdata
|
|||||||
#So we don't accidentally commit our private keys
|
#So we don't accidentally commit our private keys
|
||||||
*.gpg
|
*.gpg
|
||||||
.gigaide
|
.gigaide
|
||||||
.kotlin
|
/kotlin-js-store/yarn.lock
|
||||||
|
/test.lyng
|
||||||
|
/sample_texts/1.txt.gz
|
||||||
@@ -1,6 +1,109 @@
|
|||||||
# Ling: scripting lang for kotlin multiplatform
|
# Lyng: modern scripting for kotlin multiplatform
|
||||||
|
|
||||||
in the form of multiplatform library.
|
A KMP library and a standalone interpreter
|
||||||
|
|
||||||
|
- simple, compact, intuitive and elegant modern code style:
|
||||||
|
|
||||||
|
```
|
||||||
|
class Point(x,y) {
|
||||||
|
fun dist() { sqrt(x*x + y*y) }
|
||||||
|
}
|
||||||
|
Point(3,4).dist() //< 5
|
||||||
|
|
||||||
|
fun swapEnds(first, args..., last, f) {
|
||||||
|
f( last, ...args, first)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- extremely simple Kotlin integration on any platform
|
||||||
|
- 100% secure: no access to any API you didn't explicitly provide
|
||||||
|
- 100% coroutines! Every function/script is a coroutine, it does not block the thread, no async/await/suspend keyword garbage:
|
||||||
|
|
||||||
|
```
|
||||||
|
delay(1.5) // coroutine is delayed for 1.5s, thread is not blocked!
|
||||||
|
```
|
||||||
|
and it is multithreaded on platforms supporting it (automatically, no code changes required, just
|
||||||
|
`launch` more coroutines and they will be executed concurrently if possible). See [parallelism]
|
||||||
|
|
||||||
|
- functional style and OOP together, multiple inheritance, implementing interfaces for existing classes, writing extensions.
|
||||||
|
- Any unicode letters can be used as identifiers: `assert( sin(π/2) == 1 )`.
|
||||||
|
|
||||||
|
## Resources:
|
||||||
|
|
||||||
|
- [introduction and tutorial](docs/tutorial.md) - start here please
|
||||||
|
- [Samples directory](docs/samples)
|
||||||
|
|
||||||
|
## Integration in Kotlin multiplatform
|
||||||
|
|
||||||
|
### Add dependency to your project
|
||||||
|
|
||||||
|
```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:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
import net.sergeyh.lyng.*
|
||||||
|
|
||||||
|
// 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
|
||||||
|
|
||||||
|
Script is executed over some `Scope`. Create instance,
|
||||||
|
add your specific vars and functions to it, and call:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
|
||||||
|
import com.sun.source.tree.Scope
|
||||||
|
import new.sergeych.lyng.*
|
||||||
|
|
||||||
|
// simple function
|
||||||
|
val scope = Scope().apply {
|
||||||
|
addFn("addArgs") {
|
||||||
|
var sum = 0.0
|
||||||
|
for (a in args) sum += a.toDouble()
|
||||||
|
ObjReal(sum)
|
||||||
|
}
|
||||||
|
addConst("LIGHT_SPEED", ObjReal(299_792_458.0))
|
||||||
|
|
||||||
|
// callback back to kotlin to some suspend fn, for example::
|
||||||
|
// suspend fun doSomeWork(text: String): Int
|
||||||
|
addFn("doSomeWork") {
|
||||||
|
// this _is_ a suspend lambda, we can call suspend function,
|
||||||
|
// and it won't consume the thread:
|
||||||
|
doSomeWork(args[0].toString()).toObj()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// adding constant:
|
||||||
|
scope.eval("addArgs(1,2,3)") // <- 6
|
||||||
|
```
|
||||||
|
Note that the scope stores all changes in it so you can make calls on a single scope to preserve state between calls.
|
||||||
|
|
||||||
## Why?
|
## Why?
|
||||||
|
|
||||||
@@ -14,22 +117,53 @@ 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
|
- [x] maps, sets and sequences (flows?)
|
||||||
- p-code serialization
|
- [ ] regular exceptions
|
||||||
- static typing
|
- [x] modules
|
||||||
|
- [x] string formatting and tools
|
||||||
|
- [ ] multiple inheritance for user classes
|
||||||
|
- [x] launch, deferred, CompletableDeferred, 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
|
||||||
|
- [ ] macro-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
|
||||||
|
|
||||||
|
[parallelism]: docs/parallelism.md
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
root=./lyng/build/install/lyng-jvm/
|
||||||
|
|
||||||
|
./gradlew :lyng:installJvmDist
|
||||||
|
#strip $file
|
||||||
|
#upx $file
|
||||||
|
rm -rf ~/bin/jlyng-jvm || true
|
||||||
|
rm ~/bin/jlyng 2>/dev/null || true
|
||||||
|
mkdir -p ~/bin/jlyng-jvm
|
||||||
|
cp -R $root ~/bin/jlyng-jvm
|
||||||
|
ln -s ~/bin/jlyng-jvm/lyng-jvm/bin/lyng ~/bin/jlyng
|
||||||
Executable
+10
@@ -0,0 +1,10 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
file=./lyng/build/bin/linuxX64/releaseExecutable/lyng.kexe
|
||||||
|
|
||||||
|
./gradlew :lyng:linkReleaseExecutableLinuxX64
|
||||||
|
strip $file
|
||||||
|
upx $file
|
||||||
|
cp $file ~/bin/lyng
|
||||||
Executable
+3
@@ -0,0 +1,3 @@
|
|||||||
|
#!/usr/bin/env lyng
|
||||||
|
|
||||||
|
println("Hello from lyng!")
|
||||||
+121
@@ -0,0 +1,121 @@
|
|||||||
|
# Binary `Buffer`
|
||||||
|
|
||||||
|
Buffers are effective unsigned byte arrays of fixed size. Buffers content is mutable,
|
||||||
|
unlike its size. Buffers are comparable and implement [Array], thus [Collection] and [Iterable]. Buffer iterators return
|
||||||
|
its contents as unsigned bytes converted to `Int`
|
||||||
|
|
||||||
|
Buffers needs to be imported with `import lyng.buffer`:
|
||||||
|
|
||||||
|
import lyng.buffer
|
||||||
|
|
||||||
|
assertEquals(5, Buffer("Hello").size)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Buffer is _immutable_, there is a `MutableBuffer` with same interface but mutable.
|
||||||
|
|
||||||
|
## Constructing
|
||||||
|
|
||||||
|
There are a lo of ways to construct a buffer:
|
||||||
|
|
||||||
|
import lyng.buffer
|
||||||
|
|
||||||
|
// from string using utf8 encoding:
|
||||||
|
assertEquals( 5, Buffer("hello").size )
|
||||||
|
|
||||||
|
// from bytes, e.g. integers in range 0..255
|
||||||
|
assertEquals( 255, Buffer(1,2,3,255).last() )
|
||||||
|
|
||||||
|
// from whatever iterable that produces bytes, e.g.
|
||||||
|
// integers in 0..255 range:
|
||||||
|
assertEquals( 129, Buffer([1,2,129]).last() )
|
||||||
|
|
||||||
|
// Empty buffer of fixed size:
|
||||||
|
assertEquals(100, Buffer(100).size)
|
||||||
|
assertEquals(0, Buffer(100)[0])
|
||||||
|
|
||||||
|
// Note that you can use list iteral to create buffer with 1 byte:
|
||||||
|
assertEquals(1, Buffer([100]).size)
|
||||||
|
assertEquals(100, Buffer([100])[0])
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Accessing and modifying
|
||||||
|
|
||||||
|
Buffer implement [Array] and therefore can be accessed, and `MutableBuffers` also modified:
|
||||||
|
|
||||||
|
import lyng.buffer
|
||||||
|
val b1 = Buffer( 1, 2, 3)
|
||||||
|
assertEquals( 2, b1[1] )
|
||||||
|
|
||||||
|
val b2 = b1.toMutable()
|
||||||
|
assertEquals( 2, b1[1] )
|
||||||
|
b2[1]++
|
||||||
|
b2[0] = 100
|
||||||
|
assertEquals( Buffer(100, 3, 3), b2)
|
||||||
|
|
||||||
|
// b2 is a mutable copy so b1 has not been changed:
|
||||||
|
assertEquals( Buffer(1, 2, 3), b1)
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Buffer provides concatenation with another Buffer:
|
||||||
|
|
||||||
|
import lyng.buffer
|
||||||
|
val b = Buffer(101, 102)
|
||||||
|
assertEquals( Buffer(101, 102, 1, 2), b + [1,2])
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Please note that indexed bytes are _readonly projection_, e.g. you can't modify these with
|
||||||
|
|
||||||
|
## Comparing
|
||||||
|
|
||||||
|
Buffers are comparable with other buffers (and notice there are _mutable_ buffers, bu default buffers ar _immutable_):
|
||||||
|
|
||||||
|
import lyng.buffer
|
||||||
|
val b1 = Buffer(1, 2, 3)
|
||||||
|
val b2 = Buffer(1, 2, 3)
|
||||||
|
val b3 = MutableBuffer(b2)
|
||||||
|
|
||||||
|
b3[0] = 101
|
||||||
|
|
||||||
|
assert( b3 > b1 )
|
||||||
|
assert( b2 == b1 )
|
||||||
|
// longer string with same prefix is considered bigger:
|
||||||
|
assert( b2 + "!".characters() > b1 )
|
||||||
|
// note that characters() provide Iterable of characters that
|
||||||
|
// can be concatenated to Buffer
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Slicing
|
||||||
|
|
||||||
|
As with [List], it is possible to use ranges as indexes to slice a Buffer:
|
||||||
|
|
||||||
|
import lyng.buffer
|
||||||
|
|
||||||
|
val a = Buffer( 100, 101, 102, 103, 104, 105 )
|
||||||
|
assertEquals( a[ 0..1 ], Buffer(100, 101) )
|
||||||
|
assertEquals( a[ 0 ..< 2 ], Buffer(100, 101) )
|
||||||
|
assertEquals( a[ ..< 2 ], Buffer(100, 101) )
|
||||||
|
assertEquals( a[ 4.. ], Buffer(104, 105) )
|
||||||
|
assertEquals( a[ 2..3 ], Buffer(102, 103) )
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Members
|
||||||
|
|
||||||
|
| name | meaning | type |
|
||||||
|
|---------------|------------------------------------|---------------|
|
||||||
|
| `size` | size | Int |
|
||||||
|
| `decodeUtf8` | decodee to String using UTF8 rules | Any |
|
||||||
|
| `+` | buffer concatenation | Any |
|
||||||
|
| `toMutable()` | create a mutable copy | MutableBuffer |
|
||||||
|
|
||||||
|
(1)
|
||||||
|
: optimized implementation that override `Iterable` one
|
||||||
|
|
||||||
|
Also, it inherits methods from [Iterable] and [Array].
|
||||||
|
|
||||||
|
|
||||||
|
[Range]: Range.md
|
||||||
|
[Iterable]: Iterable.md
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Collection
|
||||||
|
|
||||||
|
Is a [Iterable] with known `size`, a finite [Iterable]:
|
||||||
|
|
||||||
|
class Collection : Iterable {
|
||||||
|
val size
|
||||||
|
}
|
||||||
|
|
||||||
|
See [List], [Set] and [Iterable]
|
||||||
|
|
||||||
|
[Iterable]: Iterable.md
|
||||||
|
[List]: List.md
|
||||||
|
[Set]: Set.md
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# Iterable interface
|
||||||
|
|
||||||
|
Iterable is a class that provides function that creates _the iterator_:
|
||||||
|
|
||||||
|
class Iterable {
|
||||||
|
abstract fun iterator()
|
||||||
|
}
|
||||||
|
|
||||||
|
Note that each call of `iterator()` must provide an independent iterator.
|
||||||
|
|
||||||
|
Iterator itself is a simple interface that should provide only to method:
|
||||||
|
|
||||||
|
class Iterator {
|
||||||
|
abstract fun hasNext(): Bool
|
||||||
|
fun next(): Obj
|
||||||
|
}
|
||||||
|
|
||||||
|
Just remember at this stage typed declarations are not yet supported.
|
||||||
|
|
||||||
|
Having `Iterable` in base classes allows to use it in for loop. Also, each `Iterable` has some utility functions available:
|
||||||
|
|
||||||
|
## Instance methods
|
||||||
|
|
||||||
|
| fun/method | description |
|
||||||
|
|-----------------|---------------------------------------------------------------------------------|
|
||||||
|
| toList() | create a list from iterable |
|
||||||
|
| toSet() | create a set from iterable |
|
||||||
|
| contains(i) | check that iterable contains `i` |
|
||||||
|
| `i in iterator` | same as `contains(i)` |
|
||||||
|
| isEmpty() | check iterable is empty |
|
||||||
|
| forEach(f) | call f for each element |
|
||||||
|
| toMap() | create a map from list of key-value pairs (arrays of 2 items or like) |
|
||||||
|
| map(f) | create a list of values returned by `f` called for each element of the iterable |
|
||||||
|
| indexOf(i) | return index if the first encounter of i or a negative value if not found |
|
||||||
|
| associateBy(kf) | create a map where keys are returned by kf that will be called for each element |
|
||||||
|
|
||||||
|
|
||||||
|
fun Iterable.toList(): List
|
||||||
|
fun Iterable.toSet(): Set
|
||||||
|
fun Iterable.indexOf(element): Int
|
||||||
|
fun Iterable.contains(element): Bool
|
||||||
|
fun Iterable.isEmpty(element): Bool
|
||||||
|
fun Iterable.forEach(block: (Any?)->Void ): Void
|
||||||
|
fun Iterable.map(block: (Any?)->Void ): List
|
||||||
|
fun Iterable.associateBy( keyMaker: (Any?)->Any): Map
|
||||||
|
|
||||||
|
|
||||||
|
## Abstract methods
|
||||||
|
|
||||||
|
fun iterator(): Iterator
|
||||||
|
|
||||||
|
Creates a list by iterating to the end. So, the Iterator should be finite to be used with it.
|
||||||
|
|
||||||
|
## Included in interfaces:
|
||||||
|
|
||||||
|
- [Collection], Array, [List]
|
||||||
|
|
||||||
|
## Implemented in classes:
|
||||||
|
|
||||||
|
- [List], [Range]
|
||||||
|
|
||||||
|
[List]: List.md
|
||||||
|
[Range]: Range.md
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Iterator interface
|
||||||
|
|
||||||
|
Iterators are representing the [Iterable] entity, to access its contents
|
||||||
|
sequentially.
|
||||||
|
|
||||||
|
To implement the iterator you need to implement only two abstract methods:
|
||||||
|
|
||||||
|
## Abstract methods
|
||||||
|
|
||||||
|
### hasNext(): Bool
|
||||||
|
|
||||||
|
Should return `true` if call to `next()` will return valid next element.
|
||||||
|
|
||||||
|
### next(): Obj
|
||||||
|
|
||||||
|
Should return next object in the iterated entity. If there is no next method,
|
||||||
|
must throw `ObjIterationFinishedError`.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Iterators are returned when implementing [Iterable] interface.
|
||||||
|
|
||||||
|
## Implemented for classes:
|
||||||
|
|
||||||
|
- [List], [Range]
|
||||||
|
|
||||||
|
[List]: List.md
|
||||||
|
[Range]: Range.md
|
||||||
|
[Iterable]: Iterable.md
|
||||||
+137
@@ -0,0 +1,137 @@
|
|||||||
|
# List built-in class
|
||||||
|
|
||||||
|
Mutable list of any objects.
|
||||||
|
|
||||||
|
It's class in Lyng is `List`:
|
||||||
|
|
||||||
|
[1,2,3]::class
|
||||||
|
>>> List
|
||||||
|
|
||||||
|
you can use it's class to ensure type:
|
||||||
|
|
||||||
|
[]::class == List
|
||||||
|
>>> true
|
||||||
|
|
||||||
|
## Indexing
|
||||||
|
|
||||||
|
indexing is zero-based, as in C/C++/Java/Kotlin, etc.
|
||||||
|
|
||||||
|
val list = [10, 20, 30]
|
||||||
|
list[1]
|
||||||
|
>>> 20
|
||||||
|
|
||||||
|
There is a shortcut for the last:
|
||||||
|
|
||||||
|
val list = [10, 20, 30]
|
||||||
|
[list.last, list.lastIndex]
|
||||||
|
>>> [30, 2]
|
||||||
|
|
||||||
|
__Important__ negative indexes works wherever indexes are used, e.g. in insertion and removal methods too.
|
||||||
|
|
||||||
|
## Concatenation
|
||||||
|
|
||||||
|
You can concatenate lists or iterable objects:
|
||||||
|
|
||||||
|
assert( [4,5] + [1,2] == [4,5,1,2])
|
||||||
|
assert( [4,5] + (1..3) == [4, 5, 1, 2, 3])
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Appending
|
||||||
|
|
||||||
|
To append to lists, use `+=` with elements, lists and any [Iterable] instances, but beware it will
|
||||||
|
concatenate [Iterable] objects instead of appending them. To append [Iterable] instance itself, use `list.add`:
|
||||||
|
|
||||||
|
var list = [1, 2]
|
||||||
|
val other = [3, 4]
|
||||||
|
|
||||||
|
// appending lists is clear:
|
||||||
|
list += other
|
||||||
|
assert( list == [1, 2, 3, 4] )
|
||||||
|
|
||||||
|
// but appending other Iterables could be confusing:
|
||||||
|
list += (10..12)
|
||||||
|
assert( list == [1, 2, 3, 4, 10, 11, 12])
|
||||||
|
|
||||||
|
// now adding list as sublist:
|
||||||
|
list.add(other)
|
||||||
|
assert( list == [1, 2, 3, 4, 10, 11, 12, [3,4]])
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Removing elements
|
||||||
|
|
||||||
|
List is mutable, so it is possible to remove its contents. To remove a single element
|
||||||
|
by index use:
|
||||||
|
|
||||||
|
assertEquals( [1,2,3].removeAt(1), [1,3] )
|
||||||
|
assertEquals( [1,2,3].removeAt(0), [2,3] )
|
||||||
|
assertEquals( [1,2,3].removeLast(), [1,2] )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
There is a way to remove a range (see [Range] for more on ranges):
|
||||||
|
|
||||||
|
assertEquals( [1, 4], [1,2,3,4].removeRange(1..2))
|
||||||
|
assertEquals( [1, 4], [1,2,3,4].removeRange(1..<3))
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Open end ranges remove head and tail elements:
|
||||||
|
|
||||||
|
assertEquals( [3, 4, 5], [1,2,3,4,5].removeRange(..1))
|
||||||
|
assertEquals( [3, 4, 5], [1,2,3,4,5].removeRange(..<2))
|
||||||
|
assertEquals( [1, 2], [1,2,3,4,5].removeRange( (2..) ))
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Comparisons
|
||||||
|
|
||||||
|
assert( [1, 2] != [1, 3])
|
||||||
|
assert( [1, 2, 3] > [1, 2])
|
||||||
|
assert( [1, 3] > [1, 2, 3])
|
||||||
|
assert( [1, 2, 3] == [1, 2, 3])
|
||||||
|
assert( [1, 2, 3] != [1, 2, "three"])
|
||||||
|
// note that in the case above objects are referentially different:
|
||||||
|
assert( [1, 2, 3] !== [1, 2, 3])
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Members
|
||||||
|
|
||||||
|
| name | meaning | type |
|
||||||
|
|-------------------------------|---------------------------------------|-------------|
|
||||||
|
| `size` | current size | Int |
|
||||||
|
| `add(elements...)` | add one or more elements to the end | Any |
|
||||||
|
| `insertAt(index,elements...)` | insert elements at position | Int, Any |
|
||||||
|
| `removeAt(index)` | remove element at position | Int |
|
||||||
|
| `remove(from,toNonInclusive)` | remove range from (incl) to (nonincl) | Int, Int |
|
||||||
|
| `remove(Range)` | remove range | Range |
|
||||||
|
| `removeLast()` | remove last element | |
|
||||||
|
| `removeLast(n)` | remove n last elements | Int |
|
||||||
|
| `contains(element)` | check the element is in the list (1) | |
|
||||||
|
| `[index]` | get or set element at index | Int |
|
||||||
|
| `[Range]` | get slice of the array (copy) | Range |
|
||||||
|
| `+=` | append element(s) | List or Obj |
|
||||||
|
|
||||||
|
(1)
|
||||||
|
: optimized implementation that override `Array` one
|
||||||
|
|
||||||
|
(2)
|
||||||
|
: `+=` append either a single element, or all elements if the List or other Iterable
|
||||||
|
instance is appended. If you want to append an Iterable object itself, use `add` instead.
|
||||||
|
|
||||||
|
It inherits from [Iterable] too.
|
||||||
|
|
||||||
|
## Member inherited from Array
|
||||||
|
|
||||||
|
| name | meaning | type |
|
||||||
|
|------------------|--------------------------------|-------|
|
||||||
|
| `last` | last element (throws if empty) | |
|
||||||
|
| `lastOrNull` | last element or null | |
|
||||||
|
| `lastIndex` | | Int |
|
||||||
|
| `indices` | range of indexes | Range |
|
||||||
|
| `contains(item)` | test that item is in the list | |
|
||||||
|
|
||||||
|
(1)
|
||||||
|
: end-inclisiveness allows to use negative indexes to, for exampe, remove several last elements, like
|
||||||
|
`list.removeRangeInclusive(-2, -1)` will remove two last elements.
|
||||||
|
|
||||||
|
|
||||||
|
[Range]: Range.md
|
||||||
|
[Iterable]: Iterable.md
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
# Map
|
||||||
|
|
||||||
|
Map is a mutable collection of key-value pars, where keys are unique. Maps could be created with
|
||||||
|
constructor or `.toMap` methods. When constructing from a list, each list item must be a [Collection] with exactly 2 elements, for example, a [List].
|
||||||
|
|
||||||
|
Important thing is that maps can't contain `null`: it is used to return from missing elements.
|
||||||
|
|
||||||
|
Constructed map instance is of class `Map` and implements `Collection` (and therefore `Iterable`)
|
||||||
|
|
||||||
|
val map = Map( "foo" => 1, "bar" => "buzz" )
|
||||||
|
assert(map is Map)
|
||||||
|
assert(map.size == 2)
|
||||||
|
assert(map is Iterable)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Notice usage of the `=>` operator that creates `MapEntry`, which implements also [Collection] of
|
||||||
|
two items, first, at index zero, is a key, second, at index 1, is the value. You can use lists too.
|
||||||
|
Map keys could be any objects (hashable, e.g. with reasonable hashCode, most of standard types are). You can access elements with indexing operator:
|
||||||
|
|
||||||
|
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||||
|
assert( map["bar"] == "buzz")
|
||||||
|
assert( map[42] == "answer" )
|
||||||
|
assertEquals( null, map["nonexisting"])
|
||||||
|
assert( map.getOrNull(101) == null )
|
||||||
|
assert( map.getOrPut(911) { "nine-eleven" } == "nine-eleven" )
|
||||||
|
// now 91 entry is set:
|
||||||
|
assert( map[911] == "nine-eleven" )
|
||||||
|
map["foo"] = -1
|
||||||
|
assert( map["foo"] == -1)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
To remove item from the collection. use `remove`. It returns last removed item or null. Be careful if you
|
||||||
|
hold nulls in the map - this is not a recommended practice when using `remove` returned value. `clear()`
|
||||||
|
removes all.
|
||||||
|
|
||||||
|
val map = Map( "foo" => 1, "bar" => "buzz", [42, "answer"] )
|
||||||
|
assertEquals( 1, map.remove("foo") )
|
||||||
|
assert( map.getOrNull("foo") == null)
|
||||||
|
assert( map.size == 2 )
|
||||||
|
map.clear()
|
||||||
|
assert( map.size == 0 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Map implements [contains] method that checks _the presence of the key_ in the map:
|
||||||
|
|
||||||
|
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||||
|
assert( "foo" in map )
|
||||||
|
assert( "answer" !in map )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
To iterate maps it is convenient to use `keys` method that returns [Set] of keys (keys are unique:
|
||||||
|
|
||||||
|
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||||
|
for( k in map.keys ) println(map[k])
|
||||||
|
>>> 1
|
||||||
|
>>> buzz
|
||||||
|
>>> answer
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Or iterate its key-value pairs that are instances of [MapEntry] class:
|
||||||
|
|
||||||
|
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||||
|
for( entry in map ) {
|
||||||
|
println("map[%s] = %s"(entry.key, entry.value))
|
||||||
|
}
|
||||||
|
void
|
||||||
|
>>> map[foo] = 1
|
||||||
|
>>> map[bar] = buzz
|
||||||
|
>>> map[42] = answer
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
There is a shortcut to use `MapEntry` to create maps: operator `=>` which creates `MapEntry`:
|
||||||
|
|
||||||
|
val entry = "answer" => 42
|
||||||
|
assert( entry is MapEntry )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
And you can use it to construct maps:
|
||||||
|
|
||||||
|
val map = Map( "foo" => 1, "bar" => 22)
|
||||||
|
assertEquals(1, map["foo"])
|
||||||
|
assertEquals(22, map["bar"])
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Or use `.toMap` on anything that implements [Iterable] and which elements implements [Array] with 2 elements size, for example, `MapEntry`:
|
||||||
|
|
||||||
|
val map = ["foo" => 1, "bar" => 22].toMap()
|
||||||
|
assert( map is Map )
|
||||||
|
assertEquals(1, map["foo"])
|
||||||
|
assertEquals(22, map["bar"])
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
|
||||||
|
It is possible also to get values as [List] (values are not unique):
|
||||||
|
|
||||||
|
val map = Map( ["foo", 1], ["bar", "buzz"], [42, "answer"] )
|
||||||
|
assertEquals(map.values, [1, "buzz", "answer"] )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Map could be tested to be equal: when all it key-value pairs are equal, the map
|
||||||
|
is equal.
|
||||||
|
|
||||||
|
val m1 = Map(["foo", 1])
|
||||||
|
val m2 = Map(["foo", 1])
|
||||||
|
val m3 = Map(["foo", 2])
|
||||||
|
assert( m1 == m2 )
|
||||||
|
// but the references are different:
|
||||||
|
assert( m1 !== m2 )
|
||||||
|
// different maps:
|
||||||
|
assert( m1 != m3 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
[Collection](Collection.md)
|
||||||
+312
@@ -0,0 +1,312 @@
|
|||||||
|
# OO implementation in Lyng
|
||||||
|
|
||||||
|
## Declaration
|
||||||
|
|
||||||
|
The class clause looks like
|
||||||
|
|
||||||
|
class Point(x,y)
|
||||||
|
assert( Point is Class )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
It creates new `Class` with two fields. Here is the more practical sample:
|
||||||
|
|
||||||
|
class Point(x,y) {
|
||||||
|
fun length() { sqrt(x*x + y*y) }
|
||||||
|
}
|
||||||
|
|
||||||
|
val p = Point(3,4)
|
||||||
|
assert(p is Point)
|
||||||
|
assertEquals(5, p.length())
|
||||||
|
|
||||||
|
// we can access the fields:
|
||||||
|
assert( p.x == 3 )
|
||||||
|
assert( p.y == 4 )
|
||||||
|
|
||||||
|
// we can assign new values to fields:
|
||||||
|
p.x = 1
|
||||||
|
p.y = 1
|
||||||
|
assertEquals(sqrt(2), p.length())
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
|
||||||
|
Let's see in details. The statement `class Point(x,y)` creates a class,
|
||||||
|
with two field, which are mutable and publicly visible.`(x,y)` here
|
||||||
|
is the [argument list], same as when defining a function. All together creates a class with
|
||||||
|
a _constructor_ that requires two parameters for fields. So when creating it with
|
||||||
|
`Point(10, 20)` we say _calling Point constructor_ with these parameters.
|
||||||
|
|
||||||
|
Form now on `Point` is a class, it's type is `Class`, and we can create instances with it as in the
|
||||||
|
example above.
|
||||||
|
|
||||||
|
Class point has a _method_, or a _member function_ `length()` that uses its _fields_ `x` and `y` to
|
||||||
|
calculate the magnitude. Length is called
|
||||||
|
|
||||||
|
### default values in constructor
|
||||||
|
|
||||||
|
Constructor arguments are the same as function arguments except visibility
|
||||||
|
statements discussed later, there could be default values, ellipsis, etc.
|
||||||
|
|
||||||
|
class Point(x=0,y=0)
|
||||||
|
val p = Point()
|
||||||
|
assert( p.x == 0 && p.y == 0 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Methods
|
||||||
|
|
||||||
|
Functions defined inside a class body are methods, and unless declared
|
||||||
|
`private` are available to be called from outside the class:
|
||||||
|
|
||||||
|
class Point(x,y) {
|
||||||
|
// public method declaration:
|
||||||
|
fun length() { sqrt(d2()) }
|
||||||
|
|
||||||
|
// private method:
|
||||||
|
private fun d2() {x*x + y*y}
|
||||||
|
}
|
||||||
|
val p = Point(3,4)
|
||||||
|
// private called from inside public: OK
|
||||||
|
assertEquals( 5, p.length() )
|
||||||
|
// but us not available directly
|
||||||
|
assertThrows { p.d2() }
|
||||||
|
void
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## fields and visibility
|
||||||
|
|
||||||
|
It is possible to add non-constructor fields:
|
||||||
|
|
||||||
|
class Point(x,y) {
|
||||||
|
fun length() { sqrt(x*x + y*y) }
|
||||||
|
|
||||||
|
// set at construction time:
|
||||||
|
val initialLength = length()
|
||||||
|
}
|
||||||
|
val p = Point(3,4)
|
||||||
|
p.x = 3
|
||||||
|
p.y = 0
|
||||||
|
assertEquals( 3, p.length() )
|
||||||
|
// but initial length could not be changed after as declard val:
|
||||||
|
assert( p.initialLength == 5 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
### Mutable fields
|
||||||
|
|
||||||
|
Are declared with var
|
||||||
|
|
||||||
|
class Point(x,y) {
|
||||||
|
var isSpecial = false
|
||||||
|
}
|
||||||
|
val p = Point(0,0)
|
||||||
|
assert( p.isSpecial == false )
|
||||||
|
|
||||||
|
p.isSpecial = true
|
||||||
|
assert( p.isSpecial == true )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
### Private fields
|
||||||
|
|
||||||
|
Private fields are visible only _inside the class instance_:
|
||||||
|
|
||||||
|
class SecretCounter {
|
||||||
|
private var count = 0
|
||||||
|
|
||||||
|
fun increment() {
|
||||||
|
count++
|
||||||
|
void // hide counter
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isEnough() {
|
||||||
|
count > 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val c = SecretCounter()
|
||||||
|
assert( c.isEnough() == false )
|
||||||
|
assert( c.increment() == void )
|
||||||
|
for( i in 0..10 ) c.increment()
|
||||||
|
assert( c.isEnough() )
|
||||||
|
|
||||||
|
// but the count is not available outside:
|
||||||
|
assertThrows { c.count }
|
||||||
|
void
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
It is possible to provide private constructor parameters so they can be
|
||||||
|
set at construction but not available outside the class:
|
||||||
|
|
||||||
|
class SecretCounter(private var count = 0) {
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
val c = SecretCounter(10)
|
||||||
|
assertThrows { c.count }
|
||||||
|
void
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Default class methods
|
||||||
|
|
||||||
|
In many cases it is necessary to implement custom comparison and `toString`, still
|
||||||
|
each class is provided with default implementations:
|
||||||
|
|
||||||
|
- default toString outputs class name and its _public_ fields.
|
||||||
|
- default comparison compares all fields in order of appearance.
|
||||||
|
|
||||||
|
For example, for our class Point:
|
||||||
|
|
||||||
|
class Point(x,y)
|
||||||
|
assert( Point(1,2) == Point(1,2) )
|
||||||
|
assert( Point(1,2) !== Point(1,2) )
|
||||||
|
assert( Point(1,2) != Point(1,3) )
|
||||||
|
assert( Point(1,2) < Point(2,2) )
|
||||||
|
assert( Point(1,2) < Point(1,3) )
|
||||||
|
Point(1,1+1)
|
||||||
|
>>> Point(x=1,y=2)
|
||||||
|
|
||||||
|
## Statics: class fields and class methods
|
||||||
|
|
||||||
|
You can mark a field or a method as static. This is borrowed from Java as more plain version of a kotlin's companion object or Scala's object. Static field and functions is one for a class, not for an instance. From inside the class, e.g. from the class method, it is a regular var. From outside, it is accessible as `ClassName.field` or method:
|
||||||
|
|
||||||
|
|
||||||
|
class Value(x) {
|
||||||
|
static var foo = Value("foo")
|
||||||
|
|
||||||
|
static fun exclamation() {
|
||||||
|
// here foo is a regular var:
|
||||||
|
foo.x + "!"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals( Value.foo.x, "foo" )
|
||||||
|
assertEquals( "foo!", Value.exclamation() )
|
||||||
|
|
||||||
|
// we can access foo from outside like this:
|
||||||
|
Value.foo = Value("bar")
|
||||||
|
assertEquals( "bar!", Value.exclamation() )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
As usual, private statics are not accessible from the outside:
|
||||||
|
|
||||||
|
class Test {
|
||||||
|
// private, inacessible from outside protected data:
|
||||||
|
private static var data = null
|
||||||
|
|
||||||
|
// the interface to access and change it:
|
||||||
|
static fun getData() { data }
|
||||||
|
static fun setData(value) { data = value }
|
||||||
|
}
|
||||||
|
|
||||||
|
// no direct access:
|
||||||
|
assertThrows { Test.data }
|
||||||
|
|
||||||
|
// accessible with the interface:
|
||||||
|
assertEquals( null, Test.getData() )
|
||||||
|
Test.setData("fubar")
|
||||||
|
assertEquals("fubar", Test.getData() )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
# Extending classes
|
||||||
|
|
||||||
|
It sometimes happen that the class is missing some particular functionality that can be _added to it_ without rewriting its inner logic and using its private state. In this case _extension methods_ could be used, for example. we want to create an extension method
|
||||||
|
that would test if some object of unknown type contains something that can be interpreted
|
||||||
|
as an integer. In this case we _extend_ class `Object`, as it is the parent class for any instance of any type:
|
||||||
|
|
||||||
|
fun Object.isInteger() {
|
||||||
|
when(this) {
|
||||||
|
// already Int?
|
||||||
|
is Int -> true
|
||||||
|
|
||||||
|
// real, but with no declimal part?
|
||||||
|
is Real -> toInt() == this
|
||||||
|
|
||||||
|
// string with int or real reuusig code above
|
||||||
|
is String -> toReal().isInteger()
|
||||||
|
|
||||||
|
// otherwise, no:
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Let's test:
|
||||||
|
assert( 12.isInteger() == true )
|
||||||
|
assert( 12.1.isInteger() == false )
|
||||||
|
assert( "5".isInteger() )
|
||||||
|
assert( ! "5.2".isInteger() )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
__Important note__ as for version 0.6.9, extensions are in __global scope__. It means, that once applied to a global type (Int in our sample), they will be available for _all_ contexts, even new created,
|
||||||
|
as they are modifying the type, not the context.
|
||||||
|
|
||||||
|
Beware of it. We might need to reconsider it later.
|
||||||
|
|
||||||
|
# Theory
|
||||||
|
|
||||||
|
## Basic principles:
|
||||||
|
|
||||||
|
- Everything is an instance of some class
|
||||||
|
- Every class except Obj has at least one parent
|
||||||
|
- Obj has no parents and is the root of the hierarchy
|
||||||
|
- instance has member fields and member functions
|
||||||
|
- Every class has hclass members and class functions, or companion ones, are these of the base class.
|
||||||
|
- every class has _type_ which is an instances of ObjClass
|
||||||
|
- ObjClass sole parent is Obj
|
||||||
|
- ObjClass contains code for instance methods, class fields, hierarchy information.
|
||||||
|
- Class information is also scoped.
|
||||||
|
- We acoid imported classes duplication using packages and import caching, so the same imported module is the same object in all its classes.
|
||||||
|
|
||||||
|
## Instances
|
||||||
|
|
||||||
|
Result of executing of any expression or statement in the Lyng is the object that
|
||||||
|
inherits `Obj`, but is not `Obj`. For example it could be Int, void, null, real, string, bool, etc.
|
||||||
|
|
||||||
|
This means whatever expression returns or the variable holds, is the first-class
|
||||||
|
object, no differenes. For example:
|
||||||
|
|
||||||
|
1.67.roundToInt()
|
||||||
|
1>>> 2
|
||||||
|
|
||||||
|
Here, instance method of the real object, created from literal `1.67` is called.
|
||||||
|
|
||||||
|
## Instance class
|
||||||
|
|
||||||
|
Everything can be classified, and classes could be tested for equivalence:
|
||||||
|
|
||||||
|
3.14::class
|
||||||
|
1>>> Real
|
||||||
|
|
||||||
|
Class is the object, naturally, with class:
|
||||||
|
|
||||||
|
3.14::class::class
|
||||||
|
1>>> Class
|
||||||
|
|
||||||
|
Classes can be compared:
|
||||||
|
|
||||||
|
assert(1.21::class == Math.PI::class)
|
||||||
|
assert(3.14::class != 1::class)
|
||||||
|
assert(π::class == Real)
|
||||||
|
π::class
|
||||||
|
>>> Real
|
||||||
|
|
||||||
|
Note `Real` class: it is global variable for Real class; there are such class instances for all built-in types:
|
||||||
|
|
||||||
|
assert("Hello"::class == String)
|
||||||
|
assert(1970::class == Int)
|
||||||
|
assert(true::class == Bool)
|
||||||
|
assert('$'::class == Char)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Singleton classes also have class:
|
||||||
|
|
||||||
|
null::class
|
||||||
|
>>> Null
|
||||||
|
|
||||||
|
At this time, `Obj` can't be accessed as a class.
|
||||||
|
|
||||||
|
|
||||||
|
### Methods in-depth
|
||||||
|
|
||||||
|
Regular methods are called on instances as usual `instance.method()`. The method resolution order is
|
||||||
|
|
||||||
|
1. this instance methods;
|
||||||
|
2. parents method: no guarantee but we enumerate parents in order of appearance;
|
||||||
|
3. possible extension methods (scoped)
|
||||||
|
|
||||||
|
TBD
|
||||||
|
|
||||||
|
[argument list](declaring_arguments.md)
|
||||||
+107
@@ -0,0 +1,107 @@
|
|||||||
|
# Range
|
||||||
|
|
||||||
|
Range is diapason between two values. Open range has at least one end open, e.g. ±∞, closed range has both ends open.
|
||||||
|
|
||||||
|
## Closed ranges
|
||||||
|
|
||||||
|
The syntax is intuitive and adopted from Kotlin:
|
||||||
|
|
||||||
|
// end inclusive:
|
||||||
|
val r = 1..5
|
||||||
|
assert(5 in r)
|
||||||
|
assert(6 !in r)
|
||||||
|
assert(0 !in r)
|
||||||
|
assert(2 in r)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Exclusive end ranges are adopted from kotlin either:
|
||||||
|
|
||||||
|
// end inclusive:
|
||||||
|
val r = 1..<5
|
||||||
|
assert(5 !in r)
|
||||||
|
assert(6 !in r)
|
||||||
|
assert(0 !in r)
|
||||||
|
assert(2 in r)
|
||||||
|
assert(4 in r)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
In any case, we can test an object to belong to using `in` and `!in` and
|
||||||
|
access limits:
|
||||||
|
|
||||||
|
val r = 0..5
|
||||||
|
(r.end - r.start)/2
|
||||||
|
>>> 2
|
||||||
|
|
||||||
|
Notice, start and end are ints, so midpoint here is int too.
|
||||||
|
|
||||||
|
It is possible to test that one range is included in another range too,
|
||||||
|
one range is defined as _contained_ in another ifm and only if, it begin and end
|
||||||
|
are equal or within another, taking into account the end-inclusiveness:
|
||||||
|
|
||||||
|
assert( (1..3) in (1..3) )
|
||||||
|
assert( (0..3) !in (1..3) )
|
||||||
|
assert( (1..2) in (1..<3) )
|
||||||
|
assert( (1..<2) in (1..<3) )
|
||||||
|
assert( (1..<3) in (1..3) )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Finite Ranges are iterable
|
||||||
|
|
||||||
|
So given a range with both ends, you can assume it is [Iterable]. This automatically let
|
||||||
|
use finite ranges in loops and convert it to lists:
|
||||||
|
|
||||||
|
assert( [-2, -1, 0, 1] == (-2..1).toList() )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
In spite of this you can use ranges in for loops:
|
||||||
|
|
||||||
|
for( i in 1..3 )
|
||||||
|
println(i)
|
||||||
|
>>> 1
|
||||||
|
>>> 2
|
||||||
|
>>> 3
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
but
|
||||||
|
|
||||||
|
for( i in 1..<3 )
|
||||||
|
println(i)
|
||||||
|
>>> 1
|
||||||
|
>>> 2
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Character ranges
|
||||||
|
|
||||||
|
You can use Char as both ends of the closed range:
|
||||||
|
|
||||||
|
val r = 'a' .. 'c'
|
||||||
|
assert( 'b' in r)
|
||||||
|
assert( 'e' !in r)
|
||||||
|
for( ch in r )
|
||||||
|
println(ch)
|
||||||
|
>>> a
|
||||||
|
>>> b
|
||||||
|
>>> c
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Exclusive end char ranges are supported too:
|
||||||
|
|
||||||
|
('a'..<'c').toList
|
||||||
|
>>> ['a', 'b']
|
||||||
|
|
||||||
|
|
||||||
|
# Instance members
|
||||||
|
|
||||||
|
| member | description | args |
|
||||||
|
|-----------------|------------------------------|---------------|
|
||||||
|
| contains(other) | used in `in` | Range, or Any |
|
||||||
|
| isEndInclusive | true for '..' | Bool |
|
||||||
|
| isOpen | at any end | Bool |
|
||||||
|
| isIntRange | both start and end are Int | Bool |
|
||||||
|
| start | | Bool |
|
||||||
|
| end | | Bool |
|
||||||
|
| size | for finite ranges, see above | Long |
|
||||||
|
| [] | see above | |
|
||||||
|
| | | |
|
||||||
|
|
||||||
|
[Iterable]: Iterable.md
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Real built-in class
|
||||||
|
|
||||||
|
Class that supports double-precision math. Woks much like double in other languages. We honor no floats, so it is '
|
||||||
|
Real'.
|
||||||
|
|
||||||
|
It's class in Lyng is `Real`:
|
||||||
|
|
||||||
|
(π/2)::class
|
||||||
|
>>> Real
|
||||||
|
|
||||||
|
you can use it's class to ensure type:
|
||||||
|
|
||||||
|
1.71::class == Real
|
||||||
|
>>> true
|
||||||
|
|
||||||
|
## Member functions
|
||||||
|
|
||||||
|
| name | meaning | type |
|
||||||
|
|-----------------|-------------------------------------------------------------|------|
|
||||||
|
| `.roundToInt()` | round to nearest int like round(x) | Int |
|
||||||
|
| `.toInt()` | convert integer part of real to `Int` dropping decimal part | Int |
|
||||||
|
| | | |
|
||||||
|
| | | |
|
||||||
|
| | | |
|
||||||
|
| | | |
|
||||||
+94
@@ -0,0 +1,94 @@
|
|||||||
|
# List built-in class
|
||||||
|
|
||||||
|
Mutable set of any objects: a group of different objects, no repetitions.
|
||||||
|
Sets are not ordered, order of appearance does not matter.
|
||||||
|
|
||||||
|
val set = Set(1,2,3, "foo")
|
||||||
|
assert( 1 in set )
|
||||||
|
assert( "foo" in set)
|
||||||
|
assert( "bar" !in set)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Set is collection and therefore [Iterable]:
|
||||||
|
|
||||||
|
assert( Set(1,2) is Set)
|
||||||
|
assert( Set(1,2) is Iterable)
|
||||||
|
assert( Set(1,2) is Collection)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
So it supports all methods from [Iterable]; set is not, though, an [Array] and has
|
||||||
|
no indexing. Use [set.toList] as needed.
|
||||||
|
|
||||||
|
## Set operations
|
||||||
|
|
||||||
|
// Union
|
||||||
|
assertEquals( Set(1,2,3,4), Set(3, 1) + Set(2, 4))
|
||||||
|
|
||||||
|
// intersection
|
||||||
|
assertEquals( Set(1,4), Set(3, 1, 4).intersect(Set(2, 4, 1)) )
|
||||||
|
// or simple
|
||||||
|
assertEquals( Set(1,4), Set(3, 1, 4) * Set(2, 4, 1) )
|
||||||
|
|
||||||
|
// To find collection elements not present in another collection, use the
|
||||||
|
// subtract() or `-`:
|
||||||
|
assertEquals( Set( 1, 2), Set(1, 2, 4, 3) - Set(3, 4))
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Adding elements
|
||||||
|
|
||||||
|
var s = Set()
|
||||||
|
s += 1
|
||||||
|
assertEquals( Set(1), s)
|
||||||
|
|
||||||
|
s += [3, 3, 4]
|
||||||
|
assertEquals( Set(3, 4, 1), s)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Removing elements
|
||||||
|
|
||||||
|
List is mutable, so it is possible to remove its contents. To remove a single element
|
||||||
|
by index use:
|
||||||
|
|
||||||
|
var s = Set(1,2,3)
|
||||||
|
s.remove(2)
|
||||||
|
assertEquals( s, Set(1,3) )
|
||||||
|
|
||||||
|
s = Set(1,2,3)
|
||||||
|
s.remove(2,1)
|
||||||
|
assertEquals( s, Set(3) )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Note that `remove` returns true if at least one element was actually removed and false
|
||||||
|
if the set has not been changed.
|
||||||
|
|
||||||
|
## Comparisons and inclusion
|
||||||
|
|
||||||
|
Sets are only equal when contains exactly same elements, order, as was said, is not significant:
|
||||||
|
|
||||||
|
assert( Set(1, 2) == Set(2, 1) )
|
||||||
|
assert( Set(1, 2, 2) == Set(2, 1) )
|
||||||
|
assert( Set(1, 3) != Set(2, 1) )
|
||||||
|
assert( 1 in Set(5,1))
|
||||||
|
assert( 10 !in Set(5,1))
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Members
|
||||||
|
|
||||||
|
| name | meaning | type |
|
||||||
|
|---------------------|--------------------------------------|-------|
|
||||||
|
| `size` | current size | Int |
|
||||||
|
| `+=` | add one or more elements | Any |
|
||||||
|
| `+`, `union` | union sets | Any |
|
||||||
|
| `-`, `subtract` | subtract sets | Any |
|
||||||
|
| `*`, `intersect` | subtract sets | Any |
|
||||||
|
| `remove(items...)` | remove one or more items | Range |
|
||||||
|
| `contains(element)` | check the element is in the list (1) | |
|
||||||
|
|
||||||
|
(1)
|
||||||
|
: optimized implementation that override `Iterable` one
|
||||||
|
|
||||||
|
Also, it inherits methods from [Iterable].
|
||||||
|
|
||||||
|
|
||||||
|
[Range]: Range.md
|
||||||
Whitespace-only changes.
@@ -0,0 +1,117 @@
|
|||||||
|
# Advanced topics
|
||||||
|
|
||||||
|
__See also:__ [parallelism].
|
||||||
|
|
||||||
|
## Closures/scopes isolation
|
||||||
|
|
||||||
|
Each block has own scope, in which it can safely use closures and override
|
||||||
|
outer vars. Lets use some lambdas to create isolated scopes:
|
||||||
|
|
||||||
|
var param = "global"
|
||||||
|
val prefix = "param in "
|
||||||
|
|
||||||
|
val scope1 = {
|
||||||
|
var param = prefix + "scope1"
|
||||||
|
param
|
||||||
|
}
|
||||||
|
|
||||||
|
val scope2 = {
|
||||||
|
var param = prefix + "scope2"
|
||||||
|
param
|
||||||
|
}
|
||||||
|
|
||||||
|
println(scope1())
|
||||||
|
println(scope2())
|
||||||
|
println(param)
|
||||||
|
>>> param in scope1
|
||||||
|
>>> param in scope2
|
||||||
|
>>> global
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
One interesting way of using closure isolation is to keep state of the functions:
|
||||||
|
|
||||||
|
val getAndIncrement = {
|
||||||
|
// will be updated by doIt()
|
||||||
|
var counter = 0
|
||||||
|
|
||||||
|
// we return callable fn from the block:
|
||||||
|
fun doit() {
|
||||||
|
val was = counter
|
||||||
|
counter = counter + 1
|
||||||
|
was
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
// notice using of () above: it calls the lambda block that returns
|
||||||
|
// a function (callable!) that we will use:
|
||||||
|
println(getAndIncrement())
|
||||||
|
println(getAndIncrement())
|
||||||
|
println(getAndIncrement())
|
||||||
|
>>> 0
|
||||||
|
>>> 1
|
||||||
|
>>> 2
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Inner `counter` is not accessible from outside, no way; still it is kept
|
||||||
|
between calls in the closure, as inner function `doit`, returned from the
|
||||||
|
block, keeps reference to it and keeps it alive.
|
||||||
|
|
||||||
|
The example above could be rewritten using inner lambda, too:
|
||||||
|
|
||||||
|
val getAndIncrement = {
|
||||||
|
// will be updated by doIt()
|
||||||
|
var counter = 0
|
||||||
|
|
||||||
|
// we return callable fn from the block:
|
||||||
|
{
|
||||||
|
val was = counter
|
||||||
|
counter = counter + 1
|
||||||
|
was
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
// notice using of () above: it calls the lambda block that returns
|
||||||
|
// a function (callable!) that we will use:
|
||||||
|
println(getAndIncrement())
|
||||||
|
println(getAndIncrement())
|
||||||
|
println(getAndIncrement())
|
||||||
|
>>> 0
|
||||||
|
>>> 1
|
||||||
|
>>> 2
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Lambda functions remember their scopes, so it will work the same as previous:
|
||||||
|
|
||||||
|
var counter = 200
|
||||||
|
fun createLambda() {
|
||||||
|
var counter = 0
|
||||||
|
{ counter += 1 }
|
||||||
|
}
|
||||||
|
val c = createLambda()
|
||||||
|
println(c)
|
||||||
|
>> 1
|
||||||
|
>> 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
|
||||||
|
|
||||||
|
,
|
||||||
|
|
||||||
|
[parallelism]: parallelism.md
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Classes
|
||||||
|
|
||||||
|
## Declaring
|
||||||
|
|
||||||
|
class Foo1
|
||||||
|
class Foo2() // same, empty constructor
|
||||||
|
class Foo3() { // full
|
||||||
|
}
|
||||||
|
class Foo4 { // Only body
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
class_declaration = ["abstract",] "class" [, constructor] [, body]
|
||||||
|
constructor = "(", [field [, field]] ")
|
||||||
|
field = [visibility ,] [access ,] name [, typedecl]
|
||||||
|
body = [visibility] ("var", vardecl) | ("val", vardecl) | ("fun", fundecl)
|
||||||
|
visibility = "private" | "protected" | "internal"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Abstract classes
|
||||||
|
|
||||||
|
Contain one pr more abstract methods which must be implemented; though they
|
||||||
|
can have constructors, the instances of the abstract classes could not be
|
||||||
|
created independently
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# Declaring arguments in Lyng
|
||||||
|
|
||||||
|
It is a common thing that occurs in many places in Lyng, function declarations,
|
||||||
|
lambdas and class declarations.
|
||||||
|
|
||||||
|
## Regular
|
||||||
|
|
||||||
|
## default values
|
||||||
|
|
||||||
|
Default parameters should not be mixed with mandatory ones:
|
||||||
|
|
||||||
|
// ok:
|
||||||
|
fun validFun(a, b, c=0, d=1) {}
|
||||||
|
|
||||||
|
// this is a compilration error
|
||||||
|
fun invalidFun(a, b=1, c) {} // throw error
|
||||||
|
|
||||||
|
Valid examples:
|
||||||
|
|
||||||
|
fun foo(bar, baz="buz", end= -1) {
|
||||||
|
println(bar + ' ' + baz + ' ' + end)
|
||||||
|
}
|
||||||
|
foo("bar")
|
||||||
|
foo("nobar", "buzz")
|
||||||
|
foo("nobar", "buzz", 120)
|
||||||
|
>>> bar buz -1
|
||||||
|
>>> nobar buzz -1
|
||||||
|
>>> nobar buzz 120
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
# Ellipsis
|
||||||
|
|
||||||
|
Ellipsis are used to declare variadic arguments. It basically means "all the arguments available here". It means, ellipsis argument could be in any part of the list, being, end or middle, but there could be only one ellipsis argument and it must not have default value, its default value is always `[]`, en empty list.
|
||||||
|
|
||||||
|
Ellipsis argument receives what is left from arguments after processing regular one that could be before or after.
|
||||||
|
|
||||||
|
Ellipsis could be a first argument:
|
||||||
|
|
||||||
|
fun testCountArgs(data...,size) {
|
||||||
|
assert(size is Int)
|
||||||
|
assertEquals(size, data.size)
|
||||||
|
}
|
||||||
|
testCountArgs( 1, 2, "three", 3)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Ellipsis could also be a last one:
|
||||||
|
|
||||||
|
fun testCountArgs(size, data...) {
|
||||||
|
assert(size is Int)
|
||||||
|
assertEquals(size, data.size)
|
||||||
|
}
|
||||||
|
testCountArgs( 3, 10, 2, "three")
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Or in the middle:
|
||||||
|
|
||||||
|
fun testCountArgs(size, data..., textToReturn) {
|
||||||
|
assert(size is Int)
|
||||||
|
assertEquals(size, data.size)
|
||||||
|
textToReturn
|
||||||
|
}
|
||||||
|
testCountArgs( 3, 10, 2, "three", "All OK")
|
||||||
|
>>> "All OK"
|
||||||
|
|
||||||
|
## Destructuring with splats
|
||||||
|
|
||||||
|
When combined with splat arguments discussed in the [tutorial] it could be used to effectively
|
||||||
|
destructuring arrays when calling functions and lambdas:
|
||||||
|
|
||||||
|
fun getFirstAndLast(first, args..., last) {
|
||||||
|
[ first, last ]
|
||||||
|
}
|
||||||
|
getFirstAndLast( ...(1..10) ) // see "splats" section below
|
||||||
|
>>> [1, 10]
|
||||||
|
|
||||||
|
# Splats
|
||||||
|
|
||||||
|
Ellipsis allows to convert argument lists to lists. The inversa algorithm that converts [List],
|
||||||
|
or whatever implementing [Iterable], is called _splats_. Here is how we use it:
|
||||||
|
|
||||||
|
fun testSplat(data...) {
|
||||||
|
println(data)
|
||||||
|
}
|
||||||
|
val array = [1,2,3]
|
||||||
|
testSplat("start", ...array, "end")
|
||||||
|
>>> ["start", 1, 2, 3, "end"]
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
There could be any number of splats at any positions. You can splat any other [Iterable] type:
|
||||||
|
|
||||||
|
fun testSplat(data...) {
|
||||||
|
println(data)
|
||||||
|
}
|
||||||
|
val range = 1..3
|
||||||
|
testSplat("start", ...range, "end")
|
||||||
|
>>> ["start", 1, 2, 3, "end"]
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
|
||||||
|
[tutorial]: tutorial.md
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
# Modules inclusion
|
||||||
|
|
||||||
|
Module is, at the low level, a statement that modifies a given context by adding
|
||||||
|
here local and exported symbols, performing some tasks and even returning some value
|
||||||
|
we don't need for now.
|
||||||
|
|
||||||
|
The compiled module is therefore a statement. When we execute it on some context,
|
||||||
|
it wills it with all it symbols, private too.
|
||||||
|
|
||||||
|
If we call it on another context, it will do it once more, no caching. This is unnecessary
|
||||||
|
if not dangerous repetition.
|
||||||
|
|
||||||
|
## What is inclusion?
|
||||||
|
|
||||||
|
The _goal_ of the inclusion is to make _exported symbols_ available in a given context,
|
||||||
|
without re-executing included module initialization code. So, when we hit the `import foo`,
|
||||||
|
we should check that foo module was executed, execute it if not on special context we store in the library, then copy all public symbols from fooContext into current one.
|
||||||
|
|
||||||
|
## Class pseudo-module
|
||||||
|
|
||||||
|
Mostly same we can do with a class
|
||||||
|
|
||||||
|
## Module initialization
|
||||||
|
|
||||||
|
We can just put the code into the module code:
|
||||||
|
|
||||||
|
module lying.samples.module
|
||||||
|
// or package?
|
||||||
|
|
||||||
|
val startuptTime = Instant.now()
|
||||||
|
|
||||||
|
// private: not available from outside
|
||||||
|
private fun moduleInitialization() {
|
||||||
|
// long code
|
||||||
|
}
|
||||||
|
|
||||||
|
// this will be called only once
|
||||||
|
moduleInitialization()
|
||||||
|
|
||||||
|
## class initialization
|
||||||
|
|
||||||
|
already done using `ObjInstance` class and instance-bound context with local
|
||||||
|
context stored in ObjInstance and class constructor statement in ObjClass.
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# Exceptions handling
|
||||||
|
|
||||||
|
Exceptions are widely used in modern programming languages, so
|
||||||
|
they are implemented also in Lyng and in the most complete way.
|
||||||
|
|
||||||
|
# Exception classes
|
||||||
|
|
||||||
|
Exceptions are throwing instances of some class that inherits `Exception`
|
||||||
|
across the code. Below is the list of built-in exceptions. Note that
|
||||||
|
only objects that inherit `Exception` can be thrown. For example:
|
||||||
|
|
||||||
|
assert( IllegalArgumentException() is Exception)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
# Try statement: catching exceptions
|
||||||
|
|
||||||
|
There general pattern is:
|
||||||
|
|
||||||
|
```
|
||||||
|
try_statement = try_clause, [catch_clause, ...], [finally_clause]
|
||||||
|
|
||||||
|
try_clause = "try", "{", statements, "}"
|
||||||
|
|
||||||
|
catch_clause = "catch", [(full_catch | shorter_catch)], "{", statements "}"
|
||||||
|
|
||||||
|
full_catch = "(", catch_var, ":", exception_class [, excetpion_class...], ")
|
||||||
|
|
||||||
|
shorter_catch = "(", catch_var, ")"
|
||||||
|
|
||||||
|
finally_clause = "{", statements, "}"
|
||||||
|
```
|
||||||
|
|
||||||
|
Let's in details.
|
||||||
|
|
||||||
|
## Full catch block:
|
||||||
|
|
||||||
|
val result = try {
|
||||||
|
throw IllegalArgumentException("the test")
|
||||||
|
}
|
||||||
|
catch( x: IndexOutOfBoundsException, IllegalArgumentException) {
|
||||||
|
x.message
|
||||||
|
}
|
||||||
|
catch(x: Exception) {
|
||||||
|
"bad"
|
||||||
|
}
|
||||||
|
assertEquals(result, "the test")
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Because our exception is listed in a first catch block, it is processed there.
|
||||||
|
|
||||||
|
The full form allow a single catch block to process exceptions with specified classes and bind actual caught object to
|
||||||
|
the given variable. This is most common and well known form, implemented like this or similar in many other languages,
|
||||||
|
like Kotlin, Java or C++.
|
||||||
|
|
||||||
|
## Shorter form
|
||||||
|
|
||||||
|
When you want to catch _all_ the exceptions, you should write `catch(e: Exception)`,
|
||||||
|
but it is somewhat redundant, so there is simpler variant:
|
||||||
|
|
||||||
|
val sample2 = try {
|
||||||
|
throw IllegalArgumentException("sample 2")
|
||||||
|
}
|
||||||
|
catch(x) {
|
||||||
|
x.message
|
||||||
|
}
|
||||||
|
assertEquals( sample2, "sample 2" )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
But well most likely you will find default variable `it`, like in Kotlin, more than enough
|
||||||
|
to catch all exceptions to, then you can write it even shorter:
|
||||||
|
|
||||||
|
val sample2 = try {
|
||||||
|
throw IllegalArgumentException("sample 3")
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
it.message
|
||||||
|
}
|
||||||
|
assertEquals( sample2, "sample 3" )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
The simplest way is to provide exception string and `Exception` class:
|
||||||
|
|
||||||
|
try {
|
||||||
|
throw Exception("this is my exception")
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
it.message
|
||||||
|
}
|
||||||
|
>>> "this is my exception"
|
||||||
|
|
||||||
|
This way, in turn, can also be shortened, as it is overly popular:
|
||||||
|
|
||||||
|
try {
|
||||||
|
throw "this is my exception"
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
it.message
|
||||||
|
}
|
||||||
|
>>> "this is my exception"
|
||||||
|
|
||||||
|
The trick, though, works with strings only, and always provide `Exception` instances, which is good for debugging but
|
||||||
|
most often not enough.
|
||||||
|
|
||||||
|
# Custom error classes
|
||||||
|
|
||||||
|
_this functionality is not yet released_
|
||||||
|
|
||||||
|
# Standard exception classes
|
||||||
|
|
||||||
|
| class | notes |
|
||||||
|
|----------------------------|-------------------------------------------------------|
|
||||||
|
| Exception | root of al throwable objects |
|
||||||
|
| NullReferenceException | |
|
||||||
|
| AssertionFailedException | |
|
||||||
|
| ClassCastException | |
|
||||||
|
| IndexOutOfBoundsException | |
|
||||||
|
| IllegalArgumentException | |
|
||||||
|
| IllegalAssignmentException | assigning to val, etc. |
|
||||||
|
| SymbolNotDefinedException | |
|
||||||
|
| IterationEndException | attempt to read iterator past end, `hasNext == false` |
|
||||||
|
| AccessException | attempt to access private members or like |
|
||||||
|
| UnknownException | unexpected kotlin exception caught |
|
||||||
|
| | |
|
||||||
|
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# Operators
|
||||||
|
|
||||||
|
## Precedence
|
||||||
|
|
||||||
|
Same as in C++.
|
||||||
|
|
||||||
|
| Priority | Operations |
|
||||||
|
|:----------------:|--------------------------------------|
|
||||||
|
| **Highest**<br>0 | power, not, calls, indexing, dot,... |
|
||||||
|
| 1 | `%` `*` `/` |
|
||||||
|
| 2 | `+` `-` |
|
||||||
|
| 3 | bit shifts (NI) |
|
||||||
|
| 4 | `<=>` (1) |
|
||||||
|
| 5 | `<=` `>=` `<` `>` |
|
||||||
|
| 6 | `==` `!=` |
|
||||||
|
| 7 | bitwise and `&` (NI) |
|
||||||
|
| 9 | bitwise or `\|` (NI) |
|
||||||
|
| 10 | `&&` |
|
||||||
|
| 11<br/>lowest | `\|\|` |
|
||||||
|
|
||||||
|
(NI)
|
||||||
|
: not yet implemented.
|
||||||
|
|
||||||
|
(1)
|
||||||
|
: Shuttle operator: `a <=> b` returns 0 if a == b, negative Int if a < b and positive Int otherwise. It is necessary to
|
||||||
|
override shuttle operator to make a class comparable.
|
||||||
|
|
||||||
|
## Operators
|
||||||
|
|
||||||
|
`+ - * / % `: if both operand is `Int`, calculates as int. Otherwise, as real:
|
||||||
|
|
||||||
|
// integer division:
|
||||||
|
3 / 2
|
||||||
|
>>> 1
|
||||||
|
|
||||||
|
but:
|
||||||
|
|
||||||
|
3 / 2.0
|
||||||
|
>>> 1.5
|
||||||
|
|
||||||
|
## Round and range
|
||||||
|
|
||||||
|
The following functions return its argument if it is `Int`,
|
||||||
|
or transformed `Real` otherwise.
|
||||||
|
|
||||||
|
| name | description |
|
||||||
|
|----------------|--------------------------------------------------------|
|
||||||
|
| floor(x) | Computes the largest integer value not greater than x |
|
||||||
|
| ceil(x) | Computes the least integer value value not less than x |
|
||||||
|
| round(x) | Rounds x |
|
||||||
|
| x.roundToInt() | shortcut to `round(x).toInt()` |
|
||||||
|
|
||||||
|
## Lyng math functions
|
||||||
|
|
||||||
|
| name | meaning |
|
||||||
|
|-----------|------------------------------------------------------|
|
||||||
|
| sin(x) | sine |
|
||||||
|
| cos(x) | cosine |
|
||||||
|
| tan(x) | tangent |
|
||||||
|
| asin(x) | $sin^{-1}(x)$ |
|
||||||
|
| acos(x) | $cos^{-1}(x)$ |
|
||||||
|
| atan(x) | $tg^{-1}(x)$ |
|
||||||
|
| sinh(x) | hyperbolic sine |
|
||||||
|
| cosh(x) | hyperbolic cosine |
|
||||||
|
| tanh(x) | hyperbolic tangent |
|
||||||
|
| asinh(x) | $sinh^{-1}(x)$ |
|
||||||
|
| acosh(x) | $cosh^{-1}(x)$ |
|
||||||
|
| atanh(x) | $tgh^{-1}(x)$ |
|
||||||
|
| ln(x) | $ln(x)$, $ log_e(x) $ |
|
||||||
|
| exp(x) | $e^x$ |
|
||||||
|
| log10(x) | $log_{10}(x)$ |
|
||||||
|
| pow(x, y) | ${x^y}$ |
|
||||||
|
| sqrt(x) | $ \sqrt {x}$ |
|
||||||
|
| abs(x) | absolute value of x. Int if x is Int, Real otherwise |
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
assert( sin(π/2) == 1.0)
|
||||||
|
assert( cos(π/2) < 0.000001)
|
||||||
|
assert( abs(ln(exp(1))) - 1 < 0.00001)
|
||||||
|
|
||||||
|
// abs() keeps the argument type:
|
||||||
|
assert( abs(-1) is Int)
|
||||||
|
assert( abs(-2.21) == 2.21 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Scientific constant
|
||||||
|
|
||||||
|
| name | meaning |
|
||||||
|
|----------------------|--------------|
|
||||||
|
| `Math.PI: Real` or π | 3.1415926... |
|
||||||
|
| | |
|
||||||
|
| | |
|
||||||
|
| | |
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# Parallelism in Lyng
|
||||||
|
|
||||||
|
Lyng is built to me multithreaded where possible (e.g. all targets byt JS and wasmJS as for now)
|
||||||
|
and cooperatively parallel (coroutine based) everywhere.
|
||||||
|
|
||||||
|
In Lyng, every function, every lambda are _coroutines_. It means, you can have as many of these as you want without risking running out of memory on threads stack, or get too many threads.
|
||||||
|
|
||||||
|
Depending on the platform, these coroutines may be executed on different CPU and cores, too, truly in parallel. Where not, like Javascript browser, they are still executed cooperatively. You should not care about the platform capabilities, just call `launch`:
|
||||||
|
|
||||||
|
// track coroutine call:
|
||||||
|
var xIsCalled = false
|
||||||
|
|
||||||
|
// launch coroutine in parallel
|
||||||
|
val x = launch {
|
||||||
|
// wait 10ms to let main code to be executed
|
||||||
|
delay(10)
|
||||||
|
// now set the flag
|
||||||
|
xIsCalled = true
|
||||||
|
// and return something useful:
|
||||||
|
"ok"
|
||||||
|
}
|
||||||
|
// corouine is launhed, but not yet executed
|
||||||
|
// due to delay call:
|
||||||
|
assert(!xIsCalled)
|
||||||
|
|
||||||
|
// now we wait for it to be executed:
|
||||||
|
assertEquals( x.await(), "ok")
|
||||||
|
|
||||||
|
// now glag should be set:
|
||||||
|
assert(xIsCalled)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
This example shows how to launch a coroutine with `launch` which returns [Deferred] instance, the latter have ways to await for the coroutine completion and retrieve possible result.
|
||||||
|
|
||||||
|
Launch has the only argument which should be a callable (lambda usually) that is run in parallel (or cooperatively in parallel), and return anything as the result.
|
||||||
|
|
||||||
|
## Synchronization: Mutex
|
||||||
|
|
||||||
|
Suppose we have a resource, that could be used concurrently, a coutner in our case. If we won'r protect it, concurrent usage cause RC, Race Condition, providing wrong result:
|
||||||
|
|
||||||
|
var counter = 0
|
||||||
|
|
||||||
|
(1..4).map {
|
||||||
|
launch {
|
||||||
|
// slow increment:
|
||||||
|
val c = counter
|
||||||
|
delay(10)
|
||||||
|
counter = c + 1
|
||||||
|
}
|
||||||
|
}.forEach { it.await() }
|
||||||
|
assert(counter < 4)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
The obviously wrong result is not 4, as all coroutines capture the counter value, which is 1, then sleep for 5ms, then save 1 + 1 as result. May some coroutines will pass, so it will be 1 or 2, most likely.
|
||||||
|
|
||||||
|
Using [Mutex] makes it all working:
|
||||||
|
|
||||||
|
var counter = 0
|
||||||
|
val mutex = Mutex()
|
||||||
|
|
||||||
|
(1..4).map {
|
||||||
|
launch {
|
||||||
|
// slow increment:
|
||||||
|
mutex.withLock {
|
||||||
|
val c = counter
|
||||||
|
delay(10)
|
||||||
|
counter = c + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.forEach { it.await() }
|
||||||
|
assertEquals(4, counter)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
now everything works as expected: `mutex.withLock` makes them all be executed in sequence, not in parallel.
|
||||||
|
|
||||||
|
|
||||||
|
## Completable deferred
|
||||||
|
|
||||||
|
Sometimes it is convenient to manually set completion status of some deferred result. This is when [CompletableDeferred] is used:
|
||||||
|
|
||||||
|
// this variable will be completed later:
|
||||||
|
val done = CompletableDeferred()
|
||||||
|
|
||||||
|
// complete it ater delay
|
||||||
|
launch {
|
||||||
|
delay(10)
|
||||||
|
// complete it setting the result:
|
||||||
|
done.complete("ok")
|
||||||
|
}
|
||||||
|
|
||||||
|
// now it is still not completed: coroutine is delayed
|
||||||
|
// (ot not started on sinthe-threaded platforms):
|
||||||
|
assert(!done.isCompleted)
|
||||||
|
assert(done.isActive)
|
||||||
|
|
||||||
|
// then we can just await it as any other deferred:
|
||||||
|
assertEquals( done.await(), "ok")
|
||||||
|
// and as any other deferred it is now complete:
|
||||||
|
assert(done.isCompleted)
|
||||||
|
|
||||||
|
## True parallelism
|
||||||
|
|
||||||
|
Cooperative, coroutine-based parallelism is automatically available on all platforms. Depending on the platform, though, the coroutines could be dispatched also in different threads; where there are multiple cores and/or CPU available, it means the coroutines could be exuted truly in parallel, unless [Mutex] is used:
|
||||||
|
|
||||||
|
| platofrm | multithreaded |
|
||||||
|
|------------|---------------|
|
||||||
|
| JVM | yes |
|
||||||
|
| Android | yes |
|
||||||
|
| Javascript | NO |
|
||||||
|
| wasmJS | NO |
|
||||||
|
| IOS | yes |
|
||||||
|
| MacOSX | yes |
|
||||||
|
| Linux | yes |
|
||||||
|
| Windows | yes |
|
||||||
|
|
||||||
|
So it is important to always use [Mutex] where concurrent execution could be a problem (so called Race Conditions, or RC).
|
||||||
|
|
||||||
|
## Yield
|
||||||
|
|
||||||
|
When the coroutine is executed, on the single-threaded environment all other coroutines are suspended until active one will wait for something. Sometimes, it is undesirable; the coroutine may perform long calculations or some other CPU consuming task. The solution is to call `yield()` periodically. Unlike `delay()`, yield does not pauses the coroutine for some specified time, but it just makes all other coroutines to be executed. In other word, yield interrupts current coroutines and out it to the end of the dispatcher list of active coroutines. It is especially important on Javascript and wasmJS targets as otherwise UI thread could be blocked.
|
||||||
|
|
||||||
|
Usage example:
|
||||||
|
|
||||||
|
fun someLongTask() { // ...
|
||||||
|
do {
|
||||||
|
// execute step
|
||||||
|
if( done ) break
|
||||||
|
yield()
|
||||||
|
} while(true)
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# Sample combinatorics calculations
|
||||||
|
|
||||||
|
The trivial to start with, the factorialorial calculation:
|
||||||
|
|
||||||
|
fun factorial(n) {
|
||||||
|
if( n < 1 )
|
||||||
|
1
|
||||||
|
else {
|
||||||
|
var result = 1
|
||||||
|
var cnt = 2
|
||||||
|
while( cnt <= n ) result = result * cnt++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Let's test it:
|
||||||
|
|
||||||
|
assert(factorial(2) == 2)
|
||||||
|
assert(factorial(3) == 6)
|
||||||
|
assert(factorial(4) == 24)
|
||||||
|
assert(factorial(5) == 120)
|
||||||
|
|
||||||
|
Now let's calculate _combination_, or the polynomial coefficient $C^n_k$. It is trivial also, the formulae is:
|
||||||
|
|
||||||
|
$$C^n_k = \frac {n!} {k! (n-k)!} $$
|
||||||
|
|
||||||
|
We can simplify it a little, as $ n ≥ k $, we can remove $k!$ from the fraction:
|
||||||
|
|
||||||
|
$$C^n_k = \frac {(k+1)(k+1)...n} { (n-k)!} $$
|
||||||
|
|
||||||
|
Now the code is much more effective:
|
||||||
|
|
||||||
|
fun C(n,k) {
|
||||||
|
var result = k+1
|
||||||
|
var ck = result + 1
|
||||||
|
while( ck <= n ) result *= ck++
|
||||||
|
result / factorial(n-k)
|
||||||
|
}
|
||||||
|
|
||||||
|
println(C(10,3))
|
||||||
|
assert( C(10, 3) == 120 )
|
||||||
|
|
||||||
|
to be continued...
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
/*
|
||||||
|
Count "happy tickets": 6-digit numbers where sum of first three
|
||||||
|
digits is equal to those of last three. Just to demonstrate and
|
||||||
|
test the Lyng way. It is not meant to be effective.
|
||||||
|
*/
|
||||||
|
|
||||||
|
fun naiveCountHappyNumbers() {
|
||||||
|
var count = 0
|
||||||
|
for( n1 in 0..9 )
|
||||||
|
for( n2 in 0..9 )
|
||||||
|
for( n3 in 0..9 )
|
||||||
|
for( n4 in 0..9 )
|
||||||
|
for( n5 in 0..9 )
|
||||||
|
for( n6 in 0..9 )
|
||||||
|
if( n1 + n2 + n3 == n4 + n5 + n6 ) count++
|
||||||
|
count
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// After all optimizations it takes ~120ms.
|
||||||
|
//
|
||||||
|
val found = naiveCountHappyNumbers()
|
||||||
|
println("Found happy numbers: "+found)
|
||||||
|
assert( found == 55252 )
|
||||||
Executable
+3
@@ -0,0 +1,3 @@
|
|||||||
|
#!/bin/env jlyng
|
||||||
|
|
||||||
|
println("Hello, world!");
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/*
|
||||||
|
Calculate the limit of Sum( f(n) )
|
||||||
|
until it reaches asymptotic limit 0.00001% change
|
||||||
|
|
||||||
|
return null or found limit
|
||||||
|
*/
|
||||||
|
fun findSumLimit(f) {
|
||||||
|
var sum = 0.0
|
||||||
|
for( n in 1..1000000 ) {
|
||||||
|
val s0 = sum
|
||||||
|
sum += f(n)
|
||||||
|
if( abs(sum - s0) / abs(sum) < 1.0e-6 ) {
|
||||||
|
println("limit reached after "+n+" rounds")
|
||||||
|
break sum
|
||||||
|
}
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
println("limit not reached")
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val limit = findSumLimit { n -> 1.0/n/n }
|
||||||
|
|
||||||
|
println("Result: "+limit)
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# Пример расчета суммы ряда
|
||||||
|
|
||||||
|
Рассмотрим как можно посчитать предел суммы ряда на lyng. Для наивной реализации
|
||||||
|
представим что у нас есть функция рассчитывающая n-й член ряда. Тогда мы можем
|
||||||
|
считать сумму до тех пор, пока отклонение при расчете следующего члена не станет
|
||||||
|
меньше чем заданная погрешность:
|
||||||
|
|
||||||
|
fun сумма_ряда(x, погрешность=0.0001, f) {
|
||||||
|
var сумма = 0
|
||||||
|
for( n in 1..100000) {
|
||||||
|
val следующая_сумма = сумма + f(x, n)
|
||||||
|
if( n > 1 && abs(следующая_сумма - сумма) < погрешность )
|
||||||
|
break следующая_сумма
|
||||||
|
сумма = следующая_сумма
|
||||||
|
}
|
||||||
|
else null
|
||||||
|
}
|
||||||
|
|
||||||
|
Для проверки можно посчитать на хорошо известном ряду Меркатора
|
||||||
|
|
||||||
|
$$ \ln(1+x)=x-{\dfrac {x^{2}}{2}}+{\dfrac {x^{3}}{3}}-\cdots =\sum \limits _{n=0}^{\infty }{\dfrac {(-1)^{n}x^{n+1}}{(n+1)}}=\sum \limits _{n=1}^{\infty }{\dfrac {(-1)^{n-1}x^{n}}{n}} $$
|
||||||
|
|
||||||
|
Который в нашем случае для точки $ x = 1 $ можно записать так:
|
||||||
|
|
||||||
|
val x = сумма_ряда(1) { x, n ->
|
||||||
|
val sign = if( n % 2 == 1 ) 1 else -1
|
||||||
|
sign * pow(x, n) / n
|
||||||
|
}
|
||||||
|
|
||||||
|
Проверим:
|
||||||
|
|
||||||
|
assert( x - ln(2) < 0.001 )
|
||||||
|
|
||||||
|
В нашем примере есть изъян - погрешность вычисляется примитивно: `abs(следующая_сумма - сумма) < погрешность`, что совершенно неверно, если значения малы. Значительно более корректно вычислять погрешность, нормированную на диапазон сравниваемых величин:
|
||||||
|
|
||||||
|
|
||||||
|
fun погрешность(x0, x1) {
|
||||||
|
abs( x1 - x0 ) / (abs( x1 + x0 ) / 2.0)
|
||||||
|
}
|
||||||
|
// относительная погрешность одинакова и в разных диапазонах
|
||||||
|
assertEquals( погрешность(5,6), погрешность(0.005,0.006))
|
||||||
|
|
||||||
|
Теперь мы могли бы написать более корректное сравнение для вещественных
|
||||||
|
|
||||||
|
// расхождение не больше 1% или сколько укажете:
|
||||||
|
fun почти_равны(a,b,epsilon=0.01) {
|
||||||
|
погрешность(a,b) <= epsilon
|
||||||
|
}
|
||||||
|
assert( почти_равны( 0.0005, 0.000501 ) )
|
||||||
|
|
||||||
|
Во многих случаях вычисление $n+1$ члена значительно проще cчитается от предыдущего члена, в нашем случае это можно было бы записать через итератор, что мы вскоре добавим.
|
||||||
|
|
||||||
|
(продолжение следует)
|
||||||
+215
@@ -0,0 +1,215 @@
|
|||||||
|
# Lyng time functions
|
||||||
|
|
||||||
|
Lyng date and time support requires importing `lyng.time` packages. Lyng uses simple yet modern time object models:
|
||||||
|
|
||||||
|
- `Instant` class for time stamps with platform-dependent resolution
|
||||||
|
- `Duration` to represent amount of time not depending on the calendar, e.g. in absolute units (milliseconds, seconds,
|
||||||
|
hours, days)
|
||||||
|
|
||||||
|
## Time instant: `Instant`
|
||||||
|
|
||||||
|
Represent some moment of time not depending on the calendar (calendar for example may b e changed, daylight saving time
|
||||||
|
can be for example introduced or dropped). It is similar to `TIMESTAMP` in SQL or `Instant` in Kotlin. Some moment of
|
||||||
|
time; not the calendar date.
|
||||||
|
|
||||||
|
Instant is comparable to other Instant. Subtracting instants produce `Duration`, period in time that is not dependent on
|
||||||
|
the calendar, e.g. absolute time period.
|
||||||
|
|
||||||
|
It is possible to add or subtract `Duration` to and from `Instant`, that gives another `Instant`.
|
||||||
|
|
||||||
|
Instants are converted to and from `Real` number of seconds before or after Unix Epoch, 01.01.1970. Constructor with
|
||||||
|
single number parameter constructs from such number of seconds,
|
||||||
|
and any instance provide `.epochSeconds` member:
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
|
||||||
|
// default constructor returns time now:
|
||||||
|
val t1 = Instant()
|
||||||
|
val t2 = Instant()
|
||||||
|
assert( t2 - t1 < 1.millisecond )
|
||||||
|
assert( t2.epochSeconds - t1.epochSeconds < 0.001 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Constructing
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
|
||||||
|
// empty constructor gives current time instant using system clock:
|
||||||
|
val now = Instant()
|
||||||
|
|
||||||
|
// constructor with Instant instance makes a copy:
|
||||||
|
assertEquals( now, Instant(now) )
|
||||||
|
|
||||||
|
// constructing from a number is trated as seconds since unix epoch:
|
||||||
|
val copyOfNow = Instant( now.epochSeconds )
|
||||||
|
|
||||||
|
// note that instant resolution is higher that Real can hold
|
||||||
|
// so reconstructed from real slightly differs:
|
||||||
|
assert( abs( (copyOfNow - now).milliseconds ) < 0.01 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
The resolution of system clock could be more precise and double precision real number of `Real`, keep it in mind.
|
||||||
|
|
||||||
|
## Comparing and calculating periods
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
|
||||||
|
val now = Instant()
|
||||||
|
|
||||||
|
// you cam add or subtract periods, and compare
|
||||||
|
assert( now - 5.minutes < now )
|
||||||
|
val oneHourAgo = now - 1.hour
|
||||||
|
assertEquals( now, oneHourAgo + 1.hour)
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Getting the max precision
|
||||||
|
|
||||||
|
Normally, subtracting instants gives precision to microseconds, which is well inside the jitter
|
||||||
|
the language VM adds. Still `Instant()` or `Instant.now()` capture most precise system timer at hand and provide inner
|
||||||
|
value of 12 bytes, up to nanoseconds (hopefully). To access it use:
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
|
||||||
|
// capture time
|
||||||
|
val now = Instant.now()
|
||||||
|
|
||||||
|
// this is Int value, number of whole epoch
|
||||||
|
// milliseconds to the moment, it fits 8 bytes Int well
|
||||||
|
val seconds = now.epochWholeSeconds
|
||||||
|
assert(seconds is Int)
|
||||||
|
|
||||||
|
// and this is Int value of nanoseconds _since_ the epochMillis,
|
||||||
|
// it effectively add 4 more mytes int:
|
||||||
|
val nanos = now.nanosecondsOfSecond
|
||||||
|
assert(nanos is Int)
|
||||||
|
assert( nanos in 0..999_999_999 )
|
||||||
|
|
||||||
|
// we can construct epochSeconds from these parts:
|
||||||
|
assertEquals( now.epochSeconds, nanos * 1e-9 + seconds )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Truncating to more realistic precision
|
||||||
|
|
||||||
|
Full precision Instant is way too long and impractical to store, especially when serializing,
|
||||||
|
so it is possible to truncate it to milliseconds, microseconds or seconds:
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
import lyng.serialization
|
||||||
|
|
||||||
|
// max supported size (now microseconds for serialized value):
|
||||||
|
// note that encoding return _bit array_ and this is a _bit size_:
|
||||||
|
val s0 = Lynon.encode(Instant.now()).size
|
||||||
|
|
||||||
|
// shorter: milliseconds only
|
||||||
|
val s1 = Lynon.encode(Instant.now().truncateToMillisecond()).size
|
||||||
|
|
||||||
|
// truncated to seconds, good for file mtime, etc:
|
||||||
|
val s2 = Lynon.encode(Instant.now().truncateToSecond()).size
|
||||||
|
assert( s1 < s0 )
|
||||||
|
assert( s2 < s1 )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Formatting instants
|
||||||
|
|
||||||
|
You can freely use `Instant` in string formatting. It supports usual sprintf-style formats:
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
val now = Instant()
|
||||||
|
|
||||||
|
// will be something like "now: 12:10:05"
|
||||||
|
val currentTimeOnly24 = "now: %tT"(now)
|
||||||
|
|
||||||
|
// we can extract epoch second with formatting too,
|
||||||
|
// this was since early C time
|
||||||
|
|
||||||
|
// get epoch while seconds from formatting
|
||||||
|
val unixEpoch = "Now is %ts since unix epoch"(now)
|
||||||
|
|
||||||
|
// and it is the same as now.epochSeconds, int part:
|
||||||
|
assertEquals( unixEpoch, "Now is %d since unix epoch"(now.epochSeconds.toInt()) )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
See
|
||||||
|
the [complete list of available formats](https://github.com/sergeych/mp_stools?tab=readme-ov-file#datetime-formatting)
|
||||||
|
and the [formatting reference](https://github.com/sergeych/mp_stools?tab=readme-ov-file#printf--sprintf): it all works
|
||||||
|
in Lyng as `"format"(args...)`!
|
||||||
|
|
||||||
|
## Instant members
|
||||||
|
|
||||||
|
| member | description |
|
||||||
|
|--------------------------------|---------------------------------------------------------|
|
||||||
|
| epochSeconds: Real | positive or negative offset in seconds since Unix epoch |
|
||||||
|
| epochWholeSeconds: Int | same, but in _whole seconds_. Slightly faster |
|
||||||
|
| nanosecondsOfSecond: Int | offset from epochWholeSeconds in nanos (1) |
|
||||||
|
| isDistantFuture: Bool | true if it `Instant.distantFuture` |
|
||||||
|
| isDistantPast: Bool | true if it `Instant.distantPast` |
|
||||||
|
| truncateToSecond: Intant | create new instnce truncated to second |
|
||||||
|
| truncateToMillisecond: Instant | truncate new instance with to millisecond |
|
||||||
|
| truncateToMicrosecond: Instant | truncate new instance to microsecond |
|
||||||
|
|
||||||
|
(1)
|
||||||
|
: The value of nanoseconds is to be added to `epochWholeSeconds` to get exact time point. It is in 0..999_999_999 range.
|
||||||
|
The precise time instant value therefore needs as for now 12 bytes integer; we might use bigint later (it is planned to
|
||||||
|
be added)
|
||||||
|
|
||||||
|
## Class members
|
||||||
|
|
||||||
|
| member | description |
|
||||||
|
|--------------------------------|----------------------------------------------|
|
||||||
|
| Instant.now() | create new instance with current system time |
|
||||||
|
| Instant.distantPast: Instant | most distant instant in past |
|
||||||
|
| Instant.distantFuture: Instant | most distant instant in future |
|
||||||
|
|
||||||
|
# `Duraion` class
|
||||||
|
|
||||||
|
Represent absolute time distance between two `Instant`.
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
val t1 = Instant()
|
||||||
|
|
||||||
|
// yes we can delay to period, and it is not blocking. is suspends!
|
||||||
|
delay(1.millisecond)
|
||||||
|
|
||||||
|
val t2 = Instant()
|
||||||
|
// be suspend, so actual time may vary:
|
||||||
|
assert( t2 - t1 >= 1.millisecond)
|
||||||
|
assert( t2 - t1 < 100.millisecond)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Duration can be converted from numbers, like `5.minutes` and so on. Extensions are created for
|
||||||
|
`Int` and `Real`, so for n as Real or Int it is possible to create durations::
|
||||||
|
|
||||||
|
- `n.millisecond`, `n.milliseconds`
|
||||||
|
- `n.second`, `n.seconds`
|
||||||
|
- `n.minute`, `n.minutes`
|
||||||
|
- `n.hour`, `n.hours`
|
||||||
|
- `n.day`, `n.days`
|
||||||
|
|
||||||
|
The bigger time units like months or years are calendar-dependent and can't be used with `Duration`.
|
||||||
|
|
||||||
|
Each duration instance can be converted to number of any of these time units, as `Real` number, if `d` is a `Duration`
|
||||||
|
instance:
|
||||||
|
|
||||||
|
- `d.microseconds`
|
||||||
|
- `d.milliseconds`
|
||||||
|
- `d.seconds`
|
||||||
|
- `d.minutes`
|
||||||
|
- `d.hours`
|
||||||
|
- `d.days`
|
||||||
|
|
||||||
|
for example
|
||||||
|
|
||||||
|
import lyng.time
|
||||||
|
assertEquals( 60, 1.minute.seconds )
|
||||||
|
assertEquals( 10.milliseconds, 0.01.seconds )
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
# Utility functions
|
||||||
|
|
||||||
|
## delay(duration: Duration)
|
||||||
|
|
||||||
|
Suspends current coroutine for at least the specified duration.
|
||||||
|
|
||||||
|
|
||||||
+1283
File diff suppressed because it is too large.
Load diff
+3
-1
@@ -4,9 +4,11 @@ org.gradle.caching=true
|
|||||||
org.gradle.configuration-cache=true
|
org.gradle.configuration-cache=true
|
||||||
#Kotlin
|
#Kotlin
|
||||||
kotlin.code.style=official
|
kotlin.code.style=official
|
||||||
kotlin.js.compiler=ir
|
|
||||||
#MPP
|
#MPP
|
||||||
kotlin.mpp.enableCInteropCommonization=true
|
kotlin.mpp.enableCInteropCommonization=true
|
||||||
#Android
|
#Android
|
||||||
android.useAndroidX=true
|
android.useAndroidX=true
|
||||||
android.nonTransitiveRClass=true
|
android.nonTransitiveRClass=true
|
||||||
|
|
||||||
|
# other
|
||||||
|
kotlin.native.cacheKind.linuxX64=none
|
||||||
@@ -1,16 +1,26 @@
|
|||||||
[versions]
|
[versions]
|
||||||
agp = "8.5.2"
|
agp = "8.5.2"
|
||||||
|
clikt = "5.0.3"
|
||||||
kotlin = "2.1.21"
|
kotlin = "2.1.21"
|
||||||
android-minSdk = "24"
|
android-minSdk = "24"
|
||||||
android-compileSdk = "34"
|
android-compileSdk = "34"
|
||||||
kotlinx-coroutines = "1.10.1"
|
kotlinx-coroutines = "1.9.0"
|
||||||
mp_bintools = "0.1.12"
|
mp_bintools = "0.1.12"
|
||||||
|
firebaseCrashlyticsBuildtools = "3.0.3"
|
||||||
|
okioVersion = "3.10.2"
|
||||||
|
compiler = "3.2.0-alpha11"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
|
clikt = { module = "com.github.ajalt.clikt:clikt", version.ref = "clikt" }
|
||||||
|
clikt-markdown = { module = "com.github.ajalt.clikt:clikt-markdown", version.ref = "clikt" }
|
||||||
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
|
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
|
||||||
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
|
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
|
||||||
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
|
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
|
||||||
mp_bintools = { module = "net.sergeych:mp_bintools", version.ref = "mp_bintools" }
|
mp_bintools = { module = "net.sergeych:mp_bintools", version.ref = "mp_bintools" }
|
||||||
|
firebase-crashlytics-buildtools = { group = "com.google.firebase", name = "firebase-crashlytics-buildtools", version.ref = "firebaseCrashlyticsBuildtools" }
|
||||||
|
okio = { module = "com.squareup.okio:okio", version.ref = "okioVersion" }
|
||||||
|
okio-fakefilesystem = { module = "com.squareup.okio:okio-fakefilesystem", version.ref = "okioVersion" }
|
||||||
|
compiler = { group = "androidx.databinding", name = "compiler", version.ref = "compiler" }
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
androidLibrary = { id = "com.android.library", version.ref = "agp" }
|
androidLibrary = { id = "com.android.library", version.ref = "agp" }
|
||||||
|
|||||||
@@ -1,101 +0,0 @@
|
|||||||
import com.vanniktech.maven.publish.SonatypeHost
|
|
||||||
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
|
||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
|
||||||
|
|
||||||
plugins {
|
|
||||||
alias(libs.plugins.kotlinMultiplatform)
|
|
||||||
alias(libs.plugins.androidLibrary)
|
|
||||||
alias(libs.plugins.vanniktech.mavenPublish)
|
|
||||||
kotlin("plugin.serialization") version "2.1.20"
|
|
||||||
}
|
|
||||||
|
|
||||||
group = "net.sergeych"
|
|
||||||
version = "0.0.1-SNAPSHOT"
|
|
||||||
|
|
||||||
kotlin {
|
|
||||||
jvm()
|
|
||||||
androidTarget {
|
|
||||||
publishLibraryVariants("release")
|
|
||||||
@OptIn(ExperimentalKotlinGradlePluginApi::class)
|
|
||||||
compilerOptions {
|
|
||||||
jvmTarget.set(JvmTarget.JVM_11)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// iosX64()
|
|
||||||
// iosArm64()
|
|
||||||
// iosSimulatorArm64()
|
|
||||||
linuxX64()
|
|
||||||
js(IR) {
|
|
||||||
browser()
|
|
||||||
nodejs()
|
|
||||||
}
|
|
||||||
|
|
||||||
sourceSets {
|
|
||||||
all {
|
|
||||||
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
|
|
||||||
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
|
|
||||||
languageSettings.optIn("kotlin.coroutines.DelicateCoroutinesApi")
|
|
||||||
}
|
|
||||||
|
|
||||||
val commonMain by getting {
|
|
||||||
dependencies {
|
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1")
|
|
||||||
//put your multiplatform dependencies here
|
|
||||||
implementation(libs.kotlinx.coroutines.core)
|
|
||||||
implementation(libs.mp.bintools)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
val commonTest by getting {
|
|
||||||
dependencies {
|
|
||||||
implementation(libs.kotlin.test)
|
|
||||||
implementation(libs.kotlinx.coroutines.test)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
android {
|
|
||||||
namespace = "org.jetbrains.kotlinx.multiplatform.library.template"
|
|
||||||
compileSdk = libs.versions.android.compileSdk.get().toInt()
|
|
||||||
defaultConfig {
|
|
||||||
minSdk = libs.versions.android.minSdk.get().toInt()
|
|
||||||
}
|
|
||||||
compileOptions {
|
|
||||||
sourceCompatibility = JavaVersion.VERSION_11
|
|
||||||
targetCompatibility = JavaVersion.VERSION_11
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
mavenPublishing {
|
|
||||||
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
|
|
||||||
|
|
||||||
signAllPublications()
|
|
||||||
|
|
||||||
coordinates(group.toString(), "library", version.toString())
|
|
||||||
|
|
||||||
pom {
|
|
||||||
name = "Ling language"
|
|
||||||
description = "Kotlin-bound scripting loanguage"
|
|
||||||
inceptionYear = "2025"
|
|
||||||
// url = "https://sergeych.net"
|
|
||||||
licenses {
|
|
||||||
license {
|
|
||||||
name = "XXX"
|
|
||||||
url = "YYY"
|
|
||||||
distribution = "ZZZ"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
developers {
|
|
||||||
developer {
|
|
||||||
id = "XXX"
|
|
||||||
name = "YYY"
|
|
||||||
url = "ZZZ"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
scm {
|
|
||||||
url = "XXX"
|
|
||||||
connection = "YYY"
|
|
||||||
developerConnection = "ZZZ"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
data class Arguments(val list: List<Obj> ) {
|
|
||||||
|
|
||||||
val size by list::size
|
|
||||||
|
|
||||||
operator fun get(index: Int): Obj = list[index]
|
|
||||||
|
|
||||||
fun firstAndOnly(): Obj {
|
|
||||||
if( list.size != 1 ) throw IllegalArgumentException("Expected one argument, got ${list.size}")
|
|
||||||
return list.first()
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
val EMPTY = Arguments(emptyList())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,301 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
//sealed class ObjType(name: String, val defaultValue: Obj? = null) {
|
|
||||||
//
|
|
||||||
// class Str : ObjType("string", ObjString(""))
|
|
||||||
// class Int : ObjType("real", ObjReal(0.0))
|
|
||||||
//
|
|
||||||
//}
|
|
||||||
//
|
|
||||||
///**
|
|
||||||
// * Descriptor for whatever object could be used as argument, return value,
|
|
||||||
// * field, etc.
|
|
||||||
// */
|
|
||||||
//data class ObjDescriptor(
|
|
||||||
// val type: ObjType,
|
|
||||||
// val mutable: Boolean,
|
|
||||||
//)
|
|
||||||
//
|
|
||||||
//data class MethodDescriptor(
|
|
||||||
// val args: Array<ObjDescriptor>,
|
|
||||||
// val result: ObjDescriptor
|
|
||||||
//)
|
|
||||||
|
|
||||||
/*
|
|
||||||
Meta context contains map of symbols.
|
|
||||||
|
|
||||||
Each symbol can be:
|
|
||||||
|
|
||||||
- a var
|
|
||||||
- a const
|
|
||||||
- a function
|
|
||||||
- a type alias
|
|
||||||
- a class definition
|
|
||||||
|
|
||||||
Each have in common only its name.
|
|
||||||
|
|
||||||
Var has: type, value. Const is same as var but value is fixed. Function has args and return value,
|
|
||||||
type alias has target type name. So we have to have something that denotes a _type_
|
|
||||||
|
|
||||||
*/
|
|
||||||
|
|
||||||
|
|
||||||
//data class MetaContext(val symbols: MutableMap<String, > = mutableMapOf()) {
|
|
||||||
//
|
|
||||||
//}
|
|
||||||
|
|
||||||
|
|
||||||
class Compiler {
|
|
||||||
|
|
||||||
fun compile(source: Source): Script {
|
|
||||||
val tokens = parseLing(source).listIterator()
|
|
||||||
val start = source.startPos
|
|
||||||
// at this level: "global" context: just script to execute or new function
|
|
||||||
// declaration forming closures
|
|
||||||
val statements = mutableListOf<Statement>()
|
|
||||||
while (parseStatement(tokens)?.also {
|
|
||||||
statements += it
|
|
||||||
} != null) {/**/
|
|
||||||
}
|
|
||||||
return Script(start, statements)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseStatement(tokens: ListIterator<Token>): Statement? {
|
|
||||||
val t = tokens.next()
|
|
||||||
return when (t.type) {
|
|
||||||
Token.Type.ID -> {
|
|
||||||
// could be keyword, assignment or just the expression
|
|
||||||
val next = tokens.next()
|
|
||||||
if (next.type == Token.Type.EQ) {
|
|
||||||
// this _is_ assignment statement
|
|
||||||
AssignStatement(
|
|
||||||
t.pos, t.value,
|
|
||||||
parseExpression(tokens) ?: throw ScriptError(
|
|
||||||
t.pos,
|
|
||||||
"Expecting expression for assignment operator"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
// not assignment, maybe keyword statement:
|
|
||||||
// get back the token which is not '=':
|
|
||||||
tokens.previous()
|
|
||||||
// try keyword statement
|
|
||||||
parseKeywordStatement(t, tokens)
|
|
||||||
?: run {
|
|
||||||
tokens.previous()
|
|
||||||
parseExpression(tokens)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Token.Type.EOF -> null
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
// could be expression
|
|
||||||
tokens.previous()
|
|
||||||
parseExpression(tokens)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun parseExpression(tokens: ListIterator<Token>, level: Int = 0): Statement? {
|
|
||||||
if (level == lastLevel)
|
|
||||||
return parseTerm(tokens)
|
|
||||||
var lvalue = parseExpression(tokens, level + 1)
|
|
||||||
if (lvalue == null) return null
|
|
||||||
|
|
||||||
while (true) {
|
|
||||||
|
|
||||||
val opToken = tokens.next()
|
|
||||||
val op = byLevel[level][opToken.value]
|
|
||||||
if (op == null) {
|
|
||||||
tokens.previous()
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
val rvalue = parseExpression(tokens, level + 1)
|
|
||||||
?: throw ScriptError(opToken.pos, "Expecting expression")
|
|
||||||
|
|
||||||
lvalue = op.generate(opToken.pos, lvalue!!, rvalue)
|
|
||||||
}
|
|
||||||
return lvalue
|
|
||||||
}
|
|
||||||
|
|
||||||
fun parseTerm(tokens: ListIterator<Token>): Statement? {
|
|
||||||
// call op
|
|
||||||
// index op
|
|
||||||
// unary op
|
|
||||||
// parenthesis
|
|
||||||
// number or string
|
|
||||||
val t = tokens.next()
|
|
||||||
// todoL var?
|
|
||||||
return when (t.type) {
|
|
||||||
Token.Type.ID -> {
|
|
||||||
parseVarAccess(t, tokens)
|
|
||||||
}
|
|
||||||
// todoL: check if it's a function call
|
|
||||||
// todoL: check if it's a field access
|
|
||||||
// todoL: check if it's a var
|
|
||||||
// todoL: check if it's a const
|
|
||||||
// todoL: check if it's a type
|
|
||||||
|
|
||||||
// "+" -> statement { parseNumber(true,tokens) }??????
|
|
||||||
// "-" -> statement { parseNumber(false,tokens) }
|
|
||||||
// "~" -> statement(t.pos) { ObjInt( parseLong(tokens)) }
|
|
||||||
|
|
||||||
Token.Type.PLUS -> {
|
|
||||||
val n = parseNumber(true, tokens)
|
|
||||||
statement(t.pos) { n }
|
|
||||||
}
|
|
||||||
|
|
||||||
Token.Type.MINUS -> {
|
|
||||||
val n = parseNumber(false, tokens)
|
|
||||||
statement(t.pos) { n }
|
|
||||||
}
|
|
||||||
|
|
||||||
Token.Type.INT, Token.Type.REAL, Token.Type.HEX -> {
|
|
||||||
tokens.previous()
|
|
||||||
val n = parseNumber(true, tokens)
|
|
||||||
statement(t.pos) { n }
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> null
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
fun parseVarAccess(id: Token, tokens: ListIterator<Token>,path: List<String> = emptyList()): Statement {
|
|
||||||
val nt = tokens.next()
|
|
||||||
|
|
||||||
fun resolve(context: Context): Context {
|
|
||||||
var targetContext = context
|
|
||||||
for( n in path) {
|
|
||||||
val x = targetContext[n] ?: throw ScriptError(id.pos, "undefined symbol: $n")
|
|
||||||
(x.value as? ObjNamespace )?.let { targetContext = it.context }
|
|
||||||
?: throw ScriptError(id.pos, "Invalid symbolic path (wrong type of ${x.name}: ${x.value}")
|
|
||||||
}
|
|
||||||
return targetContext
|
|
||||||
}
|
|
||||||
return when(nt.type) {
|
|
||||||
Token.Type.DOT -> {
|
|
||||||
// selector
|
|
||||||
val t = tokens.next()
|
|
||||||
if( t.type== Token.Type.ID) {
|
|
||||||
parseVarAccess(t,tokens,path+id.value)
|
|
||||||
}
|
|
||||||
else
|
|
||||||
throw ScriptError(t.pos,"Expected identifier after '.'")
|
|
||||||
}
|
|
||||||
Token.Type.LPAREN -> {
|
|
||||||
// Load arg list
|
|
||||||
val args = mutableListOf<Statement>()
|
|
||||||
do {
|
|
||||||
val t = tokens.next()
|
|
||||||
when(t.type) {
|
|
||||||
Token.Type.RPAREN, Token.Type.COMMA -> {}
|
|
||||||
else -> {
|
|
||||||
tokens.previous()
|
|
||||||
parseExpression(tokens)?.let { args += it }
|
|
||||||
?: throw ScriptError(t.pos, "Expecting arguments list")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} while (t.type != Token.Type.RPAREN)
|
|
||||||
statement(id.pos) { context ->
|
|
||||||
val v = resolve(context).get(id.value) ?: throw ScriptError(id.pos, "Undefined variable: $id")
|
|
||||||
(v.value as? Statement)?.execute(context.copy(Arguments(args.map { it.execute(context) })))
|
|
||||||
?: throw ScriptError(id.pos, "Variable $id is not callable ($id)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Token.Type.LBRACKET -> {
|
|
||||||
TODO("indexing")
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
// just access the var
|
|
||||||
tokens.previous()
|
|
||||||
statement(id.pos) {
|
|
||||||
val v = resolve(it).get(id.value) ?: throw ScriptError(id.pos, "Undefined variable: $id")
|
|
||||||
v.value ?: throw ScriptError(id.pos, "Variable $id is not initialized")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fun parseNumber(isPlus: Boolean, tokens: ListIterator<Token>): Obj {
|
|
||||||
val t = tokens.next()
|
|
||||||
return when (t.type) {
|
|
||||||
Token.Type.INT, Token.Type.HEX -> {
|
|
||||||
val n = t.value.toLong(if (t.type == Token.Type.HEX) 16 else 10)
|
|
||||||
if (isPlus) ObjInt(n) else ObjInt(-n)
|
|
||||||
}
|
|
||||||
|
|
||||||
Token.Type.REAL -> {
|
|
||||||
val d = t.value.toDouble()
|
|
||||||
if (isPlus) ObjReal(d) else ObjReal(-d)
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
throw ScriptError(t.pos, "expected number")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse keyword-starting statenment.
|
|
||||||
* @return parsed statement or null if, for example. [id] is not among keywords
|
|
||||||
*/
|
|
||||||
@Suppress("UNUSED_PARAMETER")
|
|
||||||
private fun parseKeywordStatement(id: Token, tokens: ListIterator<Token>): Statement? {
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
// fun parseStatement(parser: Parser): Statement? =
|
|
||||||
// parser.withToken {
|
|
||||||
// if (tokens.isEmpty()) null
|
|
||||||
// else {
|
|
||||||
// when (val token = tokens[0]) {
|
|
||||||
// else -> {
|
|
||||||
// rollback()
|
|
||||||
// null
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
data class Operator(
|
|
||||||
val name: String,
|
|
||||||
val priority: Int, val arity: Int,
|
|
||||||
val generate: (Pos, Statement, Statement) -> Statement
|
|
||||||
)
|
|
||||||
|
|
||||||
val allOps = listOf(
|
|
||||||
// Operator("||", 0, 2) { pos, a, b -> LogicalOrStatement(pos, a, b) })
|
|
||||||
Operator("&&", 1, 2) { pos, a, b ->
|
|
||||||
LogicalAndStatement(pos, a, b)
|
|
||||||
},
|
|
||||||
// bitwise or 2
|
|
||||||
// bitwise and 3
|
|
||||||
// equality/ne 4
|
|
||||||
// relational <=,... 5
|
|
||||||
// shuttle <=> 6
|
|
||||||
// bitshhifts 7
|
|
||||||
// + - : 7
|
|
||||||
Operator("+", 7, 2) { pos, a, b ->
|
|
||||||
PlusStatement(pos, a, b)
|
|
||||||
},
|
|
||||||
Operator("-", 7, 2) { pos, a, b ->
|
|
||||||
MinusStatement(pos, a, b)
|
|
||||||
},
|
|
||||||
// * / %: 8
|
|
||||||
)
|
|
||||||
val lastLevel = 9
|
|
||||||
val byLevel: List<Map<String, Operator>> = (0..<lastLevel).map { l ->
|
|
||||||
allOps.filter { it.priority == l }
|
|
||||||
.map { it.name to it }.toMap()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun compile(code: String): Script = Compiler().compile(Source("<eval>", code))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun eval(code: String) = Compiler.compile(code).execute()
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
class Context(
|
|
||||||
val parent: Context? = null,
|
|
||||||
val args: Arguments = Arguments.EMPTY
|
|
||||||
) {
|
|
||||||
|
|
||||||
data class Item(
|
|
||||||
val name: String,
|
|
||||||
var value: Obj?,
|
|
||||||
val isMutable: Boolean = false
|
|
||||||
)
|
|
||||||
|
|
||||||
private val objects = mutableMapOf<String, Item>()
|
|
||||||
|
|
||||||
operator fun get(name: String): Item? = objects[name] ?: parent?.get(name)
|
|
||||||
|
|
||||||
fun copy(args: Arguments = Arguments.EMPTY): Context = Context(this, args)
|
|
||||||
|
|
||||||
fun addItem(name: String, isMutable: Boolean, value: Obj?) {
|
|
||||||
objects.put(name, Item(name, value, isMutable))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun getOrCreateNamespace(name: String) =
|
|
||||||
(objects.getOrPut(name) { Item(name, ObjNamespace(name,copy()), isMutable = false) }.value as ObjNamespace)
|
|
||||||
.context
|
|
||||||
|
|
||||||
inline fun <reified T> addFn(vararg names: String, crossinline fn: suspend Context.() -> T) {
|
|
||||||
val newFn = object : Statement() {
|
|
||||||
override val pos: Pos = Pos.builtIn
|
|
||||||
|
|
||||||
override suspend fun execute(context: Context): Obj {
|
|
||||||
return try {
|
|
||||||
from(context.fn())
|
|
||||||
|
|
||||||
} catch (e: Exception) {
|
|
||||||
raise(e.message ?: "unexpected error")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for (name in names) {
|
|
||||||
addItem(
|
|
||||||
name,
|
|
||||||
false,
|
|
||||||
newFn
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inline fun <reified T> addConst(value: T,vararg names: String) {
|
|
||||||
val obj = Obj.from(value)
|
|
||||||
for (name in names) {
|
|
||||||
addItem(
|
|
||||||
name,
|
|
||||||
false,
|
|
||||||
obj
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
operator fun invoke() = Context()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,104 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
import kotlinx.serialization.SerialName
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import kotlin.math.floor
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
sealed class Obj {
|
|
||||||
open val asStr: ObjString by lazy {
|
|
||||||
if( this is ObjString) this else ObjString(this.toString())
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
inline fun <reified T> from(obj: T): Obj {
|
|
||||||
return when(obj) {
|
|
||||||
is Obj -> obj
|
|
||||||
is Double -> ObjReal(obj)
|
|
||||||
is Float -> ObjReal(obj.toDouble())
|
|
||||||
is Int -> ObjInt(obj.toLong())
|
|
||||||
is Long -> ObjInt(obj)
|
|
||||||
is String -> ObjString(obj)
|
|
||||||
is CharSequence -> ObjString(obj.toString())
|
|
||||||
is Boolean -> ObjBool(obj)
|
|
||||||
Unit -> ObjVoid
|
|
||||||
null -> ObjNull
|
|
||||||
else -> throw IllegalArgumentException("cannot convert to Obj: $obj")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
@SerialName("void")
|
|
||||||
object ObjVoid: Obj() {
|
|
||||||
override fun equals(other: Any?): Boolean {
|
|
||||||
return other is ObjVoid || other is Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
@SerialName("null")
|
|
||||||
object ObjNull: Obj() {
|
|
||||||
override fun equals(other: Any?): Boolean {
|
|
||||||
return other is ObjNull || other == null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
@SerialName("string")
|
|
||||||
data class ObjString(val value: String): Obj() {
|
|
||||||
override fun toString(): String = value
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Numeric {
|
|
||||||
val longValue: Long
|
|
||||||
val doubleValue: Double
|
|
||||||
val toObjInt: ObjInt
|
|
||||||
val toObjReal: ObjReal
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Obj.toDouble(): Double =
|
|
||||||
(this as? Numeric)?.doubleValue
|
|
||||||
?: (this as? ObjString)?.value?.toDouble()
|
|
||||||
?: throw IllegalArgumentException("cannot convert to double $this")
|
|
||||||
|
|
||||||
@Suppress("unused")
|
|
||||||
fun Obj.toLong(): Long =
|
|
||||||
(this as? Numeric)?.longValue
|
|
||||||
?: (this as? ObjString)?.value?.toLong()
|
|
||||||
?: throw IllegalArgumentException("cannot convert to double $this")
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
@SerialName("real")
|
|
||||||
data class ObjReal(val value: Double): Obj(), Numeric {
|
|
||||||
override val asStr by lazy { ObjString(value.toString()) }
|
|
||||||
override val longValue: Long by lazy { floor(value).toLong() }
|
|
||||||
override val doubleValue: Double by lazy { value }
|
|
||||||
override val toObjInt: ObjInt by lazy { ObjInt(longValue) }
|
|
||||||
override val toObjReal: ObjReal by lazy { ObjReal(value) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
@SerialName("int")
|
|
||||||
data class ObjInt(val value: Long): Obj(), Numeric {
|
|
||||||
override val asStr by lazy { ObjString(value.toString()) }
|
|
||||||
override val longValue: Long by lazy { value }
|
|
||||||
override val doubleValue: Double by lazy { value.toDouble() }
|
|
||||||
override val toObjInt: ObjInt by lazy { ObjInt(value) }
|
|
||||||
override val toObjReal: ObjReal by lazy { ObjReal(doubleValue) }
|
|
||||||
}
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
@SerialName("bool")
|
|
||||||
data class ObjBool(val value: Boolean): Obj() {
|
|
||||||
override val asStr by lazy { ObjString(value.toString()) }
|
|
||||||
}
|
|
||||||
|
|
||||||
data class ObjNamespace(val name: String,val context: Context): Obj() {
|
|
||||||
override fun toString(): String {
|
|
||||||
return "namespace ${name}"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,185 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
private val idFirstChars: Set<Char> = (
|
|
||||||
('a'..'z') + ('A'..'Z') + '_' + ('а'..'я') + ('А'..'Я')
|
|
||||||
).toSet()
|
|
||||||
val idNextChars: Set<Char> = idFirstChars + ('0'..'9')
|
|
||||||
val digits = ('0'..'9').toSet()
|
|
||||||
val hexDigits = digits + ('a'..'f') + ('A'..'F')
|
|
||||||
|
|
||||||
fun parseLing(source: Source): List<Token> {
|
|
||||||
val p = Parser(fromPos = source.startPos)
|
|
||||||
val tokens = mutableListOf<Token>()
|
|
||||||
do {
|
|
||||||
val t = p.nextToken()
|
|
||||||
tokens += t
|
|
||||||
} while(t.type != Token.Type.EOF)
|
|
||||||
return tokens
|
|
||||||
}
|
|
||||||
|
|
||||||
private class Parser(fromPos: Pos) {
|
|
||||||
|
|
||||||
private val pos = MutablePos(fromPos)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Immutable copy of current position
|
|
||||||
*/
|
|
||||||
private val currentPos: Pos get() = pos.toPos()
|
|
||||||
|
|
||||||
private fun raise(msg: String): Nothing = throw ScriptError(currentPos, msg)
|
|
||||||
|
|
||||||
fun nextToken(): Token {
|
|
||||||
skipws()
|
|
||||||
if (pos.end) return Token("", currentPos, Token.Type.EOF)
|
|
||||||
val from = currentPos
|
|
||||||
return when (val ch = pos.currentChar.also { advance() }) {
|
|
||||||
'(' -> Token("(", from, Token.Type.LPAREN)
|
|
||||||
')' -> Token(")", from, Token.Type.RPAREN)
|
|
||||||
'{' -> Token("{", from, Token.Type.LBRACE)
|
|
||||||
'}' -> Token("}", from, Token.Type.RBRACE)
|
|
||||||
'[' -> Token("[", from, Token.Type.LBRACKET)
|
|
||||||
']' -> Token("]", from, Token.Type.RBRACKET)
|
|
||||||
',' -> Token(",", from, Token.Type.COMMA)
|
|
||||||
';' -> Token(";", from, Token.Type.SEMICOLON)
|
|
||||||
'=' -> Token("=", from, Token.Type.ASSIGN)
|
|
||||||
'+' -> Token("+", from, Token.Type.PLUS)
|
|
||||||
'-' -> Token("-", from, Token.Type.MINUS)
|
|
||||||
'*' -> Token("*", from, Token.Type.STAR)
|
|
||||||
'/' -> Token("/", from, Token.Type.SLASH)
|
|
||||||
'.' -> Token(".", from, Token.Type.DOT)
|
|
||||||
'<' -> Token("<", from, Token.Type.LT)
|
|
||||||
'>' -> Token(">", from, Token.Type.GT)
|
|
||||||
'!' -> Token("!", from, Token.Type.NOT)
|
|
||||||
'"' -> loadStringToken()
|
|
||||||
in digits -> {
|
|
||||||
pos.back()
|
|
||||||
decodeNumber(loadChars(digits), from)
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
if( ch.isLetter() || ch == '_' )
|
|
||||||
Token(ch + loadChars(idNextChars), from, Token.Type.ID)
|
|
||||||
else
|
|
||||||
raise("can't parse token")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun decodeNumber(p1: String, start: Pos): Token =
|
|
||||||
if( pos.end )
|
|
||||||
Token(p1, start, Token.Type.INT)
|
|
||||||
else if( currentChar == '.' ) {
|
|
||||||
// could be decimal
|
|
||||||
advance()
|
|
||||||
if( currentChar in digits ) {
|
|
||||||
// decimal part
|
|
||||||
val p2 = loadChars(digits)
|
|
||||||
// with exponent?
|
|
||||||
if( currentChar == 'e' || currentChar == 'E') {
|
|
||||||
advance()
|
|
||||||
var negative = false
|
|
||||||
if(currentChar == '+' )
|
|
||||||
advance()
|
|
||||||
else if(currentChar == '-') {
|
|
||||||
negative = true
|
|
||||||
advance()
|
|
||||||
}
|
|
||||||
var p3 = loadChars(digits)
|
|
||||||
if( negative ) p3 = "-$p3"
|
|
||||||
Token("$p1.${p2}e$p3", start, Token.Type.REAL)
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// no exponent
|
|
||||||
Token("$p1.$p2", start, Token.Type.REAL)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// not decimal
|
|
||||||
// something like 10.times, method call on integer number
|
|
||||||
pos.back()
|
|
||||||
Token(p1, start, Token.Type.INT)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
// could be integer, also hex:
|
|
||||||
if (currentChar == 'x' && p1 == "0") {
|
|
||||||
advance()
|
|
||||||
Token(loadChars(hexDigits), start, Token.Type.HEX).also {
|
|
||||||
if( currentChar.isLetter() )
|
|
||||||
raise("invalid hex literal")
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Token(p1, start, Token.Type.INT)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
private val currentChar: Char get() = pos.currentChar
|
|
||||||
|
|
||||||
private fun loadStringToken(): Token {
|
|
||||||
var start = currentPos
|
|
||||||
|
|
||||||
if (currentChar == '"') advance()
|
|
||||||
else start = start.back()
|
|
||||||
|
|
||||||
val sb = StringBuilder()
|
|
||||||
while (currentChar != '"') {
|
|
||||||
if( pos.end ) raise("unterminated string")
|
|
||||||
when (currentChar) {
|
|
||||||
'\\' -> {
|
|
||||||
advance() ?: raise("unterminated string")
|
|
||||||
when (currentChar) {
|
|
||||||
'n' -> sb.append('\n')
|
|
||||||
'r' -> sb.append('\r')
|
|
||||||
't' -> sb.append('\t')
|
|
||||||
'"' -> sb.append('"')
|
|
||||||
else -> sb.append('\\').append(currentChar)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
sb.append(currentChar)
|
|
||||||
advance()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
advance()
|
|
||||||
return Token(sb.toString(), start, Token.Type.STRING)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Load characters from the set until it reaches EOF or invalid character found.
|
|
||||||
* stop at EOF on character not in [validChars].
|
|
||||||
* @return the string of valid characters, could be empty
|
|
||||||
*/
|
|
||||||
private fun loadChars(validChars: Set<Char>): String {
|
|
||||||
val result = StringBuilder()
|
|
||||||
while (!pos.end) {
|
|
||||||
val ch = pos.currentChar
|
|
||||||
if (ch in validChars) {
|
|
||||||
result.append(ch)
|
|
||||||
advance()
|
|
||||||
} else
|
|
||||||
break
|
|
||||||
}
|
|
||||||
return result.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* next non-whitespace char (newline are skipped too) or null if EOF
|
|
||||||
*/
|
|
||||||
private fun skipws(): Char? {
|
|
||||||
while (!pos.end) {
|
|
||||||
val ch = pos.currentChar
|
|
||||||
if (ch.isWhitespace())
|
|
||||||
advance()
|
|
||||||
else
|
|
||||||
return ch
|
|
||||||
}
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun advance() = pos.advance()
|
|
||||||
|
|
||||||
init {
|
|
||||||
// advance()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
import kotlin.math.PI
|
|
||||||
import kotlin.math.sin
|
|
||||||
|
|
||||||
class Script(
|
|
||||||
override val pos: Pos,
|
|
||||||
private val statements: List<Statement> = emptyList(),
|
|
||||||
) : Statement() {
|
|
||||||
|
|
||||||
override suspend fun execute(context: Context): Obj {
|
|
||||||
// todo: run script
|
|
||||||
var lastResult: Obj = ObjVoid
|
|
||||||
for (s in statements) {
|
|
||||||
lastResult = s.execute(context)
|
|
||||||
}
|
|
||||||
return lastResult
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun execute() = execute(defaultContext)
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
val defaultContext: Context = Context().apply {
|
|
||||||
addFn("println") {
|
|
||||||
require(args.size == 1)
|
|
||||||
println(args[0].asStr.value)
|
|
||||||
ObjVoid
|
|
||||||
}
|
|
||||||
addFn("sin") {
|
|
||||||
sin(args.firstAndOnly().toDouble())
|
|
||||||
}
|
|
||||||
val pi = ObjReal(PI)
|
|
||||||
addConst(pi, "π")
|
|
||||||
getOrCreateNamespace("Math").also { ns ->
|
|
||||||
ns.addConst(pi, "PI")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
class ScriptError(val pos: Pos, val errorMessage: String) : Exception(
|
|
||||||
"""
|
|
||||||
$pos: Error: $errorMessage
|
|
||||||
${pos.currentLine}
|
|
||||||
${"-".repeat(pos.column)}^
|
|
||||||
""".trimIndent()
|
|
||||||
)
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
class Source(val fileName: String, text: String) {
|
|
||||||
|
|
||||||
val lines = text.lines().map { it.trimEnd() }
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
val builtIn: Source by lazy { Source("built-in", "") }
|
|
||||||
}
|
|
||||||
|
|
||||||
val startPos: Pos = Pos(this, 0, 0)
|
|
||||||
|
|
||||||
fun posAt(line: Int, column: Int): Pos = Pos(this, line, column)
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
data class Token(val value: String, val pos: Pos, val type: Type) {
|
|
||||||
enum class Type {
|
|
||||||
ID, INT, REAL, HEX, STRING, LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, COMMA,
|
|
||||||
SEMICOLON, COLON, EQ, PLUS, MINUS, STAR, SLASH, ASSIGN, EQEQ, NEQ, LT, LTEQ, GT,
|
|
||||||
GTEQ, AND, OR, NOT, DOT, ARROW, QUESTION, COLONCOLON, EOF,
|
|
||||||
}
|
|
||||||
companion object {
|
|
||||||
// fun eof(parser: Parser) = Token("", parser.currentPos, Type.EOF)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
package net.sergeych.ling
|
|
||||||
|
|
||||||
fun String.toSource(name: String = "eval"): Source = Source(name, this)
|
|
||||||
|
|
||||||
|
|
||||||
abstract class Statement : Obj() {
|
|
||||||
abstract val pos: Pos
|
|
||||||
abstract suspend fun execute(context: Context): Obj
|
|
||||||
}
|
|
||||||
|
|
||||||
fun Statement.raise(text: String): Nothing {
|
|
||||||
throw ScriptError(pos, text)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("unused")
|
|
||||||
fun Statement.require(cond: Boolean, message: () -> String) {
|
|
||||||
if (!cond) raise(message())
|
|
||||||
}
|
|
||||||
|
|
||||||
fun statement(pos: Pos, f: suspend (Context) -> Obj): Statement = object : Statement() {
|
|
||||||
override val pos: Pos = pos
|
|
||||||
override suspend fun execute(context: Context): Obj = f(context)
|
|
||||||
}
|
|
||||||
|
|
||||||
class LogicalAndStatement(
|
|
||||||
override val pos: Pos,
|
|
||||||
val left: Statement, val right: Statement
|
|
||||||
) : Statement() {
|
|
||||||
override suspend fun execute(context: Context): Obj {
|
|
||||||
|
|
||||||
val l = left.execute(context).let {
|
|
||||||
(it as? ObjBool) ?: raise("logical and: left operand is not boolean: $it")
|
|
||||||
}
|
|
||||||
val r = right.execute(context).let {
|
|
||||||
(it as? ObjBool) ?: raise("logical and: right operand is not boolean: $it")
|
|
||||||
}
|
|
||||||
return ObjBool(l.value && r.value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class PlusStatement(
|
|
||||||
override val pos: Pos,
|
|
||||||
val left: Statement, val right: Statement
|
|
||||||
) : Statement() {
|
|
||||||
override suspend fun execute(context: Context): Obj {
|
|
||||||
// todo: implement also classes with 'plus' operator
|
|
||||||
val l = left.execute(context)
|
|
||||||
|
|
||||||
if (l is ObjString)
|
|
||||||
return ObjString(l.toString() + right.execute(context).toString())
|
|
||||||
|
|
||||||
if (l !is Numeric)
|
|
||||||
raise("left operand is not number: $l")
|
|
||||||
|
|
||||||
val r = right.execute(context)
|
|
||||||
if (r !is Numeric)
|
|
||||||
raise("right operand is not boolean: $r")
|
|
||||||
|
|
||||||
return if (l is ObjInt && r is ObjInt)
|
|
||||||
ObjInt(l.longValue + r.longValue)
|
|
||||||
else
|
|
||||||
ObjReal(l.doubleValue + r.doubleValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class MinusStatement(
|
|
||||||
override val pos: Pos,
|
|
||||||
val left: Statement, val right: Statement
|
|
||||||
) : Statement() {
|
|
||||||
override suspend fun execute(context: Context): Obj {
|
|
||||||
// todo: implement also classes with 'minus' operator
|
|
||||||
val l = left.execute(context)
|
|
||||||
if (l !is Numeric)
|
|
||||||
raise("left operand is not number: $l")
|
|
||||||
|
|
||||||
val r = right.execute(context)
|
|
||||||
if (r !is Numeric)
|
|
||||||
raise("right operand is not number: $r")
|
|
||||||
|
|
||||||
return if (l is ObjInt && r is ObjInt)
|
|
||||||
ObjInt(l.longValue - r.longValue)
|
|
||||||
else
|
|
||||||
ObjReal(l.doubleValue - r.doubleValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class AssignStatement(override val pos: Pos, val name: String, val value: Statement) : Statement() {
|
|
||||||
override suspend fun execute(context: Context): Obj {
|
|
||||||
val variable = context[name] ?: raise("can't assign: variable does not exist: $name")
|
|
||||||
variable.value = value.execute(context)
|
|
||||||
return ObjVoid
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
package io.github.kotlin.fibonacci
|
|
||||||
|
|
||||||
import kotlinx.coroutines.test.runTest
|
|
||||||
import net.sergeych.ling.*
|
|
||||||
import kotlin.math.PI
|
|
||||||
import kotlin.test.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
import kotlin.test.assertIs
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
|
|
||||||
class ScriptTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun parseNumbers() {
|
|
||||||
fun check(expected: String, type: Token.Type, row: Int, col: Int, src: String, offset: Int = 0) {
|
|
||||||
val source = src.toSource()
|
|
||||||
assertEquals(
|
|
||||||
Token(expected, source.posAt(row, col), type),
|
|
||||||
parseLing(source)[offset]
|
|
||||||
)
|
|
||||||
}
|
|
||||||
check("1", Token.Type.INT, 0, 0, "1")
|
|
||||||
check("7", Token.Type.INT, 0, 0, "7")
|
|
||||||
check("17", Token.Type.INT, 0, 0, "17")
|
|
||||||
check("17", Token.Type.INT, 0, 0, "17.")
|
|
||||||
check(".", Token.Type.DOT, 0, 2, "17.", 1)
|
|
||||||
|
|
||||||
// decimals
|
|
||||||
check("17.2", Token.Type.REAL, 0, 0, "17.2")
|
|
||||||
check("17.2", Token.Type.REAL, 0, 0, "17.2")
|
|
||||||
check("17.2", Token.Type.REAL, 0, 0, "17.2 ")
|
|
||||||
check("17.2", Token.Type.REAL, 0, 1, " 17.2")
|
|
||||||
check("17.2", Token.Type.REAL, 0, 2, " 17.2 ")
|
|
||||||
check("17.2e0", Token.Type.REAL, 0, 0, "17.2e0")
|
|
||||||
check("17.2e-22", Token.Type.REAL, 0, 0, "17.2e-22")
|
|
||||||
check("17.2e22", Token.Type.REAL, 0, 0, "17.2e+22")
|
|
||||||
check("17.2e22", Token.Type.REAL, 0, 0, "17.2E+22")
|
|
||||||
check("17.2e22", Token.Type.REAL, 0, 0, "17.2E22")
|
|
||||||
check("17.2e-22", Token.Type.REAL, 0, 0, "17.2E-22")
|
|
||||||
|
|
||||||
// hex
|
|
||||||
check("1", Token.Type.HEX, 0, 0, "0x1")
|
|
||||||
check("12", Token.Type.HEX, 0, 0, "0x12")
|
|
||||||
check("12abcdef", Token.Type.HEX, 0, 0, "0x12abcdef.gh")
|
|
||||||
check(".", Token.Type.DOT, 0, 10, "0x12abcdef.gh", 1)
|
|
||||||
check("gh", Token.Type.ID, 0, 11, "0x12abcdef.gh", 2)
|
|
||||||
|
|
||||||
check("5", Token.Type.INT, 0, 0, "5 6")
|
|
||||||
check("6", Token.Type.INT, 0, 2, "5 6", 1)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun parse0() {
|
|
||||||
val src = """
|
|
||||||
println("Hello")
|
|
||||||
println( "world" )
|
|
||||||
""".trimIndent().toSource()
|
|
||||||
|
|
||||||
val p = parseLing(src).listIterator()
|
|
||||||
|
|
||||||
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("Hello", src.posAt(0, 8), Token.Type.STRING), p.next())
|
|
||||||
assertEquals(Token(")", src.posAt(0, 15), Token.Type.RPAREN), 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("world", src.posAt(1, 9), Token.Type.STRING), p.next())
|
|
||||||
assertEquals(Token(")", src.posAt(1, 17), Token.Type.RPAREN), p.next())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun parse1() {
|
|
||||||
val src = "2 + 7".toSource()
|
|
||||||
|
|
||||||
val p = parseLing(src).listIterator()
|
|
||||||
|
|
||||||
assertEquals(Token("2", src.posAt(0, 0), Token.Type.INT), p.next())
|
|
||||||
assertEquals(Token("+", src.posAt(0, 2), Token.Type.PLUS), p.next())
|
|
||||||
assertEquals(Token("7", src.posAt(0, 4), Token.Type.INT), p.next())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun compileNumbers() = runTest {
|
|
||||||
assertEquals(ObjInt(17), eval("17"))
|
|
||||||
assertEquals(ObjInt(17), eval("+17"))
|
|
||||||
assertEquals(ObjInt(-17), eval("-17"))
|
|
||||||
|
|
||||||
|
|
||||||
assertEquals(ObjInt(1970), eval("1900 + 70"))
|
|
||||||
assertEquals(ObjInt(1970), eval("2000 - 30"))
|
|
||||||
|
|
||||||
// assertEquals(ObjReal(3.14), eval("3.14"))
|
|
||||||
assertEquals(ObjReal(314.0), eval("3.14e2"))
|
|
||||||
assertEquals(ObjReal(314.0), eval("100 3.14e2"))
|
|
||||||
assertEquals(ObjReal(314.0), eval("100\n 3.14e2"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun compileBuiltinCalls() = runTest {
|
|
||||||
// println(eval("π"))
|
|
||||||
val pi = eval("Math.PI")
|
|
||||||
assertIs<ObjReal>(pi)
|
|
||||||
assertTrue(pi.value - PI < 0.000001)
|
|
||||||
assertTrue(eval("Math.PI+1").toDouble() - PI - 1.0 < 0.000001)
|
|
||||||
|
|
||||||
assertTrue(eval("sin(Math.PI)").toDouble() - 1 < 0.000001)
|
|
||||||
assertTrue(eval("sin(π)").toDouble() - 1 < 0.000001)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
plugins {
|
||||||
|
kotlin("multiplatform") version "2.1.21"
|
||||||
|
}
|
||||||
|
|
||||||
|
group = "net.sergeych"
|
||||||
|
version = "unspecified"
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
maven("https://maven.universablockchain.com/")
|
||||||
|
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||||
|
mavenLocal()
|
||||||
|
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
jvm {
|
||||||
|
binaries {
|
||||||
|
executable {
|
||||||
|
mainClass.set("net.sergeych.lyng_cli.MainKt")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
linuxX64 {
|
||||||
|
binaries {
|
||||||
|
executable()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sourceSets {
|
||||||
|
val commonMain by getting {
|
||||||
|
dependencies {
|
||||||
|
implementation(kotlin("stdlib-common"))
|
||||||
|
implementation(project(":lynglib"))
|
||||||
|
implementation(libs.okio)
|
||||||
|
implementation(libs.clikt)
|
||||||
|
implementation(kotlin("stdlib-common"))
|
||||||
|
// optional support for rendering markdown in help messages
|
||||||
|
// implementation(libs.clikt.markdown)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val commonTest by getting {
|
||||||
|
dependencies {
|
||||||
|
implementation(kotlin("test-common"))
|
||||||
|
implementation(kotlin("test-annotations-common"))
|
||||||
|
implementation(libs.kotlinx.coroutines.core)
|
||||||
|
implementation(libs.okio.fakefilesystem)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// val nativeMain by getting {
|
||||||
|
// dependencies {
|
||||||
|
// implementation(kotlin("stdlib-common"))
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
val linuxX64Main by getting {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package net.sergeych
|
||||||
|
|
||||||
|
import com.github.ajalt.clikt.core.CliktCommand
|
||||||
|
import com.github.ajalt.clikt.core.Context
|
||||||
|
import com.github.ajalt.clikt.core.main
|
||||||
|
import com.github.ajalt.clikt.parameters.arguments.argument
|
||||||
|
import com.github.ajalt.clikt.parameters.arguments.multiple
|
||||||
|
import com.github.ajalt.clikt.parameters.arguments.optional
|
||||||
|
import com.github.ajalt.clikt.parameters.options.flag
|
||||||
|
import com.github.ajalt.clikt.parameters.options.option
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import net.sergeych.lyng.LyngVersion
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.ScriptError
|
||||||
|
import net.sergeych.lyng.Source
|
||||||
|
import net.sergeych.lyng.obj.*
|
||||||
|
import okio.FileSystem
|
||||||
|
import okio.Path.Companion.toPath
|
||||||
|
import okio.SYSTEM
|
||||||
|
import okio.buffer
|
||||||
|
import okio.use
|
||||||
|
|
||||||
|
// common code
|
||||||
|
|
||||||
|
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 baseScope = Scope().apply {
|
||||||
|
addFn("exit") {
|
||||||
|
exit(requireOnlyArg<ObjInt>().toInt())
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
// ObjString.type.addFn("shell") {
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun runMain(args: Array<String>) {
|
||||||
|
if(args.isNotEmpty()) {
|
||||||
|
if( args.size >= 2 && args[0] == "--" ) {
|
||||||
|
// -- -file.lyng <args>
|
||||||
|
executeFileWithArgs(args[1], args.drop(2))
|
||||||
|
return
|
||||||
|
} else if( args[0][0] != '-') {
|
||||||
|
// file.lyng <args>
|
||||||
|
executeFileWithArgs(args[0], args.drop(1))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// normal processing
|
||||||
|
Lyng { runBlocking { it() } }.main(args)
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Lyng(val launcher: (suspend () -> Unit) -> Unit) : CliktCommand() {
|
||||||
|
|
||||||
|
override val printHelpOnEmptyArgs = true
|
||||||
|
|
||||||
|
val version by option("-v", "--version", help = "Print version and exit").flag()
|
||||||
|
val script by argument(help = "one or more scripts to execute").optional()
|
||||||
|
val execute: String? by option(
|
||||||
|
"-x", "--execute", help = """
|
||||||
|
execute string <text>, the rest of command line is passed to Lyng as ARGV
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
val args by argument(help = "arguments for script").multiple()
|
||||||
|
|
||||||
|
override fun help(context: Context): String =
|
||||||
|
"""
|
||||||
|
The Lyng script language interpreter, language version is $LyngVersion.
|
||||||
|
|
||||||
|
Please refer form more information to the project site:
|
||||||
|
https://gitea.sergeych.net/SergeychWorks/lyng
|
||||||
|
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
override fun run() {
|
||||||
|
when {
|
||||||
|
version -> {
|
||||||
|
println("Lyng language version ${LyngVersion}")
|
||||||
|
}
|
||||||
|
|
||||||
|
execute != null -> {
|
||||||
|
val objargs = mutableListOf<String>()
|
||||||
|
script?.let { objargs += it }
|
||||||
|
objargs += args
|
||||||
|
baseScope.addConst(
|
||||||
|
"ARGV", ObjList(
|
||||||
|
objargs.map { ObjString(it) }.toMutableList()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
launcher {
|
||||||
|
// there is no script name, it is a first argument instead:
|
||||||
|
processErrors {
|
||||||
|
baseScope.eval(execute!!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
if (script == null) {
|
||||||
|
println(
|
||||||
|
"""
|
||||||
|
|
||||||
|
Error: no script specified.
|
||||||
|
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
echoFormattedHelp()
|
||||||
|
} else {
|
||||||
|
baseScope.addConst("ARGV", ObjList(args.map { ObjString(it) }.toMutableList()))
|
||||||
|
launcher { executeFile(script!!) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun executeFileWithArgs(fileName: String, args: List<String>) {
|
||||||
|
runBlocking {
|
||||||
|
baseScope.addConst("ARGV", ObjList(args.map { ObjString(it) }.toMutableList()))
|
||||||
|
executeFile(fileName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun executeFile(fileName: String) {
|
||||||
|
var text = FileSystem.SYSTEM.source(fileName.toPath()).use { fileSource ->
|
||||||
|
fileSource.buffer().use { bs ->
|
||||||
|
bs.readUtf8()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if( text.startsWith("#!") ) {
|
||||||
|
// skip shebang
|
||||||
|
val pos = text.indexOf('\n')
|
||||||
|
text = text.substring(pos + 1)
|
||||||
|
}
|
||||||
|
processErrors {
|
||||||
|
baseScope.eval(Source(fileName, text))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun processErrors(block: suspend () -> Unit) {
|
||||||
|
try {
|
||||||
|
block()
|
||||||
|
}
|
||||||
|
catch (e: ScriptError) {
|
||||||
|
println("\nError executing the script:\n$e\n")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package net.sergeych
|
||||||
|
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
|
actual fun exit(code: Int) {
|
||||||
|
exitProcess(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package net.sergeych.lyng_cli
|
||||||
|
|
||||||
|
import net.sergeych.runMain
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
runMain(args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import net.sergeych.runMain
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
runMain(args)
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
@file:OptIn(ExperimentalForeignApi::class, ExperimentalForeignApi::class, ExperimentalForeignApi::class)
|
||||||
|
|
||||||
|
package net.sergeych
|
||||||
|
|
||||||
|
import kotlinx.cinterop.*
|
||||||
|
import platform.posix.fgets
|
||||||
|
import platform.posix.pclose
|
||||||
|
import platform.posix.popen
|
||||||
|
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) {
|
||||||
|
exitProcess(code)
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import com.codingfeline.buildkonfig.compiler.FieldSpec.Type.STRING
|
||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
||||||
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
|
group = "net.sergeych"
|
||||||
|
version = "0.8.2-SNAPSHOT"
|
||||||
|
|
||||||
|
buildscript {
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
dependencies {
|
||||||
|
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.4.0")
|
||||||
|
classpath("com.codingfeline.buildkonfig:buildkonfig-gradle-plugin:latest_version")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
|
alias(libs.plugins.androidLibrary)
|
||||||
|
// alias(libs.plugins.vanniktech.mavenPublish)
|
||||||
|
kotlin("plugin.serialization") version "2.2.0"
|
||||||
|
id("com.codingfeline.buildkonfig") version "0.17.1"
|
||||||
|
`maven-publish`
|
||||||
|
}
|
||||||
|
|
||||||
|
buildkonfig {
|
||||||
|
packageName = "net.sergeych.lyng"
|
||||||
|
// objectName = "YourAwesomeConfig"
|
||||||
|
// exposeObjectWithName = "YourAwesomePublicConfig"
|
||||||
|
|
||||||
|
defaultConfigs {
|
||||||
|
buildConfigField(STRING, "bcprovider", "codingfeline")
|
||||||
|
buildConfigField(STRING, "version", version.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
jvm()
|
||||||
|
androidTarget {
|
||||||
|
publishLibraryVariants("release")
|
||||||
|
@OptIn(ExperimentalKotlinGradlePluginApi::class)
|
||||||
|
compilerOptions {
|
||||||
|
jvmTarget.set(JvmTarget.JVM_11)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// iosX64()
|
||||||
|
// iosArm64()
|
||||||
|
// iosSimulatorArm64()
|
||||||
|
linuxX64()
|
||||||
|
js {
|
||||||
|
browser()
|
||||||
|
nodejs()
|
||||||
|
}
|
||||||
|
@OptIn(ExperimentalWasmDsl::class)
|
||||||
|
wasmJs() {
|
||||||
|
browser()
|
||||||
|
nodejs()
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceSets {
|
||||||
|
all {
|
||||||
|
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
|
||||||
|
languageSettings.optIn("kotlin.contracts.ExperimentalContracts")
|
||||||
|
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
|
||||||
|
languageSettings.optIn("kotlin.coroutines.DelicateCoroutinesApi")
|
||||||
|
}
|
||||||
|
|
||||||
|
val commonMain by getting {
|
||||||
|
kotlin.srcDir("$buildDir/generated/buildConfig/commonMain/kotlin")
|
||||||
|
dependencies {
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1")
|
||||||
|
//put your multiplatform dependencies here
|
||||||
|
api(libs.kotlinx.coroutines.core)
|
||||||
|
api(libs.mp.bintools)
|
||||||
|
api("net.sergeych:mp_stools:1.5.2")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val commonTest by getting {
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.kotlin.test)
|
||||||
|
implementation(libs.kotlinx.coroutines.test)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "org.jetbrains.kotlinx.multiplatform.library.template"
|
||||||
|
compileSdk = libs.versions.android.compileSdk.get().toInt()
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = libs.versions.android.minSdk.get().toInt()
|
||||||
|
}
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_11
|
||||||
|
targetCompatibility = JavaVersion.VERSION_11
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.firebase.crashlytics.buildtools)
|
||||||
|
implementation(libs.compiler)
|
||||||
|
}
|
||||||
|
|
||||||
|
publishing {
|
||||||
|
val mavenToken by lazy {
|
||||||
|
File("${System.getProperty("user.home")}/.gitea_token").readText()
|
||||||
|
}
|
||||||
|
repositories {
|
||||||
|
maven {
|
||||||
|
credentials(HttpHeaderCredentials::class) {
|
||||||
|
name = "Authorization"
|
||||||
|
value = mavenToken
|
||||||
|
}
|
||||||
|
url = uri("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||||
|
authentication {
|
||||||
|
create("Authorization", HttpHeaderAuthentication::class)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//mavenPublishing {
|
||||||
|
// publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
|
||||||
|
//
|
||||||
|
// signAllPublications()
|
||||||
|
//
|
||||||
|
// coordinates(group.toString(), "library", version.toString())
|
||||||
|
//
|
||||||
|
// pom {
|
||||||
|
// name = "Lyng language"
|
||||||
|
// description = "Kotlin-bound scripting loanguage"
|
||||||
|
// inceptionYear = "2025"
|
||||||
|
//// url = "https://sergeych.net"
|
||||||
|
// licenses {
|
||||||
|
// license {
|
||||||
|
// name = "XXX"
|
||||||
|
// url = "YYY"
|
||||||
|
// distribution = "ZZZ"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// developers {
|
||||||
|
// developer {
|
||||||
|
// id = "XXX"
|
||||||
|
// name = "YYY"
|
||||||
|
// url = "ZZZ"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// scm {
|
||||||
|
// url = "XXX"
|
||||||
|
// connection = "YYY"
|
||||||
|
// developerConnection = "ZZZ"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
enum class AccessType(val isMutable: Boolean) {
|
||||||
|
Val(false), Var(true),
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
Initialization(false)
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.ObjRecord
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Special version of the [Scope] used to `apply` new this object to
|
||||||
|
* _parent context property.
|
||||||
|
*
|
||||||
|
* @param _parent context to apply to
|
||||||
|
* @param args arguments for the new context
|
||||||
|
* @param appliedScope the new context to apply, it will have lower priority except for `this` which
|
||||||
|
* will be reset by appliedContext's `this`.
|
||||||
|
*/
|
||||||
|
class AppliedScope(_parent: Scope, args: Arguments, val appliedScope: Scope)
|
||||||
|
: Scope(_parent, args, appliedScope.pos, appliedScope.thisObj) {
|
||||||
|
override fun get(name: String): ObjRecord? =
|
||||||
|
if (name == "this") thisObj.asReadonly
|
||||||
|
else super.get(name) ?: appliedScope[name]
|
||||||
|
}
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjList
|
||||||
|
import net.sergeych.lyng.obj.ObjRecord
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List of argument declarations in the __definition__ of the lambda, class constructor,
|
||||||
|
* function, etc. It is created by [Compiler.parseArgsDeclaration]
|
||||||
|
*/
|
||||||
|
data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type) {
|
||||||
|
init {
|
||||||
|
val i = params.count { it.isEllipsis }
|
||||||
|
if (i > 1) throw ScriptError(params[i].pos, "there can be only one argument")
|
||||||
|
val start = params.indexOfFirst { it.defaultValue != null }
|
||||||
|
if (start >= 0)
|
||||||
|
for (j in start + 1 until params.size)
|
||||||
|
// last non-default could be lambda:
|
||||||
|
if (params[j].defaultValue == null && j != params.size - 1) throw ScriptError(
|
||||||
|
params[j].pos,
|
||||||
|
"required argument can't follow default one"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* parse args and create local vars in a given context properly interpreting
|
||||||
|
* ellipsis args and default values
|
||||||
|
*/
|
||||||
|
suspend fun assignToContext(
|
||||||
|
scope: Scope,
|
||||||
|
arguments: Arguments = scope.args,
|
||||||
|
defaultAccessType: AccessType = AccessType.Var,
|
||||||
|
defaultVisibility: Visibility = Visibility.Public,
|
||||||
|
defaultRecordType: ObjRecord.Type = ObjRecord.Type.ConstructorField
|
||||||
|
) {
|
||||||
|
fun assign(a: Item, value: Obj) {
|
||||||
|
scope.addItem(a.name, (a.accessType ?: defaultAccessType).isMutable, value,
|
||||||
|
a.visibility ?: defaultVisibility,
|
||||||
|
recordType = defaultRecordType)
|
||||||
|
}
|
||||||
|
|
||||||
|
// will be used with last lambda arg fix
|
||||||
|
val callArgs: List<Obj>
|
||||||
|
val paramsSize: Int
|
||||||
|
|
||||||
|
if( arguments.tailBlockMode ) {
|
||||||
|
paramsSize = params.size - 1
|
||||||
|
assign(params.last(), arguments.list.last())
|
||||||
|
callArgs = arguments.list.dropLast(1)
|
||||||
|
} else {
|
||||||
|
paramsSize = params.size
|
||||||
|
callArgs = arguments.list
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun processHead(index: Int): Int {
|
||||||
|
var i = index
|
||||||
|
while (i != paramsSize) {
|
||||||
|
val a = params[i]
|
||||||
|
if (a.isEllipsis) break
|
||||||
|
val value = when {
|
||||||
|
i < callArgs.size -> callArgs[i]
|
||||||
|
a.defaultValue != null -> a.defaultValue.execute(scope)
|
||||||
|
else -> {
|
||||||
|
// println("callArgs: ${callArgs.joinToString()}")
|
||||||
|
// println("tailBlockMode: ${arguments.tailBlockMode}")
|
||||||
|
scope.raiseIllegalArgument("too few arguments for the call")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assign(a, value)
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun processTail(index: Int): Int {
|
||||||
|
var i = paramsSize - 1
|
||||||
|
var j = callArgs.size - 1
|
||||||
|
while (i > index) {
|
||||||
|
val a = params[i]
|
||||||
|
if (a.isEllipsis) break
|
||||||
|
val value = when {
|
||||||
|
j >= index -> {
|
||||||
|
callArgs[j--]
|
||||||
|
}
|
||||||
|
|
||||||
|
a.defaultValue != null -> a.defaultValue.execute(scope)
|
||||||
|
else -> scope.raiseIllegalArgument("too few arguments for the call")
|
||||||
|
}
|
||||||
|
assign(a, value)
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
return j
|
||||||
|
}
|
||||||
|
|
||||||
|
fun processEllipsis(index: Int, toFromIndex: Int) {
|
||||||
|
val a = params[index]
|
||||||
|
val l = if (index > toFromIndex) ObjList()
|
||||||
|
else ObjList(callArgs.subList(index, toFromIndex + 1).toMutableList())
|
||||||
|
assign(a, l)
|
||||||
|
}
|
||||||
|
|
||||||
|
val leftIndex = processHead(0)
|
||||||
|
if (leftIndex < paramsSize) {
|
||||||
|
val end = processTail(leftIndex)
|
||||||
|
processEllipsis(leftIndex, end)
|
||||||
|
} else {
|
||||||
|
if (leftIndex < callArgs.size)
|
||||||
|
scope.raiseIllegalArgument("too many arguments for the call")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Single argument declaration descriptor.
|
||||||
|
*
|
||||||
|
* @param defaultValue default value, if set, can't be an [Obj] as it can depend on the call site, call args, etc.
|
||||||
|
* If not null, could be executed on __caller context__ only.
|
||||||
|
*/
|
||||||
|
data class Item(
|
||||||
|
val name: String,
|
||||||
|
val type: TypeDecl = TypeDecl.TypeAny,
|
||||||
|
val pos: Pos = Pos.builtIn,
|
||||||
|
val isEllipsis: Boolean = false,
|
||||||
|
/**
|
||||||
|
* Default value, if set, can't be an [Obj] as it can depend on the call site, call args, etc.
|
||||||
|
* So it is a [Statement] that must be executed on __caller context__.
|
||||||
|
*/
|
||||||
|
val defaultValue: Statement? = null,
|
||||||
|
val accessType: AccessType? = null,
|
||||||
|
val visibility: Visibility? = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjIterable
|
||||||
|
import net.sergeych.lyng.obj.ObjList
|
||||||
|
|
||||||
|
data class ParsedArgument(val value: Statement, val pos: Pos, val isSplat: Boolean = false)
|
||||||
|
|
||||||
|
suspend fun Collection<ParsedArgument>.toArguments(scope: Scope, tailBlockMode: Boolean): Arguments {
|
||||||
|
val list = mutableListOf<Obj>()
|
||||||
|
|
||||||
|
for (x in this) {
|
||||||
|
val value = x.value.execute(scope)
|
||||||
|
if (x.isSplat) {
|
||||||
|
when {
|
||||||
|
value is ObjList -> {
|
||||||
|
for (subitem in value.list) list.add(subitem)
|
||||||
|
}
|
||||||
|
|
||||||
|
value.isInstanceOf(ObjIterable) -> {
|
||||||
|
val i = (value.invokeInstanceMethod(scope, "toList") as ObjList).list
|
||||||
|
i.forEach { list.add(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> scope.raiseClassCastError("expected list of objects for splat argument")
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
list.add(value)
|
||||||
|
}
|
||||||
|
return Arguments(list,tailBlockMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Arguments(val list: List<Obj>, val tailBlockMode: Boolean = false) : List<Obj> by list {
|
||||||
|
|
||||||
|
constructor(vararg values: Obj) : this(values.toList())
|
||||||
|
|
||||||
|
fun firstAndOnly(pos: Pos = Pos.UNKNOWN): Obj {
|
||||||
|
if (list.size != 1) throw ScriptError(pos, "expected one argument, got ${list.size}")
|
||||||
|
return list.first()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert to list of kotlin objects, see [Obj.toKotlin].
|
||||||
|
*/
|
||||||
|
suspend fun toKotlinList(scope: Scope): List<Any?> {
|
||||||
|
return list.map { it.toKotlin(scope) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun inspect(): String = list.joinToString(", ") { it.inspect() }
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val EMPTY = Arguments(emptyList())
|
||||||
|
fun from(values: Collection<Obj>) = Arguments(values.toList())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.ling
|
package net.sergeych.lyng
|
||||||
|
|
||||||
//fun buildDoubleFromParts(
|
//fun buildDoubleFromParts(
|
||||||
// integerPart: Long,
|
// integerPart: Long,
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,180 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
class CompilerContext(val tokens: List<Token>) {
|
||||||
|
val labels = mutableSetOf<String>()
|
||||||
|
|
||||||
|
var breakFound = false
|
||||||
|
|
||||||
|
var loopLevel = 0
|
||||||
|
|
||||||
|
inline fun <T> parseLoop(f: () -> T): Pair<Boolean, T> {
|
||||||
|
if (++loopLevel == 0) breakFound = false
|
||||||
|
val result = f()
|
||||||
|
return Pair(breakFound, result).also {
|
||||||
|
--loopLevel
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var currentIndex = 0
|
||||||
|
|
||||||
|
fun hasNext() = currentIndex < tokens.size
|
||||||
|
fun hasPrevious() = currentIndex > 0
|
||||||
|
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 savePos() = currentIndex
|
||||||
|
fun restorePos(pos: Int) {
|
||||||
|
currentIndex = pos
|
||||||
|
}
|
||||||
|
|
||||||
|
fun ensureLabelIsValid(pos: Pos, label: String) {
|
||||||
|
if (label !in labels)
|
||||||
|
throw ScriptError(pos, "Undefined label '$label'")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun requireId() = requireToken(Token.Type.ID, "identifier is required")
|
||||||
|
|
||||||
|
fun requireToken(type: Token.Type, message: String = "required ${type.name}"): Token =
|
||||||
|
next().also {
|
||||||
|
if (type != it.type) throw ScriptError(it.pos, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun syntaxError(at: Pos, message: String = "Syntax error"): Nothing {
|
||||||
|
throw ScriptError(at, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun syntaxError(message: String = "Syntax error"): Nothing {
|
||||||
|
throw ScriptError(currentPos(), message)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun currentPos(): Pos = tokens[currentIndex].pos
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the next token is identifier `name`, skip it and return `true`.
|
||||||
|
* else leave where it is and return `false`
|
||||||
|
*/
|
||||||
|
fun skipId(name: String): Boolean {
|
||||||
|
current().let { t ->
|
||||||
|
if( t.type == Token.Type.ID && t.value == name ) {
|
||||||
|
next()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Skips next token if its type is `tokenType`, returns `true` if so.
|
||||||
|
* @param errorMessage message to throw if next token is not `tokenType`
|
||||||
|
* @param isOptional if `true` and token is not of `tokenType`, just return `false` and does not skip it
|
||||||
|
* @return `true` if the token was skipped
|
||||||
|
* @throws ScriptError if [isOptional] is `false` and next token is not of [tokenType]
|
||||||
|
*/
|
||||||
|
fun skipTokenOfType(
|
||||||
|
tokenType: Token.Type,
|
||||||
|
errorMessage: String = "expected ${tokenType.name}",
|
||||||
|
isOptional: Boolean = false
|
||||||
|
): Boolean {
|
||||||
|
val t = next()
|
||||||
|
return if (t.type != tokenType) {
|
||||||
|
if (!isOptional) {
|
||||||
|
println("unexpected: $t (needed $tokenType)")
|
||||||
|
throw ScriptError(t.pos, errorMessage)
|
||||||
|
} else {
|
||||||
|
previous()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} else true
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun skipTokens(vararg tokenTypes: Token.Type) {
|
||||||
|
while (next().type in tokenTypes) { /**/
|
||||||
|
}
|
||||||
|
previous()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
inline fun ifNextIs(typeId: Token.Type, f: (Token) -> Unit): Boolean {
|
||||||
|
val t = next()
|
||||||
|
return if (t.type == typeId) {
|
||||||
|
f(t)
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
previous()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun addBreak() {
|
||||||
|
breakFound = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return value of the next token if it is an identifier, null otherwise.
|
||||||
|
* Does not change position.
|
||||||
|
*/
|
||||||
|
@Suppress("unused")
|
||||||
|
fun nextIdValue(): String? {
|
||||||
|
return if (hasNext()) {
|
||||||
|
val nt = tokens[currentIndex]
|
||||||
|
if (nt.type == Token.Type.ID)
|
||||||
|
nt.value
|
||||||
|
else null
|
||||||
|
} else null
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun current(): Token = tokens[currentIndex]
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the token at current position plus offset (could be negative) exists, returns it, otherwise returns null.
|
||||||
|
*/
|
||||||
|
@Suppress("unused")
|
||||||
|
fun atOffset(offset: Int): Token? =
|
||||||
|
if (currentIndex + offset in tokens.indices) tokens[currentIndex + offset] else null
|
||||||
|
|
||||||
|
fun matchQualifiers(keyword: String, vararg qualifiers: String): Boolean {
|
||||||
|
val pos = savePos()
|
||||||
|
var count = 0
|
||||||
|
while( count < qualifiers.size) {
|
||||||
|
val t = next()
|
||||||
|
when(t.type) {
|
||||||
|
Token.Type.ID -> {
|
||||||
|
if( t.value in qualifiers ) count++
|
||||||
|
else { restorePos(pos); return false }
|
||||||
|
}
|
||||||
|
Token.Type.MULTILINE_COMMENT, Token.Type.SINLGE_LINE_COMMENT, Token.Type.NEWLINE -> {}
|
||||||
|
else -> { restorePos(pos); return false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val t = next()
|
||||||
|
if( t.type == Token.Type.ID && t.value == keyword ) {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
restorePos(pos)
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Skip newlines and comments. Returns (and reads) first non-whitespace token.
|
||||||
|
* Note that [Token.Type.EOF] is not considered a whitespace token.
|
||||||
|
*/
|
||||||
|
fun skipWsTokens(): Token {
|
||||||
|
while( current().type in wstokens ) {
|
||||||
|
next()
|
||||||
|
}
|
||||||
|
return next()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val wstokens = setOf(Token.Type.NEWLINE, Token.Type.MULTILINE_COMMENT, Token.Type.SINLGE_LINE_COMMENT)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.Accessor
|
||||||
|
|
||||||
|
sealed class ListEntry {
|
||||||
|
data class Element(val accessor: Accessor) : ListEntry()
|
||||||
|
|
||||||
|
data class Spread(val accessor: Accessor) : ListEntry()
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjVoid
|
||||||
|
|
||||||
|
class LoopBreakContinueException(
|
||||||
|
val doContinue: Boolean,
|
||||||
|
val result: Obj = ObjVoid,
|
||||||
|
val label: String? = null
|
||||||
|
) : RuntimeException()
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.ObjRecord
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.pacman.ImportProvider
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Module scope supports importing and contains the [importProvider]; it should be the same
|
||||||
|
* used in [Compiler];
|
||||||
|
*/
|
||||||
|
class ModuleScope(
|
||||||
|
var importProvider: ImportProvider,
|
||||||
|
pos: Pos = Pos.builtIn,
|
||||||
|
override val packageName: String
|
||||||
|
) : Scope(importProvider.rootScope, Arguments.EMPTY, pos) {
|
||||||
|
|
||||||
|
constructor(importProvider: ImportProvider, source: Source) : this(importProvider, source.startPos, source.fileName)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Import symbols into the scope. It _is called_ after the module is imported by [ImportProvider.prepareImport]
|
||||||
|
* which checks symbol availability and accessibility prior to execution.
|
||||||
|
* @param scope where to copy symbols from this module
|
||||||
|
* @param symbols symbols to import, ir present, only symbols keys will be imported renamed to corresponding values
|
||||||
|
*/
|
||||||
|
override suspend fun importInto(scope: Scope, symbols: Map<String, String>?) {
|
||||||
|
val symbolsToImport = symbols?.keys?.toMutableSet()
|
||||||
|
for ((symbol, record) in this.objects) {
|
||||||
|
if (record.visibility.isPublic) {
|
||||||
|
val newName = symbols?.let { ss: Map<String, String> ->
|
||||||
|
ss[symbol]
|
||||||
|
?.also { symbolsToImport!!.remove(it) }
|
||||||
|
?: scope.raiseError("internal error: symbol $symbol not found though the module is cached")
|
||||||
|
} ?: symbol
|
||||||
|
val existing = scope.objects[newName]
|
||||||
|
if (existing != null ) {
|
||||||
|
if (existing.importedFrom != record.importedFrom)
|
||||||
|
scope.raiseError("symbol ${existing.importedFrom?.packageName}.$newName already exists, redefinition on import is not allowed")
|
||||||
|
// already imported
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// when importing records, we keep track of its package (not otherwise needed)
|
||||||
|
if (record.importedFrom == null) record.importedFrom = this
|
||||||
|
scope.objects[newName] = record
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!symbolsToImport.isNullOrEmpty())
|
||||||
|
scope.raiseSymbolNotFound("symbols $packageName.{$symbolsToImport} are.were not found")
|
||||||
|
}
|
||||||
|
|
||||||
|
val packageNameObj by lazy { ObjString(packageName).asReadonly }
|
||||||
|
|
||||||
|
override fun get(name: String): ObjRecord? {
|
||||||
|
return if (name == "__PACKAGE__")
|
||||||
|
packageNameObj
|
||||||
|
else
|
||||||
|
super.get(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
val digitsSet = ('0'..'9').toSet()
|
||||||
|
val digits = { d: Char -> d in digitsSet }
|
||||||
|
val hexDigits = digitsSet + ('a'..'f') + ('A'..'F')
|
||||||
|
val idNextChars = { d: Char -> d.isLetter() || d == '_' || d.isDigit() }
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
val idFirstChars = { d: Char -> d.isLetter() || d == '_' }
|
||||||
|
|
||||||
|
fun parseLyng(source: Source): List<Token> {
|
||||||
|
val p = Parser(fromPos = source.startPos)
|
||||||
|
val tokens = mutableListOf<Token>()
|
||||||
|
do {
|
||||||
|
val t = p.nextToken()
|
||||||
|
tokens += t
|
||||||
|
} while (t.type != Token.Type.EOF)
|
||||||
|
return tokens
|
||||||
|
}
|
||||||
|
|
||||||
|
private class Parser(fromPos: Pos) {
|
||||||
|
|
||||||
|
private val pos = MutablePos(fromPos)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Immutable copy of current position
|
||||||
|
*/
|
||||||
|
private val currentPos: Pos get() = pos.toPos()
|
||||||
|
|
||||||
|
private fun raise(msg: String): Nothing = throw ScriptError(currentPos, msg)
|
||||||
|
|
||||||
|
fun nextToken(): Token {
|
||||||
|
skipws()
|
||||||
|
if (pos.end) return Token("", currentPos, Token.Type.EOF)
|
||||||
|
val from = currentPos
|
||||||
|
return when (val ch = pos.currentChar.also { pos.advance() }) {
|
||||||
|
'(' -> Token("(", from, Token.Type.LPAREN)
|
||||||
|
')' -> Token(")", from, Token.Type.RPAREN)
|
||||||
|
'{' -> Token("{", from, Token.Type.LBRACE)
|
||||||
|
'}' -> Token("}", from, Token.Type.RBRACE)
|
||||||
|
'[' -> Token("[", from, Token.Type.LBRACKET)
|
||||||
|
']' -> Token("]", from, Token.Type.RBRACKET)
|
||||||
|
',' -> Token(",", from, Token.Type.COMMA)
|
||||||
|
';' -> Token(";", from, Token.Type.SEMICOLON)
|
||||||
|
'=' -> {
|
||||||
|
if (pos.currentChar == '=') {
|
||||||
|
pos.advance()
|
||||||
|
when (currentChar) {
|
||||||
|
'=' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("===", from, Token.Type.REF_EQ)
|
||||||
|
}
|
||||||
|
else -> Token("==", from, Token.Type.EQ)
|
||||||
|
}
|
||||||
|
} else if( currentChar == '>' ) {
|
||||||
|
pos.advance()
|
||||||
|
Token("=>", from, Token.Type.EQARROW)
|
||||||
|
}
|
||||||
|
else
|
||||||
|
Token("=", from, Token.Type.ASSIGN)
|
||||||
|
}
|
||||||
|
|
||||||
|
'+' -> {
|
||||||
|
when (currentChar) {
|
||||||
|
'+' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("+", from, Token.Type.PLUS2)
|
||||||
|
}
|
||||||
|
|
||||||
|
'=' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("+", from, Token.Type.PLUSASSIGN)
|
||||||
|
}
|
||||||
|
|
||||||
|
else ->
|
||||||
|
Token("+", from, Token.Type.PLUS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
'-' -> {
|
||||||
|
when (currentChar) {
|
||||||
|
'-' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("--", from, Token.Type.MINUS2)
|
||||||
|
}
|
||||||
|
|
||||||
|
'=' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("-", from, Token.Type.MINUSASSIGN)
|
||||||
|
}
|
||||||
|
|
||||||
|
'>' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("->", from, Token.Type.ARROW)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Token("-", from, Token.Type.MINUS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
'*' -> {
|
||||||
|
if (currentChar == '=') {
|
||||||
|
pos.advance()
|
||||||
|
Token("*=", from, Token.Type.STARASSIGN)
|
||||||
|
} else
|
||||||
|
Token("*", from, Token.Type.STAR)
|
||||||
|
}
|
||||||
|
|
||||||
|
'/' -> when (currentChar) {
|
||||||
|
'/' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token(loadToEndOfLine().trim(), from, Token.Type.SINLGE_LINE_COMMENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
'*' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token(
|
||||||
|
loadTo("*/")?.trim()
|
||||||
|
?: throw ScriptError(from, "Unterminated multiline comment"),
|
||||||
|
from,
|
||||||
|
Token.Type.MULTILINE_COMMENT
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
'=' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("/=", from, Token.Type.SLASHASSIGN)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Token("/", from, Token.Type.SLASH)
|
||||||
|
}
|
||||||
|
|
||||||
|
'%' -> when (currentChar) {
|
||||||
|
'=' -> {
|
||||||
|
pos.advance(); Token("%=", from, Token.Type.PERCENTASSIGN)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> Token("%", from, Token.Type.PERCENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
'.' -> {
|
||||||
|
// could be: dot, range .. or ..<, or ellipsis ...:
|
||||||
|
if (currentChar == '.') {
|
||||||
|
pos.advance()
|
||||||
|
// .. already parsed:
|
||||||
|
when (currentChar) {
|
||||||
|
'.' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("...", from, Token.Type.ELLIPSIS)
|
||||||
|
}
|
||||||
|
|
||||||
|
'<' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("..<", from, Token.Type.DOTDOTLT)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
Token("..", from, Token.Type.DOTDOT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
Token(".", from, Token.Type.DOT)
|
||||||
|
}
|
||||||
|
|
||||||
|
'<' -> {
|
||||||
|
if (currentChar == '=') {
|
||||||
|
pos.advance()
|
||||||
|
if (currentChar == '>') {
|
||||||
|
pos.advance()
|
||||||
|
Token("<=>", from, Token.Type.SHUTTLE)
|
||||||
|
} else {
|
||||||
|
Token("<=", from, Token.Type.LTE)
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
Token("<", from, Token.Type.LT)
|
||||||
|
}
|
||||||
|
|
||||||
|
'>' -> {
|
||||||
|
if (currentChar == '=') {
|
||||||
|
pos.advance()
|
||||||
|
Token(">=", from, Token.Type.GTE)
|
||||||
|
} else
|
||||||
|
Token(">", from, Token.Type.GT)
|
||||||
|
}
|
||||||
|
|
||||||
|
'!' -> {
|
||||||
|
if (currentChar == 'i') {
|
||||||
|
pos.advance()
|
||||||
|
when (currentChar) {
|
||||||
|
'n' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("!in", from, Token.Type.NOTIN)
|
||||||
|
}
|
||||||
|
|
||||||
|
's' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("!is", from, Token.Type.NOTIS)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
pos.back()
|
||||||
|
Token("!", from, Token.Type.NOT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
if (currentChar == '=') {
|
||||||
|
pos.advance()
|
||||||
|
if (currentChar == '=') {
|
||||||
|
pos.advance()
|
||||||
|
Token("!==", from, Token.Type.REF_NEQ)
|
||||||
|
} else
|
||||||
|
Token("!=", from, Token.Type.NEQ)
|
||||||
|
} else
|
||||||
|
Token("!", from, Token.Type.NOT)
|
||||||
|
}
|
||||||
|
|
||||||
|
'|' -> {
|
||||||
|
if (currentChar == '|') {
|
||||||
|
pos.advance()
|
||||||
|
Token("||", from, Token.Type.OR)
|
||||||
|
} else
|
||||||
|
Token("|", from, Token.Type.BITOR)
|
||||||
|
}
|
||||||
|
|
||||||
|
'&' -> {
|
||||||
|
if (currentChar == '&') {
|
||||||
|
pos.advance()
|
||||||
|
Token("&&", from, Token.Type.AND)
|
||||||
|
} else
|
||||||
|
Token("&", from, Token.Type.BITAND)
|
||||||
|
}
|
||||||
|
|
||||||
|
'@' -> {
|
||||||
|
val label = loadChars(idNextChars)
|
||||||
|
if (label.isNotEmpty()) Token(label, from, Token.Type.ATLABEL)
|
||||||
|
else raise("unexpected @ character")
|
||||||
|
}
|
||||||
|
|
||||||
|
'\n' -> Token("\n", from, Token.Type.NEWLINE)
|
||||||
|
|
||||||
|
':' -> {
|
||||||
|
if (currentChar == ':') {
|
||||||
|
pos.advance()
|
||||||
|
Token("::", from, Token.Type.COLONCOLON)
|
||||||
|
} else
|
||||||
|
Token(":", from, Token.Type.COLON)
|
||||||
|
}
|
||||||
|
|
||||||
|
'"' -> loadStringToken()
|
||||||
|
|
||||||
|
in digitsSet -> {
|
||||||
|
pos.back()
|
||||||
|
decodeNumber(loadChars { it in digitsSet || it == '_'}, from)
|
||||||
|
}
|
||||||
|
|
||||||
|
'\'' -> {
|
||||||
|
val start = pos.toPos()
|
||||||
|
var value = currentChar
|
||||||
|
pos.advance()
|
||||||
|
if (currentChar == '\\') {
|
||||||
|
value = currentChar
|
||||||
|
pos.advance()
|
||||||
|
value = when (value) {
|
||||||
|
'n' -> '\n'
|
||||||
|
'r' -> '\r'
|
||||||
|
't' -> '\t'
|
||||||
|
'\'', '\\' -> value
|
||||||
|
else -> throw ScriptError(currentPos, "unsupported escape character: $value")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (currentChar != '\'') throw ScriptError(currentPos, "expected end of character literal: '")
|
||||||
|
pos.advance()
|
||||||
|
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 -> {
|
||||||
|
// text infix operators:
|
||||||
|
// Labels processing is complicated!
|
||||||
|
// some@ statement: label 'some', ID 'statement'
|
||||||
|
// statement@some: ID 'statement', LABEL 'some'!
|
||||||
|
if (ch.isLetter() || ch == '_') {
|
||||||
|
val text = ch + loadChars(idNextChars)
|
||||||
|
if (currentChar == '@') {
|
||||||
|
pos.advance()
|
||||||
|
if (currentChar.isLetter()) {
|
||||||
|
// break@label or like
|
||||||
|
pos.back()
|
||||||
|
Token(text, from, Token.Type.ID)
|
||||||
|
} else
|
||||||
|
Token(text, from, Token.Type.LABEL)
|
||||||
|
} else
|
||||||
|
when (text) {
|
||||||
|
"in" -> Token("in", from, Token.Type.IN)
|
||||||
|
"is" -> Token("is", from, Token.Type.IS)
|
||||||
|
else -> Token(text, from, Token.Type.ID)
|
||||||
|
}
|
||||||
|
} else
|
||||||
|
raise("can't parse token")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun decodeNumber(p1: String, start: Pos): Token =
|
||||||
|
if (pos.end)
|
||||||
|
Token(p1, start, Token.Type.INT)
|
||||||
|
else if (currentChar == 'e' || currentChar == 'E') {
|
||||||
|
pos.advance()
|
||||||
|
var negative = false
|
||||||
|
if (currentChar == '+')
|
||||||
|
pos.advance()
|
||||||
|
else if (currentChar == '-') {
|
||||||
|
negative = true
|
||||||
|
pos.advance()
|
||||||
|
}
|
||||||
|
var p3 = loadChars(digits)
|
||||||
|
if (negative) p3 = "-$p3"
|
||||||
|
Token("${p1}e$p3", start, Token.Type.REAL)
|
||||||
|
} else if (currentChar == '.') {
|
||||||
|
// could be decimal
|
||||||
|
pos.advance()
|
||||||
|
if (currentChar in digitsSet) {
|
||||||
|
// decimal part
|
||||||
|
val p2 = loadChars(digits)
|
||||||
|
// with exponent?
|
||||||
|
if (currentChar == 'e' || currentChar == 'E') {
|
||||||
|
pos.advance()
|
||||||
|
var negative = false
|
||||||
|
if (currentChar == '+')
|
||||||
|
pos.advance()
|
||||||
|
else if (currentChar == '-') {
|
||||||
|
negative = true
|
||||||
|
pos.advance()
|
||||||
|
}
|
||||||
|
var p3 = loadChars(digits)
|
||||||
|
if (negative) p3 = "-$p3"
|
||||||
|
Token("$p1.${p2}e$p3", start, Token.Type.REAL)
|
||||||
|
} else {
|
||||||
|
// no exponent
|
||||||
|
Token("$p1.$p2", start, Token.Type.REAL)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// not decimal
|
||||||
|
// something like 10.times, method call on integer number
|
||||||
|
pos.back()
|
||||||
|
Token(p1, start, Token.Type.INT)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// could be integer, also hex:
|
||||||
|
if (currentChar == 'x' && p1 == "0") {
|
||||||
|
pos.advance()
|
||||||
|
Token(loadChars { it in hexDigits }, start, Token.Type.HEX).also {
|
||||||
|
if (currentChar.isLetter())
|
||||||
|
raise("invalid hex literal")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Token(p1, start, Token.Type.INT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
private val currentChar: Char get() = pos.currentChar
|
||||||
|
|
||||||
|
private fun loadStringToken(): Token {
|
||||||
|
val start = currentPos
|
||||||
|
|
||||||
|
// if (currentChar == '"') pos.advance()
|
||||||
|
// else start = start.back()
|
||||||
|
// start = start.back()
|
||||||
|
|
||||||
|
val sb = StringBuilder()
|
||||||
|
while (currentChar != '"') {
|
||||||
|
if (pos.end) throw ScriptError(start, "unterminated string started there")
|
||||||
|
when (currentChar) {
|
||||||
|
'\\' -> {
|
||||||
|
pos.advance() ?: raise("unterminated string")
|
||||||
|
when (currentChar) {
|
||||||
|
'n' -> sb.append('\n')
|
||||||
|
'r' -> sb.append('\r')
|
||||||
|
't' -> sb.append('\t')
|
||||||
|
'"' -> sb.append('"')
|
||||||
|
else -> sb.append('\\').append(currentChar)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
sb.append(currentChar)
|
||||||
|
pos.advance()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pos.advance()
|
||||||
|
return Token(sb.toString(), start, Token.Type.STRING)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load characters from the set until it reaches EOF or invalid character found.
|
||||||
|
* stop at EOF on character filtered by [isValidChar].
|
||||||
|
*
|
||||||
|
* Note this function loads only on one string. Multiline texts are not supported by
|
||||||
|
* this method.
|
||||||
|
*
|
||||||
|
* @return the string of valid characters, could be empty
|
||||||
|
*/
|
||||||
|
private fun loadChars(isValidChar: (Char) -> Boolean): String {
|
||||||
|
val startLine = pos.line
|
||||||
|
val result = StringBuilder()
|
||||||
|
while (!pos.end && pos.line == startLine) {
|
||||||
|
val ch = pos.currentChar
|
||||||
|
if (isValidChar(ch)) {
|
||||||
|
result.append(ch)
|
||||||
|
pos.advance()
|
||||||
|
} else
|
||||||
|
break
|
||||||
|
}
|
||||||
|
return result.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
private fun loadUntil(endChars: Set<Char>): String {
|
||||||
|
return if (pos.end) ""
|
||||||
|
else {
|
||||||
|
val result = StringBuilder()
|
||||||
|
while (!pos.end) {
|
||||||
|
val ch = pos.currentChar
|
||||||
|
if (ch in endChars) break
|
||||||
|
result.append(ch)
|
||||||
|
pos.advance()
|
||||||
|
}
|
||||||
|
result.toString()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadToEndOfLine(): String {
|
||||||
|
val result = StringBuilder()
|
||||||
|
val l = pos.line
|
||||||
|
do {
|
||||||
|
result.append(pos.currentChar)
|
||||||
|
pos.advance()
|
||||||
|
} while (pos.line == l)
|
||||||
|
return result.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun loadTo(str: String): String? {
|
||||||
|
val result = StringBuilder()
|
||||||
|
while (!pos.readFragment(str)) {
|
||||||
|
if (pos.end) return null
|
||||||
|
result.append(pos.currentChar); pos.advance()
|
||||||
|
}
|
||||||
|
return result.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* next non-whitespace char (newline are skipped too) or null if EOF
|
||||||
|
*/
|
||||||
|
private fun skipws(): Char? {
|
||||||
|
while (!pos.end) {
|
||||||
|
val ch = pos.currentChar
|
||||||
|
if (ch == '\n') break
|
||||||
|
if (ch.isWhitespace())
|
||||||
|
pos.advance()
|
||||||
|
else
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
// skip shebang
|
||||||
|
if( pos.readFragment("#!") )
|
||||||
|
loadToEndOfLine()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+33
-10
@@ -1,10 +1,11 @@
|
|||||||
package net.sergeych.ling
|
package net.sergeych.lyng
|
||||||
|
|
||||||
data class Pos(val source: Source, val line: Int, val column: Int) {
|
data class Pos(val source: Source, val line: Int, val column: Int) {
|
||||||
override fun toString(): String {
|
override fun toString(): String {
|
||||||
return "${source.fileName}:$line:$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)
|
||||||
@@ -16,6 +17,7 @@ data class Pos(val source: Source, val line: Int, val column: Int) {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val builtIn = Pos(Source.builtIn, 0, 0)
|
val builtIn = Pos(Source.builtIn, 0, 0)
|
||||||
|
val UNKNOWN = Pos(Source.UNKNOWN, -1, -1)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -36,27 +38,48 @@ class MutablePos(private val from: Pos) {
|
|||||||
fun advance(): Char? {
|
fun advance(): Char? {
|
||||||
if (end) return null
|
if (end) return null
|
||||||
val current = lines[line]
|
val current = lines[line]
|
||||||
return if (column+1 < current.length) {
|
return if (column < current.length) {
|
||||||
current[column++]
|
column++
|
||||||
|
currentChar
|
||||||
} else {
|
} else {
|
||||||
line++
|
|
||||||
column = 0
|
column = 0
|
||||||
if(line >= lines.size) null
|
if(++line >= lines.size) null
|
||||||
else lines[line][column]
|
else currentChar
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun resetTo(pos: Pos) { line = pos.line; column = pos.column }
|
||||||
|
|
||||||
fun back() {
|
fun back() {
|
||||||
if (column > 0) column--
|
if (column > 0) column--
|
||||||
else if (line > 0)
|
else if (line > 0)
|
||||||
column = lines[--line].length - 1
|
column = lines[--line].length - 1
|
||||||
else throw IllegalStateException("can't go back from line 0, column 0")
|
else throw IllegalStateException("can't go back from line 0, column 0")
|
||||||
}
|
}
|
||||||
|
|
||||||
val currentChar: Char
|
val currentChar: Char
|
||||||
get() =
|
get() {
|
||||||
if (end) 0.toChar()
|
if (end) return 0.toChar()
|
||||||
else lines[line][column]
|
val current = lines[line]
|
||||||
|
return if (column >= current.length) '\n'
|
||||||
|
else current[column]
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If the next characters are equal to the fragment, advances the position and returns true.
|
||||||
|
* Otherwise, does nothing and returns false.
|
||||||
|
*/
|
||||||
|
fun readFragment(fragment: String): Boolean {
|
||||||
|
val mark = toPos()
|
||||||
|
for(ch in fragment)
|
||||||
|
if( currentChar != ch ) { resetTo(mark); return false }
|
||||||
|
else advance()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
override fun toString() = "($line:$column)"
|
override fun toString() = "($line:$column)"
|
||||||
|
|
||||||
|
init {
|
||||||
|
if( lines[0].isEmpty()) advance()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.*
|
||||||
|
import net.sergeych.lyng.pacman.ImportManager
|
||||||
|
import net.sergeych.lyng.pacman.ImportProvider
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scope is where local variables and methods are stored. Scope is also a parent scope for other scopes.
|
||||||
|
* Each block usually creates a scope. Accessing Lyng closures usually is done via a scope.
|
||||||
|
*
|
||||||
|
* To create default scope, use default `Scope()` constructor, it will create a scope with a parent
|
||||||
|
* module scope with default [ImportManager], you can access with [currentImportProvider] as needed.
|
||||||
|
*
|
||||||
|
* If you want to create [ModuleScope] by hand, try [currentImportProvider] and [ImportManager.newModule],
|
||||||
|
* or [ImportManager.newModuleAt].
|
||||||
|
*
|
||||||
|
* There are special types of scopes:
|
||||||
|
*
|
||||||
|
* - [AppliedScope] - scope used to apply a closure to some thisObj scope
|
||||||
|
*/
|
||||||
|
open class Scope(
|
||||||
|
val parent: Scope?,
|
||||||
|
val args: Arguments = Arguments.EMPTY,
|
||||||
|
var pos: Pos = Pos.builtIn,
|
||||||
|
var thisObj: Obj = ObjVoid,
|
||||||
|
var skipScopeCreation: Boolean = false,
|
||||||
|
) {
|
||||||
|
open val packageName: String = "<anonymous package>"
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
args: Arguments = Arguments.EMPTY,
|
||||||
|
pos: Pos = Pos.builtIn,
|
||||||
|
)
|
||||||
|
: this(Script.defaultImportManager.copy().newModuleAt(pos), args, pos)
|
||||||
|
|
||||||
|
fun raiseNotImplemented(what: String = "operation"): Nothing = raiseError("$what is not implemented")
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun raiseNPE(): Nothing = raiseError(ObjNullReferenceException(this))
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun raiseIndexOutOfBounds(message: String = "Index out of bounds"): Nothing =
|
||||||
|
raiseError(ObjIndexOutOfBoundsException(this, message))
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun raiseIllegalArgument(message: String = "Illegal argument error"): Nothing =
|
||||||
|
raiseError(ObjIllegalArgumentException(this, message))
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun raiseIllegalState(message: String = "Illegal argument error"): Nothing =
|
||||||
|
raiseError(ObjIllegalStateException(this, message))
|
||||||
|
|
||||||
|
fun raiseIllegalAssignment(message: String): Nothing =
|
||||||
|
raiseError(ObjIllegalAssignmentException(this, message))
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun raiseNoSuchElement(message: String = "No such element"): Nothing =
|
||||||
|
raiseError(ObjIllegalArgumentException(this, message))
|
||||||
|
|
||||||
|
fun raiseClassCastError(msg: String): Nothing = raiseError(ObjClassCastException(this, msg))
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun raiseSymbolNotFound(name: String): Nothing =
|
||||||
|
raiseError(ObjSymbolNotDefinedException(this, "symbol is not defined: $name"))
|
||||||
|
|
||||||
|
fun raiseError(message: String): Nothing {
|
||||||
|
throw ExecutionError(ObjException(this, message))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun raiseError(obj: ObjException): Nothing {
|
||||||
|
throw ExecutionError(obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <reified T : Obj> requiredArg(index: Int): T {
|
||||||
|
if (args.list.size <= index) raiseError("Expected at least ${index + 1} argument, got ${args.list.size}")
|
||||||
|
return (args.list[index] as? T)
|
||||||
|
?: raiseClassCastError("Expected type ${T::class.simpleName}, got ${args.list[index]::class.simpleName}")
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <reified T : Obj> requireOnlyArg(): T {
|
||||||
|
if (args.list.size != 1) raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
||||||
|
return requiredArg(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun requireExactCount(count: Int) {
|
||||||
|
if (args.list.size != count) {
|
||||||
|
raiseError("Expected exactly $count arguments, got ${args.list.size}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun requireNoArgs() {
|
||||||
|
if( args.list.isNotEmpty())
|
||||||
|
raiseError("This function does not accept any arguments")
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <reified T : Obj> thisAs(): T = (thisObj as? T)
|
||||||
|
?: raiseClassCastError("Cannot cast ${thisObj.objClass.className} to ${T::class.simpleName}")
|
||||||
|
|
||||||
|
internal val objects = mutableMapOf<String, ObjRecord>()
|
||||||
|
|
||||||
|
open operator fun get(name: String): ObjRecord? =
|
||||||
|
if (name == "this") thisObj.asReadonly
|
||||||
|
else {
|
||||||
|
objects[name]
|
||||||
|
?: parent?.get(name)
|
||||||
|
?: thisObj.objClass.getInstanceMemberOrNull(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun copy(pos: Pos, args: Arguments = Arguments.EMPTY, newThisObj: Obj? = null): Scope =
|
||||||
|
Scope(this, args, pos, newThisObj ?: thisObj)
|
||||||
|
|
||||||
|
fun copy(args: Arguments = Arguments.EMPTY, newThisObj: Obj? = null): Scope =
|
||||||
|
Scope(this, args, pos, newThisObj ?: thisObj)
|
||||||
|
|
||||||
|
fun copy() = Scope(this, args, pos, thisObj)
|
||||||
|
|
||||||
|
fun addItem(
|
||||||
|
name: String,
|
||||||
|
isMutable: Boolean,
|
||||||
|
value: Obj,
|
||||||
|
visibility: Visibility = Visibility.Public,
|
||||||
|
recordType: ObjRecord.Type = ObjRecord.Type.Other
|
||||||
|
): ObjRecord {
|
||||||
|
return ObjRecord(value, isMutable, visibility,type = recordType).also { objects[name] = it }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getOrCreateNamespace(name: String): ObjClass {
|
||||||
|
val ns = objects.getOrPut(name) { ObjRecord(ObjNamespace(name), isMutable = false) }.value
|
||||||
|
return ns.objClass
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun addVoidFn(vararg names: String, crossinline fn: suspend Scope.() -> Unit) {
|
||||||
|
addFn<ObjVoid>(*names) {
|
||||||
|
fn(this)
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline fun <reified T : Obj> addFn(vararg names: String, crossinline fn: suspend Scope.() -> T) {
|
||||||
|
val newFn = object : Statement() {
|
||||||
|
override val pos: Pos = Pos.builtIn
|
||||||
|
|
||||||
|
override suspend fun execute(scope: Scope): Obj = scope.fn()
|
||||||
|
|
||||||
|
}
|
||||||
|
for (name in names) {
|
||||||
|
addItem(
|
||||||
|
name,
|
||||||
|
false,
|
||||||
|
newFn
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addConst(name: String, value: Obj) = addItem(name, false, value)
|
||||||
|
|
||||||
|
suspend fun eval(code: String): Obj =
|
||||||
|
Compiler.compile(code.toSource(), currentImportProvider).execute(this)
|
||||||
|
|
||||||
|
suspend fun eval(source: Source): Obj =
|
||||||
|
Compiler.compile(
|
||||||
|
source,
|
||||||
|
currentImportProvider
|
||||||
|
).execute(this)
|
||||||
|
|
||||||
|
fun containsLocal(name: String): Boolean = name in objects
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Some scopes can be imported into other scopes, like [ModuleScope]. Those must correctly implement this method.
|
||||||
|
* @param scope where to copy symbols from this module
|
||||||
|
* @param symbols symbols to import, ir present, only symbols keys will be imported renamed to corresponding values
|
||||||
|
*/
|
||||||
|
open suspend fun importInto(scope: Scope, symbols: Map<String, String>? = null) {
|
||||||
|
scope.raiseError(ObjIllegalOperationException(scope, "Import is not allowed here: import $packageName"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Find a first [ImportManager] in this Scope hierarchy. Normally there should be one. Found instance is cached.
|
||||||
|
*
|
||||||
|
* Use it to register your package sources, see [ImportManager] features.
|
||||||
|
*
|
||||||
|
* @throws IllegalStateException if there is no such manager (if you create some specific scope with no manager,
|
||||||
|
* then you knew what you did)
|
||||||
|
*/
|
||||||
|
val currentImportProvider: ImportProvider by lazy {
|
||||||
|
if (this is ModuleScope)
|
||||||
|
importProvider.getActualProvider()
|
||||||
|
else
|
||||||
|
parent?.currentImportProvider ?: throw IllegalStateException("this scope has no manager in the chain")
|
||||||
|
}
|
||||||
|
|
||||||
|
val importManager by lazy { (currentImportProvider as? ImportManager)
|
||||||
|
?: throw IllegalStateException("this scope has no manager in the chain (provided $currentImportProvider") }
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
fun new(): Scope =
|
||||||
|
Script.defaultImportManager.copy().newModuleAt(Pos.builtIn)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
import kotlinx.coroutines.yield
|
||||||
|
import net.sergeych.lyng.obj.*
|
||||||
|
import net.sergeych.lyng.pacman.ImportManager
|
||||||
|
import net.sergeych.lynon.ObjLynonClass
|
||||||
|
import net.sergeych.mp_tools.globalDefer
|
||||||
|
import kotlin.math.*
|
||||||
|
|
||||||
|
class Script(
|
||||||
|
override val pos: Pos,
|
||||||
|
private val statements: List<Statement> = emptyList(),
|
||||||
|
// private val catchReturn: Boolean = false,
|
||||||
|
) : Statement() {
|
||||||
|
|
||||||
|
override suspend fun execute(scope: Scope): Obj {
|
||||||
|
var lastResult: Obj = ObjVoid
|
||||||
|
for (s in statements) {
|
||||||
|
lastResult = s.execute(scope)
|
||||||
|
}
|
||||||
|
return lastResult
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun execute() = execute(defaultImportManager.newModule())
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
private val rootScope: Scope = Scope(null).apply {
|
||||||
|
ObjException.addExceptionsToContext(this)
|
||||||
|
addFn("println") {
|
||||||
|
for ((i, a) in args.withIndex()) {
|
||||||
|
if (i > 0) print(' ' + a.asStr.value)
|
||||||
|
else print(a.asStr.value)
|
||||||
|
}
|
||||||
|
println()
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
addFn("floor") {
|
||||||
|
val x = args.firstAndOnly()
|
||||||
|
(if (x is ObjInt) x
|
||||||
|
else ObjReal(floor(x.toDouble())))
|
||||||
|
}
|
||||||
|
addFn("ceil") {
|
||||||
|
val x = args.firstAndOnly()
|
||||||
|
(if (x is ObjInt) x
|
||||||
|
else ObjReal(ceil(x.toDouble())))
|
||||||
|
}
|
||||||
|
addFn("round") {
|
||||||
|
val x = args.firstAndOnly()
|
||||||
|
(if (x is ObjInt) x
|
||||||
|
else ObjReal(round(x.toDouble())))
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("sin") {
|
||||||
|
ObjReal(sin(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("cos") {
|
||||||
|
ObjReal(cos(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("tan") {
|
||||||
|
ObjReal(tan(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("asin") {
|
||||||
|
ObjReal(asin(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("acos") {
|
||||||
|
ObjReal(acos(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("atan") {
|
||||||
|
ObjReal(atan(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("sinh") {
|
||||||
|
ObjReal(sinh(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("cosh") {
|
||||||
|
ObjReal(cosh(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("tanh") {
|
||||||
|
ObjReal(tanh(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("asinh") {
|
||||||
|
ObjReal(asinh(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("acosh") {
|
||||||
|
ObjReal(acosh(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("atanh") {
|
||||||
|
ObjReal(atanh(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("exp") {
|
||||||
|
ObjReal(exp(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
addFn("ln") {
|
||||||
|
ObjReal(ln(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("log10") {
|
||||||
|
ObjReal(log10(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("log2") {
|
||||||
|
ObjReal(log2(args.firstAndOnly().toDouble()))
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("pow") {
|
||||||
|
requireExactCount(2)
|
||||||
|
ObjReal(
|
||||||
|
(args[0].toDouble()).pow(args[1].toDouble())
|
||||||
|
)
|
||||||
|
}
|
||||||
|
addFn("sqrt") {
|
||||||
|
ObjReal(
|
||||||
|
sqrt(args.firstAndOnly().toDouble())
|
||||||
|
)
|
||||||
|
}
|
||||||
|
addFn( "abs" ) {
|
||||||
|
val x = args.firstAndOnly()
|
||||||
|
if( x is ObjInt) ObjInt( x.value.absoluteValue ) else ObjReal( x.toDouble().absoluteValue )
|
||||||
|
}
|
||||||
|
|
||||||
|
addVoidFn("assert") {
|
||||||
|
val cond = requiredArg<ObjBool>(0)
|
||||||
|
if( !cond.value == true )
|
||||||
|
raiseError(ObjAssertionFailedException(this,"Assertion failed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
addVoidFn("assertEquals") {
|
||||||
|
val a = requiredArg<Obj>(0)
|
||||||
|
val b = requiredArg<Obj>(1)
|
||||||
|
if( a.compareTo(this, b) != 0 )
|
||||||
|
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect()} == ${b.inspect()}"))
|
||||||
|
}
|
||||||
|
addVoidFn("assertNotEquals") {
|
||||||
|
val a = requiredArg<Obj>(0)
|
||||||
|
val b = requiredArg<Obj>(1)
|
||||||
|
if( a.compareTo(this, b) == 0 )
|
||||||
|
raiseError(ObjAssertionFailedException(this,"Assertion failed: ${a.inspect()} != ${b.inspect()}"))
|
||||||
|
}
|
||||||
|
addFn("assertThrows") {
|
||||||
|
val code = requireOnlyArg<Statement>()
|
||||||
|
val result =try {
|
||||||
|
code.execute(this)
|
||||||
|
null
|
||||||
|
}
|
||||||
|
catch( e: ExecutionError ) {
|
||||||
|
e.errorObject
|
||||||
|
}
|
||||||
|
catch (e: ScriptError) {
|
||||||
|
ObjNull
|
||||||
|
}
|
||||||
|
result ?: raiseError(ObjAssertionFailedException(this,"Expected exception but nothing was thrown"))
|
||||||
|
}
|
||||||
|
|
||||||
|
addVoidFn("delay") {
|
||||||
|
delay((this.args.firstAndOnly().toDouble()/1000.0).roundToLong())
|
||||||
|
}
|
||||||
|
|
||||||
|
addConst("Object", rootObjectType)
|
||||||
|
addConst("Real", ObjReal.type)
|
||||||
|
addConst("String", ObjString.type)
|
||||||
|
addConst("Int", ObjInt.type)
|
||||||
|
addConst("Bool", ObjBool.type)
|
||||||
|
addConst("Char", ObjChar.type)
|
||||||
|
addConst("List", ObjList.type)
|
||||||
|
addConst("Set", ObjSet.type)
|
||||||
|
addConst("Range", ObjRange.type)
|
||||||
|
addConst("Map", ObjMap.type)
|
||||||
|
addConst("MapEntry", ObjMapEntry.type)
|
||||||
|
@Suppress("RemoveRedundantQualifierName")
|
||||||
|
addConst("Callable", Statement.type)
|
||||||
|
// interfaces
|
||||||
|
addConst("Iterable", ObjIterable)
|
||||||
|
addConst("Collection", ObjCollection)
|
||||||
|
addConst("Array", ObjArray)
|
||||||
|
addConst("Class", ObjClassType)
|
||||||
|
|
||||||
|
addConst("Deferred", ObjDeferred.type)
|
||||||
|
addConst("CompletableDeferred", ObjCompletableDeferred.type)
|
||||||
|
addConst("Mutex", ObjMutex.type)
|
||||||
|
|
||||||
|
addFn("launch") {
|
||||||
|
val callable = args.firstAndOnly() as Statement
|
||||||
|
ObjDeferred(globalDefer {
|
||||||
|
callable.execute(this@addFn)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("yield") {
|
||||||
|
yield()
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
val pi = ObjReal(PI)
|
||||||
|
addConst("π", pi)
|
||||||
|
getOrCreateNamespace("Math").apply {
|
||||||
|
addConst("PI", pi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val defaultImportManager: ImportManager by lazy {
|
||||||
|
ImportManager(rootScope, SecurityManager.allowAll).apply {
|
||||||
|
addPackage("lyng.buffer") {
|
||||||
|
it.addConst("Buffer", ObjBuffer.type)
|
||||||
|
it.addConst("MutableBuffer", ObjMutableBuffer.type)
|
||||||
|
}
|
||||||
|
addPackage("lyng.serialization") {
|
||||||
|
it.addConst("Lynon", ObjLynonClass)
|
||||||
|
}
|
||||||
|
addPackage("lyng.time") {
|
||||||
|
it.addConst("Instant", ObjInstant.type)
|
||||||
|
it.addConst("Duration", ObjDuration.type)
|
||||||
|
it.addFn("delay") {
|
||||||
|
val a = args.firstAndOnly()
|
||||||
|
when(a) {
|
||||||
|
is ObjInt -> delay(a.value * 1000)
|
||||||
|
is ObjReal -> delay((a.value * 1000).roundToLong())
|
||||||
|
is ObjDuration -> delay(a.duration)
|
||||||
|
else -> raiseIllegalArgument("Expected Duration, Int or Real, got ${a.inspect()}")
|
||||||
|
}
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
@file:Suppress("CanBeParameter")
|
||||||
|
|
||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import net.sergeych.lyng.obj.ObjException
|
||||||
|
|
||||||
|
open class ScriptError(val pos: Pos, val errorMessage: String, cause: Throwable? = null) : Exception(
|
||||||
|
"""
|
||||||
|
$pos: Error: $errorMessage
|
||||||
|
|
||||||
|
${pos.currentLine}
|
||||||
|
${"-".repeat(pos.column)}^
|
||||||
|
""".trimIndent(),
|
||||||
|
cause
|
||||||
|
)
|
||||||
|
|
||||||
|
class ExecutionError(val errorObject: ObjException) : ScriptError(errorObject.scope.pos, errorObject.message)
|
||||||
|
|
||||||
|
class ImportException(pos: Pos, message: String) : ScriptError(pos, message)
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
interface SecurityManager {
|
||||||
|
/**
|
||||||
|
* Check that any symbol from the corresponding module can be imported. If it returns false,
|
||||||
|
* the module will not be imported and no further processing will be done
|
||||||
|
*/
|
||||||
|
fun canImportModule(name: String): Boolean
|
||||||
|
|
||||||
|
/**\
|
||||||
|
* if [canImportModule] this method allows fine-grained control over symbols.
|
||||||
|
*/
|
||||||
|
fun canImportSymbol(moduleName: String, symbolName: String): Boolean = true
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val allowAll: SecurityManager = object : SecurityManager {
|
||||||
|
override fun canImportModule(name: String): Boolean = true
|
||||||
|
override fun canImportSymbol(moduleName: String, symbolName: String): Boolean = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
class Source(val fileName: String, text: String) {
|
||||||
|
|
||||||
|
val lines = text.lines().map { it.trimEnd() }
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val builtIn: Source by lazy { Source("built-in", "") }
|
||||||
|
val UNKNOWN: Source by lazy { Source("UNKNOWN", "") }
|
||||||
|
}
|
||||||
|
|
||||||
|
val startPos: Pos = Pos(this, 0, 0)
|
||||||
|
|
||||||
|
fun posAt(line: Int, column: Int): Pos = Pos(this, line, column)
|
||||||
|
|
||||||
|
fun extractPackageName(): String {
|
||||||
|
for ((n,line) in lines.withIndex()) {
|
||||||
|
if( line.isBlank() || line.isEmpty() )
|
||||||
|
continue
|
||||||
|
if( line.startsWith("package ") )
|
||||||
|
return line.substring(8).trim()
|
||||||
|
else throw ScriptError(Pos(this, n, 0),"package declaration expected")
|
||||||
|
}
|
||||||
|
throw ScriptError(Pos(this, 0, 0),"package declaration expected")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
data class Token(val value: String, val pos: Pos, val type: Type) {
|
||||||
|
val isComment: Boolean by lazy { type == Type.SINLGE_LINE_COMMENT || type == Type.MULTILINE_COMMENT }
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
enum class Type {
|
||||||
|
ID, INT, REAL, HEX, STRING, CHAR,
|
||||||
|
LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, COMMA,
|
||||||
|
SEMICOLON, COLON,
|
||||||
|
PLUS, MINUS, STAR, SLASH, PERCENT,
|
||||||
|
ASSIGN, PLUSASSIGN, MINUSASSIGN, STARASSIGN, SLASHASSIGN, PERCENTASSIGN,
|
||||||
|
PLUS2, MINUS2,
|
||||||
|
IN, NOTIN, IS, NOTIS,
|
||||||
|
EQ, NEQ, LT, LTE, GT, GTE, REF_EQ, REF_NEQ,
|
||||||
|
SHUTTLE,
|
||||||
|
AND, BITAND, OR, BITOR, NOT, BITNOT, DOT, ARROW, EQARROW, QUESTION, COLONCOLON,
|
||||||
|
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
||||||
|
LABEL, ATLABEL, // label@ at@label
|
||||||
|
//PUBLIC, PROTECTED, INTERNAL, EXPORT, OPEN, INLINE, OVERRIDE, ABSTRACT, SEALED, EXTERNAL, VAL, VAR, CONST, TYPE, FUN, CLASS, INTERFACE, ENUM, OBJECT, TRAIT, THIS,
|
||||||
|
ELLIPSIS, DOTDOT, DOTDOTLT,
|
||||||
|
NEWLINE,
|
||||||
|
EOF,
|
||||||
|
NULL_COALESCE,
|
||||||
|
ELVIS,
|
||||||
|
NULL_COALESCE_INDEX,
|
||||||
|
NULL_COALESCE_INVOKE,
|
||||||
|
NULL_COALESCE_BLOCKINVOKE,
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
// fun eof(parser: Parser) = Token("", parser.currentPos, Type.EOF)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
@file:Suppress("unused")
|
||||||
|
|
||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
// this is highly experimental and subject to complete redesign
|
||||||
|
// very soon
|
||||||
|
sealed class TypeDecl(val isNullable:Boolean = false) {
|
||||||
|
// ??
|
||||||
|
// data class Fn(val argTypes: List<ArgsDeclaration.Item>, val retType: TypeDecl) : TypeDecl()
|
||||||
|
object TypeAny : TypeDecl()
|
||||||
|
object TypeNullableAny : TypeDecl(true)
|
||||||
|
|
||||||
|
class Simple(val name: String,isNullable: Boolean) : TypeDecl(isNullable)
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
enum class Visibility {
|
||||||
|
Public, Private, Protected;//, Internal
|
||||||
|
val isPublic by lazy { this == Public }
|
||||||
|
@Suppress("unused")
|
||||||
|
val isProtected by lazy { this == Protected }
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
|
||||||
|
val LyngVersion = BuildKonfig.version
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
|
||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Compiler
|
||||||
|
import net.sergeych.lyng.Pos
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.ScriptError
|
||||||
|
|
||||||
|
// avoid KDOC bug: keep it
|
||||||
|
@Suppress("unused")
|
||||||
|
typealias DocCompiler = Compiler
|
||||||
|
/**
|
||||||
|
* When we need read-write access to an object in some abstract storage, we need Accessor,
|
||||||
|
* as in-site assigning is not always sufficient, in general case we need to replace the object
|
||||||
|
* in the storage.
|
||||||
|
*
|
||||||
|
* Note that assigning new value is more complex than just replacing the object, see how assignment
|
||||||
|
* operator is implemented in [Compiler.allOps].
|
||||||
|
*/
|
||||||
|
data class Accessor(
|
||||||
|
val getter: suspend (Scope) -> ObjRecord,
|
||||||
|
val setterOrNull: (suspend (Scope, Obj) -> Unit)?
|
||||||
|
) {
|
||||||
|
/**
|
||||||
|
* Simplified constructor for immutable stores.
|
||||||
|
*/
|
||||||
|
constructor(getter: suspend (Scope) -> ObjRecord) : this(getter, null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the setter or throw.
|
||||||
|
*/
|
||||||
|
fun setter(pos: Pos) = setterOrNull ?: throw ScriptError(pos, "can't assign value")
|
||||||
|
}
|
||||||
@@ -0,0 +1,546 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.serialization.SerialName
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import net.sergeych.bintools.encodeToHex
|
||||||
|
import net.sergeych.lyng.*
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
import net.sergeych.synctools.ProtectedOp
|
||||||
|
import net.sergeych.synctools.withLock
|
||||||
|
import kotlin.contracts.ExperimentalContracts
|
||||||
|
|
||||||
|
open class Obj {
|
||||||
|
|
||||||
|
open val isConst: Boolean = false
|
||||||
|
|
||||||
|
fun ensureNotConst(scope: Scope) {
|
||||||
|
if (isConst) scope.raiseError("can't assign to constant")
|
||||||
|
}
|
||||||
|
|
||||||
|
val isNull by lazy { this === ObjNull }
|
||||||
|
|
||||||
|
var isFrozen: Boolean = false
|
||||||
|
|
||||||
|
private val monitor = Mutex()
|
||||||
|
|
||||||
|
// private val memberMutex = Mutex()
|
||||||
|
internal var parentInstances: MutableList<Obj> = mutableListOf()
|
||||||
|
|
||||||
|
private val opInstances = ProtectedOp()
|
||||||
|
|
||||||
|
open fun inspect(): String = toString()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Some objects are by-value, historically [ObjInt] and [ObjReal] are usually treated as such.
|
||||||
|
* When initializing a var with it, by value objects must be copied. By-reference ones aren't.
|
||||||
|
*
|
||||||
|
* Almost all objects are by-reference.
|
||||||
|
*/
|
||||||
|
open fun byValueCopy(): Obj = this
|
||||||
|
|
||||||
|
@Suppress("SuspiciousEqualsCombination")
|
||||||
|
fun isInstanceOf(someClass: Obj) = someClass === objClass ||
|
||||||
|
objClass.allParentsSet.contains(someClass) ||
|
||||||
|
someClass == rootObjectType
|
||||||
|
|
||||||
|
|
||||||
|
suspend fun invokeInstanceMethod(scope: Scope, name: String, vararg args: Obj): Obj =
|
||||||
|
invokeInstanceMethod(scope, name, Arguments(args.toList()))
|
||||||
|
|
||||||
|
suspend inline fun <reified T : Obj> callMethod(
|
||||||
|
scope: Scope,
|
||||||
|
name: String,
|
||||||
|
args: Arguments = Arguments.EMPTY
|
||||||
|
): T = invokeInstanceMethod(scope, name, args) as T
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Invoke a method of the object if exists
|
||||||
|
* it [onNotFoundResult] is not null, it returns it when symbol is not found
|
||||||
|
* otherwise throws [ObjSymbolNotDefinedException] object exception
|
||||||
|
*/
|
||||||
|
open suspend fun invokeInstanceMethod(
|
||||||
|
scope: Scope,
|
||||||
|
name: String,
|
||||||
|
args: Arguments = Arguments.EMPTY,
|
||||||
|
onNotFoundResult: Obj?=null
|
||||||
|
): Obj =
|
||||||
|
objClass.getInstanceMemberOrNull(name)?.value?.invoke(scope, this, args)
|
||||||
|
?: onNotFoundResult
|
||||||
|
?: scope.raiseSymbolNotFound(name)
|
||||||
|
|
||||||
|
open suspend fun getInstanceMethod(
|
||||||
|
scope: Scope,
|
||||||
|
name: String,
|
||||||
|
args: Arguments = Arguments.EMPTY
|
||||||
|
): Obj =
|
||||||
|
// note that getInstanceMember traverses the hierarchy
|
||||||
|
objClass.getInstanceMember(scope.pos, name).value
|
||||||
|
|
||||||
|
fun getMemberOrNull(name: String): Obj? = objClass.getInstanceMemberOrNull(name)?.value
|
||||||
|
|
||||||
|
// methods that to override
|
||||||
|
|
||||||
|
open suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun contains(scope: Scope, other: Obj): Boolean {
|
||||||
|
return invokeInstanceMethod(scope, "contains", other).toBool()
|
||||||
|
}
|
||||||
|
|
||||||
|
open val asStr: ObjString by lazy {
|
||||||
|
if (this is ObjString) this else ObjString(this.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class of the object: definition of member functions (top-level), etc.
|
||||||
|
* Note that using lazy allows to avoid endless recursion here
|
||||||
|
*/
|
||||||
|
open val objClass: ObjClass = rootObjectType
|
||||||
|
|
||||||
|
open suspend fun plus(scope: Scope, other: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun minus(scope: Scope, other: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun negate(scope: Scope): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun mul(scope: Scope, other: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun div(scope: Scope, other: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun mod(scope: Scope, other: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun logicalNot(scope: Scope): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun logicalAnd(scope: Scope, other: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun logicalOr(scope: Scope, other: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun assign(scope: Scope, other: Obj): Obj? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* a += b
|
||||||
|
* if( the operation is not defined, it returns null and the compiler would try
|
||||||
|
* to generate it as 'this = this + other', reassigning its variable
|
||||||
|
*/
|
||||||
|
open suspend fun plusAssign(scope: Scope, other: Obj): Obj? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `-=` operations, see [plusAssign]
|
||||||
|
*/
|
||||||
|
open suspend fun minusAssign(scope: Scope, other: Obj): Obj? = null
|
||||||
|
open suspend fun mulAssign(scope: Scope, other: Obj): Obj? = null
|
||||||
|
open suspend fun divAssign(scope: Scope, other: Obj): Obj? = null
|
||||||
|
open suspend fun modAssign(scope: Scope, other: Obj): Obj? = null
|
||||||
|
|
||||||
|
open suspend fun getAndIncrement(scope: Scope): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun incrementAndGet(scope: Scope): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun decrementAndGet(scope: Scope): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun getAndDecrement(scope: Scope): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert Lyng object to its Kotlin counterpart
|
||||||
|
*/
|
||||||
|
open suspend fun toKotlin(scope: Scope): Any? {
|
||||||
|
return toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun willMutate(scope: Scope) {
|
||||||
|
if (isFrozen) scope.raiseError("attempt to mutate frozen object")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun <T> sync(block: () -> T): T = monitor.withLock { block() }
|
||||||
|
|
||||||
|
open suspend fun readField(scope: Scope, name: String): ObjRecord {
|
||||||
|
// could be property or class field:
|
||||||
|
val obj = objClass.getInstanceMemberOrNull(name) ?: scope.raiseError("no such field: $name")
|
||||||
|
return when (val value = obj.value) {
|
||||||
|
is Statement -> {
|
||||||
|
ObjRecord(value.execute(scope.copy(scope.pos, newThisObj = this)), obj.isMutable)
|
||||||
|
}
|
||||||
|
// could be writable property naturally
|
||||||
|
// null -> ObjNull.asReadonly
|
||||||
|
else -> obj
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
||||||
|
willMutate(scope)
|
||||||
|
val field = objClass.getInstanceMemberOrNull(name) ?: scope.raiseError("no such field: $name")
|
||||||
|
if (field.isMutable) field.value = newValue else scope.raiseError("can't assign to read-only field: $name")
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun getAt(scope: Scope, index: Obj): Obj {
|
||||||
|
scope.raiseNotImplemented("indexing")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun getAt(scope: Scope, index: Int): Obj = getAt(scope, ObjInt(index.toLong()))
|
||||||
|
|
||||||
|
open suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) {
|
||||||
|
scope.raiseNotImplemented("indexing")
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun callOn(scope: Scope): Obj {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun invoke(scope: Scope, thisObj: Obj, args: Arguments): Obj =
|
||||||
|
callOn(scope.copy(scope.pos, args = args, newThisObj = thisObj))
|
||||||
|
|
||||||
|
suspend fun invoke(scope: Scope, thisObj: Obj, vararg args: Obj): Obj =
|
||||||
|
callOn(
|
||||||
|
scope.copy(
|
||||||
|
scope.pos,
|
||||||
|
args = Arguments(args.toList()),
|
||||||
|
newThisObj = thisObj
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun invoke(scope: Scope, thisObj: Obj): Obj =
|
||||||
|
callOn(
|
||||||
|
scope.copy(
|
||||||
|
scope.pos,
|
||||||
|
args = Arguments.EMPTY,
|
||||||
|
newThisObj = thisObj
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
suspend fun invoke(scope: Scope, atPos: Pos, thisObj: Obj, args: Arguments): Obj =
|
||||||
|
callOn(scope.copy(atPos, args = args, newThisObj = thisObj))
|
||||||
|
|
||||||
|
|
||||||
|
val asReadonly: ObjRecord by lazy { ObjRecord(this, false) }
|
||||||
|
val asMutable: ObjRecord by lazy { ObjRecord(this, true) }
|
||||||
|
|
||||||
|
open suspend fun lynonType(): LynonType = LynonType.Other
|
||||||
|
|
||||||
|
open suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
scope.raiseNotImplemented()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
val rootObjectType = ObjClass("Obj").apply {
|
||||||
|
addFn("toString") {
|
||||||
|
thisObj.asStr
|
||||||
|
}
|
||||||
|
addFn("contains") {
|
||||||
|
ObjBool(thisObj.contains(this, args.firstAndOnly()))
|
||||||
|
}
|
||||||
|
// utilities
|
||||||
|
addFn("let") {
|
||||||
|
args.firstAndOnly().callOn(copy(Arguments(thisObj)))
|
||||||
|
}
|
||||||
|
addFn("apply") {
|
||||||
|
val newContext = (thisObj as? ObjInstance)?.instanceScope ?: this
|
||||||
|
args.firstAndOnly()
|
||||||
|
.callOn(newContext)
|
||||||
|
thisObj
|
||||||
|
}
|
||||||
|
addFn("also") {
|
||||||
|
args.firstAndOnly().callOn(copy(Arguments(thisObj)))
|
||||||
|
thisObj
|
||||||
|
}
|
||||||
|
addFn("getAt") {
|
||||||
|
requireExactCount(1)
|
||||||
|
thisObj.getAt(this, requiredArg<Obj>(0))
|
||||||
|
}
|
||||||
|
addFn("putAt") {
|
||||||
|
requireExactCount(2)
|
||||||
|
val newValue = args[1]
|
||||||
|
thisObj.putAt(this, requiredArg<Obj>(0), newValue)
|
||||||
|
newValue
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
inline fun from(obj: Any?): Obj {
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
return when (obj) {
|
||||||
|
is Obj -> obj
|
||||||
|
is Double -> ObjReal(obj)
|
||||||
|
is Float -> ObjReal(obj.toDouble())
|
||||||
|
is Int -> ObjInt(obj.toLong())
|
||||||
|
is Long -> ObjInt(obj)
|
||||||
|
is String -> ObjString(obj)
|
||||||
|
is CharSequence -> ObjString(obj.toString())
|
||||||
|
is Boolean -> ObjBool(obj)
|
||||||
|
is Set<*> -> ObjSet((obj as Set<Obj>).toMutableSet())
|
||||||
|
Unit -> ObjVoid
|
||||||
|
null -> ObjNull
|
||||||
|
is Iterator<*> -> ObjKotlinIterator(obj)
|
||||||
|
is Map.Entry<*, *> -> {
|
||||||
|
obj as MutableMap.MutableEntry<Obj, Obj>
|
||||||
|
ObjMapEntry(obj.key, obj.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> throw IllegalArgumentException("cannot convert to Obj: $obj")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Double.toObj(): Obj = ObjReal(this)
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
inline fun <reified T> T.toObj(): Obj = Obj.from(this)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
@SerialName("void")
|
||||||
|
object ObjVoid : Obj() {
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
return other is ObjVoid || other is Unit
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
return if (other === this) 0 else -1
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = "void"
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
@SerialName("null")
|
||||||
|
object ObjNull : Obj() {
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
return if (other === this) 0 else -1
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
return other is ObjNull || other == null
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
||||||
|
scope.raiseNPE()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments, onNotFoundResult: Obj?): Obj {
|
||||||
|
scope.raiseNPE()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
||||||
|
scope.raiseNPE()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) {
|
||||||
|
scope.raiseNPE()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
scope.raiseNPE()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = "null"
|
||||||
|
|
||||||
|
override suspend fun toKotlin(scope: Scope): Any? {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType {
|
||||||
|
return LynonType.Null
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
if (lynonType == null) {
|
||||||
|
encoder.putBit(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override val objClass: ObjClass by lazy {
|
||||||
|
object : ObjClass("Null") {
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||||
|
if (lynonType == LynonType.Null)
|
||||||
|
return this@ObjNull
|
||||||
|
else
|
||||||
|
scope.raiseIllegalState("can't deserialize null directly or with wrong type: ${lynonType}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Numeric {
|
||||||
|
val longValue: Long
|
||||||
|
val doubleValue: Double
|
||||||
|
val toObjInt: ObjInt
|
||||||
|
val toObjReal: ObjReal
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Obj.toDouble(): Double =
|
||||||
|
(this as? Numeric)?.doubleValue
|
||||||
|
?: (this as? ObjString)?.value?.toDouble()
|
||||||
|
?: throw IllegalArgumentException("cannot convert to double $this")
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun Obj.toLong(): Long =
|
||||||
|
when (this) {
|
||||||
|
is Numeric -> longValue
|
||||||
|
is ObjString -> value.toLong()
|
||||||
|
is ObjChar -> value.code.toLong()
|
||||||
|
else -> throw IllegalArgumentException("cannot convert to double $this")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Obj.toInt(): Int = toLong().toInt()
|
||||||
|
|
||||||
|
fun Obj.toBool(): Boolean =
|
||||||
|
(this as? ObjBool)?.value ?: throw IllegalArgumentException("cannot convert to boolean $this")
|
||||||
|
|
||||||
|
|
||||||
|
data class ObjNamespace(val name: String) : Obj() {
|
||||||
|
override val objClass by lazy { ObjClass(name) }
|
||||||
|
|
||||||
|
override fun inspect(): String = "Ns[$name]"
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return "package $name"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
open class ObjException(exceptionClass: ExceptionClass, val scope: Scope, val message: String) : Obj() {
|
||||||
|
constructor(name: String, scope: Scope, message: String) : this(
|
||||||
|
getOrCreateExceptionClass(name),
|
||||||
|
scope,
|
||||||
|
message
|
||||||
|
)
|
||||||
|
|
||||||
|
constructor(scope: Scope, message: String) : this(Root, scope, message)
|
||||||
|
|
||||||
|
fun raise(): Nothing {
|
||||||
|
throw ExecutionError(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
override val objClass: ObjClass = exceptionClass
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return "ObjException:${objClass.className}:${scope.pos}@${hashCode().encodeToHex()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
class ExceptionClass(val name: String, vararg parents: ObjClass) : ObjClass(name, *parents) {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
val message = scope.args.getOrNull(0)?.toString() ?: name
|
||||||
|
return ObjException(this, scope, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = "ExceptionClass[$name]@${hashCode().encodeToHex()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
val Root = ExceptionClass("Throwable").apply {
|
||||||
|
addConst("message", statement {
|
||||||
|
(thisObj as ObjException).message.toObj()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private val op = ProtectedOp()
|
||||||
|
private val existingErrorClasses = mutableMapOf<String, ExceptionClass>()
|
||||||
|
|
||||||
|
|
||||||
|
@OptIn(ExperimentalContracts::class)
|
||||||
|
protected fun getOrCreateExceptionClass(name: String): ExceptionClass {
|
||||||
|
return op.withLock {
|
||||||
|
existingErrorClasses.getOrPut(name) {
|
||||||
|
ExceptionClass(name, Root)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get [ObjClass] for error class by name if exists.
|
||||||
|
*/
|
||||||
|
@OptIn(ExperimentalContracts::class)
|
||||||
|
fun getErrorClass(name: String): ObjClass? = op.withLock {
|
||||||
|
existingErrorClasses[name]
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addExceptionsToContext(scope: Scope) {
|
||||||
|
scope.addConst("Exception", Root)
|
||||||
|
existingErrorClasses["Exception"] = Root
|
||||||
|
for (name in listOf(
|
||||||
|
"NullReferenceException",
|
||||||
|
"AssertionFailedException",
|
||||||
|
"ClassCastException",
|
||||||
|
"IndexOutOfBoundsException",
|
||||||
|
"IllegalArgumentException",
|
||||||
|
"NoSuchElementException",
|
||||||
|
"IllegalAssignmentException",
|
||||||
|
"SymbolNotDefinedException",
|
||||||
|
"IterationEndException",
|
||||||
|
"AccessException",
|
||||||
|
"UnknownException",
|
||||||
|
)) {
|
||||||
|
scope.addConst(name, getOrCreateExceptionClass(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ObjNullReferenceException(scope: Scope) : ObjException("NullReferenceException", scope, "object is null")
|
||||||
|
|
||||||
|
class ObjAssertionFailedException(scope: Scope, message: String) :
|
||||||
|
ObjException("AssertionFailedException", scope, message)
|
||||||
|
|
||||||
|
class ObjClassCastException(scope: Scope, message: String) : ObjException("ClassCastException", scope, message)
|
||||||
|
class ObjIndexOutOfBoundsException(scope: Scope, message: String = "index out of bounds") :
|
||||||
|
ObjException("IndexOutOfBoundsException", scope, message)
|
||||||
|
|
||||||
|
class ObjIllegalArgumentException(scope: Scope, message: String = "illegal argument") :
|
||||||
|
ObjException("IllegalArgumentException", scope, message)
|
||||||
|
|
||||||
|
class ObjIllegalStateException(scope: Scope, message: String = "illegal state") :
|
||||||
|
ObjException("IllegalStateException", scope, message)
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
class ObjNoSuchElementException(scope: Scope, message: String = "no such element") :
|
||||||
|
ObjException("IllegalArgumentException", scope, message)
|
||||||
|
|
||||||
|
class ObjIllegalAssignmentException(scope: Scope, message: String = "illegal assignment") :
|
||||||
|
ObjException("NoSuchElementException", scope, message)
|
||||||
|
|
||||||
|
class ObjSymbolNotDefinedException(scope: Scope, message: String = "symbol is not defined") :
|
||||||
|
ObjException("SymbolNotDefinedException", scope, message)
|
||||||
|
|
||||||
|
class ObjIterationFinishedException(scope: Scope) :
|
||||||
|
ObjException("IterationEndException", scope, "iteration finished")
|
||||||
|
|
||||||
|
class ObjAccessException(scope: Scope, message: String = "access not allowed error") :
|
||||||
|
ObjException("AccessException", scope, message)
|
||||||
|
|
||||||
|
class ObjUnknownException(scope: Scope, message: String = "access not allowed error") :
|
||||||
|
ObjException("UnknownException", scope, message)
|
||||||
|
|
||||||
|
class ObjIllegalOperationException(scope: Scope, message: String = "Operation is illegal") :
|
||||||
|
ObjException("IllegalOperationException", scope, message)
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
val ObjArray by lazy {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Array abstract class is a [ObjCollection] with `getAt` method.
|
||||||
|
*/
|
||||||
|
ObjClass("Array", ObjCollection).apply {
|
||||||
|
// we can create iterators using size/getat:
|
||||||
|
|
||||||
|
addFn("iterator") {
|
||||||
|
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, ObjInt(i.toLong())).compareTo(this, obj) == 0) return@addFn ObjTrue
|
||||||
|
}
|
||||||
|
ObjFalse
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("last") {
|
||||||
|
thisObj.invokeInstanceMethod(
|
||||||
|
this,
|
||||||
|
"getAt",
|
||||||
|
(thisObj.invokeInstanceMethod(this, "size").toInt() - 1).toObj()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("lastIndex") { (thisObj.invokeInstanceMethod(this, "size").toInt() - 1).toObj() }
|
||||||
|
|
||||||
|
addFn("indices") {
|
||||||
|
ObjRange(0.toObj(), thisObj.invokeInstanceMethod(this, "size"), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
class ObjArrayIterator(val array: Obj) : Obj() {
|
||||||
|
|
||||||
|
override val objClass: ObjClass by lazy { type }
|
||||||
|
|
||||||
|
private var nextIndex = 0
|
||||||
|
private var lastIndex = 0
|
||||||
|
|
||||||
|
suspend fun init(scope: Scope) {
|
||||||
|
nextIndex = 0
|
||||||
|
lastIndex = array.invokeInstanceMethod(scope, "size").toInt()
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type by lazy {
|
||||||
|
ObjClass("ArrayIterator", ObjIterator).apply {
|
||||||
|
addFn("next") {
|
||||||
|
val self = thisAs<ObjArrayIterator>()
|
||||||
|
if (self.nextIndex < self.lastIndex) {
|
||||||
|
self.array.invokeInstanceMethod(this, "getAt", (self.nextIndex++).toObj())
|
||||||
|
} else raiseError(ObjIterationFinishedException(this))
|
||||||
|
}
|
||||||
|
addFn("hasNext") {
|
||||||
|
val self = thisAs<ObjArrayIterator>()
|
||||||
|
if (self.nextIndex < self.lastIndex) ObjTrue else ObjFalse
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.bintools.toDump
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lynon.BitArray
|
||||||
|
|
||||||
|
class ObjBitBuffer(val bitArray: BitArray) : Obj() {
|
||||||
|
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
||||||
|
return bitArray[index.toLong()].toObj()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object: ObjClass("BitBuffer", ObjArray) {
|
||||||
|
|
||||||
|
}.apply {
|
||||||
|
addFn("toBuffer") {
|
||||||
|
requireNoArgs()
|
||||||
|
ObjBuffer(thisAs<ObjBitBuffer>().bitArray.asUbyteArray())
|
||||||
|
}
|
||||||
|
addFn("toDump") {
|
||||||
|
requireNoArgs()
|
||||||
|
ObjString(
|
||||||
|
thisAs<ObjBitBuffer>().bitArray.asUbyteArray().toDump()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
addFn("size") {
|
||||||
|
thisAs<ObjBitBuffer>().bitArray.size.toObj()
|
||||||
|
}
|
||||||
|
addFn("sizeInBytes") {
|
||||||
|
ObjInt((thisAs<ObjBitBuffer>().bitArray.size + 7) shr 3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
data class ObjBool(val value: Boolean) : Obj() {
|
||||||
|
override val asStr by lazy { ObjString(value.toString()) }
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other !is ObjBool) return -2
|
||||||
|
return value.compareTo(other.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return value.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = value.toString()
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
override suspend fun logicalNot(scope: Scope): Obj = ObjBool(!value)
|
||||||
|
|
||||||
|
override suspend fun logicalAnd(scope: Scope, other: Obj): Obj = ObjBool(value && other.toBool())
|
||||||
|
|
||||||
|
override suspend fun logicalOr(scope: Scope, other: Obj): Obj = ObjBool(value || other.toBool())
|
||||||
|
|
||||||
|
override suspend fun toKotlin(scope: Scope): Any {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType = LynonType.Bool
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
encoder.encodeBoolean(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjBool
|
||||||
|
|
||||||
|
return value == other.value
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object : ObjClass("Bool") {
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder,lynonType: LynonType?): Obj {
|
||||||
|
return ObjBool(decoder.unpackBoolean())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val ObjTrue = ObjBool(true)
|
||||||
|
val ObjFalse = ObjBool(false)
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.toList
|
||||||
|
import net.sergeych.bintools.encodeToHex
|
||||||
|
import net.sergeych.bintools.toDump
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.statement
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
import kotlin.math.min
|
||||||
|
|
||||||
|
open class ObjBuffer(val byteArray: UByteArray) : Obj() {
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
fun checkIndex(scope: Scope, index: Obj): Int {
|
||||||
|
if (index !is ObjInt)
|
||||||
|
scope.raiseIllegalArgument("index must be Int")
|
||||||
|
val i = index.value.toInt()
|
||||||
|
if (i < 0) scope.raiseIllegalArgument("index must be positive")
|
||||||
|
if (i >= byteArray.size)
|
||||||
|
scope.raiseIndexOutOfBounds("index $i is out of bounds 0..<${byteArray.size}")
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
||||||
|
// notice: we create a copy if content, so we don't want it
|
||||||
|
// to be treated as modifiable, or putAt will not be called:
|
||||||
|
return if (index is ObjRange) {
|
||||||
|
val start: Int = index.startInt(scope)
|
||||||
|
val end: Int = index.exclusiveIntEnd(scope) ?: size
|
||||||
|
ObjBuffer(byteArray.sliceArray(start..<end))
|
||||||
|
} else ObjInt(byteArray[checkIndex(scope, index)].toLong(), true)
|
||||||
|
}
|
||||||
|
|
||||||
|
val size by byteArray::size
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return byteArray.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other !is ObjBuffer) return super.compareTo(scope, other)
|
||||||
|
val limit = min(size, other.size)
|
||||||
|
for (i in 0..<limit) {
|
||||||
|
val own = byteArray[i]
|
||||||
|
val their = other.byteArray[i]
|
||||||
|
if (own < their) return -1
|
||||||
|
else if (own > their) return 1
|
||||||
|
}
|
||||||
|
if (size < other.size) return -1
|
||||||
|
if (size > other.size) return 1
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun plus(scope: Scope, other: Obj): Obj {
|
||||||
|
return if (other is ObjBuffer)
|
||||||
|
ObjBuffer(byteArray + other.byteArray)
|
||||||
|
else if (other.isInstanceOf(ObjIterable)) {
|
||||||
|
ObjBuffer(
|
||||||
|
byteArray + other.toFlow(scope).map { it.toLong().toUByte() }.toList().toTypedArray()
|
||||||
|
.toUByteArray()
|
||||||
|
)
|
||||||
|
} else scope.raiseIllegalArgument("can't concatenate buffer with ${other.inspect()}")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return "Buffer(${byteArray.encodeToHex()})"
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjBuffer
|
||||||
|
|
||||||
|
return byteArray contentEquals other.byteArray
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType = LynonType.Buffer
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
encoder.encodeCachedBytes(byteArray.asByteArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private suspend fun createBufferFrom(scope: Scope, obj: Obj): ObjBuffer =
|
||||||
|
when (obj) {
|
||||||
|
is ObjBuffer -> ObjBuffer(obj.byteArray.copyOf())
|
||||||
|
is ObjInt -> {
|
||||||
|
if (obj.value < 0)
|
||||||
|
scope.raiseIllegalArgument("buffer size must be positive")
|
||||||
|
val data = UByteArray(obj.value.toInt())
|
||||||
|
ObjBuffer(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
is ObjString -> ObjBuffer(obj.value.encodeToByteArray().asUByteArray())
|
||||||
|
else -> {
|
||||||
|
if (obj.isInstanceOf(ObjIterable)) {
|
||||||
|
ObjBuffer(
|
||||||
|
obj.toFlow(scope).map { it.toLong().toUByte() }.toList().toTypedArray()
|
||||||
|
.toUByteArray()
|
||||||
|
)
|
||||||
|
} else
|
||||||
|
scope.raiseIllegalArgument(
|
||||||
|
"can't construct buffer from ${obj.inspect()}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val type = object : ObjClass("Buffer", ObjArray) {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
val args = scope.args.list
|
||||||
|
return when (args.size) {
|
||||||
|
// empty buffer
|
||||||
|
0 -> ObjBuffer(ubyteArrayOf())
|
||||||
|
1 -> createBufferFrom(scope, args[0])
|
||||||
|
else -> {
|
||||||
|
// create buffer from array, each argument should be a byte then:
|
||||||
|
val data = UByteArray(args.size)
|
||||||
|
for ((i, b) in args.withIndex()) {
|
||||||
|
val code = when (b) {
|
||||||
|
is ObjChar -> b.value.code.toUByte()
|
||||||
|
is ObjInt -> b.value.toUByte()
|
||||||
|
else -> scope.raiseIllegalArgument(
|
||||||
|
"invalid byte value for buffer constructor at index $i: ${b.inspect()}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
data[i] = code
|
||||||
|
}
|
||||||
|
ObjBuffer(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
|
||||||
|
ObjBuffer( decoder.decodeCached {
|
||||||
|
decoder.decompress().asUByteArray()
|
||||||
|
})
|
||||||
|
|
||||||
|
}.apply {
|
||||||
|
createField("size",
|
||||||
|
statement {
|
||||||
|
(thisObj as ObjBuffer).byteArray.size.toObj()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
addFn("decodeUtf8") {
|
||||||
|
ObjString(
|
||||||
|
thisAs<ObjBuffer>().byteArray.toByteArray().decodeToString()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
addFn("toMutable") {
|
||||||
|
requireNoArgs()
|
||||||
|
ObjMutableBuffer(thisAs<ObjBuffer>().byteArray.copyOf())
|
||||||
|
}
|
||||||
|
addFn("toDump") {
|
||||||
|
requireNoArgs()
|
||||||
|
ObjString(
|
||||||
|
thisAs<ObjBuffer>().byteArray.toByteArray().toDump()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
class ObjChar(val value: Char): Obj() {
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int =
|
||||||
|
(other as? ObjChar)?.let { value.compareTo(it.value) } ?: -1
|
||||||
|
|
||||||
|
override fun toString(): String = value.toString()
|
||||||
|
|
||||||
|
override fun inspect(): String = "'$value'"
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return value.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjChar
|
||||||
|
|
||||||
|
return value == other.value
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = ObjClass("Char").apply {
|
||||||
|
addFn("code") { ObjInt(thisAs<ObjChar>().value.code.toLong()) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.*
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
val ObjClassType by lazy { ObjClass("Class") }
|
||||||
|
|
||||||
|
open class ObjClass(
|
||||||
|
val className: String,
|
||||||
|
vararg parents: ObjClass,
|
||||||
|
) : Obj() {
|
||||||
|
|
||||||
|
val classNameObj by lazy { ObjString(className) }
|
||||||
|
|
||||||
|
var constructorMeta: ArgsDeclaration? = null
|
||||||
|
var instanceConstructor: Statement? = null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* the scope for class methods, initialize class vars, etc.
|
||||||
|
*
|
||||||
|
* Important notice. When create a user class, e.g. from Lyng source, it should
|
||||||
|
* be set to a scope by compiler, so it could access local closure, etc. Otherwise,
|
||||||
|
* it will be initialized to default scope on first necessity, e.g. when used in
|
||||||
|
* external, kotlin classes with [addClassConst] and [addClassFn], etc.
|
||||||
|
*/
|
||||||
|
var classScope: Scope? = null
|
||||||
|
|
||||||
|
val allParentsSet: Set<ObjClass> =
|
||||||
|
parents.flatMap {
|
||||||
|
listOf(it) + it.allParentsSet
|
||||||
|
}.toMutableSet()
|
||||||
|
|
||||||
|
override val objClass: ObjClass by lazy { ObjClassType }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* members: fields most often. These are called with [ObjInstance] withs ths [ObjInstance.objClass]
|
||||||
|
*/
|
||||||
|
private val members = mutableMapOf<String, ObjRecord>()
|
||||||
|
|
||||||
|
override fun toString(): String = className
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int = if (other === this) 0 else -1
|
||||||
|
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
val instance = ObjInstance(this)
|
||||||
|
instance.instanceScope = scope.copy(newThisObj = instance,args = scope.args)
|
||||||
|
if (instanceConstructor != null) {
|
||||||
|
instanceConstructor!!.execute(instance.instanceScope)
|
||||||
|
}
|
||||||
|
return instance
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
fun createField(
|
||||||
|
name: String,
|
||||||
|
initialValue: Obj,
|
||||||
|
isMutable: Boolean = false,
|
||||||
|
visibility: Visibility = Visibility.Public,
|
||||||
|
pos: Pos = Pos.builtIn
|
||||||
|
) {
|
||||||
|
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")
|
||||||
|
members[name] = ObjRecord(initialValue, isMutable, visibility)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initClassScope(): Scope {
|
||||||
|
if( classScope == null ) classScope = Scope()
|
||||||
|
return classScope!!
|
||||||
|
}
|
||||||
|
|
||||||
|
fun createClassField(
|
||||||
|
name: String,
|
||||||
|
initialValue: Obj,
|
||||||
|
isMutable: Boolean = false,
|
||||||
|
visibility: Visibility = Visibility.Public,
|
||||||
|
pos: Pos = Pos.builtIn
|
||||||
|
) {
|
||||||
|
initClassScope()
|
||||||
|
val existing = classScope!!.objects[name]
|
||||||
|
if( existing != null)
|
||||||
|
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
|
||||||
|
classScope!!.addItem(name, isMutable, initialValue, visibility)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addFn(name: String, isOpen: Boolean = false, code: suspend Scope.() -> Obj) {
|
||||||
|
createField(name, statement { code() }, isOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addConst(name: String, value: Obj) = createField(name, value, isMutable = false)
|
||||||
|
fun addClassConst(name: String, value: Obj) = createClassField(name, value)
|
||||||
|
fun addClassFn(name: String, isOpen: Boolean = false, code: suspend Scope.() -> Obj) {
|
||||||
|
createClassField(name, statement { code() }, isOpen)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get instance member traversing the hierarchy if needed. Its meaning is different for different objects.
|
||||||
|
*/
|
||||||
|
fun getInstanceMemberOrNull(name: String): ObjRecord? {
|
||||||
|
members[name]?.let { return it }
|
||||||
|
allParentsSet.forEach { parent -> parent.getInstanceMemberOrNull(name)?.let { return it } }
|
||||||
|
return rootObjectType.members[name]
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getInstanceMember(atPos: Pos, name: String): ObjRecord =
|
||||||
|
getInstanceMemberOrNull(name)
|
||||||
|
?: throw ScriptError(atPos, "symbol doesn't exist: $name")
|
||||||
|
|
||||||
|
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
||||||
|
classScope?.objects?.get(name)?.let {
|
||||||
|
if( it.visibility.isPublic ) return it
|
||||||
|
}
|
||||||
|
return super.readField(scope, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
||||||
|
initClassScope().objects[name]?.let {
|
||||||
|
if( it.isMutable) it.value = newValue
|
||||||
|
else scope.raiseIllegalAssignment("can't assign $name is not mutable")
|
||||||
|
}
|
||||||
|
?: super.writeField(scope, name, newValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments,
|
||||||
|
onNotFoundResult: Obj?): Obj {
|
||||||
|
return classScope?.objects?.get(name)?.value?.invoke(scope, this, args)
|
||||||
|
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
||||||
|
}
|
||||||
|
|
||||||
|
open suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj = scope.raiseNotImplemented()
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Collection is an iterator with `size`]
|
||||||
|
*/
|
||||||
|
val ObjCollection = ObjClass("Collection", ObjIterable).apply {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
class ObjCompletableDeferred(val completableDeferred: CompletableDeferred<Obj>): ObjDeferred(completableDeferred) {
|
||||||
|
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object: ObjClass("CompletableDeferred", ObjDeferred.type){
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
return ObjCompletableDeferred(CompletableDeferred())
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
addFn("complete") {
|
||||||
|
thisAs<ObjCompletableDeferred>().completableDeferred.complete(args.firstAndOnly())
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Deferred
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
open class ObjDeferred(val deferred: Deferred<Obj>): Obj() {
|
||||||
|
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object: ObjClass("Deferred"){
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
scope.raiseError("Deferred constructor is not directly callable")
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
addFn("await") {
|
||||||
|
thisAs<ObjDeferred>().deferred.await()
|
||||||
|
}
|
||||||
|
addFn("isCompleted") {
|
||||||
|
thisAs<ObjDeferred>().deferred.isCompleted.toObj()
|
||||||
|
}
|
||||||
|
addFn("isActive") {
|
||||||
|
thisAs<ObjDeferred>().deferred.isActive.toObj()
|
||||||
|
}
|
||||||
|
addFn("isCancelled") {
|
||||||
|
thisAs<ObjDeferred>().deferred.isCancelled.toObj()
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import kotlin.time.Duration
|
||||||
|
import kotlin.time.Duration.Companion.days
|
||||||
|
import kotlin.time.Duration.Companion.hours
|
||||||
|
import kotlin.time.Duration.Companion.milliseconds
|
||||||
|
import kotlin.time.Duration.Companion.minutes
|
||||||
|
import kotlin.time.Duration.Companion.seconds
|
||||||
|
import kotlin.time.DurationUnit
|
||||||
|
|
||||||
|
class ObjDuration(val duration: Duration) : Obj() {
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return duration.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
return if( other is ObjDuration)
|
||||||
|
duration.compareTo(other.duration)
|
||||||
|
else -1
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return duration.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjDuration
|
||||||
|
|
||||||
|
return duration == other.duration
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object : ObjClass("Duration") {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
val args = scope.args
|
||||||
|
if( args.list.size > 1 )
|
||||||
|
scope.raiseIllegalArgument("can't construct Duration(${args.inspect()})")
|
||||||
|
val a0 = args.list.getOrNull(0)
|
||||||
|
|
||||||
|
return ObjDuration(
|
||||||
|
when (a0) {
|
||||||
|
null -> Duration.ZERO
|
||||||
|
is ObjInt -> a0.value.seconds
|
||||||
|
is ObjReal -> a0.value.seconds
|
||||||
|
else -> {
|
||||||
|
scope.raiseIllegalArgument("can't construct Instant(${args.inspect()})")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
addFn("days") {
|
||||||
|
thisAs<ObjDuration>().duration.toDouble(DurationUnit.DAYS).toObj()
|
||||||
|
}
|
||||||
|
addFn("hours") {
|
||||||
|
thisAs<ObjDuration>().duration.toDouble(DurationUnit.HOURS).toObj()
|
||||||
|
}
|
||||||
|
addFn("minutes") {
|
||||||
|
thisAs<ObjDuration>().duration.toDouble(DurationUnit.MINUTES).toObj()
|
||||||
|
}
|
||||||
|
addFn("seconds") {
|
||||||
|
thisAs<ObjDuration>().duration.toDouble(DurationUnit.SECONDS).toObj()
|
||||||
|
}
|
||||||
|
addFn("milliseconds") {
|
||||||
|
thisAs<ObjDuration>().duration.toDouble(DurationUnit.MILLISECONDS).toObj()
|
||||||
|
}
|
||||||
|
addFn("microseconds") {
|
||||||
|
thisAs<ObjDuration>().duration.toDouble(DurationUnit.MICROSECONDS).toObj()
|
||||||
|
}
|
||||||
|
// extensions
|
||||||
|
|
||||||
|
ObjInt.type.addFn("seconds") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.seconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjInt.type.addFn("second") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.seconds)
|
||||||
|
}
|
||||||
|
ObjInt.type.addFn("milliseconds") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.milliseconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjInt.type.addFn("millisecond") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.milliseconds)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("seconds") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.seconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjReal.type.addFn("second") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.seconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjReal.type.addFn("milliseconds") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.milliseconds)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("millisecond") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.milliseconds)
|
||||||
|
}
|
||||||
|
|
||||||
|
ObjInt.type.addFn("minutes") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.minutes)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("minutes") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.minutes)
|
||||||
|
}
|
||||||
|
ObjInt.type.addFn("minute") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.minutes)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("minute") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.minutes)
|
||||||
|
}
|
||||||
|
ObjInt.type.addFn("hours") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.hours)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("hours") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.hours)
|
||||||
|
}
|
||||||
|
ObjInt.type.addFn("hour") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.hours)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("hour") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.hours)
|
||||||
|
}
|
||||||
|
ObjInt.type.addFn("days") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.days)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("days") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.days)
|
||||||
|
}
|
||||||
|
ObjInt.type.addFn("day") {
|
||||||
|
ObjDuration(thisAs<ObjInt>().value.days)
|
||||||
|
}
|
||||||
|
ObjReal.type.addFn("day") {
|
||||||
|
ObjDuration(thisAs<ObjReal>().value.days)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// addFn("epochSeconds") {
|
||||||
|
// val instant = thisAs<ObjInstant>().instant
|
||||||
|
// ObjReal(instant.epochSeconds + instant.nanosecondsOfSecond * 1e-9)
|
||||||
|
// }
|
||||||
|
// addFn("epochMilliseconds") {
|
||||||
|
// ObjInt(instant.toEpochMilliseconds())
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Arguments
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
class ObjInstance(override val objClass: ObjClass) : Obj() {
|
||||||
|
|
||||||
|
internal lateinit var instanceScope: Scope
|
||||||
|
|
||||||
|
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
||||||
|
return instanceScope[name]?.let {
|
||||||
|
if (it.visibility.isPublic)
|
||||||
|
it
|
||||||
|
else
|
||||||
|
scope.raiseError(ObjAccessException(scope, "can't access non-public field $name"))
|
||||||
|
}
|
||||||
|
?: super.readField(scope, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
||||||
|
instanceScope[name]?.let { f ->
|
||||||
|
if (!f.visibility.isPublic)
|
||||||
|
ObjIllegalAssignmentException(scope, "can't assign to non-public field $name")
|
||||||
|
if (!f.isMutable) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
||||||
|
if (f.value.assign(scope, newValue) == null)
|
||||||
|
f.value = newValue
|
||||||
|
} ?: super.writeField(scope, name, newValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun invokeInstanceMethod(scope: Scope, name: String, args: Arguments,
|
||||||
|
onNotFoundResult: Obj?): Obj =
|
||||||
|
instanceScope[name]?.let {
|
||||||
|
if (it.visibility.isPublic)
|
||||||
|
it.value.invoke(scope, this, args)
|
||||||
|
else
|
||||||
|
scope.raiseError(ObjAccessException(scope, "can't invoke non-public method $name"))
|
||||||
|
}
|
||||||
|
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
||||||
|
|
||||||
|
private val publicFields: Map<String, ObjRecord>
|
||||||
|
get() = instanceScope.objects.filter { it.value.visibility.isPublic }
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
val fields = publicFields.map { "${it.key}=${it.value.value}" }.joinToString(",")
|
||||||
|
return "${objClass.className}($fields)"
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
val meta = objClass.constructorMeta
|
||||||
|
?: scope.raiseError("can't serialize non-serializable object (no constructor meta)")
|
||||||
|
// actual constructor can vary, for example, adding new fields with default
|
||||||
|
// values, so we save size of the construction:
|
||||||
|
|
||||||
|
// using objlist allow for some optimizations:
|
||||||
|
val params = meta.params.map { readField(scope, it.name).value }
|
||||||
|
encoder.encodeAnyList(scope, params)
|
||||||
|
serializeStateVars(scope, encoder)
|
||||||
|
}
|
||||||
|
|
||||||
|
protected val instanceVars: Map<String, ObjRecord> by lazy {
|
||||||
|
instanceScope.objects.filter { it.value.type.serializable }
|
||||||
|
}
|
||||||
|
|
||||||
|
protected suspend fun serializeStateVars(scope: Scope,encoder: LynonEncoder) {
|
||||||
|
val vars = instanceVars.values.map { it.value }
|
||||||
|
if( vars.isNotEmpty()) {
|
||||||
|
encoder.encodeAnyList(scope, vars)
|
||||||
|
println("serialized state vars $vars")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal suspend fun deserializeStateVars(scope: Scope, decoder: LynonDecoder) {
|
||||||
|
val localVars = instanceVars.values.toList()
|
||||||
|
if( localVars.isNotEmpty() ) {
|
||||||
|
println("gonna read vars")
|
||||||
|
val vars = decoder.decodeAnyList(scope)
|
||||||
|
if (vars.size > instanceVars.size)
|
||||||
|
scope.raiseIllegalArgument("serialized vars has bigger size than instance vars")
|
||||||
|
println("deser state vars $vars")
|
||||||
|
for ((i, v) in vars.withIndex()) {
|
||||||
|
localVars[i].value = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
protected val comparableVars: Map<String, ObjRecord> by lazy {
|
||||||
|
instanceScope.objects.filter {
|
||||||
|
it.value.type.comparable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other !is ObjInstance) return -1
|
||||||
|
if (other.objClass != objClass) return -1
|
||||||
|
for (f in comparableVars) {
|
||||||
|
val a = f.value.value
|
||||||
|
val b = other.instanceScope[f.key]!!.value
|
||||||
|
val d = a.compareTo(scope, b)
|
||||||
|
if (d != 0) return d
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Arguments
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Special variant of [ObjClass] to be used in [ObjInstance], e.g. for Lyng compiled classes
|
||||||
|
*/
|
||||||
|
class ObjInstanceClass(val name: String) : ObjClass(name) {
|
||||||
|
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||||
|
val args = decoder.decodeAnyList(scope)
|
||||||
|
println("deserializing constructor $name, $args params")
|
||||||
|
val actualSize = constructorMeta?.params?.size ?: 0
|
||||||
|
if( args.size > actualSize )
|
||||||
|
scope.raiseIllegalArgument("constructor $name has only $actualSize but serialized version has ${args.size}")
|
||||||
|
val newScope = scope.copy(args = Arguments(args))
|
||||||
|
return (callOn(newScope) as ObjInstance).apply {
|
||||||
|
deserializeStateVars(scope,decoder)
|
||||||
|
invokeInstanceMethod(scope, "onDeserialized", onNotFoundResult = ObjVoid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.datetime.isDistantFuture
|
||||||
|
import kotlinx.datetime.isDistantPast
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonSettings
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
class ObjInstant(val instant: Instant,val truncateMode: LynonSettings.InstantTruncateMode=LynonSettings.InstantTruncateMode.Microsecond) : Obj() {
|
||||||
|
override val objClass: ObjClass get() = type
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return instant.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun plus(scope: Scope, other: Obj): Obj {
|
||||||
|
return when (other) {
|
||||||
|
is ObjDuration -> ObjInstant(instant + other.duration)
|
||||||
|
else -> super.plus(scope, other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun minus(scope: Scope, other: Obj): Obj {
|
||||||
|
return when (other) {
|
||||||
|
is ObjDuration -> ObjInstant(instant - other.duration)
|
||||||
|
is ObjInstant -> ObjDuration(instant - other.instant)
|
||||||
|
else -> super.plus(scope, other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if( other is ObjInstant) {
|
||||||
|
return instant.compareTo(other.instant)
|
||||||
|
}
|
||||||
|
return super.compareTo(scope, other)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun toKotlin(scope: Scope): Any {
|
||||||
|
return instant
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return instant.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjInstant
|
||||||
|
|
||||||
|
return instant == other.instant
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType = LynonType.Instant
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
encoder.putBits(truncateMode.ordinal, 2)
|
||||||
|
when(truncateMode) {
|
||||||
|
LynonSettings.InstantTruncateMode.Millisecond ->
|
||||||
|
encoder.encodeSigned(instant.toEpochMilliseconds())
|
||||||
|
LynonSettings.InstantTruncateMode.Second ->
|
||||||
|
encoder.encodeSigned(instant.epochSeconds)
|
||||||
|
LynonSettings.InstantTruncateMode.Microsecond -> {
|
||||||
|
encoder.encodeSigned(instant.epochSeconds)
|
||||||
|
encoder.encodeUnsigned(instant.nanosecondsOfSecond.toULong() / 1000UL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val distantFuture by lazy {
|
||||||
|
ObjInstant(Instant.DISTANT_FUTURE)
|
||||||
|
}
|
||||||
|
|
||||||
|
val distantPast by lazy {
|
||||||
|
ObjInstant(Instant.DISTANT_PAST)
|
||||||
|
}
|
||||||
|
|
||||||
|
val type = object : ObjClass("Instant") {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
val args = scope.args
|
||||||
|
val a0 = args.list.getOrNull(0)
|
||||||
|
return ObjInstant(
|
||||||
|
when (a0) {
|
||||||
|
null -> {
|
||||||
|
val t = Clock.System.now()
|
||||||
|
Instant.fromEpochSeconds(t.epochSeconds, t.nanosecondsOfSecond)
|
||||||
|
}
|
||||||
|
is ObjInt -> Instant.fromEpochSeconds(a0.value)
|
||||||
|
is ObjReal -> {
|
||||||
|
val seconds = a0.value.toLong()
|
||||||
|
val nanos = (a0.value - seconds) * 1e9
|
||||||
|
Instant.fromEpochSeconds(seconds, nanos.toLong())
|
||||||
|
}
|
||||||
|
is ObjInstant -> a0.instant
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
scope.raiseIllegalArgument("can't construct Instant(${args.inspect()})")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||||
|
val mode = LynonSettings.InstantTruncateMode.entries[decoder.getBitsAsInt(2)]
|
||||||
|
return when (mode) {
|
||||||
|
LynonSettings.InstantTruncateMode.Microsecond -> ObjInstant(
|
||||||
|
Instant.fromEpochSeconds(
|
||||||
|
decoder.unpackSigned(), decoder.unpackUnsignedInt() * 1000
|
||||||
|
)
|
||||||
|
)
|
||||||
|
LynonSettings.InstantTruncateMode.Millisecond -> ObjInstant(
|
||||||
|
Instant.fromEpochMilliseconds(
|
||||||
|
decoder.unpackSigned()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
LynonSettings.InstantTruncateMode.Second -> ObjInstant(
|
||||||
|
Instant.fromEpochSeconds(decoder.unpackSigned())
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}.apply {
|
||||||
|
addFn("epochSeconds") {
|
||||||
|
val instant = thisAs<ObjInstant>().instant
|
||||||
|
ObjReal(instant.epochSeconds + instant.nanosecondsOfSecond * 1e-9)
|
||||||
|
}
|
||||||
|
addFn("isDistantFuture") {
|
||||||
|
thisAs<ObjInstant>().instant.isDistantFuture.toObj()
|
||||||
|
}
|
||||||
|
addFn("isDistantPast") {
|
||||||
|
thisAs<ObjInstant>().instant.isDistantPast.toObj()
|
||||||
|
}
|
||||||
|
addFn("epochWholeSeconds") {
|
||||||
|
ObjInt(thisAs<ObjInstant>().instant.epochSeconds)
|
||||||
|
}
|
||||||
|
addFn("nanosecondsOfSecond") {
|
||||||
|
ObjInt(thisAs<ObjInstant>().instant.nanosecondsOfSecond.toLong())
|
||||||
|
}
|
||||||
|
addFn("truncateToSecond") {
|
||||||
|
val t = thisAs<ObjInstant>().instant
|
||||||
|
ObjInstant(Instant.fromEpochSeconds(t.epochSeconds), LynonSettings.InstantTruncateMode.Second)
|
||||||
|
}
|
||||||
|
addFn("truncateToMillisecond") {
|
||||||
|
val t = thisAs<ObjInstant>().instant
|
||||||
|
ObjInstant(
|
||||||
|
Instant.fromEpochSeconds(t.epochSeconds, t.nanosecondsOfSecond / 1_000_000 * 1_000_000),
|
||||||
|
LynonSettings.InstantTruncateMode.Millisecond
|
||||||
|
)
|
||||||
|
}
|
||||||
|
addFn("truncateToMicrosecond") {
|
||||||
|
val t = thisAs<ObjInstant>().instant
|
||||||
|
ObjInstant(
|
||||||
|
Instant.fromEpochSeconds(t.epochSeconds, t.nanosecondsOfSecond / 1_000 * 1_000),
|
||||||
|
LynonSettings.InstantTruncateMode.Microsecond
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// class members
|
||||||
|
|
||||||
|
addClassConst("distantFuture", distantFuture)
|
||||||
|
addClassConst("distantPast", distantPast)
|
||||||
|
addClassFn("now") {
|
||||||
|
ObjInstant(Clock.System.now())
|
||||||
|
}
|
||||||
|
// addFn("epochMilliseconds") {
|
||||||
|
// ObjInt(instant.toEpochMilliseconds())
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
class ObjInt(var value: Long, override val isConst: Boolean = false) : Obj(), Numeric {
|
||||||
|
override val asStr get() = ObjString(value.toString())
|
||||||
|
override val longValue get() = value
|
||||||
|
override val doubleValue get() = value.toDouble()
|
||||||
|
override val toObjInt get() = this
|
||||||
|
override val toObjReal = ObjReal(doubleValue)
|
||||||
|
|
||||||
|
override fun byValueCopy(): Obj = ObjInt(value)
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return value.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getAndIncrement(scope: Scope): Obj {
|
||||||
|
ensureNotConst(scope)
|
||||||
|
return ObjInt(value).also { value++ }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getAndDecrement(scope: Scope): Obj {
|
||||||
|
ensureNotConst(scope)
|
||||||
|
return ObjInt(value).also { value-- }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun incrementAndGet(scope: Scope): Obj {
|
||||||
|
ensureNotConst(scope)
|
||||||
|
return ObjInt(++value)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun decrementAndGet(scope: Scope): Obj {
|
||||||
|
ensureNotConst(scope)
|
||||||
|
return ObjInt(--value)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other !is Numeric) return -2
|
||||||
|
return value.compareTo(other.doubleValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = value.toString()
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
override suspend fun plus(scope: Scope, other: Obj): Obj =
|
||||||
|
if (other is ObjInt)
|
||||||
|
ObjInt(this.value + other.value)
|
||||||
|
else
|
||||||
|
ObjReal(this.doubleValue + other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun minus(scope: Scope, other: Obj): Obj =
|
||||||
|
if (other is ObjInt)
|
||||||
|
ObjInt(this.value - other.value)
|
||||||
|
else
|
||||||
|
ObjReal(this.doubleValue - other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun mul(scope: Scope, other: Obj): Obj =
|
||||||
|
if (other is ObjInt) {
|
||||||
|
ObjInt(this.value * other.value)
|
||||||
|
} else ObjReal(this.value * other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun div(scope: Scope, other: Obj): Obj =
|
||||||
|
if (other is ObjInt)
|
||||||
|
ObjInt(this.value / other.value)
|
||||||
|
else ObjReal(this.value / other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun mod(scope: Scope, other: Obj): Obj =
|
||||||
|
if (other is ObjInt)
|
||||||
|
ObjInt(this.value % other.value)
|
||||||
|
else ObjReal(this.value.toDouble() % other.toDouble())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* We are by-value type ([byValueCopy] is implemented) so we can do in-place
|
||||||
|
* assignment
|
||||||
|
*/
|
||||||
|
override suspend fun assign(scope: Scope, other: Obj): Obj? {
|
||||||
|
return if (!isConst && other is ObjInt) {
|
||||||
|
value = other.value
|
||||||
|
this
|
||||||
|
} else null
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun toKotlin(scope: Scope): Any {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjInt
|
||||||
|
|
||||||
|
return value == other.value
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun negate(scope: Scope): Obj {
|
||||||
|
return ObjInt(-value)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType = when (value) {
|
||||||
|
0L -> LynonType.Int0
|
||||||
|
else -> {
|
||||||
|
if (value > 0) LynonType.IntPositive
|
||||||
|
else LynonType.IntNegative
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
when (lynonType) {
|
||||||
|
null -> encoder.encodeSigned(value)
|
||||||
|
LynonType.Int0 -> {}
|
||||||
|
LynonType.IntPositive -> encoder.encodeUnsigned(value.toULong())
|
||||||
|
LynonType.IntNegative -> encoder.encodeUnsigned((-value).toULong())
|
||||||
|
LynonType.IntSigned -> encoder.encodeSigned(value)
|
||||||
|
else -> scope.raiseIllegalArgument("Unsupported lynon type code for Int: $lynonType")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val Zero = ObjInt(0, true)
|
||||||
|
val One = ObjInt(1, true)
|
||||||
|
val type = object : ObjClass("Int") {
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
|
||||||
|
when (lynonType) {
|
||||||
|
null -> ObjInt(decoder.unpackSigned())
|
||||||
|
LynonType.Int0 -> Zero
|
||||||
|
LynonType.IntPositive -> ObjInt(decoder.unpackUnsigned().toLong())
|
||||||
|
LynonType.IntNegative -> ObjInt(-decoder.unpackUnsigned().toLong())
|
||||||
|
LynonType.IntSigned -> ObjInt(decoder.unpackSigned())
|
||||||
|
else -> scope.raiseIllegalState("illegal type code for Int: $lynonType")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun Int.toObj() = ObjInt(this.toLong())
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Arguments
|
||||||
|
import net.sergeych.lyng.Statement
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abstract class that must provide `iterator` method that returns [ObjIterator] instance.
|
||||||
|
*/
|
||||||
|
val ObjIterable by lazy {
|
||||||
|
ObjClass("Iterable").apply {
|
||||||
|
|
||||||
|
addFn("toList") {
|
||||||
|
val result = mutableListOf<Obj>()
|
||||||
|
val iterator = thisObj.invokeInstanceMethod(this, "iterator")
|
||||||
|
|
||||||
|
while (iterator.invokeInstanceMethod(this, "hasNext").toBool())
|
||||||
|
result += iterator.invokeInstanceMethod(this, "next")
|
||||||
|
ObjList(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("indexOf", isOpen = true) {
|
||||||
|
val obj = args.firstAndOnly()
|
||||||
|
var index = 0
|
||||||
|
val it = thisObj.invokeInstanceMethod(this, "iterator")
|
||||||
|
while (it.invokeInstanceMethod(this, "hasNext").toBool()) {
|
||||||
|
if (obj.compareTo(this, it.invokeInstanceMethod(this, "next")) == 0)
|
||||||
|
return@addFn ObjInt(index.toLong())
|
||||||
|
index++
|
||||||
|
}
|
||||||
|
ObjInt(-1L)
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("toSet") {
|
||||||
|
val result = mutableSetOf<Obj>()
|
||||||
|
val it = thisObj.invokeInstanceMethod(this, "iterator")
|
||||||
|
while (it.invokeInstanceMethod(this, "hasNext").toBool()) {
|
||||||
|
result += it.invokeInstanceMethod(this, "next")
|
||||||
|
}
|
||||||
|
ObjSet(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("toMap") {
|
||||||
|
val result = ObjMap()
|
||||||
|
thisObj.toFlow(this).collect { pair ->
|
||||||
|
result.map[pair.getAt(this,0)] = pair.getAt(this, 1)
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("associateBy") {
|
||||||
|
val association = requireOnlyArg<Statement>()
|
||||||
|
val result = ObjMap()
|
||||||
|
thisObj.toFlow(this).collect {
|
||||||
|
result.map[association.call(this, it)] = it
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("forEach", isOpen = true) {
|
||||||
|
val it = thisObj.invokeInstanceMethod(this, "iterator")
|
||||||
|
val fn = requiredArg<Statement>(0)
|
||||||
|
while (it.invokeInstanceMethod(this, "hasNext").toBool()) {
|
||||||
|
val x = it.invokeInstanceMethod(this, "next")
|
||||||
|
fn.execute(this.copy(Arguments(listOf(x))))
|
||||||
|
}
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("map", isOpen = true) {
|
||||||
|
val fn = requiredArg<Statement>(0)
|
||||||
|
val result = mutableListOf<Obj>()
|
||||||
|
thisObj.toFlow(this).collect {
|
||||||
|
result += fn.call(this, it)
|
||||||
|
}
|
||||||
|
ObjList(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("isEmpty") {
|
||||||
|
ObjBool(
|
||||||
|
thisObj.invokeInstanceMethod(this, "iterator")
|
||||||
|
.invokeInstanceMethod(this, "hasNext").toBool()
|
||||||
|
.not()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
val ObjIterator by lazy { ObjClass("Iterator") }
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
@file:Suppress("unused")
|
||||||
|
|
||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Iterator wrapper to allow Kotlin collections to be returned from Lyng objects;
|
||||||
|
* each object is converted to a Lyng object.
|
||||||
|
*/
|
||||||
|
class ObjKotlinIterator(val iterator: Iterator<Any?>) : Obj() {
|
||||||
|
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = ObjClass("KotlinIterator", ObjIterator).apply {
|
||||||
|
addFn("next") { thisAs<ObjKotlinIterator>().iterator.next().toObj() }
|
||||||
|
addFn("hasNext") { thisAs<ObjKotlinIterator>().iterator.hasNext().toObj() }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Propagate kotlin iterator that already produces Lyng objects, no conversion
|
||||||
|
* is applied
|
||||||
|
*/
|
||||||
|
class ObjKotlinObjIterator(val iterator: Iterator<Obj>) : Obj() {
|
||||||
|
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = ObjClass("KotlinIterator", ObjIterator).apply {
|
||||||
|
addFn("next") {
|
||||||
|
thisAs<ObjKotlinObjIterator>().iterator.next()
|
||||||
|
}
|
||||||
|
addFn("hasNext") { thisAs<ObjKotlinIterator>().iterator.hasNext().toObj() }
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert Lyng's Iterable to Kotlin's Flow.
|
||||||
|
*
|
||||||
|
* As Lyng is totally asynchronous, its iterator can't be trivially converted to Kotlin's synchronous iterator.
|
||||||
|
* It is, though, trivially convertible to Kotlin's Flow.
|
||||||
|
*/
|
||||||
|
fun Obj.toFlow(scope: Scope): Flow<Obj> = flow {
|
||||||
|
val iterator = invokeInstanceMethod(scope, "iterator")
|
||||||
|
val hasNext = iterator.getInstanceMethod(scope, "hasNext")
|
||||||
|
val next = iterator.getInstanceMethod(scope, "next")
|
||||||
|
while (hasNext.invoke(scope, iterator).toBool()) {
|
||||||
|
emit(next.invoke(scope, iterator))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.statement
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
|
||||||
|
|
||||||
|
override fun toString(): String = "[${
|
||||||
|
list.joinToString(separator = ", ") { it.inspect() }
|
||||||
|
}]"
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
||||||
|
return when (index) {
|
||||||
|
is ObjInt -> {
|
||||||
|
list[index.toInt()]
|
||||||
|
}
|
||||||
|
|
||||||
|
is ObjRange -> {
|
||||||
|
when {
|
||||||
|
index.start is ObjInt && index.end is ObjInt -> {
|
||||||
|
if (index.isEndInclusive)
|
||||||
|
ObjList(list.subList(index.start.toInt(), index.end.toInt() + 1).toMutableList())
|
||||||
|
else
|
||||||
|
ObjList(list.subList(index.start.toInt(), index.end.toInt()).toMutableList())
|
||||||
|
}
|
||||||
|
|
||||||
|
index.isOpenStart && !index.isOpenEnd -> {
|
||||||
|
if (index.isEndInclusive)
|
||||||
|
ObjList(list.subList(0, index.end!!.toInt() + 1).toMutableList())
|
||||||
|
else
|
||||||
|
ObjList(list.subList(0, index.end!!.toInt()).toMutableList())
|
||||||
|
}
|
||||||
|
|
||||||
|
index.isOpenEnd && !index.isOpenStart -> {
|
||||||
|
ObjList(list.subList(index.start!!.toInt(), list.size).toMutableList())
|
||||||
|
}
|
||||||
|
|
||||||
|
index.isOpenStart && index.isOpenEnd -> {
|
||||||
|
ObjList(list.toMutableList())
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
throw RuntimeException("Can't apply range for index: $index")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> scope.raiseIllegalArgument("Illegal index object for a list: ${index.inspect()}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) {
|
||||||
|
list[index.toInt()] = newValue
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other !is ObjList) return -2
|
||||||
|
val mySize = list.size
|
||||||
|
val otherSize = other.list.size
|
||||||
|
val commonSize = minOf(mySize, otherSize)
|
||||||
|
for (i in 0..<commonSize) {
|
||||||
|
if (list[i].compareTo(scope, other.list[i]) != 0) {
|
||||||
|
return list[i].compareTo(scope, other.list[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// equal so far, longer is greater:
|
||||||
|
return when {
|
||||||
|
mySize < otherSize -> -1
|
||||||
|
mySize > otherSize -> 1
|
||||||
|
else -> 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun plus(scope: Scope, other: Obj): Obj =
|
||||||
|
when {
|
||||||
|
other is ObjList ->
|
||||||
|
ObjList((list + other.list).toMutableList())
|
||||||
|
|
||||||
|
other.isInstanceOf(ObjIterable) -> {
|
||||||
|
val l = other.callMethod<ObjList>(scope, "toList")
|
||||||
|
ObjList((list + l.list).toMutableList())
|
||||||
|
}
|
||||||
|
|
||||||
|
else ->
|
||||||
|
scope.raiseError("'+': can't concatenate $this with $other")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
override suspend fun plusAssign(scope: Scope, other: Obj): Obj {
|
||||||
|
// optimization
|
||||||
|
if (other is ObjList) {
|
||||||
|
list += other.list
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
if (other.isInstanceOf(ObjIterable)) {
|
||||||
|
val otherList = other.invokeInstanceMethod(scope, "toList") as ObjList
|
||||||
|
list += otherList.list
|
||||||
|
} else
|
||||||
|
list += other
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun contains(scope: Scope, other: Obj): Boolean {
|
||||||
|
return list.contains(other)
|
||||||
|
}
|
||||||
|
|
||||||
|
override val objClass: ObjClass
|
||||||
|
get() = type
|
||||||
|
|
||||||
|
override suspend fun toKotlin(scope: Scope): Any {
|
||||||
|
return list.map { it.toKotlin(scope) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
// check?
|
||||||
|
return list.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjList
|
||||||
|
|
||||||
|
return list == other.list
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
encoder.encodeAnyList(scope,list)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType = LynonType.List
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object : ObjClass("List", ObjArray) {
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||||
|
return ObjList(decoder.decodeAnyList(scope))
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
createField("size",
|
||||||
|
statement {
|
||||||
|
(thisObj as ObjList).list.size.toObj()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
createField("add",
|
||||||
|
statement {
|
||||||
|
val l = thisAs<ObjList>().list
|
||||||
|
for (a in args) l.add(a)
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
)
|
||||||
|
addFn("insertAt") {
|
||||||
|
if (args.size < 2) raiseError("addAt takes 2+ arguments")
|
||||||
|
val l = thisAs<ObjList>()
|
||||||
|
var index = requiredArg<ObjInt>(0).value.toInt()
|
||||||
|
for (i in 1..<args.size) l.list.add(index++, args[i])
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("removeAt") {
|
||||||
|
val self = thisAs<ObjList>()
|
||||||
|
val start = requiredArg<ObjInt>(0).value.toInt()
|
||||||
|
if (args.size == 2) {
|
||||||
|
val end = requireOnlyArg<ObjInt>().value.toInt()
|
||||||
|
self.list.subList(start, end).clear()
|
||||||
|
} else
|
||||||
|
self.list.removeAt(start)
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("removeLast") {
|
||||||
|
val self = thisAs<ObjList>()
|
||||||
|
if (args.isNotEmpty()) {
|
||||||
|
val count = requireOnlyArg<ObjInt>().value.toInt()
|
||||||
|
val size = self.list.size
|
||||||
|
if (count >= size) self.list.clear()
|
||||||
|
else self.list.subList(size - count, size).clear()
|
||||||
|
} else self.list.removeLast()
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
addFn("removeRange") {
|
||||||
|
val self = thisAs<ObjList>()
|
||||||
|
val list = self.list
|
||||||
|
val range = requiredArg<Obj>(0)
|
||||||
|
if (range is ObjRange) {
|
||||||
|
val index = range
|
||||||
|
when {
|
||||||
|
index.start is ObjInt && index.end is ObjInt -> {
|
||||||
|
if (index.isEndInclusive)
|
||||||
|
list.subList(index.start.toInt(), index.end.toInt() + 1)
|
||||||
|
else
|
||||||
|
list.subList(index.start.toInt(), index.end.toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
index.isOpenStart && !index.isOpenEnd -> {
|
||||||
|
if (index.isEndInclusive)
|
||||||
|
list.subList(0, index.end!!.toInt() + 1)
|
||||||
|
else
|
||||||
|
list.subList(0, index.end!!.toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
index.isOpenEnd && !index.isOpenStart -> {
|
||||||
|
list.subList(index.start!!.toInt(), list.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
index.isOpenStart && index.isOpenEnd -> {
|
||||||
|
list
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
throw RuntimeException("Can't apply range for index: $index")
|
||||||
|
}
|
||||||
|
}.clear()
|
||||||
|
} else {
|
||||||
|
val start = range.toInt()
|
||||||
|
val end = requiredArg<ObjInt>(1).value.toInt() + 1
|
||||||
|
self.list.subList(start, end).clear()
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.Statement
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
|
class ObjMapEntry(val key: Obj, val value: Obj) : Obj() {
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other !is ObjMapEntry) return -1
|
||||||
|
val c = key.compareTo(scope, other.key)
|
||||||
|
if (c != 0) return c
|
||||||
|
return value.compareTo(scope, other.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return key.hashCode() + value.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
return other is ObjMapEntry && key == other.key && value == other.value
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj = when (index.toInt()) {
|
||||||
|
0 -> key
|
||||||
|
1 -> value
|
||||||
|
else -> scope.raiseIndexOutOfBounds()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return "$key=>$value"
|
||||||
|
}
|
||||||
|
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
encoder.encodeAny(scope,key)
|
||||||
|
encoder.encodeAny(scope,value)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object : ObjClass("MapEntry", ObjArray) {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
return ObjMapEntry(scope.requiredArg<Obj>(0), scope.requiredArg<Obj>(1))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||||
|
return ObjMapEntry(
|
||||||
|
decoder.decodeAny(scope),
|
||||||
|
decoder.decodeAny(scope)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
addFn("key") { thisAs<ObjMapEntry>().key }
|
||||||
|
addFn("value") { thisAs<ObjMapEntry>().value }
|
||||||
|
addFn("size") { 2.toObj() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class ObjMap(val map: MutableMap<Obj, Obj> = mutableMapOf()) : Obj() {
|
||||||
|
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj =
|
||||||
|
map.get(index) ?: ObjNull
|
||||||
|
|
||||||
|
override suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) {
|
||||||
|
map[index] = newValue
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun contains(scope: Scope, other: Obj): Boolean {
|
||||||
|
return other in map
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if( other is ObjMap && other.map == map) return 0
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
override fun toString(): String = map.toString()
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return map.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjMap
|
||||||
|
|
||||||
|
return map == other.map
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType = LynonType.Map
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
val keys = map.keys.map { it.toObj() }
|
||||||
|
val values = map.values.map { it.toObj() }
|
||||||
|
encoder.encodeAnyList(scope, keys)
|
||||||
|
encoder.encodeAnyList(scope, values, fixedSize = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
suspend fun listToMap(scope: Scope, list: List<Obj>): MutableMap<Obj, Obj> {
|
||||||
|
val map = mutableMapOf<Obj, Obj>()
|
||||||
|
if (list.isEmpty()) return map
|
||||||
|
|
||||||
|
val first = list.first()
|
||||||
|
if (first.isInstanceOf(ObjArray)) {
|
||||||
|
if (first.invokeInstanceMethod(scope, "size").toInt() != 2)
|
||||||
|
scope.raiseIllegalArgument(
|
||||||
|
"list to construct map entry should exactly be 2 element Array like [key,value], got $list"
|
||||||
|
)
|
||||||
|
} else scope.raiseIllegalArgument("first element of map list be a Collection of 2 elements; got $first")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
list.forEach {
|
||||||
|
map[it.getAt(scope, ObjInt.Zero)] = it.getAt(scope, ObjInt.One)
|
||||||
|
}
|
||||||
|
return map
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
val type = object : ObjClass("Map", ObjCollection) {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
return ObjMap(listToMap(scope, scope.args.list))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||||
|
val keys = decoder.decodeAnyList(scope)
|
||||||
|
val values = decoder.decodeAnyList(scope,fixedSize = keys.size)
|
||||||
|
if( keys.size != values.size) scope.raiseIllegalArgument("map keys and values should be same size")
|
||||||
|
return ObjMap(keys.zip(values).toMap().toMutableMap())
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
addFn("getOrNull") {
|
||||||
|
val key = args.firstAndOnly(pos)
|
||||||
|
thisAs<ObjMap>().map.getOrElse(key) { ObjNull }
|
||||||
|
}
|
||||||
|
addFn("getOrPut") {
|
||||||
|
val key = requiredArg<Obj>(0)
|
||||||
|
thisAs<ObjMap>().map.getOrPut(key) {
|
||||||
|
val lambda = requiredArg<Statement>(1)
|
||||||
|
lambda.execute(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addFn("size") {
|
||||||
|
thisAs<ObjMap>().map.size.toObj()
|
||||||
|
}
|
||||||
|
addFn("remove") {
|
||||||
|
thisAs<ObjMap>().map.remove(requiredArg<Obj>(0))?.toObj() ?: ObjNull
|
||||||
|
}
|
||||||
|
addFn("clear") {
|
||||||
|
thisAs<ObjMap>().map.clear()
|
||||||
|
thisObj
|
||||||
|
}
|
||||||
|
addFn("keys") {
|
||||||
|
thisAs<ObjMap>().map.keys.toObj()
|
||||||
|
}
|
||||||
|
addFn("values") {
|
||||||
|
ObjList(thisAs<ObjMap>().map.values.toMutableList())
|
||||||
|
}
|
||||||
|
addFn("iterator") {
|
||||||
|
ObjKotlinIterator(thisAs<ObjMap>().map.entries.iterator())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.toList
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
class ObjMutableBuffer(byteArray: UByteArray) : ObjBuffer(byteArray) {
|
||||||
|
|
||||||
|
override suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) {
|
||||||
|
byteArray[checkIndex(scope, index.toObj())] = when (newValue) {
|
||||||
|
is ObjInt -> newValue.value.toUByte()
|
||||||
|
is ObjChar -> newValue.value.code.toUByte()
|
||||||
|
else -> scope.raiseIllegalArgument(
|
||||||
|
"invalid byte value for buffer at index ${index.inspect()}: ${newValue.inspect()}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
private suspend fun createBufferFrom(scope: Scope, obj: Obj): ObjBuffer =
|
||||||
|
when (obj) {
|
||||||
|
is ObjBuffer -> ObjMutableBuffer(obj.byteArray.copyOf())
|
||||||
|
is ObjInt -> {
|
||||||
|
if (obj.value < 0)
|
||||||
|
scope.raiseIllegalArgument("buffer size must be positive")
|
||||||
|
val data = UByteArray(obj.value.toInt())
|
||||||
|
ObjMutableBuffer(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
is ObjString -> ObjMutableBuffer(obj.value.encodeToByteArray().asUByteArray())
|
||||||
|
else -> {
|
||||||
|
if (obj.isInstanceOf(ObjIterable)) {
|
||||||
|
ObjMutableBuffer(
|
||||||
|
obj.toFlow(scope).map { it.toLong().toUByte() }.toList().toTypedArray()
|
||||||
|
.toUByteArray()
|
||||||
|
)
|
||||||
|
} else
|
||||||
|
scope.raiseIllegalArgument(
|
||||||
|
"can't construct buffer from ${obj.inspect()}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val type = object : ObjClass("MutableBuffer", ObjBuffer.type) {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
val args = scope.args.list
|
||||||
|
return when (args.size) {
|
||||||
|
// empty buffer
|
||||||
|
0 -> ObjMutableBuffer(ubyteArrayOf())
|
||||||
|
1 -> createBufferFrom(scope, args[0])
|
||||||
|
else -> {
|
||||||
|
// create buffer from array, each argument should be a byte then:
|
||||||
|
val data = UByteArray(args.size)
|
||||||
|
for ((i, b) in args.withIndex()) {
|
||||||
|
val code = when (b) {
|
||||||
|
is ObjChar -> b.value.code.toUByte()
|
||||||
|
is ObjInt -> b.value.toUByte()
|
||||||
|
else -> scope.raiseIllegalArgument(
|
||||||
|
"invalid byte value for buffer constructor at index $i: ${b.inspect()}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
data[i] = code
|
||||||
|
}
|
||||||
|
ObjMutableBuffer(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.Statement
|
||||||
|
|
||||||
|
class ObjMutex(val mutex: Mutex): Obj() {
|
||||||
|
override val objClass = type
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object: ObjClass("Mutex") {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
return ObjMutex(Mutex())
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
addFn("withLock") {
|
||||||
|
val f = requiredArg<Statement>(0)
|
||||||
|
thisAs<ObjMutex>().mutex.withLock { f.execute(this) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
class ObjRange(val start: Obj?, val end: Obj?, val isEndInclusive: Boolean) : Obj() {
|
||||||
|
|
||||||
|
val isOpenStart by lazy { start == null || start.isNull }
|
||||||
|
val isOpenEnd by lazy { end == null || end.isNull }
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
val result = StringBuilder()
|
||||||
|
result.append("${start?.inspect() ?: '∞'} ..")
|
||||||
|
if (!isEndInclusive) result.append('<')
|
||||||
|
result.append(" ${end?.inspect() ?: '∞'}")
|
||||||
|
return result.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* IF end is open (null/ObjNull), returns null
|
||||||
|
* Otherwise, return correct value for the exclusive end
|
||||||
|
* raises [ObjIllegalArgumentException] if end is not ObjInt
|
||||||
|
*/
|
||||||
|
fun exclusiveIntEnd(scope: Scope): Int? =
|
||||||
|
if (end == null || end is ObjNull) null
|
||||||
|
else {
|
||||||
|
if (end !is ObjInt) scope.raiseIllegalArgument("end is not int")
|
||||||
|
if (isEndInclusive) end.value.toInt() + 1 else end.value.toInt()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If start is null/ObjNull, returns 0
|
||||||
|
* if start is not ObjInt, raises [ObjIllegalArgumentException]
|
||||||
|
* otherwise returns start.value.toInt()
|
||||||
|
*/
|
||||||
|
fun startInt(scope: Scope): Int =
|
||||||
|
if( start == null || start is ObjNull) 0
|
||||||
|
else {
|
||||||
|
if( start is ObjInt) start.value.toInt()
|
||||||
|
else scope.raiseIllegalArgument("start is not Int: ${start.inspect()}")
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun containsRange(scope: Scope, other: ObjRange): Boolean {
|
||||||
|
if (start != null) {
|
||||||
|
// our start is not -∞ so other start should be GTE or is not contained:
|
||||||
|
if (other.start != null && start.compareTo(scope, other.start) > 0) return false
|
||||||
|
}
|
||||||
|
if (end != null) {
|
||||||
|
// same with the end: if it is open, it can't be contained in ours:
|
||||||
|
if (other.end == null) return false
|
||||||
|
// both exists, now there could be 4 cases:
|
||||||
|
return when {
|
||||||
|
other.isEndInclusive && isEndInclusive ->
|
||||||
|
end.compareTo(scope, other.end) >= 0
|
||||||
|
|
||||||
|
!other.isEndInclusive && !isEndInclusive ->
|
||||||
|
end.compareTo(scope, other.end) >= 0
|
||||||
|
|
||||||
|
other.isEndInclusive && !isEndInclusive ->
|
||||||
|
end.compareTo(scope, other.end) > 0
|
||||||
|
|
||||||
|
!other.isEndInclusive && isEndInclusive ->
|
||||||
|
end.compareTo(scope, other.end) >= 0
|
||||||
|
|
||||||
|
else -> throw IllegalStateException("unknown comparison")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun contains(scope: Scope, other: Obj): Boolean {
|
||||||
|
|
||||||
|
if (other is ObjRange)
|
||||||
|
return containsRange(scope, other)
|
||||||
|
|
||||||
|
if (start == null && end == null) return true
|
||||||
|
if (start != null) {
|
||||||
|
if (start.compareTo(scope, other) > 0) return false
|
||||||
|
}
|
||||||
|
if (end != null) {
|
||||||
|
val cmp = end.compareTo(scope, other)
|
||||||
|
if (isEndInclusive && cmp < 0 || !isEndInclusive && cmp <= 0) return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
val isIntRange: Boolean by lazy {
|
||||||
|
start is ObjInt && end is ObjInt
|
||||||
|
}
|
||||||
|
|
||||||
|
val isCharRange: Boolean by lazy {
|
||||||
|
start is ObjChar && end is ObjChar
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
return (other as? ObjRange)?.let {
|
||||||
|
if( start == other.start && end == other.end ) 0 else -1
|
||||||
|
}
|
||||||
|
?: -1
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
var result = start?.hashCode() ?: 0
|
||||||
|
result = 31 * result + (end?.hashCode() ?: 0)
|
||||||
|
result = 31 * result + isEndInclusive.hashCode()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjRange
|
||||||
|
|
||||||
|
if (start != other.start) return false
|
||||||
|
if (end != other.end) return false
|
||||||
|
if (isEndInclusive != other.isEndInclusive) return false
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = ObjClass("Range", ObjIterable).apply {
|
||||||
|
addFn("start") {
|
||||||
|
thisAs<ObjRange>().start ?: ObjNull
|
||||||
|
}
|
||||||
|
addFn("end") {
|
||||||
|
thisAs<ObjRange>().end ?: ObjNull
|
||||||
|
}
|
||||||
|
addFn("isOpen") {
|
||||||
|
thisAs<ObjRange>().let { it.start == null || it.end == null }.toObj()
|
||||||
|
}
|
||||||
|
addFn("isIntRange") {
|
||||||
|
thisAs<ObjRange>().isIntRange.toObj()
|
||||||
|
}
|
||||||
|
addFn("isCharRange") {
|
||||||
|
thisAs<ObjRange>().isCharRange.toObj()
|
||||||
|
}
|
||||||
|
addFn("isEndInclusive") {
|
||||||
|
thisAs<ObjRange>().isEndInclusive.toObj()
|
||||||
|
}
|
||||||
|
addFn("iterator") {
|
||||||
|
val self = thisAs<ObjRange>()
|
||||||
|
ObjRangeIterator(self).apply { init() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
|
||||||
|
class ObjRangeIterator(val self: ObjRange) : Obj() {
|
||||||
|
|
||||||
|
private var nextIndex = 0
|
||||||
|
private var lastIndex = 0
|
||||||
|
private var isCharRange: Boolean = false
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
fun Scope.init() {
|
||||||
|
if (self.start == null || self.end == null)
|
||||||
|
raiseError("next is only available for finite ranges")
|
||||||
|
isCharRange = self.isCharRange
|
||||||
|
lastIndex = if (self.isIntRange || self.isCharRange) {
|
||||||
|
if (self.isEndInclusive)
|
||||||
|
self.end.toInt() - self.start.toInt() + 1
|
||||||
|
else
|
||||||
|
self.end.toInt() - self.start.toInt()
|
||||||
|
} else {
|
||||||
|
raiseError("not implemented iterator for range of $this")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hasNext(): Boolean = nextIndex < lastIndex
|
||||||
|
|
||||||
|
fun next(scope: Scope): Obj =
|
||||||
|
if (nextIndex < lastIndex) {
|
||||||
|
val x = if (self.isEndInclusive)
|
||||||
|
self.start!!.toLong() + nextIndex++
|
||||||
|
else
|
||||||
|
self.start!!.toLong() + nextIndex++
|
||||||
|
if( isCharRange ) ObjChar(x.toInt().toChar()) else ObjInt(x)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
scope.raiseError(ObjIterationFinishedException(scope))
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = ObjClass("RangeIterator", ObjIterable).apply {
|
||||||
|
addFn("hasNext") {
|
||||||
|
thisAs<ObjRangeIterator>().hasNext().toObj()
|
||||||
|
}
|
||||||
|
addFn("next") {
|
||||||
|
thisAs<ObjRangeIterator>().next(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Pos
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.statement
|
||||||
|
import net.sergeych.lynon.LynonDecoder
|
||||||
|
import net.sergeych.lynon.LynonEncoder
|
||||||
|
import net.sergeych.lynon.LynonType
|
||||||
|
import kotlin.math.floor
|
||||||
|
import kotlin.math.roundToLong
|
||||||
|
|
||||||
|
data class ObjReal(val value: Double) : Obj(), Numeric {
|
||||||
|
override val asStr by lazy { ObjString(value.toString()) }
|
||||||
|
override val longValue: Long by lazy { floor(value).toLong() }
|
||||||
|
override val doubleValue: Double by lazy { value }
|
||||||
|
override val toObjInt: ObjInt by lazy { ObjInt(longValue) }
|
||||||
|
override val toObjReal: ObjReal by lazy { ObjReal(value) }
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
|
override fun byValueCopy(): Obj = ObjReal(value)
|
||||||
|
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other !is Numeric) return -2
|
||||||
|
return value.compareTo(other.doubleValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = value.toString()
|
||||||
|
|
||||||
|
override fun hashCode(): Int {
|
||||||
|
return value.hashCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun plus(scope: Scope, other: Obj): Obj =
|
||||||
|
ObjReal(this.value + other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun minus(scope: Scope, other: Obj): Obj =
|
||||||
|
ObjReal(this.value - other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun mul(scope: Scope, other: Obj): Obj =
|
||||||
|
ObjReal(this.value * other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun div(scope: Scope, other: Obj): Obj =
|
||||||
|
ObjReal(this.value / other.toDouble())
|
||||||
|
|
||||||
|
override suspend fun mod(scope: Scope, other: Obj): Obj =
|
||||||
|
ObjReal(this.value % other.toDouble())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns unboxed Double value
|
||||||
|
*/
|
||||||
|
override suspend fun toKotlin(scope: Scope): Any {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun equals(other: Any?): Boolean {
|
||||||
|
if (this === other) return true
|
||||||
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
|
other as ObjReal
|
||||||
|
|
||||||
|
return value == other.value
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun negate(scope: Scope): Obj {
|
||||||
|
return ObjReal(-value)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun lynonType(): LynonType = LynonType.Real
|
||||||
|
|
||||||
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
|
encoder.encodeReal(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type: ObjClass = object : ObjClass("Real") {
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
|
||||||
|
ObjReal(decoder.unpackDouble())
|
||||||
|
}.apply {
|
||||||
|
createField(
|
||||||
|
"roundToInt",
|
||||||
|
statement(Pos.builtIn) {
|
||||||
|
(it.thisObj as ObjReal).value.roundToLong().toObj()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
addFn("toInt") {
|
||||||
|
ObjInt(thisAs<ObjReal>().value.toLong())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Loaded 100 of 132 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user