Long road starts here

This commit is contained in:
Sergey Chernov 2025-05-18 00:52:19 +04:00
commit b220299fc5
33 changed files with 2129 additions and 0 deletions

54
.github/workflows/gradle.yml vendored Normal file
View File

@ -0,0 +1,54 @@
# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.
# This workflow will build a Java project with Gradle and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-gradle
name: Java CI with Gradle
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
workflow_call:
permissions:
contents: read
jobs:
build:
strategy:
matrix:
include:
- target: iosSimulatorArm64Test
os: macos-latest
- target: jvmTest
os: ubuntu-latest
- target: linuxX64Test
os: ubuntu-latest
- target: testDebugUnitTest
os: ubuntu-latest
- target: testReleaseUnitTest
os: ubuntu-latest
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v3
- name: Validate Gradle Wrapper
uses: gradle/actions/wrapper-validation@v3
- uses: actions/cache@v3
with:
path: |
~/.konan
key: ${{ runner.os }}-${{ hashFiles('**/.lock') }}
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: Build with Gradle
uses: gradle/gradle-build-action@ce999babab2de1c4b649dc15f0ee67e6246c994f
with:
arguments: ${{ matrix.target }}

25
.github/workflows/publish.yml vendored Normal file
View File

@ -0,0 +1,25 @@
name: Publish
on:
release:
types: [released, prereleased]
jobs:
publish:
name: Release build and publish
runs-on: macOS-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: 21
- name: Publish to MavenCentral
run: ./gradlew publishToMavenCentral --no-configuration-cache
env:
ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }}
ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_KEY_ID }}
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }}
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY_CONTENTS }}

15
.gitignore vendored Normal file
View File

@ -0,0 +1,15 @@
*.iml
.gradle
.idea
.DS_Store
build
captures
.externalNativeBuild
.cxx
local.properties
xcuserdata
.kotlin
#So we don't accidentally commit our private keys
*.gpg
.gigaide
.kotlin

201
LICENSE Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2025 Sergey Chernov.
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.

35
README.md Normal file
View File

@ -0,0 +1,35 @@
# Ling: scripting lang for kotlin multiplatform
in the form of multiplatform library.
## Why?
Designed to add scripting to kotlin multiplatform application in easy and efficient way. This is attempt to achieve what Lua is for C/++.
- fast start (times and times faster than initializing v8/wasm)
- fast and simple kotlin interoperability
- coroutine-based, truly async. On platforms with multithreading, run multithreaded. No python/ruby/javascript threads hell.
- small footprint
- absolutely safe: no access to any dangerous or sensitive functions until you specifically provide it.
# Language
- dynamic
- async
- multithreaded (coroutines could be dispatched using threads on appropriate platforms, automatically)
## By-stage
Here are plans to develop it:
### First stage
Interpreted, precompiled into threaded code, actually. Dynamic types.
### Second stage
Will add:
- optimizations
- p-code serialization
- static typing

5
build.gradle.kts Normal file
View File

@ -0,0 +1,5 @@
plugins {
alias(libs.plugins.androidLibrary) apply false
alias(libs.plugins.kotlinMultiplatform) apply false
alias(libs.plugins.vanniktech.mavenPublish) apply false
}

12
gradle.properties Normal file
View File

@ -0,0 +1,12 @@
#Gradle
org.gradle.jvmargs=-Xmx2048M -Dfile.encoding=UTF-8 -Dkotlin.daemon.jvm.options\="-Xmx2048M"
org.gradle.caching=true
org.gradle.configuration-cache=true
#Kotlin
kotlin.code.style=official
kotlin.js.compiler=ir
#MPP
kotlin.mpp.enableCInteropCommonization=true
#Android
android.useAndroidX=true
android.nonTransitiveRClass=true

18
gradle/libs.versions.toml Normal file
View File

@ -0,0 +1,18 @@
[versions]
agp = "8.5.2"
kotlin = "2.1.21"
android-minSdk = "24"
android-compileSdk = "34"
kotlinx-coroutines = "1.10.1"
mp_bintools = "0.1.12"
[libraries]
kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" }
kotlinx-coroutines-test = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-test", version.ref = "kotlinx-coroutines" }
kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinx-coroutines" }
mp_bintools = { module = "net.sergeych:mp_bintools", version.ref = "mp_bintools" }
[plugins]
androidLibrary = { id = "com.android.library", version.ref = "agp" }
kotlinMultiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" }
vanniktech-mavenPublish = { id = "com.vanniktech.maven.publish", version = "0.29.0" }

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

244
gradlew vendored Executable file
View File

@ -0,0 +1,244 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# 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
#
# https://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.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

92
gradlew.bat vendored Normal file
View File

@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

BIN
images/draft_release.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

BIN
images/github_releases.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

BIN
images/github_secrets.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

BIN
images/release_settings.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

101
library/build.gradle.kts Normal file
View File

@ -0,0 +1,101 @@
import com.vanniktech.maven.publish.SonatypeHost
import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.androidLibrary)
alias(libs.plugins.vanniktech.mavenPublish)
kotlin("plugin.serialization") version "2.1.20"
}
group = "net.sergeych"
version = "0.0.1-SNAPSHOT"
kotlin {
jvm()
androidTarget {
publishLibraryVariants("release")
@OptIn(ExperimentalKotlinGradlePluginApi::class)
compilerOptions {
jvmTarget.set(JvmTarget.JVM_11)
}
}
// iosX64()
// iosArm64()
// iosSimulatorArm64()
linuxX64()
js(IR) {
browser()
nodejs()
}
sourceSets {
all {
languageSettings.optIn("kotlinx.coroutines.ExperimentalCoroutinesApi")
languageSettings.optIn("kotlin.ExperimentalUnsignedTypes")
languageSettings.optIn("kotlin.coroutines.DelicateCoroutinesApi")
}
val commonMain by getting {
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.8.1")
//put your multiplatform dependencies here
implementation(libs.kotlinx.coroutines.core)
implementation(libs.mp.bintools)
}
}
val commonTest by getting {
dependencies {
implementation(libs.kotlin.test)
implementation(libs.kotlinx.coroutines.test)
}
}
}
}
android {
namespace = "org.jetbrains.kotlinx.multiplatform.library.template"
compileSdk = libs.versions.android.compileSdk.get().toInt()
defaultConfig {
minSdk = libs.versions.android.minSdk.get().toInt()
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
}
mavenPublishing {
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
signAllPublications()
coordinates(group.toString(), "library", version.toString())
pom {
name = "Ling language"
description = "Kotlin-bound scripting loanguage"
inceptionYear = "2025"
// url = "https://sergeych.net"
licenses {
license {
name = "XXX"
url = "YYY"
distribution = "ZZZ"
}
}
developers {
developer {
id = "XXX"
name = "YYY"
url = "ZZZ"
}
}
scm {
url = "XXX"
connection = "YYY"
developerConnection = "ZZZ"
}
}
}

View File

@ -0,0 +1,12 @@
package net.sergeych.ling
data class Arguments(val list: List<Statement> ) {
val size by list::size
operator fun get(index: Int): Statement = list[index]
companion object {
val EMPTY = Arguments(emptyList())
}
}

View File

@ -0,0 +1,264 @@
package net.sergeych.ling
import kotlin.math.pow
sealed class ObjType(name: String, val defaultValue: Obj? = null) {
class Str : ObjType("string", ObjString(""))
class Int : ObjType("real", ObjReal(0.0))
}
/**
* Descriptor for whatever object could be used as argument, return value,
* field, etc.
*/
data class ObjDescriptor(
val type: ObjType,
val mutable: Boolean,
)
data class MethodDescriptor(
val args: Array<ObjDescriptor>,
val result: ObjDescriptor
)
/*
Meta context contains map of symbols.
Each symbol can be:
- a var
- a const
- a function
- a type alias
- a class definition
Each have in common only its name.
Var has: type, value. Const is same as var but value is fixed. Function has args and return value,
type alias has target type name. So we have to have something that denotes a _type_
*/
//data class MetaContext(val symbols: MutableMap<String, > = mutableMapOf()) {
//
//}
class Compiler {
fun compile(source: Source): Script {
val tokens = parseLing(source).listIterator()
val start = source.startPos
// at this level: "global" context: just script to execute or new function
// declaration forming closures
val statements = mutableListOf<Statement>()
while (parseStatement(tokens)?.also {
statements += it
} != null) {/**/
}
return Script(start, statements)
}
private fun parseStatement(tokens: ListIterator<Token>): Statement? {
val t = tokens.next()
return when (t.type) {
Token.Type.ID -> {
// could be keyword, assignment or just the expression
val next = tokens.next()
if (next.type == Token.Type.EQ) {
// this _is_ assignment statement
AssignStatement(
t.pos, t.value,
parseExpression(tokens) ?: throw ScriptError(
t.pos,
"Expecting expression for assignment operator"
)
)
}
// not assignment, maybe keyword statement:
// get back the token which is not '=':
tokens.previous()
// try keyword statement
parseKeywordStatement(t, tokens)
?: run {
parseExpression(tokens)
}
}
Token.Type.EOF -> null
else -> {
// could be expression
tokens.previous()
parseExpression(tokens)
}
}
}
private fun parseExpression(tokens: ListIterator<Token>, level: Int = 0): Statement? {
if (level == lastLevel)
return parseTerm(tokens)
var lvalue = parseExpression(tokens, level + 1)
if (lvalue == null) return null
while (true) {
val opToken = tokens.next()
val op = byLevel[level][opToken.value]
if (op == null) {
tokens.previous()
break
}
val rvalue = parseExpression(tokens, level + 1)
?: throw ScriptError(opToken.pos, "Expecting expression")
lvalue = op.generate(opToken.pos, lvalue!!, rvalue)
}
return lvalue
}
fun parseTerm(tokens: ListIterator<Token>): Statement? {
// call op
// index op
// unary op
// parenthesis
// number or string
val t = tokens.next()
// todoL var?
return when (t.type) {
// "+" -> statement { parseNumber(true,tokens) }??????
// "-" -> statement { parseNumber(false,tokens) }
// "~" -> statement(t.pos) { ObjInt( parseLong(tokens)) }
Token.Type.PLUS -> {
val n = parseNumber(true, tokens)
statement(t.pos) { n }
}
Token.Type.MINUS -> {
val n = parseNumber(false, tokens)
statement(t.pos) { n }
}
Token.Type.INT, Token.Type.REAL, Token.Type.HEX -> {
tokens.previous()
val n = parseNumber(true, tokens)
statement(t.pos) { n }
}
else -> null
}
}
fun parseLong(tokens: ListIterator<Token>): Long =
// todo: hex notation?
getLong(tokens)
fun getLong(tokens: ListIterator<Token>): Long {
val t = tokens.next()
if (t.type != Token.Type.INT) throw ScriptError(t.pos, "expected number here")
return t.value.toLong()
}
fun parseNumber(isPlus: Boolean, tokens: ListIterator<Token>): Obj {
val t = tokens.next()
return when (t.type) {
Token.Type.INT, Token.Type.HEX -> {
val n = t.value.toLong(if (t.type == Token.Type.HEX) 16 else 10)
if (isPlus) ObjInt(n) else ObjInt(-n)
}
Token.Type.REAL -> {
val d = t.value.toDouble()
if (isPlus) ObjReal(d) else ObjReal(-d)
}
else -> {
throw ScriptError(t.pos, "expected number")
}
}
}
/**
* Parse keyword-starting statenment.
* @return parsed statement or null if, for example. [id] is not among keywords
*/
private fun parseKeywordStatement(id: Token, tokens: ListIterator<Token>): Statement? {
return null
}
// fun parseStatement(parser: Parser): Statement? =
// parser.withToken {
// if (tokens.isEmpty()) null
// else {
// when (val token = tokens[0]) {
// else -> {
// rollback()
// null
// }
// }
// }
// }
companion object {
data class Operator(
val name: String,
val priority: Int, val arity: Int,
val generate: (Pos, Statement, Statement) -> Statement
)
val allOps = listOf(
// Operator("||", 0, 2) { pos, a, b -> LogicalOrStatement(pos, a, b) })
Operator("&&", 1, 2) { pos, a, b ->
LogicalAndStatement(pos, a, b)
},
// bitwise or 2
// bitwise and 3
// equality/ne 4
// relational <=,... 5
// shuttle <=> 6
// bitshhifts 7
// + - : 7
Operator("+", 7, 2) { pos, a, b ->
PlusStatement(pos, a, b)
},
Operator("-", 7, 2) { pos, a, b ->
MinusStatement(pos, a, b)
},
// * / %: 8
)
val lastLevel = 9
val byLevel: List<Map<String, Operator>> = (0..<lastLevel).map { l ->
allOps.filter { it.priority == l }
.map { it.name to it }.toMap()
}
fun compile(code: String): Script = Compiler().compile(Source("<eval>", code))
}
}
fun buildDoubleFromParts(
integerPart: Long,
decimalPart: Long,
exponent: Int
): Double {
// Handle zero decimal case efficiently
val numDecimalDigits = if (decimalPart == 0L) 0 else decimalPart.toString().length
// Calculate decimal multiplier (10^-digits)
val decimalMultiplier = 10.0.pow(-numDecimalDigits)
// Combine integer and decimal parts
val baseValue = integerPart.toDouble() + decimalPart.toDouble() * decimalMultiplier
// Apply exponent
return baseValue * 10.0.pow(exponent)
}
suspend fun eval(code: String) = Compiler.compile(code).execute()

View File

@ -0,0 +1,46 @@
package net.sergeych.ling
import kotlin.math.PI
class Context(
val callerPos: Pos,
val parent: Context? = null,
val args: Arguments = Arguments.EMPTY
) {
data class Item(
val name: String, var value: Obj?,
val isMutable: Boolean = false
)
private val objects = mutableMapOf<String, Item>()
operator fun get(name: String): Item? = objects[name] ?: parent?.get(name)
fun copy(from: Pos, args: Arguments = Arguments.EMPTY): Context = Context(from, this, args)
fun addFn(name: String, fn: suspend Context.() -> Obj) = objects.put(name, Item(name,
object : Statement() {
override val pos: Pos = Pos.builtIn
override suspend fun execute(context: Context): Obj {
return try {
context.fn()
} catch (e: Exception) {
raise(e.message ?: "unexpected error")
}
}
})
)
}
val basicContext = Context(Pos.builtIn).apply {
addFn("println") {
require(args.size == 1)
println(args[0].execute(this).asStr.value)
Void
}
addFn("π") { ObjReal(PI) }
}

View File

@ -0,0 +1,59 @@
package net.sergeych.ling
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlin.math.floor
@Serializable
sealed class Obj {
open val asStr: ObjString by lazy {
if( this is ObjString) this else ObjString(this.toString())
}
}
@Serializable
@SerialName("void")
object Void: Obj() {
override fun equals(other: Any?): Boolean {
return other is Void || other is Unit
}
}
@Serializable
@SerialName("string")
data class ObjString(val value: String): Obj() {
override fun toString(): String = value
}
interface Numeric {
val longValue: Long
val doubleValue: Double
val toObjInt: ObjInt
val toObjReal: ObjReal
}
@Serializable
@SerialName("real")
data class ObjReal(val value: Double): Obj(), Numeric {
override val asStr by lazy { ObjString(value.toString()) }
override val longValue: Long by lazy { floor(value).toLong() }
override val doubleValue: Double by lazy { value }
override val toObjInt: ObjInt by lazy { ObjInt(longValue) }
override val toObjReal: ObjReal by lazy { ObjReal(value) }
}
@Serializable
@SerialName("int")
data class ObjInt(val value: Long): Obj(), Numeric {
override val asStr by lazy { ObjString(value.toString()) }
override val longValue: Long by lazy { value }
override val doubleValue: Double by lazy { value.toDouble() }
override val toObjInt: ObjInt by lazy { ObjInt(value) }
override val toObjReal: ObjReal by lazy { ObjReal(doubleValue) }
}
@Serializable
@SerialName("bool")
data class ObjBool(val value: Boolean): Obj() {
override val asStr by lazy { ObjString(value.toString()) }
}

View File

@ -0,0 +1,184 @@
package net.sergeych.ling
private val idFirstChars: Set<Char> = (
('a'..'z') + ('A'..'Z') + '_' + ('а'..'я') + ('А'..'Я')
).toSet()
val idNextChars: Set<Char> = idFirstChars + ('0'..'9')
val digits = ('0'..'9').toSet()
val hexDigits = digits + ('a'..'f') + ('A'..'F')
fun parseLing(source: Source): List<Token> {
val p = Parser(fromPos = source.startPos)
val tokens = mutableListOf<Token>()
do {
val t = p.nextToken()
tokens += t
} while(t.type != Token.Type.EOF)
return tokens
}
private class Parser(fromPos: Pos) {
private val pos = MutablePos(fromPos)
/**
* Immutable copy of current position
*/
private val currentPos: Pos get() = pos.toPos()
private fun raise(msg: String): Nothing = throw ScriptError(currentPos, msg)
fun nextToken(): Token {
skipws()
if (pos.end) return Token("", currentPos, Token.Type.EOF)
val from = currentPos
return when (val ch = pos.currentChar.also { advance() }) {
'(' -> Token("(", from, Token.Type.LPAREN)
')' -> Token(")", from, Token.Type.RPAREN)
'{' -> Token("{", from, Token.Type.LBRACE)
'}' -> Token("}", from, Token.Type.RBRACE)
'[' -> Token("[", from, Token.Type.LBRACKET)
']' -> Token("]", from, Token.Type.RBRACKET)
',' -> Token(",", from, Token.Type.COMMA)
';' -> Token(";", from, Token.Type.SEMICOLON)
'=' -> Token("=", from, Token.Type.ASSIGN)
'+' -> Token("+", from, Token.Type.PLUS)
'-' -> Token("-", from, Token.Type.MINUS)
'*' -> Token("*", from, Token.Type.STAR)
'/' -> Token("/", from, Token.Type.SLASH)
'.' -> Token(".", from, Token.Type.DOT)
'<' -> Token("<", from, Token.Type.LT)
'>' -> Token(">", from, Token.Type.GT)
'!' -> Token("!", from, Token.Type.NOT)
'"' -> loadStringToken()
in digits -> {
pos.back()
decodeNumber(loadChars(digits), from)
}
in idFirstChars -> {
// it includes first char, so from current position
Token(ch + loadChars(idNextChars), from, Token.Type.ID)
}
else -> raise("can't parse token")
}
}
private fun decodeNumber(p1: String, start: Pos): Token =
if( pos.end )
Token(p1, start, Token.Type.INT)
else if( currentChar == '.' ) {
// could be decimal
advance()
if( currentChar in digits ) {
// decimal part
val p2 = loadChars(digits)
// with exponent?
if( currentChar == 'e' || currentChar == 'E') {
advance()
var negative = false
if(currentChar == '+' )
advance()
else if(currentChar == '-') {
negative = true
advance()
}
var p3 = loadChars(digits)
if( negative ) p3 = "-$p3"
Token("$p1.${p2}e$p3", start, Token.Type.REAL)
}
else {
// no exponent
Token("$p1.$p2", start, Token.Type.REAL)
}
}
else {
// not decimal
// something like 10.times, method call on integer number
pos.back()
Token(p1, start, Token.Type.INT)
}
}
else {
// could be integer, also hex:
if (currentChar == 'x' && p1 == "0") {
advance()
Token(loadChars(hexDigits), start, Token.Type.HEX).also {
if( currentChar.isLetter() )
raise("invalid hex literal")
}
} else {
Token(p1, start, Token.Type.INT)
}
}
private val currentChar: Char get() = pos.currentChar
private fun loadStringToken(): Token {
var start = currentPos
if (currentChar == '"') advance()
else start = start.back()
val sb = StringBuilder()
while (currentChar != '"') {
if( pos.end ) raise("unterminated string")
when (currentChar) {
'\\' -> {
advance() ?: raise("unterminated string")
when (currentChar) {
'n' -> sb.append('\n')
'r' -> sb.append('\r')
't' -> sb.append('\t')
'"' -> sb.append('"')
else -> sb.append('\\').append(currentChar)
}
}
else -> {
sb.append(currentChar)
advance()
}
}
}
advance()
return Token(sb.toString(), start, Token.Type.STRING)
}
/**
* Load characters from the set until it reaches EOF or invalid character found.
* stop at EOF on character not in [validChars].
* @return the string of valid characters, could be empty
*/
private fun loadChars(validChars: Set<Char>): String {
val result = StringBuilder()
while (!pos.end) {
val ch = pos.currentChar
if (ch in validChars) {
result.append(ch)
advance()
} else
break
}
return result.toString()
}
/**
* next non-whitespace char (newline are skipped too) or null if EOF
*/
private fun skipws(): Char? {
while (!pos.end) {
val ch = pos.currentChar
if (ch.isWhitespace())
advance()
else
return ch
}
return null
}
private fun advance() = pos.advance()
init {
// advance()
}
}

View File

@ -0,0 +1,69 @@
package net.sergeych.ling
data class Pos(val source: Source, val line: Int, val column: Int) {
override fun toString(): String {
return "${source.fileName}:$line:$column"
}
fun back(): Pos =
if( column > 0) Pos(source, line, column-1)
else if( line > 0) Pos(source, line-1, source.lines[line-1].length - 1)
else throw IllegalStateException("can't go back from line 0, column 0")
val currentLine: String get() = source.lines[line]
val showSource: String by lazy {
source.lines[line] + "\n" + "-".repeat(column - 1) + "^\n"
}
companion object {
val builtIn = Pos(Source.builtIn, 0, 0)
}
}
class MutablePos(private val from: Pos) {
val lines = from.source.lines
var line = from.line
private set
var column = from.column
private set
val end: Boolean get() =
line == lines.size
fun reset(to: Pos) {
line = to.line
column = to.column
}
fun toPos(): Pos = Pos(from.source, line, column)
fun advance(): Char? {
if (end) return null
val current = lines[line]
return if (column+1 < current.length) {
current[column++]
} else {
line++
column = 0
if(line >= lines.size) null
else lines[line][column]
}
}
fun back() {
if (column > 0) column--
else if (line > 0)
column = lines[--line].length - 1
else throw IllegalStateException("can't go back from line 0, column 0")
}
val currentChar: Char
get() =
if (end) 0.toChar()
else lines[line][column]
override fun toString() = "($line:$column)"
}

View File

@ -0,0 +1,22 @@
package net.sergeych.ling
class Script(
override val pos: Pos,
private val statements: List<Statement> = emptyList(),
) : Statement() {
override suspend fun execute(context: Context): Obj {
// todo: run script
var lastResult: Obj = Void
for (s in statements) {
lastResult = s.execute(context)
}
return lastResult
}
suspend fun execute() = execute(defaultContext)
companion object {
val defaultContext: Context = Context(Pos.builtIn)
}
}

View File

@ -0,0 +1,9 @@
package net.sergeych.ling
class ScriptError(val pos: Pos, val errorMessage: String) : Exception(
"""
$pos: Error: $errorMessage
${pos.currentLine}
${"-".repeat(pos.column)}^
""".trimIndent()
)

View File

@ -0,0 +1,14 @@
package net.sergeych.ling
class Source(val fileName: String, text: String) {
val lines = text.lines().map { it.trimEnd() }
companion object {
val builtIn: Source by lazy { Source("built-in", "") }
}
val startPos: Pos = Pos(this, 0, 0)
fun posAt(line: Int, column: Int): Pos = Pos(this, line, column)
}

View File

@ -0,0 +1,12 @@
package net.sergeych.ling
data class Token(val value: String, val pos: Pos, val type: Type) {
enum class Type {
ID, INT, REAL, HEX, STRING, LPAREN, RPAREN, LBRACE, RBRACE, LBRACKET, RBRACKET, COMMA,
SEMICOLON, COLON, EQ, PLUS, MINUS, STAR, SLASH, ASSIGN, EQEQ, NEQ, LT, LTEQ, GT,
GTEQ, AND, OR, NOT, DOT, ARROW, QUESTION, COLONCOLON, EOF,
}
companion object {
// fun eof(parser: Parser) = Token("", parser.currentPos, Type.EOF)
}
}

View File

@ -0,0 +1,117 @@
package net.sergeych.ling
fun String.toSource(name: String = "eval"): Source = Source(name, this)
abstract class Statement : Obj() {
abstract val pos: Pos
abstract suspend fun execute(context: Context): Obj
}
fun Statement.raise(text: String): Nothing {
throw ScriptError(pos, text)
}
fun Statement.require(cond: Boolean, message: () -> String) {
if (!cond) raise(message())
}
fun statement(pos: Pos, f: suspend (Context) -> Obj): Statement = object : Statement() {
override val pos: Pos = pos
override suspend fun execute(context: Context): Obj = f(context)
}
class IfStatement(
override val pos: Pos,
val cond: Statement, val ifTrue: Statement, val ifFalse: Statement?
) : Statement() {
override suspend fun execute(context: Context): Obj {
val c = cond.execute(context)
if (c !is ObjBool)
raise("if: condition must me boolean, got: $c")
return if (c.value) ifTrue.execute(context) else ifFalse?.execute(context) ?: Void
}
}
class LogicalAndStatement(
override val pos: Pos,
val left: Statement, val right: Statement
) : Statement() {
override suspend fun execute(context: Context): Obj {
val l = left.execute(context).let {
(it as? ObjBool) ?: raise("logical and: left operand is not boolean: $it")
}
val r = right.execute(context).let {
(it as? ObjBool) ?: raise("logical and: right operand is not boolean: $it")
}
return ObjBool(l.value && r.value)
}
}
class PlusStatement(
override val pos: Pos,
val left: Statement, val right: Statement
) : Statement() {
override suspend fun execute(context: Context): Obj {
// todo: implement also classes with 'plus' operator
val l = left.execute(context)
if (l is ObjString)
return ObjString(l.toString() + right.execute(context).toString())
if (l !is Numeric)
raise("left operand is not number: $l")
val r = right.execute(context)
if (r !is Numeric)
raise("right operand is not boolean: $r")
return if (l is ObjInt && r is ObjInt)
ObjInt(l.longValue + r.longValue)
else
ObjReal(l.doubleValue + r.doubleValue)
}
}
class MinusStatement(
override val pos: Pos,
val left: Statement, val right: Statement
) : Statement() {
override suspend fun execute(context: Context): Obj {
// todo: implement also classes with 'minus' operator
val l = left.execute(context)
if (l !is Numeric)
raise("left operand is not number: $l")
val r = right.execute(context)
if (r !is Numeric)
raise("right operand is not number: $r")
return if (l is ObjInt && r is ObjInt)
ObjInt(l.longValue - r.longValue)
else
ObjReal(l.doubleValue - r.doubleValue)
}
}
class AssignStatement(override val pos: Pos, val name: String, val value: Statement) : Statement() {
override suspend fun execute(context: Context): Obj {
val variable = context[name] ?: raise("can't assign: variable does not exist: $name")
variable.value = value.execute(context)
return Void
}
}
class CallStatement(
override val pos: Pos,
val name: String,
val args: Arguments = Arguments.EMPTY
) : Statement() {
override suspend fun execute(context: Context): Obj {
val callee = context[name] ?: raise("Call: unknown name: $name")
return (callee.value as? Statement)?.execute(context.copy(pos, args))
?: raise("Call: not a callable object: $callee")
}
}

View File

@ -0,0 +1,112 @@
package io.github.kotlin.fibonacci
import kotlinx.coroutines.test.runTest
import net.sergeych.ling.*
import kotlin.test.Test
import kotlin.test.assertEquals
class ScriptTest {
@Test
fun level0() = runTest {
val s = Script(
Pos.builtIn,
listOf(
CallStatement(
Pos.builtIn, "println",
Arguments(listOf(CallStatement(Pos.builtIn, "π", Arguments.EMPTY)))
)
)
)
s.execute(basicContext)
}
fun parseFirst(str: String): Token =
parseLing(str.toSource()).firstOrNull()!!
@Test
fun parseNumbers() {
fun check(expected: String, type: Token.Type, row: Int, col: Int, src: String, offset: Int = 0) {
val source = src.toSource()
assertEquals(
Token(expected, source.posAt(row, col), type),
parseLing(source)[offset]
)
}
check("1", Token.Type.INT, 0, 0, "1")
check("7", Token.Type.INT, 0, 0, "7")
check("17", Token.Type.INT, 0, 0, "17")
check("17", Token.Type.INT, 0, 0, "17.")
check(".", Token.Type.DOT, 0, 2, "17.", 1)
// decimals
check("17.2", Token.Type.REAL, 0, 0, "17.2")
check("17.2", Token.Type.REAL, 0, 0, "17.2")
check("17.2", Token.Type.REAL, 0, 0, "17.2 ")
check("17.2", Token.Type.REAL, 0, 1, " 17.2")
check("17.2", Token.Type.REAL, 0, 2, " 17.2 ")
check("17.2e0", Token.Type.REAL, 0, 0, "17.2e0")
check("17.2e-22", Token.Type.REAL, 0, 0, "17.2e-22")
check("17.2e22", Token.Type.REAL, 0, 0, "17.2e+22")
check("17.2e22", Token.Type.REAL, 0, 0, "17.2E+22")
check("17.2e22", Token.Type.REAL, 0, 0, "17.2E22")
check("17.2e-22", Token.Type.REAL, 0, 0, "17.2E-22")
// hex
check("1", Token.Type.HEX, 0, 0, "0x1")
check("12", Token.Type.HEX, 0, 0, "0x12")
check("12abcdef", Token.Type.HEX, 0, 0, "0x12abcdef.gh")
check(".", Token.Type.DOT, 0, 10, "0x12abcdef.gh", 1)
check("gh", Token.Type.ID, 0, 11, "0x12abcdef.gh", 2)
check("5", Token.Type.INT, 0, 0, "5 6")
check("6", Token.Type.INT, 0, 2, "5 6", 1)
}
@Test
fun parse0() {
val src = """
println("Hello")
println( "world" )
""".trimIndent().toSource()
val p = parseLing(src).listIterator()
assertEquals(Token("println", src.posAt(0, 0), Token.Type.ID), p.next())
assertEquals(Token("(", src.posAt(0, 7), Token.Type.LPAREN), p.next())
assertEquals(Token("Hello", src.posAt(0, 8), Token.Type.STRING), p.next())
assertEquals(Token(")", src.posAt(0, 15), Token.Type.RPAREN), p.next())
assertEquals(Token("println", src.posAt(1, 0), Token.Type.ID), p.next())
assertEquals(Token("(", src.posAt(1, 7), Token.Type.LPAREN), p.next())
assertEquals(Token("world", src.posAt(1, 9), Token.Type.STRING), p.next())
assertEquals(Token(")", src.posAt(1, 17), Token.Type.RPAREN), p.next())
}
@Test
fun parse1() {
val src = "2 + 7".toSource()
val p = parseLing(src).listIterator()
assertEquals(Token("2", src.posAt(0, 0), Token.Type.INT), p.next())
assertEquals(Token("+", src.posAt(0, 2), Token.Type.PLUS), p.next())
assertEquals(Token("7", src.posAt(0, 4), Token.Type.INT), p.next())
}
@Test
fun compileNumbers() = runTest {
assertEquals(ObjInt(17), eval("17"))
assertEquals(ObjInt(17), eval("+17"))
assertEquals(ObjInt(-17), eval("-17"))
assertEquals(ObjInt(1970), eval("1900 + 70"))
assertEquals(ObjInt(1970), eval("2000 - 30"))
// assertEquals(ObjReal(3.14), eval("3.14"))
assertEquals(ObjReal(314.0), eval("3.14e2"))
}
}

381
publishing-readme.md Normal file
View File

@ -0,0 +1,381 @@
[![official project](http://jb.gg/badges/official.svg)](https://github.com/JetBrains#jetbrains-on-github)
# Multiplatform library template
## What is it?
This repository contains a simple library project, intended to demonstrate a [Kotlin Multiplatform](https://kotlinlang.org/docs/multiplatform.html) library that is deployable to [Maven Central](https://central.sonatype.com/).
The library has only one function: generate the [Fibonacci sequence](https://en.wikipedia.org/wiki/Fibonacci_sequence) starting from platform-provided numbers. Also, it has a test for each platform just to be sure that tests run.
Note that no other actions or tools usually required for the library development are set up, such as [tracking of backwards compatibility](https://kotlinlang.org/docs/jvm-api-guidelines-backward-compatibility.html#tools-designed-to-enforce-backward-compatibility), explicit API mode, licensing, contribution guideline, code of conduct and others. You can find a guide for best practices for designing Kotlin libraries [here](https://kotlinlang.org/docs/api-guidelines-introduction.html).
## How to publish?
This guide describes the steps of publishing a library built with Kotlin Multiplatform to the [Maven Central repository](https://central.sonatype.com/). To publish your library, you’ll need to:
* Set up credentials, including an account on Maven Central and a PGP key to use for signing.
* Configure the publishing plugin in your library’s project.
* Provide your credentials to the publishing plugin so it can sign and upload your artifacts.
* Run the publication task, either locally or using continuous integration.
This guide assumes that you are:
- Creating an open-source library.
- Using macOS or Linux. If you are a Windows user, use [GnuPG or Gpg4win](https://gnupg.org/download) to generate a key pair.
- Either not registered on Maven Central yet, or have an existing account that’s suitable for [publishing to the Central Portal](https://central.sonatype.org/publish-ea/publish-ea-guide/) (created after March 12th, 2024, or migrated to the Central Portal by their support).
- Publishing your library in a GitHub repository.
- Using GitHub Actions for continuous integration.
Most of the steps here are still applicable if you’re using a different setup, but there might be some differences you need to account for. An [important limitation](https://kotlinlang.org/docs/multiplatform-publish-lib.html#host-requirements) is that Apple targets must be built on a machine with macOS.
Throughout this guide, we’ll use the [https://github.com/kotlin-hands-on/fibonacci](https://github.com/kotlin-hands-on/fibonacci) repository as an example. You can refer to the code of this repository to see how the publishing setup works. You **must replace all example values with your own** as you’re configuring your project.
### Prepare accounts and credentials
#### Register a namespace
Artifacts published to Maven repositories are identified by their coordinates, for example `com.example:library:1.0.0`. These coordinates are made up of three parts, separated by colons: the `groupId`, `artifactId`, and `version`.
As a first step for publishing to Maven Central, you’ll need to have a verified namespace. The `groupId` of the artifacts you publish will have to start with the name of your verified namespace. For example, if you register the `com.example` namespace, you’ll be able to publish artifacts with the `groupId` set to `com.example` or `com.example.libraryname`.
To get started with publishing to Maven Central, sign in (or create a new account) on the [Maven Central](https://central.sonatype.com/) portal. Once signed in, navigate to [Namespaces](https://central.sonatype.com/publishing/namespaces) under your profile, and click the Add Namespace button. Here, you can register a namespace for your artifacts, either based on your GitHub account or a domain name that you own.
**For a GitHub repository**
Using your GitHub account to create a namespace is a good option if you don’t own a domain name to use for publication. To create a namespace based on your GitHub account:
1. Enter `io.github.<your username>` as your namespace. For example, `io.github.kotlin-hands-on`.
2. Copy the Verification Key displayed.
3. On GitHub, create a new repository with your GitHub account with the verification key as the repository’s name. For example, `http://github.com/kotlin-hands-on/ex4mpl3c0d`.
4. Navigate back to Maven Central, and click on the Verify Namespace button. After verification succeeds you can delete the repository you’ve created.
**For a domain name**
To use a domain name that you own as your namespace:
1. Enter your domain as the namespace using a reverse-DNS form. If your domain is `example.com`, enter `com.example`.
2. Copy the Verification Key displayed.
3. Create a new DNS TXT record with the verification key as its contents. See [Maven Central’s FAQ](https://central.sonatype.org/faq/how-to-set-txt-record/) for more information on how to do this with various domain registrars.
4. Navigate back to Maven Central, and click on the Verify Namespace button. After verification succeeds you can delete the TXT record you’ve created.
#### Generate a Key Pair
Artifacts published to Maven Central [must be signed with a PGP signature](https://central.sonatype.org/publish/requirements/gpg/), which allows users to validate the origin of artifacts.
To get started with signing, you’ll need to generate a key pair:
* The **private key** is used to sign your artifacts, and should never be shared with others.
* The **public key** can be used by others to validate the signature of the artifacts, and should be published.
The `gpg` tool that can manage signatures for you is available from [their website](https://gnupg.org/download/index.html). You can also install it using package managers such as [Homebrew](https://brew.sh/):
```bash
brew install gpg
```
Generate a key pair with the following command, and fill in the required details when prompted.
```bash
gpg --full-generate-key
```
Choose the recommended defaults for the type of key to be created. You can leave these selections empty and press Enter to accept the default values.
> [!NOTE]
> At the time of writing, this is `ECC (sign and encrypt)` with `Curve 25519`. Older versions of `gpg` might default to `RSA` with a `3072` bit key size.
Next, you’ll be prompted to set the expiration of the key. If you choose to create a key that automatically expires after a set amount of time, you’ll need to [extend its validity](https://central.sonatype.org/publish/requirements/gpg/#dealing-with-expired-keys) when it expires.
You will be asked for your real name, email, and a comment. You can leave the comment empty.
```text
Please select what kind of key you want:
(1) RSA and RSA
(2) DSA and Elgamal
(3) DSA (sign only)
(4) RSA (sign only)
(9) ECC (sign and encrypt) *default*
(10) ECC (sign only)
(14) Existing key from card
Your selection? 9
Please select which elliptic curve you want:
(1) Curve 25519 *default*
(4) NIST P-384
(6) Brainpool P-256
Your selection? 1
Please specify how long the key should be valid.
0 = key does not expire
<n> = key expires in n days
<n>w = key expires in n weeks
<n>m = key expires in n months
<n>y = key expires in n years
Key is valid for? (0) 0
Key does not expire at all
Is this correct? (y/N) y
GnuPG needs to construct a user ID to identify your key.
```
You will be asked for a passphrase to encrypt the key, which you have to repeat. Keep this passphrase stored securely and privately. You’ll be using it later to access the private key.
Let’s take a look at the key we’ve created with the following command:
```bash
gpg --list-keys
```
The output will look something like this:
```text
pub ed25519 2024-10-06 [SC]
F175482952A225BFC4A07A715EE6B5F76620B385CE
uid [ultimate] Your name <your email address>
sub cv25519 2024-10-06 [E]
```
You’ll need to use the long alphanumerical identifier of your key displayed here in the following steps.
#### Upload the public key
You need to [upload the public key to a keyserver](https://central.sonatype.org/publish/requirements/gpg/#distributing-your-public-key) for it to be accepted by Maven Central. There are multiple available keyservers, we’ll use `keyserver.ubuntu.com` as a default choice.
Run the following command to upload your public key using `gpg`, **substituting your own keyid** in the parameters:
```bash
gpg --keyserver keyserver.ubuntu.com --send-keys F175482952A225BFC4A07A715EE6B5F76620B385CE
```
#### Export your private key
To let your Gradle project access your private key, you’ll need to export it to a file. Use the following command, **passing in your own keyid** as a parameter. You will be prompted to enter the passphrase you’ve used when creating the key.
```bash
gpg --armor --export-secret-keys F175482952A225BFC4A07A715EE6B5F76620B385CE > key.gpg
```
This will create a `key.gpg` file which contains your private key.
> [!CAUTION]
> Never share a private key with anyone.
If you check the contents of the file, you should see contents similar to this:
```text
-----BEGIN PGP PRIVATE KEY BLOCK-----
lQdGBGby2X4BEACvFj7cxScsaBpjty60ehgB6xRmt8ayt+zmgB8p+z8njF7m2XiN
...
bpD/h7ZI7FC0Db2uCU4CYdZoQVl0MNNC1Yr56Pa68qucadJhY0sFNiB63KrBUoiO
-----END PGP PRIVATE KEY BLOCK-----
```
#### Generate the user token
Your project will also need to authenticate with Maven Central to upload artifacts. On the Central Portal, navigate to the [Account](https://central.sonatype.com/account) page, and click on *Generate User Token*.
The output will look like the example below, containing a username and a password. Store this information securely, as it can’t be viewed again on the Central Portal. If you lose these credentials, you’ll need to generate new ones later.
```xml
<server>
<id>${server}</id>
<username>l3nfaPmz</username>
<password>gh9jT9XfnGtUngWTZwTu/8241keYdmQpipqLPRKeDLTh</password>
</server>
```
### Configure the project
#### Prepare your library project
If you started developing your library from a template project, this is a good time to change any default names in the project to match your own library’s name. This includes the name of your library module, and the name of the root project in your top-level `build.gradle.kts` file.
If you have an Android target in your project, you should follow the [steps to prepare your Android library release](https://developer.android.com/build/publish-library/prep-lib-release). This, at a minimum, requires you to [specify an appropriate namespace](https://developer.android.com/build/publish-library/prep-lib-release#choose-namespace) for your library, so that a unique R class will be generated when their resources are compiled. Notice that the namespace is different from the Maven namespace created in the [Register a namespace](#register-a-namespace) section above.
```kotlin
// build.gradle.kts
android {
namespace = "io.github.kotlinhandson.fibonacci"
}
```
#### Set up the publishing plugin
This guide uses [vanniktech/gradle-maven-publish-plugin](https://github.com/vanniktech/gradle-maven-publish-plugin) to help with publications to Maven Central. You can read more about the advantages of the plugin [here](https://vanniktech.github.io/gradle-maven-publish-plugin/#advantages-over-maven-publish). See the [plugin’s documentation](https://vanniktech.github.io/gradle-maven-publish-plugin/central/) to learn more about its usage and available configuration options.
To add the plugin to your project, add the following line in the plugins block, in your library module’s `build.gradle.kts` file:
```kotlin
// build.gradle.kts
plugins {
id("com.vanniktech.maven.publish") version "0.29.0"
}
```
*Note: for the latest available version of the plugin, check its [releases page](https://github.com/vanniktech/gradle-maven-publish-plugin/releases).*
In the same file, add the following configuration. Customize all these values appropriately for your library.
```kotlin
// build.gradle.kts
mavenPublishing {
publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL)
signAllPublications()
coordinates(group.toString(), "fibonacci", version.toString())
pom {
name = "Fibonacci library"
description = "A mathematics calculation library."
inceptionYear = "2024"
url = "https://github.com/kotlin-hands-on/fibonacci/"
licenses {
license {
name = "The Apache License, Version 2.0"
url = "https://www.apache.org/licenses/LICENSE-2.0.txt"
distribution = "https://www.apache.org/licenses/LICENSE-2.0.txt"
}
}
developers {
developer {
id = "kotlin-hands-on"
name = "Kotlin Developer Advocate"
url = "https://github.com/kotlin-hands-on/"
}
}
scm {
url = "https://github.com/kotlin-hands-on/fibonacci/"
connection = "scm:git:git://github.com/kotlin-hands-on/fibonacci.git"
developerConnection = "scm:git:ssh://git@github.com/kotlin-hands-on/fibonacci.git"
}
}
}
```
Note that it’s also possible to use Gradle properties instead.
Some of the most important, required settings here are:
* The `coordinates`, which specify the `groupId`, `artifactId`, and `version` of your library.
* The [license](https://central.sonatype.org/publish/requirements/#license-information) that you’re publishing your library under.
* The [developer information](https://central.sonatype.org/publish/requirements/#developer-information) which lists the authors of the library.
* [SCM (Source Code Management) information](https://central.sonatype.org/publish/requirements/#scm-information), which specifies where the sources of your library are available.
### Publish to Maven Central from Continuous Integration
#### Add a GitHub Actions workflow to your project
You can set up continuous integration which builds and publishes your library for you. We’ll use [GitHub Actions](https://docs.github.com/en/actions) as an example.
To get started, add the following workflow to your repository, in the `.github/workflows/publish.yml` file.
```yaml
# .github/workflows/publish.yml
name: Publish
on:
release:
types: [released, prereleased]
jobs:
publish:
name: Release build and publish
runs-on: macOS-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Set up JDK 21
uses: actions/setup-java@v4
with:
distribution: 'zulu'
java-version: 21
- name: Publish to MavenCentral
run: ./gradlew publishToMavenCentral --no-configuration-cache
env:
ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }}
ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }}
ORG_GRADLE_PROJECT_signingInMemoryKeyId: ${{ secrets.SIGNING_KEY_ID }}
ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }}
ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.GPG_KEY_CONTENTS }}
```
After committing and pushing this change, this workflow will run automatically when you create a release (including a pre-release) in the GitHub repository hosting your project. It checks out the current version of your code, sets up a JDK, and then runs the `publishToMavenCentral` Gradle task.
> [!NOTE]
> Alternatively, you could configure the workflow to [trigger when a tag is pushed](https://stackoverflow.com/a/61892639) to your repository.
>
> The script above disables Gradle [configuration cache](https://docs.gradle.org/current/userguide/configuration_cache.html) for the publication task by adding `--no-configuration-cache` to the Gradle command, as the publication plugin does not support it (see this [open issue](https://github.com/gradle/gradle/issues/22779)).
>
> Reminder: When using `publishToMavenCentral`, you’ll still need to check and release your deployment manually on the website, as described in the previous section. You may use `publishAndReleaseToMavenCentral` instead for a fully automated release.
This action will need your signing details and your Maven Central credentials. These will be configured as GitHub Actions secrets in the next section. The configuration of the workflow above takes these secrets and places them into environment variables, which will make them available to the Gradle build automatically.
### Add secrets to GitHub
To use the keys and credentials required for publication in your GitHub Action workflow while keeping them private, you need to place those values into secrets. From your GitHub repository, go to `Settings` \> `(Security) Secrets and variables > Actions`.
Click on the `New repository secret` button, and add the following secrets:
- `MAVEN_CENTRAL_PASSWORD` and `MAVEN_CENTRAL_PASSWORD` are the values generated by the Central Portal website in the [Generate User Token](#generate-the-user-token) section.
- `SIGNING_KEY_ID` is **the last 8 characters** of your signing key’s identifier.
- `SIGNING_PASSWORD` is the passphrase you’ve provided when generating your signing key.
- `GPG_KEY_CONTENTS` should contain the contents of your GPG private key file, which you’ve created earlier in the [Export your private key](#export-your-private-key) section.
![](/images/github_secrets.png)
Note again that the names used for these secrets must match those used by the workflow that accesses their values.
#### Create a release on GitHub
With the workflow and secrets set up, you’re now ready to [create a release](https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository#creating-a-release) that will trigger the publication of your library.
Go to your GitHub repository’s main page, and click on Releases in the menu in the right sidebar.
![](/images/github_releases.png)
Click *Draft a new release*.
![](/images/draft_release.png)
Each release creates a new tag. Set the name for the tag to be created, and set a name for the release (these may be identical). Note that setting a version here does not change the version of your coordinates configured in your `build.gradle.kts` file, so you should update that version before creating a new release.
![](/images/create_release_and_tag.png)
Double-check the branch you want to target with the release (especially if you want to release from a branch that’s different from your default), and add appropriate release notes for your new version.
The checkboxes below allow you to mark a release as a pre-release (useful for alpha, beta, or RC versions of a library), or to set the release as the latest available one:
![](/images/release_settings.png)
Click the *Publish release* button to create the new release. This will immediately show up on your GitHub repository’s main page.
Click the Actions tab on the top of your GitHub repository. Here you’ll see the new workflow was triggered by the GitHub release. Click it to see the outputs of the publication task.
After this task completes successfully, navigate to the [Deployments](https://central.sonatype.com/publishing/deployments) dashboard. You should see a new deployment here. This deployment will be in the *pending* and *validating* states for some time while Maven Central performs checks on it.
Once your deployment moves to a *validated* state, you should see that it contains all the artifacts you’ve uploaded. If everything looks correct, click the *Publish* button to release these artifacts.
![](/images/published_on_maven_central.png)
Note that it will take some time (about 15–30 minutes, usually) after the release for the artifacts to be available publicly on Maven Central.
Also note that the library may be available for use before they are indexed on [the Maven Central website](https://central.sonatype.com/).
There’s also another task available which both uploads and releases the artifacts automatically once the deployment is verified, without having to manually release them on the website:
```bash
./gradlew publishAndReleaseToMavenCentral
```
**Et voilà, you have successfully published your library to Maven Central.**
# Next steps
- Share your library with the Kotlin Community in the `#feed` channel in the [Kotlin Slack](https://kotlinlang.slack.com/) (To sign up visit https://kotl.in/slack.)
- Add [shield.io badges](https://shields.io/badges/maven-central-version) to your README.
- Create a documentation site for your project using [Writerside](https://www.jetbrains.com/writerside/).
- Share API documentation for your project using [Dokka](https://kotl.in/dokka).
- Add [Renovate](https://docs.renovatebot.com/) to automatically update dependencies.
# Other resources
* [Publishing via the Central Portal](https://central.sonatype.org/publish-ea/publish-ea-guide/)
* [Gradle Maven Publish Plugin \- Publishing to Maven Central](https://vanniktech.github.io/gradle-maven-publish-plugin/central/)

20
settings.gradle.kts Normal file
View File

@ -0,0 +1,20 @@
pluginManagement {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven("https://maven.universablockchain.com/")
maven("https://gitea.sergeych.net/api/packages/SergeychWorks/maven")
mavenLocal()
}
}
rootProject.name = "ling"
include(":library")