Compare commits
60
Commits
e13dde68b5
...
0.5.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -13,3 +13,4 @@ xcuserdata
|
|||||||
*.gpg
|
*.gpg
|
||||||
.gigaide
|
.gigaide
|
||||||
/kotlin-js-store/yarn.lock
|
/kotlin-js-store/yarn.lock
|
||||||
|
/test.lyng
|
||||||
@@ -1,11 +1,33 @@
|
|||||||
# Lying: scripting lang for kotlin multiplatform
|
# Lyng: modern scripting for kotlin multiplatform
|
||||||
|
|
||||||
in the form of multiplatform library.
|
A KMP library and a standalone interpreter
|
||||||
|
|
||||||
__current state of implementation and docs__:
|
- simple, compact, intuitive and elegant modern code style:
|
||||||
|
|
||||||
- [introduction and tutorial](docs/tutorial.md)
|
```
|
||||||
- [math and operators](docs/math.md).
|
class Point(x,y) {
|
||||||
|
fun dist() { sqrt(x*x + y*y) }
|
||||||
|
}
|
||||||
|
Point(3,4).dist() //< 5
|
||||||
|
```
|
||||||
|
|
||||||
|
- extremely simple Kotlin integration on any platform
|
||||||
|
- 100% secure: no access to any API you didn't explicitly provide
|
||||||
|
- 100% coroutines! Every function/script is a coroutine, it does not block the thread, no async/await/suspend keyword garbage:
|
||||||
|
|
||||||
|
```
|
||||||
|
delay(1.5) // coroutine is delayed for 1.5s, thread is not blocked!
|
||||||
|
```
|
||||||
|
and it is multithreaded on platforms supporting it (automatically, no code changes required, just
|
||||||
|
`launch` more coroutines and they will be executed concurrently if possible)/
|
||||||
|
|
||||||
|
- functional style and OOP together, multiple inheritance, implementing interfaces for existing classes, writing extensions.
|
||||||
|
- Any unicode letters can be used as identifiers: `assert( sin(π/2) == 1 )`.
|
||||||
|
|
||||||
|
## Resources:
|
||||||
|
|
||||||
|
- [introduction and tutorial](docs/tutorial.md) - start here please
|
||||||
|
- [Samples directory](docs/samples)
|
||||||
|
|
||||||
## Integration in Kotlin multiplatform
|
## Integration in Kotlin multiplatform
|
||||||
|
|
||||||
@@ -27,6 +49,7 @@ Script is executed over some `Context`. Create instance of the context,
|
|||||||
add your specific vars and functions to it, an call over it:
|
add your specific vars and functions to it, an call over it:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
|
// simple function
|
||||||
val context = Context().apply {
|
val context = Context().apply {
|
||||||
addFn("addArgs") {
|
addFn("addArgs") {
|
||||||
var sum = 0.0
|
var sum = 0.0
|
||||||
@@ -34,8 +57,16 @@ val context = Context().apply {
|
|||||||
ObjReal(sum)
|
ObjReal(sum)
|
||||||
}
|
}
|
||||||
addConst("LIGHT_SPEED", ObjReal(299_792_458.0))
|
addConst("LIGHT_SPEED", ObjReal(299_792_458.0))
|
||||||
}
|
|
||||||
|
|
||||||
|
// callback back to kotlin to some suspend fn, for example::
|
||||||
|
// suspend fun doSomeWork(text: String): Int
|
||||||
|
addFn("doSomeWork") {
|
||||||
|
// this _is_ a suspend lambda, we can call suspend function,
|
||||||
|
// and it won't consume the thread:
|
||||||
|
doSomeWork(args[0].toString()).toObj()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// adding constant:
|
||||||
context.eval("addArgs(1,2,3)") // <- 6
|
context.eval("addArgs(1,2,3)") // <- 6
|
||||||
```
|
```
|
||||||
Note that the context stores all changes in it so you can make calls on a single context to preserve state between calls.
|
Note that the context stores all changes in it so you can make calls on a single context to preserve state between calls.
|
||||||
|
|||||||
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
|
||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Mutable list of any objects.
|
Mutable list of any objects.
|
||||||
|
|
||||||
It's class in Lying is `List`:
|
It's class in Lyng is `List`:
|
||||||
|
|
||||||
[1,2,3]::class
|
[1,2,3]::class
|
||||||
>>> List
|
>>> List
|
||||||
|
|||||||
+169
-3
@@ -1,6 +1,168 @@
|
|||||||
# OO implementation in Lying
|
# OO implementation in Lyng
|
||||||
|
|
||||||
Basic principles:
|
## 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 compares all public 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)
|
||||||
|
|
||||||
|
# Theory
|
||||||
|
|
||||||
|
## Basic principles:
|
||||||
|
|
||||||
- Everything is an instance of some class
|
- Everything is an instance of some class
|
||||||
- Every class except Obj has at least one parent
|
- Every class except Obj has at least one parent
|
||||||
@@ -15,7 +177,7 @@ Basic principles:
|
|||||||
|
|
||||||
## Instances
|
## Instances
|
||||||
|
|
||||||
Result of executing of any expression or statement in the Lying is the object that
|
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.
|
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
|
This means whatever expression returns or the variable holds, is the first-class
|
||||||
@@ -70,3 +232,7 @@ Regular methods are called on instances as usual `instance.method()`. The method
|
|||||||
1. this instance methods;
|
1. this instance methods;
|
||||||
2. parents method: no guarantee but we enumerate parents in order of appearance;
|
2. parents method: no guarantee but we enumerate parents in order of appearance;
|
||||||
3. possible extension methods (scoped)
|
3. possible extension methods (scoped)
|
||||||
|
|
||||||
|
TBD
|
||||||
|
|
||||||
|
[argument list](declaring_arguments.md)
|
||||||
+1
-1
@@ -3,7 +3,7 @@
|
|||||||
Class that supports double-precision math. Woks much like double in other languages. We honor no floats, so it is '
|
Class that supports double-precision math. Woks much like double in other languages. We honor no floats, so it is '
|
||||||
Real'.
|
Real'.
|
||||||
|
|
||||||
It's class in Lying is `Real`:
|
It's class in Lyng is `Real`:
|
||||||
|
|
||||||
(π/2)::class
|
(π/2)::class
|
||||||
>>> Real
|
>>> Real
|
||||||
|
|||||||
+45
-8
@@ -2,24 +2,24 @@
|
|||||||
|
|
||||||
## Closures/scopes isolation
|
## Closures/scopes isolation
|
||||||
|
|
||||||
Each block has own scope, in which it can safely uses closures and override
|
Each block has own scope, in which it can safely use closures and override
|
||||||
outer vars:
|
outer vars. Lets use some lambdas to create isolated scopes:
|
||||||
|
|
||||||
> blocks are no-yet-ready lambda declaration so this sample will soon be altered
|
|
||||||
|
|
||||||
var param = "global"
|
var param = "global"
|
||||||
val prefix = "param in "
|
val prefix = "param in "
|
||||||
|
|
||||||
val scope1 = {
|
val scope1 = {
|
||||||
var param = prefix + "scope1"
|
var param = prefix + "scope1"
|
||||||
param
|
param
|
||||||
}
|
}
|
||||||
|
|
||||||
val scope2 = {
|
val scope2 = {
|
||||||
var param = prefix + "scope2"
|
var param = prefix + "scope2"
|
||||||
param
|
param
|
||||||
}
|
}
|
||||||
// note that block returns its last value
|
|
||||||
println(scope1)
|
println(scope1())
|
||||||
println(scope2)
|
println(scope2())
|
||||||
println(param)
|
println(param)
|
||||||
>>> param in scope1
|
>>> param in scope1
|
||||||
>>> param in scope2
|
>>> param in scope2
|
||||||
@@ -38,7 +38,9 @@ One interesting way of using closure isolation is to keep state of the functions
|
|||||||
counter = counter + 1
|
counter = counter + 1
|
||||||
was
|
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())
|
println(getAndIncrement())
|
||||||
println(getAndIncrement())
|
println(getAndIncrement())
|
||||||
@@ -50,3 +52,38 @@ One interesting way of using closure isolation is to keep state of the functions
|
|||||||
Inner `counter` is not accessible from outside, no way; still it is kept
|
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
|
between calls in the closure, as inner function `doit`, returned from the
|
||||||
block, keeps reference to it and keeps it alive.
|
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
|
||||||
@@ -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,129 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
# 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 |
|
||||||
|
| NullPointerException | |
|
||||||
|
| 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 |
|
||||||
|
| | |
|
||||||
|
|
||||||
+42
-18
@@ -10,7 +10,7 @@ Same as in C++.
|
|||||||
| 1 | `%` `*` `/` |
|
| 1 | `%` `*` `/` |
|
||||||
| 2 | `+` `-` |
|
| 2 | `+` `-` |
|
||||||
| 3 | bit shifts (NI) |
|
| 3 | bit shifts (NI) |
|
||||||
| 4 | `<=>` (NI) |
|
| 4 | `<=>` (1) |
|
||||||
| 5 | `<=` `>=` `<` `>` |
|
| 5 | `<=` `>=` `<` `>` |
|
||||||
| 6 | `==` `!=` |
|
| 6 | `==` `!=` |
|
||||||
| 7 | bitwise and `&` (NI) |
|
| 7 | bitwise and `&` (NI) |
|
||||||
@@ -18,7 +18,12 @@ Same as in C++.
|
|||||||
| 10 | `&&` |
|
| 10 | `&&` |
|
||||||
| 11<br/>lowest | `\|\|` |
|
| 11<br/>lowest | `\|\|` |
|
||||||
|
|
||||||
- (NI) stands for not yet implemented.
|
(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
|
## Operators
|
||||||
|
|
||||||
@@ -38,27 +43,46 @@ but:
|
|||||||
The following functions return its argument if it is `Int`,
|
The following functions return its argument if it is `Int`,
|
||||||
or transformed `Real` otherwise.
|
or transformed `Real` otherwise.
|
||||||
|
|
||||||
| name | description |
|
| name | description |
|
||||||
|----------|--------------------------------------------------------|
|
|----------------|--------------------------------------------------------|
|
||||||
| floor(x) | Computes the largest integer value not greater than x |
|
| floor(x) | Computes the largest integer value not greater than x |
|
||||||
| ceil(x) | Computes the least integer value value not less than x |
|
| ceil(x) | Computes the least integer value value not less than x |
|
||||||
| round(x) | Rounds x |
|
| round(x) | Rounds x |
|
||||||
| | |
|
| x.roundToInt() | shortcut to `round(x).toInt()` |
|
||||||
| | |
|
|
||||||
|
|
||||||
## Scientific functions
|
## Lyng math functions
|
||||||
|
|
||||||
| name | meaning |
|
| name | meaning |
|
||||||
|---------------------|---------|
|
|-----------|------------------------------------------------------|
|
||||||
| `sin(x:Real): Real` | sine |
|
| 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:
|
For example:
|
||||||
|
|
||||||
sin(π/2)
|
assert( sin(π/2) == 1.0)
|
||||||
>>> 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
|
## Scientific constant
|
||||||
|
|
||||||
|
|||||||
@@ -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 )
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
|
||||||
|
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читается от предыдущего члена, в нашем случае это можно было бы записать через итератор, что мы вскоре добавим.
|
||||||
|
|
||||||
|
(продолжение следует)
|
||||||
+278
-37
@@ -1,19 +1,25 @@
|
|||||||
# Lying tutorial
|
---
|
||||||
|
gitea: none
|
||||||
|
include_toc: true
|
||||||
|
---
|
||||||
|
|
||||||
Lying is a very simple language, where we take only most important and popular features from
|
# Lyng tutorial
|
||||||
|
|
||||||
|
Lyng is a very simple language, where we take only most important and popular features from
|
||||||
other scripts and languages. In particular, we adopt _principle of minimal confusion_[^1].
|
other scripts and languages. In particular, we adopt _principle of minimal confusion_[^1].
|
||||||
In other word, the code usually works as expected when you see it. So, nothing unusual.
|
In other word, the code usually works as expected when you see it. So, nothing unusual.
|
||||||
|
|
||||||
__Other documents to read__ maybe after this one:
|
__Other documents to read__ maybe after this one:
|
||||||
|
|
||||||
- [Advanced topics](advanced_topics.md)
|
- [Advanced topics](advanced_topics.md), [declaring arguments](declaring_arguments.md)
|
||||||
- [OOP notes](OOP.md)
|
- [OOP notes](OOP.md), [exception handling](exceptions_handling.md)
|
||||||
- [math in Lying](math.md)
|
- [math in Lyng](math.md)
|
||||||
- Some class references: [List](List.md), [Real](Real.md), [Range](Range.md)
|
- Some class references: [List], [Real], [Range], [Iterable], [Iterator]
|
||||||
|
- Some samples: [combinatorics](samples/combinatorics.lyng.md), national vars and loops: [сумма ряда](samples/сумма_ряда.lyng.md). More at [samples folder](samples)
|
||||||
|
|
||||||
# Expressions
|
# Expressions
|
||||||
|
|
||||||
Everything is an expression in Lying. Even an empty block:
|
Everything is an expression in Lyng. Even an empty block:
|
||||||
|
|
||||||
// empty block
|
// empty block
|
||||||
>>> void
|
>>> void
|
||||||
@@ -219,9 +225,21 @@ likely will know some English, the rest is the pure uncertainty.
|
|||||||
|
|
||||||
Notice how function definition return a value, instance of `Callable`.
|
Notice how function definition return a value, instance of `Callable`.
|
||||||
|
|
||||||
You can use both `fn` and `fun`. Note that function declaration _is an expression returning callable_.
|
You can use both `fn` and `fun`. Note that function declaration _is an expression returning callable_,
|
||||||
|
but Lyng syntax requires using the __lambda syntax__ to create such.
|
||||||
|
|
||||||
There are default parameters in Lying:
|
val check = {
|
||||||
|
it > 0 && it < 100
|
||||||
|
}
|
||||||
|
assert( check(1) )
|
||||||
|
assert( !check(101) )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
See lambdas section below.
|
||||||
|
|
||||||
|
## Declaring arguments
|
||||||
|
|
||||||
|
There are default parameters in Lyng:
|
||||||
|
|
||||||
fn check(amount, prefix = "answer: ") {
|
fn check(amount, prefix = "answer: ") {
|
||||||
prefix + if( amount > 100 )
|
prefix + if( amount > 100 )
|
||||||
@@ -233,19 +251,33 @@ There are default parameters in Lying:
|
|||||||
check(120)
|
check(120)
|
||||||
>>> "answer: enough"
|
>>> "answer: enough"
|
||||||
|
|
||||||
|
It is possible to define also vararg using ellipsis:
|
||||||
|
|
||||||
|
fun sum(args...) {
|
||||||
|
var result = args[0]
|
||||||
|
for( i in 1 ..< args.size ) result += args[i]
|
||||||
|
}
|
||||||
|
sum(10,20,30)
|
||||||
|
>>> 60
|
||||||
|
|
||||||
|
See the [arguments reference](declaring_arguments.md) for more details.
|
||||||
|
|
||||||
## Closures
|
## Closures
|
||||||
|
|
||||||
Each __block has an isolated context that can be accessed from closures__. For example:
|
Each __block has an isolated context that can be accessed from closures__. For example:
|
||||||
|
|
||||||
var counter = 1
|
var counter = 1
|
||||||
|
|
||||||
// this is ok: coumter is incremented
|
// this is ok: counter is incremented
|
||||||
fun increment(amount=1) {
|
fun increment(amount=1) {
|
||||||
// use counter from a closure:
|
// use counter from a closure:
|
||||||
counter = counter + amount
|
counter = counter + amount
|
||||||
}
|
}
|
||||||
|
|
||||||
val taskAlias = fun someTask() {
|
increment(10)
|
||||||
|
assert( counter == 11 )
|
||||||
|
|
||||||
|
val callable = {
|
||||||
// this obscures global outer var with a local one
|
// this obscures global outer var with a local one
|
||||||
var counter = 0
|
var counter = 0
|
||||||
// ...
|
// ...
|
||||||
@@ -253,27 +285,86 @@ Each __block has an isolated context that can be accessed from closures__. For e
|
|||||||
// ...
|
// ...
|
||||||
counter
|
counter
|
||||||
}
|
}
|
||||||
|
|
||||||
|
assert(callable() == 1)
|
||||||
|
// but the global counter is not changed:
|
||||||
|
assert(counter == 11)
|
||||||
>>> void
|
>>> void
|
||||||
|
|
||||||
As was told, `fun` statement return callable for the function, it could be used as a parameter, or elsewhere
|
## Lambda functions
|
||||||
to call it:
|
|
||||||
|
|
||||||
val taskAlias = fun someTask() {
|
Lambda expression is a block with optional argument list ending with `->`. If argument list is omitted,
|
||||||
println("Hello")
|
the call arguments will be assigned to `it`:
|
||||||
|
|
||||||
|
lambda = {
|
||||||
|
it + "!"
|
||||||
}
|
}
|
||||||
// call the callable stored in the var
|
assert( lambda is Callable)
|
||||||
taskAlias()
|
assert( lambda("hello") == "hello!" )
|
||||||
// or directly:
|
void
|
||||||
someTask()
|
|
||||||
>>> Hello
|
### `it` assignment rules
|
||||||
>>> Hello
|
|
||||||
|
When lambda is called with:
|
||||||
|
|
||||||
|
- no arguments: `it == void`
|
||||||
|
- exactly one argument: `it` will be assigned to it
|
||||||
|
- more than 1 argument: `it` will be a `List` with these arguments:
|
||||||
|
|
||||||
|
Here is an example:
|
||||||
|
|
||||||
|
val lambda = { it }
|
||||||
|
assert( lambda() == void )
|
||||||
|
assert( lambda("one") == "one")
|
||||||
|
assert( lambda("one", "two") == ["one", "two"])
|
||||||
>>> void
|
>>> void
|
||||||
|
|
||||||
If you need to create _unnamed_ function, use alternative syntax (TBD, like { -> } ?)
|
If you need to create _unnamed_ function, use alternative syntax (TBD, like { -> } ?)
|
||||||
|
|
||||||
|
### Declaring parameters
|
||||||
|
|
||||||
|
Parameter is a list of comma-separated names, with optional default value; last
|
||||||
|
one could be with ellipsis that means "the rest pf arguments as List":
|
||||||
|
|
||||||
|
assert( { a -> a }(10) == 10 )
|
||||||
|
assert( { a, b -> [a,b] }(1,2) == [1,2])
|
||||||
|
assert( { a, b=-1 -> [a,b] }(1) == [1,-1])
|
||||||
|
assert( { a, b...-> [a,...b] }(100) == [100])
|
||||||
|
// notice that splat syntax in array literal unrills
|
||||||
|
// ellipsis-caught arguments back:
|
||||||
|
assert( { a, b...-> [a,...b] }(100, 1, 2, 3) == [100, 1, 2, 3])
|
||||||
|
void
|
||||||
|
|
||||||
|
### Using lambda as the parameter
|
||||||
|
|
||||||
|
// note that fun returns its last calculated value,
|
||||||
|
// in our case, result after in-place addition:
|
||||||
|
fun mapValues(iterable, transform) {
|
||||||
|
var result = []
|
||||||
|
for( x in iterable ) result += transform(x)
|
||||||
|
}
|
||||||
|
assert( [11, 21, 31] == mapValues( [1,2,3], { it*10+1 }))
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
### Auto last parameter
|
||||||
|
|
||||||
|
When the function call is follower by the `{` in the same line, e.g. lambda immediately
|
||||||
|
after function call, it is treated as a last argument to the call, e.g.:
|
||||||
|
|
||||||
|
fun mapValues(iterable, transform) {
|
||||||
|
var result = []
|
||||||
|
for( x in iterable ) result += transform(x)
|
||||||
|
}
|
||||||
|
val mapped = mapValues( [1,2,3]) {
|
||||||
|
it*10+1
|
||||||
|
}
|
||||||
|
assert( [11, 21, 31] == mapped)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
|
||||||
# Lists (aka arrays)
|
# Lists (aka arrays)
|
||||||
|
|
||||||
Lying has built-in mutable array class `List` with simple literals:
|
Lyng has built-in mutable array class `List` with simple literals:
|
||||||
|
|
||||||
[1, "two", 3.33].size
|
[1, "two", 3.33].size
|
||||||
>>> 3
|
>>> 3
|
||||||
@@ -463,16 +554,16 @@ Or, more neat:
|
|||||||
|
|
||||||
## while
|
## while
|
||||||
|
|
||||||
Regular pre-condition while loop, as expression, loop returns it's last line result:
|
Regular pre-condition while loop, as expression, loop returns the last expression as everything else:
|
||||||
|
|
||||||
var count = 0
|
var count = 0
|
||||||
while( count < 5 ) {
|
val result = while( count < 5 ) count++
|
||||||
count++
|
result
|
||||||
count * 10
|
>>> 4
|
||||||
}
|
|
||||||
>>> 50
|
|
||||||
|
|
||||||
We can break as usual:
|
Notice it _is 4 because when count became 5, the loop body was not executed!_.
|
||||||
|
|
||||||
|
We can break while as usual:
|
||||||
|
|
||||||
var count = 0
|
var count = 0
|
||||||
while( count < 5 ) {
|
while( count < 5 ) {
|
||||||
@@ -526,17 +617,15 @@ We can skip the rest of the loop and restart it, as usual, with `continue` opera
|
|||||||
"found even numbers: " + countEven
|
"found even numbers: " + countEven
|
||||||
>>> "found even numbers: 5"
|
>>> "found even numbers: 5"
|
||||||
|
|
||||||
`continue` can't "return" anything: it just restarts the loop. It can use labeled loops to restart outer ones:
|
`continue` can't "return" anything: it just restarts the loop. It can use labeled loops to restart outer ones (we intentionally avoid using for loops here):
|
||||||
|
|
||||||
var count = 0
|
var count = 0
|
||||||
var total = 0
|
var total = 0
|
||||||
// notice the label:
|
// notice the label:
|
||||||
outerLoop@ while( count < 5 ) {
|
outerLoop@ while( count++ < 5 ) {
|
||||||
count = count + 1
|
|
||||||
var innerCount = 0
|
var innerCount = 0
|
||||||
while( innerCount < 10 ) {
|
while( innerCount < 10 ) {
|
||||||
innerCount = innerCount + 1
|
if( ++innerCount == 10 )
|
||||||
if( innerCount == 10 )
|
|
||||||
continue@outerLoop
|
continue@outerLoop
|
||||||
}
|
}
|
||||||
// we don't reach it because continue above restarts our loop
|
// we don't reach it because continue above restarts our loop
|
||||||
@@ -546,13 +635,83 @@ We can skip the rest of the loop and restart it, as usual, with `continue` opera
|
|||||||
>>> 0
|
>>> 0
|
||||||
|
|
||||||
Notice that `total` remains 0 as the end of the outerLoop@ is not reachable: `continue` is always called and always make
|
Notice that `total` remains 0 as the end of the outerLoop@ is not reachable: `continue` is always called and always make
|
||||||
Lying to skip it.
|
Lyng to skip it.
|
||||||
|
|
||||||
## else statement
|
## else statement
|
||||||
|
|
||||||
The while and for loops can be followed by the else block, which is executed when the loop
|
The while and for loops can be followed by the else block, which is executed when the loop
|
||||||
ends normally, without breaks. It allows override loop result value, for example,
|
ends normally, without breaks. It allows override loop result value, for example,
|
||||||
to not calculate it in every iteration. See for loop example just below.
|
to not calculate it in every iteration. For example, consider this naive prime number
|
||||||
|
test function (remember function return it's last expression result):
|
||||||
|
|
||||||
|
fun naive_is_prime(candidate) {
|
||||||
|
val x = if( candidate !is Int) candidate.toInt() else candidate
|
||||||
|
var divisor = 1
|
||||||
|
while( ++divisor < x/2 || divisor == 2 ) {
|
||||||
|
if( x % divisor == 0 ) break false
|
||||||
|
}
|
||||||
|
else true
|
||||||
|
}
|
||||||
|
assert( !naive_is_prime(16) )
|
||||||
|
assert( naive_is_prime(17) )
|
||||||
|
assert( naive_is_prime(3) )
|
||||||
|
assert( !naive_is_prime(4) )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
## Loop return value diagram
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
S((start)) --> Cond{check}
|
||||||
|
Cond--false, no else--->V((void))
|
||||||
|
Cond--true-->E(["last = loop_body()" ])
|
||||||
|
E--break value---->BV((value))
|
||||||
|
E--> Check2{check}
|
||||||
|
E--break---->V
|
||||||
|
Check2 --false-->E
|
||||||
|
Check2 --true, no else--->L((last))
|
||||||
|
Check2 --true, else-->Else(["else_clause()"])
|
||||||
|
Cond--false, else--->Else
|
||||||
|
Else --> Ele4$nr((else))
|
||||||
|
```
|
||||||
|
|
||||||
|
So the returned value, as seen from diagram could be one of:
|
||||||
|
|
||||||
|
- `void`, if the loop was not executed, e.g. `condition` was initially false, and there was no `else` clause, or if the empty break was executed.
|
||||||
|
- value returned from `break value' statement
|
||||||
|
- value returned from the `else` clause, of the loop was not broken
|
||||||
|
- value returned from the last execution of loop body, if there was no `break` and no `else` clause.
|
||||||
|
|
||||||
|
## do-while loops
|
||||||
|
|
||||||
|
There works exactly as while loops but the body is executed prior to checking the while condition:
|
||||||
|
|
||||||
|
var i = 0
|
||||||
|
do { i++ } while( i < 1 )
|
||||||
|
i
|
||||||
|
>>> 1
|
||||||
|
|
||||||
|
The important feature of the do-while loop is that the condition expression is
|
||||||
|
evaluated on the body scope, e.g., variables, intruduced in the loop body are
|
||||||
|
available in the condition:
|
||||||
|
|
||||||
|
do {
|
||||||
|
var continueLoop = false
|
||||||
|
"OK"
|
||||||
|
} while( continueLoop )
|
||||||
|
>>> "OK"
|
||||||
|
|
||||||
|
This is sometimes convenient when condition is complex and has to be calculated inside the loop body. Notice the value returning by the loop:
|
||||||
|
|
||||||
|
fun readLine() { "done: result" }
|
||||||
|
val result = do {
|
||||||
|
val line = readLine()
|
||||||
|
} while( !line.startsWith("done:") )
|
||||||
|
result.drop(6)
|
||||||
|
>>> "result"
|
||||||
|
|
||||||
|
Suppose readLine() here reads some stream of lines.
|
||||||
|
|
||||||
|
|
||||||
## For loops
|
## For loops
|
||||||
|
|
||||||
@@ -594,6 +753,62 @@ We can use labels too:
|
|||||||
assert( search(["hello", "world"], 'z') == null)
|
assert( search(["hello", "world"], 'z') == null)
|
||||||
>>> void
|
>>> void
|
||||||
|
|
||||||
|
# Exception handling
|
||||||
|
|
||||||
|
Very much like in Kotlin. Try block returns its body block result, if no exception was cauht, or the result from the catch block that caught the exception:
|
||||||
|
|
||||||
|
var error = "not caught"
|
||||||
|
var finallyCaught = false
|
||||||
|
val result = try {
|
||||||
|
throw IllegalArgumentException()
|
||||||
|
"invalid"
|
||||||
|
}
|
||||||
|
catch(nd: SymbolNotDefinedException) {
|
||||||
|
error = "bad catch"
|
||||||
|
}
|
||||||
|
catch(x: IllegalArgumentException) {
|
||||||
|
error = "no error"
|
||||||
|
"OK"
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
// finally does not affect returned value
|
||||||
|
"too bad"
|
||||||
|
}
|
||||||
|
assertEquals( "no error", error)
|
||||||
|
assertEquals( "OK", result)
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
There is shorter form of catch block when you want to catch any exception:
|
||||||
|
|
||||||
|
var caught = null
|
||||||
|
try {
|
||||||
|
throw IllegalArgumentException()
|
||||||
|
}
|
||||||
|
catch(t) { // same as catch(t: Exception), but simpler
|
||||||
|
caught = t
|
||||||
|
}
|
||||||
|
assert( caught is IllegalArgumentException )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
And even shortest, for the Lying lang tradition, missing var is `it`:
|
||||||
|
|
||||||
|
var caught = null
|
||||||
|
try {
|
||||||
|
throw IllegalArgumentException()
|
||||||
|
}
|
||||||
|
catch { // same as catch(it: Exception), but simpler
|
||||||
|
caught = it
|
||||||
|
}
|
||||||
|
assert( caught is IllegalArgumentException )
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
It is possible to catch several exceptions in the same block too, use
|
||||||
|
`catch( varName: ExceptionClass1, ExceptionClass2)`, etc, use short form of throw and
|
||||||
|
many more.
|
||||||
|
|
||||||
|
- see [exception handling](exceptions_handling.md) for detailed exceptions tutorial and reference.
|
||||||
|
|
||||||
|
|
||||||
# Self-assignments in expression
|
# Self-assignments in expression
|
||||||
|
|
||||||
There are auto-increments and auto-decrements:
|
There are auto-increments and auto-decrements:
|
||||||
@@ -662,7 +877,7 @@ See [Ranges](Range.md) for detailed documentation on it.
|
|||||||
|
|
||||||
// single line comment
|
// single line comment
|
||||||
var result = null // here we will store the result
|
var result = null // here we will store the result
|
||||||
>>> void
|
>>> null
|
||||||
|
|
||||||
# Integral data types
|
# Integral data types
|
||||||
|
|
||||||
@@ -708,10 +923,36 @@ Are the same as in string literals with little difference:
|
|||||||
|
|
||||||
## String details
|
## String details
|
||||||
|
|
||||||
|
Strings are much like Kotlin ones:
|
||||||
|
|
||||||
|
"Hello".length
|
||||||
|
>>> 5
|
||||||
|
And supports growing set of kotlin-borrowed operations, see below, for example:
|
||||||
|
|
||||||
|
assertEquals("Hell", "Hello".dropLast(1))
|
||||||
|
>>> void
|
||||||
|
|
||||||
### String operations
|
### String operations
|
||||||
|
|
||||||
Concatenation is a `+`: `"hello " + name` works as expected. No confusion.
|
Concatenation is a `+`: `"hello " + name` works as expected. No confusion.
|
||||||
|
|
||||||
|
Typical set of String functions includes:
|
||||||
|
|
||||||
|
| fun/prop | description / notes |
|
||||||
|
|------------------|------------------------------------------------------------|
|
||||||
|
| lower() | change case to unicode upper |
|
||||||
|
| upper() | change case to unicode lower |
|
||||||
|
| startsWith(prefix) | true if starts with a prefix |
|
||||||
|
| take(n) | get a new string from up to n first characters |
|
||||||
|
| takeLast(n) | get a new string from up to n last characters |
|
||||||
|
| drop(n) | get a new string dropping n first chars, or empty string |
|
||||||
|
| dropLast(n) | get a new string dropping n last chars, or empty string |
|
||||||
|
| size | size in characters like `length` because String is [Array] |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Literals
|
### Literals
|
||||||
|
|
||||||
String literal could be multiline:
|
String literal could be multiline:
|
||||||
|
|||||||
+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,24 @@
|
|||||||
[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.10.1"
|
||||||
mp_bintools = "0.1.12"
|
mp_bintools = "0.1.12"
|
||||||
|
firebaseCrashlyticsBuildtools = "3.0.3"
|
||||||
|
okioVersion = "3.10.2"
|
||||||
|
|
||||||
[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" }
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
androidLibrary = { id = "com.android.library", version.ref = "agp" }
|
androidLibrary = { id = "com.android.library", version.ref = "agp" }
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
count = 0
|
||||||
|
for n1 in range(10):
|
||||||
|
for n2 in range(10):
|
||||||
|
for n3 in range(10):
|
||||||
|
for n4 in range(10):
|
||||||
|
for n5 in range(10):
|
||||||
|
for n6 in range(10):
|
||||||
|
if n1 + n2 + n3 == n4 + n5 + n6:
|
||||||
|
count += 1
|
||||||
|
|
||||||
|
print(count)
|
||||||
@@ -1,17 +1,40 @@
|
|||||||
|
import com.codingfeline.buildkonfig.compiler.FieldSpec.Type.STRING
|
||||||
import com.vanniktech.maven.publish.SonatypeHost
|
import com.vanniktech.maven.publish.SonatypeHost
|
||||||
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
||||||
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
|
group = "net.sergeych"
|
||||||
|
version = "0.5.1-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 {
|
plugins {
|
||||||
alias(libs.plugins.kotlinMultiplatform)
|
alias(libs.plugins.kotlinMultiplatform)
|
||||||
alias(libs.plugins.androidLibrary)
|
alias(libs.plugins.androidLibrary)
|
||||||
alias(libs.plugins.vanniktech.mavenPublish)
|
alias(libs.plugins.vanniktech.mavenPublish)
|
||||||
kotlin("plugin.serialization") version "2.1.20"
|
kotlin("plugin.serialization") version "2.1.20"
|
||||||
|
id("com.codingfeline.buildkonfig") version "0.17.1"
|
||||||
}
|
}
|
||||||
|
|
||||||
group = "net.sergeych"
|
buildkonfig {
|
||||||
version = "0.0.1-SNAPSHOT"
|
packageName = "net.sergeych.lyng"
|
||||||
|
// objectName = "YourAwesomeConfig"
|
||||||
|
// exposeObjectWithName = "YourAwesomePublicConfig"
|
||||||
|
|
||||||
|
defaultConfigs {
|
||||||
|
buildConfigField(STRING, "bcprovider", "codingfeline")
|
||||||
|
buildConfigField(STRING, "version", version.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
jvm()
|
jvm()
|
||||||
@@ -26,7 +49,7 @@ kotlin {
|
|||||||
// iosArm64()
|
// iosArm64()
|
||||||
// iosSimulatorArm64()
|
// iosSimulatorArm64()
|
||||||
linuxX64()
|
linuxX64()
|
||||||
js(IR) {
|
js {
|
||||||
browser()
|
browser()
|
||||||
nodejs()
|
nodejs()
|
||||||
}
|
}
|
||||||
@@ -39,17 +62,19 @@ kotlin {
|
|||||||
sourceSets {
|
sourceSets {
|
||||||
all {
|
all {
|
||||||
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
|
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
|
||||||
|
languageSettings.optIn("kotlin.contracts.ExperimentalContracts::class")
|
||||||
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
|
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
|
||||||
languageSettings.optIn("kotlin.coroutines.DelicateCoroutinesApi")
|
languageSettings.optIn("kotlin.coroutines.DelicateCoroutinesApi")
|
||||||
}
|
}
|
||||||
|
|
||||||
val commonMain by getting {
|
val commonMain by getting {
|
||||||
|
kotlin.srcDir("$buildDir/generated/buildConfig/commonMain/kotlin")
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1")
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1")
|
||||||
//put your multiplatform dependencies here
|
//put your multiplatform dependencies here
|
||||||
implementation(libs.kotlinx.coroutines.core)
|
api(libs.kotlinx.coroutines.core)
|
||||||
implementation(libs.mp.bintools)
|
api(libs.mp.bintools)
|
||||||
implementation("net.sergeych:mp_stools:1.5.2")
|
api("net.sergeych:mp_stools:1.5.2")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val commonTest by getting {
|
val commonTest by getting {
|
||||||
@@ -72,6 +97,9 @@ android {
|
|||||||
targetCompatibility = JavaVersion.VERSION_11
|
targetCompatibility = JavaVersion.VERSION_11
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.firebase.crashlytics.buildtools)
|
||||||
|
}
|
||||||
|
|
||||||
mavenPublishing {
|
mavenPublishing {
|
||||||
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
|
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
|
||||||
@@ -81,7 +109,7 @@ mavenPublishing {
|
|||||||
coordinates(group.toString(), "library", version.toString())
|
coordinates(group.toString(), "library", version.toString())
|
||||||
|
|
||||||
pom {
|
pom {
|
||||||
name = "Lying language"
|
name = "Lyng language"
|
||||||
description = "Kotlin-bound scripting loanguage"
|
description = "Kotlin-bound scripting loanguage"
|
||||||
inceptionYear = "2025"
|
inceptionYear = "2025"
|
||||||
// url = "https://sergeych.net"
|
// url = "https://sergeych.net"
|
||||||
@@ -106,3 +134,40 @@ mavenPublishing {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//
|
||||||
|
//val projectVersion by project.extra(provider {
|
||||||
|
// // Compute value lazily
|
||||||
|
// (version as String)
|
||||||
|
//})
|
||||||
|
//
|
||||||
|
//val generateBuildConfig by tasks.registering {
|
||||||
|
// // Declare outputs safely
|
||||||
|
// val outputDir = layout.buildDirectory.dir("generated/buildConfig/commonMain/kotlin")
|
||||||
|
// outputs.dir(outputDir)
|
||||||
|
//
|
||||||
|
// val version = projectVersion.get()
|
||||||
|
//
|
||||||
|
// // Inputs: Version is tracked as an input
|
||||||
|
// inputs.property("version", version)
|
||||||
|
//
|
||||||
|
// doLast {
|
||||||
|
// val packageName = "net.sergeych.lyng.buildconfig"
|
||||||
|
// val packagePath = packageName.replace('.', '/')
|
||||||
|
// val buildConfigFile = outputDir.get().file("$packagePath/BuildConfig.kt").asFile
|
||||||
|
//
|
||||||
|
// buildConfigFile.parentFile?.mkdirs()
|
||||||
|
// buildConfigFile.writeText(
|
||||||
|
// """
|
||||||
|
// |package $packageName
|
||||||
|
// |
|
||||||
|
// |object BuildConfig {
|
||||||
|
// | const val VERSION = "$version"
|
||||||
|
// |}
|
||||||
|
// """.trimMargin()
|
||||||
|
// )
|
||||||
|
// }
|
||||||
|
//}
|
||||||
|
//
|
||||||
|
//tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile>().configureEach {
|
||||||
|
// dependsOn(generateBuildConfig)
|
||||||
|
//}
|
||||||
@@ -1,41 +0,0 @@
|
|||||||
package net.sergeych.lying
|
|
||||||
|
|
||||||
data class ParsedArgument(val value: Statement, val pos: Pos, val isSplat: Boolean = false)
|
|
||||||
|
|
||||||
suspend fun Collection<ParsedArgument>.toArguments(context: Context): Arguments {
|
|
||||||
val list = mutableListOf<Arguments.Info>()
|
|
||||||
|
|
||||||
for (x in this) {
|
|
||||||
val value = x.value.execute(context)
|
|
||||||
if (x.isSplat) {
|
|
||||||
(value as? ObjList) ?: context.raiseClassCastError("expected list of objects for splat argument")
|
|
||||||
for (subitem in value.list) list.add(Arguments.Info(subitem, x.pos))
|
|
||||||
} else
|
|
||||||
list.add(Arguments.Info(value, x.pos))
|
|
||||||
}
|
|
||||||
return Arguments(list)
|
|
||||||
}
|
|
||||||
|
|
||||||
data class Arguments(val list: List<Info>) : Iterable<Obj> {
|
|
||||||
|
|
||||||
data class Info(val value: Obj, val pos: Pos)
|
|
||||||
|
|
||||||
val size by list::size
|
|
||||||
|
|
||||||
operator fun get(index: Int): Obj = list[index].value
|
|
||||||
|
|
||||||
fun firstAndOnly(): Obj {
|
|
||||||
if (list.size != 1) throw IllegalArgumentException("Expected one argument, got ${list.size}")
|
|
||||||
return list.first().value
|
|
||||||
}
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
val EMPTY = Arguments(emptyList())
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun iterator(): Iterator<Obj> {
|
|
||||||
return list.map { it.value }.iterator()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
package net.sergeych.lying
|
|
||||||
|
|
||||||
internal class CompilerContext(val tokens: List<Token>) : ListIterator<Token> by tokens.listIterator() {
|
|
||||||
val labels = mutableSetOf<String>()
|
|
||||||
|
|
||||||
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 currentPos() =
|
|
||||||
if (hasNext()) next().pos.also { previous() }
|
|
||||||
else previous().pos.also { next() }
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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
|
|
||||||
}
|
|
||||||
|
|
||||||
fun ifNextIs(typeId: Token.Type, f: (Token) -> Unit): Boolean {
|
|
||||||
val t = next()
|
|
||||||
return if (t.type == typeId) {
|
|
||||||
f(t)
|
|
||||||
true
|
|
||||||
} else {
|
|
||||||
previous()
|
|
||||||
false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
package net.sergeych.lying
|
|
||||||
|
|
||||||
import kotlin.math.*
|
|
||||||
|
|
||||||
class Script(
|
|
||||||
override val pos: Pos,
|
|
||||||
private val statements: List<Statement> = emptyList(),
|
|
||||||
) : Statement() {
|
|
||||||
|
|
||||||
override suspend fun execute(context: Context): Obj {
|
|
||||||
var lastResult: Obj = ObjVoid
|
|
||||||
for (s in statements) {
|
|
||||||
lastResult = s.execute(context)
|
|
||||||
}
|
|
||||||
return lastResult
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun execute() = execute(defaultContext.copy(pos))
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
val defaultContext: Context = Context().apply {
|
|
||||||
addFn("println") {
|
|
||||||
print("yn: ")
|
|
||||||
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()))
|
|
||||||
}
|
|
||||||
|
|
||||||
addVoidFn("assert") {
|
|
||||||
val cond = requiredArg<ObjBool>(0)
|
|
||||||
if( !cond.value == true )
|
|
||||||
raiseError(ObjAssertionError(this,"Assertion failed"))
|
|
||||||
}
|
|
||||||
|
|
||||||
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("Range", ObjRange.type)
|
|
||||||
|
|
||||||
// interfaces
|
|
||||||
addConst("Iterable", ObjIterable)
|
|
||||||
addConst("Array", ObjArray)
|
|
||||||
|
|
||||||
val pi = ObjReal(PI)
|
|
||||||
addConst("π", pi)
|
|
||||||
getOrCreateNamespace("Math").apply {
|
|
||||||
addConst("PI", pi)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package net.sergeych.lying
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whatever [Obj] stored somewhere
|
|
||||||
*/
|
|
||||||
data class StoredObj(
|
|
||||||
var value: Obj?,
|
|
||||||
val isMutable: Boolean = false
|
|
||||||
) {
|
|
||||||
val asAccess: WithAccess<Obj>? get() = value?.let { WithAccess(it, isMutable) }
|
|
||||||
}
|
|
||||||
@@ -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,124 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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
|
||||||
|
*/
|
||||||
|
suspend fun assignToContext(
|
||||||
|
context: Context,
|
||||||
|
arguments: Arguments = context.args,
|
||||||
|
defaultAccessType: AccessType = AccessType.Var,
|
||||||
|
defaultVisibility: Visibility = Visibility.Public
|
||||||
|
) {
|
||||||
|
fun assign(a: Item, value: Obj) {
|
||||||
|
context.addItem(a.name, (a.accessType ?: defaultAccessType).isMutable, value,
|
||||||
|
a.visibility ?: defaultVisibility)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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(context)
|
||||||
|
else -> {
|
||||||
|
println("callArgs: ${callArgs.joinToString()}")
|
||||||
|
println("tailBlockMode: ${arguments.tailBlockMode}")
|
||||||
|
context.raiseArgumentError("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(context)
|
||||||
|
else -> context.raiseArgumentError("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)
|
||||||
|
context.raiseArgumentError("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.Obj,
|
||||||
|
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,41 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
data class ParsedArgument(val value: Statement, val pos: Pos, val isSplat: Boolean = false)
|
||||||
|
|
||||||
|
suspend fun Collection<ParsedArgument>.toArguments(context: Context,tailBlockMode: Boolean): Arguments {
|
||||||
|
val list = mutableListOf<Obj>()
|
||||||
|
|
||||||
|
for (x in this) {
|
||||||
|
val value = x.value.execute(context)
|
||||||
|
if (x.isSplat) {
|
||||||
|
when {
|
||||||
|
value is ObjList -> {
|
||||||
|
for (subitem in value.list) list.add(subitem)
|
||||||
|
}
|
||||||
|
|
||||||
|
value.isInstanceOf(ObjIterable) -> {
|
||||||
|
val i = (value.invokeInstanceMethod(context, "toList") as ObjList).list
|
||||||
|
i.forEach { list.add(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> context.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 {
|
||||||
|
|
||||||
|
fun firstAndOnly(pos: Pos = Pos.UNKNOWN): Obj {
|
||||||
|
if (list.size != 1) throw ScriptError(pos, "expected one argument, got ${list.size}")
|
||||||
|
return list.first()
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val EMPTY = Arguments(emptyList())
|
||||||
|
fun from(values: Collection<Obj>) = Arguments(values.toList())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
//fun buildDoubleFromParts(
|
//fun buildDoubleFromParts(
|
||||||
// integerPart: Long,
|
// integerPart: Long,
|
||||||
+632
-130
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
internal class CompilerContext(val tokens: List<Token>) {
|
||||||
|
val labels = mutableSetOf<String>()
|
||||||
|
|
||||||
|
var breakFound = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
var loopLevel = 0
|
||||||
|
private set
|
||||||
|
|
||||||
|
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() = tokens.getOrElse(currentIndex) { throw IllegalStateException("No next token") }.also { currentIndex++ }
|
||||||
|
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 currentPos() =
|
||||||
|
if (hasNext()) next().pos.also { previous() }
|
||||||
|
else previous().pos.also { next() }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
*/
|
||||||
|
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.
|
||||||
|
*/
|
||||||
|
fun atOffset(offset: Int): Token? =
|
||||||
|
if (currentIndex + offset in tokens.indices) tokens[currentIndex + offset] else null
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Scan backwards as deep as specified looking for visibility token. Does not change position.
|
||||||
|
*/
|
||||||
|
fun getVisibility(default: Visibility = Visibility.Public, depths: Int = 2): Visibility {
|
||||||
|
for( i in -depths .. -1) {
|
||||||
|
when( atOffset(i)?.type) {
|
||||||
|
Token.Type.PROTECTED -> return Visibility.Protected
|
||||||
|
Token.Type.PRIVATE -> return Visibility.Private
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return default
|
||||||
|
}
|
||||||
|
|
||||||
|
// fun expectKeyword(vararg keyword: String): String {
|
||||||
|
// val t = next()
|
||||||
|
// if (t.type != Token.Type.ID && t.value !in keyword) {
|
||||||
|
// throw ScriptError(t.pos, "expected one of ${keyword.joinToString()}")
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
|
||||||
|
// data class ReturnScope(val needCatch: Boolean = false)
|
||||||
|
|
||||||
|
// private val
|
||||||
|
|
||||||
|
// fun startReturnScope(): ReturnScope {
|
||||||
|
// return ReturnScope()
|
||||||
|
// }
|
||||||
|
|
||||||
|
}
|
||||||
+40
-25
@@ -1,10 +1,11 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
class Context(
|
class Context(
|
||||||
val parent: Context?,
|
val parent: Context?,
|
||||||
val args: Arguments = Arguments.EMPTY,
|
val args: Arguments = Arguments.EMPTY,
|
||||||
var pos: Pos = Pos.builtIn,
|
var pos: Pos = Pos.builtIn,
|
||||||
val thisObj: Obj = ObjVoid
|
val thisObj: Obj = ObjVoid,
|
||||||
|
var skipContextCreation: Boolean = false,
|
||||||
) {
|
) {
|
||||||
constructor(
|
constructor(
|
||||||
args: Arguments = Arguments.EMPTY,
|
args: Arguments = Arguments.EMPTY,
|
||||||
@@ -15,63 +16,77 @@ class Context(
|
|||||||
fun raiseNotImplemented(what: String = "operation"): Nothing = raiseError("$what is not implemented")
|
fun raiseNotImplemented(what: String = "operation"): Nothing = raiseError("$what is not implemented")
|
||||||
|
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
fun raiseNPE(): Nothing = raiseError(ObjNullPointerError(this))
|
fun raiseNPE(): Nothing = raiseError(ObjNullPointerException(this))
|
||||||
|
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
fun raiseIndexOutOfBounds(message: String = "Index out of bounds"): Nothing =
|
fun raiseIndexOutOfBounds(message: String = "Index out of bounds"): Nothing =
|
||||||
raiseError(ObjIndexOutOfBoundsError(this, message))
|
raiseError(ObjIndexOutOfBoundsException(this, message))
|
||||||
|
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
fun raiseArgumentError(message: String = "Illegal argument error"): Nothing =
|
fun raiseArgumentError(message: String = "Illegal argument error"): Nothing =
|
||||||
raiseError(ObjIllegalArgumentError(this, message))
|
raiseError(ObjIllegalArgumentException(this, message))
|
||||||
|
|
||||||
fun raiseClassCastError(msg: String): Nothing = raiseError(ObjClassCastError(this, msg))
|
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 {
|
fun raiseError(message: String): Nothing {
|
||||||
throw ExecutionError(ObjError(this, message))
|
throw ExecutionError(ObjException(this, message))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun raiseError(obj: ObjError): Nothing {
|
fun raiseError(obj: ObjException): Nothing {
|
||||||
throw ExecutionError(obj)
|
throw ExecutionError(obj)
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <reified T: Obj>requiredArg(index: Int): T {
|
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}")
|
if (args.list.size <= index) raiseError("Expected at least ${index + 1} argument, got ${args.list.size}")
|
||||||
return (args.list[index].value as? T)
|
return (args.list[index] as? T)
|
||||||
?: raiseClassCastError("Expected type ${T::class.simpleName}, got ${args.list[index].value::class.simpleName}")
|
?: raiseClassCastError("Expected type ${T::class.simpleName}, got ${args.list[index]::class.simpleName}")
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <reified T: Obj>requireOnlyArg(): T {
|
inline fun <reified T : Obj> requireOnlyArg(): T {
|
||||||
if( args.list.size != 1 ) raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
if (args.list.size != 1) raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
||||||
return requiredArg(0)
|
return requiredArg(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
fun requireExactCount(count: Int) {
|
fun requireExactCount(count: Int) {
|
||||||
if( args.list.size != count ) {
|
if (args.list.size != count) {
|
||||||
raiseError("Expected exactly $count arguments, got ${args.list.size}")
|
raiseError("Expected exactly $count arguments, got ${args.list.size}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <reified T: Obj>thisAs(): T = (thisObj as? T)
|
inline fun <reified T : Obj> thisAs(): T = (thisObj as? T)
|
||||||
?: raiseClassCastError("Cannot cast ${thisObj.objClass.className} to ${T::class.simpleName}")
|
?: raiseClassCastError("Cannot cast ${thisObj.objClass.className} to ${T::class.simpleName}")
|
||||||
|
|
||||||
private val objects = mutableMapOf<String, StoredObj>()
|
internal val objects = mutableMapOf<String, ObjRecord>()
|
||||||
|
|
||||||
operator fun get(name: String): StoredObj? =
|
operator fun get(name: String): ObjRecord? =
|
||||||
objects[name]
|
objects[name]
|
||||||
?: parent?.get(name)
|
?: parent?.get(name)
|
||||||
|
|
||||||
fun copy(pos: Pos, args: Arguments = Arguments.EMPTY,newThisObj: Obj? = null): Context =
|
fun copy(pos: Pos, args: Arguments = Arguments.EMPTY, newThisObj: Obj? = null): Context =
|
||||||
Context(this, args, pos, newThisObj ?: thisObj)
|
Context(this, args, pos, newThisObj ?: thisObj)
|
||||||
|
|
||||||
fun addItem(name: String, isMutable: Boolean, value: Obj?): StoredObj {
|
fun copy(args: Arguments = Arguments.EMPTY, newThisObj: Obj? = null): Context =
|
||||||
return StoredObj(value, isMutable).also { objects.put(name, it) }
|
Context(this, args, pos, newThisObj ?: thisObj)
|
||||||
|
|
||||||
|
fun copy() = Context(this, args, pos, thisObj)
|
||||||
|
|
||||||
|
fun addItem(
|
||||||
|
name: String,
|
||||||
|
isMutable: Boolean,
|
||||||
|
value: Obj,
|
||||||
|
visibility: Visibility = Visibility.Public
|
||||||
|
): ObjRecord {
|
||||||
|
return ObjRecord(value, isMutable, visibility).also { objects[name] = it }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getOrCreateNamespace(name: String): ObjClass {
|
fun getOrCreateNamespace(name: String): ObjClass {
|
||||||
val ns = objects.getOrPut(name) { StoredObj(ObjNamespace(name), isMutable = false) }.value
|
val ns = objects.getOrPut(name) { ObjRecord(ObjNamespace(name), isMutable = false) }.value
|
||||||
return ns!!.objClass
|
return ns.objClass
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun addVoidFn(vararg names: String, crossinline fn: suspend Context.() -> Unit) {
|
inline fun addVoidFn(vararg names: String, crossinline fn: suspend Context.() -> Unit) {
|
||||||
@@ -81,7 +96,7 @@ class Context(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <reified T: Obj> addFn(vararg names: String, crossinline fn: suspend Context.() -> T) {
|
inline fun <reified T : Obj> addFn(vararg names: String, crossinline fn: suspend Context.() -> T) {
|
||||||
val newFn = object : Statement() {
|
val newFn = object : Statement() {
|
||||||
override val pos: Pos = Pos.builtIn
|
override val pos: Pos = Pos.builtIn
|
||||||
|
|
||||||
@@ -97,7 +112,7 @@ class Context(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addConst(name: String,value: Obj) = addItem(name, false, value)
|
fun addConst(name: String, value: Obj) = addItem(name, false, value)
|
||||||
|
|
||||||
suspend fun eval(code: String): Obj =
|
suspend fun eval(code: String): Obj =
|
||||||
Compiler().compile(code.toSource()).execute(this)
|
Compiler().compile(code.toSource()).execute(this)
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
sealed class ListEntry {
|
sealed class ListEntry {
|
||||||
data class Element(val accessor: Accessor) : ListEntry()
|
data class Element(val accessor: Accessor) : ListEntry()
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
class LoopBreakContinueException(
|
class LoopBreakContinueException(
|
||||||
val doContinue: Boolean,
|
val doContinue: Boolean,
|
||||||
+135
-28
@@ -1,21 +1,43 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
import kotlinx.coroutines.sync.Mutex
|
import kotlinx.coroutines.sync.Mutex
|
||||||
import kotlinx.coroutines.sync.withLock
|
import kotlinx.coroutines.sync.withLock
|
||||||
import kotlinx.serialization.SerialName
|
import kotlinx.serialization.SerialName
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
import net.sergeych.bintools.encodeToHex
|
||||||
import net.sergeych.synctools.ProtectedOp
|
import net.sergeych.synctools.ProtectedOp
|
||||||
|
import net.sergeych.synctools.withLock
|
||||||
|
import kotlin.contracts.ExperimentalContracts
|
||||||
|
|
||||||
//typealias InstanceMethod = (Context, Obj) -> Obj
|
/**
|
||||||
|
* Record to store object with access rules, e.g. [isMutable] and access level [visibility].
|
||||||
data class WithAccess<T>(var value: T, val isMutable: Boolean)
|
*/
|
||||||
|
data class ObjRecord(
|
||||||
|
var value: Obj,
|
||||||
|
val isMutable: Boolean,
|
||||||
|
val visibility: Visibility = Visibility.Public
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 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(
|
data class Accessor(
|
||||||
val getter: suspend (Context) -> WithAccess<Obj>,
|
val getter: suspend (Context) -> ObjRecord,
|
||||||
val setterOrNull: (suspend (Context, Obj) -> Unit)?
|
val setterOrNull: (suspend (Context, Obj) -> Unit)?
|
||||||
) {
|
) {
|
||||||
constructor(getter: suspend (Context) -> WithAccess<Obj>) : this(getter, null)
|
/**
|
||||||
|
* Simplified constructor for immutable stores.
|
||||||
|
*/
|
||||||
|
constructor(getter: suspend (Context) -> ObjRecord) : this(getter, null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the setter or throw.
|
||||||
|
*/
|
||||||
fun setter(pos: Pos) = setterOrNull ?: throw ScriptError(pos, "can't assign value")
|
fun setter(pos: Pos) = setterOrNull ?: throw ScriptError(pos, "can't assign value")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,15 +64,15 @@ open class Obj {
|
|||||||
fun isInstanceOf(someClass: Obj) = someClass === objClass || objClass.allParentsSet.contains(someClass)
|
fun isInstanceOf(someClass: Obj) = someClass === objClass || objClass.allParentsSet.contains(someClass)
|
||||||
|
|
||||||
suspend fun invokeInstanceMethod(context: Context, name: String, vararg args: Obj): Obj =
|
suspend fun invokeInstanceMethod(context: Context, name: String, vararg args: Obj): Obj =
|
||||||
invokeInstanceMethod(context, name, Arguments(args.map { Arguments.Info(it, context.pos) }))
|
invokeInstanceMethod(context, name, Arguments(args.toList()))
|
||||||
|
|
||||||
inline suspend fun <reified T : Obj> callMethod(
|
suspend inline fun <reified T : Obj> callMethod(
|
||||||
context: Context,
|
context: Context,
|
||||||
name: String,
|
name: String,
|
||||||
args: Arguments = Arguments.EMPTY
|
args: Arguments = Arguments.EMPTY
|
||||||
): T = invokeInstanceMethod(context, name, args) as T
|
): T = invokeInstanceMethod(context, name, args) as T
|
||||||
|
|
||||||
suspend fun invokeInstanceMethod(
|
open suspend fun invokeInstanceMethod(
|
||||||
context: Context,
|
context: Context,
|
||||||
name: String,
|
name: String,
|
||||||
args: Arguments = Arguments.EMPTY
|
args: Arguments = Arguments.EMPTY
|
||||||
@@ -160,22 +182,20 @@ open class Obj {
|
|||||||
|
|
||||||
suspend fun <T> sync(block: () -> T): T = monitor.withLock { block() }
|
suspend fun <T> sync(block: () -> T): T = monitor.withLock { block() }
|
||||||
|
|
||||||
suspend fun readField(context: Context, name: String): WithAccess<Obj> {
|
open suspend fun readField(context: Context, name: String): ObjRecord {
|
||||||
// could be property or class field:
|
// could be property or class field:
|
||||||
val obj = objClass.getInstanceMemberOrNull(name)
|
val obj = objClass.getInstanceMemberOrNull(name) ?: context.raiseError("no such field: $name")
|
||||||
val value = obj?.value
|
return when (val value = obj.value) {
|
||||||
return when (value) {
|
|
||||||
is Statement -> {
|
is Statement -> {
|
||||||
// readonly property, important: call it on this
|
ObjRecord(value.execute(context.copy(context.pos, newThisObj = this)), obj.isMutable)
|
||||||
value.execute(context.copy(context.pos, newThisObj = this)).asReadonly
|
|
||||||
}
|
}
|
||||||
// could be writable property naturally
|
// could be writable property naturally
|
||||||
null -> ObjNull.asReadonly
|
// null -> ObjNull.asReadonly
|
||||||
else -> obj
|
else -> obj
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun writeField(context: Context, name: String, newValue: Obj) {
|
open suspend fun writeField(context: Context, name: String, newValue: Obj) {
|
||||||
willMutate(context)
|
willMutate(context)
|
||||||
val field = objClass.getInstanceMemberOrNull(name) ?: context.raiseError("no such field: $name")
|
val field = objClass.getInstanceMemberOrNull(name) ?: context.raiseError("no such field: $name")
|
||||||
if (field.isMutable) field.value = newValue else context.raiseError("can't assign to read-only field: $name")
|
if (field.isMutable) field.value = newValue else context.raiseError("can't assign to read-only field: $name")
|
||||||
@@ -200,7 +220,7 @@ open class Obj {
|
|||||||
callOn(
|
callOn(
|
||||||
context.copy(
|
context.copy(
|
||||||
context.pos,
|
context.pos,
|
||||||
args = Arguments(args.map { Arguments.Info(it, context.pos) }),
|
args = Arguments(args.toList()),
|
||||||
newThisObj = thisObj
|
newThisObj = thisObj
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -218,8 +238,8 @@ open class Obj {
|
|||||||
callOn(context.copy(atPos, args = args, newThisObj = thisObj))
|
callOn(context.copy(atPos, args = args, newThisObj = thisObj))
|
||||||
|
|
||||||
|
|
||||||
val asReadonly: WithAccess<Obj> by lazy { WithAccess(this, false) }
|
val asReadonly: ObjRecord by lazy { ObjRecord(this, false) }
|
||||||
val asMutable: WithAccess<Obj> by lazy { WithAccess(this, true) }
|
val asMutable: ObjRecord by lazy { ObjRecord(this, true) }
|
||||||
|
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
@@ -268,6 +288,8 @@ object ObjNull : Obj() {
|
|||||||
override fun equals(other: Any?): Boolean {
|
override fun equals(other: Any?): Boolean {
|
||||||
return other is ObjNull || other == null
|
return other is ObjNull || other == null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = "null"
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Numeric {
|
interface Numeric {
|
||||||
@@ -307,15 +329,100 @@ data class ObjNamespace(val name: String) : Obj() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
open class ObjError(val context: Context, val message: String) : Obj() {
|
open class ObjException(exceptionClass: ExceptionClass, val context: Context, val message: String) : Obj() {
|
||||||
override val asStr: ObjString by lazy { ObjString("Error: $message") }
|
constructor(name: String,context: Context, message: String) : this(getOrCreateExceptionClass(name), context, message)
|
||||||
|
constructor(context: Context, message: String) : this(Root, context, message)
|
||||||
|
|
||||||
|
fun raise(): Nothing {
|
||||||
|
throw ExecutionError(this)
|
||||||
|
}
|
||||||
|
|
||||||
|
override val objClass: ObjClass = exceptionClass
|
||||||
|
|
||||||
|
override fun toString(): String {
|
||||||
|
return "ObjException:${objClass.className}:${context.pos}@${hashCode().encodeToHex()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
|
||||||
|
class ExceptionClass(val name: String,vararg parents: ObjClass) : ObjClass(name, *parents) {
|
||||||
|
override suspend fun callOn(context: Context): Obj {
|
||||||
|
val message = context.args.getOrNull(0)?.toString() ?: name
|
||||||
|
return ObjException(this, context, 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(context: Context) {
|
||||||
|
context.addConst("Exception", Root)
|
||||||
|
existingErrorClasses["Exception"] = Root
|
||||||
|
for (name in listOf(
|
||||||
|
"NullPointerException",
|
||||||
|
"AssertionFailedException",
|
||||||
|
"ClassCastException",
|
||||||
|
"IndexOutOfBoundsException",
|
||||||
|
"IllegalArgumentException",
|
||||||
|
"IllegalAssignmentException",
|
||||||
|
"SymbolNotDefinedException",
|
||||||
|
"IterationEndException",
|
||||||
|
"AccessException",
|
||||||
|
"UnknownException",
|
||||||
|
)) {
|
||||||
|
context.addConst(name, getOrCreateExceptionClass(name))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ObjNullPointerError(context: Context) : ObjError(context, "object is null")
|
class ObjNullPointerException(context: Context) : ObjException("NullPointerException", context, "object is null")
|
||||||
|
|
||||||
class ObjAssertionError(context: Context, message: String) : ObjError(context, message)
|
class ObjAssertionFailedException(context: Context, message: String) :
|
||||||
class ObjClassCastError(context: Context, message: String) : ObjError(context, message)
|
ObjException("AssertionFailedException", context, message)
|
||||||
class ObjIndexOutOfBoundsError(context: Context, message: String = "index out of bounds") : ObjError(context, message)
|
|
||||||
class ObjIllegalArgumentError(context: Context, message: String = "illegal argument") : ObjError(context, message)
|
|
||||||
|
|
||||||
class ObjIterationFinishedError(context: Context) : ObjError(context, "iteration finished")
|
class ObjClassCastException(context: Context, message: String) : ObjException("ClassCastException", context, message)
|
||||||
|
class ObjIndexOutOfBoundsException(context: Context, message: String = "index out of bounds") :
|
||||||
|
ObjException("IndexOutOfBoundsException", context, message)
|
||||||
|
|
||||||
|
class ObjIllegalArgumentException(context: Context, message: String = "illegal argument") :
|
||||||
|
ObjException("IllegalArgumentException", context, message)
|
||||||
|
|
||||||
|
class ObjIllegalAssignmentException(context: Context, message: String = "illegal assignment") :
|
||||||
|
ObjException("IllegalAssignmentException", context, message)
|
||||||
|
|
||||||
|
class ObjSymbolNotDefinedException(context: Context, message: String = "symbol is not defined") :
|
||||||
|
ObjException("SymbolNotDefinedException", context, message)
|
||||||
|
|
||||||
|
class ObjIterationFinishedException(context: Context) :
|
||||||
|
ObjException("IterationEndException", context, "iteration finished")
|
||||||
|
|
||||||
|
class ObjAccessException(context: Context, message: String = "access not allowed error") :
|
||||||
|
ObjException("AccessException", context, message)
|
||||||
|
|
||||||
|
class ObjUnknownException(context: Context, message: String = "access not allowed error") :
|
||||||
|
ObjException("UnknownException", context, message)
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
data class ObjBool(val value: Boolean) : Obj() {
|
data class ObjBool(val value: Boolean) : Obj() {
|
||||||
override val asStr by lazy { ObjString(value.toString()) }
|
override val asStr by lazy { ObjString(value.toString()) }
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
class ObjChar(val value: Char): Obj() {
|
class ObjChar(val value: Char): Obj() {
|
||||||
|
|
||||||
+39
-35
@@ -1,12 +1,14 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
val ObjClassType by lazy { ObjClass("Class") }
|
val ObjClassType by lazy { ObjClass("Class") }
|
||||||
|
|
||||||
class ObjClass(
|
open class ObjClass(
|
||||||
val className: String,
|
val className: String,
|
||||||
vararg val parents: ObjClass,
|
vararg val parents: ObjClass,
|
||||||
) : Obj() {
|
) : Obj() {
|
||||||
|
|
||||||
|
var instanceConstructor: Statement? = null
|
||||||
|
|
||||||
val allParentsSet: Set<ObjClass> = parents.flatMap {
|
val allParentsSet: Set<ObjClass> = parents.flatMap {
|
||||||
listOf(it) + it.allParentsSet
|
listOf(it) + it.allParentsSet
|
||||||
}.toSet()
|
}.toSet()
|
||||||
@@ -14,36 +16,35 @@ class ObjClass(
|
|||||||
override val objClass: ObjClass by lazy { ObjClassType }
|
override val objClass: ObjClass by lazy { ObjClassType }
|
||||||
|
|
||||||
// members: fields most often
|
// members: fields most often
|
||||||
private val members = mutableMapOf<String, WithAccess<Obj>>()
|
private val members = mutableMapOf<String, ObjRecord>()
|
||||||
|
|
||||||
override fun toString(): String = className
|
override fun toString(): String = className
|
||||||
|
|
||||||
override suspend fun compareTo(context: Context, other: Obj): Int = if (other === this) 0 else -1
|
override suspend fun compareTo(context: Context, other: Obj): Int = if (other === this) 0 else -1
|
||||||
|
|
||||||
// private var initInstanceHandler: (suspend (Context, List<Obj>) -> Obj)? = null
|
override suspend fun callOn(context: Context): Obj {
|
||||||
|
val instance = ObjInstance(this)
|
||||||
|
instance.instanceContext = context.copy(newThisObj = instance,args = context.args)
|
||||||
|
if (instanceConstructor != null) {
|
||||||
|
instanceConstructor!!.execute(instance.instanceContext)
|
||||||
|
}
|
||||||
|
return instance
|
||||||
|
}
|
||||||
|
|
||||||
// suspend fun newInstance(context: Context, vararg args: Obj): Obj =
|
|
||||||
// initInstanceHandler?.invoke(context, args.toList())
|
|
||||||
// ?: context.raiseError("No initInstance handler for $this")
|
|
||||||
//
|
|
||||||
// fun buildInstance(f: suspend Context.(List<Obj>) -> Obj) {
|
|
||||||
// if (initInstanceHandler != null) throw IllegalStateException("initInstance already set")
|
|
||||||
// initInstanceHandler = f
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// fun addParent(context: Context, parent: Obj) {
|
|
||||||
// val self = context.thisObj
|
|
||||||
// self.parentInstances.add(parent)
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
fun defaultInstance(): Obj = object : Obj() {
|
fun defaultInstance(): Obj = object : Obj() {
|
||||||
override val objClass: ObjClass = this@ObjClass
|
override val objClass: ObjClass = this@ObjClass
|
||||||
}
|
}
|
||||||
|
|
||||||
fun createField(name: String, initialValue: Obj, isMutable: Boolean = false, pos: Pos = Pos.builtIn) {
|
fun createField(
|
||||||
if (name in members || allParentsSet.any { name in it.members } == true)
|
name: String,
|
||||||
|
initialValue: Obj,
|
||||||
|
isMutable: Boolean = false,
|
||||||
|
visibility: Visibility = Visibility.Public,
|
||||||
|
pos: Pos = Pos.builtIn
|
||||||
|
) {
|
||||||
|
if (name in members || allParentsSet.any { name in it.members })
|
||||||
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
|
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
|
||||||
members[name] = WithAccess(initialValue, isMutable)
|
members[name] = ObjRecord(initialValue, isMutable, visibility)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addFn(name: String, isOpen: Boolean = false, code: suspend Context.() -> Obj) {
|
fun addFn(name: String, isOpen: Boolean = false, code: suspend Context.() -> Obj) {
|
||||||
@@ -56,13 +57,13 @@ class ObjClass(
|
|||||||
/**
|
/**
|
||||||
* Get instance member traversing the hierarchy if needed. Its meaning is different for different objects.
|
* Get instance member traversing the hierarchy if needed. Its meaning is different for different objects.
|
||||||
*/
|
*/
|
||||||
fun getInstanceMemberOrNull(name: String): WithAccess<Obj>? {
|
fun getInstanceMemberOrNull(name: String): ObjRecord? {
|
||||||
members[name]?.let { return it }
|
members[name]?.let { return it }
|
||||||
allParentsSet.forEach { parent -> parent.getInstanceMemberOrNull(name)?.let { return it } }
|
allParentsSet.forEach { parent -> parent.getInstanceMemberOrNull(name)?.let { return it } }
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getInstanceMember(atPos: Pos, name: String): WithAccess<Obj> =
|
fun getInstanceMember(atPos: Pos, name: String): ObjRecord =
|
||||||
getInstanceMemberOrNull(name)
|
getInstanceMemberOrNull(name)
|
||||||
?: throw ScriptError(atPos, "symbol doesn't exist: $name")
|
?: throw ScriptError(atPos, "symbol doesn't exist: $name")
|
||||||
}
|
}
|
||||||
@@ -70,24 +71,26 @@ class ObjClass(
|
|||||||
/**
|
/**
|
||||||
* Abstract class that must provide `iterator` method that returns [ObjIterator] instance.
|
* Abstract class that must provide `iterator` method that returns [ObjIterator] instance.
|
||||||
*/
|
*/
|
||||||
val ObjIterable by lazy { ObjClass("Iterable").apply {
|
val ObjIterable by lazy {
|
||||||
|
ObjClass("Iterable").apply {
|
||||||
|
|
||||||
addFn("toList") {
|
addFn("toList") {
|
||||||
val result = mutableListOf<Obj>()
|
val result = mutableListOf<Obj>()
|
||||||
val iterator = thisObj.invokeInstanceMethod(this, "iterator")
|
val iterator = thisObj.invokeInstanceMethod(this, "iterator")
|
||||||
|
|
||||||
while( iterator.invokeInstanceMethod(this, "hasNext").toBool() )
|
while (iterator.invokeInstanceMethod(this, "hasNext").toBool())
|
||||||
result += iterator.invokeInstanceMethod(this, "next")
|
result += iterator.invokeInstanceMethod(this, "next")
|
||||||
|
|
||||||
|
|
||||||
// val next = iterator.getMemberOrNull("next")!!
|
// val next = iterator.getMemberOrNull("next")!!
|
||||||
// val hasNext = iterator.getMemberOrNull("hasNext")!!
|
// val hasNext = iterator.getMemberOrNull("hasNext")!!
|
||||||
// while( hasNext.invoke(this, iterator).toBool() )
|
// while( hasNext.invoke(this, iterator).toBool() )
|
||||||
// result += next.invoke(this, iterator)
|
// result += next.invoke(this, iterator)
|
||||||
ObjList(result)
|
ObjList(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
} }
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Collection is an iterator with `size`]
|
* Collection is an iterator with `size`]
|
||||||
@@ -119,11 +122,11 @@ class ObjArrayIterator(val array: Obj) : Obj() {
|
|||||||
val self = thisAs<ObjArrayIterator>()
|
val self = thisAs<ObjArrayIterator>()
|
||||||
if (self.nextIndex < self.lastIndex) {
|
if (self.nextIndex < self.lastIndex) {
|
||||||
self.array.invokeInstanceMethod(this, "getAt", (self.nextIndex++).toObj())
|
self.array.invokeInstanceMethod(this, "getAt", (self.nextIndex++).toObj())
|
||||||
} else raiseError(ObjIterationFinishedError(this))
|
} else raiseError(ObjIterationFinishedException(this))
|
||||||
}
|
}
|
||||||
addFn("hasNext") {
|
addFn("hasNext") {
|
||||||
val self = thisAs<ObjArrayIterator>()
|
val self = thisAs<ObjArrayIterator>()
|
||||||
if (self.nextIndex < self.lastIndex) ObjTrue else ObjFalse
|
if (self.nextIndex < self.lastIndex) ObjTrue else ObjFalse
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -142,6 +145,7 @@ val ObjArray by lazy {
|
|||||||
addFn("iterator") {
|
addFn("iterator") {
|
||||||
ObjArrayIterator(thisObj).also { it.init(this) }
|
ObjArrayIterator(thisObj).also { it.init(this) }
|
||||||
}
|
}
|
||||||
addFn("isample") { "ok".toObj()}
|
addFn("isample") { "ok".toObj() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
class ObjInstance(override val objClass: ObjClass) : Obj() {
|
||||||
|
|
||||||
|
internal lateinit var instanceContext: Context
|
||||||
|
|
||||||
|
override suspend fun readField(context: Context, name: String): ObjRecord {
|
||||||
|
return instanceContext[name]?.let {
|
||||||
|
if (it.visibility.isPublic)
|
||||||
|
it
|
||||||
|
else
|
||||||
|
context.raiseError(ObjAccessException(context, "can't access non-public field $name"))
|
||||||
|
}
|
||||||
|
?: super.readField(context, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun writeField(context: Context, name: String, newValue: Obj) {
|
||||||
|
instanceContext[name]?.let { f ->
|
||||||
|
if (!f.visibility.isPublic)
|
||||||
|
ObjIllegalAssignmentException(context, "can't assign to non-public field $name")
|
||||||
|
if (!f.isMutable) ObjIllegalAssignmentException(context, "can't reassign val $name").raise()
|
||||||
|
if (f.value.assign(context, newValue) == null)
|
||||||
|
f.value = newValue
|
||||||
|
} ?: super.writeField(context, name, newValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun invokeInstanceMethod(context: Context, name: String, args: Arguments): Obj =
|
||||||
|
instanceContext[name]?.let {
|
||||||
|
if (it.visibility.isPublic)
|
||||||
|
it.value.invoke(context, this, args)
|
||||||
|
else
|
||||||
|
context.raiseError(ObjAccessException(context, "can't invoke non-public method $name"))
|
||||||
|
}
|
||||||
|
?: super.invokeInstanceMethod(context, name, args)
|
||||||
|
|
||||||
|
private val publicFields: Map<String, ObjRecord>
|
||||||
|
get() = instanceContext.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 compareTo(context: Context, other: Obj): Int {
|
||||||
|
if (other !is ObjInstance) return -1
|
||||||
|
if (other.objClass != objClass) return -1
|
||||||
|
for (f in publicFields) {
|
||||||
|
val a = f.value.value
|
||||||
|
val b = other.instanceContext[f.key]!!.value
|
||||||
|
val d = a.compareTo(context, b)
|
||||||
|
if (d != 0) return d
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
data class ObjInt(var value: Long) : Obj(), Numeric {
|
data class ObjInt(var value: Long) : Obj(), Numeric {
|
||||||
override val asStr get() = ObjString(value.toString())
|
override val asStr get() = ObjString(value.toString())
|
||||||
+2
-2
@@ -1,6 +1,6 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
class ObjList(val list: MutableList<Obj>) : Obj() {
|
class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
|
||||||
|
|
||||||
init {
|
init {
|
||||||
for (p in objClass.parents)
|
for (p in objClass.parents)
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
class ObjRange(val start: Obj?, val end: Obj?, val isEndInclusive: Boolean) : Obj() {
|
class ObjRange(val start: Obj?, val end: Obj?, val isEndInclusive: Boolean) : Obj() {
|
||||||
|
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
class ObjRangeIterator(val self: ObjRange) : Obj() {
|
class ObjRangeIterator(val self: ObjRange) : Obj() {
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ class ObjRangeIterator(val self: ObjRange) : Obj() {
|
|||||||
if( isCharRange ) ObjChar(x.toInt().toChar()) else ObjInt(x)
|
if( isCharRange ) ObjChar(x.toInt().toChar()) else ObjInt(x)
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
context.raiseError(ObjIterationFinishedError(context))
|
context.raiseError(ObjIterationFinishedException(context))
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
import kotlin.math.floor
|
import kotlin.math.floor
|
||||||
import kotlin.math.roundToLong
|
import kotlin.math.roundToLong
|
||||||
+27
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
import kotlinx.serialization.SerialName
|
import kotlinx.serialization.SerialName
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
@@ -40,6 +40,32 @@ data class ObjString(val value: String) : Obj() {
|
|||||||
addConst("length",
|
addConst("length",
|
||||||
statement { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
statement { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
||||||
)
|
)
|
||||||
|
addFn("takeLast") {
|
||||||
|
thisAs<ObjString>().value.takeLast(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("take") {
|
||||||
|
thisAs<ObjString>().value.take(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("drop") {
|
||||||
|
thisAs<ObjString>().value.drop(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("dropLast") {
|
||||||
|
thisAs<ObjString>().value.dropLast(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("lower") {
|
||||||
|
thisAs<ObjString>().value.lowercase().let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("upper") {
|
||||||
|
thisAs<ObjString>().value.uppercase().let(::ObjString)
|
||||||
|
}
|
||||||
addFn("size") { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
addFn("size") { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+50
-4
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
val digitsSet = ('0'..'9').toSet()
|
val digitsSet = ('0'..'9').toSet()
|
||||||
val digits = { d: Char -> d in digitsSet }
|
val digits = { d: Char -> d in digitsSet }
|
||||||
@@ -8,7 +8,7 @@ val idNextChars = { d: Char -> d.isLetter() || d == '_' || d.isDigit() }
|
|||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
val idFirstChars = { d: Char -> d.isLetter() || d == '_' }
|
val idFirstChars = { d: Char -> d.isLetter() || d == '_' }
|
||||||
|
|
||||||
fun parseLing(source: Source): List<Token> {
|
fun parseLyng(source: Source): List<Token> {
|
||||||
val p = Parser(fromPos = source.startPos)
|
val p = Parser(fromPos = source.startPos)
|
||||||
val tokens = mutableListOf<Token>()
|
val tokens = mutableListOf<Token>()
|
||||||
do {
|
do {
|
||||||
@@ -83,6 +83,11 @@ private class Parser(fromPos: Pos) {
|
|||||||
Token("-", from, Token.Type.MINUSASSIGN)
|
Token("-", from, Token.Type.MINUSASSIGN)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
'>' -> {
|
||||||
|
pos.advance()
|
||||||
|
Token("->", from, Token.Type.ARROW)
|
||||||
|
}
|
||||||
|
|
||||||
else -> Token("-", from, Token.Type.MINUS)
|
else -> Token("-", from, Token.Type.MINUS)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -101,6 +106,16 @@ private class Parser(fromPos: Pos) {
|
|||||||
Token(loadToEnd().trim(), from, Token.Type.SINLGE_LINE_COMMENT)
|
Token(loadToEnd().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()
|
pos.advance()
|
||||||
Token("/=", from, Token.Type.SLASHASSIGN)
|
Token("/=", from, Token.Type.SLASHASSIGN)
|
||||||
@@ -138,7 +153,13 @@ private class Parser(fromPos: Pos) {
|
|||||||
'<' -> {
|
'<' -> {
|
||||||
if (currentChar == '=') {
|
if (currentChar == '=') {
|
||||||
pos.advance()
|
pos.advance()
|
||||||
Token("<=", from, Token.Type.LTE)
|
if( currentChar == '>' ) {
|
||||||
|
pos.advance()
|
||||||
|
Token("<=>", from, Token.Type.SHUTTLE)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Token("<=", from, Token.Type.LTE)
|
||||||
|
}
|
||||||
} else
|
} else
|
||||||
Token("<", from, Token.Type.LT)
|
Token("<", from, Token.Type.LT)
|
||||||
}
|
}
|
||||||
@@ -159,10 +180,12 @@ private class Parser(fromPos: Pos) {
|
|||||||
pos.advance()
|
pos.advance()
|
||||||
Token("!in", from, Token.Type.NOTIN)
|
Token("!in", from, Token.Type.NOTIN)
|
||||||
}
|
}
|
||||||
|
|
||||||
's' -> {
|
's' -> {
|
||||||
pos.advance()
|
pos.advance()
|
||||||
Token("!is", from, Token.Type.NOTIS)
|
Token("!is", from, Token.Type.NOTIS)
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> {
|
else -> {
|
||||||
pos.back()
|
pos.back()
|
||||||
Token("!", from, Token.Type.NOT)
|
Token("!", from, Token.Type.NOT)
|
||||||
@@ -257,6 +280,8 @@ private class Parser(fromPos: Pos) {
|
|||||||
when (text) {
|
when (text) {
|
||||||
"in" -> Token("in", from, Token.Type.IN)
|
"in" -> Token("in", from, Token.Type.IN)
|
||||||
"is" -> Token("is", from, Token.Type.IS)
|
"is" -> Token("is", from, Token.Type.IS)
|
||||||
|
"protected" -> Token("protected", from, Token.Type.PROTECTED)
|
||||||
|
"private" -> Token("private", from, Token.Type.PRIVATE)
|
||||||
else -> Token(text, from, Token.Type.ID)
|
else -> Token(text, from, Token.Type.ID)
|
||||||
}
|
}
|
||||||
} else
|
} else
|
||||||
@@ -268,7 +293,19 @@ private class Parser(fromPos: Pos) {
|
|||||||
private fun decodeNumber(p1: String, start: Pos): Token =
|
private fun decodeNumber(p1: String, start: Pos): Token =
|
||||||
if (pos.end)
|
if (pos.end)
|
||||||
Token(p1, start, Token.Type.INT)
|
Token(p1, start, Token.Type.INT)
|
||||||
else if (currentChar == '.') {
|
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
|
// could be decimal
|
||||||
pos.advance()
|
pos.advance()
|
||||||
if (currentChar in digitsSet) {
|
if (currentChar in digitsSet) {
|
||||||
@@ -392,6 +429,15 @@ private class Parser(fromPos: Pos) {
|
|||||||
return result.toString()
|
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
|
* next non-whitespace char (newline are skipped too) or null if EOF
|
||||||
*/
|
*/
|
||||||
+17
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
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 {
|
||||||
@@ -16,6 +16,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)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -46,12 +47,15 @@ class MutablePos(private val from: Pos) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) return 0.toChar()
|
if (end) return 0.toChar()
|
||||||
@@ -60,6 +64,18 @@ class MutablePos(private val from: Pos) {
|
|||||||
else current[column]
|
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 {
|
init {
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
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(context: Context): Obj {
|
||||||
|
var lastResult: Obj = ObjVoid
|
||||||
|
for (s in statements) {
|
||||||
|
lastResult = s.execute(context)
|
||||||
|
}
|
||||||
|
return lastResult
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun execute() = execute(defaultContext.copy(pos = pos))
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val defaultContext: Context = Context().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()}"))
|
||||||
|
}
|
||||||
|
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("Real", ObjReal.type)
|
||||||
|
addConst("String", ObjString.type)
|
||||||
|
addConst("Int", ObjInt.type)
|
||||||
|
addConst("Bool", ObjBool.type)
|
||||||
|
addConst("Char", ObjChar.type)
|
||||||
|
addConst("List", ObjList.type)
|
||||||
|
addConst("Range", ObjRange.type)
|
||||||
|
@Suppress("RemoveRedundantQualifierName")
|
||||||
|
addConst("Callable", Statement.type)
|
||||||
|
// interfaces
|
||||||
|
addConst("Iterable", ObjIterable)
|
||||||
|
addConst("Array", ObjArray)
|
||||||
|
addConst("Class", ObjClassType)
|
||||||
|
addConst("Object", Obj().objClass)
|
||||||
|
|
||||||
|
val pi = ObjReal(PI)
|
||||||
|
addConst("π", pi)
|
||||||
|
getOrCreateNamespace("Math").apply {
|
||||||
|
addConst("PI", pi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-2
@@ -1,14 +1,15 @@
|
|||||||
@file:Suppress("CanBeParameter")
|
@file:Suppress("CanBeParameter")
|
||||||
|
|
||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
open class ScriptError(val pos: Pos, val errorMessage: String,cause: Throwable?=null) : Exception(
|
open class ScriptError(val pos: Pos, val errorMessage: String,cause: Throwable?=null) : Exception(
|
||||||
"""
|
"""
|
||||||
$pos: Error: $errorMessage
|
$pos: Error: $errorMessage
|
||||||
|
|
||||||
${pos.currentLine}
|
${pos.currentLine}
|
||||||
${"-".repeat(pos.column)}^
|
${"-".repeat(pos.column)}^
|
||||||
""".trimIndent(),
|
""".trimIndent(),
|
||||||
cause
|
cause
|
||||||
)
|
)
|
||||||
|
|
||||||
class ExecutionError(val errorObject: ObjError) : ScriptError(errorObject.context.pos, errorObject.message)
|
class ExecutionError(val errorObject: ObjException) : ScriptError(errorObject.context.pos, errorObject.message)
|
||||||
+2
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
class Source(val fileName: String, text: String) {
|
class Source(val fileName: String, text: String) {
|
||||||
|
|
||||||
@@ -6,6 +6,7 @@ class Source(val fileName: String, text: String) {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val builtIn: Source by lazy { Source("built-in", "") }
|
val builtIn: Source by lazy { Source("built-in", "") }
|
||||||
|
val UNKNOWN: Source by lazy { Source("UNKNOWN", "") }
|
||||||
}
|
}
|
||||||
|
|
||||||
val startPos: Pos = Pos(this, 0, 0)
|
val startPos: Pos = Pos(this, 0, 0)
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class Symbols(
|
||||||
|
unitType: UnitType,
|
||||||
|
val name: String,
|
||||||
|
val x: TypeDecl
|
||||||
|
) {
|
||||||
|
enum class UnitType {
|
||||||
|
Module, Function, Lambda
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
data class Token(val value: String, val pos: Pos, val type: Type) {
|
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 }
|
val isComment: Boolean by lazy { type == Type.SINLGE_LINE_COMMENT || type == Type.MULTILINE_COMMENT }
|
||||||
@@ -13,9 +13,12 @@ data class Token(val value: String, val pos: Pos, val type: Type) {
|
|||||||
PLUS2, MINUS2,
|
PLUS2, MINUS2,
|
||||||
IN, NOTIN, IS, NOTIS,
|
IN, NOTIN, IS, NOTIS,
|
||||||
EQ, NEQ, LT, LTE, GT, GTE, REF_EQ, REF_NEQ,
|
EQ, NEQ, LT, LTE, GT, GTE, REF_EQ, REF_NEQ,
|
||||||
|
SHUTTLE,
|
||||||
AND, BITAND, OR, BITOR, NOT, BITNOT, DOT, ARROW, QUESTION, COLONCOLON,
|
AND, BITAND, OR, BITOR, NOT, BITNOT, DOT, ARROW, QUESTION, COLONCOLON,
|
||||||
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
||||||
LABEL, ATLABEL, // label@ at@label
|
LABEL, ATLABEL, // label@ at@label
|
||||||
|
PRIVATE, PROTECTED,
|
||||||
|
//PUBLIC, PROTECTED, INTERNAL, EXPORT, OPEN, INLINE, OVERRIDE, ABSTRACT, SEALED, EXTERNAL, VAL, VAR, CONST, TYPE, FUN, CLASS, INTERFACE, ENUM, OBJECT, TRAIT, THIS,
|
||||||
ELLIPSIS, DOTDOT, DOTDOTLT,
|
ELLIPSIS, DOTDOT, DOTDOTLT,
|
||||||
NEWLINE,
|
NEWLINE,
|
||||||
EOF,
|
EOF,
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
sealed class TypeDecl {
|
||||||
|
// ??
|
||||||
|
data class Fn(val argTypes: List<ArgsDeclaration.Item>, val retType: TypeDecl) : TypeDecl()
|
||||||
|
object Obj : TypeDecl()
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
To use in the compiler, we need symbol information when:
|
||||||
|
|
||||||
|
- declaring a class: the only way to export its public/protected symbols is to know it in compiler time
|
||||||
|
- importing a module: actually, we cam try to do it in a more efficient way.
|
||||||
|
|
||||||
|
Importing module:
|
||||||
|
|
||||||
|
The moudule is efficiently a statement, that initializes it with all its symbols modifying some context.
|
||||||
|
|
||||||
|
The thing is, we need only
|
||||||
|
|
||||||
|
*/
|
||||||
@@ -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
|
||||||
+7
-1
@@ -1,4 +1,4 @@
|
|||||||
package net.sergeych.lying
|
package net.sergeych.lyng
|
||||||
|
|
||||||
fun String.toSource(name: String = "eval"): Source = Source(name, this)
|
fun String.toSource(name: String = "eval"): Source = Source(name, this)
|
||||||
|
|
||||||
@@ -15,6 +15,8 @@ abstract class Statement(
|
|||||||
val returnType: ObjType = ObjType.Any
|
val returnType: ObjType = ObjType.Any
|
||||||
) : Obj() {
|
) : Obj() {
|
||||||
|
|
||||||
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
abstract val pos: Pos
|
abstract val pos: Pos
|
||||||
abstract suspend fun execute(context: Context): Obj
|
abstract suspend fun execute(context: Context): Obj
|
||||||
|
|
||||||
@@ -28,6 +30,10 @@ abstract class Statement(
|
|||||||
|
|
||||||
override fun toString(): String = "Callable@${this.hashCode()}"
|
override fun toString(): String = "Callable@${this.hashCode()}"
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = ObjClass("Callable")
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Statement.raise(text: String): Nothing {
|
fun Statement.raise(text: String): Nothing {
|
||||||
@@ -1,18 +1,24 @@
|
|||||||
package io.github.kotlin.fibonacci
|
package io.github.kotlin.fibonacci
|
||||||
|
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import net.sergeych.lying.*
|
import net.sergeych.lyng.*
|
||||||
import kotlin.test.*
|
import kotlin.test.*
|
||||||
|
|
||||||
class ScriptTest {
|
class ScriptTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testVersion() {
|
||||||
|
println("--------------------------------------------")
|
||||||
|
println("version = ${LyngVersion}")
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun parseNewlines() {
|
fun parseNewlines() {
|
||||||
fun check(expected: String, type: Token.Type, row: Int, col: Int, src: String, offset: Int = 0) {
|
fun check(expected: String, type: Token.Type, row: Int, col: Int, src: String, offset: Int = 0) {
|
||||||
val source = src.toSource()
|
val source = src.toSource()
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Token(expected, source.posAt(row, col), type),
|
Token(expected, source.posAt(row, col), type),
|
||||||
parseLing(source)[offset]
|
parseLyng(source)[offset]
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
check("1", Token.Type.INT, 0, 0, "1 + x\n2", 0)
|
check("1", Token.Type.INT, 0, 0, "1 + x\n2", 0)
|
||||||
@@ -30,7 +36,7 @@ class ScriptTest {
|
|||||||
val source = src.toSource()
|
val source = src.toSource()
|
||||||
assertEquals(
|
assertEquals(
|
||||||
Token(expected, source.posAt(row, col), type),
|
Token(expected, source.posAt(row, col), type),
|
||||||
parseLing(source)[offset]
|
parseLyng(source)[offset]
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
check("1", Token.Type.INT, 0, 0, "1")
|
check("1", Token.Type.INT, 0, 0, "1")
|
||||||
@@ -51,6 +57,8 @@ class ScriptTest {
|
|||||||
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.2e22", Token.Type.REAL, 0, 0, "17.2E22")
|
||||||
check("17.2e-22", Token.Type.REAL, 0, 0, "17.2E-22")
|
check("17.2e-22", Token.Type.REAL, 0, 0, "17.2E-22")
|
||||||
|
check("17.2e-22", Token.Type.REAL, 0, 0, "17.2E-22")
|
||||||
|
check("1e-22", Token.Type.REAL, 0, 0, "1E-22")
|
||||||
|
|
||||||
// hex
|
// hex
|
||||||
check("1", Token.Type.HEX, 0, 0, "0x1")
|
check("1", Token.Type.HEX, 0, 0, "0x1")
|
||||||
@@ -66,13 +74,13 @@ class ScriptTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun parseRangeTest() {
|
fun parseRangeTest() {
|
||||||
var tt = parseLing("5 .. 4".toSource())
|
var tt = parseLyng("5 .. 4".toSource())
|
||||||
|
|
||||||
assertEquals(Token.Type.INT, tt[0].type)
|
assertEquals(Token.Type.INT, tt[0].type)
|
||||||
assertEquals(Token.Type.DOTDOT, tt[1].type)
|
assertEquals(Token.Type.DOTDOT, tt[1].type)
|
||||||
assertEquals(Token.Type.INT, tt[2].type)
|
assertEquals(Token.Type.INT, tt[2].type)
|
||||||
|
|
||||||
tt = parseLing("5 ..< 4".toSource())
|
tt = parseLyng("5 ..< 4".toSource())
|
||||||
|
|
||||||
assertEquals(Token.Type.INT, tt[0].type)
|
assertEquals(Token.Type.INT, tt[0].type)
|
||||||
assertEquals(Token.Type.DOTDOTLT, tt[1].type)
|
assertEquals(Token.Type.DOTDOTLT, tt[1].type)
|
||||||
@@ -81,13 +89,13 @@ class ScriptTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun parseInTest() {
|
fun parseInTest() {
|
||||||
var tt = parseLing("5 in 4".toSource())
|
var tt = parseLyng("5 in 4".toSource())
|
||||||
|
|
||||||
assertEquals(Token.Type.INT, tt[0].type)
|
assertEquals(Token.Type.INT, tt[0].type)
|
||||||
assertEquals(Token.Type.IN, tt[1].type)
|
assertEquals(Token.Type.IN, tt[1].type)
|
||||||
assertEquals(Token.Type.INT, tt[2].type)
|
assertEquals(Token.Type.INT, tt[2].type)
|
||||||
|
|
||||||
tt = parseLing("5 ..< 4".toSource())
|
tt = parseLyng("5 ..< 4".toSource())
|
||||||
|
|
||||||
assertEquals(Token.Type.INT, tt[0].type)
|
assertEquals(Token.Type.INT, tt[0].type)
|
||||||
assertEquals(Token.Type.DOTDOTLT, tt[1].type)
|
assertEquals(Token.Type.DOTDOTLT, tt[1].type)
|
||||||
@@ -97,7 +105,7 @@ class ScriptTest {
|
|||||||
@Test
|
@Test
|
||||||
fun parserLabelsTest() {
|
fun parserLabelsTest() {
|
||||||
val src = "label@ break@label".toSource()
|
val src = "label@ break@label".toSource()
|
||||||
val tt = parseLing(src)
|
val tt = parseLyng(src)
|
||||||
assertEquals(Token("label", src.posAt(0, 0), Token.Type.LABEL), tt[0])
|
assertEquals(Token("label", src.posAt(0, 0), Token.Type.LABEL), tt[0])
|
||||||
assertEquals(Token("break", src.posAt(0, 7), Token.Type.ID), tt[1])
|
assertEquals(Token("break", src.posAt(0, 7), Token.Type.ID), tt[1])
|
||||||
assertEquals(Token("label", src.posAt(0, 12), Token.Type.ATLABEL), tt[2])
|
assertEquals(Token("label", src.posAt(0, 12), Token.Type.ATLABEL), tt[2])
|
||||||
@@ -110,7 +118,7 @@ class ScriptTest {
|
|||||||
println( "world" )
|
println( "world" )
|
||||||
""".trimIndent().toSource()
|
""".trimIndent().toSource()
|
||||||
|
|
||||||
val p = parseLing(src).listIterator()
|
val p = parseLyng(src).listIterator()
|
||||||
|
|
||||||
assertEquals(Token("println", src.posAt(0, 0), Token.Type.ID), p.next())
|
assertEquals(Token("println", src.posAt(0, 0), Token.Type.ID), p.next())
|
||||||
assertEquals(Token("(", src.posAt(0, 7), Token.Type.LPAREN), p.next())
|
assertEquals(Token("(", src.posAt(0, 7), Token.Type.LPAREN), p.next())
|
||||||
@@ -127,7 +135,7 @@ class ScriptTest {
|
|||||||
fun parse1Test() {
|
fun parse1Test() {
|
||||||
val src = "2 + 7".toSource()
|
val src = "2 + 7".toSource()
|
||||||
|
|
||||||
val p = parseLing(src).listIterator()
|
val p = parseLyng(src).listIterator()
|
||||||
|
|
||||||
assertEquals(Token("2", src.posAt(0, 0), Token.Type.INT), p.next())
|
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("+", src.posAt(0, 2), Token.Type.PLUS), p.next())
|
||||||
@@ -166,7 +174,7 @@ class ScriptTest {
|
|||||||
fun varsAndConstsTest() = runTest {
|
fun varsAndConstsTest() = runTest {
|
||||||
val context = Context(pos = Pos.builtIn)
|
val context = Context(pos = Pos.builtIn)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
ObjVoid, context.eval(
|
ObjInt(3L), context.eval(
|
||||||
"""
|
"""
|
||||||
val a = 17
|
val a = 17
|
||||||
var b = 3
|
var b = 3
|
||||||
@@ -426,6 +434,18 @@ class ScriptTest {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun whileAssignTest() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var t = 0
|
||||||
|
val x = while( t < 5 ) { t++ }
|
||||||
|
// last returned value is 4 - when t was 5 body was not executed
|
||||||
|
assertEquals( 4, x )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun whileTest() = runTest {
|
fun whileTest() = runTest {
|
||||||
assertEquals(
|
assertEquals(
|
||||||
@@ -480,6 +500,146 @@ class ScriptTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAssignArgumentsNoEllipsis() = runTest {
|
||||||
|
// equal args, no ellipsis, no defaults, ok
|
||||||
|
val ttEnd = Token.Type.RBRACE
|
||||||
|
var pa = ArgsDeclaration(
|
||||||
|
listOf(
|
||||||
|
ArgsDeclaration.Item("a"),
|
||||||
|
ArgsDeclaration.Item("b"),
|
||||||
|
ArgsDeclaration.Item("c"),
|
||||||
|
), ttEnd
|
||||||
|
)
|
||||||
|
var c = Context(pos = Pos.builtIn, args = Arguments.from(listOf(1, 2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
assertEquals(ObjInt(1), c["a"]?.value)
|
||||||
|
assertEquals(ObjInt(2), c["b"]?.value)
|
||||||
|
assertEquals(ObjInt(3), c["c"]?.value)
|
||||||
|
// less args: error
|
||||||
|
c = Context(pos = Pos.builtIn, args = Arguments.from(listOf(1, 2).map { it.toObj() }))
|
||||||
|
assertFailsWith<ScriptError> {
|
||||||
|
pa.assignToContext(c)
|
||||||
|
}
|
||||||
|
// less args, no ellipsis, defaults, ok
|
||||||
|
pa = ArgsDeclaration(
|
||||||
|
listOf(
|
||||||
|
ArgsDeclaration.Item("a"),
|
||||||
|
ArgsDeclaration.Item("b"),
|
||||||
|
ArgsDeclaration.Item("c", defaultValue = statement { ObjInt(100) }),
|
||||||
|
), ttEnd
|
||||||
|
)
|
||||||
|
pa.assignToContext(c)
|
||||||
|
assertEquals(ObjInt(1), c["a"]?.value)
|
||||||
|
assertEquals(ObjInt(2), c["b"]?.value)
|
||||||
|
assertEquals(ObjInt(100), c["c"]?.value)
|
||||||
|
// enough args. default value is ignored:
|
||||||
|
c = Context(pos = Pos.builtIn, args = Arguments.from(listOf(10, 2, 5).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
assertEquals(ObjInt(10), c["a"]?.value)
|
||||||
|
assertEquals(ObjInt(2), c["b"]?.value)
|
||||||
|
assertEquals(ObjInt(5), c["c"]?.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAssignArgumentsEndEllipsis() = runTest {
|
||||||
|
// equal args,
|
||||||
|
// less args, no ellipsis, defaults, ok
|
||||||
|
val ttEnd = Token.Type.RBRACE
|
||||||
|
val pa = ArgsDeclaration(
|
||||||
|
listOf(
|
||||||
|
ArgsDeclaration.Item("a"),
|
||||||
|
ArgsDeclaration.Item("b", isEllipsis = true),
|
||||||
|
), ttEnd
|
||||||
|
)
|
||||||
|
var c = Context(args = Arguments.from(listOf(1, 2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assert( a == 1 ); println(b)")
|
||||||
|
c.eval("assert( b == [2,3] )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(1, 2).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assertEquals( a, 1 ); println(b)")
|
||||||
|
c.eval("assertEquals( b, [2] )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(1).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assert( a == 1 ); println(b)")
|
||||||
|
c.eval("assert( b == [] )")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAssignArgumentsStartEllipsis() = runTest {
|
||||||
|
val ttEnd = Token.Type.RBRACE
|
||||||
|
val pa = ArgsDeclaration(
|
||||||
|
listOf(
|
||||||
|
ArgsDeclaration.Item("a", isEllipsis = true),
|
||||||
|
ArgsDeclaration.Item("b"),
|
||||||
|
ArgsDeclaration.Item("c"),
|
||||||
|
), ttEnd
|
||||||
|
)
|
||||||
|
var c = Context(args = Arguments.from(listOf(0, 1, 2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assertEquals( a,[0,1] )")
|
||||||
|
c.eval("assertEquals( b, 2 )")
|
||||||
|
c.eval("assertEquals( c, 3 )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(1, 2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assertEquals( a,[1] )")
|
||||||
|
c.eval("assertEquals( b, 2 )")
|
||||||
|
c.eval("assertEquals( c, 3 )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assertEquals( a,[] )")
|
||||||
|
c.eval("assertEquals( b, 2 )")
|
||||||
|
c.eval("assertEquals( c, 3 )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(3).map { it.toObj() }))
|
||||||
|
assertFailsWith<ExecutionError> {
|
||||||
|
pa.assignToContext(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAssignArgumentsmiddleEllipsis() = runTest {
|
||||||
|
val ttEnd = Token.Type.RBRACE
|
||||||
|
val pa = ArgsDeclaration(
|
||||||
|
listOf(
|
||||||
|
ArgsDeclaration.Item("i"),
|
||||||
|
ArgsDeclaration.Item("a", isEllipsis = true),
|
||||||
|
ArgsDeclaration.Item("b"),
|
||||||
|
ArgsDeclaration.Item("c"),
|
||||||
|
), ttEnd
|
||||||
|
)
|
||||||
|
var c = Context(args = Arguments.from(listOf(-1, 0, 1, 2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assertEquals( i, -1 )")
|
||||||
|
c.eval("assertEquals( a,[0,1] )")
|
||||||
|
c.eval("assertEquals( b, 2 )")
|
||||||
|
c.eval("assertEquals( c, 3 )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(0, 1, 2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assertEquals( i, 0 )")
|
||||||
|
c.eval("assertEquals( a,[1] )")
|
||||||
|
c.eval("assertEquals( b, 2 )")
|
||||||
|
c.eval("assertEquals( c, 3 )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(1, 2, 3).map { it.toObj() }))
|
||||||
|
pa.assignToContext(c)
|
||||||
|
c.eval("assertEquals( i, 1)")
|
||||||
|
c.eval("assertEquals( a,[] )")
|
||||||
|
c.eval("assertEquals( b, 2 )")
|
||||||
|
c.eval("assertEquals( c, 3 )")
|
||||||
|
|
||||||
|
c = Context(args = Arguments.from(listOf(2, 3).map { it.toObj() }))
|
||||||
|
assertFailsWith<ExecutionError> {
|
||||||
|
pa.assignToContext(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testWhileBlockIsolation1() = runTest {
|
fun testWhileBlockIsolation1() = runTest {
|
||||||
eval(
|
eval(
|
||||||
@@ -1039,16 +1199,638 @@ class ScriptTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLambdaWithIt1() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val x = {
|
||||||
|
it + "!"
|
||||||
|
}
|
||||||
|
val y = if( 4 < 3 ) "NG" else "OK"
|
||||||
|
assert( x::class == Callable)
|
||||||
|
assert( x is Callable)
|
||||||
|
assert(y == "OK")
|
||||||
|
assert( x("hello") == "hello!")
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLambdaWithIt2() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val x = {
|
||||||
|
assert(it == void)
|
||||||
|
}
|
||||||
|
assert( x() == void)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLambdaWithIt3() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val x = {
|
||||||
|
assert( it == [1,2,"end"])
|
||||||
|
}
|
||||||
|
println("0----")
|
||||||
|
assert( x(1, 2, "end") == void)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLambdaWithArgs() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val x = { x, y, z ->
|
||||||
|
assert( [x, y, z] == [1,2,"end"])
|
||||||
|
}
|
||||||
|
assert( x(1, 2, "end") == void)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLambdaWithArgsEllipsis() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val x = { x, y... ->
|
||||||
|
println("-- y=",y)
|
||||||
|
println(":: "+y::class)
|
||||||
|
assert( [x, ...y] == [1,2,"end"])
|
||||||
|
}
|
||||||
|
assert( x(1, 2, "end") == void)
|
||||||
|
assert( x(1, ...[2, "end"]) == void)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLambdaWithBadArgs() = runTest {
|
||||||
|
assertFails {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val x = { x, y ->
|
||||||
|
void
|
||||||
|
}
|
||||||
|
assert( x(1, 2) == void)
|
||||||
|
assert( x(1, ...[2, "end"]) == void)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testWhileExecuteElseIfNotExecuted() = runTest {
|
||||||
|
assertEquals(
|
||||||
|
"ok",
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
while( 5 < 1 ) {
|
||||||
|
"bad"
|
||||||
|
} else "ok"
|
||||||
|
""".trimIndent()
|
||||||
|
).toString()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIsPrimeSampleBug() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun naive_is_prime(candidate) {
|
||||||
|
val x = if( candidate !is Int) candidate.toInt() else candidate
|
||||||
|
var divisor = 1
|
||||||
|
println("start with ",x)
|
||||||
|
while( ++divisor < x/2 && divisor != 2 ) {
|
||||||
|
println("x=", x, " // ", divisor, " :: ", x % divisor)
|
||||||
|
if( x % divisor == 0 ) break false
|
||||||
|
}
|
||||||
|
else true
|
||||||
|
}
|
||||||
|
naive_is_prime(4)
|
||||||
|
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLambdaAsFnCallArg() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun mapValues(iterable, transform) {
|
||||||
|
println("start: ", transform)
|
||||||
|
var result = []
|
||||||
|
for( x in iterable ) result += transform(x)
|
||||||
|
}
|
||||||
|
assert( [11, 21, 31] == mapValues( if( true) [1,2,3] else [10], { it*10+1 }))
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testNewFnParser() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun f1(a,b) { a + b }
|
||||||
|
println(f1(1,2))
|
||||||
|
assertEquals( 7, f1(3,4) )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSpoilArgsBug() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun fnb(a,b) { a + b }
|
||||||
|
|
||||||
|
fun fna(a, b) {
|
||||||
|
val a0 = a
|
||||||
|
val b0 = b
|
||||||
|
fnb(a + 1, b + 1)
|
||||||
|
assert( a0 == a )
|
||||||
|
assert( b0 == b )
|
||||||
|
}
|
||||||
|
|
||||||
|
fna(5,6)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSpoilLamdaArgsBug() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val fnb = { a,b -> a + b }
|
||||||
|
|
||||||
|
val fna = { a, b ->
|
||||||
|
val a0 = a
|
||||||
|
val b0 = b
|
||||||
|
fnb(a + 1, b + 1)
|
||||||
|
assert( a0 == a )
|
||||||
|
assert( b0 == b )
|
||||||
|
}
|
||||||
|
|
||||||
|
fna(5,6)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun commentBlocksShouldNotAlterBehavior() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun test() {
|
||||||
|
10
|
||||||
|
/*
|
||||||
|
*/
|
||||||
|
//val x = 11
|
||||||
|
}
|
||||||
|
assert( test() == 10 )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testShuttle() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
assert( 5 <=> 3 > 0 )
|
||||||
|
assert( 0 < 5 <=> 3 )
|
||||||
|
assert( 5 <=> 5 == 0 )
|
||||||
|
assert( 5 <=> 7 < 0 )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSimpleStruct() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
class Point(x,y)
|
||||||
|
assert( Point::class is Class )
|
||||||
|
val p = Point(2,3)
|
||||||
|
assert(p is Point)
|
||||||
|
println(p)
|
||||||
|
println(p.x)
|
||||||
|
assert( p.x == 2 )
|
||||||
|
assert( p.y == 3 )
|
||||||
|
|
||||||
|
val p2 = Point(p.x+1,p.y+1)
|
||||||
|
p.x = 0
|
||||||
|
assertEquals( 0, p.x )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testNonAssignalbeFieldInStruct() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
class Point(x,y)
|
||||||
|
val p = Point("2",3)
|
||||||
|
assert(p is Point)
|
||||||
|
assert( p.x == "2" )
|
||||||
|
assert( p.y == 3 )
|
||||||
|
|
||||||
|
p.x = 0
|
||||||
|
assertEquals( 0, p.x )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStructBodyVal() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
class Point(x,y) {
|
||||||
|
val length = sqrt(x*x+y*y)
|
||||||
|
var foo = "zero"
|
||||||
|
}
|
||||||
|
val p = Point(3,4)
|
||||||
|
assertEquals(5, p.length)
|
||||||
|
assertEquals("zero", p.foo)
|
||||||
|
p.y = 10
|
||||||
|
p.foo = "bar"
|
||||||
|
assert( p.y == 10 )
|
||||||
|
assert( p.foo == "bar")
|
||||||
|
// length is a val, is shoud not change
|
||||||
|
assert( p.length == 5 )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStructBodyFun() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
class Point(x,y) {
|
||||||
|
fun length() {
|
||||||
|
sqrt(x*x+y*y)
|
||||||
|
}
|
||||||
|
var foo = "zero"
|
||||||
|
}
|
||||||
|
val p = Point(3,4)
|
||||||
|
assertEquals(5, p.length())
|
||||||
|
p.y = 10
|
||||||
|
println(p.length())
|
||||||
|
assertEquals(sqrt(109), p.length())
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPrivateConstructorParams() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
c.eval(
|
||||||
|
"""
|
||||||
|
class Point(private var x,y)
|
||||||
|
val p = Point(1,2)
|
||||||
|
p.y = 101
|
||||||
|
assertThrows { p.x = 10 }
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLBraceMethodCall() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class Foo() {
|
||||||
|
fun cond(block) {
|
||||||
|
block()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val f = Foo()
|
||||||
|
assertEquals( 1, f.cond { 1 } )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLBraceFnCall() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun cond(block) {
|
||||||
|
block()
|
||||||
|
}
|
||||||
|
assertEquals( 1, cond { 1 } )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testClasstoString() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class Point {
|
||||||
|
var x
|
||||||
|
var y
|
||||||
|
}
|
||||||
|
val p = Point()
|
||||||
|
p.x = 1
|
||||||
|
p.y = 2
|
||||||
|
println(p)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testClassDefaultCompare() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
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) )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAccessShortcuts() {
|
||||||
|
assertTrue(Visibility.Public.isPublic)
|
||||||
|
assertFalse(Visibility.Private.isPublic)
|
||||||
|
assertFalse(Visibility.Protected.isPublic)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun segfault1Test() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
|
||||||
|
fun findSumLimit(f) {
|
||||||
|
var sum = 0.0
|
||||||
|
for( n in 1..1000000 ) {
|
||||||
|
val s0 = sum
|
||||||
|
sum += f(n)
|
||||||
|
if( abs(sum - s0) < 0.00001 ) {
|
||||||
|
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)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIntExponentRealForm() = runTest {
|
||||||
|
assertEquals("1.0E-6", eval("1e-6").toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCallLastBlockAfterDetault() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
// this means last is lambda:
|
||||||
|
fun f(e=1, f) {
|
||||||
|
"e="+e+"f="+f()
|
||||||
|
}
|
||||||
|
assertEquals("e=1f=xx", f { "xx" })
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCallLastBlockWithEllipsis() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
// this means last is lambda:
|
||||||
|
fun f(e..., f) {
|
||||||
|
"e="+e+"f="+f()
|
||||||
|
}
|
||||||
|
assertEquals("e=[]f=xx", f { "xx" })
|
||||||
|
assertEquals("e=[1, 2]f=xx", f(1,2) { "xx" })
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMethodCallLastBlockAfterDefault() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class Foo {
|
||||||
|
// this means last is lambda:
|
||||||
|
fun f(e=1, f) {
|
||||||
|
"e="+e+"f="+f()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val f = Foo()
|
||||||
|
assertEquals("e=1f=xx", f.f { "xx" })
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMethodCallLastBlockWithEllipsis() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class Foo {
|
||||||
|
// this means last is lambda:
|
||||||
|
fun f(e..., f) {
|
||||||
|
"e="+e+"f="+f()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val f = Foo()
|
||||||
|
assertEquals("e=[]f=xx", f.f { "xx" })
|
||||||
|
assertEquals("e=[1, 2]f=xx", f.f(1,2) { "xx" })
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nationalCharsTest() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun сумма_ряда(x, погрешность=0.0001, f) {
|
||||||
|
var сумма = 0
|
||||||
|
for( n in 1..100000) {
|
||||||
|
val следующая_сумма = сумма + f(x, n)
|
||||||
|
if( n > 1 && abs(следующая_сумма - сумма) < погрешность )
|
||||||
|
break следующая_сумма
|
||||||
|
сумма = следующая_сумма
|
||||||
|
}
|
||||||
|
else null
|
||||||
|
}
|
||||||
|
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 )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun doWhileSimpleTest() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var sum = 0
|
||||||
|
var x = do {
|
||||||
|
val s = sum
|
||||||
|
sum += 1
|
||||||
|
} while( s < 10 )
|
||||||
|
assertEquals(11, x)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testFailDoWhileSample1() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun readLine() { "done: result" }
|
||||||
|
val result = do {
|
||||||
|
val line = readLine()
|
||||||
|
} while( !line.startsWith("done:") )
|
||||||
|
assertEquals("result", result.drop(6))
|
||||||
|
result
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testForContinue() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var x = 0
|
||||||
|
for( i in 1..10 ) {
|
||||||
|
if( i % 2 == 0 ) continue
|
||||||
|
println(i)
|
||||||
|
x++
|
||||||
|
}
|
||||||
|
assertEquals(5, x)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testForLabelNreakTest() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
var x = 0
|
||||||
|
var y = 0
|
||||||
|
FOR0@ for( i in 1..10 ) {
|
||||||
|
x = i
|
||||||
|
for( j in 1..20 ) {
|
||||||
|
y = j
|
||||||
|
if( i == 3 && j == 5 ) {
|
||||||
|
println("bb")
|
||||||
|
break@FOR0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals( 5, y )
|
||||||
|
assertEquals( 3, x )
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testThrowExisting()= runTest {
|
||||||
|
eval("""
|
||||||
|
val x = IllegalArgumentException("test")
|
||||||
|
assert( x is Exception )
|
||||||
|
|
||||||
|
var t = 0
|
||||||
|
var finallyCaught = false
|
||||||
|
try {
|
||||||
|
t = 1
|
||||||
|
throw x
|
||||||
|
t = 2
|
||||||
|
}
|
||||||
|
catch( e: SymbolNotDefinedException ) {
|
||||||
|
t = 101
|
||||||
|
}
|
||||||
|
catch( e: IllegalArgumentException ) {
|
||||||
|
t = 3
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
finallyCaught = true
|
||||||
|
}
|
||||||
|
assertEquals(3, t)
|
||||||
|
assert(finallyCaught)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCatchShort1()= runTest {
|
||||||
|
eval("""
|
||||||
|
val x = IllegalArgumentException("test")
|
||||||
|
var t = 0
|
||||||
|
var finallyCaught = false
|
||||||
|
try {
|
||||||
|
t = 1
|
||||||
|
throw x
|
||||||
|
t = 2
|
||||||
|
}
|
||||||
|
catch(e) {
|
||||||
|
t = 31
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
finallyCaught = true
|
||||||
|
}
|
||||||
|
assertEquals(31, t)
|
||||||
|
assert(finallyCaught)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCatchShort2()= runTest {
|
||||||
|
eval("""
|
||||||
|
val x = IllegalArgumentException("test")
|
||||||
|
var caught = null
|
||||||
|
try {
|
||||||
|
throw x
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
caught = it
|
||||||
|
}
|
||||||
|
assert( caught is IllegalArgumentException )
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAccessEHData() = runTest {
|
||||||
|
eval("""
|
||||||
|
val x = IllegalArgumentException("test")
|
||||||
|
val m = try {
|
||||||
|
throw x
|
||||||
|
null
|
||||||
|
}
|
||||||
|
catch(e) {
|
||||||
|
println(e)
|
||||||
|
println(e::class)
|
||||||
|
println(e.message)
|
||||||
|
println("--------------")
|
||||||
|
e.message
|
||||||
|
}
|
||||||
|
println(m)
|
||||||
|
assert( m == "test" )
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
// @Test
|
|
||||||
// fun testLambda1() = runTest {
|
|
||||||
// val l = eval("""
|
|
||||||
// x = {
|
|
||||||
// 122
|
|
||||||
// }
|
|
||||||
// x
|
|
||||||
// """.trimIndent())
|
|
||||||
// println(l)
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
}
|
}
|
||||||
@@ -3,10 +3,13 @@ import kotlinx.coroutines.flow.Flow
|
|||||||
import kotlinx.coroutines.flow.flow
|
import kotlinx.coroutines.flow.flow
|
||||||
import kotlinx.coroutines.flow.flowOn
|
import kotlinx.coroutines.flow.flowOn
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import net.sergeych.lying.Context
|
import net.sergeych.lyng.Context
|
||||||
import net.sergeych.lying.ObjVoid
|
import net.sergeych.lyng.ObjVoid
|
||||||
|
import java.nio.file.Files
|
||||||
import java.nio.file.Files.readAllLines
|
import java.nio.file.Files.readAllLines
|
||||||
import java.nio.file.Paths
|
import java.nio.file.Paths
|
||||||
|
import kotlin.io.path.absolutePathString
|
||||||
|
import kotlin.io.path.extension
|
||||||
import kotlin.test.Test
|
import kotlin.test.Test
|
||||||
import kotlin.test.assertEquals
|
import kotlin.test.assertEquals
|
||||||
import kotlin.test.fail
|
import kotlin.test.fail
|
||||||
@@ -29,25 +32,34 @@ data class DocTest(
|
|||||||
val code: String,
|
val code: String,
|
||||||
val expectedOutput: String,
|
val expectedOutput: String,
|
||||||
val expectedResult: String,
|
val expectedResult: String,
|
||||||
val expectedError: String? = null
|
val expectedError: String? = null,
|
||||||
|
val bookMode: Boolean = false
|
||||||
) {
|
) {
|
||||||
val sourceLines by lazy { code.lines() }
|
val sourceLines by lazy { code.lines() }
|
||||||
|
|
||||||
|
val fileNamePart by lazy {
|
||||||
|
Paths.get(fileName).fileName.toString()
|
||||||
|
}
|
||||||
|
|
||||||
override fun toString(): String {
|
override fun toString(): String {
|
||||||
return "DocTest:$fileName:${line + 1}..${line + sourceLines.size}"
|
val absPath = Paths.get(fileName).absolutePathString()
|
||||||
|
return "DocTest: $absPath:${line + 1}"
|
||||||
}
|
}
|
||||||
|
|
||||||
val detailedString by lazy {
|
val detailedString by lazy {
|
||||||
val codeWithLines = sourceLines.withIndex().map { (i, s) -> "${i + line + 1}: $s" }.joinToString("\n")
|
val codeWithLines = sourceLines.withIndex().map { (i, s) -> "${i + line + 1}: $s" }.joinToString("\n")
|
||||||
var result = "$this\n$codeWithLines\n"
|
var result = "$this\n$codeWithLines\n"
|
||||||
if (expectedOutput.isNotBlank())
|
if( !bookMode) {
|
||||||
result += "--------expected output--------\n$expectedOutput\n"
|
if (expectedOutput.isNotBlank())
|
||||||
|
result += "--------expected output--------\n$expectedOutput\n"
|
||||||
|
|
||||||
"$result-----expected return value-----\n$expectedResult"
|
"$result-----expected return value-----\n$expectedResult"
|
||||||
|
}
|
||||||
|
else result
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun parseDocTests(fileName: String): Flow<DocTest> = flow {
|
fun parseDocTests(fileName: String, bookMode: Boolean = false): Flow<DocTest> = flow {
|
||||||
val book = readAllLines(Paths.get(fileName))
|
val book = readAllLines(Paths.get(fileName))
|
||||||
var startOffset = 0
|
var startOffset = 0
|
||||||
val block = mutableListOf<String>()
|
val block = mutableListOf<String>()
|
||||||
@@ -74,6 +86,18 @@ fun parseDocTests(fileName: String): Flow<DocTest> = flow {
|
|||||||
} while (initial - leftMargin(x) != startOffset)
|
} while (initial - leftMargin(x) != startOffset)
|
||||||
block[i] = x
|
block[i] = x
|
||||||
}
|
}
|
||||||
|
if (bookMode) {
|
||||||
|
emit(
|
||||||
|
DocTest(
|
||||||
|
fileName, startIndex,
|
||||||
|
block.joinToString("\n"),
|
||||||
|
"",
|
||||||
|
"",
|
||||||
|
null,
|
||||||
|
bookMode = true
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
// println(block.joinToString("\n") { "${startIndex + ii++}: $it" })
|
// println(block.joinToString("\n") { "${startIndex + ii++}: $it" })
|
||||||
val outStart = block.indexOfFirst { it.startsWith(">>>") }
|
val outStart = block.indexOfFirst { it.startsWith(">>>") }
|
||||||
if (outStart < 0) {
|
if (outStart < 0) {
|
||||||
@@ -134,13 +158,19 @@ fun parseDocTests(fileName: String): Flow<DocTest> = flow {
|
|||||||
}
|
}
|
||||||
.flowOn(Dispatchers.IO)
|
.flowOn(Dispatchers.IO)
|
||||||
|
|
||||||
suspend fun DocTest.test() {
|
suspend fun DocTest.test(context: Context = Context()) {
|
||||||
val collectedOutput = StringBuilder()
|
val collectedOutput = StringBuilder()
|
||||||
val context = Context().apply {
|
val currentTest = this
|
||||||
|
context.apply {
|
||||||
addFn("println") {
|
addFn("println") {
|
||||||
for ((i, a) in args.withIndex()) {
|
if( bookMode ) {
|
||||||
if (i > 0) collectedOutput.append(' '); collectedOutput.append(a.asStr.value)
|
println("${currentTest.fileNamePart}:${currentTest.line}> ${args.joinToString(" "){it.asStr.value}}")
|
||||||
collectedOutput.append('\n')
|
}
|
||||||
|
else {
|
||||||
|
for ((i, a) in args.withIndex()) {
|
||||||
|
if (i > 0) collectedOutput.append(' '); collectedOutput.append(a.asStr.value)
|
||||||
|
collectedOutput.append('\n')
|
||||||
|
}
|
||||||
}
|
}
|
||||||
ObjVoid
|
ObjVoid
|
||||||
}
|
}
|
||||||
@@ -153,24 +183,39 @@ suspend fun DocTest.test() {
|
|||||||
null
|
null
|
||||||
}?.inspect()?.replace(Regex("@\\d+"), "@...")
|
}?.inspect()?.replace(Regex("@\\d+"), "@...")
|
||||||
|
|
||||||
if (error != null || expectedOutput != collectedOutput.toString() ||
|
if (bookMode) {
|
||||||
expectedResult != result
|
if (error != null) {
|
||||||
) {
|
println("Sample failed: ${this.detailedString}")
|
||||||
println("Test failed: ${this.detailedString}")
|
fail("book sample failed", error)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (error != null || expectedOutput != collectedOutput.toString() ||
|
||||||
|
expectedResult != result
|
||||||
|
) {
|
||||||
|
System.err.println("\nfailed: ${this.detailedString}")
|
||||||
|
}
|
||||||
|
error?.let {
|
||||||
|
fail(it.message, it)
|
||||||
|
}
|
||||||
|
assertEquals(expectedOutput, collectedOutput.toString(), "script output do not match")
|
||||||
|
assertEquals(expectedResult, result.toString(), "script result does not match")
|
||||||
|
// println("OK: $this")
|
||||||
}
|
}
|
||||||
error?.let {
|
|
||||||
fail(it.toString(), it)
|
|
||||||
}
|
|
||||||
assertEquals(expectedOutput, collectedOutput.toString(), "script output do not match")
|
|
||||||
assertEquals(expectedResult, result.toString(), "script result does not match")
|
|
||||||
// println("OK: $this")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun runDocTests(fileName: String) {
|
suspend fun runDocTests(fileName: String, bookMode: Boolean = false) {
|
||||||
parseDocTests(fileName).collect { dt ->
|
val bookContext = Context()
|
||||||
dt.test()
|
var count = 0
|
||||||
|
parseDocTests(fileName, bookMode).collect { dt ->
|
||||||
|
if (bookMode) dt.test(bookContext)
|
||||||
|
else dt.test()
|
||||||
|
count++
|
||||||
}
|
}
|
||||||
|
print("completed mdtest: $fileName; ")
|
||||||
|
if (bookMode)
|
||||||
|
println("fragments processed: $count")
|
||||||
|
else
|
||||||
|
println("tests passed: $count")
|
||||||
}
|
}
|
||||||
|
|
||||||
class BookTest {
|
class BookTest {
|
||||||
@@ -210,4 +255,22 @@ class BookTest {
|
|||||||
runDocTests("../docs/Range.md")
|
runDocTests("../docs/Range.md")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSampleBooks() = runTest {
|
||||||
|
for (bt in Files.list(Paths.get("../docs/samples")).toList()) {
|
||||||
|
if (bt.extension == "md") {
|
||||||
|
runDocTests(bt.toString(), bookMode = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testArgumentBooks() = runTest {
|
||||||
|
runDocTests("../docs/declaring_arguments.md")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testExceptionsBooks() = runTest {
|
||||||
|
runDocTests("../docs/exceptions_handling.md")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import net.sergeych.lyng.Context
|
||||||
|
import java.nio.file.Files
|
||||||
|
import java.nio.file.Paths
|
||||||
|
import kotlin.io.path.extension
|
||||||
|
import kotlin.test.Test
|
||||||
|
|
||||||
|
suspend fun executeSampleTests(fileName: String) {
|
||||||
|
val sample = withContext(Dispatchers.IO) {
|
||||||
|
Files.readString(Paths.get(fileName))
|
||||||
|
}
|
||||||
|
runBlocking {
|
||||||
|
val c = Context()
|
||||||
|
val start = Clock.System.now()
|
||||||
|
c.eval(sample)
|
||||||
|
val time = Clock.System.now() - start
|
||||||
|
println("$time: $fileName")
|
||||||
|
// delay(100)
|
||||||
|
// }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class SamplesTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSamples() = runBlocking {
|
||||||
|
for (s in Files.list(Paths.get("../docs/samples"))) {
|
||||||
|
if (s.extension == "lyng") executeSampleTests(s.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
-1
@@ -7,10 +7,20 @@ version = "unspecified"
|
|||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
mavenCentral()
|
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 {
|
kotlin {
|
||||||
jvm()
|
jvm {
|
||||||
|
binaries {
|
||||||
|
executable {
|
||||||
|
mainClass.set("net.sergeych.lyng_cli.MainKt")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
linuxX64 {
|
linuxX64 {
|
||||||
binaries {
|
binaries {
|
||||||
executable()
|
executable()
|
||||||
@@ -18,11 +28,21 @@ kotlin {
|
|||||||
}
|
}
|
||||||
sourceSets {
|
sourceSets {
|
||||||
val commonMain by getting {
|
val commonMain by getting {
|
||||||
|
dependencies {
|
||||||
|
implementation(project(":library"))
|
||||||
|
implementation(libs.okio)
|
||||||
|
|
||||||
|
implementation(libs.clikt)
|
||||||
|
|
||||||
|
// optional support for rendering markdown in help messages
|
||||||
|
// implementation(libs.clikt.markdown)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
val commonTest by getting {
|
val commonTest by getting {
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(kotlin("test-common"))
|
implementation(kotlin("test-common"))
|
||||||
implementation(kotlin("test-annotations-common"))
|
implementation(kotlin("test-annotations-common"))
|
||||||
|
implementation(libs.okio.fakefilesystem)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val linuxX64Main by getting {
|
val linuxX64Main by getting {
|
||||||
|
|||||||
@@ -1,7 +1,110 @@
|
|||||||
package net.sergeych
|
package net.sergeych
|
||||||
|
|
||||||
|
import com.github.ajalt.clikt.core.CliktCommand
|
||||||
|
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 net.sergeych.lyng.*
|
||||||
|
import okio.FileSystem
|
||||||
|
import okio.Path.Companion.toPath
|
||||||
|
import okio.SYSTEM
|
||||||
|
import okio.buffer
|
||||||
|
import okio.use
|
||||||
|
|
||||||
// common code
|
// common code
|
||||||
|
|
||||||
fun commonCode() {
|
expect fun exit(code: Int)
|
||||||
println("Common code")
|
|
||||||
|
val baseContext = Context().apply {
|
||||||
|
addFn("exit") {
|
||||||
|
exit(requireOnlyArg<ObjInt>().toInt())
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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: com.github.ajalt.clikt.core.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
|
||||||
|
baseContext.addConst(
|
||||||
|
"ARGV", ObjList(
|
||||||
|
objargs.map { ObjString(it) }.toMutableList()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
launcher {
|
||||||
|
// there is no script name, it is a first argument instead:
|
||||||
|
processErrors {
|
||||||
|
baseContext.eval(execute!!)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
if (script == null) {
|
||||||
|
println(
|
||||||
|
"""
|
||||||
|
|
||||||
|
Error: no script specified.
|
||||||
|
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
echoFormattedHelp()
|
||||||
|
} else {
|
||||||
|
baseContext.addConst("ARGV", ObjList(args.map { ObjString(it) }.toMutableList()))
|
||||||
|
launcher { executeFile(script!!) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun executeFile(fileName: String) {
|
||||||
|
val text = FileSystem.SYSTEM.source(fileName.toPath()).use { fileSource ->
|
||||||
|
fileSource.buffer().use { bs ->
|
||||||
|
bs.readUtf8()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
processErrors {
|
||||||
|
Compiler().compile(Source(fileName, text)).execute(baseContext)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
import net.sergeych.commonCode
|
|
||||||
|
|
||||||
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
|
|
||||||
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
|
|
||||||
fun main() {
|
|
||||||
val name = "Kotlin"
|
|
||||||
//TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
|
|
||||||
// to see how GIGA IDE suggests fixing it.
|
|
||||||
println("Hello, native " + name + "!")
|
|
||||||
|
|
||||||
commonCode()
|
|
||||||
|
|
||||||
for (i in 1..5) {
|
|
||||||
//TIP Press <shortcut actionId="Debug"/> to start debugging your code. We have set one <icon src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint
|
|
||||||
// for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>.
|
|
||||||
println("i = $i")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package net.sergeych.lyng_cli
|
||||||
|
|
||||||
|
import com.github.ajalt.clikt.core.main
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import net.sergeych.Lyng
|
||||||
|
|
||||||
|
fun main(args: Array<String>) {
|
||||||
|
Lyng({ runBlocking { it() } }).main(args)
|
||||||
|
}
|
||||||
@@ -1,18 +1,7 @@
|
|||||||
import net.sergeych.commonCode
|
import com.github.ajalt.clikt.core.main
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import net.sergeych.Lyng
|
||||||
|
|
||||||
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
|
fun main(args: Array<String>) {
|
||||||
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
|
Lyng( { runBlocking { it() } }).main(args)
|
||||||
fun main() {
|
|
||||||
val name = "Kotlin"
|
|
||||||
//TIP Press <shortcut actionId="ShowIntentionActions"/> with your caret at the highlighted text
|
|
||||||
// to see how GIGA IDE suggests fixing it.
|
|
||||||
println("Hello, native " + name + "!")
|
|
||||||
|
|
||||||
commonCode()
|
|
||||||
|
|
||||||
for (i in 1..5) {
|
|
||||||
//TIP Press <shortcut actionId="Debug"/> to start debugging your code. We have set one <icon src="AllIcons.Debugger.Db_set_breakpoint"/> breakpoint
|
|
||||||
// for you, but you can always add more by pressing <shortcut actionId="ToggleLineBreakpoint"/>.
|
|
||||||
println("i = $i")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package net.sergeych
|
||||||
|
|
||||||
|
import kotlin.system.exitProcess
|
||||||
|
|
||||||
|
actual fun exit(code: Int) {
|
||||||
|
exitProcess(code)
|
||||||
|
}
|
||||||
Reference in new issue
Block a user