Compare commits
18
Commits
aba122c3e6
..
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
323c455a50 | ||
|
|
370d8cf605 | ||
|
|
f338c54632 | ||
|
|
3ef80616d8 | ||
|
|
961228ca0b | ||
|
|
56e0d2fd63 | ||
|
|
33fdb0934a | ||
|
|
60384060bf | ||
|
|
d3f23be7fe | ||
|
|
397dcaae92 | ||
|
|
2b87845a40 | ||
|
|
5591a66af3 | ||
|
|
9a08da0dfd | ||
|
|
71a2933066 | ||
|
|
4dc73b91c2 | ||
|
|
c0cf190452 | ||
|
|
306a7f26ef | ||
|
|
823e9a6498 |
No files matched your search
@@ -1,14 +1,32 @@
|
|||||||
# Lyng: scripting lang for kotlin multiplatform
|
# Lyng: modern scripting for kotlin multiplatform
|
||||||
|
|
||||||
in the form of multiplatform library. Key benefits:
|
A KMP library and a standalone interpreter
|
||||||
|
|
||||||
- async and multithreaded (on JVM and native) out of the box
|
- simple, compact, intuitive and elegant modern code style:
|
||||||
- easy and efficient kotlin integration
|
|
||||||
- dynamic types yet with good checks
|
|
||||||
|
|
||||||
__current state of implementation and docs__:
|
```
|
||||||
|
class Point(x,y) {
|
||||||
|
fun dist() { sqrt(x*x + y*y) }
|
||||||
|
}
|
||||||
|
Point(3,4).dist() //< 5
|
||||||
|
```
|
||||||
|
|
||||||
- [introduction and tutorial](docs/tutorial.md)
|
- extremely simple Kotlin integration on any platform
|
||||||
|
- 100% secure: no access to any API you didn't explicitly provide
|
||||||
|
- 100% coroutines! Every function/script is a coroutine, it does not block the thread, no async/await/suspend keyword garbage:
|
||||||
|
|
||||||
|
```
|
||||||
|
delay(1.5) // coroutine is delayed for 1.5s, thread is not blocked!
|
||||||
|
```
|
||||||
|
and it is multithreaded on platforms supporting it (automatically, no code changes required, just
|
||||||
|
`launch` more coroutines and they will be executed concurrently if possible)/
|
||||||
|
|
||||||
|
- functional style and OOP together, multiple inheritance, implementing interfaces for existing classes, writing extensions.
|
||||||
|
- Any unicode letters can be used as identifiers: `assert( sin(π/2) == 1 )`.
|
||||||
|
|
||||||
|
## Resources:
|
||||||
|
|
||||||
|
- [introduction and tutorial](docs/tutorial.md) - start here please
|
||||||
- [Samples directory](docs/samples)
|
- [Samples directory](docs/samples)
|
||||||
|
|
||||||
## Integration in Kotlin multiplatform
|
## Integration in Kotlin multiplatform
|
||||||
@@ -31,6 +49,7 @@ Script is executed over some `Context`. Create instance of the context,
|
|||||||
add your specific vars and functions to it, an call over it:
|
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
|
||||||
@@ -38,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.
|
||||||
|
|||||||
+39
@@ -70,3 +70,42 @@ 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)
|
||||||
|
|
||||||
|
# Defining a new class
|
||||||
|
|
||||||
|
The class is a some data record with named fields and fixed order, in fact. To define a class,
|
||||||
|
just Provide a name and a record like this:
|
||||||
|
|
||||||
|
// creating new class with main constructor
|
||||||
|
// with all fields public and mutable:
|
||||||
|
|
||||||
|
struct Point(x,y)
|
||||||
|
assert( Point is Class )
|
||||||
|
|
||||||
|
// now we can create instance
|
||||||
|
val p1 = Point(3,4)
|
||||||
|
|
||||||
|
// is is of the newly created type:
|
||||||
|
assert( p1 is Point )
|
||||||
|
|
||||||
|
// we can read and write its fields:
|
||||||
|
assert( p1.x == 3 )
|
||||||
|
assert( p1.y == 4 )
|
||||||
|
|
||||||
|
p1.y++
|
||||||
|
assert( p1.y == 5 )
|
||||||
|
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Let's see in details. The statement `struct Point(x,y)` creates a struct, or public class,
|
||||||
|
with two field, which are mutable and publicly visible, because it is _struct_. `(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.
|
||||||
|
|
||||||
|
Such declaration is identical to `class Point(var x,var y)` which does exactly the same.
|
||||||
|
|
||||||
|
|
||||||
|
TBD
|
||||||
|
|
||||||
|
[argument list](declaring_arguments.md)
|
||||||
@@ -75,3 +75,15 @@ The example above could be rewritten using inner lambda, too:
|
|||||||
>>> 1
|
>>> 1
|
||||||
>>> 2
|
>>> 2
|
||||||
>>> void
|
>>> 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, struct 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,60 @@
|
|||||||
|
# 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
|
||||||
|
|
||||||
|
class foo {
|
||||||
|
|
||||||
|
private static var instanceCounter = 0
|
||||||
|
|
||||||
|
val instanceId = instanceCounter
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
instanceCounter--
|
||||||
|
}
|
||||||
|
|
||||||
|
// instance initializatino could be as this:
|
||||||
|
if( instanceId > 100 )
|
||||||
|
throw Exception("Too many instances")
|
||||||
|
|
||||||
|
static {
|
||||||
|
// static, one-per-class initializer could be posted here
|
||||||
|
instanceCounter = 1
|
||||||
|
}
|
||||||
|
}
|
||||||
+15
-12
@@ -22,7 +22,8 @@ Same as in C++.
|
|||||||
: not yet implemented.
|
: not yet implemented.
|
||||||
|
|
||||||
(1)
|
(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.
|
: 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
|
||||||
|
|
||||||
@@ -43,29 +44,28 @@ 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 |
|
||||||
| abs(x) | absolute value, Int for integer x, Real otherwise |
|
| x.roundToInt() | shortcut to `round(x).toInt()` |
|
||||||
| | |
|
|
||||||
|
|
||||||
## Mathematical functions
|
## Lyng math functions
|
||||||
|
|
||||||
| name | meaning |
|
| name | meaning |
|
||||||
|-----------|------------------------------------------------------|
|
|-----------|------------------------------------------------------|
|
||||||
| sin(x) | sine |
|
| sin(x) | sine |
|
||||||
| cos(x) | cosine |
|
| cos(x) | cosine |
|
||||||
| tan(x) | tangent |
|
| tan(x) | tangent |
|
||||||
| asin(x) | $sin^-1(x)$ |
|
| asin(x) | $sin^{-1}(x)$ |
|
||||||
| acos(x) | $cos^-1(x)$ |
|
| acos(x) | $cos^{-1}(x)$ |
|
||||||
| atan(x) | $tg^-1(x)$ |
|
| atan(x) | $tg^{-1}(x)$ |
|
||||||
| sinh(x) | hyperbolic sine |
|
| sinh(x) | hyperbolic sine |
|
||||||
| cosh(x) | hyperbolic cosine |
|
| cosh(x) | hyperbolic cosine |
|
||||||
| tanh(x) | hyperbolic tangent |
|
| tanh(x) | hyperbolic tangent |
|
||||||
| asinh(x) | $sinh^-1(x)$ |
|
| asinh(x) | $sinh^{-1}(x)$ |
|
||||||
| acosh(x) | $cosh^-1(x)$ |
|
| acosh(x) | $cosh^{-1}(x)$ |
|
||||||
| atanh(x) | $tgh^-1(x)$ |
|
| atanh(x) | $tgh^{-1}(x)$ |
|
||||||
| ln(x) | $ln(x)$, $ log_e(x) $ |
|
| ln(x) | $ln(x)$, $ log_e(x) $ |
|
||||||
| exp(x) | $e^x$ |
|
| exp(x) | $e^x$ |
|
||||||
| log10(x) | $log_{10}(x)$ |
|
| log10(x) | $log_{10}(x)$ |
|
||||||
@@ -73,12 +73,15 @@ or transformed `Real` otherwise.
|
|||||||
| sqrt(x) | $ \sqrt {x}$ |
|
| sqrt(x) | $ \sqrt {x}$ |
|
||||||
| abs(x) | absolute value of x. Int if x is Int, Real otherwise |
|
| abs(x) | absolute value of x. Int if x is Int, Real otherwise |
|
||||||
|
|
||||||
|
|
||||||
For example:
|
For example:
|
||||||
|
|
||||||
assert( sin(π/2) == 1.0)
|
assert( sin(π/2) == 1.0)
|
||||||
assert( cos(π/2) < 0.000001)
|
assert( cos(π/2) < 0.000001)
|
||||||
assert( abs(ln(exp(1))) - 1 < 0.00001)
|
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
|
>>> void
|
||||||
|
|
||||||
## Scientific constant
|
## Scientific constant
|
||||||
|
|||||||
+14
-1
@@ -11,7 +11,7 @@ In other word, the code usually works as expected when you see it. So, nothing u
|
|||||||
|
|
||||||
__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)
|
||||||
- [math in Lyng](math.md)
|
- [math in Lyng](math.md)
|
||||||
- Some class references: [List], [Real], [Range], [Iterable], [Iterator]
|
- Some class references: [List], [Real], [Range], [Iterable], [Iterator]
|
||||||
@@ -238,6 +238,8 @@ but Lyng syntax requires using the __lambda syntax__ to create such.
|
|||||||
|
|
||||||
See lambdas section below.
|
See lambdas section below.
|
||||||
|
|
||||||
|
## Declaring arguments
|
||||||
|
|
||||||
There are default parameters in Lyng:
|
There are default parameters in Lyng:
|
||||||
|
|
||||||
fn check(amount, prefix = "answer: ") {
|
fn check(amount, prefix = "answer: ") {
|
||||||
@@ -250,6 +252,17 @@ There are default parameters in Lyng:
|
|||||||
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:
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ plugins {
|
|||||||
}
|
}
|
||||||
|
|
||||||
group = "net.sergeych"
|
group = "net.sergeych"
|
||||||
version = "0.0.5-SNAPSHOT"
|
version = "0.2.0-SNAPSHOT"
|
||||||
|
|
||||||
kotlin {
|
kotlin {
|
||||||
jvm()
|
jvm()
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
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)
|
||||||
|
if (params[j].defaultValue == null) 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,
|
||||||
|
fromArgs: Arguments = context.args,
|
||||||
|
defaultAccessType: Compiler.AccessType = Compiler.AccessType.Var
|
||||||
|
) {
|
||||||
|
fun assign(a: Item, value: Obj) {
|
||||||
|
context.addItem(a.name, (a.accessType ?: defaultAccessType).isMutable, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun processHead(index: Int): Int {
|
||||||
|
var i = index
|
||||||
|
while (i != params.size) {
|
||||||
|
val a = params[i]
|
||||||
|
if (a.isEllipsis) break
|
||||||
|
val value = when {
|
||||||
|
i < fromArgs.size -> fromArgs[i]
|
||||||
|
a.defaultValue != null -> a.defaultValue.execute(context)
|
||||||
|
else -> context.raiseArgumentError("too few arguments for the call")
|
||||||
|
}
|
||||||
|
assign(a, value)
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
return i
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun processTail(index: Int): Int {
|
||||||
|
var i = params.size - 1
|
||||||
|
var j = fromArgs.size - 1
|
||||||
|
while (i > index) {
|
||||||
|
val a = params[i]
|
||||||
|
if (a.isEllipsis) break
|
||||||
|
val value = when {
|
||||||
|
j >= index -> {
|
||||||
|
fromArgs[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(fromArgs.values.subList(index, toFromIndex + 1).toMutableList())
|
||||||
|
assign(a, l)
|
||||||
|
}
|
||||||
|
|
||||||
|
val leftIndex = processHead(0)
|
||||||
|
if (leftIndex < params.size) {
|
||||||
|
val end = processTail(leftIndex)
|
||||||
|
processEllipsis(leftIndex, end)
|
||||||
|
} else {
|
||||||
|
if (leftIndex < fromArgs.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: Compiler.AccessType? = null,
|
||||||
|
val visibility: Compiler.Visibility? = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -8,8 +8,18 @@ suspend fun Collection<ParsedArgument>.toArguments(context: Context): Arguments
|
|||||||
for (x in this) {
|
for (x in this) {
|
||||||
val value = x.value.execute(context)
|
val value = x.value.execute(context)
|
||||||
if (x.isSplat) {
|
if (x.isSplat) {
|
||||||
(value as? ObjList) ?: context.raiseClassCastError("expected list of objects for splat argument")
|
when {
|
||||||
|
value is ObjList -> {
|
||||||
for (subitem in value.list) list.add(Arguments.Info(subitem, x.pos))
|
for (subitem in value.list) list.add(Arguments.Info(subitem, x.pos))
|
||||||
|
}
|
||||||
|
|
||||||
|
value.isInstanceOf(ObjIterable) -> {
|
||||||
|
val i = (value.invokeInstanceMethod(context, "toList") as ObjList).list
|
||||||
|
i.forEach { list.add(Arguments.Info(it, x.pos)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> context.raiseClassCastError("expected list of objects for splat argument")
|
||||||
|
}
|
||||||
} else
|
} else
|
||||||
list.add(Arguments.Info(value, x.pos))
|
list.add(Arguments.Info(value, x.pos))
|
||||||
}
|
}
|
||||||
@@ -33,6 +43,7 @@ data class Arguments(val list: List<Info>) : Iterable<Obj> {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val EMPTY = Arguments(emptyList())
|
val EMPTY = Arguments(emptyList())
|
||||||
|
fun from(values: Collection<Obj>) = Arguments(values.map { Info(it, Pos.UNKNOWN) })
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun iterator(): Iterator<Obj> {
|
override fun iterator(): Iterator<Obj> {
|
||||||
|
|||||||
@@ -11,19 +11,21 @@ class Compiler(
|
|||||||
class Settings
|
class Settings
|
||||||
|
|
||||||
fun compile(source: Source): Script {
|
fun compile(source: Source): Script {
|
||||||
return parseScript(source.startPos, CompilerContext(parseLing(source)))
|
return parseScript(source.startPos,
|
||||||
|
CompilerContext(parseLyng(source))
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseScript(start: Pos, tokens: CompilerContext): Script {
|
private fun parseScript(start: Pos, cc: CompilerContext): Script {
|
||||||
val statements = mutableListOf<Statement>()
|
val statements = mutableListOf<Statement>()
|
||||||
while (parseStatement(tokens)?.also {
|
while (parseStatement(cc, braceMeansLambda = true)?.also {
|
||||||
statements += it
|
statements += it
|
||||||
} != null) {/**/
|
} != null) {/**/
|
||||||
}
|
}
|
||||||
return Script(start, statements)
|
return Script(start, statements)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseStatement(cc: CompilerContext): Statement? {
|
private fun parseStatement(cc: CompilerContext, braceMeansLambda: Boolean = false): Statement? {
|
||||||
while (true) {
|
while (true) {
|
||||||
val t = cc.next()
|
val t = cc.next()
|
||||||
return when (t.type) {
|
return when (t.type) {
|
||||||
@@ -49,6 +51,9 @@ class Compiler(
|
|||||||
|
|
||||||
Token.Type.LBRACE -> {
|
Token.Type.LBRACE -> {
|
||||||
cc.previous()
|
cc.previous()
|
||||||
|
if (braceMeansLambda)
|
||||||
|
parseExpression(cc)
|
||||||
|
else
|
||||||
parseBlock(cc)
|
parseBlock(cc)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,7 +132,7 @@ class Compiler(
|
|||||||
operand = Accessor { context ->
|
operand = Accessor { context ->
|
||||||
context.pos = next.pos
|
context.pos = next.pos
|
||||||
val v = left.getter(context).value
|
val v = left.getter(context).value
|
||||||
WithAccess(
|
ObjRecord(
|
||||||
v.invokeInstanceMethod(
|
v.invokeInstanceMethod(
|
||||||
context,
|
context,
|
||||||
next.value,
|
next.value,
|
||||||
@@ -138,8 +143,10 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!isCall) {
|
if (!isCall) {
|
||||||
operand = Accessor { context ->
|
operand = Accessor({ context ->
|
||||||
left.getter(context).value.readField(context, next.value)
|
left.getter(context).value.readField(context, next.value)
|
||||||
|
}) { cc, newValue ->
|
||||||
|
left.getter(cc).value.writeField(cc, next.value, newValue)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} ?: throw ScriptError(t.pos, "Expecting expression before dot")
|
} ?: throw ScriptError(t.pos, "Expecting expression before dot")
|
||||||
@@ -326,9 +333,11 @@ class Compiler(
|
|||||||
throw ScriptError(startPos, "lambda must have either valid arguments declaration with '->' or no arguments")
|
throw ScriptError(startPos, "lambda must have either valid arguments declaration with '->' or no arguments")
|
||||||
val pos = cc.currentPos()
|
val pos = cc.currentPos()
|
||||||
val body = parseBlock(cc, skipLeadingBrace = true)
|
val body = parseBlock(cc, skipLeadingBrace = true)
|
||||||
return Accessor { _ ->
|
|
||||||
statement {
|
var closure: Context? = null
|
||||||
val context = this.copy(pos)
|
|
||||||
|
val callStatement = statement {
|
||||||
|
val context = closure!!.copy(pos, args)
|
||||||
if (argsDeclaration == null) {
|
if (argsDeclaration == null) {
|
||||||
// no args: automatic var 'it'
|
// no args: automatic var 'it'
|
||||||
val l = args.values
|
val l = args.values
|
||||||
@@ -342,25 +351,15 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
context.addItem("it", false, itValue)
|
context.addItem("it", false, itValue)
|
||||||
} else {
|
} else {
|
||||||
// assign vars as declared
|
// assign vars as declared the standard way
|
||||||
if (args.size != argsDeclaration.args.size && !argsDeclaration.args.last().isEllipsis)
|
argsDeclaration.assignToContext(context, defaultAccessType = AccessType.Val)
|
||||||
raiseArgumentError("Too many arguments : called with ${args.size}, lambda accepts only ${argsDeclaration.args.size}")
|
|
||||||
for ((n, a) in argsDeclaration.args.withIndex()) {
|
|
||||||
if (n >= args.size) {
|
|
||||||
if (a.initialValue != null)
|
|
||||||
context.addItem(a.name, false, a.initialValue.execute(context))
|
|
||||||
else throw ScriptError(a.pos, "argument $n is out of scope")
|
|
||||||
} else {
|
|
||||||
val value = if (a.isEllipsis) {
|
|
||||||
ObjList(args.values.subList(n, args.values.size).toMutableList())
|
|
||||||
} else
|
|
||||||
args[n]
|
|
||||||
context.addItem(a.name, false, value)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
body.execute(context)
|
body.execute(context)
|
||||||
}.asReadonly
|
}
|
||||||
|
|
||||||
|
return Accessor { x ->
|
||||||
|
if (closure == null) closure = x
|
||||||
|
callStatement.asReadonly
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,35 +401,92 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
data class ArgVar(
|
enum class AccessType(val isMutable: Boolean) {
|
||||||
val name: String,
|
Val(false), Var(true),
|
||||||
val type: TypeDecl = TypeDecl.Obj,
|
@Suppress("unused")
|
||||||
val pos: Pos,
|
Initialization(false)
|
||||||
val isEllipsis: Boolean,
|
|
||||||
val initialValue: Statement? = null
|
|
||||||
)
|
|
||||||
|
|
||||||
data class ArgsDeclaration(val args: List<ArgVar>, val endTokenType: Token.Type) {
|
|
||||||
init {
|
|
||||||
val i = args.indexOfFirst { it.isEllipsis }
|
|
||||||
if (i >= 0 && i != args.lastIndex) throw ScriptError(args[i].pos, "ellipsis argument must be last")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
enum class Visibility {
|
||||||
|
Public, Private, Protected, Internal
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parse argument declaration, used in lambda (and later in fn too)
|
* Parse argument declaration, used in lambda (and later in fn too)
|
||||||
* @return declaration or null if there is no valid list of arguments
|
* @return declaration or null if there is no valid list of arguments
|
||||||
*/
|
*/
|
||||||
private fun parseArgsDeclaration(cc: CompilerContext): ArgsDeclaration? {
|
private fun parseArgsDeclaration(cc: CompilerContext, isClassDeclaration: Boolean = false): ArgsDeclaration? {
|
||||||
val result = mutableListOf<ArgVar>()
|
val result = mutableListOf<ArgsDeclaration.Item>()
|
||||||
var endTokenType: Token.Type? = null
|
var endTokenType: Token.Type? = null
|
||||||
val startPos = cc.savePos()
|
val startPos = cc.savePos()
|
||||||
|
|
||||||
while (endTokenType == null) {
|
while (endTokenType == null) {
|
||||||
val t = cc.next()
|
var t = cc.next()
|
||||||
when (t.type) {
|
when (t.type) {
|
||||||
|
Token.Type.RPAREN, Token.Type.ARROW -> {
|
||||||
|
// empty list?
|
||||||
|
endTokenType = t.type
|
||||||
|
}
|
||||||
|
|
||||||
Token.Type.NEWLINE -> {}
|
Token.Type.NEWLINE -> {}
|
||||||
Token.Type.ID -> {
|
Token.Type.ID -> {
|
||||||
|
// visibility
|
||||||
|
val visibility = when (t.value) {
|
||||||
|
"private" -> {
|
||||||
|
if (!isClassDeclaration) {
|
||||||
|
cc.restorePos(startPos); return null
|
||||||
|
}
|
||||||
|
t = cc.next()
|
||||||
|
Visibility.Private
|
||||||
|
}
|
||||||
|
|
||||||
|
"protected" -> {
|
||||||
|
if (!isClassDeclaration) {
|
||||||
|
cc.restorePos(startPos); return null
|
||||||
|
}
|
||||||
|
t = cc.next()
|
||||||
|
Visibility.Protected
|
||||||
|
}
|
||||||
|
|
||||||
|
"internal" -> {
|
||||||
|
if (!isClassDeclaration) {
|
||||||
|
cc.restorePos(startPos); return null
|
||||||
|
}
|
||||||
|
t = cc.next()
|
||||||
|
Visibility.Internal
|
||||||
|
}
|
||||||
|
|
||||||
|
"public" -> {
|
||||||
|
if (!isClassDeclaration) {
|
||||||
|
cc.restorePos(startPos); return null
|
||||||
|
}
|
||||||
|
t = cc.next()
|
||||||
|
Visibility.Public
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
// val/var?
|
||||||
|
val access = when (t.value) {
|
||||||
|
"val" -> {
|
||||||
|
if (!isClassDeclaration) {
|
||||||
|
cc.restorePos(startPos); return null
|
||||||
|
}
|
||||||
|
t = cc.next()
|
||||||
|
AccessType.Val
|
||||||
|
}
|
||||||
|
|
||||||
|
"var" -> {
|
||||||
|
if (!isClassDeclaration) {
|
||||||
|
cc.restorePos(startPos); return null
|
||||||
|
}
|
||||||
|
t = cc.next()
|
||||||
|
AccessType.Var
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
var defaultValue: Statement? = null
|
var defaultValue: Statement? = null
|
||||||
cc.ifNextIs(Token.Type.ASSIGN) {
|
cc.ifNextIs(Token.Type.ASSIGN) {
|
||||||
defaultValue = parseExpression(cc)
|
defaultValue = parseExpression(cc)
|
||||||
@@ -438,7 +494,15 @@ class Compiler(
|
|||||||
// type information
|
// type information
|
||||||
val typeInfo = parseTypeDeclaration(cc)
|
val typeInfo = parseTypeDeclaration(cc)
|
||||||
val isEllipsis = cc.skipTokenOfType(Token.Type.ELLIPSIS, isOptional = true)
|
val isEllipsis = cc.skipTokenOfType(Token.Type.ELLIPSIS, isOptional = true)
|
||||||
result += ArgVar(t.value, typeInfo, t.pos, isEllipsis, defaultValue)
|
result += ArgsDeclaration.Item(
|
||||||
|
t.value,
|
||||||
|
typeInfo,
|
||||||
|
t.pos,
|
||||||
|
isEllipsis,
|
||||||
|
defaultValue,
|
||||||
|
access,
|
||||||
|
visibility
|
||||||
|
)
|
||||||
|
|
||||||
// important: valid argument list continues with ',' and ends with '->' or ')'
|
// important: valid argument list continues with ',' and ends with '->' or ')'
|
||||||
// otherwise it is not an argument list:
|
// otherwise it is not an argument list:
|
||||||
@@ -579,7 +643,7 @@ class Compiler(
|
|||||||
else -> {
|
else -> {
|
||||||
Accessor({
|
Accessor({
|
||||||
it.pos = t.pos
|
it.pos = t.pos
|
||||||
it.get(t.value)?.asAccess
|
it.get(t.value)
|
||||||
?: it.raiseError("symbol not defined: '${t.value}'")
|
?: it.raiseError("symbol not defined: '${t.value}'")
|
||||||
}) { ctx, newValue ->
|
}) { ctx, newValue ->
|
||||||
ctx.get(t.value)?.let { stored ->
|
ctx.get(t.value)?.let { stored ->
|
||||||
@@ -630,9 +694,101 @@ class Compiler(
|
|||||||
"continue" -> parseContinueStatement(id.pos, cc)
|
"continue" -> parseContinueStatement(id.pos, cc)
|
||||||
"fn", "fun" -> parseFunctionDeclaration(cc)
|
"fn", "fun" -> parseFunctionDeclaration(cc)
|
||||||
"if" -> parseIfStatement(cc)
|
"if" -> parseIfStatement(cc)
|
||||||
|
"class" -> parseClassDeclaration(cc, false)
|
||||||
|
"struct" -> parseClassDeclaration(cc, true)
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun parseClassDeclaration(cc: CompilerContext, isStruct: Boolean): Statement {
|
||||||
|
val nameToken = cc.requireToken(Token.Type.ID)
|
||||||
|
val constructorArgsDeclaration =
|
||||||
|
if (cc.skipTokenOfType(Token.Type.LPAREN, isOptional = true))
|
||||||
|
parseArgsDeclaration(cc)
|
||||||
|
else null
|
||||||
|
|
||||||
|
if (constructorArgsDeclaration != null && constructorArgsDeclaration.endTokenType != Token.Type.RPAREN)
|
||||||
|
throw ScriptError(
|
||||||
|
nameToken.pos,
|
||||||
|
"Bad class declaration: expected ')' at the end of the primary constructor"
|
||||||
|
)
|
||||||
|
|
||||||
|
cc.skipTokenOfType(Token.Type.NEWLINE, isOptional = true)
|
||||||
|
val t = cc.next()
|
||||||
|
|
||||||
|
val bodyInit: Statement? = if (t.type == Token.Type.LBRACE) {
|
||||||
|
// parse body
|
||||||
|
parseScript(t.pos, cc).also {
|
||||||
|
cc.skipTokens(Token.Type.RBRACE)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cc.previous()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
// create class
|
||||||
|
val className = nameToken.value
|
||||||
|
|
||||||
|
@Suppress("UNUSED_VARIABLE") val defaultAccess = if (isStruct) AccessType.Var else AccessType.Initialization
|
||||||
|
@Suppress("UNUSED_VARIABLE") val defaultVisibility = Visibility.Public
|
||||||
|
|
||||||
|
// create instance constructor
|
||||||
|
// create custom objClass with all fields and instance constructor
|
||||||
|
|
||||||
|
val constructorCode = statement {
|
||||||
|
// constructor code is registered with class instance and is called over
|
||||||
|
// new `thisObj` already set by class to ObjInstance.instanceContext
|
||||||
|
thisObj as ObjInstance
|
||||||
|
|
||||||
|
// the context now is a "class creation context", we must use its args to initialize
|
||||||
|
// fields. Note that 'this' is already set by class
|
||||||
|
constructorArgsDeclaration?.assignToContext(this)
|
||||||
|
bodyInit?.execute(this)
|
||||||
|
// export public
|
||||||
|
for( (name,record) in objects ) {
|
||||||
|
println("-- $name $record")
|
||||||
|
when(record.visibility) {
|
||||||
|
Visibility.Public -> {
|
||||||
|
thisObj.publicFields += name
|
||||||
|
thisObj.protectedFields += name
|
||||||
|
}
|
||||||
|
Visibility.Protected ->
|
||||||
|
thisObj.protectedFields += name
|
||||||
|
else -> {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
thisObj
|
||||||
|
}
|
||||||
|
// inheritance must alter this code:
|
||||||
|
val newClass = ObjClass(className).apply {
|
||||||
|
instanceConstructor = constructorCode
|
||||||
|
constructorArgsDeclaration?.let { cad ->
|
||||||
|
// we need accessors for all fields:
|
||||||
|
for (f in cad.params) {
|
||||||
|
createField(
|
||||||
|
f.name,
|
||||||
|
statement {
|
||||||
|
val context = (thisObj as ObjInstance).instanceContext
|
||||||
|
println("called on $thisObj")
|
||||||
|
context[f.name]?.value ?: raiseError("field is not initialized: ${f.name}")
|
||||||
|
},
|
||||||
|
true,
|
||||||
|
// (f.accessType ?: defaultAccess).isMutable,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return statement {
|
||||||
|
// the main statement should create custom ObjClass instance with field
|
||||||
|
// accessors, constructor registration, etc.
|
||||||
|
addItem(className, false, newClass)
|
||||||
|
newClass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private fun getLabel(cc: CompilerContext, maxDepth: Int = 2): String? {
|
private fun getLabel(cc: CompilerContext, maxDepth: Int = 2): String? {
|
||||||
var cnt = 0
|
var cnt = 0
|
||||||
var found: String? = null
|
var found: String? = null
|
||||||
@@ -743,13 +899,13 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun loopIntRange(
|
private suspend fun loopIntRange(
|
||||||
forContext: Context, start: Int, end: Int, loopVar: StoredObj,
|
forContext: Context, start: Int, end: Int, loopVar: ObjRecord,
|
||||||
body: Statement, elseStatement: Statement?, label: String?, catchBreak: Boolean
|
body: Statement, elseStatement: Statement?, label: String?, catchBreak: Boolean
|
||||||
): Obj {
|
): Obj {
|
||||||
var result: Obj = ObjVoid
|
var result: Obj = ObjVoid
|
||||||
val iVar = ObjInt(0)
|
val iVar = ObjInt(0)
|
||||||
loopVar.value = iVar
|
loopVar.value = iVar
|
||||||
if( catchBreak) {
|
if (catchBreak) {
|
||||||
for (i in start..<end) {
|
for (i in start..<end) {
|
||||||
iVar.value = i.toLong()
|
iVar.value = i.toLong()
|
||||||
try {
|
try {
|
||||||
@@ -771,7 +927,7 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun loopIterable(
|
private suspend fun loopIterable(
|
||||||
forContext: Context, sourceObj: Obj, loopVar: StoredObj,
|
forContext: Context, sourceObj: Obj, loopVar: ObjRecord,
|
||||||
body: Statement, elseStatement: Statement?, label: String?,
|
body: Statement, elseStatement: Statement?, label: String?,
|
||||||
catchBreak: Boolean
|
catchBreak: Boolean
|
||||||
): Obj {
|
): Obj {
|
||||||
@@ -945,12 +1101,6 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
data class FnParamDef(
|
|
||||||
val name: String,
|
|
||||||
val pos: Pos,
|
|
||||||
val defaultValue: Statement? = null
|
|
||||||
)
|
|
||||||
|
|
||||||
private fun parseFunctionDeclaration(tokens: CompilerContext): Statement {
|
private fun parseFunctionDeclaration(tokens: CompilerContext): Statement {
|
||||||
var t = tokens.next()
|
var t = tokens.next()
|
||||||
val start = t.pos
|
val start = t.pos
|
||||||
@@ -961,27 +1111,13 @@ class Compiler(
|
|||||||
t = tokens.next()
|
t = tokens.next()
|
||||||
if (t.type != Token.Type.LPAREN)
|
if (t.type != Token.Type.LPAREN)
|
||||||
throw ScriptError(t.pos, "Bad function definition: expected '(' after 'fn ${name}'")
|
throw ScriptError(t.pos, "Bad function definition: expected '(' after 'fn ${name}'")
|
||||||
val params = mutableListOf<FnParamDef>()
|
|
||||||
var defaultListStarted = false
|
val argsDeclaration = parseArgsDeclaration(tokens)
|
||||||
do {
|
if (argsDeclaration == null || argsDeclaration.endTokenType != Token.Type.RPAREN)
|
||||||
t = tokens.next()
|
throw ScriptError(
|
||||||
if (t.type == Token.Type.RPAREN)
|
t.pos,
|
||||||
break
|
"Bad function definition: expected valid argument declaration or () after 'fn ${name}'"
|
||||||
if (t.type != Token.Type.ID)
|
)
|
||||||
throw ScriptError(t.pos, "Expected identifier after '('")
|
|
||||||
val n = tokens.next()
|
|
||||||
val defaultValue = if (n.type == Token.Type.ASSIGN) {
|
|
||||||
parseExpression(tokens)?.also { defaultListStarted = true }
|
|
||||||
?: throw ScriptError(n.pos, "Expected initialization expression")
|
|
||||||
} else {
|
|
||||||
if (defaultListStarted)
|
|
||||||
throw ScriptError(n.pos, "requires default value too")
|
|
||||||
if (n.type != Token.Type.COMMA)
|
|
||||||
tokens.previous()
|
|
||||||
null
|
|
||||||
}
|
|
||||||
params.add(FnParamDef(t.value, t.pos, defaultValue))
|
|
||||||
} while (true)
|
|
||||||
|
|
||||||
// Here we should be at open body
|
// Here we should be at open body
|
||||||
val fnStatements = parseBlock(tokens)
|
val fnStatements = parseBlock(tokens)
|
||||||
@@ -995,21 +1131,7 @@ class Compiler(
|
|||||||
val context = closure?.copy() ?: callerContext.raiseError("bug: closure not set")
|
val context = closure?.copy() ?: callerContext.raiseError("bug: closure not set")
|
||||||
|
|
||||||
// load params from caller context
|
// load params from caller context
|
||||||
for ((i, d) in params.withIndex()) {
|
argsDeclaration.assignToContext(context, callerContext.args, defaultAccessType = AccessType.Val)
|
||||||
if (i < callerContext.args.size)
|
|
||||||
context.addItem(d.name, false, callerContext.args.list[i].value)
|
|
||||||
else
|
|
||||||
context.addItem(
|
|
||||||
d.name,
|
|
||||||
false,
|
|
||||||
d.defaultValue?.execute(context)
|
|
||||||
?: throw ScriptError(
|
|
||||||
context.pos,
|
|
||||||
"missing required argument #${1 + i}: ${d.name}"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
// save closure
|
|
||||||
fnStatements.execute(context)
|
fnStatements.execute(context)
|
||||||
}
|
}
|
||||||
return statement(start) { context ->
|
return statement(start) { context ->
|
||||||
@@ -1185,7 +1307,8 @@ class Compiler(
|
|||||||
Operator.simple(Token.Type.NOTIS, lastPrty) { c, a, b -> ObjBool(!a.isInstanceOf(b)) },
|
Operator.simple(Token.Type.NOTIS, lastPrty) { c, a, b -> ObjBool(!a.isInstanceOf(b)) },
|
||||||
// shuttle <=> 6
|
// shuttle <=> 6
|
||||||
Operator.simple(Token.Type.SHUTTLE, ++lastPrty) { c, a, b ->
|
Operator.simple(Token.Type.SHUTTLE, ++lastPrty) { c, a, b ->
|
||||||
ObjInt(a.compareTo(c, b).toLong()) },
|
ObjInt(a.compareTo(c, b).toLong())
|
||||||
|
},
|
||||||
// bit shifts 7
|
// bit shifts 7
|
||||||
Operator.simple(Token.Type.PLUS, ++lastPrty) { ctx, a, b -> a.plus(ctx, b) },
|
Operator.simple(Token.Type.PLUS, ++lastPrty) { ctx, a, b -> a.plus(ctx, b) },
|
||||||
Operator.simple(Token.Type.MINUS, lastPrty) { ctx, a, b -> a.minus(ctx, b) },
|
Operator.simple(Token.Type.MINUS, lastPrty) { ctx, a, b -> a.minus(ctx, b) },
|
||||||
@@ -1213,7 +1336,7 @@ class Compiler(
|
|||||||
/**
|
/**
|
||||||
* The keywords that stop processing of expression term
|
* The keywords that stop processing of expression term
|
||||||
*/
|
*/
|
||||||
val stopKeywords = setOf("break", "continue", "return", "if", "when", "do", "while", "for")
|
val stopKeywords = setOf("break", "continue", "return", "if", "when", "do", "while", "for", "class", "struct")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -27,6 +27,9 @@ class Context(
|
|||||||
|
|
||||||
fun raiseClassCastError(msg: String): Nothing = raiseError(ObjClassCastError(this, msg))
|
fun raiseClassCastError(msg: String): Nothing = raiseError(ObjClassCastError(this, msg))
|
||||||
|
|
||||||
|
@Suppress("unused")
|
||||||
|
fun raiseSymbolNotFound(name: String): Nothing = raiseError(ObjSymbolNotDefinedError(this, "symbol is not defined: $name"))
|
||||||
|
|
||||||
fun raiseError(message: String): Nothing {
|
fun raiseError(message: String): Nothing {
|
||||||
throw ExecutionError(ObjError(this, message))
|
throw ExecutionError(ObjError(this, message))
|
||||||
}
|
}
|
||||||
@@ -35,45 +38,48 @@ class Context(
|
|||||||
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].value 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].value::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)
|
||||||
|
|
||||||
|
fun copy(args: Arguments = Arguments.EMPTY, newThisObj: Obj? = null): Context =
|
||||||
Context(this, args, pos, newThisObj ?: thisObj)
|
Context(this, args, pos, newThisObj ?: thisObj)
|
||||||
|
|
||||||
fun copy() = Context(this, args, pos, thisObj)
|
fun copy() = Context(this, args, pos, thisObj)
|
||||||
|
|
||||||
fun addItem(name: String, isMutable: Boolean, value: Obj?): StoredObj {
|
fun addItem(name: String, isMutable: Boolean, value: Obj): ObjRecord {
|
||||||
return StoredObj(value, isMutable).also { objects.put(name, it) }
|
return ObjRecord(value, isMutable).also { objects.put(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) {
|
||||||
@@ -83,7 +89,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
|
||||||
|
|
||||||
@@ -99,7 +105,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)
|
||||||
|
|||||||
@@ -6,16 +6,35 @@ import kotlinx.serialization.SerialName
|
|||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import net.sergeych.synctools.ProtectedOp
|
import net.sergeych.synctools.ProtectedOp
|
||||||
|
|
||||||
//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: Compiler.Visibility = Compiler.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")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,7 +69,7 @@ open class Obj {
|
|||||||
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 +179,21 @@ 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> {
|
suspend open 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
|
val value = obj.value
|
||||||
return when (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")
|
||||||
@@ -218,8 +236,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 {
|
||||||
@@ -309,6 +327,10 @@ data class ObjNamespace(val name: String) : Obj() {
|
|||||||
|
|
||||||
open class ObjError(val context: Context, val message: String) : Obj() {
|
open class ObjError(val context: Context, val message: String) : Obj() {
|
||||||
override val asStr: ObjString by lazy { ObjString("Error: $message") }
|
override val asStr: ObjString by lazy { ObjString("Error: $message") }
|
||||||
|
|
||||||
|
fun raise(): Nothing {
|
||||||
|
throw ExecutionError(this)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class ObjNullPointerError(context: Context) : ObjError(context, "object is null")
|
class ObjNullPointerError(context: Context) : ObjError(context, "object is null")
|
||||||
@@ -317,5 +339,6 @@ class ObjAssertionError(context: Context, message: String) : ObjError(context, m
|
|||||||
class ObjClassCastError(context: Context, message: String) : ObjError(context, message)
|
class ObjClassCastError(context: Context, message: String) : ObjError(context, message)
|
||||||
class ObjIndexOutOfBoundsError(context: Context, message: String = "index out of bounds") : ObjError(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 ObjIllegalArgumentError(context: Context, message: String = "illegal argument") : ObjError(context, message)
|
||||||
|
class ObjIllegalAssignmentError(context: Context, message: String = "illegal assignment") : ObjError(context, message)
|
||||||
|
class ObjSymbolNotDefinedError(context: Context, message: String = "symbol is not defined") : ObjError(context, message)
|
||||||
class ObjIterationFinishedError(context: Context) : ObjError(context, "iteration finished")
|
class ObjIterationFinishedError(context: Context) : ObjError(context, "iteration finished")
|
||||||
@@ -7,6 +7,8 @@ class ObjClass(
|
|||||||
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,37 @@ 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 {
|
||||||
|
println("callOn $this constructing....")
|
||||||
|
println("on context: $context")
|
||||||
|
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(
|
||||||
|
name: String,
|
||||||
|
initialValue: Obj,
|
||||||
|
isMutable: Boolean = false,
|
||||||
|
visibility: Compiler.Visibility = Compiler.Visibility.Public,
|
||||||
|
pos: Pos = Pos.builtIn
|
||||||
|
) {
|
||||||
if (name in members || allParentsSet.any { name in it.members } == true)
|
if (name in members || allParentsSet.any { name in it.members } == true)
|
||||||
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
|
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 +59,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,13 +73,14 @@ 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")
|
||||||
|
|
||||||
|
|
||||||
@@ -87,7 +91,8 @@ val ObjIterable by lazy { ObjClass("Iterable").apply {
|
|||||||
ObjList(result)
|
ObjList(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
} }
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Collection is an iterator with `size`]
|
* Collection is an iterator with `size`]
|
||||||
@@ -142,6 +147,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,29 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
class ObjInstance(override val objClass: ObjClass) : Obj() {
|
||||||
|
|
||||||
|
internal val publicFields = mutableSetOf<String>()
|
||||||
|
internal val protectedFields = mutableSetOf<String>()
|
||||||
|
|
||||||
|
internal lateinit var instanceContext: Context
|
||||||
|
|
||||||
|
override suspend fun readField(context: Context, name: String): ObjRecord {
|
||||||
|
return if( name in publicFields ) instanceContext[name]!!
|
||||||
|
else super.readField(context, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun writeField(context: Context, name: String, newValue: Obj) {
|
||||||
|
if( name in publicFields ) {
|
||||||
|
val f = instanceContext[name]!!
|
||||||
|
if( !f.isMutable ) ObjIllegalAssignmentError(context, "can't reassign val $name").raise()
|
||||||
|
if( f.value.assign(context, newValue) == null)
|
||||||
|
f.value = newValue
|
||||||
|
}
|
||||||
|
else super.writeField(context, name, newValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun invokeInstanceMethod(context: Context, name: String, args: Arguments): Obj {
|
||||||
|
if( name in publicFields ) return instanceContext[name]!!.value.invoke(context, this, args)
|
||||||
|
return super.invokeInstanceMethod(context, name, args)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
package net.sergeych.lyng
|
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)
|
||||||
|
|||||||
@@ -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 {
|
||||||
|
|||||||
@@ -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)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -119,6 +119,27 @@ class Script(
|
|||||||
raiseError(ObjAssertionError(this,"Assertion failed"))
|
raiseError(ObjAssertionError(this,"Assertion failed"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
addVoidFn("assertEquals") {
|
||||||
|
val a = requiredArg<Obj>(0)
|
||||||
|
val b = requiredArg<Obj>(1)
|
||||||
|
if( a.compareTo(this, b) != 0 )
|
||||||
|
raiseError(ObjAssertionError(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(ObjAssertionError(this,"Expected exception but nothing was thrown"))
|
||||||
|
}
|
||||||
|
|
||||||
addVoidFn("delay") {
|
addVoidFn("delay") {
|
||||||
delay((this.args.firstAndOnly().toDouble()/1000.0).roundToLong())
|
delay((this.args.firstAndOnly().toDouble()/1000.0).roundToLong())
|
||||||
}
|
}
|
||||||
@@ -135,6 +156,8 @@ class Script(
|
|||||||
// interfaces
|
// interfaces
|
||||||
addConst("Iterable", ObjIterable)
|
addConst("Iterable", ObjIterable)
|
||||||
addConst("Array", ObjArray)
|
addConst("Array", ObjArray)
|
||||||
|
addConst("Class", ObjClassType)
|
||||||
|
addConst("Object", Obj().objClass)
|
||||||
|
|
||||||
val pi = ObjReal(PI)
|
val pi = ObjReal(PI)
|
||||||
addConst("π", pi)
|
addConst("π", pi)
|
||||||
|
|||||||
@@ -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)
|
||||||
|
|||||||
@@ -1,11 +0,0 @@
|
|||||||
package net.sergeych.lyng
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 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,13 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class Symbols(
|
||||||
|
unitType: UnitType,
|
||||||
|
val name: String,
|
||||||
|
val x: TypeDecl
|
||||||
|
) {
|
||||||
|
enum class UnitType {
|
||||||
|
Module, Function, Lambda
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,21 @@
|
|||||||
package net.sergeych.lyng
|
package net.sergeych.lyng
|
||||||
|
|
||||||
sealed class TypeDecl {
|
sealed class TypeDecl {
|
||||||
|
// ??
|
||||||
|
data class Fn(val argTypes: List<ArgsDeclaration.Item>, val retType: TypeDecl) : TypeDecl()
|
||||||
object Obj : 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
|
||||||
|
|
||||||
|
*/
|
||||||
@@ -18,7 +18,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 + x\n2", 0)
|
check("1", Token.Type.INT, 0, 0, "1 + x\n2", 0)
|
||||||
@@ -36,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")
|
||||||
@@ -72,13 +72,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)
|
||||||
@@ -87,13 +87,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)
|
||||||
@@ -103,7 +103,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])
|
||||||
@@ -116,7 +116,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())
|
||||||
@@ -133,7 +133,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())
|
||||||
@@ -486,6 +486,136 @@ 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(
|
||||||
@@ -1167,6 +1297,7 @@ class ScriptTest {
|
|||||||
eval(
|
eval(
|
||||||
"""
|
"""
|
||||||
fun mapValues(iterable, transform) {
|
fun mapValues(iterable, transform) {
|
||||||
|
println("start: ", transform)
|
||||||
var result = []
|
var result = []
|
||||||
for( x in iterable ) result += transform(x)
|
for( x in iterable ) result += transform(x)
|
||||||
}
|
}
|
||||||
@@ -1175,6 +1306,17 @@ class ScriptTest {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testNewFnParser() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
fun f1(a,b) { a + b }
|
||||||
|
println(f1(1,2))
|
||||||
|
assertEquals( 7, f1(3,4) )
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testSpoilArgsBug() = runTest {
|
fun testSpoilArgsBug() = runTest {
|
||||||
eval(
|
eval(
|
||||||
@@ -1238,6 +1380,77 @@ class ScriptTest {
|
|||||||
assert( 5 <=> 7 < 0 )
|
assert( 5 <=> 7 < 0 )
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSimpleStruct() = runTest {
|
||||||
|
val c = Context()
|
||||||
|
c.eval("""
|
||||||
|
struct 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("""
|
||||||
|
struct 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("""
|
||||||
|
struct 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("""
|
||||||
|
struct Point(x,y) {
|
||||||
|
fun length() {
|
||||||
|
sqrt(x*x+y*y)
|
||||||
|
}
|
||||||
|
var foo = "zero"
|
||||||
|
}
|
||||||
|
val p = Point(3,4)
|
||||||
|
assertEquals(5, p.length())
|
||||||
|
p.y = 10
|
||||||
|
println(p.length())
|
||||||
|
assertEquals(sqrt(109), p.length())
|
||||||
|
""".trimIndent())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -8,6 +8,7 @@ import net.sergeych.lyng.ObjVoid
|
|||||||
import java.nio.file.Files
|
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.io.path.extension
|
||||||
import kotlin.test.Test
|
import kotlin.test.Test
|
||||||
import kotlin.test.assertEquals
|
import kotlin.test.assertEquals
|
||||||
@@ -41,7 +42,8 @@ data class DocTest(
|
|||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
||||||
@@ -190,10 +192,10 @@ suspend fun DocTest.test(context: Context = Context()) {
|
|||||||
if (error != null || expectedOutput != collectedOutput.toString() ||
|
if (error != null || expectedOutput != collectedOutput.toString() ||
|
||||||
expectedResult != result
|
expectedResult != result
|
||||||
) {
|
) {
|
||||||
println("Test failed: ${this.detailedString}")
|
System.err.println("\nfailed: ${this.detailedString}")
|
||||||
}
|
}
|
||||||
error?.let {
|
error?.let {
|
||||||
fail("test failed", it)
|
fail(it.message, it)
|
||||||
}
|
}
|
||||||
assertEquals(expectedOutput, collectedOutput.toString(), "script output do not match")
|
assertEquals(expectedOutput, collectedOutput.toString(), "script output do not match")
|
||||||
assertEquals(expectedResult, result.toString(), "script result does not match")
|
assertEquals(expectedResult, result.toString(), "script result does not match")
|
||||||
@@ -261,4 +263,9 @@ class BookTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testArgumentBooks() = runTest {
|
||||||
|
runDocTests("../docs/declaring_arguments.md")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user