Compare commits
35
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
555c9b94de | ||
|
|
8cd980514b | ||
|
|
fa4dc45f15 | ||
|
|
ae68ecd066 | ||
|
|
ddfdc18ba3 | ||
|
|
1afc6d41bc | ||
|
|
83ab8cdc01 | ||
|
|
26b8370b01 | ||
|
|
660a80a26b | ||
|
|
d91acd593a | ||
|
|
5fc0969491 | ||
|
|
eec732d11a | ||
|
|
8611543623 | ||
|
|
73854f21f3 | ||
|
|
f66e61c185 | ||
|
|
41a3617850 | ||
|
|
f792c73b8f | ||
|
|
20f777f9f6 | ||
|
|
5f819dc87a | ||
|
|
8e766490d9 | ||
|
|
514ad96148 | ||
|
|
e0a59c8db6 | ||
|
|
75e2b63923 | ||
|
|
5f1e6564d5 | ||
|
|
f5a3fbe9a3 | ||
|
|
11eadc1d9f | ||
|
|
96e1ffc7d5 | ||
|
|
aad7c9619b | ||
|
|
9e138367ef | ||
|
|
1d9befe101 | ||
|
|
abb262d9cf | ||
|
|
eca451b5a3 | ||
|
|
54af50d6d6 | ||
|
|
ce0fc3650d | ||
|
|
ce021e85f4 |
No files matched your search
@@ -20,3 +20,9 @@ xcuserdata
|
|||||||
.output*.txt
|
.output*.txt
|
||||||
debug.log
|
debug.log
|
||||||
/build.log
|
/build.log
|
||||||
|
/test.md
|
||||||
|
/build_output.txt
|
||||||
|
/build_output_full.txt
|
||||||
|
/check_output.txt
|
||||||
|
/compile_jvm_output.txt
|
||||||
|
/compile_metadata_output.txt
|
||||||
+39
-1
@@ -2,6 +2,26 @@
|
|||||||
|
|
||||||
### Unreleased
|
### Unreleased
|
||||||
|
|
||||||
|
- Language: Added `return` statement
|
||||||
|
- `return [expression]` exits the innermost enclosing callable (function or lambda).
|
||||||
|
- Supports non-local returns using `@label` syntax (e.g., `return@outer 42`).
|
||||||
|
- Named functions automatically provide their name as a label for non-local returns.
|
||||||
|
- Labeled lambdas: lambdas can be explicitly labeled using `@label { ... }`.
|
||||||
|
- Restriction: `return` is forbidden in shorthand function definitions (e.g., `fun f(x) = return x` is a syntax error).
|
||||||
|
- Control Flow: `return` and `break` are now protected from being caught by user-defined `try-catch` blocks in Lyng.
|
||||||
|
- Documentation: New `docs/return_statement.md` and updated `tutorial.md`.
|
||||||
|
|
||||||
|
- Language: stdlib improvements
|
||||||
|
- Added `with(self, block)` function to `root.lyng` which executes a block with `this` set to the provided object.
|
||||||
|
- Language: Abstract Classes and Interfaces
|
||||||
|
- Support for `abstract` modifier on classes, methods, and variables.
|
||||||
|
- Introduced `interface` as a synonym for `abstract class`, supporting full state (constructors, fields, `init` blocks) and implementation by parts via MI.
|
||||||
|
- New `closed` modifier (antonym to `open`) to prevent overriding class members.
|
||||||
|
- Refined `override` logic: mandatory keyword when re-declaring members that exist in the ancestor chain (MRO).
|
||||||
|
- MI Satisfaction: Abstract requirements are automatically satisfied by matching concrete members found later in the C3 MRO chain without requiring explicit proxy methods.
|
||||||
|
- Integration: Updated highlighters (lynglib, lyngweb, IDEA plugin), IDEA completion, and Grazie grammar checking.
|
||||||
|
- Documentation: Updated `docs/OOP.md` with sections on "Abstract Classes and Members", "Interfaces", and "Overriding and Virtual Dispatch".
|
||||||
|
|
||||||
- Language: Class properties with accessors
|
- Language: Class properties with accessors
|
||||||
- Support for `val` (read-only) and `var` (read-write) properties in classes.
|
- Support for `val` (read-only) and `var` (read-write) properties in classes.
|
||||||
- Syntax: `val name [ : Type ] get() { body }` or `var name [ : Type ] get() { body } set(value) { body }`.
|
- Syntax: `val name [ : Type ] get() { body }` or `var name [ : Type ] get() { body } set(value) { body }`.
|
||||||
@@ -11,7 +31,22 @@
|
|||||||
- Integration: Updated TextMate grammar and IntelliJ plugin (highlighting + keywords).
|
- Integration: Updated TextMate grammar and IntelliJ plugin (highlighting + keywords).
|
||||||
- Documentation: New "Properties" section in `docs/OOP.md`.
|
- Documentation: New "Properties" section in `docs/OOP.md`.
|
||||||
|
|
||||||
- Docs: Scopes and Closures guidance
|
- Language: Restricted Setter Visibility
|
||||||
|
- Support for `private set` and `protected set` modifiers on `var` fields and properties.
|
||||||
|
- Allows members to be publicly readable but only writable from within the declaring class or its subclasses.
|
||||||
|
- Enforcement at runtime: throws `AccessException` on unauthorized writes.
|
||||||
|
- Supported only for declarations in class bodies (fields and properties).
|
||||||
|
- Documentation: New "Restricted Setter Visibility" section in `docs/OOP.md`.
|
||||||
|
|
||||||
|
- Language: Late-initialized `val` fields in classes
|
||||||
|
- Support for declaring `val` without an immediate initializer in class bodies.
|
||||||
|
- Compulsory initialization: every late-init `val` must be assigned at least once within the class body or an `init` block.
|
||||||
|
- Write-once enforcement: assigning to a `val` is allowed only if its current value is `Unset`.
|
||||||
|
- Access protection: reading a late-init `val` before it is assigned returns the `Unset` singleton; using `Unset` for most operations throws an `UnsetException`.
|
||||||
|
- Extension properties do not support late-init.
|
||||||
|
- Documentation: New "Late-initialized `val` fields" and "The `Unset` singleton" sections in `docs/OOP.md`.
|
||||||
|
|
||||||
|
- Docs: OOP improvements
|
||||||
- New page: `docs/scopes_and_closures.md` detailing `ClosureScope` resolution order, recursion‑safe helpers (`chainLookupIgnoreClosure`, `chainLookupWithMembers`, `baseGetIgnoreClosure`), cycle prevention, and capturing lexical environments for callbacks (`snapshotForClosure`).
|
- New page: `docs/scopes_and_closures.md` detailing `ClosureScope` resolution order, recursion‑safe helpers (`chainLookupIgnoreClosure`, `chainLookupWithMembers`, `baseGetIgnoreClosure`), cycle prevention, and capturing lexical environments for callbacks (`snapshotForClosure`).
|
||||||
- Updated: `docs/advanced_topics.md` (link to the new page), `docs/parallelism.md` (closures in `launch`/`flow`), `docs/OOP.md` (visibility from closures with preserved `currentClassCtx`), `docs/exceptions_handling.md` (compatibility alias `SymbolNotFound`).
|
- Updated: `docs/advanced_topics.md` (link to the new page), `docs/parallelism.md` (closures in `launch`/`flow`), `docs/OOP.md` (visibility from closures with preserved `currentClassCtx`), `docs/exceptions_handling.md` (compatibility alias `SymbolNotFound`).
|
||||||
- Tutorial: added quick link to Scopes and Closures.
|
- Tutorial: added quick link to Scopes and Closures.
|
||||||
@@ -83,6 +118,9 @@ All notable changes to this project will be documented in this file.
|
|||||||
- Mutually exclusive: `--check` and `--in-place` together now produce an error and exit with code 1.
|
- Mutually exclusive: `--check` and `--in-place` together now produce an error and exit with code 1.
|
||||||
- Multi-file stdout prints headers `--- <path> ---` per file.
|
- Multi-file stdout prints headers `--- <path> ---` per file.
|
||||||
- `lyng --help` shows `fmt`; `lyng fmt --help` displays dedicated help.
|
- `lyng --help` shows `fmt`; `lyng fmt --help` displays dedicated help.
|
||||||
|
- Fix: Property accessors (`get`, `set`, `private set`, `protected set`) are now correctly indented relative to the property declaration.
|
||||||
|
- Fix: Indentation now correctly carries over into blocks that start on extra‑indented lines (e.g., nested `if` statements or property accessor bodies).
|
||||||
|
- Fix: Formatting Markdown files no longer deletes content in `.lyng` code fences and works correctly with injected files (resolves clobbering, `StringIndexOutOfBoundsException`, and `nonempty text is not covered by block` errors).
|
||||||
|
|
||||||
- CLI: Preserved legacy script invocation fast-paths:
|
- CLI: Preserved legacy script invocation fast-paths:
|
||||||
- `lyng script.lyng [args...]` executes the script directly.
|
- `lyng script.lyng [args...]` executes the script directly.
|
||||||
|
|||||||
@@ -1,6 +1,14 @@
|
|||||||
# Lyng: modern scripting for kotlin multiplatform
|
# Lyng: ideal scripting for kotlin multiplatform
|
||||||
|
|
||||||
|
__Please visit the project homepage: [https://lynglang.com](https://lynglang.com) and a [telegram channel](https://t.me/lynglang).__
|
||||||
|
|
||||||
|
__Main development site:__ [https://gitea.sergeych.net/SergeychWorks/lyng](https://gitea.sergeych.net/SergeychWorks/lyng)
|
||||||
|
__github mirror__: [https://github.com/sergeych/lyng](https://github.com/sergeych/lyng)
|
||||||
|
|
||||||
|
We keep github as a mirror and backup for the project, while the main development site is hosted on gitea.sergeych.net. We use gitea for issues and pull requests, and as a main point of trust, as github access now is a thing that can momentarily be revoked for no apparent reason.
|
||||||
|
|
||||||
|
We encourage using the github if the main site is not accessible from your country and vice versa. We recommend to `publishToMavenLocal` and not depend on politics.
|
||||||
|
|
||||||
Please visit the project homepage: [https://lynglang.com](https://lynglang.com) and a [telegram channel](https://t.me/lynglang) for updates.
|
|
||||||
|
|
||||||
- simple, compact, intuitive and elegant modern code:
|
- simple, compact, intuitive and elegant modern code:
|
||||||
|
|
||||||
@@ -21,22 +29,9 @@ fun swapEnds(first, args..., last, f) {
|
|||||||
|
|
||||||
- extremely simple Kotlin integration on any platform (JVM, JS, WasmJS, Lunux, MacOS, iOS, Windows)
|
- extremely simple Kotlin integration on any platform (JVM, JS, WasmJS, Lunux, MacOS, iOS, Windows)
|
||||||
- 100% secure: no access to any API you didn't explicitly provide
|
- 100% secure: no access to any API you didn't explicitly provide
|
||||||
- 100% coroutines! Every function/script is a coroutine, it does not block the thread, no async/await/suspend keyword garbage, see [parallelism]
|
- 100% coroutines! Every function/script is a coroutine, it does not block the thread, no async/await/suspend keyword garbage, see [parallelism]. it is multithreaded on platforms supporting it (automatically, no code changes required, just `launch` more coroutines and they will be executed concurrently if possible). See [parallelism]
|
||||||
|
- functional style and OOP together: multiple inheritance (so you got it all - mixins, interfaces, etc.), delegation, sigletons, anonymous classes,extensions.
|
||||||
```
|
- nice literals for maps and arrays, destructuring assignment, ranges.
|
||||||
val deferred = launch {
|
|
||||||
delay(1.5) // coroutine is delayed for 1.5s, thread is not blocked!
|
|
||||||
"done"
|
|
||||||
}
|
|
||||||
// ...
|
|
||||||
// suspend current coroutine, no thread is blocked again,
|
|
||||||
// and wait for deferred to return something:
|
|
||||||
assertEquals("donw", deferred.await())
|
|
||||||
```
|
|
||||||
and it is multithreaded on platforms supporting it (automatically, no code changes required, just
|
|
||||||
`launch` more coroutines and they will be executed concurrently if possible). See [parallelism]
|
|
||||||
|
|
||||||
- functional style and OOP together, multiple inheritance, implementing interfaces for existing classes, writing extensions.
|
|
||||||
- Any Unicode letters can be used as identifiers: `assert( sin(π/2) == 1 )`.
|
- Any Unicode letters can be used as identifiers: `assert( sin(π/2) == 1 )`.
|
||||||
|
|
||||||
## Resources:
|
## Resources:
|
||||||
@@ -44,6 +39,8 @@ and it is multithreaded on platforms supporting it (automatically, no code chang
|
|||||||
- [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
|
||||||
- [Testing and Assertions](docs/Testing.md)
|
- [Testing and Assertions](docs/Testing.md)
|
||||||
|
- [Filesystem and Processes (lyngio)](docs/lyngio.md)
|
||||||
|
- [Return Statement](docs/return_statement.md)
|
||||||
- [Efficient Iterables in Kotlin Interop](docs/EfficientIterables.md)
|
- [Efficient Iterables in Kotlin Interop](docs/EfficientIterables.md)
|
||||||
- [Samples directory](docs/samples)
|
- [Samples directory](docs/samples)
|
||||||
- [Formatter (core + CLI + IDE)](docs/formatter.md)
|
- [Formatter (core + CLI + IDE)](docs/formatter.md)
|
||||||
@@ -191,6 +188,16 @@ Ready features:
|
|||||||
- [x] regular exceptions + extended `when`
|
- [x] regular exceptions + extended `when`
|
||||||
- [x] multiple inheritance for user classes
|
- [x] multiple inheritance for user classes
|
||||||
- [x] class properties (accessors)
|
- [x] class properties (accessors)
|
||||||
|
- [x] `return` statement for local and non-local exit
|
||||||
|
- [x] Unified Delegation model: val, var and fun
|
||||||
|
- [x] `lazy val` using delegation
|
||||||
|
- [x] singletons `object TheOnly { ... }`
|
||||||
|
- [x] object expressions `object: List { ... }`
|
||||||
|
- [x] late-init vals in classes
|
||||||
|
- [x] properties with getters and setters
|
||||||
|
- [x] assign-if-null operator `?=`
|
||||||
|
|
||||||
|
All of this is documented in the [language site](https://lynglang.com) and locally [docs/language.md](docs/tutorial.md). the current nightly builds published on the site and in the private maven repository.
|
||||||
|
|
||||||
## plan: towards v1.5 Enhancing
|
## plan: towards v1.5 Enhancing
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Obsolete files
|
||||||
|
|
||||||
|
|
||||||
|
__Do not rely on contents of the files in this directory. They are kept for historical reference only and may not be up-to-date or relevant.__
|
||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,117 @@
|
|||||||
|
/*
|
||||||
|
This is a tech proposal under construction, please do not use it yet
|
||||||
|
for any purpose
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
Abstract delegate can be used to proxy read/wrtie field access
|
||||||
|
or method call. Default implementation reports error.
|
||||||
|
*/
|
||||||
|
interface Delegate {
|
||||||
|
fun getValue() = Unset
|
||||||
|
fun setValue(newValue) { throw NotImplementedException("delegate setter is not implemented") }
|
||||||
|
fun invoke(args...) { throw NotImplementedException("delegate setter is not implemented") }
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Delegate cam be used to implement a val, var or fun, so there are
|
||||||
|
access type enum to distinguish:
|
||||||
|
*/
|
||||||
|
enum DelegateAccess {
|
||||||
|
Val,
|
||||||
|
Var,
|
||||||
|
Callable
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delegate can be associated by a val/var/fun in a declaraion site using `by` keyword
|
||||||
|
|
||||||
|
val proxiedVal by proxy(1)
|
||||||
|
var proxiedVar by proxy(2, 3)
|
||||||
|
fun proxiedFun by proxy()
|
||||||
|
|
||||||
|
// each proxy is a Lyng expression returning instance of the Proxy interface:
|
||||||
|
|
||||||
|
/*
|
||||||
|
Proxy interface is connecting some named property of a given kind with the `Delegate`.
|
||||||
|
It removes the burden of dealing with property name and this ref on each get/set value
|
||||||
|
or invoke allowing having one delegate per instance, execution buff.
|
||||||
|
*/
|
||||||
|
interface Proxy {
|
||||||
|
fun getDelegate(propertyName: String,access: DelegateAccess,thisRef: Obj?): Delegate
|
||||||
|
}
|
||||||
|
|
||||||
|
// val, var and fun can be delegated, local or class instance:
|
||||||
|
class TestProxy: Proxy {
|
||||||
|
override getDelegate(name,access,thisRef) {
|
||||||
|
Delegate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val proxy = TestProxy()
|
||||||
|
|
||||||
|
class Allowed {
|
||||||
|
val v1 by proxy
|
||||||
|
var v2 by proxy
|
||||||
|
fun f1 by proxy
|
||||||
|
}
|
||||||
|
val v3 by proxy
|
||||||
|
var v4 by proxy
|
||||||
|
fun f2 by proxy
|
||||||
|
|
||||||
|
/*
|
||||||
|
It means that for example
|
||||||
|
Allowed().f1("foo")
|
||||||
|
would call a delegate.invoke("foo") on the `Delegate` instance supplied by `proxy`, etc.
|
||||||
|
*/
|
||||||
|
|
||||||
|
// The practic sample: lazy value
|
||||||
|
|
||||||
|
/*
|
||||||
|
The delegate that caches single time evaluated value
|
||||||
|
*/
|
||||||
|
class LazyDelegate(creator): Delegate {
|
||||||
|
private var currentValue=Unset
|
||||||
|
|
||||||
|
override fun getValue() {
|
||||||
|
if( currentValue == Unset )
|
||||||
|
currentValue = creator()
|
||||||
|
currentValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
The proxy to assign it
|
||||||
|
*/
|
||||||
|
class LazyProxy(creator) {
|
||||||
|
fun getDelegate(name,access,thisRef) {
|
||||||
|
if( access != DelegateAccess.Val )
|
||||||
|
throw IllegalArgumentException("only lazy val are allowed")
|
||||||
|
LazyDelegate(creator)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
A helper function to simplify creation:
|
||||||
|
*/
|
||||||
|
fun lazy(creator) {
|
||||||
|
LazyProxy(creator)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage sample and the test:
|
||||||
|
var callCounter = 0
|
||||||
|
assertEquals(0, clallCounter)
|
||||||
|
|
||||||
|
val lazyText by lazy { "evaluated text" }
|
||||||
|
|
||||||
|
// the lazy property is not yet evaluated:
|
||||||
|
assertEquals(0, clallCounter)
|
||||||
|
// now evaluate it by using it:
|
||||||
|
assertEquals("evaluated text", lazyText)
|
||||||
|
assertEquals(1, callCounter)
|
||||||
|
|
||||||
|
// lazy delegate should fail on vars or funs:
|
||||||
|
assertThrows { var bad by lazy { "should not happen" } }
|
||||||
|
assertThrows { fun bad by lazy { 42 } }
|
||||||
|
|
||||||
|
|
||||||
File renamed without changes.
File renamed without changes.
-41198
File diff suppressed because it is too large.
Load diff
+352
-15
@@ -42,6 +42,77 @@ a _constructor_ that requires two parameters for fields. So when creating it wit
|
|||||||
Form now on `Point` is a class, it's type is `Class`, and we can create instances with it as in the
|
Form now on `Point` is a class, it's type is `Class`, and we can create instances with it as in the
|
||||||
example above.
|
example above.
|
||||||
|
|
||||||
|
## Singleton Objects
|
||||||
|
|
||||||
|
Singleton objects are declared using the `object` keyword. An `object` declaration defines both a class and a single instance of that class at the same time. This is perfect for stateless utilities, global configuration, or shared delegates.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
object Config {
|
||||||
|
val version = "1.0.0"
|
||||||
|
val debug = true
|
||||||
|
|
||||||
|
fun printInfo() {
|
||||||
|
println("App version: " + version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage:
|
||||||
|
println(Config.version)
|
||||||
|
Config.printInfo()
|
||||||
|
```
|
||||||
|
|
||||||
|
Objects can also inherit from classes or interfaces:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
object DefaultLogger : Logger("Default") {
|
||||||
|
override fun log(msg) {
|
||||||
|
println("[DEFAULT] " + msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Object Expressions
|
||||||
|
|
||||||
|
Object expressions allow you to create an instance of an anonymous class. This is useful when you need to provide a one-off implementation of an interface or inherit from a class without declaring a new named subclass.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val worker = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
println("Working...")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Object expressions can implement multiple interfaces and inherit from one class:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val x = object : Base(arg1), Interface1, Interface2 {
|
||||||
|
val property = 42
|
||||||
|
override fun method() = property * 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Scoping and `this@object`
|
||||||
|
|
||||||
|
Object expressions capture their lexical scope, meaning they can access local variables and members of the outer class. When `this` is rebound (for example, inside an `apply` block), you can use the reserved alias `this@object` to refer to the innermost anonymous object instance.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val handler = object {
|
||||||
|
fun process() {
|
||||||
|
this@object.apply {
|
||||||
|
// here 'this' is rebound to the map/context
|
||||||
|
// but we can still access the anonymous object via this@object
|
||||||
|
println("Processing in " + this@object)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Serialization and Identity
|
||||||
|
|
||||||
|
- **Serialization**: Anonymous objects are **not serializable**. Attempting to encode an anonymous object via `Lynon` will throw a `SerializationException`. This is because their class definition is transient and cannot be safely restored in a different session or process.
|
||||||
|
- **Type Identity**: Every object expression creates a unique anonymous class. Two identical object expressions will result in two different classes with distinct type identities.
|
||||||
|
|
||||||
## Properties
|
## Properties
|
||||||
|
|
||||||
Properties allow you to define member accessors that look like fields but execute code when read or written. Unlike regular fields, properties in Lyng do **not** have automatic backing fields; they are pure accessors.
|
Properties allow you to define member accessors that look like fields but execute code when read or written. Unlike regular fields, properties in Lyng do **not** have automatic backing fields; they are pure accessors.
|
||||||
@@ -50,7 +121,7 @@ Properties allow you to define member accessors that look like fields but execut
|
|||||||
|
|
||||||
Properties are declared using `val` (read-only) or `var` (read-write) followed by a name and `get()`/`set()` blocks:
|
Properties are declared using `val` (read-only) or `var` (read-write) followed by a name and `get()`/`set()` blocks:
|
||||||
|
|
||||||
```kotlin
|
```lyng
|
||||||
class Person(private var _age: Int) {
|
class Person(private var _age: Int) {
|
||||||
// Read-only property
|
// Read-only property
|
||||||
val ageCategory
|
val ageCategory
|
||||||
@@ -76,7 +147,7 @@ assertEquals("Adult", p.ageCategory)
|
|||||||
|
|
||||||
For simple accessors and methods, you can use the `=` shorthand for a more elegant and laconic form:
|
For simple accessors and methods, you can use the `=` shorthand for a more elegant and laconic form:
|
||||||
|
|
||||||
```kotlin
|
```lyng
|
||||||
class Circle(val radius: Real) {
|
class Circle(val radius: Real) {
|
||||||
val area get() = π * radius * radius
|
val area get() = π * radius * radius
|
||||||
val circumference get() = 2 * π * radius
|
val circumference get() = 2 * π * radius
|
||||||
@@ -100,6 +171,61 @@ class Counter {
|
|||||||
- **No Backing Fields**: There is no magic `field` identifier. If you need to store state, you must declare a separate (usually `private`) field.
|
- **No Backing Fields**: There is no magic `field` identifier. If you need to store state, you must declare a separate (usually `private`) field.
|
||||||
- **Type Inference**: You can omit the type declaration if it can be inferred or if you don't need strict typing.
|
- **Type Inference**: You can omit the type declaration if it can be inferred or if you don't need strict typing.
|
||||||
|
|
||||||
|
### Lazy Properties with `cached`
|
||||||
|
|
||||||
|
When you want to define a property that is computed only once (on demand) and then remembered, use the built-in `cached` function. This is more efficient than a regular property with `get()` if the computation is expensive, as it avoids re-calculating the value on every access.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class DataService(val id: Int) {
|
||||||
|
// The lambda passed to cached is only executed once, the first time data() is called.
|
||||||
|
val data = cached {
|
||||||
|
println("Fetching data for " + id)
|
||||||
|
// Perform expensive operation
|
||||||
|
"Record " + id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val service = DataService(42)
|
||||||
|
// No printing yet
|
||||||
|
println(service.data()) // Prints "Fetching data for 42", then returns "Record 42"
|
||||||
|
println(service.data()) // Returns "Record 42" immediately (no second fetch)
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that `cached` returns a lambda, so you access the value by calling it like a method: `service.data()`. This is a powerful pattern for lazy-loading resources, caching results of database queries, or delaying expensive computations until they are truly needed.
|
||||||
|
|
||||||
|
## Delegation
|
||||||
|
|
||||||
|
Delegation allows you to hand over the logic of a property or function to another object. This is done using the `by` keyword.
|
||||||
|
|
||||||
|
### Property Delegation
|
||||||
|
|
||||||
|
Instead of providing `get()` and `set()` accessors, you can delegate them to an object that implements the `getValue` and `setValue` methods.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class User {
|
||||||
|
var name by MyDelegate()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Function Delegation
|
||||||
|
|
||||||
|
You can also delegate a whole function to an object. When the function is called, it will invoke the delegate's `invoke` method.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun remoteAction by RemoteProxy("actionName")
|
||||||
|
```
|
||||||
|
|
||||||
|
### The Unified Delegate Interface
|
||||||
|
|
||||||
|
A delegate is any object that provides the following methods (all optional depending on usage):
|
||||||
|
|
||||||
|
- `getValue(thisRef, name)`: Called when a delegated `val` or `var` is read.
|
||||||
|
- `setValue(thisRef, name, newValue)`: Called when a delegated `var` is written.
|
||||||
|
- `invoke(thisRef, name, args...)`: Called when a delegated `fun` is invoked.
|
||||||
|
- `bind(name, access, thisRef)`: Called once during initialization to configure or validate the delegate.
|
||||||
|
|
||||||
|
For more details and advanced patterns (like `lazy`, `observable`, and shared stateless delegates), see the [Delegation Guide](delegation.md).
|
||||||
|
|
||||||
## Instance initialization: init block
|
## Instance initialization: init block
|
||||||
|
|
||||||
In addition to the primary constructor arguments, you can provide an `init` block that runs on each instance creation. This is useful for more complex initializations, side effects, or setting up fields that depend on multiple constructor parameters.
|
In addition to the primary constructor arguments, you can provide an `init` block that runs on each instance creation. This is useful for more complex initializations, side effects, or setting up fields that depend on multiple constructor parameters.
|
||||||
@@ -153,6 +279,44 @@ statements discussed later, there could be default values, ellipsis, etc.
|
|||||||
|
|
||||||
Note that unlike **Kotlin**, which uses `=` for named arguments, Lyng uses `:` to avoid ambiguity with assignment expressions.
|
Note that unlike **Kotlin**, which uses `=` for named arguments, Lyng uses `:` to avoid ambiguity with assignment expressions.
|
||||||
|
|
||||||
|
### Late-initialized `val` fields
|
||||||
|
|
||||||
|
You can declare a `val` field without an immediate initializer if you provide an assignment for it within an `init` block or the class body. This is useful when the initial value depends on logic that cannot be expressed in a single expression.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class DataProcessor(data: Object) {
|
||||||
|
val result: Object
|
||||||
|
|
||||||
|
init {
|
||||||
|
// Complex initialization logic
|
||||||
|
result = transform(data)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Key rules for late-init `val`:
|
||||||
|
- **Compile-time Check**: The compiler ensures that every `val` declared without an initializer in a class body has at least one assignment within that class body (including `init` blocks). Failing to do so results in a syntax error.
|
||||||
|
- **Write-Once**: A `val` can only be assigned once. Even if it was declared without an initializer, once it is assigned a value (e.g., in `init`), any subsequent assignment will throw an `IllegalAssignmentException`.
|
||||||
|
- **Access before Initialization**: If you attempt to read a late-init `val` before it has been assigned (for example, by calling a method in `init` that reads the field before its assignment), it will hold a special `Unset` value. Using `Unset` for most operations (like arithmetic or method calls) will throw an `UnsetException`.
|
||||||
|
- **No Extensions**: Extension properties do not support late initialization as they do not have per-instance storage. Extension `val`s must always have an initializer or a `get()` accessor.
|
||||||
|
|
||||||
|
### The `Unset` singleton
|
||||||
|
|
||||||
|
The `Unset` singleton represents a field that has been declared but not yet initialized. While it can be compared and converted to a string, most other operations on it are forbidden to prevent accidental use of uninitialized data.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class T {
|
||||||
|
val x
|
||||||
|
fun check() {
|
||||||
|
if (x == Unset) println("Not ready")
|
||||||
|
}
|
||||||
|
init {
|
||||||
|
check() // Prints "Not ready"
|
||||||
|
x = 42
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Methods
|
## Methods
|
||||||
|
|
||||||
Functions defined inside a class body are methods, and unless declared
|
Functions defined inside a class body are methods, and unless declared
|
||||||
@@ -177,7 +341,7 @@ Functions defined inside a class body are methods, and unless declared
|
|||||||
|
|
||||||
Lyng supports declaring a class with multiple direct base classes. The syntax is:
|
Lyng supports declaring a class with multiple direct base classes. The syntax is:
|
||||||
|
|
||||||
```
|
```lyng
|
||||||
class Foo(val a) {
|
class Foo(val a) {
|
||||||
var tag = "F"
|
var tag = "F"
|
||||||
fun runA() { "ResultA:" + a }
|
fun runA() { "ResultA:" + a }
|
||||||
@@ -226,16 +390,16 @@ Key rules and features:
|
|||||||
|
|
||||||
- Syntax
|
- Syntax
|
||||||
- `class Derived(args) : Base1(b1Args), Base2(b2Args)`
|
- `class Derived(args) : Base1(b1Args), Base2(b2Args)`
|
||||||
- Each direct base may receive constructor arguments specified in the header. Only direct bases receive header args; indirect bases must either be default‑constructible or receive their args through their direct child (future extensions may add more control).
|
- Each direct base may receive constructor arguments specified in the header. Only direct bases receive header args; indirect bases must either be default‑constructible or receive their args through their direct child.
|
||||||
|
|
||||||
- Resolution order (C3 MRO — active)
|
- Resolution order (C3 MRO)
|
||||||
- Member lookup is deterministic and follows C3 linearization (Python‑like), which provides a monotonic, predictable order for complex hierarchies and diamonds.
|
- Member lookup is deterministic and follows C3 linearization (Python‑like), which provides a monotonic, predictable order for complex hierarchies and diamonds.
|
||||||
- Intuition: for `class D() : B(), C()` where `B()` and `C()` both derive from `A()`, the C3 order is `D → B → C → A`.
|
- Intuition: for `class D() : B(), C()` where `B()` and `C()` both derive from `A()`, the C3 order is `D → B → C → A`.
|
||||||
- The first visible match along this order wins.
|
- The first visible match along this order wins.
|
||||||
|
|
||||||
- Qualified dispatch
|
- Qualified dispatch
|
||||||
- Inside a class body, use `this@Type.member(...)` to start lookup at the specified ancestor.
|
- Inside a class body, use `this@Type.member(...)` to start lookup at the specified ancestor.
|
||||||
- For arbitrary receivers, use casts: `(expr as Type).member(...)` or `(expr as? Type)?.member(...)` (safe‑call `?.` is already available in Lyng).
|
- For arbitrary receivers, use casts: `(expr as Type).member(...)` or `(expr as? Type)?.member(...)`.
|
||||||
- Qualified access does not relax visibility.
|
- Qualified access does not relax visibility.
|
||||||
|
|
||||||
- Field inheritance (`val`/`var`) and collisions
|
- Field inheritance (`val`/`var`) and collisions
|
||||||
@@ -252,10 +416,120 @@ Key rules and features:
|
|||||||
- `private`: accessible only inside the declaring class body; not visible in subclasses and cannot be accessed via `this@Type` or casts.
|
- `private`: accessible only inside the declaring class body; not visible in subclasses and cannot be accessed via `this@Type` or casts.
|
||||||
- `protected`: accessible in the declaring class and in any of its transitive subclasses (including MI), but not from unrelated contexts; qualification/casts do not bypass it.
|
- `protected`: accessible in the declaring class and in any of its transitive subclasses (including MI), but not from unrelated contexts; qualification/casts do not bypass it.
|
||||||
|
|
||||||
- Diagnostics
|
## Abstract Classes and Members
|
||||||
- When a member/field is not found, error messages include the receiver class name and the considered linearization order, with suggestions to disambiguate using `this@Type` or casts if appropriate.
|
|
||||||
- Qualifying with a non‑ancestor in `this@Type` reports a clear error mentioning the receiver lineage.
|
An `abstract` class is a class that cannot be instantiated and is intended to be inherited by other classes. It can contain `abstract` members that have no implementation and must be implemented by concrete subclasses.
|
||||||
- `as`/`as?` cast errors mention the actual and target types.
|
|
||||||
|
### Abstract Classes
|
||||||
|
|
||||||
|
To declare an abstract class, use the `abstract` modifier:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
abstract class Shape {
|
||||||
|
abstract fun area(): Real
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Abstract classes can have constructors, fields, and concrete methods, just like regular classes.
|
||||||
|
|
||||||
|
### Abstract Members
|
||||||
|
|
||||||
|
Methods and variables (`val`/`var`) can be marked as `abstract`. Abstract members must not have a body or initializer.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
abstract class Base {
|
||||||
|
abstract fun foo(): Int
|
||||||
|
abstract var bar: String
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Safety**: `abstract` members cannot be `private`, as they must be visible to subclasses for implementation.
|
||||||
|
- **Contract of Capability**: An `abstract val/var` represents a requirement for a capability. It can be implemented by either a **field** (storage) or a **property** (logic) in a subclass.
|
||||||
|
|
||||||
|
## Interfaces
|
||||||
|
|
||||||
|
An `interface` in Lyng is a synonym for an `abstract class`. Following the principle that Lyng's Multiple Inheritance system is powerful enough to handle stateful contracts, interfaces support everything classes do, including constructors, fields, and `init` blocks.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
interface Named(val name: String) {
|
||||||
|
fun greet() { "Hello, " + name }
|
||||||
|
}
|
||||||
|
|
||||||
|
class Person(name) : Named(name)
|
||||||
|
```
|
||||||
|
|
||||||
|
Using `interface` instead of `abstract class` is a matter of semantic intent, signaling that the class is primarily intended to be used as a contract in MI.
|
||||||
|
|
||||||
|
### Implementation by Parts
|
||||||
|
|
||||||
|
One of the most powerful benefits of Lyng's Multiple Inheritance and C3 MRO is the ability to satisfy an interface's requirements "by parts" from different parent classes. Since an `interface` can have state and requirements, a subclass can inherit these requirements and satisfy them using members inherited from other parents in the MRO chain.
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
// Interface with state (id) and abstract requirements
|
||||||
|
interface Character(val id) {
|
||||||
|
var health
|
||||||
|
var mana
|
||||||
|
|
||||||
|
fun isAlive() = health > 0
|
||||||
|
fun status() = name + " (#" + id + "): " + health + " HP, " + mana + " MP"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parent class 1: provides health
|
||||||
|
class HealthPool(var health)
|
||||||
|
|
||||||
|
// Parent class 2: provides mana and name
|
||||||
|
class ManaPool(var mana) {
|
||||||
|
val name = "Hero"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Composite class: implements Character by combining HealthPool and ManaPool
|
||||||
|
class Warrior(id, h, m) : HealthPool(h), ManaPool(m), Character(id)
|
||||||
|
|
||||||
|
val w = Warrior(1, 100, 50)
|
||||||
|
assertEquals("Hero (#1): 100 HP, 50 MP", w.status())
|
||||||
|
```
|
||||||
|
|
||||||
|
In this example, `Warrior` inherits from `HealthPool`, `ManaPool`, and `Character`. The abstract requirements `health` and `mana` from `Character` are automatically satisfied by the matching members inherited from `HealthPool` and `ManaPool`. The `status()` method also successfully finds the `name` field from `ManaPool`. This pattern allows for highly modular and reusable "trait-like" classes that can be combined to fulfill complex contracts without boilerplate proxy methods.
|
||||||
|
|
||||||
|
## Overriding and Virtual Dispatch
|
||||||
|
|
||||||
|
When a class defines a member that already exists in one of its parents, it is called **overriding**.
|
||||||
|
|
||||||
|
### The `override` Keyword
|
||||||
|
|
||||||
|
In Lyng, the `override` keyword is **mandatory when declaring a member** that exists in the ancestor chain (MRO).
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Parent {
|
||||||
|
fun foo() = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
class Child : Parent() {
|
||||||
|
override fun foo() = 2 // Mandatory override keyword
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Implicit Satisfaction**: If a class inherits an abstract requirement and a matching implementation from different parents, the requirement is satisfied automatically without needing an explicit `override` proxy.
|
||||||
|
- **No Accidental Overrides**: If you define a member that happens to match a parent's member but you didn't use `override`, the compiler will throw an error. This prevents the "Fragile Base Class" problem.
|
||||||
|
- **Private Members**: Private members in parent classes are NOT part of the virtual interface and cannot be overridden. Defining a member with the same name in a subclass is allowed without `override` and is treated as a new, independent member.
|
||||||
|
|
||||||
|
### Visibility Widening
|
||||||
|
|
||||||
|
A subclass can increase the visibility of an overridden member (e.g., `protected` → `public`), but it is strictly forbidden from narrowing it (e.g., `public` → `protected`).
|
||||||
|
|
||||||
|
### The `closed` Modifier
|
||||||
|
|
||||||
|
To prevent a member from being overridden in subclasses, use the `closed` modifier (equivalent to `final` in other languages).
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Critical {
|
||||||
|
closed fun secureStep() { ... }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Attempting to override a `closed` member results in a compile-time error.
|
||||||
|
|
||||||
Compatibility notes:
|
Compatibility notes:
|
||||||
|
|
||||||
@@ -372,6 +646,69 @@ Are declared with var
|
|||||||
assert( p.isSpecial == true )
|
assert( p.isSpecial == true )
|
||||||
>>> void
|
>>> void
|
||||||
|
|
||||||
|
### Restricted Setter Visibility
|
||||||
|
|
||||||
|
You can restrict the visibility of a `var` field's or property's setter by using `private set` or `protected set` modifiers. This allows the member to be publicly readable but only writable from within the class or its subclasses.
|
||||||
|
|
||||||
|
#### On Fields
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class SecretCounter {
|
||||||
|
var count = 0
|
||||||
|
private set // Can be read anywhere, but written only in SecretCounter
|
||||||
|
|
||||||
|
fun increment() { count++ }
|
||||||
|
}
|
||||||
|
|
||||||
|
val c = SecretCounter()
|
||||||
|
println(c.count) // OK
|
||||||
|
c.count = 10 // Throws IllegalAccessException
|
||||||
|
c.increment() // OK
|
||||||
|
```
|
||||||
|
|
||||||
|
#### On Properties
|
||||||
|
|
||||||
|
You can also apply restricted visibility to custom property setters:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Person(private var _age: Int) {
|
||||||
|
var age
|
||||||
|
get() = _age
|
||||||
|
private set(v) { if (v >= 0) _age = v }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Protected Setters and Inheritance
|
||||||
|
|
||||||
|
A `protected set` allows subclasses to modify a field that is otherwise read-only to the public:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Base {
|
||||||
|
var state = "initial"
|
||||||
|
protected set
|
||||||
|
}
|
||||||
|
|
||||||
|
class Derived : Base() {
|
||||||
|
fun changeState(newVal) {
|
||||||
|
state = newVal // OK: protected access from subclass
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val d = Derived()
|
||||||
|
println(d.state) // OK: "initial"
|
||||||
|
d.changeState("updated")
|
||||||
|
println(d.state) // OK: "updated"
|
||||||
|
d.state = "bad" // Throws IllegalAccessException: public write not allowed
|
||||||
|
```
|
||||||
|
|
||||||
|
### Key Rules and Limitations
|
||||||
|
|
||||||
|
- **Only for `var`**: Restricted setter visibility cannot be used with `val` declarations, as they are inherently read-only. Attempting to use it with `val` results in a syntax error.
|
||||||
|
- **Class Body Only**: These modifiers can only be used on members declared within the class body. They are not supported for primary constructor parameters.
|
||||||
|
- **`private set`**: The setter is only accessible within the same class context (specifically, when `this` is an instance of that class).
|
||||||
|
- **`protected set`**: The setter is accessible within the declaring class and all its transitive subclasses.
|
||||||
|
- **Multiple Inheritance**: In MI scenarios, visibility is checked against the class that actually declared the member. Qualified access (e.g., `this@Base.field = value`) also respects restricted setter visibility.
|
||||||
|
|
||||||
### Private fields
|
### Private fields
|
||||||
|
|
||||||
Private fields are visible only _inside the class instance_:
|
Private fields are visible only _inside the class instance_:
|
||||||
@@ -528,7 +865,7 @@ Just like methods, you can extend existing classes with properties. These can be
|
|||||||
|
|
||||||
A read-only extension can be defined by assigning an expression:
|
A read-only extension can be defined by assigning an expression:
|
||||||
|
|
||||||
```kotlin
|
```lyng
|
||||||
val String.isLong = length > 10
|
val String.isLong = length > 10
|
||||||
|
|
||||||
val s = "Hello, world!"
|
val s = "Hello, world!"
|
||||||
@@ -539,7 +876,7 @@ assert(s.isLong)
|
|||||||
|
|
||||||
For more complex logic, use `get()` and `set()` blocks:
|
For more complex logic, use `get()` and `set()` blocks:
|
||||||
|
|
||||||
```kotlin
|
```lyng
|
||||||
class Box(var value: Int)
|
class Box(var value: Int)
|
||||||
|
|
||||||
var Box.doubledValue
|
var Box.doubledValue
|
||||||
@@ -562,7 +899,7 @@ Extensions in Lyng are **scope-isolated**. This means an extension is only visib
|
|||||||
|
|
||||||
You can define different extensions with the same name in different scopes:
|
You can define different extensions with the same name in different scopes:
|
||||||
|
|
||||||
```kotlin
|
```lyng
|
||||||
fun scopeA() {
|
fun scopeA() {
|
||||||
val Int.description = "Number: " + toString()
|
val Int.description = "Number: " + toString()
|
||||||
assertEquals("Number: 42", 42.description)
|
assertEquals("Number: 42", 42.description)
|
||||||
@@ -699,12 +1036,12 @@ request](https://gitea.sergeych.net/SergeychWorks/lyng/issues).
|
|||||||
- ObjClass sole parent is Obj
|
- ObjClass sole parent is Obj
|
||||||
- ObjClass contains code for instance methods, class fields, hierarchy information.
|
- ObjClass contains code for instance methods, class fields, hierarchy information.
|
||||||
- Class information is also scoped.
|
- Class information is also scoped.
|
||||||
- We acoid imported classes duplication using packages and import caching, so the same imported module is the same object in all its classes.
|
- We avoid imported classes duplication using packages and import caching, so the same imported module is the same object in all its classes.
|
||||||
|
|
||||||
## Instances
|
## Instances
|
||||||
|
|
||||||
Result of executing of any expression or statement in the Lyng is the object that
|
Result of executing of any expression or statement in the Lyng is the object that
|
||||||
inherits `Obj`, but is not `Obj`. For example it could be Int, void, null, real, string, bool, etc.
|
inherits `Obj`, but is not `Obj`. For example, it could be Int, void, null, real, string, bool, etc.
|
||||||
|
|
||||||
This means whatever expression returns or the variable holds, is the first-class
|
This means whatever expression returns or the variable holds, is the first-class
|
||||||
object, no differenes. For example:
|
object, no differenes. For example:
|
||||||
|
|||||||
+14
-2
@@ -93,8 +93,6 @@ If we want to evaluate the message lazily:
|
|||||||
|
|
||||||
In this case, formatting will only occur if the condition is not met.
|
In this case, formatting will only occur if the condition is not met.
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### `check`
|
### `check`
|
||||||
|
|
||||||
check(condition, message="check failed")
|
check(condition, message="check failed")
|
||||||
@@ -107,3 +105,17 @@ With lazy message evaluation:
|
|||||||
|
|
||||||
In this case, formatting will only occur if the condition is not met.
|
In this case, formatting will only occur if the condition is not met.
|
||||||
|
|
||||||
|
### TODO
|
||||||
|
|
||||||
|
It is easy to mark some code and make it throw a special exception at cone with:
|
||||||
|
|
||||||
|
TODO()
|
||||||
|
|
||||||
|
or
|
||||||
|
|
||||||
|
TODO("some message")
|
||||||
|
|
||||||
|
It raises an `NotImplementedException` with the given message. You can catch it
|
||||||
|
as any other exception when necessary.
|
||||||
|
|
||||||
|
Many IDE and editors have built-in support for marking code with TODOs.
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
# Delegation in Lyng
|
||||||
|
|
||||||
|
Delegation is a powerful pattern that allows you to outsource the logic of properties (`val`, `var`) and functions (`fun`) to another object. This enables code reuse, separation of concerns, and the implementation of common patterns like lazy initialization, observable properties, and remote procedure calls (RPC) with minimal boilerplate.
|
||||||
|
|
||||||
|
## The `by` Keyword
|
||||||
|
|
||||||
|
Delegation is triggered using the `by` keyword in a declaration. The expression following `by` is evaluated once when the member is initialized, and the resulting object becomes the **delegate**.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val x by MyDelegate()
|
||||||
|
var y by MyDelegate()
|
||||||
|
fun f by MyDelegate()
|
||||||
|
```
|
||||||
|
|
||||||
|
## The Unified Delegate Model
|
||||||
|
|
||||||
|
A delegate object can implement any of the following methods to intercept member access. All methods receive the `thisRef` (the instance containing the member) and the `name` of the member.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
interface Delegate {
|
||||||
|
// Called when a 'val' or 'var' is read
|
||||||
|
fun getValue(thisRef, name)
|
||||||
|
|
||||||
|
// Called when a 'var' is assigned
|
||||||
|
fun setValue(thisRef, name, newValue)
|
||||||
|
|
||||||
|
// Called when a 'fun' is invoked
|
||||||
|
fun invoke(thisRef, name, args...)
|
||||||
|
|
||||||
|
// Optional: Called once during initialization to "bind" the delegate
|
||||||
|
// Can be used for validation or to return a different delegate instance
|
||||||
|
fun bind(name, access, thisRef) = this
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Delegate Access Types
|
||||||
|
|
||||||
|
The `bind` method receives an `access` parameter of type `DelegateAccess`, which can be one of:
|
||||||
|
- `DelegateAccess.Val`
|
||||||
|
- `DelegateAccess.Var`
|
||||||
|
- `DelegateAccess.Callable` (for `fun`)
|
||||||
|
|
||||||
|
## Usage Cases and Examples
|
||||||
|
|
||||||
|
### 1. Lazy Initialization
|
||||||
|
|
||||||
|
The classic `lazy` pattern ensures a value is computed only when first accessed and then cached. In Lyng, `lazy` is implemented as a class that follows this pattern. While classes typically start with an uppercase letter, `lazy` is an exception to make its usage feel like a native language feature.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class lazy(val creator) : Delegate {
|
||||||
|
private var value = Unset
|
||||||
|
|
||||||
|
override fun bind(name, access, thisRef) {
|
||||||
|
if (access != DelegateAccess.Val) throw "lazy delegate can only be used with 'val'"
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getValue(thisRef, name) {
|
||||||
|
if (value == Unset) {
|
||||||
|
// calculate value using thisRef as this:
|
||||||
|
value = with(thisRef) creator()
|
||||||
|
}
|
||||||
|
value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usage:
|
||||||
|
val expensiveData by lazy {
|
||||||
|
println("Performing expensive computation...")
|
||||||
|
42
|
||||||
|
}
|
||||||
|
|
||||||
|
println(expensiveData) // Computes and prints 42
|
||||||
|
println(expensiveData) // Returns 42 immediately
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Observable Properties
|
||||||
|
|
||||||
|
Delegates can be used to react to property changes.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Observable(initialValue, val onChange) {
|
||||||
|
private var value = initialValue
|
||||||
|
|
||||||
|
fun getValue(thisRef, name) = value
|
||||||
|
|
||||||
|
fun setValue(thisRef, name, newValue) {
|
||||||
|
val oldValue = value
|
||||||
|
value = newValue
|
||||||
|
onChange(name, oldValue, newValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class User {
|
||||||
|
var name by Observable("Guest") { name, old, new ->
|
||||||
|
println("Property %s changed from %s to %s"(name, old, new))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val u = User()
|
||||||
|
u.name = "Alice" // Prints: Property name changed from Guest to Alice
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. Function Delegation (Proxies)
|
||||||
|
|
||||||
|
You can delegate an entire function to an object. This is particularly useful for implementing decorators or RPC clients.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
object LoggerDelegate {
|
||||||
|
fun invoke(thisRef, name, args...) {
|
||||||
|
println("Calling function: " + name + " with args: " + args)
|
||||||
|
// Logic here...
|
||||||
|
"Result of " + name
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun remoteAction by LoggerDelegate
|
||||||
|
|
||||||
|
println(remoteAction(1, 2, 3))
|
||||||
|
// Prints: Calling function: remoteAction with args: [1, 2, 3]
|
||||||
|
// Prints: Result of remoteAction
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Stateless Delegates (Shared Singletons)
|
||||||
|
|
||||||
|
Because `getValue`, `setValue`, and `invoke` receive `thisRef`, a single object can act as a delegate for multiple properties across many instances without any per-property memory overhead.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
object Constant42 {
|
||||||
|
fun getValue(thisRef, name) = 42
|
||||||
|
}
|
||||||
|
|
||||||
|
class Foo {
|
||||||
|
val a by Constant42
|
||||||
|
val b by Constant42
|
||||||
|
}
|
||||||
|
|
||||||
|
val f = Foo()
|
||||||
|
assertEquals(42, f.a)
|
||||||
|
assertEquals(42, f.b)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. Local Delegation
|
||||||
|
|
||||||
|
Delegation is not limited to class members; you can also use it for local variables inside functions.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun test() {
|
||||||
|
val x by LocalProxy(123)
|
||||||
|
println(x)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## The `bind` Hook
|
||||||
|
|
||||||
|
The `bind(name, access, thisRef)` method is called exactly once when the member is being initialized. It allows the delegate to:
|
||||||
|
1. **Validate usage**: Throw an error if the delegate is used with the wrong member type (e.g., `lazy` on a `var`).
|
||||||
|
2. **Initialize state**: Set up internal state based on the property name or the containing instance.
|
||||||
|
3. **Substitute itself**: Return a different object that will act as the actual delegate.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class ValidatedDelegate() {
|
||||||
|
fun bind(name, access, thisRef) {
|
||||||
|
if (access == DelegateAccess.Var) {
|
||||||
|
throw "This delegate cannot be used with 'var'"
|
||||||
|
}
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getValue(thisRef, name) = "Validated"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Delegation in Lyng combines the elegance of Kotlin-style properties with the flexibility of dynamic function interception. By unifying `val`, `var`, and `fun` delegation into a single model, Lyng provides a consistent and powerful tool for meta-programming and code reuse.
|
||||||
@@ -136,7 +136,7 @@ Serializable class that conveys information about the exception. Important membe
|
|||||||
|
|
||||||
A simple structire that stores single entry in Lyng stack, it is created automatically on exception creation:
|
A simple structire that stores single entry in Lyng stack, it is created automatically on exception creation:
|
||||||
|
|
||||||
```kotlin
|
```lyng
|
||||||
class StackTraceEntry(
|
class StackTraceEntry(
|
||||||
val sourceName: String,
|
val sourceName: String,
|
||||||
val line: Int,
|
val line: Int,
|
||||||
@@ -165,7 +165,7 @@ _this functionality is not yet released_
|
|||||||
| IllegalAssignmentException | assigning to val, etc. |
|
| IllegalAssignmentException | assigning to val, etc. |
|
||||||
| SymbolNotDefinedException | |
|
| SymbolNotDefinedException | |
|
||||||
| IterationEndException | attempt to read iterator past end, `hasNext == false` |
|
| IterationEndException | attempt to read iterator past end, `hasNext == false` |
|
||||||
| AccessException | attempt to access private members or like |
|
| IllegalAccessException | attempt to access private members or like |
|
||||||
| UnknownException | unexpected kotlin exception caught |
|
| UnknownException | unexpected kotlin exception caught |
|
||||||
| | |
|
| | |
|
||||||
|
|
||||||
|
|||||||
+7
-3
@@ -8,7 +8,7 @@ This module provides a uniform, suspend-first filesystem API to Lyng scripts, ba
|
|||||||
|
|
||||||
It exposes a Lyng class `Path` with methods for file and directory operations, including streaming readers for large files.
|
It exposes a Lyng class `Path` with methods for file and directory operations, including streaming readers for large files.
|
||||||
|
|
||||||
It is a separate library because access to teh filesystem is a security risk we compensate with a separate API that user must explicitly include to the dependency and allow. Together with `FsAceessPolicy` that is required to `createFs()` which actually adds the filesystem to the scope, the security risk is isolated.
|
It is a separate library because access to the filesystem is a security risk we compensate with a separate API that user must explicitly include to the dependency and allow. Together with `FsAccessPolicy` that is required to `createFs()` which actually adds the filesystem to the scope, the security risk is isolated.
|
||||||
|
|
||||||
Also, it helps keep Lyng core small and focused.
|
Also, it helps keep Lyng core small and focused.
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ dependencies {
|
|||||||
implementation("net.sergeych:lyngio:0.0.1-SNAPSHOT")
|
implementation("net.sergeych:lyngio:0.0.1-SNAPSHOT")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
Note on maven repository. Lyngio uses ths same maven as Lyng code (`lynglib`) so it is most likely already in your project. If ont, add it to the proper section of your `build.gradle.kts` or settings.gradle.kts:
|
Note on maven repository. Lyngio uses the same maven as Lyng code (`lynglib`) so it is most likely already in your project. If not, add it to the proper section of your `build.gradle.kts` or settings.gradle.kts:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
repositories {
|
repositories {
|
||||||
@@ -43,9 +43,13 @@ This brings in:
|
|||||||
|
|
||||||
The filesystem module is not installed automatically. You must explicitly register it in the scope’s `ImportManager` using the installer. You can customize access control via `FsAccessPolicy`.
|
The filesystem module is not installed automatically. You must explicitly register it in the scope’s `ImportManager` using the installer. You can customize access control via `FsAccessPolicy`.
|
||||||
|
|
||||||
Kotlin (host) bootstrap example (imports omitted for brevity):
|
Kotlin (host) bootstrap example:
|
||||||
|
|
||||||
```kotlin
|
```kotlin
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.io.fs.createFs
|
||||||
|
import net.sergeych.lyngio.fs.security.PermitAllAccessPolicy
|
||||||
|
|
||||||
val scope: Scope = Scope.new()
|
val scope: Scope = Scope.new()
|
||||||
val installed: Boolean = createFs(PermitAllAccessPolicy, scope)
|
val installed: Boolean = createFs(PermitAllAccessPolicy, scope)
|
||||||
// installed == true on first registration in this ImportManager, false on repeats
|
// installed == true on first registration in this ImportManager, false on repeats
|
||||||
|
|||||||
@@ -0,0 +1,136 @@
|
|||||||
|
### lyng.io.process — Process execution and control for Lyng scripts
|
||||||
|
|
||||||
|
This module provides a way to run external processes and shell commands from Lyng scripts. It is designed to be multiplatform and uses coroutines for non-blocking execution.
|
||||||
|
|
||||||
|
> **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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Add the library to your project (Gradle)
|
||||||
|
|
||||||
|
If you use this repository as a multi-module project, add a dependency on `:lyngio`:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
dependencies {
|
||||||
|
implementation("net.sergeych:lyngio:0.0.1-SNAPSHOT")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For external projects, ensure you have the appropriate Maven repository configured (see `lyng.io.fs` documentation).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Install the module into a Lyng Scope
|
||||||
|
|
||||||
|
The process module is not installed automatically. You must explicitly register it in the scope’s `ImportManager` using `createProcessModule`. You can customize access control via `ProcessAccessPolicy`.
|
||||||
|
|
||||||
|
Kotlin (host) bootstrap example:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.Script
|
||||||
|
import net.sergeych.lyng.io.process.createProcessModule
|
||||||
|
import net.sergeych.lyngio.process.security.PermitAllProcessAccessPolicy
|
||||||
|
|
||||||
|
// ... inside a suspend function or runBlocking
|
||||||
|
val scope: Scope = Script.newScope()
|
||||||
|
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||||
|
|
||||||
|
// In scripts (or via scope.eval), import the module:
|
||||||
|
scope.eval("import lyng.io.process")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Using from Lyng scripts
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
import lyng.io.process
|
||||||
|
|
||||||
|
// Execute a process with arguments
|
||||||
|
val p = Process.execute("ls", ["-l", "/tmp"])
|
||||||
|
for (line in p.stdout) {
|
||||||
|
println("OUT: " + line)
|
||||||
|
}
|
||||||
|
val exitCode = p.waitFor()
|
||||||
|
println("Process exited with: " + exitCode)
|
||||||
|
|
||||||
|
// Run a shell command
|
||||||
|
val sh = Process.shell("echo 'Hello from shell' | wc -w")
|
||||||
|
for (line in sh.stdout) {
|
||||||
|
println("Word count: " + line.trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Platform information
|
||||||
|
val details = Platform.details()
|
||||||
|
println("OS: " + details.name + " " + details.version + " (" + details.arch + ")")
|
||||||
|
if (details.kernelVersion != null) {
|
||||||
|
println("Kernel: " + details.kernelVersion)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Platform.isSupported()) {
|
||||||
|
println("Processes are supported!")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### API Reference
|
||||||
|
|
||||||
|
##### `Process` (static methods)
|
||||||
|
- `execute(executable: String, args: List<String>): RunningProcess` — Start an external process.
|
||||||
|
- `shell(command: String): RunningProcess` — Run a command through the system shell (e.g., `/bin/sh` or `cmd.exe`).
|
||||||
|
|
||||||
|
##### `RunningProcess` (instance methods)
|
||||||
|
- `stdout: Flow` — Standard output stream as a Lyng Flow of lines.
|
||||||
|
- `stderr: Flow` — Standard error stream as a Lyng Flow of lines.
|
||||||
|
- `waitFor(): Int` — Wait for the process to exit and return the exit code.
|
||||||
|
- `signal(name: String)` — Send a signal to the process (e.g., `"SIGINT"`, `"SIGTERM"`, `"SIGKILL"`).
|
||||||
|
- `destroy()` — Forcefully terminate the process.
|
||||||
|
|
||||||
|
##### `Platform` (static methods)
|
||||||
|
- `details(): Map` — Get platform details. Returned map keys: `name`, `version`, `arch`, `kernelVersion`.
|
||||||
|
- `isSupported(): Bool` — True if process execution is supported on the current platform.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Security Policy
|
||||||
|
|
||||||
|
Process execution is a sensitive operation. `lyngio` uses `ProcessAccessPolicy` to control access to `execute` and `shell` operations.
|
||||||
|
|
||||||
|
- `ProcessAccessPolicy` — Interface for custom policies.
|
||||||
|
- `PermitAllProcessAccessPolicy` — Allows all operations.
|
||||||
|
- `ProcessAccessOp` (sealed) — Operations to check:
|
||||||
|
- `Execute(executable, args)`
|
||||||
|
- `Shell(command)`
|
||||||
|
|
||||||
|
Example of a restricted policy in Kotlin:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
import net.sergeych.lyngio.fs.security.AccessDecision
|
||||||
|
import net.sergeych.lyngio.fs.security.Decision
|
||||||
|
import net.sergeych.lyngio.process.security.ProcessAccessOp
|
||||||
|
import net.sergeych.lyngio.process.security.ProcessAccessPolicy
|
||||||
|
|
||||||
|
val restrictedPolicy = object : ProcessAccessPolicy {
|
||||||
|
override suspend fun check(op: ProcessAccessOp, ctx: AccessContext): AccessDecision {
|
||||||
|
return when (op) {
|
||||||
|
is ProcessAccessOp.Execute -> {
|
||||||
|
if (op.executable == "ls") AccessDecision(Decision.Allow)
|
||||||
|
else AccessDecision(Decision.Deny, "Only 'ls' is allowed")
|
||||||
|
}
|
||||||
|
is ProcessAccessOp.Shell -> AccessDecision(Decision.Deny, "Shell is forbidden")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
createProcessModule(restrictedPolicy, scope)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Platform Support
|
||||||
|
|
||||||
|
- **JVM:** Full support using `ProcessBuilder`.
|
||||||
|
- **Native (Linux/macOS):** Support via POSIX.
|
||||||
|
- **Windows:** Support planned.
|
||||||
|
- **Android/JS/iOS/Wasm:** Currently not supported; `isSupported()` returns `false` and attempts to run processes will throw `UnsupportedOperationException`.
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
### lyngio — Extended I/O and System Library for Lyng
|
||||||
|
|
||||||
|
`lyngio` is a separate library that extends the Lyng core (`lynglib`) with powerful, multiplatform, and secure I/O capabilities.
|
||||||
|
|
||||||
|
#### Why a separate module?
|
||||||
|
|
||||||
|
1. **Security:** I/O and process execution are sensitive operations. By keeping them in a separate module, we ensure that the Lyng core remains 100% safe by default. You only enable what you explicitly need.
|
||||||
|
2. **Footprint:** Not every script needs filesystem or process access. Keeping these as a separate module helps minimize the dependency footprint for small embedded projects.
|
||||||
|
3. **Control:** `lyngio` provides fine-grained security policies (`FsAccessPolicy`, `ProcessAccessPolicy`) that allow you to control exactly what a script can do.
|
||||||
|
|
||||||
|
#### Included Modules
|
||||||
|
|
||||||
|
- **[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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Quick Start: Embedding lyngio
|
||||||
|
|
||||||
|
##### 1. Add Dependencies (Gradle)
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
repositories {
|
||||||
|
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// Both are required for full I/O support
|
||||||
|
implementation("net.sergeych:lynglib:0.0.1-SNAPSHOT")
|
||||||
|
implementation("net.sergeych:lyngio:0.0.1-SNAPSHOT")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
##### 2. Initialize in Kotlin (JVM or Native)
|
||||||
|
|
||||||
|
To use `lyngio` modules in your scripts, you must install them into your Lyng scope and provide a security policy.
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
import net.sergeych.lyng.Script
|
||||||
|
import net.sergeych.lyng.io.fs.createFs
|
||||||
|
import net.sergeych.lyng.io.process.createProcessModule
|
||||||
|
import net.sergeych.lyngio.fs.security.PermitAllAccessPolicy
|
||||||
|
import net.sergeych.lyngio.process.security.PermitAllProcessAccessPolicy
|
||||||
|
|
||||||
|
suspend fun runMyScript() {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
|
||||||
|
// Install modules with policies
|
||||||
|
createFs(PermitAllAccessPolicy, scope)
|
||||||
|
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||||
|
|
||||||
|
// Now scripts can import them
|
||||||
|
scope.eval("""
|
||||||
|
import lyng.io.fs
|
||||||
|
import lyng.io.process
|
||||||
|
|
||||||
|
println("Working dir: " + Path(".").readUtf8())
|
||||||
|
println("OS: " + Platform.details().name)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Security Tools
|
||||||
|
|
||||||
|
`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).
|
||||||
|
- **Process Security:** Implement `ProcessAccessPolicy` to restrict which executables can be run or to disable shell execution entirely.
|
||||||
|
|
||||||
|
For more details, see the specific module documentation:
|
||||||
|
- [Filesystem Security Details](lyng.io.fs.md#access-policy-security)
|
||||||
|
- [Process Security Details](lyng.io.process.md#security-policy)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
#### Platform Support Overview
|
||||||
|
|
||||||
|
| Platform | lyng.io.fs | lyng.io.process |
|
||||||
|
| :--- | :---: | :---: |
|
||||||
|
| **JVM** | ✅ | ✅ |
|
||||||
|
| **Native (Linux/macOS)** | ✅ | ✅ |
|
||||||
|
| **Native (Windows)** | ✅ | 🚧 (Planned) |
|
||||||
|
| **Android** | ✅ | ❌ |
|
||||||
|
| **NodeJS** | ✅ | ❌ |
|
||||||
|
| **Browser / Wasm** | ✅ (In-memory) | ❌ |
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# The `return` statement
|
||||||
|
|
||||||
|
The `return` statement is used to terminate the execution of the innermost enclosing callable (a function or a lambda) and optionally return a value to the caller.
|
||||||
|
|
||||||
|
## Basic Usage
|
||||||
|
|
||||||
|
By default, Lyng functions and blocks return the value of their last expression. However, `return` allows you to exit early, which is particularly useful for guard clauses.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun divide(a, b) {
|
||||||
|
if (b == 0) return null // Guard clause: early exit
|
||||||
|
a / b
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If no expression is provided, `return` returns `void`:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun logIfDebug(msg) {
|
||||||
|
if (!DEBUG) return
|
||||||
|
println("[DEBUG] " + msg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Scoping Rules
|
||||||
|
|
||||||
|
In Lyng, `return` always exits the **innermost enclosing callable**. Callables include:
|
||||||
|
* Named functions (`fun` or `fn`)
|
||||||
|
* Anonymous functions/lambdas (`{ ... }`)
|
||||||
|
|
||||||
|
Standard control flow blocks like `if`, `while`, `do`, and `for` are **not** callables; `return` inside these blocks will return from the function or lambda that contains them.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun findFirstPositive(list) {
|
||||||
|
list.forEach {
|
||||||
|
if (it > 0) return it // ERROR: This returns from the lambda, not findFirstPositive!
|
||||||
|
}
|
||||||
|
null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
*Note: To return from an outer scope, use [Non-local Returns](#non-local-returns).*
|
||||||
|
|
||||||
|
## Non-local Returns
|
||||||
|
|
||||||
|
Lyng supports returning from outer scopes using labels. This is a powerful feature for a closure-intensive language.
|
||||||
|
|
||||||
|
### Named Functions as Labels
|
||||||
|
Every named function automatically provides its name as a label.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun findFirstPositive(list) {
|
||||||
|
list.forEach {
|
||||||
|
if (it > 0) return@findFirstPositive it // Returns from findFirstPositive
|
||||||
|
}
|
||||||
|
null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Labeled Lambdas
|
||||||
|
You can explicitly label a lambda using the `@label` syntax to return from it specifically when nested.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val process = @outer { x ->
|
||||||
|
val result = {
|
||||||
|
if (x < 0) return@outer "negative" // Returns from the outer lambda
|
||||||
|
x * 2
|
||||||
|
}()
|
||||||
|
"Result: " + result
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Restriction on Shorthand Functions
|
||||||
|
|
||||||
|
To maintain Lyng's clean, expression-oriented style, the `return` keyword is **forbidden** in shorthand function definitions (those using `=`).
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun square(x) = x * x // Correct
|
||||||
|
fun square(x) = return x * x // Syntax Error: 'return' not allowed here
|
||||||
|
```
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
* `return [expression]` exits the innermost `fun` or `{}`.
|
||||||
|
* Use `return@label` for non-local returns.
|
||||||
|
* Named functions provide automatic labels.
|
||||||
|
* Cannot be used in `=` shorthand functions.
|
||||||
|
* Consistency: Mirrors the syntax and behavior of `break@label expression`.
|
||||||
@@ -68,6 +68,26 @@ Tip: If a closure unexpectedly cannot see an outer local, check whether an inter
|
|||||||
- The `visited` sets used for cycle detection are tiny and short‑lived; in typical scripts the overhead is negligible.
|
- The `visited` sets used for cycle detection are tiny and short‑lived; in typical scripts the overhead is negligible.
|
||||||
- If profiling shows hotspots, consider limiting ancestry depth in your custom helpers or using small fixed arrays instead of hash sets—only for extremely hot code paths.
|
- If profiling shows hotspots, consider limiting ancestry depth in your custom helpers or using small fixed arrays instead of hash sets—only for extremely hot code paths.
|
||||||
|
|
||||||
|
## Practical Example: `cached`
|
||||||
|
|
||||||
|
The `cached` function (defined in `lyng.stdlib`) is a classic example of using closures to maintain state. It wraps a builder into a zero-argument function that computes once and remembers the result:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun cached(builder) {
|
||||||
|
var calculated = false
|
||||||
|
var value = null
|
||||||
|
{ // This lambda captures `calculated`, `value`, and `builder`
|
||||||
|
if( !calculated ) {
|
||||||
|
value = builder()
|
||||||
|
calculated = true
|
||||||
|
}
|
||||||
|
value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Because Lyng now correctly isolates closures for each evaluation of a lambda literal, using `cached` inside a class instance works as expected: each instance maintains its own private `calculated` and `value` state, even if they share the same property declaration.
|
||||||
|
|
||||||
## Dos and Don’ts
|
## Dos and Don’ts
|
||||||
- Do use `chainLookupIgnoreClosure` / `chainLookupWithMembers` for ancestry traversals.
|
- Do use `chainLookupIgnoreClosure` / `chainLookupWithMembers` for ancestry traversals.
|
||||||
- Do maintain the resolution order above for predictable behavior.
|
- Do maintain the resolution order above for predictable behavior.
|
||||||
|
|||||||
+101
-11
@@ -8,7 +8,7 @@ __Other documents to read__ maybe after this one:
|
|||||||
|
|
||||||
- [Advanced topics](advanced_topics.md), [declaring arguments](declaring_arguments.md), [Scopes and Closures](scopes_and_closures.md)
|
- [Advanced topics](advanced_topics.md), [declaring arguments](declaring_arguments.md), [Scopes and Closures](scopes_and_closures.md)
|
||||||
- [OOP notes](OOP.md), [exception handling](exceptions_handling.md)
|
- [OOP notes](OOP.md), [exception handling](exceptions_handling.md)
|
||||||
- [math in Lyng](math.md), [the `when` statement](when.md)
|
- [math in Lyng](math.md), [the `when` statement](when.md), [return statement](return_statement.md)
|
||||||
- [Testing and Assertions](Testing.md)
|
- [Testing and Assertions](Testing.md)
|
||||||
- [time](time.md) and [parallelism](parallelism.md)
|
- [time](time.md) and [parallelism](parallelism.md)
|
||||||
- [parallelism] - multithreaded code, coroutines, etc.
|
- [parallelism] - multithreaded code, coroutines, etc.
|
||||||
@@ -32,6 +32,15 @@ any block also returns it's last expression:
|
|||||||
}
|
}
|
||||||
>>> 6
|
>>> 6
|
||||||
|
|
||||||
|
If you want to exit a function or lambda earlier, use the `return` statement:
|
||||||
|
|
||||||
|
fn divide(a, b) {
|
||||||
|
if( b == 0 ) return null
|
||||||
|
a / b
|
||||||
|
}
|
||||||
|
|
||||||
|
See [return statement](return_statement.md) for more details on scoping and non-local returns.
|
||||||
|
|
||||||
If you don't want block to return anything, use `void`:
|
If you don't want block to return anything, use `void`:
|
||||||
|
|
||||||
fn voidFunction() {
|
fn voidFunction() {
|
||||||
@@ -87,6 +96,27 @@ Lyng supports simple enums for a fixed set of named constants. Declare with `enu
|
|||||||
|
|
||||||
For more details (usage patterns, `when` switching, serialization), see OOP notes: [Enums in detail](OOP.md#enums).
|
For more details (usage patterns, `when` switching, serialization), see OOP notes: [Enums in detail](OOP.md#enums).
|
||||||
|
|
||||||
|
## Singleton Objects
|
||||||
|
|
||||||
|
Singleton objects are declared using the `object` keyword. They define a class and create its single instance immediately.
|
||||||
|
|
||||||
|
object Logger {
|
||||||
|
fun log(msg) { println("[LOG] " + msg) }
|
||||||
|
}
|
||||||
|
|
||||||
|
Logger.log("Hello singleton!")
|
||||||
|
|
||||||
|
## Delegation (briefly)
|
||||||
|
|
||||||
|
You can delegate properties and functions to other objects using the `by` keyword. This is perfect for patterns like `lazy` initialization.
|
||||||
|
|
||||||
|
val expensiveData by lazy {
|
||||||
|
// computed only once on demand
|
||||||
|
"computed"
|
||||||
|
}
|
||||||
|
|
||||||
|
For more details on these features, see [Delegation in Lyng](delegation.md) and [OOP notes](OOP.md).
|
||||||
|
|
||||||
When putting multiple statments in the same line it is convenient and recommended to use `;`:
|
When putting multiple statments in the same line it is convenient and recommended to use `;`:
|
||||||
|
|
||||||
var from; var to
|
var from; var to
|
||||||
@@ -158,14 +188,13 @@ Note that assignment operator returns rvalue, it can't be assigned.
|
|||||||
## Modifying arithmetics
|
## Modifying arithmetics
|
||||||
|
|
||||||
There is a set of assigning operations: `+=`, `-=`, `*=`, `/=` and even `%=`.
|
There is a set of assigning operations: `+=`, `-=`, `*=`, `/=` and even `%=`.
|
||||||
|
There is also a special null-aware assignment operator `?=`: it performs the assignment only if the lvalue is `null`.
|
||||||
|
|
||||||
var x = 5
|
var x = null
|
||||||
assert( 25 == (x*=5) )
|
x ?= 10
|
||||||
assert( 25 == x)
|
assertEquals(10, x)
|
||||||
assert( 24 == (x-=1) )
|
x ?= 20
|
||||||
assert( 12 == (x/=2) )
|
assertEquals(10, x)
|
||||||
x
|
|
||||||
>>> 12
|
|
||||||
|
|
||||||
Notice the parentheses here: the assignment has low priority!
|
Notice the parentheses here: the assignment has low priority!
|
||||||
|
|
||||||
@@ -218,6 +247,13 @@ There is also "elvis operator", null-coalesce infix operator '?:' that returns r
|
|||||||
null ?: "nothing"
|
null ?: "nothing"
|
||||||
>>> "nothing"
|
>>> "nothing"
|
||||||
|
|
||||||
|
There is also a null-aware assignment operator `?=`, which assigns a value only if the target is `null`:
|
||||||
|
|
||||||
|
var config = null
|
||||||
|
config ?= { port: 8080 }
|
||||||
|
config ?= { port: 9000 } // no-op, config is already not null
|
||||||
|
assertEquals(8080, config.port)
|
||||||
|
|
||||||
## Utility functions
|
## Utility functions
|
||||||
|
|
||||||
The following functions simplify nullable values processing and
|
The following functions simplify nullable values processing and
|
||||||
@@ -277,6 +313,16 @@ It works much like `also`, but is executed in the context of the source object:
|
|||||||
assertEquals(p, Point(2,3))
|
assertEquals(p, Point(2,3))
|
||||||
>>> void
|
>>> void
|
||||||
|
|
||||||
|
## with
|
||||||
|
|
||||||
|
Sets `this` to the first argument and executes the block. Returns the value returned by the block:
|
||||||
|
|
||||||
|
class Point(x,y)
|
||||||
|
val p = Point(1,2)
|
||||||
|
val sum = with(p) { x + y }
|
||||||
|
assertEquals(3, sum)
|
||||||
|
>>> void
|
||||||
|
|
||||||
## run
|
## run
|
||||||
|
|
||||||
Executes a block after it returning the value passed by the block. for example, can be used with elvis operator:
|
Executes a block after it returning the value passed by the block. for example, can be used with elvis operator:
|
||||||
@@ -1497,8 +1543,8 @@ See [math functions](math.md). Other general purpose functions are:
|
|||||||
| print(args...) | Open for overriding, it prints to stdout without newline. |
|
| print(args...) | Open for overriding, it prints to stdout without newline. |
|
||||||
| flow {} | create flow sequence, see [parallelism] |
|
| flow {} | create flow sequence, see [parallelism] |
|
||||||
| delay, launch, yield | see [parallelism] |
|
| delay, launch, yield | see [parallelism] |
|
||||||
| cached(builder) | remembers builder() on first invocation and return it then |
|
| cached(builder) | [Lazy evaluation with `cached`](#lazy-evaluation-with-cached) |
|
||||||
| let, also, apply, run | see above, flow controls |
|
| let, also, apply, run, with | see above, flow controls |
|
||||||
|
|
||||||
(1)
|
(1)
|
||||||
: `fn` is optional lambda returning string message to add to exception string.
|
: `fn` is optional lambda returning string message to add to exception string.
|
||||||
@@ -1525,7 +1571,7 @@ Lambda avoid unnecessary execution if assertion is not failed. for example:
|
|||||||
|
|
||||||
[Range]: Range.md
|
[Range]: Range.md
|
||||||
|
|
||||||
[String]: development/String.md
|
[String]: ../archived/development/String.md
|
||||||
|
|
||||||
[string formatting]: https://github.com/sergeych/mp_stools?tab=readme-ov-file#sprintf-syntax-summary
|
[string formatting]: https://github.com/sergeych/mp_stools?tab=readme-ov-file#sprintf-syntax-summary
|
||||||
|
|
||||||
@@ -1545,6 +1591,50 @@ Lambda avoid unnecessary execution if assertion is not failed. for example:
|
|||||||
|
|
||||||
[Regex]: Regex.md
|
[Regex]: Regex.md
|
||||||
|
|
||||||
|
## Lazy evaluation with `cached`
|
||||||
|
|
||||||
|
Sometimes you have an expensive computation that you only want to perform if and when it is actually needed, and then remember (cache) the result for all future calls. Lyng provides the `cached(builder)` function for this purpose.
|
||||||
|
|
||||||
|
It is extremely simple to use: you pass it a block (lambda) that performs the computation, and it returns a zero-argument function that manages the caching for you.
|
||||||
|
|
||||||
|
### Basic Example
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val expensive = cached {
|
||||||
|
println("Performing expensive calculation...")
|
||||||
|
2 + 2
|
||||||
|
}
|
||||||
|
|
||||||
|
println(expensive()) // Prints "Performing expensive calculation...") then "4"
|
||||||
|
println(expensive()) // Prints only "4" (result is cached)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Benefits and Simplicity
|
||||||
|
|
||||||
|
1. **Lazy Execution:** The code inside the `cached` block doesn't run until you actually call the resulting function.
|
||||||
|
2. **Automatic State Management:** You don't need to manually check if a value has been computed or store it in a separate variable.
|
||||||
|
3. **Closures and Class Support:** `cached` works perfectly with closures. If you use it inside a class, it will correctly capture the instance variables, and each instance will have its own independent cache.
|
||||||
|
|
||||||
|
### Use Case: Lazy Properties in Classes
|
||||||
|
|
||||||
|
This is the most common use case for `cached`. It allows you to define expensive "fields" that are only computed if someone actually uses them:
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class User(val id: Int) {
|
||||||
|
// The details will be fetched only once, on demand
|
||||||
|
val details = cached {
|
||||||
|
println("Fetching details for user " + id)
|
||||||
|
// Db.query is a hypothetical example
|
||||||
|
Db.query("SELECT * FROM users WHERE id = " + id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val u = User(101)
|
||||||
|
// ... nothing happens yet ...
|
||||||
|
val d = u.details() // Computation happens here
|
||||||
|
val sameD = u.details() // Returns the same result immediately
|
||||||
|
```
|
||||||
|
|
||||||
## Multiple Inheritance (quick start)
|
## Multiple Inheritance (quick start)
|
||||||
|
|
||||||
Lyng supports multiple inheritance (MI) with simple, predictable rules. For a full reference see OOP notes, this is a quick, copy‑paste friendly overview.
|
Lyng supports multiple inheritance (MI) with simple, predictable rules. For a full reference see OOP notes, this is a quick, copy‑paste friendly overview.
|
||||||
|
|||||||
@@ -0,0 +1,171 @@
|
|||||||
|
# What's New in Lyng
|
||||||
|
|
||||||
|
This document highlights the latest additions and improvements to the Lyng language and its ecosystem.
|
||||||
|
|
||||||
|
## Language Features
|
||||||
|
|
||||||
|
### Class Properties with Accessors
|
||||||
|
Classes now support properties with custom `get()` and `set()` accessors. Properties in Lyng do **not** have automatic backing fields; they are pure accessors.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Person(private var _age: Int) {
|
||||||
|
// Read-only property
|
||||||
|
val ageCategory get() = if (_age < 18) "Minor" else "Adult"
|
||||||
|
|
||||||
|
// Read-write property
|
||||||
|
var age: Int
|
||||||
|
get() = _age
|
||||||
|
set(v) {
|
||||||
|
if (v >= 0) _age = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Private and Protected Setters
|
||||||
|
You can now restrict the visibility of a property's or field's setter using `private set` or `protected set`. This allows members to be publicly readable but only writable from within the declaring class or its subclasses.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Counter {
|
||||||
|
var count = 0
|
||||||
|
private set // Field with private setter
|
||||||
|
|
||||||
|
fun increment() { count++ }
|
||||||
|
}
|
||||||
|
|
||||||
|
class AdvancedCounter : Counter {
|
||||||
|
var totalOperations = 0
|
||||||
|
protected set // Settable here and in further subclasses
|
||||||
|
}
|
||||||
|
|
||||||
|
let c = Counter()
|
||||||
|
c.increment() // OK
|
||||||
|
// c.count = 10 // Error: setter is private
|
||||||
|
```
|
||||||
|
|
||||||
|
### Late-initialized `val` Fields
|
||||||
|
`val` fields in classes can be declared without an immediate initializer, provided they are assigned exactly once. If accessed before initialization, they hold the special `Unset` singleton.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class Service {
|
||||||
|
val logger
|
||||||
|
|
||||||
|
fun check() {
|
||||||
|
if (logger == Unset) println("Not initialized yet")
|
||||||
|
}
|
||||||
|
|
||||||
|
init {
|
||||||
|
logger = Logger("Service")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Named Arguments and Named Splats
|
||||||
|
Function calls now support named arguments using the `name: value` syntax. If the variable name matches the parameter name, you can use the `name:` shorthand.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
fun greet(name, greeting = "Hello") {
|
||||||
|
println("$greeting, $name!")
|
||||||
|
}
|
||||||
|
|
||||||
|
val name = "Alice"
|
||||||
|
greet(name:) // Shorthand for greet(name: name)
|
||||||
|
greet(greeting: "Hi", name: "Bob")
|
||||||
|
|
||||||
|
let params = { name: "Charlie", greeting: "Hey")
|
||||||
|
greet(...params) // Named splat expansion
|
||||||
|
```
|
||||||
|
|
||||||
|
### Multiple Inheritance (MI)
|
||||||
|
Lyng now supports multiple inheritance using the C3 Method Resolution Order (MRO). Use `this@Type` or casts for disambiguation.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
class A { fun foo() = "A" }
|
||||||
|
class B { fun foo() = "B" }
|
||||||
|
|
||||||
|
class Derived : A, B {
|
||||||
|
fun test() {
|
||||||
|
println(foo()) // Resolves to A.foo (leftmost)
|
||||||
|
println(this@B.foo()) // Qualified dispatch to B.foo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let d = Derived()
|
||||||
|
println((d as B).foo()) // Disambiguation via cast
|
||||||
|
```
|
||||||
|
|
||||||
|
### Singleton Objects
|
||||||
|
Singleton objects are declared using the `object` keyword. They provide a convenient way to define a class and its single instance in one go.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
object Config {
|
||||||
|
val version = "1.2.3"
|
||||||
|
fun show() = println("Config version: " + version)
|
||||||
|
}
|
||||||
|
|
||||||
|
Config.show()
|
||||||
|
```
|
||||||
|
|
||||||
|
### Object Expressions
|
||||||
|
You can now create anonymous objects that inherit from classes or interfaces using the `object : Base { ... }` syntax. These expressions capture their lexical scope and support multiple inheritance.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
val worker = object : Runnable {
|
||||||
|
override fun run() = println("Working...")
|
||||||
|
}
|
||||||
|
|
||||||
|
val x = object : Base(arg1), Interface1 {
|
||||||
|
val property = 42
|
||||||
|
override fun method() = this@object.property * 2
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `this@object` to refer to the innermost anonymous object instance when `this` is rebound.
|
||||||
|
|
||||||
|
### Unified Delegation Model
|
||||||
|
A powerful new delegation system allows `val`, `var`, and `fun` members to delegate their logic to other objects using the `by` keyword.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
// Property delegation
|
||||||
|
val lazyValue by lazy { "expensive" }
|
||||||
|
|
||||||
|
// Function delegation
|
||||||
|
fun remoteAction by myProxy
|
||||||
|
|
||||||
|
// Observable properties
|
||||||
|
var name by Observable("initial") { n, old, new ->
|
||||||
|
println("Changed!")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The system features a unified interface (`getValue`, `setValue`, `invoke`) and a `bind` hook for initialization-time validation and configuration. See the [Delegation Guide](delegation.md) for more.
|
||||||
|
|
||||||
|
### Assign-if-null Operator (`?=`)
|
||||||
|
The new `?=` operator provides a concise way to assign a value only if the target is `null`. It is especially useful for setting default values or lazy initialization.
|
||||||
|
|
||||||
|
```lyng
|
||||||
|
var x = null
|
||||||
|
x ?= 42 // x is now 42
|
||||||
|
x ?= 100 // x remains 42 (not null)
|
||||||
|
|
||||||
|
// Works with properties and index access
|
||||||
|
config.port ?= 8080
|
||||||
|
settings["theme"] ?= "dark"
|
||||||
|
```
|
||||||
|
|
||||||
|
The operator returns the final value of the receiver (the original value if it was not `null`, or the new value if the assignment occurred).
|
||||||
|
|
||||||
|
## Tooling and Infrastructure
|
||||||
|
|
||||||
|
### CLI: Formatting Command
|
||||||
|
A new `fmt` subcommand has been added to the Lyng CLI.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
lyng fmt MyFile.lyng # Print formatted code to stdout
|
||||||
|
lyng fmt --in-place MyFile.lyng # Format file in-place
|
||||||
|
lyng fmt --check MyFile.lyng # Check if file needs formatting
|
||||||
|
```
|
||||||
|
|
||||||
|
### IDEA Plugin: Autocompletion
|
||||||
|
Experimental lightweight autocompletion is now available in the IntelliJ plugin. It features type-aware member suggestions and inheritance-aware completion.
|
||||||
|
|
||||||
|
You can enable it in **Settings | Lyng Formatter | Enable Lyng autocompletion**.
|
||||||
@@ -20,7 +20,7 @@ Files
|
|||||||
- Constants: `true`, `false`, `null`, `this`
|
- Constants: `true`, `false`, `null`, `this`
|
||||||
- Annotations: `@name` (Unicode identifiers supported)
|
- Annotations: `@name` (Unicode identifiers supported)
|
||||||
- Labels: `name:` (Unicode identifiers supported)
|
- Labels: `name:` (Unicode identifiers supported)
|
||||||
- Declarations: highlights declared names in `fun|fn name`, `class|enum Name`, `val|var name`
|
- Declarations: highlights declared names in `fun|fn name`, `class|enum|interface Name`, `val|var name`
|
||||||
- Types: built-ins (`Int|Real|String|Bool|Char|Regex`) and Capitalized identifiers (heuristic)
|
- Types: built-ins (`Int|Real|String|Bool|Char|Regex`) and Capitalized identifiers (heuristic)
|
||||||
- Operators including ranges (`..`, `..<`, `...`), null-safe (`?.`, `?[`, `?(`, `?{`, `?:`, `??`), arrows (`->`, `=>`, `::`), match operators (`=~`, `!~`), bitwise, arithmetic, etc.
|
- Operators including ranges (`..`, `..<`, `...`), null-safe (`?.`, `?[`, `?(`, `?{`, `?:`, `??`), arrows (`->`, `=>`, `::`), match operators (`=~`, `!~`), bitwise, arithmetic, etc.
|
||||||
- Shuttle operator `<=>`
|
- Shuttle operator `<=>`
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"name": "lyng-textmate",
|
"name": "lyng-textmate",
|
||||||
"displayName": "Lyng",
|
"displayName": "Lyng",
|
||||||
"description": "TextMate grammar for the Lyng language (for JetBrains IDEs via TextMate Bundles and VS Code).",
|
"description": "TextMate grammar for the Lyng language (for JetBrains IDEs via TextMate Bundles and VS Code).",
|
||||||
"version": "0.0.3",
|
"version": "0.1.0",
|
||||||
"publisher": "lyng",
|
"publisher": "lyng",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"engines": { "vscode": "^1.0.0" },
|
"engines": { "vscode": "^1.0.0" },
|
||||||
|
|||||||
@@ -42,7 +42,7 @@
|
|||||||
{ "name": "constant.numeric.decimal.lyng", "match": "(?<![A-Za-z_])(?:[0-9][0-9_]*)\\.(?:[0-9_]+)(?:[eE][+-]?[0-9_]+)?|(?<![A-Za-z_])(?:[0-9][0-9_]*)(?:[eE][+-]?[0-9_]+)?" }
|
{ "name": "constant.numeric.decimal.lyng", "match": "(?<![A-Za-z_])(?:[0-9][0-9_]*)\\.(?:[0-9_]+)(?:[eE][+-]?[0-9_]+)?|(?<![A-Za-z_])(?:[0-9][0-9_]*)(?:[eE][+-]?[0-9_]+)?" }
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"annotations": { "patterns": [ { "name": "entity.name.label.at.lyng", "match": "@[\\p{L}_][\\p{L}\\p{N}_]*:" }, { "name": "storage.modifier.annotation.lyng", "match": "@[\\p{L}_][\\p{L}\\p{N}_]*" } ] },
|
"annotations": { "patterns": [ { "name": "entity.name.label.at.lyng", "match": "@[\\p{L}_][\\p{L}\\p{N}_]*" } ] },
|
||||||
"mapLiterals": {
|
"mapLiterals": {
|
||||||
"patterns": [
|
"patterns": [
|
||||||
{
|
{
|
||||||
@@ -74,11 +74,11 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"labels": { "patterns": [ { "name": "entity.name.label.lyng", "match": "[\\p{L}_][\\p{L}\\p{N}_]*:" } ] },
|
"labels": { "patterns": [ { "name": "entity.name.label.lyng", "match": "[\\p{L}_][\\p{L}\\p{N}_]*@" } ] },
|
||||||
"directives": { "patterns": [ { "name": "meta.directive.lyng", "match": "^\\s*#[_A-Za-z][_A-Za-z0-9]*" } ] },
|
"directives": { "patterns": [ { "name": "meta.directive.lyng", "match": "^\\s*#[_A-Za-z][_A-Za-z0-9]*" } ] },
|
||||||
"declarations": { "patterns": [ { "name": "meta.function.declaration.lyng", "match": "\\b(fun|fn)\\s+(?:([\\p{L}_][\\p{L}\\p{N}_]*)\\.)?([\\p{L}_][\\p{L}\\p{N}_]*)", "captures": { "1": { "name": "keyword.declaration.lyng" }, "2": { "name": "entity.name.type.lyng" }, "3": { "name": "entity.name.function.lyng" } } }, { "name": "meta.type.declaration.lyng", "match": "\\b(?:class|enum)\\s+([\\p{L}_][\\p{L}\\p{N}_]*)", "captures": { "1": { "name": "entity.name.type.lyng" } } }, { "name": "meta.variable.declaration.lyng", "match": "\\b(val|var)\\s+(?:([\\p{L}_][\\p{L}\\p{N}_]*)\\.)?([\\p{L}_][\\p{L}\\p{N}_]*)", "captures": { "1": { "name": "keyword.declaration.lyng" }, "2": { "name": "entity.name.type.lyng" }, "3": { "name": "variable.other.declaration.lyng" } } } ] },
|
"declarations": { "patterns": [ { "name": "meta.function.declaration.lyng", "match": "\\b(fun|fn)\\s+(?:([\\p{L}_][\\p{L}\\p{N}_]*)\\.)?([\\p{L}_][\\p{L}\\p{N}_]*)", "captures": { "1": { "name": "keyword.declaration.lyng" }, "2": { "name": "entity.name.type.lyng" }, "3": { "name": "entity.name.function.lyng" } } }, { "name": "meta.type.declaration.lyng", "match": "\\b(?:class|enum|interface|object)(?:\\s+([\\p{L}_][\\p{L}\\p{N}_]*))?", "captures": { "1": { "name": "entity.name.type.lyng" } } }, { "name": "meta.variable.declaration.lyng", "match": "\\b(val|var)\\s+(?:([\\p{L}_][\\p{L}\\p{N}_]*)\\.)?([\\p{L}_][\\p{L}\\p{N}_]*)", "captures": { "1": { "name": "keyword.declaration.lyng" }, "2": { "name": "entity.name.type.lyng" }, "3": { "name": "variable.other.declaration.lyng" } } } ] },
|
||||||
"keywords": { "patterns": [ { "name": "keyword.control.lyng", "match": "\\b(?:if|else|when|while|do|for|try|catch|finally|throw|return|break|continue)\\b" }, { "name": "keyword.declaration.lyng", "match": "\\b(?:fun|fn|class|enum|val|var|import|package|constructor|property|open|extern|private|protected|static|get|set)\\b" }, { "name": "keyword.operator.word.lyng", "match": "\\bnot\\s+(?:in|is)\\b" }, { "name": "keyword.operator.word.lyng", "match": "\\b(?:and|or|not|in|is|as|as\\?)\\b" } ] },
|
"keywords": { "patterns": [ { "name": "keyword.control.lyng", "match": "\\b(?:if|else|when|while|do|for|try|catch|finally|throw|return|break|continue)\\b" }, { "name": "keyword.declaration.lyng", "match": "\\b(?:fun|fn|class|enum|interface|val|var|import|package|constructor|property|abstract|override|open|closed|extern|private|protected|static|get|set|object|init|by)\\b" }, { "name": "keyword.operator.word.lyng", "match": "\\bnot\\s+(?:in|is)\\b" }, { "name": "keyword.operator.word.lyng", "match": "\\b(?:and|or|not|in|is|as|as\\?)\\b" } ] },
|
||||||
"constants": { "patterns": [ { "name": "constant.language.lyng", "match": "(?:\\b(?:true|false|null|this)\\b|π)" } ] },
|
"constants": { "patterns": [ { "name": "constant.language.lyng", "match": "(?:\\b(?:true|false|null|this(?:@[\\p{L}_][\\p{L}\\p{N}_]*)?)\\b|π)" } ] },
|
||||||
"types": { "patterns": [ { "name": "storage.type.lyng", "match": "\\b(?:Int|Real|String|Bool|Char|Regex)\\b" }, { "name": "entity.name.type.lyng", "match": "\\b[A-Z][A-Za-z0-9_]*\\b(?!\\s*\\()" } ] },
|
"types": { "patterns": [ { "name": "storage.type.lyng", "match": "\\b(?:Int|Real|String|Bool|Char|Regex)\\b" }, { "name": "entity.name.type.lyng", "match": "\\b[A-Z][A-Za-z0-9_]*\\b(?!\\s*\\()" } ] },
|
||||||
"operators": { "patterns": [ { "name": "keyword.operator.comparison.lyng", "match": "===|!==|==|!=|<=|>=|<|>" }, { "name": "keyword.operator.shuttle.lyng", "match": "<=>" }, { "name": "keyword.operator.arrow.lyng", "match": "=>|->|::" }, { "name": "keyword.operator.range.lyng", "match": "\\.\\.\\.|\\.\\.<|\\.\\." }, { "name": "keyword.operator.nullsafe.lyng", "match": "\\?\\.|\\?\\[|\\?\\(|\\?\\{|\\?:|\\?\\?" }, { "name": "keyword.operator.assignment.lyng", "match": "(?:\\+=|-=|\\*=|/=|%=|=)" }, { "name": "keyword.operator.logical.lyng", "match": "&&|\\|\\|" }, { "name": "keyword.operator.bitwise.lyng", "match": "<<|>>|&|\\||\\^|~" }, { "name": "keyword.operator.match.lyng", "match": "=~|!~" }, { "name": "keyword.operator.arithmetic.lyng", "match": "\\+\\+|--|[+\\-*/%]" }, { "name": "keyword.operator.other.lyng", "match": "[!?]" } ] },
|
"operators": { "patterns": [ { "name": "keyword.operator.comparison.lyng", "match": "===|!==|==|!=|<=|>=|<|>" }, { "name": "keyword.operator.shuttle.lyng", "match": "<=>" }, { "name": "keyword.operator.arrow.lyng", "match": "=>|->|::" }, { "name": "keyword.operator.range.lyng", "match": "\\.\\.\\.|\\.\\.<|\\.\\." }, { "name": "keyword.operator.nullsafe.lyng", "match": "\\?\\.|\\?\\[|\\?\\(|\\?\\{|\\?:|\\?\\?" }, { "name": "keyword.operator.assignment.lyng", "match": "(?:\\+=|-=|\\*=|/=|%=|=)" }, { "name": "keyword.operator.logical.lyng", "match": "&&|\\|\\|" }, { "name": "keyword.operator.bitwise.lyng", "match": "<<|>>|&|\\||\\^|~" }, { "name": "keyword.operator.match.lyng", "match": "=~|!~" }, { "name": "keyword.operator.arithmetic.lyng", "match": "\\+\\+|--|[+\\-*/%]" }, { "name": "keyword.operator.other.lyng", "match": "[!?]" } ] },
|
||||||
"punctuation": { "patterns": [ { "name": "punctuation.separator.comma.lyng", "match": "," }, { "name": "punctuation.terminator.statement.lyng", "match": ";" }, { "name": "punctuation.section.block.begin.lyng", "match": "[(]{1}|[{]{1}|\\[" }, { "name": "punctuation.section.block.end.lyng", "match": "[)]{1}|[}]{1}|\\]" }, { "name": "punctuation.accessor.dot.lyng", "match": "\\." }, { "name": "punctuation.separator.colon.lyng", "match": ":" } ] }
|
"punctuation": { "patterns": [ { "name": "punctuation.separator.comma.lyng", "match": "," }, { "name": "punctuation.terminator.statement.lyng", "match": ";" }, { "name": "punctuation.section.block.begin.lyng", "match": "[(]{1}|[{]{1}|\\[" }, { "name": "punctuation.section.block.end.lyng", "match": "[)]{1}|[}]{1}|\\]" }, { "name": "punctuation.accessor.dot.lyng", "match": "\\." }, { "name": "punctuation.separator.colon.lyng", "match": ":" } ] }
|
||||||
|
|||||||
+43
-12
@@ -94,6 +94,16 @@ class LyngExternalAnnotator : ExternalAnnotator<LyngExternalAnnotator.Input, Lyn
|
|||||||
|
|
||||||
val out = ArrayList<Span>(256)
|
val out = ArrayList<Span>(256)
|
||||||
|
|
||||||
|
fun isFollowedByParenOrBlock(rangeEnd: Int): Boolean {
|
||||||
|
var i = rangeEnd
|
||||||
|
while (i < text.length) {
|
||||||
|
val ch = text[i]
|
||||||
|
if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') { i++; continue }
|
||||||
|
return ch == '(' || ch == '{'
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
fun putRange(start: Int, end: Int, key: com.intellij.openapi.editor.colors.TextAttributesKey) {
|
fun putRange(start: Int, end: Int, key: com.intellij.openapi.editor.colors.TextAttributesKey) {
|
||||||
if (start in 0..end && end <= text.length && start < end) out += Span(start, end, key)
|
if (start in 0..end && end <= text.length && start < end) out += Span(start, end, key)
|
||||||
}
|
}
|
||||||
@@ -207,16 +217,6 @@ class LyngExternalAnnotator : ExternalAnnotator<LyngExternalAnnotator.Input, Lyn
|
|||||||
|
|
||||||
val tokens = try { SimpleLyngHighlighter().highlight(text) } catch (_: Throwable) { emptyList() }
|
val tokens = try { SimpleLyngHighlighter().highlight(text) } catch (_: Throwable) { emptyList() }
|
||||||
|
|
||||||
fun isFollowedByParenOrBlock(rangeEnd: Int): Boolean {
|
|
||||||
var i = rangeEnd
|
|
||||||
while (i < text.length) {
|
|
||||||
val ch = text[i]
|
|
||||||
if (ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n') { i++; continue }
|
|
||||||
return ch == '(' || ch == '{'
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build simple name -> role map for top-level vals/vars and parameters
|
// Build simple name -> role map for top-level vals/vars and parameters
|
||||||
val nameRole = HashMap<String, com.intellij.openapi.editor.colors.TextAttributesKey>(8)
|
val nameRole = HashMap<String, com.intellij.openapi.editor.colors.TextAttributesKey>(8)
|
||||||
for (d in mini.declarations) when (d) {
|
for (d in mini.declarations) when (d) {
|
||||||
@@ -253,7 +253,7 @@ class LyngExternalAnnotator : ExternalAnnotator<LyngExternalAnnotator.Input, Lyn
|
|||||||
if (e is com.intellij.openapi.progress.ProcessCanceledException) throw e
|
if (e is com.intellij.openapi.progress.ProcessCanceledException) throw e
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add annotation coloring using token highlighter (treat @Label as annotation)
|
// Add annotation/label coloring using token highlighter
|
||||||
run {
|
run {
|
||||||
val tokens = try { SimpleLyngHighlighter().highlight(text) } catch (_: Throwable) { emptyList() }
|
val tokens = try { SimpleLyngHighlighter().highlight(text) } catch (_: Throwable) { emptyList() }
|
||||||
for (s in tokens) if (s.kind == HighlightKind.Label) {
|
for (s in tokens) if (s.kind == HighlightKind.Label) {
|
||||||
@@ -261,12 +261,33 @@ class LyngExternalAnnotator : ExternalAnnotator<LyngExternalAnnotator.Input, Lyn
|
|||||||
val end = s.range.endExclusive
|
val end = s.range.endExclusive
|
||||||
if (start in 0..end && end <= text.length && start < end) {
|
if (start in 0..end && end <= text.length && start < end) {
|
||||||
val lexeme = try { text.substring(start, end) } catch (_: Throwable) { null }
|
val lexeme = try { text.substring(start, end) } catch (_: Throwable) { null }
|
||||||
if (lexeme != null && lexeme.startsWith("@")) {
|
if (lexeme != null) {
|
||||||
|
// Heuristic: if it starts with @ and follows a control keyword, it's likely a label
|
||||||
|
// Otherwise if it starts with @ it's an annotation.
|
||||||
|
// If it ends with @ it's a loop label.
|
||||||
|
when {
|
||||||
|
lexeme.endsWith("@") -> putRange(start, end, LyngHighlighterColors.LABEL)
|
||||||
|
lexeme.startsWith("@") -> {
|
||||||
|
// Try to see if it's an exit label
|
||||||
|
val prevNonWs = prevNonWs(text, start)
|
||||||
|
val prevWord = if (prevNonWs >= 0) {
|
||||||
|
var wEnd = prevNonWs + 1
|
||||||
|
var wStart = prevNonWs
|
||||||
|
while (wStart > 0 && text[wStart - 1].isLetter()) wStart--
|
||||||
|
text.substring(wStart, wEnd)
|
||||||
|
} else null
|
||||||
|
|
||||||
|
if (prevWord in setOf("return", "break", "continue") || isFollowedByParenOrBlock(end)) {
|
||||||
|
putRange(start, end, LyngHighlighterColors.LABEL)
|
||||||
|
} else {
|
||||||
putRange(start, end, LyngHighlighterColors.ANNOTATION)
|
putRange(start, end, LyngHighlighterColors.ANNOTATION)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Map Enum constants from token highlighter to IDEA enum constant color
|
// Map Enum constants from token highlighter to IDEA enum constant color
|
||||||
run {
|
run {
|
||||||
@@ -364,6 +385,16 @@ class LyngExternalAnnotator : ExternalAnnotator<LyngExternalAnnotator.Input, Lyn
|
|||||||
private val CACHE_KEY: Key<Result> = Key.create("LYNG_SEMANTIC_CACHE")
|
private val CACHE_KEY: Key<Result> = Key.create("LYNG_SEMANTIC_CACHE")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun prevNonWs(text: String, idxExclusive: Int): Int {
|
||||||
|
var i = idxExclusive - 1
|
||||||
|
while (i >= 0) {
|
||||||
|
val ch = text[i]
|
||||||
|
if (ch != ' ' && ch != '\t' && ch != '\n' && ch != '\r') return i
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Make the error highlight a bit wider than a single character so it is easier to see and click.
|
* Make the error highlight a bit wider than a single character so it is easier to see and click.
|
||||||
* Strategy:
|
* Strategy:
|
||||||
|
|||||||
@@ -85,7 +85,13 @@ class LyngEnterHandler : EnterHandlerDelegate {
|
|||||||
if (code == "}" || code == "*/") {
|
if (code == "}" || code == "*/") {
|
||||||
// Adjust indent for the previous line if it's a block or comment closer
|
// Adjust indent for the previous line if it's a block or comment closer
|
||||||
val prevStart = doc.getLineStartOffset(prevLine)
|
val prevStart = doc.getLineStartOffset(prevLine)
|
||||||
|
if (file.context == null) {
|
||||||
|
try {
|
||||||
CodeStyleManager.getInstance(project).adjustLineIndent(file, prevStart)
|
CodeStyleManager.getInstance(project).adjustLineIndent(file, prevStart)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.warn("Failed to adjust line indent for previous line: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Fallback for previous line: manual application
|
// Fallback for previous line: manual application
|
||||||
val desiredPrev = computeDesiredIndent(project, doc, prevLine)
|
val desiredPrev = computeDesiredIndent(project, doc, prevLine)
|
||||||
@@ -102,8 +108,13 @@ class LyngEnterHandler : EnterHandlerDelegate {
|
|||||||
}
|
}
|
||||||
// Adjust indent for the current (new) line
|
// Adjust indent for the current (new) line
|
||||||
val currentStart = doc.getLineStartOffsetSafe(currentLine)
|
val currentStart = doc.getLineStartOffsetSafe(currentLine)
|
||||||
val csm = CodeStyleManager.getInstance(project)
|
if (file.context == null) {
|
||||||
csm.adjustLineIndent(file, currentStart)
|
try {
|
||||||
|
CodeStyleManager.getInstance(project).adjustLineIndent(file, currentStart)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.warn("Failed to adjust line indent for current line: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Fallback: if the platform didn't physically insert indentation, compute it from our formatter and apply
|
// Fallback: if the platform didn't physically insert indentation, compute it from our formatter and apply
|
||||||
val lineStart = doc.getLineStartOffset(currentLine)
|
val lineStart = doc.getLineStartOffset(currentLine)
|
||||||
|
|||||||
@@ -58,7 +58,13 @@ class LyngTypedHandler : TypedHandlerDelegate() {
|
|||||||
}
|
}
|
||||||
// After block reindent, adjust line indent to what platform thinks (no-op in many cases)
|
// After block reindent, adjust line indent to what platform thinks (no-op in many cases)
|
||||||
val lineStart = doc.getLineStartOffset(line)
|
val lineStart = doc.getLineStartOffset(line)
|
||||||
|
if (file.context == null) {
|
||||||
|
try {
|
||||||
CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart)
|
CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.warn("Failed to adjust line indent for current line: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else if (c == '/') {
|
} else if (c == '/') {
|
||||||
val doc = editor.document
|
val doc = editor.document
|
||||||
@@ -67,7 +73,13 @@ class LyngTypedHandler : TypedHandlerDelegate() {
|
|||||||
PsiDocumentManager.getInstance(project).commitDocument(doc)
|
PsiDocumentManager.getInstance(project).commitDocument(doc)
|
||||||
val line = doc.getLineNumber(offset - 1)
|
val line = doc.getLineNumber(offset - 1)
|
||||||
val lineStart = doc.getLineStartOffset(line)
|
val lineStart = doc.getLineStartOffset(line)
|
||||||
|
if (file.context == null) {
|
||||||
|
try {
|
||||||
CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart)
|
CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
log.warn("Failed to adjust line indent for comment: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Manual application fallback
|
// Manual application fallback
|
||||||
val desired = computeDesiredIndent(project, doc, line)
|
val desired = computeDesiredIndent(project, doc, line)
|
||||||
|
|||||||
+3
-3
@@ -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.
|
||||||
@@ -42,7 +42,7 @@ private class LineBlocksRootBlock(
|
|||||||
private val file: PsiFile,
|
private val file: PsiFile,
|
||||||
private val settings: CodeStyleSettings
|
private val settings: CodeStyleSettings
|
||||||
) : Block {
|
) : Block {
|
||||||
override fun getTextRange(): TextRange = file.textRange
|
override fun getTextRange(): TextRange = TextRange(0, file.textLength)
|
||||||
|
|
||||||
override fun getSubBlocks(): List<Block> = emptyList()
|
override fun getSubBlocks(): List<Block> = emptyList()
|
||||||
|
|
||||||
@@ -52,7 +52,7 @@ private class LineBlocksRootBlock(
|
|||||||
override fun getSpacing(child1: Block?, child2: Block): Spacing? = null
|
override fun getSpacing(child1: Block?, child2: Block): Spacing? = null
|
||||||
override fun getChildAttributes(newChildIndex: Int): ChildAttributes = ChildAttributes(Indent.getNoneIndent(), null)
|
override fun getChildAttributes(newChildIndex: Int): ChildAttributes = ChildAttributes(Indent.getNoneIndent(), null)
|
||||||
override fun isIncomplete(): Boolean = false
|
override fun isIncomplete(): Boolean = false
|
||||||
override fun isLeaf(): Boolean = false
|
override fun isLeaf(): Boolean = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Intentionally no sub-blocks/spacing: indentation is handled by PreFormatProcessor + LineIndentProvider
|
// Intentionally no sub-blocks/spacing: indentation is handled by PreFormatProcessor + LineIndentProvider
|
||||||
@@ -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.
|
||||||
@@ -44,25 +44,67 @@ class LyngPreFormatProcessor : PreFormatProcessor {
|
|||||||
// When both spacing and wrapping are OFF, still fix indentation for the whole file to
|
// When both spacing and wrapping are OFF, still fix indentation for the whole file to
|
||||||
// guarantee visible changes on Reformat Code.
|
// guarantee visible changes on Reformat Code.
|
||||||
val runFullFileIndent = !settings.enableSpacing && !settings.enableWrapping
|
val runFullFileIndent = !settings.enableSpacing && !settings.enableWrapping
|
||||||
// Maintain a working range and a modification flag to avoid stale offsets after replacements
|
|
||||||
var modified = false
|
var modified = false
|
||||||
fun fullRange(): TextRange = TextRange(0, doc.textLength)
|
|
||||||
var workingRange: TextRange = range.intersection(fullRange()) ?: fullRange()
|
|
||||||
|
|
||||||
val startLine = if (runFullFileIndent) 0 else doc.getLineNumber(workingRange.startOffset)
|
val docW = doc as? com.intellij.injected.editor.DocumentWindow
|
||||||
val endLine = if (runFullFileIndent) (doc.lineCount - 1).coerceAtLeast(0)
|
// The host range of the entire injected fragment (or the whole file if not injected).
|
||||||
else doc.getLineNumber(workingRange.endOffset.coerceAtMost(doc.textLength))
|
fun currentHostRange(): TextRange = if (docW != null) {
|
||||||
|
TextRange(docW.injectedToHost(0), docW.injectedToHost(doc.textLength))
|
||||||
|
} else {
|
||||||
|
file.textRange
|
||||||
|
}
|
||||||
|
|
||||||
|
// The range in 'doc' coordinate system (local 0..len for injections, host offsets for normal files).
|
||||||
|
fun currentLocalRange(): TextRange = if (docW != null) {
|
||||||
|
TextRange(0, doc.textLength)
|
||||||
|
} else {
|
||||||
|
file.textRange
|
||||||
|
}
|
||||||
|
|
||||||
|
val clr = currentLocalRange()
|
||||||
|
val chr = currentHostRange()
|
||||||
|
|
||||||
|
// Convert the input range to the coordinate system of 'doc'
|
||||||
|
var workingRangeLocal: TextRange = if (docW != null) {
|
||||||
|
val hostIntersection = range.intersection(chr)
|
||||||
|
if (hostIntersection != null) {
|
||||||
|
try {
|
||||||
|
val start = docW.hostToInjected(hostIntersection.startOffset)
|
||||||
|
val end = docW.hostToInjected(hostIntersection.endOffset)
|
||||||
|
TextRange(start.coerceAtMost(end), end.coerceAtLeast(start))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
clr
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
range.intersection(clr) ?: clr
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
range.intersection(clr) ?: clr
|
||||||
|
}
|
||||||
|
|
||||||
|
val startLine = if (runFullFileIndent) {
|
||||||
|
doc.getLineNumber(currentLocalRange().startOffset)
|
||||||
|
} else {
|
||||||
|
doc.getLineNumber(workingRangeLocal.startOffset)
|
||||||
|
}
|
||||||
|
val endLine = if (runFullFileIndent) {
|
||||||
|
if (clr.endOffset <= clr.startOffset) doc.getLineNumber(clr.startOffset)
|
||||||
|
else doc.getLineNumber(clr.endOffset)
|
||||||
|
} else {
|
||||||
|
doc.getLineNumber(workingRangeLocal.endOffset.coerceAtMost(doc.textLength))
|
||||||
|
}
|
||||||
|
|
||||||
fun codePart(s: String): String {
|
fun codePart(s: String): String {
|
||||||
val idx = s.indexOf("//")
|
val idx = s.indexOf("//")
|
||||||
return if (idx >= 0) s.substring(0, idx) else s
|
return if (idx >= 0) s.substring(0, idx) else s
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pre-scan to compute balances up to startLine
|
// Pre-scan to compute balances up to startLine.
|
||||||
|
val fragmentStartLine = doc.getLineNumber(currentLocalRange().startOffset)
|
||||||
var blockLevel = 0
|
var blockLevel = 0
|
||||||
var parenBalance = 0
|
var parenBalance = 0
|
||||||
var bracketBalance = 0
|
var bracketBalance = 0
|
||||||
for (ln in 0 until startLine) {
|
for (ln in fragmentStartLine until startLine) {
|
||||||
val text = doc.getText(TextRange(doc.getLineStartOffset(ln), doc.getLineEndOffset(ln)))
|
val text = doc.getText(TextRange(doc.getLineStartOffset(ln), doc.getLineEndOffset(ln)))
|
||||||
for (ch in codePart(text)) when (ch) {
|
for (ch in codePart(text)) when (ch) {
|
||||||
'{' -> blockLevel++
|
'{' -> blockLevel++
|
||||||
@@ -80,7 +122,13 @@ class LyngPreFormatProcessor : PreFormatProcessor {
|
|||||||
val lineStart = doc.getLineStartOffset(line)
|
val lineStart = doc.getLineStartOffset(line)
|
||||||
// adjustLineIndent delegates to our LineIndentProvider which computes
|
// adjustLineIndent delegates to our LineIndentProvider which computes
|
||||||
// indentation from scratch; this is safe and idempotent
|
// indentation from scratch; this is safe and idempotent
|
||||||
|
if (file.context == null) {
|
||||||
|
try {
|
||||||
CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart)
|
CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// Log as debug because this can be called many times during reformat
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// After indentation, update block/paren/bracket balances using the current line text
|
// After indentation, update block/paren/bracket balances using the current line text
|
||||||
val lineEnd = doc.getLineEndOffset(line)
|
val lineEnd = doc.getLineEndOffset(line)
|
||||||
@@ -103,15 +151,14 @@ class LyngPreFormatProcessor : PreFormatProcessor {
|
|||||||
useTabs = options.USE_TAB_CHARACTER,
|
useTabs = options.USE_TAB_CHARACTER,
|
||||||
continuationIndentSize = options.CONTINUATION_INDENT_SIZE.coerceAtLeast(options.INDENT_SIZE.coerceAtLeast(1)),
|
continuationIndentSize = options.CONTINUATION_INDENT_SIZE.coerceAtLeast(options.INDENT_SIZE.coerceAtLeast(1)),
|
||||||
)
|
)
|
||||||
val full = fullRange()
|
val r = if (runFullFileIndent) currentLocalRange() else workingRangeLocal.intersection(currentLocalRange()) ?: currentLocalRange()
|
||||||
val r = if (runFullFileIndent) full else workingRange.intersection(full) ?: full
|
|
||||||
val text = doc.getText(r)
|
val text = doc.getText(r)
|
||||||
val formatted = LyngFormatter.reindent(text, cfg)
|
val formatted = LyngFormatter.reindent(text, cfg)
|
||||||
if (formatted != text) {
|
if (formatted != text) {
|
||||||
doc.replaceString(r.startOffset, r.endOffset, formatted)
|
doc.replaceString(r.startOffset, r.endOffset, formatted)
|
||||||
modified = true
|
modified = true
|
||||||
psiDoc.commitDocument(doc)
|
psiDoc.commitDocument(doc)
|
||||||
workingRange = fullRange()
|
workingRangeLocal = currentLocalRange()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,14 +171,14 @@ class LyngPreFormatProcessor : PreFormatProcessor {
|
|||||||
applySpacing = true,
|
applySpacing = true,
|
||||||
applyWrapping = false,
|
applyWrapping = false,
|
||||||
)
|
)
|
||||||
val safe = workingRange.intersection(fullRange()) ?: fullRange()
|
val r = if (runFullFileIndent) currentLocalRange() else workingRangeLocal.intersection(currentLocalRange()) ?: currentLocalRange()
|
||||||
val text = doc.getText(safe)
|
val text = doc.getText(r)
|
||||||
val formatted = LyngFormatter.format(text, cfg)
|
val formatted = LyngFormatter.format(text, cfg)
|
||||||
if (formatted != text) {
|
if (formatted != text) {
|
||||||
doc.replaceString(safe.startOffset, safe.endOffset, formatted)
|
doc.replaceString(r.startOffset, r.endOffset, formatted)
|
||||||
modified = true
|
modified = true
|
||||||
psiDoc.commitDocument(doc)
|
psiDoc.commitDocument(doc)
|
||||||
workingRange = fullRange()
|
workingRangeLocal = currentLocalRange()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Optionally apply wrapping (after spacing) when enabled
|
// Optionally apply wrapping (after spacing) when enabled
|
||||||
@@ -143,17 +190,19 @@ class LyngPreFormatProcessor : PreFormatProcessor {
|
|||||||
applySpacing = settings.enableSpacing,
|
applySpacing = settings.enableSpacing,
|
||||||
applyWrapping = true,
|
applyWrapping = true,
|
||||||
)
|
)
|
||||||
val safe2 = workingRange.intersection(fullRange()) ?: fullRange()
|
val r = if (runFullFileIndent) currentLocalRange() else workingRangeLocal.intersection(currentLocalRange()) ?: currentLocalRange()
|
||||||
val text2 = doc.getText(safe2)
|
val text = doc.getText(r)
|
||||||
val wrapped = LyngFormatter.format(text2, cfg)
|
val wrapped = LyngFormatter.format(text, cfg)
|
||||||
if (wrapped != text2) {
|
if (wrapped != text) {
|
||||||
doc.replaceString(safe2.startOffset, safe2.endOffset, wrapped)
|
doc.replaceString(r.startOffset, r.endOffset, wrapped)
|
||||||
modified = true
|
modified = true
|
||||||
psiDoc.commitDocument(doc)
|
psiDoc.commitDocument(doc)
|
||||||
workingRange = fullRange()
|
workingRangeLocal = currentLocalRange()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Return a safe range for the formatter to continue with, preventing stale offsets
|
// Return a safe range for the formatter to continue with, preventing stale offsets.
|
||||||
return if (modified) fullRange() else (range.intersection(fullRange()) ?: fullRange())
|
// For injected files, ALWAYS return a range in local coordinates.
|
||||||
|
val finalRange = currentLocalRange()
|
||||||
|
return if (modified) finalRange else (range.intersection(finalRange) ?: finalRange)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -579,7 +579,8 @@ class LyngGrazieAnnotator : ExternalAnnotator<LyngGrazieAnnotator.Input, LyngGra
|
|||||||
val s = w.lowercase()
|
val s = w.lowercase()
|
||||||
return s in setOf(
|
return s in setOf(
|
||||||
// common code words / language keywords to avoid noise
|
// common code words / language keywords to avoid noise
|
||||||
"val","var","fun","class","enum","type","import","package","return","if","else","when","while","for","try","catch","finally","true","false","null",
|
"val","var","fun","class","interface","enum","type","import","package","return","if","else","when","while","for","try","catch","finally","true","false","null",
|
||||||
|
"abstract","closed","override",
|
||||||
// very common English words
|
// very common English words
|
||||||
"the","and","or","not","with","from","into","this","that","file","found","count","name","value","object"
|
"the","and","or","not","with","from","into","this","that","file","found","count","name","value","object"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -43,10 +43,15 @@ class LyngColorSettingsPage : ColorSettingsPage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var counter = 0
|
var counter = 0
|
||||||
|
outer@ while (counter < 10) {
|
||||||
|
if (counter == 5) return@outer
|
||||||
counter = counter + 1
|
counter = counter + 1
|
||||||
|
}
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
|
|
||||||
override fun getAdditionalHighlightingTagToDescriptorMap(): MutableMap<String, TextAttributesKey>? = null
|
override fun getAdditionalHighlightingTagToDescriptorMap(): MutableMap<String, TextAttributesKey> = mutableMapOf(
|
||||||
|
"label" to LyngHighlighterColors.LABEL
|
||||||
|
)
|
||||||
|
|
||||||
override fun getAttributeDescriptors(): Array<AttributesDescriptor> = arrayOf(
|
override fun getAttributeDescriptors(): Array<AttributesDescriptor> = arrayOf(
|
||||||
AttributesDescriptor("Keyword", LyngHighlighterColors.KEYWORD),
|
AttributesDescriptor("Keyword", LyngHighlighterColors.KEYWORD),
|
||||||
@@ -58,6 +63,7 @@ class LyngColorSettingsPage : ColorSettingsPage {
|
|||||||
AttributesDescriptor("Punctuation", LyngHighlighterColors.PUNCT),
|
AttributesDescriptor("Punctuation", LyngHighlighterColors.PUNCT),
|
||||||
// Semantic
|
// Semantic
|
||||||
AttributesDescriptor("Annotation (semantic)", LyngHighlighterColors.ANNOTATION),
|
AttributesDescriptor("Annotation (semantic)", LyngHighlighterColors.ANNOTATION),
|
||||||
|
AttributesDescriptor("Label (semantic)", LyngHighlighterColors.LABEL),
|
||||||
AttributesDescriptor("Variable (semantic)", LyngHighlighterColors.VARIABLE),
|
AttributesDescriptor("Variable (semantic)", LyngHighlighterColors.VARIABLE),
|
||||||
AttributesDescriptor("Value (semantic)", LyngHighlighterColors.VALUE),
|
AttributesDescriptor("Value (semantic)", LyngHighlighterColors.VALUE),
|
||||||
AttributesDescriptor("Function (semantic)", LyngHighlighterColors.FUNCTION),
|
AttributesDescriptor("Function (semantic)", LyngHighlighterColors.FUNCTION),
|
||||||
|
|||||||
@@ -82,4 +82,9 @@ object LyngHighlighterColors {
|
|||||||
val ENUM_CONSTANT: TextAttributesKey = TextAttributesKey.createTextAttributesKey(
|
val ENUM_CONSTANT: TextAttributesKey = TextAttributesKey.createTextAttributesKey(
|
||||||
"LYNG_ENUM_CONSTANT", DefaultLanguageHighlighterColors.STATIC_FIELD
|
"LYNG_ENUM_CONSTANT", DefaultLanguageHighlighterColors.STATIC_FIELD
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Labels (label@ or @label used as exit target)
|
||||||
|
val LABEL: TextAttributesKey = TextAttributesKey.createTextAttributesKey(
|
||||||
|
"LYNG_LABEL", DefaultLanguageHighlighterColors.LABEL
|
||||||
|
)
|
||||||
}
|
}
|
||||||
@@ -32,10 +32,11 @@ class LyngLexer : LexerBase() {
|
|||||||
private var myTokenType: IElementType? = null
|
private var myTokenType: IElementType? = null
|
||||||
|
|
||||||
private val keywords = setOf(
|
private val keywords = setOf(
|
||||||
"fun", "val", "var", "class", "type", "import", "as",
|
"fun", "val", "var", "class", "interface", "type", "import", "as",
|
||||||
|
"abstract", "closed", "override", "static", "extern", "open", "private", "protected",
|
||||||
"if", "else", "for", "while", "return", "true", "false", "null",
|
"if", "else", "for", "while", "return", "true", "false", "null",
|
||||||
"when", "in", "is", "break", "continue", "try", "catch", "finally",
|
"when", "in", "is", "break", "continue", "try", "catch", "finally",
|
||||||
"get", "set"
|
"get", "set", "object", "enum", "init", "by", "property", "constructor"
|
||||||
)
|
)
|
||||||
|
|
||||||
override fun start(buffer: CharSequence, startOffset: Int, endOffset: Int, initialState: Int) {
|
override fun start(buffer: CharSequence, startOffset: Int, endOffset: Int, initialState: Int) {
|
||||||
@@ -132,10 +133,24 @@ class LyngLexer : LexerBase() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Identifier / keyword
|
// Labels / Annotations: @label or label@
|
||||||
|
if (ch == '@') {
|
||||||
|
i++
|
||||||
|
while (i < endOffset && (buffer[i].isIdentifierPart())) i++
|
||||||
|
myTokenEnd = i
|
||||||
|
myTokenType = LyngTokenTypes.LABEL
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
if (ch.isIdentifierStart()) {
|
if (ch.isIdentifierStart()) {
|
||||||
i++
|
i++
|
||||||
while (i < endOffset && buffer[i].isIdentifierPart()) i++
|
while (i < endOffset && buffer[i].isIdentifierPart()) i++
|
||||||
|
if (i < endOffset && buffer[i] == '@') {
|
||||||
|
i++
|
||||||
|
myTokenEnd = i
|
||||||
|
myTokenType = LyngTokenTypes.LABEL
|
||||||
|
return
|
||||||
|
}
|
||||||
myTokenEnd = i
|
myTokenEnd = i
|
||||||
val text = buffer.subSequence(myTokenStart, myTokenEnd).toString()
|
val text = buffer.subSequence(myTokenStart, myTokenEnd).toString()
|
||||||
myTokenType = if (text in keywords) LyngTokenTypes.KEYWORD else LyngTokenTypes.IDENTIFIER
|
myTokenType = if (text in keywords) LyngTokenTypes.KEYWORD else LyngTokenTypes.IDENTIFIER
|
||||||
@@ -159,5 +174,5 @@ class LyngLexer : LexerBase() {
|
|||||||
private fun Char.isDigit(): Boolean = this in '0'..'9'
|
private fun Char.isDigit(): Boolean = this in '0'..'9'
|
||||||
private fun Char.isIdentifierStart(): Boolean = this == '_' || this.isLetter()
|
private fun Char.isIdentifierStart(): Boolean = this == '_' || this.isLetter()
|
||||||
private fun Char.isIdentifierPart(): Boolean = this.isIdentifierStart() || this.isDigit()
|
private fun Char.isIdentifierPart(): Boolean = this.isIdentifierStart() || this.isDigit()
|
||||||
private fun isPunct(c: Char): Boolean = c in setOf('(', ')', '{', '}', '[', ']', '.', ',', ';', ':', '+', '-', '*', '/', '%', '=', '<', '>', '!', '?', '&', '|', '^', '~')
|
private fun isPunct(c: Char): Boolean = c in setOf('(', ')', '{', '}', '[', ']', '.', ',', ';', ':', '+', '-', '*', '/', '%', '=', '<', '>', '!', '?', '&', '|', '^', '~', '@')
|
||||||
}
|
}
|
||||||
@@ -33,6 +33,7 @@ class LyngSyntaxHighlighter : SyntaxHighlighter {
|
|||||||
LyngTokenTypes.BLOCK_COMMENT -> pack(LyngHighlighterColors.BLOCK_COMMENT)
|
LyngTokenTypes.BLOCK_COMMENT -> pack(LyngHighlighterColors.BLOCK_COMMENT)
|
||||||
LyngTokenTypes.PUNCT -> pack(LyngHighlighterColors.PUNCT)
|
LyngTokenTypes.PUNCT -> pack(LyngHighlighterColors.PUNCT)
|
||||||
LyngTokenTypes.IDENTIFIER -> pack(LyngHighlighterColors.IDENTIFIER)
|
LyngTokenTypes.IDENTIFIER -> pack(LyngHighlighterColors.IDENTIFIER)
|
||||||
|
LyngTokenTypes.LABEL -> pack(LyngHighlighterColors.LABEL)
|
||||||
else -> emptyArray()
|
else -> emptyArray()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ object LyngTokenTypes {
|
|||||||
val NUMBER = LyngTokenType("NUMBER")
|
val NUMBER = LyngTokenType("NUMBER")
|
||||||
val KEYWORD = LyngTokenType("KEYWORD")
|
val KEYWORD = LyngTokenType("KEYWORD")
|
||||||
val IDENTIFIER = LyngTokenType("IDENTIFIER")
|
val IDENTIFIER = LyngTokenType("IDENTIFIER")
|
||||||
|
val LABEL = LyngTokenType("LABEL")
|
||||||
val PUNCT = LyngTokenType("PUNCT")
|
val PUNCT = LyngTokenType("PUNCT")
|
||||||
val BAD_CHAR = LyngTokenType("BAD_CHAR")
|
val BAD_CHAR = LyngTokenType("BAD_CHAR")
|
||||||
}
|
}
|
||||||
+13
-14
@@ -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.
|
||||||
@@ -20,7 +20,6 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
|
||||||
import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
|
||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
plugins {
|
plugins {
|
||||||
@@ -53,11 +52,11 @@ kotlin {
|
|||||||
browser()
|
browser()
|
||||||
nodejs()
|
nodejs()
|
||||||
}
|
}
|
||||||
@OptIn(ExperimentalWasmDsl::class)
|
// @OptIn(ExperimentalWasmDsl::class)
|
||||||
wasmJs() {
|
// wasmJs() {
|
||||||
browser()
|
// browser()
|
||||||
nodejs()
|
// nodejs()
|
||||||
}
|
// }
|
||||||
|
|
||||||
// Keep expect/actual warning suppressed consistently with other modules
|
// Keep expect/actual warning suppressed consistently with other modules
|
||||||
targets.configureEach {
|
targets.configureEach {
|
||||||
@@ -94,13 +93,13 @@ kotlin {
|
|||||||
implementation("com.squareup.okio:okio-nodefilesystem:${libs.versions.okioVersion.get()}")
|
implementation("com.squareup.okio:okio-nodefilesystem:${libs.versions.okioVersion.get()}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// For Wasm we use in-memory VFS for now
|
// // For Wasm we use in-memory VFS for now
|
||||||
val wasmJsMain by getting {
|
// val wasmJsMain by getting {
|
||||||
dependencies {
|
// dependencies {
|
||||||
api(libs.okio)
|
// api(libs.okio)
|
||||||
implementation(libs.okio.fakefilesystem)
|
// implementation(libs.okio.fakefilesystem)
|
||||||
}
|
// }
|
||||||
}
|
// }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
actual fun getPlatformDetails(): PlatformDetails {
|
||||||
|
return PlatformDetails(
|
||||||
|
name = "Android",
|
||||||
|
version = android.os.Build.VERSION.RELEASE,
|
||||||
|
arch = android.os.Build.SUPPORTED_ABIS.firstOrNull() ?: "unknown",
|
||||||
|
kernelVersion = System.getProperty("os.version")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual fun isProcessSupported(): Boolean = false
|
||||||
|
|
||||||
|
actual fun getSystemProcessRunner(): LyngProcessRunner {
|
||||||
|
throw UnsupportedOperationException("Processes are not supported on Android yet")
|
||||||
|
}
|
||||||
@@ -0,0 +1,234 @@
|
|||||||
|
/*
|
||||||
|
* 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.process
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import net.sergeych.lyng.ModuleScope
|
||||||
|
import net.sergeych.lyng.Scope
|
||||||
|
import net.sergeych.lyng.miniast.*
|
||||||
|
import net.sergeych.lyng.obj.*
|
||||||
|
import net.sergeych.lyng.pacman.ImportManager
|
||||||
|
import net.sergeych.lyng.statement
|
||||||
|
import net.sergeych.lyngio.process.*
|
||||||
|
import net.sergeych.lyngio.process.security.ProcessAccessDeniedException
|
||||||
|
import net.sergeych.lyngio.process.security.ProcessAccessPolicy
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Install Lyng module `lyng.io.process` into the given scope's ImportManager.
|
||||||
|
*/
|
||||||
|
fun createProcessModule(policy: ProcessAccessPolicy, scope: Scope): Boolean =
|
||||||
|
createProcessModule(policy, scope.importManager)
|
||||||
|
|
||||||
|
/** Same as [createProcessModule] but with explicit [ImportManager]. */
|
||||||
|
fun createProcessModule(policy: ProcessAccessPolicy, manager: ImportManager): Boolean {
|
||||||
|
val name = "lyng.io.process"
|
||||||
|
if (manager.packageNames.contains(name)) return false
|
||||||
|
|
||||||
|
manager.addPackage(name) { module ->
|
||||||
|
buildProcessModule(module, policy)
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun buildProcessModule(module: ModuleScope, policy: ProcessAccessPolicy) {
|
||||||
|
val runner = try {
|
||||||
|
SecuredLyngProcessRunner(getSystemProcessRunner(), policy)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
val runningProcessType = object : ObjClass("RunningProcess") {}
|
||||||
|
|
||||||
|
runningProcessType.apply {
|
||||||
|
addFnDoc(
|
||||||
|
name = "stdout",
|
||||||
|
doc = "Get standard output stream as a Flow of lines.",
|
||||||
|
returns = type("lyng.Flow"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
val self = thisAs<ObjRunningProcess>()
|
||||||
|
self.process.stdout.toLyngFlow(this)
|
||||||
|
}
|
||||||
|
addFnDoc(
|
||||||
|
name = "stderr",
|
||||||
|
doc = "Get standard error stream as a Flow of lines.",
|
||||||
|
returns = type("lyng.Flow"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
val self = thisAs<ObjRunningProcess>()
|
||||||
|
self.process.stderr.toLyngFlow(this)
|
||||||
|
}
|
||||||
|
addFnDoc(
|
||||||
|
name = "signal",
|
||||||
|
doc = "Send a signal to the process (e.g. 'SIGINT', 'SIGTERM', 'SIGKILL').",
|
||||||
|
params = listOf(ParamDoc("signal", type("lyng.String"))),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
processGuard {
|
||||||
|
val sigStr = requireOnlyArg<ObjString>().value.uppercase()
|
||||||
|
val sig = try {
|
||||||
|
ProcessSignal.valueOf(sigStr)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
try {
|
||||||
|
ProcessSignal.valueOf("SIG$sigStr")
|
||||||
|
} catch (e2: Exception) {
|
||||||
|
raiseIllegalArgument("Unknown signal: $sigStr")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
thisAs<ObjRunningProcess>().process.sendSignal(sig)
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addFnDoc(
|
||||||
|
name = "waitFor",
|
||||||
|
doc = "Wait for the process to exit and return its exit code.",
|
||||||
|
returns = type("lyng.Int"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
processGuard {
|
||||||
|
thisAs<ObjRunningProcess>().process.waitFor().toObj()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addFnDoc(
|
||||||
|
name = "destroy",
|
||||||
|
doc = "Forcefully terminate the process.",
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
thisAs<ObjRunningProcess>().process.destroy()
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val processType = object : ObjClass("Process") {}
|
||||||
|
|
||||||
|
processType.apply {
|
||||||
|
addClassFnDoc(
|
||||||
|
name = "execute",
|
||||||
|
doc = "Execute a process with arguments.",
|
||||||
|
params = listOf(ParamDoc("executable", type("lyng.String")), ParamDoc("args", type("lyng.List"))),
|
||||||
|
returns = type("RunningProcess"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
if (runner == null) raiseError("Processes are not supported on this platform")
|
||||||
|
processGuard {
|
||||||
|
val executable = requiredArg<ObjString>(0).value
|
||||||
|
val args = requiredArg<ObjList>(1).list.map { it.toString() }
|
||||||
|
val lp = runner.execute(executable, args)
|
||||||
|
ObjRunningProcess(runningProcessType, lp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
addClassFnDoc(
|
||||||
|
name = "shell",
|
||||||
|
doc = "Execute a command via system shell.",
|
||||||
|
params = listOf(ParamDoc("command", type("lyng.String"))),
|
||||||
|
returns = type("RunningProcess"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
if (runner == null) raiseError("Processes are not supported on this platform")
|
||||||
|
processGuard {
|
||||||
|
val command = requireOnlyArg<ObjString>().value
|
||||||
|
val lp = runner.shell(command)
|
||||||
|
ObjRunningProcess(runningProcessType, lp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val platformType = object : ObjClass("Platform") {}
|
||||||
|
|
||||||
|
platformType.apply {
|
||||||
|
addClassFnDoc(
|
||||||
|
name = "details",
|
||||||
|
doc = "Get platform core details.",
|
||||||
|
returns = type("lyng.Map"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
val d = getPlatformDetails()
|
||||||
|
ObjMap(mutableMapOf(
|
||||||
|
ObjString("name") to ObjString(d.name),
|
||||||
|
ObjString("version") to ObjString(d.version),
|
||||||
|
ObjString("arch") to ObjString(d.arch),
|
||||||
|
ObjString("kernelVersion") to (d.kernelVersion?.toObj() ?: ObjNull)
|
||||||
|
))
|
||||||
|
}
|
||||||
|
addClassFnDoc(
|
||||||
|
name = "isSupported",
|
||||||
|
doc = "Check if processes are supported on this platform.",
|
||||||
|
returns = type("lyng.Bool"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
) {
|
||||||
|
isProcessSupported().toObj()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.addConstDoc(
|
||||||
|
name = "Process",
|
||||||
|
value = processType,
|
||||||
|
doc = "Process execution and control.",
|
||||||
|
type = type("Process"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
)
|
||||||
|
module.addConstDoc(
|
||||||
|
name = "Platform",
|
||||||
|
value = platformType,
|
||||||
|
doc = "Platform information.",
|
||||||
|
type = type("Platform"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
)
|
||||||
|
module.addConstDoc(
|
||||||
|
name = "RunningProcess",
|
||||||
|
value = runningProcessType,
|
||||||
|
doc = "Handle to a running process.",
|
||||||
|
type = type("RunningProcess"),
|
||||||
|
moduleName = module.packageName
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
class ObjRunningProcess(
|
||||||
|
override val objClass: ObjClass,
|
||||||
|
val process: LyngProcess
|
||||||
|
) : Obj() {
|
||||||
|
override fun toString(): String = "RunningProcess($process)"
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend inline fun Scope.processGuard(crossinline block: suspend () -> Obj): Obj {
|
||||||
|
return try {
|
||||||
|
block()
|
||||||
|
} catch (e: ProcessAccessDeniedException) {
|
||||||
|
raiseError(ObjIllegalOperationException(this, e.reasonDetail ?: "process access denied"))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
raiseError(ObjIllegalOperationException(this, e.message ?: "process error"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Flow<String>.toLyngFlow(flowScope: Scope): ObjFlow {
|
||||||
|
val producer = statement {
|
||||||
|
val builder = (this as? net.sergeych.lyng.ClosureScope)?.callScope?.thisObj as? ObjFlowBuilder
|
||||||
|
?: this.thisObj as? ObjFlowBuilder
|
||||||
|
|
||||||
|
this@toLyngFlow.collect {
|
||||||
|
try {
|
||||||
|
builder?.output?.send(ObjString(it))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// Channel closed or other error, stop collecting
|
||||||
|
return@collect
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ObjVoid
|
||||||
|
}
|
||||||
|
return ObjFlow(producer, flowScope)
|
||||||
|
}
|
||||||
@@ -1,3 +1,20 @@
|
|||||||
|
/*
|
||||||
|
* 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.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Filesystem module builtin docs registration, located in lyngio so core library
|
* Filesystem module builtin docs registration, located in lyngio so core library
|
||||||
* does not depend on external packages. The IDEA plugin (and any other tooling)
|
* does not depend on external packages. The IDEA plugin (and any other tooling)
|
||||||
|
|||||||
@@ -0,0 +1,93 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import net.sergeych.lyngio.process.security.ProcessAccessOp
|
||||||
|
import net.sergeych.lyngio.process.security.ProcessAccessPolicy
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Common signals for process control.
|
||||||
|
*/
|
||||||
|
enum class ProcessSignal {
|
||||||
|
SIGINT, SIGTERM, SIGKILL
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Multiplatform process representation.
|
||||||
|
*/
|
||||||
|
interface LyngProcess {
|
||||||
|
/**
|
||||||
|
* Standard output stream as a flow of strings (lines).
|
||||||
|
*/
|
||||||
|
val stdout: Flow<String>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Standard error stream as a flow of strings (lines).
|
||||||
|
*/
|
||||||
|
val stderr: Flow<String>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a signal to the process.
|
||||||
|
* Throws exception if signals are not supported on the platform or for this process.
|
||||||
|
*/
|
||||||
|
suspend fun sendSignal(signal: ProcessSignal)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wait for the process to exit and return the exit code.
|
||||||
|
*/
|
||||||
|
suspend fun waitFor(): Int
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Forcefully terminate the process.
|
||||||
|
*/
|
||||||
|
fun destroy()
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for running processes.
|
||||||
|
*/
|
||||||
|
interface LyngProcessRunner {
|
||||||
|
/**
|
||||||
|
* Execute a process with the given executable and arguments.
|
||||||
|
*/
|
||||||
|
suspend fun execute(executable: String, args: List<String>): LyngProcess
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a command via the platform's default shell.
|
||||||
|
*/
|
||||||
|
suspend fun shell(command: String): LyngProcess
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Secured implementation of [LyngProcessRunner] that checks against a [ProcessAccessPolicy].
|
||||||
|
*/
|
||||||
|
class SecuredLyngProcessRunner(
|
||||||
|
private val runner: LyngProcessRunner,
|
||||||
|
private val policy: ProcessAccessPolicy
|
||||||
|
) : LyngProcessRunner {
|
||||||
|
override suspend fun execute(executable: String, args: List<String>): LyngProcess {
|
||||||
|
policy.require(ProcessAccessOp.Execute(executable, args))
|
||||||
|
return runner.execute(executable, args)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun shell(command: String): LyngProcess {
|
||||||
|
policy.require(ProcessAccessOp.Shell(command))
|
||||||
|
return runner.shell(command)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Platform core details.
|
||||||
|
*/
|
||||||
|
data class PlatformDetails(
|
||||||
|
val name: String,
|
||||||
|
val version: String,
|
||||||
|
val arch: String,
|
||||||
|
val kernelVersion: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the current platform core details.
|
||||||
|
*/
|
||||||
|
expect fun getPlatformDetails(): PlatformDetails
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether the current platform supports processes and shell execution.
|
||||||
|
*/
|
||||||
|
expect fun isProcessSupported(): Boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the system default [LyngProcessRunner].
|
||||||
|
* Throws [UnsupportedOperationException] if processes are not supported on this platform.
|
||||||
|
*/
|
||||||
|
expect fun getSystemProcessRunner(): LyngProcessRunner
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process.security
|
||||||
|
|
||||||
|
import net.sergeych.lyngio.fs.security.AccessContext
|
||||||
|
import net.sergeych.lyngio.fs.security.AccessDecision
|
||||||
|
import net.sergeych.lyngio.fs.security.Decision
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Primitive process operations for access control decisions.
|
||||||
|
*/
|
||||||
|
sealed interface ProcessAccessOp {
|
||||||
|
data class Execute(val executable: String, val args: List<String>) : ProcessAccessOp
|
||||||
|
data class Shell(val command: String) : ProcessAccessOp
|
||||||
|
}
|
||||||
|
|
||||||
|
class ProcessAccessDeniedException(
|
||||||
|
val op: ProcessAccessOp,
|
||||||
|
val reasonDetail: String? = null,
|
||||||
|
) : IllegalStateException("Process access denied for $op" + (reasonDetail?.let { ": $it" } ?: ""))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Policy interface that decides whether a specific process operation is allowed.
|
||||||
|
*/
|
||||||
|
interface ProcessAccessPolicy {
|
||||||
|
suspend fun check(op: ProcessAccessOp, ctx: AccessContext = AccessContext()): AccessDecision
|
||||||
|
|
||||||
|
// Convenience helpers
|
||||||
|
suspend fun require(op: ProcessAccessOp, ctx: AccessContext = AccessContext()) {
|
||||||
|
val res = check(op, ctx)
|
||||||
|
if (!res.isAllowed()) throw ProcessAccessDeniedException(op, res.reason)
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun canExecute(executable: String, args: List<String>, ctx: AccessContext = AccessContext()) =
|
||||||
|
check(ProcessAccessOp.Execute(executable, args), ctx).isAllowed()
|
||||||
|
|
||||||
|
suspend fun canShell(command: String, ctx: AccessContext = AccessContext()) =
|
||||||
|
check(ProcessAccessOp.Shell(command), ctx).isAllowed()
|
||||||
|
}
|
||||||
|
|
||||||
|
object PermitAllProcessAccessPolicy : ProcessAccessPolicy {
|
||||||
|
override suspend fun check(op: ProcessAccessOp, ctx: AccessContext): AccessDecision =
|
||||||
|
AccessDecision(Decision.Allow)
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
internal actual fun getNativeKernelVersion(): String? = null
|
||||||
|
|
||||||
|
internal actual fun isNativeProcessSupported(): Boolean = false
|
||||||
|
|
||||||
|
internal actual fun getNativeProcessRunner(): LyngProcessRunner {
|
||||||
|
throw UnsupportedOperationException("Processes are not supported on iOS")
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
actual fun getPlatformDetails(): PlatformDetails {
|
||||||
|
return PlatformDetails(
|
||||||
|
name = "JavaScript",
|
||||||
|
version = "unknown",
|
||||||
|
arch = "unknown"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual fun isProcessSupported(): Boolean = false
|
||||||
|
|
||||||
|
actual fun getSystemProcessRunner(): LyngProcessRunner {
|
||||||
|
throw UnsupportedOperationException("Processes are not supported on JS")
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
|
||||||
|
package net.sergeych.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
|
||||||
|
actual fun getPlatformDetails(): PlatformDetails {
|
||||||
|
val osName = System.getProperty("os.name")
|
||||||
|
return PlatformDetails(
|
||||||
|
name = osName,
|
||||||
|
version = System.getProperty("os.version"),
|
||||||
|
arch = System.getProperty("os.arch"),
|
||||||
|
kernelVersion = if (osName.lowercase().contains("linux")) {
|
||||||
|
System.getProperty("os.version")
|
||||||
|
} else null
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
actual fun isProcessSupported(): Boolean = true
|
||||||
|
|
||||||
|
actual fun getSystemProcessRunner(): LyngProcessRunner = JvmProcessRunner
|
||||||
|
|
||||||
|
object JvmProcessRunner : LyngProcessRunner {
|
||||||
|
override suspend fun execute(executable: String, args: List<String>): LyngProcess {
|
||||||
|
val process = ProcessBuilder(listOf(executable) + args)
|
||||||
|
.start()
|
||||||
|
return JvmLyngProcess(process)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun shell(command: String): LyngProcess {
|
||||||
|
val os = System.getProperty("os.name").lowercase()
|
||||||
|
val shellCmd = if (os.contains("win")) {
|
||||||
|
listOf("cmd.exe", "/c", command)
|
||||||
|
} else {
|
||||||
|
listOf("sh", "-c", command)
|
||||||
|
}
|
||||||
|
val process = ProcessBuilder(shellCmd)
|
||||||
|
.start()
|
||||||
|
return JvmLyngProcess(process)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class JvmLyngProcess(private val process: Process) : LyngProcess {
|
||||||
|
override val stdout: Flow<String> = flow {
|
||||||
|
val reader = process.inputStream.bufferedReader()
|
||||||
|
while (true) {
|
||||||
|
val line = reader.readLine() ?: break
|
||||||
|
emit(line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override val stderr: Flow<String> = flow {
|
||||||
|
val reader = process.errorStream.bufferedReader()
|
||||||
|
while (true) {
|
||||||
|
val line = reader.readLine() ?: break
|
||||||
|
emit(line)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun sendSignal(signal: ProcessSignal) {
|
||||||
|
when (signal) {
|
||||||
|
ProcessSignal.SIGINT -> {
|
||||||
|
// SIGINT is hard on JVM without native calls or external 'kill'
|
||||||
|
val os = System.getProperty("os.name").lowercase()
|
||||||
|
if (os.contains("win")) {
|
||||||
|
throw UnsupportedOperationException("SIGINT not supported on Windows JVM")
|
||||||
|
} else {
|
||||||
|
// Try to use kill -2 <pid>
|
||||||
|
try {
|
||||||
|
val pid = process.pid()
|
||||||
|
Runtime.getRuntime().exec(arrayOf("kill", "-2", pid.toString())).waitFor()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
throw UnsupportedOperationException("Failed to send SIGINT: ${e.message}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ProcessSignal.SIGTERM -> process.destroy()
|
||||||
|
ProcessSignal.SIGKILL -> process.destroyForcibly()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun waitFor(): Int = withContext(Dispatchers.IO) {
|
||||||
|
process.waitFor()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun destroy() {
|
||||||
|
process.destroy()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/*
|
||||||
|
* 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.process
|
||||||
|
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import net.sergeych.lyng.Compiler
|
||||||
|
import net.sergeych.lyng.Script
|
||||||
|
import net.sergeych.lyngio.process.security.PermitAllProcessAccessPolicy
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class LyngProcessModuleTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLyngProcess() = runBlocking {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||||
|
|
||||||
|
val code = """
|
||||||
|
import lyng.io.process
|
||||||
|
|
||||||
|
var p = Process.execute("echo", ["hello", "lyng"])
|
||||||
|
var output = []
|
||||||
|
for (line in p.stdout()) {
|
||||||
|
output.add(line)
|
||||||
|
}
|
||||||
|
p.waitFor()
|
||||||
|
output
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val script = Compiler.compile(code)
|
||||||
|
val result = script.execute(scope)
|
||||||
|
assertTrue(result.inspect(scope).contains("hello lyng"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLyngShell() = runBlocking {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||||
|
|
||||||
|
val code = """
|
||||||
|
import lyng.io.process
|
||||||
|
|
||||||
|
var p = Process.shell("echo 'shell lyng'")
|
||||||
|
var output = ""
|
||||||
|
for (line in p.stdout()) {
|
||||||
|
output = output + line
|
||||||
|
}
|
||||||
|
p.waitFor()
|
||||||
|
output
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val script = Compiler.compile(code)
|
||||||
|
val result = script.execute(scope)
|
||||||
|
assertTrue(result.inspect(scope).contains("shell lyng"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPlatformDetails() = runBlocking {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||||
|
|
||||||
|
val code = """
|
||||||
|
import lyng.io.process
|
||||||
|
Platform.details()
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val script = Compiler.compile(code)
|
||||||
|
val result = script.execute(scope)
|
||||||
|
assertTrue(result.inspect(scope).contains("name"), "Result should contain 'name', but was: ${result.inspect(scope)}")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.toList
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import net.sergeych.lyngio.process.security.PermitAllProcessAccessPolicy
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class JvmProcessTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testExecute() = runBlocking {
|
||||||
|
val runner = getSystemProcessRunner()
|
||||||
|
val secured = SecuredLyngProcessRunner(runner, PermitAllProcessAccessPolicy)
|
||||||
|
|
||||||
|
val process = secured.execute("echo", listOf("hello", "world"))
|
||||||
|
val output = process.stdout.toList()
|
||||||
|
assertEquals(listOf("hello world"), output)
|
||||||
|
assertEquals(0, process.waitFor())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testShell() = runBlocking {
|
||||||
|
val runner = getSystemProcessRunner()
|
||||||
|
val secured = SecuredLyngProcessRunner(runner, PermitAllProcessAccessPolicy)
|
||||||
|
|
||||||
|
val process = secured.shell("echo 'hello shell'")
|
||||||
|
val output = process.stdout.toList()
|
||||||
|
assertEquals(listOf("hello shell"), output)
|
||||||
|
assertEquals(0, process.waitFor())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPlatformDetails() {
|
||||||
|
val details = getPlatformDetails()
|
||||||
|
assertTrue(details.name.isNotEmpty())
|
||||||
|
assertTrue(isProcessSupported())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.cinterop.*
|
||||||
|
import platform.posix.*
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
internal actual fun getNativeKernelVersion(): String? {
|
||||||
|
return memScoped {
|
||||||
|
val u = alloc<utsname>()
|
||||||
|
if (uname(u.ptr) == 0) {
|
||||||
|
u.release.toKString()
|
||||||
|
} else null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal actual fun isNativeProcessSupported(): Boolean = true
|
||||||
|
|
||||||
|
internal actual fun getNativeProcessRunner(): LyngProcessRunner = PosixProcessRunner
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.cinterop.*
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import kotlinx.coroutines.flow.flowOn
|
||||||
|
import platform.posix.*
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
internal class NativeLyngProcess(
|
||||||
|
private val pid: pid_t,
|
||||||
|
private val stdoutFd: Int,
|
||||||
|
private val stderrFd: Int
|
||||||
|
) : LyngProcess {
|
||||||
|
override val stdout: Flow<String> = createPipeFlow(stdoutFd)
|
||||||
|
override val stderr: Flow<String> = createPipeFlow(stderrFd)
|
||||||
|
|
||||||
|
override suspend fun sendSignal(signal: ProcessSignal) {
|
||||||
|
val sig = when (signal) {
|
||||||
|
ProcessSignal.SIGINT -> SIGINT
|
||||||
|
ProcessSignal.SIGTERM -> SIGTERM
|
||||||
|
ProcessSignal.SIGKILL -> SIGKILL
|
||||||
|
}
|
||||||
|
if (kill(pid, sig) != 0) {
|
||||||
|
throw RuntimeException("Failed to send signal $signal to process $pid: ${strerror(errno)?.toKString()}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun waitFor(): Int = withContext(Dispatchers.Default) {
|
||||||
|
memScoped {
|
||||||
|
val status = alloc<IntVar>()
|
||||||
|
if (waitpid(pid, status.ptr, 0) == -1) {
|
||||||
|
throw RuntimeException("Failed to wait for process $pid: ${strerror(errno)?.toKString()}")
|
||||||
|
}
|
||||||
|
val s = status.value
|
||||||
|
if ((s and 0x7f) == 0) (s shr 8) and 0xff else -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun destroy() {
|
||||||
|
kill(pid, SIGKILL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
private fun createPipeFlow(fd: Int): Flow<String> = flow {
|
||||||
|
val buffer = ByteArray(4096)
|
||||||
|
val lineBuffer = StringBuilder()
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
val bytesRead = buffer.usePinned { pinned ->
|
||||||
|
read(fd, pinned.addressOf(0), buffer.size.toULong())
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytesRead <= 0L) break
|
||||||
|
|
||||||
|
val text = buffer.decodeToString(endIndex = bytesRead.toInt())
|
||||||
|
lineBuffer.append(text)
|
||||||
|
|
||||||
|
var newlineIdx = lineBuffer.indexOf('\n')
|
||||||
|
while (newlineIdx != -1) {
|
||||||
|
val line = lineBuffer.substring(0, newlineIdx)
|
||||||
|
emit(line)
|
||||||
|
lineBuffer.deleteRange(0, newlineIdx + 1)
|
||||||
|
newlineIdx = lineBuffer.indexOf('\n')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (lineBuffer.isNotEmpty()) {
|
||||||
|
emit(lineBuffer.toString())
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
close(fd)
|
||||||
|
}
|
||||||
|
}.flowOn(Dispatchers.Default)
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
object PosixProcessRunner : LyngProcessRunner {
|
||||||
|
override suspend fun execute(executable: String, args: List<String>): LyngProcess = withContext(Dispatchers.Default) {
|
||||||
|
memScoped {
|
||||||
|
val pipeStdout = allocArray<IntVar>(2)
|
||||||
|
val pipeStderr = allocArray<IntVar>(2)
|
||||||
|
|
||||||
|
if (pipe(pipeStdout) != 0) throw RuntimeException("Failed to create stdout pipe")
|
||||||
|
if (pipe(pipeStderr) != 0) {
|
||||||
|
close(pipeStdout[0])
|
||||||
|
close(pipeStdout[1])
|
||||||
|
throw RuntimeException("Failed to create stderr pipe")
|
||||||
|
}
|
||||||
|
|
||||||
|
val pid = fork()
|
||||||
|
if (pid == -1) {
|
||||||
|
close(pipeStdout[0])
|
||||||
|
close(pipeStdout[1])
|
||||||
|
close(pipeStderr[0])
|
||||||
|
close(pipeStderr[1])
|
||||||
|
throw RuntimeException("Failed to fork: ${strerror(errno)?.toKString()}")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pid == 0) {
|
||||||
|
// Child process
|
||||||
|
dup2(pipeStdout[1], 1)
|
||||||
|
dup2(pipeStderr[1], 2)
|
||||||
|
|
||||||
|
close(pipeStdout[0])
|
||||||
|
close(pipeStdout[1])
|
||||||
|
close(pipeStderr[0])
|
||||||
|
close(pipeStderr[1])
|
||||||
|
|
||||||
|
val argv = allocArray<CPointerVar<ByteVar>>(args.size + 2)
|
||||||
|
argv[0] = executable.cstr.ptr
|
||||||
|
for (i in args.indices) {
|
||||||
|
argv[i + 1] = args[i].cstr.ptr
|
||||||
|
}
|
||||||
|
argv[args.size + 1] = null
|
||||||
|
|
||||||
|
execvp(executable, argv)
|
||||||
|
|
||||||
|
// If we are here, exec failed
|
||||||
|
_exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parent process
|
||||||
|
close(pipeStdout[1])
|
||||||
|
close(pipeStderr[1])
|
||||||
|
|
||||||
|
NativeLyngProcess(pid, pipeStdout[0], pipeStderr[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun shell(command: String): LyngProcess {
|
||||||
|
return execute("/bin/sh", listOf("-c", command))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.coroutines.flow.toList
|
||||||
|
import kotlinx.coroutines.runBlocking
|
||||||
|
import net.sergeych.lyng.Compiler
|
||||||
|
import net.sergeych.lyng.Script
|
||||||
|
import net.sergeych.lyng.io.process.createProcessModule
|
||||||
|
import net.sergeych.lyngio.process.security.PermitAllProcessAccessPolicy
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
|
class LinuxProcessTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testExecuteEcho() = runBlocking {
|
||||||
|
val process = PosixProcessRunner.execute("echo", listOf("hello", "native"))
|
||||||
|
val stdout = process.stdout.toList()
|
||||||
|
val exitCode = process.waitFor()
|
||||||
|
|
||||||
|
assertEquals(0, exitCode)
|
||||||
|
assertEquals(listOf("hello native"), stdout)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testShellCommand() = runBlocking {
|
||||||
|
val process = PosixProcessRunner.shell("echo 'shell native' && printf 'line2'")
|
||||||
|
val stdout = process.stdout.toList()
|
||||||
|
val exitCode = process.waitFor()
|
||||||
|
|
||||||
|
assertEquals(0, exitCode)
|
||||||
|
assertEquals(listOf("shell native", "line2"), stdout)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStderrCapture() = runBlocking {
|
||||||
|
val process = PosixProcessRunner.shell("echo 'to stdout'; echo 'to stderr' >&2")
|
||||||
|
val stdout = process.stdout.toList()
|
||||||
|
val stderr = process.stderr.toList()
|
||||||
|
process.waitFor()
|
||||||
|
|
||||||
|
assertEquals(listOf("to stdout"), stdout)
|
||||||
|
assertEquals(listOf("to stderr"), stderr)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPlatformDetails() {
|
||||||
|
val details = getPlatformDetails()
|
||||||
|
assertEquals("LINUX", details.name)
|
||||||
|
assertTrue(details.kernelVersion != null)
|
||||||
|
assertTrue(details.kernelVersion!!.isNotEmpty())
|
||||||
|
println("Linux Native Details: $details")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLyngModuleNative() = runBlocking {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
createProcessModule(PermitAllProcessAccessPolicy, scope)
|
||||||
|
|
||||||
|
val code = """
|
||||||
|
import lyng.io.process
|
||||||
|
|
||||||
|
var p = Process.execute("echo", ["hello", "lyng", "native"])
|
||||||
|
var output = []
|
||||||
|
for (line in p.stdout()) {
|
||||||
|
output.add(line)
|
||||||
|
}
|
||||||
|
p.waitFor()
|
||||||
|
println(output)
|
||||||
|
assertEquals("hello lyng native", output.joinToString(" "))
|
||||||
|
output
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val script = Compiler.compile(code)
|
||||||
|
val result = script.execute(scope)
|
||||||
|
assertTrue(result.inspect(scope).contains("hello lyng native"))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.cinterop.*
|
||||||
|
import platform.posix.*
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
internal actual fun getNativeKernelVersion(): String? {
|
||||||
|
return memScoped {
|
||||||
|
val u = alloc<utsname>()
|
||||||
|
if (uname(u.ptr) == 0) {
|
||||||
|
u.release.toKString()
|
||||||
|
} else null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal actual fun isNativeProcessSupported(): Boolean = true
|
||||||
|
|
||||||
|
internal actual fun getNativeProcessRunner(): LyngProcessRunner = PosixProcessRunner
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlinx.cinterop.*
|
||||||
|
import kotlinx.coroutines.*
|
||||||
|
import kotlinx.coroutines.flow.Flow
|
||||||
|
import kotlinx.coroutines.flow.flow
|
||||||
|
import kotlinx.coroutines.flow.flowOn
|
||||||
|
import platform.posix.*
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
internal class NativeLyngProcess(
|
||||||
|
private val pid: pid_t,
|
||||||
|
private val stdoutFd: Int,
|
||||||
|
private val stderrFd: Int
|
||||||
|
) : LyngProcess {
|
||||||
|
override val stdout: Flow<String> = createPipeFlow(stdoutFd)
|
||||||
|
override val stderr: Flow<String> = createPipeFlow(stderrFd)
|
||||||
|
|
||||||
|
override suspend fun sendSignal(signal: ProcessSignal) {
|
||||||
|
val sig = when (signal) {
|
||||||
|
ProcessSignal.SIGINT -> SIGINT
|
||||||
|
ProcessSignal.SIGTERM -> SIGTERM
|
||||||
|
ProcessSignal.SIGKILL -> SIGKILL
|
||||||
|
}
|
||||||
|
if (kill(pid, sig) != 0) {
|
||||||
|
throw RuntimeException("Failed to send signal $signal to process $pid: ${strerror(errno)?.toKString()}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun waitFor(): Int = withContext(Dispatchers.Default) {
|
||||||
|
memScoped {
|
||||||
|
val status = alloc<IntVar>()
|
||||||
|
if (waitpid(pid, status.ptr, 0) == -1) {
|
||||||
|
throw RuntimeException("Failed to wait for process $pid: ${strerror(errno)?.toKString()}")
|
||||||
|
}
|
||||||
|
val s = status.value
|
||||||
|
if ((s and 0x7f) == 0) (s shr 8) and 0xff else -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun destroy() {
|
||||||
|
kill(pid, SIGKILL)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
private fun createPipeFlow(fd: Int): Flow<String> = flow {
|
||||||
|
val buffer = ByteArray(4096)
|
||||||
|
val lineBuffer = StringBuilder()
|
||||||
|
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
val bytesRead = buffer.usePinned { pinned ->
|
||||||
|
read(fd, pinned.addressOf(0), buffer.size.toULong())
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bytesRead <= 0L) break
|
||||||
|
|
||||||
|
val text = buffer.decodeToString(endIndex = bytesRead.toInt())
|
||||||
|
lineBuffer.append(text)
|
||||||
|
|
||||||
|
var newlineIdx = lineBuffer.indexOf('\n')
|
||||||
|
while (newlineIdx != -1) {
|
||||||
|
val line = lineBuffer.substring(0, newlineIdx)
|
||||||
|
emit(line)
|
||||||
|
lineBuffer.deleteRange(0, newlineIdx + 1)
|
||||||
|
newlineIdx = lineBuffer.indexOf('\n')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (lineBuffer.isNotEmpty()) {
|
||||||
|
emit(lineBuffer.toString())
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
close(fd)
|
||||||
|
}
|
||||||
|
}.flowOn(Dispatchers.Default)
|
||||||
|
|
||||||
|
@OptIn(ExperimentalForeignApi::class)
|
||||||
|
object PosixProcessRunner : LyngProcessRunner {
|
||||||
|
override suspend fun execute(executable: String, args: List<String>): LyngProcess = withContext(Dispatchers.Default) {
|
||||||
|
memScoped {
|
||||||
|
val pipeStdout = allocArray<IntVar>(2)
|
||||||
|
val pipeStderr = allocArray<IntVar>(2)
|
||||||
|
|
||||||
|
if (pipe(pipeStdout) != 0) throw RuntimeException("Failed to create stdout pipe")
|
||||||
|
if (pipe(pipeStderr) != 0) {
|
||||||
|
close(pipeStdout[0])
|
||||||
|
close(pipeStdout[1])
|
||||||
|
throw RuntimeException("Failed to create stderr pipe")
|
||||||
|
}
|
||||||
|
|
||||||
|
val pid = fork()
|
||||||
|
if (pid == -1) {
|
||||||
|
close(pipeStdout[0])
|
||||||
|
close(pipeStdout[1])
|
||||||
|
close(pipeStderr[0])
|
||||||
|
close(pipeStderr[1])
|
||||||
|
throw RuntimeException("Failed to fork: ${strerror(errno)?.toKString()}")
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pid == 0) {
|
||||||
|
// Child process
|
||||||
|
dup2(pipeStdout[1], 1)
|
||||||
|
dup2(pipeStderr[1], 2)
|
||||||
|
|
||||||
|
close(pipeStdout[0])
|
||||||
|
close(pipeStdout[1])
|
||||||
|
close(pipeStderr[0])
|
||||||
|
close(pipeStderr[1])
|
||||||
|
|
||||||
|
val argv = allocArray<CPointerVar<ByteVar>>(args.size + 2)
|
||||||
|
argv[0] = executable.cstr.ptr
|
||||||
|
for (i in args.indices) {
|
||||||
|
argv[i + 1] = args[i].cstr.ptr
|
||||||
|
}
|
||||||
|
argv[args.size + 1] = null
|
||||||
|
|
||||||
|
execvp(executable, argv)
|
||||||
|
|
||||||
|
// If we are here, exec failed
|
||||||
|
_exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parent process
|
||||||
|
close(pipeStdout[1])
|
||||||
|
close(pipeStderr[1])
|
||||||
|
|
||||||
|
NativeLyngProcess(pid, pipeStdout[0], pipeStderr[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun shell(command: String): LyngProcess {
|
||||||
|
return execute("/bin/sh", listOf("-c", command))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
internal actual fun getNativeKernelVersion(): String? = null
|
||||||
|
|
||||||
|
internal actual fun isNativeProcessSupported(): Boolean = true
|
||||||
|
|
||||||
|
internal actual fun getNativeProcessRunner(): LyngProcessRunner = WindowsProcessRunner
|
||||||
|
|
||||||
|
object WindowsProcessRunner : LyngProcessRunner {
|
||||||
|
override suspend fun execute(executable: String, args: List<String>): LyngProcess {
|
||||||
|
throw UnsupportedOperationException("Windows native process execution not implemented yet")
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun shell(command: String): LyngProcess {
|
||||||
|
return execute("cmd.exe", listOf("/c", command))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/*
|
||||||
|
* 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.lyngio.process
|
||||||
|
|
||||||
|
import kotlin.experimental.ExperimentalNativeApi
|
||||||
|
|
||||||
|
@OptIn(ExperimentalNativeApi::class)
|
||||||
|
actual fun getPlatformDetails(): PlatformDetails {
|
||||||
|
return PlatformDetails(
|
||||||
|
name = Platform.osFamily.name,
|
||||||
|
version = "unknown",
|
||||||
|
arch = Platform.cpuArchitecture.name,
|
||||||
|
kernelVersion = getNativeKernelVersion()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal expect fun getNativeKernelVersion(): String?
|
||||||
|
|
||||||
|
actual fun isProcessSupported(): Boolean = isNativeProcessSupported()
|
||||||
|
|
||||||
|
internal expect fun isNativeProcessSupported(): Boolean
|
||||||
|
|
||||||
|
actual fun getSystemProcessRunner(): LyngProcessRunner = getNativeProcessRunner()
|
||||||
|
|
||||||
|
internal expect fun getNativeProcessRunner(): LyngProcessRunner
|
||||||
@@ -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.
|
||||||
@@ -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.1.0-SNAPSHOT"
|
version = "1.1.1-SNAPSHOT"
|
||||||
|
|
||||||
// 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
|
||||||
|
|
||||||
|
|||||||
@@ -138,7 +138,7 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
|
|||||||
} else {
|
} else {
|
||||||
val value = if (hp < callArgs.size) callArgs[hp++]
|
val value = if (hp < callArgs.size) callArgs[hp++]
|
||||||
else a.defaultValue?.execute(scope)
|
else a.defaultValue?.execute(scope)
|
||||||
?: scope.raiseIllegalArgument("too few arguments for the call (${arguments.list})")
|
?: scope.raiseIllegalArgument("too few arguments for the call (missing ${a.name})")
|
||||||
assign(a, value)
|
assign(a, value)
|
||||||
}
|
}
|
||||||
i++
|
i++
|
||||||
|
|||||||
@@ -53,26 +53,71 @@ class ClosureScope(val callScope: Scope, val closureScope: Scope) :
|
|||||||
super.objects[name]?.let { return it }
|
super.objects[name]?.let { return it }
|
||||||
super.localBindings[name]?.let { return it }
|
super.localBindings[name]?.let { return it }
|
||||||
|
|
||||||
// 2) Members on the captured receiver instance
|
// 1a) Priority: if we are in a class context, prefer our own private members to support
|
||||||
(closureScope.thisObj as? net.sergeych.lyng.obj.ObjInstance)
|
// non-virtual private dispatch. This prevents a subclass from accidentally
|
||||||
?.instanceScope
|
// capturing a private member call from a base class.
|
||||||
?.objects
|
// We only return non-field/non-property members (methods) here; fields must
|
||||||
?.get(name)
|
// be resolved via instance storage in priority 2.
|
||||||
?.let { rec ->
|
currentClassCtx?.let { ctx ->
|
||||||
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) return rec
|
ctx.members[name]?.let { rec ->
|
||||||
|
if (rec.visibility == Visibility.Private &&
|
||||||
|
rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Field &&
|
||||||
|
rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Property) return rec
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2) Members on the captured receiver instance
|
||||||
|
(closureScope.thisObj as? net.sergeych.lyng.obj.ObjInstance)?.let { inst ->
|
||||||
|
// Check direct locals in instance scope (unmangled)
|
||||||
|
inst.instanceScope.objects[name]?.let { rec ->
|
||||||
|
if (rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Property &&
|
||||||
|
canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) return rec
|
||||||
|
}
|
||||||
|
// Check mangled names for fields along MRO
|
||||||
|
for (cls in inst.objClass.mro) {
|
||||||
|
inst.instanceScope.objects["${cls.className}::$name"]?.let { rec ->
|
||||||
|
if (rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Property &&
|
||||||
|
canAccessMember(rec.visibility, rec.declaringClass ?: cls, currentClassCtx)) return rec
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
findExtension(closureScope.thisObj.objClass, name)?.let { return it }
|
findExtension(closureScope.thisObj.objClass, name)?.let { return it }
|
||||||
closureScope.thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
closureScope.thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
||||||
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) return rec
|
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) {
|
||||||
|
// Return only non-field/non-property members (methods) from class-level records.
|
||||||
|
// Fields and properties must be resolved via instance storage (mangled) or readField.
|
||||||
|
if (rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Field &&
|
||||||
|
rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Property &&
|
||||||
|
!rec.isAbstract) return rec
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3) Closure scope chain (locals/parents + members), ignore ClosureScope overrides to prevent recursion
|
// 3) Closure scope chain (locals/parents + members), ignore ClosureScope overrides to prevent recursion
|
||||||
closureScope.chainLookupWithMembers(name, currentClassCtx)?.let { return it }
|
closureScope.chainLookupWithMembers(name, currentClassCtx)?.let { return it }
|
||||||
|
|
||||||
// 4) Caller `this` members
|
// 4) Caller `this` members
|
||||||
|
(callScope.thisObj as? net.sergeych.lyng.obj.ObjInstance)?.let { inst ->
|
||||||
|
// Check direct locals in instance scope (unmangled)
|
||||||
|
inst.instanceScope.objects[name]?.let { rec ->
|
||||||
|
if (rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Property &&
|
||||||
|
canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) return rec
|
||||||
|
}
|
||||||
|
// Check mangled names for fields along MRO
|
||||||
|
for (cls in inst.objClass.mro) {
|
||||||
|
inst.instanceScope.objects["${cls.className}::$name"]?.let { rec ->
|
||||||
|
if (rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Property &&
|
||||||
|
canAccessMember(rec.visibility, rec.declaringClass ?: cls, currentClassCtx)) return rec
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
findExtension(callScope.thisObj.objClass, name)?.let { return it }
|
findExtension(callScope.thisObj.objClass, name)?.let { return it }
|
||||||
callScope.thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
callScope.thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
||||||
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) return rec
|
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) {
|
||||||
|
if (rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Field &&
|
||||||
|
rec.type != net.sergeych.lyng.obj.ObjRecord.Type.Property &&
|
||||||
|
!rec.isAbstract) return rec
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5) Caller chain (locals/parents + members)
|
// 5) Caller chain (locals/parents + members)
|
||||||
|
|||||||
@@ -20,5 +20,7 @@ package net.sergeych.lyng
|
|||||||
sealed class CodeContext {
|
sealed class CodeContext {
|
||||||
class Module(@Suppress("unused") val packageName: String?): CodeContext()
|
class Module(@Suppress("unused") val packageName: String?): CodeContext()
|
||||||
class Function(val name: String): CodeContext()
|
class Function(val name: String): CodeContext()
|
||||||
class ClassBody(val name: String): CodeContext()
|
class ClassBody(val name: String): CodeContext() {
|
||||||
|
val pendingInitializations = mutableMapOf<String, Pos>()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -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.
|
||||||
@@ -324,15 +324,15 @@ private class Parser(fromPos: Pos) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
'?' -> {
|
'?' -> {
|
||||||
when (currentChar.also { pos.advance() }) {
|
when (currentChar) {
|
||||||
':' -> Token("??", from, Token.Type.ELVIS)
|
'=' -> { pos.advance(); Token("?=", from, Token.Type.IFNULLASSIGN) }
|
||||||
'?' -> Token("??", from, Token.Type.ELVIS)
|
':' -> { pos.advance(); Token("?:", from, Token.Type.ELVIS) }
|
||||||
'.' -> Token("?.", from, Token.Type.NULL_COALESCE)
|
'?' -> { pos.advance(); Token("??", from, Token.Type.ELVIS) }
|
||||||
'[' -> Token("?(", from, Token.Type.NULL_COALESCE_INDEX)
|
'.' -> { pos.advance(); Token("?.", from, Token.Type.NULL_COALESCE) }
|
||||||
'(' -> Token("?(", from, Token.Type.NULL_COALESCE_INVOKE)
|
'[' -> { pos.advance(); Token("?[", from, Token.Type.NULL_COALESCE_INDEX) }
|
||||||
'{' -> Token("?{", from, Token.Type.NULL_COALESCE_BLOCKINVOKE)
|
'(' -> { pos.advance(); Token("?(", from, Token.Type.NULL_COALESCE_INVOKE) }
|
||||||
|
'{' -> { pos.advance(); Token("?{", from, Token.Type.NULL_COALESCE_BLOCKINVOKE) }
|
||||||
else -> {
|
else -> {
|
||||||
pos.back()
|
|
||||||
Token("?", from, Token.Type.QUESTION)
|
Token("?", from, Token.Type.QUESTION)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -357,6 +357,8 @@ private class Parser(fromPos: Pos) {
|
|||||||
when (text) {
|
when (text) {
|
||||||
"in" -> Token("in", from, Token.Type.IN)
|
"in" -> Token("in", from, Token.Type.IN)
|
||||||
"is" -> Token("is", from, Token.Type.IS)
|
"is" -> Token("is", from, Token.Type.IS)
|
||||||
|
"by" -> Token("by", from, Token.Type.BY)
|
||||||
|
"object" -> Token("object", from, Token.Type.OBJECT)
|
||||||
"as" -> {
|
"as" -> {
|
||||||
// support both `as` and tight `as?` without spaces
|
// support both `as` and tight `as?` without spaces
|
||||||
if (currentChar == '?') { pos.advance(); Token("as?", from, Token.Type.ASNULL) }
|
if (currentChar == '?') { pos.advance(); Token("as?", from, Token.Type.ASNULL) }
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* 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 net.sergeych.lyng.obj.Obj
|
||||||
|
import net.sergeych.lyng.obj.ObjVoid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Exception used to implement `return` statement.
|
||||||
|
* It carries the return value and an optional label for non-local returns.
|
||||||
|
*/
|
||||||
|
class ReturnException(
|
||||||
|
val result: Obj = ObjVoid,
|
||||||
|
val label: String? = null
|
||||||
|
) : RuntimeException()
|
||||||
@@ -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.
|
||||||
@@ -155,7 +155,10 @@ open class Scope(
|
|||||||
this.extensions[cls]?.get(name)?.let { return it }
|
this.extensions[cls]?.get(name)?.let { return it }
|
||||||
}
|
}
|
||||||
return thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
return thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
||||||
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) rec else null
|
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) {
|
||||||
|
if (rec.type == ObjRecord.Type.Field || rec.type == ObjRecord.Type.Property || rec.isAbstract) null
|
||||||
|
else rec
|
||||||
|
} else null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,7 +179,11 @@ open class Scope(
|
|||||||
s.extensions[cls]?.get(name)?.let { return it }
|
s.extensions[cls]?.get(name)?.let { return it }
|
||||||
}
|
}
|
||||||
s.thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
s.thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
||||||
if (canAccessMember(rec.visibility, rec.declaringClass, caller)) return rec
|
if (canAccessMember(rec.visibility, rec.declaringClass, caller)) {
|
||||||
|
if (rec.type == ObjRecord.Type.Field || rec.type == ObjRecord.Type.Property || rec.isAbstract) {
|
||||||
|
// ignore fields, properties and abstracts here, they will be handled by the caller via readField
|
||||||
|
} else return rec
|
||||||
|
}
|
||||||
}
|
}
|
||||||
s = s.parent
|
s = s.parent
|
||||||
}
|
}
|
||||||
@@ -262,6 +269,9 @@ open class Scope(
|
|||||||
|
|
||||||
fun raiseClassCastError(msg: String): Nothing = raiseError(ObjClassCastException(this, msg))
|
fun raiseClassCastError(msg: String): Nothing = raiseError(ObjClassCastException(this, msg))
|
||||||
|
|
||||||
|
fun raiseUnset(message: String = "property is unset (not initialized)"): Nothing =
|
||||||
|
raiseError(ObjUnsetException(this, message))
|
||||||
|
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
fun raiseSymbolNotFound(name: String): Nothing =
|
fun raiseSymbolNotFound(name: String): Nothing =
|
||||||
raiseError(ObjSymbolNotDefinedException(this, "symbol is not defined: $name"))
|
raiseError(ObjSymbolNotDefinedException(this, "symbol is not defined: $name"))
|
||||||
@@ -304,11 +314,11 @@ open class Scope(
|
|||||||
|
|
||||||
inline fun <reified T : Obj> thisAs(): T {
|
inline fun <reified T : Obj> thisAs(): T {
|
||||||
var s: Scope? = this
|
var s: Scope? = this
|
||||||
do {
|
while (s != null) {
|
||||||
val t = s!!.thisObj
|
val t = s.thisObj
|
||||||
if (t is T) return t
|
if (t is T) return t
|
||||||
s = s.parent
|
s = s.parent
|
||||||
} while (s != null)
|
}
|
||||||
raiseClassCastError("Cannot cast ${thisObj.objClass.className} to ${T::class.simpleName}")
|
raiseClassCastError("Cannot cast ${thisObj.objClass.className} to ${T::class.simpleName}")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,7 +339,10 @@ open class Scope(
|
|||||||
?: parent?.get(name)
|
?: parent?.get(name)
|
||||||
// Finally, fallback to class members on thisObj
|
// Finally, fallback to class members on thisObj
|
||||||
?: thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
?: thisObj.objClass.getInstanceMemberOrNull(name)?.let { rec ->
|
||||||
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) rec else null
|
if (canAccessMember(rec.visibility, rec.declaringClass, currentClassCtx)) {
|
||||||
|
if (rec.type == ObjRecord.Type.Field || rec.type == ObjRecord.Type.Property || rec.isAbstract) null
|
||||||
|
else rec
|
||||||
|
} else null
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -431,7 +444,11 @@ open class Scope(
|
|||||||
name: String,
|
name: String,
|
||||||
value: Obj,
|
value: Obj,
|
||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
recordType: ObjRecord.Type = ObjRecord.Type.Other
|
writeVisibility: Visibility? = null,
|
||||||
|
recordType: ObjRecord.Type = ObjRecord.Type.Other,
|
||||||
|
isAbstract: Boolean = false,
|
||||||
|
isClosed: Boolean = false,
|
||||||
|
isOverride: Boolean = false
|
||||||
): ObjRecord =
|
): ObjRecord =
|
||||||
objects[name]?.let {
|
objects[name]?.let {
|
||||||
if( !it.isMutable )
|
if( !it.isMutable )
|
||||||
@@ -445,17 +462,28 @@ open class Scope(
|
|||||||
callScope.localBindings[name] = it
|
callScope.localBindings[name] = it
|
||||||
}
|
}
|
||||||
it
|
it
|
||||||
} ?: addItem(name, true, value, visibility, recordType)
|
} ?: addItem(name, true, value, visibility, writeVisibility, recordType, isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride)
|
||||||
|
|
||||||
fun addItem(
|
fun addItem(
|
||||||
name: String,
|
name: String,
|
||||||
isMutable: Boolean,
|
isMutable: Boolean,
|
||||||
value: Obj,
|
value: Obj,
|
||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
|
writeVisibility: Visibility? = null,
|
||||||
recordType: ObjRecord.Type = ObjRecord.Type.Other,
|
recordType: ObjRecord.Type = ObjRecord.Type.Other,
|
||||||
declaringClass: net.sergeych.lyng.obj.ObjClass? = currentClassCtx
|
declaringClass: net.sergeych.lyng.obj.ObjClass? = currentClassCtx,
|
||||||
|
isAbstract: Boolean = false,
|
||||||
|
isClosed: Boolean = false,
|
||||||
|
isOverride: Boolean = false
|
||||||
): ObjRecord {
|
): ObjRecord {
|
||||||
val rec = ObjRecord(value, isMutable, visibility, declaringClass = declaringClass, type = recordType)
|
val rec = ObjRecord(
|
||||||
|
value, isMutable, visibility, writeVisibility,
|
||||||
|
declaringClass = declaringClass,
|
||||||
|
type = recordType,
|
||||||
|
isAbstract = isAbstract,
|
||||||
|
isClosed = isClosed,
|
||||||
|
isOverride = isOverride
|
||||||
|
)
|
||||||
objects[name] = rec
|
objects[name] = rec
|
||||||
// Index this binding within the current frame to help resolve locals across suspension
|
// Index this binding within the current frame to help resolve locals across suspension
|
||||||
localBindings[name] = rec
|
localBindings[name] = rec
|
||||||
@@ -593,6 +621,51 @@ open class Scope(
|
|||||||
return ref.evalValue(this)
|
return ref.evalValue(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
suspend fun resolve(rec: ObjRecord, name: String): Obj {
|
||||||
|
if (rec.type == ObjRecord.Type.Delegated) {
|
||||||
|
val del = rec.delegate ?: run {
|
||||||
|
if (thisObj is ObjInstance) {
|
||||||
|
val res = (thisObj as ObjInstance).resolveRecord(this, rec, name, rec.declaringClass).value
|
||||||
|
rec.value = res
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
raiseError("Internal error: delegated property $name has no delegate")
|
||||||
|
}
|
||||||
|
val th = if (thisObj === ObjVoid) ObjNull else thisObj
|
||||||
|
val res = del.invokeInstanceMethod(this, "getValue", Arguments(th, ObjString(name)), onNotFoundResult = {
|
||||||
|
// If getValue not found, return a wrapper that calls invoke
|
||||||
|
object : Statement() {
|
||||||
|
override val pos: Pos = Pos.builtIn
|
||||||
|
override suspend fun execute(scope: Scope): Obj {
|
||||||
|
val th2 = if (scope.thisObj === ObjVoid) ObjNull else scope.thisObj
|
||||||
|
val allArgs = (listOf(th2, ObjString(name)) + scope.args.list).toTypedArray()
|
||||||
|
return del.invokeInstanceMethod(scope, "invoke", Arguments(*allArgs))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
rec.value = res
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
return rec.value
|
||||||
|
}
|
||||||
|
|
||||||
|
suspend fun assign(rec: ObjRecord, name: String, newValue: Obj) {
|
||||||
|
if (rec.type == ObjRecord.Type.Delegated) {
|
||||||
|
val del = rec.delegate ?: run {
|
||||||
|
if (thisObj is ObjInstance) {
|
||||||
|
(thisObj as ObjInstance).writeField(this, name, newValue)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
raiseError("Internal error: delegated property $name has no delegate")
|
||||||
|
}
|
||||||
|
val th = if (thisObj === ObjVoid) ObjNull else thisObj
|
||||||
|
del.invokeInstanceMethod(this, "setValue", Arguments(th, ObjString(name), newValue))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!rec.isMutable && rec.value !== ObjUnset) raiseIllegalAssignment("can't reassign val $name")
|
||||||
|
rec.value = newValue
|
||||||
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|
||||||
fun new(): Scope =
|
fun new(): Scope =
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import kotlinx.coroutines.delay
|
|||||||
import kotlinx.coroutines.yield
|
import kotlinx.coroutines.yield
|
||||||
import net.sergeych.lyng.Script.Companion.defaultImportManager
|
import net.sergeych.lyng.Script.Companion.defaultImportManager
|
||||||
import net.sergeych.lyng.miniast.addConstDoc
|
import net.sergeych.lyng.miniast.addConstDoc
|
||||||
|
import net.sergeych.lyng.miniast.addFnDoc
|
||||||
import net.sergeych.lyng.miniast.addVoidFnDoc
|
import net.sergeych.lyng.miniast.addVoidFnDoc
|
||||||
import net.sergeych.lyng.miniast.type
|
import net.sergeych.lyng.miniast.type
|
||||||
import net.sergeych.lyng.obj.*
|
import net.sergeych.lyng.obj.*
|
||||||
@@ -60,6 +61,7 @@ class Script(
|
|||||||
|
|
||||||
internal val rootScope: Scope = Scope(null).apply {
|
internal val rootScope: Scope = Scope(null).apply {
|
||||||
ObjException.addExceptionsToContext(this)
|
ObjException.addExceptionsToContext(this)
|
||||||
|
addConst("Unset", ObjUnset)
|
||||||
addFn("print") {
|
addFn("print") {
|
||||||
for ((i, a) in args.withIndex()) {
|
for ((i, a) in args.withIndex()) {
|
||||||
if (i > 0) print(' ' + a.toString(this).value)
|
if (i > 0) print(' ' + a.toString(this).value)
|
||||||
@@ -203,7 +205,19 @@ class Script(
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
addFn("assertThrows") {
|
addFnDoc(
|
||||||
|
"assertThrows",
|
||||||
|
doc = """
|
||||||
|
Asserts that the provided code block throws an exception, with or without exception:
|
||||||
|
```lyng
|
||||||
|
assertThrows { /* ode */ }
|
||||||
|
assertThrows(IllegalArgumentException) { /* code */ }
|
||||||
|
```
|
||||||
|
If an expected exception class is provided,
|
||||||
|
it checks that the thrown exception is of that class. If no expected class is provided, any exception
|
||||||
|
will be accepted.
|
||||||
|
""".trimIndent()
|
||||||
|
) {
|
||||||
val code: Statement
|
val code: Statement
|
||||||
val expectedClass: ObjClass?
|
val expectedClass: ObjClass?
|
||||||
when (args.size) {
|
when (args.size) {
|
||||||
@@ -211,10 +225,12 @@ class Script(
|
|||||||
code = requiredArg<Statement>(0)
|
code = requiredArg<Statement>(0)
|
||||||
expectedClass = null
|
expectedClass = null
|
||||||
}
|
}
|
||||||
|
|
||||||
2 -> {
|
2 -> {
|
||||||
code = requiredArg<Statement>(1)
|
code = requiredArg<Statement>(1)
|
||||||
expectedClass = requiredArg<ObjClass>(0)
|
expectedClass = requiredArg<ObjClass>(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> raiseIllegalArgument("Expected 1 or 2 arguments, got ${args.size}")
|
else -> raiseIllegalArgument("Expected 1 or 2 arguments, got ${args.size}")
|
||||||
}
|
}
|
||||||
val result = try {
|
val result = try {
|
||||||
@@ -225,10 +241,15 @@ class Script(
|
|||||||
} catch (_: ScriptError) {
|
} catch (_: ScriptError) {
|
||||||
ObjNull
|
ObjNull
|
||||||
}
|
}
|
||||||
if( result == null ) raiseError(ObjAssertionFailedException(this, "Expected exception but nothing was thrown"))
|
if (result == null) raiseError(
|
||||||
|
ObjAssertionFailedException(
|
||||||
|
this,
|
||||||
|
"Expected exception but nothing was thrown"
|
||||||
|
)
|
||||||
|
)
|
||||||
expectedClass?.let {
|
expectedClass?.let {
|
||||||
if (result !is ObjException)
|
if (result !is ObjException)
|
||||||
raiseError("Expected $expectedClass, got $result")
|
raiseError("Expected $expectedClass, got non-lyng exception $result")
|
||||||
if (result.exceptionClass != expectedClass) {
|
if (result.exceptionClass != expectedClass) {
|
||||||
raiseError("Expected $expectedClass, got ${result.exceptionClass}")
|
raiseError("Expected $expectedClass, got ${result.exceptionClass}")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ class Source(val fileName: String, val text: String) {
|
|||||||
|
|
||||||
fun extractPackageName(): String {
|
fun extractPackageName(): String {
|
||||||
for ((n,line) in lines.withIndex()) {
|
for ((n,line) in lines.withIndex()) {
|
||||||
if( line.isBlank() || line.isEmpty() )
|
if( line.isBlank() )
|
||||||
continue
|
continue
|
||||||
if( line.startsWith("package ") )
|
if( line.startsWith("package ") )
|
||||||
return line.substring(8).trim()
|
return line.substring(8).trim()
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -34,9 +34,9 @@ data class Token(val value: String, val pos: Pos, val type: Type) {
|
|||||||
LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, COMMA,
|
LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, COMMA,
|
||||||
SEMICOLON, COLON,
|
SEMICOLON, COLON,
|
||||||
PLUS, MINUS, STAR, SLASH, PERCENT,
|
PLUS, MINUS, STAR, SLASH, PERCENT,
|
||||||
ASSIGN, PLUSASSIGN, MINUSASSIGN, STARASSIGN, SLASHASSIGN, PERCENTASSIGN,
|
ASSIGN, PLUSASSIGN, MINUSASSIGN, STARASSIGN, SLASHASSIGN, PERCENTASSIGN, IFNULLASSIGN,
|
||||||
PLUS2, MINUS2,
|
PLUS2, MINUS2,
|
||||||
IN, NOTIN, IS, NOTIS,
|
IN, NOTIN, IS, NOTIS, BY,
|
||||||
EQ, NEQ, LT, LTE, GT, GTE, REF_EQ, REF_NEQ, MATCH, NOTMATCH,
|
EQ, NEQ, LT, LTE, GT, GTE, REF_EQ, REF_NEQ, MATCH, NOTMATCH,
|
||||||
SHUTTLE,
|
SHUTTLE,
|
||||||
AND, BITAND, OR, BITOR, BITXOR, NOT, BITNOT, DOT, ARROW, EQARROW, QUESTION, COLONCOLON,
|
AND, BITAND, OR, BITOR, BITXOR, NOT, BITNOT, DOT, ARROW, EQARROW, QUESTION, COLONCOLON,
|
||||||
@@ -44,7 +44,7 @@ data class Token(val value: String, val pos: Pos, val type: Type) {
|
|||||||
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
SINLGE_LINE_COMMENT, MULTILINE_COMMENT,
|
||||||
LABEL, ATLABEL, // label@ at@label
|
LABEL, ATLABEL, // label@ at@label
|
||||||
// type-checking/casting
|
// type-checking/casting
|
||||||
AS, ASNULL,
|
AS, ASNULL, OBJECT,
|
||||||
//PUBLIC, PROTECTED, INTERNAL, EXPORT, OPEN, INLINE, OVERRIDE, ABSTRACT, SEALED, EXTERNAL, VAL, VAR, CONST, TYPE, FUN, CLASS, INTERFACE, ENUM, OBJECT, TRAIT, THIS,
|
//PUBLIC, PROTECTED, INTERNAL, EXPORT, OPEN, INLINE, OVERRIDE, ABSTRACT, SEALED, EXTERNAL, VAL, VAR, CONST, TYPE, FUN, CLASS, INTERFACE, ENUM, OBJECT, TRAIT, THIS,
|
||||||
ELLIPSIS, DOTDOT, DOTDOTLT,
|
ELLIPSIS, DOTDOT, DOTDOTLT,
|
||||||
NEWLINE,
|
NEWLINE,
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
package net.sergeych.lyng
|
package net.sergeych.lyng
|
||||||
|
|
||||||
enum class Visibility {
|
enum class Visibility {
|
||||||
Public, Private, Protected;//, Internal
|
Public, Protected, Private;//, Internal
|
||||||
val isPublic by lazy { this == Public }
|
val isPublic by lazy { this == Public }
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
val isProtected by lazy { this == Protected }
|
val isProtected by lazy { this == Protected }
|
||||||
|
|||||||
@@ -113,6 +113,15 @@ object Binder {
|
|||||||
symbols += fieldSym
|
symbols += fieldSym
|
||||||
classes.last().fields += fieldSym.id
|
classes.last().fields += fieldSym.id
|
||||||
}
|
}
|
||||||
|
// Class fields (val/var in class body, if any are reported here)
|
||||||
|
for (cf in d.classFields) {
|
||||||
|
val fs = source.offsetOf(cf.nameStart)
|
||||||
|
val fe = fs + cf.name.length
|
||||||
|
val kind = if (cf.mutable) SymbolKind.Variable else SymbolKind.Value
|
||||||
|
val fieldSym = Symbol(nextId++, cf.name, kind, fs, fe, containerId = sym.id)
|
||||||
|
symbols += fieldSym
|
||||||
|
classes.last().fields += fieldSym.id
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Second pass: functions and top-level/class vals/vars
|
// Second pass: functions and top-level/class vals/vars
|
||||||
|
|||||||
@@ -24,6 +24,24 @@ package net.sergeych.lyng.format
|
|||||||
*/
|
*/
|
||||||
object LyngFormatter {
|
object LyngFormatter {
|
||||||
|
|
||||||
|
private fun startsWithWord(s: String, w: String): Boolean =
|
||||||
|
s.startsWith(w) && s.getOrNull(w.length)?.let { !it.isLetterOrDigit() && it != '_' } != false
|
||||||
|
|
||||||
|
private fun isPropertyAccessor(s: String): Boolean {
|
||||||
|
val t = s.trim()
|
||||||
|
if (t.isEmpty()) return false
|
||||||
|
if (startsWithWord(t, "get") || startsWithWord(t, "set")) return true
|
||||||
|
if (startsWithWord(t, "private")) {
|
||||||
|
val rest = t.substring("private".length).trimStart()
|
||||||
|
if (startsWithWord(rest, "set")) return true
|
||||||
|
}
|
||||||
|
if (startsWithWord(t, "protected")) {
|
||||||
|
val rest = t.substring("protected".length).trimStart()
|
||||||
|
if (startsWithWord(rest, "set")) return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
/** Returns the input with indentation recomputed from scratch, line by line. */
|
/** Returns the input with indentation recomputed from scratch, line by line. */
|
||||||
fun reindent(text: String, config: LyngFormatConfig = LyngFormatConfig()): String {
|
fun reindent(text: String, config: LyngFormatConfig = LyngFormatConfig()): String {
|
||||||
// Normalize tabs to spaces globally before any transformation; results must contain no tabs
|
// Normalize tabs to spaces globally before any transformation; results must contain no tabs
|
||||||
@@ -35,6 +53,7 @@ object LyngFormatter {
|
|||||||
var bracketBalance = 0
|
var bracketBalance = 0
|
||||||
var prevBracketContinuation = false
|
var prevBracketContinuation = false
|
||||||
var inBlockComment = false
|
var inBlockComment = false
|
||||||
|
val extraIndents = mutableListOf<Int>()
|
||||||
// We don't keep per-"[" base alignment; continuation rules define alignment.
|
// We don't keep per-"[" base alignment; continuation rules define alignment.
|
||||||
|
|
||||||
fun updateBalances(ch: Char) {
|
fun updateBalances(ch: Char) {
|
||||||
@@ -52,7 +71,7 @@ object LyngFormatter {
|
|||||||
// Always produce spaces; tabs are not allowed in resulting code
|
// Always produce spaces; tabs are not allowed in resulting code
|
||||||
" ".repeat(level * config.indentSize + continuation)
|
" ".repeat(level * config.indentSize + continuation)
|
||||||
|
|
||||||
var awaitingSingleIndent = false
|
var awaitingExtraIndent = 0
|
||||||
fun isControlHeaderNoBrace(s: String): Boolean {
|
fun isControlHeaderNoBrace(s: String): Boolean {
|
||||||
val t = s.trim()
|
val t = s.trim()
|
||||||
if (t.isEmpty()) return false
|
if (t.isEmpty()) return false
|
||||||
@@ -60,7 +79,13 @@ object LyngFormatter {
|
|||||||
val isIf = Regex("^if\\s*\\(.*\\)\\s*$").matches(t)
|
val isIf = Regex("^if\\s*\\(.*\\)\\s*$").matches(t)
|
||||||
val isElseIf = Regex("^else\\s+if\\s*\\(.*\\)\\s*$").matches(t)
|
val isElseIf = Regex("^else\\s+if\\s*\\(.*\\)\\s*$").matches(t)
|
||||||
val isElse = t == "else"
|
val isElse = t == "else"
|
||||||
return isIf || isElseIf || isElse
|
if (isIf || isElseIf || isElse) return true
|
||||||
|
|
||||||
|
// property accessors ending with ) or =
|
||||||
|
if (isPropertyAccessor(t)) {
|
||||||
|
return if (t.contains('=')) t.endsWith('=') else t.endsWith(')')
|
||||||
|
}
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
for ((i, rawLine) in lines.withIndex()) {
|
for ((i, rawLine) in lines.withIndex()) {
|
||||||
@@ -70,7 +95,12 @@ object LyngFormatter {
|
|||||||
val trimmedLine = rawLine.trim()
|
val trimmedLine = rawLine.trim()
|
||||||
|
|
||||||
// Compute effective indent level for this line
|
// Compute effective indent level for this line
|
||||||
var effectiveLevel = blockLevel
|
val currentExtraIndent = extraIndents.sum()
|
||||||
|
var effectiveLevel = blockLevel + currentExtraIndent
|
||||||
|
|
||||||
|
val isAccessor = !inBlockComment && isPropertyAccessor(trimmedStart)
|
||||||
|
if (isAccessor) effectiveLevel += 1
|
||||||
|
|
||||||
if (inBlockComment) {
|
if (inBlockComment) {
|
||||||
if (!trimmedLine.startsWith("*/")) {
|
if (!trimmedLine.startsWith("*/")) {
|
||||||
effectiveLevel += 1
|
effectiveLevel += 1
|
||||||
@@ -83,9 +113,9 @@ object LyngFormatter {
|
|||||||
|
|
||||||
// Single-line control header (if/else/else if) without braces: indent the next
|
// Single-line control header (if/else/else if) without braces: indent the next
|
||||||
// non-empty, non-'}', non-'else' line by one extra level
|
// non-empty, non-'}', non-'else' line by one extra level
|
||||||
val applyAwaiting = awaitingSingleIndent && trimmedStart.isNotEmpty() &&
|
val applyAwaiting = awaitingExtraIndent > 0 && trimmedStart.isNotEmpty() &&
|
||||||
!trimmedStart.startsWith("else") && !trimmedStart.startsWith("}")
|
!trimmedStart.startsWith("else") && !trimmedStart.startsWith("}")
|
||||||
if (applyAwaiting) effectiveLevel += 1
|
if (applyAwaiting) effectiveLevel += awaitingExtraIndent
|
||||||
|
|
||||||
val firstChar = trimmedStart.firstOrNull()
|
val firstChar = trimmedStart.firstOrNull()
|
||||||
// While inside parentheses, continuation applies scaled by nesting level
|
// While inside parentheses, continuation applies scaled by nesting level
|
||||||
@@ -129,23 +159,43 @@ object LyngFormatter {
|
|||||||
// New line (keep EOF semantics similar to input)
|
// New line (keep EOF semantics similar to input)
|
||||||
if (i < lines.lastIndex) sb.append('\n')
|
if (i < lines.lastIndex) sb.append('\n')
|
||||||
|
|
||||||
|
val oldBlockLevel = blockLevel
|
||||||
// Update balances using this line's code content
|
// Update balances using this line's code content
|
||||||
for (part in parts) {
|
for (part in parts) {
|
||||||
if (part.type == PartType.Code) {
|
if (part.type == PartType.Code) {
|
||||||
for (ch in part.text) updateBalances(ch)
|
for (ch in part.text) updateBalances(ch)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val newBlockLevel = blockLevel
|
||||||
|
if (newBlockLevel > oldBlockLevel) {
|
||||||
|
val addedThisLine = (if (applyAwaiting) awaitingExtraIndent else 0) + (if (isAccessor) 1 else 0)
|
||||||
|
repeat(newBlockLevel - oldBlockLevel) {
|
||||||
|
extraIndents.add(addedThisLine)
|
||||||
|
}
|
||||||
|
} else if (newBlockLevel < oldBlockLevel) {
|
||||||
|
repeat(oldBlockLevel - newBlockLevel) {
|
||||||
|
if (extraIndents.isNotEmpty()) extraIndents.removeAt(extraIndents.size - 1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
inBlockComment = nextInBlockComment
|
inBlockComment = nextInBlockComment
|
||||||
|
|
||||||
// Update awaitingSingleIndent based on current line
|
// Update awaitingExtraIndent based on current line
|
||||||
if (applyAwaiting && trimmedStart.isNotEmpty()) {
|
if (applyAwaiting && trimmedStart.isNotEmpty()) {
|
||||||
// we have just consumed the body line
|
// we have just applied it.
|
||||||
awaitingSingleIndent = false
|
val endsWithBrace = code.trimEnd().endsWith("{")
|
||||||
|
if (!endsWithBrace && isControlHeaderNoBrace(code)) {
|
||||||
|
// It's another header, increment
|
||||||
|
awaitingExtraIndent += if (isAccessor) 2 else 1
|
||||||
|
} else {
|
||||||
|
// It's the body, reset
|
||||||
|
awaitingExtraIndent = 0
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// start awaiting if current line is a control header without '{'
|
// start awaiting if current line is a control header without '{'
|
||||||
val endsWithBrace = code.trimEnd().endsWith("{")
|
val endsWithBrace = code.trimEnd().endsWith("{")
|
||||||
if (!endsWithBrace && isControlHeaderNoBrace(code)) {
|
if (!endsWithBrace && isControlHeaderNoBrace(code)) {
|
||||||
awaitingSingleIndent = true
|
awaitingExtraIndent = if (isAccessor) 2 else 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -196,9 +246,6 @@ object LyngFormatter {
|
|||||||
return applyControlledWrapping(spacedText, config)
|
return applyControlledWrapping(spacedText, config)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startsWithWord(s: String, w: String): Boolean =
|
|
||||||
s.startsWith(w) && s.getOrNull(w.length)?.let { !it.isLetterOrDigit() && it != '_' } != false
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Reindents a slice of [text] specified by [range] and returns a new string with that slice replaced.
|
* Reindents a slice of [text] specified by [range] and returns a new string with that slice replaced.
|
||||||
* By default, preserves the base indent of the first line in the slice (so the block stays at
|
* By default, preserves the base indent of the first line in the slice (so the block stays at
|
||||||
@@ -241,7 +288,20 @@ object LyngFormatter {
|
|||||||
i++
|
i++
|
||||||
}
|
}
|
||||||
// Normalize collected base indent: replace tabs with spaces
|
// Normalize collected base indent: replace tabs with spaces
|
||||||
var baseIndent = if (onlyWs) base.toString().replace("\t", " ".repeat(config.indentSize)) else ""
|
var baseIndent = if (onlyWs) {
|
||||||
|
if (start == lineStart) {
|
||||||
|
// Range starts at line start, pick up this line's indentation as base
|
||||||
|
var k = start
|
||||||
|
val lineIndent = StringBuilder()
|
||||||
|
while (k < text.length && text[k] != '\n' && (text[k] == ' ' || text[k] == '\t')) {
|
||||||
|
lineIndent.append(text[k])
|
||||||
|
k++
|
||||||
|
}
|
||||||
|
lineIndent.toString().replace("\t", " ".repeat(config.indentSize))
|
||||||
|
} else {
|
||||||
|
base.toString().replace("\t", " ".repeat(config.indentSize))
|
||||||
|
}
|
||||||
|
} else ""
|
||||||
var parentBaseIndent: String? = baseIndent
|
var parentBaseIndent: String? = baseIndent
|
||||||
if (baseIndent.isEmpty()) {
|
if (baseIndent.isEmpty()) {
|
||||||
// Fallback: use the indent of the nearest previous non-empty line as base.
|
// Fallback: use the indent of the nearest previous non-empty line as base.
|
||||||
@@ -417,7 +477,7 @@ private fun splitIntoParts(
|
|||||||
private fun applyMinimalSpacingRules(code: String): String {
|
private fun applyMinimalSpacingRules(code: String): String {
|
||||||
var s = code
|
var s = code
|
||||||
// Ensure space before '(' for control-flow keywords
|
// Ensure space before '(' for control-flow keywords
|
||||||
s = s.replace(Regex("\\b(if|for|while)\\("), "$1 (")
|
s = s.replace(Regex("\\b(if|for|while|return|break|continue)\\("), "$1 (")
|
||||||
// Space before '{' for control-flow headers only (avoid function declarations)
|
// Space before '{' for control-flow headers only (avoid function declarations)
|
||||||
s = s.replace(Regex("\\b(if|for|while)(\\s*\\([^)]*\\))\\s*\\{"), "$1$2 {")
|
s = s.replace(Regex("\\b(if|for|while)(\\s*\\([^)]*\\))\\s*\\{"), "$1$2 {")
|
||||||
s = s.replace(Regex("\\belse\\s+if(\\s*\\([^)]*\\))\\s*\\{"), "else if$1 {")
|
s = s.replace(Regex("\\belse\\s+if(\\s*\\([^)]*\\))\\s*\\{"), "else if$1 {")
|
||||||
@@ -438,6 +498,8 @@ private fun applyMinimalSpacingRules(code: String): String {
|
|||||||
s = s.replace(Regex("(\\bcatch\\s*\\([^)]*\\))\\s*\\{"), "$1 {")
|
s = s.replace(Regex("(\\bcatch\\s*\\([^)]*\\))\\s*\\{"), "$1 {")
|
||||||
// Ensure space before '(' for catch parameter
|
// Ensure space before '(' for catch parameter
|
||||||
s = s.replace(Regex("\\bcatch\\("), "catch (")
|
s = s.replace(Regex("\\bcatch\\("), "catch (")
|
||||||
|
// Remove space between control keyword and label: return @label -> return@label
|
||||||
|
s = s.replace(Regex("\\b(return|break|continue)\\s+(@[\\p{L}_][\\p{L}\\p{N}_]*)"), "$1$2")
|
||||||
// Remove spaces just inside parentheses/brackets: "( a )" -> "(a)"
|
// Remove spaces just inside parentheses/brackets: "( a )" -> "(a)"
|
||||||
s = s.replace(Regex("\\(\\s+"), "(")
|
s = s.replace(Regex("\\(\\s+"), "(")
|
||||||
// Do not strip leading indentation before a closing bracket/paren on its own line
|
// Do not strip leading indentation before a closing bracket/paren on its own line
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -41,11 +41,12 @@ private val fallbackKeywordIds = setOf(
|
|||||||
// boolean operators
|
// boolean operators
|
||||||
"and", "or", "not",
|
"and", "or", "not",
|
||||||
// declarations & modifiers
|
// declarations & modifiers
|
||||||
"fun", "fn", "class", "enum", "val", "var", "import", "package",
|
"fun", "fn", "class", "interface", "enum", "val", "var", "import", "package",
|
||||||
"private", "protected", "static", "open", "extern",
|
"abstract", "closed", "override",
|
||||||
|
"private", "protected", "static", "open", "extern", "init", "get", "set", "by",
|
||||||
// control flow and misc
|
// control flow and misc
|
||||||
"if", "else", "when", "while", "do", "for", "try", "catch", "finally",
|
"if", "else", "when", "while", "do", "for", "try", "catch", "finally",
|
||||||
"throw", "return", "break", "continue", "this", "null", "true", "false"
|
"throw", "return", "break", "continue", "this", "null", "true", "false", "unset"
|
||||||
)
|
)
|
||||||
|
|
||||||
/** Maps lexer token type (and sometimes value) to a [HighlightKind]. */
|
/** Maps lexer token type (and sometimes value) to a [HighlightKind]. */
|
||||||
@@ -73,7 +74,7 @@ private fun kindOf(type: Type, value: String): HighlightKind? = when (type) {
|
|||||||
Type.COMMA, Type.SEMICOLON, Type.COLON -> HighlightKind.Punctuation
|
Type.COMMA, Type.SEMICOLON, Type.COLON -> HighlightKind.Punctuation
|
||||||
|
|
||||||
// textual control keywords
|
// textual control keywords
|
||||||
Type.IN, Type.NOTIN, Type.IS, Type.NOTIS, Type.AS, Type.ASNULL,
|
Type.IN, Type.NOTIN, Type.IS, Type.NOTIS, Type.AS, Type.ASNULL, Type.BY, Type.OBJECT,
|
||||||
Type.AND, Type.OR, Type.NOT -> HighlightKind.Keyword
|
Type.AND, Type.OR, Type.NOT -> HighlightKind.Keyword
|
||||||
|
|
||||||
// labels / annotations
|
// labels / annotations
|
||||||
@@ -81,7 +82,7 @@ private fun kindOf(type: Type, value: String): HighlightKind? = when (type) {
|
|||||||
|
|
||||||
// operators and symbolic constructs
|
// operators and symbolic constructs
|
||||||
Type.PLUS, Type.MINUS, Type.STAR, Type.SLASH, Type.PERCENT,
|
Type.PLUS, Type.MINUS, Type.STAR, Type.SLASH, Type.PERCENT,
|
||||||
Type.ASSIGN, Type.PLUSASSIGN, Type.MINUSASSIGN, Type.STARASSIGN, Type.SLASHASSIGN, Type.PERCENTASSIGN,
|
Type.ASSIGN, Type.PLUSASSIGN, Type.MINUSASSIGN, Type.STARASSIGN, Type.SLASHASSIGN, Type.PERCENTASSIGN, Type.IFNULLASSIGN,
|
||||||
Type.PLUS2, Type.MINUS2,
|
Type.PLUS2, Type.MINUS2,
|
||||||
Type.EQ, Type.NEQ, Type.LT, Type.LTE, Type.GT, Type.GTE, Type.REF_EQ, Type.REF_NEQ, Type.MATCH, Type.NOTMATCH,
|
Type.EQ, Type.NEQ, Type.LT, Type.LTE, Type.GT, Type.GTE, Type.REF_EQ, Type.REF_NEQ, Type.MATCH, Type.NOTMATCH,
|
||||||
Type.DOT, Type.ARROW, Type.EQARROW, Type.QUESTION, Type.COLONCOLON,
|
Type.DOT, Type.ARROW, Type.EQARROW, Type.QUESTION, Type.COLONCOLON,
|
||||||
|
|||||||
@@ -112,8 +112,8 @@ object BuiltinDocRegistry : BuiltinDocSource {
|
|||||||
fun extensionMemberNamesFor(className: String): List<String> {
|
fun extensionMemberNamesFor(className: String): List<String> {
|
||||||
val src = try { rootLyng } catch (_: Throwable) { null } ?: return emptyList()
|
val src = try { rootLyng } catch (_: Throwable) { null } ?: return emptyList()
|
||||||
val out = LinkedHashSet<String>()
|
val out = LinkedHashSet<String>()
|
||||||
// Match lines like: fun String.trim(...) or val Int.isEven = ...
|
// Match lines like: fun String.trim(...) or val Int.isEven = ... (allowing modifiers)
|
||||||
val re = Regex("^\\s*(?:fun|val|var)\\s+${className}\\.([A-Za-z_][A-Za-z0-9_]*)\\b", RegexOption.MULTILINE)
|
val re = Regex("^\\s*(?:(?:abstract|override|closed|private|protected|static|open|extern)\\s+)*(?:fun|val|var)\\s+${className}\\.([A-Za-z_][A-Za-z0-9_]*)\\b", RegexOption.MULTILINE)
|
||||||
re.findAll(src).forEach { m ->
|
re.findAll(src).forEach { m ->
|
||||||
val name = m.groupValues.getOrNull(1)?.trim()
|
val name = m.groupValues.getOrNull(1)?.trim()
|
||||||
if (!name.isNullOrEmpty()) out.add(name)
|
if (!name.isNullOrEmpty()) out.add(name)
|
||||||
@@ -371,20 +371,20 @@ private object StdlibInlineDocIndex {
|
|||||||
else -> {
|
else -> {
|
||||||
// Non-comment, non-blank: try to match a declaration just after comments
|
// Non-comment, non-blank: try to match a declaration just after comments
|
||||||
if (buf.isNotEmpty()) {
|
if (buf.isNotEmpty()) {
|
||||||
// fun/val/var Class.name( ... )
|
// fun/val/var Class.name( ... ) (allowing modifiers)
|
||||||
val mExt = Regex("^(?:fun|val|var)\\s+([A-Za-z_][A-Za-z0-9_]*)\\.([A-Za-z_][A-Za-z0-9_]*)\\b").find(line)
|
val mExt = Regex("^(?:(?:abstract|override|closed|private|protected|static|open|extern)\\s+)*(?:fun|val|var)\\s+([A-Za-z_][A-Za-z0-9_]*)\\.([A-Za-z_][A-Za-z0-9_]*)\\b").find(line)
|
||||||
if (mExt != null) {
|
if (mExt != null) {
|
||||||
val (cls, name) = mExt.destructured
|
val (cls, name) = mExt.destructured
|
||||||
flushTo(Key.Method(cls, name))
|
flushTo(Key.Method(cls, name))
|
||||||
} else {
|
} else {
|
||||||
// fun name( ... )
|
// fun name( ... ) (allowing modifiers)
|
||||||
val mTop = Regex("^fun\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(").find(line)
|
val mTop = Regex("^(?:(?:abstract|override|closed|private|protected|static|open|extern)\\s+)*fun\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(").find(line)
|
||||||
if (mTop != null) {
|
if (mTop != null) {
|
||||||
val (name) = mTop.destructured
|
val (name) = mTop.destructured
|
||||||
flushTo(Key.TopFun(name))
|
flushTo(Key.TopFun(name))
|
||||||
} else {
|
} else {
|
||||||
// class Name
|
// class/interface Name (allowing modifiers)
|
||||||
val mClass = Regex("^class\\s+([A-Za-z_][A-Za-z0-9_]*)\\b").find(line)
|
val mClass = Regex("^(?:(?:abstract|private|protected|static|open|extern)\\s+)*(?:class|interface)\\s+([A-Za-z_][A-Za-z0-9_]*)\\b").find(line)
|
||||||
if (mClass != null) {
|
if (mClass != null) {
|
||||||
val (name) = mClass.destructured
|
val (name) = mClass.destructured
|
||||||
flushTo(Key.Clazz(name))
|
flushTo(Key.Clazz(name))
|
||||||
|
|||||||
@@ -96,8 +96,7 @@ object CompletionEngineLight {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Global identifiers: params > local decls > imported > stdlib; Functions > Classes > Values; alphabetical
|
// Global identifiers: params > local decls > imported > stdlib; Functions > Classes > Values; alphabetical
|
||||||
mini?.let { m ->
|
val decls = mini.declarations
|
||||||
val decls = m.declarations
|
|
||||||
val funs = decls.filterIsInstance<MiniFunDecl>().sortedBy { it.name.lowercase() }
|
val funs = decls.filterIsInstance<MiniFunDecl>().sortedBy { it.name.lowercase() }
|
||||||
val classes = decls.filterIsInstance<MiniClassDecl>().sortedBy { it.name.lowercase() }
|
val classes = decls.filterIsInstance<MiniClassDecl>().sortedBy { it.name.lowercase() }
|
||||||
val enums = decls.filterIsInstance<MiniEnumDecl>().sortedBy { it.name.lowercase() }
|
val enums = decls.filterIsInstance<MiniEnumDecl>().sortedBy { it.name.lowercase() }
|
||||||
@@ -106,7 +105,6 @@ object CompletionEngineLight {
|
|||||||
classes.forEach { offerDeclAdd(out, prefix, it) }
|
classes.forEach { offerDeclAdd(out, prefix, it) }
|
||||||
enums.forEach { offerDeclAdd(out, prefix, it) }
|
enums.forEach { offerDeclAdd(out, prefix, it) }
|
||||||
vals.forEach { offerDeclAdd(out, prefix, it) }
|
vals.forEach { offerDeclAdd(out, prefix, it) }
|
||||||
}
|
|
||||||
|
|
||||||
// Imported and builtin
|
// Imported and builtin
|
||||||
val (nonStd, std) = imported.partition { it != "lyng.stdlib" }
|
val (nonStd, std) = imported.partition { it != "lyng.stdlib" }
|
||||||
@@ -192,7 +190,7 @@ object CompletionEngineLight {
|
|||||||
val chosen = variants.asSequence()
|
val chosen = variants.asSequence()
|
||||||
.filterIsInstance<MiniMemberValDecl>()
|
.filterIsInstance<MiniMemberValDecl>()
|
||||||
.firstOrNull { it.type != null } ?: rep
|
.firstOrNull { it.type != null } ?: rep
|
||||||
val ci = CompletionItem(name, Kind.Field, typeText = typeOf((chosen as MiniMemberValDecl).type))
|
val ci = CompletionItem(name, Kind.Field, typeText = typeOf(chosen.type))
|
||||||
if (ci.name.startsWith(prefix, true)) out += ci
|
if (ci.name.startsWith(prefix, true)) out += ci
|
||||||
}
|
}
|
||||||
is MiniInitDecl -> {}
|
is MiniInitDecl -> {}
|
||||||
|
|||||||
@@ -435,16 +435,16 @@ object DocLookupUtils {
|
|||||||
if (start !in 0..end) return emptyMap()
|
if (start !in 0..end) return emptyMap()
|
||||||
val body = text.substring(start, end)
|
val body = text.substring(start, end)
|
||||||
val map = LinkedHashMap<String, ScannedSig>()
|
val map = LinkedHashMap<String, ScannedSig>()
|
||||||
// fun name(params): Type
|
// fun name(params): Type (allowing modifiers like abstract, override, closed)
|
||||||
val funRe = Regex("^\\s*fun\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(([^)]*)\\)\\s*(?::\\s*([A-Za-z_][A-Za-z0-9_]*))?", RegexOption.MULTILINE)
|
val funRe = Regex("^\\s*(?:(?:abstract|override|closed|private|protected|static|open|extern)\\s+)*fun\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*\\(([^)]*)\\)\\s*(?::\\s*([A-Za-z_][A-Za-z0-9_]*))?", RegexOption.MULTILINE)
|
||||||
for (m in funRe.findAll(body)) {
|
for (m in funRe.findAll(body)) {
|
||||||
val name = m.groupValues.getOrNull(1) ?: continue
|
val name = m.groupValues.getOrNull(1) ?: continue
|
||||||
val params = m.groupValues.getOrNull(2)?.split(',')?.mapNotNull { it.trim().takeIf { it.isNotEmpty() } } ?: emptyList()
|
val params = m.groupValues.getOrNull(2)?.split(',')?.mapNotNull { it.trim().takeIf { it.isNotEmpty() } } ?: emptyList()
|
||||||
val type = m.groupValues.getOrNull(3)?.takeIf { it.isNotBlank() }
|
val type = m.groupValues.getOrNull(3)?.takeIf { it.isNotBlank() }
|
||||||
map[name] = ScannedSig("fun", params, type)
|
map[name] = ScannedSig("fun", params, type)
|
||||||
}
|
}
|
||||||
// val/var name: Type
|
// val/var name: Type (allowing modifiers)
|
||||||
val valRe = Regex("^\\s*(val|var)\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*(?::\\s*([A-Za-z_][A-Za-z0-9_]*))?", RegexOption.MULTILINE)
|
val valRe = Regex("^\\s*(?:(?:abstract|override|closed|private|protected|static|open|extern)\\s+)*(val|var)\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*(?::\\s*([A-Za-z_][A-Za-z0-9_]*))?", RegexOption.MULTILINE)
|
||||||
for (m in valRe.findAll(body)) {
|
for (m in valRe.findAll(body)) {
|
||||||
val kind = m.groupValues.getOrNull(1) ?: continue
|
val kind = m.groupValues.getOrNull(1) ?: continue
|
||||||
val name = m.groupValues.getOrNull(2) ?: continue
|
val name = m.groupValues.getOrNull(2) ?: continue
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -89,18 +89,12 @@ open class Obj {
|
|||||||
for (cls in objClass.mro) {
|
for (cls in objClass.mro) {
|
||||||
if (cls.className == "Obj") break
|
if (cls.className == "Obj") break
|
||||||
val rec = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
val rec = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
||||||
if (rec != null) {
|
if (rec != null && !rec.isAbstract && rec.type != ObjRecord.Type.Property) {
|
||||||
val decl = rec.declaringClass ?: cls
|
val decl = rec.declaringClass ?: cls
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(ObjAccessException(scope, "can't invoke ${name}: not visible (declared in ${decl.className}, caller ${caller?.className ?: "?"})"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't invoke ${name}: not visible (declared in ${decl.className}, caller ${caller?.className ?: "?"})"))
|
||||||
val saved = scope.currentClassCtx
|
return rec.value.invoke(scope, this, args, decl)
|
||||||
scope.currentClassCtx = decl
|
|
||||||
try {
|
|
||||||
return rec.value.invoke(scope, this, args)
|
|
||||||
} finally {
|
|
||||||
scope.currentClassCtx = saved
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,14 +111,8 @@ open class Obj {
|
|||||||
val decl = rec.declaringClass ?: cls
|
val decl = rec.declaringClass ?: cls
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(ObjAccessException(scope, "can't invoke ${name}: not visible (declared in ${decl.className}, caller ${caller?.className ?: "?"})"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't invoke ${name}: not visible (declared in ${decl.className}, caller ${caller?.className ?: "?"})"))
|
||||||
val saved = scope.currentClassCtx
|
return rec.value.invoke(scope, this, args, decl)
|
||||||
scope.currentClassCtx = decl
|
|
||||||
try {
|
|
||||||
return rec.value.invoke(scope, this, args)
|
|
||||||
} finally {
|
|
||||||
scope.currentClassCtx = saved
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,9 +137,20 @@ open class Obj {
|
|||||||
// methods that to override
|
// methods that to override
|
||||||
|
|
||||||
open suspend fun compareTo(scope: Scope, other: Obj): Int {
|
open suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
|
if (other === this) return 0
|
||||||
|
if (other === ObjNull || other === ObjUnset || other === ObjVoid) return 2
|
||||||
scope.raiseNotImplemented()
|
scope.raiseNotImplemented()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
open suspend fun equals(scope: Scope, other: Obj): Boolean {
|
||||||
|
if (other === this) return true
|
||||||
|
return try {
|
||||||
|
compareTo(scope, other) == 0
|
||||||
|
} catch (e: ExecutionError) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
open suspend fun contains(scope: Scope, other: Obj): Boolean {
|
open suspend fun contains(scope: Scope, other: Obj): Boolean {
|
||||||
return invokeInstanceMethod(scope, "contains", other).toBool()
|
return invokeInstanceMethod(scope, "contains", other).toBool()
|
||||||
}
|
}
|
||||||
@@ -345,8 +344,12 @@ open class Obj {
|
|||||||
// 1. Hierarchy members (excluding root fallback)
|
// 1. Hierarchy members (excluding root fallback)
|
||||||
for (cls in objClass.mro) {
|
for (cls in objClass.mro) {
|
||||||
if (cls.className == "Obj") break
|
if (cls.className == "Obj") break
|
||||||
cls.members[name]?.let { return resolveRecord(scope, it, name, it.declaringClass) }
|
val rec = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
||||||
cls.classScope?.objects?.get(name)?.let { return resolveRecord(scope, it, name, it.declaringClass) }
|
if (rec != null) {
|
||||||
|
if (!rec.isAbstract) {
|
||||||
|
return resolveRecord(scope, rec, name, rec.declaringClass)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. Extensions
|
// 2. Extensions
|
||||||
@@ -370,7 +373,14 @@ open class Obj {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
protected suspend fun resolveRecord(scope: Scope, obj: ObjRecord, name: String, decl: ObjClass?): ObjRecord {
|
open suspend fun resolveRecord(scope: Scope, obj: ObjRecord, name: String, decl: ObjClass?): ObjRecord {
|
||||||
|
if (obj.type == ObjRecord.Type.Delegated) {
|
||||||
|
val del = obj.delegate ?: scope.raiseError("Internal error: delegated property $name has no delegate")
|
||||||
|
return obj.copy(
|
||||||
|
value = del.invokeInstanceMethod(scope, "getValue", Arguments(this, ObjString(name))),
|
||||||
|
type = ObjRecord.Type.Other
|
||||||
|
)
|
||||||
|
}
|
||||||
val value = obj.value
|
val value = obj.value
|
||||||
if (value is ObjProperty) {
|
if (value is ObjProperty) {
|
||||||
return ObjRecord(value.callGetter(scope, this, decl), obj.isMutable)
|
return ObjRecord(value.callGetter(scope, this, decl), obj.isMutable)
|
||||||
@@ -381,7 +391,7 @@ open class Obj {
|
|||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
// Check visibility for non-property members here if they weren't checked before
|
// Check visibility for non-property members here if they weren't checked before
|
||||||
if (!canAccessMember(obj.visibility, decl, caller))
|
if (!canAccessMember(obj.visibility, decl, caller))
|
||||||
scope.raiseError(ObjAccessException(scope, "can't access field ${name}: not visible (declared in ${decl?.className ?: "?"}, caller ${caller?.className ?: "?"})"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't access field ${name}: not visible (declared in ${decl?.className ?: "?"}, caller ${caller?.className ?: "?"})"))
|
||||||
return obj
|
return obj
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,8 +401,11 @@ open class Obj {
|
|||||||
// 1. Hierarchy members (excluding root fallback)
|
// 1. Hierarchy members (excluding root fallback)
|
||||||
for (cls in objClass.mro) {
|
for (cls in objClass.mro) {
|
||||||
if (cls.className == "Obj") break
|
if (cls.className == "Obj") break
|
||||||
field = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
val rec = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
||||||
if (field != null) break
|
if (rec != null && !rec.isAbstract) {
|
||||||
|
field = rec
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// 2. Extensions
|
// 2. Extensions
|
||||||
if (field == null) {
|
if (field == null) {
|
||||||
@@ -414,9 +427,12 @@ open class Obj {
|
|||||||
|
|
||||||
val decl = field.declaringClass
|
val decl = field.declaringClass
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(field.visibility, decl, caller))
|
if (!canAccessMember(field.effectiveWriteVisibility, decl, caller))
|
||||||
scope.raiseError(ObjAccessException(scope, "can't assign field ${name}: not visible (declared in ${decl?.className ?: "?"}, caller ${caller?.className ?: "?"})"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't assign field ${name}: not visible (declared in ${decl?.className ?: "?"}, caller ${caller?.className ?: "?"})"))
|
||||||
if (field.value is ObjProperty) {
|
if (field.type == ObjRecord.Type.Delegated) {
|
||||||
|
val del = field.delegate ?: scope.raiseError("Internal error: delegated property $name has no delegate")
|
||||||
|
del.invokeInstanceMethod(scope, "setValue", Arguments(this, ObjString(name), newValue))
|
||||||
|
} else if (field.value is ObjProperty) {
|
||||||
(field.value as ObjProperty).callSetter(scope, this, newValue, decl)
|
(field.value as ObjProperty).callSetter(scope, this, newValue, decl)
|
||||||
} else if (field.isMutable) field.value = newValue else scope.raiseError("can't assign to read-only field: $name")
|
} else if (field.isMutable) field.value = newValue else scope.raiseError("can't assign to read-only field: $name")
|
||||||
}
|
}
|
||||||
@@ -435,13 +451,16 @@ open class Obj {
|
|||||||
scope.raiseNotImplemented()
|
scope.raiseNotImplemented()
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun invoke(scope: Scope, thisObj: Obj, args: Arguments): Obj =
|
suspend fun invoke(scope: Scope, thisObj: Obj, args: Arguments, declaringClass: ObjClass? = null): Obj =
|
||||||
if (PerfFlags.SCOPE_POOL)
|
if (PerfFlags.SCOPE_POOL)
|
||||||
scope.withChildFrame(args, newThisObj = thisObj) { child ->
|
scope.withChildFrame(args, newThisObj = thisObj) { child ->
|
||||||
|
if (declaringClass != null) child.currentClassCtx = declaringClass
|
||||||
callOn(child)
|
callOn(child)
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
callOn(scope.createChildScope(scope.pos, args = args, newThisObj = thisObj))
|
callOn(scope.createChildScope(scope.pos, args = args, newThisObj = thisObj).also {
|
||||||
|
if (declaringClass != null) it.currentClassCtx = declaringClass
|
||||||
|
})
|
||||||
|
|
||||||
suspend fun invoke(scope: Scope, thisObj: Obj, vararg args: Obj): Obj =
|
suspend fun invoke(scope: Scope, thisObj: Obj, vararg args: Obj): Obj =
|
||||||
callOn(
|
callOn(
|
||||||
@@ -663,6 +682,50 @@ object ObjNull : Obj() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
@SerialName("unset")
|
||||||
|
object ObjUnset : Obj() {
|
||||||
|
override suspend fun compareTo(scope: Scope, other: Obj): Int = if (other === this) 0 else -1
|
||||||
|
override fun equals(other: Any?): Boolean = other === this
|
||||||
|
override fun toString(): String = "Unset"
|
||||||
|
|
||||||
|
override suspend fun readField(scope: Scope, name: String): ObjRecord = scope.raiseUnset()
|
||||||
|
override suspend fun invokeInstanceMethod(
|
||||||
|
scope: Scope,
|
||||||
|
name: String,
|
||||||
|
args: Arguments,
|
||||||
|
onNotFoundResult: (suspend () -> Obj?)?
|
||||||
|
): Obj = scope.raiseUnset()
|
||||||
|
|
||||||
|
override suspend fun getAt(scope: Scope, index: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun putAt(scope: Scope, index: Obj, newValue: Obj) = scope.raiseUnset()
|
||||||
|
override suspend fun callOn(scope: Scope): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun plus(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun minus(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun negate(scope: Scope): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun mul(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun div(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun mod(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun logicalNot(scope: Scope): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun logicalAnd(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun logicalOr(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun operatorMatch(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun bitAnd(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun bitOr(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun bitXor(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun shl(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun shr(scope: Scope, other: Obj): Obj = scope.raiseUnset()
|
||||||
|
override suspend fun bitNot(scope: Scope): Obj = scope.raiseUnset()
|
||||||
|
|
||||||
|
override val objClass: ObjClass by lazy {
|
||||||
|
object : ObjClass("Unset") {
|
||||||
|
override suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj {
|
||||||
|
return ObjUnset
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* TODO: get rid of it. Maybe we ise some Lyng inheritance instead
|
* TODO: get rid of it. Maybe we ise some Lyng inheritance instead
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ private object ClassIdGen { var c: Long = 1L; fun nextId(): Long = c++ }
|
|||||||
|
|
||||||
val ObjClassType by lazy {
|
val ObjClassType by lazy {
|
||||||
ObjClass("Class").apply {
|
ObjClass("Class").apply {
|
||||||
|
addProperty("className", getter = { thisAs<ObjClass>().classNameObj })
|
||||||
addFnDoc(
|
addFnDoc(
|
||||||
name = "name",
|
name = "name",
|
||||||
doc = "Simple name of this class (without package).",
|
doc = "Simple name of this class (without package).",
|
||||||
@@ -91,6 +92,10 @@ open class ObjClass(
|
|||||||
vararg parents: ObjClass,
|
vararg parents: ObjClass,
|
||||||
) : Obj() {
|
) : Obj() {
|
||||||
|
|
||||||
|
var isAnonymous: Boolean = false
|
||||||
|
|
||||||
|
var isAbstract: Boolean = false
|
||||||
|
|
||||||
// Stable identity and simple structural version for PICs
|
// Stable identity and simple structural version for PICs
|
||||||
val classId: Long = ClassIdGen.nextId()
|
val classId: Long = ClassIdGen.nextId()
|
||||||
var layoutVersion: Int = 0
|
var layoutVersion: Int = 0
|
||||||
@@ -178,7 +183,10 @@ open class ObjClass(
|
|||||||
val mro: List<ObjClass> by lazy {
|
val mro: List<ObjClass> by lazy {
|
||||||
val base = c3Linearize(this, mutableMapOf())
|
val base = c3Linearize(this, mutableMapOf())
|
||||||
if (this.className == "Obj" || base.any { it.className == "Obj" }) base
|
if (this.className == "Obj" || base.any { it.className == "Obj" }) base
|
||||||
else base + rootObjectType
|
else {
|
||||||
|
val root = Obj.rootObjectType
|
||||||
|
base + root
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Parents in C3 order (no self). */
|
/** Parents in C3 order (no self). */
|
||||||
@@ -189,7 +197,7 @@ open class ObjClass(
|
|||||||
val list = mutableListOf<String>()
|
val list = mutableListOf<String>()
|
||||||
if (includeSelf) list += className
|
if (includeSelf) list += className
|
||||||
mroParents.forEach { list += it.className }
|
mroParents.forEach { list += it.className }
|
||||||
return list.joinToString(" → ")
|
return list.joinToString(", ")
|
||||||
}
|
}
|
||||||
|
|
||||||
override val objClass: ObjClass by lazy { ObjClassType }
|
override val objClass: ObjClass by lazy { ObjClassType }
|
||||||
@@ -204,6 +212,7 @@ open class ObjClass(
|
|||||||
override suspend fun compareTo(scope: Scope, other: Obj): Int = if (other === this) 0 else -1
|
override suspend fun compareTo(scope: Scope, other: Obj): Int = if (other === this) 0 else -1
|
||||||
|
|
||||||
override suspend fun callOn(scope: Scope): Obj {
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
if (isAbstract) scope.raiseError("can't instantiate abstract class $className")
|
||||||
val instance = createInstance(scope)
|
val instance = createInstance(scope)
|
||||||
initializeInstance(instance, scope.args, runConstructors = true)
|
initializeInstance(instance, scope.args, runConstructors = true)
|
||||||
return instance
|
return instance
|
||||||
@@ -225,16 +234,16 @@ open class ObjClass(
|
|||||||
// This mirrors Obj.autoInstanceScope behavior for ad-hoc scopes and makes fb.method() resolution robust
|
// This mirrors Obj.autoInstanceScope behavior for ad-hoc scopes and makes fb.method() resolution robust
|
||||||
// 1) members-defined methods
|
// 1) members-defined methods
|
||||||
for ((k, v) in members) {
|
for ((k, v) in members) {
|
||||||
if (v.value is Statement) {
|
if (v.value is Statement || v.type == ObjRecord.Type.Delegated) {
|
||||||
instance.instanceScope.objects[k] = v
|
instance.instanceScope.objects[k] = if (v.type == ObjRecord.Type.Delegated) v.copy() else v
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 2) class-scope methods registered during class-body execution
|
// 2) class-scope methods registered during class-body execution
|
||||||
classScope?.objects?.forEach { (k, rec) ->
|
classScope?.objects?.forEach { (k, rec) ->
|
||||||
if (rec.value is Statement) {
|
if (rec.value is Statement || rec.type == ObjRecord.Type.Delegated) {
|
||||||
// if not already present, copy reference for dispatch
|
// if not already present, copy reference for dispatch
|
||||||
if (!instance.instanceScope.objects.containsKey(k)) {
|
if (!instance.instanceScope.objects.containsKey(k)) {
|
||||||
instance.instanceScope.objects[k] = rec
|
instance.instanceScope.objects[k] = if (rec.type == ObjRecord.Type.Delegated) rec.copy() else rec
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -345,17 +354,60 @@ open class ObjClass(
|
|||||||
initialValue: Obj,
|
initialValue: Obj,
|
||||||
isMutable: Boolean = false,
|
isMutable: Boolean = false,
|
||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
|
writeVisibility: Visibility? = null,
|
||||||
pos: Pos = Pos.builtIn,
|
pos: Pos = Pos.builtIn,
|
||||||
declaringClass: ObjClass? = this
|
declaringClass: ObjClass? = this,
|
||||||
) {
|
isAbstract: Boolean = false,
|
||||||
|
isClosed: Boolean = false,
|
||||||
|
isOverride: Boolean = false,
|
||||||
|
type: ObjRecord.Type = ObjRecord.Type.Field,
|
||||||
|
): ObjRecord {
|
||||||
|
// Validation of override rules: only for non-system declarations
|
||||||
|
if (pos != Pos.builtIn) {
|
||||||
|
val existing = getInstanceMemberOrNull(name)
|
||||||
|
var actualOverride = false
|
||||||
|
if (existing != null && existing.declaringClass != this) {
|
||||||
|
// If the existing member is private in the ancestor, it's not visible for overriding.
|
||||||
|
// It should be treated as a new member in this class.
|
||||||
|
if (!existing.visibility.isPublic && !canAccessMember(existing.visibility, existing.declaringClass, this)) {
|
||||||
|
// It's effectively not there for us, so actualOverride remains false
|
||||||
|
} else {
|
||||||
|
actualOverride = true
|
||||||
|
// It's an override (implicit or explicit)
|
||||||
|
if (existing.isClosed)
|
||||||
|
throw ScriptError(pos, "can't override closed member $name from ${existing.declaringClass?.className}")
|
||||||
|
|
||||||
|
if (!isOverride)
|
||||||
|
throw ScriptError(pos, "member $name overrides parent member but 'override' keyword is missing")
|
||||||
|
|
||||||
|
if (visibility.ordinal > existing.visibility.ordinal)
|
||||||
|
throw ScriptError(pos, "can't narrow visibility of $name from ${existing.visibility} to $visibility")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isOverride && !actualOverride) {
|
||||||
|
throw ScriptError(pos, "member $name is marked 'override' but does not override anything")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Allow overriding ancestors: only prevent redefinition if THIS class already defines an immutable member
|
// Allow overriding ancestors: only prevent redefinition if THIS class already defines an immutable member
|
||||||
val existingInSelf = members[name]
|
val existingInSelf = members[name]
|
||||||
if (existingInSelf != null && existingInSelf.isMutable == false)
|
if (existingInSelf != null && existingInSelf.isMutable == false)
|
||||||
throw ScriptError(pos, "$name is already defined in $objClass")
|
throw ScriptError(pos, "$name is already defined in $objClass")
|
||||||
|
|
||||||
// Install/override in this class
|
// Install/override in this class
|
||||||
members[name] = ObjRecord(initialValue, isMutable, visibility, declaringClass = declaringClass)
|
val rec = ObjRecord(
|
||||||
|
initialValue, isMutable, visibility, writeVisibility,
|
||||||
|
declaringClass = declaringClass,
|
||||||
|
isAbstract = isAbstract,
|
||||||
|
isClosed = isClosed,
|
||||||
|
isOverride = isOverride,
|
||||||
|
type = type
|
||||||
|
)
|
||||||
|
members[name] = rec
|
||||||
// Structural change: bump layout version for PIC invalidation
|
// Structural change: bump layout version for PIC invalidation
|
||||||
layoutVersion += 1
|
layoutVersion += 1
|
||||||
|
return rec
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun initClassScope(): Scope {
|
private fun initClassScope(): Scope {
|
||||||
@@ -368,26 +420,38 @@ open class ObjClass(
|
|||||||
initialValue: Obj,
|
initialValue: Obj,
|
||||||
isMutable: Boolean = false,
|
isMutable: Boolean = false,
|
||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
pos: Pos = Pos.builtIn
|
writeVisibility: Visibility? = null,
|
||||||
) {
|
pos: Pos = Pos.builtIn,
|
||||||
|
type: ObjRecord.Type = ObjRecord.Type.Field
|
||||||
|
): ObjRecord {
|
||||||
initClassScope()
|
initClassScope()
|
||||||
val existing = classScope!!.objects[name]
|
val existing = classScope!!.objects[name]
|
||||||
if (existing != null)
|
if (existing != null)
|
||||||
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
|
throw ScriptError(pos, "$name is already defined in $objClass or one of its supertypes")
|
||||||
classScope!!.addItem(name, isMutable, initialValue, visibility)
|
val rec = classScope!!.addItem(name, isMutable, initialValue, visibility, writeVisibility, recordType = type)
|
||||||
// Structural change: bump layout version for PIC invalidation
|
// Structural change: bump layout version for PIC invalidation
|
||||||
layoutVersion += 1
|
layoutVersion += 1
|
||||||
|
return rec
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addFn(
|
fun addFn(
|
||||||
name: String,
|
name: String,
|
||||||
isOpen: Boolean = false,
|
isMutable: Boolean = false,
|
||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
|
writeVisibility: Visibility? = null,
|
||||||
declaringClass: ObjClass? = this,
|
declaringClass: ObjClass? = this,
|
||||||
code: suspend Scope.() -> Obj
|
isAbstract: Boolean = false,
|
||||||
|
isClosed: Boolean = false,
|
||||||
|
isOverride: Boolean = false,
|
||||||
|
pos: Pos = Pos.builtIn,
|
||||||
|
code: (suspend Scope.() -> Obj)? = null
|
||||||
) {
|
) {
|
||||||
val stmt = statement { code() }
|
val stmt = code?.let { statement { it() } } ?: ObjNull
|
||||||
createField(name, stmt, isOpen, visibility, Pos.builtIn, declaringClass)
|
createField(
|
||||||
|
name, stmt, isMutable, visibility, writeVisibility, pos, declaringClass,
|
||||||
|
isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride,
|
||||||
|
type = ObjRecord.Type.Fun
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addConst(name: String, value: Obj) = createField(name, value, isMutable = false)
|
fun addConst(name: String, value: Obj) = createField(name, value, isMutable = false)
|
||||||
@@ -397,18 +461,26 @@ open class ObjClass(
|
|||||||
getter: (suspend Scope.() -> Obj)? = null,
|
getter: (suspend Scope.() -> Obj)? = null,
|
||||||
setter: (suspend Scope.(Obj) -> Unit)? = null,
|
setter: (suspend Scope.(Obj) -> Unit)? = null,
|
||||||
visibility: Visibility = Visibility.Public,
|
visibility: Visibility = Visibility.Public,
|
||||||
declaringClass: ObjClass? = this
|
writeVisibility: Visibility? = null,
|
||||||
|
declaringClass: ObjClass? = this,
|
||||||
|
isAbstract: Boolean = false,
|
||||||
|
isClosed: Boolean = false,
|
||||||
|
isOverride: Boolean = false,
|
||||||
|
pos: Pos = Pos.builtIn,
|
||||||
) {
|
) {
|
||||||
val g = getter?.let { statement { it() } }
|
val g = getter?.let { statement { it() } }
|
||||||
val s = setter?.let { statement { it(requiredArg(0)); ObjVoid } }
|
val s = setter?.let { statement { it(requiredArg(0)); ObjVoid } }
|
||||||
val prop = ObjProperty(name, g, s)
|
val prop = if (isAbstract) ObjNull else ObjProperty(name, g, s)
|
||||||
members[name] = ObjRecord(prop, false, visibility, declaringClass, type = ObjRecord.Type.Property)
|
createField(
|
||||||
layoutVersion += 1
|
name, prop, false, visibility, writeVisibility, pos, declaringClass,
|
||||||
|
isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride,
|
||||||
|
type = ObjRecord.Type.Property
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
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 Scope.() -> Obj) {
|
fun addClassFn(name: String, isOpen: Boolean = false, code: suspend Scope.() -> Obj) {
|
||||||
createClassField(name, statement { code() }, isOpen)
|
createClassField(name, statement { code() }, isOpen, type = ObjRecord.Type.Fun)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -438,6 +510,38 @@ open class ObjClass(
|
|||||||
getInstanceMemberOrNull(name)
|
getInstanceMemberOrNull(name)
|
||||||
?: throw ScriptError(atPos, "symbol doesn't exist: $name")
|
?: throw ScriptError(atPos, "symbol doesn't exist: $name")
|
||||||
|
|
||||||
|
fun findFirstConcreteMember(name: String): ObjRecord? {
|
||||||
|
for (cls in mro) {
|
||||||
|
cls.members[name]?.let {
|
||||||
|
if (!it.isAbstract) return it
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun checkAbstractSatisfaction(pos: Pos) {
|
||||||
|
if (isAbstract) return
|
||||||
|
|
||||||
|
val missing = mutableSetOf<String>()
|
||||||
|
for (cls in mroParents) {
|
||||||
|
for ((name, rec) in cls.members) {
|
||||||
|
if (rec.isAbstract) {
|
||||||
|
val current = findFirstConcreteMember(name)
|
||||||
|
if (current == null) {
|
||||||
|
missing.add(name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missing.isNotEmpty()) {
|
||||||
|
throw ScriptError(
|
||||||
|
pos,
|
||||||
|
"class $className is not abstract and does not implement abstract members: ${missing.joinToString(", ")}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Resolve member starting from a specific ancestor class [start], not from this class.
|
* Resolve member starting from a specific ancestor class [start], not from this class.
|
||||||
* Searches [start] first, then traverses its linearized parents.
|
* Searches [start] first, then traverses its linearized parents.
|
||||||
@@ -458,15 +562,21 @@ open class ObjClass(
|
|||||||
|
|
||||||
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
||||||
classScope?.objects?.get(name)?.let {
|
classScope?.objects?.get(name)?.let {
|
||||||
if (it.visibility.isPublic) return it
|
if (it.visibility.isPublic) return resolveRecord(scope, it, name, this)
|
||||||
}
|
}
|
||||||
return super.readField(scope, name)
|
return super.readField(scope, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
||||||
initClassScope().objects[name]?.let {
|
initClassScope().objects[name]?.let { rec ->
|
||||||
if (it.isMutable) it.value = newValue
|
if (rec.type == ObjRecord.Type.Delegated) {
|
||||||
|
val del = rec.delegate ?: scope.raiseError("Internal error: delegated property $name has no delegate")
|
||||||
|
del.invokeInstanceMethod(scope, "setValue", Arguments(this, ObjString(name), newValue))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (rec.isMutable) rec.value = newValue
|
||||||
else scope.raiseIllegalAssignment("can't assign $name is not mutable")
|
else scope.raiseIllegalAssignment("can't assign $name is not mutable")
|
||||||
|
return
|
||||||
}
|
}
|
||||||
?: super.writeField(scope, name, newValue)
|
?: super.writeField(scope, name, newValue)
|
||||||
}
|
}
|
||||||
@@ -475,8 +585,26 @@ open class ObjClass(
|
|||||||
scope: Scope, name: String, args: Arguments,
|
scope: Scope, name: String, args: Arguments,
|
||||||
onNotFoundResult: (suspend () -> Obj?)?
|
onNotFoundResult: (suspend () -> Obj?)?
|
||||||
): Obj {
|
): Obj {
|
||||||
return classScope?.objects?.get(name)?.value?.invoke(scope, this, args)
|
getInstanceMemberOrNull(name)?.let { rec ->
|
||||||
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
val decl = rec.declaringClass ?: findDeclaringClassOf(name) ?: this
|
||||||
|
if (rec.type == ObjRecord.Type.Delegated) {
|
||||||
|
val del = rec.delegate ?: scope.raiseError("Internal error: delegated member $name has no delegate")
|
||||||
|
val allArgs = (listOf(this, ObjString(name)) + args.list).toTypedArray()
|
||||||
|
return del.invokeInstanceMethod(scope, "invoke", Arguments(*allArgs), onNotFoundResult = {
|
||||||
|
// Fallback: property delegation
|
||||||
|
val propVal = del.invokeInstanceMethod(scope, "getValue", Arguments(this, ObjString(name)))
|
||||||
|
propVal.invoke(scope, this, args, decl)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (rec.type == ObjRecord.Type.Fun) {
|
||||||
|
return rec.value.invoke(scope, this, args, decl)
|
||||||
|
} else {
|
||||||
|
// Resolved field or property value
|
||||||
|
val resolved = readField(scope, name)
|
||||||
|
return resolved.value.invoke(scope, this, args, decl)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
||||||
}
|
}
|
||||||
|
|
||||||
open suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
|
open suspend fun deserialize(scope: Scope, decoder: LynonDecoder, lynonType: LynonType?): Obj =
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -191,10 +191,13 @@ open class ObjException(
|
|||||||
"IllegalAssignmentException",
|
"IllegalAssignmentException",
|
||||||
"SymbolNotDefinedException",
|
"SymbolNotDefinedException",
|
||||||
"IterationEndException",
|
"IterationEndException",
|
||||||
"AccessException",
|
"IllegalAccessException",
|
||||||
"UnknownException",
|
"UnknownException",
|
||||||
"NotFoundException",
|
"NotFoundException",
|
||||||
"IllegalOperationException"
|
"IllegalOperationException",
|
||||||
|
"UnsetException",
|
||||||
|
"NotImplementedException",
|
||||||
|
"SyntaxError"
|
||||||
)) {
|
)) {
|
||||||
scope.addConst(name, getOrCreateExceptionClass(name))
|
scope.addConst(name, getOrCreateExceptionClass(name))
|
||||||
}
|
}
|
||||||
@@ -234,8 +237,8 @@ class ObjSymbolNotDefinedException(scope: Scope, message: String = "symbol is no
|
|||||||
class ObjIterationFinishedException(scope: Scope) :
|
class ObjIterationFinishedException(scope: Scope) :
|
||||||
ObjException("IterationEndException", scope, "iteration finished")
|
ObjException("IterationEndException", scope, "iteration finished")
|
||||||
|
|
||||||
class ObjAccessException(scope: Scope, message: String = "access not allowed error") :
|
class ObjIllegalAccessException(scope: Scope, message: String = "access not allowed error") :
|
||||||
ObjException("AccessException", scope, message)
|
ObjException("IllegalAccessException", scope, message)
|
||||||
|
|
||||||
class ObjUnknownException(scope: Scope, message: String = "access not allowed error") :
|
class ObjUnknownException(scope: Scope, message: String = "access not allowed error") :
|
||||||
ObjException("UnknownException", scope, message)
|
ObjException("UnknownException", scope, message)
|
||||||
@@ -245,3 +248,9 @@ class ObjIllegalOperationException(scope: Scope, message: String = "Operation is
|
|||||||
|
|
||||||
class ObjNotFoundException(scope: Scope, message: String = "not found") :
|
class ObjNotFoundException(scope: Scope, message: String = "not found") :
|
||||||
ObjException("NotFoundException", scope, message)
|
ObjException("NotFoundException", scope, message)
|
||||||
|
|
||||||
|
class ObjUnsetException(scope: Scope, message: String = "property is unset (not initialized)") :
|
||||||
|
ObjException("UnsetException", scope, message)
|
||||||
|
|
||||||
|
class ObjNotImplementedException(scope: Scope, message: String = "not implemented") :
|
||||||
|
ObjException("NotImplementedException", scope, message)
|
||||||
@@ -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.
|
||||||
@@ -31,7 +31,7 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
internal lateinit var instanceScope: Scope
|
internal lateinit var instanceScope: Scope
|
||||||
|
|
||||||
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
override suspend fun readField(scope: Scope, name: String): ObjRecord {
|
||||||
// Direct (unmangled) lookup first
|
// 1. Direct (unmangled) lookup first
|
||||||
instanceScope[name]?.let { rec ->
|
instanceScope[name]?.let { rec ->
|
||||||
val decl = rec.declaringClass
|
val decl = rec.declaringClass
|
||||||
// Allow unconditional access when accessing through `this` of the same instance
|
// Allow unconditional access when accessing through `this` of the same instance
|
||||||
@@ -40,33 +40,26 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjAccessException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't access field $name (declared in ${decl?.className ?: "?"})"
|
"can't access field $name (declared in ${decl?.className ?: "?"})"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (rec.type == ObjRecord.Type.Property) {
|
return resolveRecord(scope, rec, name, decl)
|
||||||
val prop = rec.value as ObjProperty
|
|
||||||
return rec.copy(value = prop.callGetter(scope, this, decl))
|
|
||||||
}
|
}
|
||||||
return rec
|
|
||||||
}
|
|
||||||
// Try MI-mangled lookup along linearization (C3 MRO): ClassName::name
|
|
||||||
val cls = objClass
|
|
||||||
|
|
||||||
// self first, then parents
|
// 2. MI-mangled instance scope lookup
|
||||||
fun findMangled(): ObjRecord? {
|
val cls = objClass
|
||||||
// self
|
fun findMangledInRead(): ObjRecord? {
|
||||||
instanceScope.objects["${cls.className}::$name"]?.let { return it }
|
instanceScope.objects["${cls.className}::$name"]?.let { return it }
|
||||||
// ancestors in deterministic C3 order
|
|
||||||
for (p in cls.mroParents) {
|
for (p in cls.mroParents) {
|
||||||
instanceScope.objects["${p.className}::$name"]?.let { return it }
|
instanceScope.objects["${p.className}::$name"]?.let { return it }
|
||||||
}
|
}
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
findMangled()?.let { rec ->
|
|
||||||
// derive declaring class by mangled prefix: try self then parents
|
findMangledInRead()?.let { rec ->
|
||||||
val declaring = when {
|
val declaring = when {
|
||||||
instanceScope.objects.containsKey("${cls.className}::$name") -> cls
|
instanceScope.objects.containsKey("${cls.className}::$name") -> cls
|
||||||
else -> cls.mroParents.firstOrNull { instanceScope.objects.containsKey("${it.className}::$name") }
|
else -> cls.mroParents.firstOrNull { instanceScope.objects.containsKey("${it.className}::$name") }
|
||||||
@@ -75,30 +68,45 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, declaring, caller))
|
if (!canAccessMember(rec.visibility, declaring, caller))
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjAccessException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't access field $name (declared in ${declaring?.className ?: "?"})"
|
"can't access field $name (declared in ${declaring?.className ?: "?"})"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (rec.type == ObjRecord.Type.Property) {
|
return resolveRecord(scope, rec, name, declaring)
|
||||||
val prop = rec.value as ObjProperty
|
|
||||||
return rec.copy(value = prop.callGetter(scope, this, declaring))
|
|
||||||
}
|
}
|
||||||
return rec
|
|
||||||
}
|
// 3. Fall back to super (handles class members and extensions)
|
||||||
// Fall back to methods/properties on class
|
|
||||||
return super.readField(scope, name)
|
return super.readField(scope, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override suspend fun resolveRecord(scope: Scope, obj: ObjRecord, name: String, decl: ObjClass?): ObjRecord {
|
||||||
|
if (obj.type == ObjRecord.Type.Delegated) {
|
||||||
|
val storageName = "${decl?.className}::$name"
|
||||||
|
var del = instanceScope[storageName]?.delegate
|
||||||
|
if (del == null) {
|
||||||
|
for (c in objClass.mro) {
|
||||||
|
del = instanceScope["${c.className}::$name"]?.delegate
|
||||||
|
if (del != null) break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
del = del ?: obj.delegate ?: scope.raiseError("Internal error: delegated property $name has no delegate (tried $storageName)")
|
||||||
|
val res = del.invokeInstanceMethod(scope, "getValue", Arguments(this, ObjString(name)))
|
||||||
|
obj.value = res
|
||||||
|
return obj
|
||||||
|
}
|
||||||
|
return super.resolveRecord(scope, obj, name, decl)
|
||||||
|
}
|
||||||
|
|
||||||
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
||||||
// Direct (unmangled) first
|
// Direct (unmangled) first
|
||||||
instanceScope[name]?.let { f ->
|
instanceScope[name]?.let { f ->
|
||||||
val decl = f.declaringClass
|
val decl = f.declaringClass
|
||||||
if (scope.thisObj !== this || scope.currentClassCtx == null) {
|
if (scope.thisObj !== this || scope.currentClassCtx == null) {
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(f.visibility, decl, caller))
|
if (!canAccessMember(f.effectiveWriteVisibility, decl, caller))
|
||||||
ObjIllegalAssignmentException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't assign to field $name (declared in ${decl?.className ?: "?"})"
|
"can't assign to field $name (declared in ${decl?.className ?: "?"})"
|
||||||
).raise()
|
).raise()
|
||||||
@@ -108,7 +116,20 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
prop.callSetter(scope, this, newValue, decl)
|
prop.callSetter(scope, this, newValue, decl)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!f.isMutable) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
if (f.type == ObjRecord.Type.Delegated) {
|
||||||
|
val storageName = "${decl?.className}::$name"
|
||||||
|
var del = instanceScope[storageName]?.delegate
|
||||||
|
if (del == null) {
|
||||||
|
for (c in objClass.mro) {
|
||||||
|
del = instanceScope["${c.className}::$name"]?.delegate
|
||||||
|
if (del != null) break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
del = del ?: f.delegate ?: scope.raiseError("Internal error: delegated property $name has no delegate (tried $storageName)")
|
||||||
|
del.invokeInstanceMethod(scope, "setValue", Arguments(this, ObjString(name), newValue))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!f.isMutable && f.value !== ObjUnset) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
||||||
if (f.value.assign(scope, newValue) == null)
|
if (f.value.assign(scope, newValue) == null)
|
||||||
f.value = newValue
|
f.value = newValue
|
||||||
return
|
return
|
||||||
@@ -131,8 +152,8 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
}
|
}
|
||||||
if (scope.thisObj !== this || scope.currentClassCtx == null) {
|
if (scope.thisObj !== this || scope.currentClassCtx == null) {
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, declaring, caller))
|
if (!canAccessMember(rec.effectiveWriteVisibility, declaring, caller))
|
||||||
ObjIllegalAssignmentException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't assign to field $name (declared in ${declaring?.className ?: "?"})"
|
"can't assign to field $name (declared in ${declaring?.className ?: "?"})"
|
||||||
).raise()
|
).raise()
|
||||||
@@ -142,7 +163,20 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
prop.callSetter(scope, this, newValue, declaring)
|
prop.callSetter(scope, this, newValue, declaring)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (!rec.isMutable) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
if (rec.type == ObjRecord.Type.Delegated) {
|
||||||
|
val storageName = "${declaring?.className}::$name"
|
||||||
|
var del = instanceScope[storageName]?.delegate
|
||||||
|
if (del == null) {
|
||||||
|
for (c in objClass.mro) {
|
||||||
|
del = instanceScope["${c.className}::$name"]?.delegate
|
||||||
|
if (del != null) break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
del = del ?: rec.delegate ?: scope.raiseError("Internal error: delegated property $name has no delegate (tried $storageName)")
|
||||||
|
del.invokeInstanceMethod(scope, "setValue", Arguments(this, ObjString(name), newValue))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!rec.isMutable && rec.value !== ObjUnset) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
||||||
if (rec.value.assign(scope, newValue) == null)
|
if (rec.value.assign(scope, newValue) == null)
|
||||||
rec.value = newValue
|
rec.value = newValue
|
||||||
return
|
return
|
||||||
@@ -153,39 +187,49 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
override suspend fun invokeInstanceMethod(
|
override suspend fun invokeInstanceMethod(
|
||||||
scope: Scope, name: String, args: Arguments,
|
scope: Scope, name: String, args: Arguments,
|
||||||
onNotFoundResult: (suspend () -> Obj?)?
|
onNotFoundResult: (suspend () -> Obj?)?
|
||||||
): Obj =
|
): Obj {
|
||||||
instanceScope[name]?.let { rec ->
|
// 1. Walk MRO to find member, handling delegation
|
||||||
val decl = rec.declaringClass
|
for (cls in objClass.mro) {
|
||||||
|
if (cls.className == "Obj") break
|
||||||
|
val rec = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
||||||
|
if (rec != null) {
|
||||||
|
if (rec.type == ObjRecord.Type.Delegated) {
|
||||||
|
val storageName = "${cls.className}::$name"
|
||||||
|
val del = instanceScope[storageName]?.delegate ?: rec.delegate
|
||||||
|
?: scope.raiseError("Internal error: delegated member $name has no delegate (tried $storageName)")
|
||||||
|
val allArgs = (listOf(this, ObjString(name)) + args.list).toTypedArray()
|
||||||
|
return del.invokeInstanceMethod(scope, "invoke", Arguments(*allArgs), onNotFoundResult = {
|
||||||
|
// Fallback: property delegation
|
||||||
|
val propVal = del.invokeInstanceMethod(scope, "getValue", Arguments(this, ObjString(name)))
|
||||||
|
propVal.invoke(scope, this, args, rec.declaringClass ?: cls)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
if (rec.type == ObjRecord.Type.Fun && !rec.isAbstract) {
|
||||||
|
val decl = rec.declaringClass ?: cls
|
||||||
val caller = scope.currentClassCtx ?: if (scope.thisObj === this) objClass else null
|
val caller = scope.currentClassCtx ?: if (scope.thisObj === this) objClass else null
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjAccessException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't invoke method $name (declared in ${decl?.className ?: "?"})"
|
"can't invoke method $name (declared in ${decl.className})"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
rec.value.invoke(
|
return rec.value.invoke(
|
||||||
instanceScope,
|
instanceScope,
|
||||||
this,
|
this,
|
||||||
args
|
args,
|
||||||
|
decl
|
||||||
)
|
)
|
||||||
}
|
} else if ((rec.type == ObjRecord.Type.Field || rec.type == ObjRecord.Type.Property) && !rec.isAbstract) {
|
||||||
?: run {
|
val resolved = readField(scope, name)
|
||||||
// fallback: class-scope function (registered during class body execution)
|
return resolved.value.invoke(scope, this, args, resolved.declaringClass)
|
||||||
objClass.classScope?.objects?.get(name)?.let { rec ->
|
|
||||||
val decl = rec.declaringClass
|
|
||||||
val caller = scope.currentClassCtx ?: if (scope.thisObj === this) objClass else null
|
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
|
||||||
scope.raiseError(
|
|
||||||
ObjAccessException(
|
|
||||||
scope,
|
|
||||||
"can't invoke method $name (declared in ${decl?.className ?: "?"})"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
rec.value.invoke(instanceScope, this, args)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
?: super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
}
|
||||||
|
|
||||||
|
// 2. Fall back to super (handles extensions and root fallback)
|
||||||
|
return super.invokeInstanceMethod(scope, name, args, onNotFoundResult)
|
||||||
|
}
|
||||||
|
|
||||||
private val publicFields: Map<String, ObjRecord>
|
private val publicFields: Map<String, ObjRecord>
|
||||||
get() = instanceScope.objects.filter {
|
get() = instanceScope.objects.filter {
|
||||||
@@ -219,7 +263,7 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
val params = meta.params.map { readField(scope, it.name).value }
|
val params = meta.params.map { readField(scope, it.name).value }
|
||||||
encoder.encodeAnyList(scope, params)
|
encoder.encodeAnyList(scope, params)
|
||||||
val vars = serializingVars.values.map { it.value }
|
val vars = serializingVars.values.map { it.value }
|
||||||
if (vars.isNotEmpty<Obj>()) {
|
if (vars.isNotEmpty()) {
|
||||||
encoder.encodeAnyList(scope, vars)
|
encoder.encodeAnyList(scope, vars)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,7 +315,7 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
|
|||||||
|
|
||||||
protected val comparableVars: Map<String, ObjRecord> by lazy {
|
protected val comparableVars: Map<String, ObjRecord> by lazy {
|
||||||
instanceScope.objects.filter {
|
instanceScope.objects.filter {
|
||||||
it.value.type.comparable
|
it.value.type.comparable && (it.value.type != ObjRecord.Type.Field || it.value.isMutable)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -306,8 +350,8 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
val decl = rec.declaringClass ?: startClass
|
val decl = rec.declaringClass ?: startClass
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(ObjAccessException(scope, "can't access field $name (declared in ${decl.className})"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't access field $name (declared in ${decl.className})"))
|
||||||
return rec
|
return resolveRecord(scope, rec, name, decl)
|
||||||
}
|
}
|
||||||
// Then try instance locals (unmangled) only if startClass is the dynamic class itself
|
// Then try instance locals (unmangled) only if startClass is the dynamic class itself
|
||||||
if (startClass === instance.objClass) {
|
if (startClass === instance.objClass) {
|
||||||
@@ -316,12 +360,12 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjAccessException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't access field $name (declared in ${decl?.className ?: "?"})"
|
"can't access field $name (declared in ${decl?.className ?: "?"})"
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
return rec
|
return resolveRecord(scope, rec, name, decl)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Finally try methods/properties starting from ancestor
|
// Finally try methods/properties starting from ancestor
|
||||||
@@ -329,19 +373,9 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
val decl = r.declaringClass ?: startClass
|
val decl = r.declaringClass ?: startClass
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(r.visibility, decl, caller))
|
if (!canAccessMember(r.visibility, decl, caller))
|
||||||
scope.raiseError(ObjAccessException(scope, "can't access field $name (declared in ${decl.className})"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't access field $name (declared in ${decl.className})"))
|
||||||
return when (val value = r.value) {
|
|
||||||
is net.sergeych.lyng.Statement -> ObjRecord(
|
|
||||||
value.execute(
|
|
||||||
instance.instanceScope.createChildScope(
|
|
||||||
scope.pos,
|
|
||||||
newThisObj = instance
|
|
||||||
)
|
|
||||||
), r.isMutable
|
|
||||||
)
|
|
||||||
|
|
||||||
else -> r
|
return resolveRecord(scope, r, name, decl)
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
override suspend fun writeField(scope: Scope, name: String, newValue: Obj) {
|
||||||
@@ -350,12 +384,12 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
instance.instanceScope.objects[mangled]?.let { f ->
|
instance.instanceScope.objects[mangled]?.let { f ->
|
||||||
val decl = f.declaringClass ?: startClass
|
val decl = f.declaringClass ?: startClass
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(f.visibility, decl, caller))
|
if (!canAccessMember(f.effectiveWriteVisibility, decl, caller))
|
||||||
ObjIllegalAssignmentException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't assign to field $name (declared in ${decl.className})"
|
"can't assign to field $name (declared in ${decl.className})"
|
||||||
).raise()
|
).raise()
|
||||||
if (!f.isMutable) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
if (!f.isMutable && f.value !== ObjUnset) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
||||||
if (f.value.assign(scope, newValue) == null) f.value = newValue
|
if (f.value.assign(scope, newValue) == null) f.value = newValue
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -364,12 +398,12 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
instance.instanceScope[name]?.let { f ->
|
instance.instanceScope[name]?.let { f ->
|
||||||
val decl = f.declaringClass ?: instance.objClass.findDeclaringClassOf(name)
|
val decl = f.declaringClass ?: instance.objClass.findDeclaringClassOf(name)
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(f.visibility, decl, caller))
|
if (!canAccessMember(f.effectiveWriteVisibility, decl, caller))
|
||||||
ObjIllegalAssignmentException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't assign to field $name (declared in ${decl?.className ?: "?"})"
|
"can't assign to field $name (declared in ${decl?.className ?: "?"})"
|
||||||
).raise()
|
).raise()
|
||||||
if (!f.isMutable) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
if (!f.isMutable && f.value !== ObjUnset) ObjIllegalAssignmentException(scope, "can't reassign val $name").raise()
|
||||||
if (f.value.assign(scope, newValue) == null) f.value = newValue
|
if (f.value.assign(scope, newValue) == null) f.value = newValue
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -377,8 +411,8 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
val r = memberFromAncestor(name) ?: scope.raiseError("no such field: $name")
|
val r = memberFromAncestor(name) ?: scope.raiseError("no such field: $name")
|
||||||
val decl = r.declaringClass ?: startClass
|
val decl = r.declaringClass ?: startClass
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(r.visibility, decl, caller))
|
if (!canAccessMember(r.effectiveWriteVisibility, decl, caller))
|
||||||
ObjIllegalAssignmentException(scope, "can't assign to field $name (declared in ${decl.className})").raise()
|
ObjIllegalAccessException(scope, "can't assign to field $name (declared in ${decl.className})").raise()
|
||||||
if (!r.isMutable) scope.raiseError("can't assign to read-only field: $name")
|
if (!r.isMutable) scope.raiseError("can't assign to read-only field: $name")
|
||||||
if (r.value.assign(scope, newValue) == null) r.value = newValue
|
if (r.value.assign(scope, newValue) == null) r.value = newValue
|
||||||
}
|
}
|
||||||
@@ -394,7 +428,7 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
val decl = rec.declaringClass ?: startClass
|
val decl = rec.declaringClass ?: startClass
|
||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(ObjAccessException(scope, "can't invoke method $name (declared in ${decl.className})"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't invoke method $name (declared in ${decl.className})"))
|
||||||
val saved = instance.instanceScope.currentClassCtx
|
val saved = instance.instanceScope.currentClassCtx
|
||||||
instance.instanceScope.currentClassCtx = decl
|
instance.instanceScope.currentClassCtx = decl
|
||||||
try {
|
try {
|
||||||
@@ -410,7 +444,7 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
|
|||||||
val caller = scope.currentClassCtx
|
val caller = scope.currentClassCtx
|
||||||
if (!canAccessMember(rec.visibility, decl, caller))
|
if (!canAccessMember(rec.visibility, decl, caller))
|
||||||
scope.raiseError(
|
scope.raiseError(
|
||||||
ObjAccessException(
|
ObjIllegalAccessException(
|
||||||
scope,
|
scope,
|
||||||
"can't invoke method $name (declared in ${decl?.className ?: "?"})"
|
"can't invoke method $name (declared in ${decl?.className ?: "?"})"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -115,9 +115,9 @@ class ObjRange(val start: Obj?, val end: Obj?, val isEndInclusive: Boolean) : Ob
|
|||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun enumerate(scope: Scope, callback: suspend (Obj) -> Boolean) {
|
override suspend fun enumerate(scope: Scope, callback: suspend (Obj) -> Boolean) {
|
||||||
if (isIntRange) {
|
if (start is ObjInt && end is ObjInt) {
|
||||||
val s = (start as ObjInt).value
|
val s = start.value
|
||||||
val e = (end as ObjInt).value
|
val e = end.value
|
||||||
if (isEndInclusive) {
|
if (isEndInclusive) {
|
||||||
for (i in s..e) {
|
for (i in s..e) {
|
||||||
if (!callback(ObjInt.of(i))) break
|
if (!callback(ObjInt.of(i))) break
|
||||||
@@ -127,9 +127,9 @@ class ObjRange(val start: Obj?, val end: Obj?, val isEndInclusive: Boolean) : Ob
|
|||||||
if (!callback(ObjInt.of(i))) break
|
if (!callback(ObjInt.of(i))) break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (isCharRange) {
|
} else if (start is ObjChar && end is ObjChar) {
|
||||||
val s = (start as ObjChar).value
|
val s = start.value
|
||||||
val e = (end as ObjChar).value
|
val e = end.value
|
||||||
if (isEndInclusive) {
|
if (isEndInclusive) {
|
||||||
for (c in s..e) {
|
for (c in s..e) {
|
||||||
if (!callback(ObjChar(c))) break
|
if (!callback(ObjChar(c))) break
|
||||||
|
|||||||
@@ -29,14 +29,19 @@ class ObjRangeIterator(val self: ObjRange) : Obj() {
|
|||||||
override val objClass: ObjClass = type
|
override val objClass: ObjClass = type
|
||||||
|
|
||||||
fun Scope.init() {
|
fun Scope.init() {
|
||||||
if (self.start == null || self.end == null)
|
val s = self.start
|
||||||
raiseError("next is only available for finite ranges")
|
val e = self.end
|
||||||
isCharRange = self.isCharRange
|
if (s is ObjInt && e is ObjInt) {
|
||||||
lastIndex = if (self.isIntRange || self.isCharRange) {
|
lastIndex = if (self.isEndInclusive)
|
||||||
if (self.isEndInclusive)
|
(e.value - s.value + 1).toInt()
|
||||||
self.end.toInt() - self.start.toInt() + 1
|
|
||||||
else
|
else
|
||||||
self.end.toInt() - self.start.toInt()
|
(e.value - s.value).toInt()
|
||||||
|
} else if (s is ObjChar && e is ObjChar) {
|
||||||
|
isCharRange = true
|
||||||
|
lastIndex = if (self.isEndInclusive)
|
||||||
|
(e.value.code - s.value.code + 1)
|
||||||
|
else
|
||||||
|
(e.value.code - s.value.code)
|
||||||
} else {
|
} else {
|
||||||
raiseError("not implemented iterator for range of $this")
|
raiseError("not implemented iterator for range of $this")
|
||||||
}
|
}
|
||||||
@@ -46,10 +51,13 @@ class ObjRangeIterator(val self: ObjRange) : Obj() {
|
|||||||
|
|
||||||
fun next(scope: Scope): Obj =
|
fun next(scope: Scope): Obj =
|
||||||
if (nextIndex < lastIndex) {
|
if (nextIndex < lastIndex) {
|
||||||
val x = if (self.isEndInclusive)
|
val start = self.start
|
||||||
self.start!!.toLong() + nextIndex++
|
val x = if (start is ObjInt)
|
||||||
|
start.value + nextIndex++
|
||||||
|
else if (start is ObjChar)
|
||||||
|
start.value.code.toLong() + nextIndex++
|
||||||
else
|
else
|
||||||
self.start!!.toLong() + nextIndex++
|
scope.raiseError("iterator error: unsupported range start")
|
||||||
if( isCharRange ) ObjChar(x.toInt().toChar()) else ObjInt(x)
|
if( isCharRange ) ObjChar(x.toInt().toChar()) else ObjInt(x)
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -26,12 +26,18 @@ data class ObjRecord(
|
|||||||
var value: Obj,
|
var value: Obj,
|
||||||
val isMutable: Boolean,
|
val isMutable: Boolean,
|
||||||
val visibility: Visibility = Visibility.Public,
|
val visibility: Visibility = Visibility.Public,
|
||||||
|
val writeVisibility: Visibility? = null,
|
||||||
/** If non-null, denotes the class that declared this member (field/method). */
|
/** If non-null, denotes the class that declared this member (field/method). */
|
||||||
val declaringClass: ObjClass? = null,
|
val declaringClass: ObjClass? = null,
|
||||||
var importedFrom: Scope? = null,
|
var importedFrom: Scope? = null,
|
||||||
val isTransient: Boolean = false,
|
val isTransient: Boolean = false,
|
||||||
val type: Type = Type.Other,
|
val type: Type = Type.Other,
|
||||||
|
val isAbstract: Boolean = false,
|
||||||
|
val isClosed: Boolean = false,
|
||||||
|
val isOverride: Boolean = false,
|
||||||
|
var delegate: Obj? = null,
|
||||||
) {
|
) {
|
||||||
|
val effectiveWriteVisibility: Visibility get() = writeVisibility ?: visibility
|
||||||
enum class Type(val comparable: Boolean = false,val serializable: Boolean = false) {
|
enum class Type(val comparable: Boolean = false,val serializable: Boolean = false) {
|
||||||
Field(true, true),
|
Field(true, true),
|
||||||
@Suppress("unused")
|
@Suppress("unused")
|
||||||
@@ -43,6 +49,7 @@ data class ObjRecord(
|
|||||||
Class,
|
Class,
|
||||||
Enum,
|
Enum,
|
||||||
Property,
|
Property,
|
||||||
|
Delegated,
|
||||||
Other;
|
Other;
|
||||||
|
|
||||||
val isArgument get() = this == Argument
|
val isArgument get() = this == Argument
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -32,7 +32,11 @@ sealed interface ObjRef {
|
|||||||
* Fast path for evaluating an expression to a raw Obj value without wrapping it into ObjRecord.
|
* Fast path for evaluating an expression to a raw Obj value without wrapping it into ObjRecord.
|
||||||
* Default implementation calls [get] and returns its value. Nodes can override to avoid record traffic.
|
* Default implementation calls [get] and returns its value. Nodes can override to avoid record traffic.
|
||||||
*/
|
*/
|
||||||
suspend fun evalValue(scope: Scope): Obj = get(scope).value
|
suspend fun evalValue(scope: Scope): Obj {
|
||||||
|
val rec = get(scope)
|
||||||
|
if (rec.type == ObjRecord.Type.Delegated) return scope.resolve(rec, "unknown")
|
||||||
|
return rec.value
|
||||||
|
}
|
||||||
suspend fun setAt(pos: Pos, scope: Scope, newValue: Obj) {
|
suspend fun setAt(pos: Pos, scope: Scope, newValue: Obj) {
|
||||||
throw ScriptError(pos, "can't assign value")
|
throw ScriptError(pos, "can't assign value")
|
||||||
}
|
}
|
||||||
@@ -79,8 +83,7 @@ enum class BinOp {
|
|||||||
/** R-value reference for unary operations. */
|
/** R-value reference for unary operations. */
|
||||||
class UnaryOpRef(private val op: UnaryOp, private val a: ObjRef) : ObjRef {
|
class UnaryOpRef(private val op: UnaryOp, private val a: ObjRef) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
val v = a.evalValue(scope)
|
||||||
val v = if (fastRval) a.evalValue(scope) else a.get(scope).value
|
|
||||||
if (PerfFlags.PRIMITIVE_FASTOPS) {
|
if (PerfFlags.PRIMITIVE_FASTOPS) {
|
||||||
val rFast: Obj? = when (op) {
|
val rFast: Obj? = when (op) {
|
||||||
UnaryOp.NOT -> if (v is ObjBool) if (!v.value) ObjTrue else ObjFalse else null
|
UnaryOp.NOT -> if (v is ObjBool) if (!v.value) ObjTrue else ObjFalse else null
|
||||||
@@ -108,8 +111,8 @@ class UnaryOpRef(private val op: UnaryOp, private val a: ObjRef) : ObjRef {
|
|||||||
/** R-value reference for binary operations. */
|
/** R-value reference for binary operations. */
|
||||||
class BinaryOpRef(private val op: BinOp, private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
class BinaryOpRef(private val op: BinOp, private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val a = if (PerfFlags.RVAL_FASTPATH) left.evalValue(scope) else left.get(scope).value
|
val a = left.evalValue(scope)
|
||||||
val b = if (PerfFlags.RVAL_FASTPATH) right.evalValue(scope) else right.get(scope).value
|
val b = right.evalValue(scope)
|
||||||
|
|
||||||
// Primitive fast paths for common cases (guarded by PerfFlags.PRIMITIVE_FASTOPS)
|
// Primitive fast paths for common cases (guarded by PerfFlags.PRIMITIVE_FASTOPS)
|
||||||
if (PerfFlags.PRIMITIVE_FASTOPS) {
|
if (PerfFlags.PRIMITIVE_FASTOPS) {
|
||||||
@@ -240,8 +243,8 @@ class BinaryOpRef(private val op: BinOp, private val left: ObjRef, private val r
|
|||||||
BinOp.OR -> a.logicalOr(scope, b)
|
BinOp.OR -> a.logicalOr(scope, b)
|
||||||
BinOp.AND -> a.logicalAnd(scope, b)
|
BinOp.AND -> a.logicalAnd(scope, b)
|
||||||
BinOp.EQARROW -> ObjMapEntry(a, b)
|
BinOp.EQARROW -> ObjMapEntry(a, b)
|
||||||
BinOp.EQ -> ObjBool(a.compareTo(scope, b) == 0)
|
BinOp.EQ -> ObjBool(a.equals(scope, b))
|
||||||
BinOp.NEQ -> ObjBool(a.compareTo(scope, b) != 0)
|
BinOp.NEQ -> ObjBool(!a.equals(scope, b))
|
||||||
BinOp.REF_EQ -> ObjBool(a === b)
|
BinOp.REF_EQ -> ObjBool(a === b)
|
||||||
BinOp.REF_NEQ -> ObjBool(a !== b)
|
BinOp.REF_NEQ -> ObjBool(a !== b)
|
||||||
BinOp.MATCH -> a.operatorMatch(scope, b)
|
BinOp.MATCH -> a.operatorMatch(scope, b)
|
||||||
@@ -277,7 +280,7 @@ class ConditionalRef(
|
|||||||
private val ifFalse: ObjRef
|
private val ifFalse: ObjRef
|
||||||
) : ObjRef {
|
) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val condVal = if (PerfFlags.RVAL_FASTPATH) condition.evalValue(scope) else condition.get(scope).value
|
val condVal = condition.evalValue(scope)
|
||||||
val condTrue = when (condVal) {
|
val condTrue = when (condVal) {
|
||||||
is ObjBool -> condVal.value
|
is ObjBool -> condVal.value
|
||||||
is ObjInt -> condVal.value != 0L
|
is ObjInt -> condVal.value != 0L
|
||||||
@@ -296,8 +299,8 @@ class CastRef(
|
|||||||
private val atPos: Pos,
|
private val atPos: Pos,
|
||||||
) : ObjRef {
|
) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val v0 = if (PerfFlags.RVAL_FASTPATH) valueRef.evalValue(scope) else valueRef.get(scope).value
|
val v0 = valueRef.evalValue(scope)
|
||||||
val t = if (PerfFlags.RVAL_FASTPATH) typeRef.evalValue(scope) else typeRef.get(scope).value
|
val t = typeRef.evalValue(scope)
|
||||||
val target = (t as? ObjClass) ?: scope.raiseClassCastError("${'$'}t is not the class instance")
|
val target = (t as? ObjClass) ?: scope.raiseClassCastError("${'$'}t is not the class instance")
|
||||||
// unwrap qualified views
|
// unwrap qualified views
|
||||||
val v = when (v0) {
|
val v = when (v0) {
|
||||||
@@ -318,18 +321,25 @@ class CastRef(
|
|||||||
/** Qualified `this@Type`: resolves to a view of current `this` starting dispatch from the ancestor Type. */
|
/** Qualified `this@Type`: resolves to a view of current `this` starting dispatch from the ancestor Type. */
|
||||||
class QualifiedThisRef(private val typeName: String, private val atPos: Pos) : ObjRef {
|
class QualifiedThisRef(private val typeName: String, private val atPos: Pos) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val thisObj = scope.thisObj
|
|
||||||
val t = scope[typeName]?.value as? ObjClass
|
val t = scope[typeName]?.value as? ObjClass
|
||||||
?: scope.raiseError("unknown type $typeName")
|
?: scope.raiseError("unknown type $typeName")
|
||||||
val inst = (thisObj as? ObjInstance)
|
|
||||||
?: scope.raiseClassCastError("this is not an instance")
|
var s: Scope? = scope
|
||||||
if (!inst.objClass.allParentsSet.contains(t) && inst.objClass !== t)
|
while (s != null) {
|
||||||
scope.raiseClassCastError(
|
val inst = s.thisObj as? ObjInstance
|
||||||
"Qualifier ${'$'}{t.className} is not an ancestor of ${'$'}{inst.objClass.className} (order: ${'$'}{inst.objClass.renderLinearization(true)})"
|
if (inst != null) {
|
||||||
)
|
if (inst.objClass === t || inst.objClass.allParentsSet.contains(t)) {
|
||||||
return ObjQualifiedView(inst, t).asReadonly
|
return ObjQualifiedView(inst, t).asReadonly
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
s = s.parent
|
||||||
|
}
|
||||||
|
|
||||||
|
scope.raiseClassCastError(
|
||||||
|
"No instance of type ${t.className} found in the scope chain"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Assignment compound op: target op= value */
|
/** Assignment compound op: target op= value */
|
||||||
class AssignOpRef(
|
class AssignOpRef(
|
||||||
@@ -339,8 +349,8 @@ class AssignOpRef(
|
|||||||
private val atPos: Pos,
|
private val atPos: Pos,
|
||||||
) : ObjRef {
|
) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val x = target.get(scope).value
|
val x = target.evalValue(scope)
|
||||||
val y = if (PerfFlags.RVAL_FASTPATH) value.evalValue(scope) else value.get(scope).value
|
val y = value.evalValue(scope)
|
||||||
val inPlace: Obj? = when (op) {
|
val inPlace: Obj? = when (op) {
|
||||||
BinOp.PLUS -> x.plusAssign(scope, y)
|
BinOp.PLUS -> x.plusAssign(scope, y)
|
||||||
BinOp.MINUS -> x.minusAssign(scope, y)
|
BinOp.MINUS -> x.minusAssign(scope, y)
|
||||||
@@ -373,7 +383,7 @@ class IncDecRef(
|
|||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val rec = target.get(scope)
|
val rec = target.get(scope)
|
||||||
if (!rec.isMutable) scope.raiseError("Cannot ${if (isIncrement) "increment" else "decrement"} immutable value")
|
if (!rec.isMutable) scope.raiseError("Cannot ${if (isIncrement) "increment" else "decrement"} immutable value")
|
||||||
val v = rec.value
|
val v = scope.resolve(rec, "unknown")
|
||||||
val one = ObjInt.One
|
val one = ObjInt.One
|
||||||
// We now treat numbers as immutable and always perform write-back via setAt.
|
// We now treat numbers as immutable and always perform write-back via setAt.
|
||||||
// This avoids issues where literals are shared and mutated in-place.
|
// This avoids issues where literals are shared and mutated in-place.
|
||||||
@@ -387,9 +397,8 @@ class IncDecRef(
|
|||||||
/** Elvis operator reference: a ?: b */
|
/** Elvis operator reference: a ?: b */
|
||||||
class ElvisRef(private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
class ElvisRef(private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
val a = left.evalValue(scope)
|
||||||
val a = if (fastRval) left.evalValue(scope) else left.get(scope).value
|
val r = if (a != ObjNull) a else right.evalValue(scope)
|
||||||
val r = if (a != ObjNull) a else if (fastRval) right.evalValue(scope) else right.get(scope).value
|
|
||||||
return r.asReadonly
|
return r.asReadonly
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -397,12 +406,10 @@ class ElvisRef(private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
|||||||
/** Logical OR with short-circuit: a || b */
|
/** Logical OR with short-circuit: a || b */
|
||||||
class LogicalOrRef(private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
class LogicalOrRef(private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
val a = left.evalValue(scope)
|
||||||
val fastPrim = PerfFlags.PRIMITIVE_FASTOPS
|
|
||||||
val a = if (fastRval) left.evalValue(scope) else left.get(scope).value
|
|
||||||
if ((a as? ObjBool)?.value == true) return ObjTrue.asReadonly
|
if ((a as? ObjBool)?.value == true) return ObjTrue.asReadonly
|
||||||
val b = if (fastRval) right.evalValue(scope) else right.get(scope).value
|
val b = right.evalValue(scope)
|
||||||
if (fastPrim) {
|
if (PerfFlags.PRIMITIVE_FASTOPS) {
|
||||||
if (a is ObjBool && b is ObjBool) {
|
if (a is ObjBool && b is ObjBool) {
|
||||||
return if (a.value || b.value) ObjTrue.asReadonly else ObjFalse.asReadonly
|
return if (a.value || b.value) ObjTrue.asReadonly else ObjFalse.asReadonly
|
||||||
}
|
}
|
||||||
@@ -414,13 +421,10 @@ class LogicalOrRef(private val left: ObjRef, private val right: ObjRef) : ObjRef
|
|||||||
/** Logical AND with short-circuit: a && b */
|
/** Logical AND with short-circuit: a && b */
|
||||||
class LogicalAndRef(private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
class LogicalAndRef(private val left: ObjRef, private val right: ObjRef) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
// Hoist flags to locals for JIT friendliness
|
val a = left.evalValue(scope)
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
|
||||||
val fastPrim = PerfFlags.PRIMITIVE_FASTOPS
|
|
||||||
val a = if (fastRval) left.evalValue(scope) else left.get(scope).value
|
|
||||||
if ((a as? ObjBool)?.value == false) return ObjFalse.asReadonly
|
if ((a as? ObjBool)?.value == false) return ObjFalse.asReadonly
|
||||||
val b = if (fastRval) right.evalValue(scope) else right.get(scope).value
|
val b = right.evalValue(scope)
|
||||||
if (fastPrim) {
|
if (PerfFlags.PRIMITIVE_FASTOPS) {
|
||||||
if (a is ObjBool && b is ObjBool) {
|
if (a is ObjBool && b is ObjBool) {
|
||||||
return if (a.value && b.value) ObjTrue.asReadonly else ObjFalse.asReadonly
|
return if (a.value && b.value) ObjTrue.asReadonly else ObjFalse.asReadonly
|
||||||
}
|
}
|
||||||
@@ -442,9 +446,9 @@ class ConstRef(private val record: ObjRecord) : ObjRef {
|
|||||||
* Reference to an object's field with optional chaining.
|
* Reference to an object's field with optional chaining.
|
||||||
*/
|
*/
|
||||||
class FieldRef(
|
class FieldRef(
|
||||||
private val target: ObjRef,
|
val target: ObjRef,
|
||||||
private val name: String,
|
val name: String,
|
||||||
private val isOptional: Boolean,
|
val isOptional: Boolean,
|
||||||
) : ObjRef {
|
) : ObjRef {
|
||||||
// 4-entry PIC for reads/writes (guarded by PerfFlags.FIELD_PIC)
|
// 4-entry PIC for reads/writes (guarded by PerfFlags.FIELD_PIC)
|
||||||
// Reads
|
// Reads
|
||||||
@@ -465,9 +469,11 @@ class FieldRef(
|
|||||||
// Adaptive PIC (2→4) for reads/writes
|
// Adaptive PIC (2→4) for reads/writes
|
||||||
private var rAccesses: Int = 0; private var rMisses: Int = 0; private var rPromotedTo4: Boolean = false
|
private var rAccesses: Int = 0; private var rMisses: Int = 0; private var rPromotedTo4: Boolean = false
|
||||||
private var wAccesses: Int = 0; private var wMisses: Int = 0; private var wPromotedTo4: Boolean = false
|
private var wAccesses: Int = 0; private var wMisses: Int = 0; private var wPromotedTo4: Boolean = false
|
||||||
|
@Suppress("NOTHING_TO_INLINE")
|
||||||
private inline fun size4ReadsEnabled(): Boolean =
|
private inline fun size4ReadsEnabled(): Boolean =
|
||||||
PerfFlags.FIELD_PIC_SIZE_4 ||
|
PerfFlags.FIELD_PIC_SIZE_4 ||
|
||||||
(PerfFlags.PIC_ADAPTIVE_2_TO_4 && rPromotedTo4)
|
(PerfFlags.PIC_ADAPTIVE_2_TO_4 && rPromotedTo4)
|
||||||
|
@Suppress("NOTHING_TO_INLINE")
|
||||||
private inline fun size4WritesEnabled(): Boolean =
|
private inline fun size4WritesEnabled(): Boolean =
|
||||||
PerfFlags.FIELD_PIC_SIZE_4 ||
|
PerfFlags.FIELD_PIC_SIZE_4 ||
|
||||||
(PerfFlags.PIC_ADAPTIVE_2_TO_4 && wPromotedTo4)
|
(PerfFlags.PIC_ADAPTIVE_2_TO_4 && wPromotedTo4)
|
||||||
@@ -505,10 +511,9 @@ class FieldRef(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
|
||||||
val fieldPic = PerfFlags.FIELD_PIC
|
val fieldPic = PerfFlags.FIELD_PIC
|
||||||
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
||||||
val base = if (fastRval) target.evalValue(scope) else target.get(scope).value
|
val base = target.evalValue(scope)
|
||||||
if (base == ObjNull && isOptional) return ObjNull.asMutable
|
if (base == ObjNull && isOptional) return ObjNull.asMutable
|
||||||
if (fieldPic) {
|
if (fieldPic) {
|
||||||
val (key, ver) = receiverKeyAndVersion(base)
|
val (key, ver) = receiverKeyAndVersion(base)
|
||||||
@@ -595,7 +600,7 @@ class FieldRef(
|
|||||||
val scope0 = (obj as ObjClass).classScope!!
|
val scope0 = (obj as ObjClass).classScope!!
|
||||||
val r0 = scope0.getSlotRecord(capturedIdx)
|
val r0 = scope0.getSlotRecord(capturedIdx)
|
||||||
if (!r0.visibility.isPublic)
|
if (!r0.visibility.isPublic)
|
||||||
sc.raiseError(ObjAccessException(sc, "can't access non-public field $name"))
|
sc.raiseError(ObjIllegalAccessException(sc, "can't access non-public field $name"))
|
||||||
r0
|
r0
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -615,7 +620,7 @@ class FieldRef(
|
|||||||
override suspend fun setAt(pos: Pos, scope: Scope, newValue: Obj) {
|
override suspend fun setAt(pos: Pos, scope: Scope, newValue: Obj) {
|
||||||
val fieldPic = PerfFlags.FIELD_PIC
|
val fieldPic = PerfFlags.FIELD_PIC
|
||||||
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
||||||
val base = target.get(scope).value
|
val base = target.evalValue(scope)
|
||||||
if (base == ObjNull && isOptional) {
|
if (base == ObjNull && isOptional) {
|
||||||
// no-op on null receiver for optional chaining assignment
|
// no-op on null receiver for optional chaining assignment
|
||||||
return
|
return
|
||||||
@@ -631,7 +636,7 @@ class FieldRef(
|
|||||||
// visibility/mutability checks
|
// visibility/mutability checks
|
||||||
if (!rec.isMutable) scope.raiseError(ObjIllegalAssignmentException(scope, "can't reassign val $name"))
|
if (!rec.isMutable) scope.raiseError(ObjIllegalAssignmentException(scope, "can't reassign val $name"))
|
||||||
if (!rec.visibility.isPublic)
|
if (!rec.visibility.isPublic)
|
||||||
scope.raiseError(ObjAccessException(scope, "can't access non-public field $name"))
|
scope.raiseError(ObjIllegalAccessException(scope, "can't access non-public field $name"))
|
||||||
if (rec.value.assign(scope, newValue) == null) rec.value = newValue
|
if (rec.value.assign(scope, newValue) == null) rec.value = newValue
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -718,10 +723,9 @@ class FieldRef(
|
|||||||
|
|
||||||
override suspend fun evalValue(scope: Scope): Obj {
|
override suspend fun evalValue(scope: Scope): Obj {
|
||||||
// Mirror get(), but return raw Obj to avoid transient ObjRecord on R-value paths
|
// Mirror get(), but return raw Obj to avoid transient ObjRecord on R-value paths
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
|
||||||
val fieldPic = PerfFlags.FIELD_PIC
|
val fieldPic = PerfFlags.FIELD_PIC
|
||||||
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
||||||
val base = if (fastRval) target.evalValue(scope) else target.get(scope).value
|
val base = target.evalValue(scope)
|
||||||
if (base == ObjNull && isOptional) return ObjNull
|
if (base == ObjNull && isOptional) return ObjNull
|
||||||
if (fieldPic) {
|
if (fieldPic) {
|
||||||
val (key, ver) = receiverKeyAndVersion(base)
|
val (key, ver) = receiverKeyAndVersion(base)
|
||||||
@@ -800,11 +804,10 @@ class IndexRef(
|
|||||||
else -> 0L to -1
|
else -> 0L to -1
|
||||||
}
|
}
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
val base = target.evalValue(scope)
|
||||||
val base = if (fastRval) target.evalValue(scope) else target.get(scope).value
|
|
||||||
if (base == ObjNull && isOptional) return ObjNull.asMutable
|
if (base == ObjNull && isOptional) return ObjNull.asMutable
|
||||||
val idx = if (fastRval) index.evalValue(scope) else index.get(scope).value
|
val idx = index.evalValue(scope)
|
||||||
if (fastRval) {
|
if (PerfFlags.RVAL_FASTPATH) {
|
||||||
// Primitive list index fast path: avoid virtual dispatch to getAt when shapes match
|
// Primitive list index fast path: avoid virtual dispatch to getAt when shapes match
|
||||||
if (base is ObjList && idx is ObjInt) {
|
if (base is ObjList && idx is ObjInt) {
|
||||||
val i = idx.toInt()
|
val i = idx.toInt()
|
||||||
@@ -874,11 +877,10 @@ class IndexRef(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun evalValue(scope: Scope): Obj {
|
override suspend fun evalValue(scope: Scope): Obj {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
val base = target.evalValue(scope)
|
||||||
val base = if (fastRval) target.evalValue(scope) else target.get(scope).value
|
|
||||||
if (base == ObjNull && isOptional) return ObjNull
|
if (base == ObjNull && isOptional) return ObjNull
|
||||||
val idx = if (fastRval) index.evalValue(scope) else index.get(scope).value
|
val idx = index.evalValue(scope)
|
||||||
if (fastRval) {
|
if (PerfFlags.RVAL_FASTPATH) {
|
||||||
// Fast list[int] path
|
// Fast list[int] path
|
||||||
if (base is ObjList && idx is ObjInt) {
|
if (base is ObjList && idx is ObjInt) {
|
||||||
val i = idx.toInt()
|
val i = idx.toInt()
|
||||||
@@ -1027,9 +1029,8 @@ class CallRef(
|
|||||||
private val isOptionalInvoke: Boolean,
|
private val isOptionalInvoke: Boolean,
|
||||||
) : ObjRef {
|
) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
|
||||||
val usePool = PerfFlags.SCOPE_POOL
|
val usePool = PerfFlags.SCOPE_POOL
|
||||||
val callee = if (fastRval) target.evalValue(scope) else target.get(scope).value
|
val callee = target.evalValue(scope)
|
||||||
if (callee == ObjNull && isOptionalInvoke) return ObjNull.asReadonly
|
if (callee == ObjNull && isOptionalInvoke) return ObjNull.asReadonly
|
||||||
val callArgs = args.toArguments(scope, tailBlock)
|
val callArgs = args.toArguments(scope, tailBlock)
|
||||||
val result: Obj = if (usePool) {
|
val result: Obj = if (usePool) {
|
||||||
@@ -1065,6 +1066,7 @@ class MethodCallRef(
|
|||||||
private var mFreezeWindowsLeft: Int = 0
|
private var mFreezeWindowsLeft: Int = 0
|
||||||
private var mWindowAccesses: Int = 0
|
private var mWindowAccesses: Int = 0
|
||||||
private var mWindowMisses: Int = 0
|
private var mWindowMisses: Int = 0
|
||||||
|
@Suppress("NOTHING_TO_INLINE")
|
||||||
private inline fun size4MethodsEnabled(): Boolean =
|
private inline fun size4MethodsEnabled(): Boolean =
|
||||||
PerfFlags.METHOD_PIC_SIZE_4 ||
|
PerfFlags.METHOD_PIC_SIZE_4 ||
|
||||||
((PerfFlags.PIC_ADAPTIVE_2_TO_4 || PerfFlags.PIC_ADAPTIVE_METHODS_ONLY) && mPromotedTo4 && mFreezeWindowsLeft == 0)
|
((PerfFlags.PIC_ADAPTIVE_2_TO_4 || PerfFlags.PIC_ADAPTIVE_METHODS_ONLY) && mPromotedTo4 && mFreezeWindowsLeft == 0)
|
||||||
@@ -1117,10 +1119,9 @@ class MethodCallRef(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val fastRval = PerfFlags.RVAL_FASTPATH
|
|
||||||
val methodPic = PerfFlags.METHOD_PIC
|
val methodPic = PerfFlags.METHOD_PIC
|
||||||
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
val picCounters = PerfFlags.PIC_DEBUG_COUNTERS
|
||||||
val base = if (fastRval) receiver.evalValue(scope) else receiver.get(scope).value
|
val base = receiver.evalValue(scope)
|
||||||
if (base == ObjNull && isOptional) return ObjNull.asReadonly
|
if (base == ObjNull && isOptional) return ObjNull.asReadonly
|
||||||
val callArgs = args.toArguments(scope, tailBlock)
|
val callArgs = args.toArguments(scope, tailBlock)
|
||||||
if (methodPic) {
|
if (methodPic) {
|
||||||
@@ -1182,8 +1183,11 @@ class MethodCallRef(
|
|||||||
var hierarchyMember: ObjRecord? = null
|
var hierarchyMember: ObjRecord? = null
|
||||||
for (cls in base.objClass.mro) {
|
for (cls in base.objClass.mro) {
|
||||||
if (cls.className == "Obj") break
|
if (cls.className == "Obj") break
|
||||||
hierarchyMember = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
val rec = cls.members[name] ?: cls.classScope?.objects?.get(name)
|
||||||
if (hierarchyMember != null) break
|
if (rec != null && !rec.isAbstract && rec.type != ObjRecord.Type.Field) {
|
||||||
|
hierarchyMember = rec
|
||||||
|
break
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hierarchyMember != null) {
|
if (hierarchyMember != null) {
|
||||||
@@ -1192,7 +1196,7 @@ class MethodCallRef(
|
|||||||
mKey1 = key; mVer1 = ver; mInvoker1 = { obj, sc, a ->
|
mKey1 = key; mVer1 = ver; mInvoker1 = { obj, sc, a ->
|
||||||
val inst = obj as ObjInstance
|
val inst = obj as ObjInstance
|
||||||
if (!visibility.isPublic && !canAccessMember(visibility, hierarchyMember.declaringClass ?: inst.objClass, sc.currentClassCtx))
|
if (!visibility.isPublic && !canAccessMember(visibility, hierarchyMember.declaringClass ?: inst.objClass, sc.currentClassCtx))
|
||||||
sc.raiseError(ObjAccessException(sc, "can't invoke non-public method $name"))
|
sc.raiseError(ObjIllegalAccessException(sc, "can't invoke non-public method $name"))
|
||||||
callable.invoke(inst.instanceScope, inst, a)
|
callable.invoke(inst.instanceScope, inst, a)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -1324,21 +1328,21 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
override suspend fun evalValue(scope: Scope): Obj {
|
override suspend fun evalValue(scope: Scope): Obj {
|
||||||
scope.pos = atPos
|
scope.pos = atPos
|
||||||
if (!PerfFlags.LOCAL_SLOT_PIC) {
|
if (!PerfFlags.LOCAL_SLOT_PIC) {
|
||||||
scope.getSlotIndexOf(name)?.let { return scope.getSlotRecord(it).value }
|
scope.getSlotIndexOf(name)?.let { return scope.resolve(scope.getSlotRecord(it), name) }
|
||||||
// fallback to current-scope object or field on `this`
|
// fallback to current-scope object or field on `this`
|
||||||
scope[name]?.let { return it.value }
|
scope[name]?.let { return scope.resolve(it, name) }
|
||||||
run {
|
run {
|
||||||
var s: Scope? = scope
|
var s: Scope? = scope
|
||||||
val visited = HashSet<Long>(4)
|
val visited = HashSet<Long>(4)
|
||||||
while (s != null) {
|
while (s != null) {
|
||||||
if (!visited.add(s.frameId)) break
|
if (!visited.add(s.frameId)) break
|
||||||
if (s is ClosureScope) {
|
if (s is ClosureScope) {
|
||||||
s.closureScope.chainLookupWithMembers(name)?.let { return it.value }
|
s.closureScope.chainLookupWithMembers(name)?.let { return s.resolve(it, name) }
|
||||||
}
|
}
|
||||||
s = s.parent
|
s = s.parent
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
scope.chainLookupIgnoreClosure(name)?.let { return it.value }
|
scope.chainLookupIgnoreClosure(name)?.let { return scope.resolve(it, name) }
|
||||||
return try {
|
return try {
|
||||||
scope.thisObj.readField(scope, name).value
|
scope.thisObj.readField(scope, name).value
|
||||||
} catch (e: ExecutionError) {
|
} catch (e: ExecutionError) {
|
||||||
@@ -1350,25 +1354,29 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
val slot = if (hit) cachedSlot else resolveSlot(scope)
|
val slot = if (hit) cachedSlot else resolveSlot(scope)
|
||||||
if (slot >= 0) {
|
if (slot >= 0) {
|
||||||
val rec = scope.getSlotRecord(slot)
|
val rec = scope.getSlotRecord(slot)
|
||||||
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx)) {
|
||||||
return rec.value
|
return scope.resolve(rec, name)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Fallback name in scope or field on `this`
|
// Fallback name in scope or field on `this`
|
||||||
scope[name]?.let { return it.value }
|
scope[name]?.let {
|
||||||
|
return scope.resolve(it, name)
|
||||||
|
}
|
||||||
run {
|
run {
|
||||||
var s: Scope? = scope
|
var s: Scope? = scope
|
||||||
val visited = HashSet<Long>(4)
|
val visited = HashSet<Long>(4)
|
||||||
while (s != null) {
|
while (s != null) {
|
||||||
if (!visited.add(s.frameId)) break
|
if (!visited.add(s.frameId)) break
|
||||||
if (s is ClosureScope) {
|
if (s is ClosureScope) {
|
||||||
s.closureScope.chainLookupWithMembers(name)?.let { return it.value }
|
s.closureScope.chainLookupWithMembers(name)?.let { return s.resolve(it, name) }
|
||||||
}
|
}
|
||||||
s = s.parent
|
s = s.parent
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
scope.chainLookupIgnoreClosure(name)?.let { return it.value }
|
scope.chainLookupIgnoreClosure(name)?.let { return scope.resolve(it, name) }
|
||||||
return try {
|
return try {
|
||||||
scope.thisObj.readField(scope, name).value
|
val res = scope.thisObj.readField(scope, name).value
|
||||||
|
res
|
||||||
} catch (e: ExecutionError) {
|
} catch (e: ExecutionError) {
|
||||||
if ((e.message ?: "").contains("no such field: $name")) scope.raiseSymbolNotFound(name)
|
if ((e.message ?: "").contains("no such field: $name")) scope.raiseSymbolNotFound(name)
|
||||||
throw e
|
throw e
|
||||||
@@ -1380,13 +1388,11 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
if (!PerfFlags.LOCAL_SLOT_PIC) {
|
if (!PerfFlags.LOCAL_SLOT_PIC) {
|
||||||
scope.getSlotIndexOf(name)?.let {
|
scope.getSlotIndexOf(name)?.let {
|
||||||
val rec = scope.getSlotRecord(it)
|
val rec = scope.getSlotRecord(it)
|
||||||
if (!rec.isMutable) scope.raiseError("Cannot assign to immutable value")
|
scope.assign(rec, name, newValue)
|
||||||
rec.value = newValue
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
scope[name]?.let { stored ->
|
scope[name]?.let { stored ->
|
||||||
if (stored.isMutable) stored.value = newValue
|
scope.assign(stored, name, newValue)
|
||||||
else scope.raiseError("Cannot assign to immutable value")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
run {
|
run {
|
||||||
@@ -1396,8 +1402,7 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
if (!visited.add(s.frameId)) break
|
if (!visited.add(s.frameId)) break
|
||||||
if (s is ClosureScope) {
|
if (s is ClosureScope) {
|
||||||
s.closureScope.chainLookupWithMembers(name)?.let { stored ->
|
s.closureScope.chainLookupWithMembers(name)?.let { stored ->
|
||||||
if (stored.isMutable) stored.value = newValue
|
s.assign(stored, name, newValue)
|
||||||
else scope.raiseError("Cannot assign to immutable value")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1405,8 +1410,7 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
scope.chainLookupIgnoreClosure(name)?.let { stored ->
|
scope.chainLookupIgnoreClosure(name)?.let { stored ->
|
||||||
if (stored.isMutable) stored.value = newValue
|
scope.assign(stored, name, newValue)
|
||||||
else scope.raiseError("Cannot assign to immutable value")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Fallback: write to field on `this`
|
// Fallback: write to field on `this`
|
||||||
@@ -1417,14 +1421,12 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
if (slot >= 0) {
|
if (slot >= 0) {
|
||||||
val rec = scope.getSlotRecord(slot)
|
val rec = scope.getSlotRecord(slot)
|
||||||
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx)) {
|
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx)) {
|
||||||
if (!rec.isMutable) scope.raiseError("Cannot assign to immutable value")
|
scope.assign(rec, name, newValue)
|
||||||
rec.value = newValue
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
scope[name]?.let { stored ->
|
scope[name]?.let { stored ->
|
||||||
if (stored.isMutable) stored.value = newValue
|
scope.assign(stored, name, newValue)
|
||||||
else scope.raiseError("Cannot assign to immutable value")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
run {
|
run {
|
||||||
@@ -1434,8 +1436,7 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
if (!visited.add(s.frameId)) break
|
if (!visited.add(s.frameId)) break
|
||||||
if (s is ClosureScope) {
|
if (s is ClosureScope) {
|
||||||
s.closureScope.chainLookupWithMembers(name)?.let { stored ->
|
s.closureScope.chainLookupWithMembers(name)?.let { stored ->
|
||||||
if (stored.isMutable) stored.value = newValue
|
s.assign(stored, name, newValue)
|
||||||
else scope.raiseError("Cannot assign to immutable value")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1443,8 +1444,7 @@ class LocalVarRef(val name: String, private val atPos: Pos) : ObjRef {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
scope.chainLookupIgnoreClosure(name)?.let { stored ->
|
scope.chainLookupIgnoreClosure(name)?.let { stored ->
|
||||||
if (stored.isMutable) stored.value = newValue
|
scope.assign(stored, name, newValue)
|
||||||
else scope.raiseError("Cannot assign to immutable value")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
scope.thisObj.writeField(scope, name, newValue)
|
scope.thisObj.writeField(scope, name, newValue)
|
||||||
@@ -1464,7 +1464,7 @@ class BoundLocalVarRef(
|
|||||||
scope.pos = atPos
|
scope.pos = atPos
|
||||||
val rec = scope.getSlotRecord(slot)
|
val rec = scope.getSlotRecord(slot)
|
||||||
if (rec.declaringClass != null && !canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
if (rec.declaringClass != null && !canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
||||||
scope.raiseError(ObjAccessException(scope, "private field access"))
|
scope.raiseError(ObjIllegalAccessException(scope, "private field access"))
|
||||||
return rec
|
return rec
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1472,17 +1472,19 @@ class BoundLocalVarRef(
|
|||||||
scope.pos = atPos
|
scope.pos = atPos
|
||||||
val rec = scope.getSlotRecord(slot)
|
val rec = scope.getSlotRecord(slot)
|
||||||
if (rec.declaringClass != null && !canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
if (rec.declaringClass != null && !canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
||||||
scope.raiseError(ObjAccessException(scope, "private field access"))
|
scope.raiseError(ObjIllegalAccessException(scope, "private field access"))
|
||||||
return rec.value
|
// We might not have the name in BoundLocalVarRef, but let's try to find it or use a placeholder
|
||||||
|
// Actually BoundLocalVarRef is mostly used for parameters which are not delegated yet.
|
||||||
|
// But for consistency:
|
||||||
|
return scope.resolve(rec, "local")
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun setAt(pos: Pos, scope: Scope, newValue: Obj) {
|
override suspend fun setAt(pos: Pos, scope: Scope, newValue: Obj) {
|
||||||
scope.pos = atPos
|
scope.pos = atPos
|
||||||
val rec = scope.getSlotRecord(slot)
|
val rec = scope.getSlotRecord(slot)
|
||||||
if (rec.declaringClass != null && !canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
if (rec.declaringClass != null && !canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
||||||
scope.raiseError(ObjAccessException(scope, "private field access"))
|
scope.raiseError(ObjIllegalAccessException(scope, "private field access"))
|
||||||
if (!rec.isMutable) scope.raiseError("Cannot assign to immutable value")
|
scope.assign(rec, "local", newValue)
|
||||||
rec.value = newValue
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1589,15 +1591,18 @@ class FastLocalVarRef(
|
|||||||
val actualOwner = cachedOwnerScope
|
val actualOwner = cachedOwnerScope
|
||||||
if (slot >= 0 && actualOwner != null) {
|
if (slot >= 0 && actualOwner != null) {
|
||||||
val rec = actualOwner.getSlotRecord(slot)
|
val rec = actualOwner.getSlotRecord(slot)
|
||||||
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx))
|
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx)) {
|
||||||
return rec.value
|
return scope.resolve(rec, name)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Try per-frame local binding maps in the ancestry first
|
// Try per-frame local binding maps in the ancestry first
|
||||||
run {
|
run {
|
||||||
var s: Scope? = scope
|
var s: Scope? = scope
|
||||||
var guard = 0
|
var guard = 0
|
||||||
while (s != null) {
|
while (s != null) {
|
||||||
s.localBindings[name]?.let { return it.value }
|
s.localBindings[name]?.let {
|
||||||
|
return s.resolve(it, name)
|
||||||
|
}
|
||||||
val next = s.parent
|
val next = s.parent
|
||||||
if (next === s) break
|
if (next === s) break
|
||||||
s = next
|
s = next
|
||||||
@@ -1609,7 +1614,9 @@ class FastLocalVarRef(
|
|||||||
var s: Scope? = scope
|
var s: Scope? = scope
|
||||||
var guard = 0
|
var guard = 0
|
||||||
while (s != null) {
|
while (s != null) {
|
||||||
s.objects[name]?.let { return it.value }
|
s.objects[name]?.let {
|
||||||
|
return s.resolve(it, name)
|
||||||
|
}
|
||||||
val next = s.parent
|
val next = s.parent
|
||||||
if (next === s) break
|
if (next === s) break
|
||||||
s = next
|
s = next
|
||||||
@@ -1617,7 +1624,9 @@ class FastLocalVarRef(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Fallback to standard name lookup (locals or closure chain)
|
// Fallback to standard name lookup (locals or closure chain)
|
||||||
scope[name]?.let { return it.value }
|
scope[name]?.let {
|
||||||
|
return scope.resolve(it, name)
|
||||||
|
}
|
||||||
return scope.thisObj.readField(scope, name).value
|
return scope.thisObj.readField(scope, name).value
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1629,8 +1638,7 @@ class FastLocalVarRef(
|
|||||||
if (slot >= 0 && actualOwner != null) {
|
if (slot >= 0 && actualOwner != null) {
|
||||||
val rec = actualOwner.getSlotRecord(slot)
|
val rec = actualOwner.getSlotRecord(slot)
|
||||||
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx)) {
|
if (rec.declaringClass == null || canAccessMember(rec.visibility, rec.declaringClass, scope.currentClassCtx)) {
|
||||||
if (!rec.isMutable) scope.raiseError("Cannot assign to immutable value")
|
scope.assign(rec, name, newValue)
|
||||||
rec.value = newValue
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1641,8 +1649,7 @@ class FastLocalVarRef(
|
|||||||
while (s != null) {
|
while (s != null) {
|
||||||
val rec = s.localBindings[name]
|
val rec = s.localBindings[name]
|
||||||
if (rec != null) {
|
if (rec != null) {
|
||||||
if (!rec.isMutable) scope.raiseError("Cannot assign to immutable value")
|
s.assign(rec, name, newValue)
|
||||||
rec.value = newValue
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
val next = s.parent
|
val next = s.parent
|
||||||
@@ -1653,8 +1660,7 @@ class FastLocalVarRef(
|
|||||||
}
|
}
|
||||||
// Fallback to standard name lookup
|
// Fallback to standard name lookup
|
||||||
scope[name]?.let { stored ->
|
scope[name]?.let { stored ->
|
||||||
if (stored.isMutable) stored.value = newValue
|
scope.assign(stored, name, newValue)
|
||||||
else scope.raiseError("Cannot assign to immutable value")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
scope.thisObj.writeField(scope, name, newValue)
|
scope.thisObj.writeField(scope, name, newValue)
|
||||||
@@ -1688,11 +1694,11 @@ class ListLiteralRef(private val entries: List<ListEntry>) : ObjRef {
|
|||||||
for (e in entries) {
|
for (e in entries) {
|
||||||
when (e) {
|
when (e) {
|
||||||
is ListEntry.Element -> {
|
is ListEntry.Element -> {
|
||||||
val v = if (PerfFlags.RVAL_FASTPATH) e.ref.evalValue(scope) else e.ref.get(scope).value
|
val v = if (PerfFlags.RVAL_FASTPATH) e.ref.evalValue(scope) else e.ref.evalValue(scope)
|
||||||
list += v
|
list += v
|
||||||
}
|
}
|
||||||
is ListEntry.Spread -> {
|
is ListEntry.Spread -> {
|
||||||
val elements = if (PerfFlags.RVAL_FASTPATH) e.ref.evalValue(scope) else e.ref.get(scope).value
|
val elements = e.ref.evalValue(scope)
|
||||||
when (elements) {
|
when (elements) {
|
||||||
is ObjList -> {
|
is ObjList -> {
|
||||||
// Grow underlying array once when possible
|
// Grow underlying array once when possible
|
||||||
@@ -1768,11 +1774,11 @@ class MapLiteralRef(private val entries: List<MapLiteralEntry>) : ObjRef {
|
|||||||
for (e in entries) {
|
for (e in entries) {
|
||||||
when (e) {
|
when (e) {
|
||||||
is MapLiteralEntry.Named -> {
|
is MapLiteralEntry.Named -> {
|
||||||
val v = if (PerfFlags.RVAL_FASTPATH) e.value.evalValue(scope) else e.value.get(scope).value
|
val v = e.value.evalValue(scope)
|
||||||
result.map[ObjString(e.key)] = v
|
result.map[ObjString(e.key)] = v
|
||||||
}
|
}
|
||||||
is MapLiteralEntry.Spread -> {
|
is MapLiteralEntry.Spread -> {
|
||||||
val m = if (PerfFlags.RVAL_FASTPATH) e.ref.evalValue(scope) else e.ref.get(scope).value
|
val m = e.ref.evalValue(scope)
|
||||||
if (m !is ObjMap) scope.raiseIllegalArgument("spread element in map literal must be a Map")
|
if (m !is ObjMap) scope.raiseIllegalArgument("spread element in map literal must be a Map")
|
||||||
for ((k, v) in m.map) {
|
for ((k, v) in m.map) {
|
||||||
result.map[k] = v
|
result.map[k] = v
|
||||||
@@ -1793,12 +1799,27 @@ class RangeRef(
|
|||||||
private val isEndInclusive: Boolean
|
private val isEndInclusive: Boolean
|
||||||
) : ObjRef {
|
) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val l = left?.let { if (PerfFlags.RVAL_FASTPATH) it.evalValue(scope) else it.get(scope).value } ?: ObjNull
|
val l = left?.evalValue(scope) ?: ObjNull
|
||||||
val r = right?.let { if (PerfFlags.RVAL_FASTPATH) it.evalValue(scope) else it.get(scope).value } ?: ObjNull
|
val r = right?.evalValue(scope) ?: ObjNull
|
||||||
return ObjRange(l, r, isEndInclusive = isEndInclusive).asReadonly
|
return ObjRange(l, r, isEndInclusive = isEndInclusive).asReadonly
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Assignment if null op: target ?= value */
|
||||||
|
class AssignIfNullRef(
|
||||||
|
private val target: ObjRef,
|
||||||
|
private val value: ObjRef,
|
||||||
|
private val atPos: Pos,
|
||||||
|
) : ObjRef {
|
||||||
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
|
val current = target.evalValue(scope)
|
||||||
|
if (current != ObjNull) return current.asReadonly
|
||||||
|
val newValue = value.evalValue(scope)
|
||||||
|
target.setAt(atPos, scope, newValue)
|
||||||
|
return newValue.asReadonly
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Simple assignment: target = value */
|
/** Simple assignment: target = value */
|
||||||
class AssignRef(
|
class AssignRef(
|
||||||
private val target: ObjRef,
|
private val target: ObjRef,
|
||||||
@@ -1806,7 +1827,7 @@ class AssignRef(
|
|||||||
private val atPos: Pos,
|
private val atPos: Pos,
|
||||||
) : ObjRef {
|
) : ObjRef {
|
||||||
override suspend fun get(scope: Scope): ObjRecord {
|
override suspend fun get(scope: Scope): ObjRecord {
|
||||||
val v = if (PerfFlags.RVAL_FASTPATH) value.evalValue(scope) else value.get(scope).value
|
val v = value.evalValue(scope)
|
||||||
// For properties, we should not call get() on target because it invokes the getter.
|
// For properties, we should not call get() on target because it invokes the getter.
|
||||||
// Instead, we call setAt directly.
|
// Instead, we call setAt directly.
|
||||||
if (target is FieldRef || target is IndexRef || target is LocalVarRef || target is FastLocalVarRef || target is BoundLocalVarRef) {
|
if (target is FieldRef || target is IndexRef || target is LocalVarRef || target is FastLocalVarRef || target is BoundLocalVarRef) {
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ class ObjRegexMatch(val match: MatchResult) : Obj() {
|
|||||||
// Use groupValues so that index 0 is the whole match and subsequent indices are capturing groups,
|
// Use groupValues so that index 0 is the whole match and subsequent indices are capturing groups,
|
||||||
// which matches the language/tests expectation for `$~[i]`.
|
// which matches the language/tests expectation for `$~[i]`.
|
||||||
ObjList(
|
ObjList(
|
||||||
match.groupValues.map { ObjString(it) as Obj }.toMutableList()
|
match.groupValues.map { ObjString(it) }.toMutableList()
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -19,7 +19,6 @@ package net.sergeych.lyng
|
|||||||
|
|
||||||
import net.sergeych.lyng.obj.Obj
|
import net.sergeych.lyng.obj.Obj
|
||||||
import net.sergeych.lyng.obj.ObjClass
|
import net.sergeych.lyng.obj.ObjClass
|
||||||
import net.sergeych.lyng.obj.ObjNull
|
|
||||||
import net.sergeych.lyng.obj.ObjVoid
|
import net.sergeych.lyng.obj.ObjVoid
|
||||||
|
|
||||||
fun String.toSource(name: String = "eval"): Source = Source(name, this)
|
fun String.toSource(name: String = "eval"): Source = Source(name, this)
|
||||||
@@ -46,9 +45,8 @@ abstract class Statement(
|
|||||||
abstract suspend fun execute(scope: Scope): Obj
|
abstract suspend fun execute(scope: Scope): Obj
|
||||||
|
|
||||||
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
override suspend fun compareTo(scope: Scope, other: Obj): Int {
|
||||||
if( other == ObjNull || other == ObjVoid ) return 1
|
|
||||||
if( other === this ) return 0
|
if( other === this ) return 0
|
||||||
return -1
|
return -3
|
||||||
}
|
}
|
||||||
|
|
||||||
override suspend fun callOn(scope: Scope): Obj {
|
override suspend fun callOn(scope: Scope): Obj {
|
||||||
|
|||||||
@@ -101,6 +101,7 @@ open class LynonEncoder(val bout: BitOutput, val settings: LynonSettings = Lynon
|
|||||||
* Caching is used automatically.
|
* Caching is used automatically.
|
||||||
*/
|
*/
|
||||||
suspend fun encodeAny(scope: Scope, obj: Obj) {
|
suspend fun encodeAny(scope: Scope, obj: Obj) {
|
||||||
|
if (obj.objClass.isAnonymous) scope.raiseError("Cannot serialize anonymous object")
|
||||||
encodeCached(obj) {
|
encodeCached(obj) {
|
||||||
val type = putTypeRecord(scope, obj, obj.lynonType())
|
val type = putTypeRecord(scope, obj, obj.lynonType())
|
||||||
obj.serialize(scope, this, type)
|
obj.serialize(scope, this, type)
|
||||||
|
|||||||
@@ -47,7 +47,7 @@ class BindingHighlightTest {
|
|||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini, "Mini-AST must be built")
|
assertNotNull(mini, "Mini-AST must be built")
|
||||||
|
|
||||||
val binding = Binder.bind(text, mini!!)
|
val binding = Binder.bind(text, mini)
|
||||||
|
|
||||||
// Find the top-level symbol for counter and ensure it is mutable (Variable)
|
// Find the top-level symbol for counter and ensure it is mutable (Variable)
|
||||||
val sym = binding.symbols.firstOrNull { it.name == "counter" }
|
val sym = binding.symbols.firstOrNull { it.name == "counter" }
|
||||||
@@ -78,7 +78,7 @@ class BindingHighlightTest {
|
|||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini, "Mini-AST must be built")
|
assertNotNull(mini, "Mini-AST must be built")
|
||||||
|
|
||||||
val binding = Binder.bind(text, mini!!)
|
val binding = Binder.bind(text, mini)
|
||||||
|
|
||||||
val sym = binding.symbols.firstOrNull { it.name == "answer" }
|
val sym = binding.symbols.firstOrNull { it.name == "answer" }
|
||||||
assertNotNull(sym, "Top-level val 'answer' must be registered as a symbol")
|
assertNotNull(sym, "Top-level val 'answer' must be registered as a symbol")
|
||||||
@@ -114,7 +114,7 @@ class BindingHighlightTest {
|
|||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini, "Mini-AST must be built")
|
assertNotNull(mini, "Mini-AST must be built")
|
||||||
|
|
||||||
val binding = Binder.bind(text, mini!!)
|
val binding = Binder.bind(text, mini)
|
||||||
|
|
||||||
// Ensure we registered the local var/val symbol for `name`
|
// Ensure we registered the local var/val symbol for `name`
|
||||||
val nameSym = binding.symbols.firstOrNull { it.name == "name" }
|
val nameSym = binding.symbols.firstOrNull { it.name == "name" }
|
||||||
@@ -163,7 +163,7 @@ class BindingHighlightTest {
|
|||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini, "Mini-AST must be built")
|
assertNotNull(mini, "Mini-AST must be built")
|
||||||
|
|
||||||
val binding = Binder.bind(text, mini!!)
|
val binding = Binder.bind(text, mini)
|
||||||
|
|
||||||
val nameSym = binding.symbols.firstOrNull { it.name == "name" && (it.kind == SymbolKind.Variable || it.kind == SymbolKind.Value) }
|
val nameSym = binding.symbols.firstOrNull { it.name == "name" && (it.kind == SymbolKind.Variable || it.kind == SymbolKind.Value) }
|
||||||
assertNotNull(nameSym, "Local variable 'name' should be registered as a symbol")
|
assertNotNull(nameSym, "Local variable 'name' should be registered as a symbol")
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ class BindingTest {
|
|||||||
Compiler.compileWithMini(src, sink)
|
Compiler.compileWithMini(src, sink)
|
||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini, "MiniScript should be built")
|
assertNotNull(mini, "MiniScript should be built")
|
||||||
return Binder.bind(src, mini!!)
|
return Binder.bind(src, mini)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -72,7 +72,7 @@ class BindingTest {
|
|||||||
val xSym = snap.symbols.firstOrNull { it.name == "x" }
|
val xSym = snap.symbols.firstOrNull { it.name == "x" }
|
||||||
assertNotNull(xSym)
|
assertNotNull(xSym)
|
||||||
// One reference usage to top-level x
|
// One reference usage to top-level x
|
||||||
val refs = snap.references.filter { it.symbolId == xSym!!.id }
|
val refs = snap.references.filter { it.symbolId == xSym.id }
|
||||||
assertEquals(1, refs.size)
|
assertEquals(1, refs.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +111,7 @@ class BindingTest {
|
|||||||
val fooField = snap.symbols.firstOrNull { it.name == "foo" }
|
val fooField = snap.symbols.firstOrNull { it.name == "foo" }
|
||||||
assertNotNull(fooField)
|
assertNotNull(fooField)
|
||||||
// Should have at least one reference (usage in bar)
|
// Should have at least one reference (usage in bar)
|
||||||
val refs = snap.references.count { it.symbolId == fooField!!.id }
|
val refs = snap.references.count { it.symbolId == fooField.id }
|
||||||
assertEquals(1, refs)
|
assertEquals(1, refs)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,7 +126,7 @@ class BindingTest {
|
|||||||
)
|
)
|
||||||
val xField = snap.symbols.firstOrNull { it.name == "x" }
|
val xField = snap.symbols.firstOrNull { it.name == "x" }
|
||||||
assertNotNull(xField)
|
assertNotNull(xField)
|
||||||
val refs = snap.references.count { it.symbolId == xField!!.id }
|
val refs = snap.references.count { it.symbolId == xField.id }
|
||||||
assertEquals(1, refs)
|
assertEquals(1, refs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.lyng.eval
|
||||||
|
import kotlin.test.Test
|
||||||
|
|
||||||
|
class IfNullAssignTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBasicAssignment() = runTest {
|
||||||
|
eval("""
|
||||||
|
var x = null
|
||||||
|
x ?= 42
|
||||||
|
assertEquals(42, x)
|
||||||
|
x ?= 100
|
||||||
|
assertEquals(42, x)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPropertyAssignment() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Box(var value)
|
||||||
|
val b = Box(null)
|
||||||
|
b.value ?= 10
|
||||||
|
assertEquals(10, b.value)
|
||||||
|
b.value ?= 20
|
||||||
|
assertEquals(10, b.value)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testIndexAssignment() = runTest {
|
||||||
|
eval("""
|
||||||
|
val a = [null, 1]
|
||||||
|
a[0] ?= 10
|
||||||
|
assertEquals(10, a[0])
|
||||||
|
a[1] ?= 20
|
||||||
|
assertEquals(1, a[1])
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testOptionalChaining() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Inner(var value)
|
||||||
|
class Outer(var inner)
|
||||||
|
|
||||||
|
var o = null
|
||||||
|
o?.inner?.value ?= 10 // should do nothing
|
||||||
|
assertEquals(null, o)
|
||||||
|
|
||||||
|
o = Outer(null)
|
||||||
|
o?.inner?.value ?= 10 // should do nothing because inner is null
|
||||||
|
assertEquals(null, o.inner)
|
||||||
|
|
||||||
|
o.inner = Inner(null)
|
||||||
|
o?.inner?.value ?= 42
|
||||||
|
assertEquals(42, o.inner.value)
|
||||||
|
o?.inner?.value ?= 100
|
||||||
|
assertEquals(42, o.inner.value)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDoubleEvaluation() = runTest {
|
||||||
|
eval("""
|
||||||
|
var count = 0
|
||||||
|
fun getIdx() {
|
||||||
|
count = count + 1
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
val a = [null]
|
||||||
|
a[getIdx()] ?= 10
|
||||||
|
|
||||||
|
// Current behavior: double evaluation happens in ObjRef for compound ops
|
||||||
|
// getIdx() is called once for checking if null, and once for setting if it was null.
|
||||||
|
assertEquals(10, a[0])
|
||||||
|
assertEquals(2, count)
|
||||||
|
|
||||||
|
a[getIdx()] ?= 20
|
||||||
|
// If it's NOT null, it only evaluates once to check the value.
|
||||||
|
assertEquals(10, a[0])
|
||||||
|
assertEquals(3, count)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReturnValue() = runTest {
|
||||||
|
eval("""
|
||||||
|
var x = null
|
||||||
|
val r1 = (x ?= 42)
|
||||||
|
assertEquals(42, r1)
|
||||||
|
assertEquals(42, x)
|
||||||
|
|
||||||
|
val r2 = (x ?= 100)
|
||||||
|
assertEquals(42, r2)
|
||||||
|
assertEquals(42, x)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -52,8 +52,8 @@ class MIC3MroTest {
|
|||||||
eval(
|
eval(
|
||||||
"""
|
"""
|
||||||
class A() { fun common() { "A" } }
|
class A() { fun common() { "A" } }
|
||||||
class B() : A() { fun common() { "B" } }
|
class B() : A() { override fun common() { "B" } }
|
||||||
class C() : A() { fun common() { "C" } }
|
class C() : A() { override fun common() { "C" } }
|
||||||
class D() : B(), C()
|
class D() : B(), C()
|
||||||
|
|
||||||
val d = D()
|
val d = D()
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ class MiniAstTest {
|
|||||||
val (_, sink) = compileWithMini(code)
|
val (_, sink) = compileWithMini(code)
|
||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini)
|
assertNotNull(mini)
|
||||||
val imps = mini!!.imports
|
val imps = mini.imports
|
||||||
assertTrue(imps.isNotEmpty(), "imports should be captured")
|
assertTrue(imps.isNotEmpty(), "imports should be captured")
|
||||||
val first = imps.first()
|
val first = imps.first()
|
||||||
val segNames = first.segments.map { it.name }
|
val segNames = first.segments.map { it.name }
|
||||||
@@ -68,12 +68,12 @@ class MiniAstTest {
|
|||||||
val (_, sink) = compileWithMini(code)
|
val (_, sink) = compileWithMini(code)
|
||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini)
|
assertNotNull(mini)
|
||||||
val fn = mini!!.declarations.filterIsInstance<MiniFunDecl>().firstOrNull { it.name == "foo" }
|
val fn = mini.declarations.filterIsInstance<MiniFunDecl>().firstOrNull { it.name == "foo" }
|
||||||
assertNotNull(fn, "function decl should be captured")
|
assertNotNull(fn, "function decl should be captured")
|
||||||
// Doc
|
// Doc
|
||||||
assertNotNull(fn.doc)
|
assertNotNull(fn.doc)
|
||||||
assertEquals("Summary: does foo", fn.doc!!.summary)
|
assertEquals("Summary: does foo", fn.doc.summary)
|
||||||
assertTrue(fn.doc!!.raw.contains("details"))
|
assertTrue(fn.doc.raw.contains("details"))
|
||||||
// Params
|
// Params
|
||||||
assertEquals(2, fn.params.size)
|
assertEquals(2, fn.params.size)
|
||||||
val p1 = fn.params[0]
|
val p1 = fn.params[0]
|
||||||
@@ -99,10 +99,10 @@ class MiniAstTest {
|
|||||||
val (_, sink) = compileWithMini(code)
|
val (_, sink) = compileWithMini(code)
|
||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini)
|
assertNotNull(mini)
|
||||||
val vd = mini!!.declarations.filterIsInstance<net.sergeych.lyng.miniast.MiniValDecl>().firstOrNull { it.name == "x" }
|
val vd = mini.declarations.filterIsInstance<net.sergeych.lyng.miniast.MiniValDecl>().firstOrNull { it.name == "x" }
|
||||||
assertNotNull(vd)
|
assertNotNull(vd)
|
||||||
assertNotNull(vd.doc)
|
assertNotNull(vd.doc)
|
||||||
assertEquals("docs for x", vd.doc!!.summary)
|
assertEquals("docs for x", vd.doc.summary)
|
||||||
val ty = vd.type
|
val ty = vd.type
|
||||||
assertNotNull(ty)
|
assertNotNull(ty)
|
||||||
val gen = ty as MiniGenericType
|
val gen = ty as MiniGenericType
|
||||||
@@ -115,6 +115,23 @@ class MiniAstTest {
|
|||||||
assertNotNull(vd.initRange)
|
assertNotNull(vd.initRange)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun miniAst_captures_class_doc_with_members() = runTest {
|
||||||
|
val code = """
|
||||||
|
/** Class C docs */
|
||||||
|
class C {
|
||||||
|
fun foo() {}
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
val (_, sink) = compileWithMini(code)
|
||||||
|
val mini = sink.build()
|
||||||
|
assertNotNull(mini)
|
||||||
|
val cd = mini.declarations.filterIsInstance<MiniClassDecl>().firstOrNull { it.name == "C" }
|
||||||
|
assertNotNull(cd)
|
||||||
|
assertNotNull(cd.doc, "Class doc should be preserved even with members")
|
||||||
|
assertTrue(cd.doc.raw.contains("Class C docs"))
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun miniAst_captures_class_bases_and_doc() = runTest {
|
fun miniAst_captures_class_bases_and_doc() = runTest {
|
||||||
val code = """
|
val code = """
|
||||||
@@ -124,10 +141,10 @@ class MiniAstTest {
|
|||||||
val (_, sink) = compileWithMini(code)
|
val (_, sink) = compileWithMini(code)
|
||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini)
|
assertNotNull(mini)
|
||||||
val cd = mini!!.declarations.filterIsInstance<MiniClassDecl>().firstOrNull { it.name == "C" }
|
val cd = mini.declarations.filterIsInstance<MiniClassDecl>().firstOrNull { it.name == "C" }
|
||||||
assertNotNull(cd)
|
assertNotNull(cd)
|
||||||
assertNotNull(cd.doc)
|
assertNotNull(cd.doc)
|
||||||
assertTrue(cd.doc!!.raw.contains("Class C docs"))
|
assertTrue(cd.doc.raw.contains("Class C docs"))
|
||||||
// Bases captured as plain names for now
|
// Bases captured as plain names for now
|
||||||
assertEquals(listOf("Base1", "Base2"), cd.bases)
|
assertEquals(listOf("Base1", "Base2"), cd.bases)
|
||||||
}
|
}
|
||||||
@@ -145,10 +162,10 @@ class MiniAstTest {
|
|||||||
val (_, sink) = compileWithMini(code)
|
val (_, sink) = compileWithMini(code)
|
||||||
val mini = sink.build()
|
val mini = sink.build()
|
||||||
assertNotNull(mini)
|
assertNotNull(mini)
|
||||||
val ed = mini!!.declarations.filterIsInstance<MiniEnumDecl>().firstOrNull { it.name == "E" }
|
val ed = mini.declarations.filterIsInstance<MiniEnumDecl>().firstOrNull { it.name == "E" }
|
||||||
assertNotNull(ed)
|
assertNotNull(ed)
|
||||||
assertNotNull(ed.doc)
|
assertNotNull(ed.doc)
|
||||||
assertTrue(ed.doc!!.raw.contains("Enum E docs"))
|
assertTrue(ed.doc.raw.contains("Enum E docs"))
|
||||||
assertEquals(listOf("A", "B", "C"), ed.entries)
|
assertEquals(listOf("A", "B", "C"), ed.entries)
|
||||||
assertEquals("E", ed.name)
|
assertEquals("E", ed.name)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.
|
||||||
@@ -348,7 +348,8 @@ class OOTest {
|
|||||||
@Test
|
@Test
|
||||||
fun testPropAsExtension() = runTest {
|
fun testPropAsExtension() = runTest {
|
||||||
val scope = Script.newScope()
|
val scope = Script.newScope()
|
||||||
scope.eval("""
|
scope.eval(
|
||||||
|
"""
|
||||||
class A(x) {
|
class A(x) {
|
||||||
private val privateVal = 100
|
private val privateVal = 100
|
||||||
val p1 get() = x + 1
|
val p1 get() = x + 1
|
||||||
@@ -368,7 +369,8 @@ class OOTest {
|
|||||||
// it should also work with properties:
|
// it should also work with properties:
|
||||||
val A.p10 get() = x * 10
|
val A.p10 get() = x * 10
|
||||||
assertEquals(20, A(2).p10)
|
assertEquals(20, A(2).p10)
|
||||||
""".trimIndent())
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
// important is that such extensions should not be able to access private members
|
// important is that such extensions should not be able to access private members
|
||||||
// and thus remove privateness:
|
// and thus remove privateness:
|
||||||
@@ -383,17 +385,350 @@ class OOTest {
|
|||||||
@Test
|
@Test
|
||||||
fun testExtensionsAreScopeIsolated() = runTest {
|
fun testExtensionsAreScopeIsolated() = runTest {
|
||||||
val scope1 = Script.newScope()
|
val scope1 = Script.newScope()
|
||||||
scope1.eval("""
|
scope1.eval(
|
||||||
|
"""
|
||||||
val String.totalDigits get() {
|
val String.totalDigits get() {
|
||||||
// notice using `this`:
|
// notice using `this`:
|
||||||
this.characters.filter{ it.isDigit() }.size()
|
this.characters.filter{ it.isDigit() }.size()
|
||||||
}
|
}
|
||||||
assertEquals(2, "answer is 42".totalDigits)
|
assertEquals(2, "answer is 42".totalDigits)
|
||||||
""")
|
"""
|
||||||
|
)
|
||||||
val scope2 = Script.newScope()
|
val scope2 = Script.newScope()
|
||||||
scope2.eval("""
|
scope2.eval(
|
||||||
|
"""
|
||||||
// in scope2 we didn't override `totalDigits` extension:
|
// in scope2 we didn't override `totalDigits` extension:
|
||||||
assertThrows { "answer is 42".totalDigits }
|
assertThrows { "answer is 42".totalDigits }
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testCacheInClass() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class T(salt) {
|
||||||
|
private var c
|
||||||
|
|
||||||
|
init {
|
||||||
|
println("create cached with "+salt)
|
||||||
|
c = cached { salt + "." }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun getResult() = c()
|
||||||
|
}
|
||||||
|
|
||||||
|
val t1 = T("foo")
|
||||||
|
val t2 = T("bar")
|
||||||
|
assertEquals("bar.", t2.getResult())
|
||||||
|
assertEquals("foo.", t1.getResult())
|
||||||
|
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLateInitValsInClasses() = runTest {
|
||||||
|
assertFails {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class T {
|
||||||
|
val x
|
||||||
|
}
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
assertFails {
|
||||||
|
eval("val String.late")
|
||||||
|
}
|
||||||
|
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
// but we can "late-init" them in init block:
|
||||||
|
class OK {
|
||||||
|
val x
|
||||||
|
|
||||||
|
init {
|
||||||
|
x = "foo"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val ok = OK()
|
||||||
|
assertEquals("foo", ok.x)
|
||||||
|
|
||||||
|
// they can't be reassigned:
|
||||||
|
assertThrows(IllegalAssignmentException) {
|
||||||
|
ok.x = "bar"
|
||||||
|
}
|
||||||
|
|
||||||
|
// To test access before init, we need a trick:
|
||||||
|
class AccessBefore {
|
||||||
|
val x
|
||||||
|
fun readX() = x
|
||||||
|
init {
|
||||||
|
assertEquals(x, Unset)
|
||||||
|
// if we call readX() here, x is Unset.
|
||||||
|
// Just reading it is fine, but using it should throw:
|
||||||
|
assertThrows(UnsetException) { readX() + 1 }
|
||||||
|
x = 42
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AccessBefore()
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testPrivateSet() = runTest {
|
||||||
|
eval(
|
||||||
|
"""
|
||||||
|
class A {
|
||||||
|
var y = 100
|
||||||
|
private set
|
||||||
|
fun setValue(newValue) { y = newValue }
|
||||||
|
}
|
||||||
|
assertEquals(100, A().y)
|
||||||
|
assertThrows(IllegalAccessException) { A().y = 200 }
|
||||||
|
val a = A()
|
||||||
|
a.setValue(200)
|
||||||
|
assertEquals(200, a.y)
|
||||||
|
|
||||||
|
class B(initial) {
|
||||||
|
var y = initial
|
||||||
|
protected set
|
||||||
|
}
|
||||||
|
class C(initial) : B(initial) {
|
||||||
|
fun setBValue(v) { y = v }
|
||||||
|
}
|
||||||
|
val c = C(10)
|
||||||
|
assertEquals(10, c.y)
|
||||||
|
assertThrows(IllegalAccessException) { c.y = 20 }
|
||||||
|
c.setBValue(30)
|
||||||
|
assertEquals(30, c.y)
|
||||||
|
|
||||||
|
class D {
|
||||||
|
private var _y = 0
|
||||||
|
var y
|
||||||
|
get() = _y
|
||||||
|
private set(v) { _y = v }
|
||||||
|
fun setY(v) { y = v }
|
||||||
|
}
|
||||||
|
val d = D()
|
||||||
|
assertEquals(0, d.y)
|
||||||
|
assertThrows(IllegalAccessException) { d.y = 10 }
|
||||||
|
d.setY(20)
|
||||||
|
assertEquals(20, d.y)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testValPrivateSetError() = runTest {
|
||||||
|
assertFails {
|
||||||
|
eval("class E { val x = 1 private set }")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAbstractClassesAndOverridingProposal() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
/*
|
||||||
|
Abstract class is a sort of interface on steroidsL it is a class some members/methods of which
|
||||||
|
are required to be implemented by heirs. Still it is a regular class in all other respects.
|
||||||
|
Just can't be instantiated
|
||||||
|
*/
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
// abstract modifier is required. It can have a constructor, or be without it:
|
||||||
|
abstract class A(someParam=1) {
|
||||||
|
// if the method is marked as abstract, it has no body:
|
||||||
|
abstract fun foo(): Int
|
||||||
|
|
||||||
|
// abstract var/var have no initializer:
|
||||||
|
abstract var bar
|
||||||
|
}
|
||||||
|
// can't create instance of the abstract class:
|
||||||
|
assertThrows { A() }
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
// create abstract method with body or val/var with initializer is an error:
|
||||||
|
assertFails { scope.eval("abstract class B { abstract fun foo() = 1 }") }
|
||||||
|
assertFails { scope.eval("abstract class C { abstract val bar = 1 }") }
|
||||||
|
|
||||||
|
// inheriting an abstract class without implementing all of it abstract members and methods
|
||||||
|
// is not allowed:
|
||||||
|
assertFails { scope.eval("class D : A(1) { override fun foo() = 10 }") }
|
||||||
|
|
||||||
|
// but it is allowed to inherit in another abstract class:
|
||||||
|
scope.eval("abstract class E : A(1) { override fun foo() = 10 }")
|
||||||
|
|
||||||
|
// implementing all abstracts let us have regular class:
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
class F : E() { override val bar = 11 }
|
||||||
|
assertEquals(10, F().foo())
|
||||||
|
assertEquals(11, F().bar)
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
// Another possibility to override symbol is multiple inheritance: the parent that
|
||||||
|
// follows the abstract class in MI chain can override the abstract symbol:
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
// This implementor know nothing of A but still implements de-facto its needs:
|
||||||
|
class Implementor {
|
||||||
|
val bar = 3
|
||||||
|
fun foo() = 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// now we can use MI to implement abstract class:
|
||||||
|
class F2 : A(42), Implementor
|
||||||
|
|
||||||
|
assertEquals(1, F2().foo())
|
||||||
|
assertEquals(3, F2().bar)
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testAbstractAndOverrideEdgeCases() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
|
||||||
|
// 1. abstract private is an error:
|
||||||
|
assertFails { scope.eval("abstract class Err { abstract private fun foo() }") }
|
||||||
|
assertFails { scope.eval("abstract class Err { abstract private val x }") }
|
||||||
|
|
||||||
|
// 2. private member in parent is not visible for overriding:
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
class Base {
|
||||||
|
private fun secret() = 1
|
||||||
|
fun callSecret() = secret()
|
||||||
|
}
|
||||||
|
class Derived : Base() {
|
||||||
|
// This is NOT an override, but a new method
|
||||||
|
fun secret() = 2
|
||||||
|
}
|
||||||
|
val d = Derived()
|
||||||
|
assertEquals(2, d.secret())
|
||||||
|
assertEquals(1, d.callSecret())
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
// Using override keyword when there is only a private member in parent is an error:
|
||||||
|
assertFails { scope.eval("class D2 : Base() { override fun secret() = 3 }") }
|
||||||
|
|
||||||
|
// 3. interface can have state (constructor, fields, init):
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
interface I(val x) {
|
||||||
|
var y = x * 2
|
||||||
|
val z
|
||||||
|
init {
|
||||||
|
z = y + 1
|
||||||
|
}
|
||||||
|
fun foo() = x + y + z
|
||||||
|
}
|
||||||
|
class Impl : I(10)
|
||||||
|
val impl = Impl()
|
||||||
|
assertEquals(10, impl.x)
|
||||||
|
assertEquals(20, impl.y)
|
||||||
|
assertEquals(21, impl.z)
|
||||||
|
assertEquals(51, impl.foo())
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
|
||||||
|
// 4. closed members cannot be overridden:
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
class G {
|
||||||
|
closed fun locked() = "locked"
|
||||||
|
closed val permanent = 42
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
assertFails { scope.eval("class H : G() { override fun locked() = \"free\" }") }
|
||||||
|
assertFails { scope.eval("class H : G() { override val permanent = 0 }") }
|
||||||
|
// Even without override keyword, it should fail if it's closed:
|
||||||
|
assertFails { scope.eval("class H : G() { fun locked() = \"free\" }") }
|
||||||
|
|
||||||
|
// 5. Visibility widening is allowed, narrowing is forbidden:
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
class BaseVis {
|
||||||
|
protected fun prot() = 1
|
||||||
|
}
|
||||||
|
class Widened : BaseVis() {
|
||||||
|
override fun prot() = 2 // Widened to public (default)
|
||||||
|
}
|
||||||
|
assertEquals(2, Widened().prot())
|
||||||
|
|
||||||
|
class BasePub {
|
||||||
|
fun pub() = 1
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
// Narrowing:
|
||||||
|
assertFails { scope.eval("class Narrowed : BasePub() { override protected fun pub() = 2 }") }
|
||||||
|
assertFails { scope.eval("class Narrowed : BasePub() { override private fun pub() = 2 }") }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testInterfaceImplementationByParts() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
scope.eval(
|
||||||
|
"""
|
||||||
|
// Interface with state (id) and abstract requirements
|
||||||
|
interface Character(val id) {
|
||||||
|
var health
|
||||||
|
var mana
|
||||||
|
fun isAlive() = health > 0
|
||||||
|
fun status() = name + " (#" + id + "): " + health + " HP, " + mana + " MP"
|
||||||
|
// name is also abstractly required by the status method,
|
||||||
|
// even if not explicitly marked 'abstract val' here,
|
||||||
|
// it will be looked up in MRO
|
||||||
|
}
|
||||||
|
|
||||||
|
// Part 1: Provides health
|
||||||
|
class HealthPool(var health)
|
||||||
|
|
||||||
|
// Part 2: Provides mana and name
|
||||||
|
class ManaPool(var mana) {
|
||||||
|
val name = "Hero"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Composite class implementing Character by parts
|
||||||
|
class Warrior(id, h, m) : HealthPool(h), ManaPool(m), Character(id)
|
||||||
|
|
||||||
|
val w = Warrior(1, 100, 50)
|
||||||
|
assertEquals(100, w.health)
|
||||||
|
assertEquals(50, w.mana)
|
||||||
|
assertEquals(1, w.id)
|
||||||
|
assert(w.isAlive())
|
||||||
|
assertEquals("Hero (#1): 100 HP, 50 MP", w.status())
|
||||||
|
|
||||||
|
w.health = 0
|
||||||
|
assert(!w.isAlive())
|
||||||
|
""".trimIndent()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
@Test
|
||||||
|
fun testBasicObjectExpression() = runTest {
|
||||||
|
eval("""
|
||||||
|
val x = object { val y = 1 }
|
||||||
|
assertEquals(1, x.y)
|
||||||
|
|
||||||
|
class Base(v) {
|
||||||
|
val value = v
|
||||||
|
fun squares() = value * value
|
||||||
|
}
|
||||||
|
|
||||||
|
val y = object : Base(2) {
|
||||||
|
override val value = 5
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(25, y.squares())
|
||||||
|
|
||||||
""".trimIndent())
|
""".trimIndent())
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package net.sergeych.lyng
|
||||||
|
|
||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.lynon.lynonEncodeAny
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertFailsWith
|
||||||
|
|
||||||
|
class ObjectExpressionTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBasicObjectExpression() = runTest {
|
||||||
|
eval("""
|
||||||
|
val x = object { val y = 1 }
|
||||||
|
assertEquals(1, x.y)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testInheritanceWithArgs() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Base(x) {
|
||||||
|
val value = x
|
||||||
|
val squares = x * x
|
||||||
|
}
|
||||||
|
|
||||||
|
val y = object : Base(5) {
|
||||||
|
val z = value + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(5, y.value)
|
||||||
|
assertEquals(25, y.squares)
|
||||||
|
assertEquals(6, y.z)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMultipleInheritance() = runTest {
|
||||||
|
eval("""
|
||||||
|
interface A { fun a() = "A" }
|
||||||
|
interface B { fun b() = "B" }
|
||||||
|
|
||||||
|
val x = object : A, B {
|
||||||
|
fun c() = a() + b()
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("AB", x.c())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testScopeCapture() = runTest {
|
||||||
|
eval("""
|
||||||
|
fun createCounter(start) {
|
||||||
|
var count = start
|
||||||
|
object {
|
||||||
|
fun next() {
|
||||||
|
val res = count
|
||||||
|
count = count + 1
|
||||||
|
res
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val c = createCounter(10)
|
||||||
|
assertEquals(10, c.next())
|
||||||
|
assertEquals(11, c.next())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testThisObjectAlias() = runTest {
|
||||||
|
eval("""
|
||||||
|
val x = object {
|
||||||
|
val value = 42
|
||||||
|
fun self() = this@object
|
||||||
|
fun getValue() = this@object.value
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(42, x.getValue())
|
||||||
|
// assert(x === x.self()) // Lyng might not have === for identity yet, checking if it compiles and runs
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSerializationRejection() = runTest {
|
||||||
|
val scope = Script.newScope()
|
||||||
|
val obj = scope.eval("object { val x = 1 }")
|
||||||
|
assertFailsWith<Exception> {
|
||||||
|
lynonEncodeAny(scope, obj)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testQualifiedThis() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Outer {
|
||||||
|
val value = 1
|
||||||
|
fun getObj() {
|
||||||
|
object {
|
||||||
|
fun getOuterValue() = this@Outer.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val o = Outer()
|
||||||
|
val x = o.getObj()
|
||||||
|
assertEquals(1, x.getOuterValue())
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDiagnosticName() = runTest {
|
||||||
|
// This is harder to test directly, but we can check if it has a class and if that class name looks "anonymous"
|
||||||
|
eval("""
|
||||||
|
val x = object { }
|
||||||
|
val name = x::class.className
|
||||||
|
assert(name.startsWith("${'$'}Anon_"))
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
import kotlinx.coroutines.test.runTest
|
||||||
|
import net.sergeych.lyng.ScriptError
|
||||||
|
import net.sergeych.lyng.eval
|
||||||
|
import net.sergeych.lyng.obj.toInt
|
||||||
|
import kotlin.test.Test
|
||||||
|
import kotlin.test.assertEquals
|
||||||
|
import kotlin.test.assertFailsWith
|
||||||
|
|
||||||
|
class ReturnStatementTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBasicReturn() = runTest {
|
||||||
|
assertEquals(10, eval("""
|
||||||
|
fun foo() {
|
||||||
|
return 10
|
||||||
|
20
|
||||||
|
}
|
||||||
|
foo()
|
||||||
|
""").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReturnFromIf() = runTest {
|
||||||
|
assertEquals(5, eval("""
|
||||||
|
fun foo(x) {
|
||||||
|
if (x > 0) return 5
|
||||||
|
10
|
||||||
|
}
|
||||||
|
foo(1)
|
||||||
|
""").toInt())
|
||||||
|
|
||||||
|
assertEquals(10, eval("""
|
||||||
|
fun foo(x) {
|
||||||
|
if (x > 0) return 5
|
||||||
|
10
|
||||||
|
}
|
||||||
|
foo(-1)
|
||||||
|
""").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReturnFromLambda() = runTest {
|
||||||
|
assertEquals(2, eval("""
|
||||||
|
val f = { x ->
|
||||||
|
if (x < 0) return 0
|
||||||
|
x * 2
|
||||||
|
}
|
||||||
|
f(1)
|
||||||
|
""").toInt())
|
||||||
|
|
||||||
|
assertEquals(0, eval("""
|
||||||
|
val f = { x ->
|
||||||
|
if (x < 0) return 0
|
||||||
|
x * 2
|
||||||
|
}
|
||||||
|
f(-1)
|
||||||
|
""").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testNonLocalReturn() = runTest {
|
||||||
|
assertEquals(100, eval("""
|
||||||
|
fun outer() {
|
||||||
|
[1, 2, 3].forEach {
|
||||||
|
if (it == 2) return@outer 100
|
||||||
|
}
|
||||||
|
0
|
||||||
|
}
|
||||||
|
outer()
|
||||||
|
""").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLabeledLambdaReturn() = runTest {
|
||||||
|
assertEquals(42, eval("""
|
||||||
|
val f = @inner { x ->
|
||||||
|
if (x == 0) return@inner 42
|
||||||
|
x
|
||||||
|
}
|
||||||
|
f(0)
|
||||||
|
""").toInt())
|
||||||
|
|
||||||
|
assertEquals(5, eval("""
|
||||||
|
val f = @inner { x ->
|
||||||
|
if (x == 0) return@inner 42
|
||||||
|
x
|
||||||
|
}
|
||||||
|
f(5)
|
||||||
|
""").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testForbidEqualReturn() = runTest {
|
||||||
|
assertFailsWith<ScriptError> {
|
||||||
|
eval("fun foo(x) = return x")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testDeepNestedReturn() = runTest {
|
||||||
|
assertEquals(42, eval("""
|
||||||
|
fun find() {
|
||||||
|
val data = [[1, 2], [3, 42], [5, 6]]
|
||||||
|
data.forEach { row ->
|
||||||
|
row.forEach { item ->
|
||||||
|
if (item == 42) return@find item
|
||||||
|
}
|
||||||
|
}
|
||||||
|
0
|
||||||
|
}
|
||||||
|
find()
|
||||||
|
""").toInt())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testReturnFromOuterLambda() = runTest {
|
||||||
|
assertEquals("found", eval("""
|
||||||
|
val f_outer = @outer {
|
||||||
|
val f_inner = {
|
||||||
|
return@outer "found"
|
||||||
|
}
|
||||||
|
f_inner()
|
||||||
|
"not found"
|
||||||
|
}
|
||||||
|
f_outer()
|
||||||
|
""").toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -4532,4 +4532,44 @@ class ScriptTest {
|
|||||||
""".trimIndent())
|
""".trimIndent())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// @Test
|
||||||
|
// fun testUserClassExceptions() = runTest {
|
||||||
|
// eval("""
|
||||||
|
// val x = try { throw IllegalAccessException("test1") } catch { it }
|
||||||
|
// assertEquals("test1", x.message)
|
||||||
|
// assert( x is IllegalAccessException)
|
||||||
|
// assertThrows(IllegalAccessException) { throw IllegalAccessException("test2") }
|
||||||
|
//
|
||||||
|
// class X : Exception("test3")
|
||||||
|
// val y = try { throw X() } catch { it }
|
||||||
|
// println(y)
|
||||||
|
// assertEquals("test3", y.message)
|
||||||
|
// assert( y is X)
|
||||||
|
//
|
||||||
|
// """.trimIndent())
|
||||||
|
// }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testTodo() = runTest {
|
||||||
|
eval("""
|
||||||
|
assertThrows(NotImplementedException) {
|
||||||
|
TODO()
|
||||||
|
}
|
||||||
|
val x = try { TODO("check me") } catch { it }
|
||||||
|
assertEquals("check me", x.message)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testOptOnNullAssignment() = runTest {
|
||||||
|
eval("""
|
||||||
|
var x = null
|
||||||
|
assertEquals(null, x)
|
||||||
|
x ?= 1
|
||||||
|
assertEquals(1, x)
|
||||||
|
x ?= 2
|
||||||
|
assertEquals(1, x)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -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.
|
||||||
@@ -113,4 +113,22 @@ class StdlibTest {
|
|||||||
assertEquals(5, (1..10).toList().count { it % 2 == 1 } )
|
assertEquals(5, (1..10).toList().count { it % 2 == 1 } )
|
||||||
""")
|
""")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testWith() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Person(val name, var age)
|
||||||
|
val p = Person("Alice", 30)
|
||||||
|
|
||||||
|
val result = with(p) {
|
||||||
|
assertEquals("Alice", name)
|
||||||
|
assertEquals(30, age)
|
||||||
|
age = 31
|
||||||
|
"done"
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals("done", result)
|
||||||
|
assertEquals(31, p.age)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,326 @@
|
|||||||
|
/*
|
||||||
|
* 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 kotlin.test.Test
|
||||||
|
|
||||||
|
class DelegationTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testSimpleDelegation() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Proxy() {
|
||||||
|
fun getValue(r, n) = 42
|
||||||
|
}
|
||||||
|
val x by Proxy()
|
||||||
|
assertEquals(42, x)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testConstructorVal() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Foo(val v) {
|
||||||
|
fun getV() = v
|
||||||
|
}
|
||||||
|
val f = Foo(42)
|
||||||
|
assertEquals(42, f.v)
|
||||||
|
assertEquals(42, f.getV())
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBasicValVarDelegation() = runTest {
|
||||||
|
eval("""
|
||||||
|
class MapDelegate(val map) {
|
||||||
|
fun getValue(thisRef, name) = map[name]
|
||||||
|
fun setValue(thisRef, name, value) { map[name] = value }
|
||||||
|
}
|
||||||
|
|
||||||
|
val data = { "x": 10 }
|
||||||
|
val x by MapDelegate(data)
|
||||||
|
var y by MapDelegate(data)
|
||||||
|
|
||||||
|
assertEquals(10, x)
|
||||||
|
assertEquals(null, y)
|
||||||
|
y = 20
|
||||||
|
assertEquals(20, data["y"])
|
||||||
|
assertEquals(20, y)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testClassDelegationWithThisRef() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Proxy(val target) {
|
||||||
|
fun getValue(thisRef, name) = target[name]
|
||||||
|
fun setValue(thisRef, name, value) { target[name] = value }
|
||||||
|
}
|
||||||
|
|
||||||
|
class User(initialName) {
|
||||||
|
val storage = { "name": initialName }
|
||||||
|
var name by Proxy(storage)
|
||||||
|
}
|
||||||
|
|
||||||
|
val u = User("Alice")
|
||||||
|
assertEquals("Alice", u.name)
|
||||||
|
u.name = "Bob"
|
||||||
|
assertEquals("Bob", u.name)
|
||||||
|
assertEquals("Bob", u.storage["name"])
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testFunDelegation() = runTest {
|
||||||
|
eval("""
|
||||||
|
class ActionDelegate() {
|
||||||
|
fun invoke(thisRef, name, args...) {
|
||||||
|
"Called %s with %d args: %s"(name, args.size, args.joinToString(","))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun greet by ActionDelegate()
|
||||||
|
|
||||||
|
assertEquals("Called greet with 2 args: hello,world", greet("hello", "world"))
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testBindHook() = runTest {
|
||||||
|
eval("""
|
||||||
|
// Note: DelegateAccess might need to be defined or built-in
|
||||||
|
// For the test, let's assume it's passed as an integer or we define it
|
||||||
|
val VAL = 0
|
||||||
|
val VAR = 1
|
||||||
|
val CALLABLE = 2
|
||||||
|
|
||||||
|
class OnlyVal() {
|
||||||
|
fun bind(name, access, thisRef) {
|
||||||
|
if (access != VAL) throw "Only val allowed"
|
||||||
|
this
|
||||||
|
}
|
||||||
|
fun getValue(thisRef, name) = 42
|
||||||
|
}
|
||||||
|
|
||||||
|
val ok by OnlyVal()
|
||||||
|
assertEquals(42, ok)
|
||||||
|
|
||||||
|
assertThrows {
|
||||||
|
eval("var bad by OnlyVal()")
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStatelessObjectDelegate() = runTest {
|
||||||
|
eval("""
|
||||||
|
object Constant42 {
|
||||||
|
fun getValue(thisRef, name) = 42
|
||||||
|
}
|
||||||
|
|
||||||
|
class Foo {
|
||||||
|
val a by Constant42
|
||||||
|
val b by Constant42
|
||||||
|
}
|
||||||
|
|
||||||
|
val f = Foo()
|
||||||
|
assertEquals(42, f.a)
|
||||||
|
assertEquals(42, f.b)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLazyImplementation() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Lazy(val creator) {
|
||||||
|
private var value = Unset
|
||||||
|
fun getValue(thisRef, name) {
|
||||||
|
if (this.value == Unset) {
|
||||||
|
this.value = creator()
|
||||||
|
}
|
||||||
|
this.value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fun lazy(creator) = Lazy(creator)
|
||||||
|
|
||||||
|
var counter = 0
|
||||||
|
val x by lazy { counter++; "computed" }
|
||||||
|
|
||||||
|
assertEquals(0, counter)
|
||||||
|
assertEquals("computed", x)
|
||||||
|
assertEquals(1, counter)
|
||||||
|
assertEquals("computed", x)
|
||||||
|
assertEquals(1, counter)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLocalDelegation() = runTest {
|
||||||
|
eval("""
|
||||||
|
class LocalProxy(val v) {
|
||||||
|
fun getValue(thisRef, name) = v
|
||||||
|
}
|
||||||
|
|
||||||
|
fun test() {
|
||||||
|
val x by LocalProxy(123)
|
||||||
|
x
|
||||||
|
}
|
||||||
|
|
||||||
|
assertEquals(123, test())
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testStdlibLazy() = runTest {
|
||||||
|
eval("""
|
||||||
|
var counter = 0
|
||||||
|
val x by lazy { counter++; "computed" }
|
||||||
|
|
||||||
|
assertEquals(0, counter)
|
||||||
|
assertEquals("computed", x)
|
||||||
|
assertEquals(1, counter)
|
||||||
|
assertEquals("computed", x)
|
||||||
|
|
||||||
|
assertThrows {
|
||||||
|
eval("var y by lazy { 1 }")
|
||||||
|
}
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLazyIsDelegate() = runTest {
|
||||||
|
eval("""
|
||||||
|
val l = lazy { 42 }
|
||||||
|
assert(l is Delegate)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testRealLifeBug1() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Cell {
|
||||||
|
val tags = [1,2,3]
|
||||||
|
}
|
||||||
|
class T {
|
||||||
|
val cell by lazy { Cell() }
|
||||||
|
val tags get() = cell.tags
|
||||||
|
}
|
||||||
|
assertEquals([1,2,3], T().tags)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testInstanceIsolation() = runTest {
|
||||||
|
eval("""
|
||||||
|
class CounterDelegate() {
|
||||||
|
private var count = 0
|
||||||
|
fun getValue(thisRef, name) = ++count
|
||||||
|
}
|
||||||
|
|
||||||
|
class Foo {
|
||||||
|
val x by CounterDelegate()
|
||||||
|
}
|
||||||
|
|
||||||
|
val f1 = Foo()
|
||||||
|
val f2 = Foo()
|
||||||
|
|
||||||
|
assertEquals(1, f1.x)
|
||||||
|
assertEquals(1, f2.x)
|
||||||
|
assertEquals(2, f1.x)
|
||||||
|
assertEquals(2, f2.x)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLazyRegexBug() = runTest {
|
||||||
|
eval("""
|
||||||
|
class T {
|
||||||
|
val re by lazy { Regex(".*") }
|
||||||
|
}
|
||||||
|
val t = T()
|
||||||
|
t.re
|
||||||
|
// Second access triggered the bug before fix (value == Unset failed)
|
||||||
|
t.re
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testEqualityRobustness() = runTest {
|
||||||
|
eval("""
|
||||||
|
val re1 = Regex("a")
|
||||||
|
val re2 = Regex("a")
|
||||||
|
// Equality should not throw even if types don't implement compareTo
|
||||||
|
assertEquals(true, re1 == re1)
|
||||||
|
assertEquals(false, re1 == re2)
|
||||||
|
assertEquals(false, re1 == Unset)
|
||||||
|
assertEquals(false, re1 == null)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testLazy2() = runTest {
|
||||||
|
eval("""
|
||||||
|
class A {
|
||||||
|
val tags = [1,2,3]
|
||||||
|
}
|
||||||
|
class B {
|
||||||
|
val tags by lazy { myA.tags }
|
||||||
|
val myA by lazy { A() }
|
||||||
|
}
|
||||||
|
assert( B().tags == [1,2,3])
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testThisInLazy() = runTest {
|
||||||
|
eval("""
|
||||||
|
class A {
|
||||||
|
val numbers = [1,2,3]
|
||||||
|
val tags by lazy { this.numbers }
|
||||||
|
}
|
||||||
|
class B {
|
||||||
|
val a by lazy { A() }
|
||||||
|
val test by lazy { a.tags + [4] }
|
||||||
|
}
|
||||||
|
assertEquals( [1,2,3], A().tags)
|
||||||
|
assertEquals( [1,2,3,4], B().test)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testScopeInLazy() = runTest {
|
||||||
|
val s1 = Script.newScope()
|
||||||
|
s1.eval("""
|
||||||
|
class A {
|
||||||
|
val tags by lazy { GLOBAL_NUMBERS }
|
||||||
|
}
|
||||||
|
""".trimIndent())
|
||||||
|
// on the same scope, it will see my GLOBAL_NUMBERS:
|
||||||
|
s1.eval("""
|
||||||
|
val GLOBAL_NUMBERS = [1,2,3]
|
||||||
|
class B {
|
||||||
|
val a by lazy { A() }
|
||||||
|
val test by lazy { a.tags + [4] }
|
||||||
|
}
|
||||||
|
assertEquals( [1,2,3], A().tags)
|
||||||
|
assertEquals( [1,2,3,4], B().test)
|
||||||
|
""")
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -39,7 +39,7 @@ class BlockReindentTest {
|
|||||||
val open = BraceUtils.findMatchingOpenBrace(text, close)
|
val open = BraceUtils.findMatchingOpenBrace(text, close)
|
||||||
assertNotNull(open)
|
assertNotNull(open)
|
||||||
// The char at open must be '{'
|
// The char at open must be '{'
|
||||||
assertEquals('{', text[open!!])
|
assertEquals('{', text[open])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -55,7 +55,7 @@ class BlockReindentTest {
|
|||||||
val range = BraceUtils.findEnclosingBlockRange(text, close, includeTrailingNewline = true)
|
val range = BraceUtils.findEnclosingBlockRange(text, close, includeTrailingNewline = true)
|
||||||
assertNotNull(range)
|
assertNotNull(range)
|
||||||
// The range must start at the line start of the matching '{' and end at or after the newline after '}'
|
// The range must start at the line start of the matching '{' and end at or after the newline after '}'
|
||||||
val start = range!!.first
|
val start = range.first
|
||||||
val end = range.last + 1
|
val end = range.last + 1
|
||||||
val startLinePrefix = text.substring(BraceUtils.lineStart(text, start), start)
|
val startLinePrefix = text.substring(BraceUtils.lineStart(text, start), start)
|
||||||
// start at column 0 of the line
|
// start at column 0 of the line
|
||||||
@@ -434,4 +434,37 @@ class BlockReindentTest {
|
|||||||
kotlin.test.assertTrue(lines.getOrNull(innerStart + 1)?.trimStart()?.startsWith("1") == true)
|
kotlin.test.assertTrue(lines.getOrNull(innerStart + 1)?.trimStart()?.startsWith("1") == true)
|
||||||
kotlin.test.assertEquals("}", lines.getOrNull(innerStart + 2)?.trim())
|
kotlin.test.assertEquals("}", lines.getOrNull(innerStart + 2)?.trim())
|
||||||
}
|
}
|
||||||
|
@Test
|
||||||
|
fun reindentRange_doubledIndentationFix() {
|
||||||
|
val src = """
|
||||||
|
class X {
|
||||||
|
fun funA(): String {
|
||||||
|
"a"
|
||||||
|
}
|
||||||
|
fun runB() {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
// The range for runB should be from the start of 'fun runB' line to the end of '}' line.
|
||||||
|
val startOfRunB = src.indexOf(" fun runB")
|
||||||
|
val endOfRunB = src.indexOf(" }") + " }".length
|
||||||
|
val range = startOfRunB until endOfRunB
|
||||||
|
|
||||||
|
val cfg = LyngFormatConfig(indentSize = 4)
|
||||||
|
val updated = LyngFormatter.reindentRange(src, range, cfg, preserveBaseIndent = true)
|
||||||
|
|
||||||
|
val expected = """
|
||||||
|
class X {
|
||||||
|
fun funA(): String {
|
||||||
|
"a"
|
||||||
|
}
|
||||||
|
fun runB() {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
assertEquals(expected, updated)
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -21,6 +21,15 @@ import kotlin.test.assertEquals
|
|||||||
|
|
||||||
class LyngFormatterTest {
|
class LyngFormatterTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun labelFormatting() {
|
||||||
|
val src = "return @label; break @outer; continue @inner"
|
||||||
|
val expected = "return@label; break@outer; continue@inner"
|
||||||
|
val cfg = LyngFormatConfig(applySpacing = true)
|
||||||
|
val out = LyngFormatter.format(src, cfg)
|
||||||
|
assertEquals(expected, out)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun reindent_simpleFunction() {
|
fun reindent_simpleFunction() {
|
||||||
val src = """
|
val src = """
|
||||||
@@ -730,4 +739,124 @@ class LyngFormatterTest {
|
|||||||
|
|
||||||
assertEquals(expected, formatted)
|
assertEquals(expected, formatted)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun privateSet_indentation() {
|
||||||
|
val src = """
|
||||||
|
class A {
|
||||||
|
var x = 1
|
||||||
|
private set
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
// What we expect: private set should be indented relative to the property
|
||||||
|
val expected = """
|
||||||
|
class A {
|
||||||
|
var x = 1
|
||||||
|
private set
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val cfg = LyngFormatConfig(indentSize = 4, continuationIndentSize = 4)
|
||||||
|
val out = LyngFormatter.reindent(src, cfg)
|
||||||
|
assertEquals(expected, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun propertyAccessors_indentation() {
|
||||||
|
val src = """
|
||||||
|
class A {
|
||||||
|
var x
|
||||||
|
get() = 1
|
||||||
|
private set(v) {
|
||||||
|
_x = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val expected = """
|
||||||
|
class A {
|
||||||
|
var x
|
||||||
|
get() = 1
|
||||||
|
private set(v) {
|
||||||
|
_x = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val cfg = LyngFormatConfig(indentSize = 4, continuationIndentSize = 4)
|
||||||
|
val out = LyngFormatter.reindent(src, cfg)
|
||||||
|
assertEquals(expected, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nestedAwaitingIndentation() {
|
||||||
|
val src = """
|
||||||
|
if (cond)
|
||||||
|
if (other)
|
||||||
|
fun f() {
|
||||||
|
stmt
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val expected = """
|
||||||
|
if (cond)
|
||||||
|
if (other)
|
||||||
|
fun f() {
|
||||||
|
stmt
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val cfg = LyngFormatConfig(indentSize = 4, continuationIndentSize = 4)
|
||||||
|
val out = LyngFormatter.reindent(src, cfg)
|
||||||
|
assertEquals(expected, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun propertyAccessor_followedByMethod() {
|
||||||
|
val src = """
|
||||||
|
var state: BarRequestState get() = getState()
|
||||||
|
set(value) = setState(value)
|
||||||
|
|
||||||
|
fun save() { cell.value = this }
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val expected = """
|
||||||
|
var state: BarRequestState get() = getState()
|
||||||
|
set(value) = setState(value)
|
||||||
|
|
||||||
|
fun save() { cell.value = this }
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val cfg = LyngFormatConfig(indentSize = 4, continuationIndentSize = 4)
|
||||||
|
val out = LyngFormatter.reindent(src, cfg)
|
||||||
|
assertEquals(expected, out)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun propertyAccessor_dangling() {
|
||||||
|
val src1 = """
|
||||||
|
var x
|
||||||
|
get()
|
||||||
|
= 1
|
||||||
|
""".trimIndent()
|
||||||
|
val expected1 = """
|
||||||
|
var x
|
||||||
|
get()
|
||||||
|
= 1
|
||||||
|
""".trimIndent()
|
||||||
|
assertEquals(expected1, LyngFormatter.reindent(src1, LyngFormatConfig(indentSize = 4)))
|
||||||
|
|
||||||
|
val src2 = """
|
||||||
|
var x
|
||||||
|
get() =
|
||||||
|
1
|
||||||
|
""".trimIndent()
|
||||||
|
val expected2 = """
|
||||||
|
var x
|
||||||
|
get() =
|
||||||
|
1
|
||||||
|
""".trimIndent()
|
||||||
|
assertEquals(expected2, LyngFormatter.reindent(src2, LyngFormatConfig(indentSize = 4)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -34,7 +34,7 @@ class CommentEolTest {
|
|||||||
assertTrue(cmt != null, "Expected a comment span")
|
assertTrue(cmt != null, "Expected a comment span")
|
||||||
// It should start at 0 and extend exactly to the end of the line (before \n)
|
// It should start at 0 and extend exactly to the end of the line (before \n)
|
||||||
val eol = text.indexOf('\n')
|
val eol = text.indexOf('\n')
|
||||||
assertEquals(0, cmt!!.range.start, "Comment should start at column 0")
|
assertEquals(0, cmt.range.start, "Comment should start at column 0")
|
||||||
assertEquals(eol, cmt.range.endExclusive, "Comment should extend to EOL")
|
assertEquals(eol, cmt.range.endExclusive, "Comment should extend to EOL")
|
||||||
// Ensure there is no other span overlapping within the same line
|
// Ensure there is no other span overlapping within the same line
|
||||||
spans.filter { it !== cmt }.forEach {
|
spans.filter { it !== cmt }.forEach {
|
||||||
@@ -50,7 +50,7 @@ class CommentEolTest {
|
|||||||
assertTrue(cmt != null, "Expected a block comment span")
|
assertTrue(cmt != null, "Expected a block comment span")
|
||||||
// The comment should end right after "/* block */"
|
// The comment should end right after "/* block */"
|
||||||
val expectedEnd = "/* block */".length
|
val expectedEnd = "/* block */".length
|
||||||
assertEquals(expectedEnd, cmt!!.range.endExclusive, "Block comment should not be extended to EOL")
|
assertEquals(expectedEnd, cmt.range.endExclusive, "Block comment should not be extended to EOL")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -25,6 +25,16 @@ class HighlightMappingTest {
|
|||||||
private fun spansToLabeled(text: String, spans: List<HighlightSpan>): List<Pair<String, HighlightKind>> =
|
private fun spansToLabeled(text: String, spans: List<HighlightSpan>): List<Pair<String, HighlightKind>> =
|
||||||
spans.map { text.substring(it.range.start, it.range.endExclusive) to it.kind }
|
spans.map { text.substring(it.range.start, it.range.endExclusive) to it.kind }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun returnAndExits() {
|
||||||
|
val text = "return 42; break@outer null"
|
||||||
|
val spans = SimpleLyngHighlighter().highlight(text)
|
||||||
|
val labeled = spansToLabeled(text, spans)
|
||||||
|
assertTrue(labeled.any { it.first == "return" && it.second == HighlightKind.Keyword })
|
||||||
|
assertTrue(labeled.any { it.first == "break" && it.second == HighlightKind.Keyword })
|
||||||
|
assertTrue(labeled.any { it.first == "@outer" && it.second == HighlightKind.Label })
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun keywordsAndIdentifiers() {
|
fun keywordsAndIdentifiers() {
|
||||||
val text = "a and b or not c"
|
val text = "a and b or not c"
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package net.sergeych.lyng.miniast
|
|||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
import kotlin.test.Test
|
import kotlin.test.Test
|
||||||
import kotlin.test.assertFalse
|
import kotlin.test.assertFalse
|
||||||
|
import kotlin.test.assertNotNull
|
||||||
import kotlin.test.assertTrue
|
import kotlin.test.assertTrue
|
||||||
|
|
||||||
class CompletionEngineLightTest {
|
class CompletionEngineLightTest {
|
||||||
@@ -89,9 +90,9 @@ class CompletionEngineLightTest {
|
|||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
val items = CompletionEngineLight.completeAtMarkerSuspend(code)
|
val items = CompletionEngineLight.completeAtMarkerSuspend(code)
|
||||||
val reItem = items.firstOrNull { it.name == "re" }
|
val reItem = items.firstOrNull { it.name == "re" }
|
||||||
assertTrue(reItem != null, "Expected to find 're' in String members, got: ${items.map { it.name }}")
|
assertNotNull(reItem, "Expected to find 're' in String members, got: ${items.map { it.name }}")
|
||||||
// Type text should contain ": Regex"
|
// Type text should contain ": Regex"
|
||||||
assertTrue(reItem!!.typeText?.contains("Regex") == true, "Expected type text to contain 'Regex', was: ${reItem.typeText}")
|
assertTrue(reItem.typeText?.contains("Regex") == true, "Expected type text to contain 'Regex', was: ${reItem.typeText}")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -106,8 +107,8 @@ class CompletionEngineLightTest {
|
|||||||
val names = items.map { it.name }
|
val names = items.map { it.name }
|
||||||
assertTrue(names.isNotEmpty(), "Expected String members for parenthesized literal, got empty list")
|
assertTrue(names.isNotEmpty(), "Expected String members for parenthesized literal, got empty list")
|
||||||
val reItem = items.firstOrNull { it.name == "re" }
|
val reItem = items.firstOrNull { it.name == "re" }
|
||||||
assertTrue(reItem != null, "Expected to find 're' for parenthesized String literal, got: $names")
|
assertNotNull(reItem, "Expected to find 're' for parenthesized String literal, got: $names")
|
||||||
assertTrue(reItem!!.typeText?.contains("Regex") == true, "Expected ': Regex' for re(), was: ${reItem.typeText}")
|
assertTrue(reItem.typeText?.contains("Regex") == true, "Expected ': Regex' for re(), was: ${reItem.typeText}")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -120,8 +121,8 @@ class CompletionEngineLightTest {
|
|||||||
val names = items.map { it.name }
|
val names = items.map { it.name }
|
||||||
assertTrue(names.isNotEmpty(), "Expected String members without explicit imports, got empty list")
|
assertTrue(names.isNotEmpty(), "Expected String members without explicit imports, got empty list")
|
||||||
val reItem = items.firstOrNull { it.name == "re" }
|
val reItem = items.firstOrNull { it.name == "re" }
|
||||||
assertTrue(reItem != null, "Expected to find 're' without explicit imports, got: $names")
|
assertNotNull(reItem, "Expected to find 're' without explicit imports, got: $names")
|
||||||
assertTrue(reItem!!.typeText?.contains("Regex") == true, "Expected ': Regex' for re() without imports, was: ${reItem.typeText}")
|
assertTrue(reItem.typeText?.contains("Regex") == true, "Expected ': Regex' for re() without imports, was: ${reItem.typeText}")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user