Compare commits

...
52 changed files with 2361 additions and 1024 deletions

No files matched your search

+1
View File
@@ -20,3 +20,4 @@ xcuserdata
.output*.txt .output*.txt
debug.log debug.log
/build.log /build.log
/test.md
+10
View File
@@ -2,6 +2,15 @@
### Unreleased ### Unreleased
- 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 }`.
@@ -100,6 +109,7 @@ All notable changes to this project will be documented in this 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: 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: 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.
+195 -23
View File
@@ -42,6 +42,35 @@ 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)
}
}
```
## 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 +79,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 +105,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
@@ -104,7 +133,7 @@ class Counter {
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. 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.
```kotlin ```lyng
class DataService(val id: Int) { class DataService(val id: Int) {
// The lambda passed to cached is only executed once, the first time data() is called. // The lambda passed to cached is only executed once, the first time data() is called.
val data = cached { val data = cached {
@@ -122,6 +151,39 @@ 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. 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.
@@ -179,7 +241,7 @@ Note that unlike **Kotlin**, which uses `=` for named arguments, Lyng uses `:` t
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. 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.
```kotlin ```lyng
class DataProcessor(data: Object) { class DataProcessor(data: Object) {
val result: Object val result: Object
@@ -200,7 +262,7 @@ Key rules for late-init `val`:
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. 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.
```kotlin ```lyng
class T { class T {
val x val x
fun check() { fun check() {
@@ -237,7 +299,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 }
@@ -286,16 +348,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
@@ -312,10 +374,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:
@@ -438,7 +610,7 @@ You can restrict the visibility of a `var` field's or property's setter by using
#### On Fields #### On Fields
```kotlin ```lyng
class SecretCounter { class SecretCounter {
var count = 0 var count = 0
private set // Can be read anywhere, but written only in SecretCounter private set // Can be read anywhere, but written only in SecretCounter
@@ -448,7 +620,7 @@ class SecretCounter {
val c = SecretCounter() val c = SecretCounter()
println(c.count) // OK println(c.count) // OK
c.count = 10 // Throws AccessException c.count = 10 // Throws IllegalAccessException
c.increment() // OK c.increment() // OK
``` ```
@@ -456,7 +628,7 @@ c.increment() // OK
You can also apply restricted visibility to custom property setters: You can also apply restricted visibility to custom property setters:
```kotlin ```lyng
class Person(private var _age: Int) { class Person(private var _age: Int) {
var age var age
get() = _age get() = _age
@@ -468,7 +640,7 @@ class Person(private var _age: Int) {
A `protected set` allows subclasses to modify a field that is otherwise read-only to the public: A `protected set` allows subclasses to modify a field that is otherwise read-only to the public:
```kotlin ```lyng
class Base { class Base {
var state = "initial" var state = "initial"
protected set protected set
@@ -484,7 +656,7 @@ val d = Derived()
println(d.state) // OK: "initial" println(d.state) // OK: "initial"
d.changeState("updated") d.changeState("updated")
println(d.state) // OK: "updated" println(d.state) // OK: "updated"
d.state = "bad" // Throws AccessException: public write not allowed d.state = "bad" // Throws IllegalAccessException: public write not allowed
``` ```
### Key Rules and Limitations ### Key Rules and Limitations
@@ -651,7 +823,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!"
@@ -662,7 +834,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
@@ -685,7 +857,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)
@@ -822,12 +994,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
View File
@@ -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.
+15
View File
@@ -0,0 +1,15 @@
# AI notes: avoid Kotlin/Wasm invalid IR with suspend lambdas
## Do
- Prefer explicit `object : Statement()` with `override suspend fun execute(...)` when building compiler statements.
- Keep `Statement` objects non-lambda, especially in compiler hot paths like parsing/var declarations.
- If you need conditional behavior, return early in `execute` instead of wrapping `parseExpression()` with `statement(...) { ... }`.
- When wasmJs tests hang in the browser, first check `wasmJsNodeTest` for a compile error; hangs often mean module instantiation failed.
## Don't
- Do not create suspend lambdas inside `Statement` factories (`statement { ... }`) for wasm targets.
- Do not "fix" hangs by increasing browser timeouts; it masks invalid wasm generation.
## Debugging tips
- Look for `$invokeCOROUTINE$` in wasm function names when mapping failures.
- If node test logs a wasm compile error, the browser hang is likely the same root cause.
+175
View File
@@ -0,0 +1,175 @@
# 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) {
value = 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.
+2 -2
View File
@@ -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 |
| | | | | |
+1 -1
View File
@@ -72,7 +72,7 @@ Tip: If a closure unexpectedly cannot see an outer local, check whether an inter
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: 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:
```kotlin ```lyng
fun cached(builder) { fun cached(builder) {
var calculated = false var calculated = false
var value = null var value = null
+24 -3
View File
@@ -87,6 +87,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
@@ -1553,13 +1574,13 @@ It is extremely simple to use: you pass it a block (lambda) that performs the co
### Basic Example ### Basic Example
```kotlin ```lyng
val expensive = cached { val expensive = cached {
println("Performing expensive calculation...") println("Performing expensive calculation...")
2 + 2 2 + 2
} }
println(expensive()) // Prints "Performing expensive calculation..." then "4" println(expensive()) // Prints "Performing expensive calculation...") then "4"
println(expensive()) // Prints only "4" (result is cached) println(expensive()) // Prints only "4" (result is cached)
``` ```
@@ -1573,7 +1594,7 @@ println(expensive()) // Prints only "4" (result is cached)
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: 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:
```kotlin ```lyng
class User(val id: Int) { class User(val id: Int) {
// The details will be fetched only once, on demand // The details will be fetched only once, on demand
val details = cached { val details = cached {
+27
View File
@@ -0,0 +1,27 @@
# Wasm generation hang in wasmJs browser tests
## Summary
The wasmJs browser test runner hung after commit 5f819dc. The root cause was invalid WebAssembly generated by the Kotlin/Wasm backend when certain compiler paths emitted suspend lambdas for `Statement` execution. The invalid module failed to instantiate in the browser, and Karma kept the browser connected but never ran tests.
## Symptoms
- `:lynglib:wasmJsBrowserTest` hangs indefinitely in ChromeHeadless.
- `:lynglib:wasmJsNodeTest` fails with a WebAssembly compile error similar to:
- `struct.set expected type (ref null XXXX), found global.get of type (ref null YYYY)`
- The failing function name in the wasm name section looks like:
- `net.sergeych.lyng.$invokeCOROUTINE$.doResume`
## Root cause
The delegation/var-declaration changes introduced compiler-generated suspend lambdas inside `Statement` construction (e.g., `statement { ... }` wrappers). Kotlin/Wasm generates extra coroutine state for those suspend lambdas, which in this case produced invalid wasm IR (mismatched GC reference types). The browser loader then waits forever because the module fails to instantiate.
## Fix
Avoid suspend-lambda `Statement` construction in compiler code paths. Replace `statement { ... }` and other anonymous suspend lambdas with explicit `object : Statement()` implementations and move logic into `override suspend fun execute(...)`. This keeps the resulting wasm IR valid while preserving behavior.
## Where it was fixed
- `lynglib/src/commonMain/kotlin/net/sergeych/lyng/Compiler.kt`
- `lynglib/src/commonMain/kotlin/net/sergeych/lyng/Scope.kt`
## Verification
- `./gradlew :lynglib:wasmJsNodeTest --info`
- `./gradlew :lynglib:wasmJsBrowserTest --info`
Both tests finish quickly after the change.
+30
View File
@@ -93,6 +93,36 @@ let d = Derived()
println((d as B).foo()) // Disambiguation via cast 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()
```
### 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.
## Tooling and Infrastructure ## Tooling and Infrastructure
### CLI: Formatting Command ### CLI: Formatting Command
+1 -1
View File
@@ -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 `<=>`
+1 -1
View File
@@ -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" },
@@ -76,8 +76,8 @@
}, },
"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)\\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)\\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)\\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": "[!?]" } ] },
@@ -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
@@ -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++
@@ -85,7 +127,6 @@ class LyngPreFormatProcessor : PreFormatProcessor {
CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart) CodeStyleManager.getInstance(project).adjustLineIndent(file, lineStart)
} catch (e: Exception) { } catch (e: Exception) {
// Log as debug because this can be called many times during reformat // Log as debug because this can be called many times during reformat
// and we don't want to spam warnings if it's a known platform issue with injections
} }
} }
@@ -110,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()
} }
} }
@@ -131,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
@@ -150,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"
) )
@@ -32,7 +32,8 @@ 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",
"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"
+1 -1
View File
@@ -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-rc" version = "1.1.0-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
@@ -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.
@@ -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") ?: 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)
@@ -236,7 +236,7 @@ class Compiler(
cc.next() cc.next()
pendingDeclStart = t.pos pendingDeclStart = t.pos
pendingDeclDoc = consumePendingDoc() pendingDeclDoc = consumePendingDoc()
val st = parseFunctionDeclaration(isOpen = false, isExtern = false, isStatic = false) val st = parseFunctionDeclaration(isExtern = false, isStatic = false)
statements += st statements += st
continue continue
} }
@@ -286,7 +286,7 @@ class Compiler(
while (true) { while (true) {
val t = cc.next() val t = cc.next()
return when (t.type) { return when (t.type) {
Token.Type.ID -> { Token.Type.ID, Token.Type.OBJECT -> {
parseKeywordStatement(t) parseKeywordStatement(t)
?: run { ?: run {
cc.previous() cc.previous()
@@ -337,7 +337,7 @@ class Compiler(
private suspend fun parseExpression(): Statement? { private suspend fun parseExpression(): Statement? {
val pos = cc.currentPos() val pos = cc.currentPos()
return parseExpressionLevel()?.let { a -> statement(pos) { a.get(it).value } } return parseExpressionLevel()?.let { a -> statement(pos) { a.evalValue(it) } }
} }
private suspend fun parseExpressionLevel(level: Int = 0): ObjRef? { private suspend fun parseExpressionLevel(level: Int = 0): ObjRef? {
@@ -1063,7 +1063,7 @@ class Compiler(
val next = cc.peekNextNonWhitespace() val next = cc.peekNextNonWhitespace()
if (next.type == Token.Type.COMMA || next.type == Token.Type.RPAREN) { if (next.type == Token.Type.COMMA || next.type == Token.Type.RPAREN) {
val localVar = LocalVarRef(name, t1.pos) val localVar = LocalVarRef(name, t1.pos)
return ParsedArgument(statement(t1.pos) { localVar.get(it).value }, t1.pos, isSplat = false, name = name) return ParsedArgument(statement(t1.pos) { localVar.evalValue(it) }, t1.pos, isSplat = false, name = name)
} }
val rhs = parseExpression() ?: t2.raiseSyntax("expected expression after named argument '${name}:'") val rhs = parseExpression() ?: t2.raiseSyntax("expected expression after named argument '${name}:'")
return ParsedArgument(rhs, t1.pos, isSplat = false, name = name) return ParsedArgument(rhs, t1.pos, isSplat = false, name = name)
@@ -1135,7 +1135,7 @@ class Compiler(
val next = cc.peekNextNonWhitespace() val next = cc.peekNextNonWhitespace()
if (next.type == Token.Type.COMMA || next.type == Token.Type.RPAREN) { if (next.type == Token.Type.COMMA || next.type == Token.Type.RPAREN) {
val localVar = LocalVarRef(name, t1.pos) val localVar = LocalVarRef(name, t1.pos)
return ParsedArgument(statement(t1.pos) { localVar.get(it).value }, t1.pos, isSplat = false, name = name) return ParsedArgument(statement(t1.pos) { localVar.evalValue(it) }, t1.pos, isSplat = false, name = name)
} }
val rhs = parseExpression() ?: t2.raiseSyntax("expected expression after named argument '${name}:'") val rhs = parseExpression() ?: t2.raiseSyntax("expected expression after named argument '${name}:'")
return ParsedArgument(rhs, t1.pos, isSplat = false, name = name) return ParsedArgument(rhs, t1.pos, isSplat = false, name = name)
@@ -1298,11 +1298,99 @@ class Compiler(
else else
null null
private suspend fun parseDeclarationWithModifiers(firstId: Token): Statement {
val modifiers = mutableSetOf<String>()
var currentToken = firstId
while (true) {
when (currentToken.value) {
"private", "protected", "static", "abstract", "closed", "override", "extern", "open" -> {
modifiers.add(currentToken.value)
val next = cc.peekNextNonWhitespace()
if (next.type == Token.Type.ID) {
currentToken = cc.next()
} else {
break
}
}
else -> break
}
}
val visibility = when {
modifiers.contains("private") -> Visibility.Private
modifiers.contains("protected") -> Visibility.Protected
else -> Visibility.Public
}
val isStatic = modifiers.contains("static")
val isAbstract = modifiers.contains("abstract")
val isClosed = modifiers.contains("closed")
val isOverride = modifiers.contains("override")
val isExtern = modifiers.contains("extern")
if (isStatic && (isAbstract || isOverride || isClosed))
throw ScriptError(currentToken.pos, "static members cannot be abstract, closed or override")
if (visibility == Visibility.Private && isAbstract)
throw ScriptError(currentToken.pos, "abstract members cannot be private")
pendingDeclStart = firstId.pos
pendingDeclDoc = consumePendingDoc()
val isMember = (codeContexts.lastOrNull() is CodeContext.ClassBody)
if (!isMember && (isOverride || isClosed))
throw ScriptError(currentToken.pos, "modifiers override and closed are only allowed for class members")
if (!isMember && isAbstract && currentToken.value != "class")
throw ScriptError(currentToken.pos, "modifier abstract at top level is only allowed for classes")
return when (currentToken.value) {
"val" -> parseVarDeclaration(false, visibility, isAbstract, isClosed, isOverride, isStatic)
"var" -> parseVarDeclaration(true, visibility, isAbstract, isClosed, isOverride, isStatic)
"fun", "fn" -> parseFunctionDeclaration(visibility, isAbstract, isClosed, isOverride, isExtern, isStatic)
"class" -> {
if (isStatic || isClosed || isOverride || isExtern)
throw ScriptError(currentToken.pos, "unsupported modifiers for class: ${modifiers.joinToString(" ")}")
parseClassDeclaration(isAbstract)
}
"object" -> {
if (isStatic || isClosed || isOverride || isExtern || isAbstract)
throw ScriptError(currentToken.pos, "unsupported modifiers for object: ${modifiers.joinToString(" ")}")
parseObjectDeclaration()
}
"interface" -> {
if (isStatic || isClosed || isOverride || isExtern || isAbstract)
throw ScriptError(
currentToken.pos,
"unsupported modifiers for interface: ${modifiers.joinToString(" ")}"
)
// interface is synonym for abstract class
parseClassDeclaration(isAbstract = true)
}
else -> throw ScriptError(currentToken.pos, "expected declaration after modifiers, found ${currentToken.value}")
}
}
/** /**
* Parse keyword-starting statement. * Parse keyword-starting statement.
* @return parsed statement or null if, for example. [id] is not among keywords * @return parsed statement or null if, for example. [id] is not among keywords
*/ */
private suspend fun parseKeywordStatement(id: Token): Statement? = when (id.value) { private suspend fun parseKeywordStatement(id: Token): Statement? = when (id.value) {
"abstract", "closed", "override", "extern", "private", "protected", "static" -> {
parseDeclarationWithModifiers(id)
}
"interface" -> {
pendingDeclStart = id.pos
pendingDeclDoc = consumePendingDoc()
parseClassDeclaration(isAbstract = true)
}
"val" -> { "val" -> {
pendingDeclStart = id.pos pendingDeclStart = id.pos
pendingDeclDoc = consumePendingDoc() pendingDeclDoc = consumePendingDoc()
@@ -1318,71 +1406,15 @@ class Compiler(
"fun" -> { "fun" -> {
pendingDeclStart = id.pos pendingDeclStart = id.pos
pendingDeclDoc = consumePendingDoc() pendingDeclDoc = consumePendingDoc()
parseFunctionDeclaration(isOpen = false, isExtern = false, isStatic = false) parseFunctionDeclaration(isExtern = false, isStatic = false)
} }
"fn" -> { "fn" -> {
pendingDeclStart = id.pos pendingDeclStart = id.pos
pendingDeclDoc = consumePendingDoc() pendingDeclDoc = consumePendingDoc()
parseFunctionDeclaration(isOpen = false, isExtern = false, isStatic = false) parseFunctionDeclaration(isExtern = false, isStatic = false)
} }
// Visibility modifiers for declarations: private/protected val/var/fun/fn // Visibility modifiers for declarations: private/protected val/var/fun/fn
"private" -> {
var k = cc.requireToken(Token.Type.ID, "declaration expected after 'private'")
var isStatic = false
if (k.value == "static") {
isStatic = true
k = cc.requireToken(Token.Type.ID, "declaration expected after 'private static'")
}
when (k.value) {
"val" -> parseVarDeclaration(false, Visibility.Private, isStatic = isStatic)
"var" -> parseVarDeclaration(true, Visibility.Private, isStatic = isStatic)
"fun" -> parseFunctionDeclaration(
visibility = Visibility.Private,
isOpen = false,
isExtern = false,
isStatic = isStatic
)
"fn" -> parseFunctionDeclaration(
visibility = Visibility.Private,
isOpen = false,
isExtern = false,
isStatic = isStatic
)
else -> k.raiseSyntax("unsupported private declaration kind: ${k.value}")
}
}
"protected" -> {
var k = cc.requireToken(Token.Type.ID, "declaration expected after 'protected'")
var isStatic = false
if (k.value == "static") {
isStatic = true
k = cc.requireToken(Token.Type.ID, "declaration expected after 'protected static'")
}
when (k.value) {
"val" -> parseVarDeclaration(false, Visibility.Protected, isStatic = isStatic)
"var" -> parseVarDeclaration(true, Visibility.Protected, isStatic = isStatic)
"fun" -> parseFunctionDeclaration(
visibility = Visibility.Protected,
isOpen = false,
isExtern = false,
isStatic = isStatic
)
"fn" -> parseFunctionDeclaration(
visibility = Visibility.Protected,
isOpen = false,
isExtern = false,
isStatic = isStatic
)
else -> k.raiseSyntax("unsupported protected declaration kind: ${k.value}")
}
}
"while" -> parseWhileStatement() "while" -> parseWhileStatement()
"do" -> parseDoWhileStatement() "do" -> parseDoWhileStatement()
"for" -> parseForStatement() "for" -> parseForStatement()
@@ -1395,6 +1427,12 @@ class Compiler(
parseClassDeclaration() parseClassDeclaration()
} }
"object" -> {
pendingDeclStart = id.pos
pendingDeclDoc = consumePendingDoc()
parseObjectDeclaration()
}
"init" -> { "init" -> {
if (codeContexts.lastOrNull() is CodeContext.ClassBody && cc.peekNextNonWhitespace().type == Token.Type.LBRACE) { if (codeContexts.lastOrNull() is CodeContext.ClassBody && cc.peekNextNonWhitespace().type == Token.Type.LBRACE) {
val block = parseBlock() val block = parseBlock()
@@ -1444,17 +1482,17 @@ class Compiler(
) )
cc.matchQualifiers("fn", "private") -> parseFunctionDeclaration(Visibility.Private, isExtern) cc.matchQualifiers("fn", "private") -> parseFunctionDeclaration(Visibility.Private, isExtern)
cc.matchQualifiers("fun", "open") -> parseFunctionDeclaration(isOpen = true, isExtern = isExtern) cc.matchQualifiers("fun", "open") -> parseFunctionDeclaration(isExtern = isExtern)
cc.matchQualifiers("fn", "open") -> parseFunctionDeclaration(isOpen = true, isExtern = isExtern) cc.matchQualifiers("fn", "open") -> parseFunctionDeclaration(isExtern = isExtern)
cc.matchQualifiers("fun") -> { cc.matchQualifiers("fun") -> {
pendingDeclStart = id.pos; pendingDeclDoc = pendingDeclStart = id.pos; pendingDeclDoc =
consumePendingDoc(); parseFunctionDeclaration(isOpen = false, isExtern = isExtern) consumePendingDoc(); parseFunctionDeclaration(isExtern = isExtern)
} }
cc.matchQualifiers("fn") -> { cc.matchQualifiers("fn") -> {
pendingDeclStart = id.pos; pendingDeclDoc = pendingDeclStart = id.pos; pendingDeclDoc =
consumePendingDoc(); parseFunctionDeclaration(isOpen = false, isExtern = isExtern) consumePendingDoc(); parseFunctionDeclaration(isExtern = isExtern)
} }
cc.matchQualifiers("val", "private", "static") -> { cc.matchQualifiers("val", "private", "static") -> {
@@ -1773,10 +1811,11 @@ class Compiler(
} }
private fun parseEnumDeclaration(): Statement { private fun parseEnumDeclaration(): Statement {
val startPos = pendingDeclStart ?: cc.currentPos() val nameToken = cc.requireToken(Token.Type.ID)
val startPos = pendingDeclStart ?: nameToken.pos
val doc = pendingDeclDoc ?: consumePendingDoc() val doc = pendingDeclDoc ?: consumePendingDoc()
pendingDeclDoc = null pendingDeclDoc = null
val nameToken = cc.requireToken(Token.Type.ID) pendingDeclStart = null
// so far only simplest enums: // so far only simplest enums:
val names = mutableListOf<String>() val names = mutableListOf<String>()
// skip '{' // skip '{'
@@ -1820,8 +1859,87 @@ class Compiler(
} }
} }
private suspend fun parseClassDeclaration(): Statement { private suspend fun parseObjectDeclaration(): Statement {
val nameToken = cc.requireToken(Token.Type.ID) val nameToken = cc.requireToken(Token.Type.ID)
val startPos = pendingDeclStart ?: nameToken.pos
val doc = pendingDeclDoc ?: consumePendingDoc()
pendingDeclDoc = null
pendingDeclStart = null
// Optional base list: ":" Base ("," Base)* where Base := ID ( "(" args? ")" )?
data class BaseSpec(val name: String, val args: List<ParsedArgument>?)
val baseSpecs = mutableListOf<BaseSpec>()
if (cc.skipTokenOfType(Token.Type.COLON, isOptional = true)) {
do {
val baseId = cc.requireToken(Token.Type.ID, "base class name expected")
var argsList: List<ParsedArgument>? = null
if (cc.skipTokenOfType(Token.Type.LPAREN, isOptional = true)) {
argsList = parseArgsNoTailBlock()
}
baseSpecs += BaseSpec(baseId.value, argsList)
} while (cc.skipTokenOfType(Token.Type.COMMA, isOptional = true))
}
cc.skipTokenOfType(Token.Type.NEWLINE, isOptional = true)
pushInitScope()
// Robust body detection
var classBodyRange: MiniRange? = null
val bodyInit: Statement? = run {
val saved = cc.savePos()
val next = cc.nextNonWhitespace()
if (next.type == Token.Type.LBRACE) {
val bodyStart = next.pos
val st = withLocalNames(emptySet()) {
parseScript()
}
val rbTok = cc.next()
if (rbTok.type != Token.Type.RBRACE) throw ScriptError(rbTok.pos, "unbalanced braces in object body")
classBodyRange = MiniRange(bodyStart, rbTok.pos)
st
} else {
cc.restorePos(saved)
null
}
}
val initScope = popInitScope()
val className = nameToken.value
return statement(startPos) { context ->
val parentClasses = baseSpecs.map { baseSpec ->
val rec = context[baseSpec.name] ?: throw ScriptError(nameToken.pos, "unknown base class: ${baseSpec.name}")
(rec.value as? ObjClass) ?: throw ScriptError(nameToken.pos, "${baseSpec.name} is not a class")
}
val newClass = ObjInstanceClass(className, *parentClasses.toTypedArray())
for (i in parentClasses.indices) {
val argsList = baseSpecs[i].args
// In object, we evaluate parent args once at creation time
if (argsList != null) newClass.directParentArgs[parentClasses[i]] = argsList
}
val classScope = context.createChildScope(newThisObj = newClass)
classScope.currentClassCtx = newClass
newClass.classScope = classScope
bodyInit?.execute(classScope)
// Create instance (singleton)
val instance = newClass.callOn(context.createChildScope(Arguments.EMPTY))
context.addItem(className, false, instance)
instance
}
}
private suspend fun parseClassDeclaration(isAbstract: Boolean = false): Statement {
val nameToken = cc.requireToken(Token.Type.ID)
val startPos = pendingDeclStart ?: nameToken.pos
val doc = pendingDeclDoc ?: consumePendingDoc()
pendingDeclDoc = null
pendingDeclStart = null
return inCodeContext(CodeContext.ClassBody(nameToken.value)) { return inCodeContext(CodeContext.ClassBody(nameToken.value)) {
val constructorArgsDeclaration = val constructorArgsDeclaration =
if (cc.skipTokenOfType(Token.Type.LPAREN, isOptional = true)) if (cc.skipTokenOfType(Token.Type.LPAREN, isOptional = true))
@@ -1879,7 +1997,7 @@ class Compiler(
// Emit MiniClassDecl with collected base names; bodyRange is omitted for now // Emit MiniClassDecl with collected base names; bodyRange is omitted for now
run { run {
val declRange = MiniRange(pendingDeclStart ?: nameToken.pos, cc.currentPos()) val declRange = MiniRange(startPos, cc.currentPos())
val bases = baseSpecs.map { it.name } val bases = baseSpecs.map { it.name }
// Collect constructor fields declared as val/var in primary constructor // Collect constructor fields declared as val/var in primary constructor
val ctorFields = mutableListOf<MiniCtorField>() val ctorFields = mutableListOf<MiniCtorField>()
@@ -1903,11 +2021,10 @@ class Compiler(
bases = bases, bases = bases,
bodyRange = classBodyRange, bodyRange = classBodyRange,
ctorFields = ctorFields, ctorFields = ctorFields,
doc = pendingDeclDoc, doc = doc,
nameStart = nameToken.pos nameStart = nameToken.pos
) )
miniSink?.onClassDecl(node) miniSink?.onClassDecl(node)
pendingDeclDoc = null
} }
val initScope = popInitScope() val initScope = popInitScope()
@@ -1943,6 +2060,7 @@ class Compiler(
} }
val newClass = ObjInstanceClass(className, *parentClasses.toTypedArray()).also { val newClass = ObjInstanceClass(className, *parentClasses.toTypedArray()).also {
it.isAbstract = isAbstract
it.instanceConstructor = constructorCode it.instanceConstructor = constructorCode
it.constructorMeta = constructorArgsDeclaration it.constructorMeta = constructorArgsDeclaration
// Attach per-parent constructor args (thunks) if provided // Attach per-parent constructor args (thunks) if provided
@@ -1950,6 +2068,22 @@ class Compiler(
val argsList = baseSpecs[i].args val argsList = baseSpecs[i].args
if (argsList != null) it.directParentArgs[parentClasses[i]] = argsList if (argsList != null) it.directParentArgs[parentClasses[i]] = argsList
} }
// Register constructor fields in the class members
constructorArgsDeclaration?.params?.forEach { p ->
if (p.accessType != null) {
it.createField(
p.name, ObjNull,
isMutable = p.accessType == AccessType.Var,
visibility = p.visibility ?: Visibility.Public,
declaringClass = it,
// Constructor fields are not currently supporting override/closed in parser
// but we should pass Pos.builtIn to skip validation for now if needed,
// or p.pos to allow it.
pos = Pos.builtIn,
type = ObjRecord.Type.ConstructorField
)
}
}
} }
addItem(className, false, newClass) addItem(className, false, newClass)
@@ -1970,7 +2104,7 @@ class Compiler(
val v = rec.value val v = rec.value
if (v is Statement) { if (v is Statement) {
if (newClass.members[k] == null) { if (newClass.members[k] == null) {
newClass.addFn(k, isOpen = true) { newClass.addFn(k, isMutable = true, pos = rec.importedFrom?.pos ?: nameToken.pos) {
(thisObj as? ObjInstance)?.let { i -> (thisObj as? ObjInstance)?.let { i ->
v.execute(ClosureScope(this, i.instanceScope)) v.execute(ClosureScope(this, i.instanceScope))
} ?: v.execute(thisObj.autoInstanceScope(this)) } ?: v.execute(thisObj.autoInstanceScope(this))
@@ -1978,6 +2112,7 @@ class Compiler(
} }
} }
} }
newClass.checkAbstractSatisfaction(nameToken.pos)
// Debug summary: list registered instance methods and class-scope functions for this class // Debug summary: list registered instance methods and class-scope functions for this class
newClass newClass
} }
@@ -2391,7 +2526,9 @@ class Compiler(
private suspend fun parseFunctionDeclaration( private suspend fun parseFunctionDeclaration(
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
@Suppress("UNUSED_PARAMETER") isOpen: Boolean = false, isAbstract: Boolean = false,
isClosed: Boolean = false,
isOverride: Boolean = false,
isExtern: Boolean = false, isExtern: Boolean = false,
isStatic: Boolean = false, isStatic: Boolean = false,
): Statement { ): Statement {
@@ -2407,9 +2544,9 @@ class Compiler(
val annotation = lastAnnotation val annotation = lastAnnotation
val parentContext = codeContexts.last() val parentContext = codeContexts.last()
t = cc.next()
// Is extension? // Is extension?
if (t.type == Token.Type.DOT) { if (cc.peekNextNonWhitespace().type == Token.Type.DOT) {
cc.nextNonWhitespace() // consume DOT
extTypeName = name extTypeName = name
val receiverEnd = Pos(start.source, start.line, start.column + name.length) val receiverEnd = Pos(start.source, start.line, start.column + name.length)
receiverMini = MiniTypeName( receiverMini = MiniTypeName(
@@ -2422,24 +2559,33 @@ class Compiler(
throw ScriptError(t.pos, "illegal extension format: expected function name") throw ScriptError(t.pos, "illegal extension format: expected function name")
name = t.value name = t.value
nameStartPos = t.pos nameStartPos = t.pos
t = cc.next()
} }
if (t.type != Token.Type.LPAREN) val argsDeclaration: ArgsDeclaration =
throw ScriptError(t.pos, "Bad function definition: expected '(' after 'fn ${name}'") if (cc.peekNextNonWhitespace().type == Token.Type.LPAREN) {
cc.nextNonWhitespace() // consume (
parseArgsDeclaration() ?: ArgsDeclaration(emptyList(), Token.Type.RPAREN)
} else ArgsDeclaration(emptyList(), Token.Type.RPAREN)
val argsDeclaration = parseArgsDeclaration() // Optional return type
if (argsDeclaration == null || argsDeclaration.endTokenType != Token.Type.RPAREN) val returnTypeMini: MiniTypeRef? = if (cc.peekNextNonWhitespace().type == Token.Type.COLON) {
parseTypeDeclarationWithMini().second
} else null
var isDelegated = false
var delegateExpression: Statement? = null
if (cc.peekNextNonWhitespace().type == Token.Type.BY) {
cc.nextNonWhitespace() // consume by
isDelegated = true
delegateExpression = parseExpression() ?: throw ScriptError(cc.current().pos, "Expected delegate expression")
}
if (!isDelegated && argsDeclaration.endTokenType != Token.Type.RPAREN)
throw ScriptError( throw ScriptError(
t.pos, t.pos,
"Bad function definition: expected valid argument declaration or () after 'fn ${name}'" "Bad function definition: expected valid argument declaration or () after 'fn ${name}'"
) )
// Optional return type
val returnTypeMini: MiniTypeRef? = if (cc.current().type == Token.Type.COLON) {
parseTypeDeclarationWithMini().second
} else null
// Capture doc locally to reuse even if we need to emit later // Capture doc locally to reuse even if we need to emit later
val declDocLocal = pendingDeclDoc val declDocLocal = pendingDeclDoc
@@ -2476,12 +2622,13 @@ class Compiler(
localDeclCountStack.add(0) localDeclCountStack.add(0)
val fnStatements = if (isExtern) val fnStatements = if (isExtern)
statement { raiseError("extern function not provided: $name") } statement { raiseError("extern function not provided: $name") }
else else if (isAbstract || isDelegated) {
null
} else
withLocalNames(paramNames) { withLocalNames(paramNames) {
val next = cc.peekNextNonWhitespace() val next = cc.peekNextNonWhitespace()
if (next.type == Token.Type.ASSIGN) { if (next.type == Token.Type.ASSIGN) {
cc.skipWsTokens() cc.nextNonWhitespace() // consume '='
cc.next() // consume '='
val expr = parseExpression() ?: throw ScriptError(cc.current().pos, "Expected function body expression") val expr = parseExpression() ?: throw ScriptError(cc.current().pos, "Expected function body expression")
// Shorthand function returns the expression value // Shorthand function returns the expression value
statement(expr.pos) { scope -> statement(expr.pos) { scope ->
@@ -2514,10 +2661,61 @@ class Compiler(
if (extTypeName != null) { if (extTypeName != null) {
context.thisObj = callerContext.thisObj context.thisObj = callerContext.thisObj
} }
fnStatements.execute(context) fnStatements?.execute(context) ?: ObjVoid
} }
// parentContext // parentContext
val fnCreateStatement = statement(start) { context -> val fnCreateStatement = statement(start) { context ->
if (isDelegated) {
val accessType = context.resolveQualifiedIdentifier("DelegateAccess.Callable")
val initValue = delegateExpression!!.execute(context)
val finalDelegate = try {
initValue.invokeInstanceMethod(context, "bind", Arguments(ObjString(name), accessType, context.thisObj))
} catch (e: Exception) {
initValue
}
if (extTypeName != null) {
val type = context[extTypeName!!]?.value ?: context.raiseSymbolNotFound("class $extTypeName not found")
if (type !is ObjClass) context.raiseClassCastError("$extTypeName is not the class instance")
context.addExtension(type, name, ObjRecord(ObjUnset, isMutable = false, visibility = visibility, declaringClass = null, type = ObjRecord.Type.Delegated).apply {
delegate = finalDelegate
})
return@statement ObjVoid
}
val th = context.thisObj
if (isStatic) {
(th as ObjClass).createClassField(name, ObjUnset, false, visibility, null, start, type = ObjRecord.Type.Delegated).apply {
delegate = finalDelegate
}
context.addItem(name, false, ObjUnset, visibility, recordType = ObjRecord.Type.Delegated).apply {
delegate = finalDelegate
}
} else if (th is ObjClass) {
val cls: ObjClass = th
val storageName = "${cls.className}::$name"
cls.createField(name, ObjUnset, false, visibility, null, start, declaringClass = cls, isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride, type = ObjRecord.Type.Delegated)
cls.instanceInitializers += statement(start) { scp ->
val accessType2 = scp.resolveQualifiedIdentifier("DelegateAccess.Callable")
val initValue2 = delegateExpression!!.execute(scp)
val finalDelegate2 = try {
initValue2.invokeInstanceMethod(scp, "bind", Arguments(ObjString(name), accessType2, scp.thisObj))
} catch (e: Exception) {
initValue2
}
scp.addItem(storageName, false, ObjUnset, visibility, null, recordType = ObjRecord.Type.Delegated, isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride).apply {
delegate = finalDelegate2
}
ObjVoid
}
} else {
context.addItem(name, false, ObjUnset, visibility, recordType = ObjRecord.Type.Delegated).apply {
delegate = finalDelegate
}
}
return@statement ObjVoid
}
// we added fn in the context. now we must save closure // we added fn in the context. now we must save closure
// for the function, unless we're in the class scope: // for the function, unless we're in the class scope:
if (isStatic || parentContext !is CodeContext.ClassBody) if (isStatic || parentContext !is CodeContext.ClassBody)
@@ -2546,7 +2744,15 @@ class Compiler(
if (!isStatic && th is ObjClass) { if (!isStatic && th is ObjClass) {
// Instance method declared inside a class body: register on the class // Instance method declared inside a class body: register on the class
val cls: ObjClass = th val cls: ObjClass = th
cls.addFn(name, isOpen = true, visibility = visibility) { cls.addFn(
name,
isMutable = true,
visibility = visibility,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride,
pos = start
) {
// Execute with the instance as receiver; set caller lexical class for visibility // Execute with the instance as receiver; set caller lexical class for visibility
val savedCtx = this.currentClassCtx val savedCtx = this.currentClassCtx
this.currentClassCtx = cls this.currentClassCtx = cls
@@ -2624,7 +2830,9 @@ class Compiler(
private suspend fun parseVarDeclaration( private suspend fun parseVarDeclaration(
isMutable: Boolean, isMutable: Boolean,
visibility: Visibility, visibility: Visibility,
@Suppress("UNUSED_PARAMETER") isOpen: Boolean = false, isAbstract: Boolean = false,
isClosed: Boolean = false,
isOverride: Boolean = false,
isStatic: Boolean = false isStatic: Boolean = false
): Statement { ): Statement {
val nextToken = cc.next() val nextToken = cc.next()
@@ -2737,7 +2945,15 @@ class Compiler(
// Register the local name at compile time so that subsequent identifiers can be emitted as fast locals // Register the local name at compile time so that subsequent identifiers can be emitted as fast locals
if (!isStatic) declareLocalName(name) if (!isStatic) declareLocalName(name)
val isDelegate = if (!isProperty && eqToken.isId("by")) { val isDelegate = if (isAbstract) {
if (!isProperty && (eqToken.type == Token.Type.ASSIGN || eqToken.type == Token.Type.BY))
throw ScriptError(eqToken.pos, "abstract variable $name cannot have an initializer or delegate")
// Abstract variables don't have initializers
cc.restorePos(markBeforeEq)
cc.skipWsTokens()
setNull = true
false
} else if (!isProperty && eqToken.type == Token.Type.BY) {
true true
} else { } else {
if (!isProperty && eqToken.type != Token.Type.ASSIGN) { if (!isProperty && eqToken.type != Token.Type.ASSIGN) {
@@ -2785,11 +3001,35 @@ class Compiler(
// when creating instance, but we need to execute it in the class initializer which // when creating instance, but we need to execute it in the class initializer which
// is missing as for now. Add it to the compiler context? // is missing as for now. Add it to the compiler context?
// if (isDelegate) throw ScriptError(start, "static delegates are not yet implemented")
currentInitScope += statement { currentInitScope += statement {
val initValue = initialExpression?.execute(this)?.byValueCopy() ?: ObjNull val initValue = initialExpression?.execute(this)?.byValueCopy() ?: ObjNull
(thisObj as ObjClass).createClassField(name, initValue, isMutable, visibility, null, pos) if (isDelegate) {
addItem(name, isMutable, initValue, visibility, null, ObjRecord.Type.Field) val accessTypeStr = if (isMutable) "Var" else "Val"
val accessType = resolveQualifiedIdentifier("DelegateAccess.$accessTypeStr")
val finalDelegate = try {
initValue.invokeInstanceMethod(this, "bind", Arguments(ObjString(name), accessType, thisObj))
} catch (e: Exception) {
initValue
}
(thisObj as ObjClass).createClassField(
name,
ObjUnset,
isMutable,
visibility,
null,
start,
type = ObjRecord.Type.Delegated
).apply {
delegate = finalDelegate
}
// Also expose in current init scope
addItem(name, isMutable, ObjUnset, visibility, null, ObjRecord.Type.Delegated).apply {
delegate = finalDelegate
}
} else {
(thisObj as ObjClass).createClassField(name, initValue, isMutable, visibility, null, start)
addItem(name, isMutable, initValue, visibility, null, ObjRecord.Type.Field)
}
ObjVoid ObjVoid
} }
return NopStatement return NopStatement
@@ -2813,7 +3053,7 @@ class Compiler(
cc.skipWsTokens() cc.skipWsTokens()
cc.next() // consume '=' cc.next() // consume '='
val expr = parseExpression() ?: throw ScriptError(cc.current().pos, "Expected getter expression") val expr = parseExpression() ?: throw ScriptError(cc.current().pos, "Expected getter expression")
(expr as? Statement) ?: statement(expr.pos) { s -> expr.execute(s) } expr
} else { } else {
throw ScriptError(cc.current().pos, "Expected { or = after get()") throw ScriptError(cc.current().pos, "Expected { or = after get()")
} }
@@ -2834,7 +3074,7 @@ class Compiler(
cc.skipWsTokens() cc.skipWsTokens()
cc.next() // consume '=' cc.next() // consume '='
val expr = parseExpression() ?: throw ScriptError(cc.current().pos, "Expected setter expression") val expr = parseExpression() ?: throw ScriptError(cc.current().pos, "Expected setter expression")
val st = (expr as? Statement) ?: statement(expr.pos) { s -> expr.execute(s) } val st = expr
statement(st.pos) { scope -> statement(st.pos) { scope ->
val value = scope.args.list.firstOrNull() ?: ObjNull val value = scope.args.list.firstOrNull() ?: ObjNull
scope.addItem(setArg.value, true, value, recordType = ObjRecord.Type.Argument) scope.addItem(setArg.value, true, value, recordType = ObjRecord.Type.Argument)
@@ -2869,7 +3109,7 @@ class Compiler(
cc.current().pos, cc.current().pos,
"Expected setter expression" "Expected setter expression"
) )
val st = (expr as? Statement) ?: statement(expr.pos) { s -> expr.execute(s) } val st = expr
statement(st.pos) { scope -> statement(st.pos) { scope ->
val value = scope.args.list.firstOrNull() ?: ObjNull val value = scope.args.list.firstOrNull() ?: ObjNull
scope.addItem(setArg.value, true, value, recordType = ObjRecord.Type.Argument) scope.addItem(setArg.value, true, value, recordType = ObjRecord.Type.Argument)
@@ -2901,14 +3141,23 @@ class Compiler(
} }
} }
return statement(start) { context -> return object : Statement() {
override val pos: Pos = start
override suspend fun execute(context: Scope): Obj {
if (extTypeName != null) { if (extTypeName != null) {
val prop = if (getter != null || setter != null) { val prop = if (getter != null || setter != null) {
ObjProperty(name, getter, setter) ObjProperty(name, getter, setter)
} else { } else {
// Simple val extension with initializer // Simple val extension with initializer
val initExpr = initialExpression ?: throw ScriptError(start, "Extension val must be initialized") val initExpr = initialExpression ?: throw ScriptError(start, "Extension val must be initialized")
ObjProperty(name, statement(initExpr.pos) { scp -> initExpr.execute(scp) }, null) ObjProperty(
name,
object : Statement() {
override val pos: Pos = initExpr.pos
override suspend fun execute(scp: Scope): Obj = initExpr.execute(scp)
},
null
)
} }
val type = context[extTypeName]?.value ?: context.raiseSymbolNotFound("class $extTypeName not found") val type = context[extTypeName]?.value ?: context.raiseSymbolNotFound("class $extTypeName not found")
@@ -2916,7 +3165,7 @@ class Compiler(
context.addExtension(type, name, ObjRecord(prop, isMutable = false, visibility = visibility, writeVisibility = setterVisibility, declaringClass = null, type = ObjRecord.Type.Property)) context.addExtension(type, name, ObjRecord(prop, isMutable = false, visibility = visibility, writeVisibility = setterVisibility, declaringClass = null, type = ObjRecord.Type.Property))
return@statement prop return prop
} }
// In true class bodies (not inside a function), store fields under a class-qualified key to support MI collisions // In true class bodies (not inside a function), store fields under a class-qualified key to support MI collisions
// Do NOT infer declaring class from runtime thisObj here; only the compile-time captured // Do NOT infer declaring class from runtime thisObj here; only the compile-time captured
@@ -2931,7 +3180,90 @@ class Compiler(
if (!isStatic) declareLocalName(name) if (!isStatic) declareLocalName(name)
if (isDelegate) { if (isDelegate) {
TODO() val declaringClassName = declaringClassNameCaptured
if (declaringClassName != null) {
val storageName = "$declaringClassName::$name"
val isClassScope = context.thisObj is ObjClass && (context.thisObj !is ObjInstance)
if (isClassScope) {
val cls = context.thisObj as ObjClass
cls.createField(
name,
ObjUnset,
isMutable,
visibility,
setterVisibility,
start,
type = ObjRecord.Type.Delegated,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
)
cls.instanceInitializers += object : Statement() {
override val pos: Pos = start
override suspend fun execute(scp: Scope): Obj {
val initValue = initialExpression!!.execute(scp)
val accessTypeStr = if (isMutable) "Var" else "Val"
val accessType = scp.resolveQualifiedIdentifier("DelegateAccess.$accessTypeStr")
val finalDelegate = try {
initValue.invokeInstanceMethod(
scp,
"bind",
Arguments(ObjString(name), accessType, scp.thisObj)
)
} catch (e: Exception) {
initValue
}
scp.addItem(
storageName, isMutable, ObjUnset, visibility, setterVisibility,
recordType = ObjRecord.Type.Delegated,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
).apply {
delegate = finalDelegate
}
return ObjVoid
}
}
return ObjVoid
} else {
val initValue = initialExpression!!.execute(context)
val accessTypeStr = if (isMutable) "Var" else "Val"
val accessType = context.resolveQualifiedIdentifier("DelegateAccess.$accessTypeStr")
val finalDelegate = try {
initValue.invokeInstanceMethod(context, "bind", Arguments(ObjString(name), accessType, context.thisObj))
} catch (e: Exception) {
initValue
}
val rec = context.addItem(
storageName, isMutable, ObjUnset, visibility, setterVisibility,
recordType = ObjRecord.Type.Delegated,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
)
rec.delegate = finalDelegate
return finalDelegate
}
} else {
val initValue = initialExpression!!.execute(context)
val accessTypeStr = if (isMutable) "Var" else "Val"
val accessType = context.resolveQualifiedIdentifier("DelegateAccess.$accessTypeStr")
val finalDelegate = try {
initValue.invokeInstanceMethod(context, "bind", Arguments(ObjString(name), accessType, ObjNull))
} catch (e: Exception) {
initValue
}
val rec = context.addItem(
name, isMutable, ObjUnset, visibility, setterVisibility,
recordType = ObjRecord.Type.Delegated,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
)
rec.delegate = finalDelegate
return finalDelegate
}
} else if (getter != null || setter != null) { } else if (getter != null || setter != null) {
val declaringClassName = declaringClassNameCaptured!! val declaringClassName = declaringClassNameCaptured!!
val storageName = "$declaringClassName::$name" val storageName = "$declaringClassName::$name"
@@ -2939,62 +3271,135 @@ class Compiler(
// If we are in class scope now (defining instance field), defer initialization to instance time // If we are in class scope now (defining instance field), defer initialization to instance time
val isClassScope = context.thisObj is ObjClass && (context.thisObj !is ObjInstance) val isClassScope = context.thisObj is ObjClass && (context.thisObj !is ObjInstance)
if (isClassScope) { return if (isClassScope) {
val cls = context.thisObj as ObjClass val cls = context.thisObj as ObjClass
// Register the property // Register in class members for reflection/MRO/satisfaction checks
cls.instanceInitializers += statement(start) { scp -> if (isProperty) {
scp.addItem( cls.addProperty(
storageName, name,
isMutable, visibility = visibility,
prop, writeVisibility = setterVisibility,
visibility, isAbstract = isAbstract,
setterVisibility, isClosed = isClosed,
recordType = ObjRecord.Type.Property isOverride = isOverride,
pos = start
) )
ObjVoid } else {
cls.createField(
name,
ObjNull,
isMutable = isMutable,
visibility = visibility,
writeVisibility = setterVisibility,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride,
type = ObjRecord.Type.Field
)
}
// Register the property/field initialization thunk
if (!isAbstract) {
cls.instanceInitializers += object : Statement() {
override val pos: Pos = start
override suspend fun execute(scp: Scope): Obj {
scp.addItem(
storageName,
isMutable,
prop,
visibility,
setterVisibility,
recordType = ObjRecord.Type.Property,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
)
return ObjVoid
}
}
} }
ObjVoid ObjVoid
} else { } else {
// We are in instance scope already: perform initialization immediately // We are in instance scope already: perform initialization immediately
context.addItem(storageName, isMutable, prop, visibility, setterVisibility, recordType = ObjRecord.Type.Property) context.addItem(
storageName, isMutable, prop, visibility, setterVisibility,
recordType = ObjRecord.Type.Property,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
)
prop prop
} }
} else { } else {
val isLateInitVal = !isMutable && initialExpression == null && getter == null && setter == null val isLateInitVal = !isMutable && initialExpression == null && getter == null && setter == null
if (declaringClassName != null && !isStatic) { return if (declaringClassName != null && !isStatic) {
val storageName = "$declaringClassName::$name" val storageName = "$declaringClassName::$name"
// If we are in class scope now (defining instance field), defer initialization to instance time // If we are in class scope now (defining instance field), defer initialization to instance time
val isClassScope = context.thisObj is ObjClass && (context.thisObj !is ObjInstance) val isClassScope = context.thisObj is ObjClass && (context.thisObj !is ObjInstance)
if (isClassScope) { if (isClassScope) {
val cls = context.thisObj as ObjClass val cls = context.thisObj as ObjClass
// Defer: at instance construction, evaluate initializer in instance scope and store under mangled name // Register in class members for reflection/MRO/satisfaction checks
val initStmt = statement(start) { scp -> cls.createField(
val initValue = name,
initialExpression?.execute(scp)?.byValueCopy() ?: if (isLateInitVal) ObjUnset else ObjNull ObjNull,
// Preserve mutability of declaration: do NOT use addOrUpdateItem here, as it creates mutable records isMutable = isMutable,
scp.addItem(storageName, isMutable, initValue, visibility, setterVisibility, recordType = ObjRecord.Type.Field) visibility = visibility,
ObjVoid writeVisibility = setterVisibility,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride,
pos = start,
type = ObjRecord.Type.Field
)
// Defer: at instance construction, evaluate initializer in instance scope and store under mangled name
if (!isAbstract) {
val initStmt = object : Statement() {
override val pos: Pos = start
override suspend fun execute(scp: Scope): Obj {
val initValue =
initialExpression?.execute(scp)?.byValueCopy()
?: if (isLateInitVal) ObjUnset else ObjNull
// Preserve mutability of declaration: do NOT use addOrUpdateItem here, as it creates mutable records
scp.addItem(
storageName, isMutable, initValue, visibility, setterVisibility,
recordType = ObjRecord.Type.Field,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
)
return ObjVoid
}
} }
cls.instanceInitializers += initStmt cls.instanceInitializers += initStmt
ObjVoid
} else {
// We are in instance scope already: perform initialization immediately
val initValue =
initialExpression?.execute(context)?.byValueCopy() ?: if (isLateInitVal) ObjUnset else ObjNull
// Preserve mutability of declaration: create record with correct mutability
context.addItem(storageName, isMutable, initValue, visibility, setterVisibility, recordType = ObjRecord.Type.Field)
initValue
} }
ObjVoid
} else { } else {
// Not in class body: regular local/var declaration // We are in instance scope already: perform initialization immediately
val initValue = initialExpression?.execute(context)?.byValueCopy() ?: ObjNull val initValue =
context.addItem(name, isMutable, initValue, visibility, recordType = ObjRecord.Type.Field) initialExpression?.execute(context)?.byValueCopy() ?: if (isLateInitVal) ObjUnset else ObjNull
// Preserve mutability of declaration: create record with correct mutability
context.addItem(
storageName, isMutable, initValue, visibility, setterVisibility,
recordType = ObjRecord.Type.Field,
isAbstract = isAbstract,
isClosed = isClosed,
isOverride = isOverride
)
initValue initValue
} }
} else {
// Not in class body: regular local/var declaration
val initValue = initialExpression?.execute(context)?.byValueCopy() ?: ObjNull
context.addItem(name, isMutable, initValue, visibility, recordType = ObjRecord.Type.Field)
initValue
}
} }
} }
} }
}
data class Operator( data class Operator(
val tokenType: Token.Type, val tokenType: Token.Type,
val priority: Int, val arity: Int = 2, val priority: Int, val arity: Int = 2,
@@ -3301,4 +3706,3 @@ class Compiler(
} }
suspend fun eval(code: String) = compile(code).execute() suspend fun eval(code: String) = compile(code).execute()
@@ -356,6 +356,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) }
@@ -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
} }
@@ -332,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
} }
) )
} }
@@ -435,7 +445,10 @@ open class Scope(
value: Obj, value: Obj,
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
writeVisibility: Visibility? = null, writeVisibility: Visibility? = null,
recordType: ObjRecord.Type = ObjRecord.Type.Other 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 )
@@ -449,7 +462,7 @@ open class Scope(
callScope.localBindings[name] = it callScope.localBindings[name] = it
} }
it it
} ?: addItem(name, true, value, visibility, writeVisibility, recordType) } ?: addItem(name, true, value, visibility, writeVisibility, recordType, isAbstract = isAbstract, isClosed = isClosed, isOverride = isOverride)
fun addItem( fun addItem(
name: String, name: String,
@@ -458,9 +471,19 @@ open class Scope(
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
writeVisibility: Visibility? = null, 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, writeVisibility, 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
@@ -598,6 +621,36 @@ 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 ?: raiseError("Internal error: delegated property $name has no delegate")
val th = if (thisObj === ObjVoid) ObjNull else thisObj
if (del.objClass.getInstanceMemberOrNull("getValue") == null) {
return 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))
}
}
}
return del.invokeInstanceMethod(this, "getValue", Arguments(th, ObjString(name)))
}
return rec.value
}
suspend fun assign(rec: ObjRecord, name: String, newValue: Obj) {
if (rec.type == ObjRecord.Type.Delegated) {
val del = rec.delegate ?: 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.*
@@ -204,18 +205,32 @@ 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) {
1 -> { 1 -> {
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 {
@@ -226,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}")
} }
@@ -255,7 +275,7 @@ class Script(
val condition = requiredArg<ObjBool>(0) val condition = requiredArg<ObjBool>(0)
if (!condition.value) { if (!condition.value) {
var message = args.list.getOrNull(1) var message = args.list.getOrNull(1)
if( message is Statement ) message = message.execute(this) if (message is Statement) message = message.execute(this)
raiseIllegalArgument(message?.toString() ?: "requirement not met") raiseIllegalArgument(message?.toString() ?: "requirement not met")
} }
ObjVoid ObjVoid
@@ -264,7 +284,7 @@ class Script(
val condition = requiredArg<ObjBool>(0) val condition = requiredArg<ObjBool>(0)
if (!condition.value) { if (!condition.value) {
var message = args.list.getOrNull(1) var message = args.list.getOrNull(1)
if( message is Statement ) message = message.execute(this) if (message is Statement) message = message.execute(this)
raiseIllegalState(message?.toString() ?: "check failed") raiseIllegalState(message?.toString() ?: "check failed")
} }
ObjVoid ObjVoid
@@ -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.
@@ -36,7 +36,7 @@ data class Token(val value: String, val pos: Pos, val type: Type) {
PLUS, MINUS, STAR, SLASH, PERCENT, PLUS, MINUS, STAR, SLASH, PERCENT,
ASSIGN, PLUSASSIGN, MINUSASSIGN, STARASSIGN, SLASHASSIGN, PERCENTASSIGN, ASSIGN, PLUSASSIGN, MINUSASSIGN, STARASSIGN, SLASHASSIGN, PERCENTASSIGN,
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 }
@@ -288,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.
@@ -41,7 +41,8 @@ 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",
"abstract", "closed", "override",
"private", "protected", "static", "open", "extern", "init", "get", "set", "by", "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",
@@ -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
@@ -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))
@@ -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
@@ -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
}
} }
} }
} }
@@ -347,8 +335,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
@@ -372,7 +364,14 @@ open class Obj {
) )
} }
protected suspend fun resolveRecord(scope: Scope, obj: ObjRecord, name: String, decl: ObjClass?): ObjRecord { protected 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)
@@ -383,7 +382,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
} }
@@ -393,8 +392,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) {
@@ -417,8 +419,11 @@ open class Obj {
val decl = field.declaringClass val decl = field.declaringClass
val caller = scope.currentClassCtx val caller = scope.currentClassCtx
if (!canAccessMember(field.effectiveWriteVisibility, 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")
} }
@@ -437,13 +442,17 @@ 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 -> return scope.withChildFrame(args, newThisObj = thisObj) { child ->
if (declaringClass != null) child.currentClassCtx = declaringClass
callOn(child) callOn(child)
} }
else }
callOn(scope.createChildScope(scope.pos, args = args, newThisObj = thisObj)) val child = scope.createChildScope(scope.pos, args = args, newThisObj = thisObj)
if (declaringClass != null) child.currentClassCtx = declaringClass
return callOn(child)
}
suspend fun invoke(scope: Scope, thisObj: Obj, vararg args: Obj): Obj = suspend fun invoke(scope: Scope, thisObj: Obj, vararg args: Obj): Obj =
callOn( callOn(
@@ -91,6 +91,8 @@ open class ObjClass(
vararg parents: ObjClass, vararg parents: ObjClass,
) : Obj() { ) : Obj() {
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 +180,13 @@ 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 {
// During very early bootstrap rootObjectType might not be initialized yet.
// We use a safe check here.
@Suppress("UNNECESSARY_SAFE_CALL")
val root = net.sergeych.lyng.obj.Obj.rootObjectType
if (root != null) base + root else base
}
} }
/** 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,13 +234,13 @@ 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] = 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] = rec
@@ -347,16 +356,58 @@ open class ObjClass(
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
writeVisibility: Visibility? = null, 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, writeVisibility, 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 {
@@ -370,27 +421,37 @@ open class ObjClass(
isMutable: Boolean = false, isMutable: Boolean = false,
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
writeVisibility: Visibility? = null, writeVisibility: Visibility? = null,
pos: Pos = Pos.builtIn 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, writeVisibility) 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, 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, writeVisibility, 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)
@@ -401,13 +462,20 @@ open class ObjClass(
setter: (suspend Scope.(Obj) -> Unit)? = null, setter: (suspend Scope.(Obj) -> Unit)? = null,
visibility: Visibility = Visibility.Public, visibility: Visibility = Visibility.Public,
writeVisibility: Visibility? = null, writeVisibility: Visibility? = null,
declaringClass: ObjClass? = this 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, writeVisibility, 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)
@@ -442,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.
@@ -462,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)
} }
@@ -479,8 +585,16 @@ 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 function $name has no delegate")
val allArgs = (listOf(this, ObjString(name)) + args.list).toTypedArray()
return del.invokeInstanceMethod(scope, "invoke", Arguments(*allArgs))
}
return rec.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,11 +191,12 @@ open class ObjException(
"IllegalAssignmentException", "IllegalAssignmentException",
"SymbolNotDefinedException", "SymbolNotDefinedException",
"IterationEndException", "IterationEndException",
"AccessException", "IllegalAccessException",
"UnknownException", "UnknownException",
"NotFoundException", "NotFoundException",
"IllegalOperationException", "IllegalOperationException",
"UnsetException", "UnsetException",
"NotImplementedException",
"SyntaxError" "SyntaxError"
)) { )) {
scope.addConst(name, getOrCreateExceptionClass(name)) scope.addConst(name, getOrCreateExceptionClass(name))
@@ -236,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)
@@ -250,3 +251,6 @@ class ObjNotFoundException(scope: Scope, message: String = "not found") :
class ObjUnsetException(scope: Scope, message: String = "property is unset (not initialized)") : class ObjUnsetException(scope: Scope, message: String = "property is unset (not initialized)") :
ObjException("UnsetException", scope, message) ObjException("UnsetException", scope, message)
class ObjNotImplementedException(scope: Scope, message: String = "not implemented") :
ObjException("NotImplementedException", scope, message)
@@ -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,22 +68,38 @@ 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
} }
// Fall back to methods/properties on class
// 3. Fall back to super (handles class members and extensions)
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)")
return obj.copy(
value = del.invokeInstanceMethod(scope, "getValue", Arguments(this, ObjString(name))),
type = ObjRecord.Type.Other
)
}
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 ->
@@ -98,7 +107,7 @@ 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(f.effectiveWriteVisibility, decl, caller)) if (!canAccessMember(f.effectiveWriteVisibility, decl, caller))
ObjAccessException( 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,6 +117,19 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
prop.callSetter(scope, this, newValue, decl) prop.callSetter(scope, this, newValue, decl)
return return
} }
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.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
@@ -132,7 +154,7 @@ 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.effectiveWriteVisibility, declaring, caller)) if (!canAccessMember(rec.effectiveWriteVisibility, declaring, caller))
ObjAccessException( 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,6 +164,19 @@ class ObjInstance(override val objClass: ObjClass) : Obj() {
prop.callSetter(scope, this, newValue, declaring) prop.callSetter(scope, this, newValue, declaring)
return return
} }
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.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
@@ -153,39 +188,42 @@ 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) {
val caller = scope.currentClassCtx ?: if (scope.thisObj === this) objClass else null if (cls.className == "Obj") break
if (!canAccessMember(rec.visibility, decl, caller)) val rec = cls.members[name] ?: cls.classScope?.objects?.get(name)
scope.raiseError( if (rec != null) {
ObjAccessException( if (rec.type == ObjRecord.Type.Delegated) {
scope, val storageName = "${cls.className}::$name"
"can't invoke method $name (declared in ${decl?.className ?: "?"})" val del = instanceScope[storageName]?.delegate ?: rec.delegate
) ?: scope.raiseError("Internal error: delegated function $name has no delegate (tried $storageName)")
) val allArgs = (listOf(this, ObjString(name)) + args.list).toTypedArray()
rec.value.invoke( return del.invokeInstanceMethod(scope, "invoke", Arguments(*allArgs))
instanceScope, }
this, if (rec.type != ObjRecord.Type.Property && !rec.isAbstract) {
args val decl = rec.declaringClass ?: cls
)
}
?: run {
// fallback: class-scope function (registered during class body execution)
objClass.classScope?.objects?.get(name)?.let { rec ->
val decl = rec.declaringClass
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(instanceScope, this, args) return rec.value.invoke(
instanceScope,
this,
args,
decl
)
} }
} }
?: 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 {
@@ -306,8 +344,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 +354,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 +367,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) {
@@ -351,7 +379,7 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
val decl = f.declaringClass ?: startClass val decl = f.declaringClass ?: startClass
val caller = scope.currentClassCtx val caller = scope.currentClassCtx
if (!canAccessMember(f.effectiveWriteVisibility, decl, caller)) if (!canAccessMember(f.effectiveWriteVisibility, decl, caller))
ObjAccessException( 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()
@@ -365,7 +393,7 @@ class ObjQualifiedView(val instance: ObjInstance, private val startClass: ObjCla
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.effectiveWriteVisibility, decl, caller)) if (!canAccessMember(f.effectiveWriteVisibility, decl, caller))
ObjAccessException( 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()
@@ -378,7 +406,7 @@ 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.effectiveWriteVisibility, decl, caller)) if (!canAccessMember(r.effectiveWriteVisibility, decl, caller))
ObjAccessException(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 +422,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 +438,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 ?: "?"})"
) )
@@ -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,6 +32,10 @@ data class ObjRecord(
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 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) {
@@ -45,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) {
@@ -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) {
@@ -339,8 +342,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 +376,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 +390,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 +399,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 +414,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
} }
@@ -505,10 +502,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 +591,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 {
@@ -631,7 +627,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
} }
@@ -800,11 +796,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 +869,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 +1021,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) {
@@ -1117,10 +1110,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 +1174,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 +1187,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 +1319,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 +1345,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 +1379,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 +1393,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 +1401,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 +1412,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 +1427,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 +1435,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 +1455,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 +1463,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 +1582,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 actualOwner.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 +1605,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 +1615,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 +1629,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 +1640,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 +1651,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 +1685,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 +1765,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,8 +1790,8 @@ 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
} }
} }
@@ -1806,7 +1803,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) {
+2 -2
View File
@@ -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()
@@ -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 = """
+213 -17
View File
@@ -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,23 +385,28 @@ 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()) """.trimIndent()
)
} }
@Test @Test
fun testCacheInClass() = runTest { fun testCacheInClass() = runTest {
eval(""" eval(
"""
class T(salt) { class T(salt) {
private var c private var c
@@ -416,24 +423,28 @@ class OOTest {
assertEquals("bar.", t2.getResult()) assertEquals("bar.", t2.getResult())
assertEquals("foo.", t1.getResult()) assertEquals("foo.", t1.getResult())
""".trimIndent()) """.trimIndent()
)
} }
@Test @Test
fun testLateInitValsInClasses() = runTest { fun testLateInitValsInClasses() = runTest {
assertFails { assertFails {
eval(""" eval(
"""
class T { class T {
val x val x
} }
""") """
)
} }
assertFails { assertFails {
eval("val String.late") eval("val String.late")
} }
eval(""" eval(
"""
// but we can "late-init" them in init block: // but we can "late-init" them in init block:
class OK { class OK {
val x val x
@@ -463,19 +474,21 @@ class OOTest {
} }
} }
AccessBefore() AccessBefore()
""".trimIndent()) """.trimIndent()
)
} }
@Test @Test
fun testPrivateSet() = runTest { fun testPrivateSet() = runTest {
eval(""" eval(
"""
class A { class A {
var y = 100 var y = 100
private set private set
fun setValue(newValue) { y = newValue } fun setValue(newValue) { y = newValue }
} }
assertEquals(100, A().y) assertEquals(100, A().y)
assertThrows(AccessException) { A().y = 200 } assertThrows(IllegalAccessException) { A().y = 200 }
val a = A() val a = A()
a.setValue(200) a.setValue(200)
assertEquals(200, a.y) assertEquals(200, a.y)
@@ -489,7 +502,7 @@ class OOTest {
} }
val c = C(10) val c = C(10)
assertEquals(10, c.y) assertEquals(10, c.y)
assertThrows(AccessException) { c.y = 20 } assertThrows(IllegalAccessException) { c.y = 20 }
c.setBValue(30) c.setBValue(30)
assertEquals(30, c.y) assertEquals(30, c.y)
@@ -502,10 +515,11 @@ class OOTest {
} }
val d = D() val d = D()
assertEquals(0, d.y) assertEquals(0, d.y)
assertThrows(AccessException) { d.y = 10 } assertThrows(IllegalAccessException) { d.y = 10 }
d.setY(20) d.setY(20)
assertEquals(20, d.y) assertEquals(20, d.y)
""") """
)
} }
@Test @Test
@@ -515,4 +529,186 @@ class OOTest {
} }
} }
@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()
)
}
} }
+29 -1
View File
@@ -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,32 @@ 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())
}
} }
@@ -0,0 +1,213 @@
/*
* 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)
""")
}
}
@@ -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)
}
} }
+53
View File
@@ -276,3 +276,56 @@ fun Exception.printStackTrace() {
/* Compile this string into a regular expression. */ /* Compile this string into a regular expression. */
val String.re get() = Regex(this) val String.re get() = Regex(this)
fun TODO(message=null) = throw NotImplementedException(message ?: "not implemented")
/*
Provides different access types for delegates.
Used in the 'bind' hook to validate delegate usage.
*/
enum DelegateAccess {
Val,
Var,
Callable
}
/*
Base interface for all delegates.
Implementing this interface is optional as Lyng uses dynamic dispatch,
but it is recommended for documentation and clarity.
*/
interface Delegate {
/* Called when a delegated 'val' or 'var' is read. */
fun getValue(thisRef, name) = TODO("delegate getter is not implemented")
/* Called when a delegated 'var' is written. */
fun setValue(thisRef, name, newValue) = TODO("delegate setter is not implemented")
/* Called when a delegated function is invoked. */
fun invoke(thisRef, name, args...) = TODO("delegate invoke is not implemented")
/*
Called once during initialization to configure or validate the delegate.
Should return the delegate object to be used (usually 'this').
*/
fun bind(name, access, thisRef) = this
}
/*
Standard implementation of a lazy-initialized property delegate.
The provided creator lambda is called once on the first access to compute the value.
Can only be used with 'val' properties.
*/
class lazy(creatorParam) : Delegate {
private val creator = creatorParam
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) value = creator()
value
}
}
@@ -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.
@@ -318,6 +318,21 @@ fun EditorWithOverlay(
try { ta.setSelectionRange(res.selStart, res.selEnd) } catch (_: Throwable) {} try { ta.setSelectionRange(res.selStart, res.selEnd) } catch (_: Throwable) {}
pendingSelStart = res.selStart pendingSelStart = res.selStart
pendingSelEnd = res.selEnd pendingSelEnd = res.selEnd
} else if (key.length == 1 && !ev.ctrlKey && !ev.metaKey && !ev.altKey) {
// Handle single character input (like '}') for dedenting
// This is an alternative to onInput to have better control
val start = ta.selectionStart ?: 0
val end = ta.selectionEnd ?: start
val current = ta.value
val res = applyChar(current, start, end, key[0], tabSize)
if (res.text != (current.substring(0, start) + key + current.substring(end))) {
// Logic decided to change something else (e.g. dedent)
ev.preventDefault()
setCode(res.text)
try { ta.setSelectionRange(res.selStart, res.selEnd) } catch (_: Throwable) {}
pendingSelStart = res.selStart
pendingSelEnd = res.selEnd
}
} }
} }
@@ -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.
@@ -83,55 +83,6 @@ private fun nextNonWs(text: String, idxInclusive: Int): Int {
/** Apply Enter key behavior with smart indent/undent rules. */ /** Apply Enter key behavior with smart indent/undent rules. */
fun applyEnter(text: String, selStart: Int, selEnd: Int, tabSize: Int): EditResult { fun applyEnter(text: String, selStart: Int, selEnd: Int, tabSize: Int): EditResult {
// Global early rule (Rule 3): if the line after the current line is brace-only, dedent that line by one block and
// do NOT insert a newline. This uses precise line boundaries.
run {
val start = minOf(selStart, text.length)
val eol = lineEndAt(text, start)
val nextLineStart = if (eol < text.length && text[eol] == '\n') eol + 1 else eol
val nextLineEnd = lineEndAt(text, nextLineStart)
if (nextLineStart <= nextLineEnd && nextLineStart < text.length) {
val trimmedNext = text.substring(nextLineStart, nextLineEnd).trim()
if (trimmedNext == "}") {
val rbraceIndent = countIndentSpaces(text, nextLineStart, nextLineEnd)
val removeCount = kotlin.math.min(tabSize, rbraceIndent)
val crShift = if (nextLineStart < text.length && text[nextLineStart] == '\r') 1 else 0
val out = buildString(text.length) {
append(safeSubstring(text, 0, nextLineStart))
append(safeSubstring(text, nextLineStart + crShift + removeCount, text.length))
}
val caret = nextLineStart + kotlin.math.max(0, rbraceIndent - removeCount)
return EditResult(out, caret, caret)
}
}
}
// Absolute top-priority: caret is exactly at a line break and the next line is '}'-only (ignoring spaces).
// Dedent that next line by one block (tabSize) and do NOT insert a newline.
run {
if (selStart < text.length) {
val isCrLf = selStart + 1 < text.length && text[selStart] == '\r' && text[selStart + 1] == '\n'
val isLf = text[selStart] == '\n'
if (isCrLf || isLf) {
val nextLineStart = selStart + if (isCrLf) 2 else 1
val nextLineEnd = lineEndAt(text, nextLineStart)
if (nextLineStart <= nextLineEnd) {
val trimmed = text.substring(nextLineStart, nextLineEnd).trim()
if (trimmed == "}") {
val rbraceIndent = countIndentSpaces(text, nextLineStart, nextLineEnd)
val removeCount = kotlin.math.min(tabSize, rbraceIndent)
val crShift = if (nextLineStart < text.length && text[nextLineStart] == '\r') 1 else 0
val out = buildString(text.length) {
append(safeSubstring(text, 0, nextLineStart))
append(safeSubstring(text, nextLineStart + crShift + removeCount, text.length))
}
val caret = nextLineStart + kotlin.math.max(0, rbraceIndent - removeCount)
return EditResult(out, caret, caret)
}
}
}
}
}
// If there is a selection, replace it by newline + current line indent // If there is a selection, replace it by newline + current line indent
if (selEnd != selStart) { if (selEnd != selStart) {
val lineStart = lineStartAt(text, selStart) val lineStart = lineStartAt(text, selStart)
@@ -148,8 +99,6 @@ fun applyEnter(text: String, selStart: Int, selEnd: Int, tabSize: Int): EditResu
val lineEnd = lineEndAt(text, start) val lineEnd = lineEndAt(text, start)
val indent = countIndentSpaces(text, lineStart, lineEnd) val indent = countIndentSpaces(text, lineStart, lineEnd)
// (Handled by the global early rule above; no need for additional EOL variants.)
// Compute neighborhood characters early so rule precedence can use them // Compute neighborhood characters early so rule precedence can use them
val prevIdx = prevNonWs(text, start) val prevIdx = prevNonWs(text, start)
val nextIdx = nextNonWs(text, start) val nextIdx = nextNonWs(text, start)
@@ -158,85 +107,6 @@ fun applyEnter(text: String, selStart: Int, selEnd: Int, tabSize: Int): EditResu
val before = text.substring(0, start) val before = text.substring(0, start)
val after = text.substring(start) val after = text.substring(start)
// Rule 2: On a brace-only line '}' (caret on the same line)
// If the current line’s trimmed text is exactly '}', decrease that line’s indent by one block (not below 0),
// then insert a newline. The newly inserted line uses the (decreased) indent. Place the caret at the start of
// the newly inserted line.
run {
val trimmed = text.substring(lineStart, lineEnd).trim()
// IMPORTANT: Rule precedence — do NOT trigger this rule when caret is after '}' and the rest of the line
// up to EOL contains only spaces (Rule 5 handles that case). That scenario must insert AFTER the brace,
// not before it.
var onlySpacesAfterCaret = true
var k = start
while (k < lineEnd) { if (text[k] != ' ') { onlySpacesAfterCaret = false; break }; k++ }
val rule5Situation = (prevCh == '}') && onlySpacesAfterCaret
if (trimmed == "}" && !rule5Situation) {
val removeCount = kotlin.math.min(tabSize, indent)
val newIndent = (indent - removeCount).coerceAtLeast(0)
val crShift = if (lineStart < text.length && text[lineStart] == '\r') 1 else 0
val out = buildString(text.length + 1 + newIndent) {
append(safeSubstring(text, 0, lineStart))
append("\n")
append(" ".repeat(newIndent))
// Write the brace line but with its indent reduced by removeCount spaces
append(safeSubstring(text, lineStart + crShift + removeCount, text.length))
}
val caret = lineStart + 1 + newIndent
return EditResult(out, caret, caret)
}
}
// (The special case of caret after the last non-ws on a '}'-only line is covered by the rule above.)
// 0) Caret is at end-of-line and the next line is a closing brace-only line: dedent that line, no extra newline
run {
val atCr = start + 1 < text.length && text[start] == '\r' && text[start + 1] == '\n'
val atNl = start < text.length && text[start] == '\n'
val atEol = atNl || atCr
if (atEol) {
val nlAdvance = if (atCr) 2 else 1
val nextLineStart = start + nlAdvance
val nextLineEnd = lineEndAt(text, nextLineStart)
val trimmedNext = text.substring(nextLineStart, nextLineEnd).trim()
if (trimmedNext == "}") {
val rbraceIndent = countIndentSpaces(text, nextLineStart, nextLineEnd)
// Dedent the '}' line by one block level (tabSize), but not below column 0
val removeCount = kotlin.math.min(tabSize, rbraceIndent)
val crShift = if (nextLineStart < text.length && text[nextLineStart] == '\r') 1 else 0
val out = buildString(text.length) {
append(safeSubstring(text, 0, nextLineStart))
append(safeSubstring(text, nextLineStart + crShift + removeCount, text.length))
}
val caret = start + nlAdvance + kotlin.math.max(0, rbraceIndent - removeCount)
return EditResult(out, caret, caret)
}
}
}
// 0b) If there is a newline at or after caret and the next line starts (ignoring spaces) with '}',
// dedent that '}' line without inserting an extra newline.
run {
val nlPos = text.indexOf('\n', start)
if (nlPos >= 0) {
val nextLineStart = nlPos + 1
val nextLineEnd = lineEndAt(text, nextLineStart)
val nextLineFirstNonWs = nextNonWs(text, nextLineStart)
if (nextLineFirstNonWs in nextLineStart until nextLineEnd && text[nextLineFirstNonWs] == '}') {
val rbraceIndent = countIndentSpaces(text, nextLineStart, nextLineEnd)
val removeCount = kotlin.math.min(tabSize, rbraceIndent)
val crShift = if (nextLineStart < text.length && text[nextLineStart] == '\r') 1 else 0
val out = buildString(text.length) {
append(safeSubstring(text, 0, nextLineStart))
append(safeSubstring(text, nextLineStart + crShift + removeCount, text.length))
}
val caret = nextLineStart + kotlin.math.max(0, rbraceIndent - removeCount)
return EditResult(out, caret, caret)
}
}
}
// 1) Between braces { | } -> two lines, inner indented // 1) Between braces { | } -> two lines, inner indented
if (prevCh == '{' && nextCh == '}') { if (prevCh == '{' && nextCh == '}') {
val innerIndent = indent + tabSize val innerIndent = indent + tabSize
@@ -254,119 +124,17 @@ fun applyEnter(text: String, selStart: Int, selEnd: Int, tabSize: Int): EditResu
} }
// 3) Before '}' // 3) Before '}'
if (nextCh == '}') { if (nextCh == '}') {
// We want two things:
// - reduce indentation of the upcoming '}' line by one level
// - avoid creating an extra blank line if caret is already at EOL (the next char is a newline)
// Compute where the '}' line starts and how many leading spaces it has
val rbraceLineStart = lineStartAt(text, nextIdx)
val rbraceLineEnd = lineEndAt(text, nextIdx)
val rbraceIndent = countIndentSpaces(text, rbraceLineStart, rbraceLineEnd)
// Dedent the '}' line by one block level (tabSize), but not below column 0
val removeCount = kotlin.math.min(tabSize, rbraceIndent)
val crShift = if (rbraceLineStart < text.length && text[rbraceLineStart] == '\r') 1 else 0
// If there is already a newline between caret and the '}', do NOT insert another newline.
// Just dedent the existing '}' line by one block and place caret at its start.
run {
val nlBetween = text.indexOf('\n', start)
if (nlBetween in start until rbraceLineStart) {
val out = buildString(text.length) {
append(safeSubstring(text, 0, rbraceLineStart))
append(safeSubstring(text, rbraceLineStart + crShift + removeCount, text.length))
}
val caret = rbraceLineStart + kotlin.math.max(0, rbraceIndent - removeCount)
return EditResult(out, caret, caret)
}
}
val hasNewlineAtCaret = (start < text.length && text[start] == '\n')
// New indentation for the line we create (if we actually insert one now)
val newLineIndent = (indent - tabSize).coerceAtLeast(0)
val insertion = if (hasNewlineAtCaret) "" else "\n" + " ".repeat(newLineIndent)
val out = buildString(text.length + insertion.length) {
append(before)
append(insertion)
// keep text up to the start of '}' line
append(safeSubstring(text, start, rbraceLineStart))
// drop up to tabSize spaces before '}'
append(safeSubstring(text, rbraceLineStart + crShift + removeCount, text.length))
}
val caret = if (hasNewlineAtCaret) {
// Caret moves to the beginning of the '}' line after dedent (right after the single newline)
start + 1 + kotlin.math.max(0, rbraceIndent - removeCount)
} else {
start + insertion.length
}
return EditResult(out, caret, caret)
}
// 4) After '}' with only trailing spaces before EOL
// According to Rule 5: if the last non-whitespace before the caret is '}' and
// only spaces remain until EOL, we must:
// - dedent the current (brace) line by one block (not below 0)
// - insert a newline just AFTER '}' (do NOT move caret backward)
// - set the caret at the start of the newly inserted blank line, whose indent equals the dedented indent
if (prevCh == '}') {
var onlySpaces = true
var k = prevIdx + 1
while (k < lineEnd) { if (text[k] != ' ') { onlySpaces = false; break }; k++ }
if (onlySpaces) {
val removeCount = kotlin.math.min(tabSize, indent)
val newIndent = (indent - removeCount).coerceAtLeast(0)
val crShift = if (lineStart < text.length && text[lineStart] == '\r') 1 else 0
// Build the result:
// - keep everything before the line start
// - write the current line content up to the caret, but with its left indent reduced by removeCount
// - insert newline + spaces(newIndent)
// - drop trailing spaces after caret up to EOL
// - keep the rest of the text starting from EOL
val out = buildString(text.length) {
append(safeSubstring(text, 0, lineStart))
append(safeSubstring(text, lineStart + crShift + removeCount, start))
append("\n")
append(" ".repeat(newIndent))
append(safeSubstring(text, lineEnd, text.length))
}
val caret = (lineStart + (start - (lineStart + crShift + removeCount)) + 1 + newIndent)
return EditResult(out, caret, caret)
} else {
// Default smart indent for cases where there are non-space characters after '}'
val insertion = "\n" + " ".repeat(indent)
val out = before + insertion + after
val caret = start + insertion.length
return EditResult(out, caret, caret)
}
}
// 5) Fallback: if there is a newline ahead and the next line, trimmed, equals '}', dedent that '}' line by one block
run {
val nlPos = text.indexOf('\n', start)
if (nlPos >= 0) {
val nextLineStart = nlPos + 1
val nextLineEnd = lineEndAt(text, nextLineStart)
val trimmedNext = text.substring(nextLineStart, nextLineEnd).trim()
if (trimmedNext == "}") {
val rbraceIndent = countIndentSpaces(text, nextLineStart, nextLineEnd)
val removeCount = kotlin.math.min(tabSize, rbraceIndent)
val crShift = if (nextLineStart < text.length && text[nextLineStart] == '\r') 1 else 0
val out = buildString(text.length) {
append(safeSubstring(text, 0, nextLineStart))
append(safeSubstring(text, nextLineStart + crShift + removeCount, text.length))
}
val caret = nextLineStart + kotlin.math.max(0, rbraceIndent - removeCount)
return EditResult(out, caret, caret)
}
}
}
// default keep same indent
run {
val insertion = "\n" + " ".repeat(indent) val insertion = "\n" + " ".repeat(indent)
val out = before + insertion + after val out = before + insertion + after
val caret = start + insertion.length val caret = start + insertion.length
return EditResult(out, caret, caret) return EditResult(out, caret, caret)
} }
// default keep same indent
val insertion = "\n" + " ".repeat(indent)
val out = before + insertion + after
val caret = start + insertion.length
return EditResult(out, caret, caret)
} }
/** Apply Tab key: insert spaces at caret (single-caret only). */ /** Apply Tab key: insert spaces at caret (single-caret only). */
@@ -423,3 +191,37 @@ fun applyShiftTab(text: String, selStart: Int, selEnd: Int, tabSize: Int): EditR
val e = maxOf(newSelStart, newSelEnd) val e = maxOf(newSelStart, newSelEnd)
return EditResult(sb.toString(), s, e) return EditResult(sb.toString(), s, e)
} }
/**
* Apply a typed character. If the character is '}', and it's the only non-whitespace on the line,
* it may be dedented.
*/
fun applyChar(text: String, selStart: Int, selEnd: Int, ch: Char, tabSize: Int): EditResult {
// Selection replacement
val current = if (selStart != selEnd) {
text.substring(0, minOf(selStart, selEnd)) + text.substring(maxOf(selStart, selEnd))
} else text
val pos = minOf(selStart, selEnd)
val before = current.substring(0, pos)
val after = current.substring(pos)
val newText = before + ch + after
val newPos = pos + 1
if (ch == '}') {
val lineStart = lineStartAt(newText, pos)
val lineEnd = lineEndAt(newText, newPos)
val trimmed = newText.substring(lineStart, lineEnd).trim()
if (trimmed == "}") {
// Dedent this line
val indent = countIndentSpaces(newText, lineStart, lineEnd)
val removeCount = minOf(tabSize, indent)
if (removeCount > 0) {
val out = newText.substring(0, lineStart) + newText.substring(lineStart + removeCount)
return EditResult(out, newPos - removeCount, newPos - removeCount)
}
}
}
return EditResult(newText, newPos, newPos)
}
@@ -530,10 +530,10 @@ private fun detectDeclarationAndParamOverrides(text: String): Map<Pair<Int, Int>
fun isIdentPart(ch: Char) = ch == '_' || ch == '$' || ch == '~' || ch.isLetterOrDigit() fun isIdentPart(ch: Char) = ch == '_' || ch == '$' || ch == '~' || ch.isLetterOrDigit()
// A conservative list of language keywords to avoid misclassifying as function calls // A conservative list of language keywords to avoid misclassifying as function calls
val kw = setOf( val kw = setOf(
"package", "import", "fun", "fn", "class", "enum", "val", "var", "package", "import", "fun", "fn", "class", "interface", "enum", "val", "var",
"if", "else", "while", "do", "for", "when", "try", "catch", "finally", "if", "else", "while", "do", "for", "when", "try", "catch", "finally",
"throw", "return", "break", "continue", "in", "is", "as", "as?", "not", "throw", "return", "break", "continue", "in", "is", "as", "as?", "not",
"true", "false", "null", "private", "protected", "open", "extern", "static", "true", "false", "null", "private", "protected", "abstract", "closed", "override", "open", "extern", "static",
"init", "get", "set", "Unset", "by" "init", "get", "set", "Unset", "by"
) )
fun skipWs(idx0: Int): Int { fun skipWs(idx0: Int): Int {
+36 -282
View File
@@ -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.
@@ -25,81 +25,19 @@ class EditorLogicTest {
private val tab = 4 private val tab = 4
@Test @Test
fun enter_after_only_rbrace_undents() { fun type_rbrace_dedents_if_only_char_on_line() {
val line = " } " // 4 spaces, brace, trailing spaces; caret after last non-ws val text = " "
val res = applyEnter(line, line.length, line.length, tab) val res = applyChar(text, 4, 4, '}', tab)
// Should insert newline with one indent level less (0 spaces here) assertEquals("}", res.text)
assertEquals(" } \n" + "" , res.text.substring(0, res.text.indexOf('\n')+1)) assertEquals(1, res.selStart)
// After insertion caret should be at end of inserted indentation
// Here indent was 4 and undented by 4 -> 0 spaces after newline
val expectedCaret = line.length + 1 + 0
assertEquals(expectedCaret, res.selStart)
assertEquals(expectedCaret, res.selEnd)
} }
@Test @Test
fun enter_after_rbrace_with_only_spaces_to_eol_inserts_after_brace_and_dedents_and_undents_brace_line() { fun type_rbrace_no_dedent_if_not_only_char() {
// Rule 5 exact check: last non-ws before caret is '}', remainder to EOL only spaces val text = " foo "
val indents = listOf(0, 4, 8) val res = applyChar(text, 8, 8, '}', tab)
for (indent in indents) { assertEquals(" foo }", res.text)
val spaces = " ".repeat(indent) assertEquals(9, res.selStart)
// Line ends with '}' followed by three spaces
val before = (
"""
1
${'$'}spaces}
"""
).trimIndent() + " "
// Caret right after '}', before trailing spaces
val caret = before.indexOf('}') + 1
val res = applyEnter(before, caret, caret, tab)
val newBraceIndent = (indent - tab).coerceAtLeast(0)
val newLineIndent = newBraceIndent
val expected = buildString {
append("1\n")
append(" ".repeat(newBraceIndent))
append("}\n")
append(" ".repeat(newLineIndent))
}
assertEquals(expected, res.text)
// Caret must be at start of the newly inserted line (after the final newline)
assertEquals(expected.length, res.selStart)
assertEquals(res.selStart, res.selEnd)
}
}
@Test
fun enter_after_rbrace_with_only_spaces_to_eol_crlf_and_undents_brace_line() {
val indent = 4
val spaces = " ".repeat(indent)
val beforeLf = (
"""
1
${'$'}spaces}
"""
).trimIndent() + " "
val before = beforeLf.replace("\n", "\r\n")
val caret = before.indexOf('}') + 1
val res = applyEnter(before, caret, caret, tab)
val actual = res.text.replace("\r\n", "\n")
val newIndent = (indent - tab).coerceAtLeast(0)
val expected = "1\n${" ".repeat(newIndent)}}\n${" ".repeat(newIndent)}"
assertEquals(expected, actual)
assertEquals(expected.length, res.selStart)
assertEquals(res.selStart, res.selEnd)
}
@Test
fun enter_before_closing_brace_outdents() {
val text = " }" // caret before '}' at index 4
val caret = 4
val res = applyEnter(text, caret, caret, tab)
// Inserted a newline with indent reduced to 0
assertEquals("\n" + "" + "}", res.text.substring(caret, caret + 2))
val expectedCaret = caret + 1 + 0
assertEquals(expectedCaret, res.selStart)
assertEquals(expectedCaret, res.selEnd)
} }
@Test @Test
@@ -123,23 +61,6 @@ class EditorLogicTest {
assertEquals(1 + 1 + 4, res.selStart) assertEquals(1 + 1 + 4, res.selStart)
} }
@Test
fun enter_after_rbrace_line_undents_ignoring_trailing_ws() {
// Line contains only '}' plus trailing spaces; caret after last non-ws
val line = " } "
val res = applyEnter(line, line.length, line.length, tab)
// Expect insertion of a newline and an undented indentation of (indent - tab)
val expectedIndentAfterNewline = 0 // 4 - 4
val expected = line + "\n" + " ".repeat(expectedIndentAfterNewline)
// Compare prefix up to inserted indentation
val prefix = res.text.substring(0, expected.length)
assertEquals(expected, prefix)
// Caret positioned at end of inserted indentation
val expectedCaret = expected.length
assertEquals(expectedCaret, res.selStart)
assertEquals(expectedCaret, res.selEnd)
}
@Test @Test
fun shift_tab_outdents_rbrace_only_line_no_newline() { fun shift_tab_outdents_rbrace_only_line_no_newline() {
// Multi-line: a block followed by a number; we outdent the '}' line only // Multi-line: a block followed by a number; we outdent the '}' line only
@@ -171,222 +92,55 @@ class EditorLogicTest {
assertEquals(1 + 4, res.selStart) assertEquals(1 + 4, res.selStart)
} }
/*
@Test @Test
fun enter_before_line_with_only_rbrace_dedents_that_line() { fun enter_before_line_with_only_rbrace_dedents_that_line() {
// Initial content as reported by user before fix ...
val before = ( */
"""
{
1
2
3
}
1
2
3
"""
).trimIndent()
// Place caret at the end of the line that contains just " 3" (before the line with '}')
val lines = before.split('\n')
// Build index of end of the line with the last " 3"
var idx = 0
var caret = 0
for (i in lines.indices) {
val line = lines[i]
if (line.trimEnd() == "3" && i + 1 < lines.size && lines[i + 1].trim() == "}") {
caret = idx + line.length // position after '3', before the newline
break
}
idx += line.length + 1 // +1 for newline
}
val res = applyEnter(before, caret, caret, tab)
val expected = (
"""
{
1
2
3
}
1
2
3
"""
).trimIndent()
assertEquals(expected, res.text)
}
/*
@Test @Test
fun enter_eol_before_brace_only_next_line_various_indents() { fun enter_eol_before_brace_only_next_line_various_indents() {
// Cover Rule 3 with LF newlines, at indents 0, 2, 4, 8 ...
val indents = listOf(0, 2, 4, 8) */
for (indent in indents) {
val spaces = " ".repeat(indent)
val before = (
"""
1
2
3
${'$'}spaces}
4
"""
).trimIndent()
// Caret at end of the line with '3' (line before the rbrace-only line)
val caret = before.indexOf("3\n") + 1 // just before LF
val res = applyEnter(before, caret, caret, tab)
// The '}' line must be dedented by one block (clamped at 0) and caret moved to its start
val expectedIndent = (indent - tab).coerceAtLeast(0)
val expected = (
"""
1
2
3
${'$'}{" ".repeat(expectedIndent)}}
4
"""
).trimIndent()
assertEquals(expected, res.text, "EOL before '}' dedent failed for indent=${'$'}indent")
// Caret should be at start of that '}' line (line index 3)
val lines = res.text.split('\n')
var pos = 0
for (i in 0 until 3) pos += lines[i].length + 1
assertEquals(pos, res.selStart, "Caret pos mismatch for indent=${'$'}indent")
assertEquals(pos, res.selEnd, "Caret pos mismatch for indent=${'$'}indent")
}
}
/*
@Test @Test
fun enter_eol_before_brace_only_next_line_various_indents_crlf() { fun enter_eol_before_brace_only_next_line_various_indents_crlf() {
// Same as above but with CRLF newlines ...
val indents = listOf(0, 2, 4, 8) */
for (indent in indents) {
val spaces = " ".repeat(indent)
val beforeLf = (
"""
1
2
3
${'$'}spaces}
4
"""
).trimIndent()
val before = beforeLf.replace("\n", "\r\n")
val caret = before.indexOf("3\r\n") + 1 // at '3' index + 1 moves to end-of-line before CR
val res = applyEnter(before, caret, caret, tab)
val expectedIndent = (indent - tab).coerceAtLeast(0)
val expectedLf = (
"""
1
2
3
${'$'}{" ".repeat(expectedIndent)}}
4
"""
).trimIndent()
assertEquals(expectedLf, res.text.replace("\r\n", "\n"), "CRLF case failed for indent=${'$'}indent")
}
}
/*
@Test @Test
fun enter_at_start_of_brace_only_line_at_cols_0_2_4() { fun enter_at_start_of_brace_only_line_at_cols_0_2_4() {
val indents = listOf(0, 2, 4) ...
for (indent in indents) { */
val spaces = " ".repeat(indent)
val before = (
"""
1
2
${'$'}spaces}
3
"""
).trimIndent()
// Caret at start of the brace line
val lines = before.split('\n')
var caret = 0
for (i in 0 until 2) caret += lines[i].length + 1
caret += 0 // column 0 of brace line
val res = applyEnter(before, caret, caret, tab)
// Expect the brace line to be dedented by one block, and a new line inserted before it
val expectedIndent = (indent - tab).coerceAtLeast(0)
val expected = (
"""
1
2
${'$'}{" ".repeat(expectedIndent)}
${'$'}{" ".repeat(expectedIndent)}}
3
"""
).trimIndent()
assertEquals(expected, res.text, "Brace-line start enter failed for indent=${'$'}indent")
// Caret must be at start of the inserted line, which has expectedIndent spaces
val afterLines = res.text.split('\n')
var pos = 0
for (i in 0 until 3) pos += afterLines[i].length + 1
// The inserted line is line index 2 (0-based), caret at its start
pos -= afterLines[2].length + 1
pos += 0
assertEquals(pos, res.selStart, "Caret mismatch for indent=${'$'}indent")
assertEquals(pos, res.selEnd, "Caret mismatch for indent=${'$'}indent")
}
}
@Test @Test
fun enter_on_whitespace_only_line_keeps_same_indent() { fun enter_on_whitespace_only_line_keeps_same_indent() {
val before = " \nnext" // line 0 has 4 spaces only val before = " \nnext" // line 0 has 4 spaces only
val caret = 0 + 4 // at end of spaces, before LF val caret = 4 // at end of spaces, before LF
val res = applyEnter(before, caret, caret, tab) val res = applyEnter(before, caret, caret, tab)
// Default smart indent should keep indent = 4 // Default smart indent should keep indent = 4
// Original text: ' ' + '\n' + 'next'
// Inserted: '\n' + ' ' at caret 4
// Result: ' ' + '\n' + ' ' + '\n' + 'next'
assertEquals(" \n \nnext", res.text) assertEquals(" \n \nnext", res.text)
// Caret at start of the new blank line with 4 spaces // Caret at start of the new blank line with 4 spaces (after first newline)
assertEquals(1 + 4, res.selStart) // lineStart(0) + indent(4) + newline(1) + newIndent(4) = 9
assertEquals(4 + 1 + 4, res.selStart)
assertEquals(res.selStart, res.selEnd) assertEquals(res.selStart, res.selEnd)
} }
/*
@Test @Test
fun enter_on_line_with_rbrace_else_lbrace_defaults_smart() { fun enter_on_line_with_rbrace_else_lbrace_defaults_smart() {
val text = " } else {" ...
// Try caret positions after '}', before 'e', and after '{' */
val carets = listOf(5, 6, text.length)
for (c in carets) {
val res = applyEnter(text, c, c, tab)
// Should not trigger special cases since line is not brace-only or only-spaces after '}'
// Expect same indent (4 spaces)
val expectedPrefix = text.substring(0, c) + "\n" + " ".repeat(4)
assertEquals(expectedPrefix, res.text.substring(0, expectedPrefix.length))
assertEquals(c + 1 + 4, res.selStart)
assertEquals(res.selStart, res.selEnd)
}
}
/*
@Test @Test
fun enter_with_selection_replaces_and_uses_anchor_indent() { fun enter_with_selection_replaces_and_uses_anchor_indent() {
val text = ( ...
""" */
1
2
3
"""
).trimIndent()
// Select "2\n3" starting at column 4 of line 1 (indent = 4)
val idxLine0 = text.indexOf('1')
val idxLine1 = text.indexOf('\n', idxLine0) + 1
val selStart = idxLine1 + 4 // after 4 spaces
val selEnd = text.length
val res = applyEnter(text, selStart, selEnd, tab)
val expected = (
"""
1
"""
).trimIndent()
assertEquals(expected, res.text)
assertEquals(expected.length, res.selStart)
assertEquals(res.selStart, res.selEnd)
}
} }
+14 -1
View File
@@ -28,6 +28,7 @@ fun App() {
var toc by remember { mutableStateOf<List<TocItem>>(emptyList()) } var toc by remember { mutableStateOf<List<TocItem>>(emptyList()) }
var activeTocId by remember { mutableStateOf<String?>(null) } var activeTocId by remember { mutableStateOf<String?>(null) }
var contentEl by remember { mutableStateOf<HTMLElement?>(null) } var contentEl by remember { mutableStateOf<HTMLElement?>(null) }
var navEl by remember { mutableStateOf<HTMLElement?>(null) }
val isDocsRoute = route.startsWith("docs/") val isDocsRoute = route.startsWith("docs/")
val docKey = stripFragment(route) val docKey = stripFragment(route)
@@ -60,6 +61,13 @@ fun App() {
onDispose { window.removeEventListener("hashchange", listener) } onDispose { window.removeEventListener("hashchange", listener) }
} }
LaunchedEffect(activeTocId) {
val activeId = activeTocId ?: return@LaunchedEffect
val nav = navEl ?: return@LaunchedEffect
val activeLink = nav.querySelector("a[data-toc-id=\"$activeId\"]") as? HTMLElement
activeLink?.scrollIntoView(js("({block: 'nearest', behavior: 'smooth'})"))
}
PageTemplate(title = when { PageTemplate(title = when {
isDocsRoute -> null isDocsRoute -> null
route.startsWith("reference") -> "Reference" route.startsWith("reference") -> "Reference"
@@ -71,7 +79,11 @@ fun App() {
Div({ classes("col-12", "col-lg-3") }) { Div({ classes("col-12", "col-lg-3") }) {
Nav({ Nav({
classes("position-sticky") classes("position-sticky")
attr("style", "top: calc(var(--navbar-offset) + 1rem)") attr("style", "top: calc(var(--navbar-offset) + 1rem); max-height: calc(100vh - var(--navbar-offset) - 2rem); overflow-y: auto;")
ref {
navEl = it
onDispose { navEl = null }
}
}) { }) {
H2({ classes("h6", "text-uppercase", "text-muted") }) { Text("On this page") } H2({ classes("h6", "text-uppercase", "text-muted") }) { Text("On this page") }
Ul({ classes("list-unstyled") }) { Ul({ classes("list-unstyled") }) {
@@ -82,6 +94,7 @@ fun App() {
val tocHref = "#/$routeNoFrag#${item.id}" val tocHref = "#/$routeNoFrag#${item.id}"
A(attrs = { A(attrs = {
attr("href", tocHref) attr("href", tocHref)
attr("data-toc-id", item.id)
attr("style", "padding-left: $pad") attr("style", "padding-left: $pad")
classes("link-body-emphasis", "text-decoration-none") classes("link-body-emphasis", "text-decoration-none")
if (activeTocId == item.id) { if (activeTocId == item.id) {
+11
View File
@@ -180,6 +180,17 @@ fun ensureDocsLayoutStyles() {
.markdown-body h1:first-child { .markdown-body h1:first-child {
margin-top: 0 !important; margin-top: 0 !important;
} }
/* Hide scrollbar for the TOC nav but allow scrolling */
nav.position-sticky::-webkit-scrollbar {
width: 4px;
}
nav.position-sticky::-webkit-scrollbar-thumb {
background: rgba(128,128,128,0.2);
border-radius: 4px;
}
nav.position-sticky:hover::-webkit-scrollbar-thumb {
background: rgba(128,128,128,0.5);
}
""" """
.trimIndent() .trimIndent()
) )
+2 -2
View File
@@ -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.
@@ -329,7 +329,7 @@
<!-- Top-left version ribbon --> <!-- Top-left version ribbon -->
<div class="corner-ribbon bg-danger text-white"> <div class="corner-ribbon bg-danger text-white">
<span style="margin-left: -5em"> <span style="margin-left: -5em">
v1.1.0-beta2 v1.1.0-rc
</span> </span>
</div> </div>
<!-- Fixed top navbar for the whole site --> <!-- Fixed top navbar for the whole site -->
+2 -2
View File
@@ -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.
@@ -60,7 +60,7 @@ class HighlightSmokeTest {
// Spread operator present // Spread operator present
assertContains(html, "<span class=\"hl-op\">...</span>") assertContains(html, "<span class=\"hl-op\">...</span>")
// String key and identifier key appear // String key and identifier key appear
assertContains(html, "<span class=\"hl-str\">\"a\"</span>") assertContains(html, "<span class=\"hl-str\">&quot;a&quot;</span>")
assertContains(html, "<span class=\"hl-id\">b</span>") assertContains(html, "<span class=\"hl-id\">b</span>")
} }