Compare commits
74
Commits
0e065e0d7c
..
v0.2.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
323c455a50 | ||
|
|
370d8cf605 | ||
|
|
f338c54632 | ||
|
|
3ef80616d8 | ||
|
|
961228ca0b | ||
|
|
56e0d2fd63 | ||
|
|
33fdb0934a | ||
|
|
60384060bf | ||
|
|
d3f23be7fe | ||
|
|
397dcaae92 | ||
|
|
2b87845a40 | ||
|
|
5591a66af3 | ||
|
|
9a08da0dfd | ||
|
|
71a2933066 | ||
|
|
4dc73b91c2 | ||
|
|
c0cf190452 | ||
|
|
306a7f26ef | ||
|
|
823e9a6498 | ||
|
|
aba122c3e6 | ||
|
|
75d90d7228 | ||
|
|
b331f4edaa | ||
|
|
148d1b6d24 | ||
|
|
953e0e696b | ||
|
|
7b76b7d80f | ||
|
|
512dda5984 | ||
|
|
53eb1bc5e7 | ||
|
|
1323f93923 | ||
|
|
c167ebe6a8 | ||
|
|
29c643eed2 | ||
|
|
4a597886e6 | ||
|
|
3cd2786ef0 | ||
|
|
25ace7370b | ||
|
|
d1b6ec03f7 | ||
|
|
f40c28504d | ||
|
|
f18038f9ca | ||
|
|
19a2a1d909 | ||
|
|
2344e19857 | ||
|
|
dae09f0dc9 | ||
|
|
e13dde68b5 | ||
|
|
6ef94fff65 | ||
|
|
939e391a20 | ||
|
|
c65f711ee3 | ||
|
|
698d169612 | ||
|
|
86d59abfbc | ||
|
|
d2c732ceef | ||
|
|
dcab60b7bb | ||
|
|
2b3b0b298c | ||
|
|
b82a97ed20 | ||
|
|
3908b8ee9f | ||
|
|
f7b35c7576 | ||
|
|
f3b3ebbb52 | ||
|
|
7288de4ea8 | ||
|
|
3a7a0c34c6 | ||
|
|
f4a3ad4c19 | ||
|
|
1479df4426 | ||
|
|
b56b5c521d | ||
|
|
c18345823b | ||
|
|
f881faf89f | ||
|
|
ca93d73b9c | ||
|
|
ff03f3066d | ||
|
|
9a9f712cec | ||
|
|
72f637e7de | ||
|
|
2130974929 | ||
|
|
47c061d2b4 | ||
|
|
f885300d18 | ||
|
|
d21544ca5d | ||
|
|
361c1d5b13 | ||
|
|
eba29aedb7 | ||
|
|
baf9eab3ba | ||
|
|
9ae9752634 | ||
|
|
758f49603f | ||
|
|
ebeed385e9 | ||
|
|
22fbd5584b | ||
|
|
0569be3b21 |
No files matched your search
+1
-1
@@ -12,4 +12,4 @@ xcuserdata
|
||||
#So we don't accidentally commit our private keys
|
||||
*.gpg
|
||||
.gigaide
|
||||
.kotlin
|
||||
/kotlin-js-store/yarn.lock
|
||||
@@ -1,8 +1,75 @@
|
||||
# Ling: scripting lang for kotlin multiplatform
|
||||
# Lyng: modern scripting for kotlin multiplatform
|
||||
|
||||
in the form of multiplatform library.
|
||||
A KMP library and a standalone interpreter
|
||||
|
||||
__current state of implementation and docs__: [math and operators](docs/math.md).
|
||||
- simple, compact, intuitive and elegant modern code style:
|
||||
|
||||
```
|
||||
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
|
||||
|
||||
### Add library
|
||||
|
||||
TBD
|
||||
|
||||
### Execute script:
|
||||
|
||||
```kotlin
|
||||
assertEquals("hello, world", eval("""
|
||||
"hello, " + "world"
|
||||
""").toString())
|
||||
```
|
||||
|
||||
### Exchanging information
|
||||
|
||||
Script is executed over some `Context`. Create instance of the context,
|
||||
add your specific vars and functions to it, an call over it:
|
||||
|
||||
```kotlin
|
||||
// simple function
|
||||
val context = Context().apply {
|
||||
addFn("addArgs") {
|
||||
var sum = 0.0
|
||||
for( a in args) sum += a.toDouble()
|
||||
ObjReal(sum)
|
||||
}
|
||||
addConst("LIGHT_SPEED", ObjReal(299_792_458.0))
|
||||
|
||||
// callback back to kotlin to some suspend fn, for example::
|
||||
// suspend fun doSomeWork(text: String): Int
|
||||
addFn("doSomeWork") {
|
||||
// this _is_ a suspend lambda, we can call suspend function,
|
||||
// and it won't consume the thread:
|
||||
doSomeWork(args[0].toString()).toObj()
|
||||
}
|
||||
}
|
||||
// adding constant:
|
||||
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.
|
||||
|
||||
## Why?
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,37 @@
|
||||
# Iterable interface
|
||||
|
||||
The inteface which requires iterator to be implemented:
|
||||
|
||||
fun iterator(): Iterator
|
||||
|
||||
Iterator itself is a simple interface that should provide only to method:
|
||||
|
||||
interface Iterable {
|
||||
fun hasNext(): Bool
|
||||
fun next(): Obj
|
||||
}
|
||||
|
||||
Just remember at this stage typed declarations are not yet supported.
|
||||
|
||||
Having `Iterable` in base classes allows to use it in for loop. Also, each `Iterable` has some utility functions available:
|
||||
|
||||
## Abstract methods
|
||||
|
||||
fun iterator(): Iterator
|
||||
|
||||
## Instance methods
|
||||
|
||||
### toList()
|
||||
|
||||
Creates a list by iterating to the end. So, the Iterator should be finite to be used with it.
|
||||
|
||||
## Included in interfaces:
|
||||
|
||||
- Collection, Array, [List]
|
||||
|
||||
## Implemented in classes:
|
||||
|
||||
- [List], [Range]
|
||||
|
||||
[List]: List.md
|
||||
[Range]: Range.md
|
||||
@@ -0,0 +1,29 @@
|
||||
# Iterator interface
|
||||
|
||||
Iterators are representing the [Iterable] entity, to access its contents
|
||||
sequentially.
|
||||
|
||||
To implement the iterator you need to implement only two abstract methods:
|
||||
|
||||
## Abstract methods
|
||||
|
||||
### hasNext(): Bool
|
||||
|
||||
Should return `true` if call to `next()` will return valid next element.
|
||||
|
||||
### next(): Obj
|
||||
|
||||
Should return next object in the iterated entity. If there is no next method,
|
||||
must throw `ObjIterationFinishedError`.
|
||||
|
||||
## Usage
|
||||
|
||||
Iterators are returned when implementing [Iterable] interface.
|
||||
|
||||
## Implemented for classes:
|
||||
|
||||
- [List], [Range]
|
||||
|
||||
[List]: List.md
|
||||
[Range]: Range.md
|
||||
[Iterable]: Iterable.md
|
||||
@@ -0,0 +1,90 @@
|
||||
# List built-in class
|
||||
|
||||
Mutable list of any objects.
|
||||
|
||||
It's class in Lyng is `List`:
|
||||
|
||||
[1,2,3]::class
|
||||
>>> List
|
||||
|
||||
you can use it's class to ensure type:
|
||||
|
||||
[]::class == List
|
||||
>>> true
|
||||
|
||||
## Indexing
|
||||
|
||||
indexing is zero-based, as in C/C++/Java/Kotlin, etc.
|
||||
|
||||
val list = [10, 20, 30]
|
||||
list[1]
|
||||
>>> 20
|
||||
|
||||
Using negative indexes has a special meaning: _offset from the end of the list_:
|
||||
|
||||
val list = [10, 20, 30]
|
||||
list[-1]
|
||||
>>> 30
|
||||
|
||||
__Important__ negative indexes works wherever indexes are used, e.g. in insertion and removal methods too.
|
||||
|
||||
## Concatenation
|
||||
|
||||
You can concatenate lists or iterable objects:
|
||||
|
||||
assert( [4,5] + [1,2] == [4,5,1,2])
|
||||
assert( [4,5] + (1..3) == [4, 5, 1, 2, 3])
|
||||
>>> void
|
||||
|
||||
## Appending
|
||||
|
||||
To append to lists, use `+=` with elements, lists and any [Iterable] instances, but beware it will concatenate [Iterable] objects instead of appending them. To append [Iterable] instance itself, use `list.add`:
|
||||
|
||||
var list = [1, 2]
|
||||
val other = [3, 4]
|
||||
|
||||
// appending lists is clear:
|
||||
list += other
|
||||
assert( list == [1, 2, 3, 4] )
|
||||
|
||||
// but appending other Iterables could be confusing:
|
||||
list += (10..12)
|
||||
assert( list == [1, 2, 3, 4, 10, 11, 12])
|
||||
|
||||
// now adding list as sublist:
|
||||
list.add(other)
|
||||
assert( list == [1, 2, 3, 4, 10, 11, 12, [3,4]])
|
||||
|
||||
>>> void
|
||||
|
||||
|
||||
|
||||
## Comparisons
|
||||
|
||||
assert( [1, 2] != [1, 3])
|
||||
assert( [1, 2, 3] > [1, 2])
|
||||
assert( [1, 3] > [1, 2, 3])
|
||||
assert( [1, 2, 3] == [1, 2, 3])
|
||||
assert( [1, 2, 3] != [1, 2, "three"])
|
||||
// note that in the case above objects are referentially different:
|
||||
assert( [1, 2, 3] !== [1, 2, 3])
|
||||
>>> void
|
||||
|
||||
## Members
|
||||
|
||||
| name | meaning | type |
|
||||
|-----------------------------------|-------------------------------------|----------|
|
||||
| `size` | current size | Int |
|
||||
| `add(elements...)` | add one or more elements to the end | Any |
|
||||
| `addAt(index,elements...)` | insert elements at position | Int, Any |
|
||||
| `removeAt(index)` | remove element at position | Int |
|
||||
| `removeRangeInclusive(start,end)` | remove range, inclusive (1) | Int, Int |
|
||||
| | | |
|
||||
|
||||
(1)
|
||||
: end-inclisiveness allows to use negative indexes to, for exampe, remove several last elements, like `list.removeRangeInclusive(-2, -1)` will remove two last elements.
|
||||
|
||||
|
||||
# Notes
|
||||
|
||||
Could be rewritten using array as a class but List as the interface
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# OO implementation in Lyng
|
||||
|
||||
Basic principles:
|
||||
|
||||
- Everything is an instance of some class
|
||||
- Every class except Obj has at least one parent
|
||||
- Obj has no parents and is the root of the hierarchy
|
||||
- instance has member fields and member functions
|
||||
- Every class has hclass members and class functions, or companion ones, are these of the base class.
|
||||
- every class has _type_ which is an instances of ObjClass
|
||||
- ObjClass sole parent is Obj
|
||||
- ObjClass contains code for instance methods, class fields, hierarchy information.
|
||||
- Class information is also scoped.
|
||||
- We acoid imported classes duplication using packages and import caching, so the same imported module is the same object in all its classes.
|
||||
|
||||
## Instances
|
||||
|
||||
Result of executing of any expression or statement in the Lyng is the object that
|
||||
inherits `Obj`, but is not `Obj`. For example it could be Int, void, null, real, string, bool, etc.
|
||||
|
||||
This means whatever expression returns or the variable holds, is the first-class
|
||||
object, no differenes. For example:
|
||||
|
||||
1.67.roundToInt()
|
||||
1>>> 2
|
||||
|
||||
Here, instance method of the real object, created from literal `1.67` is called.
|
||||
|
||||
## Instance class
|
||||
|
||||
Everything can be classified, and classes could be tested for equivalence:
|
||||
|
||||
3.14::class
|
||||
1>>> Real
|
||||
|
||||
Class is the object, naturally, with class:
|
||||
|
||||
3.14::class::class
|
||||
1>>> Class
|
||||
|
||||
Classes can be compared:
|
||||
|
||||
assert(1.21::class == Math.PI::class)
|
||||
assert(3.14::class != 1::class)
|
||||
assert(π::class == Real)
|
||||
π::class
|
||||
>>> Real
|
||||
|
||||
Note `Real` class: it is global variable for Real class; there are such class instances for all built-in types:
|
||||
|
||||
assert("Hello"::class == String)
|
||||
assert(1970::class == Int)
|
||||
assert(true::class == Bool)
|
||||
assert('$'::class == Char)
|
||||
>>> void
|
||||
|
||||
More complex is singleton classes, because you don't need to compare their class
|
||||
instances and generally don't need them at all, these are normally just Obj:
|
||||
|
||||
null::class
|
||||
>>> Obj
|
||||
|
||||
At this time, `Obj` can't be accessed as a class.
|
||||
|
||||
|
||||
### Methods in-depth
|
||||
|
||||
Regular methods are called on instances as usual `instance.method()`. The method resolution order is
|
||||
|
||||
1. this instance methods;
|
||||
2. parents method: no guarantee but we enumerate parents in order of appearance;
|
||||
3. possible extension methods (scoped)
|
||||
|
||||
# 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)
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
# Range
|
||||
|
||||
Range is diapason between two values. Open range has at least one end open, e.g. ±∞, closed range has both ends open.
|
||||
|
||||
## Closed ranges
|
||||
|
||||
The syntax is intuitive and adopted from Kotlin:
|
||||
|
||||
// end inclusive:
|
||||
val r = 1..5
|
||||
assert(5 in r)
|
||||
assert(6 !in r)
|
||||
assert(0 !in r)
|
||||
assert(2 in r)
|
||||
>>> void
|
||||
|
||||
Exclusive end ranges are adopted from kotlin either:
|
||||
|
||||
// end inclusive:
|
||||
val r = 1..<5
|
||||
assert(5 !in r)
|
||||
assert(6 !in r)
|
||||
assert(0 !in r)
|
||||
assert(2 in r)
|
||||
assert(4 in r)
|
||||
>>> void
|
||||
|
||||
In any case, we can test an object to belong to using `in` and `!in` and
|
||||
access limits:
|
||||
|
||||
val r = 0..5
|
||||
(r.end - r.start)/2
|
||||
>>> 2
|
||||
|
||||
Notice, start and end are ints, so midpoint here is int too.
|
||||
|
||||
It is possible to test that one range is included in another range too,
|
||||
one range is defined as _contained_ in another ifm and only if, it begin and end
|
||||
are equal or within another, taking into account the end-inclusiveness:
|
||||
|
||||
assert( (1..3) in (1..3) )
|
||||
assert( (0..3) !in (1..3) )
|
||||
assert( (1..2) in (1..<3) )
|
||||
assert( (1..<2) in (1..<3) )
|
||||
assert( (1..<3) in (1..3) )
|
||||
>>> void
|
||||
|
||||
## Finite Ranges are iterable
|
||||
|
||||
So given a range with both ends, you can assume it is [Iterable]. This automatically let
|
||||
use finite ranges in loops and convert it to lists:
|
||||
|
||||
assert( [-2, -1, 0, 1] == (-2..1).toList() )
|
||||
>>> void
|
||||
|
||||
In spite of this you can use ranges in for loops:
|
||||
|
||||
for( i in 1..3 )
|
||||
println(i)
|
||||
>>> 1
|
||||
>>> 2
|
||||
>>> 3
|
||||
>>> void
|
||||
|
||||
but
|
||||
|
||||
for( i in 1..<3 )
|
||||
println(i)
|
||||
>>> 1
|
||||
>>> 2
|
||||
>>> void
|
||||
|
||||
## Character ranges
|
||||
|
||||
You can use Char as both ends of the closed range:
|
||||
|
||||
val r = 'a' .. 'c'
|
||||
assert( 'b' in r)
|
||||
assert( 'e' !in r)
|
||||
for( ch in r )
|
||||
println(ch)
|
||||
>>> a
|
||||
>>> b
|
||||
>>> c
|
||||
>>> void
|
||||
|
||||
Exclusive end char ranges are supported too:
|
||||
|
||||
('a'..<'c').toList
|
||||
>>> ['a', 'b']
|
||||
|
||||
|
||||
# Instance members
|
||||
|
||||
| member | description | args |
|
||||
|-----------------|------------------------------|---------------|
|
||||
| contains(other) | used in `in` | Range, or Any |
|
||||
| isEndInclusive | true for '..' | Bool |
|
||||
| isOpen | at any end | Bool |
|
||||
| isIntRange | both start and end are Int | Bool |
|
||||
| start | | Bool |
|
||||
| end | | Bool |
|
||||
| size | for finite ranges, see above | Long |
|
||||
| [] | see above | |
|
||||
| | | |
|
||||
|
||||
[Iterable]: Iterable.md
|
||||
@@ -0,0 +1,25 @@
|
||||
# Real built-in class
|
||||
|
||||
Class that supports double-precision math. Woks much like double in other languages. We honor no floats, so it is '
|
||||
Real'.
|
||||
|
||||
It's class in Lyng is `Real`:
|
||||
|
||||
(π/2)::class
|
||||
>>> Real
|
||||
|
||||
you can use it's class to ensure type:
|
||||
|
||||
1.71::class == Real
|
||||
>>> true
|
||||
|
||||
## Member functions
|
||||
|
||||
| name | meaning | type |
|
||||
|-----------------|------------------------------------|------|
|
||||
| `.roundToInt()` | round to nearest int like round(x) | Int |
|
||||
| | | |
|
||||
| | | |
|
||||
| | | |
|
||||
| | | |
|
||||
| | | |
|
||||
@@ -0,0 +1,89 @@
|
||||
# Advanced topics
|
||||
|
||||
## Closures/scopes isolation
|
||||
|
||||
Each block has own scope, in which it can safely use closures and override
|
||||
outer vars. Lets use some lambdas to create isolated scopes:
|
||||
|
||||
var param = "global"
|
||||
val prefix = "param in "
|
||||
|
||||
val scope1 = {
|
||||
var param = prefix + "scope1"
|
||||
param
|
||||
}
|
||||
|
||||
val scope2 = {
|
||||
var param = prefix + "scope2"
|
||||
param
|
||||
}
|
||||
|
||||
println(scope1())
|
||||
println(scope2())
|
||||
println(param)
|
||||
>>> param in scope1
|
||||
>>> param in scope2
|
||||
>>> global
|
||||
>>> void
|
||||
|
||||
One interesting way of using closure isolation is to keep state of the functions:
|
||||
|
||||
val getAndIncrement = {
|
||||
// will be updated by doIt()
|
||||
var counter = 0
|
||||
|
||||
// we return callable fn from the block:
|
||||
fun doit() {
|
||||
val was = counter
|
||||
counter = counter + 1
|
||||
was
|
||||
}
|
||||
}()
|
||||
// notice using of () above: it calls the lambda block that returns
|
||||
// a function (callable!) that we will use:
|
||||
println(getAndIncrement())
|
||||
println(getAndIncrement())
|
||||
println(getAndIncrement())
|
||||
>>> 0
|
||||
>>> 1
|
||||
>>> 2
|
||||
>>> void
|
||||
|
||||
Inner `counter` is not accessible from outside, no way; still it is kept
|
||||
between calls in the closure, as inner function `doit`, returned from the
|
||||
block, keeps reference to it and keeps it alive.
|
||||
|
||||
The example above could be rewritten using inner lambda, too:
|
||||
|
||||
val getAndIncrement = {
|
||||
// will be updated by doIt()
|
||||
var counter = 0
|
||||
|
||||
// we return callable fn from the block:
|
||||
{
|
||||
val was = counter
|
||||
counter = counter + 1
|
||||
was
|
||||
}
|
||||
}()
|
||||
// notice using of () above: it calls the lambda block that returns
|
||||
// a function (callable!) that we will use:
|
||||
println(getAndIncrement())
|
||||
println(getAndIncrement())
|
||||
println(getAndIncrement())
|
||||
>>> 0
|
||||
>>> 1
|
||||
>>> 2
|
||||
>>> void
|
||||
|
||||
Lambda functions remember their scopes, so it will work the same as previous:
|
||||
|
||||
var counter = 200
|
||||
fun createLambda() {
|
||||
var counter = 0
|
||||
{ counter += 1 }
|
||||
}
|
||||
val c = createLambda()
|
||||
println(c)
|
||||
>> 1
|
||||
>> void
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+59
-21
@@ -10,41 +10,79 @@ Same as in C++.
|
||||
| 1 | `%` `*` `/` |
|
||||
| 2 | `+` `-` |
|
||||
| 3 | bit shifts (NI) |
|
||||
| 4 | `<=>` (NI) |
|
||||
| 5 | `<=` `>=` `<` `>` (NI) |
|
||||
| 6 | `==` `!=` (NI) |
|
||||
| 7 | `&` (NI) |
|
||||
| 9 | `\|` (NI) |
|
||||
| 4 | `<=>` (1) |
|
||||
| 5 | `<=` `>=` `<` `>` |
|
||||
| 6 | `==` `!=` |
|
||||
| 7 | bitwise and `&` (NI) |
|
||||
| 9 | bitwise or `\|` (NI) |
|
||||
| 10 | `&&` |
|
||||
| 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
|
||||
|
||||
`+ - * / % `: if both operand is `Int`, calculates as int. Otherwise, as real.
|
||||
`+ - * / % `: if both operand is `Int`, calculates as int. Otherwise, as real:
|
||||
|
||||
// integer division:
|
||||
3 / 2
|
||||
>>> 1
|
||||
|
||||
but:
|
||||
|
||||
3 / 2.0
|
||||
>>> 1.5
|
||||
|
||||
## Round and range
|
||||
|
||||
The following functions return its argument if it is `Int`,
|
||||
or transformed `Real` otherwise.
|
||||
|
||||
| name | description |
|
||||
|----------|--------------------------------------------------------|
|
||||
| floor(x) | Computes the largest integer value not greater than x |
|
||||
| ceil(x) | Computes the least integer value value not less than x |
|
||||
| round(x) | Rounds x |
|
||||
| | |
|
||||
| | |
|
||||
| name | description |
|
||||
|----------------|--------------------------------------------------------|
|
||||
| floor(x) | Computes the largest integer value not greater than x |
|
||||
| ceil(x) | Computes the least integer value value not less than x |
|
||||
| round(x) | Rounds x |
|
||||
| x.roundToInt() | shortcut to `round(x).toInt()` |
|
||||
|
||||
## Scientific functions
|
||||
## Lyng math functions
|
||||
|
||||
| name | meaning |
|
||||
|---------------------|---------|
|
||||
| `sin(x:Real): Real` | sine |
|
||||
| | |
|
||||
| | |
|
||||
| | |
|
||||
| name | meaning |
|
||||
|-----------|------------------------------------------------------|
|
||||
| sin(x) | sine |
|
||||
| cos(x) | cosine |
|
||||
| tan(x) | tangent |
|
||||
| asin(x) | $sin^{-1}(x)$ |
|
||||
| acos(x) | $cos^{-1}(x)$ |
|
||||
| atan(x) | $tg^{-1}(x)$ |
|
||||
| sinh(x) | hyperbolic sine |
|
||||
| cosh(x) | hyperbolic cosine |
|
||||
| tanh(x) | hyperbolic tangent |
|
||||
| asinh(x) | $sinh^{-1}(x)$ |
|
||||
| acosh(x) | $cosh^{-1}(x)$ |
|
||||
| atanh(x) | $tgh^{-1}(x)$ |
|
||||
| ln(x) | $ln(x)$, $ log_e(x) $ |
|
||||
| exp(x) | $e^x$ |
|
||||
| log10(x) | $log_{10}(x)$ |
|
||||
| pow(x, y) | ${x^y}$ |
|
||||
| sqrt(x) | $ \sqrt {x}$ |
|
||||
| abs(x) | absolute value of x. Int if x is Int, Real otherwise |
|
||||
|
||||
For example:
|
||||
|
||||
assert( sin(π/2) == 1.0)
|
||||
assert( cos(π/2) < 0.000001)
|
||||
assert( abs(ln(exp(1))) - 1 < 0.00001)
|
||||
|
||||
// abs() keeps the argument type:
|
||||
assert( abs(-1) is Int)
|
||||
assert( abs(-2.21) == 2.21 )
|
||||
>>> void
|
||||
|
||||
## Scientific constant
|
||||
|
||||
|
||||
@@ -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!");
|
||||
+770
-53
@@ -1,97 +1,284 @@
|
||||
# Ling tutorial
|
||||
---
|
||||
gitea: none
|
||||
include_toc: true
|
||||
---
|
||||
|
||||
Ling 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].
|
||||
In other word, the code usually works as expected when you see it. So, nothing unusual.
|
||||
|
||||
# Expressions and blocks.
|
||||
__Other documents to read__ maybe after this one:
|
||||
|
||||
Everything is an expression in Ling. Even an empty block:
|
||||
- [Advanced topics](advanced_topics.md), [declaring arguments](declaring_arguments.md)
|
||||
- [OOP notes](OOP.md)
|
||||
- [math in Lyng](math.md)
|
||||
- Some class references: [List], [Real], [Range], [Iterable], [Iterator]
|
||||
- Some samples: [combinatorics](samples/combinatorics.lyng.md)
|
||||
See [samples folder](samples)
|
||||
|
||||
{
|
||||
// empty block
|
||||
}
|
||||
# Expressions
|
||||
|
||||
Everything is an expression in Lyng. Even an empty block:
|
||||
|
||||
// empty block
|
||||
>>> void
|
||||
|
||||
Block returns it last expression as "return value":
|
||||
any block also returns it's last expression:
|
||||
|
||||
{
|
||||
if( true ) {
|
||||
2 + 2
|
||||
3 + 3
|
||||
}
|
||||
>>> 6
|
||||
|
||||
Same is without block:
|
||||
|
||||
3 + 3
|
||||
>>> 6
|
||||
|
||||
If you don't want block to return anything, use `void`:
|
||||
|
||||
{
|
||||
3 + 4
|
||||
fn voidFunction() {
|
||||
3 + 4 // this will be ignored
|
||||
void
|
||||
}
|
||||
voidFunction()
|
||||
>>> void
|
||||
|
||||
otherwise, last expression will be returned:
|
||||
|
||||
fn normalize(value, minValue, maxValue) {
|
||||
(value - minValue) / (maxValue-minValue)
|
||||
}
|
||||
normalize( 4, 0.0, 10.0)
|
||||
>>> 0.4
|
||||
|
||||
Every construction is an expression that returns something (or `void`):
|
||||
|
||||
val x = 111 // or autotest will fail!
|
||||
val limited = if( x > 100 ) 100 else x
|
||||
limited
|
||||
>>> 100
|
||||
|
||||
You can use blocks in if statement, as expected:
|
||||
|
||||
val x = 200
|
||||
val limited = if( x > 100 ) {
|
||||
100 + x * 0.1
|
||||
}
|
||||
else
|
||||
x
|
||||
limited
|
||||
>>> 120.0
|
||||
|
||||
So the principles are:
|
||||
When putting multiple statments in the same line it is convenient and recommended to use `;`:
|
||||
|
||||
- everything is an expression returning its last calculated value or `void`
|
||||
- expression could be a `{ block }`
|
||||
var from; var to
|
||||
from = 0; to = 100
|
||||
>>> 100
|
||||
|
||||
## Expression details
|
||||
Notice: returned value is `100` as assignment operator returns its assigned value.
|
||||
Most often you can omit `;`, but improves readability and prevent some hardly seen bugs.
|
||||
|
||||
## Assignments
|
||||
|
||||
Assignemnt is an expression that changes its lvalue and return assigned value:
|
||||
|
||||
var x = 100
|
||||
x = 20
|
||||
println(5 + (x=6)) // 11: x changes its value!
|
||||
x
|
||||
>>> 11
|
||||
>>> 6
|
||||
|
||||
As the assignment itself is an expression, you can use it in strange ways. Just remember
|
||||
to use parentheses as assignment operation insofar is left-associated and will not
|
||||
allow chained assignments (we might fix it later). Use parentheses insofar:
|
||||
|
||||
var x = 0
|
||||
var y = 0
|
||||
x = (y = 5)
|
||||
assert(x==5)
|
||||
assert(y==5)
|
||||
>>> void
|
||||
|
||||
Note that assignment operator returns rvalue, it can't be assigned.
|
||||
|
||||
## Modifying arithmetics
|
||||
|
||||
There is a set of assigning operations: `+=`, `-=`, `*=`, `/=` and even `%=`.
|
||||
|
||||
var x = 5
|
||||
assert( 25 == (x*=5) )
|
||||
assert( 25 == x)
|
||||
assert( 24 == (x-=1) )
|
||||
assert( 12 == (x/=2) )
|
||||
x
|
||||
>>> 12
|
||||
|
||||
Notice the parentheses here: the assignment has low priority!
|
||||
|
||||
These operators return rvalue, unmodifiable.
|
||||
|
||||
## Assignment return r-value!
|
||||
|
||||
## Math
|
||||
|
||||
It is rather simple, like everywhere else:
|
||||
|
||||
val x = 2.0
|
||||
sin(x * π/4) / 2.0
|
||||
>>> 0.5
|
||||
|
||||
See [math](math.md) for more on it.
|
||||
See [math](math.md) for more on it. Notice using Greek as identifier, all languages are allowed.
|
||||
|
||||
Logical operation could be used the same
|
||||
|
||||
var x = 10
|
||||
++x >= 11
|
||||
>>> true
|
||||
|
||||
## Supported operators
|
||||
|
||||
| op | ass | args | comments |
|
||||
|:--------:|-----|-------------------|----------|
|
||||
| + | += | Int or Real | |
|
||||
| - | -= | Int or Real | infix |
|
||||
| * | *= | Int or Real | |
|
||||
| / | /= | Int or Real | |
|
||||
| % | %= | Int or Real | |
|
||||
| && | | Bool | |
|
||||
| \|\| | | Bool | |
|
||||
| !x | | Bool | |
|
||||
| < | | String, Int, Real | (1) |
|
||||
| <= | | String, Int, Real | (1) |
|
||||
| >= | | String, Int, Real | (1) |
|
||||
| > | | String, Int, Real | (1) |
|
||||
| == | | Any | (1) |
|
||||
| === | | Any | (2) |
|
||||
| !== | | Any | (2) |
|
||||
| != | | Any | (1) |
|
||||
| ++a, a++ | | Int | |
|
||||
| --a, a-- | | Int | |
|
||||
|
||||
(1)
|
||||
: comparison are based on comparison operator which can be overloaded
|
||||
|
||||
(2)
|
||||
: referential equality means left and right operands references exactly same instance of some object. Note that all
|
||||
singleton object, like `null`, are referentially equal too, while string different literals even being equal are most
|
||||
likely referentially not equal
|
||||
|
||||
Reference quality and object equality example:
|
||||
|
||||
assert( null == null) // singletons
|
||||
assert( null === null)
|
||||
// but, for non-singletons:
|
||||
assert( 5 == 5)
|
||||
assert( 5 !== 5)
|
||||
assert( "foo" !== "foo" )
|
||||
>>> void
|
||||
|
||||
# Variables
|
||||
|
||||
Much like in kotlin, there are _variables_:
|
||||
|
||||
var name = "Sergey"
|
||||
|
||||
Variables can be not initialized at declaration, in which case they must be assigned before use, or an exception
|
||||
will be thrown:
|
||||
|
||||
var foo
|
||||
// WRONG! Exception will be thrown at next line:
|
||||
foo + "bar"
|
||||
|
||||
Correct pattern is:
|
||||
|
||||
foo = "foo"
|
||||
// now is OK:
|
||||
foo + bar
|
||||
|
||||
This is though a rare case when you need uninitialized variables, most often you can use conditional operators
|
||||
and even loops to assign results (see below).
|
||||
|
||||
# Constants
|
||||
|
||||
Almost the same, using `val`:
|
||||
|
||||
val foo = 1
|
||||
foo += 1 // this will throw exception
|
||||
|
||||
# Constants
|
||||
|
||||
Same as in kotlin:
|
||||
|
||||
val HalfPi = π / 2
|
||||
|
||||
Note using greek characters in identifiers! All letters allowed, but remember who might try to read your script, most
|
||||
likely will know some English, the rest is the pure uncertainty.
|
||||
|
||||
# Defining functions
|
||||
|
||||
fun check(amount) {
|
||||
if( amount > 100 )
|
||||
"anough"
|
||||
"enough"
|
||||
else
|
||||
"more"
|
||||
}
|
||||
>>> Callable@...
|
||||
|
||||
You can use both `fn` and `fun`. Note that function declaration _is an expression returning callable_.
|
||||
Notice how function definition return a value, instance of `Callable`.
|
||||
|
||||
There are default parameters in Ling:
|
||||
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.
|
||||
|
||||
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: ") {
|
||||
prefix + if( amount > 100 )
|
||||
"anough"
|
||||
"enough"
|
||||
else
|
||||
"more"
|
||||
}
|
||||
assert( "do: more" == check(10, "do: ") )
|
||||
check(120)
|
||||
>>> "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
|
||||
|
||||
Each __block has an isolated context that can be accessed from closures__. For example:
|
||||
|
||||
var counter = 1
|
||||
|
||||
// this is ok: coumter is incremented
|
||||
def increment(amount=1) {
|
||||
|
||||
// this is ok: counter is incremented
|
||||
fun increment(amount=1) {
|
||||
// use counter from a closure:
|
||||
counter = counter + amount
|
||||
}
|
||||
|
||||
val taskAlias = def someTask() {
|
||||
increment(10)
|
||||
assert( counter == 11 )
|
||||
|
||||
val callable = {
|
||||
// this obscures global outer var with a local one
|
||||
var counter = 0
|
||||
// ...
|
||||
@@ -100,16 +287,513 @@ Each __block has an isolated context that can be accessed from closures__. For e
|
||||
counter
|
||||
}
|
||||
|
||||
As was told, `def` statement return callable for the function, it could be used as a parameter, or elsewhere
|
||||
to call it:
|
||||
assert(callable() == 1)
|
||||
// but the global counter is not changed:
|
||||
assert(counter == 11)
|
||||
>>> void
|
||||
|
||||
## Lambda functions
|
||||
|
||||
Lambda expression is a block with optional argument list ending with `->`. If argument list is omitted,
|
||||
the call arguments will be assigned to `it`:
|
||||
|
||||
lambda = {
|
||||
it + "!"
|
||||
}
|
||||
assert( lambda is Callable)
|
||||
assert( lambda("hello") == "hello!" )
|
||||
void
|
||||
|
||||
### `it` assignment rules
|
||||
|
||||
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
|
||||
|
||||
// call the callable stored in the var
|
||||
taskAlias()
|
||||
// or directly:
|
||||
someTask()
|
||||
|
||||
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)
|
||||
|
||||
Lyng has built-in mutable array class `List` with simple literals:
|
||||
|
||||
[1, "two", 3.33].size
|
||||
>>> 3
|
||||
|
||||
[List] is an implementation of the type `Array`, and through it `Collection` and [Iterable].
|
||||
|
||||
Lists can contain any type of objects, lists too:
|
||||
|
||||
val list = [1, [2, 3], 4]
|
||||
assert( list is List ) // concrete implementatino
|
||||
assert( list is Array ) // general interface
|
||||
assert(list.size == 3)
|
||||
// second element is a list too:
|
||||
assert(list[1].size == 2)
|
||||
>>> void
|
||||
|
||||
Notice usage of indexing. You can use negative indexes to offset from the end of the list; see more in [Lists](List.md).
|
||||
|
||||
When you want to "flatten" it to single array, you can use splat syntax:
|
||||
|
||||
[1, ...[2,3], 4]
|
||||
>>> [1, 2, 3, 4]
|
||||
|
||||
Of course, you can splat from anything that is List (or list-like, but it will be defined later):
|
||||
|
||||
val a = ["one", "two"]
|
||||
val b = [10.1, 20.2]
|
||||
["start", ...b, ...a, "end"]
|
||||
>>> ["start", 10.1, 20.2, "one", "two", "end"]
|
||||
|
||||
Of course, you can set any list element:
|
||||
|
||||
val a = [1, 2, 3]
|
||||
a[1] = 200
|
||||
a
|
||||
>>> [1, 200, 3]
|
||||
|
||||
Lists are comparable, and it works well as long as their respective elements are:
|
||||
|
||||
assert( [1,2,3] == [1,2,3])
|
||||
|
||||
// but they are _different_ objects:
|
||||
assert( [1,2,3] !== [1,2,3])
|
||||
|
||||
// when sizes are different, but common part is equal,
|
||||
// longer is greater
|
||||
assert( [1,2,3] > [1,2] )
|
||||
|
||||
// otherwise, where the common part is greater, the list is greater:
|
||||
assert( [1,2,3] < [1,3] )
|
||||
>>> void
|
||||
|
||||
The simplest way to concatenate lists is using `+` and `+=`:
|
||||
|
||||
// + works to concatenate iterables:
|
||||
assert( [5, 4] + ["foo", 2] == [5, 4, "foo", 2])
|
||||
var list = [1, 2]
|
||||
|
||||
// append allow adding iterables: all elements of it:
|
||||
list += [2, 1]
|
||||
// or you can append a single element:
|
||||
list += "end"
|
||||
assert( list == [1, 2, 2, 1, "end"])
|
||||
>>> void
|
||||
|
||||
***Important note***: the pitfall of using `+=` is that you can't append in [Iterable] instance as an object: it will always add all its contents. Use `list.add` to add a single iterable instance:
|
||||
|
||||
var list = [1, 2]
|
||||
val other = [3, 4]
|
||||
|
||||
// appending lists is clear:
|
||||
list += other
|
||||
assert( list == [1, 2, 3, 4] )
|
||||
|
||||
// but appending other Iterables could be confusing:
|
||||
list += (10..12)
|
||||
assert( list == [1, 2, 3, 4, 10, 11, 12])
|
||||
>>> void
|
||||
|
||||
Use `list.add` to avoid confusion:
|
||||
|
||||
var list = [1, 2]
|
||||
val other = [3, 4]
|
||||
|
||||
// appending lists is clear:
|
||||
list.add(other)
|
||||
assert( list == [1, 2, [3, 4]] )
|
||||
|
||||
// but appending other Iterables could be confusing:
|
||||
list.add(10..12)
|
||||
assert( list == [1, 2, [3, 4], (10..12)])
|
||||
>>> void
|
||||
|
||||
|
||||
To add elements to the list:
|
||||
|
||||
val x = [1,2]
|
||||
x.add(3)
|
||||
assert( x == [1,2,3])
|
||||
// same as x += ["the", "end"] but faster:
|
||||
x.add("the", "end")
|
||||
assert( x == [1, 2, 3, "the", "end"])
|
||||
>>> void
|
||||
|
||||
Self-modifying concatenation by `+=` also works:
|
||||
|
||||
val x = [1, 2]
|
||||
x += [3, 4]
|
||||
assert( x == [1, 2, 3, 4])
|
||||
>>> void
|
||||
|
||||
You can insert elements at any position using `addAt`:
|
||||
|
||||
val x = [1,2,3]
|
||||
x.addAt(1, "foo", "bar")
|
||||
assert( x == [1, "foo", "bar", 2, 3])
|
||||
>>> void
|
||||
|
||||
Using splat arguments can simplify inserting list in list:
|
||||
|
||||
val x = [1, 2, 3]
|
||||
x.addAt( 1, ...[0,100,0])
|
||||
x
|
||||
>>> [1, 0, 100, 0, 2, 3]
|
||||
|
||||
Using negative indexes can insert elements as offset from the end, for example:
|
||||
|
||||
val x = [1,2,3]
|
||||
x.addAt(-1, 10)
|
||||
x
|
||||
>>> [1, 2, 10, 3]
|
||||
|
||||
Note that to add to the end you still need to use `add` or positive index of the after-last element:
|
||||
|
||||
val x = [1,2,3]
|
||||
x.addAt(3, 10)
|
||||
x
|
||||
>>> [1, 2, 3, 10]
|
||||
|
||||
## Removing list items
|
||||
|
||||
val x = [1, 2, 3, 4, 5]
|
||||
x.removeAt(2)
|
||||
assert( x == [1, 2, 4, 5])
|
||||
// or remove range (start inclusive, end exclusive):
|
||||
x.removeRangeInclusive(1,2)
|
||||
assert( x == [1, 5])
|
||||
>>> void
|
||||
|
||||
Again, you can use negative indexes. For example, removing last elements like:
|
||||
|
||||
val x = [1, 2, 3, 4, 5]
|
||||
|
||||
// remove last:
|
||||
x.removeAt(-1)
|
||||
assert( x == [1, 2, 3, 4])
|
||||
|
||||
// remove 2 last:
|
||||
x.removeRangeInclusive(-2,-1)
|
||||
assert( x == [1, 2])
|
||||
>>> void
|
||||
|
||||
# Flow control operators
|
||||
|
||||
## if-then-else
|
||||
|
||||
As everywhere else, and as expression:
|
||||
|
||||
val count = 11
|
||||
if( count > 10 )
|
||||
println("too much")
|
||||
else {
|
||||
// do something else
|
||||
println("just "+count)
|
||||
}
|
||||
>>> too much
|
||||
>>> void
|
||||
|
||||
Notice returned value `void`: it is because of `println` have no return value, e.g., `void`.
|
||||
|
||||
Or, more neat:
|
||||
|
||||
var count = 3
|
||||
println( if( count > 10 ) "too much" else "just " + count )
|
||||
>>> just 3
|
||||
>>> void
|
||||
|
||||
## while
|
||||
|
||||
Regular pre-condition while loop, as expression, loop returns it's last line result:
|
||||
|
||||
var count = 0
|
||||
while( count < 5 ) {
|
||||
count++
|
||||
count * 10
|
||||
}
|
||||
>>> 50
|
||||
|
||||
We can break as usual:
|
||||
|
||||
var count = 0
|
||||
while( count < 5 ) {
|
||||
if( count < 5 ) break
|
||||
count = ++count * 10
|
||||
}
|
||||
>>> void
|
||||
|
||||
Why `void`? Because `break` drops out without the chute, not providing anything to return. Indeed, we should provide
|
||||
exit value in the case:
|
||||
|
||||
var count = 0
|
||||
while( count < 50 ) {
|
||||
if( count > 3 ) break "too much"
|
||||
count = ++count * 10
|
||||
"wrong "+count
|
||||
}
|
||||
>>> "too much"
|
||||
|
||||
### Breaking nested loops
|
||||
|
||||
If you have several loops and want to exit not the inner one, use labels:
|
||||
|
||||
var count = 0
|
||||
// notice the label:
|
||||
outerLoop@ while( count < 5 ) {
|
||||
var innerCount = 0
|
||||
while( innerCount < 100 ) {
|
||||
innerCount = innerCount + 1
|
||||
|
||||
if( innerCount == 5 && count == 2 )
|
||||
// and here we break the labelled loop:
|
||||
break@outerLoop "5/2 situation"
|
||||
}
|
||||
count = count + 1
|
||||
count * 10
|
||||
}
|
||||
>>> "5/2 situation"
|
||||
|
||||
### and continue
|
||||
|
||||
We can skip the rest of the loop and restart it, as usual, with `continue` operator.
|
||||
|
||||
var count = 0
|
||||
var countEven = 0
|
||||
while( count < 10 ) {
|
||||
count = count + 1
|
||||
if( count % 2 == 1) continue
|
||||
countEven = countEven + 1
|
||||
}
|
||||
"found even numbers: " + countEven
|
||||
>>> "found even numbers: 5"
|
||||
|
||||
`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 total = 0
|
||||
// notice the label:
|
||||
outerLoop@ while( count++ < 5 ) {
|
||||
var innerCount = 0
|
||||
while( innerCount < 10 ) {
|
||||
if( ++innerCount == 10 )
|
||||
continue@outerLoop
|
||||
}
|
||||
// we don't reach it because continue above restarts our loop
|
||||
total = total + 1
|
||||
}
|
||||
total
|
||||
>>> 0
|
||||
|
||||
Notice that `total` remains 0 as the end of the outerLoop@ is not reachable: `continue` is always called and always make
|
||||
Lyng to skip it.
|
||||
|
||||
## else statement
|
||||
|
||||
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,
|
||||
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.
|
||||
|
||||
|
||||
## For loops
|
||||
|
||||
For loop are intended to traverse collections, and all other objects that supports
|
||||
size and index access, like lists:
|
||||
|
||||
var letters = 0
|
||||
for( w in ["hello", "wolrd"]) {
|
||||
letters += w.length
|
||||
}
|
||||
"total letters: "+letters
|
||||
>>> "total letters: 10"
|
||||
|
||||
For loop support breaks the same as while loops above:
|
||||
|
||||
fun search(haystack, needle) {
|
||||
for(ch in haystack) {
|
||||
if( ch == needle)
|
||||
break "found"
|
||||
}
|
||||
else null
|
||||
}
|
||||
assert( search("hello", 'l') == "found")
|
||||
assert( search("hello", 'z') == null)
|
||||
>>> void
|
||||
|
||||
We can use labels too:
|
||||
|
||||
fun search(haystacks, needle) {
|
||||
exit@ for( hs in haystacks ) {
|
||||
for(ch in hs ) {
|
||||
if( ch == needle)
|
||||
break@exit "found"
|
||||
}
|
||||
}
|
||||
else null
|
||||
}
|
||||
assert( search(["hello", "world"], 'l') == "found")
|
||||
assert( search(["hello", "world"], 'z') == null)
|
||||
>>> void
|
||||
|
||||
# Self-assignments in expression
|
||||
|
||||
There are auto-increments and auto-decrements:
|
||||
|
||||
var counter = 0
|
||||
assert(counter++ * 100 == 0)
|
||||
assert(counter == 1)
|
||||
>>> void
|
||||
|
||||
but:
|
||||
|
||||
var counter = 0
|
||||
assert( ++counter * 100 == 100)
|
||||
assert(counter == 1)
|
||||
>>> void
|
||||
|
||||
The same with `--`:
|
||||
|
||||
var count = 100
|
||||
var sum = 0
|
||||
while( count > 0 ) sum = sum + count--
|
||||
sum
|
||||
>>> 5050
|
||||
|
||||
There are self-assigning version for operators too:
|
||||
|
||||
var count = 100
|
||||
var sum = 0
|
||||
while( count > 0 ) sum += count--
|
||||
sum
|
||||
>>> 5050
|
||||
|
||||
# Ranges
|
||||
|
||||
Ranges are convenient to represent the interval between two values:
|
||||
|
||||
5 in (0..100)
|
||||
>>> true
|
||||
|
||||
It could be open and closed:
|
||||
|
||||
assert( 5 in (1..5) )
|
||||
assert( 5 !in (1..<5) )
|
||||
>>> void
|
||||
|
||||
Ranges could be inside other ranges:
|
||||
|
||||
assert( (2..3) in (1..10) )
|
||||
>>> void
|
||||
|
||||
There are character ranges too:
|
||||
|
||||
'd' in 'a'..'e'
|
||||
>>> true
|
||||
|
||||
and you can use ranges in for-loops:
|
||||
|
||||
for( x in 'a' ..< 'c' ) println(x)
|
||||
>>> a
|
||||
>>> b
|
||||
>>> void
|
||||
|
||||
See [Ranges](Range.md) for detailed documentation on it.
|
||||
|
||||
# Comments
|
||||
|
||||
// single line comment
|
||||
var result = null // here we will store the result
|
||||
>>> void
|
||||
|
||||
# Integral data types
|
||||
|
||||
| type | description | literal samples |
|
||||
@@ -117,11 +801,41 @@ If you need to create _unnamed_ function, use alternative syntax (TBD, like { ->
|
||||
| Int | 64 bit signed | `1` `-22` `0x1FF` |
|
||||
| Real | 64 bit double | `1.0`, `2e-11` |
|
||||
| Bool | boolean | `true` `false` |
|
||||
| Char | single unicode character | `'S'`, `'\n'` |
|
||||
| String | unicode string, no limits | "hello" (see below) |
|
||||
| List | mutable list | [1, "two", 3] |
|
||||
| Void | no value could exist, singleton | void |
|
||||
| Null | missing value, singleton | null |
|
||||
| Fn | callable type | |
|
||||
|
||||
See also [math operations](math.md)
|
||||
|
||||
## Character details
|
||||
|
||||
The type for the character objects is `Char`.
|
||||
|
||||
### Char literal escapes
|
||||
|
||||
Are the same as in string literals with little difference:
|
||||
|
||||
| escape | ASCII value |
|
||||
|--------|-------------------|
|
||||
| \n | 0x10, newline |
|
||||
| \t | 0x07, tabulation |
|
||||
| \\ | \ slash character |
|
||||
| \' | ' apostrophe |
|
||||
|
||||
### Char instance members
|
||||
|
||||
assert( 'a'.code == 0x61 )
|
||||
>>> void
|
||||
|
||||
| member | type | meaning |
|
||||
|--------|------|--------------------------------|
|
||||
| code | Int | Unicode code for the character |
|
||||
| | | |
|
||||
|
||||
|
||||
## String details
|
||||
|
||||
### String operations
|
||||
@@ -132,28 +846,31 @@ Concatenation is a `+`: `"hello " + name` works as expected. No confusion.
|
||||
|
||||
String literal could be multiline:
|
||||
|
||||
"
|
||||
Hello,
|
||||
World!
|
||||
"
|
||||
>>> "Hello
|
||||
"Hello
|
||||
World"
|
||||
|
||||
In that case compiler removes left margin and first/last empty lines. Note that it won't remove margin:
|
||||
though multiline literals is yet work in progress.
|
||||
|
||||
"Hello,
|
||||
World
|
||||
"
|
||||
>>> "Hello,
|
||||
World
|
||||
"
|
||||
# Built-in functions
|
||||
|
||||
because the first line has no margin in the literal.
|
||||
See [math functions](math.md). Other general purpose functions are:
|
||||
|
||||
# Comments
|
||||
|
||||
// single line comment
|
||||
var result = null // here we will store the result
|
||||
| name | description |
|
||||
|----------------------------------------------|----------------------------------------------------------|
|
||||
| assert(condition,message="assertion failed") | runtime code check. There will be an option to skip them |
|
||||
| println(args...) | Open for overriding, it prints to stdout. |
|
||||
|
||||
# Built-in constants
|
||||
|
||||
| name | description |
|
||||
|-------------------------------------|------------------------------|
|
||||
| Real, Int, List, String, List, Bool | Class types for real numbers |
|
||||
| π | See [math](math.md) |
|
||||
|
||||
[List]: List.md
|
||||
[Iterable]: Iterable.md
|
||||
[Iterator]: Iterator.md
|
||||
[Real]: Real.md
|
||||
[Range]: Range.md
|
||||
|
||||
|
||||
+3
-1
@@ -4,9 +4,11 @@ org.gradle.caching=true
|
||||
org.gradle.configuration-cache=true
|
||||
#Kotlin
|
||||
kotlin.code.style=official
|
||||
kotlin.js.compiler=ir
|
||||
#MPP
|
||||
kotlin.mpp.enableCInteropCommonization=true
|
||||
#Android
|
||||
android.useAndroidX=true
|
||||
android.nonTransitiveRClass=true
|
||||
|
||||
# other
|
||||
kotlin.native.cacheKind.linuxX64=none
|
||||
@@ -1,16 +1,24 @@
|
||||
[versions]
|
||||
agp = "8.5.2"
|
||||
clikt = "5.0.3"
|
||||
kotlin = "2.1.21"
|
||||
android-minSdk = "24"
|
||||
android-compileSdk = "34"
|
||||
kotlinx-coroutines = "1.10.1"
|
||||
mp_bintools = "0.1.12"
|
||||
firebaseCrashlyticsBuildtools = "3.0.3"
|
||||
okioVersion = "3.10.2"
|
||||
|
||||
[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" }
|
||||
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" }
|
||||
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]
|
||||
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)
|
||||
@@ -11,7 +11,7 @@ plugins {
|
||||
}
|
||||
|
||||
group = "net.sergeych"
|
||||
version = "0.0.1-SNAPSHOT"
|
||||
version = "0.2.0-SNAPSHOT"
|
||||
|
||||
kotlin {
|
||||
jvm()
|
||||
@@ -26,7 +26,7 @@ kotlin {
|
||||
// iosArm64()
|
||||
// iosSimulatorArm64()
|
||||
linuxX64()
|
||||
js(IR) {
|
||||
js {
|
||||
browser()
|
||||
nodejs()
|
||||
}
|
||||
@@ -44,11 +44,13 @@ kotlin {
|
||||
}
|
||||
|
||||
val commonMain by getting {
|
||||
kotlin.srcDir("$buildDir/generated/buildConfig/commonMain/kotlin")
|
||||
dependencies {
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1")
|
||||
//put your multiplatform dependencies here
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
implementation(libs.mp.bintools)
|
||||
api(libs.kotlinx.coroutines.core)
|
||||
api(libs.mp.bintools)
|
||||
api("net.sergeych:mp_stools:1.5.2")
|
||||
}
|
||||
}
|
||||
val commonTest by getting {
|
||||
@@ -71,6 +73,9 @@ android {
|
||||
targetCompatibility = JavaVersion.VERSION_11
|
||||
}
|
||||
}
|
||||
dependencies {
|
||||
implementation(libs.firebase.crashlytics.buildtools)
|
||||
}
|
||||
|
||||
mavenPublishing {
|
||||
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
|
||||
@@ -80,7 +85,7 @@ mavenPublishing {
|
||||
coordinates(group.toString(), "library", version.toString())
|
||||
|
||||
pom {
|
||||
name = "Ling language"
|
||||
name = "Lyng language"
|
||||
description = "Kotlin-bound scripting loanguage"
|
||||
inceptionYear = "2025"
|
||||
// url = "https://sergeych.net"
|
||||
@@ -105,3 +110,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,19 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
data class Arguments(val callerPos: Pos,val list: List<Info>) {
|
||||
|
||||
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("".toSource().startPos,emptyList())
|
||||
}
|
||||
}
|
||||
@@ -1,504 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
//sealed class ObjType(name: String, val defaultValue: Obj? = null) {
|
||||
//
|
||||
// class Str : ObjType("string", ObjString(""))
|
||||
// class Int : ObjType("real", ObjReal(0.0))
|
||||
//
|
||||
//}
|
||||
//
|
||||
///**
|
||||
// * Descriptor for whatever object could be used as argument, return value,
|
||||
// * field, etc.
|
||||
// */
|
||||
//data class ObjDescriptor(
|
||||
// val type: ObjType,
|
||||
// val mutable: Boolean,
|
||||
//)
|
||||
//
|
||||
//data class MethodDescriptor(
|
||||
// val args: Array<ObjDescriptor>,
|
||||
// val result: ObjDescriptor
|
||||
//)
|
||||
|
||||
/*
|
||||
Meta context contains map of symbols.
|
||||
|
||||
Each symbol can be:
|
||||
|
||||
- a var
|
||||
- a const
|
||||
- a function
|
||||
- a type alias
|
||||
- a class definition
|
||||
|
||||
Each have in common only its name.
|
||||
|
||||
Var has: type, value. Const is same as var but value is fixed. Function has args and return value,
|
||||
type alias has target type name. So we have to have something that denotes a _type_
|
||||
|
||||
*/
|
||||
|
||||
|
||||
//data class MetaContext(val symbols: MutableMap<String, > = mutableMapOf()) {
|
||||
//
|
||||
//}
|
||||
|
||||
|
||||
class Compiler {
|
||||
|
||||
fun compile(source: Source): Script {
|
||||
return parseScript(source.startPos, parseLing(source).listIterator())
|
||||
}
|
||||
|
||||
private fun parseScript(start: Pos, tokens: ListIterator<Token>): Script {
|
||||
val statements = mutableListOf<Statement>()
|
||||
while (parseStatement(tokens)?.also {
|
||||
statements += it
|
||||
} != null) {/**/
|
||||
}
|
||||
return Script(start, statements)
|
||||
}
|
||||
|
||||
private fun parseStatement(tokens: ListIterator<Token>): Statement? {
|
||||
while (true) {
|
||||
val t = tokens.next()
|
||||
return when (t.type) {
|
||||
Token.Type.ID -> {
|
||||
// could be keyword, assignment or just the expression
|
||||
val next = tokens.next()
|
||||
if (next.type == Token.Type.ASSIGN) {
|
||||
// this _is_ assignment statement
|
||||
return AssignStatement(
|
||||
t.pos, t.value,
|
||||
parseExpression(tokens) ?: throw ScriptError(
|
||||
t.pos,
|
||||
"Expecting expression for assignment operator"
|
||||
)
|
||||
)
|
||||
}
|
||||
// not assignment, maybe keyword statement:
|
||||
// get back the token which is not '=':
|
||||
tokens.previous()
|
||||
// try keyword statement
|
||||
parseKeywordStatement(t, tokens)
|
||||
?: run {
|
||||
tokens.previous()
|
||||
parseExpression(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
Token.Type.SINLGE_LINE_COMMENT, Token.Type.MULTILINE_COMMENT -> continue
|
||||
|
||||
Token.Type.SEMICOLON -> continue
|
||||
|
||||
Token.Type.LBRACE -> {
|
||||
tokens.previous()
|
||||
parseBlock(tokens)
|
||||
}
|
||||
|
||||
Token.Type.RBRACE -> {
|
||||
tokens.previous()
|
||||
return null
|
||||
}
|
||||
|
||||
Token.Type.EOF -> null
|
||||
|
||||
else -> {
|
||||
// could be expression
|
||||
tokens.previous()
|
||||
parseExpression(tokens)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseExpression(tokens: ListIterator<Token>, level: Int = 0): Statement? {
|
||||
if (level == lastLevel)
|
||||
return parseTerm(tokens)
|
||||
var lvalue = parseExpression(tokens, level + 1)
|
||||
if (lvalue == null) return null
|
||||
|
||||
while (true) {
|
||||
|
||||
val opToken = tokens.next()
|
||||
val op = byLevel[level][opToken.type]
|
||||
if (op == null) {
|
||||
tokens.previous()
|
||||
break
|
||||
}
|
||||
|
||||
val rvalue = parseExpression(tokens, level + 1)
|
||||
?: throw ScriptError(opToken.pos, "Expecting expression")
|
||||
|
||||
lvalue = op.generate(opToken.pos, lvalue!!, rvalue)
|
||||
}
|
||||
return lvalue
|
||||
}
|
||||
|
||||
fun parseTerm(tokens: ListIterator<Token>): Statement? {
|
||||
// call op
|
||||
// index op
|
||||
// unary op
|
||||
// parenthesis
|
||||
// number or string
|
||||
val t = tokens.next()
|
||||
// todoL var?
|
||||
return when (t.type) {
|
||||
Token.Type.ID -> {
|
||||
when (t.value) {
|
||||
"void" -> statement(t.pos, true) { ObjVoid }
|
||||
"null" -> statement(t.pos, true) { ObjNull }
|
||||
"true" -> statement(t.pos, true) { ObjBool(true) }
|
||||
"false" -> statement(t.pos, true) { ObjBool(false) }
|
||||
else -> parseVarAccess(t, tokens)
|
||||
}
|
||||
}
|
||||
|
||||
Token.Type.STRING -> statement(t.pos, true) { ObjString(t.value) }
|
||||
|
||||
Token.Type.LPAREN -> {
|
||||
// ( subexpr )
|
||||
parseExpression(tokens)?.also {
|
||||
val tl = tokens.next()
|
||||
if (tl.type != Token.Type.RPAREN)
|
||||
throw ScriptError(t.pos, "unbalanced parenthesis: no ')' for it")
|
||||
}
|
||||
}
|
||||
|
||||
Token.Type.PLUS -> {
|
||||
val n = parseNumber(true, tokens)
|
||||
statement(t.pos, true) { n }
|
||||
}
|
||||
|
||||
Token.Type.MINUS -> {
|
||||
val n = parseNumber(false, tokens)
|
||||
statement(t.pos, true) { n }
|
||||
}
|
||||
|
||||
Token.Type.INT, Token.Type.REAL, Token.Type.HEX -> {
|
||||
tokens.previous()
|
||||
val n = parseNumber(true, tokens)
|
||||
statement(t.pos, true) { n }
|
||||
}
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun parseVarAccess(id: Token, tokens: ListIterator<Token>, path: List<String> = emptyList()): Statement {
|
||||
val nt = tokens.next()
|
||||
|
||||
fun resolve(context: Context): Context {
|
||||
var targetContext = context
|
||||
for (n in path) {
|
||||
val x = targetContext[n] ?: throw ScriptError(id.pos, "undefined symbol: $n")
|
||||
(x.value as? ObjNamespace)?.let { targetContext = it.context }
|
||||
?: throw ScriptError(id.pos, "Invalid symbolic path (wrong type of ${x.name}: ${x.value}")
|
||||
}
|
||||
return targetContext
|
||||
}
|
||||
return when (nt.type) {
|
||||
Token.Type.DOT -> {
|
||||
// selector
|
||||
val t = tokens.next()
|
||||
if (t.type == Token.Type.ID) {
|
||||
parseVarAccess(t, tokens, path + id.value)
|
||||
} else
|
||||
throw ScriptError(t.pos, "Expected identifier after '.'")
|
||||
}
|
||||
|
||||
Token.Type.LPAREN -> {
|
||||
// function call
|
||||
// Load arg list
|
||||
val args = mutableListOf<Arguments.Info>()
|
||||
do {
|
||||
val t = tokens.next()
|
||||
when (t.type) {
|
||||
Token.Type.RPAREN, Token.Type.COMMA -> {}
|
||||
else -> {
|
||||
tokens.previous()
|
||||
parseExpression(tokens)?.let { args += Arguments.Info(it, t.pos) }
|
||||
?: throw ScriptError(t.pos, "Expecting arguments list")
|
||||
}
|
||||
}
|
||||
} while (t.type != Token.Type.RPAREN)
|
||||
|
||||
statement(id.pos) { context ->
|
||||
val v =
|
||||
resolve(context).get(id.value) ?: throw ScriptError(id.pos, "Undefined function: ${id.value}")
|
||||
(v.value as? Statement)?.execute(
|
||||
context.copy(
|
||||
Arguments(
|
||||
nt.pos,
|
||||
args.map { Arguments.Info((it.value as Statement).execute(context), it.pos) }
|
||||
)
|
||||
)
|
||||
)
|
||||
?: throw ScriptError(id.pos, "Variable $id is not callable ($id)")
|
||||
}
|
||||
}
|
||||
|
||||
Token.Type.LBRACKET -> {
|
||||
TODO("indexing")
|
||||
}
|
||||
|
||||
else -> {
|
||||
// just access the var
|
||||
tokens.previous()
|
||||
statement(id.pos) {
|
||||
val v = resolve(it).get(id.value) ?: throw ScriptError(id.pos, "Undefined variable: ${id.value}")
|
||||
v.value ?: throw ScriptError(id.pos, "Variable $id is not initialized")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fun parseNumber(isPlus: Boolean, tokens: ListIterator<Token>): Obj {
|
||||
val t = tokens.next()
|
||||
return when (t.type) {
|
||||
Token.Type.INT, Token.Type.HEX -> {
|
||||
val n = t.value.toLong(if (t.type == Token.Type.HEX) 16 else 10)
|
||||
if (isPlus) ObjInt(n) else ObjInt(-n)
|
||||
}
|
||||
|
||||
Token.Type.REAL -> {
|
||||
val d = t.value.toDouble()
|
||||
if (isPlus) ObjReal(d) else ObjReal(-d)
|
||||
}
|
||||
|
||||
else -> {
|
||||
throw ScriptError(t.pos, "expected number")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse keyword-starting statenment.
|
||||
* @return parsed statement or null if, for example. [id] is not among keywords
|
||||
*/
|
||||
private fun parseKeywordStatement(id: Token, tokens: ListIterator<Token>): Statement? = when (id.value) {
|
||||
"val" -> parseVarDeclaration(id.value, false, tokens)
|
||||
"var" -> parseVarDeclaration(id.value, true, tokens)
|
||||
"fn", "fun" -> parseFunctionDeclaration(tokens)
|
||||
"if" -> parseIfStatement(tokens)
|
||||
else -> null
|
||||
}
|
||||
|
||||
private fun parseIfStatement(tokens: ListIterator<Token>): Statement {
|
||||
var t = tokens.next()
|
||||
val start = t.pos
|
||||
if( t.type != Token.Type.LPAREN)
|
||||
throw ScriptError(t.pos, "Bad if statement: expected '('")
|
||||
|
||||
val condition = parseExpression(tokens)
|
||||
?: throw ScriptError(t.pos, "Bad if statement: expected expression")
|
||||
|
||||
t = tokens.next()
|
||||
if( t.type != Token.Type.RPAREN)
|
||||
throw ScriptError(t.pos, "Bad if statement: expected ')' after condition expression")
|
||||
|
||||
val ifBody = parseStatement(tokens) ?: throw ScriptError(t.pos, "Bad if statement: expected statement")
|
||||
|
||||
// could be else block:
|
||||
val t2 = tokens.next()
|
||||
|
||||
// we generate different statements: optimization
|
||||
return if( t2.type == Token.Type.ID && t2.value == "else") {
|
||||
val elseBody = parseStatement(tokens) ?: throw ScriptError(t.pos, "Bad else statement: expected statement")
|
||||
return statement(start) {
|
||||
if (condition.execute(it).toBool())
|
||||
ifBody.execute(it)
|
||||
else
|
||||
elseBody.execute(it)
|
||||
}
|
||||
}
|
||||
else {
|
||||
tokens.previous()
|
||||
statement(start) {
|
||||
if (condition.execute(it).toBool())
|
||||
ifBody.execute(it)
|
||||
else
|
||||
ObjVoid
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class FnParamDef(
|
||||
val name: String,
|
||||
val pos: Pos,
|
||||
val defaultValue: Statement? = null
|
||||
)
|
||||
|
||||
private fun parseFunctionDeclaration(tokens: ListIterator<Token>): Statement {
|
||||
var t = tokens.next()
|
||||
val start = t.pos
|
||||
val name = if (t.type != Token.Type.ID)
|
||||
throw ScriptError(t.pos, "Expected identifier after 'fn'")
|
||||
else t.value
|
||||
|
||||
t = tokens.next()
|
||||
if (t.type != Token.Type.LPAREN)
|
||||
throw ScriptError(t.pos, "Bad function definition: expected '(' after 'fn ${name}'")
|
||||
val params = mutableListOf<FnParamDef>()
|
||||
var defaultListStarted = false
|
||||
do {
|
||||
t = tokens.next()
|
||||
if (t.type == Token.Type.RPAREN)
|
||||
break
|
||||
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
|
||||
val fnStatements = parseBlock(tokens)
|
||||
|
||||
val fnBody = statement(t.pos) { context ->
|
||||
// load params
|
||||
for ((i, d) in params.withIndex()) {
|
||||
if (i < context.args.size)
|
||||
context.addItem(d.name, false, context.args.list[i].value)
|
||||
else
|
||||
context.addItem(
|
||||
d.name,
|
||||
false,
|
||||
d.defaultValue?.execute(context)
|
||||
?: throw ScriptError(
|
||||
context.args.callerPos,
|
||||
"missing required argument #${1 + i}: ${d.name}"
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
fnStatements.execute(context)
|
||||
}
|
||||
return statement(start) { context ->
|
||||
context.addItem(name, false, fnBody)
|
||||
fnBody
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseBlock(tokens: ListIterator<Token>): Statement {
|
||||
val t = tokens.next()
|
||||
if (t.type != Token.Type.LBRACE)
|
||||
throw ScriptError(t.pos, "Expected block body start: {")
|
||||
val block = parseScript(t.pos, tokens)
|
||||
return statement(t.pos) {
|
||||
// block run on inner context:
|
||||
block.execute(it.copy())
|
||||
}.also {
|
||||
val t1 = tokens.next()
|
||||
if (t1.type != Token.Type.RBRACE)
|
||||
throw ScriptError(t1.pos, "unbalanced braces: expected block body end: }")
|
||||
}
|
||||
}
|
||||
|
||||
private fun parseVarDeclaration(kind: String, mutable: Boolean, tokens: ListIterator<Token>): Statement {
|
||||
val nameToken = tokens.next()
|
||||
if (nameToken.type != Token.Type.ID)
|
||||
throw ScriptError(nameToken.pos, "Expected identifier after '$kind'")
|
||||
val name = nameToken.value
|
||||
val eqToken = tokens.next()
|
||||
var setNull = false
|
||||
if (eqToken.type != Token.Type.ASSIGN) {
|
||||
if (!mutable)
|
||||
throw ScriptError(eqToken.pos, "Expected initializer: '=' after '$kind ${name}'")
|
||||
else {
|
||||
tokens.previous()
|
||||
setNull = true
|
||||
}
|
||||
}
|
||||
val initialExpression = if (setNull) null else parseExpression(tokens)
|
||||
?: throw ScriptError(eqToken.pos, "Expected initializer expression")
|
||||
return statement(nameToken.pos) { context ->
|
||||
if (context.containsLocal(name))
|
||||
throw ScriptError(nameToken.pos, "Variable $name is already defined")
|
||||
val initValue = initialExpression?.execute(context) ?: ObjNull
|
||||
context.addItem(name, mutable, initValue)
|
||||
ObjVoid
|
||||
}
|
||||
}
|
||||
|
||||
// fun parseStatement(parser: Parser): Statement? =
|
||||
// parser.withToken {
|
||||
// if (tokens.isEmpty()) null
|
||||
// else {
|
||||
// when (val token = tokens[0]) {
|
||||
// else -> {
|
||||
// rollback()
|
||||
// null
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
data class Operator(
|
||||
val tokenType: Token.Type,
|
||||
val priority: Int, val arity: Int,
|
||||
val generate: (Pos, Statement, Statement) -> Statement
|
||||
)
|
||||
|
||||
companion object {
|
||||
|
||||
val allOps = listOf(
|
||||
Operator(Token.Type.OR, 0, 2) { pos, a, b -> LogicalOrStatement(pos, a, b) },
|
||||
Operator(Token.Type.AND, 1, 2) { pos, a, b -> LogicalAndStatement(pos, a, b) },
|
||||
// bitwise or 2
|
||||
// bitwise and 3
|
||||
// equality/ne 4
|
||||
LogicalOp(Token.Type.EQ, 4) { a, b -> a == b },
|
||||
LogicalOp(Token.Type.NEQ, 4) { a, b -> a != b },
|
||||
// relational <=,... 5
|
||||
LogicalOp(Token.Type.LTE, 5) { a, b -> a <= b },
|
||||
LogicalOp(Token.Type.LT, 5) { a, b -> a < b },
|
||||
LogicalOp(Token.Type.GTE, 5) { a, b -> a >= b },
|
||||
LogicalOp(Token.Type.GT, 5) { a, b -> a > b },
|
||||
// shuttle <=> 6
|
||||
// bitshhifts 7
|
||||
Operator(Token.Type.PLUS, 8, 2) { pos, a, b ->
|
||||
PlusStatement(pos, a, b)
|
||||
},
|
||||
Operator(Token.Type.MINUS, 8, 2) { pos, a, b ->
|
||||
MinusStatement(pos, a, b)
|
||||
},
|
||||
Operator(Token.Type.STAR, 9, 2) { pos, a, b -> MulStatement(pos, a, b) },
|
||||
Operator(Token.Type.SLASH, 9, 2) { pos, a, b -> DivStatement(pos, a, b) },
|
||||
Operator(Token.Type.PERCENT, 9, 2) { pos, a, b -> ModStatement(pos, a, b) },
|
||||
)
|
||||
val lastLevel = 10
|
||||
val byLevel: List<Map<Token.Type, Operator>> = (0..<lastLevel).map { l ->
|
||||
allOps.filter { it.priority == l }
|
||||
.map { it.tokenType to it }.toMap()
|
||||
}
|
||||
|
||||
fun compile(code: String): Script = Compiler().compile(Source("<eval>", code))
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun eval(code: String) = Compiler.compile(code).execute()
|
||||
|
||||
fun LogicalOp(tokenType: Token.Type, priority: Int, f: (Obj, Obj) -> Boolean) = Compiler.Operator(
|
||||
tokenType,
|
||||
priority,
|
||||
2
|
||||
) { pos, a, b ->
|
||||
statement(pos) {
|
||||
ObjBool(
|
||||
f(a.execute(it), b.execute(it))
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
class Context(
|
||||
val parent: Context? = Script.defaultContext.copy(),
|
||||
val args: Arguments = Arguments.EMPTY
|
||||
) {
|
||||
|
||||
data class Item(
|
||||
val name: String,
|
||||
var value: Obj?,
|
||||
val isMutable: Boolean = false
|
||||
)
|
||||
|
||||
private val objects = mutableMapOf<String, Item>()
|
||||
|
||||
operator fun get(name: String): Item? = objects[name] ?: parent?.get(name)
|
||||
|
||||
fun copy(args: Arguments = Arguments.EMPTY): Context = Context(this, args)
|
||||
|
||||
fun addItem(name: String, isMutable: Boolean, value: Obj?) {
|
||||
objects.put(name, Item(name, value, isMutable))
|
||||
}
|
||||
|
||||
fun getOrCreateNamespace(name: String) =
|
||||
(objects.getOrPut(name) { Item(name, ObjNamespace(name,copy()), isMutable = false) }.value as ObjNamespace)
|
||||
.context
|
||||
|
||||
inline fun <reified T> addFn(vararg names: String, crossinline fn: suspend Context.() -> T) {
|
||||
val newFn = object : Statement() {
|
||||
override val pos: Pos = Pos.builtIn
|
||||
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
return try {
|
||||
from(context.fn())
|
||||
|
||||
} catch (e: Exception) {
|
||||
raise(e.message ?: "unexpected error")
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name in names) {
|
||||
addItem(
|
||||
name,
|
||||
false,
|
||||
newFn
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <reified T> addConst(value: T,vararg names: String) {
|
||||
val obj = Obj.from(value)
|
||||
for (name in names) {
|
||||
addItem(
|
||||
name,
|
||||
false,
|
||||
obj
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun eval(code: String): Obj =
|
||||
Compiler().compile(code.toSource()).execute(this)
|
||||
|
||||
fun containsLocal(name: String): Boolean = name in objects
|
||||
|
||||
companion object {
|
||||
operator fun invoke() = Context()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlin.math.floor
|
||||
|
||||
@Serializable
|
||||
sealed class Obj : Comparable<Obj> {
|
||||
open val asStr: ObjString by lazy {
|
||||
if (this is ObjString) this else ObjString(this.toString())
|
||||
}
|
||||
|
||||
open val type: Type = Type.Any
|
||||
|
||||
@Suppress("unused")
|
||||
enum class Type {
|
||||
@SerialName("Void")
|
||||
Void,
|
||||
@SerialName("Null")
|
||||
Null,
|
||||
@SerialName("String")
|
||||
String,
|
||||
@SerialName("Int")
|
||||
Int,
|
||||
@SerialName("Real")
|
||||
Real,
|
||||
@SerialName("Bool")
|
||||
Bool,
|
||||
@SerialName("Fn")
|
||||
Fn,
|
||||
@SerialName("Any")
|
||||
Any,
|
||||
}
|
||||
|
||||
companion object {
|
||||
inline fun <reified T> from(obj: T): Obj {
|
||||
return when (obj) {
|
||||
is Obj -> obj
|
||||
is Double -> ObjReal(obj)
|
||||
is Float -> ObjReal(obj.toDouble())
|
||||
is Int -> ObjInt(obj.toLong())
|
||||
is Long -> ObjInt(obj)
|
||||
is String -> ObjString(obj)
|
||||
is CharSequence -> ObjString(obj.toString())
|
||||
is Boolean -> ObjBool(obj)
|
||||
Unit -> ObjVoid
|
||||
null -> ObjNull
|
||||
else -> throw IllegalArgumentException("cannot convert to Obj: $obj")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
inline fun <reified T> T.toObj(): Obj = Obj.from(this)
|
||||
|
||||
@Serializable
|
||||
@SerialName("void")
|
||||
object ObjVoid : Obj() {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
return other is ObjVoid || other is Unit
|
||||
}
|
||||
|
||||
override fun compareTo(other: Obj): Int {
|
||||
return if (other === this) 0 else -1
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@SerialName("null")
|
||||
object ObjNull : Obj() {
|
||||
override fun compareTo(other: Obj): Int {
|
||||
return if (other === this) 0 else -1
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
return other is ObjNull || other == null
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@SerialName("string")
|
||||
data class ObjString(val value: String) : Obj() {
|
||||
|
||||
override fun compareTo(other: Obj): Int {
|
||||
if (other !is ObjString) throw IllegalArgumentException("cannot compare string with $other")
|
||||
return this.value.compareTo(other.value)
|
||||
}
|
||||
|
||||
override fun toString(): String = value
|
||||
}
|
||||
|
||||
interface Numeric {
|
||||
val longValue: Long
|
||||
val doubleValue: Double
|
||||
val toObjInt: ObjInt
|
||||
val toObjReal: ObjReal
|
||||
}
|
||||
|
||||
fun Obj.toDouble(): Double =
|
||||
(this as? Numeric)?.doubleValue
|
||||
?: (this as? ObjString)?.value?.toDouble()
|
||||
?: throw IllegalArgumentException("cannot convert to double $this")
|
||||
|
||||
@Suppress("unused")
|
||||
fun Obj.toLong(): Long =
|
||||
(this as? Numeric)?.longValue
|
||||
?: (this as? ObjString)?.value?.toLong()
|
||||
?: throw IllegalArgumentException("cannot convert to double $this")
|
||||
|
||||
fun Obj.toInt(): Int = toLong().toInt()
|
||||
|
||||
fun Obj.toBool(): Boolean = (this as? ObjBool)?.value ?: throw IllegalArgumentException("cannot convert to boolean ${this.type}:$this")
|
||||
|
||||
|
||||
@Serializable
|
||||
@SerialName("real")
|
||||
data class ObjReal(val value: Double) : Obj(), Numeric {
|
||||
override val asStr by lazy { ObjString(value.toString()) }
|
||||
override val longValue: Long by lazy { floor(value).toLong() }
|
||||
override val doubleValue: Double by lazy { value }
|
||||
override val toObjInt: ObjInt by lazy { ObjInt(longValue) }
|
||||
override val toObjReal: ObjReal by lazy { ObjReal(value) }
|
||||
|
||||
override fun compareTo(other: Obj): Int {
|
||||
if( other !is Numeric) throw IllegalArgumentException("cannot compare $this with $other")
|
||||
return value.compareTo(other.doubleValue)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@SerialName("int")
|
||||
data class ObjInt(val value: Long) : Obj(), Numeric {
|
||||
override val asStr by lazy { ObjString(value.toString()) }
|
||||
override val longValue: Long by lazy { value }
|
||||
override val doubleValue: Double by lazy { value.toDouble() }
|
||||
override val toObjInt: ObjInt by lazy { ObjInt(value) }
|
||||
override val toObjReal: ObjReal by lazy { ObjReal(doubleValue) }
|
||||
|
||||
override fun compareTo(other: Obj): Int {
|
||||
if( other !is Numeric) throw IllegalArgumentException("cannot compare $this with $other")
|
||||
return value.compareTo(other.doubleValue)
|
||||
}
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@SerialName("bool")
|
||||
data class ObjBool(val value: Boolean) : Obj() {
|
||||
override val asStr by lazy { ObjString(value.toString()) }
|
||||
|
||||
override fun compareTo(other: Obj): Int {
|
||||
if( other !is ObjBool) throw IllegalArgumentException("cannot compare $this with $other")
|
||||
return value.compareTo(other.value)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
data class ObjNamespace(val name: String, val context: Context) : Obj() {
|
||||
override fun toString(): String {
|
||||
return "namespace ${name}"
|
||||
}
|
||||
|
||||
override fun compareTo(other: Obj): Int {
|
||||
throw IllegalArgumentException("cannot compare namespaces")
|
||||
}
|
||||
}
|
||||
@@ -1,256 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
private val idFirstChars: Set<Char> = (
|
||||
('a'..'z') + ('A'..'Z') + '_' + ('а'..'я') + ('А'..'Я')
|
||||
).toSet()
|
||||
val idNextChars: Set<Char> = idFirstChars + ('0'..'9')
|
||||
val digits = ('0'..'9').toSet()
|
||||
val hexDigits = digits + ('a'..'f') + ('A'..'F')
|
||||
|
||||
fun parseLing(source: Source): List<Token> {
|
||||
val p = Parser(fromPos = source.startPos)
|
||||
val tokens = mutableListOf<Token>()
|
||||
do {
|
||||
val t = p.nextToken()
|
||||
tokens += t
|
||||
} while (t.type != Token.Type.EOF)
|
||||
return tokens
|
||||
}
|
||||
|
||||
private class Parser(fromPos: Pos) {
|
||||
|
||||
private val pos = MutablePos(fromPos)
|
||||
|
||||
/**
|
||||
* Immutable copy of current position
|
||||
*/
|
||||
private val currentPos: Pos get() = pos.toPos()
|
||||
|
||||
private fun raise(msg: String): Nothing = throw ScriptError(currentPos, msg)
|
||||
|
||||
fun nextToken(): Token {
|
||||
skipws()
|
||||
if (pos.end) return Token("", currentPos, Token.Type.EOF)
|
||||
val from = currentPos
|
||||
return when (val ch = pos.currentChar.also { advance() }) {
|
||||
'(' -> Token("(", from, Token.Type.LPAREN)
|
||||
')' -> Token(")", from, Token.Type.RPAREN)
|
||||
'{' -> Token("{", from, Token.Type.LBRACE)
|
||||
'}' -> Token("}", from, Token.Type.RBRACE)
|
||||
'[' -> Token("[", from, Token.Type.LBRACKET)
|
||||
']' -> Token("]", from, Token.Type.RBRACKET)
|
||||
',' -> Token(",", from, Token.Type.COMMA)
|
||||
';' -> Token(";", from, Token.Type.SEMICOLON)
|
||||
'=' -> {
|
||||
if (pos.currentChar == '=') {
|
||||
advance()
|
||||
Token("==", from, Token.Type.EQ)
|
||||
} else
|
||||
Token("=", from, Token.Type.ASSIGN)
|
||||
}
|
||||
|
||||
'+' -> Token("+", from, Token.Type.PLUS)
|
||||
'-' -> Token("-", from, Token.Type.MINUS)
|
||||
'*' -> Token("*", from, Token.Type.STAR)
|
||||
'/' -> {
|
||||
if( currentChar == '/') {
|
||||
advance()
|
||||
Token(loadToEnd().trim(), from, Token.Type.SINLGE_LINE_COMMENT)
|
||||
}
|
||||
else
|
||||
Token("/", from, Token.Type.SLASH)
|
||||
}
|
||||
'%' -> Token("%", from, Token.Type.PERCENT)
|
||||
'.' -> Token(".", from, Token.Type.DOT)
|
||||
'<' -> {
|
||||
if(currentChar == '=') {
|
||||
advance()
|
||||
Token("<=", from, Token.Type.LTE)
|
||||
}
|
||||
else
|
||||
Token("<", from, Token.Type.LT)
|
||||
}
|
||||
'>' -> {
|
||||
if( currentChar == '=') {
|
||||
advance()
|
||||
Token(">=", from, Token.Type.GTE)
|
||||
}
|
||||
else
|
||||
Token(">", from, Token.Type.GT)
|
||||
}
|
||||
'!' -> {
|
||||
if( currentChar == '=') {
|
||||
advance()
|
||||
Token("!=", from, Token.Type.NEQ)
|
||||
}
|
||||
else
|
||||
Token("!", from, Token.Type.NOT)
|
||||
}
|
||||
'|' -> {
|
||||
if (currentChar == '|') {
|
||||
advance()
|
||||
Token("||", from, Token.Type.OR)
|
||||
} else
|
||||
Token("|", from, Token.Type.BITOR)
|
||||
}
|
||||
'&' -> {
|
||||
if (currentChar == '&') {
|
||||
advance()
|
||||
Token("&&", from, Token.Type.AND)
|
||||
} else
|
||||
Token("&", from, Token.Type.BITAND)
|
||||
}
|
||||
|
||||
'"' -> loadStringToken()
|
||||
in digits -> {
|
||||
pos.back()
|
||||
decodeNumber(loadChars(digits), from)
|
||||
}
|
||||
|
||||
else -> {
|
||||
if (ch.isLetter() || ch == '_')
|
||||
Token(ch + loadChars(idNextChars), from, Token.Type.ID)
|
||||
else
|
||||
raise("can't parse token")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeNumber(p1: String, start: Pos): Token =
|
||||
if (pos.end)
|
||||
Token(p1, start, Token.Type.INT)
|
||||
else if (currentChar == '.') {
|
||||
// could be decimal
|
||||
advance()
|
||||
if (currentChar in digits) {
|
||||
// decimal part
|
||||
val p2 = loadChars(digits)
|
||||
// with exponent?
|
||||
if (currentChar == 'e' || currentChar == 'E') {
|
||||
advance()
|
||||
var negative = false
|
||||
if (currentChar == '+')
|
||||
advance()
|
||||
else if (currentChar == '-') {
|
||||
negative = true
|
||||
advance()
|
||||
}
|
||||
var p3 = loadChars(digits)
|
||||
if (negative) p3 = "-$p3"
|
||||
Token("$p1.${p2}e$p3", start, Token.Type.REAL)
|
||||
} else {
|
||||
// no exponent
|
||||
Token("$p1.$p2", start, Token.Type.REAL)
|
||||
}
|
||||
} else {
|
||||
// not decimal
|
||||
// something like 10.times, method call on integer number
|
||||
pos.back()
|
||||
Token(p1, start, Token.Type.INT)
|
||||
}
|
||||
} else {
|
||||
// could be integer, also hex:
|
||||
if (currentChar == 'x' && p1 == "0") {
|
||||
advance()
|
||||
Token(loadChars(hexDigits), start, Token.Type.HEX).also {
|
||||
if (currentChar.isLetter())
|
||||
raise("invalid hex literal")
|
||||
}
|
||||
} else {
|
||||
Token(p1, start, Token.Type.INT)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private val currentChar: Char get() = pos.currentChar
|
||||
|
||||
private fun loadStringToken(): Token {
|
||||
var start = currentPos
|
||||
|
||||
if (currentChar == '"') advance()
|
||||
else start = start.back()
|
||||
|
||||
val sb = StringBuilder()
|
||||
while (currentChar != '"') {
|
||||
if (pos.end) raise("unterminated string")
|
||||
when (currentChar) {
|
||||
'\\' -> {
|
||||
advance() ?: raise("unterminated string")
|
||||
when (currentChar) {
|
||||
'n' -> sb.append('\n')
|
||||
'r' -> sb.append('\r')
|
||||
't' -> sb.append('\t')
|
||||
'"' -> sb.append('"')
|
||||
else -> sb.append('\\').append(currentChar)
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
sb.append(currentChar)
|
||||
advance()
|
||||
}
|
||||
}
|
||||
}
|
||||
advance()
|
||||
return Token(sb.toString(), start, Token.Type.STRING)
|
||||
}
|
||||
|
||||
/**
|
||||
* Load characters from the set until it reaches EOF or invalid character found.
|
||||
* stop at EOF on character not in [validChars].
|
||||
* @return the string of valid characters, could be empty
|
||||
*/
|
||||
private fun loadChars(validChars: Set<Char>): String {
|
||||
val result = StringBuilder()
|
||||
while (!pos.end) {
|
||||
val ch = pos.currentChar
|
||||
if (ch in validChars) {
|
||||
result.append(ch)
|
||||
advance()
|
||||
} else
|
||||
break
|
||||
}
|
||||
return result.toString()
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
private fun loadUntil(endChars: Set<Char>): String {
|
||||
return if (pos.end) ""
|
||||
else {
|
||||
val result = StringBuilder()
|
||||
while (!pos.end) {
|
||||
val ch = pos.currentChar
|
||||
if (ch in endChars) break
|
||||
result.append(ch)
|
||||
pos.advance()
|
||||
}
|
||||
result.toString()
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadToEnd(): String {
|
||||
val result = StringBuilder()
|
||||
val l = pos.line
|
||||
do {
|
||||
result.append(pos.currentChar)
|
||||
advance()
|
||||
} while (pos.line == l)
|
||||
return result.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* next non-whitespace char (newline are skipped too) or null if EOF
|
||||
*/
|
||||
private fun skipws(): Char? {
|
||||
while (!pos.end) {
|
||||
val ch = pos.currentChar
|
||||
if (ch.isWhitespace())
|
||||
advance()
|
||||
else
|
||||
return ch
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun advance() = pos.advance()
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
import kotlin.math.*
|
||||
|
||||
class Script(
|
||||
override val pos: Pos,
|
||||
private val statements: List<Statement> = emptyList(),
|
||||
) : Statement() {
|
||||
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
// todo: run script
|
||||
var lastResult: Obj = ObjVoid
|
||||
for (s in statements) {
|
||||
lastResult = s.execute(context)
|
||||
}
|
||||
return lastResult
|
||||
}
|
||||
|
||||
suspend fun execute() = execute(defaultContext.copy())
|
||||
|
||||
companion object {
|
||||
val defaultContext: Context = Context(null).apply {
|
||||
addFn("println") {
|
||||
require(args.size == 1)
|
||||
println(args[0].asStr.value)
|
||||
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") {
|
||||
sin(args.firstAndOnly().toDouble())
|
||||
}
|
||||
val pi = ObjReal(PI)
|
||||
addConst(pi, "π")
|
||||
getOrCreateNamespace("Math").also { ns ->
|
||||
ns.addConst(pi, "PI")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
class ScriptError(val pos: Pos, val errorMessage: String) : Exception(
|
||||
"""
|
||||
$pos: Error: $errorMessage
|
||||
${pos.currentLine}
|
||||
${"-".repeat(pos.column)}^
|
||||
""".trimIndent()
|
||||
)
|
||||
@@ -1,18 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
data class Token(val value: String, val pos: Pos, val type: Type) {
|
||||
@Suppress("unused")
|
||||
enum class Type {
|
||||
ID, INT, REAL, HEX, STRING, LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, COMMA,
|
||||
SEMICOLON, COLON,
|
||||
PLUS, MINUS, STAR, SLASH, ASSIGN,
|
||||
EQ, NEQ, LT, LTE, GT, GTE,
|
||||
AND, BITAND, OR, BITOR, NOT, DOT, ARROW, QUESTION, COLONCOLON, PERCENT,
|
||||
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
||||
EOF,
|
||||
}
|
||||
|
||||
companion object {
|
||||
// fun eof(parser: Parser) = Token("", parser.currentPos, Type.EOF)
|
||||
}
|
||||
}
|
||||
@@ -1,186 +0,0 @@
|
||||
package net.sergeych.ling
|
||||
|
||||
fun String.toSource(name: String = "eval"): Source = Source(name, this)
|
||||
|
||||
|
||||
@Suppress("unused")
|
||||
abstract class Statement(
|
||||
val isStaticConst: Boolean = false,
|
||||
val isConst: Boolean = false,
|
||||
val returnType: Type = Type.Any
|
||||
) : Obj() {
|
||||
|
||||
abstract val pos: Pos
|
||||
abstract suspend fun execute(context: Context): Obj
|
||||
|
||||
override fun compareTo(other: Obj): Int {
|
||||
throw UnsupportedOperationException("not comparable")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun Statement.raise(text: String): Nothing {
|
||||
throw ScriptError(pos, text)
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
fun Statement.require(cond: Boolean, message: () -> String) {
|
||||
if (!cond) raise(message())
|
||||
}
|
||||
|
||||
fun statement(pos: Pos, isStaticConst: Boolean = false, f: suspend (Context) -> Obj): Statement =
|
||||
object : Statement(isStaticConst) {
|
||||
override val pos: Pos = pos
|
||||
override suspend fun execute(context: Context): Obj = f(context)
|
||||
}
|
||||
|
||||
class LogicalAndStatement(
|
||||
override val pos: Pos,
|
||||
val left: Statement, val right: Statement
|
||||
) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
|
||||
val l = left.execute(context).let {
|
||||
(it as? ObjBool) ?: raise("left operand is not boolean: $it")
|
||||
}
|
||||
val r = right.execute(context).let {
|
||||
(it as? ObjBool) ?: raise("right operand is not boolean: $it")
|
||||
}
|
||||
return ObjBool(l.value && r.value)
|
||||
}
|
||||
}
|
||||
|
||||
class LogicalOrStatement(
|
||||
override val pos: Pos,
|
||||
val left: Statement, val right: Statement
|
||||
) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
|
||||
val l = left.execute(context).let {
|
||||
(it as? ObjBool) ?: raise("left operand is not boolean: $it")
|
||||
}
|
||||
val r = right.execute(context).let {
|
||||
(it as? ObjBool) ?: raise("right operand is not boolean: $it")
|
||||
}
|
||||
return ObjBool(l.value || r.value)
|
||||
}
|
||||
}
|
||||
|
||||
class PlusStatement(
|
||||
override val pos: Pos,
|
||||
val left: Statement, val right: Statement
|
||||
) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
// todo: implement also classes with 'plus' operator
|
||||
val l = left.execute(context)
|
||||
|
||||
if (l is ObjString)
|
||||
return ObjString(l.toString() + right.execute(context).asStr)
|
||||
|
||||
if (l !is Numeric)
|
||||
raise("left operand is not number: $l")
|
||||
|
||||
val r = right.execute(context)
|
||||
if (r !is Numeric)
|
||||
raise("right operand is not boolean: $r")
|
||||
|
||||
return if (l is ObjInt && r is ObjInt)
|
||||
ObjInt(l.longValue + r.longValue)
|
||||
else
|
||||
ObjReal(l.doubleValue + r.doubleValue)
|
||||
}
|
||||
}
|
||||
|
||||
class MinusStatement(
|
||||
override val pos: Pos,
|
||||
val left: Statement, val right: Statement
|
||||
) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
// todo: implement also classes with 'minus' operator
|
||||
val l = left.execute(context)
|
||||
if (l !is Numeric)
|
||||
raise("left operand is not number: $l")
|
||||
|
||||
val r = right.execute(context)
|
||||
if (r !is Numeric)
|
||||
raise("right operand is not number: $r")
|
||||
|
||||
return if (l is ObjInt && r is ObjInt)
|
||||
ObjInt(l.longValue - r.longValue)
|
||||
else
|
||||
ObjReal(l.doubleValue - r.doubleValue)
|
||||
}
|
||||
}
|
||||
|
||||
class MulStatement(
|
||||
override val pos: Pos,
|
||||
val left: Statement, val right: Statement
|
||||
) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
val l = left.execute(context)
|
||||
if (l !is Numeric)
|
||||
raise("left operand is not number: $l")
|
||||
|
||||
val r = right.execute(context)
|
||||
if (r !is Numeric)
|
||||
raise("right operand is not number: $r")
|
||||
|
||||
return if (l is ObjInt && r is ObjInt)
|
||||
ObjInt(l.longValue * r.longValue)
|
||||
else
|
||||
ObjReal(l.doubleValue * r.doubleValue)
|
||||
}
|
||||
}
|
||||
|
||||
class DivStatement(
|
||||
override val pos: Pos,
|
||||
val left: Statement, val right: Statement
|
||||
) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
val l = left.execute(context)
|
||||
if (l !is Numeric)
|
||||
raise("left operand is not number: $l")
|
||||
|
||||
val r = right.execute(context)
|
||||
if (r !is Numeric)
|
||||
raise("right operand is not number: $r")
|
||||
|
||||
return if (l is ObjInt && r is ObjInt)
|
||||
ObjInt(l.longValue / r.longValue)
|
||||
else
|
||||
ObjReal(l.doubleValue / r.doubleValue)
|
||||
}
|
||||
}
|
||||
|
||||
class ModStatement(
|
||||
override val pos: Pos,
|
||||
val left: Statement, val right: Statement
|
||||
) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
val l = left.execute(context)
|
||||
if (l !is Numeric)
|
||||
raise("left operand is not number: $l")
|
||||
|
||||
val r = right.execute(context)
|
||||
if (r !is Numeric)
|
||||
raise("right operand is not number: $r")
|
||||
|
||||
return if (l is ObjInt && r is ObjInt)
|
||||
ObjInt(l.longValue % r.longValue)
|
||||
else
|
||||
ObjReal(l.doubleValue % r.doubleValue)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
class AssignStatement(override val pos: Pos, val name: String, val value: Statement) : Statement() {
|
||||
override suspend fun execute(context: Context): Obj {
|
||||
val variable = context[name] ?: raise("can't assign: variable does not exist: $name")
|
||||
if (!variable.isMutable)
|
||||
throw ScriptError(pos, "can't reassign val $name")
|
||||
variable.value = value.execute(context)
|
||||
return ObjVoid
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
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) {
|
||||
when {
|
||||
value is ObjList -> {
|
||||
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
|
||||
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
|
||||
|
||||
val values: List<Obj> by lazy { list.map { it.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())
|
||||
fun from(values: Collection<Obj>) = Arguments(values.map { Info(it, Pos.UNKNOWN) })
|
||||
}
|
||||
|
||||
override fun iterator(): Iterator<Obj> {
|
||||
return list.map { it.value }.iterator()
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package net.sergeych.ling
|
||||
package net.sergeych.lyng
|
||||
|
||||
//fun buildDoubleFromParts(
|
||||
// integerPart: Long,
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,101 @@
|
||||
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
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
class Context(
|
||||
val parent: Context?,
|
||||
val args: Arguments = Arguments.EMPTY,
|
||||
var pos: Pos = Pos.builtIn,
|
||||
val thisObj: Obj = ObjVoid
|
||||
) {
|
||||
constructor(
|
||||
args: Arguments = Arguments.EMPTY,
|
||||
pos: Pos = Pos.builtIn,
|
||||
)
|
||||
: this(Script.defaultContext, args, pos)
|
||||
|
||||
fun raiseNotImplemented(what: String = "operation"): Nothing = raiseError("$what is not implemented")
|
||||
|
||||
@Suppress("unused")
|
||||
fun raiseNPE(): Nothing = raiseError(ObjNullPointerError(this))
|
||||
|
||||
@Suppress("unused")
|
||||
fun raiseIndexOutOfBounds(message: String = "Index out of bounds"): Nothing =
|
||||
raiseError(ObjIndexOutOfBoundsError(this, message))
|
||||
|
||||
@Suppress("unused")
|
||||
fun raiseArgumentError(message: String = "Illegal argument error"): Nothing =
|
||||
raiseError(ObjIllegalArgumentError(this, message))
|
||||
|
||||
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 {
|
||||
throw ExecutionError(ObjError(this, message))
|
||||
}
|
||||
|
||||
fun raiseError(obj: ObjError): Nothing {
|
||||
throw ExecutionError(obj)
|
||||
}
|
||||
|
||||
inline fun <reified T : Obj> requiredArg(index: Int): T {
|
||||
if (args.list.size <= index) raiseError("Expected at least ${index + 1} argument, got ${args.list.size}")
|
||||
return (args.list[index].value as? T)
|
||||
?: raiseClassCastError("Expected type ${T::class.simpleName}, got ${args.list[index].value::class.simpleName}")
|
||||
}
|
||||
|
||||
inline fun <reified T : Obj> requireOnlyArg(): T {
|
||||
if (args.list.size != 1) raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
||||
return requiredArg(0)
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
fun requireExactCount(count: Int) {
|
||||
if (args.list.size != count) {
|
||||
raiseError("Expected exactly $count arguments, got ${args.list.size}")
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <reified T : Obj> thisAs(): T = (thisObj as? T)
|
||||
?: raiseClassCastError("Cannot cast ${thisObj.objClass.className} to ${T::class.simpleName}")
|
||||
|
||||
internal val objects = mutableMapOf<String, ObjRecord>()
|
||||
|
||||
operator fun get(name: String): ObjRecord? =
|
||||
objects[name]
|
||||
?: parent?.get(name)
|
||||
|
||||
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)
|
||||
|
||||
fun copy() = Context(this, args, pos, thisObj)
|
||||
|
||||
fun addItem(name: String, isMutable: Boolean, value: Obj): ObjRecord {
|
||||
return ObjRecord(value, isMutable).also { objects.put(name, it) }
|
||||
}
|
||||
|
||||
fun getOrCreateNamespace(name: String): ObjClass {
|
||||
val ns = objects.getOrPut(name) { ObjRecord(ObjNamespace(name), isMutable = false) }.value
|
||||
return ns.objClass
|
||||
}
|
||||
|
||||
inline fun addVoidFn(vararg names: String, crossinline fn: suspend Context.() -> Unit) {
|
||||
addFn<ObjVoid>(*names) {
|
||||
fn(this)
|
||||
ObjVoid
|
||||
}
|
||||
}
|
||||
|
||||
inline fun <reified T : Obj> addFn(vararg names: String, crossinline fn: suspend Context.() -> T) {
|
||||
val newFn = object : Statement() {
|
||||
override val pos: Pos = Pos.builtIn
|
||||
|
||||
override suspend fun execute(context: Context): Obj = context.fn()
|
||||
|
||||
}
|
||||
for (name in names) {
|
||||
addItem(
|
||||
name,
|
||||
false,
|
||||
newFn
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun addConst(name: String, value: Obj) = addItem(name, false, value)
|
||||
|
||||
suspend fun eval(code: String): Obj =
|
||||
Compiler().compile(code.toSource()).execute(this)
|
||||
|
||||
fun containsLocal(name: String): Boolean = name in objects
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
sealed class ListEntry {
|
||||
data class Element(val accessor: Accessor) : ListEntry()
|
||||
|
||||
data class Spread(val accessor: Accessor) : ListEntry()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
class LoopBreakContinueException(
|
||||
val doContinue: Boolean,
|
||||
val result: Obj = ObjVoid,
|
||||
val label: String? = null
|
||||
) : RuntimeException()
|
||||
@@ -0,0 +1,344 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
import net.sergeych.synctools.ProtectedOp
|
||||
|
||||
/**
|
||||
* Record to store object with access rules, e.g. [isMutable] and access level [visibility].
|
||||
*/
|
||||
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(
|
||||
val getter: suspend (Context) -> ObjRecord,
|
||||
val setterOrNull: (suspend (Context, Obj) -> Unit)?
|
||||
) {
|
||||
/**
|
||||
* 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")
|
||||
}
|
||||
|
||||
open class Obj {
|
||||
var isFrozen: Boolean = false
|
||||
|
||||
private val monitor = Mutex()
|
||||
|
||||
// private val memberMutex = Mutex()
|
||||
internal var parentInstances: MutableList<Obj> = mutableListOf()
|
||||
|
||||
private val opInstances = ProtectedOp()
|
||||
|
||||
open fun inspect(): String = toString()
|
||||
|
||||
/**
|
||||
* Some objects are by-value, historically [ObjInt] and [ObjReal] are usually treated as such.
|
||||
* When initializing a var with it, by value objects must be copied. By-reference ones aren't.
|
||||
*
|
||||
* Almost all objects are by-reference.
|
||||
*/
|
||||
open fun byValueCopy(): Obj = this
|
||||
|
||||
fun isInstanceOf(someClass: Obj) = someClass === objClass || objClass.allParentsSet.contains(someClass)
|
||||
|
||||
suspend fun invokeInstanceMethod(context: Context, name: String, vararg args: Obj): Obj =
|
||||
invokeInstanceMethod(context, name, Arguments(args.map { Arguments.Info(it, context.pos) }))
|
||||
|
||||
inline suspend fun <reified T : Obj> callMethod(
|
||||
context: Context,
|
||||
name: String,
|
||||
args: Arguments = Arguments.EMPTY
|
||||
): T = invokeInstanceMethod(context, name, args) as T
|
||||
|
||||
open suspend fun invokeInstanceMethod(
|
||||
context: Context,
|
||||
name: String,
|
||||
args: Arguments = Arguments.EMPTY
|
||||
): Obj =
|
||||
// note that getInstanceMember traverses the hierarchy
|
||||
objClass.getInstanceMember(context.pos, name).value.invoke(context, this, args)
|
||||
|
||||
fun getMemberOrNull(name: String): Obj? = objClass.getInstanceMemberOrNull(name)?.value
|
||||
|
||||
// methods that to override
|
||||
|
||||
open suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun contains(context: Context, other: Obj): Boolean {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open val asStr: ObjString by lazy {
|
||||
if (this is ObjString) this else ObjString(this.toString())
|
||||
}
|
||||
|
||||
/**
|
||||
* Class of the object: definition of member functions (top-level), etc.
|
||||
* Note that using lazy allows to avoid endless recursion here
|
||||
*/
|
||||
open val objClass: ObjClass by lazy {
|
||||
ObjClass("Obj").apply {
|
||||
addFn("toString") {
|
||||
thisObj.asStr
|
||||
}
|
||||
addFn("contains") {
|
||||
ObjBool(thisObj.contains(this, args.firstAndOnly()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
open suspend fun plus(context: Context, other: Obj): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun minus(context: Context, other: Obj): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun mul(context: Context, other: Obj): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun div(context: Context, other: Obj): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun mod(context: Context, other: Obj): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun logicalNot(context: Context): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun logicalAnd(context: Context, other: Obj): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun logicalOr(context: Context, other: Obj): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun assign(context: Context, other: Obj): Obj? = null
|
||||
|
||||
/**
|
||||
* a += b
|
||||
* if( the operation is not defined, it returns null and the compiler would try
|
||||
* to generate it as 'this = this + other', reassigning its variable
|
||||
*/
|
||||
open suspend fun plusAssign(context: Context, other: Obj): Obj? = null
|
||||
|
||||
/**
|
||||
* `-=` operations, see [plusAssign]
|
||||
*/
|
||||
open suspend fun minusAssign(context: Context, other: Obj): Obj? = null
|
||||
open suspend fun mulAssign(context: Context, other: Obj): Obj? = null
|
||||
open suspend fun divAssign(context: Context, other: Obj): Obj? = null
|
||||
open suspend fun modAssign(context: Context, other: Obj): Obj? = null
|
||||
|
||||
open suspend fun getAndIncrement(context: Context): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun incrementAndGet(context: Context): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun decrementAndGet(context: Context): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
open suspend fun getAndDecrement(context: Context): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
fun willMutate(context: Context) {
|
||||
if (isFrozen) context.raiseError("attempt to mutate frozen object")
|
||||
}
|
||||
|
||||
suspend fun <T> sync(block: () -> T): T = monitor.withLock { block() }
|
||||
|
||||
suspend open fun readField(context: Context, name: String): ObjRecord {
|
||||
// could be property or class field:
|
||||
val obj = objClass.getInstanceMemberOrNull(name) ?: context.raiseError("no such field: $name")
|
||||
val value = obj.value
|
||||
return when (value) {
|
||||
is Statement -> {
|
||||
ObjRecord(value.execute(context.copy(context.pos, newThisObj = this)), obj.isMutable)
|
||||
}
|
||||
// could be writable property naturally
|
||||
// null -> ObjNull.asReadonly
|
||||
else -> obj
|
||||
}
|
||||
}
|
||||
|
||||
open suspend fun writeField(context: Context, name: String, newValue: Obj) {
|
||||
willMutate(context)
|
||||
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")
|
||||
}
|
||||
|
||||
open suspend fun getAt(context: Context, index: Int): Obj {
|
||||
context.raiseNotImplemented("indexing")
|
||||
}
|
||||
|
||||
open suspend fun putAt(context: Context, index: Int, newValue: Obj) {
|
||||
context.raiseNotImplemented("indexing")
|
||||
}
|
||||
|
||||
open suspend fun callOn(context: Context): Obj {
|
||||
context.raiseNotImplemented()
|
||||
}
|
||||
|
||||
suspend fun invoke(context: Context, thisObj: Obj, args: Arguments): Obj =
|
||||
callOn(context.copy(context.pos, args = args, newThisObj = thisObj))
|
||||
|
||||
suspend fun invoke(context: Context, thisObj: Obj, vararg args: Obj): Obj =
|
||||
callOn(
|
||||
context.copy(
|
||||
context.pos,
|
||||
args = Arguments(args.map { Arguments.Info(it, context.pos) }),
|
||||
newThisObj = thisObj
|
||||
)
|
||||
)
|
||||
|
||||
suspend fun invoke(context: Context, thisObj: Obj): Obj =
|
||||
callOn(
|
||||
context.copy(
|
||||
context.pos,
|
||||
args = Arguments.EMPTY,
|
||||
newThisObj = thisObj
|
||||
)
|
||||
)
|
||||
|
||||
suspend fun invoke(context: Context, atPos: Pos, thisObj: Obj, args: Arguments): Obj =
|
||||
callOn(context.copy(atPos, args = args, newThisObj = thisObj))
|
||||
|
||||
|
||||
val asReadonly: ObjRecord by lazy { ObjRecord(this, false) }
|
||||
val asMutable: ObjRecord by lazy { ObjRecord(this, true) }
|
||||
|
||||
|
||||
companion object {
|
||||
inline fun <reified T> from(obj: T): Obj {
|
||||
return when (obj) {
|
||||
is Obj -> obj
|
||||
is Double -> ObjReal(obj)
|
||||
is Float -> ObjReal(obj.toDouble())
|
||||
is Int -> ObjInt(obj.toLong())
|
||||
is Long -> ObjInt(obj)
|
||||
is String -> ObjString(obj)
|
||||
is CharSequence -> ObjString(obj.toString())
|
||||
is Boolean -> ObjBool(obj)
|
||||
Unit -> ObjVoid
|
||||
null -> ObjNull
|
||||
else -> throw IllegalArgumentException("cannot convert to Obj: $obj")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
inline fun <reified T> T.toObj(): Obj = Obj.from(this)
|
||||
|
||||
@Serializable
|
||||
@SerialName("void")
|
||||
object ObjVoid : Obj() {
|
||||
override fun equals(other: Any?): Boolean {
|
||||
return other is ObjVoid || other is Unit
|
||||
}
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
return if (other === this) 0 else -1
|
||||
}
|
||||
|
||||
override fun toString(): String = "void"
|
||||
}
|
||||
|
||||
@Serializable
|
||||
@SerialName("null")
|
||||
object ObjNull : Obj() {
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
return if (other === this) 0 else -1
|
||||
}
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
return other is ObjNull || other == null
|
||||
}
|
||||
}
|
||||
|
||||
interface Numeric {
|
||||
val longValue: Long
|
||||
val doubleValue: Double
|
||||
val toObjInt: ObjInt
|
||||
val toObjReal: ObjReal
|
||||
}
|
||||
|
||||
fun Obj.toDouble(): Double =
|
||||
(this as? Numeric)?.doubleValue
|
||||
?: (this as? ObjString)?.value?.toDouble()
|
||||
?: throw IllegalArgumentException("cannot convert to double $this")
|
||||
|
||||
@Suppress("unused")
|
||||
fun Obj.toLong(): Long =
|
||||
when (this) {
|
||||
is Numeric -> longValue
|
||||
is ObjString -> value.toLong()
|
||||
is ObjChar -> value.code.toLong()
|
||||
else -> throw IllegalArgumentException("cannot convert to double $this")
|
||||
}
|
||||
|
||||
fun Obj.toInt(): Int = toLong().toInt()
|
||||
|
||||
fun Obj.toBool(): Boolean =
|
||||
(this as? ObjBool)?.value ?: throw IllegalArgumentException("cannot convert to boolean $this")
|
||||
|
||||
|
||||
data class ObjNamespace(val name: String) : Obj() {
|
||||
override val objClass by lazy { ObjClass(name) }
|
||||
|
||||
override fun inspect(): String = "Ns[$name]"
|
||||
|
||||
override fun toString(): String {
|
||||
return "package $name"
|
||||
}
|
||||
}
|
||||
|
||||
open class ObjError(val context: Context, val message: String) : Obj() {
|
||||
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 ObjAssertionError(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 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")
|
||||
@@ -0,0 +1,27 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
data class ObjBool(val value: Boolean) : Obj() {
|
||||
override val asStr by lazy { ObjString(value.toString()) }
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
if (other !is ObjBool) return -2
|
||||
return value.compareTo(other.value)
|
||||
}
|
||||
|
||||
override fun toString(): String = value.toString()
|
||||
|
||||
override val objClass: ObjClass = type
|
||||
|
||||
override suspend fun logicalNot(context: Context): Obj = ObjBool(!value)
|
||||
|
||||
override suspend fun logicalAnd(context: Context, other: Obj): Obj = ObjBool(value && other.toBool())
|
||||
|
||||
override suspend fun logicalOr(context: Context, other: Obj): Obj = ObjBool(value || other.toBool())
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("Bool")
|
||||
}
|
||||
}
|
||||
|
||||
val ObjTrue = ObjBool(true)
|
||||
val ObjFalse = ObjBool(false)
|
||||
@@ -0,0 +1,19 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
class ObjChar(val value: Char): Obj() {
|
||||
|
||||
override val objClass: ObjClass = type
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int =
|
||||
(other as? ObjChar)?.let { value.compareTo(it.value) } ?: -1
|
||||
|
||||
override fun toString(): String = value.toString()
|
||||
|
||||
override fun inspect(): String = "'$value'"
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("Char").apply {
|
||||
addFn("code") { ObjInt(thisAs<ObjChar>().value.code.toLong()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
val ObjClassType by lazy { ObjClass("Class") }
|
||||
|
||||
class ObjClass(
|
||||
val className: String,
|
||||
vararg val parents: ObjClass,
|
||||
) : Obj() {
|
||||
|
||||
var instanceConstructor: Statement? = null
|
||||
|
||||
val allParentsSet: Set<ObjClass> = parents.flatMap {
|
||||
listOf(it) + it.allParentsSet
|
||||
}.toSet()
|
||||
|
||||
override val objClass: ObjClass by lazy { ObjClassType }
|
||||
|
||||
// members: fields most often
|
||||
private val members = mutableMapOf<String, ObjRecord>()
|
||||
|
||||
override fun toString(): String = className
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int = if (other === this) 0 else -1
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
fun defaultInstance(): Obj = object : Obj() {
|
||||
override val objClass: ObjClass = this@ObjClass
|
||||
}
|
||||
|
||||
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)
|
||||
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
|
||||
members[name] = ObjRecord(initialValue, isMutable, visibility)
|
||||
}
|
||||
|
||||
fun addFn(name: String, isOpen: Boolean = false, code: suspend Context.() -> Obj) {
|
||||
createField(name, statement { code() }, isOpen)
|
||||
}
|
||||
|
||||
fun addConst(name: String, value: Obj) = createField(name, value, isMutable = false)
|
||||
|
||||
|
||||
/**
|
||||
* Get instance member traversing the hierarchy if needed. Its meaning is different for different objects.
|
||||
*/
|
||||
fun getInstanceMemberOrNull(name: String): ObjRecord? {
|
||||
members[name]?.let { return it }
|
||||
allParentsSet.forEach { parent -> parent.getInstanceMemberOrNull(name)?.let { return it } }
|
||||
return null
|
||||
}
|
||||
|
||||
fun getInstanceMember(atPos: Pos, name: String): ObjRecord =
|
||||
getInstanceMemberOrNull(name)
|
||||
?: throw ScriptError(atPos, "symbol doesn't exist: $name")
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract class that must provide `iterator` method that returns [ObjIterator] instance.
|
||||
*/
|
||||
val ObjIterable by lazy {
|
||||
ObjClass("Iterable").apply {
|
||||
|
||||
addFn("toList") {
|
||||
val result = mutableListOf<Obj>()
|
||||
val iterator = thisObj.invokeInstanceMethod(this, "iterator")
|
||||
|
||||
while (iterator.invokeInstanceMethod(this, "hasNext").toBool())
|
||||
result += iterator.invokeInstanceMethod(this, "next")
|
||||
|
||||
|
||||
// val next = iterator.getMemberOrNull("next")!!
|
||||
// val hasNext = iterator.getMemberOrNull("hasNext")!!
|
||||
// while( hasNext.invoke(this, iterator).toBool() )
|
||||
// result += next.invoke(this, iterator)
|
||||
ObjList(result)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collection is an iterator with `size`]
|
||||
*/
|
||||
val ObjCollection by lazy {
|
||||
val i: ObjClass = ObjIterable
|
||||
ObjClass("Collection", i)
|
||||
}
|
||||
|
||||
val ObjIterator by lazy { ObjClass("Iterator") }
|
||||
|
||||
class ObjArrayIterator(val array: Obj) : Obj() {
|
||||
|
||||
override val objClass: ObjClass by lazy { type }
|
||||
|
||||
private var nextIndex = 0
|
||||
private var lastIndex = 0
|
||||
|
||||
suspend fun init(context: Context) {
|
||||
nextIndex = 0
|
||||
lastIndex = array.invokeInstanceMethod(context, "size").toInt()
|
||||
ObjVoid
|
||||
}
|
||||
|
||||
companion object {
|
||||
val type by lazy {
|
||||
ObjClass("ArrayIterator", ObjIterator).apply {
|
||||
addFn("next") {
|
||||
val self = thisAs<ObjArrayIterator>()
|
||||
if (self.nextIndex < self.lastIndex) {
|
||||
self.array.invokeInstanceMethod(this, "getAt", (self.nextIndex++).toObj())
|
||||
} else raiseError(ObjIterationFinishedError(this))
|
||||
}
|
||||
addFn("hasNext") {
|
||||
val self = thisAs<ObjArrayIterator>()
|
||||
if (self.nextIndex < self.lastIndex) ObjTrue else ObjFalse
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
val ObjArray by lazy {
|
||||
|
||||
/**
|
||||
* Array abstract class is a [ObjCollection] with `getAt` method.
|
||||
*/
|
||||
ObjClass("Array", ObjCollection).apply {
|
||||
// we can create iterators using size/getat:
|
||||
|
||||
addFn("iterator") {
|
||||
ObjArrayIterator(thisObj).also { it.init(this) }
|
||||
}
|
||||
addFn("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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
data class ObjInt(var value: Long) : Obj(), Numeric {
|
||||
override val asStr get() = ObjString(value.toString())
|
||||
override val longValue get() = value
|
||||
override val doubleValue get() = value.toDouble()
|
||||
override val toObjInt get() = this
|
||||
override val toObjReal = ObjReal(doubleValue)
|
||||
|
||||
override fun byValueCopy(): Obj = ObjInt(value)
|
||||
|
||||
override suspend fun getAndIncrement(context: Context): Obj {
|
||||
return ObjInt(value).also { value++ }
|
||||
}
|
||||
|
||||
override suspend fun getAndDecrement(context: Context): Obj {
|
||||
return ObjInt(value).also { value-- }
|
||||
}
|
||||
|
||||
override suspend fun incrementAndGet(context: Context): Obj {
|
||||
return ObjInt(++value)
|
||||
}
|
||||
|
||||
override suspend fun decrementAndGet(context: Context): Obj {
|
||||
return ObjInt(--value)
|
||||
}
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
if (other !is Numeric) return -2
|
||||
return value.compareTo(other.doubleValue)
|
||||
}
|
||||
|
||||
override fun toString(): String = value.toString()
|
||||
|
||||
override val objClass: ObjClass = type
|
||||
|
||||
override suspend fun plus(context: Context, other: Obj): Obj =
|
||||
if (other is ObjInt)
|
||||
ObjInt(this.value + other.value)
|
||||
else
|
||||
ObjReal(this.doubleValue + other.toDouble())
|
||||
|
||||
override suspend fun minus(context: Context, other: Obj): Obj =
|
||||
if (other is ObjInt)
|
||||
ObjInt(this.value - other.value)
|
||||
else
|
||||
ObjReal(this.doubleValue - other.toDouble())
|
||||
|
||||
override suspend fun mul(context: Context, other: Obj): Obj =
|
||||
if (other is ObjInt) {
|
||||
ObjInt(this.value * other.value)
|
||||
} else ObjReal(this.value * other.toDouble())
|
||||
|
||||
override suspend fun div(context: Context, other: Obj): Obj =
|
||||
if (other is ObjInt)
|
||||
ObjInt(this.value / other.value)
|
||||
else ObjReal(this.value / other.toDouble())
|
||||
|
||||
override suspend fun mod(context: Context, other: Obj): Obj =
|
||||
if (other is ObjInt)
|
||||
ObjInt(this.value % other.value)
|
||||
else ObjReal(this.value.toDouble() % other.toDouble())
|
||||
|
||||
/**
|
||||
* We are by-value type ([byValueCopy] is implemented) so we can do in-place
|
||||
* assignment
|
||||
*/
|
||||
override suspend fun assign(context: Context, other: Obj): Obj? {
|
||||
return if (other is ObjInt) {
|
||||
value = other.value
|
||||
this
|
||||
} else null
|
||||
}
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("Int")
|
||||
}
|
||||
}
|
||||
|
||||
fun Int.toObj() = ObjInt(this.toLong())
|
||||
@@ -0,0 +1,137 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
class ObjList(val list: MutableList<Obj> = mutableListOf()) : Obj() {
|
||||
|
||||
init {
|
||||
for (p in objClass.parents)
|
||||
parentInstances.add(p.defaultInstance())
|
||||
}
|
||||
|
||||
override fun toString(): String = "[${
|
||||
list.joinToString(separator = ", ") { it.inspect() }
|
||||
}]"
|
||||
|
||||
fun normalize(context: Context, index: Int, allowisEndInclusive: Boolean = false): Int {
|
||||
val i = if (index < 0) list.size + index else index
|
||||
if (allowisEndInclusive && i == list.size) return i
|
||||
if (i !in list.indices) context.raiseError("index $index out of bounds for size ${list.size}")
|
||||
return i
|
||||
}
|
||||
|
||||
override suspend fun getAt(context: Context, index: Int): Obj {
|
||||
val i = normalize(context, index)
|
||||
return list[i]
|
||||
}
|
||||
|
||||
override suspend fun putAt(context: Context, index: Int, newValue: Obj) {
|
||||
val i = normalize(context, index)
|
||||
list[i] = newValue
|
||||
}
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
if (other !is ObjList) return -2
|
||||
val mySize = list.size
|
||||
val otherSize = other.list.size
|
||||
val commonSize = minOf(mySize, otherSize)
|
||||
for (i in 0..<commonSize) {
|
||||
if (list[i].compareTo(context, other.list[i]) != 0) {
|
||||
return list[i].compareTo(context, other.list[i])
|
||||
}
|
||||
}
|
||||
// equal so far, longer is greater:
|
||||
return when {
|
||||
mySize < otherSize -> -1
|
||||
mySize > otherSize -> 1
|
||||
else -> 0
|
||||
}
|
||||
}
|
||||
|
||||
override suspend fun plus(context: Context, other: Obj): Obj =
|
||||
when {
|
||||
other is ObjList ->
|
||||
ObjList((list + other.list).toMutableList())
|
||||
|
||||
other.isInstanceOf(ObjIterable) -> {
|
||||
val l = other.callMethod<ObjList>(context, "toList")
|
||||
ObjList((list + l.list).toMutableList())
|
||||
}
|
||||
|
||||
else ->
|
||||
context.raiseError("'+': can't concatenate $this with $other")
|
||||
}
|
||||
|
||||
|
||||
override suspend fun plusAssign(context: Context, other: Obj): Obj {
|
||||
// optimization
|
||||
if (other is ObjList) {
|
||||
list += other.list
|
||||
return this
|
||||
}
|
||||
if (other.isInstanceOf(ObjIterable)) {
|
||||
val otherList = other.invokeInstanceMethod(context, "toList") as ObjList
|
||||
list += otherList.list
|
||||
} else
|
||||
list += other
|
||||
return this
|
||||
}
|
||||
|
||||
override val objClass: ObjClass
|
||||
get() = type
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("List", ObjArray).apply {
|
||||
|
||||
createField("size",
|
||||
statement {
|
||||
(thisObj as ObjList).list.size.toObj()
|
||||
}
|
||||
)
|
||||
addFn("getAt") {
|
||||
requireExactCount(1)
|
||||
thisAs<ObjList>().getAt(this, requiredArg<ObjInt>(0).value.toInt())
|
||||
}
|
||||
addFn("putAt") {
|
||||
requireExactCount(2)
|
||||
val newValue = args[1]
|
||||
thisAs<ObjList>().putAt(this, requiredArg<ObjInt>(0).value.toInt(), newValue)
|
||||
newValue
|
||||
}
|
||||
createField("add",
|
||||
statement {
|
||||
val l = thisAs<ObjList>().list
|
||||
for (a in args) l.add(a)
|
||||
ObjVoid
|
||||
}
|
||||
)
|
||||
createField("addAt",
|
||||
statement {
|
||||
if (args.size < 2) raiseError("addAt takes 2+ arguments")
|
||||
val l = thisAs<ObjList>()
|
||||
var index = l.normalize(
|
||||
this, requiredArg<ObjInt>(0).value.toInt(),
|
||||
allowisEndInclusive = true
|
||||
)
|
||||
for (i in 1..<args.size) l.list.add(index++, args[i])
|
||||
ObjVoid
|
||||
}
|
||||
)
|
||||
addFn("removeAt") {
|
||||
val self = thisAs<ObjList>()
|
||||
val start = self.normalize(this, requiredArg<ObjInt>(0).value.toInt())
|
||||
if (args.size == 2) {
|
||||
val end = requireOnlyArg<ObjInt>().value.toInt()
|
||||
self.list.subList(start, self.normalize(this, end)).clear()
|
||||
} else
|
||||
self.list.removeAt(start)
|
||||
self
|
||||
}
|
||||
addFn("removeRangeInclusive") {
|
||||
val self = thisAs<ObjList>()
|
||||
val start = self.normalize(this, requiredArg<ObjInt>(0).value.toInt())
|
||||
val end = self.normalize(this, requiredArg<ObjInt>(1).value.toInt()) + 1
|
||||
self.list.subList(start, end).clear()
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
class ObjRange(val start: Obj?, val end: Obj?, val isEndInclusive: Boolean) : Obj() {
|
||||
|
||||
override val objClass: ObjClass = type
|
||||
|
||||
override fun toString(): String {
|
||||
val result = StringBuilder()
|
||||
result.append("${start?.inspect() ?: '∞'} ..")
|
||||
if (!isEndInclusive) result.append('<')
|
||||
result.append(" ${end?.inspect() ?: '∞'}")
|
||||
return result.toString()
|
||||
}
|
||||
|
||||
suspend fun containsRange(context: Context, other: ObjRange): Boolean {
|
||||
if (start != null) {
|
||||
// our start is not -∞ so other start should be GTE or is not contained:
|
||||
if (other.start != null && start.compareTo(context, other.start) > 0) return false
|
||||
}
|
||||
if (end != null) {
|
||||
// same with the end: if it is open, it can't be contained in ours:
|
||||
if (other.end == null) return false
|
||||
// both exists, now there could be 4 cases:
|
||||
return when {
|
||||
other.isEndInclusive && isEndInclusive ->
|
||||
end.compareTo(context, other.end) >= 0
|
||||
|
||||
!other.isEndInclusive && !isEndInclusive ->
|
||||
end.compareTo(context, other.end) >= 0
|
||||
|
||||
other.isEndInclusive && !isEndInclusive ->
|
||||
end.compareTo(context, other.end) > 0
|
||||
|
||||
!other.isEndInclusive && isEndInclusive ->
|
||||
end.compareTo(context, other.end) >= 0
|
||||
|
||||
else -> throw IllegalStateException("unknown comparison")
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
override suspend fun contains(context: Context, other: Obj): Boolean {
|
||||
|
||||
if (other is ObjRange)
|
||||
return containsRange(context, other)
|
||||
|
||||
if (start == null && end == null) return true
|
||||
if (start != null) {
|
||||
if (start.compareTo(context, other) > 0) return false
|
||||
}
|
||||
if (end != null) {
|
||||
val cmp = end.compareTo(context, other)
|
||||
if (isEndInclusive && cmp < 0 || !isEndInclusive && cmp <= 0) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
val isIntRange: Boolean by lazy {
|
||||
start is ObjInt && end is ObjInt
|
||||
}
|
||||
|
||||
val isCharRange: Boolean by lazy {
|
||||
start is ObjChar && end is ObjChar
|
||||
}
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
return (other as? ObjRange)?.let {
|
||||
if( start == other.start && end == other.end ) 0 else -1
|
||||
}
|
||||
?: -1
|
||||
}
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("Range", ObjIterable).apply {
|
||||
addFn("start") {
|
||||
thisAs<ObjRange>().start ?: ObjNull
|
||||
}
|
||||
addFn("end") {
|
||||
thisAs<ObjRange>().end ?: ObjNull
|
||||
}
|
||||
addFn("isOpen") {
|
||||
thisAs<ObjRange>().let { it.start == null || it.end == null }.toObj()
|
||||
}
|
||||
addFn("isIntRange") {
|
||||
thisAs<ObjRange>().isIntRange.toObj()
|
||||
}
|
||||
addFn("isCharRange") {
|
||||
thisAs<ObjRange>().isCharRange.toObj()
|
||||
}
|
||||
addFn("isEndInclusive") {
|
||||
thisAs<ObjRange>().isEndInclusive.toObj()
|
||||
}
|
||||
addFn("iterator") {
|
||||
val self = thisAs<ObjRange>()
|
||||
ObjRangeIterator(self).apply { init() }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
class ObjRangeIterator(val self: ObjRange) : Obj() {
|
||||
|
||||
private var nextIndex = 0
|
||||
private var lastIndex = 0
|
||||
private var isCharRange: Boolean = false
|
||||
|
||||
override val objClass: ObjClass = type
|
||||
|
||||
fun Context.init() {
|
||||
if (self.start == null || self.end == null)
|
||||
raiseError("next is only available for finite ranges")
|
||||
isCharRange = self.isCharRange
|
||||
lastIndex = if (self.isIntRange || self.isCharRange) {
|
||||
if (self.isEndInclusive)
|
||||
self.end.toInt() - self.start.toInt() + 1
|
||||
else
|
||||
self.end.toInt() - self.start.toInt()
|
||||
} else {
|
||||
raiseError("not implemented iterator for range of $this")
|
||||
}
|
||||
}
|
||||
|
||||
fun hasNext(): Boolean = nextIndex < lastIndex
|
||||
|
||||
fun next(context: Context): Obj =
|
||||
if (nextIndex < lastIndex) {
|
||||
val x = if (self.isEndInclusive)
|
||||
self.start!!.toLong() + nextIndex++
|
||||
else
|
||||
self.start!!.toLong() + nextIndex++
|
||||
if( isCharRange ) ObjChar(x.toInt().toChar()) else ObjInt(x)
|
||||
}
|
||||
else {
|
||||
context.raiseError(ObjIterationFinishedError(context))
|
||||
}
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("RangeIterator", ObjIterable).apply {
|
||||
addFn("hasNext") {
|
||||
thisAs<ObjRangeIterator>().hasNext().toObj()
|
||||
}
|
||||
addFn("next") {
|
||||
thisAs<ObjRangeIterator>().next(this)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
import kotlin.math.floor
|
||||
import kotlin.math.roundToLong
|
||||
|
||||
data class ObjReal(val value: Double) : Obj(), Numeric {
|
||||
override val asStr by lazy { ObjString(value.toString()) }
|
||||
override val longValue: Long by lazy { floor(value).toLong() }
|
||||
override val doubleValue: Double by lazy { value }
|
||||
override val toObjInt: ObjInt by lazy { ObjInt(longValue) }
|
||||
override val toObjReal: ObjReal by lazy { ObjReal(value) }
|
||||
|
||||
override fun byValueCopy(): Obj = ObjReal(value)
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
if (other !is Numeric) return -2
|
||||
return value.compareTo(other.doubleValue)
|
||||
}
|
||||
|
||||
override fun toString(): String = value.toString()
|
||||
|
||||
override val objClass: ObjClass = type
|
||||
|
||||
override suspend fun plus(context: Context, other: Obj): Obj =
|
||||
ObjReal(this.value + other.toDouble())
|
||||
|
||||
override suspend fun minus(context: Context, other: Obj): Obj =
|
||||
ObjReal(this.value - other.toDouble())
|
||||
|
||||
override suspend fun mul(context: Context, other: Obj): Obj =
|
||||
ObjReal(this.value * other.toDouble())
|
||||
|
||||
override suspend fun div(context: Context, other: Obj): Obj =
|
||||
ObjReal(this.value / other.toDouble())
|
||||
|
||||
override suspend fun mod(context: Context, other: Obj): Obj =
|
||||
ObjReal(this.value % other.toDouble())
|
||||
|
||||
companion object {
|
||||
val type: ObjClass = ObjClass("Real").apply {
|
||||
createField(
|
||||
"roundToInt",
|
||||
statement(Pos.builtIn) {
|
||||
(it.thisObj as ObjReal).value.roundToLong().toObj()
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
import kotlinx.serialization.SerialName
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
@SerialName("string")
|
||||
data class ObjString(val value: String) : Obj() {
|
||||
|
||||
override suspend fun compareTo(context: Context, other: Obj): Int {
|
||||
if (other !is ObjString) return -2
|
||||
return this.value.compareTo(other.value)
|
||||
}
|
||||
|
||||
override fun toString(): String = value
|
||||
|
||||
override val asStr: ObjString by lazy { this }
|
||||
|
||||
override fun inspect(): String {
|
||||
return "\"$value\""
|
||||
}
|
||||
|
||||
override val objClass: ObjClass
|
||||
get() = type
|
||||
|
||||
override suspend fun plus(context: Context, other: Obj): Obj {
|
||||
return ObjString(value + other.asStr.value)
|
||||
}
|
||||
|
||||
override suspend fun getAt(context: Context, index: Int): Obj {
|
||||
return ObjChar(value[index])
|
||||
}
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("String").apply {
|
||||
addConst("startsWith",
|
||||
statement {
|
||||
ObjBool(thisAs<ObjString>().value.startsWith(requiredArg<ObjString>(0).value))
|
||||
})
|
||||
addConst("length",
|
||||
statement { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
||||
)
|
||||
addFn("size") { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
val digitsSet = ('0'..'9').toSet()
|
||||
val digits = { d: Char -> d in digitsSet }
|
||||
val hexDigits = digitsSet + ('a'..'f') + ('A'..'F')
|
||||
val idNextChars = { d: Char -> d.isLetter() || d == '_' || d.isDigit() }
|
||||
|
||||
@Suppress("unused")
|
||||
val idFirstChars = { d: Char -> d.isLetter() || d == '_' }
|
||||
|
||||
fun parseLyng(source: Source): List<Token> {
|
||||
val p = Parser(fromPos = source.startPos)
|
||||
val tokens = mutableListOf<Token>()
|
||||
do {
|
||||
val t = p.nextToken()
|
||||
tokens += t
|
||||
} while (t.type != Token.Type.EOF)
|
||||
return tokens
|
||||
}
|
||||
|
||||
private class Parser(fromPos: Pos) {
|
||||
|
||||
private val pos = MutablePos(fromPos)
|
||||
|
||||
/**
|
||||
* Immutable copy of current position
|
||||
*/
|
||||
private val currentPos: Pos get() = pos.toPos()
|
||||
|
||||
private fun raise(msg: String): Nothing = throw ScriptError(currentPos, msg)
|
||||
|
||||
fun nextToken(): Token {
|
||||
skipws()
|
||||
if (pos.end) return Token("", currentPos, Token.Type.EOF)
|
||||
val from = currentPos
|
||||
return when (val ch = pos.currentChar.also { pos.advance() }) {
|
||||
'(' -> Token("(", from, Token.Type.LPAREN)
|
||||
')' -> Token(")", from, Token.Type.RPAREN)
|
||||
'{' -> Token("{", from, Token.Type.LBRACE)
|
||||
'}' -> Token("}", from, Token.Type.RBRACE)
|
||||
'[' -> Token("[", from, Token.Type.LBRACKET)
|
||||
']' -> Token("]", from, Token.Type.RBRACKET)
|
||||
',' -> Token(",", from, Token.Type.COMMA)
|
||||
';' -> Token(";", from, Token.Type.SEMICOLON)
|
||||
'=' -> {
|
||||
if (pos.currentChar == '=') {
|
||||
pos.advance()
|
||||
if (currentChar == '=') {
|
||||
pos.advance()
|
||||
Token("===", from, Token.Type.REF_EQ)
|
||||
} else
|
||||
Token("==", from, Token.Type.EQ)
|
||||
} else
|
||||
Token("=", from, Token.Type.ASSIGN)
|
||||
}
|
||||
|
||||
'+' -> {
|
||||
when (currentChar) {
|
||||
'+' -> {
|
||||
pos.advance()
|
||||
Token("+", from, Token.Type.PLUS2)
|
||||
}
|
||||
|
||||
'=' -> {
|
||||
pos.advance()
|
||||
Token("+", from, Token.Type.PLUSASSIGN)
|
||||
}
|
||||
|
||||
else ->
|
||||
Token("+", from, Token.Type.PLUS)
|
||||
}
|
||||
}
|
||||
|
||||
'-' -> {
|
||||
when (currentChar) {
|
||||
'-' -> {
|
||||
pos.advance()
|
||||
Token("--", from, Token.Type.MINUS2)
|
||||
}
|
||||
|
||||
'=' -> {
|
||||
pos.advance()
|
||||
Token("-", from, Token.Type.MINUSASSIGN)
|
||||
}
|
||||
|
||||
'>' -> {
|
||||
pos.advance()
|
||||
Token("->", from, Token.Type.ARROW)
|
||||
}
|
||||
|
||||
else -> Token("-", from, Token.Type.MINUS)
|
||||
}
|
||||
}
|
||||
|
||||
'*' -> {
|
||||
if (currentChar == '=') {
|
||||
pos.advance()
|
||||
Token("*=", from, Token.Type.STARASSIGN)
|
||||
} else
|
||||
Token("*", from, Token.Type.STAR)
|
||||
}
|
||||
|
||||
'/' -> when (currentChar) {
|
||||
'/' -> {
|
||||
pos.advance()
|
||||
Token(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()
|
||||
Token("/=", from, Token.Type.SLASHASSIGN)
|
||||
}
|
||||
|
||||
else -> Token("/", from, Token.Type.SLASH)
|
||||
}
|
||||
|
||||
'%' -> when (currentChar) {
|
||||
'=' -> {
|
||||
pos.advance(); Token("%=", from, Token.Type.PERCENTASSIGN)
|
||||
}
|
||||
|
||||
else -> Token("%", from, Token.Type.PERCENT)
|
||||
}
|
||||
|
||||
'.' -> {
|
||||
// could be: dot, range .. or ..<, or ellipsis ...:
|
||||
if (currentChar == '.') {
|
||||
pos.advance()
|
||||
// .. already parsed:
|
||||
if (currentChar == '.') {
|
||||
pos.advance()
|
||||
Token("...", from, Token.Type.ELLIPSIS)
|
||||
} else if (currentChar == '<') {
|
||||
pos.advance()
|
||||
Token("..<", from, Token.Type.DOTDOTLT)
|
||||
} else {
|
||||
Token("..", from, Token.Type.DOTDOT)
|
||||
}
|
||||
} else
|
||||
Token(".", from, Token.Type.DOT)
|
||||
}
|
||||
|
||||
'<' -> {
|
||||
if (currentChar == '=') {
|
||||
pos.advance()
|
||||
if( currentChar == '>' ) {
|
||||
pos.advance()
|
||||
Token("<=>", from, Token.Type.SHUTTLE)
|
||||
}
|
||||
else {
|
||||
Token("<=", from, Token.Type.LTE)
|
||||
}
|
||||
} else
|
||||
Token("<", from, Token.Type.LT)
|
||||
}
|
||||
|
||||
'>' -> {
|
||||
if (currentChar == '=') {
|
||||
pos.advance()
|
||||
Token(">=", from, Token.Type.GTE)
|
||||
} else
|
||||
Token(">", from, Token.Type.GT)
|
||||
}
|
||||
|
||||
'!' -> {
|
||||
if (currentChar == 'i') {
|
||||
pos.advance()
|
||||
when (currentChar) {
|
||||
'n' -> {
|
||||
pos.advance()
|
||||
Token("!in", from, Token.Type.NOTIN)
|
||||
}
|
||||
|
||||
's' -> {
|
||||
pos.advance()
|
||||
Token("!is", from, Token.Type.NOTIS)
|
||||
}
|
||||
|
||||
else -> {
|
||||
pos.back()
|
||||
Token("!", from, Token.Type.NOT)
|
||||
}
|
||||
}
|
||||
} else
|
||||
if (currentChar == '=') {
|
||||
pos.advance()
|
||||
if (currentChar == '=') {
|
||||
pos.advance()
|
||||
Token("!==", from, Token.Type.REF_NEQ)
|
||||
} else
|
||||
Token("!=", from, Token.Type.NEQ)
|
||||
} else
|
||||
Token("!", from, Token.Type.NOT)
|
||||
}
|
||||
|
||||
'|' -> {
|
||||
if (currentChar == '|') {
|
||||
pos.advance()
|
||||
Token("||", from, Token.Type.OR)
|
||||
} else
|
||||
Token("|", from, Token.Type.BITOR)
|
||||
}
|
||||
|
||||
'&' -> {
|
||||
if (currentChar == '&') {
|
||||
pos.advance()
|
||||
Token("&&", from, Token.Type.AND)
|
||||
} else
|
||||
Token("&", from, Token.Type.BITAND)
|
||||
}
|
||||
|
||||
'@' -> {
|
||||
val label = loadChars(idNextChars)
|
||||
if (label.isNotEmpty()) Token(label, from, Token.Type.ATLABEL)
|
||||
else raise("unexpected @ character")
|
||||
}
|
||||
|
||||
'\n' -> Token("\n", from, Token.Type.NEWLINE)
|
||||
|
||||
':' -> {
|
||||
if (currentChar == ':') {
|
||||
pos.advance()
|
||||
Token("::", from, Token.Type.COLONCOLON)
|
||||
} else
|
||||
Token(":", from, Token.Type.COLON)
|
||||
}
|
||||
|
||||
'"' -> loadStringToken()
|
||||
in digitsSet -> {
|
||||
pos.back()
|
||||
decodeNumber(loadChars(digits), from)
|
||||
}
|
||||
|
||||
'\'' -> {
|
||||
val start = pos.toPos()
|
||||
var value = currentChar
|
||||
pos.advance()
|
||||
if (currentChar == '\\') {
|
||||
value = currentChar
|
||||
pos.advance()
|
||||
value = when (value) {
|
||||
'n' -> '\n'
|
||||
'r' -> '\r'
|
||||
't' -> '\t'
|
||||
'\'', '\\' -> value
|
||||
else -> throw ScriptError(currentPos, "unsupported escape character: $value")
|
||||
}
|
||||
}
|
||||
if (currentChar != '\'') throw ScriptError(currentPos, "expected end of character literal: '")
|
||||
pos.advance()
|
||||
Token(value.toString(), start, Token.Type.CHAR)
|
||||
}
|
||||
|
||||
else -> {
|
||||
// text infix operators:
|
||||
// Labels processing is complicated!
|
||||
// some@ statement: label 'some', ID 'statement'
|
||||
// statement@some: ID 'statement', LABEL 'some'!
|
||||
if (ch.isLetter() || ch == '_') {
|
||||
val text = ch + loadChars(idNextChars)
|
||||
if (currentChar == '@') {
|
||||
pos.advance()
|
||||
if (currentChar.isLetter()) {
|
||||
// break@label or like
|
||||
pos.back()
|
||||
Token(text, from, Token.Type.ID)
|
||||
} else
|
||||
Token(text, from, Token.Type.LABEL)
|
||||
} else
|
||||
when (text) {
|
||||
"in" -> Token("in", from, Token.Type.IN)
|
||||
"is" -> Token("is", from, Token.Type.IS)
|
||||
else -> Token(text, from, Token.Type.ID)
|
||||
}
|
||||
} else
|
||||
raise("can't parse token")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun decodeNumber(p1: String, start: Pos): Token =
|
||||
if (pos.end)
|
||||
Token(p1, start, Token.Type.INT)
|
||||
else if (currentChar == '.') {
|
||||
// could be decimal
|
||||
pos.advance()
|
||||
if (currentChar in digitsSet) {
|
||||
// decimal part
|
||||
val p2 = loadChars(digits)
|
||||
// with exponent?
|
||||
if (currentChar == 'e' || currentChar == 'E') {
|
||||
pos.advance()
|
||||
var negative = false
|
||||
if (currentChar == '+')
|
||||
pos.advance()
|
||||
else if (currentChar == '-') {
|
||||
negative = true
|
||||
pos.advance()
|
||||
}
|
||||
var p3 = loadChars(digits)
|
||||
if (negative) p3 = "-$p3"
|
||||
Token("$p1.${p2}e$p3", start, Token.Type.REAL)
|
||||
} else {
|
||||
// no exponent
|
||||
Token("$p1.$p2", start, Token.Type.REAL)
|
||||
}
|
||||
} else {
|
||||
// not decimal
|
||||
// something like 10.times, method call on integer number
|
||||
pos.back()
|
||||
Token(p1, start, Token.Type.INT)
|
||||
}
|
||||
} else {
|
||||
// could be integer, also hex:
|
||||
if (currentChar == 'x' && p1 == "0") {
|
||||
pos.advance()
|
||||
Token(loadChars({ it in hexDigits }), start, Token.Type.HEX).also {
|
||||
if (currentChar.isLetter())
|
||||
raise("invalid hex literal")
|
||||
}
|
||||
} else {
|
||||
Token(p1, start, Token.Type.INT)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private val currentChar: Char get() = pos.currentChar
|
||||
|
||||
private fun loadStringToken(): Token {
|
||||
var start = currentPos
|
||||
|
||||
if (currentChar == '"') pos.advance()
|
||||
else start = start.back()
|
||||
|
||||
val sb = StringBuilder()
|
||||
while (currentChar != '"') {
|
||||
if (pos.end) throw ScriptError(start, "unterminated string started there")
|
||||
when (currentChar) {
|
||||
'\\' -> {
|
||||
pos.advance() ?: raise("unterminated string")
|
||||
when (currentChar) {
|
||||
'n' -> sb.append('\n')
|
||||
'r' -> sb.append('\r')
|
||||
't' -> sb.append('\t')
|
||||
'"' -> sb.append('"')
|
||||
else -> sb.append('\\').append(currentChar)
|
||||
}
|
||||
}
|
||||
|
||||
else -> {
|
||||
sb.append(currentChar)
|
||||
pos.advance()
|
||||
}
|
||||
}
|
||||
}
|
||||
pos.advance()
|
||||
return Token(sb.toString(), start, Token.Type.STRING)
|
||||
}
|
||||
|
||||
/**
|
||||
* Load characters from the set until it reaches EOF or invalid character found.
|
||||
* stop at EOF on character filtered by [isValidChar].
|
||||
*
|
||||
* Note this function loads only on one string. Multiline texts are not supported by
|
||||
* this method.
|
||||
*
|
||||
* @return the string of valid characters, could be empty
|
||||
*/
|
||||
private fun loadChars(isValidChar: (Char) -> Boolean): String {
|
||||
val startLine = pos.line
|
||||
val result = StringBuilder()
|
||||
while (!pos.end && pos.line == startLine) {
|
||||
val ch = pos.currentChar
|
||||
if (isValidChar(ch)) {
|
||||
result.append(ch)
|
||||
pos.advance()
|
||||
} else
|
||||
break
|
||||
}
|
||||
return result.toString()
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
private fun loadUntil(endChars: Set<Char>): String {
|
||||
return if (pos.end) ""
|
||||
else {
|
||||
val result = StringBuilder()
|
||||
while (!pos.end) {
|
||||
val ch = pos.currentChar
|
||||
if (ch in endChars) break
|
||||
result.append(ch)
|
||||
pos.advance()
|
||||
}
|
||||
result.toString()
|
||||
}
|
||||
}
|
||||
|
||||
private fun loadToEnd(): String {
|
||||
val result = StringBuilder()
|
||||
val l = pos.line
|
||||
do {
|
||||
result.append(pos.currentChar)
|
||||
pos.advance()
|
||||
} while (pos.line == l)
|
||||
return result.toString()
|
||||
}
|
||||
|
||||
private fun loadTo(str: String): String? {
|
||||
val result = StringBuilder()
|
||||
while (!pos.readFragment(str)) {
|
||||
if (pos.end) return null
|
||||
result.append(pos.currentChar); pos.advance()
|
||||
}
|
||||
return result.toString()
|
||||
}
|
||||
|
||||
/**
|
||||
* next non-whitespace char (newline are skipped too) or null if EOF
|
||||
*/
|
||||
private fun skipws(): Char? {
|
||||
while (!pos.end) {
|
||||
val ch = pos.currentChar
|
||||
if (ch == '\n') break
|
||||
if (ch.isWhitespace())
|
||||
pos.advance()
|
||||
else
|
||||
return ch
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
}
|
||||
+29
-12
@@ -1,8 +1,8 @@
|
||||
package net.sergeych.ling
|
||||
package net.sergeych.lyng
|
||||
|
||||
data class Pos(val source: Source, val line: Int, val column: Int) {
|
||||
override fun toString(): String {
|
||||
return "${source.fileName}:$line:$column"
|
||||
return "${source.fileName}:${line+1}:${column}"
|
||||
}
|
||||
|
||||
fun back(): Pos =
|
||||
@@ -16,6 +16,7 @@ data class Pos(val source: Source, val line: Int, val column: Int) {
|
||||
|
||||
companion object {
|
||||
val builtIn = Pos(Source.builtIn, 0, 0)
|
||||
val UNKNOWN = Pos(Source.UNKNOWN, -1, -1)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -36,28 +37,44 @@ class MutablePos(private val from: Pos) {
|
||||
fun advance(): Char? {
|
||||
if (end) return null
|
||||
val current = lines[line]
|
||||
return if (column+1 < current.length) {
|
||||
current[column++]
|
||||
return if (column < current.length) {
|
||||
column++
|
||||
currentChar
|
||||
} else {
|
||||
column = 0
|
||||
while( ++line < lines.size && lines[line].isEmpty() ) {
|
||||
// skip empty lines
|
||||
}
|
||||
if(line >= lines.size) null
|
||||
else lines[line][column]
|
||||
if(++line >= lines.size) null
|
||||
else currentChar
|
||||
}
|
||||
}
|
||||
|
||||
fun resetTo(pos: Pos) { line = pos.line; column = pos.column }
|
||||
|
||||
fun back() {
|
||||
if (column > 0) column--
|
||||
else if (line > 0)
|
||||
column = lines[--line].length - 1
|
||||
else throw IllegalStateException("can't go back from line 0, column 0")
|
||||
}
|
||||
|
||||
val currentChar: Char
|
||||
get() =
|
||||
if (end) 0.toChar()
|
||||
else lines[line][column]
|
||||
get() {
|
||||
if (end) return 0.toChar()
|
||||
val current = lines[line]
|
||||
return if (column >= current.length) '\n'
|
||||
else current[column]
|
||||
}
|
||||
|
||||
/**
|
||||
* If the next characters are equal to the fragment, advances the position and returns true.
|
||||
* Otherwise, does nothing and returns false.
|
||||
*/
|
||||
fun readFragment(fragment: String): Boolean {
|
||||
val mark = toPos()
|
||||
for(ch in fragment)
|
||||
if( currentChar != ch ) { resetTo(mark); return false }
|
||||
else advance()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun toString() = "($line:$column)"
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
import kotlinx.coroutines.delay
|
||||
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") {
|
||||
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(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") {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
@file:Suppress("CanBeParameter")
|
||||
|
||||
package net.sergeych.lyng
|
||||
|
||||
open class ScriptError(val pos: Pos, val errorMessage: String,cause: Throwable?=null) : Exception(
|
||||
"""
|
||||
$pos: Error: $errorMessage
|
||||
|
||||
${pos.currentLine}
|
||||
${"-".repeat(pos.column)}^
|
||||
""".trimIndent(),
|
||||
cause
|
||||
)
|
||||
|
||||
class ExecutionError(val errorObject: ObjError) : ScriptError(errorObject.context.pos, errorObject.message)
|
||||
+2
-1
@@ -1,4 +1,4 @@
|
||||
package net.sergeych.ling
|
||||
package net.sergeych.lyng
|
||||
|
||||
class Source(val fileName: String, text: String) {
|
||||
|
||||
@@ -6,6 +6,7 @@ class Source(val fileName: String, text: String) {
|
||||
|
||||
companion object {
|
||||
val builtIn: Source by lazy { Source("built-in", "") }
|
||||
val UNKNOWN: Source by lazy { Source("UNKNOWN", "") }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
data class Token(val value: String, val pos: Pos, val type: Type) {
|
||||
val isComment: Boolean by lazy { type == Type.SINLGE_LINE_COMMENT || type == Type.MULTILINE_COMMENT }
|
||||
|
||||
@Suppress("unused")
|
||||
enum class Type {
|
||||
ID, INT, REAL, HEX, STRING, CHAR,
|
||||
LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, COMMA,
|
||||
SEMICOLON, COLON,
|
||||
PLUS, MINUS, STAR, SLASH, PERCENT,
|
||||
ASSIGN, PLUSASSIGN, MINUSASSIGN, STARASSIGN, SLASHASSIGN, PERCENTASSIGN,
|
||||
PLUS2, MINUS2,
|
||||
IN, NOTIN, IS, NOTIS,
|
||||
EQ, NEQ, LT, LTE, GT, GTE, REF_EQ, REF_NEQ,
|
||||
SHUTTLE,
|
||||
AND, BITAND, OR, BITOR, NOT, BITNOT, DOT, ARROW, QUESTION, COLONCOLON,
|
||||
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
||||
LABEL, ATLABEL, // label@ at@label
|
||||
ELLIPSIS, DOTDOT, DOTDOTLT,
|
||||
NEWLINE,
|
||||
EOF,
|
||||
}
|
||||
|
||||
companion object {
|
||||
// fun eof(parser: Parser) = Token("", parser.currentPos, Type.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,5 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
import net.sergeych.lyng.buildconfig.BuildConfig
|
||||
|
||||
val LyngVersion = BuildConfig.VERSION
|
||||
@@ -0,0 +1,60 @@
|
||||
package net.sergeych.lyng
|
||||
|
||||
fun String.toSource(name: String = "eval"): Source = Source(name, this)
|
||||
|
||||
sealed class ObjType {
|
||||
object Any : ObjType()
|
||||
object Int : ObjType()
|
||||
}
|
||||
|
||||
|
||||
@Suppress("unused")
|
||||
abstract class Statement(
|
||||
val isStaticConst: Boolean = false,
|
||||
val isConst: Boolean = false,
|
||||
val returnType: ObjType = ObjType.Any
|
||||
) : Obj() {
|
||||
|
||||
override val objClass: ObjClass = type
|
||||
|
||||
abstract val pos: Pos
|
||||
abstract suspend fun execute(context: Context): Obj
|
||||
|
||||
override suspend fun compareTo(context: Context,other: Obj): Int {
|
||||
throw UnsupportedOperationException("not comparable")
|
||||
}
|
||||
|
||||
override suspend fun callOn(context: Context): Obj {
|
||||
return execute(context)
|
||||
}
|
||||
|
||||
override fun toString(): String = "Callable@${this.hashCode()}"
|
||||
|
||||
companion object {
|
||||
val type = ObjClass("Callable")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fun Statement.raise(text: String): Nothing {
|
||||
throw ScriptError(pos, text)
|
||||
}
|
||||
|
||||
@Suppress("unused")
|
||||
fun Statement.require(cond: Boolean, message: () -> String) {
|
||||
if (!cond) raise(message())
|
||||
}
|
||||
|
||||
fun statement(pos: Pos, isStaticConst: Boolean = false, isConst: Boolean = false, f: suspend (Context) -> Obj): Statement =
|
||||
object : Statement(isStaticConst, isConst) {
|
||||
override val pos: Pos = pos
|
||||
override suspend fun execute(context: Context): Obj = f(context)
|
||||
}
|
||||
|
||||
fun statement(isStaticConst: Boolean = false, isConst: Boolean = false, f: suspend Context.() -> Obj): Statement =
|
||||
object : Statement(isStaticConst, isConst) {
|
||||
override val pos: Pos = Pos.builtIn
|
||||
override suspend fun execute(context: Context): Obj = f(context)
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,271 @@
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.test.runTest
|
||||
import net.sergeych.lyng.Context
|
||||
import net.sergeych.lyng.ObjVoid
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.Files.readAllLines
|
||||
import java.nio.file.Paths
|
||||
import kotlin.io.path.absolutePathString
|
||||
import kotlin.io.path.extension
|
||||
import kotlin.test.Test
|
||||
import kotlin.test.assertEquals
|
||||
import kotlin.test.fail
|
||||
|
||||
fun leftMargin(s: String): Int {
|
||||
var cnt = 0
|
||||
for (c in s) {
|
||||
when (c) {
|
||||
' ' -> cnt++
|
||||
'\t' -> cnt = (cnt / 4.0 + 0.9).toInt() * 4
|
||||
else -> break
|
||||
}
|
||||
}
|
||||
return cnt
|
||||
}
|
||||
|
||||
data class DocTest(
|
||||
val fileName: String,
|
||||
val line: Int,
|
||||
val code: String,
|
||||
val expectedOutput: String,
|
||||
val expectedResult: String,
|
||||
val expectedError: String? = null,
|
||||
val bookMode: Boolean = false
|
||||
) {
|
||||
val sourceLines by lazy { code.lines() }
|
||||
|
||||
val fileNamePart by lazy {
|
||||
Paths.get(fileName).fileName.toString()
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
val absPath = Paths.get(fileName).absolutePathString()
|
||||
return "DocTest: $absPath:${line + 1}"
|
||||
}
|
||||
|
||||
val detailedString by lazy {
|
||||
val codeWithLines = sourceLines.withIndex().map { (i, s) -> "${i + line + 1}: $s" }.joinToString("\n")
|
||||
var result = "$this\n$codeWithLines\n"
|
||||
if( !bookMode) {
|
||||
if (expectedOutput.isNotBlank())
|
||||
result += "--------expected output--------\n$expectedOutput\n"
|
||||
|
||||
"$result-----expected return value-----\n$expectedResult"
|
||||
}
|
||||
else result
|
||||
}
|
||||
}
|
||||
|
||||
fun parseDocTests(fileName: String, bookMode: Boolean = false): Flow<DocTest> = flow {
|
||||
val book = readAllLines(Paths.get(fileName))
|
||||
var startOffset = 0
|
||||
val block = mutableListOf<String>()
|
||||
var startIndex = 0
|
||||
for ((index, l) in book.withIndex()) {
|
||||
val off = leftMargin(l)
|
||||
when {
|
||||
off < startOffset && startOffset != 0 -> {
|
||||
if (l.isBlank()) {
|
||||
continue
|
||||
}
|
||||
// end of block or just text:
|
||||
if (block.isNotEmpty()) {
|
||||
// check/create block
|
||||
// 2 lines min
|
||||
if (block.size > 1) {
|
||||
// remove prefix
|
||||
for ((i, s) in block.withIndex()) {
|
||||
var x = s
|
||||
// could be tabs :(
|
||||
val initial = leftMargin(x)
|
||||
do {
|
||||
x = x.drop(1)
|
||||
} while (initial - leftMargin(x) != startOffset)
|
||||
block[i] = x
|
||||
}
|
||||
if (bookMode) {
|
||||
emit(
|
||||
DocTest(
|
||||
fileName, startIndex,
|
||||
block.joinToString("\n"),
|
||||
"",
|
||||
"",
|
||||
null,
|
||||
bookMode = true
|
||||
)
|
||||
)
|
||||
}
|
||||
// println(block.joinToString("\n") { "${startIndex + ii++}: $it" })
|
||||
val outStart = block.indexOfFirst { it.startsWith(">>>") }
|
||||
if (outStart < 0) {
|
||||
// println("No output at block from line ${startIndex+1}")
|
||||
} else {
|
||||
var isValid = true
|
||||
val result = mutableListOf<String>()
|
||||
while (block.size > outStart) {
|
||||
val line = block.removeAt(outStart)
|
||||
if (!line.startsWith(">>> ")) {
|
||||
println("invalid output line, must start with '>>> ', block from ${startIndex + 1}: $line")
|
||||
isValid = false
|
||||
break
|
||||
}
|
||||
result.add(line.drop(4))
|
||||
}
|
||||
if (isValid) {
|
||||
emit(
|
||||
DocTest(
|
||||
fileName, startIndex,
|
||||
block.joinToString("\n"),
|
||||
if (result.size > 1)
|
||||
result.dropLast(1).joinToString("") { it + "\n" }
|
||||
else "",
|
||||
result.last()
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
// last line '>>>'
|
||||
}
|
||||
block.clear()
|
||||
startOffset = 0
|
||||
}
|
||||
}
|
||||
|
||||
off != 0 && startOffset == 0 -> {
|
||||
// start
|
||||
block.clear()
|
||||
startIndex = index
|
||||
block.add(l)
|
||||
startOffset = off
|
||||
}
|
||||
|
||||
off != 0 -> {
|
||||
block.add(l)
|
||||
}
|
||||
|
||||
off == 0 && startOffset == 0 -> {
|
||||
// skip
|
||||
}
|
||||
|
||||
else -> {
|
||||
throw RuntimeException("Unexpected line: ($off/$startOffset) $l")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.flowOn(Dispatchers.IO)
|
||||
|
||||
suspend fun DocTest.test(context: Context = Context()) {
|
||||
val collectedOutput = StringBuilder()
|
||||
val currentTest = this
|
||||
context.apply {
|
||||
addFn("println") {
|
||||
if( bookMode ) {
|
||||
println("${currentTest.fileNamePart}:${currentTest.line}> ${args.joinToString(" "){it.asStr.value}}")
|
||||
}
|
||||
else {
|
||||
for ((i, a) in args.withIndex()) {
|
||||
if (i > 0) collectedOutput.append(' '); collectedOutput.append(a.asStr.value)
|
||||
collectedOutput.append('\n')
|
||||
}
|
||||
}
|
||||
ObjVoid
|
||||
}
|
||||
}
|
||||
var error: Throwable? = null
|
||||
val result = try {
|
||||
context.eval(code)
|
||||
} catch (e: Throwable) {
|
||||
error = e
|
||||
null
|
||||
}?.inspect()?.replace(Regex("@\\d+"), "@...")
|
||||
|
||||
if (bookMode) {
|
||||
if (error != null) {
|
||||
println("Sample 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")
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun runDocTests(fileName: String, bookMode: Boolean = false) {
|
||||
val bookContext = Context()
|
||||
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 {
|
||||
|
||||
@Test
|
||||
fun testsFromTutorial() = runTest {
|
||||
runDocTests("../docs/tutorial.md")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testsFromMath() = runTest {
|
||||
runDocTests("../docs/math.md")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testsFromAdvanced() = runTest {
|
||||
runDocTests("../docs/advanced_topics.md")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testsFromOOP() = runTest {
|
||||
runDocTests("../docs/OOP.md")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFromReal() = runTest {
|
||||
runDocTests("../docs/Real.md")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFromList() = runTest {
|
||||
runDocTests("../docs/List.md")
|
||||
}
|
||||
|
||||
@Test
|
||||
fun testFromRange() = runTest {
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
plugins {
|
||||
kotlin("multiplatform") version "2.1.21"
|
||||
}
|
||||
|
||||
group = "net.sergeych"
|
||||
version = "unspecified"
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://maven.universablockchain.com/")
|
||||
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||
mavenLocal()
|
||||
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvm {
|
||||
binaries {
|
||||
executable {
|
||||
mainClass.set("net.sergeych.lyng_cli.MainKt")
|
||||
}
|
||||
}
|
||||
}
|
||||
linuxX64 {
|
||||
binaries {
|
||||
executable()
|
||||
}
|
||||
}
|
||||
sourceSets {
|
||||
val commonMain by getting {
|
||||
dependencies {
|
||||
implementation(project(":library"))
|
||||
implementation(libs.okio)
|
||||
|
||||
implementation(libs.clikt)
|
||||
|
||||
// optional support for rendering markdown in help messages
|
||||
// implementation(libs.clikt.markdown)
|
||||
}
|
||||
}
|
||||
val commonTest by getting {
|
||||
dependencies {
|
||||
implementation(kotlin("test-common"))
|
||||
implementation(kotlin("test-annotations-common"))
|
||||
implementation(libs.okio.fakefilesystem)
|
||||
}
|
||||
}
|
||||
val linuxX64Main by getting {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
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
|
||||
|
||||
expect fun exit(code: Int)
|
||||
|
||||
val baseContext = Context().apply {
|
||||
addFn("exit") {
|
||||
exit(requireOnlyArg<ObjInt>().toInt())
|
||||
ObjVoid
|
||||
}
|
||||
}
|
||||
|
||||
class LyngCLI(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)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package net.sergeych.lyng_cli
|
||||
|
||||
import com.github.ajalt.clikt.core.main
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import net.sergeych.LyngCLI
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
LyngCLI({ runBlocking { it() } }).main(args)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import com.github.ajalt.clikt.core.main
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import net.sergeych.LyngCLI
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
LyngCLI( { runBlocking { it() } }).main(args)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package net.sergeych
|
||||
|
||||
import kotlin.system.exitProcess
|
||||
|
||||
actual fun exit(code: Int) {
|
||||
exitProcess(code)
|
||||
}
|
||||
+3
-1
@@ -13,8 +13,10 @@ dependencyResolutionManagement {
|
||||
maven("https://maven.universablockchain.com/")
|
||||
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||
mavenLocal()
|
||||
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "ling"
|
||||
rootProject.name = "lyng"
|
||||
include(":library")
|
||||
include(":lyng")
|
||||
Reference in new issue
Block a user