Compare commits
38
Commits
ee392daa13
...
1.5.5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9735774efd | ||
|
|
14214e91e1 | ||
|
|
0f5343fa17 | ||
|
|
d0f51928de | ||
|
|
0973a6afeb | ||
|
|
953f237ca3 | ||
|
|
fbb5688696 | ||
|
|
f4ab2ebab4 | ||
|
|
0c3242cbd8 | ||
|
|
1d5caaa836 | ||
|
|
3be2892025 | ||
|
|
c80900c503 | ||
|
|
ee634c8dff | ||
|
|
6c91b77a85 | ||
|
|
3721ee8332 | ||
|
|
97990f00ce | ||
|
|
80693e7690 | ||
|
|
029fe874fa | ||
|
|
ffa64d691b | ||
|
|
30c9a5a565 | ||
|
|
db3a780645 | ||
|
|
fc7d26ee4b | ||
|
|
a61b5a31be | ||
|
|
33d170f525 | ||
|
|
f72cdfdf83 | ||
|
|
10fa4de4fa | ||
|
|
4acee56de8 | ||
|
|
87060c7eb7 | ||
|
|
6ba128f7ba | ||
|
|
a8f73dc8bd | ||
|
|
145c3ae34a | ||
|
|
f9a07f176a | ||
|
|
30e56946a0 | ||
|
|
49fc700233 | ||
|
|
07cb5a519c | ||
|
|
8f66cd7680 | ||
|
|
bb2119b1d1 | ||
|
|
64273ac60a |
No files matched your search
@@ -29,3 +29,5 @@ debug.log
|
|||||||
test_output*.txt
|
test_output*.txt
|
||||||
/site/src/version-template/lyng-version.js
|
/site/src/version-template/lyng-version.js
|
||||||
/bugcontents.db
|
/bugcontents.db
|
||||||
|
/bugs/
|
||||||
|
contents.db
|
||||||
+37
-15
@@ -9,24 +9,46 @@ History note:
|
|||||||
|
|
||||||
## Unreleased
|
## Unreleased
|
||||||
|
|
||||||
### Database access
|
- No unreleased entries yet.
|
||||||
- Added the portable `lyng.io.db` SQL contract and the first concrete provider, `lyng.io.db.sqlite`.
|
|
||||||
- Added SQLite support on JVM and Linux Native with:
|
|
||||||
- generic `openDatabase("sqlite:...")` dispatch
|
|
||||||
- typed `openSqlite(...)` helper
|
|
||||||
- real nested transactions via savepoints
|
|
||||||
- generated keys through `ExecutionResult.getGeneratedKeys()`
|
|
||||||
- strict schema-driven value conversion for `Bool`, `Decimal`, `Date`, `DateTime`, and `Instant`
|
|
||||||
- documented option handling for `readOnly`, `createIfMissing`, `foreignKeys`, and `busyTimeoutMillis`
|
|
||||||
- Added public docs for database usage and SQLite provider behavior.
|
|
||||||
|
|
||||||
### Time
|
## 1.5.5 (2026-04-23)
|
||||||
- Added `Date` to `lyng.time` and the core library as a first-class calendar-date type.
|
|
||||||
- Added `Instant.toDate(...)`, `DateTime.date`, `DateTime.toDate()`, `Date.toDateTime(...)`, and related date arithmetic.
|
### Concurrency and collections
|
||||||
- Added docs, stdlib reference updates, serialization support, and comprehensive tests for `Date`.
|
- Added coroutine coordination primitives and helpers for everyday parallel code:
|
||||||
|
- `Channel` for coroutine-to-coroutine communication
|
||||||
|
- `LaunchPool` for bounded-concurrency task execution
|
||||||
|
- `Iterable<Deferred>.joinAll()` to await a whole collection of deferreds in input order
|
||||||
|
- `CompletableDeferred.completeExceptionally(...)` and `Deferred.cancelAndJoin()`
|
||||||
|
- Added docs and examples for the new concurrency APIs, including `joinAll()` coverage in iterable and parallelism references.
|
||||||
|
|
||||||
|
### Database and time APIs
|
||||||
|
- Added the portable `lyng.io.db` SQL contract and the first concrete providers:
|
||||||
|
- `lyng.io.db.sqlite` on JVM and Linux Native
|
||||||
|
- `lyng.io.db.jdbc` on JVM
|
||||||
|
- Added SQLite/JDBC release hardening:
|
||||||
|
- nested transactions via savepoints
|
||||||
|
- detached materialized rows
|
||||||
|
- generated-key support through `ExecutionResult.getGeneratedKeys()`
|
||||||
|
- schema-driven value conversion for `Bool`, `Decimal`, `Date`, `DateTime`, and `Instant`
|
||||||
|
- portable SQLite linker/deployment fixes and documented runtime options
|
||||||
|
- Added `Date` to `lyng.time` and the core runtime as a first-class calendar-date type, plus conversions and arithmetic across `Instant`, `DateTime`, and `Date`.
|
||||||
|
|
||||||
|
### Language, stdlib, and tooling
|
||||||
|
- Added extensions on singleton `object` declarations, including object-scoped indexer overrides for bracket syntax.
|
||||||
|
- Added backtick string literals and formatter support.
|
||||||
|
- Added `lyng.legacy_digest` for SHA-1 compatibility work, `String.replace`, and `buffer.base64std`.
|
||||||
|
- Improved CLI/runtime behavior with `atExit` shutdown handlers, native release-binary work, and follow-up CLI packaging/import fixes.
|
||||||
|
- Expanded docs across the tutorial, stdlib references, database docs, networking docs, and release notes.
|
||||||
|
|
||||||
|
### Runtime/compiler stability and performance
|
||||||
|
- Extended exact-call and higher-order lambda inlining through the bytecode compiler, including compiled fast paths for simple lambdas, wrappers, captures, and common higher-order helpers.
|
||||||
|
- Fixed import caching and class/object bytecode dispatch on JVM.
|
||||||
|
- Fixed immutable `val` compound assignments so true mutating `*Assign` operations continue to work while fallback reassignments report the correct read-only error.
|
||||||
|
- Fixed closure/capture and import regressions across launched loops, singleton/object extensions, aliasing, transitive re-exports, and immutable capture escaping.
|
||||||
|
- Improved list-fill/list-append fast paths, nullable-let inference, Decimal/Complex interop, and related regression coverage.
|
||||||
|
|
||||||
### Release notes
|
### Release notes
|
||||||
- Full `:lyngio:jvmTest` and `:lyngio:linuxX64Test` pass on the release tree after SQLite hardening.
|
- Release metadata, homepage samples, docs, and README now point to `1.5.5`.
|
||||||
|
|
||||||
## 1.5.4 (2026-04-03)
|
## 1.5.4 (2026-04-03)
|
||||||
|
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ assertEquals(A.E.One, A.One)
|
|||||||
|
|
||||||
- [Language home](https://lynglang.com)
|
- [Language home](https://lynglang.com)
|
||||||
- [introduction and tutorial](docs/tutorial.md) - start here please
|
- [introduction and tutorial](docs/tutorial.md) - start here please
|
||||||
- [Latest release notes (1.5.4)](docs/whats_new.md)
|
- [Latest release notes (1.5.5)](docs/whats_new.md)
|
||||||
- [What's New in 1.5](docs/whats_new_1_5.md)
|
- [What's New in 1.5](docs/whats_new_1_5.md)
|
||||||
- [Testing and Assertions](docs/Testing.md)
|
- [Testing and Assertions](docs/Testing.md)
|
||||||
- [Filesystem and Processes (lyngio)](docs/lyngio.md)
|
- [Filesystem and Processes (lyngio)](docs/lyngio.md)
|
||||||
@@ -66,7 +66,7 @@ assertEquals(A.E.One, A.One)
|
|||||||
### Add dependency to your project
|
### Add dependency to your project
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
val lyngVersion = "1.5.4"
|
val lyngVersion = "1.5.5"
|
||||||
|
|
||||||
repositories {
|
repositories {
|
||||||
// ...
|
// ...
|
||||||
@@ -186,7 +186,7 @@ Designed to add scripting to kotlin multiplatform application in easy and effici
|
|||||||
|
|
||||||
# Language Roadmap
|
# Language Roadmap
|
||||||
|
|
||||||
The current stable release is **v1.5.4**: the 1.5 cycle is feature-complete, compiler/runtime stabilization work is in, and the language, tooling, and site are aligned around the current release.
|
The current stable release is **v1.5.5**: the 1.5 cycle now includes the database/date/concurrency additions as well as the latest compiler/runtime stabilization work, and the language, tooling, and site are aligned around this release.
|
||||||
|
|
||||||
Ready features:
|
Ready features:
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -20,7 +20,7 @@
|
|||||||
set -e
|
set -e
|
||||||
echo "publishing all artifacts"
|
echo "publishing all artifacts"
|
||||||
echo
|
echo
|
||||||
./gradlew publishToMavenLocal site:jsBrowserDistribution publish buildInstallablePlugin :lyng:linkReleaseExecutableLinuxX64 :lyng:installJvmDist --parallel #--no-configuration-cache
|
./gradlew publishToMavenLocal site:jsBrowserDistribution publish buildInstallablePlugin :lyng:linkReleaseExecutableLinuxX64 :lyng:installJvmDist --parallel --no-configuration-cache
|
||||||
|
|
||||||
#echo
|
#echo
|
||||||
#echo "Creating plugin"
|
#echo "Creating plugin"
|
||||||
|
|||||||
+14
-11
@@ -18,10 +18,12 @@
|
|||||||
#
|
#
|
||||||
|
|
||||||
upload_only=false
|
upload_only=false
|
||||||
|
target=vps # default: new server; use --old for d.lynglang.com
|
||||||
for arg in "$@"; do
|
for arg in "$@"; do
|
||||||
if [[ "$arg" == "-u" || "$arg" == "--upload-only" ]]; then
|
if [[ "$arg" == "-u" || "$arg" == "--upload-only" ]]; then
|
||||||
upload_only=true
|
upload_only=true
|
||||||
break
|
elif [[ "$arg" == "--old" ]]; then
|
||||||
|
target=com
|
||||||
fi
|
fi
|
||||||
done
|
done
|
||||||
|
|
||||||
@@ -88,19 +90,20 @@ function updateIdeaPluginDownloadLink() {
|
|||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
# default target settings
|
# target settings (-t com | -t vps)
|
||||||
case "com" in
|
case "$target" in
|
||||||
com)
|
com)
|
||||||
SSH_HOST=sergeych@d.lynglang.com # host to deploy to
|
SSH_HOST=sergeych@d.lynglang.com
|
||||||
SSH_PORT=22 # ssh port on it
|
SSH_PORT=22
|
||||||
ROOT=/bigstore/sergeych_pub/lyng # directory to rsync to
|
ROOT=/bigstore/sergeych_pub/lyng
|
||||||
|
;;
|
||||||
|
vps)
|
||||||
|
SSH_HOST=sergeych@94.130.36.94
|
||||||
|
SSH_PORT=22
|
||||||
|
ROOT=/var/www/lynglang
|
||||||
;;
|
;;
|
||||||
# com)
|
|
||||||
# SSH_HOST=vvk@front-01.neurodatalab.com
|
|
||||||
# ROOT=/home/vvk
|
|
||||||
# ;;
|
|
||||||
*)
|
*)
|
||||||
echo "*** ERROR: target not specified (use deploy com | dev)"
|
echo "*** ERROR: unknown target '$target' (use -t com | -t vps)"
|
||||||
echo "*** stop"
|
echo "*** stop"
|
||||||
exit 101
|
exit 101
|
||||||
esac
|
esac
|
||||||
|
|||||||
+211
@@ -0,0 +1,211 @@
|
|||||||
|
# Channel
|
||||||
|
|
||||||
|
A `Channel` is a **hot, bidirectional pipe** for passing values between concurrently running coroutines.
|
||||||
|
Unlike a [Flow], which is cold and replayed on every collection, a `Channel` is stateful: each value
|
||||||
|
sent is consumed by exactly one receiver.
|
||||||
|
|
||||||
|
Channels model the classic _producer / consumer_ pattern and are the right tool when:
|
||||||
|
|
||||||
|
- two or more coroutines need to exchange individual values at their own pace;
|
||||||
|
- you want back-pressure (rendezvous) or explicit buffering control;
|
||||||
|
- you need a push-based, hot data source (opposite of the pull-based, cold [Flow]).
|
||||||
|
|
||||||
|
## Constructors
|
||||||
|
|
||||||
|
```
|
||||||
|
Channel() // rendezvous — sender and receiver must meet
|
||||||
|
Channel(n: Int) // buffered — sender may run n items ahead of the receiver
|
||||||
|
Channel(Channel.UNLIMITED) // no limit on buffered items
|
||||||
|
```
|
||||||
|
|
||||||
|
**Rendezvous** (`Channel()`, capacity 0): `send` suspends until a matching `receive` is ready,
|
||||||
|
and vice-versa. This gives the tightest synchronisation and the smallest memory footprint.
|
||||||
|
|
||||||
|
**Buffered** (`Channel(n)`): `send` only suspends when the internal buffer is full. Allows the
|
||||||
|
producer to get up to _n_ items ahead of the consumer.
|
||||||
|
|
||||||
|
**Unlimited** (`Channel(Channel.UNLIMITED)`): `send` never suspends. Useful when the producer is
|
||||||
|
bursty and you do not want it blocked, but be careful not to grow the buffer without bound.
|
||||||
|
|
||||||
|
## Sending and receiving
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val ch = Channel() // rendezvous channel
|
||||||
|
|
||||||
|
val producer = launch {
|
||||||
|
ch.send("hello") // suspends until the receiver is ready
|
||||||
|
ch.send("world")
|
||||||
|
ch.close() // signal: no more values
|
||||||
|
}
|
||||||
|
|
||||||
|
val a = ch.receive() // suspends until "hello" arrives
|
||||||
|
val b = ch.receive() // suspends until "world" arrives
|
||||||
|
val c = ch.receive() // channel is closed and drained → null
|
||||||
|
assertEquals("hello", a)
|
||||||
|
assertEquals("world", b)
|
||||||
|
assertEquals(null, c)
|
||||||
|
```
|
||||||
|
|
||||||
|
`receive()` returns `null` when the channel is both **closed** _and_ **fully drained** — that is
|
||||||
|
the idiomatic loop termination condition:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val ch = Channel(4)
|
||||||
|
|
||||||
|
launch {
|
||||||
|
for (i in 1..5) ch.send(i)
|
||||||
|
ch.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
var item = ch.receive()
|
||||||
|
while (item != null) {
|
||||||
|
println(item)
|
||||||
|
item = ch.receive()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Non-suspending poll
|
||||||
|
|
||||||
|
`tryReceive()` never suspends. It returns the next buffered value, or `null` if the buffer is
|
||||||
|
empty or the channel is closed.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val ch = Channel(8)
|
||||||
|
ch.send(42)
|
||||||
|
println(ch.tryReceive()) // 42
|
||||||
|
println(ch.tryReceive()) // null — nothing buffered right now
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `tryReceive` for _polling_ patterns where blocking would be unacceptable, for example when
|
||||||
|
combining channel checks with other work inside a coroutine loop.
|
||||||
|
|
||||||
|
## Closing a channel
|
||||||
|
|
||||||
|
`close()` marks the channel so that no further `send` calls are accepted. Any items already in the
|
||||||
|
buffer can still be received. Once the buffer is drained, `receive()` returns `null` and
|
||||||
|
`isClosedForReceive` becomes `true`.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val ch = Channel(2)
|
||||||
|
ch.send(1)
|
||||||
|
ch.send(2)
|
||||||
|
ch.close()
|
||||||
|
|
||||||
|
assert(ch.isClosedForSend)
|
||||||
|
assert(!ch.isClosedForReceive) // still has 2 buffered items
|
||||||
|
|
||||||
|
ch.receive() // 1
|
||||||
|
ch.receive() // 2
|
||||||
|
assert(ch.isClosedForReceive) // drained
|
||||||
|
```
|
||||||
|
|
||||||
|
Calling `send` after `close()` throws `IllegalStateException`.
|
||||||
|
|
||||||
|
## Properties
|
||||||
|
|
||||||
|
| property | type | description |
|
||||||
|
|---------------------|--------|----------------------------------------------------------|
|
||||||
|
| `isClosedForSend` | `Bool` | `true` after `close()` is called |
|
||||||
|
| `isClosedForReceive`| `Bool` | `true` when closed _and_ every buffered item is consumed |
|
||||||
|
|
||||||
|
## Methods
|
||||||
|
|
||||||
|
| method | suspends | description |
|
||||||
|
|-----------------|----------|----------------------------------------------------------------------------------|
|
||||||
|
| `send(value)` | yes | send a value; suspends when buffer full (rendezvous: always until partner ready) |
|
||||||
|
| `receive()` | yes | receive next value; suspends when empty; returns `null` when closed + drained |
|
||||||
|
| `tryReceive()` | no | return next buffered value or `null`; never suspends |
|
||||||
|
| `close()` | no | signal end of production; existing buffer items are still receivable |
|
||||||
|
|
||||||
|
## Static constants
|
||||||
|
|
||||||
|
| constant | value | description |
|
||||||
|
|---------------------|------------------|-------------------------------------|
|
||||||
|
| `Channel.UNLIMITED` | `Int.MAX_VALUE` | capacity for an unlimited-buffer channel |
|
||||||
|
|
||||||
|
## Common patterns
|
||||||
|
|
||||||
|
### Producer / consumer
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val ch = Channel()
|
||||||
|
val results = []
|
||||||
|
val mu = Mutex()
|
||||||
|
|
||||||
|
val consumer = launch {
|
||||||
|
var item = ch.receive()
|
||||||
|
while (item != null) {
|
||||||
|
mu.withLock { results += item }
|
||||||
|
item = ch.receive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
launch {
|
||||||
|
for (i in 1..5) ch.send("msg:$i")
|
||||||
|
ch.close()
|
||||||
|
}.await()
|
||||||
|
|
||||||
|
consumer.await()
|
||||||
|
println(results)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Fan-out: one channel, many consumers
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val ch = Channel(16)
|
||||||
|
|
||||||
|
// multiple consumers
|
||||||
|
val workers = (1..4).map { id ->
|
||||||
|
launch {
|
||||||
|
var task = ch.receive()
|
||||||
|
while (task != null) {
|
||||||
|
println("worker $id handles $task")
|
||||||
|
task = ch.receive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// single producer
|
||||||
|
for (i in 1..20) ch.send(i)
|
||||||
|
ch.close()
|
||||||
|
|
||||||
|
workers.forEach { it.await() }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Ping-pong between two coroutines
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val ping = Channel()
|
||||||
|
val pong = Channel()
|
||||||
|
|
||||||
|
launch {
|
||||||
|
repeat(3) {
|
||||||
|
val msg = ping.receive()
|
||||||
|
println("got: $msg → sending pong")
|
||||||
|
pong.send("pong")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repeat(3) {
|
||||||
|
ping.send("ping")
|
||||||
|
println(pong.receive())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Channel vs Flow
|
||||||
|
|
||||||
|
| | [Flow] | Channel |
|
||||||
|
|---|---|---|
|
||||||
|
| **temperature** | cold (lazy) | hot (eager) |
|
||||||
|
| **replay** | every collector gets a fresh run | each item is consumed once |
|
||||||
|
| **consumers** | any number; each gets all items | one receiver per item |
|
||||||
|
| **back-pressure** | built-in via rendezvous | configurable (rendezvous / buffered / unlimited) |
|
||||||
|
| **typical use** | transform pipelines, sequences | producer–consumer, fan-out |
|
||||||
|
|
||||||
|
## See also
|
||||||
|
|
||||||
|
- [parallelism] — `launch`, `Deferred`, `Mutex`, `Flow`, and the full concurrency picture
|
||||||
|
- [Flow] — cold async sequences
|
||||||
|
|
||||||
|
[Flow]: parallelism.md#flow
|
||||||
|
[parallelism]: parallelism.md
|
||||||
@@ -55,6 +55,23 @@ Here is the sample:
|
|||||||
assertEquals( (1..3).joinToString { it * 10 }, "10 20 30")
|
assertEquals( (1..3).joinToString { it * 10 }, "10 20 30")
|
||||||
>>> void
|
>>> void
|
||||||
|
|
||||||
|
## joinAll
|
||||||
|
|
||||||
|
`joinAll()` is an `Iterable<Deferred>` helper that awaits every deferred in iteration order and returns a `List`
|
||||||
|
with the collected results.
|
||||||
|
|
||||||
|
val jobs = (1..4).map { n ->
|
||||||
|
launch { n * n }
|
||||||
|
}
|
||||||
|
assertEquals([1, 4, 9, 16], jobs.joinAll())
|
||||||
|
>>> void
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
|
||||||
|
- it does not start any task by itself; it only awaits the deferreds already present in the iterable.
|
||||||
|
- awaiting happens in iteration order, so the result list keeps the same order as the input iterable.
|
||||||
|
- if any deferred fails or was cancelled, that `await()` error is propagated from `joinAll()`.
|
||||||
|
|
||||||
## `sum` and `sumOf`
|
## `sum` and `sumOf`
|
||||||
|
|
||||||
These, again, does the thing:
|
These, again, does the thing:
|
||||||
@@ -184,6 +201,7 @@ Search for the first element that satisfies the given predicate:
|
|||||||
| sortedWith(comparator) | sort using a comparator that compares elements (1) |
|
| sortedWith(comparator) | sort using a comparator that compares elements (1) |
|
||||||
| sortedBy(predicate) | sort by comparing results of the predicate function |
|
| sortedBy(predicate) | sort by comparing results of the predicate function |
|
||||||
| joinToString(s,t) | convert iterable to string, see (2) |
|
| joinToString(s,t) | convert iterable to string, see (2) |
|
||||||
|
| joinAll() | for `Iterable<Deferred>`, await all items in order and collect results to [List] |
|
||||||
| reversed() | create a list containing items from this in reverse order |
|
| reversed() | create a list containing items from this in reverse order |
|
||||||
| shuffled() | create a list of shuffled elements |
|
| shuffled() | create a list of shuffled elements |
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
# LaunchPool
|
||||||
|
|
||||||
|
`LaunchPool` is a bounded-concurrency task pool: you submit lambdas with `launch`, and the pool runs them using a fixed number of worker coroutines.
|
||||||
|
|
||||||
|
## Constructor
|
||||||
|
|
||||||
|
```
|
||||||
|
LaunchPool(maxWorkers, maxQueueSize = Channel.UNLIMITED)
|
||||||
|
```
|
||||||
|
|
||||||
|
| Parameter | Description |
|
||||||
|
|-----------|-------------|
|
||||||
|
| `maxWorkers` | Maximum number of tasks that run in parallel. |
|
||||||
|
| `maxQueueSize` | Maximum number of tasks that may wait in the queue. When the queue is full, `launch` suspends the caller until space becomes available. Defaults to `Channel.UNLIMITED` (no bound). |
|
||||||
|
|
||||||
|
## Methods
|
||||||
|
|
||||||
|
### `launch(lambda): Deferred`
|
||||||
|
|
||||||
|
Schedules `lambda` for execution and returns a `Deferred` for its result.
|
||||||
|
|
||||||
|
- Suspends if the queue is full (`maxQueueSize` reached).
|
||||||
|
- Throws `IllegalStateException` if the pool is already closed or cancelled.
|
||||||
|
- Any exception thrown by `lambda` is captured in the returned `Deferred` and **does not escape the pool**.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val pool = LaunchPool(4)
|
||||||
|
val d1 = pool.launch { computeSomething() }
|
||||||
|
val d2 = pool.launch { computeOther() }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
println(d1.await())
|
||||||
|
println(d2.await())
|
||||||
|
```
|
||||||
|
|
||||||
|
### `closeAndJoin()`
|
||||||
|
|
||||||
|
Stops accepting new tasks and suspends until all queued and running tasks complete normally. After this call, any further `launch` throws `IllegalStateException`. Idempotent — safe to call multiple times.
|
||||||
|
|
||||||
|
### `cancel()`
|
||||||
|
|
||||||
|
Immediately closes the queue and cancels all worker coroutines. Queued but unstarted tasks are discarded. After this call, `launch` throws `IllegalStateException`. Idempotent.
|
||||||
|
|
||||||
|
### `cancelAndJoin()`
|
||||||
|
|
||||||
|
Like `cancel()`, but also suspends until all worker coroutines have stopped. Useful when you need to be sure no worker code is still running before proceeding. Idempotent.
|
||||||
|
|
||||||
|
## Exception handling
|
||||||
|
|
||||||
|
Exceptions from submitted lambdas are captured per-task in the returned `Deferred`. The pool itself continues running after a task failure:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
val good = pool.launch { 42 }
|
||||||
|
val bad = pool.launch { throw IllegalArgumentException("boom") }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
|
||||||
|
assertEquals(42, good.await())
|
||||||
|
assertThrows(IllegalArgumentException) { bad.await() }
|
||||||
|
```
|
||||||
|
|
||||||
|
## Bounded queue / back-pressure
|
||||||
|
|
||||||
|
When `maxQueueSize` is set, the producer suspends if the queue fills up, providing automatic back-pressure:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
// 1 worker, queue of 2 — producer can be at most 2 tasks ahead of what's running
|
||||||
|
val pool = LaunchPool(1, 2)
|
||||||
|
val d1 = pool.launch { delay(10); "a" }
|
||||||
|
val d2 = pool.launch { delay(10); "b" }
|
||||||
|
val d3 = pool.launch { delay(10); "c" } // suspends until d1 is picked up by the worker
|
||||||
|
pool.closeAndJoin()
|
||||||
|
```
|
||||||
|
|
||||||
|
## Collecting all results
|
||||||
|
|
||||||
|
`launch` returns a `Deferred`, so you can collect results with `joinAll()`:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val pool = LaunchPool(4)
|
||||||
|
val jobs = (1..10).map { n -> pool.launch { n * n } }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
val results = jobs.joinAll()
|
||||||
|
// results == [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Concurrency limit in practice
|
||||||
|
|
||||||
|
With `maxWorkers = 2`, at most 2 tasks run simultaneously regardless of how many are queued:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val mu = Mutex()
|
||||||
|
var active = 0
|
||||||
|
var maxSeen = 0
|
||||||
|
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
(1..8).map {
|
||||||
|
pool.launch {
|
||||||
|
mu.withLock { active++; if (active > maxSeen) maxSeen = active }
|
||||||
|
delay(5)
|
||||||
|
mu.withLock { active-- }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pool.closeAndJoin()
|
||||||
|
assert(maxSeen <= 2)
|
||||||
|
```
|
||||||
|
|
||||||
|
## See also
|
||||||
|
|
||||||
|
- [parallelism.md](parallelism.md) — `launch`, `Deferred`, `Mutex`, `Channel`, and coroutine basics
|
||||||
|
- [Channel.md](Channel.md) — the underlying channel primitive used by `LaunchPool`
|
||||||
@@ -175,6 +175,8 @@ List could be sorted in place, just like [Collection] provide sorted copies, in
|
|||||||
| `[Range]` | get slice of the array (copy) | Range |
|
| `[Range]` | get slice of the array (copy) | Range |
|
||||||
| `+=` | append element(s) (2) | List or Obj |
|
| `+=` | append element(s) (2) | List or Obj |
|
||||||
| `List.fill(size, block)` | build a new list from indices `0..<size` | Int, Callable |
|
| `List.fill(size, block)` | build a new list from indices `0..<size` | Int, Callable |
|
||||||
|
| `List.fill(size,capacity,block)` | same, pre-allocating capacity slots | Int, Int, Callable |
|
||||||
|
| `ensureCapacity(count)` | pre-allocate storage for at least `count` elements without reallocation (5) | Int |
|
||||||
| `sort()` | in-place sort, natural order | void |
|
| `sort()` | in-place sort, natural order | void |
|
||||||
| `sortBy(predicate)` | in-place sort bu `predicate` call result (3) | void |
|
| `sortBy(predicate)` | in-place sort bu `predicate` call result (3) | void |
|
||||||
| `sortWith(comparator)` | in-place sort using `comarator` function (4) | void |
|
| `sortWith(comparator)` | in-place sort using `comarator` function (4) | void |
|
||||||
@@ -197,6 +199,11 @@ order, e.g. is same as `list.sortWith { a,b -> predicate(a) <=> predicate(b) }`
|
|||||||
positive if first is greater, and zero if they are equal. For example, the equvalent comparator
|
positive if first is greater, and zero if they are equal. For example, the equvalent comparator
|
||||||
for `sort()` will be `sort { a, b -> a <=> b }
|
for `sort()` will be `sort { a, b -> a <=> b }
|
||||||
|
|
||||||
|
(5)
|
||||||
|
: if the current capacity is already ≥ `count`, this is a no-op. Otherwise the internal storage
|
||||||
|
is reallocated to hold at least `count` elements. Use this before a bulk `+=` loop to avoid
|
||||||
|
repeated reallocations. `List.fill(size, capacity, block)` calls this automatically.
|
||||||
|
|
||||||
It inherits from [Iterable] too and thus all iterable methods are applicable to any list.
|
It inherits from [Iterable] too and thus all iterable methods are applicable to any list.
|
||||||
|
|
||||||
## Observable list hooks
|
## Observable list hooks
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ Sources: `lynglib/src/commonMain/kotlin/net/sergeych/lyng/Script.kt`, `lynglib/s
|
|||||||
- Async/concurrency: `launch`, `yield`, `flow`, `delay`.
|
- Async/concurrency: `launch`, `yield`, `flow`, `delay`.
|
||||||
- `Deferred.cancel()` cancels an active task.
|
- `Deferred.cancel()` cancels an active task.
|
||||||
- `Deferred.await()` throws `CancellationException` if that task was cancelled.
|
- `Deferred.await()` throws `CancellationException` if that task was cancelled.
|
||||||
|
- `Iterable<Deferred>.joinAll()` awaits every deferred in iteration order and returns a `List` of results.
|
||||||
- Math: `floor`, `ceil`, `round`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, `exp`, `ln`, `log10`, `log2`, `pow`, `sqrt`, `abs`, `clamp`.
|
- Math: `floor`, `ceil`, `round`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, `exp`, `ln`, `log10`, `log2`, `pow`, `sqrt`, `abs`, `clamp`.
|
||||||
- These helpers also accept `lyng.decimal.Decimal`.
|
- These helpers also accept `lyng.decimal.Decimal`.
|
||||||
- Exact Decimal path today: `abs`, `floor`, `ceil`, `round`, and `pow` with integral exponent.
|
- Exact Decimal path today: `abs`, `floor`, `ceil`, `round`, and `pow` with integral exponent.
|
||||||
|
|||||||
+167
-6
@@ -1,6 +1,6 @@
|
|||||||
### lyng.io.db — SQL database access for Lyng scripts
|
### lyng.io.db — SQL database access for Lyng scripts
|
||||||
|
|
||||||
This module provides the portable SQL database contract for Lyng. The first shipped provider is SQLite via `lyng.io.db.sqlite`.
|
This module provides the portable SQL database contract for Lyng. The current shipped providers are SQLite via `lyng.io.db.sqlite` and a JVM-only JDBC bridge via `lyng.io.db.jdbc`.
|
||||||
|
|
||||||
> **Note:** `lyngio` is a separate library module. It must be explicitly added as a dependency to your host application and initialized in your Lyng scopes.
|
> **Note:** `lyngio` is a separate library module. It must be explicitly added as a dependency to your host application and initialized in your Lyng scopes.
|
||||||
|
|
||||||
@@ -30,6 +30,28 @@ suspend fun bootstrapDb() {
|
|||||||
|
|
||||||
`createSqliteModule(...)` also registers the `sqlite:` scheme for generic `openDatabase(...)`.
|
`createSqliteModule(...)` also registers the `sqlite:` scheme for generic `openDatabase(...)`.
|
||||||
|
|
||||||
|
For JVM JDBC-backed access, install the JDBC provider as well:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
import net.sergeych.lyng.EvalSession
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.io.db.createDbModule
|
||||||
|
import net.sergeych.lyng.io.db.jdbc.createJdbcModule
|
||||||
|
|
||||||
|
suspend fun bootstrapJdbc() {
|
||||||
|
val session = EvalSession()
|
||||||
|
val scope: Scope = session.getScope()
|
||||||
|
createDbModule(scope)
|
||||||
|
createJdbcModule(scope)
|
||||||
|
session.eval("""
|
||||||
|
import lyng.io.db
|
||||||
|
import lyng.io.db.jdbc
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`createJdbcModule(...)` registers `jdbc:`, `h2:`, `postgres:`, and `postgresql:` for `openDatabase(...)`.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
#### Using from Lyng scripts
|
#### Using from Lyng scripts
|
||||||
@@ -66,6 +88,63 @@ val db = openDatabase(
|
|||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
JVM JDBC open with H2:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
import lyng.io.db.jdbc
|
||||||
|
|
||||||
|
val db = openH2("mem:demo;DB_CLOSE_DELAY=-1")
|
||||||
|
|
||||||
|
val names = db.transaction { tx ->
|
||||||
|
tx.execute("create table person(id bigint auto_increment primary key, name varchar(120) not null)")
|
||||||
|
tx.execute("insert into person(name) values(?)", "Ada")
|
||||||
|
tx.execute("insert into person(name) values(?)", "Linus")
|
||||||
|
tx.select("select name from person order by id").toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("Ada", names[0]["name"])
|
||||||
|
assertEquals("Linus", names[1]["name"])
|
||||||
|
```
|
||||||
|
|
||||||
|
Generic JDBC open through `openDatabase(...)`:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
import lyng.io.db
|
||||||
|
import lyng.io.db.jdbc
|
||||||
|
|
||||||
|
val db = openDatabase(
|
||||||
|
"jdbc:h2:mem:demo2;DB_CLOSE_DELAY=-1",
|
||||||
|
Map()
|
||||||
|
)
|
||||||
|
|
||||||
|
val answer = db.transaction { tx ->
|
||||||
|
tx.select("select 42 as answer").toList()[0]["answer"]
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(42, answer)
|
||||||
|
```
|
||||||
|
|
||||||
|
PostgreSQL typed open:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
import lyng.io.db.jdbc
|
||||||
|
|
||||||
|
val db = openPostgres(
|
||||||
|
"jdbc:postgresql://127.0.0.1/appdb",
|
||||||
|
"appuser",
|
||||||
|
"secret"
|
||||||
|
)
|
||||||
|
|
||||||
|
val titles = db.transaction { tx ->
|
||||||
|
tx.execute("create table if not exists task(id bigserial primary key, title text not null)")
|
||||||
|
tx.execute("insert into task(title) values(?)", "Ship JDBC provider")
|
||||||
|
tx.execute("insert into task(title) values(?)", "Test PostgreSQL path")
|
||||||
|
tx.select("select title from task order by id").toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("Ship JDBC provider", titles[0]["title"])
|
||||||
|
```
|
||||||
|
|
||||||
Nested transactions use real savepoint semantics:
|
Nested transactions use real savepoint semantics:
|
||||||
|
|
||||||
```lyng
|
```lyng
|
||||||
@@ -126,7 +205,8 @@ assertThrows(RollbackException) {
|
|||||||
- `columns` — positional `SqlColumn` metadata, available before iteration.
|
- `columns` — positional `SqlColumn` metadata, available before iteration.
|
||||||
- `size()` — result row count.
|
- `size()` — result row count.
|
||||||
- `isEmpty()` — fast emptiness check where possible.
|
- `isEmpty()` — fast emptiness check where possible.
|
||||||
- `iterator()` / `toList()` — normal row iteration.
|
- `iterator()` — normal row iteration while the transaction is active.
|
||||||
|
- `toList()` — materialize detached `SqlRow` snapshots that may be used after the transaction ends.
|
||||||
|
|
||||||
##### `SqlRow`
|
##### `SqlRow`
|
||||||
|
|
||||||
@@ -217,18 +297,98 @@ Open-time validation failures:
|
|||||||
- malformed URL or bad option shape -> `IllegalArgumentException`
|
- malformed URL or bad option shape -> `IllegalArgumentException`
|
||||||
- runtime open failure -> `DatabaseException`
|
- runtime open failure -> `DatabaseException`
|
||||||
|
|
||||||
|
#### JDBC provider
|
||||||
|
|
||||||
|
`lyng.io.db.jdbc` is currently implemented on the JVM target only. The `lyngio-jvm` artifact bundles and explicitly loads these JDBC drivers:
|
||||||
|
|
||||||
|
- SQLite
|
||||||
|
- H2
|
||||||
|
- PostgreSQL
|
||||||
|
|
||||||
|
Typed helpers:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
openJdbc(
|
||||||
|
connectionUrl: String,
|
||||||
|
user: String? = null,
|
||||||
|
password: String? = null,
|
||||||
|
driverClass: String? = null,
|
||||||
|
properties: Map<String, Object?>? = null
|
||||||
|
): Database
|
||||||
|
|
||||||
|
openH2(
|
||||||
|
connectionUrl: String,
|
||||||
|
user: String? = null,
|
||||||
|
password: String? = null,
|
||||||
|
properties: Map<String, Object?>? = null
|
||||||
|
): Database
|
||||||
|
|
||||||
|
openPostgres(
|
||||||
|
connectionUrl: String,
|
||||||
|
user: String? = null,
|
||||||
|
password: String? = null,
|
||||||
|
properties: Map<String, Object?>? = null
|
||||||
|
): Database
|
||||||
|
```
|
||||||
|
|
||||||
|
Accepted generic URL forms:
|
||||||
|
|
||||||
|
- `jdbc:h2:mem:test;DB_CLOSE_DELAY=-1`
|
||||||
|
- `h2:mem:test;DB_CLOSE_DELAY=-1`
|
||||||
|
- `jdbc:postgresql://localhost/app`
|
||||||
|
- `postgres://localhost/app`
|
||||||
|
- `postgresql://localhost/app`
|
||||||
|
|
||||||
|
Supported `openDatabase(..., extraParams)` keys for JDBC:
|
||||||
|
|
||||||
|
- `driverClass: String`
|
||||||
|
- `user: String`
|
||||||
|
- `password: String`
|
||||||
|
- `properties: Map<String, Object?>`
|
||||||
|
|
||||||
|
Behavior notes for the JDBC bridge:
|
||||||
|
|
||||||
|
- the portable `Database` / `SqlTransaction` API stays the same as for SQLite
|
||||||
|
- nested transactions use JDBC savepoints
|
||||||
|
- JDBC connection properties are built from `user`, `password`, and `properties`
|
||||||
|
- `properties` values are stringified before being passed to JDBC
|
||||||
|
- statements with row-returning clauses still must use `select(...)`, not `execute(...)`
|
||||||
|
|
||||||
|
Platform support for this provider:
|
||||||
|
|
||||||
|
- `lyng.io.db.jdbc` — JVM only
|
||||||
|
- `openH2(...)` — works out of the box with `lyngio-jvm`
|
||||||
|
- `openPostgres(...)` — driver included, but an actual PostgreSQL server is still required
|
||||||
|
|
||||||
|
PostgreSQL-specific notes:
|
||||||
|
|
||||||
|
- `openPostgres(...)` accepts either a full JDBC URL or shorthand forms such as `//localhost/app`
|
||||||
|
- local peer/trust setups may use an empty password string
|
||||||
|
- generated keys work with PostgreSQL `bigserial` / identity columns through `ExecutionResult.getGeneratedKeys()`
|
||||||
|
- for reproducible automated tests, prefer a disposable PostgreSQL instance such as Docker/Testcontainers instead of a long-lived shared server
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
#### Lifetime rules
|
#### Lifetime rules
|
||||||
|
|
||||||
Result sets and rows are valid only while their owning transaction is active.
|
`ResultSet` is valid only while its owning transaction is active.
|
||||||
|
|
||||||
|
`SqlRow` values are detached snapshots once materialized, so this pattern is valid:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val rows = db.transaction { tx ->
|
||||||
|
tx.select("select name from person order by id").toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("Ada", rows[0]["name"])
|
||||||
|
```
|
||||||
|
|
||||||
This means:
|
This means:
|
||||||
|
|
||||||
- do not keep `ResultSet` or `SqlRow` objects after the transaction block returns
|
- do not keep `ResultSet` objects after the transaction block returns
|
||||||
- copy the values you need into ordinary Lyng objects inside the transaction
|
- materialize rows with `toList()` inside the transaction when they must outlive it
|
||||||
|
|
||||||
The same lifetime rule applies to generated keys returned by `ExecutionResult.getGeneratedKeys()`.
|
The same rule applies to generated keys from `ExecutionResult.getGeneratedKeys()`: the `ResultSet` is transaction-scoped, but rows returned by `toList()` are detached.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -236,5 +396,6 @@ The same lifetime rule applies to generated keys returned by `ExecutionResult.ge
|
|||||||
|
|
||||||
- `lyng.io.db` — generic contract, available when host code installs it
|
- `lyng.io.db` — generic contract, available when host code installs it
|
||||||
- `lyng.io.db.sqlite` — implemented on JVM and Linux Native in the current release tree
|
- `lyng.io.db.sqlite` — implemented on JVM and Linux Native in the current release tree
|
||||||
|
- `lyng.io.db.jdbc` — implemented on JVM in the current release tree
|
||||||
|
|
||||||
For the broader I/O overview, see [lyngio overview](lyngio.md).
|
For the broader I/O overview, see [lyngio overview](lyngio.md).
|
||||||
+16
-12
@@ -12,7 +12,7 @@
|
|||||||
|
|
||||||
#### Included Modules
|
#### Included Modules
|
||||||
|
|
||||||
- **[lyng.io.db](lyng.io.db.md):** Portable SQL database access. Provides `Database`, `SqlTransaction`, `ResultSet`, and SQLite support through `lyng.io.db.sqlite`.
|
- **[lyng.io.db](lyng.io.db.md):** Portable SQL database access. Provides `Database`, `SqlTransaction`, `ResultSet`, SQLite support through `lyng.io.db.sqlite`, and JVM JDBC support through `lyng.io.db.jdbc`.
|
||||||
- **[lyng.io.fs](lyng.io.fs.md):** Async filesystem access. Provides the `Path` class for file/directory operations, streaming, and globbing.
|
- **[lyng.io.fs](lyng.io.fs.md):** Async filesystem access. Provides the `Path` class for file/directory operations, streaming, and globbing.
|
||||||
- **[lyng.io.process](lyng.io.process.md):** External process execution and shell commands. Provides `Process`, `RunningProcess`, and `Platform` information.
|
- **[lyng.io.process](lyng.io.process.md):** External process execution and shell commands. Provides `Process`, `RunningProcess`, and `Platform` information.
|
||||||
- **[lyng.io.console](lyng.io.console.md):** Rich console/TTY access. Provides `Console` capability detection, geometry, output, and iterable events.
|
- **[lyng.io.console](lyng.io.console.md):** Rich console/TTY access. Provides `Console` capability detection, geometry, output, and iterable events.
|
||||||
@@ -45,6 +45,7 @@ To use `lyngio` modules in your scripts, you must install them into your Lyng sc
|
|||||||
```kotlin
|
```kotlin
|
||||||
import net.sergeych.lyng.EvalSession
|
import net.sergeych.lyng.EvalSession
|
||||||
import net.sergeych.lyng.io.db.createDbModule
|
import net.sergeych.lyng.io.db.createDbModule
|
||||||
|
import net.sergeych.lyng.io.db.jdbc.createJdbcModule
|
||||||
import net.sergeych.lyng.io.db.sqlite.createSqliteModule
|
import net.sergeych.lyng.io.db.sqlite.createSqliteModule
|
||||||
import net.sergeych.lyng.io.fs.createFs
|
import net.sergeych.lyng.io.fs.createFs
|
||||||
import net.sergeych.lyng.io.process.createProcessModule
|
import net.sergeych.lyng.io.process.createProcessModule
|
||||||
@@ -65,6 +66,7 @@ suspend fun runMyScript() {
|
|||||||
|
|
||||||
// Install modules with policies
|
// Install modules with policies
|
||||||
createDbModule(scope)
|
createDbModule(scope)
|
||||||
|
createJdbcModule(scope)
|
||||||
createSqliteModule(scope)
|
createSqliteModule(scope)
|
||||||
createFs(PermitAllAccessPolicy, scope)
|
createFs(PermitAllAccessPolicy, scope)
|
||||||
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||||
@@ -76,6 +78,7 @@ suspend fun runMyScript() {
|
|||||||
// Now scripts can import them
|
// Now scripts can import them
|
||||||
session.eval("""
|
session.eval("""
|
||||||
import lyng.io.db
|
import lyng.io.db
|
||||||
|
import lyng.io.db.jdbc
|
||||||
import lyng.io.db.sqlite
|
import lyng.io.db.sqlite
|
||||||
import lyng.io.fs
|
import lyng.io.fs
|
||||||
import lyng.io.process
|
import lyng.io.process
|
||||||
@@ -84,6 +87,7 @@ suspend fun runMyScript() {
|
|||||||
import lyng.io.net
|
import lyng.io.net
|
||||||
import lyng.io.ws
|
import lyng.io.ws
|
||||||
|
|
||||||
|
println("H2 JDBC available: " + (openH2("mem:demo;DB_CLOSE_DELAY=-1") != null))
|
||||||
println("SQLite available: " + (openSqlite(":memory:") != null))
|
println("SQLite available: " + (openSqlite(":memory:") != null))
|
||||||
println("Working dir: " + Path(".").readUtf8())
|
println("Working dir: " + Path(".").readUtf8())
|
||||||
println("OS: " + Platform.details().name)
|
println("OS: " + Platform.details().name)
|
||||||
@@ -102,7 +106,7 @@ suspend fun runMyScript() {
|
|||||||
`lyngio` is built with a "Secure by Default" philosophy. Every I/O or process operation is checked against a policy.
|
`lyngio` is built with a "Secure by Default" philosophy. Every I/O or process operation is checked against a policy.
|
||||||
|
|
||||||
- **Filesystem Security:** Implement `FsAccessPolicy` to restrict access to specific paths or operations (e.g., read-only access to a sandbox directory).
|
- **Filesystem Security:** Implement `FsAccessPolicy` to restrict access to specific paths or operations (e.g., read-only access to a sandbox directory).
|
||||||
- **Database Installation:** Database access is still explicit-capability style. The host must install `lyng.io.db` and at least one provider such as `lyng.io.db.sqlite`; otherwise scripts cannot open databases.
|
- **Database Installation:** Database access is still explicit-capability style. The host must install `lyng.io.db` and at least one provider such as `lyng.io.db.sqlite` or `lyng.io.db.jdbc`; otherwise scripts cannot open databases.
|
||||||
- **Process Security:** Implement `ProcessAccessPolicy` to restrict which executables can be run or to disable shell execution entirely.
|
- **Process Security:** Implement `ProcessAccessPolicy` to restrict which executables can be run or to disable shell execution entirely.
|
||||||
- **Console Security:** Implement `ConsoleAccessPolicy` to control output writes, event reads, and raw mode switching.
|
- **Console Security:** Implement `ConsoleAccessPolicy` to control output writes, event reads, and raw mode switching.
|
||||||
- **HTTP Security:** Implement `HttpAccessPolicy` to restrict which requests scripts may send.
|
- **HTTP Security:** Implement `HttpAccessPolicy` to restrict which requests scripts may send.
|
||||||
@@ -122,16 +126,16 @@ For more details, see the specific module documentation:
|
|||||||
|
|
||||||
#### Platform Support Overview
|
#### Platform Support Overview
|
||||||
|
|
||||||
| Platform | lyng.io.db/sqlite | lyng.io.fs | lyng.io.process | lyng.io.console | lyng.io.http | lyng.io.ws | lyng.io.net |
|
| Platform | lyng.io.db/sqlite | lyng.io.db/jdbc | lyng.io.fs | lyng.io.process | lyng.io.console | lyng.io.http | lyng.io.ws | lyng.io.net |
|
||||||
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||||
| **JVM** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| **JVM** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
| **Linux Native** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
| **Linux Native** | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||||
| **Apple Native** | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ |
|
| **Apple Native** | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ⚠️ |
|
||||||
| **Windows Native** | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ |
|
| **Windows Native** | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ |
|
||||||
| **Android** | ⚠️ | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
| **Android** | ⚠️ | ❌ | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
||||||
| **JS / Node** | ❌ | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
| **JS / Node** | ❌ | ❌ | ✅ | ❌ | ⚠️ | ✅ | ✅ | ✅ |
|
||||||
| **JS / Browser** | ❌ | ✅ (in-memory) | ❌ | ⚠️ | ✅ | ✅ | ❌ |
|
| **JS / Browser** | ❌ | ❌ | ✅ (in-memory) | ❌ | ⚠️ | ✅ | ✅ | ❌ |
|
||||||
| **Wasm** | ❌ | ✅ (in-memory) | ❌ | ⚠️ | ❌ | ❌ | ❌ |
|
| **Wasm** | ❌ | ❌ | ✅ (in-memory) | ❌ | ⚠️ | ❌ | ❌ | ❌ |
|
||||||
|
|
||||||
Legend:
|
Legend:
|
||||||
- `✅` supported
|
- `✅` supported
|
||||||
|
|||||||
@@ -36,6 +36,17 @@ This example shows how to launch a coroutine with `launch` which returns [Deferr
|
|||||||
|
|
||||||
Launch has the only argument which should be a callable (lambda usually) that is run in parallel (or cooperatively in parallel), and return anything as the result.
|
Launch has the only argument which should be a callable (lambda usually) that is run in parallel (or cooperatively in parallel), and return anything as the result.
|
||||||
|
|
||||||
|
When you have an iterable of deferreds, use `joinAll()` to await all of them and collect results in input order:
|
||||||
|
|
||||||
|
val jobs = (1..4).map { n ->
|
||||||
|
launch {
|
||||||
|
delay(1)
|
||||||
|
n * 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals([10, 20, 30, 40], jobs.joinAll())
|
||||||
|
>>> void
|
||||||
|
|
||||||
If you no longer need the result, cancel the deferred. Awaiting a cancelled deferred throws `CancellationException`:
|
If you no longer need the result, cancel the deferred. Awaiting a cancelled deferred throws `CancellationException`:
|
||||||
|
|
||||||
var reached = false
|
var reached = false
|
||||||
@@ -219,6 +230,73 @@ Flows allow easy transforming of any [Iterable]. See how the standard Lyng libra
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
## Channel
|
||||||
|
|
||||||
|
A [Channel] is a **hot pipe** between coroutines: values are pushed in by a producer and pulled out by a consumer, with each value consumed exactly once.
|
||||||
|
|
||||||
|
Unlike a `Flow` (which is cold and re-runs its generator on every collection), a `Channel` is stateful — the right tool for classic _producer / consumer_ work.
|
||||||
|
|
||||||
|
val ch = Channel() // rendezvous: sender waits for receiver
|
||||||
|
|
||||||
|
val producer = launch {
|
||||||
|
for (i in 1..5) ch.send(i)
|
||||||
|
ch.close() // signal: no more values
|
||||||
|
}
|
||||||
|
|
||||||
|
var item = ch.receive() // suspends until a value is ready
|
||||||
|
while (item != null) {
|
||||||
|
println(item)
|
||||||
|
item = ch.receive()
|
||||||
|
}
|
||||||
|
// prints 1 2 3 4 5
|
||||||
|
|
||||||
|
`receive()` returns `null` when the channel is both closed and fully drained — that is the idiomatic loop termination condition.
|
||||||
|
|
||||||
|
Channels can also be buffered so the producer can run ahead:
|
||||||
|
|
||||||
|
val ch = Channel(4) // buffer up to 4 items without blocking
|
||||||
|
|
||||||
|
ch.send(10)
|
||||||
|
ch.send(20)
|
||||||
|
ch.send(30)
|
||||||
|
ch.close()
|
||||||
|
|
||||||
|
assertEquals(10, ch.receive())
|
||||||
|
assertEquals(20, ch.receive())
|
||||||
|
assertEquals(30, ch.receive())
|
||||||
|
assertEquals(null, ch.receive()) // drained
|
||||||
|
|
||||||
|
For the full API — including `tryReceive`, `Channel.UNLIMITED`, and the fan-out / ping-pong patterns — see the [Channel] reference page.
|
||||||
|
|
||||||
|
## LaunchPool
|
||||||
|
|
||||||
|
When you need **bounded concurrency** — run at most *N* tasks at the same time without spawning a new coroutine per task — use [LaunchPool]:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val pool = LaunchPool(4) // at most 4 tasks run in parallel
|
||||||
|
|
||||||
|
val jobs = (1..20).map { n ->
|
||||||
|
pool.launch { expensiveCompute(n) }
|
||||||
|
}
|
||||||
|
pool.closeAndJoin() // wait for all tasks to complete
|
||||||
|
|
||||||
|
val results = jobs.joinAll()
|
||||||
|
```
|
||||||
|
|
||||||
|
Exceptions thrown inside a submitted lambda are captured in the returned `Deferred` and do not crash the pool, so other tasks continue running normally.
|
||||||
|
|
||||||
|
See [LaunchPool] for the full API including bounded queues and cancellation.
|
||||||
|
|
||||||
|
[LaunchPool]: LaunchPool.md
|
||||||
|
|
||||||
|
| | Flow | Channel |
|
||||||
|
|---|---|---|
|
||||||
|
| **temperature** | cold (lazy) | hot (eager) |
|
||||||
|
| **replay** | every collector gets a fresh run | each item consumed once |
|
||||||
|
| **consumers** | any number, each gets all items | one receiver per item |
|
||||||
|
| **typical use** | transform pipelines, sequences | producer–consumer, fan-out |
|
||||||
|
|
||||||
|
[Channel]: Channel.md
|
||||||
|
|
||||||
[Iterable]: Iterable.md
|
[Iterable]: Iterable.md
|
||||||
|
|
||||||
|
|||||||
+11
-8
@@ -1,26 +1,29 @@
|
|||||||
# What's New in Lyng
|
# What's New in Lyng
|
||||||
|
|
||||||
This document highlights the current Lyng release, **1.5.4**, and the broader additions from the 1.5 cycle.
|
This document highlights the current Lyng release, **1.5.5**, and the broader additions from the 1.5 cycle.
|
||||||
It is intentionally user-facing: new language features, new modules, new tools, and the practical things you can build with them.
|
It is intentionally user-facing: new language features, new modules, new tools, and the practical things you can build with them.
|
||||||
For a programmer-focused migration summary across 1.5.x, see `docs/whats_new_1_5.md`.
|
For a programmer-focused migration summary across 1.5.x, see `docs/whats_new_1_5.md`.
|
||||||
|
|
||||||
## Release 1.5.4 Highlights
|
## Release 1.5.5 Highlights
|
||||||
|
|
||||||
- `1.5.4` is the stabilization release for the 1.5 feature set.
|
- `1.5.5` extends the 1.5 line with practical database APIs, first-class calendar dates, and better coroutine building blocks.
|
||||||
- The 1.5 line now brings together richer ranges and loops, interpolation, math modules, immutable and observable collections, richer `lyngio`, and much better CLI/IDE support.
|
- The 1.5 line now brings together richer ranges and loops, interpolation, math modules, immutable and observable collections, richer `lyngio`, and much better CLI/IDE support.
|
||||||
- `1.5.4` specifically fixes user-visible issues around decimal arithmetic, mixed numeric flows, list behavior, and observable list hooks.
|
- `1.5.5` adds `Channel`, `LaunchPool`, and `joinAll()` so coroutine-heavy scripts can coordinate work more directly.
|
||||||
- `1.5.4` also fixes extension-member registration for named singleton `object` declarations, so `fun X.foo()` and `val X.bar` now work as expected.
|
- `1.5.5` adds `Date`, the portable `lyng.io.db` layer, SQLite/JDBC providers, and a compatibility `lyng.legacy_digest` module.
|
||||||
- `1.5.4` also lets named singleton `object` declarations use scoped indexer extensions with bracket syntax, so patterns like `Storage["name"]` can be implemented with `override fun Storage.getAt(...)` / `putAt(...)`.
|
- `1.5.5` also continues runtime/compiler hardening with better import dispatch, faster exact lambda calls, and correct `val +=`/`-=` behavior for mutating types versus real reassignment.
|
||||||
- The docs, homepage samples, and release metadata now point at the current stable version.
|
- The docs, homepage samples, and release metadata now point at the current stable version.
|
||||||
|
|
||||||
## User Highlights Across 1.5.x
|
## User Highlights Across 1.5.x
|
||||||
|
|
||||||
- Descending ranges and loops with `downTo` / `downUntil`
|
- Descending ranges and loops with `downTo` / `downUntil`
|
||||||
- String interpolation with `$name` and `${expr}`
|
- String interpolation with `$name` and `${expr}`
|
||||||
|
- Backtick string literals for raw-ish string text
|
||||||
- Decimal arithmetic, matrices/vectors, and complex numbers
|
- Decimal arithmetic, matrices/vectors, and complex numbers
|
||||||
- Calendar `Date` support in `lyng.time`
|
- Calendar `Date` support in `lyng.time`
|
||||||
|
- `Channel`, `LaunchPool`, and `joinAll()` for coroutine workflows
|
||||||
- Immutable collections and opt-in `ObservableList`
|
- Immutable collections and opt-in `ObservableList`
|
||||||
- Rich `lyngio` modules for SQLite databases, console, HTTP, WebSocket, TCP, and UDP
|
- Rich `lyngio` modules for SQLite/JDBC databases, console, HTTP, WebSocket, TCP, and UDP
|
||||||
|
- Legacy SHA-1 compatibility helpers in `lyng.legacy_digest`
|
||||||
- CLI improvements including the built-in formatter `lyng fmt`
|
- CLI improvements including the built-in formatter `lyng fmt`
|
||||||
- Better IDE support and stronger docs around the released feature set
|
- Better IDE support and stronger docs around the released feature set
|
||||||
|
|
||||||
@@ -324,7 +327,7 @@ Singleton objects are declared using the `object` keyword. They provide a conven
|
|||||||
|
|
||||||
```lyng
|
```lyng
|
||||||
object Config {
|
object Config {
|
||||||
val version = "1.5.4"
|
val version = "1.5.5"
|
||||||
fun show() = println("Config version: " + version)
|
fun show() = println("Config version: " + version)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Whitespace-only changes.
@@ -0,0 +1,15 @@
|
|||||||
|
import lyng.time
|
||||||
|
|
||||||
|
val n = 700_000
|
||||||
|
|
||||||
|
fun tm<T>(block: ()->T): T {
|
||||||
|
val t = Instant()
|
||||||
|
block().also {
|
||||||
|
println("tm: ${Instant() - t}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val x = tm { List.fill(n) { it * 10 + 1 } }
|
||||||
|
val y = tm { List.fill(n, n + 10) { it * 10 + 1 } }
|
||||||
|
tm { x.add(-1) }
|
||||||
|
tm { y.add(-2) }
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import lyng.io.db
|
||||||
|
import lyng.io.db.jdbc
|
||||||
|
|
||||||
|
println("H2 JDBC demo: typed open, generic open, generated keys")
|
||||||
|
|
||||||
|
val db = openH2("mem:lyng_h2_demo;DB_CLOSE_DELAY=-1")
|
||||||
|
|
||||||
|
db.transaction { tx ->
|
||||||
|
tx.execute("create table if not exists person(id bigint auto_increment primary key, name varchar(120) not null, active boolean not null)")
|
||||||
|
tx.execute("delete from person")
|
||||||
|
|
||||||
|
val firstInsert = tx.execute(
|
||||||
|
"insert into person(name, active) values(?, ?)",
|
||||||
|
"Ada",
|
||||||
|
true
|
||||||
|
)
|
||||||
|
val firstId = firstInsert.getGeneratedKeys().toList()[0][0]
|
||||||
|
assertEquals(1, firstId)
|
||||||
|
|
||||||
|
tx.execute(
|
||||||
|
"insert into person(name, active) values(?, ?)",
|
||||||
|
"Linus",
|
||||||
|
false
|
||||||
|
)
|
||||||
|
|
||||||
|
val rows = tx.select("select id, name, active from person order by id").toList()
|
||||||
|
assertEquals(2, rows.size)
|
||||||
|
println("#" + rows[0]["id"] + " " + rows[0]["name"] + " active=" + rows[0]["active"])
|
||||||
|
println("#" + rows[1]["id"] + " " + rows[1]["name"] + " active=" + rows[1]["active"])
|
||||||
|
}
|
||||||
|
|
||||||
|
val genericDb = openDatabase(
|
||||||
|
"jdbc:h2:mem:lyng_h2_generic;DB_CLOSE_DELAY=-1",
|
||||||
|
Map()
|
||||||
|
)
|
||||||
|
|
||||||
|
val answer = genericDb.transaction { tx ->
|
||||||
|
tx.select("select 42 as answer").toList()[0]["answer"]
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(42, answer)
|
||||||
|
println("Generic JDBC openDatabase(...) also works: answer=$answer")
|
||||||
|
println("OK")
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import lyng.io.db.jdbc
|
||||||
|
|
||||||
|
/*
|
||||||
|
PostgreSQL JDBC demo.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
lyng examples/postgres_basic.lyng [jdbc-url] [user] [password]
|
||||||
|
|
||||||
|
Typical local URL:
|
||||||
|
jdbc:postgresql://127.0.0.1/postgres
|
||||||
|
*/
|
||||||
|
|
||||||
|
fun cliArgs(): List<String> {
|
||||||
|
val result: List<String> = []
|
||||||
|
for (raw in ARGV as List) {
|
||||||
|
result.add(raw as String)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
val argv = cliArgs()
|
||||||
|
val URL = if (argv.size > 0) argv[0] else "jdbc:postgresql://127.0.0.1/postgres"
|
||||||
|
val USER = if (argv.size > 1) argv[1] else ""
|
||||||
|
val PASSWORD = if (argv.size > 2) argv[2] else ""
|
||||||
|
|
||||||
|
println("PostgreSQL JDBC demo: typed open, generated keys, nested transaction")
|
||||||
|
|
||||||
|
val db = openPostgres(URL, USER, PASSWORD)
|
||||||
|
|
||||||
|
db.transaction { tx ->
|
||||||
|
tx.execute("create table if not exists lyng_pg_demo(id bigserial primary key, title text not null, done boolean not null)")
|
||||||
|
tx.execute("delete from lyng_pg_demo")
|
||||||
|
|
||||||
|
val firstInsert = tx.execute(
|
||||||
|
"insert into lyng_pg_demo(title, done) values(?, ?)",
|
||||||
|
"Verify PostgreSQL JDBC support",
|
||||||
|
false
|
||||||
|
)
|
||||||
|
val firstId = firstInsert.getGeneratedKeys().toList()[0][0]
|
||||||
|
println("First generated id=" + firstId)
|
||||||
|
|
||||||
|
tx.execute(
|
||||||
|
"insert into lyng_pg_demo(title, done) values(?, ?)",
|
||||||
|
"Review documentation",
|
||||||
|
true
|
||||||
|
)
|
||||||
|
|
||||||
|
try {
|
||||||
|
tx.transaction { inner ->
|
||||||
|
inner.execute(
|
||||||
|
"insert into lyng_pg_demo(title, done) values(?, ?)",
|
||||||
|
"This row is rolled back",
|
||||||
|
false
|
||||||
|
)
|
||||||
|
throw IllegalStateException("rollback nested")
|
||||||
|
}
|
||||||
|
} catch (_: IllegalStateException) {
|
||||||
|
println("Nested transaction rolled back as expected")
|
||||||
|
}
|
||||||
|
|
||||||
|
val rows = tx.select("select id, title, done from lyng_pg_demo order by id").toList()
|
||||||
|
for (row in rows) {
|
||||||
|
println("#" + row["id"] + " " + row["title"] + " done=" + row["done"])
|
||||||
|
}
|
||||||
|
|
||||||
|
val count = tx.select("select count(*) as count from lyng_pg_demo").toList()[0]["count"]
|
||||||
|
assertEquals(2, count)
|
||||||
|
println("Visible rows after nested rollback: " + count)
|
||||||
|
}
|
||||||
|
|
||||||
|
println("OK")
|
||||||
@@ -65,7 +65,7 @@ db.transaction { tx ->
|
|||||||
println(" #" + row["ID"] + " " + row["title"] + " done=" + row["done"] + " due=" + row["due_date"])
|
println(" #" + row["ID"] + " " + row["title"] + " done=" + row["done"] + " due=" + row["due_date"])
|
||||||
}
|
}
|
||||||
|
|
||||||
// If values need to survive after the transaction closes, copy them now.
|
// toList() materializes detached rows that stay usable after transaction close.
|
||||||
val snapshot = tx.select("select title, due_date from task order by id").toList()
|
val snapshot = tx.select("select title, due_date from task order by id").toList()
|
||||||
assertEquals("Write a SQLite example", snapshot[0]["title"])
|
assertEquals("Write a SQLite example", snapshot[0]["title"])
|
||||||
assertEquals(Date(2026, 4, 16), snapshot[1]["due_date"])
|
assertEquals(Date(2026, 4, 16), snapshot[1]["due_date"])
|
||||||
|
|||||||
@@ -16,6 +16,10 @@ compiler = "3.2.0-alpha11"
|
|||||||
ktor = "3.3.1"
|
ktor = "3.3.1"
|
||||||
slf4j = "2.0.17"
|
slf4j = "2.0.17"
|
||||||
sqlite-jdbc = "3.50.3.0"
|
sqlite-jdbc = "3.50.3.0"
|
||||||
|
h2 = "2.4.240"
|
||||||
|
postgresql = "42.7.8"
|
||||||
|
testcontainers = "1.20.6"
|
||||||
|
hikaricp = "6.2.1"
|
||||||
|
|
||||||
[libraries]
|
[libraries]
|
||||||
clikt = { module = "com.github.ajalt.clikt:clikt", version.ref = "clikt" }
|
clikt = { module = "com.github.ajalt.clikt:clikt", version.ref = "clikt" }
|
||||||
@@ -45,6 +49,11 @@ ktor-client-websockets = { module = "io.ktor:ktor-client-websockets", version.re
|
|||||||
ktor-network = { module = "io.ktor:ktor-network", version.ref = "ktor" }
|
ktor-network = { module = "io.ktor:ktor-network", version.ref = "ktor" }
|
||||||
slf4j-nop = { module = "org.slf4j:slf4j-nop", version.ref = "slf4j" }
|
slf4j-nop = { module = "org.slf4j:slf4j-nop", version.ref = "slf4j" }
|
||||||
sqlite-jdbc = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite-jdbc" }
|
sqlite-jdbc = { module = "org.xerial:sqlite-jdbc", version.ref = "sqlite-jdbc" }
|
||||||
|
h2 = { module = "com.h2database:h2", version.ref = "h2" }
|
||||||
|
postgresql = { module = "org.postgresql:postgresql", version.ref = "postgresql" }
|
||||||
|
testcontainers = { module = "org.testcontainers:testcontainers", version.ref = "testcontainers" }
|
||||||
|
testcontainers-postgresql = { module = "org.testcontainers:postgresql", version.ref = "testcontainers" }
|
||||||
|
hikaricp = { module = "com.zaxxer:HikariCP", version.ref = "hikaricp" }
|
||||||
|
|
||||||
[plugins]
|
[plugins]
|
||||||
androidLibrary = { id = "com.android.library", version.ref = "agp" }
|
androidLibrary = { id = "com.android.library", version.ref = "agp" }
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
[vps]
|
||||||
|
94.130.36.94 ansible_user=sergeych
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
---
|
||||||
|
- name: Setup lynglang.com static site on VPS
|
||||||
|
hosts: vps
|
||||||
|
become: yes
|
||||||
|
vars:
|
||||||
|
domain: lynglang.com
|
||||||
|
web_root: /var/www/lynglang
|
||||||
|
deploy_user: sergeych
|
||||||
|
certbot_email: real.sergeych@gmail.com
|
||||||
|
|
||||||
|
tasks:
|
||||||
|
# Debian 10 buster is EOL; security/backports repos moved to archive.debian.org
|
||||||
|
- name: Fix sources.list for Debian buster EOL
|
||||||
|
copy:
|
||||||
|
dest: /etc/apt/sources.list
|
||||||
|
content: |
|
||||||
|
deb http://archive.debian.org/debian/ buster main contrib non-free
|
||||||
|
deb http://archive.debian.org/debian-security/ buster/updates main contrib non-free
|
||||||
|
deb http://archive.debian.org/debian/ buster-backports main contrib non-free
|
||||||
|
|
||||||
|
- name: Remove stale third-party sources (broken for buster EOL)
|
||||||
|
file:
|
||||||
|
path: "/etc/apt/sources.list.d/{{ item }}"
|
||||||
|
state: absent
|
||||||
|
loop:
|
||||||
|
- cassandra.list
|
||||||
|
- icinga.list
|
||||||
|
- postgres.list
|
||||||
|
- salt-stack.list
|
||||||
|
- yarn.list
|
||||||
|
|
||||||
|
- name: Install nginx, certbot, and python3-certbot-nginx
|
||||||
|
apt:
|
||||||
|
name:
|
||||||
|
- nginx
|
||||||
|
- certbot
|
||||||
|
- python3-certbot-nginx
|
||||||
|
state: present
|
||||||
|
update_cache: yes
|
||||||
|
|
||||||
|
- name: Create web root directory
|
||||||
|
file:
|
||||||
|
path: "{{ web_root }}/release/dist"
|
||||||
|
state: directory
|
||||||
|
owner: "{{ deploy_user }}"
|
||||||
|
group: www-data
|
||||||
|
mode: "0755"
|
||||||
|
recurse: yes
|
||||||
|
|
||||||
|
- name: Create distributables directory
|
||||||
|
file:
|
||||||
|
path: "{{ web_root }}/release/dist/distributables"
|
||||||
|
state: directory
|
||||||
|
owner: "{{ deploy_user }}"
|
||||||
|
group: www-data
|
||||||
|
mode: "0755"
|
||||||
|
|
||||||
|
- name: Deploy nginx site config (HTTP, pre-certbot)
|
||||||
|
template:
|
||||||
|
src: templates/nginx_lynglang.conf.j2
|
||||||
|
dest: /etc/nginx/sites-available/{{ domain }}
|
||||||
|
notify: reload nginx
|
||||||
|
|
||||||
|
- name: Enable nginx site
|
||||||
|
file:
|
||||||
|
src: /etc/nginx/sites-available/{{ domain }}
|
||||||
|
dest: /etc/nginx/sites-enabled/{{ domain }}
|
||||||
|
state: link
|
||||||
|
notify: reload nginx
|
||||||
|
|
||||||
|
- name: Disable default nginx site
|
||||||
|
file:
|
||||||
|
path: /etc/nginx/sites-enabled/default
|
||||||
|
state: absent
|
||||||
|
notify: reload nginx
|
||||||
|
|
||||||
|
- name: Ensure nginx is started
|
||||||
|
service:
|
||||||
|
name: nginx
|
||||||
|
state: started
|
||||||
|
enabled: yes
|
||||||
|
|
||||||
|
- name: Reload nginx before certbot
|
||||||
|
meta: flush_handlers
|
||||||
|
|
||||||
|
- name: Obtain SSL certificate via certbot (--nginx plugin)
|
||||||
|
command: >
|
||||||
|
certbot --nginx
|
||||||
|
-d {{ domain }} -d www.{{ domain }}
|
||||||
|
--non-interactive --agree-tos
|
||||||
|
--email {{ certbot_email }}
|
||||||
|
--redirect
|
||||||
|
args:
|
||||||
|
creates: /etc/letsencrypt/live/{{ domain }}/fullchain.pem
|
||||||
|
|
||||||
|
handlers:
|
||||||
|
- name: reload nginx
|
||||||
|
service:
|
||||||
|
name: nginx
|
||||||
|
state: reloaded
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name {{ domain }} www.{{ domain }};
|
||||||
|
|
||||||
|
root {{ web_root }}/release/dist;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
# SPA fallback
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ /index.html;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Distributables served directly
|
||||||
|
location /distributables/ {
|
||||||
|
try_files $uri =404;
|
||||||
|
autoindex on;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Long-lived cache for hashed assets
|
||||||
|
location ~* \.(js|css|woff2?|ttf|eot|svg|png|jpg|ico)$ {
|
||||||
|
expires 1y;
|
||||||
|
add_header Cache-Control "public, immutable";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -151,8 +151,13 @@ kotlin {
|
|||||||
|
|
||||||
tasks.named<KotlinNativeTest>("linuxX64Test") {
|
tasks.named<KotlinNativeTest>("linuxX64Test") {
|
||||||
dependsOn(tasks.named("linkDebugExecutableLinuxX64"))
|
dependsOn(tasks.named("linkDebugExecutableLinuxX64"))
|
||||||
|
dependsOn(tasks.named("linkReleaseExecutableLinuxX64"))
|
||||||
environment(
|
environment(
|
||||||
"LYNG_CLI_NATIVE_BIN",
|
"LYNG_CLI_NATIVE_BIN",
|
||||||
layout.buildDirectory.file("bin/linuxX64/debugExecutable/lyng.kexe").get().asFile.absolutePath
|
layout.buildDirectory.file("bin/linuxX64/debugExecutable/lyng.kexe").get().asFile.absolutePath
|
||||||
)
|
)
|
||||||
|
environment(
|
||||||
|
"LYNG_CLI_NATIVE_RELEASE_BIN",
|
||||||
|
layout.buildDirectory.file("bin/linuxX64/releaseExecutable/lyng.kexe").get().asFile.absolutePath
|
||||||
|
)
|
||||||
}
|
}
|
||||||
@@ -41,6 +41,7 @@ import net.sergeych.lyng.Source
|
|||||||
import net.sergeych.lyng.asFacade
|
import net.sergeych.lyng.asFacade
|
||||||
import net.sergeych.lyng.io.console.createConsoleModule
|
import net.sergeych.lyng.io.console.createConsoleModule
|
||||||
import net.sergeych.lyng.io.db.createDbModule
|
import net.sergeych.lyng.io.db.createDbModule
|
||||||
|
import net.sergeych.lyng.io.db.jdbc.createJdbcModule
|
||||||
import net.sergeych.lyng.io.db.sqlite.createSqliteModule
|
import net.sergeych.lyng.io.db.sqlite.createSqliteModule
|
||||||
import net.sergeych.lyng.io.fs.createFs
|
import net.sergeych.lyng.io.fs.createFs
|
||||||
import net.sergeych.lyng.io.http.createHttpModule
|
import net.sergeych.lyng.io.http.createHttpModule
|
||||||
@@ -118,8 +119,9 @@ internal class CliExecutionRuntime(
|
|||||||
facade.call(handler)
|
facade.call(handler)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
session.cancelAndJoin()
|
session.cancel()
|
||||||
shutdownSystemNetEngine()
|
shutdownSystemNetEngine()
|
||||||
|
session.join()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun shutdownBlocking() {
|
fun shutdownBlocking() {
|
||||||
@@ -140,6 +142,7 @@ private val baseCliImportManagerDefer = globalDefer {
|
|||||||
private fun ImportManager.invalidateCliModuleCaches() {
|
private fun ImportManager.invalidateCliModuleCaches() {
|
||||||
invalidatePackageCache("lyng.io.fs")
|
invalidatePackageCache("lyng.io.fs")
|
||||||
invalidatePackageCache("lyng.io.console")
|
invalidatePackageCache("lyng.io.console")
|
||||||
|
invalidatePackageCache("lyng.io.db.jdbc")
|
||||||
invalidatePackageCache("lyng.io.db.sqlite")
|
invalidatePackageCache("lyng.io.db.sqlite")
|
||||||
invalidatePackageCache("lyng.io.http")
|
invalidatePackageCache("lyng.io.http")
|
||||||
invalidatePackageCache("lyng.io.ws")
|
invalidatePackageCache("lyng.io.ws")
|
||||||
@@ -229,6 +232,7 @@ private fun installCliModules(manager: ImportManager) {
|
|||||||
createFs(PermitAllAccessPolicy, manager)
|
createFs(PermitAllAccessPolicy, manager)
|
||||||
createConsoleModule(PermitAllConsoleAccessPolicy, manager)
|
createConsoleModule(PermitAllConsoleAccessPolicy, manager)
|
||||||
createDbModule(manager)
|
createDbModule(manager)
|
||||||
|
createJdbcModule(manager)
|
||||||
createSqliteModule(manager)
|
createSqliteModule(manager)
|
||||||
createHttpModule(PermitAllHttpAccessPolicy, manager)
|
createHttpModule(PermitAllHttpAccessPolicy, manager)
|
||||||
createWsModule(PermitAllWsAccessPolicy, manager)
|
createWsModule(PermitAllWsAccessPolicy, manager)
|
||||||
|
|||||||
@@ -0,0 +1,132 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng_cli
|
||||||
|
|
||||||
|
import kotlinx.cinterop.*
|
||||||
|
import okio.FileSystem
|
||||||
|
import okio.Path
|
||||||
|
import okio.Path.Companion.toPath
|
||||||
|
import platform.posix.O_CREAT
|
||||||
|
import platform.posix.O_TRUNC
|
||||||
|
import platform.posix.O_WRONLY
|
||||||
|
import platform.posix.SIGKILL
|
||||||
|
import platform.posix.SIGSEGV
|
||||||
|
import platform.posix._exit
|
||||||
|
import platform.posix.close
|
||||||
|
import platform.posix.dup2
|
||||||
|
import platform.posix.execvp
|
||||||
|
import platform.posix.fork
|
||||||
|
import platform.posix.getenv
|
||||||
|
import platform.posix.getpid
|
||||||
|
import platform.posix.kill
|
||||||
|
import platform.posix.open
|
||||||
|
import platform.posix.usleep
|
||||||
|
import platform.posix.waitpid
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertFalse
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
class CliWebSocketNativeRegressionTest {
|
||||||
|
@Test
|
||||||
|
fun releaseCliDoesNotSegfaultOnConcurrentWebSocketClients() {
|
||||||
|
val executable = getenv("LYNG_CLI_NATIVE_RELEASE_BIN")?.toKString()
|
||||||
|
?: error("LYNG_CLI_NATIVE_RELEASE_BIN is not set")
|
||||||
|
val fs = FileSystem.SYSTEM
|
||||||
|
val repoRoot = ascend(executable.toPath(), 6)
|
||||||
|
val scriptPath = repoRoot / "bugs" / "ws-segfault.lyng"
|
||||||
|
check(fs.exists(scriptPath)) { "bug repro script not found at $scriptPath" }
|
||||||
|
|
||||||
|
val tempDir = "/tmp/lyng_ws_native_${getpid()}_${kotlin.random.Random.nextInt()}".toPath()
|
||||||
|
val stdoutPath = tempDir / "stdout.txt"
|
||||||
|
val stderrPath = tempDir / "stderr.txt"
|
||||||
|
|
||||||
|
fs.createDirectories(tempDir)
|
||||||
|
try {
|
||||||
|
val pid = launchCli(executable, scriptPath, stdoutPath, stderrPath)
|
||||||
|
usleep(5_000_000u)
|
||||||
|
|
||||||
|
if (kill(pid, 0) == 0) {
|
||||||
|
kill(pid, SIGKILL)
|
||||||
|
}
|
||||||
|
|
||||||
|
val status = waitForPid(pid)
|
||||||
|
val termSignal = status and 0x7f
|
||||||
|
val stdout = readUtf8IfExists(fs, stdoutPath)
|
||||||
|
val stderr = readUtf8IfExists(fs, stderrPath)
|
||||||
|
val allOutput = "$stdout\n$stderr"
|
||||||
|
|
||||||
|
assertFalse(termSignal == SIGSEGV, "native CLI crashed with SIGSEGV. Output:\n$allOutput")
|
||||||
|
assertTrue(
|
||||||
|
stdout.lineSequence().count { it == "test send to ws://127.0.0.1:9998... OK" } == 2,
|
||||||
|
"expected both websocket clients to finish. Output:\n$allOutput"
|
||||||
|
)
|
||||||
|
assertFalse(allOutput.contains("Segmentation fault"), "process output reported a segmentation fault:\n$allOutput")
|
||||||
|
} finally {
|
||||||
|
fs.deleteRecursively(tempDir, mustExist = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ascend(path: Path, levels: Int): Path {
|
||||||
|
var current = path
|
||||||
|
repeat(levels) {
|
||||||
|
current = current.parent ?: error("cannot ascend $levels levels from $path")
|
||||||
|
}
|
||||||
|
return current
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readUtf8IfExists(fs: FileSystem, path: Path): String {
|
||||||
|
return if (fs.exists(path)) fs.read(path) { readUtf8() } else ""
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun waitForPid(pid: Int): Int = memScoped {
|
||||||
|
val status = alloc<IntVar>()
|
||||||
|
val waited = waitpid(pid, status.ptr, 0)
|
||||||
|
check(waited == pid) { "waitpid failed for $pid" }
|
||||||
|
status.value
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchCli(
|
||||||
|
executable: String,
|
||||||
|
scriptPath: Path,
|
||||||
|
stdoutPath: Path,
|
||||||
|
stderrPath: Path,
|
||||||
|
): Int = memScoped {
|
||||||
|
val pid = fork()
|
||||||
|
check(pid >= 0) { "fork failed" }
|
||||||
|
if (pid == 0) {
|
||||||
|
val stdoutFd = open(stdoutPath.toString(), O_WRONLY or O_CREAT or O_TRUNC, 0x1A4)
|
||||||
|
val stderrFd = open(stderrPath.toString(), O_WRONLY or O_CREAT or O_TRUNC, 0x1A4)
|
||||||
|
if (stdoutFd < 0 || stderrFd < 0) {
|
||||||
|
_exit(2)
|
||||||
|
}
|
||||||
|
dup2(stdoutFd, 1)
|
||||||
|
dup2(stderrFd, 2)
|
||||||
|
close(stdoutFd)
|
||||||
|
close(stderrFd)
|
||||||
|
|
||||||
|
val argv = allocArray<CPointerVar<ByteVar>>(3)
|
||||||
|
argv[0] = executable.cstr.ptr
|
||||||
|
argv[1] = scriptPath.toString().cstr.ptr
|
||||||
|
argv[2] = null
|
||||||
|
execvp(executable, argv)
|
||||||
|
_exit(127)
|
||||||
|
}
|
||||||
|
pid
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -19,7 +19,6 @@
|
|||||||
* LyngIO: Compose Multiplatform library module depending on :lynglib
|
* LyngIO: Compose Multiplatform library module depending on :lynglib
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import org.gradle.api.Project
|
|
||||||
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
@@ -181,6 +180,12 @@ kotlin {
|
|||||||
implementation(libs.kotlinx.coroutines.test)
|
implementation(libs.kotlinx.coroutines.test)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val jvmTest by getting {
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.testcontainers)
|
||||||
|
implementation(libs.testcontainers.postgresql)
|
||||||
|
}
|
||||||
|
}
|
||||||
val linuxTest by creating {
|
val linuxTest by creating {
|
||||||
dependsOn(commonTest)
|
dependsOn(commonTest)
|
||||||
}
|
}
|
||||||
@@ -217,6 +222,9 @@ kotlin {
|
|||||||
implementation(libs.ktor.client.cio)
|
implementation(libs.ktor.client.cio)
|
||||||
implementation(libs.ktor.network)
|
implementation(libs.ktor.network)
|
||||||
implementation(libs.sqlite.jdbc)
|
implementation(libs.sqlite.jdbc)
|
||||||
|
implementation(libs.h2)
|
||||||
|
implementation(libs.postgresql)
|
||||||
|
implementation(libs.hikaricp)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// // For Wasm we use in-memory VFS for now
|
// // For Wasm we use in-memory VFS for now
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package net.sergeych.lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
|
import net.sergeych.lyng.obj.ObjException
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
|
||||||
|
internal actual suspend fun openJdbcBackend(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
options: JdbcOpenOptions,
|
||||||
|
): SqlDatabaseBackend {
|
||||||
|
scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
core.databaseException,
|
||||||
|
scope.requireScope(),
|
||||||
|
ObjString("lyng.io.db.jdbc is available only on the JVM target")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -18,15 +18,17 @@
|
|||||||
package net.sergeych.lyng.io.db.sqlite
|
package net.sergeych.lyng.io.db.sqlite
|
||||||
|
|
||||||
import net.sergeych.lyng.ScopeFacade
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
import net.sergeych.lyng.requireScope
|
import net.sergeych.lyng.requireScope
|
||||||
import net.sergeych.lyng.obj.ObjException
|
import net.sergeych.lyng.obj.ObjException
|
||||||
import net.sergeych.lyng.obj.ObjString
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
|
||||||
internal actual suspend fun openSqliteBackend(
|
internal actual suspend fun openSqliteBackend(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
options: SqliteOpenOptions,
|
options: SqliteOpenOptions,
|
||||||
): SqliteDatabaseBackend {
|
): SqlDatabaseBackend {
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjException(
|
ObjException(
|
||||||
core.databaseException,
|
core.databaseException,
|
||||||
|
|||||||
@@ -0,0 +1,399 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng.io.db
|
||||||
|
|
||||||
|
import net.sergeych.lyng.Arguments
|
||||||
|
import net.sergeych.lyng.ModuleScope
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjBool
|
||||||
|
import net.sergeych.lyng.obj.ObjClass
|
||||||
|
import net.sergeych.lyng.obj.ObjEnumClass
|
||||||
|
import net.sergeych.lyng.obj.ObjEnumEntry
|
||||||
|
import net.sergeych.lyng.obj.ObjException
|
||||||
|
import net.sergeych.lyng.obj.ObjImmutableList
|
||||||
|
import net.sergeych.lyng.obj.ObjInt
|
||||||
|
import net.sergeych.lyng.obj.ObjNull
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.obj.thisAs
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
import kotlin.collections.List
|
||||||
|
import kotlin.collections.Map
|
||||||
|
import kotlin.collections.MutableList
|
||||||
|
import kotlin.collections.associateWith
|
||||||
|
import kotlin.collections.drop
|
||||||
|
import kotlin.collections.first
|
||||||
|
import kotlin.collections.forEachIndexed
|
||||||
|
import kotlin.collections.getOrNull
|
||||||
|
import kotlin.collections.getOrPut
|
||||||
|
import kotlin.collections.indices
|
||||||
|
import kotlin.collections.linkedMapOf
|
||||||
|
import kotlin.collections.listOf
|
||||||
|
import kotlin.collections.map
|
||||||
|
import kotlin.collections.mutableListOf
|
||||||
|
import kotlin.text.lowercase
|
||||||
|
|
||||||
|
internal data class SqlColumnMeta(
|
||||||
|
val name: String,
|
||||||
|
val sqlType: ObjEnumEntry,
|
||||||
|
val nullable: Boolean,
|
||||||
|
val nativeType: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal data class SqlResultSetData(
|
||||||
|
val columns: List<SqlColumnMeta>,
|
||||||
|
val rows: List<List<Obj>>,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal data class SqlExecutionResultData(
|
||||||
|
val affectedRowsCount: Int,
|
||||||
|
val generatedKeys: SqlResultSetData,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal interface SqlDatabaseBackend {
|
||||||
|
suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T
|
||||||
|
fun close() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal interface SqlTransactionBackend {
|
||||||
|
suspend fun select(scope: ScopeFacade, clause: String, params: List<Obj>): SqlResultSetData
|
||||||
|
suspend fun execute(scope: ScopeFacade, clause: String, params: List<Obj>): SqlExecutionResultData
|
||||||
|
suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlCoreModule private constructor(
|
||||||
|
val module: ModuleScope,
|
||||||
|
val databaseClass: ObjClass,
|
||||||
|
val transactionClass: ObjClass,
|
||||||
|
val resultSetClass: ObjClass,
|
||||||
|
val rowClass: ObjClass,
|
||||||
|
val columnClass: ObjClass,
|
||||||
|
val executionResultClass: ObjClass,
|
||||||
|
val databaseException: ObjException.Companion.ExceptionClass,
|
||||||
|
val sqlExecutionException: ObjException.Companion.ExceptionClass,
|
||||||
|
val sqlConstraintException: ObjException.Companion.ExceptionClass,
|
||||||
|
val sqlUsageException: ObjException.Companion.ExceptionClass,
|
||||||
|
val rollbackException: ObjException.Companion.ExceptionClass,
|
||||||
|
val sqlTypes: SqlTypeEntries,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
fun resolve(module: ModuleScope): SqlCoreModule = SqlCoreModule(
|
||||||
|
module = module,
|
||||||
|
databaseClass = module.requireClass("Database"),
|
||||||
|
transactionClass = module.requireClass("SqlTransaction"),
|
||||||
|
resultSetClass = module.requireClass("ResultSet"),
|
||||||
|
rowClass = module.requireClass("SqlRow"),
|
||||||
|
columnClass = module.requireClass("SqlColumn"),
|
||||||
|
executionResultClass = module.requireClass("ExecutionResult"),
|
||||||
|
databaseException = module.requireClass("DatabaseException") as ObjException.Companion.ExceptionClass,
|
||||||
|
sqlExecutionException = module.requireClass("SqlExecutionException") as ObjException.Companion.ExceptionClass,
|
||||||
|
sqlConstraintException = module.requireClass("SqlConstraintException") as ObjException.Companion.ExceptionClass,
|
||||||
|
sqlUsageException = module.requireClass("SqlUsageException") as ObjException.Companion.ExceptionClass,
|
||||||
|
rollbackException = module.requireClass("RollbackException") as ObjException.Companion.ExceptionClass,
|
||||||
|
sqlTypes = SqlTypeEntries.resolve(module),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlTypeEntries private constructor(
|
||||||
|
private val entries: Map<String, ObjEnumEntry>,
|
||||||
|
) {
|
||||||
|
fun require(name: String): ObjEnumEntry = entries[name]
|
||||||
|
?: error("lyng.io.db.SqlType entry is missing: $name")
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun resolve(module: ModuleScope): SqlTypeEntries {
|
||||||
|
val enumClass = resolveEnum(module, "SqlType")
|
||||||
|
return SqlTypeEntries(
|
||||||
|
listOf(
|
||||||
|
"Binary", "String", "Int", "Double", "Decimal",
|
||||||
|
"Bool", "Instant", "Date", "DateTime"
|
||||||
|
).associateWith { name ->
|
||||||
|
enumClass.byName[ObjString(name)] as? ObjEnumEntry
|
||||||
|
?: error("lyng.io.db.SqlType.$name is missing")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolveEnum(module: ModuleScope, enumName: String): ObjEnumClass {
|
||||||
|
val local = module.get(enumName)?.value as? ObjEnumClass
|
||||||
|
if (local != null) return local
|
||||||
|
val root = module.importProvider.rootScope.get(enumName)?.value as? ObjEnumClass
|
||||||
|
return root ?: error("lyng.io.db declaration enum is missing: $enumName")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlRuntimeTypes private constructor(
|
||||||
|
val core: SqlCoreModule,
|
||||||
|
val databaseClass: ObjClass,
|
||||||
|
val transactionClass: ObjClass,
|
||||||
|
val resultSetClass: ObjClass,
|
||||||
|
val rowClass: ObjClass,
|
||||||
|
val columnClass: ObjClass,
|
||||||
|
val executionResultClass: ObjClass,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
fun create(prefix: String, core: SqlCoreModule): SqlRuntimeTypes {
|
||||||
|
val databaseClass = object : ObjClass("${prefix}Database", core.databaseClass) {}
|
||||||
|
val transactionClass = object : ObjClass("${prefix}Transaction", core.transactionClass) {}
|
||||||
|
val resultSetClass = object : ObjClass("${prefix}ResultSet", core.resultSetClass) {}
|
||||||
|
val rowClass = object : ObjClass("${prefix}Row", core.rowClass) {}
|
||||||
|
val columnClass = object : ObjClass("${prefix}Column", core.columnClass) {}
|
||||||
|
val executionResultClass = object : ObjClass("${prefix}ExecutionResult", core.executionResultClass) {}
|
||||||
|
val runtime = SqlRuntimeTypes(
|
||||||
|
core = core,
|
||||||
|
databaseClass = databaseClass,
|
||||||
|
transactionClass = transactionClass,
|
||||||
|
resultSetClass = resultSetClass,
|
||||||
|
rowClass = rowClass,
|
||||||
|
columnClass = columnClass,
|
||||||
|
executionResultClass = executionResultClass,
|
||||||
|
)
|
||||||
|
runtime.bind()
|
||||||
|
return runtime
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun bind() {
|
||||||
|
databaseClass.addFn("close") {
|
||||||
|
thisAs<SqlDatabaseObj>().backend.close()
|
||||||
|
ObjNull
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseClass.addFn("transaction") {
|
||||||
|
val self = thisAs<SqlDatabaseObj>()
|
||||||
|
val block = args.list.getOrNull(0) ?: raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
||||||
|
if (!block.isInstanceOf("Callable")) {
|
||||||
|
raiseClassCastError("transaction block must be callable")
|
||||||
|
}
|
||||||
|
self.backend.transaction(this) { backend ->
|
||||||
|
val lifetime = SqlTransactionLifetime(this@SqlRuntimeTypes.core)
|
||||||
|
try {
|
||||||
|
call(block, Arguments(SqlTransactionObj(this@SqlRuntimeTypes, backend, lifetime)), ObjNull)
|
||||||
|
} finally {
|
||||||
|
lifetime.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
transactionClass.addFn("select") {
|
||||||
|
val self = thisAs<SqlTransactionObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
val clause = (args.list.getOrNull(0) as? ObjString)?.value
|
||||||
|
?: raiseClassCastError("query must be String")
|
||||||
|
val params = args.list.drop(1)
|
||||||
|
SqlResultSetObj(self.types, self.lifetime, self.backend.select(this, clause, params))
|
||||||
|
}
|
||||||
|
transactionClass.addFn("execute") {
|
||||||
|
val self = thisAs<SqlTransactionObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
val clause = (args.list.getOrNull(0) as? ObjString)?.value
|
||||||
|
?: raiseClassCastError("query must be String")
|
||||||
|
val params = args.list.drop(1)
|
||||||
|
SqlExecutionResultObj(self.types, self.lifetime, self.backend.execute(this, clause, params))
|
||||||
|
}
|
||||||
|
transactionClass.addFn("transaction") {
|
||||||
|
val self = thisAs<SqlTransactionObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
val block = args.list.getOrNull(0) ?: raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
||||||
|
if (!block.isInstanceOf("Callable")) {
|
||||||
|
raiseClassCastError("transaction block must be callable")
|
||||||
|
}
|
||||||
|
self.backend.transaction(this) { backend ->
|
||||||
|
val lifetime = SqlTransactionLifetime(this@SqlRuntimeTypes.core)
|
||||||
|
try {
|
||||||
|
call(block, Arguments(SqlTransactionObj(self.types, backend, lifetime)), ObjNull)
|
||||||
|
} finally {
|
||||||
|
lifetime.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
resultSetClass.addProperty("columns", getter = {
|
||||||
|
val self = thisAs<SqlResultSetObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
ObjImmutableList(self.columns)
|
||||||
|
})
|
||||||
|
resultSetClass.addFn("size") {
|
||||||
|
val self = thisAs<SqlResultSetObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
ObjInt.of(self.rows.size.toLong())
|
||||||
|
}
|
||||||
|
resultSetClass.addFn("isEmpty") {
|
||||||
|
val self = thisAs<SqlResultSetObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
ObjBool(self.rows.isEmpty())
|
||||||
|
}
|
||||||
|
resultSetClass.addFn("iterator") {
|
||||||
|
val self = thisAs<SqlResultSetObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
ObjImmutableList(self.rows).invokeInstanceMethod(requireScope(), "iterator")
|
||||||
|
}
|
||||||
|
resultSetClass.addFn("toList") {
|
||||||
|
val self = thisAs<SqlResultSetObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
ObjImmutableList(self.rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
rowClass.addProperty("size", getter = {
|
||||||
|
val self = thisAs<SqlRowObj>()
|
||||||
|
ObjInt.of(self.values.size.toLong())
|
||||||
|
})
|
||||||
|
rowClass.addProperty("values", getter = {
|
||||||
|
val self = thisAs<SqlRowObj>()
|
||||||
|
ObjImmutableList(self.values)
|
||||||
|
})
|
||||||
|
|
||||||
|
columnClass.addProperty("name", getter = { ObjString(thisAs<SqlColumnObj>().meta.name) })
|
||||||
|
columnClass.addProperty("sqlType", getter = { thisAs<SqlColumnObj>().meta.sqlType })
|
||||||
|
columnClass.addProperty("nullable", getter = { ObjBool(thisAs<SqlColumnObj>().meta.nullable) })
|
||||||
|
columnClass.addProperty("nativeType", getter = { ObjString(thisAs<SqlColumnObj>().meta.nativeType) })
|
||||||
|
|
||||||
|
executionResultClass.addProperty("affectedRowsCount", getter = {
|
||||||
|
val self = thisAs<SqlExecutionResultObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
ObjInt.of(self.result.affectedRowsCount.toLong())
|
||||||
|
})
|
||||||
|
executionResultClass.addFn("getGeneratedKeys") {
|
||||||
|
val self = thisAs<SqlExecutionResultObj>()
|
||||||
|
self.lifetime.ensureActive(this)
|
||||||
|
SqlResultSetObj(self.types, self.lifetime, self.result.generatedKeys)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlTransactionLifetime(
|
||||||
|
private val core: SqlCoreModule,
|
||||||
|
) {
|
||||||
|
private var active = true
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
active = false
|
||||||
|
}
|
||||||
|
|
||||||
|
fun ensureActive(scope: ScopeFacade) {
|
||||||
|
if (!active) {
|
||||||
|
scope.raiseError(
|
||||||
|
ObjException(core.sqlUsageException, scope.requireScope(), ObjString("SQL result can be used only while its transaction is active"))
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlDatabaseObj(
|
||||||
|
val types: SqlRuntimeTypes,
|
||||||
|
val backend: SqlDatabaseBackend,
|
||||||
|
) : Obj() {
|
||||||
|
override val objClass: ObjClass
|
||||||
|
get() = types.databaseClass
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlTransactionObj(
|
||||||
|
val types: SqlRuntimeTypes,
|
||||||
|
val backend: SqlTransactionBackend,
|
||||||
|
val lifetime: SqlTransactionLifetime,
|
||||||
|
) : Obj() {
|
||||||
|
override val objClass: ObjClass
|
||||||
|
get() = types.transactionClass
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlResultSetObj(
|
||||||
|
val types: SqlRuntimeTypes,
|
||||||
|
val lifetime: SqlTransactionLifetime,
|
||||||
|
data: SqlResultSetData,
|
||||||
|
) : Obj() {
|
||||||
|
val columns: List<Obj> = data.columns.map { SqlColumnObj(types, it) }
|
||||||
|
val rows: List<Obj> = buildRows(types, data)
|
||||||
|
|
||||||
|
override val objClass: ObjClass
|
||||||
|
get() = types.resultSetClass
|
||||||
|
|
||||||
|
private fun buildRows(
|
||||||
|
types: SqlRuntimeTypes,
|
||||||
|
data: SqlResultSetData,
|
||||||
|
): List<Obj> {
|
||||||
|
val indexByName = linkedMapOf<String, MutableList<Int>>()
|
||||||
|
data.columns.forEachIndexed { index, column ->
|
||||||
|
indexByName.getOrPut(column.name.lowercase()) { mutableListOf() }.add(index)
|
||||||
|
}
|
||||||
|
return data.rows.map { rowValues ->
|
||||||
|
SqlRowObj(types, rowValues, indexByName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlRowObj(
|
||||||
|
val types: SqlRuntimeTypes,
|
||||||
|
val values: List<Obj>,
|
||||||
|
private val indexByName: Map<String, List<Int>>,
|
||||||
|
) : Obj() {
|
||||||
|
override val objClass: ObjClass
|
||||||
|
get() = types.rowClass
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
||||||
|
return when (index) {
|
||||||
|
is ObjInt -> {
|
||||||
|
val idx = index.value.toInt()
|
||||||
|
if (idx !in values.indices) {
|
||||||
|
scope.raiseIndexOutOfBounds("SQL row index $idx is out of bounds")
|
||||||
|
}
|
||||||
|
values[idx]
|
||||||
|
}
|
||||||
|
is ObjString -> {
|
||||||
|
val matches = indexByName[index.value.lowercase()]
|
||||||
|
?: scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
types.core.sqlUsageException,
|
||||||
|
scope,
|
||||||
|
ObjString("No such SQL result column: ${index.value}")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
if (matches.size != 1) {
|
||||||
|
scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
types.core.sqlUsageException,
|
||||||
|
scope,
|
||||||
|
ObjString("Ambiguous SQL result column: ${index.value}")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
values[matches.first()]
|
||||||
|
}
|
||||||
|
else -> scope.raiseClassCastError("SQL row index must be Int or String")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlColumnObj(
|
||||||
|
val types: SqlRuntimeTypes,
|
||||||
|
val meta: SqlColumnMeta,
|
||||||
|
) : Obj() {
|
||||||
|
override val objClass: ObjClass
|
||||||
|
get() = types.columnClass
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SqlExecutionResultObj(
|
||||||
|
val types: SqlRuntimeTypes,
|
||||||
|
val lifetime: SqlTransactionLifetime,
|
||||||
|
val result: SqlExecutionResultData,
|
||||||
|
) : Obj() {
|
||||||
|
override val objClass: ObjClass
|
||||||
|
get() = types.executionResultClass
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import net.sergeych.lyng.ModuleScope
|
||||||
|
import net.sergeych.lyng.Pos
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.Source
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseObj
|
||||||
|
import net.sergeych.lyng.io.db.SqlRuntimeTypes
|
||||||
|
import net.sergeych.lyng.io.db.createDbModule
|
||||||
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjBool
|
||||||
|
import net.sergeych.lyng.obj.ObjImmutableMap
|
||||||
|
import net.sergeych.lyng.obj.ObjInt
|
||||||
|
import net.sergeych.lyng.obj.ObjMap
|
||||||
|
import net.sergeych.lyng.obj.ObjNull
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.obj.ObjVoid
|
||||||
|
import net.sergeych.lyng.obj.requiredArg
|
||||||
|
import net.sergeych.lyng.pacman.ImportManager
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
import net.sergeych.lyngio.stdlib_included.db_jdbcLyng
|
||||||
|
|
||||||
|
private const val JDBC_MODULE_NAME = "lyng.io.db.jdbc"
|
||||||
|
private const val DB_MODULE_NAME = "lyng.io.db"
|
||||||
|
private const val JDBC_SCHEME = "jdbc"
|
||||||
|
private const val H2_DRIVER = "org.h2.Driver"
|
||||||
|
private const val POSTGRES_DRIVER = "org.postgresql.Driver"
|
||||||
|
|
||||||
|
fun createJdbcModule(scope: Scope): Boolean = createJdbcModule(scope.importManager)
|
||||||
|
|
||||||
|
fun createJdbc(scope: Scope): Boolean = createJdbcModule(scope)
|
||||||
|
|
||||||
|
fun createJdbcModule(manager: ImportManager): Boolean {
|
||||||
|
createDbModule(manager)
|
||||||
|
if (manager.packageNames.contains(JDBC_MODULE_NAME)) return false
|
||||||
|
manager.addPackage(JDBC_MODULE_NAME) { module ->
|
||||||
|
buildJdbcModule(module)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun createJdbc(manager: ImportManager): Boolean = createJdbcModule(manager)
|
||||||
|
|
||||||
|
private suspend fun buildJdbcModule(module: ModuleScope) {
|
||||||
|
module.eval(Source(JDBC_MODULE_NAME, db_jdbcLyng))
|
||||||
|
val dbModule = module.importProvider.createModuleScope(Pos.builtIn, DB_MODULE_NAME)
|
||||||
|
val core = SqlCoreModule.resolve(dbModule)
|
||||||
|
val runtimeTypes = SqlRuntimeTypes.create("Jdbc", core)
|
||||||
|
|
||||||
|
module.addFn("openJdbc") {
|
||||||
|
val options = parseOpenJdbcArgs(this)
|
||||||
|
SqlDatabaseObj(runtimeTypes, openJdbcBackend(this, core, options))
|
||||||
|
}
|
||||||
|
module.addFn("openH2") {
|
||||||
|
val options = parseOpenShortcutArgs(this, H2_DRIVER, ::normalizeH2Url)
|
||||||
|
SqlDatabaseObj(runtimeTypes, openJdbcBackend(this, core, options))
|
||||||
|
}
|
||||||
|
module.addFn("openPostgres") {
|
||||||
|
val options = parseOpenShortcutArgs(this, POSTGRES_DRIVER, ::normalizePostgresUrl)
|
||||||
|
SqlDatabaseObj(runtimeTypes, openJdbcBackend(this, core, options))
|
||||||
|
}
|
||||||
|
|
||||||
|
registerProvider(dbModule, runtimeTypes, core, JDBC_SCHEME, null)
|
||||||
|
registerProvider(dbModule, runtimeTypes, core, "h2", H2_DRIVER)
|
||||||
|
registerProvider(dbModule, runtimeTypes, core, "postgres", POSTGRES_DRIVER)
|
||||||
|
registerProvider(dbModule, runtimeTypes, core, "postgresql", POSTGRES_DRIVER)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun registerProvider(
|
||||||
|
dbModule: ModuleScope,
|
||||||
|
runtimeTypes: SqlRuntimeTypes,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
scheme: String,
|
||||||
|
implicitDriverClass: String?,
|
||||||
|
) {
|
||||||
|
dbModule.callFn(
|
||||||
|
"registerDatabaseProvider",
|
||||||
|
ObjString(scheme),
|
||||||
|
net.sergeych.lyng.obj.ObjExternCallable.fromBridge {
|
||||||
|
val connectionUrl = requiredArg<ObjString>(0).value
|
||||||
|
val extraParams = args.list.getOrNull(1)
|
||||||
|
?: raiseError("Expected exactly 2 arguments, got ${args.list.size}")
|
||||||
|
val options = parseJdbcConnectionUrl(this, scheme, implicitDriverClass, connectionUrl, extraParams)
|
||||||
|
SqlDatabaseObj(runtimeTypes, openJdbcBackend(this, core, options))
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun parseOpenJdbcArgs(scope: ScopeFacade): JdbcOpenOptions {
|
||||||
|
val rawUrl = readArg(scope, "connectionUrl", 0) ?: scope.raiseError("argument 'connectionUrl' is required")
|
||||||
|
val connectionUrl = (rawUrl as? ObjString)?.value ?: scope.raiseClassCastError("connectionUrl must be String")
|
||||||
|
val user = readNullableStringArg(scope, "user", 1)
|
||||||
|
val password = readNullableStringArg(scope, "password", 2)
|
||||||
|
val driverClass = readNullableStringArg(scope, "driverClass", 3)
|
||||||
|
val properties = readPropertiesArg(scope, "properties", 4)
|
||||||
|
return JdbcOpenOptions(
|
||||||
|
connectionUrl = normalizeJdbcUrl(connectionUrl, scope),
|
||||||
|
user = user,
|
||||||
|
password = password,
|
||||||
|
driverClass = driverClass,
|
||||||
|
properties = properties,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun parseOpenShortcutArgs(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
defaultDriverClass: String,
|
||||||
|
normalize: (String, ScopeFacade) -> String,
|
||||||
|
): JdbcOpenOptions {
|
||||||
|
val rawUrl = readArg(scope, "connectionUrl", 0) ?: scope.raiseError("argument 'connectionUrl' is required")
|
||||||
|
val connectionUrl = (rawUrl as? ObjString)?.value ?: scope.raiseClassCastError("connectionUrl must be String")
|
||||||
|
val user = readNullableStringArg(scope, "user", 1)
|
||||||
|
val password = readNullableStringArg(scope, "password", 2)
|
||||||
|
val properties = readPropertiesArg(scope, "properties", 3)
|
||||||
|
return JdbcOpenOptions(
|
||||||
|
connectionUrl = normalize(connectionUrl, scope),
|
||||||
|
user = user,
|
||||||
|
password = password,
|
||||||
|
driverClass = defaultDriverClass,
|
||||||
|
properties = properties,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun parseJdbcConnectionUrl(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
scheme: String,
|
||||||
|
implicitDriverClass: String?,
|
||||||
|
connectionUrl: String,
|
||||||
|
extraParams: Obj,
|
||||||
|
): JdbcOpenOptions {
|
||||||
|
val driverClass = mapNullableString(extraParams, scope, "driverClass") ?: implicitDriverClass
|
||||||
|
val user = mapNullableString(extraParams, scope, "user")
|
||||||
|
val password = mapNullableString(extraParams, scope, "password")
|
||||||
|
val properties = mapProperties(extraParams, scope, "properties")
|
||||||
|
val normalizedUrl = when (scheme) {
|
||||||
|
JDBC_SCHEME -> normalizeJdbcUrl(connectionUrl, scope)
|
||||||
|
"h2" -> normalizeH2Url(connectionUrl, scope)
|
||||||
|
"postgres", "postgresql" -> normalizePostgresUrl(connectionUrl, scope)
|
||||||
|
else -> scope.raiseIllegalArgument("Unsupported JDBC provider scheme: $scheme")
|
||||||
|
}
|
||||||
|
return JdbcOpenOptions(
|
||||||
|
connectionUrl = normalizedUrl,
|
||||||
|
user = user,
|
||||||
|
password = password,
|
||||||
|
driverClass = driverClass,
|
||||||
|
properties = properties,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun normalizeJdbcUrl(rawUrl: String, scope: ScopeFacade): String {
|
||||||
|
val trimmed = rawUrl.trim()
|
||||||
|
if (!trimmed.startsWith("jdbc:", ignoreCase = true)) {
|
||||||
|
scope.raiseIllegalArgument("JDBC connection URL must start with jdbc:")
|
||||||
|
}
|
||||||
|
return trimmed
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun normalizeH2Url(rawUrl: String, scope: ScopeFacade): String {
|
||||||
|
val trimmed = rawUrl.trim()
|
||||||
|
if (trimmed.isEmpty()) {
|
||||||
|
scope.raiseIllegalArgument("H2 connection URL must not be empty")
|
||||||
|
}
|
||||||
|
return when {
|
||||||
|
trimmed.startsWith("jdbc:h2:", ignoreCase = true) -> trimmed
|
||||||
|
trimmed.startsWith("h2:", ignoreCase = true) -> "jdbc:${trimmed}"
|
||||||
|
else -> "jdbc:h2:$trimmed"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun normalizePostgresUrl(rawUrl: String, scope: ScopeFacade): String {
|
||||||
|
val trimmed = rawUrl.trim()
|
||||||
|
if (trimmed.isEmpty()) {
|
||||||
|
scope.raiseIllegalArgument("PostgreSQL connection URL must not be empty")
|
||||||
|
}
|
||||||
|
return when {
|
||||||
|
trimmed.startsWith("jdbc:postgresql:", ignoreCase = true) -> trimmed
|
||||||
|
trimmed.startsWith("postgresql:", ignoreCase = true) -> "jdbc:$trimmed"
|
||||||
|
trimmed.startsWith("postgres:", ignoreCase = true) -> "jdbc:postgresql:${trimmed.substringAfter(':')}"
|
||||||
|
else -> "jdbc:postgresql:$trimmed"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readArg(scope: ScopeFacade, name: String, position: Int): Obj? {
|
||||||
|
val named = scope.args.named[name]
|
||||||
|
val positional = scope.args.list.getOrNull(position)
|
||||||
|
if (named != null && positional != null) {
|
||||||
|
scope.raiseIllegalArgument("argument '$name' is already set")
|
||||||
|
}
|
||||||
|
return named ?: positional
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readNullableStringArg(scope: ScopeFacade, name: String, position: Int): String? {
|
||||||
|
val value = readArg(scope, name, position) ?: return null
|
||||||
|
return when (value) {
|
||||||
|
ObjNull -> null
|
||||||
|
is ObjString -> value.value
|
||||||
|
else -> scope.raiseClassCastError("$name must be String?")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readPropertiesArg(scope: ScopeFacade, name: String, position: Int): Map<String, String> {
|
||||||
|
val value = readArg(scope, name, position) ?: return emptyMap()
|
||||||
|
return when (value) {
|
||||||
|
ObjNull -> emptyMap()
|
||||||
|
else -> objToStringMap(value, scope, name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun mapNullableString(map: Obj, scope: ScopeFacade, key: String): String? {
|
||||||
|
val value = map.getAt(scope.requireScope(), ObjString(key))
|
||||||
|
return when (value) {
|
||||||
|
ObjNull -> null
|
||||||
|
is ObjString -> value.value
|
||||||
|
else -> scope.raiseClassCastError("extraParams.$key must be String?")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun mapProperties(map: Obj, scope: ScopeFacade, key: String): Map<String, String> {
|
||||||
|
val value = map.getAt(scope.requireScope(), ObjString(key))
|
||||||
|
return when (value) {
|
||||||
|
ObjNull -> emptyMap()
|
||||||
|
else -> objToStringMap(value, scope, "extraParams.$key")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun objToStringMap(value: Obj, scope: ScopeFacade, label: String): Map<String, String> {
|
||||||
|
val rawEntries = when (value) {
|
||||||
|
is ObjMap -> value.map
|
||||||
|
is ObjImmutableMap -> value.map
|
||||||
|
else -> scope.raiseClassCastError("$label must be Map<String, Object?>")
|
||||||
|
}
|
||||||
|
val properties = linkedMapOf<String, String>()
|
||||||
|
for ((rawKey, rawValue) in rawEntries) {
|
||||||
|
val key = (rawKey as? ObjString)?.value ?: scope.raiseClassCastError("$label keys must be String")
|
||||||
|
if (rawValue == ObjNull) continue
|
||||||
|
properties[key] = scope.toStringOf(rawValue).value
|
||||||
|
}
|
||||||
|
return properties
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun ModuleScope.callFn(name: String, vararg args: Obj): Obj {
|
||||||
|
val callee = get(name)?.value ?: error("Missing $name in module")
|
||||||
|
return callee.invoke(this, ObjNull, *args)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal data class JdbcOpenOptions(
|
||||||
|
val connectionUrl: String,
|
||||||
|
val user: String?,
|
||||||
|
val password: String?,
|
||||||
|
val driverClass: String?,
|
||||||
|
val properties: Map<String, String>,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal expect suspend fun openJdbcBackend(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
options: JdbcOpenOptions,
|
||||||
|
): SqlDatabaseBackend
|
||||||
@@ -24,22 +24,20 @@ import net.sergeych.lyng.Scope
|
|||||||
import net.sergeych.lyng.ScopeFacade
|
import net.sergeych.lyng.ScopeFacade
|
||||||
import net.sergeych.lyng.Source
|
import net.sergeych.lyng.Source
|
||||||
import net.sergeych.lyng.asFacade
|
import net.sergeych.lyng.asFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseObj
|
||||||
|
import net.sergeych.lyng.io.db.SqlRuntimeTypes
|
||||||
|
import net.sergeych.lyng.io.db.SqlTransactionBackend
|
||||||
import net.sergeych.lyng.io.db.createDbModule
|
import net.sergeych.lyng.io.db.createDbModule
|
||||||
import net.sergeych.lyng.requireScope
|
import net.sergeych.lyng.requireScope
|
||||||
import net.sergeych.lyng.obj.Obj
|
import net.sergeych.lyng.obj.Obj
|
||||||
import net.sergeych.lyng.obj.ObjBool
|
import net.sergeych.lyng.obj.ObjBool
|
||||||
import net.sergeych.lyng.obj.ObjClass
|
|
||||||
import net.sergeych.lyng.obj.ObjEnumClass
|
|
||||||
import net.sergeych.lyng.obj.ObjEnumEntry
|
|
||||||
import net.sergeych.lyng.obj.ObjException
|
|
||||||
import net.sergeych.lyng.obj.ObjImmutableList
|
|
||||||
import net.sergeych.lyng.obj.ObjInt
|
import net.sergeych.lyng.obj.ObjInt
|
||||||
import net.sergeych.lyng.obj.ObjNull
|
import net.sergeych.lyng.obj.ObjNull
|
||||||
import net.sergeych.lyng.obj.ObjReal
|
|
||||||
import net.sergeych.lyng.obj.ObjString
|
import net.sergeych.lyng.obj.ObjString
|
||||||
import net.sergeych.lyng.obj.ObjVoid
|
import net.sergeych.lyng.obj.ObjVoid
|
||||||
import net.sergeych.lyng.obj.requiredArg
|
import net.sergeych.lyng.obj.requiredArg
|
||||||
import net.sergeych.lyng.obj.thisAs
|
|
||||||
import net.sergeych.lyng.pacman.ImportManager
|
import net.sergeych.lyng.pacman.ImportManager
|
||||||
import net.sergeych.lyngio.stdlib_included.db_sqliteLyng
|
import net.sergeych.lyngio.stdlib_included.db_sqliteLyng
|
||||||
|
|
||||||
@@ -64,12 +62,12 @@ fun createSqlite(manager: ImportManager): Boolean = createSqliteModule(manager)
|
|||||||
private suspend fun buildSqliteModule(module: ModuleScope) {
|
private suspend fun buildSqliteModule(module: ModuleScope) {
|
||||||
module.eval(Source(SQLITE_MODULE_NAME, db_sqliteLyng))
|
module.eval(Source(SQLITE_MODULE_NAME, db_sqliteLyng))
|
||||||
val dbModule = module.importProvider.createModuleScope(Pos.builtIn, DB_MODULE_NAME)
|
val dbModule = module.importProvider.createModuleScope(Pos.builtIn, DB_MODULE_NAME)
|
||||||
val core = SqliteCoreModule.resolve(dbModule)
|
val core = SqlCoreModule.resolve(dbModule)
|
||||||
val runtimeTypes = SqliteRuntimeTypes.create(core)
|
val runtimeTypes = SqlRuntimeTypes.create("Sqlite", core)
|
||||||
|
|
||||||
module.addFn("openSqlite") {
|
module.addFn("openSqlite") {
|
||||||
val options = parseOpenSqliteArgs(this)
|
val options = parseOpenSqliteArgs(this)
|
||||||
SqliteDatabaseObj(runtimeTypes, openSqliteBackend(this, core, options))
|
SqlDatabaseObj(runtimeTypes, openSqliteBackend(this, core, options))
|
||||||
}
|
}
|
||||||
|
|
||||||
dbModule.callFn(
|
dbModule.callFn(
|
||||||
@@ -80,7 +78,7 @@ private suspend fun buildSqliteModule(module: ModuleScope) {
|
|||||||
val extraParams = args.list.getOrNull(1)
|
val extraParams = args.list.getOrNull(1)
|
||||||
?: raiseError("Expected exactly 2 arguments, got ${args.list.size}")
|
?: raiseError("Expected exactly 2 arguments, got ${args.list.size}")
|
||||||
val options = parseSqliteConnectionUrl(this, connectionUrl, extraParams)
|
val options = parseSqliteConnectionUrl(this, connectionUrl, extraParams)
|
||||||
SqliteDatabaseObj(runtimeTypes, openSqliteBackend(this, core, options))
|
SqlDatabaseObj(runtimeTypes, openSqliteBackend(this, core, options))
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -189,354 +187,8 @@ internal data class SqliteOpenOptions(
|
|||||||
val busyTimeoutMillis: Int,
|
val busyTimeoutMillis: Int,
|
||||||
)
|
)
|
||||||
|
|
||||||
internal data class SqliteColumnMeta(
|
|
||||||
val name: String,
|
|
||||||
val sqlType: ObjEnumEntry,
|
|
||||||
val nullable: Boolean,
|
|
||||||
val nativeType: String,
|
|
||||||
)
|
|
||||||
|
|
||||||
internal data class SqliteResultSetData(
|
|
||||||
val columns: List<SqliteColumnMeta>,
|
|
||||||
val rows: List<List<Obj>>,
|
|
||||||
)
|
|
||||||
|
|
||||||
internal data class SqliteExecutionResultData(
|
|
||||||
val affectedRowsCount: Int,
|
|
||||||
val generatedKeys: SqliteResultSetData,
|
|
||||||
)
|
|
||||||
|
|
||||||
internal interface SqliteDatabaseBackend {
|
|
||||||
suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqliteTransactionBackend) -> T): T
|
|
||||||
}
|
|
||||||
|
|
||||||
internal interface SqliteTransactionBackend {
|
|
||||||
suspend fun select(scope: ScopeFacade, clause: String, params: List<Obj>): SqliteResultSetData
|
|
||||||
suspend fun execute(scope: ScopeFacade, clause: String, params: List<Obj>): SqliteExecutionResultData
|
|
||||||
suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqliteTransactionBackend) -> T): T
|
|
||||||
}
|
|
||||||
|
|
||||||
internal expect suspend fun openSqliteBackend(
|
internal expect suspend fun openSqliteBackend(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
options: SqliteOpenOptions,
|
options: SqliteOpenOptions,
|
||||||
): SqliteDatabaseBackend
|
): SqlDatabaseBackend
|
||||||
|
|
||||||
internal class SqliteCoreModule private constructor(
|
|
||||||
val module: ModuleScope,
|
|
||||||
val databaseClass: ObjClass,
|
|
||||||
val transactionClass: ObjClass,
|
|
||||||
val resultSetClass: ObjClass,
|
|
||||||
val rowClass: ObjClass,
|
|
||||||
val columnClass: ObjClass,
|
|
||||||
val executionResultClass: ObjClass,
|
|
||||||
val databaseException: ObjException.Companion.ExceptionClass,
|
|
||||||
val sqlExecutionException: ObjException.Companion.ExceptionClass,
|
|
||||||
val sqlConstraintException: ObjException.Companion.ExceptionClass,
|
|
||||||
val sqlUsageException: ObjException.Companion.ExceptionClass,
|
|
||||||
val rollbackException: ObjException.Companion.ExceptionClass,
|
|
||||||
val sqlTypes: SqlTypeEntries,
|
|
||||||
) {
|
|
||||||
companion object {
|
|
||||||
fun resolve(module: ModuleScope): SqliteCoreModule = SqliteCoreModule(
|
|
||||||
module = module,
|
|
||||||
databaseClass = module.requireClass("Database"),
|
|
||||||
transactionClass = module.requireClass("SqlTransaction"),
|
|
||||||
resultSetClass = module.requireClass("ResultSet"),
|
|
||||||
rowClass = module.requireClass("SqlRow"),
|
|
||||||
columnClass = module.requireClass("SqlColumn"),
|
|
||||||
executionResultClass = module.requireClass("ExecutionResult"),
|
|
||||||
databaseException = module.requireClass("DatabaseException") as ObjException.Companion.ExceptionClass,
|
|
||||||
sqlExecutionException = module.requireClass("SqlExecutionException") as ObjException.Companion.ExceptionClass,
|
|
||||||
sqlConstraintException = module.requireClass("SqlConstraintException") as ObjException.Companion.ExceptionClass,
|
|
||||||
sqlUsageException = module.requireClass("SqlUsageException") as ObjException.Companion.ExceptionClass,
|
|
||||||
rollbackException = module.requireClass("RollbackException") as ObjException.Companion.ExceptionClass,
|
|
||||||
sqlTypes = SqlTypeEntries.resolve(module),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
internal class SqlTypeEntries private constructor(
|
|
||||||
private val entries: Map<String, ObjEnumEntry>,
|
|
||||||
) {
|
|
||||||
fun require(name: String): ObjEnumEntry = entries[name]
|
|
||||||
?: error("lyng.io.db.SqlType entry is missing: $name")
|
|
||||||
|
|
||||||
companion object {
|
|
||||||
fun resolve(module: ModuleScope): SqlTypeEntries {
|
|
||||||
val enumClass = resolveEnum(module, "SqlType")
|
|
||||||
return SqlTypeEntries(
|
|
||||||
listOf(
|
|
||||||
"Binary", "String", "Int", "Double", "Decimal",
|
|
||||||
"Bool", "Instant", "Date", "DateTime"
|
|
||||||
).associateWith { name ->
|
|
||||||
enumClass.byName[ObjString(name)] as? ObjEnumEntry
|
|
||||||
?: error("lyng.io.db.SqlType.$name is missing")
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun resolveEnum(module: ModuleScope, enumName: String): ObjEnumClass {
|
|
||||||
val local = module.get(enumName)?.value as? ObjEnumClass
|
|
||||||
if (local != null) return local
|
|
||||||
val root = module.importProvider.rootScope.get(enumName)?.value as? ObjEnumClass
|
|
||||||
return root ?: error("lyng.io.db declaration enum is missing: $enumName")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class SqliteRuntimeTypes private constructor(
|
|
||||||
val core: SqliteCoreModule,
|
|
||||||
val databaseClass: ObjClass,
|
|
||||||
val transactionClass: ObjClass,
|
|
||||||
val resultSetClass: ObjClass,
|
|
||||||
val rowClass: ObjClass,
|
|
||||||
val columnClass: ObjClass,
|
|
||||||
val executionResultClass: ObjClass,
|
|
||||||
) {
|
|
||||||
companion object {
|
|
||||||
fun create(core: SqliteCoreModule): SqliteRuntimeTypes {
|
|
||||||
val databaseClass = object : ObjClass("SqliteDatabase", core.databaseClass) {}
|
|
||||||
val transactionClass = object : ObjClass("SqliteTransaction", core.transactionClass) {}
|
|
||||||
val resultSetClass = object : ObjClass("SqliteResultSet", core.resultSetClass) {}
|
|
||||||
val rowClass = object : ObjClass("SqliteRow", core.rowClass) {}
|
|
||||||
val columnClass = object : ObjClass("SqliteColumn", core.columnClass) {}
|
|
||||||
val executionResultClass = object : ObjClass("SqliteExecutionResult", core.executionResultClass) {}
|
|
||||||
val runtime = SqliteRuntimeTypes(
|
|
||||||
core = core,
|
|
||||||
databaseClass = databaseClass,
|
|
||||||
transactionClass = transactionClass,
|
|
||||||
resultSetClass = resultSetClass,
|
|
||||||
rowClass = rowClass,
|
|
||||||
columnClass = columnClass,
|
|
||||||
executionResultClass = executionResultClass,
|
|
||||||
)
|
|
||||||
runtime.bind()
|
|
||||||
return runtime
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun bind() {
|
|
||||||
databaseClass.addFn("transaction") {
|
|
||||||
val self = thisAs<SqliteDatabaseObj>()
|
|
||||||
val block = args.list.getOrNull(0) ?: raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
|
||||||
if (!block.isInstanceOf("Callable")) {
|
|
||||||
raiseClassCastError("transaction block must be callable")
|
|
||||||
}
|
|
||||||
self.backend.transaction(this) { backend ->
|
|
||||||
val lifetime = TransactionLifetime(this@SqliteRuntimeTypes.core)
|
|
||||||
try {
|
|
||||||
call(block, Arguments(SqliteTransactionObj(this@SqliteRuntimeTypes, backend, lifetime)), ObjNull)
|
|
||||||
} finally {
|
|
||||||
lifetime.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
transactionClass.addFn("select") {
|
|
||||||
val self = thisAs<SqliteTransactionObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
val clause = requiredArg<ObjString>(0).value
|
|
||||||
val params = args.list.drop(1)
|
|
||||||
SqliteResultSetObj(thisAs<SqliteTransactionObj>().types, self.lifetime, self.backend.select(this, clause, params))
|
|
||||||
}
|
|
||||||
transactionClass.addFn("execute") {
|
|
||||||
val self = thisAs<SqliteTransactionObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
val clause = requiredArg<ObjString>(0).value
|
|
||||||
val params = args.list.drop(1)
|
|
||||||
SqliteExecutionResultObj(self.types, self.lifetime, self.backend.execute(this, clause, params))
|
|
||||||
}
|
|
||||||
transactionClass.addFn("transaction") {
|
|
||||||
val self = thisAs<SqliteTransactionObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
val block = args.list.getOrNull(0) ?: raiseError("Expected exactly 1 argument, got ${args.list.size}")
|
|
||||||
if (!block.isInstanceOf("Callable")) {
|
|
||||||
raiseClassCastError("transaction block must be callable")
|
|
||||||
}
|
|
||||||
self.backend.transaction(this) { backend ->
|
|
||||||
val lifetime = TransactionLifetime(this@SqliteRuntimeTypes.core)
|
|
||||||
try {
|
|
||||||
call(block, Arguments(SqliteTransactionObj(self.types, backend, lifetime)), ObjNull)
|
|
||||||
} finally {
|
|
||||||
lifetime.close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
resultSetClass.addProperty("columns", getter = {
|
|
||||||
val self = thisAs<SqliteResultSetObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjImmutableList(self.columns)
|
|
||||||
})
|
|
||||||
resultSetClass.addFn("size") {
|
|
||||||
val self = thisAs<SqliteResultSetObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjInt.of(self.rows.size.toLong())
|
|
||||||
}
|
|
||||||
resultSetClass.addFn("isEmpty") {
|
|
||||||
val self = thisAs<SqliteResultSetObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjBool(self.rows.isEmpty())
|
|
||||||
}
|
|
||||||
resultSetClass.addFn("iterator") {
|
|
||||||
val self = thisAs<SqliteResultSetObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjImmutableList(self.rows).invokeInstanceMethod(requireScope(), "iterator")
|
|
||||||
}
|
|
||||||
resultSetClass.addFn("toList") {
|
|
||||||
val self = thisAs<SqliteResultSetObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjImmutableList(self.rows)
|
|
||||||
}
|
|
||||||
|
|
||||||
rowClass.addProperty("size", getter = {
|
|
||||||
val self = thisAs<SqliteRowObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjInt.of(self.values.size.toLong())
|
|
||||||
})
|
|
||||||
rowClass.addProperty("values", getter = {
|
|
||||||
val self = thisAs<SqliteRowObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjImmutableList(self.values)
|
|
||||||
})
|
|
||||||
|
|
||||||
columnClass.addProperty("name", getter = { ObjString(thisAs<SqliteColumnObj>().meta.name) })
|
|
||||||
columnClass.addProperty("sqlType", getter = { thisAs<SqliteColumnObj>().meta.sqlType })
|
|
||||||
columnClass.addProperty("nullable", getter = { ObjBool(thisAs<SqliteColumnObj>().meta.nullable) })
|
|
||||||
columnClass.addProperty("nativeType", getter = { ObjString(thisAs<SqliteColumnObj>().meta.nativeType) })
|
|
||||||
|
|
||||||
executionResultClass.addProperty("affectedRowsCount", getter = {
|
|
||||||
val self = thisAs<SqliteExecutionResultObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
ObjInt.of(self.result.affectedRowsCount.toLong())
|
|
||||||
})
|
|
||||||
executionResultClass.addFn("getGeneratedKeys") {
|
|
||||||
val self = thisAs<SqliteExecutionResultObj>()
|
|
||||||
self.lifetime.ensureActive(this)
|
|
||||||
SqliteResultSetObj(self.types, self.lifetime, self.result.generatedKeys)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class TransactionLifetime(
|
|
||||||
private val core: SqliteCoreModule,
|
|
||||||
) {
|
|
||||||
private var active = true
|
|
||||||
|
|
||||||
fun close() {
|
|
||||||
active = false
|
|
||||||
}
|
|
||||||
|
|
||||||
fun ensureActive(scope: ScopeFacade) {
|
|
||||||
if (!active) {
|
|
||||||
scope.raiseError(
|
|
||||||
ObjException(core.sqlUsageException, scope.requireScope(), ObjString("SQL result can be used only while its transaction is active"))
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class SqliteDatabaseObj(
|
|
||||||
val types: SqliteRuntimeTypes,
|
|
||||||
val backend: SqliteDatabaseBackend,
|
|
||||||
) : Obj() {
|
|
||||||
override val objClass: ObjClass
|
|
||||||
get() = types.databaseClass
|
|
||||||
}
|
|
||||||
|
|
||||||
private class SqliteTransactionObj(
|
|
||||||
val types: SqliteRuntimeTypes,
|
|
||||||
val backend: SqliteTransactionBackend,
|
|
||||||
val lifetime: TransactionLifetime,
|
|
||||||
) : Obj() {
|
|
||||||
override val objClass: ObjClass
|
|
||||||
get() = types.transactionClass
|
|
||||||
}
|
|
||||||
|
|
||||||
private class SqliteResultSetObj(
|
|
||||||
val types: SqliteRuntimeTypes,
|
|
||||||
val lifetime: TransactionLifetime,
|
|
||||||
data: SqliteResultSetData,
|
|
||||||
) : Obj() {
|
|
||||||
val columns: List<Obj> = data.columns.map { SqliteColumnObj(types, it) }
|
|
||||||
val rows: List<Obj> = buildRows(types, lifetime, data)
|
|
||||||
|
|
||||||
override val objClass: ObjClass
|
|
||||||
get() = types.resultSetClass
|
|
||||||
|
|
||||||
private fun buildRows(
|
|
||||||
types: SqliteRuntimeTypes,
|
|
||||||
lifetime: TransactionLifetime,
|
|
||||||
data: SqliteResultSetData,
|
|
||||||
): List<Obj> {
|
|
||||||
val indexByName = linkedMapOf<String, MutableList<Int>>()
|
|
||||||
data.columns.forEachIndexed { index, column ->
|
|
||||||
indexByName.getOrPut(column.name.lowercase()) { mutableListOf() }.add(index)
|
|
||||||
}
|
|
||||||
return data.rows.map { rowValues ->
|
|
||||||
SqliteRowObj(types, lifetime, rowValues, indexByName)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class SqliteRowObj(
|
|
||||||
val types: SqliteRuntimeTypes,
|
|
||||||
val lifetime: TransactionLifetime,
|
|
||||||
val values: List<Obj>,
|
|
||||||
private val indexByName: Map<String, List<Int>>,
|
|
||||||
) : Obj() {
|
|
||||||
override val objClass: ObjClass
|
|
||||||
get() = types.rowClass
|
|
||||||
|
|
||||||
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
|
||||||
lifetime.ensureActive(scope.asFacade())
|
|
||||||
return when (index) {
|
|
||||||
is ObjInt -> {
|
|
||||||
val idx = index.value.toInt()
|
|
||||||
if (idx !in values.indices) {
|
|
||||||
scope.raiseIndexOutOfBounds("SQL row index $idx is out of bounds")
|
|
||||||
}
|
|
||||||
values[idx]
|
|
||||||
}
|
|
||||||
is ObjString -> {
|
|
||||||
val matches = indexByName[index.value.lowercase()]
|
|
||||||
?: scope.raiseError(
|
|
||||||
ObjException(
|
|
||||||
types.core.sqlUsageException,
|
|
||||||
scope,
|
|
||||||
ObjString("No such SQL result column: ${index.value}")
|
|
||||||
)
|
|
||||||
)
|
|
||||||
if (matches.size != 1) {
|
|
||||||
scope.raiseError(
|
|
||||||
ObjException(
|
|
||||||
types.core.sqlUsageException,
|
|
||||||
scope,
|
|
||||||
ObjString("Ambiguous SQL result column: ${index.value}")
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
values[matches.first()]
|
|
||||||
}
|
|
||||||
else -> scope.raiseClassCastError("SQL row index must be Int or String")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private class SqliteColumnObj(
|
|
||||||
val types: SqliteRuntimeTypes,
|
|
||||||
val meta: SqliteColumnMeta,
|
|
||||||
) : Obj() {
|
|
||||||
override val objClass: ObjClass
|
|
||||||
get() = types.columnClass
|
|
||||||
}
|
|
||||||
|
|
||||||
private class SqliteExecutionResultObj(
|
|
||||||
val types: SqliteRuntimeTypes,
|
|
||||||
val lifetime: TransactionLifetime,
|
|
||||||
val result: SqliteExecutionResultData,
|
|
||||||
) : Obj() {
|
|
||||||
override val objClass: ObjClass
|
|
||||||
get() = types.executionResultClass
|
|
||||||
}
|
|
||||||
@@ -17,35 +17,46 @@ import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
|||||||
|
|
||||||
internal fun createKtorWsEngine(
|
internal fun createKtorWsEngine(
|
||||||
engineFactory: HttpClientEngineFactory<HttpClientEngineConfig>,
|
engineFactory: HttpClientEngineFactory<HttpClientEngineConfig>,
|
||||||
): LyngWsEngine = KtorLyngWsEngine(engineFactory)
|
shareClient: Boolean = true,
|
||||||
|
): LyngWsEngine = KtorLyngWsEngine(engineFactory, shareClient)
|
||||||
|
|
||||||
private class KtorLyngWsEngine(
|
private class KtorLyngWsEngine(
|
||||||
engineFactory: HttpClientEngineFactory<HttpClientEngineConfig>,
|
engineFactory: HttpClientEngineFactory<HttpClientEngineConfig>,
|
||||||
|
private val shareClient: Boolean,
|
||||||
) : LyngWsEngine {
|
) : LyngWsEngine {
|
||||||
private val clientResult = runCatching {
|
private val clientFactory: () -> HttpClient = {
|
||||||
HttpClient(engineFactory) {
|
HttpClient(engineFactory) {
|
||||||
install(WebSockets)
|
install(WebSockets)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private val sharedClientResult = if (shareClient) runCatching { clientFactory() } else null
|
||||||
|
private val supportProbe = if (!shareClient) runCatching { clientFactory().close() } else null
|
||||||
|
|
||||||
override val isSupported: Boolean
|
override val isSupported: Boolean
|
||||||
get() = clientResult.isSuccess
|
get() = sharedClientResult?.isSuccess ?: supportProbe?.isSuccess ?: true
|
||||||
|
|
||||||
override suspend fun connect(url: String, headers: Map<String, String>): LyngWsSession {
|
override suspend fun connect(url: String, headers: Map<String, String>): LyngWsSession {
|
||||||
val client = clientResult.getOrElse {
|
val client = (sharedClientResult?.getOrElse {
|
||||||
throw UnsupportedOperationException(it.message ?: "WebSocket client is not supported")
|
throw UnsupportedOperationException(it.message ?: "WebSocket client is not supported")
|
||||||
}
|
} ?: runCatching { clientFactory() }.getOrElse {
|
||||||
|
throw UnsupportedOperationException(it.message ?: "WebSocket client is not supported")
|
||||||
|
})
|
||||||
val session = client.webSocketSession {
|
val session = client.webSocketSession {
|
||||||
url(url)
|
url(url)
|
||||||
headers.forEach { (name, value) -> header(name, value) }
|
headers.forEach { (name, value) -> header(name, value) }
|
||||||
}
|
}
|
||||||
return KtorLyngWsSession(url, session)
|
return KtorLyngWsSession(
|
||||||
|
targetUrl = url,
|
||||||
|
session = session,
|
||||||
|
ownedClient = client.takeUnless { shareClient },
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private class KtorLyngWsSession(
|
private class KtorLyngWsSession(
|
||||||
private val targetUrl: String,
|
private val targetUrl: String,
|
||||||
private val session: DefaultWebSocketSession,
|
private val session: DefaultWebSocketSession,
|
||||||
|
private val ownedClient: HttpClient? = null,
|
||||||
) : LyngWsSession {
|
) : LyngWsSession {
|
||||||
private var closed = false
|
private var closed = false
|
||||||
|
|
||||||
@@ -55,12 +66,22 @@ private class KtorLyngWsSession(
|
|||||||
|
|
||||||
override suspend fun sendText(text: String) {
|
override suspend fun sendText(text: String) {
|
||||||
ensureOpen()
|
ensureOpen()
|
||||||
|
try {
|
||||||
session.send(text)
|
session.send(text)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
release()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun sendBytes(data: ByteArray) {
|
override suspend fun sendBytes(data: ByteArray) {
|
||||||
ensureOpen()
|
ensureOpen()
|
||||||
|
try {
|
||||||
session.send(data)
|
session.send(data)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
release()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun receive(): LyngWsMessage? {
|
override suspend fun receive(): LyngWsMessage? {
|
||||||
@@ -68,14 +89,17 @@ private class KtorLyngWsSession(
|
|||||||
val frame = try {
|
val frame = try {
|
||||||
session.incoming.receive()
|
session.incoming.receive()
|
||||||
} catch (_: ClosedReceiveChannelException) {
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
closed = true
|
release()
|
||||||
return null
|
return null
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
release()
|
||||||
|
throw e
|
||||||
}
|
}
|
||||||
return when (frame) {
|
return when (frame) {
|
||||||
is Frame.Text -> LyngWsMessage(isText = true, text = frame.readText())
|
is Frame.Text -> LyngWsMessage(isText = true, text = frame.readText())
|
||||||
is Frame.Binary -> LyngWsMessage(isText = false, data = frame.data.copyOf())
|
is Frame.Binary -> LyngWsMessage(isText = false, data = frame.data.copyOf())
|
||||||
is Frame.Close -> {
|
is Frame.Close -> {
|
||||||
closed = true
|
release()
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
else -> receive()
|
else -> receive()
|
||||||
@@ -84,11 +108,20 @@ private class KtorLyngWsSession(
|
|||||||
|
|
||||||
override suspend fun close(code: Int, reason: String) {
|
override suspend fun close(code: Int, reason: String) {
|
||||||
if (closed) return
|
if (closed) return
|
||||||
closed = true
|
try {
|
||||||
session.close(CloseReason(code.toShort(), reason))
|
session.close(CloseReason(code.toShort(), reason))
|
||||||
|
} finally {
|
||||||
|
release()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun ensureOpen() {
|
private fun ensureOpen() {
|
||||||
if (closed) throw IllegalStateException("websocket session is closed")
|
if (closed) throw IllegalStateException("websocket session is closed")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun release() {
|
||||||
|
if (closed) return
|
||||||
|
closed = true
|
||||||
|
ownedClient?.close()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,392 @@
|
|||||||
|
package net.sergeych.lyngio.ws
|
||||||
|
|
||||||
|
import io.ktor.http.Url
|
||||||
|
import io.ktor.http.URLProtocol
|
||||||
|
import net.sergeych.lyngio.net.LyngNetEngine
|
||||||
|
import net.sergeych.lyngio.net.LyngTcpSocket
|
||||||
|
import net.sergeych.lyngio.net.getSystemNetEngine
|
||||||
|
import net.sergeych.mp_tools.encodeToBase64
|
||||||
|
import kotlin.random.Random
|
||||||
|
|
||||||
|
internal fun createSocketWsEngine(
|
||||||
|
secureFallback: LyngWsEngine = UnsupportedLyngWsEngine,
|
||||||
|
): LyngWsEngine = SocketLyngWsEngine(getSystemNetEngine(), secureFallback)
|
||||||
|
|
||||||
|
private class SocketLyngWsEngine(
|
||||||
|
private val netEngine: LyngNetEngine,
|
||||||
|
private val secureFallback: LyngWsEngine,
|
||||||
|
) : LyngWsEngine {
|
||||||
|
override val isSupported: Boolean
|
||||||
|
get() = (netEngine.isSupported && netEngine.isTcpAvailable) || secureFallback.isSupported
|
||||||
|
|
||||||
|
override suspend fun connect(url: String, headers: Map<String, String>): LyngWsSession {
|
||||||
|
val parsedUrl = Url(url)
|
||||||
|
return when (parsedUrl.protocol.name.lowercase()) {
|
||||||
|
URLProtocol.WS.name.lowercase() -> connectPlain(parsedUrl, headers)
|
||||||
|
URLProtocol.WSS.name.lowercase() -> secureFallback.connect(url, headers)
|
||||||
|
else -> throw UnsupportedOperationException("Unsupported websocket scheme: ${parsedUrl.protocol.name}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun connectPlain(url: Url, headers: Map<String, String>): LyngWsSession {
|
||||||
|
if (!netEngine.isSupported || !netEngine.isTcpAvailable) {
|
||||||
|
throw UnsupportedOperationException("WebSocket client is not supported on this runtime")
|
||||||
|
}
|
||||||
|
val socket = netEngine.tcpConnect(url.host, url.port, timeoutMillis = null, noDelay = true)
|
||||||
|
try {
|
||||||
|
val key = randomBytes(16).encodeToBase64()
|
||||||
|
val requestPath = buildRequestPath(url)
|
||||||
|
val hostHeader = buildHostHeader(url)
|
||||||
|
val request = buildString {
|
||||||
|
append("GET ").append(requestPath).append(" HTTP/1.1\r\n")
|
||||||
|
append("Host: ").append(hostHeader).append("\r\n")
|
||||||
|
append("Upgrade: websocket\r\n")
|
||||||
|
append("Connection: Upgrade\r\n")
|
||||||
|
append("Sec-WebSocket-Key: ").append(key).append("\r\n")
|
||||||
|
append("Sec-WebSocket-Version: 13\r\n")
|
||||||
|
headers.forEach { (name, value) ->
|
||||||
|
append(name).append(": ").append(value).append("\r\n")
|
||||||
|
}
|
||||||
|
append("\r\n")
|
||||||
|
}
|
||||||
|
socket.writeUtf8(request)
|
||||||
|
socket.flush()
|
||||||
|
validateHandshake(socket, key)
|
||||||
|
return SocketLyngWsSession(url.toString(), socket)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
socket.close()
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class SocketLyngWsSession(
|
||||||
|
private val targetUrl: String,
|
||||||
|
private val socket: LyngTcpSocket,
|
||||||
|
) : LyngWsSession {
|
||||||
|
private var closed = false
|
||||||
|
private var closeSent = false
|
||||||
|
private var pending = ByteArray(0)
|
||||||
|
private var fragmentedOpcode: Int? = null
|
||||||
|
private var fragmentedPayload = ByteArray(0)
|
||||||
|
|
||||||
|
override fun isOpen(): Boolean = !closed && socket.isOpen()
|
||||||
|
|
||||||
|
override fun url(): String = targetUrl
|
||||||
|
|
||||||
|
override suspend fun sendText(text: String) {
|
||||||
|
ensureOpen()
|
||||||
|
sendFrame(OPCODE_TEXT, text.encodeToByteArray())
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun sendBytes(data: ByteArray) {
|
||||||
|
ensureOpen()
|
||||||
|
sendFrame(OPCODE_BINARY, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun receive(): LyngWsMessage? {
|
||||||
|
if (closed) return null
|
||||||
|
while (true) {
|
||||||
|
val frame = readFrame() ?: run {
|
||||||
|
release()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
when (frame.opcode) {
|
||||||
|
OPCODE_CONTINUATION -> {
|
||||||
|
val opcode = fragmentedOpcode ?: throw IllegalStateException("unexpected websocket continuation frame")
|
||||||
|
fragmentedPayload += frame.payload
|
||||||
|
if (frame.fin) {
|
||||||
|
val payload = fragmentedPayload
|
||||||
|
fragmentedOpcode = null
|
||||||
|
fragmentedPayload = ByteArray(0)
|
||||||
|
return payload.toMessage(opcode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
OPCODE_TEXT, OPCODE_BINARY -> {
|
||||||
|
if (frame.fin) return frame.payload.toMessage(frame.opcode)
|
||||||
|
fragmentedOpcode = frame.opcode
|
||||||
|
fragmentedPayload = frame.payload
|
||||||
|
}
|
||||||
|
OPCODE_CLOSE -> {
|
||||||
|
if (!closeSent) {
|
||||||
|
sendFrame(OPCODE_CLOSE, frame.payload)
|
||||||
|
closeSent = true
|
||||||
|
}
|
||||||
|
release()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
OPCODE_PING -> sendFrame(OPCODE_PONG, frame.payload)
|
||||||
|
OPCODE_PONG -> Unit
|
||||||
|
else -> Unit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun close(code: Int, reason: String) {
|
||||||
|
if (closed) return
|
||||||
|
val reasonBytes = reason.encodeToByteArray()
|
||||||
|
val payload = ByteArray(reasonBytes.size + 2)
|
||||||
|
payload[0] = (code shr 8).toByte()
|
||||||
|
payload[1] = code.toByte()
|
||||||
|
reasonBytes.copyInto(payload, destinationOffset = 2)
|
||||||
|
try {
|
||||||
|
if (!closeSent) {
|
||||||
|
sendFrame(OPCODE_CLOSE, payload)
|
||||||
|
closeSent = true
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
release()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun sendFrame(opcode: Int, payload: ByteArray) {
|
||||||
|
ensureOpen()
|
||||||
|
val header = buildFrameHeader(opcode, payload.size, masked = true)
|
||||||
|
val mask = randomBytes(4)
|
||||||
|
val maskedPayload = payload.copyOf()
|
||||||
|
maskedPayload.indices.forEach { index ->
|
||||||
|
maskedPayload[index] = (maskedPayload[index].toInt() xor mask[index % mask.size].toInt()).toByte()
|
||||||
|
}
|
||||||
|
socket.write(header + mask + maskedPayload)
|
||||||
|
socket.flush()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readFrame(): WsFrame? {
|
||||||
|
val head = readExact(2) ?: return null
|
||||||
|
val fin = (head[0].toInt() and 0x80) != 0
|
||||||
|
val opcode = head[0].toInt() and 0x0f
|
||||||
|
val masked = (head[1].toInt() and 0x80) != 0
|
||||||
|
val payloadLength = when (val lengthCode = head[1].toInt() and 0x7f) {
|
||||||
|
126 -> {
|
||||||
|
val extended = readExact(2) ?: return null
|
||||||
|
((extended[0].toInt() and 0xff) shl 8) or (extended[1].toInt() and 0xff)
|
||||||
|
}
|
||||||
|
127 -> {
|
||||||
|
val extended = readExact(8) ?: return null
|
||||||
|
var acc = 0L
|
||||||
|
extended.forEach { byte ->
|
||||||
|
acc = (acc shl 8) or (byte.toInt() and 0xff).toLong()
|
||||||
|
}
|
||||||
|
require(acc <= Int.MAX_VALUE.toLong()) { "websocket frame is too large" }
|
||||||
|
acc.toInt()
|
||||||
|
}
|
||||||
|
else -> lengthCode
|
||||||
|
}
|
||||||
|
val mask = if (masked) readExact(4) ?: return null else null
|
||||||
|
val payload = if (payloadLength > 0) readExact(payloadLength) ?: return null else ByteArray(0)
|
||||||
|
if (mask != null) {
|
||||||
|
payload.indices.forEach { index ->
|
||||||
|
payload[index] = (payload[index].toInt() xor mask[index % mask.size].toInt()).toByte()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return WsFrame(fin = fin, opcode = opcode, payload = payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readExact(byteCount: Int): ByteArray? {
|
||||||
|
while (pending.size < byteCount) {
|
||||||
|
val chunk = socket.read(maxOf(4096, byteCount - pending.size)) ?: break
|
||||||
|
if (chunk.isEmpty()) break
|
||||||
|
pending += chunk
|
||||||
|
}
|
||||||
|
if (pending.size < byteCount) return null
|
||||||
|
val result = pending.copyOfRange(0, byteCount)
|
||||||
|
pending = pending.copyOfRange(byteCount, pending.size)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun release() {
|
||||||
|
if (closed) return
|
||||||
|
closed = true
|
||||||
|
socket.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ensureOpen() {
|
||||||
|
if (closed || !socket.isOpen()) throw IllegalStateException("websocket session is closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private data class WsFrame(
|
||||||
|
val fin: Boolean,
|
||||||
|
val opcode: Int,
|
||||||
|
val payload: ByteArray,
|
||||||
|
)
|
||||||
|
|
||||||
|
private suspend fun validateHandshake(socket: LyngTcpSocket, key: String) {
|
||||||
|
val statusLine = socket.readLine() ?: error("websocket handshake failed: missing response status")
|
||||||
|
require(statusLine.startsWith("HTTP/1.1 101") || statusLine.startsWith("HTTP/1.0 101")) {
|
||||||
|
"websocket handshake failed: $statusLine"
|
||||||
|
}
|
||||||
|
val headers = linkedMapOf<String, String>()
|
||||||
|
while (true) {
|
||||||
|
val line = socket.readLine() ?: error("websocket handshake failed: unexpected EOF")
|
||||||
|
if (line.isBlank()) break
|
||||||
|
val colonAt = line.indexOf(':')
|
||||||
|
require(colonAt > 0) { "invalid websocket header: $line" }
|
||||||
|
val name = line.substring(0, colonAt).trim().lowercase()
|
||||||
|
val value = line.substring(colonAt + 1).trim()
|
||||||
|
headers[name] = value
|
||||||
|
}
|
||||||
|
require(headers["upgrade"]?.lowercase() == "websocket") { "websocket handshake failed: missing Upgrade header" }
|
||||||
|
require(headers["connection"]?.lowercase()?.contains("upgrade") == true) {
|
||||||
|
"websocket handshake failed: missing Connection header"
|
||||||
|
}
|
||||||
|
require(headers["sec-websocket-accept"] == websocketAcceptKey(key)) {
|
||||||
|
"websocket handshake failed: invalid Sec-WebSocket-Accept"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun websocketAcceptKey(key: String): String =
|
||||||
|
sha1((key + WS_GUID).encodeToByteArray()).encodeToBase64()
|
||||||
|
|
||||||
|
private fun buildRequestPath(url: Url): String {
|
||||||
|
val path = url.encodedPath.ifEmpty { "/" }
|
||||||
|
val query = url.encodedQuery
|
||||||
|
return if (query.isBlank()) path else "$path?$query"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildHostHeader(url: Url): String {
|
||||||
|
val host = if (':' in url.host && !url.host.startsWith("[")) "[${url.host}]" else url.host
|
||||||
|
return if (url.port == url.protocol.defaultPort) host else "$host:${url.port}"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildFrameHeader(opcode: Int, payloadSize: Int, masked: Boolean): ByteArray {
|
||||||
|
require(payloadSize >= 0) { "payload size must be non-negative" }
|
||||||
|
val firstByte = (0x80 or (opcode and 0x0f)).toByte()
|
||||||
|
val maskBit = if (masked) 0x80 else 0
|
||||||
|
return when {
|
||||||
|
payloadSize <= 125 -> byteArrayOf(firstByte, (maskBit or payloadSize).toByte())
|
||||||
|
payloadSize <= 0xffff -> byteArrayOf(
|
||||||
|
firstByte,
|
||||||
|
(maskBit or 126).toByte(),
|
||||||
|
((payloadSize ushr 8) and 0xff).toByte(),
|
||||||
|
(payloadSize and 0xff).toByte(),
|
||||||
|
)
|
||||||
|
else -> byteArrayOf(
|
||||||
|
firstByte,
|
||||||
|
(maskBit or 127).toByte(),
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
((payloadSize ushr 24) and 0xff).toByte(),
|
||||||
|
((payloadSize ushr 16) and 0xff).toByte(),
|
||||||
|
((payloadSize ushr 8) and 0xff).toByte(),
|
||||||
|
(payloadSize and 0xff).toByte(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ByteArray.toMessage(opcode: Int): LyngWsMessage = when (opcode) {
|
||||||
|
OPCODE_TEXT -> LyngWsMessage(isText = true, text = decodeToString())
|
||||||
|
OPCODE_BINARY -> LyngWsMessage(isText = false, data = copyOf())
|
||||||
|
else -> throw IllegalStateException("unsupported websocket opcode: $opcode")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun randomBytes(size: Int): ByteArray = ByteArray(size).also(Random.Default::nextBytes)
|
||||||
|
|
||||||
|
private fun sha1(input: ByteArray): ByteArray {
|
||||||
|
var h0 = 0x67452301
|
||||||
|
var h1 = 0xEFCDAB89.toInt()
|
||||||
|
var h2 = 0x98BADCFE.toInt()
|
||||||
|
var h3 = 0x10325476
|
||||||
|
var h4 = 0xC3D2E1F0.toInt()
|
||||||
|
|
||||||
|
val msgLen = input.size
|
||||||
|
val bitLen = msgLen.toLong() * 8L
|
||||||
|
val totalLen = ((msgLen + 1 + 8 + 63) / 64) * 64
|
||||||
|
val padded = ByteArray(totalLen).also { buf ->
|
||||||
|
input.copyInto(buf)
|
||||||
|
buf[msgLen] = 0x80.toByte()
|
||||||
|
for (i in 0..7) {
|
||||||
|
buf[totalLen - 8 + i] = ((bitLen ushr (56 - i * 8)) and 0xff).toByte()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val words = IntArray(80)
|
||||||
|
var blockStart = 0
|
||||||
|
while (blockStart < padded.size) {
|
||||||
|
for (i in 0..15) {
|
||||||
|
val off = blockStart + i * 4
|
||||||
|
words[i] = ((padded[off].toInt() and 0xff) shl 24) or
|
||||||
|
((padded[off + 1].toInt() and 0xff) shl 16) or
|
||||||
|
((padded[off + 2].toInt() and 0xff) shl 8) or
|
||||||
|
(padded[off + 3].toInt() and 0xff)
|
||||||
|
}
|
||||||
|
for (i in 16..79) {
|
||||||
|
val mixed = words[i - 3] xor words[i - 8] xor words[i - 14] xor words[i - 16]
|
||||||
|
words[i] = (mixed shl 1) or (mixed ushr 31)
|
||||||
|
}
|
||||||
|
|
||||||
|
var a = h0
|
||||||
|
var b = h1
|
||||||
|
var c = h2
|
||||||
|
var d = h3
|
||||||
|
var e = h4
|
||||||
|
|
||||||
|
for (i in 0..19) {
|
||||||
|
val f = (b and c) or (b.inv() and d)
|
||||||
|
val temp = ((a shl 5) or (a ushr 27)) + f + e + 0x5A827999 + words[i]
|
||||||
|
e = d
|
||||||
|
d = c
|
||||||
|
c = (b shl 30) or (b ushr 2)
|
||||||
|
b = a
|
||||||
|
a = temp
|
||||||
|
}
|
||||||
|
for (i in 20..39) {
|
||||||
|
val f = b xor c xor d
|
||||||
|
val temp = ((a shl 5) or (a ushr 27)) + f + e + 0x6ED9EBA1 + words[i]
|
||||||
|
e = d
|
||||||
|
d = c
|
||||||
|
c = (b shl 30) or (b ushr 2)
|
||||||
|
b = a
|
||||||
|
a = temp
|
||||||
|
}
|
||||||
|
for (i in 40..59) {
|
||||||
|
val f = (b and c) or (b and d) or (c and d)
|
||||||
|
val temp = ((a shl 5) or (a ushr 27)) + f + e + 0x8F1BBCDC.toInt() + words[i]
|
||||||
|
e = d
|
||||||
|
d = c
|
||||||
|
c = (b shl 30) or (b ushr 2)
|
||||||
|
b = a
|
||||||
|
a = temp
|
||||||
|
}
|
||||||
|
for (i in 60..79) {
|
||||||
|
val f = b xor c xor d
|
||||||
|
val temp = ((a shl 5) or (a ushr 27)) + f + e + 0xCA62C1D6.toInt() + words[i]
|
||||||
|
e = d
|
||||||
|
d = c
|
||||||
|
c = (b shl 30) or (b ushr 2)
|
||||||
|
b = a
|
||||||
|
a = temp
|
||||||
|
}
|
||||||
|
|
||||||
|
h0 += a
|
||||||
|
h1 += b
|
||||||
|
h2 += c
|
||||||
|
h3 += d
|
||||||
|
h4 += e
|
||||||
|
blockStart += 64
|
||||||
|
}
|
||||||
|
|
||||||
|
return ByteArray(20).also { out ->
|
||||||
|
fun putInt(offset: Int, value: Int) {
|
||||||
|
out[offset] = (value ushr 24).toByte()
|
||||||
|
out[offset + 1] = (value ushr 16).toByte()
|
||||||
|
out[offset + 2] = (value ushr 8).toByte()
|
||||||
|
out[offset + 3] = value.toByte()
|
||||||
|
}
|
||||||
|
putInt(0, h0)
|
||||||
|
putInt(4, h1)
|
||||||
|
putInt(8, h2)
|
||||||
|
putInt(12, h3)
|
||||||
|
putInt(16, h4)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||||
|
private const val OPCODE_CONTINUATION = 0x0
|
||||||
|
private const val OPCODE_TEXT = 0x1
|
||||||
|
private const val OPCODE_BINARY = 0x2
|
||||||
|
private const val OPCODE_CLOSE = 0x8
|
||||||
|
private const val OPCODE_PING = 0x9
|
||||||
|
private const val OPCODE_PONG = 0xA
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package net.sergeych.lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
|
import net.sergeych.lyng.obj.ObjException
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
|
||||||
|
internal actual suspend fun openJdbcBackend(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
options: JdbcOpenOptions,
|
||||||
|
): SqlDatabaseBackend {
|
||||||
|
scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
core.databaseException,
|
||||||
|
scope.requireScope(),
|
||||||
|
ObjString("lyng.io.db.jdbc is available only on the JVM target")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -18,15 +18,17 @@
|
|||||||
package net.sergeych.lyng.io.db.sqlite
|
package net.sergeych.lyng.io.db.sqlite
|
||||||
|
|
||||||
import net.sergeych.lyng.ScopeFacade
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
import net.sergeych.lyng.requireScope
|
import net.sergeych.lyng.requireScope
|
||||||
import net.sergeych.lyng.obj.ObjException
|
import net.sergeych.lyng.obj.ObjException
|
||||||
import net.sergeych.lyng.obj.ObjString
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
|
||||||
internal actual suspend fun openSqliteBackend(
|
internal actual suspend fun openSqliteBackend(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
options: SqliteOpenOptions,
|
options: SqliteOpenOptions,
|
||||||
): SqliteDatabaseBackend {
|
): SqlDatabaseBackend {
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjException(
|
ObjException(
|
||||||
core.databaseException,
|
core.databaseException,
|
||||||
|
|||||||
@@ -0,0 +1,448 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import com.zaxxer.hikari.HikariConfig
|
||||||
|
import com.zaxxer.hikari.HikariDataSource
|
||||||
|
import kotlinx.datetime.LocalDate
|
||||||
|
import kotlinx.datetime.LocalDateTime
|
||||||
|
import kotlinx.datetime.TimeZone
|
||||||
|
import kotlinx.datetime.toInstant
|
||||||
|
import net.sergeych.lyng.ExecutionError
|
||||||
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.*
|
||||||
|
import net.sergeych.lyng.obj.*
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
import java.math.BigDecimal
|
||||||
|
import java.sql.*
|
||||||
|
import kotlin.time.Instant
|
||||||
|
|
||||||
|
private val knownJdbcDrivers = listOf(
|
||||||
|
"org.sqlite.JDBC",
|
||||||
|
"org.h2.Driver",
|
||||||
|
"org.postgresql.Driver",
|
||||||
|
)
|
||||||
|
|
||||||
|
internal actual suspend fun openJdbcBackend(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
options: JdbcOpenOptions,
|
||||||
|
): SqlDatabaseBackend {
|
||||||
|
ensureJdbcDriversLoaded(scope, core, options.driverClass)
|
||||||
|
val dataSource = try {
|
||||||
|
val config = HikariConfig().apply {
|
||||||
|
jdbcUrl = options.connectionUrl
|
||||||
|
options.user?.let { username = it }
|
||||||
|
options.password?.let { password = it }
|
||||||
|
options.driverClass?.let { driverClassName = it }
|
||||||
|
options.properties.forEach { (key, value) -> addDataSourceProperty(key, value) }
|
||||||
|
// Statement caching: avoids re-parsing identical SQL on every call
|
||||||
|
addDataSourceProperty("cachePrepStmts", "true")
|
||||||
|
addDataSourceProperty("prepStmtCacheSize", "250")
|
||||||
|
addDataSourceProperty("prepStmtCacheSqlLimit", "2048")
|
||||||
|
// Connections from the pool are already in autoCommit=false territory;
|
||||||
|
// we manage commits explicitly in transaction().
|
||||||
|
isAutoCommit = false
|
||||||
|
}
|
||||||
|
HikariDataSource(config)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
val cause = e.cause as? SQLException ?: (e as? SQLException)
|
||||||
|
if (cause != null) throw mapOpenException(scope, core, cause)
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
return JdbcDatabaseBackend(core, dataSource)
|
||||||
|
}
|
||||||
|
|
||||||
|
private class JdbcDatabaseBackend(
|
||||||
|
private val core: SqlCoreModule,
|
||||||
|
private val dataSource: HikariDataSource,
|
||||||
|
) : SqlDatabaseBackend {
|
||||||
|
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T {
|
||||||
|
val connection = try {
|
||||||
|
dataSource.connection
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapOpenException(scope, core, e)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
val tx = JdbcTransactionBackend(core, connection)
|
||||||
|
val result = try {
|
||||||
|
block(tx)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
throw finishFailedTransaction(scope, core, e) {
|
||||||
|
rollbackOrThrow(scope, core, connection)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
connection.commit()
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlException(scope, core, e)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
connection.close() // returns connection to pool
|
||||||
|
} catch (_: SQLException) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun close() {
|
||||||
|
dataSource.close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private class JdbcTransactionBackend(
|
||||||
|
private val core: SqlCoreModule,
|
||||||
|
private val connection: Connection,
|
||||||
|
) : SqlTransactionBackend {
|
||||||
|
override suspend fun select(scope: ScopeFacade, clause: String, params: List<Obj>): SqlResultSetData {
|
||||||
|
try {
|
||||||
|
connection.prepareStatement(clause).use { statement ->
|
||||||
|
bindParams(statement, params, scope, core)
|
||||||
|
statement.executeQuery().use { rs ->
|
||||||
|
return readResultSet(scope, core, rs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlException(scope, core, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun execute(scope: ScopeFacade, clause: String, params: List<Obj>): SqlExecutionResultData {
|
||||||
|
if (containsRowReturningClause(clause)) {
|
||||||
|
scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
core.sqlUsageException,
|
||||||
|
scope.requireScope(),
|
||||||
|
ObjString("execute(...) cannot be used with statements that return rows; use select(...)")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
connection.prepareStatement(clause, Statement.RETURN_GENERATED_KEYS).use { statement ->
|
||||||
|
bindParams(statement, params, scope, core)
|
||||||
|
val hasResultSet = statement.execute()
|
||||||
|
if (hasResultSet) {
|
||||||
|
scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
core.sqlUsageException,
|
||||||
|
scope.requireScope(),
|
||||||
|
ObjString("execute(...) cannot be used with statements that return rows; use select(...)")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val generatedKeys = statement.generatedKeys.use { rs ->
|
||||||
|
if (rs == null) emptyResultSet() else readResultSet(scope, core, rs)
|
||||||
|
}
|
||||||
|
return SqlExecutionResultData(statement.updateCount, generatedKeys)
|
||||||
|
}
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlException(scope, core, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T {
|
||||||
|
val savepoint = try {
|
||||||
|
connection.setSavepoint()
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlUsage(scope, core, "Nested transactions are not supported by this JDBC backend", e)
|
||||||
|
}
|
||||||
|
val nested = JdbcTransactionBackend(core, connection)
|
||||||
|
val result = try {
|
||||||
|
block(nested)
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
throw finishFailedTransaction(scope, core, e) {
|
||||||
|
rollbackToSavepointOrThrow(scope, core, connection, savepoint)
|
||||||
|
releaseSavepointOrThrow(scope, core, connection, savepoint)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
connection.releaseSavepoint(savepoint)
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlException(scope, core, e)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun bindParams(statement: PreparedStatement, params: List<Obj>, scope: ScopeFacade, core: SqlCoreModule) {
|
||||||
|
params.forEachIndexed { index, value ->
|
||||||
|
val jdbcIndex = index + 1
|
||||||
|
when (value) {
|
||||||
|
ObjNull -> statement.setObject(jdbcIndex, null)
|
||||||
|
is ObjBool -> statement.setBoolean(jdbcIndex, value.value)
|
||||||
|
is ObjInt -> statement.setLong(jdbcIndex, value.value)
|
||||||
|
is ObjReal -> statement.setDouble(jdbcIndex, value.value)
|
||||||
|
is ObjString -> statement.setString(jdbcIndex, value.value)
|
||||||
|
is ObjBuffer -> statement.setBytes(jdbcIndex, value.byteArray.toByteArray())
|
||||||
|
is ObjDate -> statement.setObject(jdbcIndex, java.time.LocalDate.parse(value.date.toString()))
|
||||||
|
is ObjDateTime -> statement.setObject(jdbcIndex, java.time.LocalDateTime.parse(value.localDateTime.toString()))
|
||||||
|
is ObjInstant -> statement.setObject(jdbcIndex, java.time.Instant.parse(value.instant.toString()))
|
||||||
|
else -> when (value.objClass.className) {
|
||||||
|
"Decimal" -> statement.setBigDecimal(jdbcIndex, BigDecimal(scope.toStringOf(value).value))
|
||||||
|
else -> scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
core.sqlUsageException,
|
||||||
|
scope.requireScope(),
|
||||||
|
ObjString("Unsupported JDBC parameter type: ${value.objClass.className}")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readResultSet(scope: ScopeFacade, core: SqlCoreModule, resultSet: ResultSet): SqlResultSetData {
|
||||||
|
val meta = resultSet.metaData
|
||||||
|
val columns = (1..meta.columnCount).map { index ->
|
||||||
|
val nativeType = meta.getColumnTypeName(index) ?: ""
|
||||||
|
SqlColumnMeta(
|
||||||
|
name = meta.getColumnLabel(index),
|
||||||
|
sqlType = mapSqlType(core, nativeType, meta.getColumnType(index)),
|
||||||
|
nullable = meta.isNullable(index) != java.sql.ResultSetMetaData.columnNoNulls,
|
||||||
|
nativeType = nativeType,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val rows = mutableListOf<List<Obj>>()
|
||||||
|
while (resultSet.next()) {
|
||||||
|
rows += columns.mapIndexed { index, column ->
|
||||||
|
readColumnValue(scope, core, resultSet, index + 1, column.nativeType)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SqlResultSetData(columns, rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readColumnValue(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
resultSet: ResultSet,
|
||||||
|
index: Int,
|
||||||
|
nativeType: String,
|
||||||
|
): Obj {
|
||||||
|
val value = resultSet.getObject(index) ?: return ObjNull
|
||||||
|
val normalizedNativeType = normalizeDeclaredTypeName(nativeType)
|
||||||
|
return when (value) {
|
||||||
|
is Boolean -> ObjBool(value)
|
||||||
|
is Byte, is Short, is Int -> ObjInt.of((value as Number).toLong())
|
||||||
|
is Long -> ObjInt.of(value)
|
||||||
|
is Float, is Double -> ObjReal.of((value as Number).toDouble())
|
||||||
|
is java.math.BigInteger -> ObjInt.of(value.longValueExact())
|
||||||
|
is BigDecimal -> decimalFromString(scope, value.toPlainString())
|
||||||
|
is ByteArray -> ObjBuffer(value.toUByteArray())
|
||||||
|
is java.sql.Date -> ObjDate(LocalDate.parse(value.toLocalDate().toString()))
|
||||||
|
is java.sql.Timestamp -> timestampValue(scope, normalizedNativeType, value.toInstant())
|
||||||
|
is java.time.LocalDate -> ObjDate(LocalDate.parse(value.toString()))
|
||||||
|
is java.time.LocalDateTime -> ObjDateTime(value.toString().let(LocalDateTime::parse).toInstant(TimeZone.UTC), TimeZone.UTC)
|
||||||
|
is java.time.OffsetDateTime -> ObjInstant(Instant.parse(value.toInstant().toString()))
|
||||||
|
is java.time.ZonedDateTime -> ObjInstant(Instant.parse(value.toInstant().toString()))
|
||||||
|
is java.time.Instant -> ObjInstant(Instant.parse(value.toString()))
|
||||||
|
is java.sql.Time -> ObjString(value.toLocalTime().toString())
|
||||||
|
is java.time.LocalTime -> ObjString(value.toString())
|
||||||
|
is java.time.OffsetTime -> ObjString(value.toString())
|
||||||
|
is String -> stringValue(scope, normalizedNativeType, value)
|
||||||
|
else -> ObjString(value.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun stringValue(scope: ScopeFacade, normalizedNativeType: String, value: String): Obj {
|
||||||
|
return when {
|
||||||
|
normalizedNativeType == "DATE" -> ObjDate(LocalDate.parse(value.trim()))
|
||||||
|
normalizedNativeType == "TIMESTAMP WITH TIME ZONE" || normalizedNativeType == "TIMESTAMPTZ" ->
|
||||||
|
ObjInstant(Instant.parse(value.trim()))
|
||||||
|
normalizedNativeType == "TIMESTAMP" || normalizedNativeType == "DATETIME" ->
|
||||||
|
ObjDateTime(LocalDateTime.parse(value.trim()).toInstant(TimeZone.UTC), TimeZone.UTC)
|
||||||
|
normalizedNativeType == "DECIMAL" || normalizedNativeType == "NUMERIC" -> decimalFromString(scope, value.trim())
|
||||||
|
else -> ObjString(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun timestampValue(scope: ScopeFacade, normalizedNativeType: String, value: java.time.Instant): Obj {
|
||||||
|
return if (normalizedNativeType == "TIMESTAMP WITH TIME ZONE" || normalizedNativeType == "TIMESTAMPTZ") {
|
||||||
|
ObjInstant(Instant.parse(value.toString()))
|
||||||
|
} else {
|
||||||
|
val local = value.atOffset(java.time.ZoneOffset.UTC).toLocalDateTime().toString()
|
||||||
|
ObjDateTime(LocalDateTime.parse(local).toInstant(TimeZone.UTC), TimeZone.UTC)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun decimalFromString(scope: ScopeFacade, value: String): Obj {
|
||||||
|
val decimalModule = scope.requireScope().currentImportProvider.createModuleScope(scope.pos, "lyng.decimal")
|
||||||
|
val decimalClass = decimalModule.requireClass("Decimal")
|
||||||
|
return decimalClass.invokeInstanceMethod(scope.requireScope(), "fromString", ObjString(value))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun normalizeDeclaredTypeName(nativeTypeName: String): String {
|
||||||
|
val strippedSuffix = nativeTypeName.trim().replace(Regex("""\s*\(.*\)\s*$"""), "")
|
||||||
|
return strippedSuffix.uppercase().replace(Regex("""\s+"""), " ").trim()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mapSqlType(core: SqlCoreModule, nativeTypeName: String, jdbcType: Int): ObjEnumEntry {
|
||||||
|
val normalized = normalizeDeclaredTypeName(nativeTypeName)
|
||||||
|
return when {
|
||||||
|
normalized == "BOOLEAN" || normalized == "BOOL" -> core.sqlTypes.require("Bool")
|
||||||
|
normalized == "DATE" -> core.sqlTypes.require("Date")
|
||||||
|
normalized == "TIMESTAMP" || normalized == "DATETIME" -> core.sqlTypes.require("DateTime")
|
||||||
|
normalized == "TIMESTAMP WITH TIME ZONE" || normalized == "TIMESTAMPTZ" -> core.sqlTypes.require("Instant")
|
||||||
|
normalized == "TIME" || normalized == "TIME WITHOUT TIME ZONE" || normalized == "TIME WITH TIME ZONE" -> core.sqlTypes.require("String")
|
||||||
|
normalized == "DECIMAL" || normalized == "NUMERIC" -> core.sqlTypes.require("Decimal")
|
||||||
|
normalized.contains("BLOB") || normalized.contains("BINARY") || normalized == "BYTEA" -> core.sqlTypes.require("Binary")
|
||||||
|
normalized.contains("INT") -> core.sqlTypes.require("Int")
|
||||||
|
normalized.contains("CHAR") || normalized.contains("TEXT") || normalized.contains("CLOB") || normalized == "VARCHAR" -> core.sqlTypes.require("String")
|
||||||
|
normalized.contains("REAL") || normalized.contains("FLOA") || normalized.contains("DOUB") -> core.sqlTypes.require("Double")
|
||||||
|
jdbcType == java.sql.Types.BOOLEAN || jdbcType == java.sql.Types.BIT -> core.sqlTypes.require("Bool")
|
||||||
|
jdbcType == java.sql.Types.DATE -> core.sqlTypes.require("Date")
|
||||||
|
jdbcType == java.sql.Types.TIMESTAMP -> core.sqlTypes.require("DateTime")
|
||||||
|
jdbcType == java.sql.Types.TIMESTAMP_WITH_TIMEZONE -> core.sqlTypes.require("Instant")
|
||||||
|
jdbcType == java.sql.Types.TIME || jdbcType == java.sql.Types.TIME_WITH_TIMEZONE -> core.sqlTypes.require("String")
|
||||||
|
jdbcType == java.sql.Types.BLOB || jdbcType == java.sql.Types.BINARY || jdbcType == java.sql.Types.VARBINARY || jdbcType == java.sql.Types.LONGVARBINARY -> core.sqlTypes.require("Binary")
|
||||||
|
jdbcType == java.sql.Types.INTEGER || jdbcType == java.sql.Types.BIGINT || jdbcType == java.sql.Types.SMALLINT || jdbcType == java.sql.Types.TINYINT -> core.sqlTypes.require("Int")
|
||||||
|
jdbcType == java.sql.Types.DECIMAL || jdbcType == java.sql.Types.NUMERIC -> core.sqlTypes.require("Decimal")
|
||||||
|
jdbcType == java.sql.Types.FLOAT || jdbcType == java.sql.Types.REAL || jdbcType == java.sql.Types.DOUBLE -> core.sqlTypes.require("Double")
|
||||||
|
else -> core.sqlTypes.require("String")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun emptyResultSet(): SqlResultSetData = SqlResultSetData(emptyList(), emptyList())
|
||||||
|
|
||||||
|
private fun containsRowReturningClause(clause: String): Boolean =
|
||||||
|
Regex("""\b(returning|output)\b""", RegexOption.IGNORE_CASE).containsMatchIn(clause)
|
||||||
|
|
||||||
|
private fun ensureJdbcDriversLoaded(scope: ScopeFacade, core: SqlCoreModule, requestedDriverClass: String?) {
|
||||||
|
for (driverClass in knownJdbcDrivers) {
|
||||||
|
try {
|
||||||
|
Class.forName(driverClass)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val explicit = requestedDriverClass ?: return
|
||||||
|
try {
|
||||||
|
Class.forName(explicit)
|
||||||
|
} catch (e: ClassNotFoundException) {
|
||||||
|
throw ExecutionError(
|
||||||
|
ObjException(core.databaseException, scope.requireScope(), ObjString("JDBC driver class not found: $explicit")),
|
||||||
|
scope.pos,
|
||||||
|
"JDBC driver class not found: $explicit",
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rollbackOrThrow(scope: ScopeFacade, core: SqlCoreModule, connection: Connection) {
|
||||||
|
try {
|
||||||
|
connection.rollback()
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlException(scope, core, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun rollbackToSavepointOrThrow(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
connection: Connection,
|
||||||
|
savepoint: java.sql.Savepoint,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
connection.rollback(savepoint)
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlException(scope, core, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun releaseSavepointOrThrow(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
connection: Connection,
|
||||||
|
savepoint: java.sql.Savepoint,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
connection.releaseSavepoint(savepoint)
|
||||||
|
} catch (e: SQLException) {
|
||||||
|
throw mapSqlException(scope, core, e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private inline fun finishFailedTransaction(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
failure: Throwable,
|
||||||
|
rollback: () -> Unit,
|
||||||
|
): Throwable {
|
||||||
|
return try {
|
||||||
|
rollback()
|
||||||
|
failure
|
||||||
|
} catch (rollbackFailure: Throwable) {
|
||||||
|
if (isRollbackSignal(failure, core)) {
|
||||||
|
attachSecondaryFailure(rollbackFailure, failure)
|
||||||
|
rollbackFailure
|
||||||
|
} else {
|
||||||
|
attachSecondaryFailure(failure, rollbackFailure)
|
||||||
|
failure
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isRollbackSignal(failure: Throwable, core: SqlCoreModule): Boolean {
|
||||||
|
val errorObject = (failure as? ExecutionError)?.errorObject ?: return false
|
||||||
|
return errorObject.isInstanceOf(core.rollbackException)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun attachSecondaryFailure(primary: Throwable, secondary: Throwable) {
|
||||||
|
if (primary === secondary) return
|
||||||
|
primary.addSuppressed(secondary)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mapOpenException(scope: ScopeFacade, core: SqlCoreModule, e: SQLException): Nothing {
|
||||||
|
val message = e.message ?: "JDBC open failed"
|
||||||
|
if (e is SQLNonTransientConnectionException) {
|
||||||
|
throw ExecutionError(
|
||||||
|
ObjException(core.databaseException, scope.requireScope(), ObjString(message)),
|
||||||
|
scope.pos,
|
||||||
|
message,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
throw ExecutionError(
|
||||||
|
ObjException(core.databaseException, scope.requireScope(), ObjString(message)),
|
||||||
|
scope.pos,
|
||||||
|
message,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mapSqlException(scope: ScopeFacade, core: SqlCoreModule, e: SQLException): ExecutionError {
|
||||||
|
val exceptionClass = when {
|
||||||
|
e is SQLIntegrityConstraintViolationException -> core.sqlConstraintException
|
||||||
|
e.sqlState?.startsWith("23") == true -> core.sqlConstraintException
|
||||||
|
else -> core.sqlExecutionException
|
||||||
|
}
|
||||||
|
return ExecutionError(
|
||||||
|
ObjException(exceptionClass, scope.requireScope(), ObjString(e.message ?: "JDBC error")),
|
||||||
|
scope.pos,
|
||||||
|
e.message ?: "JDBC error",
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mapSqlUsage(scope: ScopeFacade, core: SqlCoreModule, message: String, cause: Throwable? = null): ExecutionError {
|
||||||
|
return ExecutionError(
|
||||||
|
ObjException(core.sqlUsageException, scope.requireScope(), ObjString(message)),
|
||||||
|
scope.pos,
|
||||||
|
message,
|
||||||
|
cause,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -20,6 +20,12 @@ package net.sergeych.lyng.io.db.sqlite
|
|||||||
import net.sergeych.lyng.ExecutionError
|
import net.sergeych.lyng.ExecutionError
|
||||||
import net.sergeych.lyng.Arguments
|
import net.sergeych.lyng.Arguments
|
||||||
import net.sergeych.lyng.ScopeFacade
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlColumnMeta
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
|
import net.sergeych.lyng.io.db.SqlExecutionResultData
|
||||||
|
import net.sergeych.lyng.io.db.SqlResultSetData
|
||||||
|
import net.sergeych.lyng.io.db.SqlTransactionBackend
|
||||||
import net.sergeych.lyng.obj.Obj
|
import net.sergeych.lyng.obj.Obj
|
||||||
import net.sergeych.lyng.obj.ObjBool
|
import net.sergeych.lyng.obj.ObjBool
|
||||||
import net.sergeych.lyng.obj.ObjBuffer
|
import net.sergeych.lyng.obj.ObjBuffer
|
||||||
@@ -50,24 +56,24 @@ import kotlin.time.Instant
|
|||||||
|
|
||||||
internal actual suspend fun openSqliteBackend(
|
internal actual suspend fun openSqliteBackend(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
options: SqliteOpenOptions,
|
options: SqliteOpenOptions,
|
||||||
): SqliteDatabaseBackend {
|
): SqlDatabaseBackend {
|
||||||
if (options.busyTimeoutMillis < 0) {
|
if (options.busyTimeoutMillis < 0) {
|
||||||
scope.raiseIllegalArgument("busyTimeoutMillis must be >= 0")
|
scope.raiseIllegalArgument("busyTimeoutMillis must be >= 0")
|
||||||
}
|
}
|
||||||
return JdbcSqliteDatabaseBackend(core, options)
|
return JdbcSqlDatabaseBackend(core, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
private class JdbcSqliteDatabaseBackend(
|
private class JdbcSqlDatabaseBackend(
|
||||||
private val core: SqliteCoreModule,
|
private val core: SqlCoreModule,
|
||||||
private val options: SqliteOpenOptions,
|
private val options: SqliteOpenOptions,
|
||||||
) : SqliteDatabaseBackend {
|
) : SqlDatabaseBackend {
|
||||||
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqliteTransactionBackend) -> T): T {
|
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T {
|
||||||
val connection = openConnection(scope)
|
val connection = openConnection(scope)
|
||||||
try {
|
try {
|
||||||
connection.autoCommit = false
|
connection.autoCommit = false
|
||||||
val tx = JdbcSqliteTransactionBackend(core, connection)
|
val tx = JdbcSqlTransactionBackend(core, connection)
|
||||||
val result = try {
|
val result = try {
|
||||||
block(tx)
|
block(tx)
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
@@ -124,11 +130,11 @@ private class JdbcSqliteDatabaseBackend(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private class JdbcSqliteTransactionBackend(
|
private class JdbcSqlTransactionBackend(
|
||||||
private val core: SqliteCoreModule,
|
private val core: SqlCoreModule,
|
||||||
private val connection: Connection,
|
private val connection: Connection,
|
||||||
) : SqliteTransactionBackend {
|
) : SqlTransactionBackend {
|
||||||
override suspend fun select(scope: ScopeFacade, clause: String, params: List<Obj>): SqliteResultSetData {
|
override suspend fun select(scope: ScopeFacade, clause: String, params: List<Obj>): SqlResultSetData {
|
||||||
try {
|
try {
|
||||||
connection.prepareStatement(clause).use { statement ->
|
connection.prepareStatement(clause).use { statement ->
|
||||||
bindParams(statement, params, scope, core)
|
bindParams(statement, params, scope, core)
|
||||||
@@ -141,7 +147,7 @@ private class JdbcSqliteTransactionBackend(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun execute(scope: ScopeFacade, clause: String, params: List<Obj>): SqliteExecutionResultData {
|
override suspend fun execute(scope: ScopeFacade, clause: String, params: List<Obj>): SqlExecutionResultData {
|
||||||
if (containsRowReturningClause(clause)) {
|
if (containsRowReturningClause(clause)) {
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjException(
|
ObjException(
|
||||||
@@ -172,20 +178,20 @@ private class JdbcSqliteTransactionBackend(
|
|||||||
readResultSet(scope, core, rs)
|
readResultSet(scope, core, rs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return SqliteExecutionResultData(affected, generatedKeys)
|
return SqlExecutionResultData(affected, generatedKeys)
|
||||||
}
|
}
|
||||||
} catch (e: SQLException) {
|
} catch (e: SQLException) {
|
||||||
throw mapSqlException(scope, core, e)
|
throw mapSqlException(scope, core, e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqliteTransactionBackend) -> T): T {
|
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T {
|
||||||
val savepoint = try {
|
val savepoint = try {
|
||||||
connection.setSavepoint()
|
connection.setSavepoint()
|
||||||
} catch (e: SQLException) {
|
} catch (e: SQLException) {
|
||||||
throw mapSqlUsage(scope, core, "Nested transactions are not supported by this SQLite backend", e)
|
throw mapSqlUsage(scope, core, "Nested transactions are not supported by this SQLite backend", e)
|
||||||
}
|
}
|
||||||
val nested = JdbcSqliteTransactionBackend(core, connection)
|
val nested = JdbcSqlTransactionBackend(core, connection)
|
||||||
val result = try {
|
val result = try {
|
||||||
block(nested)
|
block(nested)
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
@@ -203,7 +209,7 @@ private class JdbcSqliteTransactionBackend(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun bindParams(statement: PreparedStatement, params: List<Obj>, scope: ScopeFacade, core: SqliteCoreModule) {
|
private suspend fun bindParams(statement: PreparedStatement, params: List<Obj>, scope: ScopeFacade, core: SqlCoreModule) {
|
||||||
params.forEachIndexed { index, value ->
|
params.forEachIndexed { index, value ->
|
||||||
val jdbcIndex = index + 1
|
val jdbcIndex = index + 1
|
||||||
when (value) {
|
when (value) {
|
||||||
@@ -231,12 +237,12 @@ private suspend fun bindParams(statement: PreparedStatement, params: List<Obj>,
|
|||||||
|
|
||||||
private suspend fun readResultSet(
|
private suspend fun readResultSet(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
resultSet: ResultSet,
|
resultSet: ResultSet,
|
||||||
): SqliteResultSetData {
|
): SqlResultSetData {
|
||||||
val meta = resultSet.metaData
|
val meta = resultSet.metaData
|
||||||
val columns = (1..meta.columnCount).map { index ->
|
val columns = (1..meta.columnCount).map { index ->
|
||||||
SqliteColumnMeta(
|
SqlColumnMeta(
|
||||||
name = meta.getColumnLabel(index),
|
name = meta.getColumnLabel(index),
|
||||||
sqlType = mapSqlType(core, meta.getColumnTypeName(index), meta.getColumnType(index)),
|
sqlType = mapSqlType(core, meta.getColumnTypeName(index), meta.getColumnType(index)),
|
||||||
nullable = meta.isNullable(index) != java.sql.ResultSetMetaData.columnNoNulls,
|
nullable = meta.isNullable(index) != java.sql.ResultSetMetaData.columnNoNulls,
|
||||||
@@ -249,12 +255,12 @@ private suspend fun readResultSet(
|
|||||||
readColumnValue(scope, core, resultSet, index + 1, column.nativeType)
|
readColumnValue(scope, core, resultSet, index + 1, column.nativeType)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return SqliteResultSetData(columns, rows)
|
return SqlResultSetData(columns, rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun readColumnValue(
|
private suspend fun readColumnValue(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
resultSet: ResultSet,
|
resultSet: ResultSet,
|
||||||
index: Int,
|
index: Int,
|
||||||
nativeType: String,
|
nativeType: String,
|
||||||
@@ -278,7 +284,7 @@ private suspend fun readColumnValue(
|
|||||||
|
|
||||||
private fun convertIntegerValue(
|
private fun convertIntegerValue(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
normalizedNativeType: String,
|
normalizedNativeType: String,
|
||||||
value: Long,
|
value: Long,
|
||||||
): Obj {
|
): Obj {
|
||||||
@@ -294,7 +300,7 @@ private fun convertIntegerValue(
|
|||||||
|
|
||||||
private suspend fun convertStringValue(
|
private suspend fun convertStringValue(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
normalizedNativeType: String,
|
normalizedNativeType: String,
|
||||||
value: String,
|
value: String,
|
||||||
): Obj {
|
): Obj {
|
||||||
@@ -317,7 +323,7 @@ private fun isDecimalNativeType(normalizedNativeType: String): Boolean =
|
|||||||
private fun isBooleanNativeType(normalizedNativeType: String): Boolean =
|
private fun isBooleanNativeType(normalizedNativeType: String): Boolean =
|
||||||
normalizedNativeType == "BOOLEAN" || normalizedNativeType == "BOOL"
|
normalizedNativeType == "BOOLEAN" || normalizedNativeType == "BOOL"
|
||||||
|
|
||||||
private fun booleanFromString(scope: ScopeFacade, core: SqliteCoreModule, value: String): Obj {
|
private fun booleanFromString(scope: ScopeFacade, core: SqlCoreModule, value: String): Obj {
|
||||||
return when (value.trim().lowercase()) {
|
return when (value.trim().lowercase()) {
|
||||||
"true", "t" -> ObjBool(true)
|
"true", "t" -> ObjBool(true)
|
||||||
"false", "f" -> ObjBool(false)
|
"false", "f" -> ObjBool(false)
|
||||||
@@ -331,7 +337,7 @@ private suspend fun decimalFromString(scope: ScopeFacade, value: String): Obj {
|
|||||||
return decimalClass.invokeInstanceMethod(scope.requireScope(), "fromString", ObjString(value))
|
return decimalClass.invokeInstanceMethod(scope.requireScope(), "fromString", ObjString(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun dateTimeFromString(scope: ScopeFacade, core: SqliteCoreModule, value: String): ObjDateTime {
|
private fun dateTimeFromString(scope: ScopeFacade, core: SqlCoreModule, value: String): ObjDateTime {
|
||||||
val trimmed = value.trim()
|
val trimmed = value.trim()
|
||||||
if (hasExplicitTimeZone(trimmed)) {
|
if (hasExplicitTimeZone(trimmed)) {
|
||||||
sqlExecutionFailure(scope, core, "SQLite TIMESTAMP/DATETIME value must not contain a timezone offset: $value")
|
sqlExecutionFailure(scope, core, "SQLite TIMESTAMP/DATETIME value must not contain a timezone offset: $value")
|
||||||
@@ -358,7 +364,7 @@ private fun normalizeDeclaredTypeName(nativeTypeName: String): String {
|
|||||||
return strippedSuffix.uppercase().replace(Regex("""\s+"""), " ").trim()
|
return strippedSuffix.uppercase().replace(Regex("""\s+"""), " ").trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun mapSqlType(core: SqliteCoreModule, nativeTypeName: String, jdbcType: Int): ObjEnumEntry {
|
private fun mapSqlType(core: SqlCoreModule, nativeTypeName: String, jdbcType: Int): ObjEnumEntry {
|
||||||
val normalized = normalizeDeclaredTypeName(nativeTypeName)
|
val normalized = normalizeDeclaredTypeName(nativeTypeName)
|
||||||
return when {
|
return when {
|
||||||
normalized == "BOOLEAN" || normalized == "BOOL" -> core.sqlTypes.require("Bool")
|
normalized == "BOOLEAN" || normalized == "BOOL" -> core.sqlTypes.require("Bool")
|
||||||
@@ -385,9 +391,9 @@ private fun mapSqlType(core: SqliteCoreModule, nativeTypeName: String, jdbcType:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun emptyResultSet(core: SqliteCoreModule): SqliteResultSetData = SqliteResultSetData(emptyList(), emptyList())
|
private fun emptyResultSet(core: SqlCoreModule): SqlResultSetData = SqlResultSetData(emptyList(), emptyList())
|
||||||
|
|
||||||
private fun sqlExecutionFailure(scope: ScopeFacade, core: SqliteCoreModule, message: String): Nothing {
|
private fun sqlExecutionFailure(scope: ScopeFacade, core: SqlCoreModule, message: String): Nothing {
|
||||||
throw ExecutionError(
|
throw ExecutionError(
|
||||||
ObjException(core.sqlExecutionException, scope.requireScope(), ObjString(message)),
|
ObjException(core.sqlExecutionException, scope.requireScope(), ObjString(message)),
|
||||||
scope.pos,
|
scope.pos,
|
||||||
@@ -395,7 +401,7 @@ private fun sqlExecutionFailure(scope: ScopeFacade, core: SqliteCoreModule, mess
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun rollbackOrThrow(scope: ScopeFacade, core: SqliteCoreModule, connection: Connection) {
|
private fun rollbackOrThrow(scope: ScopeFacade, core: SqlCoreModule, connection: Connection) {
|
||||||
try {
|
try {
|
||||||
connection.rollback()
|
connection.rollback()
|
||||||
} catch (e: SQLException) {
|
} catch (e: SQLException) {
|
||||||
@@ -405,7 +411,7 @@ private fun rollbackOrThrow(scope: ScopeFacade, core: SqliteCoreModule, connecti
|
|||||||
|
|
||||||
private fun rollbackToSavepointOrThrow(
|
private fun rollbackToSavepointOrThrow(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
connection: Connection,
|
connection: Connection,
|
||||||
savepoint: java.sql.Savepoint,
|
savepoint: java.sql.Savepoint,
|
||||||
) {
|
) {
|
||||||
@@ -418,7 +424,7 @@ private fun rollbackToSavepointOrThrow(
|
|||||||
|
|
||||||
private fun releaseSavepointOrThrow(
|
private fun releaseSavepointOrThrow(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
connection: Connection,
|
connection: Connection,
|
||||||
savepoint: java.sql.Savepoint,
|
savepoint: java.sql.Savepoint,
|
||||||
) {
|
) {
|
||||||
@@ -431,7 +437,7 @@ private fun releaseSavepointOrThrow(
|
|||||||
|
|
||||||
private inline fun finishFailedTransaction(
|
private inline fun finishFailedTransaction(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
failure: Throwable,
|
failure: Throwable,
|
||||||
rollback: () -> Unit,
|
rollback: () -> Unit,
|
||||||
): Throwable {
|
): Throwable {
|
||||||
@@ -449,7 +455,7 @@ private inline fun finishFailedTransaction(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isRollbackSignal(failure: Throwable, core: SqliteCoreModule): Boolean {
|
private fun isRollbackSignal(failure: Throwable, core: SqlCoreModule): Boolean {
|
||||||
val errorObject = (failure as? ExecutionError)?.errorObject ?: return false
|
val errorObject = (failure as? ExecutionError)?.errorObject ?: return false
|
||||||
return errorObject.isInstanceOf(core.rollbackException)
|
return errorObject.isInstanceOf(core.rollbackException)
|
||||||
}
|
}
|
||||||
@@ -459,7 +465,7 @@ private fun attachSecondaryFailure(primary: Throwable, secondary: Throwable) {
|
|||||||
primary.addSuppressed(secondary)
|
primary.addSuppressed(secondary)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun mapOpenException(scope: ScopeFacade, core: SqliteCoreModule, e: SQLException): Nothing {
|
private fun mapOpenException(scope: ScopeFacade, core: SqlCoreModule, e: SQLException): Nothing {
|
||||||
val message = e.message ?: "SQLite open failed"
|
val message = e.message ?: "SQLite open failed"
|
||||||
val lower = message.lowercase()
|
val lower = message.lowercase()
|
||||||
if ("malformed" in lower || "no such access mode" in lower || "invalid uri" in lower) {
|
if ("malformed" in lower || "no such access mode" in lower || "invalid uri" in lower) {
|
||||||
@@ -473,7 +479,7 @@ private fun mapOpenException(scope: ScopeFacade, core: SqliteCoreModule, e: SQLE
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun mapSqlException(scope: ScopeFacade, core: SqliteCoreModule, e: SQLException): ExecutionError {
|
private fun mapSqlException(scope: ScopeFacade, core: SqlCoreModule, e: SQLException): ExecutionError {
|
||||||
val code = SQLiteErrorCode.getErrorCode(e.errorCode)
|
val code = SQLiteErrorCode.getErrorCode(e.errorCode)
|
||||||
val exceptionClass = when (code) {
|
val exceptionClass = when (code) {
|
||||||
SQLiteErrorCode.SQLITE_CONSTRAINT,
|
SQLiteErrorCode.SQLITE_CONSTRAINT,
|
||||||
@@ -491,7 +497,7 @@ private fun mapSqlException(scope: ScopeFacade, core: SqliteCoreModule, e: SQLEx
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun mapSqlUsage(scope: ScopeFacade, core: SqliteCoreModule, message: String, cause: Throwable? = null): ExecutionError {
|
private fun mapSqlUsage(scope: ScopeFacade, core: SqlCoreModule, message: String, cause: Throwable? = null): ExecutionError {
|
||||||
return ExecutionError(
|
return ExecutionError(
|
||||||
ObjException(core.sqlUsageException, scope.requireScope(), ObjString(message)),
|
ObjException(core.sqlUsageException, scope.requireScope(), ObjString(message)),
|
||||||
scope.pos,
|
scope.pos,
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.lyng.Compiler
|
||||||
|
import net.sergeych.lyng.Pos
|
||||||
|
import net.sergeych.lyng.Script
|
||||||
|
import net.sergeych.lyng.Source
|
||||||
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjExternCallable
|
||||||
|
import net.sergeych.lyng.obj.ObjInt
|
||||||
|
import net.sergeych.lyng.obj.ObjMap
|
||||||
|
import net.sergeych.lyng.obj.ObjNull
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.obj.requiredArg
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class LyngJdbcModuleTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testTypedOpenH2ExecutesQueriesAndGeneratedKeys() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createJdbcModule(scope.importManager)
|
||||||
|
val jdbcModule = scope.importManager.createModuleScope(Pos.builtIn, "lyng.io.db.jdbc")
|
||||||
|
val db = jdbcModule.callFn("openH2", ObjString("mem:typed_h2_${System.nanoTime()};DB_CLOSE_DELAY=-1"))
|
||||||
|
|
||||||
|
val insertedId = db.invokeInstanceMethod(
|
||||||
|
scope,
|
||||||
|
"transaction",
|
||||||
|
ObjExternCallable.fromBridge {
|
||||||
|
val tx = requiredArg<Obj>(0)
|
||||||
|
tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"execute",
|
||||||
|
ObjString("create table person(id bigint auto_increment primary key, name varchar(120) not null)")
|
||||||
|
)
|
||||||
|
val result = tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"execute",
|
||||||
|
ObjString("insert into person(name) values(?)"),
|
||||||
|
ObjString("Ada")
|
||||||
|
)
|
||||||
|
val rows = result.invokeInstanceMethod(requireScope(), "getGeneratedKeys")
|
||||||
|
.invokeInstanceMethod(requireScope(), "toList")
|
||||||
|
rows.getAt(requireScope(), ObjInt.Zero).getAt(requireScope(), ObjInt.Zero)
|
||||||
|
}
|
||||||
|
) as ObjInt
|
||||||
|
|
||||||
|
assertEquals(1L, insertedId.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGenericOpenDatabaseUsesJdbcAndH2AliasProviders() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createJdbcModule(scope.importManager)
|
||||||
|
scope.importManager.createModuleScope(Pos.builtIn, "lyng.io.db.jdbc")
|
||||||
|
val dbModule = scope.importManager.createModuleScope(Pos.builtIn, "lyng.io.db")
|
||||||
|
|
||||||
|
val genericJdbcDb = dbModule.callFn(
|
||||||
|
"openDatabase",
|
||||||
|
ObjString("jdbc:h2:mem:generic_jdbc_${System.nanoTime()};DB_CLOSE_DELAY=-1"),
|
||||||
|
emptyMapObj()
|
||||||
|
)
|
||||||
|
val h2AliasDb = dbModule.callFn(
|
||||||
|
"openDatabase",
|
||||||
|
ObjString("h2:mem:generic_alias_${System.nanoTime()};DB_CLOSE_DELAY=-1"),
|
||||||
|
emptyMapObj()
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals(42L, scalarSelect(scope, genericJdbcDb, "select 42 as answer"))
|
||||||
|
assertEquals(7L, scalarSelect(scope, h2AliasDb, "select 7 as answer"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testImportedJdbcOpenersPreserveDeclaredReturnTypesForInference() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createJdbcModule(scope.importManager)
|
||||||
|
|
||||||
|
val code = """
|
||||||
|
import lyng.io.db
|
||||||
|
import lyng.io.db.jdbc
|
||||||
|
|
||||||
|
val h2db = openH2("mem:inference_demo;DB_CLOSE_DELAY=-1")
|
||||||
|
h2db.transaction { 1 }
|
||||||
|
|
||||||
|
val jdbcDb = openJdbc("jdbc:h2:mem:inference_demo_2;DB_CLOSE_DELAY=-1")
|
||||||
|
jdbcDb.transaction { 2 }
|
||||||
|
|
||||||
|
val genericDb = openDatabase("jdbc:h2:mem:inference_demo_3;DB_CLOSE_DELAY=-1", Map())
|
||||||
|
genericDb.transaction { 3 }
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val result = Compiler.compile(Source("<jdbc-inference>", code), scope.importManager).execute(scope) as ObjInt
|
||||||
|
assertEquals(3L, result.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMaterializedRowsListCanBeReturnedFromTransaction() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createJdbcModule(scope.importManager)
|
||||||
|
val jdbcModule = scope.importManager.createModuleScope(Pos.builtIn, "lyng.io.db.jdbc")
|
||||||
|
val db = jdbcModule.callFn("openH2", ObjString("mem:rows_return_${System.nanoTime()};DB_CLOSE_DELAY=-1"))
|
||||||
|
|
||||||
|
val rows = db.invokeInstanceMethod(
|
||||||
|
scope,
|
||||||
|
"transaction",
|
||||||
|
ObjExternCallable.fromBridge {
|
||||||
|
val tx = requiredArg<Obj>(0)
|
||||||
|
tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"execute",
|
||||||
|
ObjString("create table person(id bigint auto_increment primary key, name varchar(120) not null)")
|
||||||
|
)
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "execute", ObjString("insert into person(name) values(?)"), ObjString("Ada"))
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "execute", ObjString("insert into person(name) values(?)"), ObjString("Linus"))
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "select", ObjString("select name from person order by id"))
|
||||||
|
.invokeInstanceMethod(requireScope(), "toList")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("Ada", (rows.getAt(scope, ObjInt.Zero).getAt(scope, ObjString("name")) as ObjString).value)
|
||||||
|
assertEquals("Linus", (rows.getAt(scope, ObjInt.of(1)).getAt(scope, ObjString("name")) as ObjString).value)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun scalarSelect(scope: net.sergeych.lyng.Scope, db: Obj, sql: String): Long {
|
||||||
|
val result = db.invokeInstanceMethod(
|
||||||
|
scope,
|
||||||
|
"transaction",
|
||||||
|
ObjExternCallable.fromBridge {
|
||||||
|
val tx = requiredArg<Obj>(0)
|
||||||
|
val rows = tx.invokeInstanceMethod(requireScope(), "select", ObjString(sql))
|
||||||
|
.invokeInstanceMethod(requireScope(), "toList")
|
||||||
|
rows.getAt(requireScope(), ObjInt.Zero).getAt(requireScope(), ObjString("answer"))
|
||||||
|
}
|
||||||
|
) as ObjInt
|
||||||
|
return result.value
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun net.sergeych.lyng.ModuleScope.callFn(name: String, vararg args: Obj): Obj {
|
||||||
|
val callee = get(name)?.value ?: error("Missing $name in module")
|
||||||
|
return callee.invoke(this, ObjNull, *args)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun emptyMapObj(): Obj = ObjMap()
|
||||||
|
}
|
||||||
+123
@@ -0,0 +1,123 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.lyng.Pos
|
||||||
|
import net.sergeych.lyng.Script
|
||||||
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjExternCallable
|
||||||
|
import net.sergeych.lyng.obj.ObjInt
|
||||||
|
import net.sergeych.lyng.obj.ObjMap
|
||||||
|
import net.sergeych.lyng.obj.ObjNull
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.obj.requiredArg
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
import org.testcontainers.containers.PostgreSQLContainer
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
|
||||||
|
class LyngJdbcPostgresContainerTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testOpenPostgresAgainstContainer() = runTest {
|
||||||
|
PostgreSQLContainer("postgres:16-alpine").use { postgres ->
|
||||||
|
postgres.start()
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createJdbcModule(scope.importManager)
|
||||||
|
val jdbcModule = scope.importManager.createModuleScope(Pos.builtIn, "lyng.io.db.jdbc")
|
||||||
|
val db = jdbcModule.callFn(
|
||||||
|
"openPostgres",
|
||||||
|
ObjString(postgres.jdbcUrl),
|
||||||
|
ObjString(postgres.username),
|
||||||
|
ObjString(postgres.password)
|
||||||
|
)
|
||||||
|
|
||||||
|
val count = rowCount(scope, db, "people", "Ada", "Linus")
|
||||||
|
assertEquals(2L, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testGenericPostgresAliasAgainstContainer() = runTest {
|
||||||
|
PostgreSQLContainer("postgres:16-alpine").use { postgres ->
|
||||||
|
postgres.start()
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createJdbcModule(scope.importManager)
|
||||||
|
scope.importManager.createModuleScope(Pos.builtIn, "lyng.io.db.jdbc")
|
||||||
|
val dbModule = scope.importManager.createModuleScope(Pos.builtIn, "lyng.io.db")
|
||||||
|
val aliasUrl = postgres.jdbcUrl.removePrefix("jdbc:postgresql:")
|
||||||
|
val db = dbModule.callFn(
|
||||||
|
"openDatabase",
|
||||||
|
ObjString("postgres:$aliasUrl"),
|
||||||
|
mapOfStrings(
|
||||||
|
"user" to postgres.username,
|
||||||
|
"password" to postgres.password
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
val count = rowCount(scope, db, "pets", "Milo", "Otis", "Pixel")
|
||||||
|
assertEquals(3L, count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun rowCount(scope: net.sergeych.lyng.Scope, db: Obj, table: String, vararg names: String): Long {
|
||||||
|
val result = db.invokeInstanceMethod(
|
||||||
|
scope,
|
||||||
|
"transaction",
|
||||||
|
ObjExternCallable.fromBridge {
|
||||||
|
val tx = requiredArg<Obj>(0)
|
||||||
|
tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"execute",
|
||||||
|
ObjString("create table $table(id bigserial primary key, name text not null)")
|
||||||
|
)
|
||||||
|
for (name in names) {
|
||||||
|
tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"execute",
|
||||||
|
ObjString("insert into $table(name) values(?)"),
|
||||||
|
ObjString(name)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val rows = tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"select",
|
||||||
|
ObjString("select count(*) as count from $table")
|
||||||
|
).invokeInstanceMethod(requireScope(), "toList")
|
||||||
|
rows.getAt(requireScope(), ObjInt.Zero).getAt(requireScope(), ObjString("count"))
|
||||||
|
}
|
||||||
|
) as ObjInt
|
||||||
|
return result.value
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun mapOfStrings(vararg entries: Pair<String, String>): Obj {
|
||||||
|
val map = ObjMap()
|
||||||
|
for ((key, value) in entries) {
|
||||||
|
map.map[ObjString(key)] = ObjString(value)
|
||||||
|
}
|
||||||
|
return map
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun net.sergeych.lyng.ModuleScope.callFn(name: String, vararg args: Obj): Obj {
|
||||||
|
val callee = get(name)?.value ?: error("Missing $name in module")
|
||||||
|
return callee.invoke(this, ObjNull, *args)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -250,7 +250,7 @@ class LyngSqliteModuleTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testRowFailsAfterTransactionEnds() = runTest {
|
fun testMaterializedRowSurvivesAfterTransactionEnds() = runTest {
|
||||||
val scope = Script.newScope()
|
val scope = Script.newScope()
|
||||||
val db = openMemoryDb(scope)
|
val db = openMemoryDb(scope)
|
||||||
var leakedRow: Obj = ObjNull
|
var leakedRow: Obj = ObjNull
|
||||||
@@ -265,12 +265,34 @@ class LyngSqliteModuleTest {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
val error = assertFailsWith<ExecutionError> {
|
val answer = leakedRow.getAt(scope, ObjString("answer")) as ObjInt
|
||||||
leakedRow.getAt(scope, ObjString("answer"))
|
assertEquals(42L, answer.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
assertEquals("SqlUsageException", error.errorObject.objClass.className)
|
@Test
|
||||||
assertTrue(error.errorMessage.contains("transaction is active"), error.errorMessage)
|
fun testMaterializedRowsListCanBeReturnedFromTransaction() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val db = openMemoryDb(scope)
|
||||||
|
|
||||||
|
val rows = db.invokeInstanceMethod(
|
||||||
|
scope,
|
||||||
|
"transaction",
|
||||||
|
ObjExternCallable.fromBridge {
|
||||||
|
val tx = requiredArg<Obj>(0)
|
||||||
|
tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"execute",
|
||||||
|
ObjString("create table items(id integer primary key autoincrement, name text not null)")
|
||||||
|
)
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "execute", ObjString("insert into items(name) values(?)"), ObjString("alpha"))
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "execute", ObjString("insert into items(name) values(?)"), ObjString("beta"))
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "select", ObjString("select name from items order by id"))
|
||||||
|
.invokeInstanceMethod(requireScope(), "toList")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("alpha", stringValue(scope, rows.getAt(scope, ObjInt.Zero).getAt(scope, ObjString("name"))))
|
||||||
|
assertEquals("beta", stringValue(scope, rows.getAt(scope, ObjInt.of(1)).getAt(scope, ObjString("name"))))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -2,4 +2,5 @@ package net.sergeych.lyngio.ws
|
|||||||
|
|
||||||
import io.ktor.client.engine.curl.Curl
|
import io.ktor.client.engine.curl.Curl
|
||||||
|
|
||||||
actual fun getSystemWsEngine(): LyngWsEngine = createKtorWsEngine(Curl)
|
actual fun getSystemWsEngine(): LyngWsEngine =
|
||||||
|
createSocketWsEngine(secureFallback = createKtorWsEngine(Curl, shareClient = false))
|
||||||
+27
-5
@@ -186,7 +186,7 @@ class LyngSqliteModuleNativeTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testRowFailsAfterTransactionEnds() = runTest {
|
fun testMaterializedRowSurvivesAfterTransactionEnds() = runTest {
|
||||||
val scope = Script.newScope()
|
val scope = Script.newScope()
|
||||||
val db = openMemoryDb(scope)
|
val db = openMemoryDb(scope)
|
||||||
var leakedRow: Obj = ObjNull
|
var leakedRow: Obj = ObjNull
|
||||||
@@ -201,12 +201,34 @@ class LyngSqliteModuleNativeTest {
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
val error = assertFailsWith<ExecutionError> {
|
val answer = leakedRow.getAt(scope, ObjString("answer")) as ObjInt
|
||||||
leakedRow.getAt(scope, ObjString("answer"))
|
assertEquals(42L, answer.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
assertEquals("SqlUsageException", error.errorObject.objClass.className)
|
@Test
|
||||||
assertTrue(error.errorMessage.contains("transaction is active"), error.errorMessage)
|
fun testMaterializedRowsListCanBeReturnedFromTransaction() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val db = openMemoryDb(scope)
|
||||||
|
|
||||||
|
val rows = db.invokeInstanceMethod(
|
||||||
|
scope,
|
||||||
|
"transaction",
|
||||||
|
ObjExternCallable.fromBridge {
|
||||||
|
val tx = requiredArg<Obj>(0)
|
||||||
|
tx.invokeInstanceMethod(
|
||||||
|
requireScope(),
|
||||||
|
"execute",
|
||||||
|
ObjString("create table items(id integer primary key autoincrement, name text not null)")
|
||||||
|
)
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "execute", ObjString("insert into items(name) values(?)"), ObjString("alpha"))
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "execute", ObjString("insert into items(name) values(?)"), ObjString("beta"))
|
||||||
|
tx.invokeInstanceMethod(requireScope(), "select", ObjString("select name from items order by id"))
|
||||||
|
.invokeInstanceMethod(requireScope(), "toList")
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
assertEquals("alpha", stringValue(scope, rows.getAt(scope, ObjInt.Zero).getAt(scope, ObjString("name"))))
|
||||||
|
assertEquals("beta", stringValue(scope, rows.getAt(scope, ObjInt.of(1)).getAt(scope, ObjString("name"))))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package net.sergeych.lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
|
import net.sergeych.lyng.obj.ObjException
|
||||||
|
import net.sergeych.lyng.obj.ObjString
|
||||||
|
import net.sergeych.lyng.requireScope
|
||||||
|
|
||||||
|
internal actual suspend fun openJdbcBackend(
|
||||||
|
scope: ScopeFacade,
|
||||||
|
core: SqlCoreModule,
|
||||||
|
options: JdbcOpenOptions,
|
||||||
|
): SqlDatabaseBackend {
|
||||||
|
scope.raiseError(
|
||||||
|
ObjException(
|
||||||
|
core.databaseException,
|
||||||
|
scope.requireScope(),
|
||||||
|
ObjString("lyng.io.db.jdbc is available only on the JVM target")
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -41,6 +41,12 @@ import kotlinx.datetime.TimeZone
|
|||||||
import kotlinx.datetime.toInstant
|
import kotlinx.datetime.toInstant
|
||||||
import net.sergeych.lyng.ExecutionError
|
import net.sergeych.lyng.ExecutionError
|
||||||
import net.sergeych.lyng.ScopeFacade
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.io.db.SqlColumnMeta
|
||||||
|
import net.sergeych.lyng.io.db.SqlCoreModule
|
||||||
|
import net.sergeych.lyng.io.db.SqlDatabaseBackend
|
||||||
|
import net.sergeych.lyng.io.db.SqlExecutionResultData
|
||||||
|
import net.sergeych.lyng.io.db.SqlResultSetData
|
||||||
|
import net.sergeych.lyng.io.db.SqlTransactionBackend
|
||||||
import net.sergeych.lyng.io.db.sqlite.cinterop.SQLITE_BLOB
|
import net.sergeych.lyng.io.db.sqlite.cinterop.SQLITE_BLOB
|
||||||
import net.sergeych.lyng.io.db.sqlite.cinterop.SQLITE_CONSTRAINT
|
import net.sergeych.lyng.io.db.sqlite.cinterop.SQLITE_CONSTRAINT
|
||||||
import net.sergeych.lyng.io.db.sqlite.cinterop.SQLITE_DONE
|
import net.sergeych.lyng.io.db.sqlite.cinterop.SQLITE_DONE
|
||||||
@@ -100,25 +106,25 @@ import kotlin.time.Instant
|
|||||||
|
|
||||||
internal actual suspend fun openSqliteBackend(
|
internal actual suspend fun openSqliteBackend(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
options: SqliteOpenOptions,
|
options: SqliteOpenOptions,
|
||||||
): SqliteDatabaseBackend {
|
): SqlDatabaseBackend {
|
||||||
if (options.busyTimeoutMillis < 0) {
|
if (options.busyTimeoutMillis < 0) {
|
||||||
scope.raiseIllegalArgument("busyTimeoutMillis must be >= 0")
|
scope.raiseIllegalArgument("busyTimeoutMillis must be >= 0")
|
||||||
}
|
}
|
||||||
return NativeSqliteDatabaseBackend(core, options)
|
return NativeSqlDatabaseBackend(core, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
private class NativeSqliteDatabaseBackend(
|
private class NativeSqlDatabaseBackend(
|
||||||
private val core: SqliteCoreModule,
|
private val core: SqlCoreModule,
|
||||||
private val options: SqliteOpenOptions,
|
private val options: SqliteOpenOptions,
|
||||||
) : SqliteDatabaseBackend {
|
) : SqlDatabaseBackend {
|
||||||
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqliteTransactionBackend) -> T): T {
|
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T {
|
||||||
val handle = openHandle(scope, core, options)
|
val handle = openHandle(scope, core, options)
|
||||||
val savepoints = SavepointCounter()
|
val savepoints = SavepointCounter()
|
||||||
try {
|
try {
|
||||||
handle.execUnit(scope, core, "begin")
|
handle.execUnit(scope, core, "begin")
|
||||||
val tx = NativeSqliteTransactionBackend(core, handle, savepoints)
|
val tx = NativeSqlTransactionBackend(core, handle, savepoints)
|
||||||
val result = try {
|
val result = try {
|
||||||
block(tx)
|
block(tx)
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
@@ -134,23 +140,23 @@ private class NativeSqliteDatabaseBackend(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private class NativeSqliteTransactionBackend(
|
private class NativeSqlTransactionBackend(
|
||||||
private val core: SqliteCoreModule,
|
private val core: SqlCoreModule,
|
||||||
private val handle: NativeSqliteHandle,
|
private val handle: NativeSqliteHandle,
|
||||||
private val savepoints: SavepointCounter,
|
private val savepoints: SavepointCounter,
|
||||||
) : SqliteTransactionBackend {
|
) : SqlTransactionBackend {
|
||||||
override suspend fun select(scope: ScopeFacade, clause: String, params: List<Obj>): SqliteResultSetData {
|
override suspend fun select(scope: ScopeFacade, clause: String, params: List<Obj>): SqlResultSetData {
|
||||||
return handle.select(scope, core, clause, params)
|
return handle.select(scope, core, clause, params)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun execute(scope: ScopeFacade, clause: String, params: List<Obj>): SqliteExecutionResultData {
|
override suspend fun execute(scope: ScopeFacade, clause: String, params: List<Obj>): SqlExecutionResultData {
|
||||||
return handle.execute(scope, core, clause, params)
|
return handle.execute(scope, core, clause, params)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqliteTransactionBackend) -> T): T {
|
override suspend fun <T> transaction(scope: ScopeFacade, block: suspend (SqlTransactionBackend) -> T): T {
|
||||||
val savepoint = "lyng_sp_${savepoints.next()}"
|
val savepoint = "lyng_sp_${savepoints.next()}"
|
||||||
handle.execUnit(scope, core, "savepoint $savepoint")
|
handle.execUnit(scope, core, "savepoint $savepoint")
|
||||||
val nested = NativeSqliteTransactionBackend(core, handle, savepoints)
|
val nested = NativeSqlTransactionBackend(core, handle, savepoints)
|
||||||
val result = try {
|
val result = try {
|
||||||
block(nested)
|
block(nested)
|
||||||
} catch (e: Throwable) {
|
} catch (e: Throwable) {
|
||||||
@@ -178,10 +184,10 @@ private class NativeSqliteHandle(
|
|||||||
) {
|
) {
|
||||||
suspend fun select(
|
suspend fun select(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
clause: String,
|
clause: String,
|
||||||
params: List<Obj>,
|
params: List<Obj>,
|
||||||
): SqliteResultSetData = memScoped {
|
): SqlResultSetData = memScoped {
|
||||||
val stmt = prepare(scope, core, clause)
|
val stmt = prepare(scope, core, clause)
|
||||||
try {
|
try {
|
||||||
bindParams(scope, core, stmt, params, this)
|
bindParams(scope, core, stmt, params, this)
|
||||||
@@ -193,10 +199,10 @@ private class NativeSqliteHandle(
|
|||||||
|
|
||||||
suspend fun execute(
|
suspend fun execute(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
clause: String,
|
clause: String,
|
||||||
params: List<Obj>,
|
params: List<Obj>,
|
||||||
): SqliteExecutionResultData = memScoped {
|
): SqlExecutionResultData = memScoped {
|
||||||
if (containsRowReturningClause(clause)) {
|
if (containsRowReturningClause(clause)) {
|
||||||
raiseExecuteReturningUsage(scope, core)
|
raiseExecuteReturningUsage(scope, core)
|
||||||
}
|
}
|
||||||
@@ -207,7 +213,7 @@ private class NativeSqliteHandle(
|
|||||||
SQLITE_DONE -> {
|
SQLITE_DONE -> {
|
||||||
val affectedRows = sqlite3_changes(db)
|
val affectedRows = sqlite3_changes(db)
|
||||||
val generatedKeys = readGeneratedKeys(core, clause, affectedRows)
|
val generatedKeys = readGeneratedKeys(core, clause, affectedRows)
|
||||||
SqliteExecutionResultData(affectedRows, generatedKeys)
|
SqlExecutionResultData(affectedRows, generatedKeys)
|
||||||
}
|
}
|
||||||
SQLITE_ROW -> raiseExecuteReturningUsage(scope, core)
|
SQLITE_ROW -> raiseExecuteReturningUsage(scope, core)
|
||||||
else -> throw sqlError(scope, core, rc)
|
else -> throw sqlError(scope, core, rc)
|
||||||
@@ -218,7 +224,7 @@ private class NativeSqliteHandle(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun execUnit(scope: ScopeFacade, core: SqliteCoreModule, sql: String) {
|
fun execUnit(scope: ScopeFacade, core: SqlCoreModule, sql: String) {
|
||||||
memScoped {
|
memScoped {
|
||||||
val stmt = prepare(scope, core, sql)
|
val stmt = prepare(scope, core, sql)
|
||||||
try {
|
try {
|
||||||
@@ -236,13 +242,13 @@ private class NativeSqliteHandle(
|
|||||||
sqlite3_close_v2(db)
|
sqlite3_close_v2(db)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun MemScope.prepare(scope: ScopeFacade, core: SqliteCoreModule, sql: String): CPointer<sqlite3_stmt> {
|
private fun MemScope.prepare(scope: ScopeFacade, core: SqlCoreModule, sql: String): CPointer<sqlite3_stmt> {
|
||||||
return lyng_sqlite3_prepare(db, sql) ?: throw sqlError(scope, core, sqlite3_extended_errcode(db))
|
return lyng_sqlite3_prepare(db, sql) ?: throw sqlError(scope, core, sqlite3_extended_errcode(db))
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun bindParams(
|
private suspend fun bindParams(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
stmt: CPointer<sqlite3_stmt>,
|
stmt: CPointer<sqlite3_stmt>,
|
||||||
params: List<Obj>,
|
params: List<Obj>,
|
||||||
memScope: MemScope,
|
memScope: MemScope,
|
||||||
@@ -308,13 +314,13 @@ private class NativeSqliteHandle(
|
|||||||
|
|
||||||
private suspend fun readResultSet(
|
private suspend fun readResultSet(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
stmt: CPointer<sqlite3_stmt>,
|
stmt: CPointer<sqlite3_stmt>,
|
||||||
): SqliteResultSetData {
|
): SqlResultSetData {
|
||||||
val columnCount = sqlite3_column_count(stmt)
|
val columnCount = sqlite3_column_count(stmt)
|
||||||
val columns = (0 until columnCount).map { index ->
|
val columns = (0 until columnCount).map { index ->
|
||||||
val nativeType = sqlite3_column_decltype(stmt, index)?.toKString().orEmpty()
|
val nativeType = sqlite3_column_decltype(stmt, index)?.toKString().orEmpty()
|
||||||
SqliteColumnMeta(
|
SqlColumnMeta(
|
||||||
name = sqlite3_column_name(stmt, index)?.toKString().orEmpty(),
|
name = sqlite3_column_name(stmt, index)?.toKString().orEmpty(),
|
||||||
sqlType = mapSqlType(core, nativeType, SQLITE_NULL),
|
sqlType = mapSqlType(core, nativeType, SQLITE_NULL),
|
||||||
nullable = true,
|
nullable = true,
|
||||||
@@ -338,7 +344,7 @@ private class NativeSqliteHandle(
|
|||||||
}
|
}
|
||||||
rows += row
|
rows += row
|
||||||
}
|
}
|
||||||
SQLITE_DONE -> return SqliteResultSetData(columns, rows)
|
SQLITE_DONE -> return SqlResultSetData(columns, rows)
|
||||||
else -> throw sqlError(scope, core, rc)
|
else -> throw sqlError(scope, core, rc)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -346,7 +352,7 @@ private class NativeSqliteHandle(
|
|||||||
|
|
||||||
private suspend fun readColumnValue(
|
private suspend fun readColumnValue(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
stmt: CPointer<sqlite3_stmt>,
|
stmt: CPointer<sqlite3_stmt>,
|
||||||
index: Int,
|
index: Int,
|
||||||
nativeType: String,
|
nativeType: String,
|
||||||
@@ -383,7 +389,7 @@ private class NativeSqliteHandle(
|
|||||||
|
|
||||||
private suspend fun convertStringValue(
|
private suspend fun convertStringValue(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
normalizedNativeType: String,
|
normalizedNativeType: String,
|
||||||
value: String,
|
value: String,
|
||||||
): Obj {
|
): Obj {
|
||||||
@@ -401,16 +407,16 @@ private class NativeSqliteHandle(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun readGeneratedKeys(
|
private fun readGeneratedKeys(
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
clause: String,
|
clause: String,
|
||||||
affectedRows: Int,
|
affectedRows: Int,
|
||||||
): SqliteResultSetData {
|
): SqlResultSetData {
|
||||||
if (affectedRows <= 0 || !looksLikeInsert(clause)) {
|
if (affectedRows <= 0 || !looksLikeInsert(clause)) {
|
||||||
return emptyResultSet()
|
return emptyResultSet()
|
||||||
}
|
}
|
||||||
return SqliteResultSetData(
|
return SqlResultSetData(
|
||||||
columns = listOf(
|
columns = listOf(
|
||||||
SqliteColumnMeta(
|
SqlColumnMeta(
|
||||||
name = "generated_key",
|
name = "generated_key",
|
||||||
sqlType = core.sqlTypes.require("Int"),
|
sqlType = core.sqlTypes.require("Int"),
|
||||||
nullable = false,
|
nullable = false,
|
||||||
@@ -425,7 +431,7 @@ private class NativeSqliteHandle(
|
|||||||
return sqlite3_column_text(stmt, index)?.reinterpret<ByteVar>()?.toKString().orEmpty()
|
return sqlite3_column_text(stmt, index)?.reinterpret<ByteVar>()?.toKString().orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun sqlError(scope: ScopeFacade, core: SqliteCoreModule, rc: Int): ExecutionError {
|
private fun sqlError(scope: ScopeFacade, core: SqlCoreModule, rc: Int): ExecutionError {
|
||||||
val code = sqlite3_extended_errcode(db)
|
val code = sqlite3_extended_errcode(db)
|
||||||
val message = sqlite3_errmsg(db)?.toKString() ?: "SQLite error ($rc)"
|
val message = sqlite3_errmsg(db)?.toKString() ?: "SQLite error ($rc)"
|
||||||
val exceptionClass = if ((code and 0xff) == SQLITE_CONSTRAINT) core.sqlConstraintException else core.sqlExecutionException
|
val exceptionClass = if ((code and 0xff) == SQLITE_CONSTRAINT) core.sqlConstraintException else core.sqlExecutionException
|
||||||
@@ -439,7 +445,7 @@ private class NativeSqliteHandle(
|
|||||||
|
|
||||||
private fun openHandle(
|
private fun openHandle(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
options: SqliteOpenOptions,
|
options: SqliteOpenOptions,
|
||||||
): NativeSqliteHandle = memScoped {
|
): NativeSqliteHandle = memScoped {
|
||||||
val flags = buildOpenFlags(options)
|
val flags = buildOpenFlags(options)
|
||||||
@@ -488,9 +494,9 @@ private fun looksLikeInsert(clause: String): Boolean = clause.trimStart().starts
|
|||||||
|
|
||||||
private val SQLITE_TRANSIENT = (-1L).toCPointer<CFunction<(COpaquePointer?) -> Unit>>()
|
private val SQLITE_TRANSIENT = (-1L).toCPointer<CFunction<(COpaquePointer?) -> Unit>>()
|
||||||
|
|
||||||
private fun emptyResultSet(): SqliteResultSetData = SqliteResultSetData(emptyList(), emptyList())
|
private fun emptyResultSet(): SqlResultSetData = SqlResultSetData(emptyList(), emptyList())
|
||||||
|
|
||||||
private fun mapSqlType(core: SqliteCoreModule, nativeType: String, sqliteType: Int): ObjEnumEntry = when (val normalized = normalizeDeclaredTypeName(nativeType)) {
|
private fun mapSqlType(core: SqlCoreModule, nativeType: String, sqliteType: Int): ObjEnumEntry = when (val normalized = normalizeDeclaredTypeName(nativeType)) {
|
||||||
"BOOLEAN", "BOOL" -> core.sqlTypes.require("Bool")
|
"BOOLEAN", "BOOL" -> core.sqlTypes.require("Bool")
|
||||||
"DATE" -> core.sqlTypes.require("Date")
|
"DATE" -> core.sqlTypes.require("Date")
|
||||||
"DATETIME", "TIMESTAMP" -> core.sqlTypes.require("DateTime")
|
"DATETIME", "TIMESTAMP" -> core.sqlTypes.require("DateTime")
|
||||||
@@ -521,7 +527,7 @@ private suspend fun decimalFromString(scope: ScopeFacade, value: String): Obj {
|
|||||||
return decimalClass.invokeInstanceMethod(scope.requireScope(), "fromString", ObjString(value))
|
return decimalClass.invokeInstanceMethod(scope.requireScope(), "fromString", ObjString(value))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun dateTimeFromString(scope: ScopeFacade, core: SqliteCoreModule, value: String): ObjDateTime {
|
private fun dateTimeFromString(scope: ScopeFacade, core: SqlCoreModule, value: String): ObjDateTime {
|
||||||
val trimmed = value.trim()
|
val trimmed = value.trim()
|
||||||
if (hasExplicitTimeZone(trimmed)) {
|
if (hasExplicitTimeZone(trimmed)) {
|
||||||
throw sqlExecutionError(scope, core, "SQLite TIMESTAMP/DATETIME value must not contain a timezone offset: $value")
|
throw sqlExecutionError(scope, core, "SQLite TIMESTAMP/DATETIME value must not contain a timezone offset: $value")
|
||||||
@@ -540,7 +546,7 @@ private fun hasExplicitTimeZone(value: String): Boolean {
|
|||||||
return offsetStart > tIndex
|
return offsetStart > tIndex
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun raiseExecuteReturningUsage(scope: ScopeFacade, core: SqliteCoreModule): Nothing {
|
private fun raiseExecuteReturningUsage(scope: ScopeFacade, core: SqlCoreModule): Nothing {
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjException(
|
ObjException(
|
||||||
core.sqlUsageException,
|
core.sqlUsageException,
|
||||||
@@ -550,7 +556,7 @@ private fun raiseExecuteReturningUsage(scope: ScopeFacade, core: SqliteCoreModul
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun usageError(scope: ScopeFacade, core: SqliteCoreModule, message: String): ExecutionError {
|
private fun usageError(scope: ScopeFacade, core: SqlCoreModule, message: String): ExecutionError {
|
||||||
return ExecutionError(
|
return ExecutionError(
|
||||||
ObjException(core.sqlUsageException, scope.requireScope(), ObjString(message)),
|
ObjException(core.sqlUsageException, scope.requireScope(), ObjString(message)),
|
||||||
scope.pos,
|
scope.pos,
|
||||||
@@ -558,7 +564,7 @@ private fun usageError(scope: ScopeFacade, core: SqliteCoreModule, message: Stri
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun databaseError(scope: ScopeFacade, core: SqliteCoreModule, message: String): ExecutionError {
|
private fun databaseError(scope: ScopeFacade, core: SqlCoreModule, message: String): ExecutionError {
|
||||||
return ExecutionError(
|
return ExecutionError(
|
||||||
ObjException(core.databaseException, scope.requireScope(), ObjString(message)),
|
ObjException(core.databaseException, scope.requireScope(), ObjString(message)),
|
||||||
scope.pos,
|
scope.pos,
|
||||||
@@ -566,14 +572,14 @@ private fun databaseError(scope: ScopeFacade, core: SqliteCoreModule, message: S
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun integerToBool(scope: ScopeFacade, core: SqliteCoreModule, value: Long): Obj =
|
private fun integerToBool(scope: ScopeFacade, core: SqlCoreModule, value: Long): Obj =
|
||||||
when (value) {
|
when (value) {
|
||||||
0L -> ObjBool(false)
|
0L -> ObjBool(false)
|
||||||
1L -> ObjBool(true)
|
1L -> ObjBool(true)
|
||||||
else -> throw sqlExecutionError(scope, core, "Invalid SQLite boolean value: $value")
|
else -> throw sqlExecutionError(scope, core, "Invalid SQLite boolean value: $value")
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun stringToBool(scope: ScopeFacade, core: SqliteCoreModule, value: String): Obj =
|
private fun stringToBool(scope: ScopeFacade, core: SqlCoreModule, value: String): Obj =
|
||||||
when (value.trim().lowercase()) {
|
when (value.trim().lowercase()) {
|
||||||
"true", "t" -> ObjBool(true)
|
"true", "t" -> ObjBool(true)
|
||||||
"false", "f" -> ObjBool(false)
|
"false", "f" -> ObjBool(false)
|
||||||
@@ -585,7 +591,7 @@ private fun normalizeDeclaredTypeName(nativeTypeName: String): String {
|
|||||||
return strippedSuffix.uppercase().replace(Regex("""\s+"""), " ").trim()
|
return strippedSuffix.uppercase().replace(Regex("""\s+"""), " ").trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun sqlExecutionError(scope: ScopeFacade, core: SqliteCoreModule, message: String): ExecutionError {
|
private fun sqlExecutionError(scope: ScopeFacade, core: SqlCoreModule, message: String): ExecutionError {
|
||||||
return ExecutionError(
|
return ExecutionError(
|
||||||
ObjException(core.sqlExecutionException, scope.requireScope(), ObjString(message)),
|
ObjException(core.sqlExecutionException, scope.requireScope(), ObjString(message)),
|
||||||
scope.pos,
|
scope.pos,
|
||||||
@@ -595,7 +601,7 @@ private fun sqlExecutionError(scope: ScopeFacade, core: SqliteCoreModule, messag
|
|||||||
|
|
||||||
private inline fun finishFailedTransaction(
|
private inline fun finishFailedTransaction(
|
||||||
scope: ScopeFacade,
|
scope: ScopeFacade,
|
||||||
core: SqliteCoreModule,
|
core: SqlCoreModule,
|
||||||
failure: Throwable,
|
failure: Throwable,
|
||||||
rollback: () -> Unit,
|
rollback: () -> Unit,
|
||||||
): Throwable {
|
): Throwable {
|
||||||
@@ -613,7 +619,7 @@ private inline fun finishFailedTransaction(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isRollbackSignal(failure: Throwable, core: SqliteCoreModule): Boolean {
|
private fun isRollbackSignal(failure: Throwable, core: SqlCoreModule): Boolean {
|
||||||
val errorObject = (failure as? ExecutionError)?.errorObject ?: return false
|
val errorObject = (failure as? ExecutionError)?.errorObject ?: return false
|
||||||
return errorObject.isInstanceOf(core.rollbackException)
|
return errorObject.isInstanceOf(core.rollbackException)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,11 +44,11 @@ extern class SqlRow {
|
|||||||
- iteration to the end or canceled iteration should close the underlying
|
- iteration to the end or canceled iteration should close the underlying
|
||||||
resources automatically
|
resources automatically
|
||||||
- using the result set after its transaction ends is invalid
|
- using the result set after its transaction ends is invalid
|
||||||
- rows obtained from the result set are also invalid after the owning
|
- rows obtained from the result set stay usable after the owning
|
||||||
transaction ends, even if the implementation had already buffered them
|
transaction ends once they have been materialized
|
||||||
|
|
||||||
If user code wants row data to survive independently, it should copy the
|
Calling `toList()` while the transaction is active is the normal way to
|
||||||
values it needs into ordinary Lyng objects while the transaction is active.
|
detach rows for use after the transaction block returns.
|
||||||
*/
|
*/
|
||||||
extern class ResultSet : Iterable<SqlRow> {
|
extern class ResultSet : Iterable<SqlRow> {
|
||||||
/*
|
/*
|
||||||
@@ -84,7 +84,8 @@ extern class ExecutionResult {
|
|||||||
other result set.
|
other result set.
|
||||||
|
|
||||||
If the statement produced no generated values, the returned result set
|
If the statement produced no generated values, the returned result set
|
||||||
is empty.
|
is empty. Call `toList()` if generated-key rows must outlive the
|
||||||
|
transaction.
|
||||||
*/
|
*/
|
||||||
fun getGeneratedKeys(): ResultSet
|
fun getGeneratedKeys(): ResultSet
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package lyng.io.db.jdbc
|
||||||
|
|
||||||
|
import lyng.io.db
|
||||||
|
|
||||||
|
/*
|
||||||
|
Generic JDBC provider for `lyng.io.db` on the JVM target.
|
||||||
|
|
||||||
|
Importing this module registers:
|
||||||
|
- `jdbc:` for raw JDBC URLs such as `jdbc:h2:mem:test`
|
||||||
|
- `h2:` as a shorthand alias for `jdbc:h2:...`
|
||||||
|
- `postgres:` / `postgresql:` as shorthand aliases for `jdbc:postgresql:...`
|
||||||
|
|
||||||
|
The JVM artifact bundles and explicitly loads the SQLite, H2, and
|
||||||
|
PostgreSQL JDBC drivers, so `openJdbc(...)`, `openH2(...)`, and
|
||||||
|
`openPostgres(...)` work under the standard `jlyng` launcher without extra
|
||||||
|
classpath setup.
|
||||||
|
|
||||||
|
Supported `openDatabase(..., extraParams)` keys for JDBC:
|
||||||
|
- `driverClass: String`
|
||||||
|
- `user: String`
|
||||||
|
- `password: String`
|
||||||
|
- `properties: Map<String, Object?>`
|
||||||
|
|
||||||
|
The optional `properties` map is converted to JDBC connection properties by
|
||||||
|
stringifying each non-null value.
|
||||||
|
*/
|
||||||
|
extern fun openJdbc(
|
||||||
|
connectionUrl: String,
|
||||||
|
user: String? = null,
|
||||||
|
password: String? = null,
|
||||||
|
driverClass: String? = null,
|
||||||
|
properties: Map<String, Object?>? = null
|
||||||
|
): Database
|
||||||
|
|
||||||
|
/*
|
||||||
|
Open an H2 database. `connectionUrl` may be a full JDBC URL such as
|
||||||
|
`jdbc:h2:mem:test`, or the shorter H2-specific tail such as
|
||||||
|
`mem:test;DB_CLOSE_DELAY=-1`.
|
||||||
|
*/
|
||||||
|
extern fun openH2(
|
||||||
|
connectionUrl: String,
|
||||||
|
user: String? = null,
|
||||||
|
password: String? = null,
|
||||||
|
properties: Map<String, Object?>? = null
|
||||||
|
): Database
|
||||||
|
|
||||||
|
/*
|
||||||
|
Open a PostgreSQL database. `connectionUrl` may be a full JDBC URL such as
|
||||||
|
`jdbc:postgresql://localhost/app`, or the shorter provider tail such as
|
||||||
|
`//localhost/app`.
|
||||||
|
*/
|
||||||
|
extern fun openPostgres(
|
||||||
|
connectionUrl: String,
|
||||||
|
user: String? = null,
|
||||||
|
password: String? = null,
|
||||||
|
properties: Map<String, Object?>? = null
|
||||||
|
): Database
|
||||||
@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
|||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
group = "net.sergeych"
|
group = "net.sergeych"
|
||||||
version = "1.5.5-SNAPSHOT"
|
version = "1.5.5"
|
||||||
|
|
||||||
// Removed legacy buildscript classpath declarations; plugins are applied via the plugins DSL below
|
// Removed legacy buildscript classpath declarations; plugins are applied via the plugins DSL below
|
||||||
|
|
||||||
@@ -302,8 +302,6 @@ android {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
dependencies {
|
dependencies {
|
||||||
implementation(libs.firebase.crashlytics.buildtools)
|
|
||||||
implementation(libs.compiler)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
publishing {
|
publishing {
|
||||||
@@ -345,7 +343,6 @@ tasks.withType<org.gradle.api.tasks.testing.Test> {
|
|||||||
|
|
||||||
// Make the flag visible inside tests if they want to branch on it
|
// Make the flag visible inside tests if they want to branch on it
|
||||||
systemProperty("LYNG_BENCHMARKS", benchmarksEnabled.toString())
|
systemProperty("LYNG_BENCHMARKS", benchmarksEnabled.toString())
|
||||||
|
|
||||||
if (!benchmarksEnabled) {
|
if (!benchmarksEnabled) {
|
||||||
// Exclude all JVM tests whose class name ends with or contains BenchmarkTest
|
// Exclude all JVM tests whose class name ends with or contains BenchmarkTest
|
||||||
// This keeps CI fast and avoids noisy timing logs by default.
|
// This keeps CI fast and avoids noisy timing logs by default.
|
||||||
|
|||||||
@@ -434,6 +434,57 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun supportsFastFrameBinding(arguments: Arguments): Boolean {
|
||||||
|
if (arguments.named.isNotEmpty() || arguments.tailBlockMode) return false
|
||||||
|
return params.none { it.isEllipsis || it.defaultValue != null }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun assignToFrameFast(
|
||||||
|
scope: Scope,
|
||||||
|
arguments: Arguments = scope.args,
|
||||||
|
paramSlotPlan: Map<String, Int>,
|
||||||
|
frame: FrameAccess,
|
||||||
|
slotOffset: Int = 0
|
||||||
|
) {
|
||||||
|
if (!supportsFastFrameBinding(arguments)) {
|
||||||
|
scope.raiseIllegalState("fast frame binding is not supported for this call shape")
|
||||||
|
}
|
||||||
|
|
||||||
|
fun slotFor(name: String): Int {
|
||||||
|
val full = paramSlotPlan[name] ?: scope.raiseIllegalState("parameter slot for '$name' is missing")
|
||||||
|
val slot = full - slotOffset
|
||||||
|
if (slot < 0) scope.raiseIllegalState("parameter slot for '$name' is out of range")
|
||||||
|
return slot
|
||||||
|
}
|
||||||
|
|
||||||
|
fun assign(slot: Int, value: Obj) {
|
||||||
|
when (value) {
|
||||||
|
is net.sergeych.lyng.obj.ObjInt -> frame.setInt(slot, value.value)
|
||||||
|
is net.sergeych.lyng.obj.ObjReal -> frame.setReal(slot, value.value)
|
||||||
|
is net.sergeych.lyng.obj.ObjBool -> frame.setBool(slot, value.value)
|
||||||
|
else -> frame.setObj(slot, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (arguments.list.size > params.size) {
|
||||||
|
scope.raiseIllegalArgument("expected ${params.size} arguments, got ${arguments.list.size}")
|
||||||
|
}
|
||||||
|
if (arguments.list.size < params.size) {
|
||||||
|
for (i in arguments.list.size until params.size) {
|
||||||
|
val a = params[i]
|
||||||
|
if (!a.type.isNullable) {
|
||||||
|
scope.raiseIllegalArgument("expected ${params.size} arguments, got ${arguments.list.size}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (i in params.indices) {
|
||||||
|
val slot = slotFor(params[i].name)
|
||||||
|
val value = if (i < arguments.list.size) arguments.list[i] else ObjNull
|
||||||
|
assign(slot, value.byValueCopy())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Single argument declaration descriptor.
|
* Single argument declaration descriptor.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -16,4 +16,12 @@
|
|||||||
|
|
||||||
package net.sergeych.lyng
|
package net.sergeych.lyng
|
||||||
|
|
||||||
interface BytecodeCallable
|
import net.sergeych.lyng.obj.Obj
|
||||||
|
|
||||||
|
interface BytecodeCallable {
|
||||||
|
fun callOnFast(scope: Scope): Obj? = null
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BytecodeArgCallable {
|
||||||
|
fun callWithArgsFast(scope: Scope, args: Arguments): Obj? = null
|
||||||
|
}
|
||||||
@@ -28,6 +28,7 @@ internal suspend fun executeBytecodeWithSeed(scope: Scope, stmt: Statement, labe
|
|||||||
else -> null
|
else -> null
|
||||||
} ?: scope.raiseIllegalState("$label requires bytecode statement")
|
} ?: scope.raiseIllegalState("$label requires bytecode statement")
|
||||||
scope.pos = bytecode.pos
|
scope.pos = bytecode.pos
|
||||||
|
bytecode.callOnFast(scope)?.let { return it }
|
||||||
return CmdVm().execute(bytecode.bytecodeFunction(), scope, scope.args) { frame, _ ->
|
return CmdVm().execute(bytecode.bytecodeFunction(), scope, scope.args) { frame, _ ->
|
||||||
seedFrameLocalsFromScope(frame, scope)
|
seedFrameLocalsFromScope(frame, scope)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,5 +20,30 @@ package net.sergeych.lyng
|
|||||||
* Compile-time call metadata for known functions. Used to select lambda receiver semantics.
|
* Compile-time call metadata for known functions. Used to select lambda receiver semantics.
|
||||||
*/
|
*/
|
||||||
data class CallSignature(
|
data class CallSignature(
|
||||||
val tailBlockReceiverType: String? = null
|
val tailBlockReceiverType: String? = null,
|
||||||
|
val inlineHigherOrder: HigherOrderInline? = null
|
||||||
|
) {
|
||||||
|
data class HigherOrderInline(
|
||||||
|
val kind: Kind,
|
||||||
|
val result: ResultMode,
|
||||||
|
val argCount: Int = 1,
|
||||||
|
val lambdaArgIndex: Int = 0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
enum class Kind {
|
||||||
|
UNARY_ARGUMENT,
|
||||||
|
RECEIVER,
|
||||||
|
ITERABLE,
|
||||||
|
MAP_GET_OR_PUT
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class ResultMode {
|
||||||
|
BLOCK_RESULT,
|
||||||
|
RETURN_RECEIVER,
|
||||||
|
FOR_EACH,
|
||||||
|
MAP,
|
||||||
|
FILTER,
|
||||||
|
MAP_NOT_NULL,
|
||||||
|
ASSOCIATE_BY
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
/*
|
/*
|
||||||
* Copyright 2025 Sergey S. Chernov real.sergeych@gmail.com
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
*
|
*
|
||||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
* you may not use this file except in compliance with the License.
|
* you may not use this file except in compliance with the License.
|
||||||
@@ -24,7 +24,10 @@ sealed class CodeContext {
|
|||||||
val implicitThisMembers: Boolean = false,
|
val implicitThisMembers: Boolean = false,
|
||||||
val implicitThisTypeName: String? = null,
|
val implicitThisTypeName: String? = null,
|
||||||
val typeParams: Set<String> = emptySet(),
|
val typeParams: Set<String> = emptySet(),
|
||||||
val typeParamDecls: List<TypeDecl.TypeParam> = emptyList()
|
val typeParamDecls: List<TypeDecl.TypeParam> = emptyList(),
|
||||||
|
/** True for static methods and top-level functions: they have no implicit `this`,
|
||||||
|
* so class-body field initializers inside them should not inherit the class name. */
|
||||||
|
val noImplicitThis: Boolean = false
|
||||||
): CodeContext()
|
): CodeContext()
|
||||||
class ClassBody(val name: String, val isExtern: Boolean = false): CodeContext() {
|
class ClassBody(val name: String, val isExtern: Boolean = false): CodeContext() {
|
||||||
var typeParams: Set<String> = emptySet()
|
var typeParams: Set<String> = emptySet()
|
||||||
|
|||||||
@@ -187,7 +187,9 @@ class Compiler(
|
|||||||
private val callableReturnTypeByScopeId: MutableMap<Int, MutableMap<Int, ObjClass>> = mutableMapOf()
|
private val callableReturnTypeByScopeId: MutableMap<Int, MutableMap<Int, ObjClass>> = mutableMapOf()
|
||||||
private val callableReturnTypeByName: MutableMap<String, ObjClass> = mutableMapOf()
|
private val callableReturnTypeByName: MutableMap<String, ObjClass> = mutableMapOf()
|
||||||
private val callableReturnTypeDeclByName: MutableMap<String, TypeDecl> = mutableMapOf()
|
private val callableReturnTypeDeclByName: MutableMap<String, TypeDecl> = mutableMapOf()
|
||||||
|
private val callSignatureByName: MutableMap<String, CallSignature> = mutableMapOf()
|
||||||
private val lambdaReturnTypeByRef: MutableMap<ObjRef, ObjClass> = mutableMapOf()
|
private val lambdaReturnTypeByRef: MutableMap<ObjRef, ObjClass> = mutableMapOf()
|
||||||
|
private val exactLambdaRefByScopeId: MutableMap<Int, MutableMap<Int, LambdaFnRef>> = mutableMapOf()
|
||||||
private val lambdaCaptureEntriesByRef: MutableMap<ValueFnRef, List<net.sergeych.lyng.bytecode.LambdaCaptureEntry>> =
|
private val lambdaCaptureEntriesByRef: MutableMap<ValueFnRef, List<net.sergeych.lyng.bytecode.LambdaCaptureEntry>> =
|
||||||
mutableMapOf()
|
mutableMapOf()
|
||||||
private val classFieldTypesByName: MutableMap<String, MutableMap<String, ObjClass>> = mutableMapOf()
|
private val classFieldTypesByName: MutableMap<String, MutableMap<String, ObjClass>> = mutableMapOf()
|
||||||
@@ -264,6 +266,11 @@ class Compiler(
|
|||||||
if (plan.slots.containsKey(name)) continue
|
if (plan.slots.containsKey(name)) continue
|
||||||
declareSlotNameIn(plan, name, record.isMutable, record.type == ObjRecord.Type.Delegated)
|
declareSlotNameIn(plan, name, record.isMutable, record.type == ObjRecord.Type.Delegated)
|
||||||
scopeSeedNames.add(name)
|
scopeSeedNames.add(name)
|
||||||
|
record.callSignature?.let { signature ->
|
||||||
|
if (!callSignatureByName.containsKey(name)) {
|
||||||
|
callSignatureByName[name] = signature
|
||||||
|
}
|
||||||
|
}
|
||||||
if (record.typeDecl != null && nameTypeDecl[name] == null) {
|
if (record.typeDecl != null && nameTypeDecl[name] == null) {
|
||||||
nameTypeDecl[name] = record.typeDecl
|
nameTypeDecl[name] = record.typeDecl
|
||||||
if (nameObjClass[name] == null) {
|
if (nameObjClass[name] == null) {
|
||||||
@@ -290,6 +297,11 @@ class Compiler(
|
|||||||
)
|
)
|
||||||
scopeSeedNames.add(getterName)
|
scopeSeedNames.add(getterName)
|
||||||
}
|
}
|
||||||
|
record.callSignature?.let { signature ->
|
||||||
|
if (!callSignatureByName.containsKey(getterName)) {
|
||||||
|
callSignatureByName[getterName] = signature
|
||||||
|
}
|
||||||
|
}
|
||||||
val prop = record.value as? ObjProperty
|
val prop = record.value as? ObjProperty
|
||||||
if (prop?.setter != null) {
|
if (prop?.setter != null) {
|
||||||
val setterName = extensionPropertySetterName(cls.className, name)
|
val setterName = extensionPropertySetterName(cls.className, name)
|
||||||
@@ -315,6 +327,11 @@ class Compiler(
|
|||||||
)
|
)
|
||||||
scopeSeedNames.add(callableName)
|
scopeSeedNames.add(callableName)
|
||||||
}
|
}
|
||||||
|
record.callSignature?.let { signature ->
|
||||||
|
if (!callSignatureByName.containsKey(callableName)) {
|
||||||
|
callSignatureByName[callableName] = signature
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -346,6 +363,11 @@ class Compiler(
|
|||||||
record.type == ObjRecord.Type.Delegated
|
record.type == ObjRecord.Type.Delegated
|
||||||
)
|
)
|
||||||
scopeSeedNames.add(name)
|
scopeSeedNames.add(name)
|
||||||
|
record.callSignature?.let { signature ->
|
||||||
|
if (!callSignatureByName.containsKey(name)) {
|
||||||
|
callSignatureByName[name] = signature
|
||||||
|
}
|
||||||
|
}
|
||||||
if (record.typeDecl != null && nameTypeDecl[name] == null) {
|
if (record.typeDecl != null && nameTypeDecl[name] == null) {
|
||||||
nameTypeDecl[name] = record.typeDecl
|
nameTypeDecl[name] = record.typeDecl
|
||||||
if (nameObjClass[name] == null) {
|
if (nameObjClass[name] == null) {
|
||||||
@@ -761,6 +783,29 @@ class Compiler(
|
|||||||
?: importManager.rootScope.getLocalRecordDirect(name)?.callSignature
|
?: importManager.rootScope.getLocalRecordDirect(name)?.callSignature
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun declaredCallSignature(name: String, extTypeName: String?, actualExtern: Boolean): CallSignature? {
|
||||||
|
val imported = if (actualExtern) {
|
||||||
|
importManager.rootScope.getLocalRecordDirect(name)?.callSignature
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
val inferred = when {
|
||||||
|
extTypeName == "Iterable" && name == "filter" -> CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.ITERABLE,
|
||||||
|
result = CallSignature.ResultMode.FILTER
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
return when {
|
||||||
|
imported == null -> inferred
|
||||||
|
inferred == null -> imported
|
||||||
|
imported.inlineHigherOrder != null -> imported
|
||||||
|
else -> imported.copy(inlineHigherOrder = inferred.inlineHigherOrder)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
internal data class MemberIds(val fieldId: Int?, val methodId: Int?)
|
internal data class MemberIds(val fieldId: Int?, val methodId: Int?)
|
||||||
|
|
||||||
private fun resolveMemberIds(name: String, pos: Pos, qualifier: String? = null): MemberIds {
|
private fun resolveMemberIds(name: String, pos: Pos, qualifier: String? = null): MemberIds {
|
||||||
@@ -812,8 +857,18 @@ class Compiler(
|
|||||||
|
|
||||||
private fun currentImplicitThisTypeName(): String? {
|
private fun currentImplicitThisTypeName(): String? {
|
||||||
for (ctx in codeContexts.asReversed()) {
|
for (ctx in codeContexts.asReversed()) {
|
||||||
val fn = ctx as? CodeContext.Function ?: continue
|
when (ctx) {
|
||||||
if (fn.implicitThisTypeName != null) return fn.implicitThisTypeName
|
is CodeContext.Function -> {
|
||||||
|
if (ctx.implicitThisTypeName != null) return ctx.implicitThisTypeName
|
||||||
|
// A static method or top-level function explicitly has no implicit `this`.
|
||||||
|
// Stop here — do not fall through to an enclosing ClassBody.
|
||||||
|
if (ctx.noImplicitThis) return null
|
||||||
|
}
|
||||||
|
// Class field initializers are compiled directly under ClassBody with no wrapping
|
||||||
|
// Function. Lambdas inside those initializers must still see `this` as the class.
|
||||||
|
is CodeContext.ClassBody -> return ctx.name
|
||||||
|
else -> {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
@@ -1418,6 +1473,11 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun seedImportTypeMetadata(name: String, record: ObjRecord) {
|
private fun seedImportTypeMetadata(name: String, record: ObjRecord) {
|
||||||
|
record.callSignature?.let { signature ->
|
||||||
|
if (!callSignatureByName.containsKey(name)) {
|
||||||
|
callSignatureByName[name] = signature
|
||||||
|
}
|
||||||
|
}
|
||||||
if (record.typeDecl != null && nameTypeDecl[name] == null) {
|
if (record.typeDecl != null && nameTypeDecl[name] == null) {
|
||||||
nameTypeDecl[name] = record.typeDecl
|
nameTypeDecl[name] = record.typeDecl
|
||||||
}
|
}
|
||||||
@@ -1884,14 +1944,16 @@ class Compiler(
|
|||||||
forcedLocalSlotInfo = forcedLocalInfo,
|
forcedLocalSlotInfo = forcedLocalInfo,
|
||||||
forcedLocalScopeId = forcedLocalScopeId,
|
forcedLocalScopeId = forcedLocalScopeId,
|
||||||
slotTypeByScopeId = slotTypeByScopeId,
|
slotTypeByScopeId = slotTypeByScopeId,
|
||||||
|
exactLambdaRefByScopeId = exactLambdaRefByScopeId,
|
||||||
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
||||||
knownNameObjClass = knownClassMapForBytecode(),
|
knownNameObjClass = knownClassMapForBytecode(),
|
||||||
knownClassNames = knownClassNamesForBytecode(),
|
knownClassNames = knownClassNamesForBytecode(),
|
||||||
knownObjectNames = objectDeclNames,
|
knownObjectNames = knownObjectNamesForBytecode(),
|
||||||
classFieldTypesByName = classFieldTypesByName,
|
classFieldTypesByName = classFieldTypesByName,
|
||||||
enumEntriesByName = enumEntriesByName,
|
enumEntriesByName = enumEntriesByName,
|
||||||
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
||||||
callableReturnTypeByName = callableReturnTypeByName,
|
callableReturnTypeByName = callableReturnTypeByName,
|
||||||
|
callSignatureByName = callSignatureByName,
|
||||||
externBindingNames = externBindingNames,
|
externBindingNames = externBindingNames,
|
||||||
preparedModuleBindingNames = importBindings.keys,
|
preparedModuleBindingNames = importBindings.keys,
|
||||||
scopeRefPosByName = moduleReferencePosByName,
|
scopeRefPosByName = moduleReferencePosByName,
|
||||||
@@ -2086,12 +2148,19 @@ class Compiler(
|
|||||||
plan.captureOwners[name] = slotLoc
|
plan.captureOwners[name] = slotLoc
|
||||||
plan.captures += capture
|
plan.captures += capture
|
||||||
if (!plan.slotPlan.slots.containsKey(name)) {
|
if (!plan.slotPlan.slots.containsKey(name)) {
|
||||||
|
val newSlot = plan.slotPlan.nextIndex
|
||||||
plan.slotPlan.slots[name] = SlotEntry(
|
plan.slotPlan.slots[name] = SlotEntry(
|
||||||
plan.slotPlan.nextIndex,
|
newSlot,
|
||||||
isMutable = slotLoc.isMutable,
|
isMutable = slotLoc.isMutable,
|
||||||
isDelegated = slotLoc.isDelegated
|
isDelegated = slotLoc.isDelegated
|
||||||
)
|
)
|
||||||
plan.slotPlan.nextIndex += 1
|
plan.slotPlan.nextIndex += 1
|
||||||
|
slotTypeByScopeId[slotLoc.scopeId]?.get(slotLoc.slot)?.let { cls ->
|
||||||
|
slotTypeByScopeId.getOrPut(plan.slotPlan.id) { mutableMapOf() }[newSlot] = cls
|
||||||
|
}
|
||||||
|
slotTypeDeclByScopeId[slotLoc.scopeId]?.get(slotLoc.slot)?.let { decl ->
|
||||||
|
slotTypeDeclByScopeId.getOrPut(plan.slotPlan.id) { mutableMapOf() }[newSlot] = decl
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2208,6 +2277,23 @@ class Compiler(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun knownObjectNamesForBytecode(): Set<String> {
|
||||||
|
val result = LinkedHashSet<String>()
|
||||||
|
fun addScope(scope: Scope?) {
|
||||||
|
if (scope == null) return
|
||||||
|
for ((name, rec) in scope.objects) {
|
||||||
|
if (rec.value is ObjInstance) result.add(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addScope(seedScope)
|
||||||
|
addScope(importManager.rootScope)
|
||||||
|
for (module in importedModules) {
|
||||||
|
addScope(module.scope)
|
||||||
|
}
|
||||||
|
result.addAll(objectDeclNames)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
private fun wrapBytecode(stmt: Statement): Statement {
|
private fun wrapBytecode(stmt: Statement): Statement {
|
||||||
if (codeContexts.lastOrNull() is CodeContext.Module) return stmt
|
if (codeContexts.lastOrNull() is CodeContext.Module) return stmt
|
||||||
if (codeContexts.lastOrNull() is CodeContext.ClassBody) return stmt
|
if (codeContexts.lastOrNull() is CodeContext.ClassBody) return stmt
|
||||||
@@ -2232,14 +2318,16 @@ class Compiler(
|
|||||||
scopeSlotNameSet = scopeSlotNameSet,
|
scopeSlotNameSet = scopeSlotNameSet,
|
||||||
moduleScopeId = moduleScopeId,
|
moduleScopeId = moduleScopeId,
|
||||||
slotTypeByScopeId = slotTypeByScopeId,
|
slotTypeByScopeId = slotTypeByScopeId,
|
||||||
|
exactLambdaRefByScopeId = exactLambdaRefByScopeId,
|
||||||
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
||||||
knownNameObjClass = knownClassMapForBytecode(),
|
knownNameObjClass = knownClassMapForBytecode(),
|
||||||
knownClassNames = knownClassNamesForBytecode(),
|
knownClassNames = knownClassNamesForBytecode(),
|
||||||
knownObjectNames = objectDeclNames,
|
knownObjectNames = knownObjectNamesForBytecode(),
|
||||||
classFieldTypesByName = classFieldTypesByName,
|
classFieldTypesByName = classFieldTypesByName,
|
||||||
enumEntriesByName = enumEntriesByName,
|
enumEntriesByName = enumEntriesByName,
|
||||||
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
||||||
callableReturnTypeByName = callableReturnTypeByName,
|
callableReturnTypeByName = callableReturnTypeByName,
|
||||||
|
callSignatureByName = callSignatureByName,
|
||||||
externCallableNames = externCallableNames,
|
externCallableNames = externCallableNames,
|
||||||
externBindingNames = externBindingNames,
|
externBindingNames = externBindingNames,
|
||||||
preparedModuleBindingNames = importBindings.keys,
|
preparedModuleBindingNames = importBindings.keys,
|
||||||
@@ -2265,14 +2353,16 @@ class Compiler(
|
|||||||
scopeSlotNameSet = scopeSlotNameSet,
|
scopeSlotNameSet = scopeSlotNameSet,
|
||||||
moduleScopeId = moduleScopeId,
|
moduleScopeId = moduleScopeId,
|
||||||
slotTypeByScopeId = slotTypeByScopeId,
|
slotTypeByScopeId = slotTypeByScopeId,
|
||||||
|
exactLambdaRefByScopeId = exactLambdaRefByScopeId,
|
||||||
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
||||||
knownNameObjClass = knownClassMapForBytecode(),
|
knownNameObjClass = knownClassMapForBytecode(),
|
||||||
knownClassNames = knownClassNamesForBytecode(),
|
knownClassNames = knownClassNamesForBytecode(),
|
||||||
knownObjectNames = objectDeclNames,
|
knownObjectNames = knownObjectNamesForBytecode(),
|
||||||
classFieldTypesByName = classFieldTypesByName,
|
classFieldTypesByName = classFieldTypesByName,
|
||||||
enumEntriesByName = enumEntriesByName,
|
enumEntriesByName = enumEntriesByName,
|
||||||
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
||||||
callableReturnTypeByName = callableReturnTypeByName,
|
callableReturnTypeByName = callableReturnTypeByName,
|
||||||
|
callSignatureByName = callSignatureByName,
|
||||||
externCallableNames = externCallableNames,
|
externCallableNames = externCallableNames,
|
||||||
externBindingNames = externBindingNames,
|
externBindingNames = externBindingNames,
|
||||||
preparedModuleBindingNames = importBindings.keys,
|
preparedModuleBindingNames = importBindings.keys,
|
||||||
@@ -2323,14 +2413,16 @@ class Compiler(
|
|||||||
globalSlotInfo = globalSlotInfo,
|
globalSlotInfo = globalSlotInfo,
|
||||||
globalSlotScopeId = globalSlotScopeId,
|
globalSlotScopeId = globalSlotScopeId,
|
||||||
slotTypeByScopeId = slotTypeByScopeId,
|
slotTypeByScopeId = slotTypeByScopeId,
|
||||||
|
exactLambdaRefByScopeId = exactLambdaRefByScopeId,
|
||||||
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
||||||
knownNameObjClass = knownNames,
|
knownNameObjClass = knownNames,
|
||||||
knownClassNames = knownClassNamesForBytecode(),
|
knownClassNames = knownClassNamesForBytecode(),
|
||||||
knownObjectNames = objectDeclNames,
|
knownObjectNames = knownObjectNamesForBytecode(),
|
||||||
classFieldTypesByName = classFieldTypesByName,
|
classFieldTypesByName = classFieldTypesByName,
|
||||||
enumEntriesByName = enumEntriesByName,
|
enumEntriesByName = enumEntriesByName,
|
||||||
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
||||||
callableReturnTypeByName = callableReturnTypeByName,
|
callableReturnTypeByName = callableReturnTypeByName,
|
||||||
|
callSignatureByName = callSignatureByName,
|
||||||
externCallableNames = externCallableNames,
|
externCallableNames = externCallableNames,
|
||||||
externBindingNames = externBindingNames,
|
externBindingNames = externBindingNames,
|
||||||
preparedModuleBindingNames = importBindings.keys,
|
preparedModuleBindingNames = importBindings.keys,
|
||||||
@@ -3407,6 +3499,10 @@ class Compiler(
|
|||||||
index < expectedParams.size
|
index < expectedParams.size
|
||||||
) {
|
) {
|
||||||
expectedParams[index]
|
expectedParams[index]
|
||||||
|
} else if (param.type == TypeDecl.TypeAny && index == 0 && argsDeclaration.params.size == 1 &&
|
||||||
|
implicitItType != null
|
||||||
|
) {
|
||||||
|
implicitItType
|
||||||
} else {
|
} else {
|
||||||
param.type
|
param.type
|
||||||
}
|
}
|
||||||
@@ -3518,14 +3614,91 @@ class Compiler(
|
|||||||
body
|
body
|
||||||
}
|
}
|
||||||
val bytecodeFn = (fnStatements as? BytecodeStatement)?.bytecodeFunction()
|
val bytecodeFn = (fnStatements as? BytecodeStatement)?.bytecodeFunction()
|
||||||
|
val inlineBodyRef = argsDeclaration?.let { null } ?: extractInlineLambdaBodyRef(body)
|
||||||
|
val supportsDirectInvokeFastPath = bytecodeFn != null &&
|
||||||
|
bytecodeFn.scopeSlotCount == 0 &&
|
||||||
|
expectedReceiverType == null &&
|
||||||
|
!wrapAsExtensionCallable &&
|
||||||
|
!containsDelegatedRefs(body)
|
||||||
val ref = LambdaFnRef(
|
val ref = LambdaFnRef(
|
||||||
valueFn = { closureScope ->
|
valueFn = { closureScope ->
|
||||||
val captureRecords = closureScope.captureRecords
|
val captureRecords = closureScope.captureRecords
|
||||||
val stmt = object : Statement(), BytecodeBodyProvider {
|
val stmt = object : Statement(), BytecodeBodyProvider, BytecodeCallable {
|
||||||
override val pos: Pos = fnStatements.pos
|
override val pos: Pos = fnStatements.pos
|
||||||
|
|
||||||
override fun bytecodeBody(): BytecodeStatement? = fnStatements as? BytecodeStatement
|
override fun bytecodeBody(): BytecodeStatement? = fnStatements as? BytecodeStatement
|
||||||
|
|
||||||
|
override fun callOnFast(scope: Scope): Obj? {
|
||||||
|
val context = scope.applyClosureForBytecode(closureScope, preferredThisType = expectedReceiverType).also {
|
||||||
|
it.args = scope.args
|
||||||
|
}
|
||||||
|
if (captureSlots.isNotEmpty()) {
|
||||||
|
if (captureRecords != null) {
|
||||||
|
context.captureRecords = captureRecords
|
||||||
|
context.captureNames = captureSlots.map { it.name }
|
||||||
|
} else {
|
||||||
|
val resolvedRecords = ArrayList<ObjRecord>(captureSlots.size)
|
||||||
|
val resolvedNames = ArrayList<String>(captureSlots.size)
|
||||||
|
for (capture in captureSlots) {
|
||||||
|
val rec = resolveStableCaptureRecord(
|
||||||
|
closureScope,
|
||||||
|
capture.name,
|
||||||
|
context.currentClassCtx
|
||||||
|
) ?: closureScope.raiseSymbolNotFound("symbol ${capture.name} not found")
|
||||||
|
resolvedRecords.add(freezeImmutableCaptureRecord(rec))
|
||||||
|
resolvedNames.add(capture.name)
|
||||||
|
}
|
||||||
|
context.captureRecords = resolvedRecords
|
||||||
|
context.captureNames = resolvedNames
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val bytecodeBody = fnStatements as? BytecodeStatement ?: return null
|
||||||
|
val bytecodeFn = bytecodeBody.bytecodeFunction()
|
||||||
|
if (!supportsDirectInvokeFastPath || !bytecodeFn.fastOnly) return null
|
||||||
|
val fastPreboundNames = if (argsDeclaration == null) {
|
||||||
|
setOf("it")
|
||||||
|
} else {
|
||||||
|
argsDeclaration.params.mapTo(LinkedHashSet()) { it.name }
|
||||||
|
}
|
||||||
|
val declaredNames = bytecodeFn.constants
|
||||||
|
.mapNotNull { it as? BytecodeConst.LocalDecl }
|
||||||
|
.mapTo(mutableSetOf()) { it.name }
|
||||||
|
if (!canFastSeedUndeclaredLocals(bytecodeFn, declaredNames, fastPreboundNames)) return null
|
||||||
|
if (argsDeclaration != null && !argsDeclaration.supportsFastFrameBinding(scope.args)) return null
|
||||||
|
val slotPlan = bytecodeFn.localSlotPlanByName()
|
||||||
|
val binder: (net.sergeych.lyng.bytecode.CmdFrame, Arguments) -> Unit = { frame, arguments ->
|
||||||
|
if (argsDeclaration == null) {
|
||||||
|
val l = arguments.list
|
||||||
|
val itValue: Obj = when (l.size) {
|
||||||
|
0 -> ObjVoid
|
||||||
|
1 -> l[0]
|
||||||
|
else -> ObjList(l.toMutableList())
|
||||||
|
}
|
||||||
|
val itSlot = slotPlan["it"]
|
||||||
|
if (itSlot != null) {
|
||||||
|
when (itValue) {
|
||||||
|
is ObjInt -> frame.frame.setInt(itSlot, itValue.value)
|
||||||
|
is ObjReal -> frame.frame.setReal(itSlot, itValue.value)
|
||||||
|
is ObjBool -> frame.frame.setBool(itSlot, itValue.value)
|
||||||
|
else -> frame.frame.setObj(itSlot, itValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
argsDeclaration.assignToFrameFast(
|
||||||
|
context,
|
||||||
|
arguments,
|
||||||
|
slotPlan,
|
||||||
|
frame.frame
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
net.sergeych.lyng.bytecode.CmdVm().executeFastOnlyNoSuspend(bytecodeFn, context, scope.args, binder)
|
||||||
|
} catch (e: ReturnException) {
|
||||||
|
if (e.label == null || returnLabels.contains(e.label)) e.result else throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun execute(scope: Scope): Obj {
|
override suspend fun execute(scope: Scope): Obj {
|
||||||
val context = scope.applyClosureForBytecode(closureScope, preferredThisType = expectedReceiverType).also {
|
val context = scope.applyClosureForBytecode(closureScope, preferredThisType = expectedReceiverType).also {
|
||||||
it.args = scope.args
|
it.args = scope.args
|
||||||
@@ -3600,6 +3773,8 @@ class Compiler(
|
|||||||
argsDeclaration = argsDeclaration,
|
argsDeclaration = argsDeclaration,
|
||||||
captureEntries = captureEntries,
|
captureEntries = captureEntries,
|
||||||
inferredReturnClass = returnClass,
|
inferredReturnClass = returnClass,
|
||||||
|
inlineBodyRef = inlineBodyRef,
|
||||||
|
supportsDirectInvokeFastPath = supportsDirectInvokeFastPath,
|
||||||
preferredThisType = expectedReceiverType,
|
preferredThisType = expectedReceiverType,
|
||||||
wrapAsExtensionCallable = wrapAsExtensionCallable,
|
wrapAsExtensionCallable = wrapAsExtensionCallable,
|
||||||
returnLabels = returnLabels,
|
returnLabels = returnLabels,
|
||||||
@@ -3614,6 +3789,18 @@ class Compiler(
|
|||||||
return ref
|
return ref
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun extractInlineLambdaBodyRef(statement: Statement): ObjRef? {
|
||||||
|
val target = if (statement is BytecodeStatement) statement.original else statement
|
||||||
|
return when (target) {
|
||||||
|
is ExpressionStatement -> target.ref
|
||||||
|
is BlockStatement -> {
|
||||||
|
val statements = target.statements()
|
||||||
|
if (statements.size == 1) extractInlineLambdaBodyRef(statements[0]) else null
|
||||||
|
}
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private suspend fun parseArrayLiteral(): List<ListEntry> {
|
private suspend fun parseArrayLiteral(): List<ListEntry> {
|
||||||
// it should be called after Token.Type.LBRACKET is consumed
|
// it should be called after Token.Type.LBRACKET is consumed
|
||||||
val entries = mutableListOf<ListEntry>()
|
val entries = mutableListOf<ListEntry>()
|
||||||
@@ -4947,6 +5134,26 @@ class Compiler(
|
|||||||
?: slotTypeDeclByScopeId[slotLoc.scopeId]?.get(slotLoc.slot)?.let { resolveTypeDeclObjClass(it) }
|
?: slotTypeDeclByScopeId[slotLoc.scopeId]?.get(slotLoc.slot)?.let { resolveTypeDeclObjClass(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun lookupExactLambdaRefByName(name: String): LambdaFnRef? {
|
||||||
|
val slotLoc = lookupSlotLocation(name, includeModule = true) ?: return null
|
||||||
|
return exactLambdaRefByScopeId[slotLoc.scopeId]?.get(slotLoc.slot)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun resolveExactLambdaRef(ref: ObjRef?): LambdaFnRef? {
|
||||||
|
return when (ref) {
|
||||||
|
is LambdaFnRef -> ref
|
||||||
|
is LocalVarRef -> lookupExactLambdaRefByName(ref.name)
|
||||||
|
is FastLocalVarRef -> lookupExactLambdaRefByName(ref.name)
|
||||||
|
is LocalSlotRef -> {
|
||||||
|
val ownerScopeId = ref.captureOwnerScopeId ?: ref.scopeId
|
||||||
|
val ownerSlot = ref.captureOwnerSlot ?: ref.slot
|
||||||
|
exactLambdaRefByScopeId[ownerScopeId]?.get(ownerSlot)
|
||||||
|
?: ref.name.takeIf { it.isNotEmpty() }?.let(::lookupExactLambdaRefByName)
|
||||||
|
}
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun resolveReceiverTypeDecl(ref: ObjRef): TypeDecl? {
|
private fun resolveReceiverTypeDecl(ref: ObjRef): TypeDecl? {
|
||||||
return when (ref) {
|
return when (ref) {
|
||||||
is LocalSlotRef -> {
|
is LocalSlotRef -> {
|
||||||
@@ -9071,7 +9278,7 @@ class Compiler(
|
|||||||
val extensionWrapperName = extTypeName?.let { extensionCallableName(it, name) }
|
val extensionWrapperName = extTypeName?.let { extensionCallableName(it, name) }
|
||||||
val classCtx = codeContexts.asReversed().firstOrNull { it is CodeContext.ClassBody } as? CodeContext.ClassBody
|
val classCtx = codeContexts.asReversed().firstOrNull { it is CodeContext.ClassBody } as? CodeContext.ClassBody
|
||||||
var memberMethodId = if (extTypeName == null) classCtx?.memberMethodIds?.get(name) else null
|
var memberMethodId = if (extTypeName == null) classCtx?.memberMethodIds?.get(name) else null
|
||||||
val externCallSignature = if (actualExtern) importManager.rootScope.getLocalRecordDirect(name)?.callSignature else null
|
val externCallSignature = declaredCallSignature(name, extTypeName, actualExtern)
|
||||||
|
|
||||||
val declKind = if (parentContext is CodeContext.ClassBody) SymbolKind.MEMBER else SymbolKind.FUNCTION
|
val declKind = if (parentContext is CodeContext.ClassBody) SymbolKind.MEMBER else SymbolKind.FUNCTION
|
||||||
resolutionSink?.declareSymbol(name, declKind, isMutable = false, pos = nameStartPos, isOverride = isOverride)
|
resolutionSink?.declareSymbol(name, declKind, isMutable = false, pos = nameStartPos, isOverride = isOverride)
|
||||||
@@ -9093,7 +9300,9 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
if (extensionWrapperName != null) {
|
if (extensionWrapperName != null) {
|
||||||
declareLocalName(extensionWrapperName, isMutable = false)
|
declareLocalName(extensionWrapperName, isMutable = false)
|
||||||
|
externCallSignature?.let { callSignatureByName[extensionWrapperName] = it }
|
||||||
}
|
}
|
||||||
|
externCallSignature?.let { callSignatureByName[name] = it }
|
||||||
if (actualExtern && declKind != SymbolKind.MEMBER) {
|
if (actualExtern && declKind != SymbolKind.MEMBER) {
|
||||||
externCallableNames.add(name)
|
externCallableNames.add(name)
|
||||||
}
|
}
|
||||||
@@ -9214,13 +9423,17 @@ class Compiler(
|
|||||||
parentContext is CodeContext.ClassBody && !isStatic -> parentContext.name
|
parentContext is CodeContext.ClassBody && !isStatic -> parentContext.name
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
|
// Static methods and top-level functions have no implicit `this`; mark them so that
|
||||||
|
// currentImplicitThisTypeName() does not fall through to an enclosing ClassBody.
|
||||||
|
val noImplicitThis = implicitThisTypeName == null && extTypeName == null
|
||||||
return inCodeContext(
|
return inCodeContext(
|
||||||
CodeContext.Function(
|
CodeContext.Function(
|
||||||
name,
|
name,
|
||||||
implicitThisMembers = implicitThisMembers,
|
implicitThisMembers = implicitThisMembers,
|
||||||
implicitThisTypeName = implicitThisTypeName,
|
implicitThisTypeName = implicitThisTypeName,
|
||||||
typeParams = typeParams,
|
typeParams = typeParams,
|
||||||
typeParamDecls = typeParamDecls
|
typeParamDecls = typeParamDecls,
|
||||||
|
noImplicitThis = noImplicitThis
|
||||||
)
|
)
|
||||||
) {
|
) {
|
||||||
cc.labels.add(name)
|
cc.labels.add(name)
|
||||||
@@ -9372,9 +9585,8 @@ class Compiler(
|
|||||||
val fnBody = object : Statement(), BytecodeBodyProvider {
|
val fnBody = object : Statement(), BytecodeBodyProvider {
|
||||||
override val pos: Pos = start
|
override val pos: Pos = start
|
||||||
override fun bytecodeBody(): BytecodeStatement? = fnStatements as? BytecodeStatement
|
override fun bytecodeBody(): BytecodeStatement? = fnStatements as? BytecodeStatement
|
||||||
override suspend fun execute(scope: Scope): Obj {
|
|
||||||
scope.pos = start
|
|
||||||
|
|
||||||
|
override suspend fun execute(scope: Scope): Obj {
|
||||||
// restore closure where the function was defined, and making a copy of it
|
// restore closure where the function was defined, and making a copy of it
|
||||||
// for local space. If there is no closure, we are in, say, class context where
|
// for local space. If there is no closure, we are in, say, class context where
|
||||||
// the closure is in the class initialization and we needn't more:
|
// the closure is in the class initialization and we needn't more:
|
||||||
@@ -9383,6 +9595,7 @@ class Compiler(
|
|||||||
it.args = scope.args
|
it.args = scope.args
|
||||||
}
|
}
|
||||||
} ?: scope
|
} ?: scope
|
||||||
|
context.pos = start
|
||||||
|
|
||||||
// Capacity hint: parameters + declared locals + small overhead
|
// Capacity hint: parameters + declared locals + small overhead
|
||||||
val capacityHint = paramNames.size + fnLocalDecls + 4
|
val capacityHint = paramNames.size + fnLocalDecls + 4
|
||||||
@@ -10332,6 +10545,9 @@ class Compiler(
|
|||||||
if (initClass != null) {
|
if (initClass != null) {
|
||||||
classFieldTypesByName.getOrPut(declaringClassNameCaptured) { mutableMapOf() }[name] = initClass
|
classFieldTypesByName.getOrPut(declaringClassNameCaptured) { mutableMapOf() }[name] = initClass
|
||||||
}
|
}
|
||||||
|
if (!isDelegate && varTypeDecl is TypeDecl.Generic) {
|
||||||
|
classMemberTypeDeclByName.getOrPut(declaringClassNameCaptured) { mutableMapOf() }[name] = varTypeDecl
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Emit MiniValDecl for this declaration (before execution wiring), attach doc if any
|
// Emit MiniValDecl for this declaration (before execution wiring), attach doc if any
|
||||||
@@ -10387,6 +10603,15 @@ class Compiler(
|
|||||||
encodedPayloadTypeByName[name] = payloadClass
|
encodedPayloadTypeByName[name] = payloadClass
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (slotIndex != null && scopeId != null) {
|
||||||
|
val exactLambdaRef = if (!isMutable) resolveExactLambdaRef(directRef) else null
|
||||||
|
val scopeMap = exactLambdaRefByScopeId.getOrPut(scopeId) { mutableMapOf() }
|
||||||
|
if (exactLambdaRef != null) {
|
||||||
|
scopeMap[slotIndex] = exactLambdaRef
|
||||||
|
} else {
|
||||||
|
scopeMap.remove(slotIndex)
|
||||||
|
}
|
||||||
|
}
|
||||||
if (initObjClass != null) {
|
if (initObjClass != null) {
|
||||||
if (slotIndex != null && scopeId != null) {
|
if (slotIndex != null && scopeId != null) {
|
||||||
slotTypeByScopeId.getOrPut(scopeId) { mutableMapOf() }[slotIndex] = initObjClass
|
slotTypeByScopeId.getOrPut(scopeId) { mutableMapOf() }[slotIndex] = initObjClass
|
||||||
@@ -10679,8 +10904,12 @@ class Compiler(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (getter != null || setter != null) {
|
if (getter != null || setter != null) {
|
||||||
val prop = ObjProperty(name, getter, setter)
|
val prop = if (actualExtern) {
|
||||||
val initStmt = if (!isAbstract) {
|
ObjProperty(name, null, null)
|
||||||
|
} else {
|
||||||
|
ObjProperty(name, getter, setter)
|
||||||
|
}
|
||||||
|
val initStmt = if (!isAbstract && !actualExtern) {
|
||||||
val initStatement = InstancePropertyInitStatement(
|
val initStatement = InstancePropertyInitStatement(
|
||||||
storageName = storageName,
|
storageName = storageName,
|
||||||
isMutable = isMutable,
|
isMutable = isMutable,
|
||||||
|
|||||||
@@ -118,7 +118,14 @@ internal suspend fun executeFunctionDecl(
|
|||||||
scope.addExtension(
|
scope.addExtension(
|
||||||
type,
|
type,
|
||||||
spec.name,
|
spec.name,
|
||||||
ObjRecord(ObjUnset, isMutable = false, visibility = spec.visibility, declaringClass = null, type = ObjRecord.Type.Delegated).apply {
|
ObjRecord(
|
||||||
|
ObjUnset,
|
||||||
|
isMutable = false,
|
||||||
|
visibility = spec.visibility,
|
||||||
|
declaringClass = null,
|
||||||
|
type = ObjRecord.Type.Delegated,
|
||||||
|
callSignature = spec.externCallSignature
|
||||||
|
).apply {
|
||||||
delegate = finalDelegate
|
delegate = finalDelegate
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
@@ -135,7 +142,8 @@ internal suspend fun executeFunctionDecl(
|
|||||||
null,
|
null,
|
||||||
spec.startPos,
|
spec.startPos,
|
||||||
isTransient = spec.isTransient,
|
isTransient = spec.isTransient,
|
||||||
type = ObjRecord.Type.Delegated
|
type = ObjRecord.Type.Delegated,
|
||||||
|
callSignature = spec.externCallSignature
|
||||||
).apply {
|
).apply {
|
||||||
delegate = finalDelegate
|
delegate = finalDelegate
|
||||||
}
|
}
|
||||||
@@ -204,6 +212,7 @@ internal suspend fun executeFunctionDecl(
|
|||||||
visibility = spec.visibility,
|
visibility = spec.visibility,
|
||||||
pos = spec.startPos,
|
pos = spec.startPos,
|
||||||
type = ObjRecord.Type.Fun,
|
type = ObjRecord.Type.Fun,
|
||||||
|
callSignature = spec.externCallSignature,
|
||||||
)
|
)
|
||||||
} else {
|
} else {
|
||||||
scope.addExtension(
|
scope.addExtension(
|
||||||
@@ -215,6 +224,7 @@ internal suspend fun executeFunctionDecl(
|
|||||||
visibility = spec.visibility,
|
visibility = spec.visibility,
|
||||||
declaringClass = null,
|
declaringClass = null,
|
||||||
type = ObjRecord.Type.Fun,
|
type = ObjRecord.Type.Fun,
|
||||||
|
callSignature = spec.externCallSignature,
|
||||||
typeDecl = spec.typeDecl
|
typeDecl = spec.typeDecl
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -227,6 +237,7 @@ internal suspend fun executeFunctionDecl(
|
|||||||
wrapper,
|
wrapper,
|
||||||
spec.visibility,
|
spec.visibility,
|
||||||
recordType = ObjRecord.Type.Fun,
|
recordType = ObjRecord.Type.Fun,
|
||||||
|
callSignature = spec.externCallSignature,
|
||||||
typeDecl = spec.typeDecl
|
typeDecl = spec.typeDecl
|
||||||
)
|
)
|
||||||
} ?: run {
|
} ?: run {
|
||||||
@@ -245,7 +256,8 @@ internal suspend fun executeFunctionDecl(
|
|||||||
isOverride = spec.isOverride,
|
isOverride = spec.isOverride,
|
||||||
type = ObjRecord.Type.Fun,
|
type = ObjRecord.Type.Fun,
|
||||||
methodId = spec.memberMethodId,
|
methodId = spec.memberMethodId,
|
||||||
typeDecl = spec.typeDecl
|
typeDecl = spec.typeDecl,
|
||||||
|
callSignature = spec.externCallSignature
|
||||||
)
|
)
|
||||||
val memberValue = cls.members[spec.name]?.value ?: compiledFnBody
|
val memberValue = cls.members[spec.name]?.value ?: compiledFnBody
|
||||||
scope.addItem(
|
scope.addItem(
|
||||||
|
|||||||
@@ -66,7 +66,11 @@ internal class ScopeBridge(internal val scope: Scope) : ScopeFacade {
|
|||||||
override fun raiseIllegalState(message: String): Nothing = scope.raiseIllegalState(message)
|
override fun raiseIllegalState(message: String): Nothing = scope.raiseIllegalState(message)
|
||||||
override fun raiseNotImplemented(what: String): Nothing = scope.raiseNotImplemented(what)
|
override fun raiseNotImplemented(what: String): Nothing = scope.raiseNotImplemented(what)
|
||||||
override suspend fun call(callee: Obj, args: Arguments, newThisObj: Obj?): Obj {
|
override suspend fun call(callee: Obj, args: Arguments, newThisObj: Obj?): Obj {
|
||||||
return callee.callOn(scope.createChildScope(scope.pos, args = args, newThisObj = newThisObj))
|
if (newThisObj == null) {
|
||||||
|
(callee as? BytecodeArgCallable)?.callWithArgsFast(scope, args)?.let { return it }
|
||||||
|
}
|
||||||
|
val child = scope.createChildScope(scope.pos, args = args, newThisObj = newThisObj)
|
||||||
|
return (callee as? BytecodeCallable)?.callOnFast(child) ?: callee.callOn(child)
|
||||||
}
|
}
|
||||||
override suspend fun toStringOf(obj: Obj, forInspect: Boolean): ObjString = obj.toString(scope, forInspect)
|
override suspend fun toStringOf(obj: Obj, forInspect: Boolean): ObjString = obj.toString(scope, forInspect)
|
||||||
override suspend fun inspect(obj: Obj): String = obj.inspect(scope)
|
override suspend fun inspect(obj: Obj): String = obj.inspect(scope)
|
||||||
|
|||||||
@@ -108,11 +108,7 @@ class Script(
|
|||||||
seedImportBindings(scope, seedScope)
|
seedImportBindings(scope, seedScope)
|
||||||
}
|
}
|
||||||
if (moduleSlotPlan.isNotEmpty()) {
|
if (moduleSlotPlan.isNotEmpty()) {
|
||||||
scope.applySlotPlan(moduleSlotPlan)
|
installModuleSlotPlan(scope)
|
||||||
for (name in moduleSlotPlan.keys) {
|
|
||||||
val record = scope.objects[name] ?: scope.localBindings[name] ?: continue
|
|
||||||
scope.updateSlotFor(name, record)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,13 +116,27 @@ class Script(
|
|||||||
if (importBindings.isEmpty() && importedModules.isEmpty()) return
|
if (importBindings.isEmpty() && importedModules.isEmpty()) return
|
||||||
seedImportBindings(scope, seedScope)
|
seedImportBindings(scope, seedScope)
|
||||||
if (moduleSlotPlan.isNotEmpty()) {
|
if (moduleSlotPlan.isNotEmpty()) {
|
||||||
scope.applySlotPlan(moduleSlotPlan)
|
installModuleSlotPlan(scope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun installModuleSlotPlan(scope: Scope) {
|
||||||
|
for ((name, index) in moduleSlotPlan) {
|
||||||
|
if (scope.getSlotIndexOf(name) != null) continue
|
||||||
|
if (scope.hasSlotPlanConflict(mapOf(name to index))) {
|
||||||
|
val record = scope.objects[name]
|
||||||
|
?: scope.localBindings[name]
|
||||||
|
?: ObjRecord(ObjUnset, isMutable = true)
|
||||||
|
scope.allocateSlotFor(name, record)
|
||||||
|
} else {
|
||||||
|
scope.applySlotPlan(mapOf(name to index))
|
||||||
|
}
|
||||||
|
}
|
||||||
for (name in moduleSlotPlan.keys) {
|
for (name in moduleSlotPlan.keys) {
|
||||||
val record = scope.objects[name] ?: scope.localBindings[name] ?: continue
|
val record = scope.objects[name] ?: scope.localBindings[name] ?: continue
|
||||||
scope.updateSlotFor(name, record)
|
scope.updateSlotFor(name, record)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private suspend fun seedModuleLocals(
|
private suspend fun seedModuleLocals(
|
||||||
frame: net.sergeych.lyng.bytecode.CmdFrame,
|
frame: net.sergeych.lyng.bytecode.CmdFrame,
|
||||||
@@ -634,6 +644,7 @@ class Script(
|
|||||||
addConst("Deferred", ObjDeferred.type)
|
addConst("Deferred", ObjDeferred.type)
|
||||||
addConst("CompletableDeferred", ObjCompletableDeferred.type)
|
addConst("CompletableDeferred", ObjCompletableDeferred.type)
|
||||||
addConst("Mutex", ObjMutex.type)
|
addConst("Mutex", ObjMutex.type)
|
||||||
|
addConst("Channel", ObjChannel.type)
|
||||||
addConst("Flow", ObjFlow.type)
|
addConst("Flow", ObjFlow.type)
|
||||||
addConst("FlowBuilder", ObjFlowBuilder.type)
|
addConst("FlowBuilder", ObjFlowBuilder.type)
|
||||||
addConst("Delegate", ObjDynamic.type)
|
addConst("Delegate", ObjDynamic.type)
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -40,6 +40,7 @@ sealed class BytecodeConst {
|
|||||||
val captureNames: List<String>,
|
val captureNames: List<String>,
|
||||||
val paramSlotPlan: Map<String, Int>,
|
val paramSlotPlan: Map<String, Int>,
|
||||||
val argsDeclaration: ArgsDeclaration?,
|
val argsDeclaration: ArgsDeclaration?,
|
||||||
|
val supportsDirectInvokeFastPath: Boolean,
|
||||||
val preferredThisType: String?,
|
val preferredThisType: String?,
|
||||||
val wrapAsExtensionCallable: Boolean,
|
val wrapAsExtensionCallable: Boolean,
|
||||||
val returnLabels: Set<String>,
|
val returnLabels: Set<String>,
|
||||||
|
|||||||
@@ -18,27 +18,41 @@
|
|||||||
package net.sergeych.lyng.bytecode
|
package net.sergeych.lyng.bytecode
|
||||||
|
|
||||||
import net.sergeych.lyng.*
|
import net.sergeych.lyng.*
|
||||||
import net.sergeych.lyng.obj.Obj
|
import net.sergeych.lyng.obj.*
|
||||||
import net.sergeych.lyng.obj.ObjClass
|
|
||||||
import net.sergeych.lyng.obj.ObjRecord
|
|
||||||
import net.sergeych.lyng.obj.ValueFnRef
|
|
||||||
|
|
||||||
class BytecodeStatement private constructor(
|
class BytecodeStatement private constructor(
|
||||||
val original: Statement,
|
val original: Statement,
|
||||||
private val function: CmdFunction,
|
private val function: CmdFunction,
|
||||||
) : Statement(original.isStaticConst, original.isConst, original.returnType) {
|
) : Statement(original.isStaticConst, original.isConst, original.returnType), BytecodeCallable {
|
||||||
override val pos: Pos = original.pos
|
override val pos: Pos = original.pos
|
||||||
|
|
||||||
|
private val declaredLocalNames: Set<String> by lazy(LazyThreadSafetyMode.NONE) {
|
||||||
|
function.constants
|
||||||
|
.mapNotNull { it as? BytecodeConst.LocalDecl }
|
||||||
|
.mapTo(mutableSetOf()) { it.name }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun callOnFast(scope: Scope): Obj? {
|
||||||
|
scope.pos = pos
|
||||||
|
if (!function.fastOnly) return null
|
||||||
|
if (!canFastSeedUndeclaredLocals(function, declaredLocalNames, emptySet())) return null
|
||||||
|
val binder: (CmdFrame, Arguments) -> Unit = { frame, _ ->
|
||||||
|
if (!trySeedFrameLocalsFromScopeFast(frame, scope)) {
|
||||||
|
scope.raiseIllegalState("fast local seeding is not available")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return CmdVm().executeFastOnlyNoSuspend(function, scope, scope.args, binder)
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun execute(scope: Scope): Obj {
|
override suspend fun execute(scope: Scope): Obj {
|
||||||
scope.pos = pos
|
scope.pos = pos
|
||||||
val declaredNames = function.constants
|
val fastResult = callOnFast(scope)
|
||||||
.mapNotNull { it as? BytecodeConst.LocalDecl }
|
if (fastResult != null) return fastResult
|
||||||
.mapTo(mutableSetOf()) { it.name }
|
|
||||||
val binder: suspend (CmdFrame, Arguments) -> Unit = { frame, _ ->
|
val binder: suspend (CmdFrame, Arguments) -> Unit = { frame, _ ->
|
||||||
val localNames = frame.fn.localSlotNames
|
val localNames = frame.fn.localSlotNames
|
||||||
for (i in localNames.indices) {
|
for (i in localNames.indices) {
|
||||||
val name = localNames[i] ?: continue
|
val name = localNames[i] ?: continue
|
||||||
if (declaredNames.contains(name)) continue
|
if (declaredLocalNames.contains(name)) continue
|
||||||
val slotType = frame.getLocalSlotTypeCode(i)
|
val slotType = frame.getLocalSlotTypeCode(i)
|
||||||
if (slotType != SlotType.UNKNOWN.code && slotType != SlotType.OBJ.code) {
|
if (slotType != SlotType.UNKNOWN.code && slotType != SlotType.OBJ.code) {
|
||||||
continue
|
continue
|
||||||
@@ -84,6 +98,7 @@ class BytecodeStatement private constructor(
|
|||||||
globalSlotInfo: Map<String, ForcedLocalSlotInfo> = emptyMap(),
|
globalSlotInfo: Map<String, ForcedLocalSlotInfo> = emptyMap(),
|
||||||
globalSlotScopeId: Int? = null,
|
globalSlotScopeId: Int? = null,
|
||||||
slotTypeByScopeId: Map<Int, Map<Int, ObjClass>> = emptyMap(),
|
slotTypeByScopeId: Map<Int, Map<Int, ObjClass>> = emptyMap(),
|
||||||
|
exactLambdaRefByScopeId: Map<Int, Map<Int, LambdaFnRef>> = emptyMap(),
|
||||||
knownNameObjClass: Map<String, ObjClass> = emptyMap(),
|
knownNameObjClass: Map<String, ObjClass> = emptyMap(),
|
||||||
knownClassNames: Set<String> = emptySet(),
|
knownClassNames: Set<String> = emptySet(),
|
||||||
knownObjectNames: Set<String> = emptySet(),
|
knownObjectNames: Set<String> = emptySet(),
|
||||||
@@ -91,6 +106,7 @@ class BytecodeStatement private constructor(
|
|||||||
enumEntriesByName: Map<String, List<String>> = emptyMap(),
|
enumEntriesByName: Map<String, List<String>> = emptyMap(),
|
||||||
callableReturnTypeByScopeId: Map<Int, Map<Int, ObjClass>> = emptyMap(),
|
callableReturnTypeByScopeId: Map<Int, Map<Int, ObjClass>> = emptyMap(),
|
||||||
callableReturnTypeByName: Map<String, ObjClass> = emptyMap(),
|
callableReturnTypeByName: Map<String, ObjClass> = emptyMap(),
|
||||||
|
callSignatureByName: Map<String, CallSignature> = emptyMap(),
|
||||||
externCallableNames: Set<String> = emptySet(),
|
externCallableNames: Set<String> = emptySet(),
|
||||||
externBindingNames: Set<String> = emptySet(),
|
externBindingNames: Set<String> = emptySet(),
|
||||||
preparedModuleBindingNames: Set<String> = emptySet(),
|
preparedModuleBindingNames: Set<String> = emptySet(),
|
||||||
@@ -122,6 +138,7 @@ class BytecodeStatement private constructor(
|
|||||||
globalSlotInfo = globalSlotInfo,
|
globalSlotInfo = globalSlotInfo,
|
||||||
globalSlotScopeId = globalSlotScopeId,
|
globalSlotScopeId = globalSlotScopeId,
|
||||||
slotTypeByScopeId = slotTypeByScopeId,
|
slotTypeByScopeId = slotTypeByScopeId,
|
||||||
|
exactLambdaRefByScopeId = exactLambdaRefByScopeId,
|
||||||
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
slotTypeDeclByScopeId = slotTypeDeclByScopeId,
|
||||||
knownNameObjClass = knownNameObjClass,
|
knownNameObjClass = knownNameObjClass,
|
||||||
knownClassNames = knownClassNames,
|
knownClassNames = knownClassNames,
|
||||||
@@ -130,6 +147,7 @@ class BytecodeStatement private constructor(
|
|||||||
enumEntriesByName = enumEntriesByName,
|
enumEntriesByName = enumEntriesByName,
|
||||||
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
callableReturnTypeByScopeId = callableReturnTypeByScopeId,
|
||||||
callableReturnTypeByName = callableReturnTypeByName,
|
callableReturnTypeByName = callableReturnTypeByName,
|
||||||
|
callSignatureByName = callSignatureByName,
|
||||||
externCallableNames = externCallableNames,
|
externCallableNames = externCallableNames,
|
||||||
externBindingNames = externBindingNames,
|
externBindingNames = externBindingNames,
|
||||||
preparedModuleBindingNames = preparedModuleBindingNames,
|
preparedModuleBindingNames = preparedModuleBindingNames,
|
||||||
|
|||||||
@@ -112,6 +112,7 @@ class CmdBuilder {
|
|||||||
}
|
}
|
||||||
cmds.add(createCmd(ins.op, operands, scopeSlotCount, localSlotCaptures))
|
cmds.add(createCmd(ins.op, operands, scopeSlotCount, localSlotCaptures))
|
||||||
}
|
}
|
||||||
|
val cmdArray = cmds.toTypedArray()
|
||||||
return CmdFunction(
|
return CmdFunction(
|
||||||
name = name,
|
name = name,
|
||||||
localCount = localCount,
|
localCount = localCount,
|
||||||
@@ -128,8 +129,9 @@ class CmdBuilder {
|
|||||||
localSlotDelegated = localSlotDelegated,
|
localSlotDelegated = localSlotDelegated,
|
||||||
localSlotCaptures = localSlotCaptures,
|
localSlotCaptures = localSlotCaptures,
|
||||||
constants = constPool.toList(),
|
constants = constPool.toList(),
|
||||||
cmds = cmds.toTypedArray(),
|
cmds = cmdArray,
|
||||||
posByIp = posByInstr.toTypedArray()
|
posByIp = posByInstr.toTypedArray(),
|
||||||
|
fastOnly = computeFastOnlyBytecode(scopeSlotCount, cmdArray)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,8 +233,16 @@ class CmdBuilder {
|
|||||||
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
Opcode.SET_INDEX_INT ->
|
Opcode.SET_INDEX_INT ->
|
||||||
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_NEW_INT ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT)
|
||||||
Opcode.LIST_FILL_INT ->
|
Opcode.LIST_FILL_INT ->
|
||||||
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_IOTA_INT ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_NEW_INT_CAP ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_FILL_INT_CAP ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
Opcode.MAKE_RANGE ->
|
Opcode.MAKE_RANGE ->
|
||||||
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
Opcode.LIST_LITERAL ->
|
Opcode.LIST_LITERAL ->
|
||||||
@@ -835,7 +845,11 @@ class CmdBuilder {
|
|||||||
Opcode.SET_INDEX -> CmdSetIndex(operands[0], operands[1], operands[2])
|
Opcode.SET_INDEX -> CmdSetIndex(operands[0], operands[1], operands[2])
|
||||||
Opcode.GET_INDEX_INT -> CmdGetIndexInt(operands[0], operands[1], operands[2])
|
Opcode.GET_INDEX_INT -> CmdGetIndexInt(operands[0], operands[1], operands[2])
|
||||||
Opcode.SET_INDEX_INT -> CmdSetIndexInt(operands[0], operands[1], operands[2])
|
Opcode.SET_INDEX_INT -> CmdSetIndexInt(operands[0], operands[1], operands[2])
|
||||||
|
Opcode.LIST_NEW_INT -> CmdListNewInt(operands[0], operands[1])
|
||||||
Opcode.LIST_FILL_INT -> CmdListFillInt(operands[0], operands[1], operands[2])
|
Opcode.LIST_FILL_INT -> CmdListFillInt(operands[0], operands[1], operands[2])
|
||||||
|
Opcode.LIST_IOTA_INT -> CmdListIotaInt(operands[0], operands[1])
|
||||||
|
Opcode.LIST_NEW_INT_CAP -> CmdListNewIntCap(operands[0], operands[1], operands[2])
|
||||||
|
Opcode.LIST_FILL_INT_CAP -> CmdListFillIntCap(operands[0], operands[1], operands[2], operands[3])
|
||||||
Opcode.LIST_LITERAL -> CmdListLiteral(operands[0], operands[1], operands[2], operands[3])
|
Opcode.LIST_LITERAL -> CmdListLiteral(operands[0], operands[1], operands[2], operands[3])
|
||||||
Opcode.GET_MEMBER_SLOT -> CmdGetMemberSlot(operands[0], operands[1], operands[2], operands[3])
|
Opcode.GET_MEMBER_SLOT -> CmdGetMemberSlot(operands[0], operands[1], operands[2], operands[3])
|
||||||
Opcode.SET_MEMBER_SLOT -> CmdSetMemberSlot(operands[0], operands[1], operands[2], operands[3])
|
Opcode.SET_MEMBER_SLOT -> CmdSetMemberSlot(operands[0], operands[1], operands[2], operands[3])
|
||||||
|
|||||||
@@ -495,7 +495,11 @@ object CmdDisassembler {
|
|||||||
is CmdSetIndex -> Opcode.SET_INDEX to intArrayOf(cmd.targetSlot, cmd.indexSlot, cmd.valueSlot)
|
is CmdSetIndex -> Opcode.SET_INDEX to intArrayOf(cmd.targetSlot, cmd.indexSlot, cmd.valueSlot)
|
||||||
is CmdGetIndexInt -> Opcode.GET_INDEX_INT to intArrayOf(cmd.targetSlot, cmd.indexSlot, cmd.dst)
|
is CmdGetIndexInt -> Opcode.GET_INDEX_INT to intArrayOf(cmd.targetSlot, cmd.indexSlot, cmd.dst)
|
||||||
is CmdSetIndexInt -> Opcode.SET_INDEX_INT to intArrayOf(cmd.targetSlot, cmd.indexSlot, cmd.valueSlot)
|
is CmdSetIndexInt -> Opcode.SET_INDEX_INT to intArrayOf(cmd.targetSlot, cmd.indexSlot, cmd.valueSlot)
|
||||||
|
is CmdListNewInt -> Opcode.LIST_NEW_INT to intArrayOf(cmd.sizeSlot, cmd.dst)
|
||||||
is CmdListFillInt -> Opcode.LIST_FILL_INT to intArrayOf(cmd.sizeSlot, cmd.callableSlot, cmd.dst)
|
is CmdListFillInt -> Opcode.LIST_FILL_INT to intArrayOf(cmd.sizeSlot, cmd.callableSlot, cmd.dst)
|
||||||
|
is CmdListIotaInt -> Opcode.LIST_IOTA_INT to intArrayOf(cmd.sizeSlot, cmd.dst)
|
||||||
|
is CmdListNewIntCap -> Opcode.LIST_NEW_INT_CAP to intArrayOf(cmd.sizeSlot, cmd.capacitySlot, cmd.dst)
|
||||||
|
is CmdListFillIntCap -> Opcode.LIST_FILL_INT_CAP to intArrayOf(cmd.sizeSlot, cmd.capacitySlot, cmd.callableSlot, cmd.dst)
|
||||||
is CmdListLiteral -> Opcode.LIST_LITERAL to intArrayOf(cmd.planId, cmd.baseSlot, cmd.count, cmd.dst)
|
is CmdListLiteral -> Opcode.LIST_LITERAL to intArrayOf(cmd.planId, cmd.baseSlot, cmd.count, cmd.dst)
|
||||||
is CmdGetMemberSlot -> Opcode.GET_MEMBER_SLOT to intArrayOf(cmd.recvSlot, cmd.fieldId, cmd.methodId, cmd.dst)
|
is CmdGetMemberSlot -> Opcode.GET_MEMBER_SLOT to intArrayOf(cmd.recvSlot, cmd.fieldId, cmd.methodId, cmd.dst)
|
||||||
is CmdSetMemberSlot -> Opcode.SET_MEMBER_SLOT to intArrayOf(cmd.recvSlot, cmd.fieldId, cmd.methodId, cmd.valueSlot)
|
is CmdSetMemberSlot -> Opcode.SET_MEMBER_SLOT to intArrayOf(cmd.recvSlot, cmd.fieldId, cmd.methodId, cmd.valueSlot)
|
||||||
@@ -619,8 +623,16 @@ object CmdDisassembler {
|
|||||||
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
Opcode.SET_INDEX_INT ->
|
Opcode.SET_INDEX_INT ->
|
||||||
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_NEW_INT ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT)
|
||||||
Opcode.LIST_FILL_INT ->
|
Opcode.LIST_FILL_INT ->
|
||||||
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_IOTA_INT ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_NEW_INT_CAP ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
|
Opcode.LIST_FILL_INT_CAP ->
|
||||||
|
listOf(OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT, OperandKind.SLOT)
|
||||||
Opcode.LIST_LITERAL ->
|
Opcode.LIST_LITERAL ->
|
||||||
listOf(OperandKind.CONST, OperandKind.SLOT, OperandKind.COUNT, OperandKind.SLOT)
|
listOf(OperandKind.CONST, OperandKind.SLOT, OperandKind.COUNT, OperandKind.SLOT)
|
||||||
Opcode.GET_MEMBER_SLOT ->
|
Opcode.GET_MEMBER_SLOT ->
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ data class CmdFunction(
|
|||||||
val constants: List<BytecodeConst>,
|
val constants: List<BytecodeConst>,
|
||||||
val cmds: Array<Cmd>,
|
val cmds: Array<Cmd>,
|
||||||
val posByIp: Array<net.sergeych.lyng.Pos?>,
|
val posByIp: Array<net.sergeych.lyng.Pos?>,
|
||||||
|
val fastOnly: Boolean = false,
|
||||||
) {
|
) {
|
||||||
init {
|
init {
|
||||||
require(scopeSlotIndices.size == scopeSlotCount) { "scopeSlotIndices size mismatch" }
|
require(scopeSlotIndices.size == scopeSlotCount) { "scopeSlotIndices size mismatch" }
|
||||||
@@ -71,3 +72,118 @@ data class CmdFunction(
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun computeFastOnlyBytecode(scopeSlotCount: Int, cmds: Array<Cmd>): Boolean {
|
||||||
|
if (scopeSlotCount != 0) return false
|
||||||
|
return cmds.all(::supportsFastOnlyExecution)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun supportsFastOnlyExecution(cmd: Cmd): Boolean {
|
||||||
|
return when (cmd) {
|
||||||
|
is CmdMoveIntLocal,
|
||||||
|
is CmdMoveRealLocal,
|
||||||
|
is CmdMoveBoolLocal,
|
||||||
|
is CmdConstObj,
|
||||||
|
is CmdConstInt,
|
||||||
|
is CmdConstIntLocal,
|
||||||
|
is CmdConstReal,
|
||||||
|
is CmdConstBool,
|
||||||
|
is CmdConstNull,
|
||||||
|
is CmdUnboxIntObjLocal,
|
||||||
|
is CmdUnboxRealObjLocal,
|
||||||
|
is CmdIntToRealLocal,
|
||||||
|
is CmdRealToIntLocal,
|
||||||
|
is CmdBoolToIntLocal,
|
||||||
|
is CmdIntToBoolLocal,
|
||||||
|
is CmdAddIntLocal,
|
||||||
|
is CmdSubIntLocal,
|
||||||
|
is CmdMulIntLocal,
|
||||||
|
is CmdDivIntLocal,
|
||||||
|
is CmdModIntLocal,
|
||||||
|
is CmdNegIntLocal,
|
||||||
|
is CmdIncIntLocal,
|
||||||
|
is CmdDecIntLocal,
|
||||||
|
is CmdAddRealLocal,
|
||||||
|
is CmdSubRealLocal,
|
||||||
|
is CmdMulRealLocal,
|
||||||
|
is CmdDivRealLocal,
|
||||||
|
is CmdNegRealLocal,
|
||||||
|
is CmdAndIntLocal,
|
||||||
|
is CmdOrIntLocal,
|
||||||
|
is CmdXorIntLocal,
|
||||||
|
is CmdShlIntLocal,
|
||||||
|
is CmdShrIntLocal,
|
||||||
|
is CmdUshrIntLocal,
|
||||||
|
is CmdInvIntLocal,
|
||||||
|
is CmdCmpEqIntLocal,
|
||||||
|
is CmdCmpNeqIntLocal,
|
||||||
|
is CmdCmpLtIntLocal,
|
||||||
|
is CmdCmpLteIntLocal,
|
||||||
|
is CmdCmpGtIntLocal,
|
||||||
|
is CmdCmpGteIntLocal,
|
||||||
|
is CmdCmpEqRealLocal,
|
||||||
|
is CmdCmpNeqRealLocal,
|
||||||
|
is CmdCmpLtRealLocal,
|
||||||
|
is CmdCmpLteRealLocal,
|
||||||
|
is CmdCmpGtRealLocal,
|
||||||
|
is CmdCmpGteRealLocal,
|
||||||
|
is CmdCmpEqBoolLocal,
|
||||||
|
is CmdCmpNeqBoolLocal,
|
||||||
|
is CmdCmpEqIntRealLocal,
|
||||||
|
is CmdCmpEqRealIntLocal,
|
||||||
|
is CmdCmpLtIntRealLocal,
|
||||||
|
is CmdCmpLtRealIntLocal,
|
||||||
|
is CmdCmpLteIntRealLocal,
|
||||||
|
is CmdCmpLteRealIntLocal,
|
||||||
|
is CmdCmpGtIntRealLocal,
|
||||||
|
is CmdCmpGtRealIntLocal,
|
||||||
|
is CmdCmpGteIntRealLocal,
|
||||||
|
is CmdCmpGteRealIntLocal,
|
||||||
|
is CmdCmpNeqIntRealLocal,
|
||||||
|
is CmdCmpNeqRealIntLocal,
|
||||||
|
is CmdCmpEqStrLocal,
|
||||||
|
is CmdCmpNeqStrLocal,
|
||||||
|
is CmdCmpLtStrLocal,
|
||||||
|
is CmdCmpLteStrLocal,
|
||||||
|
is CmdCmpGtStrLocal,
|
||||||
|
is CmdCmpGteStrLocal,
|
||||||
|
is CmdCmpEqIntObjLocal,
|
||||||
|
is CmdCmpNeqIntObjLocal,
|
||||||
|
is CmdCmpLtIntObjLocal,
|
||||||
|
is CmdCmpLteIntObjLocal,
|
||||||
|
is CmdCmpGtIntObjLocal,
|
||||||
|
is CmdCmpGteIntObjLocal,
|
||||||
|
is CmdCmpEqRealObjLocal,
|
||||||
|
is CmdCmpNeqRealObjLocal,
|
||||||
|
is CmdCmpLtRealObjLocal,
|
||||||
|
is CmdCmpLteRealObjLocal,
|
||||||
|
is CmdCmpGtRealObjLocal,
|
||||||
|
is CmdCmpGteRealObjLocal,
|
||||||
|
is CmdAddIntObjLocal,
|
||||||
|
is CmdSubIntObjLocal,
|
||||||
|
is CmdMulIntObjLocal,
|
||||||
|
is CmdDivIntObjLocal,
|
||||||
|
is CmdModIntObjLocal,
|
||||||
|
is CmdAddRealObjLocal,
|
||||||
|
is CmdSubRealObjLocal,
|
||||||
|
is CmdMulRealObjLocal,
|
||||||
|
is CmdDivRealObjLocal,
|
||||||
|
is CmdModRealObjLocal,
|
||||||
|
is CmdNotBoolLocal,
|
||||||
|
is CmdAndBoolLocal,
|
||||||
|
is CmdOrBoolLocal,
|
||||||
|
is CmdJmp,
|
||||||
|
is CmdJmpIfTrueLocal,
|
||||||
|
is CmdJmpIfFalseLocal,
|
||||||
|
is CmdJmpIfEqIntLocal,
|
||||||
|
is CmdJmpIfNeqIntLocal,
|
||||||
|
is CmdJmpIfLtIntLocal,
|
||||||
|
is CmdJmpIfLteIntLocal,
|
||||||
|
is CmdJmpIfGtIntLocal,
|
||||||
|
is CmdJmpIfGteIntLocal,
|
||||||
|
is CmdRet,
|
||||||
|
is CmdRetVoid -> true
|
||||||
|
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -57,6 +57,64 @@ class CmdVm {
|
|||||||
suspend fun execute(fn: CmdFunction, scope0: Scope, args: List<Obj>): Obj {
|
suspend fun execute(fn: CmdFunction, scope0: Scope, args: List<Obj>): Obj {
|
||||||
return execute(fn, scope0, Arguments.from(args))
|
return execute(fn, scope0, Arguments.from(args))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun executeFastOnlyNoSuspend(
|
||||||
|
fn: CmdFunction,
|
||||||
|
scope0: Scope,
|
||||||
|
args: Arguments,
|
||||||
|
binder: ((CmdFrame, Arguments) -> Unit)? = null
|
||||||
|
): Obj {
|
||||||
|
require(fn.fastOnly) { "fast-only execution requested for non-fast function ${fn.name}" }
|
||||||
|
result = null
|
||||||
|
val frame = CmdFrame(this, fn, scope0, args.list)
|
||||||
|
frame.applyCaptureRecords()
|
||||||
|
binder?.invoke(frame, args)
|
||||||
|
val cmds = fn.cmds
|
||||||
|
try {
|
||||||
|
while (result == null) {
|
||||||
|
val cmd = cmds[frame.ip++]
|
||||||
|
if (!cmd.performFast(frame)) {
|
||||||
|
error("fast-only command not supported: ${cmd::class.simpleName}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
throw frame.normalizeThrowableFast(e)
|
||||||
|
}
|
||||||
|
return result ?: ObjVoid
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun executeFastOnly(
|
||||||
|
fn: CmdFunction,
|
||||||
|
scope0: Scope,
|
||||||
|
args: Arguments,
|
||||||
|
binder: ((CmdFrame, Arguments) -> Unit)? = null
|
||||||
|
): Obj {
|
||||||
|
require(fn.fastOnly) { "fast-only execution requested for non-fast function ${fn.name}" }
|
||||||
|
result = null
|
||||||
|
val frame = CmdFrame(this, fn, scope0, args.list)
|
||||||
|
frame.applyCaptureRecords()
|
||||||
|
binder?.invoke(frame, args)
|
||||||
|
val cmds = fn.cmds
|
||||||
|
while (true) {
|
||||||
|
try {
|
||||||
|
while (result == null) {
|
||||||
|
val cmd = cmds[frame.ip++]
|
||||||
|
if (!cmd.performFast(frame)) {
|
||||||
|
error("fast-only command not supported: ${cmd::class.simpleName}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
val throwable = frame.normalizeThrowable(e)
|
||||||
|
if (!frame.handleException(throwable)) {
|
||||||
|
frame.cancelIterators()
|
||||||
|
throw throwable
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
frame.cancelIterators()
|
||||||
|
return result ?: ObjVoid
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
sealed class Cmd {
|
sealed class Cmd {
|
||||||
@@ -280,6 +338,11 @@ class CmdMakeRange(
|
|||||||
}
|
}
|
||||||
|
|
||||||
class CmdConstNull(internal val dst: Int) : Cmd() {
|
class CmdConstNull(internal val dst: Int) : Cmd() {
|
||||||
|
override fun performFast(frame: CmdFrame): Boolean {
|
||||||
|
frame.setObj(dst, ObjNull)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun perform(frame: CmdFrame) {
|
override suspend fun perform(frame: CmdFrame) {
|
||||||
frame.setObj(dst, ObjNull)
|
frame.setObj(dst, ObjNull)
|
||||||
return
|
return
|
||||||
@@ -2141,8 +2204,8 @@ class CmdAssignOpObj(
|
|||||||
}
|
}
|
||||||
if (result == null) {
|
if (result == null) {
|
||||||
val name = (frame.fn.constants.getOrNull(nameId) as? BytecodeConst.StringVal)?.value
|
val name = (frame.fn.constants.getOrNull(nameId) as? BytecodeConst.StringVal)?.value
|
||||||
if (name != null) frame.ensureScope().raiseIllegalAssignment("symbol is readonly: $name")
|
if (name != null) frame.ensureScope().raiseIllegalAssignment("can't reassign val $name")
|
||||||
frame.ensureScope().raiseIllegalAssignment("symbol is readonly")
|
frame.ensureScope().raiseIllegalAssignment("can't reassign val")
|
||||||
}
|
}
|
||||||
frame.storeObjResult(dst, result)
|
frame.storeObjResult(dst, result)
|
||||||
return
|
return
|
||||||
@@ -2301,6 +2364,11 @@ class CmdJmpIfGteIntLocal(internal val a: Int, internal val b: Int, internal val
|
|||||||
}
|
}
|
||||||
|
|
||||||
class CmdRet(internal val slot: Int) : Cmd() {
|
class CmdRet(internal val slot: Int) : Cmd() {
|
||||||
|
override fun performFast(frame: CmdFrame): Boolean {
|
||||||
|
frame.vm.result = frame.storedSlotObj(slot)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun perform(frame: CmdFrame) {
|
override suspend fun perform(frame: CmdFrame) {
|
||||||
frame.vm.result = frame.slotToObj(slot)
|
frame.vm.result = frame.slotToObj(slot)
|
||||||
return
|
return
|
||||||
@@ -2322,6 +2390,11 @@ class CmdRetLabel(internal val labelId: Int, internal val slot: Int) : Cmd() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class CmdRetVoid : Cmd() {
|
class CmdRetVoid : Cmd() {
|
||||||
|
override fun performFast(frame: CmdFrame): Boolean {
|
||||||
|
frame.vm.result = ObjVoid
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun perform(frame: CmdFrame) {
|
override suspend fun perform(frame: CmdFrame) {
|
||||||
frame.vm.result = ObjVoid
|
frame.vm.result = ObjVoid
|
||||||
return
|
return
|
||||||
@@ -3217,10 +3290,21 @@ class CmdCallDirect(
|
|||||||
frame.ensureScope().raiseIllegalState("bytecode runtime cannot call non-bytecode Statement")
|
frame.ensureScope().raiseIllegalState("bytecode runtime cannot call non-bytecode Statement")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val result = if (PerfFlags.SCOPE_POOL) {
|
val directFastResult = (callee as? BytecodeArgCallable)?.callWithArgsFast(frame.ensureScope(), args)
|
||||||
frame.ensureScope().withChildFrame(args) { child -> callee.callOn(child) }
|
val result = if (directFastResult != null) {
|
||||||
|
directFastResult
|
||||||
|
} else if (PerfFlags.SCOPE_POOL) {
|
||||||
|
frame.ensureScope().withChildFrame(args) { child ->
|
||||||
|
(callee as? BytecodeCallable)?.callOnFast(child) ?: callee.callOn(child)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
callee.callOn(frame.ensureScope().createChildScope(frame.ensureScope().pos, args = args))
|
val scope = frame.ensureScope()
|
||||||
|
if (callee is BytecodeLambdaCallable && callee.supportsDirectInvokeFastPath()) {
|
||||||
|
callee.invokeWithArgsFast(scope, args) ?: callee.invokeWithArgs(scope, args)
|
||||||
|
} else {
|
||||||
|
val child = scope.createChildScope(scope.pos, args = args)
|
||||||
|
(callee as? BytecodeCallable)?.callOnFast(child) ?: callee.callOn(child)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
frame.storeObjResult(dst, result)
|
frame.storeObjResult(dst, result)
|
||||||
return
|
return
|
||||||
@@ -3247,18 +3331,28 @@ class CmdCallSlot(
|
|||||||
frame.ensureScope().raiseUnset(message)
|
frame.ensureScope().raiseUnset(message)
|
||||||
}
|
}
|
||||||
val args = frame.buildArguments(argBase, argCount)
|
val args = frame.buildArguments(argBase, argCount)
|
||||||
val canPool = PerfFlags.SCOPE_POOL && callee !is Statement
|
|
||||||
val result = if (canPool) {
|
|
||||||
frame.ensureScope().withChildFrame(args) { child -> callee.callOn(child) }
|
|
||||||
} else {
|
|
||||||
val scope = frame.ensureScope()
|
val scope = frame.ensureScope()
|
||||||
|
val directFastResult = (callee as? BytecodeArgCallable)?.callWithArgsFast(scope, args)
|
||||||
|
val canPool = PerfFlags.SCOPE_POOL && callee !is Statement
|
||||||
|
val result = if (directFastResult != null) {
|
||||||
|
directFastResult
|
||||||
|
} else if (canPool) {
|
||||||
|
frame.ensureScope().withChildFrame(args) { child ->
|
||||||
|
(callee as? BytecodeCallable)?.callOnFast(child) ?: callee.callOn(child)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
if (callee is Statement) {
|
if (callee is Statement) {
|
||||||
val bytecodeBody = (callee as? BytecodeBodyProvider)?.bytecodeBody()
|
val bytecodeBody = (callee as? BytecodeBodyProvider)?.bytecodeBody()
|
||||||
if (callee !is BytecodeStatement && callee !is BytecodeCallable && bytecodeBody == null) {
|
if (callee !is BytecodeStatement && callee !is BytecodeCallable && bytecodeBody == null) {
|
||||||
scope.raiseIllegalState("bytecode runtime cannot call non-bytecode Statement")
|
scope.raiseIllegalState("bytecode runtime cannot call non-bytecode Statement")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
callee.callOn(scope.createChildScope(scope.pos, args = args))
|
if (callee is BytecodeLambdaCallable && callee.supportsDirectInvokeFastPath()) {
|
||||||
|
callee.invokeWithArgsFast(scope, args) ?: callee.invokeWithArgs(scope, args)
|
||||||
|
} else {
|
||||||
|
val child = scope.createChildScope(scope.pos, args = args)
|
||||||
|
(callee as? BytecodeCallable)?.callOnFast(child) ?: callee.callOn(child)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
frame.storeObjResult(dst, result)
|
frame.storeObjResult(dst, result)
|
||||||
return
|
return
|
||||||
@@ -3341,10 +3435,53 @@ class CmdListFillInt(
|
|||||||
val scope = frame.ensureScope()
|
val scope = frame.ensureScope()
|
||||||
val result = ObjList(LongArray(size))
|
val result = ObjList(LongArray(size))
|
||||||
for (i in 0 until size) {
|
for (i in 0 until size) {
|
||||||
|
val args = Arguments(ObjInt.of(i.toLong()))
|
||||||
val value = if (callable is BytecodeLambdaCallable && callable.supportsImplicitIntFillFastPath()) {
|
val value = if (callable is BytecodeLambdaCallable && callable.supportsImplicitIntFillFastPath()) {
|
||||||
callable.invokeImplicitIntArg(scope, i.toLong())
|
callable.invokeImplicitIntArgFast(scope, i.toLong()) ?: callable.invokeImplicitIntArg(scope, i.toLong())
|
||||||
|
} else if (callable is BytecodeArgCallable) {
|
||||||
|
callable.callWithArgsFast(scope, args) ?: run {
|
||||||
|
val child = scope.createChildScope(scope.pos, args = args)
|
||||||
|
(callable as? BytecodeCallable)?.callOnFast(child) ?: callable.callOn(child)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
callable.callOn(scope.createChildScope(scope.pos, args = Arguments(ObjInt.of(i.toLong()))))
|
val child = scope.createChildScope(scope.pos, args = args)
|
||||||
|
(callable as? BytecodeCallable)?.callOnFast(child) ?: callable.callOn(child)
|
||||||
|
}
|
||||||
|
val intValue = (value as? ObjInt)?.value ?: scope.raiseClassCastError("expected Int fill result")
|
||||||
|
result.setIntAtFast(i, intValue)
|
||||||
|
}
|
||||||
|
frame.storeObjResult(dst, result)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CmdListFillIntCap(
|
||||||
|
internal val sizeSlot: Int,
|
||||||
|
internal val capacitySlot: Int,
|
||||||
|
internal val callableSlot: Int,
|
||||||
|
internal val dst: Int,
|
||||||
|
) : Cmd() {
|
||||||
|
override suspend fun perform(frame: CmdFrame) {
|
||||||
|
val size = frame.getInt(sizeSlot).toInt()
|
||||||
|
if (size < 0) frame.ensureScope().raiseIllegalArgument("list size must be non-negative")
|
||||||
|
val capacity = frame.getInt(capacitySlot).toInt()
|
||||||
|
val actualCapacity = maxOf(size, capacity)
|
||||||
|
if (actualCapacity < 0) frame.ensureScope().raiseIllegalArgument("list capacity must be non-negative")
|
||||||
|
val callable = frame.storedSlotObj(callableSlot)
|
||||||
|
val scope = frame.ensureScope()
|
||||||
|
val result = ObjList(LongArray(actualCapacity), size)
|
||||||
|
for (i in 0 until size) {
|
||||||
|
val args = Arguments(ObjInt.of(i.toLong()))
|
||||||
|
val value = if (callable is BytecodeLambdaCallable && callable.supportsImplicitIntFillFastPath()) {
|
||||||
|
callable.invokeImplicitIntArgFast(scope, i.toLong()) ?: callable.invokeImplicitIntArg(scope, i.toLong())
|
||||||
|
} else if (callable is BytecodeArgCallable) {
|
||||||
|
callable.callWithArgsFast(scope, args) ?: run {
|
||||||
|
val child = scope.createChildScope(scope.pos, args = args)
|
||||||
|
(callable as? BytecodeCallable)?.callOnFast(child) ?: callable.callOn(child)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
val child = scope.createChildScope(scope.pos, args = args)
|
||||||
|
(callable as? BytecodeCallable)?.callOnFast(child) ?: callable.callOn(child)
|
||||||
}
|
}
|
||||||
val intValue = (value as? ObjInt)?.value ?: scope.raiseClassCastError("expected Int fill result")
|
val intValue = (value as? ObjInt)?.value ?: scope.raiseClassCastError("expected Int fill result")
|
||||||
result.setIntAtFast(i, intValue)
|
result.setIntAtFast(i, intValue)
|
||||||
@@ -3730,6 +3867,50 @@ class CmdCallMemberSlot(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class CmdListIotaInt(
|
||||||
|
internal val sizeSlot: Int,
|
||||||
|
internal val dst: Int,
|
||||||
|
) : Cmd() {
|
||||||
|
override suspend fun perform(frame: CmdFrame) {
|
||||||
|
val size = frame.getInt(sizeSlot).toInt()
|
||||||
|
if (size < 0) frame.ensureScope().raiseIllegalArgument("list size must be non-negative")
|
||||||
|
val values = LongArray(size)
|
||||||
|
for (i in 0 until size) {
|
||||||
|
values[i] = i.toLong()
|
||||||
|
}
|
||||||
|
frame.storeObjResult(dst, ObjList(values))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CmdListNewInt(
|
||||||
|
internal val sizeSlot: Int,
|
||||||
|
internal val dst: Int,
|
||||||
|
) : Cmd() {
|
||||||
|
override suspend fun perform(frame: CmdFrame) {
|
||||||
|
val size = frame.getInt(sizeSlot).toInt()
|
||||||
|
if (size < 0) frame.ensureScope().raiseIllegalArgument("list size must be non-negative")
|
||||||
|
frame.storeObjResult(dst, ObjList(LongArray(size)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CmdListNewIntCap(
|
||||||
|
internal val sizeSlot: Int,
|
||||||
|
internal val capacitySlot: Int,
|
||||||
|
internal val dst: Int,
|
||||||
|
) : Cmd() {
|
||||||
|
override suspend fun perform(frame: CmdFrame) {
|
||||||
|
val size = frame.getInt(sizeSlot).toInt()
|
||||||
|
if (size < 0) frame.ensureScope().raiseIllegalArgument("list size must be non-negative")
|
||||||
|
val capacity = frame.getInt(capacitySlot).toInt()
|
||||||
|
val actualCapacity = maxOf(size, capacity)
|
||||||
|
if (actualCapacity < 0) frame.ensureScope().raiseIllegalArgument("list capacity must be non-negative")
|
||||||
|
frame.storeObjResult(dst, ObjList(LongArray(actualCapacity), size))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
class CmdGetIndex(
|
class CmdGetIndex(
|
||||||
internal val targetSlot: Int,
|
internal val targetSlot: Int,
|
||||||
internal val indexSlot: Int,
|
internal val indexSlot: Int,
|
||||||
@@ -3834,6 +4015,7 @@ class CmdMakeLambda(internal val id: Int, internal val dst: Int) : Cmd() {
|
|||||||
captureNames = lambdaConst.captureNames,
|
captureNames = lambdaConst.captureNames,
|
||||||
paramSlotPlan = lambdaConst.paramSlotPlan,
|
paramSlotPlan = lambdaConst.paramSlotPlan,
|
||||||
argsDeclaration = lambdaConst.argsDeclaration,
|
argsDeclaration = lambdaConst.argsDeclaration,
|
||||||
|
supportsDirectInvokeFastPath = lambdaConst.supportsDirectInvokeFastPath,
|
||||||
preferredThisType = lambdaConst.preferredThisType,
|
preferredThisType = lambdaConst.preferredThisType,
|
||||||
returnLabels = lambdaConst.returnLabels,
|
returnLabels = lambdaConst.returnLabels,
|
||||||
pos = lambdaConst.pos
|
pos = lambdaConst.pos
|
||||||
@@ -3855,10 +4037,18 @@ class BytecodeLambdaCallable(
|
|||||||
private val captureNames: List<String>,
|
private val captureNames: List<String>,
|
||||||
private val paramSlotPlan: Map<String, Int>,
|
private val paramSlotPlan: Map<String, Int>,
|
||||||
private val argsDeclaration: ArgsDeclaration?,
|
private val argsDeclaration: ArgsDeclaration?,
|
||||||
|
private val supportsDirectInvokeFastPath: Boolean,
|
||||||
private val preferredThisType: String?,
|
private val preferredThisType: String?,
|
||||||
private val returnLabels: Set<String>,
|
private val returnLabels: Set<String>,
|
||||||
override val pos: Pos,
|
override val pos: Pos,
|
||||||
) : Statement(), BytecodeCallable {
|
) : Statement(), BytecodeCallable, BytecodeArgCallable {
|
||||||
|
private val slotPlanByName: Map<String, Int> by lazy(LazyThreadSafetyMode.NONE) { fn.localSlotPlanByName() }
|
||||||
|
private val declaredLocalNames: Set<String> by lazy(LazyThreadSafetyMode.NONE) {
|
||||||
|
fn.constants
|
||||||
|
.mapNotNull { it as? BytecodeConst.LocalDecl }
|
||||||
|
.mapTo(mutableSetOf()) { it.name }
|
||||||
|
}
|
||||||
|
|
||||||
private fun freezeRecord(record: ObjRecord): ObjRecord {
|
private fun freezeRecord(record: ObjRecord): ObjRecord {
|
||||||
if (record.isMutable) return record
|
if (record.isMutable) return record
|
||||||
val raw = record.value as Obj?
|
val raw = record.value as Obj?
|
||||||
@@ -3890,6 +4080,7 @@ class BytecodeLambdaCallable(
|
|||||||
captureNames = captureNames,
|
captureNames = captureNames,
|
||||||
paramSlotPlan = paramSlotPlan,
|
paramSlotPlan = paramSlotPlan,
|
||||||
argsDeclaration = argsDeclaration,
|
argsDeclaration = argsDeclaration,
|
||||||
|
supportsDirectInvokeFastPath = supportsDirectInvokeFastPath,
|
||||||
preferredThisType = preferredThisType,
|
preferredThisType = preferredThisType,
|
||||||
returnLabels = returnLabels,
|
returnLabels = returnLabels,
|
||||||
pos = pos
|
pos = pos
|
||||||
@@ -3906,6 +4097,7 @@ class BytecodeLambdaCallable(
|
|||||||
captureNames = captureNames,
|
captureNames = captureNames,
|
||||||
paramSlotPlan = paramSlotPlan,
|
paramSlotPlan = paramSlotPlan,
|
||||||
argsDeclaration = argsDeclaration,
|
argsDeclaration = argsDeclaration,
|
||||||
|
supportsDirectInvokeFastPath = supportsDirectInvokeFastPath,
|
||||||
preferredThisType = preferredThisType,
|
preferredThisType = preferredThisType,
|
||||||
returnLabels = returnLabels,
|
returnLabels = returnLabels,
|
||||||
pos = pos
|
pos = pos
|
||||||
@@ -3914,32 +4106,29 @@ class BytecodeLambdaCallable(
|
|||||||
|
|
||||||
fun supportsImplicitIntFillFastPath(): Boolean = argsDeclaration == null
|
fun supportsImplicitIntFillFastPath(): Boolean = argsDeclaration == null
|
||||||
|
|
||||||
suspend fun invokeImplicitIntArg(scope: Scope, arg: Long): Obj {
|
fun supportsDirectInvokeFastPath(): Boolean = supportsDirectInvokeFastPath
|
||||||
val context = scope.applyClosureForBytecode(closureScope, preferredThisType).also {
|
|
||||||
it.args = Arguments.EMPTY
|
private val fastPreboundLocalNames: Set<String> by lazy(LazyThreadSafetyMode.NONE) {
|
||||||
}
|
if (argsDeclaration == null) {
|
||||||
if (captureRecords != null) {
|
setOf("it")
|
||||||
context.captureRecords = captureRecords
|
} else {
|
||||||
context.captureNames = captureNames
|
argsDeclaration.params.mapTo(LinkedHashSet()) { it.name }
|
||||||
} else if (captureNames.isNotEmpty()) {
|
|
||||||
closureScope.raiseIllegalState("bytecode lambda capture records missing")
|
|
||||||
}
|
|
||||||
val binder: suspend (CmdFrame, Arguments) -> Unit = { frame, _ ->
|
|
||||||
paramSlotPlan["it"]?.let { itSlot ->
|
|
||||||
frame.frame.setInt(itSlot, arg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return try {
|
|
||||||
CmdVm().execute(fn, context, Arguments.EMPTY, binder)
|
|
||||||
} catch (e: ReturnException) {
|
|
||||||
if (e.label == null || returnLabels.contains(e.label)) e.result
|
|
||||||
else throw e
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun execute(scope: Scope): Obj {
|
private val supportsFastUndeclaredLocalInit: Boolean by lazy(LazyThreadSafetyMode.NONE) {
|
||||||
val context = scope.applyClosureForBytecode(closureScope, preferredThisType).also {
|
canFastSeedUndeclaredLocals(fn, declaredLocalNames, fastPreboundLocalNames)
|
||||||
it.args = scope.args
|
}
|
||||||
|
|
||||||
|
private fun supportsFastOnlyVm(arguments: Arguments): Boolean {
|
||||||
|
if (!supportsDirectInvokeFastPath || !fn.fastOnly) return false
|
||||||
|
if (!supportsFastUndeclaredLocalInit) return false
|
||||||
|
return argsDeclaration == null || argsDeclaration.supportsFastFrameBinding(arguments)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildContext(callScope: Scope, args: Arguments): Scope {
|
||||||
|
val context = callScope.applyClosureForBytecode(closureScope, preferredThisType).also {
|
||||||
|
it.args = args
|
||||||
}
|
}
|
||||||
if (captureRecords != null) {
|
if (captureRecords != null) {
|
||||||
context.captureRecords = captureRecords
|
context.captureRecords = captureRecords
|
||||||
@@ -3947,17 +4136,10 @@ class BytecodeLambdaCallable(
|
|||||||
} else if (captureNames.isNotEmpty()) {
|
} else if (captureNames.isNotEmpty()) {
|
||||||
closureScope.raiseIllegalState("bytecode lambda capture records missing")
|
closureScope.raiseIllegalState("bytecode lambda capture records missing")
|
||||||
}
|
}
|
||||||
if (argsDeclaration == null) {
|
return context
|
||||||
// Bound in the bytecode entry binder.
|
|
||||||
} else {
|
|
||||||
// args bound into frame slots in the bytecode entry binder
|
|
||||||
}
|
}
|
||||||
return try {
|
|
||||||
val declaredNames = fn.constants
|
private fun bindArgumentsFast(frame: CmdFrame, context: Scope, arguments: Arguments) {
|
||||||
.mapNotNull { it as? BytecodeConst.LocalDecl }
|
|
||||||
.mapTo(mutableSetOf()) { it.name }
|
|
||||||
val binder: suspend (CmdFrame, Arguments) -> Unit = { frame, arguments ->
|
|
||||||
val slotPlan = fn.localSlotPlanByName()
|
|
||||||
if (argsDeclaration == null) {
|
if (argsDeclaration == null) {
|
||||||
val l = arguments.list
|
val l = arguments.list
|
||||||
val itValue: Obj = when (l.size) {
|
val itValue: Obj = when (l.size) {
|
||||||
@@ -3965,7 +4147,7 @@ class BytecodeLambdaCallable(
|
|||||||
1 -> l[0]
|
1 -> l[0]
|
||||||
else -> ObjList(l.toMutableList())
|
else -> ObjList(l.toMutableList())
|
||||||
}
|
}
|
||||||
val itSlot = slotPlan["it"]
|
val itSlot = slotPlanByName["it"]
|
||||||
if (itSlot != null) {
|
if (itSlot != null) {
|
||||||
when (itValue) {
|
when (itValue) {
|
||||||
is ObjInt -> frame.frame.setInt(itSlot, itValue.value)
|
is ObjInt -> frame.frame.setInt(itSlot, itValue.value)
|
||||||
@@ -3975,17 +4157,33 @@ class BytecodeLambdaCallable(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
argsDeclaration.assignToFrame(
|
argsDeclaration.assignToFrameFast(
|
||||||
context,
|
context,
|
||||||
arguments,
|
arguments,
|
||||||
slotPlan,
|
slotPlanByName,
|
||||||
frame.frame
|
frame.frame
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun bindArguments(frame: CmdFrame, context: Scope, arguments: Arguments) {
|
||||||
|
if (argsDeclaration == null) {
|
||||||
|
bindArgumentsFast(frame, context, arguments)
|
||||||
|
} else {
|
||||||
|
argsDeclaration.assignToFrame(
|
||||||
|
context,
|
||||||
|
arguments,
|
||||||
|
slotPlanByName,
|
||||||
|
frame.frame
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun seedUndeclaredLocals(frame: CmdFrame, context: Scope) {
|
||||||
val localNames = frame.fn.localSlotNames
|
val localNames = frame.fn.localSlotNames
|
||||||
for (i in localNames.indices) {
|
for (i in localNames.indices) {
|
||||||
val name = localNames[i] ?: continue
|
val name = localNames[i] ?: continue
|
||||||
if (declaredNames.contains(name)) continue
|
if (declaredLocalNames.contains(name)) continue
|
||||||
val slotType = frame.getLocalSlotTypeCode(i)
|
val slotType = frame.getLocalSlotTypeCode(i)
|
||||||
if (slotType != SlotType.UNKNOWN.code && slotType != SlotType.OBJ.code) {
|
if (slotType != SlotType.UNKNOWN.code && slotType != SlotType.OBJ.code) {
|
||||||
continue
|
continue
|
||||||
@@ -4011,11 +4209,88 @@ class BytecodeLambdaCallable(
|
|||||||
frame.frame.setObj(i, value)
|
frame.frame.setObj(i, value)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
CmdVm().execute(fn, context, scope.args, binder)
|
|
||||||
|
suspend fun invokeImplicitIntArg(scope: Scope, arg: Long): Obj {
|
||||||
|
val context = buildContext(scope, Arguments.EMPTY)
|
||||||
|
val fastBinder: (CmdFrame, Arguments) -> Unit = { frame, _ ->
|
||||||
|
slotPlanByName["it"]?.let { itSlot ->
|
||||||
|
frame.frame.setInt(itSlot, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
val vm = CmdVm()
|
||||||
|
if (supportsFastOnlyVm(Arguments.EMPTY)) {
|
||||||
|
vm.executeFastOnly(fn, context, Arguments.EMPTY, fastBinder)
|
||||||
|
} else {
|
||||||
|
val binder: suspend (CmdFrame, Arguments) -> Unit = { frame, _ ->
|
||||||
|
slotPlanByName["it"]?.let { itSlot ->
|
||||||
|
frame.frame.setInt(itSlot, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
vm.execute(fn, context, Arguments.EMPTY, binder)
|
||||||
|
}
|
||||||
|
} catch (e: ReturnException) {
|
||||||
|
if (e.label == null || returnLabels.contains(e.label)) e.result
|
||||||
|
else throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun invokeImplicitIntArgFast(scope: Scope, arg: Long): Obj? {
|
||||||
|
if (!supportsFastOnlyVm(Arguments.EMPTY)) return null
|
||||||
|
val context = buildContext(scope, Arguments.EMPTY)
|
||||||
|
val binder: (CmdFrame, Arguments) -> Unit = { frame, _ ->
|
||||||
|
slotPlanByName["it"]?.let { itSlot ->
|
||||||
|
frame.frame.setInt(itSlot, arg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
CmdVm().executeFastOnlyNoSuspend(fn, context, Arguments.EMPTY, binder)
|
||||||
} catch (e: ReturnException) {
|
} catch (e: ReturnException) {
|
||||||
if (e.label == null || returnLabels.contains(e.label)) e.result else throw e
|
if (e.label == null || returnLabels.contains(e.label)) e.result else throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun invokeWithArgs(scope: Scope, args: Arguments): Obj {
|
||||||
|
val context = buildContext(scope, args)
|
||||||
|
return try {
|
||||||
|
val vm = CmdVm()
|
||||||
|
if (supportsFastOnlyVm(args)) {
|
||||||
|
val binder: (CmdFrame, Arguments) -> Unit = { frame, arguments ->
|
||||||
|
bindArgumentsFast(frame, context, arguments)
|
||||||
|
}
|
||||||
|
vm.executeFastOnly(fn, context, args, binder)
|
||||||
|
} else {
|
||||||
|
val binder: suspend (CmdFrame, Arguments) -> Unit = { frame, arguments ->
|
||||||
|
bindArguments(frame, context, arguments)
|
||||||
|
seedUndeclaredLocals(frame, context)
|
||||||
|
}
|
||||||
|
vm.execute(fn, context, args, binder)
|
||||||
|
}
|
||||||
|
} catch (e: ReturnException) {
|
||||||
|
if (e.label == null || returnLabels.contains(e.label)) e.result else throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun invokeWithArgsFast(scope: Scope, args: Arguments): Obj? {
|
||||||
|
if (!supportsFastOnlyVm(args)) return null
|
||||||
|
val context = buildContext(scope, args)
|
||||||
|
val binder: (CmdFrame, Arguments) -> Unit = { frame, arguments ->
|
||||||
|
bindArgumentsFast(frame, context, arguments)
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
CmdVm().executeFastOnlyNoSuspend(fn, context, args, binder)
|
||||||
|
} catch (e: ReturnException) {
|
||||||
|
if (e.label == null || returnLabels.contains(e.label)) e.result else throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun callWithArgsFast(scope: Scope, args: Arguments): Obj? = invokeWithArgsFast(scope, args)
|
||||||
|
|
||||||
|
override fun callOnFast(scope: Scope): Obj? = invokeWithArgsFast(scope, scope.args)
|
||||||
|
|
||||||
|
override suspend fun execute(scope: Scope): Obj {
|
||||||
|
return invokeWithArgs(scope, scope.args)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
class CmdIterPush(internal val iterSlot: Int) : Cmd() {
|
class CmdIterPush(internal val iterSlot: Int) : Cmd() {
|
||||||
@@ -4174,10 +4449,15 @@ class CmdFrame(
|
|||||||
} else {
|
} else {
|
||||||
val value = record.value
|
val value = record.value
|
||||||
if (!record.isMutable && value is FrameSlotRef) {
|
if (!record.isMutable && value is FrameSlotRef) {
|
||||||
val resolved = value.peekValue()
|
val resolved = value.resolvedCaptureValueOrNull()
|
||||||
if (resolved != null) {
|
if (resolved != null) {
|
||||||
if (value.refersTo(frame, localIndex)) continue
|
if (value.refersTo(frame, localIndex)) continue
|
||||||
frame.setObj(localIndex, value.read())
|
when (resolved) {
|
||||||
|
is ObjInt -> frame.setInt(localIndex, resolved.value)
|
||||||
|
is ObjReal -> frame.setReal(localIndex, resolved.value)
|
||||||
|
is ObjBool -> frame.setBool(localIndex, resolved.value)
|
||||||
|
else -> frame.setObj(localIndex, resolved)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
frame.setObj(localIndex, value)
|
frame.setObj(localIndex, value)
|
||||||
}
|
}
|
||||||
@@ -4213,9 +4493,14 @@ class CmdFrame(
|
|||||||
} else {
|
} else {
|
||||||
val value = record.value
|
val value = record.value
|
||||||
if (!record.isMutable && value is FrameSlotRef) {
|
if (!record.isMutable && value is FrameSlotRef) {
|
||||||
val resolved = value.peekValue()
|
val resolved = value.resolvedCaptureValueOrNull()
|
||||||
if (resolved != null) {
|
if (resolved != null) {
|
||||||
frame.setObj(idx, value.read())
|
when (resolved) {
|
||||||
|
is ObjInt -> frame.setInt(idx, resolved.value)
|
||||||
|
is ObjReal -> frame.setReal(idx, resolved.value)
|
||||||
|
is ObjBool -> frame.setBool(idx, resolved.value)
|
||||||
|
else -> frame.setObj(idx, resolved)
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
frame.setObj(idx, value)
|
frame.setObj(idx, value)
|
||||||
}
|
}
|
||||||
@@ -4267,7 +4552,7 @@ class CmdFrame(
|
|||||||
type = inherited.type
|
type = inherited.type
|
||||||
)
|
)
|
||||||
copied.delegate = inherited.delegate
|
copied.delegate = inherited.delegate
|
||||||
return@mapIndexed copied
|
return@mapIndexed freezeImmutableCaptureRecord(copied)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val isMutable = fn.localSlotMutables.getOrNull(localIndex) ?: false
|
val isMutable = fn.localSlotMutables.getOrNull(localIndex) ?: false
|
||||||
@@ -4279,15 +4564,25 @@ class CmdFrame(
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
val raw = frame.getRawObj(localIndex)
|
val raw = frame.getRawObj(localIndex)
|
||||||
if (raw == null && name != null) {
|
// For primitive-typed slots (INT/REAL/BOOL), getRawObj returns null
|
||||||
|
// but the value exists in the typed slot array. Skip the scope name
|
||||||
|
// lookup to avoid finding a same-named symbol higher in the scope chain
|
||||||
|
// (e.g., a List.size property when capturing a `size: Int` parameter).
|
||||||
|
val isPrimitiveSlot = when (frame.getSlotTypeCode(localIndex)) {
|
||||||
|
SlotType.INT.code, SlotType.REAL.code, SlotType.BOOL.code -> true
|
||||||
|
else -> false
|
||||||
|
}
|
||||||
|
if (raw == null && name != null && !isPrimitiveSlot) {
|
||||||
val record = findNamedExistingRecord(scope, name)
|
val record = findNamedExistingRecord(scope, name)
|
||||||
if (record != null) {
|
if (record != null) {
|
||||||
val value = record.value
|
val value = record.value
|
||||||
return@mapIndexed when (value) {
|
return@mapIndexed freezeImmutableCaptureRecord(
|
||||||
|
when (value) {
|
||||||
is FrameSlotRef -> ObjRecord(value, isMutable)
|
is FrameSlotRef -> ObjRecord(value, isMutable)
|
||||||
is RecordSlotRef -> ObjRecord(value, isMutable)
|
is RecordSlotRef -> ObjRecord(value, isMutable)
|
||||||
else -> ObjRecord(value, isMutable)
|
else -> ObjRecord(value, isMutable)
|
||||||
}
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if (hasNamedScopeBinding(scope, name)) {
|
if (hasNamedScopeBinding(scope, name)) {
|
||||||
throw ScriptError(
|
throw ScriptError(
|
||||||
@@ -4296,11 +4591,13 @@ class CmdFrame(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
freezeImmutableCaptureRecord(
|
||||||
when (raw) {
|
when (raw) {
|
||||||
is FrameSlotRef -> ObjRecord(raw, isMutable)
|
is FrameSlotRef -> ObjRecord(raw, isMutable)
|
||||||
is RecordSlotRef -> ObjRecord(raw, isMutable)
|
is RecordSlotRef -> ObjRecord(raw, isMutable)
|
||||||
else -> ObjRecord(FrameSlotRef(frame, localIndex), isMutable)
|
else -> ObjRecord(FrameSlotRef(frame, localIndex), isMutable)
|
||||||
}
|
}
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4446,6 +4743,19 @@ class CmdFrame(
|
|||||||
return ExecutionError(errorObject, pos, message, t)
|
return ExecutionError(errorObject, pos, message, t)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun normalizeThrowableFast(t: Throwable): Throwable {
|
||||||
|
if (t is ExecutionError || t is ReturnException || t is LoopBreakContinueException) return t
|
||||||
|
val parentScope = ensureScope()
|
||||||
|
val pos = (t as? ScriptError)?.pos ?: currentErrorPos() ?: parentScope.pos
|
||||||
|
val throwScope = parentScope.createChildScope(pos = pos)
|
||||||
|
val message = when (t) {
|
||||||
|
is ScriptError -> t.errorMessage
|
||||||
|
else -> t.message ?: t.toString()
|
||||||
|
}
|
||||||
|
val errorObject = ObjUnknownException(throwScope, message)
|
||||||
|
return ExecutionError(errorObject, pos, message, t)
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun handleException(t: Throwable): Boolean {
|
suspend fun handleException(t: Throwable): Boolean {
|
||||||
val handler = tryStack.lastOrNull() ?: return false
|
val handler = tryStack.lastOrNull() ?: return false
|
||||||
vmIterDebug {
|
vmIterDebug {
|
||||||
@@ -5400,6 +5710,14 @@ class CmdFrame(
|
|||||||
if (index < target.slotCount) return index
|
if (index < target.slotCount) return index
|
||||||
return index
|
return index
|
||||||
}
|
}
|
||||||
|
if (target.hasSlotPlanConflict(mapOf(name to index))) {
|
||||||
|
val record = target.getLocalRecordDirect(name)
|
||||||
|
?: target.localBindings[name]
|
||||||
|
?: target.parent?.get(name)
|
||||||
|
?: target.get(name)
|
||||||
|
?: ObjRecord(ObjUnset, isMutable = true)
|
||||||
|
return target.allocateSlotFor(name, record)
|
||||||
|
}
|
||||||
target.applySlotPlan(mapOf(name to index))
|
target.applySlotPlan(mapOf(name to index))
|
||||||
val existing = target.getLocalRecordDirect(name) ?: target.localBindings[name]
|
val existing = target.getLocalRecordDirect(name) ?: target.localBindings[name]
|
||||||
if (existing != null) {
|
if (existing != null) {
|
||||||
|
|||||||
@@ -175,6 +175,8 @@ enum class Opcode(val code: Int) {
|
|||||||
CALL_SLOT(0x93),
|
CALL_SLOT(0x93),
|
||||||
CALL_BRIDGE_SLOT(0x94),
|
CALL_BRIDGE_SLOT(0x94),
|
||||||
|
|
||||||
|
LIST_NEW_INT(0xA0),
|
||||||
|
LIST_IOTA_INT(0xA1),
|
||||||
GET_INDEX(0xA2),
|
GET_INDEX(0xA2),
|
||||||
SET_INDEX(0xA3),
|
SET_INDEX(0xA3),
|
||||||
GET_INDEX_INT(0xA4),
|
GET_INDEX_INT(0xA4),
|
||||||
@@ -188,6 +190,8 @@ enum class Opcode(val code: Int) {
|
|||||||
GET_DYNAMIC_MEMBER(0xAC),
|
GET_DYNAMIC_MEMBER(0xAC),
|
||||||
SET_DYNAMIC_MEMBER(0xAD),
|
SET_DYNAMIC_MEMBER(0xAD),
|
||||||
CALL_DYNAMIC_MEMBER(0xAE),
|
CALL_DYNAMIC_MEMBER(0xAE),
|
||||||
|
LIST_NEW_INT_CAP(0xAF),
|
||||||
|
LIST_FILL_INT_CAP(0xB0),
|
||||||
|
|
||||||
RESOLVE_SCOPE_SLOT(0xB1),
|
RESOLVE_SCOPE_SLOT(0xB1),
|
||||||
LOAD_OBJ_ADDR(0xB2),
|
LOAD_OBJ_ADDR(0xB2),
|
||||||
|
|||||||
@@ -17,7 +17,58 @@
|
|||||||
package net.sergeych.lyng.bytecode
|
package net.sergeych.lyng.bytecode
|
||||||
|
|
||||||
import net.sergeych.lyng.Scope
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.FrameSlotRef
|
||||||
|
import net.sergeych.lyng.RecordSlotRef
|
||||||
|
import net.sergeych.lyng.ScopeSlotRef
|
||||||
import net.sergeych.lyng.obj.ObjRecord
|
import net.sergeych.lyng.obj.ObjRecord
|
||||||
|
import net.sergeych.lyng.obj.ObjProperty
|
||||||
|
|
||||||
|
internal fun canFastSeedUndeclaredLocals(
|
||||||
|
fn: CmdFunction,
|
||||||
|
declaredLocalNames: Set<String>,
|
||||||
|
preboundLocalNames: Set<String>
|
||||||
|
): Boolean {
|
||||||
|
if (fn.localSlotNames.isEmpty()) return true
|
||||||
|
for (i in fn.localSlotNames.indices) {
|
||||||
|
val name = fn.localSlotNames[i] ?: continue
|
||||||
|
if (declaredLocalNames.contains(name)) continue
|
||||||
|
if (fn.localSlotCaptures.getOrNull(i) == true) continue
|
||||||
|
if (preboundLocalNames.contains(name)) continue
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun trySeedFrameLocalsFromScopeFast(frame: CmdFrame, scope: Scope): Boolean {
|
||||||
|
val localNames = frame.fn.localSlotNames
|
||||||
|
if (localNames.isEmpty()) return true
|
||||||
|
val base = frame.fn.scopeSlotCount
|
||||||
|
for (i in localNames.indices) {
|
||||||
|
val name = localNames[i] ?: continue
|
||||||
|
val slotType = frame.getLocalSlotTypeCode(i)
|
||||||
|
if (slotType != SlotType.UNKNOWN.code && slotType != SlotType.OBJ.code) continue
|
||||||
|
if (slotType == SlotType.OBJ.code && frame.frame.getRawObj(i) != null) continue
|
||||||
|
val record = scope.getLocalRecordDirect(name)
|
||||||
|
?: scope.chainLookupIgnoreClosure(name, followClosure = true)
|
||||||
|
?: continue
|
||||||
|
val value = when {
|
||||||
|
record.type == ObjRecord.Type.Delegated -> return false
|
||||||
|
record.type == ObjRecord.Type.Property -> return false
|
||||||
|
record.value is ObjProperty -> return false
|
||||||
|
else -> when (val direct = record.value) {
|
||||||
|
is FrameSlotRef -> direct.resolvedCaptureValueOrNull() ?: return false
|
||||||
|
is RecordSlotRef -> direct.resolvedCaptureValueOrNull() ?: return false
|
||||||
|
is ScopeSlotRef -> direct.resolvedCaptureValueOrNull() ?: return false
|
||||||
|
else -> direct
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (value is FrameSlotRef && value.refersTo(frame.frame, i)) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
frame.setObjUnchecked(base + i, value)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
internal suspend fun seedFrameLocalsFromScope(frame: CmdFrame, scope: Scope) {
|
internal suspend fun seedFrameLocalsFromScope(frame: CmdFrame, scope: Scope) {
|
||||||
val localNames = frame.fn.localSlotNames
|
val localNames = frame.fn.localSlotNames
|
||||||
|
|||||||
@@ -99,10 +99,11 @@ fun ObjClass.addFnDoc(
|
|||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
tags: Map<String, List<String>> = emptyMap(),
|
tags: Map<String, List<String>> = emptyMap(),
|
||||||
moduleName: String? = null,
|
moduleName: String? = null,
|
||||||
|
callSignature: net.sergeych.lyng.CallSignature? = null,
|
||||||
code: suspend ScopeFacade.() -> Obj
|
code: suspend ScopeFacade.() -> Obj
|
||||||
) {
|
) {
|
||||||
// Register runtime method
|
// Register runtime method
|
||||||
addFn(name, isOpen, visibility, code = code)
|
addFn(name, isOpen, visibility, callSignature = callSignature, code = code)
|
||||||
// Register docs for the member under this class
|
// Register docs for the member under this class
|
||||||
BuiltinDocRegistry.module(moduleName ?: ownerModuleNameFromClassOrUnknown()) {
|
BuiltinDocRegistry.module(moduleName ?: ownerModuleNameFromClassOrUnknown()) {
|
||||||
classDoc(this@addFnDoc.className, doc = "") {
|
classDoc(this@addFnDoc.className, doc = "") {
|
||||||
@@ -137,9 +138,10 @@ fun ObjClass.addClassFnDoc(
|
|||||||
isOpen: Boolean = false,
|
isOpen: Boolean = false,
|
||||||
tags: Map<String, List<String>> = emptyMap(),
|
tags: Map<String, List<String>> = emptyMap(),
|
||||||
moduleName: String? = null,
|
moduleName: String? = null,
|
||||||
|
callSignature: net.sergeych.lyng.CallSignature? = null,
|
||||||
code: suspend ScopeFacade.() -> Obj
|
code: suspend ScopeFacade.() -> Obj
|
||||||
) {
|
) {
|
||||||
addClassFn(name, isOpen, code)
|
addClassFn(name, isOpen, callSignature, code)
|
||||||
BuiltinDocRegistry.module(moduleName ?: ownerModuleNameFromClassOrUnknown()) {
|
BuiltinDocRegistry.module(moduleName ?: ownerModuleNameFromClassOrUnknown()) {
|
||||||
classDoc(this@addClassFnDoc.className, doc = "") {
|
classDoc(this@addClassFnDoc.className, doc = "") {
|
||||||
method(name = name, doc = doc, params = params, returns = returns, isStatic = true, tags = tags)
|
method(name = name, doc = doc, params = params, returns = returns, isStatic = true, tags = tags)
|
||||||
|
|||||||
@@ -30,6 +30,8 @@ class LambdaFnRef(
|
|||||||
val argsDeclaration: ArgsDeclaration?,
|
val argsDeclaration: ArgsDeclaration?,
|
||||||
val captureEntries: List<LambdaCaptureEntry>,
|
val captureEntries: List<LambdaCaptureEntry>,
|
||||||
val inferredReturnClass: ObjClass?,
|
val inferredReturnClass: ObjClass?,
|
||||||
|
val inlineBodyRef: ObjRef?,
|
||||||
|
val supportsDirectInvokeFastPath: Boolean,
|
||||||
val preferredThisType: String?,
|
val preferredThisType: String?,
|
||||||
val wrapAsExtensionCallable: Boolean,
|
val wrapAsExtensionCallable: Boolean,
|
||||||
val returnLabels: Set<String>,
|
val returnLabels: Set<String>,
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import kotlinx.serialization.json.Json
|
|||||||
import kotlinx.serialization.json.JsonElement
|
import kotlinx.serialization.json.JsonElement
|
||||||
import kotlinx.serialization.json.JsonNull
|
import kotlinx.serialization.json.JsonNull
|
||||||
import kotlinx.serialization.serializer
|
import kotlinx.serialization.serializer
|
||||||
|
import net.sergeych.lyng.BytecodeCallable
|
||||||
import net.sergeych.lyng.*
|
import net.sergeych.lyng.*
|
||||||
import net.sergeych.lyng.InteropOperator
|
import net.sergeych.lyng.InteropOperator
|
||||||
import net.sergeych.lyng.OperatorInteropRegistry
|
import net.sergeych.lyng.OperatorInteropRegistry
|
||||||
@@ -723,40 +724,39 @@ open class Obj {
|
|||||||
scope.raiseNotImplemented()
|
scope.raiseNotImplemented()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun invoke(scope: Scope, thisObj: Obj, args: Arguments, declaringClass: ObjClass? = null): Obj {
|
private suspend fun invokeWithBoundScope(
|
||||||
val usePool = PerfFlags.SCOPE_POOL && this !is Statement
|
scope: Scope,
|
||||||
|
args: Arguments,
|
||||||
|
thisObj: Obj,
|
||||||
|
declaringClass: ObjClass? = null,
|
||||||
|
atPos: Pos = scope.pos
|
||||||
|
): Obj {
|
||||||
|
val usePool = PerfFlags.SCOPE_POOL && this !is Statement && atPos == scope.pos
|
||||||
return if (usePool) {
|
return if (usePool) {
|
||||||
scope.withChildFrame(args, newThisObj = thisObj) { child ->
|
scope.withChildFrame(args, newThisObj = thisObj) { child ->
|
||||||
if (declaringClass != null) child.currentClassCtx = declaringClass
|
if (declaringClass != null) child.currentClassCtx = declaringClass
|
||||||
callOn(child)
|
(this as? BytecodeCallable)?.callOnFast(child) ?: callOn(child)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
callOn(scope.createChildScope(scope.pos, args = args, newThisObj = thisObj).also {
|
val child = scope.createChildScope(atPos, args = args, newThisObj = thisObj).also {
|
||||||
if (declaringClass != null) it.currentClassCtx = declaringClass
|
if (declaringClass != null) it.currentClassCtx = declaringClass
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
(this as? BytecodeCallable)?.callOnFast(child) ?: callOn(child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun invoke(scope: Scope, thisObj: Obj, args: Arguments, declaringClass: ObjClass? = null): Obj {
|
||||||
|
return invokeWithBoundScope(scope, args, thisObj, declaringClass)
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun invoke(scope: Scope, thisObj: Obj, vararg args: Obj): Obj =
|
suspend fun invoke(scope: Scope, thisObj: Obj, vararg args: Obj): Obj =
|
||||||
callOn(
|
invokeWithBoundScope(scope, Arguments(args.toList()), thisObj)
|
||||||
scope.createChildScope(
|
|
||||||
scope.pos,
|
|
||||||
args = Arguments(args.toList()),
|
|
||||||
newThisObj = thisObj
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
suspend fun invoke(scope: Scope, thisObj: Obj): Obj =
|
suspend fun invoke(scope: Scope, thisObj: Obj): Obj =
|
||||||
callOn(
|
invokeWithBoundScope(scope, Arguments.EMPTY, thisObj)
|
||||||
scope.createChildScope(
|
|
||||||
scope.pos,
|
|
||||||
args = Arguments.EMPTY,
|
|
||||||
newThisObj = thisObj
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
suspend fun invoke(scope: Scope, atPos: Pos, thisObj: Obj, args: Arguments): Obj =
|
suspend fun invoke(scope: Scope, atPos: Pos, thisObj: Obj, args: Arguments): Obj =
|
||||||
callOn(scope.createChildScope(atPos, args = args, newThisObj = thisObj))
|
invokeWithBoundScope(scope, args, thisObj, atPos = atPos)
|
||||||
|
|
||||||
|
|
||||||
val asReadonly: ObjRecord by lazy { ObjRecord(this, false) }
|
val asReadonly: ObjRecord by lazy { ObjRecord(this, false) }
|
||||||
@@ -828,7 +828,13 @@ open class Obj {
|
|||||||
name = "let",
|
name = "let",
|
||||||
doc = "Calls the specified function block with `this` value as its argument and returns its result.",
|
doc = "Calls the specified function block with `this` value as its argument and returns its result.",
|
||||||
params = listOf(ParamDoc("block")),
|
params = listOf(ParamDoc("block")),
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.UNARY_ARGUMENT,
|
||||||
|
result = CallSignature.ResultMode.BLOCK_RESULT
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
call(args.firstAndOnly(), Arguments(thisObj))
|
call(args.firstAndOnly(), Arguments(thisObj))
|
||||||
}
|
}
|
||||||
@@ -836,7 +842,13 @@ open class Obj {
|
|||||||
name = "apply",
|
name = "apply",
|
||||||
doc = "Calls the specified function block with `this` value as its receiver and returns `this` value.",
|
doc = "Calls the specified function block with `this` value as its receiver and returns `this` value.",
|
||||||
params = listOf(ParamDoc("block")),
|
params = listOf(ParamDoc("block")),
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.RECEIVER,
|
||||||
|
result = CallSignature.ResultMode.RETURN_RECEIVER
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
val body = args.firstAndOnly()
|
val body = args.firstAndOnly()
|
||||||
val scope = requireScope()
|
val scope = requireScope()
|
||||||
@@ -852,7 +864,13 @@ open class Obj {
|
|||||||
name = "also",
|
name = "also",
|
||||||
doc = "Calls the specified function block with `this` value as its argument and returns `this` value.",
|
doc = "Calls the specified function block with `this` value as its argument and returns `this` value.",
|
||||||
params = listOf(ParamDoc("block")),
|
params = listOf(ParamDoc("block")),
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.UNARY_ARGUMENT,
|
||||||
|
result = CallSignature.ResultMode.RETURN_RECEIVER
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
call(args.firstAndOnly(), Arguments(thisObj))
|
call(args.firstAndOnly(), Arguments(thisObj))
|
||||||
thisObj
|
thisObj
|
||||||
@@ -861,7 +879,13 @@ open class Obj {
|
|||||||
name = "run",
|
name = "run",
|
||||||
doc = "Calls the specified function block with `this` value as its receiver and returns its result.",
|
doc = "Calls the specified function block with `this` value as its receiver and returns its result.",
|
||||||
params = listOf(ParamDoc("block")),
|
params = listOf(ParamDoc("block")),
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.RECEIVER,
|
||||||
|
result = CallSignature.ResultMode.BLOCK_RESULT
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
call(args.firstAndOnly())
|
call(args.firstAndOnly())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import net.sergeych.lyng.ScopeFacade
|
||||||
|
import net.sergeych.lyng.requiredArg
|
||||||
|
|
||||||
|
internal fun ObjClass.bindClassFn(name: String, code: suspend ScopeFacade.() -> Obj) {
|
||||||
|
val callable = ObjExternCallable.fromBridge { code() }
|
||||||
|
val memberRecord = members[name]
|
||||||
|
val classScopeRecord = classScope?.objects?.get(name)
|
||||||
|
if (memberRecord != null) {
|
||||||
|
val methodId = ensureMethodIdForBridge(name, memberRecord)
|
||||||
|
val newRecord = memberRecord.copy(
|
||||||
|
value = callable,
|
||||||
|
type = ObjRecord.Type.Fun,
|
||||||
|
methodId = methodId,
|
||||||
|
isAbstract = false,
|
||||||
|
)
|
||||||
|
replaceMemberForBridge(name, newRecord)
|
||||||
|
if (classScopeRecord != null) {
|
||||||
|
replaceClassScopeMemberForBridge(name, newRecord)
|
||||||
|
}
|
||||||
|
} else if (classScopeRecord != null) {
|
||||||
|
val methodId = ensureMethodIdForBridge(name, classScopeRecord)
|
||||||
|
replaceClassScopeMemberForBridge(
|
||||||
|
name,
|
||||||
|
classScopeRecord.copy(
|
||||||
|
value = callable,
|
||||||
|
type = ObjRecord.Type.Fun,
|
||||||
|
methodId = methodId,
|
||||||
|
isAbstract = false,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
addClassFn(name, code = code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun ObjClass.bindProperty(
|
||||||
|
name: String,
|
||||||
|
getter: (suspend ScopeFacade.() -> Obj)? = null,
|
||||||
|
setter: (suspend ScopeFacade.(Obj) -> Unit)? = null,
|
||||||
|
) {
|
||||||
|
val g = getter?.let { ObjExternCallable.fromBridge { it() } }
|
||||||
|
val s = setter?.let { ObjExternCallable.fromBridge { it(requiredArg(0)); ObjVoid } }
|
||||||
|
val prop = ObjProperty(name, g, s)
|
||||||
|
val existing = members[name]
|
||||||
|
if (existing != null) {
|
||||||
|
val newRecord = existing.copy(
|
||||||
|
value = prop,
|
||||||
|
type = ObjRecord.Type.Property,
|
||||||
|
methodId = ensureMethodIdForBridge(name, existing),
|
||||||
|
fieldId = null,
|
||||||
|
isAbstract = false,
|
||||||
|
)
|
||||||
|
replaceMemberForBridge(name, newRecord)
|
||||||
|
if (classScope?.objects?.containsKey(name) == true) {
|
||||||
|
replaceClassScopeMemberForBridge(name, newRecord)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
addProperty(name, getter = getter, setter = setter)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
|
import kotlinx.coroutines.channels.Channel
|
||||||
|
import kotlinx.coroutines.channels.ClosedReceiveChannelException
|
||||||
|
import kotlinx.coroutines.channels.ClosedSendChannelException
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.miniast.ParamDoc
|
||||||
|
import net.sergeych.lyng.miniast.addFnDoc
|
||||||
|
import net.sergeych.lyng.miniast.addPropertyDoc
|
||||||
|
import net.sergeych.lyng.miniast.type
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lyng-visible wrapper around Kotlin's [Channel].
|
||||||
|
*
|
||||||
|
* Construction:
|
||||||
|
* - `Channel()` – rendezvous channel (capacity 0, sender and receiver synchronise)
|
||||||
|
* - `Channel(n)` – buffered channel with capacity *n* (n > 0)
|
||||||
|
* - `Channel(Channel.UNLIMITED)` – unlimited-buffer channel
|
||||||
|
*
|
||||||
|
* Methods:
|
||||||
|
* - `send(value)` – suspend until the value is accepted by a receiver (or buffered)
|
||||||
|
* - `receive()` – suspend until a value is available; returns `null` when channel is closed and drained
|
||||||
|
* - `tryReceive()` – return the next value immediately, or `null` if none is available
|
||||||
|
* - `close()` – signal that no more values will be sent; pending receivers can still drain buffered items
|
||||||
|
*
|
||||||
|
* Properties:
|
||||||
|
* - `isClosedForSend: Bool`
|
||||||
|
* - `isClosedForReceive: Bool`
|
||||||
|
*/
|
||||||
|
class ObjChannel(val channel: Channel<Obj>) : Obj() {
|
||||||
|
|
||||||
|
override val objClass get() = type
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
val type = object : ObjClass("Channel") {
|
||||||
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
val capacity = scope.args.list.getOrNull(0)
|
||||||
|
?.let { (it as? ObjInt)?.value?.toInt() ?: scope.raiseIllegalArgument("Channel capacity must be an integer") }
|
||||||
|
?: Channel.RENDEZVOUS
|
||||||
|
return ObjChannel(Channel(capacity))
|
||||||
|
}
|
||||||
|
}.apply {
|
||||||
|
// Expose Channel.UNLIMITED as a static constant on the Channel class so scripts can write
|
||||||
|
// Channel(Channel.UNLIMITED).
|
||||||
|
addConst("UNLIMITED", ObjInt(Channel.UNLIMITED.toLong()))
|
||||||
|
|
||||||
|
addFnDoc(
|
||||||
|
name = "send",
|
||||||
|
doc = "Suspend until the value is accepted by a receiver (or placed into the buffer). " +
|
||||||
|
"Throws if the channel is already closed.",
|
||||||
|
params = listOf(ParamDoc("value", type("lyng.Any"))),
|
||||||
|
returns = type("lyng.Void"),
|
||||||
|
moduleName = "lyng.stdlib"
|
||||||
|
) {
|
||||||
|
val value = requiredArg<Obj>(0)
|
||||||
|
try {
|
||||||
|
thisAs<ObjChannel>().channel.send(value)
|
||||||
|
} catch (e: ClosedSendChannelException) {
|
||||||
|
raiseIllegalState("Channel is closed for send")
|
||||||
|
}
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
|
||||||
|
addFnDoc(
|
||||||
|
name = "receive",
|
||||||
|
doc = "Suspend until a value is available and return it, or return `null` when the channel " +
|
||||||
|
"is closed and all buffered items have been consumed.",
|
||||||
|
returns = type("lyng.Any"),
|
||||||
|
moduleName = "lyng.stdlib"
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
thisAs<ObjChannel>().channel.receive()
|
||||||
|
} catch (_: ClosedReceiveChannelException) {
|
||||||
|
ObjNull
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addFnDoc(
|
||||||
|
name = "tryReceive",
|
||||||
|
doc = "Return the next buffered value immediately without suspending, or `null` if the " +
|
||||||
|
"channel is empty or closed.",
|
||||||
|
returns = type("lyng.Any"),
|
||||||
|
moduleName = "lyng.stdlib"
|
||||||
|
) {
|
||||||
|
val result = thisAs<ObjChannel>().channel.tryReceive()
|
||||||
|
result.getOrNull() ?: ObjNull
|
||||||
|
}
|
||||||
|
|
||||||
|
addFnDoc(
|
||||||
|
name = "close",
|
||||||
|
doc = "Signal that no more values will be sent. Receivers can still drain any buffered items.",
|
||||||
|
returns = type("lyng.Void"),
|
||||||
|
moduleName = "lyng.stdlib"
|
||||||
|
) {
|
||||||
|
thisAs<ObjChannel>().channel.close()
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
|
||||||
|
addPropertyDoc(
|
||||||
|
name = "isClosedForSend",
|
||||||
|
doc = "Whether this channel is closed for sending (no more `send` calls are permitted).",
|
||||||
|
type = type("lyng.Bool"),
|
||||||
|
moduleName = "lyng.stdlib",
|
||||||
|
getter = { thisAs<ObjChannel>().channel.isClosedForSend.toObj() }
|
||||||
|
)
|
||||||
|
|
||||||
|
addPropertyDoc(
|
||||||
|
name = "isClosedForReceive",
|
||||||
|
doc = "Whether this channel is closed for receiving (closed and fully drained).",
|
||||||
|
type = type("lyng.Bool"),
|
||||||
|
moduleName = "lyng.stdlib",
|
||||||
|
getter = { thisAs<ObjChannel>().channel.isClosedForReceive.toObj() }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -809,7 +809,8 @@ open class ObjClass(
|
|||||||
if (initStmt is net.sergeych.lyng.Statement) {
|
if (initStmt is net.sergeych.lyng.Statement) {
|
||||||
executeBytecodeWithSeed(instance.instanceScope, initStmt, "instance init")
|
executeBytecodeWithSeed(instance.instanceScope, initStmt, "instance init")
|
||||||
} else {
|
} else {
|
||||||
initStmt.callOn(instance.instanceScope)
|
(initStmt as? net.sergeych.lyng.BytecodeCallable)?.callOnFast(instance.instanceScope)
|
||||||
|
?: initStmt.callOn(instance.instanceScope)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -821,13 +822,14 @@ open class ObjClass(
|
|||||||
c.instanceConstructor?.let { ctor ->
|
c.instanceConstructor?.let { ctor ->
|
||||||
val execScope =
|
val execScope =
|
||||||
instance.instanceScope.createChildScope(args = argsForThis ?: Arguments.EMPTY, newThisObj = instance)
|
instance.instanceScope.createChildScope(args = argsForThis ?: Arguments.EMPTY, newThisObj = instance)
|
||||||
ctor.callOn(execScope)
|
(ctor as? net.sergeych.lyng.BytecodeCallable)?.callOnFast(execScope) ?: ctor.callOn(execScope)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun callWithArgs(scope: Scope, vararg plainArgs: Obj): Obj {
|
suspend fun callWithArgs(scope: Scope, vararg plainArgs: Obj): Obj {
|
||||||
return callOn(scope.createChildScope(Arguments(*plainArgs)))
|
val child = scope.createChildScope(Arguments(*plainArgs))
|
||||||
|
return (this as? net.sergeych.lyng.BytecodeCallable)?.callOnFast(child) ?: callOn(child)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -847,6 +849,7 @@ open class ObjClass(
|
|||||||
fieldId: Int? = null,
|
fieldId: Int? = null,
|
||||||
methodId: Int? = null,
|
methodId: Int? = null,
|
||||||
typeDecl: net.sergeych.lyng.TypeDecl? = null,
|
typeDecl: net.sergeych.lyng.TypeDecl? = null,
|
||||||
|
callSignature: net.sergeych.lyng.CallSignature? = null,
|
||||||
): ObjRecord {
|
): ObjRecord {
|
||||||
// Validation of override rules: only for non-system declarations
|
// Validation of override rules: only for non-system declarations
|
||||||
var existing: ObjRecord? = null
|
var existing: ObjRecord? = null
|
||||||
@@ -947,6 +950,7 @@ open class ObjClass(
|
|||||||
isOverride = isOverride,
|
isOverride = isOverride,
|
||||||
isTransient = isTransient,
|
isTransient = isTransient,
|
||||||
type = type,
|
type = type,
|
||||||
|
callSignature = callSignature,
|
||||||
typeDecl = typeDecl,
|
typeDecl = typeDecl,
|
||||||
memberName = name,
|
memberName = name,
|
||||||
fieldId = effectiveFieldId,
|
fieldId = effectiveFieldId,
|
||||||
@@ -959,7 +963,7 @@ open class ObjClass(
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun initClassScope(): Scope {
|
private fun initClassScope(): Scope {
|
||||||
if (classScope == null) classScope = Scope()
|
if (classScope == null) classScope = Scope(parent = null)
|
||||||
return classScope!!
|
return classScope!!
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -973,7 +977,8 @@ open class ObjClass(
|
|||||||
isTransient: Boolean = false,
|
isTransient: Boolean = false,
|
||||||
type: ObjRecord.Type = ObjRecord.Type.Field,
|
type: ObjRecord.Type = ObjRecord.Type.Field,
|
||||||
fieldId: Int? = null,
|
fieldId: Int? = null,
|
||||||
methodId: Int? = null
|
methodId: Int? = null,
|
||||||
|
callSignature: net.sergeych.lyng.CallSignature? = null
|
||||||
): ObjRecord {
|
): ObjRecord {
|
||||||
initClassScope()
|
initClassScope()
|
||||||
val existing = classScope!!.objects[name]
|
val existing = classScope!!.objects[name]
|
||||||
@@ -1014,6 +1019,7 @@ open class ObjClass(
|
|||||||
writeVisibility,
|
writeVisibility,
|
||||||
recordType = type,
|
recordType = type,
|
||||||
isTransient = isTransient,
|
isTransient = isTransient,
|
||||||
|
callSignature = callSignature,
|
||||||
fieldId = effectiveFieldId,
|
fieldId = effectiveFieldId,
|
||||||
methodId = effectiveMethodId
|
methodId = effectiveMethodId
|
||||||
)
|
)
|
||||||
@@ -1033,6 +1039,7 @@ open class ObjClass(
|
|||||||
isOverride: Boolean = false,
|
isOverride: Boolean = false,
|
||||||
pos: Pos = Pos.builtIn,
|
pos: Pos = Pos.builtIn,
|
||||||
methodId: Int? = null,
|
methodId: Int? = null,
|
||||||
|
callSignature: net.sergeych.lyng.CallSignature? = null,
|
||||||
code: (suspend net.sergeych.lyng.ScopeFacade.() -> Obj)? = null
|
code: (suspend net.sergeych.lyng.ScopeFacade.() -> Obj)? = null
|
||||||
) {
|
) {
|
||||||
val stmt = code?.let { ObjExternCallable.fromBridge { it() } } ?: ObjNull
|
val stmt = code?.let { ObjExternCallable.fromBridge { it() } } ?: ObjNull
|
||||||
@@ -1040,7 +1047,8 @@ open class ObjClass(
|
|||||||
name, stmt, isMutable, visibility, writeVisibility, pos, declaringClass,
|
name, stmt, isMutable, visibility, writeVisibility, pos, declaringClass,
|
||||||
isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride,
|
isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride,
|
||||||
type = ObjRecord.Type.Fun,
|
type = ObjRecord.Type.Fun,
|
||||||
methodId = methodId
|
methodId = methodId,
|
||||||
|
callSignature = callSignature
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1072,8 +1080,19 @@ open class ObjClass(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun addClassConst(name: String, value: Obj) = createClassField(name, value)
|
fun addClassConst(name: String, value: Obj) = createClassField(name, value)
|
||||||
fun addClassFn(name: String, isOpen: Boolean = false, code: suspend net.sergeych.lyng.ScopeFacade.() -> Obj) {
|
fun addClassFn(
|
||||||
createClassField(name, ObjExternCallable.fromBridge { code() }, isOpen, type = ObjRecord.Type.Fun)
|
name: String,
|
||||||
|
isOpen: Boolean = false,
|
||||||
|
callSignature: net.sergeych.lyng.CallSignature? = null,
|
||||||
|
code: suspend net.sergeych.lyng.ScopeFacade.() -> Obj
|
||||||
|
) {
|
||||||
|
createClassField(
|
||||||
|
name,
|
||||||
|
ObjExternCallable.fromBridge { code() },
|
||||||
|
isOpen,
|
||||||
|
type = ObjRecord.Type.Fun,
|
||||||
|
callSignature = callSignature
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
package net.sergeych.lyng.obj
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
import kotlinx.coroutines.CompletableDeferred
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import net.sergeych.lyng.ExecutionError
|
||||||
import net.sergeych.lyng.Scope
|
import net.sergeych.lyng.Scope
|
||||||
import net.sergeych.lyng.miniast.ParamDoc
|
import net.sergeych.lyng.miniast.ParamDoc
|
||||||
import net.sergeych.lyng.miniast.addFnDoc
|
import net.sergeych.lyng.miniast.addFnDoc
|
||||||
@@ -43,6 +44,30 @@ class ObjCompletableDeferred(val completableDeferred: CompletableDeferred<Obj>):
|
|||||||
thisAs<ObjCompletableDeferred>().completableDeferred.complete(args.firstAndOnly())
|
thisAs<ObjCompletableDeferred>().completableDeferred.complete(args.firstAndOnly())
|
||||||
ObjVoid
|
ObjVoid
|
||||||
}
|
}
|
||||||
|
addFnDoc(
|
||||||
|
name = "completeExceptionally",
|
||||||
|
doc = "Fail this deferred with the given exception. Awaiting it will then throw that exception. " +
|
||||||
|
"Subsequent calls have no effect. The argument must be an `Exception` instance.",
|
||||||
|
params = listOf(ParamDoc("exception", type("lyng.Exception"))),
|
||||||
|
returns = type("lyng.Void"),
|
||||||
|
moduleName = "lyng.stdlib"
|
||||||
|
) {
|
||||||
|
val ex = requiredArg<Obj>(0)
|
||||||
|
val scope = requireScope()
|
||||||
|
val msg = when (ex) {
|
||||||
|
is ObjException -> ex.message.value
|
||||||
|
else -> ex.toString(scope).value
|
||||||
|
}
|
||||||
|
val pos = when (ex) {
|
||||||
|
is ObjException -> ex.scope.pos
|
||||||
|
else -> scope.pos
|
||||||
|
}
|
||||||
|
// Always carry the original Lyng object as errorObject so that
|
||||||
|
// assertThrows / catch clauses see the correct exception class.
|
||||||
|
val cause = ExecutionError(ex, pos, msg)
|
||||||
|
thisAs<ObjCompletableDeferred>().completableDeferred.completeExceptionally(cause)
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -18,13 +18,10 @@
|
|||||||
package net.sergeych.lyng.obj
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
import net.sergeych.lyng.*
|
import net.sergeych.lyng.*
|
||||||
import net.sergeych.lyng.miniast.addPropertyDoc
|
|
||||||
import net.sergeych.lyng.miniast.type
|
|
||||||
import net.sergeych.lyng.requiredArg
|
import net.sergeych.lyng.requiredArg
|
||||||
|
|
||||||
object ObjComplexSupport {
|
object ObjComplexSupport {
|
||||||
private object BoundMarker
|
private object BoundMarker
|
||||||
private val complexTypeDecl = TypeDecl.Simple("lyng.complex.Complex", false)
|
|
||||||
|
|
||||||
suspend fun bindTo(module: ModuleScope) {
|
suspend fun bindTo(module: ModuleScope) {
|
||||||
val complexClass = module.requireClass("Complex")
|
val complexClass = module.requireClass("Complex")
|
||||||
@@ -33,36 +30,20 @@ object ObjComplexSupport {
|
|||||||
|
|
||||||
val decimalModule = module.currentImportProvider.createModuleScope(module.pos, "lyng.decimal")
|
val decimalModule = module.currentImportProvider.createModuleScope(module.pos, "lyng.decimal")
|
||||||
val decimalClass = decimalModule.requireClass("Decimal")
|
val decimalClass = decimalModule.requireClass("Decimal")
|
||||||
|
decimalClass.bindProperty("re", getter = {
|
||||||
decimalClass.addPropertyDoc(
|
|
||||||
name = "re",
|
|
||||||
doc = "Convert this Decimal to a Complex with zero imaginary part.",
|
|
||||||
type = type("lyng.complex.Complex"),
|
|
||||||
moduleName = "lyng.complex",
|
|
||||||
getter = {
|
|
||||||
newComplex(
|
newComplex(
|
||||||
complexClass,
|
complexClass,
|
||||||
decimalToReal(thisObj),
|
decimalToReal(thisObj),
|
||||||
0.0
|
0.0
|
||||||
)
|
)
|
||||||
}
|
})
|
||||||
)
|
decimalClass.bindProperty("i", getter = {
|
||||||
decimalClass.members["re"] = decimalClass.members.getValue("re").copy(typeDecl = complexTypeDecl)
|
|
||||||
|
|
||||||
decimalClass.addPropertyDoc(
|
|
||||||
name = "i",
|
|
||||||
doc = "Convert this Decimal to a pure imaginary Complex after rounding to Real.",
|
|
||||||
type = type("lyng.complex.Complex"),
|
|
||||||
moduleName = "lyng.complex",
|
|
||||||
getter = {
|
|
||||||
newComplex(
|
newComplex(
|
||||||
complexClass,
|
complexClass,
|
||||||
0.0,
|
0.0,
|
||||||
decimalToReal(thisObj)
|
decimalToReal(thisObj)
|
||||||
)
|
)
|
||||||
}
|
})
|
||||||
)
|
|
||||||
decimalClass.members["i"] = decimalClass.members.getValue("i").copy(typeDecl = complexTypeDecl)
|
|
||||||
|
|
||||||
OperatorInteropRegistry.register(
|
OperatorInteropRegistry.register(
|
||||||
leftClass = decimalClass,
|
leftClass = decimalClass,
|
||||||
|
|||||||
@@ -106,15 +106,15 @@ object ObjDecimalSupport {
|
|||||||
decimalClass.addFn("toStringExpanded") {
|
decimalClass.addFn("toStringExpanded") {
|
||||||
ObjString(valueOf(thisObj).toStringExpanded())
|
ObjString(valueOf(thisObj).toStringExpanded())
|
||||||
}
|
}
|
||||||
decimalClass.addClassFn("fromInt") {
|
decimalClass.bindClassFn("fromInt") {
|
||||||
val value = requiredArg<ObjInt>(0).value
|
val value = requiredArg<ObjInt>(0).value
|
||||||
newInstance(decimalClass, IonBigDecimal.fromLong(value))
|
newInstance(decimalClass, IonBigDecimal.fromLong(value))
|
||||||
}
|
}
|
||||||
decimalClass.addClassFn("fromReal") {
|
decimalClass.bindClassFn("fromReal") {
|
||||||
val value = requiredArg<ObjReal>(0).value
|
val value = requiredArg<ObjReal>(0).value
|
||||||
newInstanceFromFiniteReal(decimalClass, value)
|
newInstanceFromFiniteReal(decimalClass, value)
|
||||||
}
|
}
|
||||||
decimalClass.addClassFn("fromString") {
|
decimalClass.bindClassFn("fromString") {
|
||||||
val value = requiredArg<ObjString>(0).value
|
val value = requiredArg<ObjString>(0).value
|
||||||
try {
|
try {
|
||||||
newInstance(decimalClass, IonBigDecimal.parseStringWithMode(value))
|
newInstance(decimalClass, IonBigDecimal.parseStringWithMode(value))
|
||||||
@@ -142,7 +142,7 @@ object ObjDecimalSupport {
|
|||||||
}
|
}
|
||||||
val child = requireScope().createChildScope()
|
val child = requireScope().createChildScope()
|
||||||
child.addConst(decimalContextVar, context)
|
child.addConst(decimalContextVar, context)
|
||||||
block.callOn(child)
|
(block as? net.sergeych.lyng.BytecodeCallable)?.callOnFast(child) ?: block.callOn(child)
|
||||||
}
|
}
|
||||||
registerBuiltinConversions(decimalClass)
|
registerBuiltinConversions(decimalClass)
|
||||||
registerInterop(decimalClass)
|
registerInterop(decimalClass)
|
||||||
|
|||||||
@@ -64,13 +64,19 @@ open class ObjDynamic(var readCallback: Obj? = null, var writeCallback: Obj? = n
|
|||||||
return (callback as? BytecodeLambdaCallable)?.rebindClosure(context) ?: callback
|
return (callback as? BytecodeLambdaCallable)?.rebindClosure(context) ?: callback
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private suspend fun callCallback(callback: Obj, child: Scope): Obj {
|
||||||
|
return (callback as? net.sergeych.lyng.BytecodeCallable)?.callOnFast(child) ?: callback.callOn(child)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Use read callback to dynamically resolve the field name. Note that it does not work
|
* Use read callback to dynamically resolve the field name. Note that it does not work
|
||||||
* with method invocation which is implemented separately in [invokeInstanceMethod] below.
|
* with method invocation which is implemented separately in [invokeInstanceMethod] below.
|
||||||
*/
|
*/
|
||||||
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
||||||
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
||||||
return readCallback?.callOn(execBase.createChildScope(Arguments(ObjString(name))))?.let {
|
return readCallback?.let { callback ->
|
||||||
|
callCallback(callback, execBase.createChildScope(Arguments(ObjString(name))))
|
||||||
|
}?.let {
|
||||||
if (writeCallback != null)
|
if (writeCallback != null)
|
||||||
it.asMutable
|
it.asMutable
|
||||||
else
|
else
|
||||||
@@ -90,26 +96,34 @@ open class ObjDynamic(var readCallback: Obj? = null, var writeCallback: Obj? = n
|
|||||||
onNotFoundResult: (suspend () -> Obj?)?
|
onNotFoundResult: (suspend () -> Obj?)?
|
||||||
): Obj {
|
): Obj {
|
||||||
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
||||||
val over = readCallback?.callOn(execBase.createChildScope(Arguments(ObjString(name))))
|
val over = readCallback?.let { callback ->
|
||||||
|
callCallback(callback, execBase.createChildScope(Arguments(ObjString(name))))
|
||||||
|
}
|
||||||
return over?.invoke(scope, scope.thisObj, args)
|
return over?.invoke(scope, scope.thisObj, args)
|
||||||
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
||||||
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
||||||
writeCallback?.callOn(execBase.createChildScope(Arguments(ObjString(name), newValue)))
|
writeCallback?.let { callback ->
|
||||||
|
callCallback(callback, execBase.createChildScope(Arguments(ObjString(name), newValue)))
|
||||||
|
}
|
||||||
?: super.writeField(scope, name, newValue)
|
?: super.writeField(scope, name, newValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
override suspend fun getAt(scope: Scope, index: Obj): Obj {
|
||||||
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
||||||
return readCallback?.callOn(execBase.createChildScope(Arguments(index)))
|
return readCallback?.let { callback ->
|
||||||
|
callCallback(callback, execBase.createChildScope(Arguments(index)))
|
||||||
|
}
|
||||||
?: super.getAt(scope, index)
|
?: super.getAt(scope, index)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) {
|
override suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) {
|
||||||
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
val execBase = builderScope?.let { scope.applyClosure(it) } ?: scope
|
||||||
writeCallback?.callOn(execBase.createChildScope(Arguments(index, newValue)))
|
writeCallback?.let { callback ->
|
||||||
|
callCallback(callback, execBase.createChildScope(Arguments(index, newValue)))
|
||||||
|
}
|
||||||
?: super.putAt(scope, index, newValue)
|
?: super.putAt(scope, index, newValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,7 +138,7 @@ open class ObjDynamic(var readCallback: Obj? = null, var writeCallback: Obj? = n
|
|||||||
// Snapshot the caller scope to capture locals/args even if the runtime pools/reuses frames.
|
// Snapshot the caller scope to capture locals/args even if the runtime pools/reuses frames.
|
||||||
// Module scope should stay late-bound to allow extern class rebinding and similar updates.
|
// Module scope should stay late-bound to allow extern class rebinding and similar updates.
|
||||||
delegate.builderScope = if (scope is net.sergeych.lyng.ModuleScope) null else scope.snapshotForClosure()
|
delegate.builderScope = if (scope is net.sergeych.lyng.ModuleScope) null else scope.snapshotForClosure()
|
||||||
builder.callOn(buildScope)
|
(builder as? net.sergeych.lyng.BytecodeCallable)?.callOnFast(buildScope) ?: builder.callOn(buildScope)
|
||||||
return delegate
|
return delegate
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -395,8 +395,17 @@ suspend fun Obj.getLyngExceptionMessageWithStackTrace(scope: Scope? = null,showD
|
|||||||
var at = "unknown"
|
var at = "unknown"
|
||||||
val stack = if (!trace.list.isEmpty()) {
|
val stack = if (!trace.list.isEmpty()) {
|
||||||
val first = trace.list[0]
|
val first = trace.list[0]
|
||||||
at = (first.readField(s, "at").value as ObjString).value
|
suspend fun formatTraceEntry(entry: Obj): String {
|
||||||
"\n" + trace.list.map { " at " + it.toString(s).value }.joinToString("\n")
|
return when (entry) {
|
||||||
|
is ObjString -> entry.value.removePrefix("#")
|
||||||
|
else -> entry.toString(s).value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
at = when (first) {
|
||||||
|
is ObjString -> formatTraceEntry(first)
|
||||||
|
else -> (first.readField(s, "at").value as ObjString).value
|
||||||
|
}
|
||||||
|
"\n" + trace.list.map { " at " + formatTraceEntry(it) }.joinToString("\n")
|
||||||
} else {
|
} else {
|
||||||
val pos = s.pos
|
val pos = s.pos
|
||||||
if (pos.source.fileName.isNotEmpty() && pos.currentLine.isNotEmpty()) {
|
if (pos.source.fileName.isNotEmpty() && pos.currentLine.isNotEmpty()) {
|
||||||
|
|||||||
@@ -81,7 +81,7 @@ private suspend fun createLyngFlowInput(scope: Scope, producer: Obj, ownerSessio
|
|||||||
val runProducer: suspend CoroutineScope.() -> Unit = {
|
val runProducer: suspend CoroutineScope.() -> Unit = {
|
||||||
var failure: Throwable? = null
|
var failure: Throwable? = null
|
||||||
try {
|
try {
|
||||||
producer.callOn(builderScope)
|
(producer as? net.sergeych.lyng.BytecodeCallable)?.callOnFast(builderScope) ?: producer.callOn(builderScope)
|
||||||
} catch (x: ScriptFlowIsNoMoreCollected) {
|
} catch (x: ScriptFlowIsNoMoreCollected) {
|
||||||
// premature flow closing, OK
|
// premature flow closing, OK
|
||||||
} catch (x: Throwable) {
|
} catch (x: Throwable) {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
package net.sergeych.lyng.obj
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
import net.sergeych.lyng.Arguments
|
import net.sergeych.lyng.Arguments
|
||||||
|
import net.sergeych.lyng.CallSignature
|
||||||
import net.sergeych.lyng.miniast.ParamDoc
|
import net.sergeych.lyng.miniast.ParamDoc
|
||||||
import net.sergeych.lyng.miniast.addFnDoc
|
import net.sergeych.lyng.miniast.addFnDoc
|
||||||
import net.sergeych.lyng.miniast.addPropertyDoc
|
import net.sergeych.lyng.miniast.addPropertyDoc
|
||||||
@@ -189,7 +190,13 @@ val ObjIterable by lazy {
|
|||||||
doc = "Build a map from elements using the lambda result as key.",
|
doc = "Build a map from elements using the lambda result as key.",
|
||||||
params = listOf(ParamDoc("keySelector")),
|
params = listOf(ParamDoc("keySelector")),
|
||||||
returns = type("lyng.Map"),
|
returns = type("lyng.Map"),
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.ITERABLE,
|
||||||
|
result = CallSignature.ResultMode.ASSOCIATE_BY
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
val association = requireOnlyArg<Obj>()
|
val association = requireOnlyArg<Obj>()
|
||||||
val result = ObjMap()
|
val result = ObjMap()
|
||||||
@@ -204,7 +211,13 @@ val ObjIterable by lazy {
|
|||||||
doc = "Apply the lambda to each element in iteration order.",
|
doc = "Apply the lambda to each element in iteration order.",
|
||||||
params = listOf(ParamDoc("action")),
|
params = listOf(ParamDoc("action")),
|
||||||
isOpen = true,
|
isOpen = true,
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.ITERABLE,
|
||||||
|
result = CallSignature.ResultMode.FOR_EACH
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
val scope = requireScope()
|
val scope = requireScope()
|
||||||
val it = thisObj.invokeInstanceMethod(scope, "iterator")
|
val it = thisObj.invokeInstanceMethod(scope, "iterator")
|
||||||
@@ -222,7 +235,13 @@ val ObjIterable by lazy {
|
|||||||
params = listOf(ParamDoc("transform")),
|
params = listOf(ParamDoc("transform")),
|
||||||
returns = type("lyng.List"),
|
returns = type("lyng.List"),
|
||||||
isOpen = true,
|
isOpen = true,
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.ITERABLE,
|
||||||
|
result = CallSignature.ResultMode.MAP
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
val fn = requiredArg<Obj>(0)
|
val fn = requiredArg<Obj>(0)
|
||||||
val result = mutableListOf<Obj>()
|
val result = mutableListOf<Obj>()
|
||||||
@@ -238,7 +257,13 @@ val ObjIterable by lazy {
|
|||||||
params = listOf(ParamDoc("transform")),
|
params = listOf(ParamDoc("transform")),
|
||||||
returns = type("lyng.List"),
|
returns = type("lyng.List"),
|
||||||
isOpen = true,
|
isOpen = true,
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.ITERABLE,
|
||||||
|
result = CallSignature.ResultMode.MAP_NOT_NULL
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
val fn = requiredArg<Obj>(0)
|
val fn = requiredArg<Obj>(0)
|
||||||
val result = mutableListOf<Obj>()
|
val result = mutableListOf<Obj>()
|
||||||
|
|||||||
@@ -30,19 +30,27 @@ import net.sergeych.lynon.LynonEncoder
|
|||||||
import net.sergeych.lynon.LynonType
|
import net.sergeych.lynon.LynonType
|
||||||
|
|
||||||
open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
||||||
private var boxedList: MutableList<Obj>? = null
|
internal var boxedList: MutableList<Obj>? = null
|
||||||
private var primitiveIntList: LongArray? = null
|
internal var primitiveIntList: LongArray? = null
|
||||||
|
// Logical size of primitiveIntList; capacity = primitiveIntList!!.size
|
||||||
|
internal var primitiveIntSize: Int = 0
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
if (initialList.isNotEmpty()) {
|
||||||
if (!adoptPrimitiveIntList(initialList)) {
|
if (!adoptPrimitiveIntList(initialList)) {
|
||||||
boxedList = initialList
|
boxedList = initialList
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Empty initialList: both null — lazy mode, avoids boxing on first append
|
||||||
|
}
|
||||||
|
|
||||||
val list: MutableList<Obj>
|
val list: MutableList<Obj>
|
||||||
get() = ensureBoxedList()
|
get() = ensureBoxedList()
|
||||||
|
|
||||||
internal fun sizeFast(): Int = primitiveIntList?.size ?: boxedList?.size ?: 0
|
internal fun sizeFast(): Int = when {
|
||||||
|
primitiveIntList != null -> primitiveIntSize
|
||||||
|
else -> boxedList?.size ?: 0
|
||||||
|
}
|
||||||
|
|
||||||
internal fun getObjAtFast(index: Int): Obj =
|
internal fun getObjAtFast(index: Int): Obj =
|
||||||
primitiveIntList?.let { ObjInt.of(it[index]) } ?: boxedList!![index]
|
primitiveIntList?.let { ObjInt.of(it[index]) } ?: boxedList!![index]
|
||||||
@@ -80,10 +88,25 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
|
|
||||||
internal fun appendFast(value: Obj) {
|
internal fun appendFast(value: Obj) {
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
if (ints != null && value is ObjInt) {
|
if (value is ObjInt) {
|
||||||
primitiveIntList = ints.copyOf(ints.size + 1).also { it[ints.size] = value.value }
|
if (ints != null) {
|
||||||
|
// Primitive mode: amortized growth (no copy when capacity allows)
|
||||||
|
if (primitiveIntSize < ints.size) {
|
||||||
|
ints[primitiveIntSize++] = value.value
|
||||||
|
} else {
|
||||||
|
val grown = ints.copyOf(maxOf(ints.size * 2, 16))
|
||||||
|
grown[primitiveIntSize++] = value.value
|
||||||
|
primitiveIntList = grown
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (boxedList == null) {
|
||||||
|
// Lazy empty state: first int element starts primitive mode
|
||||||
|
primitiveIntList = LongArray(16).also { it[0] = value.value }
|
||||||
|
primitiveIntSize = 1
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
ensureBoxedList().add(value)
|
ensureBoxedList().add(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,10 +114,12 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
val otherInts = other.primitiveIntList
|
val otherInts = other.primitiveIntList
|
||||||
if (ints != null && otherInts != null) {
|
if (ints != null && otherInts != null) {
|
||||||
primitiveIntList = LongArray(ints.size + otherInts.size).also {
|
val otherSize = other.primitiveIntSize
|
||||||
ints.copyInto(it, 0, 0, ints.size)
|
val newSize = primitiveIntSize + otherSize
|
||||||
otherInts.copyInto(it, ints.size, 0, otherInts.size)
|
val dest = if (newSize <= ints.size) ints else ints.copyOf(newSize)
|
||||||
}
|
otherInts.copyInto(dest, primitiveIntSize, 0, otherSize)
|
||||||
|
primitiveIntList = dest
|
||||||
|
primitiveIntSize = newSize
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ensureBoxedList().addAll(other.list)
|
ensureBoxedList().addAll(other.list)
|
||||||
@@ -108,6 +133,7 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
ints[i] = value.value
|
ints[i] = value.value
|
||||||
}
|
}
|
||||||
primitiveIntList = ints
|
primitiveIntList = ints
|
||||||
|
primitiveIntSize = ints.size
|
||||||
boxedList = null
|
boxedList = null
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
@@ -120,12 +146,13 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
boxedList = empty
|
boxedList = empty
|
||||||
return empty
|
return empty
|
||||||
}
|
}
|
||||||
val materialized = ArrayList<Obj>(ints.size)
|
val materialized = ArrayList<Obj>(primitiveIntSize)
|
||||||
for (value in ints) {
|
for (i in 0..<primitiveIntSize) {
|
||||||
materialized.add(ObjInt.of(value))
|
materialized.add(ObjInt.of(ints[i]))
|
||||||
}
|
}
|
||||||
boxedList = materialized
|
boxedList = materialized
|
||||||
primitiveIntList = null
|
primitiveIntList = null
|
||||||
|
primitiveIntSize = 0
|
||||||
return materialized
|
return materialized
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -138,8 +165,9 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
internal constructor(intValues: LongArray) : this(mutableListOf()) {
|
internal constructor(intValues: LongArray, size: Int = intValues.size) : this(mutableListOf()) {
|
||||||
primitiveIntList = intValues
|
primitiveIntList = intValues
|
||||||
|
primitiveIntSize = size
|
||||||
boxedList = null
|
boxedList = null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,9 +281,11 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
val otherInts = other.primitiveIntList
|
val otherInts = other.primitiveIntList
|
||||||
if (ints != null && otherInts != null) {
|
if (ints != null && otherInts != null) {
|
||||||
ObjList(LongArray(ints.size + otherInts.size).also {
|
val mySize = primitiveIntSize
|
||||||
ints.copyInto(it, 0, 0, ints.size)
|
val otherSize = other.primitiveIntSize
|
||||||
otherInts.copyInto(it, ints.size, 0, otherInts.size)
|
ObjList(LongArray(mySize + otherSize).also {
|
||||||
|
ints.copyInto(it, 0, 0, mySize)
|
||||||
|
otherInts.copyInto(it, mySize, 0, otherSize)
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
ObjList((list + other.list).toMutableList())
|
ObjList((list + other.list).toMutableList())
|
||||||
@@ -276,7 +306,9 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
|
|
||||||
|
|
||||||
open override suspend fun plusAssign(scope: Scope, other: Obj): Obj {
|
open override suspend fun plusAssign(scope: Scope, other: Obj): Obj {
|
||||||
if (other is ObjList) {
|
if (other is ObjInt || other is ObjString || other is ObjBool || other is ObjReal || other is ObjNull) {
|
||||||
|
appendFast(other)
|
||||||
|
} else if (other is ObjList) {
|
||||||
appendAllFast(other)
|
appendAllFast(other)
|
||||||
} else if (!shouldTreatAsSingleElement(scope, other) && other.isInstanceOf(ObjIterable)) {
|
} else if (!shouldTreatAsSingleElement(scope, other) && other.isInstanceOf(ObjIterable)) {
|
||||||
val otherList = (other.invokeInstanceMethod(scope, "toList") as ObjList).list
|
val otherList = (other.invokeInstanceMethod(scope, "toList") as ObjList).list
|
||||||
@@ -327,8 +359,8 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
override suspend fun contains(scope: Scope, other: Obj): Boolean {
|
override suspend fun contains(scope: Scope, other: Obj): Boolean {
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
if (ints != null && other is ObjInt) {
|
if (ints != null && other is ObjInt) {
|
||||||
for (value in ints) {
|
for (i in 0..<primitiveIntSize) {
|
||||||
if (value == other.value) return true
|
if (ints[i] == other.value) return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@@ -351,8 +383,8 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
override suspend fun enumerate(scope: Scope, callback: suspend (Obj) -> Boolean) {
|
override suspend fun enumerate(scope: Scope, callback: suspend (Obj) -> Boolean) {
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
if (ints != null) {
|
if (ints != null) {
|
||||||
for (value in ints) {
|
for (i in 0..<primitiveIntSize) {
|
||||||
if (!callback(ObjInt.of(value))) break
|
if (!callback(ObjInt.of(ints[i]))) break
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -366,7 +398,7 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
|
|
||||||
override suspend fun toKotlin(scope: Scope): Any {
|
override suspend fun toKotlin(scope: Scope): Any {
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
if (ints != null) return ints.map { it }
|
if (ints != null) return (0..<primitiveIntSize).map { ints[it] }
|
||||||
return list.map { it.toKotlin(scope) }
|
return list.map { it.toKotlin(scope) }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -398,19 +430,24 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun hashCode(): Int {
|
override fun hashCode(): Int {
|
||||||
return primitiveIntList?.contentHashCode() ?: list.hashCode()
|
val ints = primitiveIntList
|
||||||
|
return if (ints != null) {
|
||||||
|
var result = 1
|
||||||
|
for (i in 0..<primitiveIntSize) result = 31 * result + ints[i].hashCode()
|
||||||
|
result
|
||||||
|
} else list.hashCode()
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun equals(other: Any?): Boolean {
|
override fun equals(other: Any?): Boolean {
|
||||||
if (this === other) return true
|
if (this === other) return true
|
||||||
if (other == null || this::class != other::class) return false
|
if (other == null || this::class != other::class) return false
|
||||||
|
|
||||||
other as ObjList
|
other as ObjList
|
||||||
|
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
val otherInts = other.primitiveIntList
|
val otherInts = other.primitiveIntList
|
||||||
return if (ints != null && otherInts != null) {
|
return if (ints != null && otherInts != null) {
|
||||||
ints.contentEquals(otherInts)
|
if (primitiveIntSize != other.primitiveIntSize) return false
|
||||||
|
for (i in 0..<primitiveIntSize) if (ints[i] != otherInts[i]) return false
|
||||||
|
true
|
||||||
} else {
|
} else {
|
||||||
list == other.list
|
list == other.list
|
||||||
}
|
}
|
||||||
@@ -419,7 +456,9 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
override suspend fun serialize(scope: Scope, encoder: LynonEncoder, lynonType: LynonType?) {
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
if (ints != null) {
|
if (ints != null) {
|
||||||
encoder.encodeAnyList(scope, ints.mapTo(ArrayList(ints.size)) { ObjInt.of(it) })
|
val boxed = ArrayList<Obj>(primitiveIntSize)
|
||||||
|
for (i in 0..<primitiveIntSize) boxed.add(ObjInt.of(ints[i]))
|
||||||
|
encoder.encodeAnyList(scope, boxed)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
encoder.encodeAnyList(scope, list)
|
encoder.encodeAnyList(scope, list)
|
||||||
@@ -430,7 +469,7 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
override suspend fun toJson(scope: Scope): JsonElement {
|
override suspend fun toJson(scope: Scope): JsonElement {
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
if (ints != null) {
|
if (ints != null) {
|
||||||
return JsonArray(ints.map { ObjInt.of(it).toJson(scope) })
|
return JsonArray((0..<primitiveIntSize).map { ObjInt.of(ints[it]).toJson(scope) })
|
||||||
}
|
}
|
||||||
return JsonArray(list.map { it.toJson(scope) })
|
return JsonArray(list.map { it.toJson(scope) })
|
||||||
}
|
}
|
||||||
@@ -441,9 +480,9 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
var first = true
|
var first = true
|
||||||
val ints = primitiveIntList
|
val ints = primitiveIntList
|
||||||
if (ints != null) {
|
if (ints != null) {
|
||||||
for (v in ints) {
|
for (i in 0..<primitiveIntSize) {
|
||||||
if (first) first = false else append(",")
|
if (first) first = false else append(",")
|
||||||
append(v)
|
append(ints[i])
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (v in list) {
|
for (v in list) {
|
||||||
@@ -480,8 +519,8 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
doc = "Append one or more elements to the end of this list.",
|
doc = "Append one or more elements to the end of this list.",
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib"
|
||||||
) {
|
) {
|
||||||
val l = thisAs<ObjList>().list
|
val l = thisAs<ObjList>()
|
||||||
for (a in args) l.add(a)
|
for (a in args) l.appendFast(a)
|
||||||
ObjVoid
|
ObjVoid
|
||||||
}
|
}
|
||||||
addFnDoc(
|
addFnDoc(
|
||||||
@@ -528,6 +567,28 @@ open class ObjList(initialList: MutableList<Obj> = mutableListOf()) : Obj() {
|
|||||||
} else self.list.removeLast()
|
} else self.list.removeLast()
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
addFnDoc(
|
||||||
|
name= "ensureCapacity",
|
||||||
|
doc = """
|
||||||
|
ensure the list capacity allows storing specified amount if items without reallocation.
|
||||||
|
If current capacity is greater or equal to `count`, does nothing. Note that possible reallocation
|
||||||
|
could be a costly operation,
|
||||||
|
""".trimIndent(),
|
||||||
|
params = listOf(ParamDoc("count", type("lyng.Int"))),
|
||||||
|
moduleName = "lyng.stdlib"
|
||||||
|
) {
|
||||||
|
val self = thisAs<ObjList>()
|
||||||
|
val count = requireOnlyArg<ObjInt>().value.toInt()
|
||||||
|
if (count > 0) {
|
||||||
|
val ints = self.primitiveIntList
|
||||||
|
when {
|
||||||
|
ints != null -> if (ints.size < count) self.primitiveIntList = ints.copyOf(count)
|
||||||
|
self.boxedList == null -> { self.primitiveIntList = LongArray(count); self.primitiveIntSize = 0 }
|
||||||
|
else -> (self.boxedList as? ArrayList)?.ensureCapacity(count)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
addFnDoc(
|
addFnDoc(
|
||||||
name = "removeRange",
|
name = "removeRange",
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ package net.sergeych.lyng.obj
|
|||||||
|
|
||||||
import kotlinx.serialization.json.JsonElement
|
import kotlinx.serialization.json.JsonElement
|
||||||
import kotlinx.serialization.json.JsonObject
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
import net.sergeych.lyng.CallSignature
|
||||||
import net.sergeych.lyng.Scope
|
import net.sergeych.lyng.Scope
|
||||||
import net.sergeych.lyng.miniast.*
|
import net.sergeych.lyng.miniast.*
|
||||||
import net.sergeych.lynon.LynonDecoder
|
import net.sergeych.lynon.LynonDecoder
|
||||||
@@ -262,7 +263,15 @@ class ObjMap(val map: MutableMap<Obj, Obj> = mutableMapOf()) : Obj() {
|
|||||||
doc = "Get value by key or compute, store, and return the default from a lambda.",
|
doc = "Get value by key or compute, store, and return the default from a lambda.",
|
||||||
params = listOf(ParamDoc("key"), ParamDoc("default")),
|
params = listOf(ParamDoc("key"), ParamDoc("default")),
|
||||||
returns = type("lyng.Any"),
|
returns = type("lyng.Any"),
|
||||||
moduleName = "lyng.stdlib"
|
moduleName = "lyng.stdlib",
|
||||||
|
callSignature = CallSignature(
|
||||||
|
inlineHigherOrder = CallSignature.HigherOrderInline(
|
||||||
|
kind = CallSignature.Kind.MAP_GET_OR_PUT,
|
||||||
|
result = CallSignature.ResultMode.BLOCK_RESULT,
|
||||||
|
argCount = 2,
|
||||||
|
lambdaArgIndex = 1
|
||||||
|
)
|
||||||
|
)
|
||||||
) {
|
) {
|
||||||
val key = requiredArg<Obj>(0)
|
val key = requiredArg<Obj>(0)
|
||||||
thisAs<ObjMap>().map.getOrPut(key) {
|
thisAs<ObjMap>().map.getOrPut(key) {
|
||||||
|
|||||||
@@ -53,10 +53,10 @@ object ObjMatrixSupport {
|
|||||||
}
|
}
|
||||||
hooks += { _, instance -> instance.kotlinInstanceData = defaultVector }
|
hooks += { _, instance -> instance.kotlinInstanceData = defaultVector }
|
||||||
|
|
||||||
vectorClass.addProperty("size", getter = {
|
vectorClass.bindProperty("size", getter = {
|
||||||
ObjInt.of(vectorOf(thisObj).size.toLong())
|
ObjInt.of(vectorOf(thisObj).size.toLong())
|
||||||
})
|
})
|
||||||
vectorClass.addProperty("length", getter = {
|
vectorClass.bindProperty("length", getter = {
|
||||||
ObjInt.of(vectorOf(thisObj).size.toLong())
|
ObjInt.of(vectorOf(thisObj).size.toLong())
|
||||||
})
|
})
|
||||||
vectorClass.addFn("toList") {
|
vectorClass.addFn("toList") {
|
||||||
@@ -99,10 +99,10 @@ object ObjMatrixSupport {
|
|||||||
ObjInt.of(vectorOf(thisObj).compareTo(coerceVectorArg(requireScope(), args.firstAndOnly())).toLong())
|
ObjInt.of(vectorOf(thisObj).compareTo(coerceVectorArg(requireScope(), args.firstAndOnly())).toLong())
|
||||||
}
|
}
|
||||||
|
|
||||||
vectorClass.addClassFn("fromList") {
|
vectorClass.bindClassFn("fromList") {
|
||||||
newVector(vectorClass, parseVector(requireScope(), requiredArg(0)))
|
newVector(vectorClass, parseVector(requireScope(), requiredArg(0)))
|
||||||
}
|
}
|
||||||
vectorClass.addClassFn("zeros") {
|
vectorClass.bindClassFn("zeros") {
|
||||||
val size = requiredArg<ObjInt>(0).value.toInt()
|
val size = requiredArg<ObjInt>(0).value.toInt()
|
||||||
if (size <= 0) requireScope().raiseIllegalArgument("vector size must be positive")
|
if (size <= 0) requireScope().raiseIllegalArgument("vector size must be positive")
|
||||||
newVector(vectorClass, VectorData(DoubleArray(size)))
|
newVector(vectorClass, VectorData(DoubleArray(size)))
|
||||||
@@ -119,13 +119,13 @@ object ObjMatrixSupport {
|
|||||||
}
|
}
|
||||||
hooks += { _, instance -> instance.kotlinInstanceData = defaultMatrix }
|
hooks += { _, instance -> instance.kotlinInstanceData = defaultMatrix }
|
||||||
|
|
||||||
matrixClass.addProperty("rows", getter = {
|
matrixClass.bindProperty("rows", getter = {
|
||||||
ObjInt.of(matrixOf(thisObj).rows.toLong())
|
ObjInt.of(matrixOf(thisObj).rows.toLong())
|
||||||
})
|
})
|
||||||
matrixClass.addProperty("cols", getter = {
|
matrixClass.bindProperty("cols", getter = {
|
||||||
ObjInt.of(matrixOf(thisObj).cols.toLong())
|
ObjInt.of(matrixOf(thisObj).cols.toLong())
|
||||||
})
|
})
|
||||||
matrixClass.addProperty("shape", getter = {
|
matrixClass.bindProperty("shape", getter = {
|
||||||
ObjList(
|
ObjList(
|
||||||
mutableListOf(
|
mutableListOf(
|
||||||
ObjInt.of(matrixOf(thisObj).rows.toLong()),
|
ObjInt.of(matrixOf(thisObj).rows.toLong()),
|
||||||
@@ -133,7 +133,7 @@ object ObjMatrixSupport {
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
})
|
})
|
||||||
matrixClass.addProperty("isSquare", getter = {
|
matrixClass.bindProperty("isSquare", getter = {
|
||||||
matrixOf(thisObj).isSquare.toObj()
|
matrixOf(thisObj).isSquare.toObj()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -208,17 +208,17 @@ object ObjMatrixSupport {
|
|||||||
ObjInt.of(matrixOf(thisObj).compareTo(coerceMatrixArg(requireScope(), args.firstAndOnly())).toLong())
|
ObjInt.of(matrixOf(thisObj).compareTo(coerceMatrixArg(requireScope(), args.firstAndOnly())).toLong())
|
||||||
}
|
}
|
||||||
|
|
||||||
matrixClass.addClassFn("fromRows") {
|
matrixClass.bindClassFn("fromRows") {
|
||||||
newMatrix(matrixClass, parseRows(requireScope(), requiredArg(0)))
|
newMatrix(matrixClass, parseRows(requireScope(), requiredArg(0)))
|
||||||
}
|
}
|
||||||
matrixClass.addClassFn("zeros") {
|
matrixClass.bindClassFn("zeros") {
|
||||||
val rows = requiredArg<ObjInt>(0).value.toInt()
|
val rows = requiredArg<ObjInt>(0).value.toInt()
|
||||||
val cols = requiredArg<ObjInt>(1).value.toInt()
|
val cols = requiredArg<ObjInt>(1).value.toInt()
|
||||||
if (rows <= 0) requireScope().raiseIllegalArgument("matrix must have at least one row")
|
if (rows <= 0) requireScope().raiseIllegalArgument("matrix must have at least one row")
|
||||||
if (cols <= 0) requireScope().raiseIllegalArgument("matrix must have at least one column")
|
if (cols <= 0) requireScope().raiseIllegalArgument("matrix must have at least one column")
|
||||||
newMatrix(matrixClass, MatrixData(rows, cols, DoubleArray(rows * cols)))
|
newMatrix(matrixClass, MatrixData(rows, cols, DoubleArray(rows * cols)))
|
||||||
}
|
}
|
||||||
matrixClass.addClassFn("identity") {
|
matrixClass.bindClassFn("identity") {
|
||||||
val size = requiredArg<ObjInt>(0).value.toInt()
|
val size = requiredArg<ObjInt>(0).value.toInt()
|
||||||
if (size <= 0) requireScope().raiseIllegalArgument("identity matrix size must be positive")
|
if (size <= 0) requireScope().raiseIllegalArgument("identity matrix size must be positive")
|
||||||
val values = DoubleArray(size * size)
|
val values = DoubleArray(size * size)
|
||||||
|
|||||||
@@ -18,6 +18,7 @@
|
|||||||
package net.sergeych.lyng.obj
|
package net.sergeych.lyng.obj
|
||||||
|
|
||||||
import net.sergeych.lyng.Arguments
|
import net.sergeych.lyng.Arguments
|
||||||
|
import net.sergeych.lyng.BytecodeCallable
|
||||||
import net.sergeych.lyng.BytecodeBodyProvider
|
import net.sergeych.lyng.BytecodeBodyProvider
|
||||||
import net.sergeych.lyng.Scope
|
import net.sergeych.lyng.Scope
|
||||||
import net.sergeych.lyng.Statement
|
import net.sergeych.lyng.Statement
|
||||||
@@ -41,14 +42,16 @@ class ObjProperty(
|
|||||||
val instanceScope = (instance as? ObjInstance)?.instanceScope ?: instance.autoInstanceScope(scope)
|
val instanceScope = (instance as? ObjInstance)?.instanceScope ?: instance.autoInstanceScope(scope)
|
||||||
val execScope = scope.applyClosure(instanceScope).createChildScope(newThisObj = instance)
|
val execScope = scope.applyClosure(instanceScope).createChildScope(newThisObj = instance)
|
||||||
execScope.currentClassCtx = declaringClass
|
execScope.currentClassCtx = declaringClass
|
||||||
|
(g as? BytecodeCallable)?.callOnFast(execScope)?.let { return it }
|
||||||
return when (g) {
|
return when (g) {
|
||||||
is BytecodeStatement -> executeBytecodeWithSeed(execScope, g, "property getter")
|
is BytecodeStatement -> executeBytecodeWithSeed(execScope, g, "property getter")
|
||||||
is BytecodeBodyProvider -> {
|
is BytecodeBodyProvider -> {
|
||||||
val body = g.bytecodeBody()
|
val body = g.bytecodeBody()
|
||||||
if (body != null) executeBytecodeWithSeed(execScope, body, "property getter") else g.callOn(execScope)
|
if (body != null) executeBytecodeWithSeed(execScope, body, "property getter")
|
||||||
|
else (g as? BytecodeCallable)?.callOnFast(execScope) ?: g.callOn(execScope)
|
||||||
}
|
}
|
||||||
is Statement -> g.callOn(execScope)
|
is Statement -> (g as? BytecodeCallable)?.callOnFast(execScope) ?: g.callOn(execScope)
|
||||||
else -> g.callOn(execScope)
|
else -> (g as? BytecodeCallable)?.callOnFast(execScope) ?: g.callOn(execScope)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,14 +62,16 @@ class ObjProperty(
|
|||||||
val instanceScope = (instance as? ObjInstance)?.instanceScope ?: instance.autoInstanceScope(scope)
|
val instanceScope = (instance as? ObjInstance)?.instanceScope ?: instance.autoInstanceScope(scope)
|
||||||
val execScope = scope.applyClosure(instanceScope).createChildScope(args = Arguments(value), newThisObj = instance)
|
val execScope = scope.applyClosure(instanceScope).createChildScope(args = Arguments(value), newThisObj = instance)
|
||||||
execScope.currentClassCtx = declaringClass
|
execScope.currentClassCtx = declaringClass
|
||||||
|
(s as? BytecodeCallable)?.callOnFast(execScope)?.let { return }
|
||||||
when (s) {
|
when (s) {
|
||||||
is BytecodeStatement -> executeBytecodeWithSeed(execScope, s, "property setter")
|
is BytecodeStatement -> executeBytecodeWithSeed(execScope, s, "property setter")
|
||||||
is BytecodeBodyProvider -> {
|
is BytecodeBodyProvider -> {
|
||||||
val body = s.bytecodeBody()
|
val body = s.bytecodeBody()
|
||||||
if (body != null) executeBytecodeWithSeed(execScope, body, "property setter") else s.callOn(execScope)
|
if (body != null) executeBytecodeWithSeed(execScope, body, "property setter")
|
||||||
|
else (s as? BytecodeCallable)?.callOnFast(execScope) ?: s.callOn(execScope)
|
||||||
}
|
}
|
||||||
is Statement -> s.callOn(execScope)
|
is Statement -> (s as? BytecodeCallable)?.callOnFast(execScope) ?: s.callOn(execScope)
|
||||||
else -> s.callOn(execScope)
|
else -> (s as? BytecodeCallable)?.callOnFast(execScope) ?: s.callOn(execScope)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -38,17 +38,26 @@ class ImportManager(
|
|||||||
|
|
||||||
val packageNames: List<String> get() = imports.keys.toList()
|
val packageNames: List<String> get() = imports.keys.toList()
|
||||||
|
|
||||||
|
private class CacheCell(var scope: ModuleScope? = null)
|
||||||
|
|
||||||
private inner class Entry(
|
private inner class Entry(
|
||||||
val packageName: String,
|
val packageName: String,
|
||||||
val builder: suspend (ModuleScope) -> Unit,
|
val builder: suspend (ModuleScope) -> Unit,
|
||||||
var cachedScope: ModuleScope? = null
|
val cacheCell: CacheCell = CacheCell()
|
||||||
) {
|
) {
|
||||||
|
|
||||||
suspend fun getScope(pos: Pos): ModuleScope {
|
suspend fun getScope(pos: Pos): ModuleScope {
|
||||||
cachedScope?.let { return it }
|
cacheCell.scope?.let { return it }
|
||||||
return ModuleScope(inner, pos, packageName).apply {
|
val module = ModuleScope(inner, pos, packageName)
|
||||||
cachedScope = this
|
cacheCell.scope = module
|
||||||
builder(this)
|
return try {
|
||||||
|
builder(module)
|
||||||
|
module
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
if (cacheCell.scope === module) {
|
||||||
|
cacheCell.scope = null
|
||||||
|
}
|
||||||
|
throw e
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -152,14 +161,14 @@ class ImportManager(
|
|||||||
op.withLock {
|
op.withLock {
|
||||||
ImportManager(rootScope, securityManager).apply {
|
ImportManager(rootScope, securityManager).apply {
|
||||||
for ((name, entry) in this@ImportManager.imports) {
|
for ((name, entry) in this@ImportManager.imports) {
|
||||||
imports[name] = Entry(entry.packageName, entry.builder, entry.cachedScope)
|
imports[name] = Entry(entry.packageName, entry.builder, entry.cacheCell)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun invalidatePackageCache(name: String) {
|
fun invalidatePackageCache(name: String) {
|
||||||
op.withLock {
|
op.withLock {
|
||||||
imports[name]?.cachedScope = null
|
imports[name]?.cacheCell?.scope = null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,7 +58,10 @@ abstract class Statement(
|
|||||||
val type = ObjClass("Callable")
|
val type = ObjClass("Callable")
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun call(scope: Scope, vararg args: Obj) = execute(scope.createChildScope(args = Arguments(*args)))
|
suspend fun call(scope: Scope, vararg args: Obj): Obj {
|
||||||
|
val child = scope.createChildScope(args = Arguments(*args))
|
||||||
|
return (this as? BytecodeCallable)?.callOnFast(child) ?: execute(child)
|
||||||
|
}
|
||||||
|
|
||||||
protected fun bytecodeOnly(scope: Scope, label: String): Nothing {
|
protected fun bytecodeOnly(scope: Scope, label: String): Nothing {
|
||||||
return scope.raiseIllegalState("bytecode-only execution is required; $label needs compiled bytecode")
|
return scope.raiseIllegalState("bytecode-only execution is required; $label needs compiled bytecode")
|
||||||
|
|||||||
@@ -201,14 +201,7 @@ extern class Decimal() {
|
|||||||
*
|
*
|
||||||
* Contexts are dynamic and block-local. After the block finishes, the previous context is restored.
|
* Contexts are dynamic and block-local. After the block finishes, the previous context is restored.
|
||||||
*/
|
*/
|
||||||
extern fun withDecimalContext<T>(context: DecimalContext, block: ()->T): T
|
extern fun withDecimalContext<T>(context: Object, block: ()->T): T
|
||||||
|
|
||||||
/**
|
|
||||||
* Convenience overload for changing only precision.
|
|
||||||
*
|
|
||||||
* Equivalent to `withDecimalContext(DecimalContext(precision, DecimalRounding.HalfEven), block)`.
|
|
||||||
*/
|
|
||||||
extern fun withDecimalContext<T>(precision: Int, block: ()->T): T
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convenience overload for changing precision and rounding explicitly.
|
* Convenience overload for changing precision and rounding explicitly.
|
||||||
|
|||||||
@@ -17,8 +17,10 @@
|
|||||||
|
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import net.sergeych.lyng.*
|
import net.sergeych.lyng.*
|
||||||
|
import net.sergeych.lyng.obj.ObjNull
|
||||||
import net.sergeych.lyng.obj.toInt
|
import net.sergeych.lyng.obj.toInt
|
||||||
import kotlin.test.Test
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertFalse
|
||||||
import kotlin.test.assertEquals
|
import kotlin.test.assertEquals
|
||||||
import kotlin.test.assertFailsWith
|
import kotlin.test.assertFailsWith
|
||||||
import kotlin.test.assertTrue
|
import kotlin.test.assertTrue
|
||||||
@@ -161,7 +163,7 @@ class BytecodeRecentOpsTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun listFillIntUsesPrimitiveFillBytecode() = runTest {
|
fun listFillConstantExpressionUsesInlineBytecode() = runTest {
|
||||||
val scope = Script.newScope()
|
val scope = Script.newScope()
|
||||||
scope.eval(
|
scope.eval(
|
||||||
"""
|
"""
|
||||||
@@ -172,26 +174,626 @@ class BytecodeRecentOpsTest {
|
|||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
)
|
)
|
||||||
val disasm = scope.disassembleSymbol("calc")
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
assertTrue(disasm.contains("LIST_FILL_INT"), disasm)
|
assertTrue(disasm.contains("LIST_NEW_INT"), disasm)
|
||||||
|
assertFalse(disasm.contains("LIST_FILL_INT"), disasm)
|
||||||
assertEquals(4, scope.eval("calc()").toInt())
|
assertEquals(4, scope.eval("calc()").toInt())
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun listFillIntWithIndexLambdaKeepsSemantics() = runTest {
|
fun listFillCapturedExpressionUsesInlineBytecode() = runTest {
|
||||||
val scope = Script.newScope()
|
val scope = Script.newScope()
|
||||||
scope.eval(
|
scope.eval(
|
||||||
"""
|
"""
|
||||||
fun calc() {
|
fun calc() {
|
||||||
val xs = List.fill(5) { it * 3 }
|
val k = 3
|
||||||
|
val xs = List.fill(5) { it * k }
|
||||||
xs[0] + xs[4]
|
xs[0] + xs[4]
|
||||||
}
|
}
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
)
|
)
|
||||||
val disasm = scope.disassembleSymbol("calc")
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
assertTrue(disasm.contains("LIST_FILL_INT"), disasm)
|
assertTrue(disasm.contains("LIST_NEW_INT"), disasm)
|
||||||
|
assertFalse(disasm.contains("LIST_FILL_INT"), disasm)
|
||||||
assertEquals(12, scope.eval("calc()").toInt())
|
assertEquals(12, scope.eval("calc()").toInt())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun listFillIdentityUsesIotaBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val xs = List.fill(5) { it }
|
||||||
|
xs[0] + xs[4]
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("LIST_IOTA_INT"), disasm)
|
||||||
|
assertEquals(4, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun listFillWithCapacityUsesPrimitiveCapacityBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val xs = List.fill(5, 12) { it * 2 }
|
||||||
|
xs.add(99)
|
||||||
|
xs[0] + xs[4] + xs[5]
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("LIST_NEW_INT_CAP"), disasm)
|
||||||
|
assertFalse(disasm.contains("LIST_FILL_INT_CAP"), disasm)
|
||||||
|
assertEquals(107, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun directLambdaLiteralCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
{ x -> x + 1 }(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("MAKE_LAMBDA_FN"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun capturedLambdaCanCallListFillOnCapturedClassReceiver() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val result = scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc(n: Int) {
|
||||||
|
val xs = { List.fill(n) { it } }()
|
||||||
|
xs[4]
|
||||||
|
}
|
||||||
|
calc(5)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
assertEquals(4, result.toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun directLambdaLiteralCallWithCaptureUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val k = 3
|
||||||
|
{ x -> x * k }(4)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("MAKE_LAMBDA_FN"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(12, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun localImmutableLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val f = { x -> x + 1 }
|
||||||
|
f(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun localImmutableCapturedLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val k = 3
|
||||||
|
val f = { x -> x * k }
|
||||||
|
f(4)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(12, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aliasedImmutableLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val f = { x -> x + 1 }
|
||||||
|
val g = f
|
||||||
|
g(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun topLevelImmutableLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
val f = { x -> x + 1 }
|
||||||
|
fun calc() {
|
||||||
|
f(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun topLevelAliasedImmutableLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
val f = { x -> x + 1 }
|
||||||
|
val g = f
|
||||||
|
fun calc() {
|
||||||
|
g(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun topLevelCapturedLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
val k = 3
|
||||||
|
val f = { x -> x * k }
|
||||||
|
fun calc() {
|
||||||
|
f(4)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(12, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nestedInlineLambdaParamCallAvoidsCallSlot() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
{ g -> g(10) }({ x -> x + 1 })
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun optionalExactLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
type IntFn = (Int)->Int
|
||||||
|
fun calc() {
|
||||||
|
val f: IntFn? = { x -> x + 1 }
|
||||||
|
f?(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun conditionalExactLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
val base = { x -> x + 1 }
|
||||||
|
fun calc(flag: Bool) {
|
||||||
|
(if(flag) base else base)(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc(true)").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun elvisExactLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
val base = { x -> x + 1 }
|
||||||
|
fun calc() {
|
||||||
|
(null ?: base)(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun castExactLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
type IntFn = (Int)->Int
|
||||||
|
val base: IntFn = { x -> x + 1 }
|
||||||
|
fun calc() {
|
||||||
|
(base as IntFn)(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun whenExactLambdaCallUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
val base = { x -> x + 1 }
|
||||||
|
fun calc(flag: Bool) {
|
||||||
|
(when(flag) {
|
||||||
|
true -> base
|
||||||
|
else -> base
|
||||||
|
})(10)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc(true)").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun letLiteralUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
10.let { it + 1 }
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun letAliasedLambdaUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val k = 3
|
||||||
|
val f = { x -> x * k }
|
||||||
|
4.let(f)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(12, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun alsoLiteralUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
var acc = 0
|
||||||
|
val result = 10.also { x ->
|
||||||
|
acc = x + 1
|
||||||
|
}
|
||||||
|
acc + result
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(21, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun optionalLetLiteralUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc(flag: Bool) {
|
||||||
|
val x: Int? = if(flag) 10 else null
|
||||||
|
x?.let { it + 1 }
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc(true)").toInt())
|
||||||
|
assertEquals(ObjNull, scope.eval("calc(false)"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun applyReceiverLambdaUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
class Box(value: Int)
|
||||||
|
|
||||||
|
fun calc() {
|
||||||
|
val box = Box(10).apply { value += 1 }
|
||||||
|
box.value
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun runReceiverLambdaUsesInlineBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
class Box(value: Int)
|
||||||
|
|
||||||
|
fun calc() {
|
||||||
|
Box(10).run { value + 1 }
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(11, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun forEachUsesInlineLoopBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
[1, 2, 3, 4].forEach { it + 1 }
|
||||||
|
5
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("ITER_PUSH"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(5, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun mapUsesInlineLoopBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val f = { x -> x * 2 }
|
||||||
|
val xs = [1, 2, 3].map(f)
|
||||||
|
xs[0] + xs[2]
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("ITER_PUSH"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(8, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun filterUsesInlineLoopBytecode() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val xs = [1, 2, 3, 4].filter { it % 2 == 0 }
|
||||||
|
xs[0] + xs[1]
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("ITER_PUSH"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_DYNAMIC_MEMBER"), disasm)
|
||||||
|
assertEquals(6, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun mapLiteralUsesDirectConstructorCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val m = { a: 1, b: 2 }
|
||||||
|
m.size
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(2, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun mapEntryLiteralUsesDirectConstructorCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val e = "a" => 2
|
||||||
|
e.value
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(2, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun constructorNameUsesDirectCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
Map().size
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(0, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun constructorAliasUsesDirectCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val ctor = Map
|
||||||
|
val m = ctor() as Map
|
||||||
|
m.size
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(0, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ifExpressionConstructorAliasUsesDirectCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc(flag: Bool) {
|
||||||
|
val ctor = if(flag) Map else Map
|
||||||
|
val m = ctor() as Map
|
||||||
|
m.size
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(0, scope.eval("calc(true)").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun elvisConstructorAliasUsesDirectCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
val ctor = null ?: Map
|
||||||
|
val m = ctor() as Map
|
||||||
|
m.size
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(0, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun whenConstructorAliasUsesDirectCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc(flag: Bool) {
|
||||||
|
val ctor = when(flag) {
|
||||||
|
true -> Map
|
||||||
|
else -> Map
|
||||||
|
}
|
||||||
|
val m = ctor() as Map
|
||||||
|
m.size
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(0, scope.eval("calc(true)").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun localNamedFunctionUsesDirectCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
fun twice(x: Int) { x * 2 }
|
||||||
|
twice(3)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(6, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun localNamedFunctionAliasUsesDirectCall() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun calc() {
|
||||||
|
fun twice(x: Int) { x * 2 }
|
||||||
|
val f = twice
|
||||||
|
f(3)
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
val disasm = scope.disassembleSymbol("calc")
|
||||||
|
assertTrue(disasm.contains("CALL_DIRECT"), disasm)
|
||||||
|
assertFalse(disasm.contains("CALL_SLOT"), disasm)
|
||||||
|
assertEquals(6, scope.eval("calc()").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun optionalIndexPreIncSkipsOnNullReceiver() = runTest {
|
fun optionalIndexPreIncSkipsOnNullReceiver() = runTest {
|
||||||
eval(
|
eval(
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.lyng.eval
|
||||||
|
import kotlin.test.Test
|
||||||
|
|
||||||
|
class ChannelTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testRendezvousChannel() = runTest {
|
||||||
|
eval("""
|
||||||
|
val ch = Channel()
|
||||||
|
val producer = launch {
|
||||||
|
ch.send(1)
|
||||||
|
ch.send(2)
|
||||||
|
ch.send(3)
|
||||||
|
ch.close()
|
||||||
|
}
|
||||||
|
val results = []
|
||||||
|
var v = ch.receive()
|
||||||
|
while (v != null) {
|
||||||
|
results += v
|
||||||
|
v = ch.receive()
|
||||||
|
}
|
||||||
|
assertEquals([1, 2, 3], results)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBufferedChannel() = runTest {
|
||||||
|
eval("""
|
||||||
|
val ch = Channel(4)
|
||||||
|
ch.send(10)
|
||||||
|
ch.send(20)
|
||||||
|
ch.send(30)
|
||||||
|
ch.close()
|
||||||
|
assertEquals(10, ch.receive())
|
||||||
|
assertEquals(20, ch.receive())
|
||||||
|
assertEquals(30, ch.receive())
|
||||||
|
// closed and drained
|
||||||
|
assertEquals(null, ch.receive())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testTryReceive() = runTest {
|
||||||
|
eval("""
|
||||||
|
val ch = Channel(2)
|
||||||
|
// nothing buffered yet
|
||||||
|
assertEquals(null, ch.tryReceive())
|
||||||
|
ch.send(42)
|
||||||
|
assertEquals(42, ch.tryReceive())
|
||||||
|
assertEquals(null, ch.tryReceive())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testChannelProperties() = runTest {
|
||||||
|
eval("""
|
||||||
|
val ch = Channel(1)
|
||||||
|
assert(!ch.isClosedForSend)
|
||||||
|
assert(!ch.isClosedForReceive)
|
||||||
|
ch.send(1)
|
||||||
|
ch.close()
|
||||||
|
assert(ch.isClosedForSend)
|
||||||
|
// still has one buffered item, so not yet closed for receive
|
||||||
|
assert(!ch.isClosedForReceive)
|
||||||
|
ch.receive()
|
||||||
|
// now fully drained
|
||||||
|
assert(ch.isClosedForReceive)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testUnlimitedChannel() = runTest {
|
||||||
|
eval("""
|
||||||
|
val ch = Channel(Channel.UNLIMITED)
|
||||||
|
(1..100).forEach { ch.send(it) }
|
||||||
|
ch.close()
|
||||||
|
var sum = 0
|
||||||
|
var v = ch.receive()
|
||||||
|
while (v != null) {
|
||||||
|
sum += v
|
||||||
|
v = ch.receive()
|
||||||
|
}
|
||||||
|
assertEquals(5050, sum)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testChannelProducerConsumerPattern() = runTest {
|
||||||
|
eval("""
|
||||||
|
val ch = Channel()
|
||||||
|
val results = []
|
||||||
|
val mu = Mutex()
|
||||||
|
|
||||||
|
val consumer = launch {
|
||||||
|
var item = ch.receive()
|
||||||
|
while (item != null) {
|
||||||
|
mu.withLock { results += item }
|
||||||
|
item = ch.receive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
launch {
|
||||||
|
for (i in 1..5) {
|
||||||
|
ch.send("msg:${'$'}i")
|
||||||
|
}
|
||||||
|
ch.close()
|
||||||
|
}.await()
|
||||||
|
|
||||||
|
consumer.await()
|
||||||
|
assertEquals(["msg:1","msg:2","msg:3","msg:4","msg:5"], results)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -16,11 +16,17 @@
|
|||||||
|
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import net.sergeych.lyng.Compiler
|
import net.sergeych.lyng.Compiler
|
||||||
|
import net.sergeych.lyng.Arguments
|
||||||
|
import net.sergeych.lyng.Pos
|
||||||
import net.sergeych.lyng.Scope
|
import net.sergeych.lyng.Scope
|
||||||
import net.sergeych.lyng.Script
|
import net.sergeych.lyng.Script
|
||||||
import net.sergeych.lyng.ScriptError
|
import net.sergeych.lyng.ScriptError
|
||||||
import net.sergeych.lyng.Source
|
import net.sergeych.lyng.Source
|
||||||
|
import net.sergeych.lyng.Statement
|
||||||
import net.sergeych.lyng.asFacade
|
import net.sergeych.lyng.asFacade
|
||||||
|
import net.sergeych.lyng.obj.ObjDynamic
|
||||||
|
import net.sergeych.lyng.obj.ObjInt
|
||||||
|
import net.sergeych.lyng.obj.ObjList
|
||||||
import net.sergeych.lyng.obj.ObjString
|
import net.sergeych.lyng.obj.ObjString
|
||||||
import net.sergeych.lyng.obj.toInt
|
import net.sergeych.lyng.obj.toInt
|
||||||
import net.sergeych.lyng.pacman.ImportManager
|
import net.sergeych.lyng.pacman.ImportManager
|
||||||
@@ -68,6 +74,235 @@ class CompilerVmReviewRegressionTest {
|
|||||||
assertContains(ex.errorMessage, "module binding 'answer'")
|
assertContains(ex.errorMessage, "module binding 'answer'")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun facadeCallUsesPreparedLambdaWithArgs() = runTest {
|
||||||
|
val lambda = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<facade-call-lambda>",
|
||||||
|
"""
|
||||||
|
val base = 2
|
||||||
|
{ x -> x + base }
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val callable = lambda.execute(scope)
|
||||||
|
assertEquals(42, scope.asFacade().call(callable, Arguments(ObjInt.of(40))).toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun genericInvokeHelpersUsePreparedLambdaEntryPoints() = runTest {
|
||||||
|
val unaryLambda = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<generic-invoke-unary>",
|
||||||
|
"""
|
||||||
|
val delta = 2
|
||||||
|
{ x -> x + delta }
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
val nullaryLambda = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<generic-invoke-nullary>",
|
||||||
|
"""
|
||||||
|
val base = 7
|
||||||
|
{ base }
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val unaryScope = Script.newScope()
|
||||||
|
val nullaryScope = Script.newScope()
|
||||||
|
val unaryCallable = unaryLambda.execute(unaryScope)
|
||||||
|
val nullaryCallable = nullaryLambda.execute(nullaryScope)
|
||||||
|
|
||||||
|
assertEquals(42, unaryCallable.invoke(unaryScope, ObjString("receiver"), ObjInt.of(40)).toInt())
|
||||||
|
assertEquals(7, nullaryCallable.invoke(nullaryScope, ObjString("receiver")).toInt())
|
||||||
|
assertEquals(
|
||||||
|
42,
|
||||||
|
unaryCallable.invoke(
|
||||||
|
unaryScope,
|
||||||
|
Pos(Source("<generic-invoke-pos>", ""), 0, 0),
|
||||||
|
ObjString("receiver"),
|
||||||
|
Arguments(ObjInt.of(40))
|
||||||
|
).toInt()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun statementCallUsesPreparedLambdaFastPath() = runTest {
|
||||||
|
val unaryLambda = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<statement-call-unary>",
|
||||||
|
"""
|
||||||
|
val delta = 2
|
||||||
|
{ x -> x + delta }
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val callable = unaryLambda.execute(scope) as Statement
|
||||||
|
|
||||||
|
assertEquals(42, callable.call(scope, ObjInt.of(40)).toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun preparedLambdaKeepsImmutableModuleCaptureAcrossOtherScriptsInSameScope() = runTest {
|
||||||
|
val unaryLambda = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<cross-script-capture-unary>",
|
||||||
|
"""
|
||||||
|
val delta = 2
|
||||||
|
{ x -> x + delta }
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
val unrelatedScript = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<cross-script-capture-unrelated>",
|
||||||
|
"""
|
||||||
|
val base = 7
|
||||||
|
base
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val callable = unaryLambda.execute(scope) as Statement
|
||||||
|
unrelatedScript.execute(scope)
|
||||||
|
|
||||||
|
assertEquals(42, callable.call(scope, ObjInt.of(40)).toInt())
|
||||||
|
assertEquals(42, scope.asFacade().call(callable, Arguments(ObjInt.of(40))).toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun dynamicCallbacksUsePreparedLambdaFastPath() = runTest {
|
||||||
|
val script = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<dynamic-fast-callbacks>",
|
||||||
|
"""
|
||||||
|
var seen = ""
|
||||||
|
dynamic {
|
||||||
|
get { name -> name + seen }
|
||||||
|
set { name, value -> seen = name + "=" + value }
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val dynamic = script.execute(scope) as ObjDynamic
|
||||||
|
|
||||||
|
assertEquals("foo", (dynamic.readField(scope, "foo").value as ObjString).value)
|
||||||
|
dynamic.writeField(scope, "foo", ObjInt.of(7))
|
||||||
|
assertEquals("barfoo=7", (dynamic.getAt(scope, ObjString("bar")) as ObjString).value)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun higherOrderMethodInliningSupportsCapturedValues() = runTest {
|
||||||
|
val script = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<higher-order-inline-captures>",
|
||||||
|
"""
|
||||||
|
val suffix = "!"
|
||||||
|
val offset = 10
|
||||||
|
var sum = 0
|
||||||
|
|
||||||
|
val letResult = "a".let { it + suffix }
|
||||||
|
val applyResult = List<Int>().apply { add(offset); add(offset + 1) }
|
||||||
|
val mapped = [1, 2, 3].map { it + offset }
|
||||||
|
val filtered = [1, 2, 3].filter { it + offset >= 12 }
|
||||||
|
val notNull = [1, 2, 3].mapNotNull { if (it + offset >= 12) it + offset else null }
|
||||||
|
val associated = [1, 2, 3].associateBy { "k" + (it + offset) }
|
||||||
|
[1, 2, 3].forEach { sum += it + offset }
|
||||||
|
|
||||||
|
[letResult, applyResult, mapped, filtered, notNull, associated, sum]
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val result = script.execute(scope) as ObjList
|
||||||
|
|
||||||
|
assertEquals("a!", (result.list[0] as ObjString).value)
|
||||||
|
val applied = result.list[1] as ObjList
|
||||||
|
assertEquals(listOf(10, 11), applied.list.map { it.toInt() })
|
||||||
|
|
||||||
|
val mapped = result.list[2] as ObjList
|
||||||
|
assertEquals(listOf(11, 12, 13), mapped.list.map { it.toInt() })
|
||||||
|
|
||||||
|
val filtered = result.list[3] as ObjList
|
||||||
|
assertEquals(listOf(2, 3), filtered.list.map { it.toInt() })
|
||||||
|
|
||||||
|
val notNull = result.list[4] as ObjList
|
||||||
|
assertEquals(listOf(12, 13), notNull.list.map { it.toInt() })
|
||||||
|
|
||||||
|
val associated = result.list[5].toString(scope).value
|
||||||
|
assertContains(associated, "\"k11\" => 1")
|
||||||
|
assertContains(associated, "\"k12\" => 2")
|
||||||
|
assertContains(associated, "\"k13\" => 3")
|
||||||
|
|
||||||
|
assertEquals(36, result.list[6].toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun directLambdaInliningMatchesImplicitItInvocationSemantics() = runTest {
|
||||||
|
val script = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<direct-inline-it-semantics>",
|
||||||
|
"""
|
||||||
|
val zeroFn = { if (it == void) 1 else 0 }
|
||||||
|
val multiFn = { it }
|
||||||
|
val zero = zeroFn()
|
||||||
|
val multi = multiFn(1, 2, 3)
|
||||||
|
[zero, multi]
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val result = script.execute(scope) as ObjList
|
||||||
|
|
||||||
|
assertEquals(1, result.list[0].toInt())
|
||||||
|
val multi = result.list[1] as ObjList
|
||||||
|
assertEquals(listOf(1, 2, 3), multi.list.map { it.toInt() })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun mapGetOrPutUsesInlineDefaultLambda() = runTest {
|
||||||
|
val script = Compiler.compile(
|
||||||
|
Source(
|
||||||
|
"<map-get-or-put-inline>",
|
||||||
|
"""
|
||||||
|
val offset = 10
|
||||||
|
val m = Map()
|
||||||
|
val first = m.getOrPut("k") { offset + 1 }
|
||||||
|
val second = m.getOrPut("k") { offset + 2 }
|
||||||
|
[first, second, m["k"]]
|
||||||
|
""".trimIndent()
|
||||||
|
),
|
||||||
|
Script.defaultImportManager
|
||||||
|
)
|
||||||
|
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val result = script.execute(scope) as ObjList
|
||||||
|
|
||||||
|
assertEquals(11, result.list[0].toInt())
|
||||||
|
assertEquals(11, result.list[1].toInt())
|
||||||
|
assertEquals(11, result.list[2].toInt())
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun subjectlessWhenReportsScriptError() = runTest {
|
fun subjectlessWhenReportsScriptError() = runTest {
|
||||||
val ex = assertFailsWith<ScriptError> {
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
|||||||
@@ -58,6 +58,38 @@ class TestCoroutines {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCompletableExceptionally() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
val done = CompletableDeferred()
|
||||||
|
|
||||||
|
launch {
|
||||||
|
delay(10)
|
||||||
|
done.completeExceptionally(IllegalStateException("boom"))
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(!done.isCompleted)
|
||||||
|
assertThrows(IllegalStateException) { done.await() }
|
||||||
|
assert(done.isCompleted)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCompletableExceptionallyWithCustomException() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class MyError(msg) : Exception(msg) {}
|
||||||
|
|
||||||
|
val done = CompletableDeferred()
|
||||||
|
done.completeExceptionally(MyError("custom failure"))
|
||||||
|
|
||||||
|
assertThrows(MyError) { done.await() }
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testDeferredCancel() = runTest {
|
fun testDeferredCancel() = runTest {
|
||||||
eval(
|
eval(
|
||||||
|
|||||||
@@ -0,0 +1,189 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import kotlinx.coroutines.withTimeout
|
||||||
|
import kotlin.test.Test
|
||||||
|
import net.sergeych.lyng.eval as lyngEval
|
||||||
|
|
||||||
|
class LaunchPoolTest {
|
||||||
|
|
||||||
|
private suspend fun eval(code: String) = withTimeout(2_000L) { lyngEval(code) }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBasicExecution() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
val d1 = pool.launch { 1 + 1 }
|
||||||
|
val d2 = pool.launch { "hello" }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
assertEquals(2, d1.await())
|
||||||
|
assertEquals("hello", d2.await())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testResultsCollected() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(4)
|
||||||
|
val jobs = (1..10).map { n -> pool.launch { n * n } }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
val results = jobs.map { (it as Deferred).await() }
|
||||||
|
assertEquals([1,4,9,16,25,36,49,64,81,100], results)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testConcurrencyLimit() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
// With maxWorkers=2, at most 2 tasks run at the same time.
|
||||||
|
val mu = Mutex()
|
||||||
|
var active = 0
|
||||||
|
var maxSeen = 0
|
||||||
|
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
val jobs = (1..8).map {
|
||||||
|
pool.launch {
|
||||||
|
mu.withLock { active++; if (active > maxSeen) maxSeen = active }
|
||||||
|
delay(5)
|
||||||
|
mu.withLock { active-- }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pool.closeAndJoin()
|
||||||
|
|
||||||
|
assert(maxSeen <= 2) { "maxSeen was " + maxSeen + ", expected <= 2" }
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testExceptionCapturedInDeferred() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
val good = pool.launch { 42 }
|
||||||
|
val bad = pool.launch { throw IllegalArgumentException("boom") }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
|
||||||
|
assertEquals(42, good.await())
|
||||||
|
assertThrows(IllegalArgumentException) { bad.await() }
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPoolContinuesAfterLambdaException() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(1)
|
||||||
|
val bad = pool.launch { throw IllegalArgumentException("fail") }
|
||||||
|
val good = pool.launch { "ok" }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException) { bad.await() }
|
||||||
|
assertEquals("ok", good.await())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLaunchAfterCloseAndJoinThrows() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
pool.launch { 1 }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException) { pool.launch { 2 } }
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLaunchAfterCancelThrows() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
pool.cancel()
|
||||||
|
|
||||||
|
assertThrows(IllegalStateException) { pool.launch { 1 } }
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCancelAndJoinWaitsForWorkers() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
pool.launch { delay(5) }
|
||||||
|
pool.cancelAndJoin()
|
||||||
|
// pool is now closed — further launches must throw
|
||||||
|
assertThrows(IllegalStateException) { pool.launch { 1 } }
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCloseAndJoinDrainsQueue() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val mu = Mutex()
|
||||||
|
val results = []
|
||||||
|
val pool = LaunchPool(1) // single worker to force sequential execution
|
||||||
|
|
||||||
|
(1..5).forEach { n ->
|
||||||
|
pool.launch {
|
||||||
|
delay(1)
|
||||||
|
mu.withLock { results += n }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pool.closeAndJoin() // waits for all 5 to complete
|
||||||
|
|
||||||
|
assertEquals(5, results.size)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBoundedQueueSuspendsProducer() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
// queue of 2 + 1 worker; producer can only be 1 ahead of what's running
|
||||||
|
val pool = LaunchPool(1, 2)
|
||||||
|
val order = []
|
||||||
|
val mu = Mutex()
|
||||||
|
|
||||||
|
// fill the queue
|
||||||
|
val d1 = pool.launch { delay(5); mu.withLock { order += 1 } }
|
||||||
|
val d2 = pool.launch { delay(3); mu.withLock { order += 2 } }
|
||||||
|
val d3 = pool.launch { delay(3); mu.withLock { order += 3 } }
|
||||||
|
|
||||||
|
pool.closeAndJoin()
|
||||||
|
assertEquals(3, order.size)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testUnlimitedQueueDefault() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(4)
|
||||||
|
val jobs = (1..50).map { n -> pool.launch { n } }
|
||||||
|
pool.closeAndJoin()
|
||||||
|
var sum = 0
|
||||||
|
for (j in jobs) { sum += (j as Deferred).await() }
|
||||||
|
assertEquals(1275, sum) // 1+2+...+50
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIdempotentClose() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
val pool = LaunchPool(2)
|
||||||
|
pool.closeAndJoin()
|
||||||
|
pool.closeAndJoin() // calling again must not throw
|
||||||
|
pool.cancel() // mixing close calls must not throw either
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -436,4 +436,36 @@ class StdlibTest {
|
|||||||
assertEquals(2, x)
|
assertEquals(2, x)
|
||||||
""".trimIndent())
|
""".trimIndent())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testListFill() = runTest {
|
||||||
|
eval("""
|
||||||
|
val x = List.fill(5) { i -> i * 10 }
|
||||||
|
assertEquals([0, 10, 20, 30, 40], x)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
fun testListFill2() = runTest {
|
||||||
|
eval("""
|
||||||
|
val b: List<Int> = List.fill(5,10) { it }
|
||||||
|
println(b)
|
||||||
|
assertEquals(b, [0,1,2,3,4])
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testTypedParamCaptureInClosure() = runTest {
|
||||||
|
// Regression: typed (Int) parameters lost their value when captured into a closure
|
||||||
|
// because peekValue() returned null for INT-typed frame slots, causing the capture
|
||||||
|
// to store a FrameSlotRef as OBJ while bytecode expected INT type.
|
||||||
|
eval("""
|
||||||
|
fun makeList(n: Int): List<Int> {
|
||||||
|
List<Int>().also {
|
||||||
|
for( i in 0..<n ) it += i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertEquals([0,1,2,3,4], makeList(5))
|
||||||
|
assertEquals([], makeList(0))
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import net.sergeych.lyng.eval
|
||||||
|
import kotlin.test.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression tests for type inference of class fields accessed inside nested closures.
|
||||||
|
*
|
||||||
|
* A class field declared as `val foo = SomeType(...)` should have its type inferred as
|
||||||
|
* `SomeType` everywhere inside the class body, including inside lambdas and closures
|
||||||
|
* that capture the field via the implicit `this` receiver.
|
||||||
|
*/
|
||||||
|
class TypeInferenceTest {
|
||||||
|
|
||||||
|
/** Channel field type inferred from constructor — accessed in a launch closure */
|
||||||
|
@Test
|
||||||
|
fun testChannelFieldInLaunchClosure() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
class Foo {
|
||||||
|
private val ch = Channel(Channel.UNLIMITED)
|
||||||
|
private val worker = launch {
|
||||||
|
var item = ch.receive()
|
||||||
|
while (item != null) {
|
||||||
|
item = ch.receive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun start() {
|
||||||
|
ch.send(1)
|
||||||
|
ch.close()
|
||||||
|
(worker as Deferred).await()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Foo().start()
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mutex field type inferred from constructor — used directly in a method body */
|
||||||
|
@Test
|
||||||
|
fun testMutexFieldDirectUse() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
class Bar {
|
||||||
|
private val mu = Mutex()
|
||||||
|
private var count = 0
|
||||||
|
fun inc() { mu.withLock { count++ } }
|
||||||
|
fun get() { count }
|
||||||
|
}
|
||||||
|
val b = Bar()
|
||||||
|
b.inc()
|
||||||
|
b.inc()
|
||||||
|
assertEquals(2, b.get())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** CompletableDeferred field type inferred — complete/await used directly */
|
||||||
|
@Test
|
||||||
|
fun testCompletableDeferredFieldDirectUse() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
class Baz {
|
||||||
|
private val d = CompletableDeferred()
|
||||||
|
fun complete(v) { d.complete(v) }
|
||||||
|
fun result() { (d as Deferred).await() }
|
||||||
|
}
|
||||||
|
val baz = Baz()
|
||||||
|
launch { baz.complete(42) }
|
||||||
|
assertEquals(42, baz.result())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Channel field accessed inside a map closure within class initializer */
|
||||||
|
@Test
|
||||||
|
fun testChannelFieldInMapAndLaunchClosure() = runBlocking<Unit> {
|
||||||
|
eval("""
|
||||||
|
class Pool(n) {
|
||||||
|
private val ch = Channel(Channel.UNLIMITED)
|
||||||
|
private val workers = (1..n).map {
|
||||||
|
launch {
|
||||||
|
var item = ch.receive()
|
||||||
|
while (item != null) {
|
||||||
|
item = ch.receive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun closeAll() {
|
||||||
|
ch.close()
|
||||||
|
for (w in workers) { (w as Deferred).await() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Pool(2).closeAll()
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -104,14 +104,14 @@ class WebsiteSamplesTest {
|
|||||||
val name = "Lyng"
|
val name = "Lyng"
|
||||||
val base = { id:, name: } // Shorthand for id: id, name: name
|
val base = { id:, name: } // Shorthand for id: id, name: name
|
||||||
|
|
||||||
val full = { ...base, version: "1.5.4", status: "stable" }
|
val full = { ...base, version: "1.5.5", status: "stable" }
|
||||||
full
|
full
|
||||||
""".trimIndent())
|
""".trimIndent())
|
||||||
assertTrue(result is ObjMap)
|
assertTrue(result is ObjMap)
|
||||||
val m = result.map
|
val m = result.map
|
||||||
assertEquals(101L, (m[ObjString("id")] as ObjInt).value)
|
assertEquals(101L, (m[ObjString("id")] as ObjInt).value)
|
||||||
assertEquals("Lyng", (m[ObjString("name")] as ObjString).value)
|
assertEquals("Lyng", (m[ObjString("name")] as ObjString).value)
|
||||||
assertEquals("1.5.4", (m[ObjString("version")] as ObjString).value)
|
assertEquals("1.5.5", (m[ObjString("version")] as ObjString).value)
|
||||||
assertEquals("stable", (m[ObjString("status")] as ObjString).value)
|
assertEquals("stable", (m[ObjString("status")] as ObjString).value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -205,10 +205,8 @@ class DecimalModuleTest {
|
|||||||
assertEquals("0.3333333333333333333333333333333333", (1.d / 3.d).toStringExpanded())
|
assertEquals("0.3333333333333333333333333333333333", (1.d / 3.d).toStringExpanded())
|
||||||
assertEquals("0.3333333333", withDecimalContext(10) { (1.d / 3.d).toStringExpanded() })
|
assertEquals("0.3333333333", withDecimalContext(10) { (1.d / 3.d).toStringExpanded() })
|
||||||
assertEquals("0.666667", withDecimalContext(6) { ("2".d / 3.d).toStringExpanded() })
|
assertEquals("0.666667", withDecimalContext(6) { ("2".d / 3.d).toStringExpanded() })
|
||||||
assertEquals("0.666667", withDecimalContext(DecimalContext(6)) { ("2".d / 3.d).toStringExpanded() })
|
|
||||||
assertEquals("0.12", withDecimalContext(2) { (1.d / 8.d).toStringExpanded() })
|
assertEquals("0.12", withDecimalContext(2) { (1.d / 8.d).toStringExpanded() })
|
||||||
assertEquals("0.13", withDecimalContext(2, DecimalRounding.HalfAwayFromZero) { (1.d / 8.d).toStringExpanded() })
|
assertEquals("0.13", withDecimalContext(2, DecimalRounding.HalfAwayFromZero) { (1.d / 8.d).toStringExpanded() })
|
||||||
assertEquals("0.13", withDecimalContext(DecimalContext(2, DecimalRounding.HalfAwayFromZero)) { (1.d / 8.d).toStringExpanded() })
|
|
||||||
assertEquals("0.3333333333333333333333333333333333", (1.d / 3.d).toStringExpanded())
|
assertEquals("0.3333333333333333333333333333333333", (1.d / 3.d).toStringExpanded())
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ package net.sergeych.lyng
|
|||||||
|
|
||||||
import kotlinx.coroutines.test.runTest
|
import kotlinx.coroutines.test.runTest
|
||||||
import kotlin.test.Test
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContains
|
||||||
|
import kotlin.test.assertFailsWith
|
||||||
|
|
||||||
class OperatorOverloadingTest {
|
class OperatorOverloadingTest {
|
||||||
@Test
|
@Test
|
||||||
@@ -63,6 +65,24 @@ class OperatorOverloadingTest {
|
|||||||
""".trimIndent())
|
""".trimIndent())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBuiltinListPlusAssignOnVal() = runTest {
|
||||||
|
eval("""
|
||||||
|
val list = [1, 2]
|
||||||
|
list += 3
|
||||||
|
assertEquals([1, 2, 3], list)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBuiltinListMinusAssignOnVal() = runTest {
|
||||||
|
eval("""
|
||||||
|
val list = [1, 2, 3]
|
||||||
|
list -= 2
|
||||||
|
assertEquals([1, 3], list)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testPlusAssignFallback() = runTest {
|
fun testPlusAssignFallback() = runTest {
|
||||||
eval("""
|
eval("""
|
||||||
@@ -76,6 +96,130 @@ class OperatorOverloadingTest {
|
|||||||
""".trimIndent())
|
""".trimIndent())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPlusAssignFallbackOnValReportsReadonlyError() = runTest {
|
||||||
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
eval("""
|
||||||
|
class Vector(var x: Int, var y: Int) {
|
||||||
|
fun plus(other: Vector) = Vector(this.x + other.x, this.y + other.y)
|
||||||
|
fun equals(other: Vector) = this.x == other.x && this.y == other.y
|
||||||
|
}
|
||||||
|
val v = Vector(1, 2)
|
||||||
|
v += Vector(3, 4)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
assertContains(ex.errorMessage, "can't reassign val v")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMinusAssignOverloadingOnVal() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun minusAssign(x: Int) { this.n = this.n - x }
|
||||||
|
}
|
||||||
|
val c = Counter(10)
|
||||||
|
c -= 3
|
||||||
|
assertEquals(7, c.n)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMinusAssignFallbackOnValReportsReadonlyError() = runTest {
|
||||||
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun minus(x: Int) = Counter(this.n - x)
|
||||||
|
}
|
||||||
|
val c = Counter(10)
|
||||||
|
c -= 3
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
assertContains(ex.errorMessage, "can't reassign val c")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMulAssignOverloadingOnVal() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun mulAssign(x: Int) { this.n = this.n * x }
|
||||||
|
}
|
||||||
|
val c = Counter(10)
|
||||||
|
c *= 3
|
||||||
|
assertEquals(30, c.n)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMulAssignFallbackOnValReportsReadonlyError() = runTest {
|
||||||
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun times(x: Int) = Counter(this.n * x)
|
||||||
|
}
|
||||||
|
val c = Counter(10)
|
||||||
|
c *= 3
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
assertContains(ex.errorMessage, "can't reassign val c")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDivAssignOverloadingOnVal() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun divAssign(x: Int) { this.n = this.n / x }
|
||||||
|
}
|
||||||
|
val c = Counter(21)
|
||||||
|
c /= 3
|
||||||
|
assertEquals(7, c.n)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDivAssignFallbackOnValReportsReadonlyError() = runTest {
|
||||||
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun div(x: Int) = Counter(this.n / x)
|
||||||
|
}
|
||||||
|
val c = Counter(21)
|
||||||
|
c /= 3
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
assertContains(ex.errorMessage, "can't reassign val c")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testModAssignOverloadingOnVal() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun modAssign(x: Int) { this.n = this.n % x }
|
||||||
|
}
|
||||||
|
val c = Counter(23)
|
||||||
|
c %= 5
|
||||||
|
assertEquals(3, c.n)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testModAssignFallbackOnValReportsReadonlyError() = runTest {
|
||||||
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
eval("""
|
||||||
|
class Counter(var n: Int) {
|
||||||
|
fun mod(x: Int) = Counter(this.n % x)
|
||||||
|
}
|
||||||
|
val c = Counter(23)
|
||||||
|
c %= 5
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
assertContains(ex.errorMessage, "can't reassign val c")
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun testCompareOverloading() = runTest {
|
fun testCompareOverloading() = runTest {
|
||||||
eval("""
|
eval("""
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
/*
|
||||||
|
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
|
||||||
|
*
|
||||||
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
* you may not use this file except in compliance with the License.
|
||||||
|
* You may obtain a copy of the License at
|
||||||
|
*
|
||||||
|
* http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
*
|
||||||
|
* Unless required by applicable law or agreed to in writing, software
|
||||||
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
* See the License for the specific language governing permissions and
|
||||||
|
* limitations under the License.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.lyng.obj.toInt
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertContains
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFailsWith
|
||||||
|
import kotlin.time.TimeSource
|
||||||
|
|
||||||
|
class OptTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAddToArray() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
fun buildArray(n: Int) {
|
||||||
|
val a: List<Int> = List.fill(n) { it * 10 + 1 }
|
||||||
|
a.size
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
repeat(3) { pass ->
|
||||||
|
val size = scope.eval("buildArray(200000)").toInt()
|
||||||
|
assertEquals(200000, size, "warmup pass ${pass + 1} failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
val passes = 4
|
||||||
|
var bestMs = Long.MAX_VALUE
|
||||||
|
var totalMs = 0L
|
||||||
|
repeat(passes) { pass ->
|
||||||
|
val start = TimeSource.Monotonic.markNow()
|
||||||
|
val size = scope.eval("buildArray(10000000)").toInt()
|
||||||
|
val elapsedMs = start.elapsedNow().inWholeMilliseconds
|
||||||
|
assertEquals(10000000, size, "measured pass ${pass + 1} failed")
|
||||||
|
bestMs = minOf(bestMs, elapsedMs)
|
||||||
|
totalMs += elapsedMs
|
||||||
|
println("add-to-array pass ${pass + 1}/$passes: ${elapsedMs}ms size=$size")
|
||||||
|
}
|
||||||
|
println("add-to-array best=${bestMs}ms avg=${totalMs / passes}ms after warmup")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAddToArray2() = runTest {
|
||||||
|
eval(
|
||||||
|
$$"""
|
||||||
|
import lyng.time
|
||||||
|
val n = 700_000
|
||||||
|
fun tm<T>(block: ()->T): T {
|
||||||
|
val t = Instant()
|
||||||
|
block().also {
|
||||||
|
println("tm: ${Instant() - t}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val x = tm { List.fill(n) { it * 10 + 1 } }
|
||||||
|
val y = tm { List.fill(n, n + 10) { it * 10 + 1 } }
|
||||||
|
tm { x.add(-1) }
|
||||||
|
tm { y.add(-2) }
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testErrorMessage() = runTest {
|
||||||
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
eval("""
|
||||||
|
val a = 1
|
||||||
|
a++
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
assertContains(ex.errorMessage, "can't reassign val a")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAssignOpErrorMessageFromExample() = runTest {
|
||||||
|
val source = Source(
|
||||||
|
"examples/error1.lyng",
|
||||||
|
"""
|
||||||
|
val a = 1
|
||||||
|
a += 2
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
val ex = assertFailsWith<ScriptError> {
|
||||||
|
Script.newScope().eval(source)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertContains(ex.errorMessage, "can't reassign val a")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testClosuresInLaunchPool() = runTest {
|
||||||
|
eval($$"""
|
||||||
|
val result = Set()
|
||||||
|
val mu = Mutex()
|
||||||
|
fn doSomething(value) {
|
||||||
|
delay(100)
|
||||||
|
println(value)
|
||||||
|
mu.withLock {
|
||||||
|
result += value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val lp = LaunchPool(4, 1000)
|
||||||
|
for (i in 1 .. 10) {
|
||||||
|
val ii: Int = i
|
||||||
|
lp.launch {
|
||||||
|
doSomething( ii )
|
||||||
|
}
|
||||||
|
}
|
||||||
|
println("all tasks were placed into lauchpool")
|
||||||
|
lp.closeAndJoin()
|
||||||
|
println("ALL DONE: $result")
|
||||||
|
assertEquals((1..10).toSet(), result)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ actual object PerfDefaults {
|
|||||||
|
|
||||||
actual val ARG_BUILDER: Boolean = true
|
actual val ARG_BUILDER: Boolean = true
|
||||||
actual val SKIP_ARGS_ON_NULL_RECEIVER: Boolean = true
|
actual val SKIP_ARGS_ON_NULL_RECEIVER: Boolean = true
|
||||||
actual val SCOPE_POOL: Boolean = true
|
actual val SCOPE_POOL: Boolean = false
|
||||||
|
|
||||||
actual val FIELD_PIC: Boolean = true
|
actual val FIELD_PIC: Boolean = true
|
||||||
actual val METHOD_PIC: Boolean = true
|
actual val METHOD_PIC: Boolean = true
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package lyng.complex
|
package lyng.complex
|
||||||
|
|
||||||
|
import lyng.decimal
|
||||||
import lyng.operators
|
import lyng.operators
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@@ -112,8 +113,10 @@ fun cis(angle: Real): Complex = Complex.fromPolar(1.0, angle)
|
|||||||
|
|
||||||
val Int.re: Complex get() = Complex.fromInt(this)
|
val Int.re: Complex get() = Complex.fromInt(this)
|
||||||
val Real.re: Complex get() = Complex.fromReal(this)
|
val Real.re: Complex get() = Complex.fromReal(this)
|
||||||
|
val Decimal.re: Complex get() = Complex(this.toReal(), 0.0)
|
||||||
val Int.i: Complex get() = Complex.imaginary(this + 0.0)
|
val Int.i: Complex get() = Complex.imaginary(this + 0.0)
|
||||||
val Real.i: Complex get() = Complex.imaginary(this)
|
val Real.i: Complex get() = Complex.imaginary(this)
|
||||||
|
val Decimal.i: Complex get() = Complex(0.0, this.toReal())
|
||||||
|
|
||||||
OperatorInterop.register(
|
OperatorInterop.register(
|
||||||
Int,
|
Int,
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ type MatrixScalar = Real | Int
|
|||||||
extern class Vector() {
|
extern class Vector() {
|
||||||
/** Number of elements. */
|
/** Number of elements. */
|
||||||
val size: Int
|
val size: Int
|
||||||
|
get() = 0
|
||||||
|
|
||||||
/** Alias to `size`. */
|
/** Alias to `size`. */
|
||||||
val length: Int
|
val length: Int
|
||||||
|
get() = 0
|
||||||
|
|
||||||
/** Convert to a plain list. */
|
/** Convert to a plain list. */
|
||||||
extern fun toList(): List<Real>
|
extern fun toList(): List<Real>
|
||||||
@@ -61,15 +63,19 @@ extern class Vector() {
|
|||||||
extern class Matrix() {
|
extern class Matrix() {
|
||||||
/** Number of rows. */
|
/** Number of rows. */
|
||||||
val rows: Int
|
val rows: Int
|
||||||
|
get() = 0
|
||||||
|
|
||||||
/** Number of columns. */
|
/** Number of columns. */
|
||||||
val cols: Int
|
val cols: Int
|
||||||
|
get() = 0
|
||||||
|
|
||||||
/** Two-element shape `[rows, cols]`. */
|
/** Two-element shape `[rows, cols]`. */
|
||||||
val shape: List<Int>
|
val shape: List<Int>
|
||||||
|
get() = []
|
||||||
|
|
||||||
/** Whether `rows == cols`. */
|
/** Whether `rows == cols`. */
|
||||||
val isSquare: Bool
|
val isSquare: Bool
|
||||||
|
get() = false
|
||||||
|
|
||||||
/** Element-wise addition. Shapes must match. */
|
/** Element-wise addition. Shapes must match. */
|
||||||
extern fun plus(other: Matrix): Matrix
|
extern fun plus(other: Matrix): Matrix
|
||||||
|
|||||||
Loaded 100 of 108 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user