summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--build.gradle.kts5
-rw-r--r--gradle/wrapper/gradle-wrapper.jarbin0 -> 61608 bytes
-rw-r--r--gradle/wrapper/gradle-wrapper.properties6
-rwxr-xr-xgradlew244
-rw-r--r--gradlew.bat92
-rw-r--r--src/CoreBindings.kt109
-rw-r--r--src/LispAst.kt41
-rw-r--r--src/LispData.kt105
-rw-r--r--src/LispErrorReporter.kt15
-rw-r--r--src/LispExecutionContext.kt61
-rw-r--r--src/LispParser.kt116
-rw-r--r--src/LispParsingError.kt4
-rw-r--r--src/LispPosition.kt21
-rw-r--r--src/StackFrame.kt32
-rw-r--r--src/StringRacer.kt81
-rw-r--r--test/res/test.lisp11
-rw-r--r--test/src/TestLisp.kt14
17 files changed, 957 insertions, 0 deletions
diff --git a/build.gradle.kts b/build.gradle.kts
new file mode 100644
index 0000000..0a2df9e
--- /dev/null
+++ b/build.gradle.kts
@@ -0,0 +1,5 @@
+plugins { kotlin("jvm").version("1.7.20"); java; `maven-publish` }
+repositories { mavenCentral() }
+java.toolchain { languageVersion.set(JavaLanguageVersion.of(8)) }
+sourceSets.main { java.setSrcDirs(listOf("src/")); resources.setSrcDirs(listOf("res")) }
+sourceSets.test { java.setSrcDirs(listOf("test/src")); resources.setSrcDirs(listOf("test/res")) }
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..ccebba7
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.jar
Binary files differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..42defcc
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,6 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip
+networkTimeout=10000
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..79a61d4
--- /dev/null
+++ b/gradlew
@@ -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" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..93e3f59
--- /dev/null
+++ b/gradlew.bat
@@ -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
diff --git a/src/CoreBindings.kt b/src/CoreBindings.kt
new file mode 100644
index 0000000..9213917
--- /dev/null
+++ b/src/CoreBindings.kt
@@ -0,0 +1,109 @@
+package moe.nea.lisp
+
+object CoreBindings {
+ val nil = LispData.LispNil
+ val def = LispData.externalRawCall { context, callsite, stackFrame, args ->
+ if (args.size != 2) {
+ return@externalRawCall context.reportError("Function define expects exactly two arguments", callsite)
+ }
+ val (name, value) = args
+ if (name !is LispAst.Reference) {
+ return@externalRawCall context.reportError("Define expects a name as first argument", name)
+ }
+ if (name.label in stackFrame.variables) {
+ return@externalRawCall context.reportError("Cannot redefine value in local context", name)
+ }
+ return@externalRawCall stackFrame.setValueLocal(name.label, context.resolveValue(stackFrame, value))
+ }
+
+ val pure = LispData.externalCall { args, reportError ->
+ return@externalCall args.singleOrNull()?.let { value ->
+ LispData.externalCall { args, reportError ->
+ if (args.isNotEmpty())
+ reportError("Pure function does not expect arguments")
+ else
+ value
+ }
+ } ?: reportError("Function pure expects exactly one argument")
+ }
+
+ val lambda = LispData.externalRawCall { context, callsite, stackFrame, args ->
+ if (args.size != 2) {
+ return@externalRawCall context.reportError("Lambda needs exactly 2 arguments", callsite)
+ }
+ val (argumentNames, body) = args
+ if (argumentNames !is LispAst.Parenthesis) {
+ return@externalRawCall context.reportError("Lambda has invalid argument declaration", argumentNames)
+ }
+ val argumentNamesString = argumentNames.items.map {
+ val ref = it as? LispAst.Reference
+ if (ref == null) {
+ return@externalRawCall context.reportError("Lambda has invalid argument declaration", it)
+ }
+ ref.label
+ }
+ if (body !is LispAst.Parenthesis) {
+ return@externalRawCall context.reportError("Lambda has invalid body declaration", body)
+ }
+ LispData.createLambda(stackFrame, argumentNamesString, body)
+ }
+
+ val defun = LispData.externalRawCall { context, callSite, stackFrame, lispAsts ->
+ if (lispAsts.size != 3) {
+ return@externalRawCall context.reportError("Invalid function definition", callSite)
+ }
+ val (name, args, body) = lispAsts
+ if (name !is LispAst.Reference) {
+ return@externalRawCall context.reportError("Invalid function definition name", name)
+ }
+ if (name.label in stackFrame.variables) {
+ return@externalRawCall context.reportError("Cannot redefine function in local context", name)
+ }
+ if (args !is LispAst.Parenthesis) {
+ return@externalRawCall context.reportError("Invalid function definition arguments", args)
+ }
+ val argumentNames = args.items.map {
+ val ref = it as? LispAst.Reference
+ ?: return@externalRawCall context.reportError("Invalid function definition argument name", it)
+ ref.label
+ }
+ if (body !is LispAst.Parenthesis) {
+ return@externalRawCall context.reportError("Invalid function definition body", body)
+ }
+ return@externalRawCall stackFrame.setValueLocal(
+ name.label,
+ LispData.createLambda(stackFrame, argumentNames, body, name.label)
+ )
+ }
+ val seq = LispData.externalRawCall { context, callsite, stackFrame, args ->
+ var lastResult: LispData? = null
+ for (arg in args) {
+ lastResult = context.executeLisp(stackFrame, arg)
+ }
+ lastResult ?: context.reportError("Seq cannot be invoked with 0 argumens", callsite)
+ }
+ val debuglog = LispData.externalRawCall { context, callsite, stackFrame, args ->
+ println(args.joinToString(" ") { arg ->
+ when (val resolved = context.resolveValue(stackFrame, arg)) {
+ is LispData.Atom -> ":${resolved.label}"
+ is LispData.JavaExecutable -> "<native code>"
+ LispData.LispNil -> "nil"
+ is LispData.LispNumber -> resolved.number.toString()
+ is LispData.LispNode -> resolved.node.toSource()
+ is LispData.LispObject<*> -> resolved.data.toString()
+ is LispData.LispInterpretedCallable -> "<function ${resolved.name ?: ""} ${resolved.argNames} ${resolved.body.toSource()}>"
+ }
+ })
+ LispData.LispNil
+ }
+
+ fun offerAllTo(bindings: StackFrame) {
+ bindings.setValueLocal("nil", nil)
+ bindings.setValueLocal("def", def)
+ bindings.setValueLocal("pure", pure)
+ bindings.setValueLocal("lambda", lambda)
+ bindings.setValueLocal("defun", defun)
+ bindings.setValueLocal("seq", seq)
+ bindings.setValueLocal("debuglog", debuglog)
+ }
+} \ No newline at end of file
diff --git a/src/LispAst.kt b/src/LispAst.kt
new file mode 100644
index 0000000..79fee8a
--- /dev/null
+++ b/src/LispAst.kt
@@ -0,0 +1,41 @@
+package moe.nea.lisp
+
+sealed class LispAst : HasLispPosition {
+
+
+ abstract fun toSource(): String
+
+
+ data class Program(override val position: LispPosition, val nodes: List<LispNode>) : LispAst() {
+ override fun toSource(): String {
+ return nodes.joinToString("\n") {
+ it.toSource()
+ }
+ }
+ }
+
+ sealed class LispNode : LispAst()
+ data class Atom(override val position: LispPosition, val label: String) : LispNode() {
+ override fun toSource(): String {
+ return ":$label"
+ }
+ }
+
+ data class Reference(override val position: LispPosition, val label: String) : LispNode() {
+ override fun toSource(): String {
+ return label
+ }
+ }
+
+ data class Parenthesis(override val position: LispPosition, val items: List<LispNode>) : LispNode() {
+ override fun toSource(): String {
+ return items.joinToString(" ", "(", ")") { it.toSource() }
+ }
+ }
+
+ data class StringLiteral(override val position: LispPosition, val parsedString: String) : LispNode() {
+ override fun toSource(): String {
+ return "\"${parsedString.replace("\\", "\\\\").replace("\"", "\\\"")}\"" // TODO: better escaping
+ }
+ }
+}
diff --git a/src/LispData.kt b/src/LispData.kt
new file mode 100644
index 0000000..1f13ad3
--- /dev/null
+++ b/src/LispData.kt
@@ -0,0 +1,105 @@
+package moe.nea.lisp
+
+sealed class LispData {
+
+ fun <T : Any> lispCastObject(lClass: LispClass<T>): LispObject<T>? {
+ if (this !is LispObject<*>) return null
+ if (this.handler != lClass) return null
+ return this as LispObject<T>
+ }
+
+ object LispNil : LispData()
+ data class Atom(val label: String) : LispData()
+ data class LispNode(val node: LispAst.LispNode) : LispData()
+ data class LispNumber(val number: Double) : LispData()
+ data class LispObject<T : Any>(val data: T, val handler: LispClass<T>) : LispData()
+ sealed class LispExecutable() : LispData() {
+ abstract fun execute(
+ executionContext: LispExecutionContext,
+ callsite: LispAst.LispNode,
+ stackFrame: StackFrame,
+ args: List<LispAst.LispNode>
+ ): LispData
+ }
+
+
+ abstract class JavaExecutable : LispExecutable() {
+ }
+
+ data class LispInterpretedCallable(
+ val declarationStackFrame: StackFrame,
+ val argNames: List<String>,
+ val body: LispAst.Parenthesis,
+ val name: String?,
+ ) : LispExecutable() {
+ override fun execute(
+ executionContext: LispExecutionContext,
+ callsite: LispAst.LispNode,
+ stackFrame: StackFrame,
+ args: List<LispAst.LispNode>
+ ): LispData {
+ if (argNames.size != args.size) {
+ TODO("ERROR")
+ }
+ val invocationFrame = declarationStackFrame.fork()
+
+ for ((name, value) in argNames.zip(args)) {
+ invocationFrame.setValueLocal(name, executionContext.resolveValue(stackFrame, value))
+ }
+ return executionContext.executeLisp(invocationFrame, body)
+ }
+ }
+
+ interface LispClass<T : Any> {
+ fun access(obj: T, name: String): LispData
+ fun instantiate(obj: T) = LispObject(obj, this)
+ }
+
+ object LispStringClass : LispClass<String> {
+ override fun access(obj: String, name: String): LispData {
+ return LispNil
+ }
+ }
+
+ companion object {
+ fun string(value: String): LispObject<String> =
+ LispStringClass.instantiate(value)
+
+ fun externalRawCall(callable: (context: LispExecutionContext, callsite: LispAst.LispNode, stackFrame: StackFrame, args: List<LispAst.LispNode>) -> LispData): LispExecutable {
+ return object : JavaExecutable() {
+ override fun execute(
+ executionContext: LispExecutionContext,
+ callsite: LispAst.LispNode,
+ stackFrame: StackFrame,
+ args: List<LispAst.LispNode>
+ ): LispData {
+ return callable.invoke(executionContext, callsite, stackFrame, args)
+ }
+ }
+ }
+
+ fun externalCall(callable: (args: List<LispData>, reportError: (String) -> LispData) -> LispData): LispExecutable {
+ return object : JavaExecutable() {
+ override fun execute(
+ executionContext: LispExecutionContext,
+ callsite: LispAst.LispNode,
+ stackFrame: StackFrame,
+ args: List<LispAst.LispNode>
+ ): LispData {
+ val mappedArgs = args.map { executionContext.resolveValue(stackFrame, it) }
+ return callable.invoke(mappedArgs) { executionContext.reportError(it, callsite) }
+ }
+ }
+ }
+
+
+ fun createLambda(
+ declarationStackFrame: StackFrame,
+ args: List<String>,
+ body: LispAst.Parenthesis,
+ nameHint: String? = null,
+ ): LispExecutable {
+ return LispInterpretedCallable(declarationStackFrame, args, body, nameHint)
+ }
+ }
+}
diff --git a/src/LispErrorReporter.kt b/src/LispErrorReporter.kt
new file mode 100644
index 0000000..d9ad148
--- /dev/null
+++ b/src/LispErrorReporter.kt
@@ -0,0 +1,15 @@
+package moe.nea.lisp
+
+class LispErrorReporter {
+
+ data class LispError(val name: String, val position: LispPosition)
+
+
+ val errors = listOf<LispError>()
+
+ fun reportError(name: String, position: HasLispPosition) {
+ println("LISP ERROR: $name at ${position.position}")
+ }
+
+
+}
diff --git a/src/LispExecutionContext.kt b/src/LispExecutionContext.kt
new file mode 100644
index 0000000..f169ba9
--- /dev/null
+++ b/src/LispExecutionContext.kt
@@ -0,0 +1,61 @@
+package moe.nea.lisp
+
+class LispExecutionContext() {
+
+ private val errorReporter = LispErrorReporter()
+ private val rootStackFrame = StackFrame(null)
+
+
+ fun reportError(name: String, position: HasLispPosition): LispData.LispNil {
+ println("Error: $name ${position.position}")
+ return LispData.LispNil
+ }
+
+
+ fun genBindings(): StackFrame {
+ return StackFrame(rootStackFrame)
+ }
+
+ fun executeProgram(stackFrame: StackFrame, program: LispAst.Program) {
+ for (node in program.nodes) {
+ executeLisp(stackFrame, node)
+ }
+ }
+
+
+ fun executeLisp(stackFrame: StackFrame, node: LispAst.LispNode): LispData {
+ when (node) {
+ is LispAst.Parenthesis -> {
+ val first = node.items.firstOrNull()
+ ?: return reportError("Cannot execute empty parenthesis ()", node)
+
+ val rest = node.items.drop(1)
+ return when (val resolvedValue = resolveValue(stackFrame, first)) {
+ is LispData.Atom -> reportError("Cannot execute atom", node)
+ LispData.LispNil -> reportError("Cannot execute nil", node)
+ is LispData.LispNumber -> reportError("Cannot execute number", node)
+ is LispData.LispNode -> reportError("Cannot execute node", node)
+ is LispData.LispObject<*> -> reportError("Cannot execute object-value", node)
+ is LispData.LispExecutable -> {
+ resolvedValue.execute(this, node, stackFrame, rest)
+ }
+ }
+
+ }
+
+ else -> return reportError("Expected invocation", node)
+ }
+ }
+
+ fun resolveValue(stackFrame: StackFrame, node: LispAst.LispNode): LispData {
+ return when (node) {
+ is LispAst.Atom -> LispData.Atom(node.label)
+ is LispAst.Parenthesis -> executeLisp(stackFrame, node)
+ is LispAst.Reference -> stackFrame.resolveReference(node.label)
+ ?: reportError("Could not resolve variable ${node.label}", node)
+
+ is LispAst.StringLiteral -> LispData.string(node.parsedString)
+ }
+ }
+}
+
diff --git a/src/LispParser.kt b/src/LispParser.kt
new file mode 100644
index 0000000..1117397
--- /dev/null
+++ b/src/LispParser.kt
@@ -0,0 +1,116 @@
+package moe.nea.lisp
+
+import java.io.File
+
+class LispParser private constructor(filename: String, string: String) {
+ val racer = StringRacer(filename, string)
+ val program = parseProgram()
+
+ companion object {
+ fun parse(filename: String, string: String): LispAst.Program {
+ return LispParser(filename, string).program
+ }
+ fun parse(file: File): LispAst.Program {
+ return parse(file.absolutePath, file.readText())
+ }
+
+ val digits = "1234567890"
+ val alphabet = "abcdefghijklmnopqrstuvwxyz"
+ val validStartingIdentifiers = "-.#+*'!$%&/=?_~|^" + alphabet + alphabet.uppercase()
+ val validIdentifiers = validStartingIdentifiers + digits
+ val parenthesisMatches = mapOf(
+ "(" to ")",
+ "[" to "]",
+ "{" to "}",
+ "<" to ">",
+ )
+ }
+
+ fun parseProgram(): LispAst.Program {
+ val start = racer.idx
+ val nodes = mutableListOf<LispAst.LispNode>()
+ while (true) {
+ racer.skipWhitespace()
+ if (racer.finished())
+ break
+ nodes.add(parseNode())
+ }
+ return LispAst.Program(racer.span(start), nodes)
+ }
+
+ private fun parseNode(): LispAst.LispNode {
+ val start = racer.idx
+ val paren = racer.peekReq(1) ?: racer.error("Expected start of expression")
+ val matchingParen = parenthesisMatches[paren]
+ if (matchingParen != null) {
+ val paren = parseParenthesis(paren, matchingParen)
+ return LispAst.Parenthesis(racer.span(start), paren)
+ }
+ if (paren == "\"") {
+ return parseString()
+ }
+ if (paren == ":") {
+ return parseAtom()
+ }
+ val ident = parseIdentifier()
+ return LispAst.Reference(racer.span(start), ident)
+ }
+
+
+ fun parseAtom(): LispAst.Atom {
+ val start = racer.idx
+ racer.expect(":", "Expected : at start of atom")
+ val ident = parseIdentifier()
+ return LispAst.Atom(racer.span(start), ident)
+ }
+
+
+ fun parseIdentifier(): String {
+ return racer.consumeWhile { it.first() in validStartingIdentifiers && it.last() in validIdentifiers }.also {
+ if (it.isEmpty()) racer.error("Expected identifier")
+ }
+ }
+
+ fun parseString(): LispAst.StringLiteral {
+ val start = racer.idx
+ val quoted = parseQuotedString()
+ return LispAst.StringLiteral(racer.span(start), quoted)
+ }
+
+ fun parseQuotedString(): String {
+ racer.expect("\"", "Expected '\"' at string start")
+ val sb = StringBuilder()
+ while (true) {
+ when (val peek = racer.consumeCountReq(1)) {
+ "\"" -> break
+ "\\" -> {
+ val escaped = racer.consumeCountReq(1) ?: racer.error("Unfinished backslash escape")
+ if (escaped != "\"" && escaped != "\\") {
+ // Surprisingly i couldn't find unicode escapes to be generated by the original minecraft 1.8.9 implementation
+ racer.idx--
+ racer.error("Invalid backslash escape '$escaped'")
+ }
+ sb.append(escaped)
+ }
+
+ null -> racer.error("Unfinished string")
+ else -> {
+ sb.append(peek)
+ }
+ }
+ }
+ return sb.toString()
+ }
+
+ private fun parseParenthesis(opening: String, closing: String): List<LispAst.LispNode> {
+ val l = mutableListOf<LispAst.LispNode>()
+ racer.expect(opening, "Expected $opening")
+ while (true) {
+ racer.skipWhitespace()
+ if (racer.tryConsume(closing)) {
+ return l
+ }
+ l.add(parseNode())
+ }
+ }
+}
diff --git a/src/LispParsingError.kt b/src/LispParsingError.kt
new file mode 100644
index 0000000..f6e76de
--- /dev/null
+++ b/src/LispParsingError.kt
@@ -0,0 +1,4 @@
+package moe.nea.lisp
+
+data class LispParsingError(val baseString: String, val offset: Int, val mes0: String) :
+ Exception("$mes0 at $offset in `$baseString`.") \ No newline at end of file
diff --git a/src/LispPosition.kt b/src/LispPosition.kt
new file mode 100644
index 0000000..ea901a2
--- /dev/null
+++ b/src/LispPosition.kt
@@ -0,0 +1,21 @@
+package moe.nea.lisp
+
+data class LispPosition(
+ val start: Int,
+ val end: Int,
+ val fileName: String,
+ val fileContent: String,
+) : HasLispPosition {
+ val startLine by lazy { fileContent.substring(0, start).count { it == '\n' } + 1 }
+ val startColumn by lazy { start - fileContent.substring(0, start).indexOfLast { it == '\n' } }
+ val endLine by lazy { fileContent.substring(0, end).count { it == '\n' } + 1 }
+ val endColumn by lazy { end - fileContent.substring(0, end).indexOfLast { it == '\n' } }
+ override val position get() = this
+ override fun toString(): String {
+ return "at $fileName:$startLine:$startColumn until $endLine:$endColumn"
+ }
+}
+
+interface HasLispPosition {
+ val position: LispPosition
+}
diff --git a/src/StackFrame.kt b/src/StackFrame.kt
new file mode 100644
index 0000000..66d74b2
--- /dev/null
+++ b/src/StackFrame.kt
@@ -0,0 +1,32 @@
+package moe.nea.lisp
+
+class StackFrame(val parent: StackFrame?) {
+
+ val variables = mutableMapOf<String, LispData>()
+
+ interface MetaKey<T>
+
+ private val meta: MutableMap<MetaKey<*>, Any> = mutableMapOf()
+
+ fun <T : Any> getMeta(key: MetaKey<T>): T? {
+ return meta[key] as? T
+ }
+
+ fun <T : Any> setMeta(key: MetaKey<T>, value: T) {
+ meta[key] = value
+ }
+
+ fun resolveReference(label: String): LispData? =
+ variables[label] ?: parent?.resolveReference(label)
+
+ fun setValueLocal(label: String, value: LispData): LispData {
+ variables[label] = value
+ return value
+ }
+
+ fun fork(): StackFrame {
+ return StackFrame(this)
+ }
+
+
+}
diff --git a/src/StringRacer.kt b/src/StringRacer.kt
new file mode 100644
index 0000000..d0a4a15
--- /dev/null
+++ b/src/StringRacer.kt
@@ -0,0 +1,81 @@
+package moe.nea.lisp
+
+import java.util.*
+
+class StringRacer(val filename: String, val backing: String) {
+ var idx = 0
+ val stack = Stack<Int>()
+
+ fun pushState() {
+ stack.push(idx)
+ }
+
+ fun popState() {
+ idx = stack.pop()
+ }
+
+ fun span(start: Int) = LispPosition(start, idx, filename, backing)
+
+ fun discardState() {
+ stack.pop()
+ }
+
+ fun peek(count: Int): String {
+ return backing.substring(minOf(idx, backing.length), minOf(idx + count, backing.length))
+ }
+
+ fun finished(): Boolean {
+ return peek(1).isEmpty()
+ }
+
+ fun peekReq(count: Int): String? {
+ val p = peek(count)
+ if (p.length != count)
+ return null
+ return p
+ }
+
+ fun consumeCountReq(count: Int): String? {
+ val p = peekReq(count)
+ if (p != null)
+ idx += count
+ return p
+ }
+
+ fun tryConsume(string: String): Boolean {
+ val p = peek(string.length)
+ if (p != string)
+ return false
+ idx += p.length
+ return true
+ }
+
+ fun consumeWhile(shouldConsumeThisString: (String) -> Boolean): String {
+ var lastString: String = ""
+ while (true) {
+ val nextPart = peek(1)
+ if (nextPart.isEmpty()) break
+ val nextString = lastString + nextPart
+ if (!shouldConsumeThisString(nextString)) {
+ break
+ }
+ idx++
+ lastString = nextString
+ }
+ return lastString
+ }
+
+ fun expect(search: String, errorMessage: String) {
+ if (!tryConsume(search))
+ error(errorMessage)
+ }
+
+ fun error(errorMessage: String): Nothing {
+ throw LispParsingError(backing, idx, errorMessage)
+ }
+
+ fun skipWhitespace() {
+ consumeWhile { Character.isWhitespace(it.last()) }
+ }
+}
+
diff --git a/test/res/test.lisp b/test/res/test.lisp
new file mode 100644
index 0000000..f3d21d9
--- /dev/null
+++ b/test/res/test.lisp
@@ -0,0 +1,11 @@
+(debuglog "Hello, World, here is an atom:" :iamanatom)
+(defun myfun (var) (debuglog var))
+(myfun :myfunworks)
+((lambda (a) (debuglog a)) :atom)
+(debuglog a)
+(def helloworld (pure "hello world"))
+(debuglog helloworld (helloworld))
+(defun + () (seq
+ (debuglog "also multiplication")
+ (debuglog "addition")))
+(debuglog +)
diff --git a/test/src/TestLisp.kt b/test/src/TestLisp.kt
new file mode 100644
index 0000000..f986f1c
--- /dev/null
+++ b/test/src/TestLisp.kt
@@ -0,0 +1,14 @@
+import moe.nea.lisp.CoreBindings
+import moe.nea.lisp.LispExecutionContext
+import moe.nea.lisp.LispParser
+import java.io.File
+
+object T
+
+fun main() {
+ val otherP = LispParser.parse(File(T::class.java.getResource("/test.lisp")!!.file))
+ val executionContext = LispExecutionContext()
+ val bindings = executionContext.genBindings()
+ CoreBindings.offerAllTo(bindings)
+ executionContext.executeProgram(bindings, otherP)
+}