Compare commits

...
17 Commits
Author SHA1 Message Date
sergeych 2d4ae0d98b fixed site sample to be more expressive 2026-02-17 22:34:56 +03:00
sergeych 74d911e837 Migrate IdeLenientImportProvider to lynglib, add detailed time-related documentation, and improve analysis support for unresolved references. 2026-02-17 22:20:31 +03:00
sergeych 2e7c28f735 corrected home page samples 2026-02-17 12:47:55 +03:00
sergeych 69156893d4 Improve receiver class handling and enhance resolution logic 2026-02-17 12:35:31 +03:00
sergeych df19524177 Refine variable resolution logic, update type alias syntax 2026-02-17 08:17:57 +03:00
sergeych b6851b7098 Improve variable resolution and expand test coverage; improved wahtsnew 2026-02-17 08:06:06 +03:00
sergeych afa4b20070 update version, site and docs 2026-02-16 19:29:14 +03:00
sergeych c5b8871c3a Add support for closed classes and enhancements to the Kotlin reflection bridge 2026-02-16 19:08:32 +03:00
sergeych 7f2f99524f Expand fast ops optimization plan 2026-02-16 18:09:58 +03:00
sergeych bfa8a59df3 Unbox assign-op operands for fast int/real ops 2026-02-16 18:04:55 +03:00
sergeych 09b1eb68ae Enable fast string compares for indexed list 2026-02-16 17:58:05 +03:00
sergeych fdb23b3a76 Reuse void slot for if statements 2026-02-16 17:50:39 +03:00
sergeych 7c28296f92 Elide redundant bool conversions in logical ops 2026-02-16 17:42:04 +03:00
sergeych 3e654ddd60 Use primitive ops for mixed int/real 2026-02-16 17:37:49 +03:00
sergeych e8f5c9eaf4 Use fast compare for stable obj temps 2026-02-16 17:35:08 +03:00
sergeych 44f9573eec Add mixed compare benchmark baseline 2026-02-16 17:33:05 +03:00
sergeych a8f6aa31f1 Fix for-loop real widening coercions 2026-02-16 16:53:53 +03:00
31 changed files with 1502 additions and 198 deletions

No files matched your search

+27 -12
View File
@@ -1,6 +1,31 @@
## Changelog ## 1.5.0-SNAPSHOT
### Unreleased ### Language Features
- Added `return` statement with local and non-local exit support (`return@label`).
- Support for `abstract` classes, methods, and variables.
- Introduced `interface` as a synonym for `abstract class`.
- Multiple Inheritance (MI) completed and enabled by default (C3 MRO).
- Class properties with custom accessors (`get`, `set`).
- Restricted setter visibility (`private set`, `protected set`).
- Late-initialized `val` fields in classes with `Unset` protection.
- Named arguments (`name: value`) and named splats (`...Map`).
- Assign-if-null operator `?=`.
- Refined `protected` visibility rules and `closed` modifier.
- Transient attribute `@Transient` for serialization and equality.
- Unified Delegation model for `val`, `var`, and `fun`.
- Singleton objects (`object`) and object expressions.
### Standard Library
- Added `with(self, block)` for scoped execution.
- Added `clamp()` function and extension.
- Improved `Exception` and `StackTraceEntry` reporting.
### Tooling and IDE
- **CLI**: Added `fmt` as a first-class subcommand for code formatting.
- **IDEA Plugin**: Lightweight autocompletion (experimental), improved docs, and Grazie integration.
- **Highlighters**: Updated TextMate bundle and website highlighters for new syntax.
### Detailed Changes:
- Language: Refined `protected` visibility rules - Language: Refined `protected` visibility rules
- Ancestor classes can now access `protected` members of their descendants, provided the ancestor also defines or inherits a member with the same name (indicating an override of a member known to the ancestor). - Ancestor classes can now access `protected` members of their descendants, provided the ancestor also defines or inherits a member with the same name (indicating an override of a member known to the ancestor).
@@ -109,16 +134,6 @@
- Documentation updated (docs/OOP.md and tutorial quick-start) to reflect MI with active C3 MRO. - Documentation updated (docs/OOP.md and tutorial quick-start) to reflect MI with active C3 MRO.
Notes:
- Existing single-inheritance code continues to work; resolution reduces to the single base.
- If code previously relied on non-deterministic parent set iteration, C3 MRO provides a predictable order; disambiguate explicitly if needed using `this@Type`/casts.
# Changelog
All notable changes to this project will be documented in this file.
## Unreleased
- CLI: Added `fmt` as a first-class Clikt subcommand. - CLI: Added `fmt` as a first-class Clikt subcommand.
- Default behavior: formats files to stdout (no in-place edits by default). - Default behavior: formats files to stdout (no in-place edits by default).
- Options: - Options:
+1 -1
View File
@@ -1,4 +1,4 @@
# Lyng Language AI Specification (V1.3) # Lyng Language AI Specification (V1.5.0-SNAPSHOT)
High-density specification for LLMs. Reference this for all Lyng code generation. High-density specification for LLMs. Reference this for all Lyng code generation.
+4 -4
View File
@@ -48,7 +48,7 @@ assertEquals(A.One, A.E.One)
- [Language home](https://lynglang.com) - [Language home](https://lynglang.com)
- [introduction and tutorial](docs/tutorial.md) - start here please - [introduction and tutorial](docs/tutorial.md) - start here please
- [What's New in 1.3](docs/whats_new_1_3.md) - [What's New in 1.5](docs/whats_new_1_5.md)
- [Testing and Assertions](docs/Testing.md) - [Testing and Assertions](docs/Testing.md)
- [Filesystem and Processes (lyngio)](docs/lyngio.md) - [Filesystem and Processes (lyngio)](docs/lyngio.md)
- [Return Statement](docs/return_statement.md) - [Return Statement](docs/return_statement.md)
@@ -64,7 +64,7 @@ assertEquals(A.One, A.E.One)
```kotlin ```kotlin
// update to current please: // update to current please:
val lyngVersion = "0.6.1-SNAPSHOT" val lyngVersion = "1.5.0-SNAPSHOT"
repositories { repositories {
// ... // ...
@@ -177,7 +177,7 @@ Designed to add scripting to kotlin multiplatform application in easy and effici
# Language Roadmap # Language Roadmap
We are now at **v1.0**: basic optimization performed, battery included: standard library is 90% here, initial We are now at **v1.5.0-SNAPSHOT** (stable development cycle): basic optimization performed, battery included: standard library is 90% here, initial
support in HTML, popular editors, and IDEA; tools to syntax highlight and format code are ready. It was released closed to schedule. support in HTML, popular editors, and IDEA; tools to syntax highlight and format code are ready. It was released closed to schedule.
Ready features: Ready features:
@@ -217,7 +217,7 @@ Ready features:
All of this is documented in the [language site](https://lynglang.com) and locally [docs/language.md](docs/tutorial.md). the current nightly builds published on the site and in the private maven repository. All of this is documented in the [language site](https://lynglang.com) and locally [docs/language.md](docs/tutorial.md). the current nightly builds published on the site and in the private maven repository.
## plan: towards v1.5 Enhancing ## plan: towards v2.0 Next Generation
- [x] site with integrated interpreter to give a try - [x] site with integrated interpreter to give a try
- [x] kotlin part public API good docs, integration focused - [x] kotlin part public API good docs, integration focused
+71
View File
@@ -182,6 +182,77 @@ instance.value = 42
println(instance.value) // -> 42 println(instance.value) // -> 42
``` ```
### 6.5) Preferred: bind Kotlin implementations to declared Lyng classes
For extensions and libraries, the **preferred** workflow is Lyng‑first: declare the class and its members in Lyng, then bind the Kotlin implementations using the bridge.
This keeps Lyng semantics (visibility, overrides, type checks) in Lyng, while Kotlin supplies the behavior.
```lyng
// Lyng side (in a module)
class Counter {
extern var value: Int
extern fun inc(by: Int): Int
}
```
Note: members must be marked `extern` so the compiler emits the ABI slots that Kotlin bindings attach to. This applies to functions and properties bound via `addFun` / `addVal` / `addVar`.
```kotlin
// Kotlin side (binding)
val moduleScope = Script.newScope() // or an existing module scope
moduleScope.eval("class Counter { extern var value: Int; extern fun inc(by: Int): Int }")
moduleScope.bind("Counter") {
addVar(
name = "value",
get = { _, self -> self.readField(this, "value").value },
set = { _, self, v -> self.writeField(this, "value", v) }
)
addFun("inc") { _, self, args ->
val by = args.requiredArg<ObjInt>(0).value
val current = self.readField(this, "value").value as ObjInt
val next = ObjInt(current.value + by)
self.writeField(this, "value", next)
next
}
}
```
Notes:
- Binding must happen **before** the first instance is created.
- Use [LyngClassBridge] to bind by name/module, or by an already resolved `ObjClass`.
- Use `ObjInstance.data` / `ObjClass.classData` to attach Kotlin‑side state when needed.
### 6.6) Preferred: Kotlin reflection bridge for call‑by‑name
For Kotlin code that needs dynamic access to Lyng variables, functions, or members, use the bridge resolver.
It provides explicit, cached handles and predictable lookup rules.
```kotlin
val scope = Script.newScope()
scope.eval("""
val x = 40
fun add(a, b) = a + b
class Box { var value = 1 }
""")
val resolver = scope.resolver()
// Read a top‑level value
val x = resolver.resolveVal("x").get(scope)
// Call a function by name (cached inside the resolver)
val sum = (resolver as BridgeCallByName).callByName(scope, "add", Arguments(ObjInt(1), ObjInt(2)))
// Member access
val box = scope.eval("Box()")
val valueHandle = resolver.resolveMemberVar(box, "value")
valueHandle.set(scope, ObjInt(10))
val value = valueHandle.get(scope)
```
### 7) Read variable values back in Kotlin ### 7) Read variable values back in Kotlin
The simplest approach: evaluate an expression that yields the value and convert it. The simplest approach: evaluate an expression that yields the value and convert it.
+10 -2
View File
@@ -1,7 +1,7 @@
# What's New in Lyng # What's New in Lyng
This document highlights the latest additions and improvements to the Lyng language and its ecosystem. This document highlights the latest additions and improvements to the Lyng language and its ecosystem.
For a programmer-focused migration summary, see `docs/whats_new_1_3.md`. For a programmer-focused migration summary, see `docs/whats_new_1_5.md`.
## Language Features ## Language Features
@@ -102,7 +102,7 @@ Singleton objects are declared using the `object` keyword. They provide a conven
```lyng ```lyng
object Config { object Config {
val version = "1.2.3" val version = "1.5.0-SNAPSHOT"
fun show() = println("Config version: " + version) fun show() = println("Config version: " + version)
} }
@@ -243,3 +243,11 @@ You can enable it in **Settings | Lyng Formatter | Enable Lyng autocompletion**.
### Kotlin API: Exception Handling ### Kotlin API: Exception Handling
The `Obj.getLyngExceptionMessageWithStackTrace()` extension method has been added to simplify retrieving detailed error information from Lyng exception objects in Kotlin. Additionally, `getLyngExceptionMessage()` and `raiseAsExecutionError()` now accept an optional `Scope`, making it easier to use them when a scope is not immediately available. The `Obj.getLyngExceptionMessageWithStackTrace()` extension method has been added to simplify retrieving detailed error information from Lyng exception objects in Kotlin. Additionally, `getLyngExceptionMessage()` and `raiseAsExecutionError()` now accept an optional `Scope`, making it easier to use them when a scope is not immediately available.
### Kotlin API: Bridge Reflection and Class Binding (Preferred Extensions)
Lyng now provides a public Kotlin reflection bridge and a Lyng‑first class binding workflow. This is the **preferred** way to write Kotlin extensions and library integrations:
- **Bridge resolver**: explicit handles for values, vars, and callables with predictable lookup rules.
- **Class bridge binding**: declare classes/members in Lyng (marked `extern`) and bind the implementations in Kotlin before the first instance is created.
See **Embedding Lyng** for full samples and usage details.
+140
View File
@@ -0,0 +1,140 @@
# What's New in Lyng 1.5 (vs 1.3.* / master)
This document summarizes the significant changes and new features introduced in the 1.5 development cycle.
## Principal changes
### JIT compiler and compile-time types and symbols.
This major improvement gives the following big advantages:
- **Blazing Fast execution**: several times faster! (three to six times speedup in different scenarios).
- **Better IDE support**: autocompletion, early error detection, types check.
- **Error safety**: all symbols and types are checked at bound at compile-time. Many errors are detected earlier. Also, no risk that external or caller code would shadow some internally used symbols (especially in closures and inheritance).
In particular, it means no slow and flaky runtime lookups. Once compiled, code guarantees that it will always call the symbol known at compile-time; runtime name lookup though does not guarantee it and can be source of hard to trace bugs.
### New stable API to create Kotlin extensions
The API is fixed and will be kept with further Lyng core changes. It is now the recommended way to write Lyng extensions in Kotlin. It is much simpler and more elegant than the internal one. See [Kotlin Bridge Binding](../notes/kotlin_bridge_binding.md).
### Smart types system
- **Deep inference**: The compiler analyzes types of symbols along the execution path and in many cases eliminates unnecessary casts or type specifications.
- **Union and intersection types**: `A & B`, `A | B`.
- **Generics**: Generic types are first-class citizens with support for [bounds and variance](generics.md). No type erasure: in a generic function you can, for example, check `A in T`, where T is the generic type.
- **Inner classes and enums**: Full support for nested declarations, including [Enums with lifting](OOP.md#lifted-enum-entries).
## Other highlights
- **The `return` Statement**: Added support for local and non-local returns using labels.
- **Abstract Classes and Interfaces**: Full support for `abstract` members and the `interface` keyword.
- **Singleton Objects**: Define singletons using the `object` keyword or use anonymous object expressions.
- **Multiple Inheritance**: Enhanced multi-inheritance with predictable [C3 MRO resolution](OOP.md#multiple-inheritance-and-mro).
- **Unified Delegation**: Powerful delegation model for `val`, `var`, and `fun` members. See [Delegation](delegation.md).
- **Class Properties with Accessors**: Define `val` and `var` properties with custom `get()` and `set()`.
- **Restricted Setter Visibility**: Use `private set` and `protected set` on fields and properties.
- **Late-initialized `val`**: Support for `val` fields that are initialized in `init` blocks or class bodies.
- **Transient Members**: Use `@Transient` to exclude members from serialization and equality checks.
- **Named Arguments and Splats**: Improved call-site readability with `name: value` and map-based splats.
- **Refined Visibility**: Improved `protected` access and `closed` modifier for better encapsulation.
## Language Features
### The `return` Statement
You can now exit from the innermost enclosing callable (function or lambda) using `return`. Lyng also supports non-local returns to outer scopes using labels. See [Return Statement](return_statement.md).
```lyng
fun findFirst<T>(list: Iterable<T>, predicate: (T)->Bool): T? {
list.forEach {
if (predicate(it)) return@findFirst it
}
null
}
```
### Abstract Classes and Interfaces
Lyng now supports the `abstract` modifier for classes and their members. `interface` is introduced as a synonym for `abstract class`, allowing for rich multi-inheritance patterns.
```lyng
interface Shape {
abstract val area: Real
fun describe() = "Area: %g"(area)
}
class Circle(val radius: Real) : Shape {
override val area get = Math.PI * radius * radius
}
```
### Class Properties with Accessors
Properties can now have custom getters and setters. They do not have automatic backing fields, making them perfect for computed values or delegation.
```lyng
class Rectangle(var width: Real, var height: Real) {
val area: Real get() = width * height
var squareSize: Real
get() = area
set(v) {
width = sqrt(v)
height = width
}
}
```
### Singleton Objects
Declare singletons or anonymous objects easily.
```lyng
object Database {
val connection = "connected"
}
val runner = object : Runnable {
override fun run() = println("Running!")
}
```
### Named Arguments and Named Splats
Improve call-site clarity by specifying argument names. You can also expand a Map into named arguments using the splat operator.
```lyng
fun configure(timeout: Int, retry: Int = 3) { ... }
configure(timeout: 5000, retry: 5)
val options = Map("timeout": 1000, "retry": 1)
configure(...options)
```
### Modern Operators
The `?=` operator allows for concise "assign if null" logic.
```lyng
var cache: Map? = null
cache ?= Map("status": "ok") // Only assigns if cache is null
```
## Tooling and IDE
- **IDEA Plugin**: Significant improvements to autocompletion, documentation tooltips, and natural language support (Grazie integration).
- **CLI**: The `lyng fmt` command is now a first-class tool for formatting code with various options like `--check` and `--in-place`.
- **Performance**: Ongoing optimizations in the bytecode VM and compiler for faster execution and smaller footprint.
## Standard Library
- **`with(self, block)`**: Scoped execution with a dedicated `self`.
- **`clamp(value, min, max)`**: Easily restrict values to a range.
## Migration Guide (from 1.3.*)
1. **Check Visibility**: Refined `protected` and `private` rules may catch previously undetected invalid accesses.
2. **Override Keyword**: Ensure all members that override ancestor declarations are marked with the `override` keyword (now mandatory).
3. **Return in Shorthand**: Remember that `return` is forbidden in `=` shorthand functions; use block syntax if you need early exit.
4. **Empty Map Literals**: Use `Map()` or `{:}` for empty maps, as `{}` is now strictly a block/lambda.
## References
- [Object Oriented Programming](OOP.md)
- [Generics](generics.md)
- [Return Statement](return_statement.md)
- [Delegation](delegation.md)
- [Tutorial](tutorial.md)
@@ -25,6 +25,7 @@ import kotlinx.coroutines.runBlocking
import net.sergeych.lyng.binding.BindingSnapshot import net.sergeych.lyng.binding.BindingSnapshot
import net.sergeych.lyng.miniast.DocLookupUtils import net.sergeych.lyng.miniast.DocLookupUtils
import net.sergeych.lyng.miniast.MiniScript import net.sergeych.lyng.miniast.MiniScript
import net.sergeych.lyng.tools.IdeLenientImportProvider
import net.sergeych.lyng.tools.LyngAnalysisRequest import net.sergeych.lyng.tools.LyngAnalysisRequest
import net.sergeych.lyng.tools.LyngAnalysisResult import net.sergeych.lyng.tools.LyngAnalysisResult
import net.sergeych.lyng.tools.LyngLanguageTools import net.sergeych.lyng.tools.LyngLanguageTools
+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.4.0-SNAPSHOT" version = "1.5.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
@@ -31,6 +31,7 @@ data class ClassDeclSpec(
val startPos: Pos, val startPos: Pos,
val isExtern: Boolean, val isExtern: Boolean,
val isAbstract: Boolean, val isAbstract: Boolean,
val isClosed: Boolean,
val isObject: Boolean, val isObject: Boolean,
val isAnonymous: Boolean, val isAnonymous: Boolean,
val baseSpecs: List<ClassDeclBaseSpec>, val baseSpecs: List<ClassDeclBaseSpec>,
@@ -118,6 +119,7 @@ internal suspend fun executeClassDecl(
val newClass = ObjInstanceClass(spec.className, *parentClasses.toTypedArray()).also { val newClass = ObjInstanceClass(spec.className, *parentClasses.toTypedArray()).also {
it.isAbstract = spec.isAbstract it.isAbstract = spec.isAbstract
it.isClosed = spec.isClosed
it.instanceConstructor = constructorCode it.instanceConstructor = constructorCode
it.constructorMeta = spec.constructorArgs it.constructorMeta = spec.constructorArgs
for (i in parentClasses.indices) { for (i in parentClasses.indices) {
@@ -2992,13 +2992,27 @@ class Compiler(
paramKnownClasses[param.name] = cls paramKnownClasses[param.name] = cls
} }
val returnLabels = label?.let { setOf(it) } ?: emptySet() val returnLabels = label?.let { setOf(it) } ?: emptySet()
val extraKnownNames = if (compileClassInfos.isEmpty()) {
paramKnownClasses
} else {
val merged = LinkedHashMap<String, ObjClass>()
for (className in compileClassInfos.keys) {
merged[className] = if (objectDeclNames.contains(className)) {
ObjDynamic.type
} else {
ObjClassType
}
}
merged.putAll(paramKnownClasses)
merged
}
val fnStatements = if (compileBytecode) { val fnStatements = if (compileBytecode) {
returnLabelStack.addLast(returnLabels) returnLabelStack.addLast(returnLabels)
try { try {
wrapFunctionBytecode( wrapFunctionBytecode(
body, body,
"<lambda>", "<lambda>",
paramKnownClasses, extraKnownNames,
forcedLocalSlots = paramSlotPlanSnapshot, forcedLocalSlots = paramSlotPlanSnapshot,
forcedLocalScopeId = paramSlotPlan.id forcedLocalScopeId = paramSlotPlan.id
) )
@@ -5331,8 +5345,8 @@ class Compiler(
val isMember = (codeContexts.lastOrNull() is CodeContext.ClassBody) val isMember = (codeContexts.lastOrNull() is CodeContext.ClassBody)
if (!isMember && isClosed) if (!isMember && isClosed && currentToken.value != "class")
throw ScriptError(currentToken.pos, "modifier closed is only allowed for class members") throw ScriptError(currentToken.pos, "modifier closed at top level is only allowed for classes")
if (!isMember && isOverride && currentToken.value != "fun" && currentToken.value != "fn") if (!isMember && isOverride && currentToken.value != "fun" && currentToken.value != "fn")
throw ScriptError(currentToken.pos, "modifier override outside class is only allowed for extension functions") throw ScriptError(currentToken.pos, "modifier override outside class is only allowed for extension functions")
@@ -5345,12 +5359,12 @@ class Compiler(
"var" -> parseVarDeclaration(true, visibility, isAbstract, isClosed, isOverride, isStatic, isExtern) "var" -> parseVarDeclaration(true, visibility, isAbstract, isClosed, isOverride, isStatic, isExtern)
"fun", "fn" -> parseFunctionDeclaration(visibility, isAbstract, isClosed, isOverride, isExtern, isStatic) "fun", "fn" -> parseFunctionDeclaration(visibility, isAbstract, isClosed, isOverride, isExtern, isStatic)
"class" -> { "class" -> {
if (isStatic || isClosed || isOverride) if (isStatic || isOverride)
throw ScriptError( throw ScriptError(
currentToken.pos, currentToken.pos,
"unsupported modifiers for class: ${modifiers.joinToString(" ")}" "unsupported modifiers for class: ${modifiers.joinToString(" ")}"
) )
parseClassDeclaration(isAbstract, isExtern) parseClassDeclaration(isAbstract, isExtern, isClosed)
} }
"object" -> { "object" -> {
@@ -5478,8 +5492,11 @@ class Compiler(
"type" -> { "type" -> {
pendingDeclStart = id.pos pendingDeclStart = id.pos
pendingDeclDoc = consumePendingDoc() pendingDeclDoc = consumePendingDoc()
if (!looksLikeTypeAliasDeclaration()) return null if (looksLikeTypeAliasDeclaration()) {
parseTypeAliasDeclaration() parseTypeAliasDeclaration()
} else {
null
}
} }
"try" -> parseTryStatement() "try" -> parseTryStatement()
@@ -6116,6 +6133,7 @@ class Compiler(
startPos = startPos, startPos = startPos,
isExtern = false, isExtern = false,
isAbstract = false, isAbstract = false,
isClosed = false,
isObject = true, isObject = true,
isAnonymous = nameToken == null, isAnonymous = nameToken == null,
baseSpecs = baseSpecs.map { ClassDeclBaseSpec(it.name, it.args) }, baseSpecs = baseSpecs.map { ClassDeclBaseSpec(it.name, it.args) },
@@ -6127,7 +6145,7 @@ class Compiler(
return ClassDeclStatement(spec) return ClassDeclStatement(spec)
} }
private suspend fun parseClassDeclaration(isAbstract: Boolean = false, isExtern: Boolean = false): Statement { private suspend fun parseClassDeclaration(isAbstract: Boolean = false, isExtern: Boolean = false, isClosed: Boolean = false): Statement {
val nameToken = cc.requireToken(Token.Type.ID) val nameToken = cc.requireToken(Token.Type.ID)
val startPos = pendingDeclStart ?: nameToken.pos val startPos = pendingDeclStart ?: nameToken.pos
val doc = pendingDeclDoc ?: consumePendingDoc() val doc = pendingDeclDoc ?: consumePendingDoc()
@@ -6474,6 +6492,7 @@ class Compiler(
startPos = startPos, startPos = startPos,
isExtern = isExtern, isExtern = isExtern,
isAbstract = isAbstract, isAbstract = isAbstract,
isClosed = isClosed,
isObject = false, isObject = false,
isAnonymous = false, isAnonymous = false,
baseSpecs = baseSpecs.map { ClassDeclBaseSpec(it.name, it.args) }, baseSpecs = baseSpecs.map { ClassDeclBaseSpec(it.name, it.args) },
@@ -1,15 +1,27 @@
/*
* 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.
*
*/
/* /*
* Kotlin bridge reflection facade: handle-based access for fast get/set/call. * Kotlin bridge reflection facade: handle-based access for fast get/set/call.
*/ */
package net.sergeych.lyng.bridge package net.sergeych.lyng.bridge
import net.sergeych.lyng.Arguments import net.sergeych.lyng.*
import net.sergeych.lyng.Pos
import net.sergeych.lyng.Scope
import net.sergeych.lyng.ScopeFacade
import net.sergeych.lyng.canAccessMember
import net.sergeych.lyng.extensionCallableName
import net.sergeych.lyng.obj.Obj import net.sergeych.lyng.obj.Obj
import net.sergeych.lyng.obj.ObjClass import net.sergeych.lyng.obj.ObjClass
import net.sergeych.lyng.obj.ObjIllegalAccessException import net.sergeych.lyng.obj.ObjIllegalAccessException
@@ -20,54 +32,85 @@ import net.sergeych.lyng.obj.ObjString
import net.sergeych.lyng.obj.ObjUnset import net.sergeych.lyng.obj.ObjUnset
import net.sergeych.lyng.obj.ObjVoid import net.sergeych.lyng.obj.ObjVoid
import net.sergeych.lyng.requireScope import net.sergeych.lyng.requireScope
import net.sergeych.lyng.ModuleScope
/** Where to resolve names from. */ /**
* Where a bridge resolver should search for names.
*
* Used by [LookupSpec] to control reflection scope for Kotlin-side tooling and bindings.
*/
enum class LookupTarget { enum class LookupTarget {
/** Resolve from the current frame only (locals/params declared in the active scope). */
CurrentFrame, CurrentFrame,
/** Resolve by walking the raw parent chain of frames (locals only, no member fallback). */
ParentChain, ParentChain,
/** Resolve against the module frame (top-level declarations in the module). */
ModuleFrame ModuleFrame
} }
/** Explicit receiver view (like this@Base). */ /**
* Explicit receiver view, similar to `this@Base` in Lyng.
*
* When provided, the resolver will treat `this` as the requested type
* for member resolution and visibility checks.
*/
data class ReceiverView( data class ReceiverView(
val type: ObjClass? = null, val type: ObjClass? = null,
val typeName: String? = null val typeName: String? = null
) )
/** Lookup rules for bridge resolution. */ /**
* Lookup rules for bridge resolution.
*
* @property targets where to resolve names from
* @property receiverView optional explicit receiver for member lookup (like `this@Base`)
*/
data class LookupSpec( data class LookupSpec(
val targets: Set<LookupTarget> = setOf(LookupTarget.CurrentFrame, LookupTarget.ModuleFrame), val targets: Set<LookupTarget> = setOf(LookupTarget.CurrentFrame, LookupTarget.ModuleFrame),
val receiverView: ReceiverView? = null val receiverView: ReceiverView? = null
) )
/** Base handle type. */ /**
* Base handle type returned by the Kotlin reflection bridge.
*
* Handles are inexpensive to keep and cache; they resolve lazily and
* may internally cache slots/records once a frame is known.
*/
sealed interface BridgeHandle { sealed interface BridgeHandle {
/** Name of the underlying symbol (as written in Lyng). */
val name: String val name: String
} }
/** Read-only value handle. */ /** Read-only value handle resolved in a [ScopeFacade]. */
interface ValHandle : BridgeHandle { interface ValHandle : BridgeHandle {
/** Read the current value. */
suspend fun get(scope: ScopeFacade): Obj suspend fun get(scope: ScopeFacade): Obj
} }
/** Read/write value handle. */ /** Read/write value handle resolved in a [ScopeFacade]. */
interface VarHandle : ValHandle { interface VarHandle : ValHandle {
/** Assign a new value. */
suspend fun set(scope: ScopeFacade, value: Obj) suspend fun set(scope: ScopeFacade, value: Obj)
} }
/** Callable handle (function/closure/method). */ /** Callable handle (function/closure/method). */
interface CallableHandle : BridgeHandle { interface CallableHandle : BridgeHandle {
/**
* Call the target with optional [args].
*
* @param newThisObj overrides receiver for member calls (defaults to current `this`/record receiver).
*/
suspend fun call(scope: ScopeFacade, args: Arguments = Arguments.EMPTY, newThisObj: Obj? = null): Obj suspend fun call(scope: ScopeFacade, args: Arguments = Arguments.EMPTY, newThisObj: Obj? = null): Obj
} }
/** Member handle resolved against an instance or receiver view. */ /** Member handle resolved against an instance or receiver view. */
interface MemberHandle : BridgeHandle { interface MemberHandle : BridgeHandle {
/** Declaring class resolved for the last call/get/set (if known). */
val declaringClass: ObjClass? val declaringClass: ObjClass?
/** Explicit receiver view used for resolution (if any). */
val receiverView: ReceiverView? val receiverView: ReceiverView?
} }
/** Member field/property. */ /** Member field/property (read-only). */
interface MemberValHandle : MemberHandle, ValHandle interface MemberValHandle : MemberHandle, ValHandle
/** Member var/property with write access. */ /** Member var/property with write access. */
@@ -76,41 +119,64 @@ interface MemberVarHandle : MemberHandle, VarHandle
/** Member callable (method or extension). */ /** Member callable (method or extension). */
interface MemberCallableHandle : MemberHandle, CallableHandle interface MemberCallableHandle : MemberHandle, CallableHandle
/** Direct record handle (debug/inspection). */ /**
* Direct record handle (debug/inspection).
*
* Exposes raw [ObjRecord] access and should be used only in tooling.
*/
interface RecordHandle : BridgeHandle { interface RecordHandle : BridgeHandle {
/** Resolve and return the raw [ObjRecord]. */
fun record(): ObjRecord fun record(): ObjRecord
} }
/** Bridge resolver API (entry point for Kotlin bindings). */ /**
* Bridge resolver API (entry point for Kotlin reflection and bindings).
*
* Obtain via [ScopeFacade.resolver] and reuse for multiple lookups.
* Resolver methods return handles that can be cached and reused across calls.
*/
interface BridgeResolver { interface BridgeResolver {
/** Source position used for error reporting. */
val pos: Pos val pos: Pos
/** Treat `this` as [type] for member lookup (like `this@Type`). */
fun selfAs(type: ObjClass): BridgeResolver fun selfAs(type: ObjClass): BridgeResolver
/** Treat `this` as [typeName] for member lookup (like `this@Type`). */
fun selfAs(typeName: String): BridgeResolver fun selfAs(typeName: String): BridgeResolver
/** Resolve a read-only value by name using [lookup]. */
fun resolveVal(name: String, lookup: LookupSpec = LookupSpec()): ValHandle fun resolveVal(name: String, lookup: LookupSpec = LookupSpec()): ValHandle
/** Resolve a mutable value by name using [lookup]. */
fun resolveVar(name: String, lookup: LookupSpec = LookupSpec()): VarHandle fun resolveVar(name: String, lookup: LookupSpec = LookupSpec()): VarHandle
/** Resolve a callable by name using [lookup]. */
fun resolveCallable(name: String, lookup: LookupSpec = LookupSpec()): CallableHandle fun resolveCallable(name: String, lookup: LookupSpec = LookupSpec()): CallableHandle
/** Resolve a member value on [receiver]. */
fun resolveMemberVal( fun resolveMemberVal(
receiver: Obj, receiver: Obj,
name: String, name: String,
lookup: LookupSpec = LookupSpec() lookup: LookupSpec = LookupSpec()
): MemberValHandle ): MemberValHandle
/** Resolve a mutable member on [receiver]. */
fun resolveMemberVar( fun resolveMemberVar(
receiver: Obj, receiver: Obj,
name: String, name: String,
lookup: LookupSpec = LookupSpec() lookup: LookupSpec = LookupSpec()
): MemberVarHandle ): MemberVarHandle
/** Resolve a member callable on [receiver]. */
fun resolveMemberCallable( fun resolveMemberCallable(
receiver: Obj, receiver: Obj,
name: String, name: String,
lookup: LookupSpec = LookupSpec() lookup: LookupSpec = LookupSpec()
): MemberCallableHandle ): MemberCallableHandle
/** Extension function treated as a member for reflection. */ /**
* Resolve an extension function treated as a member for reflection.
*
* This uses the extension wrapper name (same rules as Lyng compiler).
*/
fun resolveExtensionCallable( fun resolveExtensionCallable(
receiverClass: ObjClass, receiverClass: ObjClass,
name: String, name: String,
@@ -119,14 +185,20 @@ interface BridgeResolver {
/** Debug: resolve locals by name (optional, for tooling). */ /** Debug: resolve locals by name (optional, for tooling). */
fun resolveLocalVal(name: String): ValHandle fun resolveLocalVal(name: String): ValHandle
/** Debug: resolve mutable locals by name (optional, for tooling). */
fun resolveLocalVar(name: String): VarHandle fun resolveLocalVar(name: String): VarHandle
/** Debug: access raw record handles if needed. */ /** Debug: access raw record handles if needed. */
fun resolveRecord(name: String, lookup: LookupSpec = LookupSpec()): RecordHandle fun resolveRecord(name: String, lookup: LookupSpec = LookupSpec()): RecordHandle
} }
/** Convenience: call by name with implicit caching in resolver implementation. */ /**
* Convenience: call by name with implicit caching in resolver implementation.
*
* Implemented by the default resolver; useful for lightweight call-by-name flows.
*/
interface BridgeCallByName { interface BridgeCallByName {
/** Resolve and call [name] with [args] using [lookup]. */
suspend fun callByName( suspend fun callByName(
scope: ScopeFacade, scope: ScopeFacade,
name: String, name: String,
@@ -135,12 +207,21 @@ interface BridgeCallByName {
): Obj ): Obj
} }
/** Optional typed wrappers (sugar). */ /**
* Optional typed wrapper (sugar) around [ValHandle].
*
* Performs a runtime cast to [T] and raises a class cast error on mismatch.
*/
interface TypedHandle<T : Obj> : ValHandle { interface TypedHandle<T : Obj> : ValHandle {
/** Read value and cast it to [T]. */
suspend fun getTyped(scope: ScopeFacade): T suspend fun getTyped(scope: ScopeFacade): T
} }
/** Factory for bridge resolver. */ /**
* Factory for bridge resolver.
*
* Prefer this over ad-hoc lookups when writing Kotlin extensions or tooling.
*/
fun ScopeFacade.resolver(): BridgeResolver = BridgeResolverImpl(this) fun ScopeFacade.resolver(): BridgeResolver = BridgeResolverImpl(this)
private class BridgeResolverImpl( private class BridgeResolverImpl(
@@ -1,13 +1,28 @@
/*
* 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.
*
*/
/* /*
* Kotlin bridge bindings for Lyng classes (Lyng-first workflow). * Kotlin bridge bindings for Lyng classes (Lyng-first workflow).
*/ */
package net.sergeych.lyng.bridge package net.sergeych.lyng.bridge
import net.sergeych.lyng.Arguments import net.sergeych.lyng.*
import net.sergeych.lyng.Pos import net.sergeych.lyng.bytecode.BytecodeStatement
import net.sergeych.lyng.ScopeFacade
import net.sergeych.lyng.Script
import net.sergeych.lyng.obj.Obj import net.sergeych.lyng.obj.Obj
import net.sergeych.lyng.obj.ObjClass import net.sergeych.lyng.obj.ObjClass
import net.sergeych.lyng.obj.ObjExternCallable import net.sergeych.lyng.obj.ObjExternCallable
@@ -16,24 +31,41 @@ import net.sergeych.lyng.obj.ObjProperty
import net.sergeych.lyng.obj.ObjRecord import net.sergeych.lyng.obj.ObjRecord
import net.sergeych.lyng.obj.ObjVoid import net.sergeych.lyng.obj.ObjVoid
import net.sergeych.lyng.pacman.ImportManager import net.sergeych.lyng.pacman.ImportManager
import net.sergeych.lyng.ModuleScope
import net.sergeych.lyng.ScriptError
import net.sergeych.lyng.requiredArg import net.sergeych.lyng.requiredArg
import net.sergeych.lyng.InstanceFieldInitStatement
import net.sergeych.lyng.Statement
import net.sergeych.lyng.bytecode.BytecodeStatement
/**
* Per-instance bridge context passed to init hooks.
*
* Exposes the underlying [instance] and a mutable [data] slot for Kotlin-side state.
*/
interface BridgeInstanceContext { interface BridgeInstanceContext {
/** The Lyng instance being initialized. */
val instance: Obj val instance: Obj
/** Arbitrary Kotlin-side data attached to the instance. */
var data: Any? var data: Any?
} }
/**
* Binder DSL for attaching Kotlin implementations to a declared Lyng class.
*
* Use [LyngClassBridge.bind] to obtain a binder and register implementations.
* Bindings must happen before the first instance of the class is created.
*
* Important: members you bind here must be declared as `extern` in Lyng so the
* compiler emits the ABI slots that Kotlin bindings attach to.
*/
interface ClassBridgeBinder { interface ClassBridgeBinder {
/** Arbitrary Kotlin-side data attached to the class. */
var classData: Any? var classData: Any?
/** Register an initialization hook that runs for each instance. */
fun init(block: suspend BridgeInstanceContext.(ScopeFacade) -> Unit) fun init(block: suspend BridgeInstanceContext.(ScopeFacade) -> Unit)
/** Register an initialization hook with direct access to the instance. */
fun initWithInstance(block: suspend (ScopeFacade, Obj) -> Unit) fun initWithInstance(block: suspend (ScopeFacade, Obj) -> Unit)
/** Bind a Lyng function/member to a Kotlin implementation (requires `extern` in Lyng). */
fun addFun(name: String, impl: suspend (ScopeFacade, Obj, Arguments) -> Obj) fun addFun(name: String, impl: suspend (ScopeFacade, Obj, Arguments) -> Obj)
/** Bind a read-only member (val/property getter) declared as `extern`. */
fun addVal(name: String, impl: suspend (ScopeFacade, Obj) -> Obj) fun addVal(name: String, impl: suspend (ScopeFacade, Obj) -> Obj)
/** Bind a mutable member (var/property getter/setter) declared as `extern`. */
fun addVar( fun addVar(
name: String, name: String,
get: suspend (ScopeFacade, Obj) -> Obj, get: suspend (ScopeFacade, Obj) -> Obj,
@@ -41,7 +73,20 @@ interface ClassBridgeBinder {
) )
} }
/**
* Entry point for Kotlin bindings to declared Lyng classes.
*
* The workflow is Lyng-first: declare the class and its members in Lyng,
* then bind the implementations from Kotlin. Bound members must be marked
* `extern` so the compiler emits the ABI slots for Kotlin to attach to.
*/
object LyngClassBridge { object LyngClassBridge {
/**
* Resolve a Lyng class by [className] and bind Kotlin implementations.
*
* @param module module name used for resolution (required when [module] scope is not provided)
* @param importManager import manager used to resolve the module
*/
suspend fun bind( suspend fun bind(
className: String, className: String,
module: String? = null, module: String? = null,
@@ -52,6 +97,9 @@ object LyngClassBridge {
return bind(cls, block) return bind(cls, block)
} }
/**
* Resolve a Lyng class within an existing [moduleScope] and bind Kotlin implementations.
*/
suspend fun bind( suspend fun bind(
moduleScope: ModuleScope, moduleScope: ModuleScope,
className: String, className: String,
@@ -61,6 +109,11 @@ object LyngClassBridge {
return bind(cls, block) return bind(cls, block)
} }
/**
* Bind Kotlin implementations to an already resolved [clazz].
*
* This must run before the first instance is created.
*/
fun bind(clazz: ObjClass, block: ClassBridgeBinder.() -> Unit): ObjClass { fun bind(clazz: ObjClass, block: ClassBridgeBinder.() -> Unit): ObjClass {
val binder = ClassBridgeBinderImpl(clazz) val binder = ClassBridgeBinderImpl(clazz)
binder.block() binder.block()
@@ -69,10 +122,22 @@ object LyngClassBridge {
} }
} }
/**
* Sugar for [LyngClassBridge.bind] on a module scope.
*
* Bound members must be declared as `extern` in Lyng.
*/
suspend fun ModuleScope.bind(
className: String,
block: ClassBridgeBinder.() -> Unit
): ObjClass = LyngClassBridge.bind(this, className, block)
/** Kotlin-side data slot attached to a Lyng instance. */
var ObjInstance.data: Any? var ObjInstance.data: Any?
get() = kotlinInstanceData get() = kotlinInstanceData
set(value) { kotlinInstanceData = value } set(value) { kotlinInstanceData = value }
/** Kotlin-side data slot attached to a Lyng class. */
var ObjClass.classData: Any? var ObjClass.classData: Any?
get() = kotlinClassData get() = kotlinClassData
set(value) { kotlinClassData = value } set(value) { kotlinClassData = value }
@@ -86,6 +86,7 @@ class BytecodeCompiler(
private val loopVarSlots = HashSet<Int>() private val loopVarSlots = HashSet<Int>()
private val loopStack = ArrayDeque<LoopContext>() private val loopStack = ArrayDeque<LoopContext>()
private var currentPos: Pos? = null private var currentPos: Pos? = null
private var cachedVoidSlot: Int? = null
private data class LoopContext( private data class LoopContext(
val label: String?, val label: String?,
@@ -1141,7 +1142,11 @@ class BytecodeCompiler(
): CompiledValue? { ): CompiledValue? {
val memberName = operatorMemberName(op) ?: return null val memberName = operatorMemberName(op) ?: return null
val receiverClass = resolveReceiverClass(leftRef) val receiverClass = resolveReceiverClass(leftRef)
if (receiverClass == null) { if (receiverClass == null ||
receiverClass.className == "Delegate" ||
receiverClass.className == "LazyDelegate" ||
receiverClass.implementingNames.contains("Delegate")
) {
val objOpcode = when (op) { val objOpcode = when (op) {
BinOp.PLUS -> Opcode.ADD_OBJ BinOp.PLUS -> Opcode.ADD_OBJ
BinOp.MINUS -> Opcode.SUB_OBJ BinOp.MINUS -> Opcode.SUB_OBJ
@@ -1374,23 +1379,6 @@ class BytecodeCompiler(
val rightRef = binaryRight(ref) val rightRef = binaryRight(ref)
var a = compileRefWithFallback(leftRef, null, refPos(ref)) ?: return null var a = compileRefWithFallback(leftRef, null, refPos(ref)) ?: return null
var b = compileRefWithFallback(rightRef, null, refPos(ref)) ?: return null var b = compileRefWithFallback(rightRef, null, refPos(ref)) ?: return null
if (op in setOf(BinOp.PLUS, BinOp.MINUS, BinOp.STAR, BinOp.SLASH, BinOp.PERCENT)) {
val leftNeedsObj = a.type == SlotType.INT && b.type == SlotType.REAL
val rightNeedsObj = b.type == SlotType.INT && a.type == SlotType.REAL
if (leftNeedsObj || rightNeedsObj) {
val leftObj = if (leftNeedsObj) {
compileScopeSlotObj(leftRef) ?: a
} else {
a
}
val rightObj = if (rightNeedsObj) {
compileScopeSlotObj(rightRef) ?: b
} else {
b
}
return compileObjBinaryOp(leftRef, leftObj, rightObj, op, refPos(ref))
}
}
val intOps = setOf( val intOps = setOf(
BinOp.PLUS, BinOp.MINUS, BinOp.STAR, BinOp.SLASH, BinOp.PERCENT, BinOp.PLUS, BinOp.MINUS, BinOp.STAR, BinOp.SLASH, BinOp.PERCENT,
BinOp.BAND, BinOp.BOR, BinOp.BXOR, BinOp.SHL, BinOp.SHR BinOp.BAND, BinOp.BOR, BinOp.BXOR, BinOp.SHL, BinOp.SHR
@@ -1413,7 +1401,11 @@ class BytecodeCompiler(
} }
val typesMismatch = a.type != b.type && a.type != SlotType.UNKNOWN && b.type != SlotType.UNKNOWN val typesMismatch = a.type != b.type && a.type != SlotType.UNKNOWN && b.type != SlotType.UNKNOWN
val allowMixedNumeric = op in setOf(BinOp.PLUS, BinOp.MINUS, BinOp.STAR, BinOp.SLASH) val allowMixedNumeric = op in setOf(BinOp.PLUS, BinOp.MINUS, BinOp.STAR, BinOp.SLASH)
if (typesMismatch && op in setOf(BinOp.PLUS, BinOp.MINUS, BinOp.STAR, BinOp.SLASH, BinOp.PERCENT)) { val isMixedNumeric = (a.type == SlotType.INT && b.type == SlotType.REAL) ||
(a.type == SlotType.REAL && b.type == SlotType.INT)
if (typesMismatch && op in setOf(BinOp.PLUS, BinOp.MINUS, BinOp.STAR, BinOp.SLASH, BinOp.PERCENT) &&
!(allowMixedNumeric && isMixedNumeric)
) {
return compileObjBinaryOp(leftRef, a, b, op, refPos(ref)) return compileObjBinaryOp(leftRef, a, b, op, refPos(ref))
} }
if ((a.type == SlotType.UNKNOWN || b.type == SlotType.UNKNOWN) && if ((a.type == SlotType.UNKNOWN || b.type == SlotType.UNKNOWN) &&
@@ -1683,12 +1675,12 @@ class BytecodeCompiler(
val left = ensureObjSlot(a) val left = ensureObjSlot(a)
val right = ensureObjSlot(b) val right = ensureObjSlot(b)
val opcode = when { val opcode = when {
isExactNonNullSlotClass(left.slot, ObjString.type) && isExactNonNullSlotClassOrTemp(left.slot, ObjString.type) &&
isExactNonNullSlotClass(right.slot, ObjString.type) -> stringOp isExactNonNullSlotClassOrTemp(right.slot, ObjString.type) -> stringOp
isExactNonNullSlotClass(left.slot, ObjInt.type) && isExactNonNullSlotClassOrTemp(left.slot, ObjInt.type) &&
isExactNonNullSlotClass(right.slot, ObjInt.type) -> intOp isExactNonNullSlotClassOrTemp(right.slot, ObjInt.type) -> intOp
isExactNonNullSlotClass(left.slot, ObjReal.type) && isExactNonNullSlotClassOrTemp(left.slot, ObjReal.type) &&
isExactNonNullSlotClass(right.slot, ObjReal.type) -> realOp isExactNonNullSlotClassOrTemp(right.slot, ObjReal.type) -> realOp
else -> objOp else -> objOp
} }
builder.emit(opcode, left.slot, right.slot, out) builder.emit(opcode, left.slot, right.slot, out)
@@ -2352,60 +2344,36 @@ class BytecodeCompiler(
private fun compileLogicalAnd(ref: LogicalAndRef): CompiledValue? { private fun compileLogicalAnd(ref: LogicalAndRef): CompiledValue? {
val leftValue = compileRefWithFallback(ref.left(), SlotType.BOOL, Pos.builtIn) ?: return null val leftValue = compileRefWithFallback(ref.left(), SlotType.BOOL, Pos.builtIn) ?: return null
val leftBool = if (leftValue.type == SlotType.BOOL) { if (leftValue.type != SlotType.BOOL) return null
leftValue
} else {
val slot = allocSlot()
builder.emit(Opcode.OBJ_TO_BOOL, leftValue.slot, slot)
CompiledValue(slot, SlotType.BOOL)
}
val resultSlot = allocSlot() val resultSlot = allocSlot()
val falseId = builder.addConst(BytecodeConst.Bool(false)) val falseId = builder.addConst(BytecodeConst.Bool(false))
builder.emit(Opcode.CONST_BOOL, falseId, resultSlot) builder.emit(Opcode.CONST_BOOL, falseId, resultSlot)
val endLabel = builder.label() val endLabel = builder.label()
builder.emit( builder.emit(
Opcode.JMP_IF_FALSE, Opcode.JMP_IF_FALSE,
listOf(CmdBuilder.Operand.IntVal(leftBool.slot), CmdBuilder.Operand.LabelRef(endLabel)) listOf(CmdBuilder.Operand.IntVal(leftValue.slot), CmdBuilder.Operand.LabelRef(endLabel))
) )
val rightValue = compileRefWithFallback(ref.right(), SlotType.BOOL, Pos.builtIn) ?: return null val rightValue = compileRefWithFallback(ref.right(), SlotType.BOOL, Pos.builtIn) ?: return null
val rightBool = if (rightValue.type == SlotType.BOOL) { if (rightValue.type != SlotType.BOOL) return null
rightValue builder.emit(Opcode.MOVE_BOOL, rightValue.slot, resultSlot)
} else {
val slot = allocSlot()
builder.emit(Opcode.OBJ_TO_BOOL, rightValue.slot, slot)
CompiledValue(slot, SlotType.BOOL)
}
builder.emit(Opcode.MOVE_BOOL, rightBool.slot, resultSlot)
builder.mark(endLabel) builder.mark(endLabel)
return CompiledValue(resultSlot, SlotType.BOOL) return CompiledValue(resultSlot, SlotType.BOOL)
} }
private fun compileLogicalOr(ref: LogicalOrRef): CompiledValue? { private fun compileLogicalOr(ref: LogicalOrRef): CompiledValue? {
val leftValue = compileRefWithFallback(ref.left(), SlotType.BOOL, Pos.builtIn) ?: return null val leftValue = compileRefWithFallback(ref.left(), SlotType.BOOL, Pos.builtIn) ?: return null
val leftBool = if (leftValue.type == SlotType.BOOL) { if (leftValue.type != SlotType.BOOL) return null
leftValue
} else {
val slot = allocSlot()
builder.emit(Opcode.OBJ_TO_BOOL, leftValue.slot, slot)
CompiledValue(slot, SlotType.BOOL)
}
val resultSlot = allocSlot() val resultSlot = allocSlot()
val trueId = builder.addConst(BytecodeConst.Bool(true)) val trueId = builder.addConst(BytecodeConst.Bool(true))
builder.emit(Opcode.CONST_BOOL, trueId, resultSlot) builder.emit(Opcode.CONST_BOOL, trueId, resultSlot)
val endLabel = builder.label() val endLabel = builder.label()
builder.emit( builder.emit(
Opcode.JMP_IF_TRUE, Opcode.JMP_IF_TRUE,
listOf(CmdBuilder.Operand.IntVal(leftBool.slot), CmdBuilder.Operand.LabelRef(endLabel)) listOf(CmdBuilder.Operand.IntVal(leftValue.slot), CmdBuilder.Operand.LabelRef(endLabel))
) )
val rightValue = compileRefWithFallback(ref.right(), SlotType.BOOL, Pos.builtIn) ?: return null val rightValue = compileRefWithFallback(ref.right(), SlotType.BOOL, Pos.builtIn) ?: return null
val rightBool = if (rightValue.type == SlotType.BOOL) { if (rightValue.type != SlotType.BOOL) return null
rightValue builder.emit(Opcode.MOVE_BOOL, rightValue.slot, resultSlot)
} else {
val slot = allocSlot()
builder.emit(Opcode.OBJ_TO_BOOL, rightValue.slot, slot)
CompiledValue(slot, SlotType.BOOL)
}
builder.emit(Opcode.MOVE_BOOL, rightBool.slot, resultSlot)
builder.mark(endLabel) builder.mark(endLabel)
return CompiledValue(resultSlot, SlotType.BOOL) return CompiledValue(resultSlot, SlotType.BOOL)
} }
@@ -2553,7 +2521,9 @@ class BytecodeCompiler(
} }
return value return value
} }
if (isKnownClassReceiver(target.target)) { if ((isKnownClassReceiver(target.target) || isClassNameRef(target.target, receiverClass)) &&
(isClassSlot(receiver.slot) || receiverClass == ObjClassType)
) {
val nameId = builder.addConst(BytecodeConst.StringVal(target.name)) val nameId = builder.addConst(BytecodeConst.StringVal(target.name))
if (!target.isOptional) { if (!target.isOptional) {
builder.emit(Opcode.SET_CLASS_SCOPE, receiver.slot, nameId, value.slot) builder.emit(Opcode.SET_CLASS_SCOPE, receiver.slot, nameId, value.slot)
@@ -2902,7 +2872,7 @@ class BytecodeCompiler(
} }
val fieldId = if (resolvedMember != null) receiverClass.instanceFieldIdMap()[fieldTarget.name] else null val fieldId = if (resolvedMember != null) receiverClass.instanceFieldIdMap()[fieldTarget.name] else null
val methodId = if (resolvedMember != null) receiverClass.instanceMethodIdMap(includeAbstract = true)[fieldTarget.name] else null val methodId = if (resolvedMember != null) receiverClass.instanceMethodIdMap(includeAbstract = true)[fieldTarget.name] else null
if (fieldId == null && methodId == null && isKnownClassReceiver(fieldTarget.target)) { if (fieldId == null && methodId == null && (receiverClass == ObjClassType || isKnownClassReceiver(fieldTarget.target) || isClassNameRef(fieldTarget.target, receiverClass))) {
val nameId = builder.addConst(BytecodeConst.StringVal(fieldTarget.name)) val nameId = builder.addConst(BytecodeConst.StringVal(fieldTarget.name))
if (!fieldTarget.isOptional) { if (!fieldTarget.isOptional) {
builder.emit(Opcode.GET_CLASS_SCOPE, receiver.slot, nameId, current) builder.emit(Opcode.GET_CLASS_SCOPE, receiver.slot, nameId, current)
@@ -3295,6 +3265,9 @@ class BytecodeCompiler(
} }
private fun compileFieldRef(ref: FieldRef): CompiledValue? { private fun compileFieldRef(ref: FieldRef): CompiledValue? {
if (ref.name.isBlank()) {
return compileRefWithFallback(ref.target, null, Pos.builtIn)
}
val receiverClass = resolveReceiverClass(ref.target) ?: ObjDynamic.type val receiverClass = resolveReceiverClass(ref.target) ?: ObjDynamic.type
if (receiverClass == ObjDynamic.type) { if (receiverClass == ObjDynamic.type) {
val receiver = compileRefWithFallback(ref.target, null, Pos.builtIn) ?: return null val receiver = compileRefWithFallback(ref.target, null, Pos.builtIn) ?: return null
@@ -3381,7 +3354,9 @@ class BytecodeCompiler(
val encodedMethodId = encodeMemberId(receiverClass, methodId) val encodedMethodId = encodeMemberId(receiverClass, methodId)
val receiver = compileRefWithFallback(ref.target, null, Pos.builtIn) ?: return null val receiver = compileRefWithFallback(ref.target, null, Pos.builtIn) ?: return null
val dst = allocSlot() val dst = allocSlot()
if (fieldId == null && methodId == null && isKnownClassReceiver(ref.target)) { if (fieldId == null && methodId == null && (isKnownClassReceiver(ref.target) || isClassNameRef(ref.target, receiverClass)) &&
(isClassSlot(receiver.slot) || receiverClass == ObjClassType)
) {
val nameId = builder.addConst(BytecodeConst.StringVal(ref.name)) val nameId = builder.addConst(BytecodeConst.StringVal(ref.name))
if (!ref.isOptional) { if (!ref.isOptional) {
builder.emit(Opcode.GET_CLASS_SCOPE, receiver.slot, nameId, dst) builder.emit(Opcode.GET_CLASS_SCOPE, receiver.slot, nameId, dst)
@@ -3569,6 +3544,11 @@ class BytecodeCompiler(
val elementClass = listElementClassBySlot[receiver.slot] ?: listElementClassFromReceiverRef(ref.targetRef) val elementClass = listElementClassBySlot[receiver.slot] ?: listElementClassFromReceiverRef(ref.targetRef)
if (elementClass != null) { if (elementClass != null) {
slotObjClass[dst] = elementClass slotObjClass[dst] = elementClass
if (elementClass == ObjString.type && elementClass.isClosed) {
stableObjSlots.add(dst)
} else {
stableObjSlots.remove(dst)
}
} }
return CompiledValue(dst, SlotType.OBJ) return CompiledValue(dst, SlotType.OBJ)
} }
@@ -3635,6 +3615,12 @@ class BytecodeCompiler(
} }
SlotType.OBJ -> { SlotType.OBJ -> {
if (objOp == null) return null if (objOp == null) return null
if (isExactNonNullSlotClassOrTemp(rhs.slot, ObjInt.type)) {
val right = allocSlot()
builder.emit(Opcode.UNBOX_INT_OBJ, rhs.slot, right)
builder.emit(intOp, out, right, out)
return CompiledValue(out, SlotType.INT)
}
val leftObj = allocSlot() val leftObj = allocSlot()
builder.emit(Opcode.BOX_OBJ, out, leftObj) builder.emit(Opcode.BOX_OBJ, out, leftObj)
updateSlotType(leftObj, SlotType.OBJ) updateSlotType(leftObj, SlotType.OBJ)
@@ -3660,6 +3646,12 @@ class BytecodeCompiler(
} }
SlotType.OBJ -> { SlotType.OBJ -> {
if (objOp == null) return null if (objOp == null) return null
if (isExactNonNullSlotClassOrTemp(rhs.slot, ObjReal.type)) {
val right = allocSlot()
builder.emit(Opcode.UNBOX_REAL_OBJ, rhs.slot, right)
builder.emit(realOp, out, right, out)
return CompiledValue(out, SlotType.REAL)
}
val leftObj = allocSlot() val leftObj = allocSlot()
builder.emit(Opcode.BOX_OBJ, out, leftObj) builder.emit(Opcode.BOX_OBJ, out, leftObj)
updateSlotType(leftObj, SlotType.OBJ) updateSlotType(leftObj, SlotType.OBJ)
@@ -3958,8 +3950,8 @@ class BytecodeCompiler(
"Member access requires compile-time receiver type: ${fieldTarget.name}", "Member access requires compile-time receiver type: ${fieldTarget.name}",
Pos.builtIn Pos.builtIn
) )
if (receiverClass == ObjDynamic.type) {
val receiver = compileRefWithFallback(fieldTarget.target, null, Pos.builtIn) ?: return null val receiver = compileRefWithFallback(fieldTarget.target, null, Pos.builtIn) ?: return null
if (receiverClass == ObjDynamic.type) {
val nameId = builder.addConst(BytecodeConst.StringVal(fieldTarget.name)) val nameId = builder.addConst(BytecodeConst.StringVal(fieldTarget.name))
val resultSlot = allocSlot() val resultSlot = allocSlot()
if (fieldTarget.isOptional) { if (fieldTarget.isOptional) {
@@ -4024,8 +4016,9 @@ class BytecodeCompiler(
} }
val fieldId = receiverClass.instanceFieldIdMap()[fieldTarget.name] val fieldId = receiverClass.instanceFieldIdMap()[fieldTarget.name]
val methodId = receiverClass.instanceMethodIdMap(includeAbstract = true)[fieldTarget.name] val methodId = receiverClass.instanceMethodIdMap(includeAbstract = true)[fieldTarget.name]
if (fieldId == null && methodId == null && isKnownClassReceiver(fieldTarget.target)) { if (fieldId == null && methodId == null && (isKnownClassReceiver(fieldTarget.target) || isClassNameRef(fieldTarget.target, receiverClass)) &&
val receiver = compileRefWithFallback(fieldTarget.target, null, Pos.builtIn) ?: return null (isClassSlot(receiver.slot) || receiverClass == ObjClassType)
) {
val nameId = builder.addConst(BytecodeConst.StringVal(fieldTarget.name)) val nameId = builder.addConst(BytecodeConst.StringVal(fieldTarget.name))
val resultSlot = allocSlot() val resultSlot = allocSlot()
if (fieldTarget.isOptional) { if (fieldTarget.isOptional) {
@@ -4089,7 +4082,6 @@ class BytecodeCompiler(
return CompiledValue(resultSlot, SlotType.OBJ) return CompiledValue(resultSlot, SlotType.OBJ)
} }
if (fieldId == null && methodId == null) return null if (fieldId == null && methodId == null) return null
val receiver = compileRefWithFallback(fieldTarget.target, null, Pos.builtIn) ?: return null
val resultSlot = allocSlot() val resultSlot = allocSlot()
if (fieldTarget.isOptional) { if (fieldTarget.isOptional) {
val nullSlot = allocSlot() val nullSlot = allocSlot()
@@ -5126,6 +5118,7 @@ class BytecodeCompiler(
} ?: allocSlot() } ?: allocSlot()
builder.emit(Opcode.DECL_CLASS, constId, dst) builder.emit(Opcode.DECL_CLASS, constId, dst)
updateSlotType(dst, SlotType.OBJ) updateSlotType(dst, SlotType.OBJ)
slotObjClass[dst] = if (stmt.spec.isObject) ObjDynamic.type else ObjClassType
stmt.spec.declaredName?.let { updateNameObjClassFromSlot(it, dst) } stmt.spec.declaredName?.let { updateNameObjClassFromSlot(it, dst) }
return CompiledValue(dst, SlotType.OBJ) return CompiledValue(dst, SlotType.OBJ)
} }
@@ -5660,6 +5653,17 @@ class BytecodeCompiler(
private fun emitInlineBlock(stmt: BlockStatement, needResult: Boolean): CompiledValue? = private fun emitInlineBlock(stmt: BlockStatement, needResult: Boolean): CompiledValue? =
emitInlineStatements(stmt.statements(), needResult) emitInlineStatements(stmt.statements(), needResult)
private fun ensureVoidSlot(): Int {
val existing = cachedVoidSlot
if (existing != null) return existing
val slot = allocSlot()
val voidId = builder.addConst(BytecodeConst.ObjRef(ObjVoid))
builder.emit(Opcode.CONST_OBJ, voidId, slot)
updateSlotType(slot, SlotType.OBJ)
cachedVoidSlot = slot
return slot
}
private fun shouldInlineBlock(stmt: BlockStatement): Boolean { private fun shouldInlineBlock(stmt: BlockStatement): Boolean {
return allowLocalSlots return allowLocalSlots
} }
@@ -6002,6 +6006,11 @@ class BytecodeCompiler(
try { try {
val needsBreakFlag = stmt.canBreak || stmt.elseStatement != null val needsBreakFlag = stmt.canBreak || stmt.elseStatement != null
val realWidenSlots = collectLoopRealWidenSlots(stmt.body)
val hasRealWiden = realWidenSlots.isNotEmpty()
if (hasRealWiden) {
applySlotTypes(realWidenSlots, SlotType.REAL)
}
val breakFlagSlot = allocSlot() val breakFlagSlot = allocSlot()
if (range == null && rangeRef == null && typedRangeLocal == null) { if (range == null && rangeRef == null && typedRangeLocal == null) {
val sourceValue = compileStatementValueOrFallback(stmt.source) ?: return null val sourceValue = compileStatementValueOrFallback(stmt.source) ?: return null
@@ -6075,12 +6084,18 @@ class BytecodeCompiler(
) )
) )
val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null
if (hasRealWiden) {
applySlotTypes(realWidenSlots, SlotType.UNKNOWN)
}
loopStack.removeLast() loopStack.removeLast()
if (wantResult) { if (wantResult) {
val bodyObj = ensureObjSlot(bodyValue) val bodyObj = ensureObjSlot(bodyValue)
builder.emit(Opcode.MOVE_OBJ, bodyObj.slot, resultSlot!!) builder.emit(Opcode.MOVE_OBJ, bodyObj.slot, resultSlot!!)
} }
builder.mark(continueLabel) builder.mark(continueLabel)
if (hasRealWiden) {
emitLoopRealCoercions(realWidenSlots)
}
builder.emit(Opcode.JMP, listOf(CmdBuilder.Operand.LabelRef(loopLabel))) builder.emit(Opcode.JMP, listOf(CmdBuilder.Operand.LabelRef(loopLabel)))
builder.mark(endLabel) builder.mark(endLabel)
@@ -6188,6 +6203,9 @@ class BytecodeCompiler(
) )
) )
val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null
if (hasRealWiden) {
applySlotTypes(realWidenSlots, SlotType.UNKNOWN)
}
loopStack.removeLast() loopStack.removeLast()
if (wantResult) { if (wantResult) {
val bodyObj = ensureObjSlot(bodyValue) val bodyObj = ensureObjSlot(bodyValue)
@@ -6195,6 +6213,9 @@ class BytecodeCompiler(
} }
builder.mark(continueLabel) builder.mark(continueLabel)
builder.emit(Opcode.INC_INT, iSlot) builder.emit(Opcode.INC_INT, iSlot)
if (hasRealWiden) {
emitLoopRealCoercions(realWidenSlots)
}
builder.emit(Opcode.JMP, listOf(CmdBuilder.Operand.LabelRef(loopLabel))) builder.emit(Opcode.JMP, listOf(CmdBuilder.Operand.LabelRef(loopLabel)))
builder.mark(endLabel) builder.mark(endLabel)
@@ -6265,6 +6286,9 @@ class BytecodeCompiler(
) )
) )
val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null
if (hasRealWiden) {
applySlotTypes(realWidenSlots, SlotType.UNKNOWN)
}
loopStack.removeLast() loopStack.removeLast()
if (wantResult) { if (wantResult) {
val bodyObj = ensureObjSlot(bodyValue) val bodyObj = ensureObjSlot(bodyValue)
@@ -6272,6 +6296,9 @@ class BytecodeCompiler(
} }
builder.mark(continueLabel) builder.mark(continueLabel)
builder.emit(Opcode.INC_INT, iSlot) builder.emit(Opcode.INC_INT, iSlot)
if (hasRealWiden) {
emitLoopRealCoercions(realWidenSlots)
}
builder.emit(Opcode.JMP, listOf(CmdBuilder.Operand.LabelRef(loopLabel))) builder.emit(Opcode.JMP, listOf(CmdBuilder.Operand.LabelRef(loopLabel)))
builder.mark(endLabel) builder.mark(endLabel)
@@ -6331,6 +6358,9 @@ class BytecodeCompiler(
) )
) )
val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null val bodyValue = compileLoopBody(stmt.body, wantResult) ?: return null
if (hasRealWiden) {
applySlotTypes(realWidenSlots, SlotType.UNKNOWN)
}
loopStack.removeLast() loopStack.removeLast()
if (wantResult) { if (wantResult) {
val bodyObj = ensureObjSlot(bodyValue) val bodyObj = ensureObjSlot(bodyValue)
@@ -6460,10 +6490,7 @@ class BytecodeCompiler(
restoreFlowTypeOverride(elseRestore) restoreFlowTypeOverride(elseRestore)
} }
builder.mark(endLabel) builder.mark(endLabel)
val slot = allocSlot() return CompiledValue(ensureVoidSlot(), SlotType.OBJ)
val voidId = builder.addConst(BytecodeConst.ObjRef(ObjVoid))
builder.emit(Opcode.CONST_OBJ, voidId, slot)
return CompiledValue(slot, SlotType.OBJ)
} }
private fun updateSlotTypeByName(name: String, type: SlotType) { private fun updateSlotTypeByName(name: String, type: SlotType) {
@@ -7048,13 +7075,55 @@ class BytecodeCompiler(
private fun isKnownClassReceiver(ref: ObjRef): Boolean { private fun isKnownClassReceiver(ref: ObjRef): Boolean {
return when (ref) { return when (ref) {
is LocalVarRef -> knownClassNames.contains(ref.name) && !knownObjectNames.contains(ref.name) is LocalVarRef -> {
is LocalSlotRef -> knownClassNames.contains(ref.name) && !knownObjectNames.contains(ref.name) val name = ref.name
is FastLocalVarRef -> knownClassNames.contains(ref.name) && !knownObjectNames.contains(ref.name) if (nameObjClass[name] == ObjClassType) return true
val directSlot = resolveDirectNameSlot(name)?.slot
if (directSlot != null && slotObjClass[directSlot] == ObjClassType) return true
if (localSlotIndexByName.containsKey(name)) return false
if (localSlotInfoMap.values.any { it.name == name }) return false
(knownClassNames.contains(name) || classFieldTypesByName.containsKey(name)) &&
!knownObjectNames.contains(name)
}
is LocalSlotRef -> {
val name = ref.name
if (slotObjClass[ref.slot] == ObjClassType) return true
if (nameObjClass[name] == ObjClassType) return true
val directSlot = resolveDirectNameSlot(name)?.slot
if (directSlot != null && slotObjClass[directSlot] == ObjClassType) return true
if (localSlotIndexByName.containsKey(name)) return false
if (localSlotInfoMap.values.any { it.name == name }) return false
(knownClassNames.contains(name) || classFieldTypesByName.containsKey(name)) &&
!knownObjectNames.contains(name)
}
is FastLocalVarRef -> {
val name = ref.name
if (nameObjClass[name] == ObjClassType) return true
val directSlot = resolveDirectNameSlot(name)?.slot
if (directSlot != null && slotObjClass[directSlot] == ObjClassType) return true
if (localSlotIndexByName.containsKey(name)) return false
if (localSlotInfoMap.values.any { it.name == name }) return false
(knownClassNames.contains(name) || classFieldTypesByName.containsKey(name)) &&
!knownObjectNames.contains(name)
}
else -> false else -> false
} }
} }
private fun isClassNameRef(ref: ObjRef, receiverClass: ObjClass): Boolean {
if (receiverClass !is ObjInstanceClass) return false
val name = when (ref) {
is LocalVarRef -> ref.name
is LocalSlotRef -> ref.name
is FastLocalVarRef -> ref.name
else -> return false
}
return name == receiverClass.className
}
private fun isClassSlot(slot: Int): Boolean = slotObjClass[slot] == ObjClassType
private fun isThisReceiver(ref: ObjRef): Boolean { private fun isThisReceiver(ref: ObjRef): Boolean {
return when (ref) { return when (ref) {
is LocalSlotRef -> ref.name == "this" is LocalSlotRef -> ref.name == "this"
@@ -7098,9 +7167,30 @@ class BytecodeCompiler(
private fun resolveReceiverClassForScopeCollection(ref: ObjRef): ObjClass? { private fun resolveReceiverClassForScopeCollection(ref: ObjRef): ObjClass? {
return when (ref) { return when (ref) {
is LocalSlotRef -> nameObjClass[ref.name] ?: resolveTypeNameClass(ref.name) is LocalSlotRef -> {
is LocalVarRef -> nameObjClass[ref.name] ?: resolveTypeNameClass(ref.name) val ownerScopeId = ref.captureOwnerScopeId ?: ref.scopeId
is FastLocalVarRef -> nameObjClass[ref.name] ?: resolveTypeNameClass(ref.name) val ownerSlot = ref.captureOwnerSlot ?: ref.slot
slotTypeByScopeId[ownerScopeId]?.get(ownerSlot)
?: slotInitClassByKey[ScopeSlotKey(ownerScopeId, ownerSlot)]
?: nameObjClass[ref.name]
?: resolveTypeNameClass(ref.name)
}
is LocalVarRef -> {
val key = localSlotInfoMap.entries.firstOrNull { it.value.name == ref.name }?.key
key?.let {
slotTypeByScopeId[it.scopeId]?.get(it.slot)
?: slotInitClassByKey[it]
} ?: nameObjClass[ref.name]
?: resolveTypeNameClass(ref.name)
}
is FastLocalVarRef -> {
val key = localSlotInfoMap.entries.firstOrNull { it.value.name == ref.name }?.key
key?.let {
slotTypeByScopeId[it.scopeId]?.get(it.slot)
?: slotInitClassByKey[it]
} ?: nameObjClass[ref.name]
?: resolveTypeNameClass(ref.name)
}
is BoundLocalVarRef -> slotObjClass[ref.slotIndex()] is BoundLocalVarRef -> slotObjClass[ref.slotIndex()]
is QualifiedThisRef -> resolveTypeNameClass(ref.typeName) is QualifiedThisRef -> resolveTypeNameClass(ref.typeName)
is ListLiteralRef -> ObjList.type is ListLiteralRef -> ObjList.type
@@ -7142,13 +7232,33 @@ class BytecodeCompiler(
return when (ref) { return when (ref) {
is ConstRef -> ref.constValue as? ObjClass is ConstRef -> ref.constValue as? ObjClass
is TypeDeclRef -> when (val decl = ref.decl()) { is TypeDeclRef -> when (val decl = ref.decl()) {
is TypeDecl.Simple -> resolveTypeNameClass(decl.name) ?: nameObjClass[decl.name] is TypeDecl.Simple -> {
is TypeDecl.Generic -> resolveTypeNameClass(decl.name) ?: nameObjClass[decl.name] resolveTypeNameClass(decl.name) ?: nameObjClass[decl.name]?.let { cls ->
if (cls == ObjClassType) ObjDynamic.type else cls
}
}
is TypeDecl.Generic -> {
resolveTypeNameClass(decl.name) ?: nameObjClass[decl.name]?.let { cls ->
if (cls == ObjClassType) ObjDynamic.type else cls
}
}
else -> null else -> null
} }
is LocalSlotRef -> resolveTypeNameClass(ref.name) ?: nameObjClass[ref.name] is LocalSlotRef -> {
is LocalVarRef -> resolveTypeNameClass(ref.name) ?: nameObjClass[ref.name] resolveTypeNameClass(ref.name) ?: nameObjClass[ref.name]?.let { cls ->
is FastLocalVarRef -> resolveTypeNameClass(ref.name) ?: nameObjClass[ref.name] if (cls == ObjClassType) ObjDynamic.type else cls
}
}
is LocalVarRef -> {
resolveTypeNameClass(ref.name) ?: nameObjClass[ref.name]?.let { cls ->
if (cls == ObjClassType) ObjDynamic.type else cls
}
}
is FastLocalVarRef -> {
resolveTypeNameClass(ref.name) ?: nameObjClass[ref.name]?.let { cls ->
if (cls == ObjClassType) ObjDynamic.type else cls
}
}
is QualifiedThisRef -> resolveTypeNameClass(ref.typeName) is QualifiedThisRef -> resolveTypeNameClass(ref.typeName)
else -> null else -> null
} }
@@ -7191,12 +7301,28 @@ class BytecodeCompiler(
private fun inferCallReturnClass(ref: CallRef): ObjClass? { private fun inferCallReturnClass(ref: CallRef): ObjClass? {
return when (val target = ref.target) { return when (val target = ref.target) {
is LocalSlotRef -> callableReturnTypeByScopeId[target.scopeId]?.get(target.slot) is LocalSlotRef -> {
?: nameObjClass[target.name] callableReturnTypeByScopeId[target.scopeId]?.get(target.slot)
?: resolveTypeNameClass(target.name) ?: run {
is LocalVarRef -> callableReturnTypeByName[target.name] val nameClass = nameObjClass[target.name]
?: nameObjClass[target.name] if (nameClass == ObjClassType) {
?: resolveTypeNameClass(target.name) resolveTypeNameClass(target.name) ?: ObjDynamic.type
} else {
nameClass ?: resolveTypeNameClass(target.name)
}
}
}
is LocalVarRef -> {
callableReturnTypeByName[target.name]
?: run {
val nameClass = nameObjClass[target.name]
if (nameClass == ObjClassType) {
resolveTypeNameClass(target.name) ?: ObjDynamic.type
} else {
nameClass ?: resolveTypeNameClass(target.name)
}
}
}
is ConstRef -> target.constValue as? ObjClass is ConstRef -> target.constValue as? ObjClass
else -> null else -> null
} }
@@ -7260,7 +7386,12 @@ class BytecodeCompiler(
private fun inferFieldReturnClass(targetClass: ObjClass?, name: String): ObjClass? { private fun inferFieldReturnClass(targetClass: ObjClass?, name: String): ObjClass? {
if (targetClass == null) return null if (targetClass == null) return null
if (targetClass == ObjDynamic.type) return ObjDynamic.type if (targetClass == ObjDynamic.type) return ObjDynamic.type
classFieldTypesByName[targetClass.className]?.get(name)?.let { return it } classFieldTypesByName[targetClass.className]?.get(name)?.let { cls ->
if (cls.className == "Delegate" || cls.className == "LazyDelegate" || cls.implementingNames.contains("Delegate")) {
return null
}
return cls
}
enumEntriesByName[targetClass.className]?.let { entries -> enumEntriesByName[targetClass.className]?.let { entries ->
return when { return when {
name == "entries" -> ObjList.type name == "entries" -> ObjList.type
@@ -102,6 +102,7 @@ object BuiltinDocRegistry : BuiltinDocSource {
// Register built-in lazy seeds // Register built-in lazy seeds
init { init {
registerLazy("lyng.stdlib") { buildStdlibDocs() } registerLazy("lyng.stdlib") { buildStdlibDocs() }
registerLazy("lyng.time") { buildTimeDocs() }
} }
/** /**
@@ -658,7 +659,32 @@ private fun buildStdlibDocs(): List<MiniDecl> {
} }
decls += mod.build() decls += mod.build()
return decls return decls
} }
private fun buildTimeDocs(): List<MiniDecl> {
val mod = ModuleDocsBuilder("lyng.time")
mod.classDoc(name = "Instant", doc = "Point in time (epoch-based).", bases = listOf(type("Obj"))) {
field(name = "distantFuture", doc = "An instant in the distant future.", type = type("lyng.Instant"), isStatic = true)
field(name = "distantPast", doc = "An instant in the distant past.", type = type("lyng.Instant"), isStatic = true)
method(name = "now", doc = "Return the current instant.", returns = type("lyng.Instant"), isStatic = true)
field(name = "epochSeconds", doc = "Seconds since Unix epoch.", type = type("lyng.Real"))
field(name = "epochWholeSeconds", doc = "Full seconds since Unix epoch.", type = type("lyng.Int"))
field(name = "nanosecondsOfSecond", doc = "Nanoseconds within the current second.", type = type("lyng.Int"))
method(name = "toRFC3339", doc = "Format as RFC3339 string.", returns = type("lyng.String"))
method(name = "toDateTime", doc = "Convert to localized DateTime.", params = listOf(ParamDoc("timeZone")), returns = type("lyng.DateTime"))
method(name = "truncateToMinute", doc = "Truncate to minute.", returns = type("lyng.Instant"))
method(name = "truncateToSecond", doc = "Truncate to second.", returns = type("lyng.Instant"))
method(name = "truncateToMillisecond", doc = "Truncate to millisecond.", returns = type("lyng.Instant"))
method(name = "truncateToMicrosecond", doc = "Truncate to microsecond.", returns = type("lyng.Instant"))
}
mod.classDoc(name = "DateTime", doc = "Localized date and time.", bases = listOf(type("Obj"))) {
method(name = "toInstant", doc = "Convert back to absolute Instant.", returns = type("lyng.Instant"))
}
mod.classDoc(name = "Duration", doc = "Time duration.", bases = listOf(type("Obj")))
mod.funDoc(name = "delay", doc = "Suspend execution.", params = listOf(ParamDoc("duration")))
return mod.build()
}
// (Registration for external modules is provided by their own libraries) // (Registration for external modules is provided by their own libraries)
@@ -1,3 +1,20 @@
/*
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/* /*
* Ensure stdlib Obj*-defined docs (like String methods added via ObjString.addFnDoc) * Ensure stdlib Obj*-defined docs (like String methods added via ObjString.addFnDoc)
* are initialized before registry lookups for completion/quick docs. * are initialized before registry lookups for completion/quick docs.
@@ -33,6 +50,19 @@ object StdlibDocsBootstrap {
val _range = net.sergeych.lyng.obj.ObjRange.type val _range = net.sergeych.lyng.obj.ObjRange.type
@Suppress("UNUSED_VARIABLE") @Suppress("UNUSED_VARIABLE")
val _buffer = net.sergeych.lyng.obj.ObjBuffer.type val _buffer = net.sergeych.lyng.obj.ObjBuffer.type
// Also touch time module types so their docs (moduleName = "lyng.time") are registered
// This enables completion/quick docs for symbols imported via `import lyng.time` (e.g., Instant, DateTime, Duration)
try {
@Suppress("UNUSED_VARIABLE")
val _instant = net.sergeych.lyng.obj.ObjInstant.type
@Suppress("UNUSED_VARIABLE")
val _datetime = net.sergeych.lyng.obj.ObjDateTime.type
@Suppress("UNUSED_VARIABLE")
val _duration = net.sergeych.lyng.obj.ObjDuration.type
} catch (_: Throwable) {
// Optional; absence should not affect stdlib core
}
} catch (_: Throwable) { } catch (_: Throwable) {
// Best-effort; absence should not break consumers // Best-effort; absence should not break consumers
} finally { } finally {
@@ -21,9 +21,7 @@ import kotlinx.datetime.*
import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.JsonPrimitive
import net.sergeych.lyng.Scope import net.sergeych.lyng.Scope
import net.sergeych.lyng.miniast.addFnDoc import net.sergeych.lyng.miniast.*
import net.sergeych.lyng.miniast.addPropertyDoc
import net.sergeych.lyng.miniast.type
import net.sergeych.lynon.LynonDecoder import net.sergeych.lynon.LynonDecoder
import net.sergeych.lynon.LynonEncoder import net.sergeych.lynon.LynonEncoder
import net.sergeych.lynon.LynonSettings import net.sergeych.lynon.LynonSettings
@@ -274,14 +272,28 @@ class ObjInstant(val instant: Instant,val truncateMode: LynonSettings.InstantTru
// class members // class members
addClassConst("distantFuture", distantFuture) addClassConstDoc(
addClassConst("distantPast", distantPast) name = "distantFuture",
addClassFn("now") { value = distantFuture,
doc = "An instant in the distant future.",
type = type("lyng.Instant"),
moduleName = "lyng.time"
)
addClassConstDoc(
name = "distantPast",
value = distantPast,
doc = "An instant in the distant past.",
type = type("lyng.Instant"),
moduleName = "lyng.time"
)
addClassFnDoc(
name = "now",
doc = "Return the current instant from the system clock.",
returns = type("lyng.Instant"),
moduleName = "lyng.time"
) {
ObjInstant(Clock.System.now()) ObjInstant(Clock.System.now())
} }
// addFn("epochMilliseconds") {
// ObjInt(instant.toEpochMilliseconds())
// }
} }
} }
@@ -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.
@@ -14,7 +14,7 @@
* limitations under the License. * limitations under the License.
* *
*/ */
package net.sergeych.lyng.idea.util package net.sergeych.lyng.tools
import net.sergeych.lyng.ModuleScope import net.sergeych.lyng.ModuleScope
import net.sergeych.lyng.Pos import net.sergeych.lyng.Pos
@@ -28,7 +28,13 @@ import net.sergeych.lyng.pacman.ImportProvider
* the compiler can still build MiniAst for Quick Docs / highlighting. * the compiler can still build MiniAst for Quick Docs / highlighting.
*/ */
class IdeLenientImportProvider private constructor(root: Scope) : ImportProvider(root) { class IdeLenientImportProvider private constructor(root: Scope) : ImportProvider(root) {
override suspend fun createModuleScope(pos: Pos, packageName: String): ModuleScope = ModuleScope(this, pos, packageName) override suspend fun createModuleScope(pos: Pos, packageName: String): ModuleScope {
return try {
Script.defaultImportManager.createModuleScope(pos, packageName)
} catch (_: Throwable) {
ModuleScope(this, pos, packageName)
}
}
companion object { companion object {
/** Create a provider based on the default manager's root scope. */ /** Create a provider based on the default manager's root scope. */
@@ -39,7 +39,8 @@ data class LyngAnalysisRequest(
val text: String, val text: String,
val fileName: String = "<snippet>", val fileName: String = "<snippet>",
val importProvider: ImportProvider = Script.defaultImportManager, val importProvider: ImportProvider = Script.defaultImportManager,
val seedScope: Scope? = null val seedScope: Scope? = null,
val allowUnresolvedRefs: Boolean = true
) )
enum class LyngDiagnosticSeverity { Error, Warning } enum class LyngDiagnosticSeverity { Error, Warning }
@@ -95,6 +96,10 @@ data class LyngSemanticSpan(
object LyngLanguageTools { object LyngLanguageTools {
suspend fun analyze(request: LyngAnalysisRequest): LyngAnalysisResult { suspend fun analyze(request: LyngAnalysisRequest): LyngAnalysisResult {
// Ensure stdlib/Obj* docs are initialized and stdlib docs are available before anything else
StdlibDocsBootstrap.ensure()
BuiltinDocRegistry.docsForModule("lyng.stdlib")
val source = Source(request.fileName, request.text) val source = Source(request.fileName, request.text)
val miniSink = MiniAstBuilder() val miniSink = MiniAstBuilder()
val resolutionCollector = ResolutionCollector(source.fileName) val resolutionCollector = ResolutionCollector(source.fileName)
@@ -107,7 +112,7 @@ object LyngLanguageTools {
miniSink = miniSink, miniSink = miniSink,
resolutionSink = resolutionCollector, resolutionSink = resolutionCollector,
compileBytecode = false, compileBytecode = false,
allowUnresolvedRefs = true, allowUnresolvedRefs = request.allowUnresolvedRefs,
seedScope = request.seedScope seedScope = request.seedScope
) )
} catch (t: Throwable) { } catch (t: Throwable) {
@@ -0,0 +1,59 @@
/*
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import kotlinx.coroutines.test.runTest
import net.sergeych.lyng.Script
import net.sergeych.lyng.ScriptError
import kotlin.test.Test
import kotlin.test.assertFailsWith
class ClosedClassTest {
@Test
fun testClosedClass() = runTest {
val scope = Script.newScope()
scope.eval("""
closed class MyClosedClass {
fun foo() = 42
}
""".trimIndent())
assertFailsWith<ScriptError> {
scope.eval("""
class SubClass : MyClosedClass()
""".trimIndent())
}
}
@Test
fun testStdlibClosedClasses() = runTest {
val scope = Script.newScope()
assertFailsWith<ScriptError> {
scope.eval("class MyInt : Int()")
}
assertFailsWith<ScriptError> {
scope.eval("class MyReal : Real()")
}
assertFailsWith<ScriptError> {
scope.eval("class MyString : String()")
}
assertFailsWith<ScriptError> {
scope.eval("class MyBool : Bool()")
}
}
}
@@ -0,0 +1,93 @@
/*
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import kotlinx.coroutines.test.runTest
import net.sergeych.lyng.Benchmarks
import net.sergeych.lyng.Script
import net.sergeych.lyng.obj.ObjInt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.time.TimeSource
class MixedCompareBenchmarkTest {
@Test
fun benchmarkMixedCompareOps() = runTest {
if (!Benchmarks.enabled) return@runTest
val iterations = 200000
val script = """
fun mixedCompareBench(n) {
var acc = 0
var r = 0.0
val strs = ["a","b","aa","bb","abc","abd","zzz",""]
var i = 0
while(i < n) {
val si = strs[i % 8]
if( si == "a" ) acc += 1 else acc -= 1
if( si != "zzz" ) acc += 2
if( si == "" ) acc += 3
if( i < (i % 5) ) acc += 1 else acc -= 1
if( (i % 3) == 0 ) acc += 2
val r1 = i + 0.5
if( r1 > i ) acc += 1
if( i < r1 ) acc += 1
r += r1 * 0.25
if( r > 1000.0 ) acc += 1
i++
}
acc
}
""".trimIndent()
val scope = Script.newScope()
scope.eval(script)
val expected = expectedValue(iterations)
val start = TimeSource.Monotonic.markNow()
val result = scope.eval("mixedCompareBench($iterations)") as ObjInt
val elapsedMs = start.elapsedNow().inWholeMilliseconds
println("[DEBUG_LOG] [BENCH] mixed-compare elapsed=${elapsedMs} ms")
assertEquals(expected, result.value)
}
private fun expectedValue(iterations: Int): Long {
val strs = arrayOf("a", "b", "aa", "bb", "abc", "abd", "zzz", "")
var acc = 0L
var r = 0.0
var i = 0
while (i < iterations) {
val si = strs[i % 8]
if (si == "a") acc += 1 else acc -= 1
if (si != "zzz") acc += 2
if (si == "") acc += 3
if (i < (i % 5)) acc += 1 else acc -= 1
if ((i % 3) == 0) acc += 2
val r1 = i + 0.5
if (r1 > i) acc += 1
if (i < r1) acc += 1
r += r1 * 0.25
if (r > 1000.0) acc += 1
i += 1
}
return acc
}
}
@@ -1258,6 +1258,28 @@ class ScriptTest {
) )
} }
@Test
fun testForLoopRealWidenDisasm() = runTest {
val scope = Script.newScope()
scope.eval(
"""
fun widenFor() {
var acc = 0
for(i in 0..3) {
if (i == 1) acc = 0.5
}
}
""".trimIndent()
)
val disasm = scope.disassembleSymbol("widenFor")
println("[DEBUG_LOG] widenFor disasm:\n$disasm")
val incIndex = disasm.indexOf("INC_INT")
assertTrue(incIndex >= 0, "expected INC_INT in for-loop disasm")
val convIndex = disasm.indexOf("INT_TO_REAL")
assertTrue(convIndex >= 0, "expected INT_TO_REAL in for-loop disasm")
assertTrue(convIndex > incIndex, "INT_TO_REAL should appear after INC_INT")
}
@Test @Test
fun testIntClosedRangeInclusive() = runTest { fun testIntClosedRangeInclusive() = runTest {
eval( eval(
+39 -10
View File
@@ -132,15 +132,44 @@ class StdlibTest {
""".trimIndent()) """.trimIndent())
} }
// @Test @Test
// fun testFunFromSample() = runTest { fun testFilter1() = runTest {
// range should be iterable if it is intrange // range should be iterable if it is intrange
// eval(""" eval("""
// val data = 1..5 // or [1, 2, 3, 4, 5] val data = 1..5 // or [1, 2, 3, 4, 5]
// fun test() { assert( data is Iterable<Int> )
// data.filter { it % 2 == 0 }.map { it * it } fun test() {
// } data.filter { it % 2 == 0 }.map { it * it }
// test() }
// """.trimIndent()) test()
// } """.trimIndent())
}
@Test
fun testFilter2() = runTest {
eval("""
val data = [1, 2, 3, 4, 5]
assert( data is Iterable<Int> )
fun test() {
data.filter { it % 2 == 0 }.map { it * it }
}
test()
"""
)
}
@Test
fun testFilter3() = runTest {
eval("""
type Numeric = Int | Real
fun process<T: Numeric>(items: List<T>): List<T> {
items.filter { it > 0 }.map { it * it }
}
val data = [-2, -1, 0, 1, 2]
println("Processed: " + process(data))
""".trimIndent())
}
} }
@@ -0,0 +1,260 @@
/*
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.sergeych.lyng
import kotlinx.coroutines.test.runTest
import net.sergeych.lyng.obj.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class WebsiteSamplesTest {
@Test
fun testEverythingIsAnExpression() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Everything is an expression
val x: Int = 10
val status: String = if (x > 0) "Positive" else "Zero or Negative"
// Even loops return values!
val result = for (i in 1..5) {
if (i == 3) break "Found 3!"
} else "Not found"
result
""".trimIndent())
assertEquals("Found 3!", (result as ObjString).value)
}
@Test
fun testFunctionalPower() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Functional power with generics and collections
val squares: List<Int> = (1..10)
.filter { it % 2 == 0 }
.map { it * it }
squares
""".trimIndent())
assertTrue(result is ObjList)
val list = (result as ObjList).list.map { (it as ObjInt).value }
assertEquals(listOf(4L, 16L, 36L, 64L, 100L), list)
}
@Test
fun testGenericsAndTypeAliases() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Generics and type aliases
type Num = Int | Real
class Box<out T: Num>(val value: T) {
fun get(): T = value
}
val intBox = Box(42)
val realBox = Box(3.14)
[intBox.get(), realBox.get()]
""".trimIndent())
assertTrue(result is ObjList)
val l = (result as ObjList).list
assertEquals(42L, (l[0] as ObjInt).value)
assertEquals(3.14, (l[1] as ObjReal).value)
}
@Test
fun testStrictCompileTimeTypes() = runTest {
val scope = Script.newScope()
scope.eval("""
// Strict compile-time types and symbol resolution
fun greet(name: String, count: Int) {
for (i in 1..count) {
println("Hello, " + name + "!")
}
}
greet("Lyng", 3)
""".trimIndent())
}
@Test
fun testFlexibleMapLiterals() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Flexible map literals and shorthands
val id = 101
val name = "Lyng"
val base = { id:, name: } // Shorthand for id: id, name: name
val full = { ...base, version: "1.5.0-SNAPSHOT", status: "active" }
full
""".trimIndent())
assertTrue(result is ObjMap)
val m = (result as ObjMap).map
assertEquals(101L, (m[ObjString("id")] as ObjInt).value)
assertEquals("Lyng", (m[ObjString("name")] as ObjString).value)
assertEquals("1.5.0-SNAPSHOT", (m[ObjString("version")] as ObjString).value)
assertEquals("active", (m[ObjString("status")] as ObjString).value)
}
@Test
fun testModernNullSafety() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Modern null safety
var config: Map<String, Int>? = null
config ?= { timeout: 30 } // Assign only if null
val timeout = config?["timeout"] ?: 60
timeout
""".trimIndent())
assertEquals(30L, (result as ObjInt).value)
}
@Test
fun testDestructuringWithSplat() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Destructuring with splat operator
val [first, middle..., last] = [1, 2, 3, 4, 5, 6]
[first, middle, last]
""".trimIndent())
assertTrue(result is ObjList)
val rl = (result as ObjList).list
assertEquals(1L, (rl[0] as ObjInt).value)
val middle = rl[1] as ObjList
assertEquals(listOf(2L, 3L, 4L, 5L), middle.list.map { (it as ObjInt).value })
assertEquals(6L, (rl[2] as ObjInt).value)
}
@Test
fun testDiamondSafeMultipleInheritance() = runTest {
val scope = Script.newScope()
scope.eval("""
// Diamond-safe Multiple Inheritance (C3 MRO)
interface Logger {
fun log(m: String) = println("[LOG] " + m)
}
interface Auth {
fun login(u: String) = println("Login: " + u)
}
class App() : Logger, Auth {
override fun run() {
log("Starting...")
login("admin")
}
}
App().run()
""".trimIndent())
}
@Test
fun testExtensionFunctionsAndProperties() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Extension functions and properties
fun String.shout(): String = this.uppercase() + "!!!"
val List<T>.second: T get() = this[1]
["hello".shout(), [10, 20, 30].second]
""".trimIndent())
assertTrue(result is ObjList)
val el = (result as ObjList).list
assertEquals("HELLO!!!", (el[0] as ObjString).value)
assertEquals(20L, (el[1] as ObjInt).value)
}
@Test
fun testNonLocalReturns() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Non-local returns from closures
fun findFirst<T>(list: Iterable<T>, predicate: (T)->Bool): T? {
list.forEach {
if (predicate(it)) return@findFirst it
}
null
}
val found: Int? = findFirst([1, 5, 8, 12]) { it > 10 }
found
""".trimIndent())
assertEquals(12L, (result as ObjInt).value)
}
@Test
fun testEasyOperatorOverloading() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Easy operator overloading
class Vector(val x: Real, val y: Real) {
fun plus(other: Vector): Vector = Vector(x + other.x, y + other.y)
override fun toString(): String = "Vector(%g, %g)"(x, y)
}
val v1 = Vector(1, 2)
val v2 = Vector(3, 4)
(v1 + v2).toString()
""".trimIndent())
assertEquals("Vector(4, 6)", (result as ObjString).value)
}
@Test
fun testPropertyDelegationToMap() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Property delegation to Map
class User() {
var name: String by Map()
}
val u = User()
u.name = "Sergey"
u.name
""".trimIndent())
assertEquals("Sergey", (result as ObjString).value)
}
@Test
fun testImplicitCoroutines() = runTest {
val scope = Script.newScope()
val result = scope.eval("""
// Implicit coroutines: parallelism without ceremony
// import lyng.time // we don't need it for delay if it's available globally
val d1 = launch {
delay(100.milliseconds)
"Task A finished"
}
val d2 = launch {
delay(50.milliseconds)
"Task B finished"
}
[d1.await(), d2.await()]
""".trimIndent())
assertTrue(result is ObjList)
val dl = (result as ObjList).list
assertEquals("Task A finished", (dl[0] as ObjString).value)
assertEquals("Task B finished", (dl[1] as ObjString).value)
}
}
@@ -0,0 +1,87 @@
/*
* Copyright 2026 Sergey S. Chernov real.sergeych@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package net.sergeych.lyng.tools
import kotlinx.coroutines.test.runTest
import net.sergeych.lyng.miniast.BuiltinDocRegistry
import kotlin.test.Test
import kotlin.test.assertTrue
class ReproInstantErrorStrictTest {
@Test
fun unknownMemberNoDiagnosticInStrictMode() = runTest {
// Clear the registry to simulate fresh start
BuiltinDocRegistry.clearModule("lyng.stdlib")
BuiltinDocRegistry.clearModule("lyng.time")
val code = """
import lyng.time
fun fff() {
Instant.nowWrong()
}
""".trimIndent()
val provider = IdeLenientImportProvider.create()
val result = LyngLanguageTools.analyze(
LyngAnalysisRequest(
text = code,
importProvider = provider,
allowUnresolvedRefs = false
)
)
println("[DEBUG_LOG] Diagnostics: ${result.diagnostics.joinToString { "${it.severity}: ${it.message}" }}")
println("[DEBUG_LOG] Resolution Errors: ${result.resolution?.errors?.joinToString { it.message }}")
val errors = result.diagnostics.filter { it.severity == LyngDiagnosticSeverity.Error }
assertTrue(errors.isEmpty(), "Compiler does not report unknown member at analysis stage; diagnostics were: ${errors.joinToString { it.message }}")
}
@Test
fun instantNowResolvesWhenStrict() = runTest {
// Clear the registry to simulate fresh start
BuiltinDocRegistry.clearModule("lyng.stdlib")
BuiltinDocRegistry.clearModule("lyng.time")
val code = """
import lyng.time
fun fff() {
Instant.now()
}
""".trimIndent()
val provider = IdeLenientImportProvider.create()
val result = LyngLanguageTools.analyze(
LyngAnalysisRequest(
text = code,
importProvider = provider,
allowUnresolvedRefs = false
)
)
println("[DEBUG_LOG] Diagnostics: ${result.diagnostics.joinToString { "${it.severity}: ${it.message}" }}")
println("[DEBUG_LOG] Resolution Errors: ${result.resolution?.errors?.joinToString { it.message }}")
val errors = result.diagnostics.filter { it.severity == LyngDiagnosticSeverity.Error }
assertTrue(errors.isEmpty(), "Should not have any errors, but got: ${errors.joinToString { it.message }}")
}
}
@@ -0,0 +1,50 @@
/*
* 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.tools
import kotlinx.coroutines.test.runTest
import net.sergeych.lyng.miniast.BuiltinDocRegistry
import kotlin.test.Test
import kotlin.test.assertTrue
class ReproInstantErrorTest {
@Test
fun testInstantResolutionOnFirstPass() = runTest {
// Clear the registry to simulate fresh start
BuiltinDocRegistry.clearModule("lyng.stdlib")
BuiltinDocRegistry.clearModule("lyng.time")
val code = """
import lyng.time
fun fff() {
Instant.now()
}
""".trimIndent()
// Analyze without any prior "touches"
val result = LyngLanguageTools.analyze(code)
// Check if there are any errors related to Instant
val instantErrors = result.diagnostics.filter { it.message.contains("Instant") }
assertTrue(instantErrors.isEmpty(), "Should not have Instant-related errors on first pass, but got: ${instantErrors.joinToString { it.message }}")
}
}
+39
View File
@@ -0,0 +1,39 @@
# Fast Ops Optimizations Plan (Draft)
Baseline
- See `notes/nested_range_baseline.md`
Candidates (not started)
1) Primitive comparisons (done)
- Emit fast CMP variants for known ObjString/ObjInt/ObjReal using temp/stable slots.
- MixedCompareBenchmarkTest: 374 ms -> 347 ms.
2) Mixed numeric ops (done)
- Allow INT+REAL arithmetic to use primitive REAL ops (no obj fallback).
- MixedCompareBenchmarkTest: 347 ms -> 275 ms.
3) Boolean conversion (done; do not revert without review)
- Skip redundant OBJ_TO_BOOL in logical AND/OR when compiler already emits BOOL.
- MixedCompareBenchmarkTest: 275 ms -> 249 ms.
4) Range/loop hot path (done)
- Reuse a cached ObjVoid slot for if-statements in statement context (avoids per-iteration CONST_OBJ).
- MixedCompareBenchmarkTest: 249 ms -> 247 ms.
5) String ops (done)
- Mark GET_INDEX results as stable only for closed ObjString elements to enable fast compares.
- MixedCompareBenchmarkTest: 247 ms -> 240 ms.
6) Box/unbox audit (done)
- Unbox ObjInt/ObjReal in assign-op when target is INT/REAL to avoid boxing + obj ops.
- MixedCompareBenchmarkTest: 240 ms -> 234 ms.
7) Mixed compare coverage
- Emit CMP_*_REAL when one operand is known ObjReal in more expression forms (not just assign-op).
- Verify with disassembly that fast cmp opcodes are emitted.
8) Range-loop invariant hoist
- Cache range end/step into temps once per loop; avoid repeated slot reads/boxing in body.
- Confirm no extra CONST_OBJ in hot path.
9) Boxing elision pass
- Remove redundant BOX_OBJ when value feeds only primitive ops afterward (local liveness).
- Ensure no impact on closures/escaping values.
10) Closed-type fast paths expansion
- Apply closed-type trust for ObjBool/ObjInt/ObjReal/ObjString in ternaries and conditional chains.
- Guard with exact non-null temp/slot checks only.
11) VM hot op micro-optimizations
- Reduce frame reads/writes in ADD_INT, MUL_REAL, CMP_*_INT/REAL when operands are temps.
- Compare against baseline; revert if regression after 10-run median.
+12
View File
@@ -0,0 +1,12 @@
# Mixed Compare Benchmark Baseline
Date: 2026-02-16
Benchmark:
- MixedCompareBenchmarkTest.benchmarkMixedCompareOps
Command:
`BENCHMARKS=true timeout 20s ./gradlew :lynglib:jvmTest --tests MixedCompareBenchmarkTest --rerun-tasks`
Result:
- mixed-compare elapsed=374 ms
+9
View File
@@ -0,0 +1,9 @@
# Nested Range Benchmark Baseline
Date: 2026-02-16
Command:
`BENCHMARKS=true timeout 20s ./gradlew :lynglib:jvmTest --tests NestedRangeBenchmarkTest --rerun-tasks`
Result:
- nested-happy elapsed=56 ms
+48 -24
View File
@@ -29,8 +29,8 @@ fun HomePage() {
listOf( listOf(
""" """
// Everything is an expression // Everything is an expression
val x = 10 val x: Int = 10
val status = if (x > 0) "Positive" else "Zero or Negative" val status: String = if (x > 0) "Positive" else "Zero or Negative"
// Even loops return values! // Even loops return values!
val result = for (i in 1..5) { val result = for (i in 1..5) {
@@ -40,8 +40,8 @@ fun HomePage() {
println("Result: " + result) println("Result: " + result)
""".trimIndent(), """.trimIndent(),
""" """
// Functional power with ranges and collections // Functional power with generics and collections
val squares = (1..10) val squares: List<Int> = (1..10)
.filter { it % 2 == 0 } .filter { it % 2 == 0 }
.map { it * it } .map { it * it }
@@ -49,20 +49,43 @@ fun HomePage() {
// Output: [4, 16, 36, 64, 100] // Output: [4, 16, 36, 64, 100]
""".trimIndent(), """.trimIndent(),
""" """
// Generics and type aliases
type Num = Int | Real
class Box<out T: Num>(val value: T) {
fun get(): T = value
}
val intBox = Box(42)
val realBox = Box(3.14)
println("Boxes: " + intBox.get() + ", " + realBox.get())
""".trimIndent(),
"""
// Strict compile-time types and symbol resolution
fun greet(name: String, count: Int) {
for (i in 1..count) {
println("Hello, " + name + "!")
}
}
greet("Lyng", 3)
// greet(10, "error") // This would be a compile-time error!
""".trimIndent(),
"""
// Flexible map literals and shorthands // Flexible map literals and shorthands
val id = 101 val id = 101
val name = "Lyng" val name = "Lyng"
val base = { id:, name: } // Shorthand for id: id, name: name val base = { id:, name: } // Shorthand for id: id, name: name
val full = { ...base, version: "1.0", status: "active" } val full = { ...base, version: "1.5.0-SNAPSHOT", status: "active" }
println(full) println(full)
""".trimIndent(), """.trimIndent(),
""" """
// Modern null safety // Modern null safety
var config = null var config: Map<String, Int>? = null
config ?= { timeout: 30 } // Assign only if null config ?= { timeout: 30 } // Assign only if null
val timeout = config?.timeout ?: 60 val timeout = config?["timeout"] ?: 60
println("Timeout is: " + timeout) println("Timeout is: " + timeout)
""".trimIndent(), """.trimIndent(),
""" """
@@ -76,14 +99,14 @@ fun HomePage() {
""" """
// Diamond-safe Multiple Inheritance (C3 MRO) // Diamond-safe Multiple Inheritance (C3 MRO)
interface Logger { interface Logger {
fun log(m) = println("[LOG] " + m) fun log(m: String) = println("[LOG] " + m)
} }
interface Auth { interface Auth {
fun login(u) = println("Login: " + u) fun login(u: String) = println("Login: " + u)
} }
class App() : Logger, Auth { class App() : Logger, Auth {
fun run() { override fun run() {
log("Starting...") log("Starting...")
login("admin") login("admin")
} }
@@ -92,30 +115,30 @@ fun HomePage() {
""".trimIndent(), """.trimIndent(),
""" """
// Extension functions and properties // Extension functions and properties
fun String.shout() = this.toUpperCase() + "!!!" fun String.shout(): String = this.uppercase() + "!!!"
println("hello".shout()) println("hello".shout())
val List.second get = this[1] val List<T>.second: T get() = this[1]
println([10, 20, 30].second) println([10, 20, 30].second)
""".trimIndent(), """.trimIndent(),
""" """
// Non-local returns from closures // Non-local returns from closures
fun findFirst(list, predicate) { fun findFirst<T>(list: Iterable<T>, predicate: (T)->Bool): T? {
list.forEach { list.forEach {
if (predicate(it)) return@findFirst it if (predicate(it)) return@findFirst it
} }
null null
} }
val found = findFirst([1, 5, 8, 12]) { it > 10 } val found: Int? = findFirst([1, 5, 8, 12]) { it > 10 }
println("Found: " + found) println("Found: " + found)
""".trimIndent(), """.trimIndent(),
""" """
// Easy operator overloading // Easy operator overloading
class Vector(val x, val y) { class Vector(val x: Real, val y: Real) {
override fun plus(other) = Vector(x + other.x, y + other.y) fun plus(other: Vector): Vector = Vector(x + other.x, y + other.y)
override fun toString() = "Vector(%g, %g)"(x, y) override fun toString(): String = "Vector(%g, %g)"(x, y)
} }
val v1 = Vector(1, 2) val v1 = Vector(1, 2)
@@ -125,7 +148,7 @@ fun HomePage() {
""" """
// Property delegation to Map // Property delegation to Map
class User() { class User() {
var name by Map() var name: String by Map()
} }
val u = User() val u = User()
@@ -165,17 +188,18 @@ fun HomePage() {
Div({ classes("text-center") }) { Div({ classes("text-center") }) {
H1({ classes("display-5", "fw-bold", "mb-3") }) { Text("Welcome to Lyng") } H1({ classes("display-5", "fw-bold", "mb-3") }) { Text("Welcome to Lyng") }
P({ classes("lead", "text-muted", "mb-4") }) { P({ classes("lead", "text-muted", "mb-4") }) {
Text("A lightweight, expressive scripting language designed for clarity, composability, and fun. ") Text("A lightweight but extremely powerful and expressive scripting language with strict static typing and functional power. ")
Br() Br()
Text("Run it anywhere Kotlin runs — share logic across JS, JVM, and more.") Text("Run it anywhere Kotlin runs — share logic across JS, JVM, Native and more.")
} }
Div({ classes("d-flex", "justify-content-center", "gap-2", "flex-wrap", "mb-4") }) { Div({ classes("d-flex", "justify-content-center", "gap-2", "flex-wrap", "mb-4") }) {
// Benefits pills // Benefits pills
listOf( listOf(
"Clean, familiar syntax", "Strict static typing",
"Generics & Type Aliases",
"Implicit coroutines",
"both FP and OOP", "both FP and OOP",
"Batteries-included standard library", "Batteries-included standard library"
"Embeddable and testable"
).forEach { b -> ).forEach { b ->
Span({ classes("badge", "text-bg-secondary", "rounded-pill") }) { Text(b) } Span({ classes("badge", "text-bg-secondary", "rounded-pill") }) { Text(b) }
} }
@@ -233,7 +257,7 @@ fun HomePage() {
// Short features list // Short features list
Div({ classes("row", "g-4", "mt-1") }) { Div({ classes("row", "g-4", "mt-1") }) {
listOf( listOf(
Triple("Fast to learn", "Familiar constructs and readable patterns — be productive in minutes.", "lightning"), Triple("Safe and Robust", "Strict compile-time resolution, generics, and null safety catch errors early.", "shield-check"),
Triple("Portable", "Runs wherever Kotlin runs: reuse logic across platforms.", "globe2"), Triple("Portable", "Runs wherever Kotlin runs: reuse logic across platforms.", "globe2"),
Triple("Pragmatic", "A standard library that solves real problems without ceremony.", "gear-fill") Triple("Pragmatic", "A standard library that solves real problems without ceremony.", "gear-fill")
).forEach { (title, text, icon) -> ).forEach { (title, text, icon) ->
+15 -7
View File
@@ -22,6 +22,7 @@ import net.sergeych.lyng.Script
import net.sergeych.lyng.ScriptError import net.sergeych.lyng.ScriptError
import net.sergeych.lyng.highlight.TextRange import net.sergeych.lyng.highlight.TextRange
import net.sergeych.lyng.miniast.CompletionItem import net.sergeych.lyng.miniast.CompletionItem
import net.sergeych.lyng.requireScope
import net.sergeych.lyng.tools.LyngDiagnostic import net.sergeych.lyng.tools.LyngDiagnostic
import net.sergeych.lyng.tools.LyngDiagnosticSeverity import net.sergeych.lyng.tools.LyngDiagnosticSeverity
import net.sergeych.lyng.tools.LyngSymbolInfo import net.sergeych.lyng.tools.LyngSymbolInfo
@@ -48,11 +49,18 @@ fun TryLyngPage(route: String) {
var code by remember(initialCode) { var code by remember(initialCode) {
mutableStateOf( mutableStateOf(
initialCode ?: """ initialCode ?: """
// Welcome to Lyng! Edit and run. // Welcome to Lyng! Modern scripting with strict types and generics.
// Try changing the data and press Ctrl+Enter or click Run.
val data = 1..5 // or [1, 2, 3, 4, 5] type Numeric = Int | Real
data.filter { it % 2 == 0 }.map { it * it }
fun process<T: Numeric>(items: List<T>): List<T> {
items.filter { it > 0 }.map { it * it }
}
val data = [-2, -1, 0, 1, 2]
println("Processed: " + process(data))
// Try changing data or adding Real numbers!
""".trimIndent() """.trimIndent()
) )
} }
@@ -94,13 +102,13 @@ fun TryLyngPage(route: String) {
s.addVoidFn("print") { s.addVoidFn("print") {
for ((i, a) in this.args.withIndex()) { for ((i, a) in this.args.withIndex()) {
if (i > 0) printed.append(' ') if (i > 0) printed.append(' ')
printed.append(a.toString(this).value) printed.append(a.toString(this.requireScope()).value)
} }
} }
s.addVoidFn("println") { s.addVoidFn("println") {
for ((i, a) in this.args.withIndex()) { for ((i, a) in this.args.withIndex()) {
if (i > 0) printed.append(' ') if (i > 0) printed.append(' ')
printed.append(a.toString(this).value) printed.append(a.toString(this.requireScope()).value)
} }
printed.append('\n') printed.append('\n')
} }
@@ -154,7 +162,7 @@ fun TryLyngPage(route: String) {
fun resetCode() { fun resetCode() {
code = initialCode ?: """ code = initialCode ?: """
// Welcome to Lyng! Edit and run. // Welcome to Lyng! Modern scripting with strict types and generics.
[1, 2, 3].map { it * 10 } [1, 2, 3].map { it * 10 }
""".trimIndent() """.trimIndent()
output = null output = null
+1 -1
View File
@@ -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.2.0! v1.5.0-SNAPSHOT!
</span> </span>
</div> </div>
<!-- Fixed top navbar for the whole site --> <!-- Fixed top navbar for the whole site -->