├── .github └── workflows │ └── release.yaml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── docs └── Basic Usage.md ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle.kts └── src ├── main └── java │ └── net │ └── hollowcube │ └── mql │ ├── MqlScript.java │ ├── foreign │ ├── MqlForeignFunctions.java │ ├── MqlForeignTypes.java │ └── Query.java │ ├── jit │ ├── AsmUtil.java │ ├── MqlCompiler.java │ ├── MqlEnv.java │ ├── MqlQueryScript.java │ └── MqlRuntime.java │ ├── parser │ ├── MqlLexer.java │ ├── MqlParseError.java │ ├── MqlParser.java │ └── MqlToken.java │ ├── runtime │ ├── MqlMath.java │ ├── MqlRuntimeError.java │ ├── MqlScope.java │ ├── MqlScopeImpl.java │ └── MqlScriptScope.java │ ├── tree │ ├── MqlAccessExpr.java │ ├── MqlArgListExpr.java │ ├── MqlBinaryExpr.java │ ├── MqlCallExpr.java │ ├── MqlExpr.java │ ├── MqlIdentExpr.java │ ├── MqlNumberExpr.java │ ├── MqlTernaryExpr.java │ ├── MqlUnaryExpr.java │ └── MqlVisitor.java │ ├── util │ └── MqlPrinter.java │ └── value │ ├── MqlCallable.java │ ├── MqlHolder.java │ ├── MqlIdentValue.java │ ├── MqlNumberValue.java │ └── MqlValue.java └── test └── java └── net └── hollowcube └── mql ├── TestMql.java ├── foreign └── TestMqlForeignFunctions.java ├── jit ├── BaseScript.java ├── QueryScript.java ├── QueryTest.java ├── TestCompilation.java ├── TestExecution.java └── TestRegression.java ├── parser ├── TestMqlLexer.java └── TestMqlParser.java └── runtime └── TestMqlMath.java /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: Gradle Publish to Maven Central 2 | 3 | on: 4 | push: 5 | tags: 6 | - '[0-9]+.[0-9]+.[0-9]+' 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | env: 12 | SONATYPE_USERNAME: ${{ secrets.SONATYPE_USERNAME }} 13 | SONATYPE_PASSWORD: ${{ secrets.SONATYPE_PASSWORD }} 14 | GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} 15 | GPG_PASSPHRASE: ${{ secrets.GPG_PASSWORD }} 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up JDK 17 19 | uses: actions/setup-java@v2 20 | with: 21 | java-version: '17' 22 | distribution: 'temurin' 23 | - name: Setup Gradle 24 | uses: gradle/gradle-build-action@v2 25 | - name: Publish to Sonatype 26 | env: 27 | TAG_VERSION: ${{ github.ref_name }} 28 | run: | 29 | ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository 30 | echo "Version: ${TAG_VERSION}" >> $GITHUB_STEP_SUMMARY -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/**/build/ 5 | !**/src/test/**/build/ 6 | 7 | ### IntelliJ IDEA ### 8 | .idea 9 | *.iws 10 | *.iml 11 | *.ipr 12 | out/ 13 | !**/src/main/**/out/ 14 | !**/src/test/**/out/ 15 | 16 | ### Eclipse ### 17 | .apt_generated 18 | .classpath 19 | .factorypath 20 | .project 21 | .settings 22 | .springBeans 23 | .sts4-cache 24 | bin/ 25 | !**/src/main/**/bin/ 26 | !**/src/test/**/bin/ 27 | 28 | ### NetBeans ### 29 | /nbproject/private/ 30 | /nbbuild/ 31 | /dist/ 32 | /nbdist/ 33 | /.nb-gradle/ 34 | 35 | ### VS Code ### 36 | .vscode/ 37 | 38 | ### Mac OS ### 39 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 HollowCube Contibutors 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Minecraft Query Language (mql) 2 | 3 | A subset of MoLang (may eventually be a full implementation). Available as an interpreter or a JIT compiled mode. 4 | 5 | ## Background 6 | 7 | ## Install 8 | 9 | Artifacts are published on Maven Central. Add the following to your `build.gradle(.kts)`: 10 | 11 | ```kotlin 12 | dependencies { 13 | implementation("dev.hollowcube:mql:{VERSION}") 14 | } 15 | ``` 16 | 17 | ## Syntax 18 | 19 | `mql` supports the following syntax 20 | 21 | * Query functions 22 | * Math & Comparison operators (`+`, `*`, `==`, etc) 23 | 24 | ## Usage 25 | 26 | See the [docs](./docs/Basic%20Usage.md). 27 | 28 | ## Future Plans 29 | 30 | * Unify the interpreter and compiler apis 31 | * Allows for fallback if using unsupported JIT features, permission issues, etc. 32 | * Temp variables 33 | * Public variables/querying other scripts 34 | * Other data types & functions 35 | 36 | ## License 37 | 38 | This project is licensed under the [MIT License](../../LICENSE). 39 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | `java-library` 3 | 4 | `maven-publish` 5 | signing 6 | alias(libs.plugins.nexuspublish) 7 | } 8 | 9 | group = "dev.hollowcube" 10 | version = System.getenv("TAG_VERSION") ?: "dev" 11 | description = "An interpreter and JIT compiler for a subset of Molang" 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | api(libs.jetbrainsAnnotations) 19 | implementation(libs.bundles.asm) 20 | 21 | testImplementation(platform("org.junit:junit-bom:5.9.1")) 22 | testImplementation("org.junit.jupiter:junit-jupiter") 23 | } 24 | 25 | java { 26 | withSourcesJar() 27 | withJavadocJar() 28 | 29 | sourceCompatibility = JavaVersion.VERSION_17 30 | targetCompatibility = JavaVersion.VERSION_17 31 | } 32 | 33 | tasks.test { 34 | useJUnitPlatform() 35 | 36 | // jvmArgs("--add-opens", "java.base/java.lang=ALL-UNNAMED") 37 | } 38 | 39 | nexusPublishing { 40 | this.packageGroup.set("dev.hollowcube") 41 | 42 | repositories.sonatype { 43 | nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) 44 | snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) 45 | 46 | if (System.getenv("SONATYPE_USERNAME") != null) { 47 | username.set(System.getenv("SONATYPE_USERNAME")) 48 | password.set(System.getenv("SONATYPE_PASSWORD")) 49 | } 50 | } 51 | } 52 | 53 | publishing.publications.create("maven") { 54 | groupId = "dev.hollowcube" 55 | artifactId = "mql" 56 | version = project.version.toString() 57 | 58 | from(project.components["java"]) 59 | 60 | pom { 61 | name.set(artifactId) 62 | description.set(project.description) 63 | url.set("https://github.com/hollow-cube/mql") 64 | 65 | licenses { 66 | license { 67 | name.set("MIT") 68 | url.set("https://github.com/hollow-cube/mql/blob/main/LICENSE") 69 | } 70 | } 71 | 72 | developers { 73 | developer { 74 | id.set("mworzala") 75 | name.set("Matt Worzala") 76 | email.set("matt@hollowcube.dev") 77 | } 78 | } 79 | 80 | issueManagement { 81 | system.set("GitHub") 82 | url.set("https://github.com/hollow-cube/mql/issues") 83 | } 84 | 85 | scm { 86 | connection.set("scm:git:git://github.com/hollow-cube/mql.git") 87 | developerConnection.set("scm:git:git@github.com:hollow-cube/mql.git") 88 | url.set("https://github.com/hollow-cube/mql") 89 | tag.set(System.getenv("TAG_VERSION") ?: "HEAD") 90 | } 91 | 92 | ciManagement { 93 | system.set("Github Actions") 94 | url.set("https://github.com/hollow-cube/mql/actions") 95 | } 96 | } 97 | } 98 | 99 | signing { 100 | isRequired = System.getenv("CI") != null 101 | 102 | val privateKey = System.getenv("GPG_PRIVATE_KEY") 103 | val keyPassphrase = System.getenv()["GPG_PASSPHRASE"] 104 | useInMemoryPgpKeys(privateKey, keyPassphrase) 105 | 106 | sign(publishing.publications) 107 | } -------------------------------------------------------------------------------- /docs/Basic Usage.md: -------------------------------------------------------------------------------- 1 | MQL may be used either in an interpreted mode, which may support features not present in compiled mode. 2 | 3 | ### Interpreted 4 | Interpreted mode uses a tree-walk interpreter to evaluate the script. The API consists of `MqlScript` and `MqlScope`s. 5 | A script is created using `MqlScript#parse(String)`, and then evaluated using `MqlScript#evaluate(MqlScope)double`. 6 | 7 | The simplest example of interpreting a script is as follows: 8 | ``` 9 | var script = MqlScript.parse("1.234"); 10 | var result = script.evaluate(new MqlScopeImpl()); 11 | System.out.println(result); // 1.234 12 | ``` 13 | 14 | The scope may be used to provide variables and functions to the script. `MqlMath.INSTANCE` itself is a scope, which 15 | provides the language spec math queries. In interpreted mode, math is not available unless provided explicitly. 16 | 17 | ``` 18 | var script = MqlScript.parse("math.pi + 1"); 19 | var result = script.evaluate(new MqlScopeImpl(){{ 20 | put("math", MqlMath.INSTANCE); 21 | }}); 22 | System.out.println(result); // 4.141592653589793 23 | ``` 24 | 25 | `MqlForeignFunctions` provides an interface for calling Java functions from MQL. The main function is 26 | `MqlForeignFunctions.create(Class, T)MqlScope`, which creates a scope from the provided class, 27 | exposing all `@Query` methods to the script. See the example below: 28 | 29 | ``` 30 | public class MyQuery { 31 | @Query 32 | public double add(double a, double b) { 33 | return a + b; 34 | } 35 | } 36 | 37 | var script = MqlScript.parse("my.add(1, 2)"); 38 | var result = script.evaluate(new MqlScopeImpl(){{ 39 | data.put("my", MqlForeignFunctions.create(MyQuery.class, new MyQuery())); 40 | }}); 41 | System.out.println(result); // 3.0 42 | ``` 43 | 44 | ### Compiled 45 | Compiled (JIT) mode compiles the script to JVM bytecode at runtime. Compiled mode is significantly faster than 46 | interpreted mode (solid benchmarks wip), however it is not as flexible. 47 | 48 | Due to Java security, the following vm argument must be provided to allow dynamic class loading: 49 | - `--add-opens java.base/java.lang=ALL-UNNAMED` 50 | 51 | The simple interpreted example can be rewritten as follows: 52 | ``` 53 | public interface MyScript { 54 | double evaluate(); 55 | } 56 | 57 | var compiler = new MqlCompiler<>(MyScript.class); 58 | var scriptClass = compiler.compile("1.234"); // Class 59 | var script = scriptClass.newInstance(); // Deprecated and unsafe, handle errors in real usage 60 | var result = script.evaluate(); 61 | System.out.println(result); // 1.234 62 | ``` 63 | 64 | Unlike interpreted mode, compiled mode provides math functions implicitly (for now): 65 | 66 | ``` 67 | // ... 68 | var script = compiler.compile("math.pi + 1").newInstance(); 69 | var result = script.evaluate(); 70 | System.out.println(result); // 4.141592653589793 71 | ``` 72 | 73 | Compiled mode requires all types to be known at compile time, particularly, they must be present in the 74 | script interface given to the compiler. The third example can be rewritten as follows: 75 | 76 | ``` 77 | public class MyQuery { 78 | @Query 79 | public double add(double a, double b) { 80 | return a + b; 81 | } 82 | } 83 | 84 | public interface MyScript { 85 | double evaluate(@MqlEnv("my") MyQuery my); 86 | } 87 | 88 | var compiler = new MqlCompiler<>(MyScript.class); 89 | var script = compiler.compile("my.add(1, 2)").newInstance(); 90 | var result = script.evaluate(new MyQuery()); 91 | System.out.println(result); // 3.0 92 | ``` 93 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | metadata.format.version = "1.1" 2 | 3 | [versions] 4 | 5 | jetbrainsAnnotations = "23.0.0" 6 | asm = "9.4" 7 | 8 | nexuspublish = "1.3.0" 9 | 10 | [libraries] 11 | 12 | jetbrainsAnnotations = { group = "org.jetbrains", name = "annotations", version.ref = "jetbrainsAnnotations" } 13 | asm-core = { group = "org.ow2.asm", name = "asm", version.ref = "asm" } 14 | asm-util = { group = "org.ow2.asm", name = "asm-util", version.ref = "asm" } 15 | 16 | [bundles] 17 | 18 | asm = ["asm-core", "asm-util"] 19 | 20 | [plugins] 21 | 22 | nexuspublish = { id = "io.github.gradle-nexus.publish-plugin", version.ref = "nexuspublish" } 23 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hollow-cube/mql/f68420b12eb1bc870e2836f19b3189a12821db9b/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Feb 29 08:46:46 EST 2024 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "mql" 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/MqlScript.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql; 2 | 3 | import net.hollowcube.mql.parser.MqlParser; 4 | import net.hollowcube.mql.runtime.MqlScope; 5 | import net.hollowcube.mql.tree.MqlExpr; 6 | import net.hollowcube.mql.tree.MqlNumberExpr; 7 | import net.hollowcube.mql.value.MqlNumberValue; 8 | import net.hollowcube.mql.value.MqlValue; 9 | import org.jetbrains.annotations.NotNull; 10 | 11 | public record MqlScript(@NotNull MqlExpr expr) { 12 | 13 | public static @NotNull MqlScript parse(@NotNull String script) { 14 | if (script.trim().isEmpty()) // Empty script is always the number 1 15 | return new MqlScript(new MqlNumberExpr(1)); 16 | MqlExpr expr = new MqlParser(script).parse(); 17 | return new MqlScript(expr); 18 | } 19 | 20 | public double evaluate(@NotNull MqlScope scope) { 21 | MqlValue result = expr().evaluate(scope); 22 | if (result instanceof MqlNumberValue num) 23 | return num.value(); 24 | return 0.0; 25 | } 26 | 27 | public boolean evaluateToBool(@NotNull MqlScope scope) { 28 | MqlValue result = expr().evaluate(scope); 29 | if (result instanceof MqlNumberValue num) 30 | return num.value() != 0; 31 | return result != MqlValue.NULL; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/foreign/MqlForeignFunctions.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.foreign; 2 | 3 | import net.hollowcube.mql.runtime.MqlRuntimeError; 4 | import net.hollowcube.mql.runtime.MqlScope; 5 | import net.hollowcube.mql.tree.MqlExpr; 6 | import net.hollowcube.mql.value.MqlCallable; 7 | import net.hollowcube.mql.value.MqlValue; 8 | import org.intellij.lang.annotations.Language; 9 | import org.jetbrains.annotations.NotNull; 10 | import org.jetbrains.annotations.Nullable; 11 | import org.jetbrains.annotations.UnknownNullability; 12 | 13 | import java.lang.invoke.CallSite; 14 | import java.lang.invoke.LambdaMetafactory; 15 | import java.lang.invoke.MethodHandles; 16 | import java.lang.invoke.MethodType; 17 | import java.lang.reflect.Method; 18 | import java.lang.reflect.Modifier; 19 | import java.util.Arrays; 20 | import java.util.HashMap; 21 | import java.util.List; 22 | import java.util.Map; 23 | 24 | @SuppressWarnings({"rawtypes", "unchecked"}) 25 | public class MqlForeignFunctions { 26 | 27 | public static @NotNull MqlScope create(@NotNull Class type, @Nullable T instance) { 28 | // Construct a map with all static and non static @Query methods in the class 29 | Map functions = new HashMap<>(); 30 | for (Method method : type.getMethods()) { 31 | Query annotation = method.getAnnotation(Query.class); 32 | if (annotation == null) continue; 33 | 34 | boolean isStatic = (method.getModifiers() & Modifier.STATIC) != 0; 35 | MqlCallable callable = createForeign(method, isStatic ? null : instance); 36 | 37 | String name = annotation.value(); 38 | if (name.isEmpty()) name = camelCaseToSnakeCase(method.getName()); 39 | 40 | functions.put(name, callable); 41 | } 42 | 43 | // Return the scope using the functions map 44 | return name -> { 45 | MqlCallable function = functions.get(name); 46 | if (function == null) 47 | throw new MqlRuntimeError("No such function: " + name); 48 | 49 | // 0 arg functions do not need an explicit call 50 | if (function.arity() == 0) 51 | return function.call(List.of(), null); 52 | return function; 53 | }; 54 | } 55 | 56 | /** 57 | * @param method The method to bind. Must be public, may be static. 58 | * @param bindTo The instance of the method's class to bind to. If the method is static, this must be null. 59 | * @return An {@link MqlCallable} representing an mql accessible function. 60 | * @see FastInvokerFactory 61 | */ 62 | public static @NotNull MqlCallable createForeign(@NotNull Method method, @UnknownNullability Object bindTo) { 63 | if ((method.getModifiers() & Modifier.PUBLIC) == 0) 64 | throw new IllegalArgumentException("method must be public"); 65 | if (bindTo != null && !method.getDeclaringClass().isInstance(bindTo)) 66 | throw new IllegalArgumentException("bindTo must be an instance of the method class"); 67 | 68 | try { 69 | MethodHandles.Lookup lookup = MethodHandles.lookup(); 70 | 71 | Class[] erasedTypes = new Class[method.getParameterCount()]; 72 | Arrays.fill(erasedTypes, Object.class); 73 | Class erasedReturnType = method.getReturnType(); 74 | if (erasedReturnType != void.class) { 75 | erasedReturnType = Object.class; 76 | } 77 | 78 | Class[] fixedTypes = new Class[method.getParameterCount()]; 79 | int index = 0; 80 | for (Class clazz : method.getParameterTypes()) { 81 | fixedTypes[index++] = convertPrimitive(clazz); 82 | } 83 | Class fixedReturnType = method.getReturnType(); 84 | if (fixedReturnType != void.class) { 85 | fixedReturnType = convertPrimitive(fixedReturnType); 86 | } 87 | 88 | boolean isVoid = erasedReturnType == void.class; 89 | boolean isStatic = (method.getModifiers() & Modifier.STATIC) != 0; 90 | 91 | CallSite callsite = LambdaMetafactory.metafactory( 92 | lookup, 93 | "accept" + method.getParameterCount() + (isVoid ? "V" : "R"), 94 | MethodType.methodType(NConsumer.class, isStatic ? new Class[0] : new Class[]{method.getDeclaringClass()}), 95 | MethodType.methodType(erasedReturnType, erasedTypes), 96 | lookup.unreflect(method), 97 | MethodType.methodType(fixedReturnType, fixedTypes) 98 | ); 99 | 100 | var handle = (NConsumer) (isStatic ? callsite.getTarget().invoke() : callsite.getTarget().bindTo(bindTo).invoke()); 101 | 102 | return new ForeignCallable(handle, fixedTypes, fixedReturnType); 103 | } catch (Throwable e) { 104 | throw new RuntimeException(e); 105 | } 106 | } 107 | 108 | private static Class convertPrimitive(Class in) { 109 | if (in == int.class) { 110 | return Integer.class; 111 | } else if (in == float.class) { 112 | return Float.class; 113 | } else if (in == boolean.class) { 114 | return Boolean.class; 115 | } else if (in == double.class) { 116 | return Double.class; 117 | } else if (in == long.class) { 118 | return Long.class; 119 | } else { 120 | return in; 121 | } 122 | } 123 | 124 | private record ForeignCallable( 125 | NConsumer handle, 126 | Class[] parameterTypes, 127 | Class returnType 128 | ) implements MqlCallable { 129 | 130 | @Override 131 | public int arity() { 132 | return parameterTypes.length; 133 | } 134 | 135 | @Override 136 | public @NotNull MqlValue call(@NotNull List args, MqlScope scope) { 137 | if (args.size() != parameterTypes.length) { 138 | //todo mql exception 139 | throw new IllegalArgumentException("Expected " + parameterTypes.length + " arguments, got " + args.size()); 140 | } 141 | 142 | Object[] javaArgs = new Object[args.size()]; 143 | for (int i = 0; i < args.size(); i++) { 144 | javaArgs[i] = MqlForeignTypes.fromMql(args.get(i).evaluate(scope), parameterTypes[i]); 145 | } 146 | 147 | boolean isVoid = returnType == void.class; 148 | if (isVoid) { 149 | switch (args.size()) { 150 | case 0 -> handle.accept0V(); 151 | case 1 -> handle.accept1V(javaArgs[0]); 152 | case 2 -> handle.accept2V(javaArgs[0], javaArgs[1]); 153 | case 3 -> handle.accept3V(javaArgs[0], javaArgs[1], javaArgs[2]); 154 | case 4 -> handle.accept4V(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3]); 155 | case 5 -> handle.accept5V(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4]); 156 | case 6 -> 157 | handle.accept6V(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5]); 158 | case 7 -> 159 | handle.accept7V(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5], javaArgs[6]); 160 | case 8 -> 161 | handle.accept8V(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5], javaArgs[6], javaArgs[7]); 162 | case 9 -> 163 | handle.accept9V(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5], javaArgs[6], javaArgs[7], javaArgs[8]); 164 | } 165 | } else { 166 | Object result = switch (args.size()) { 167 | case 0 -> handle.accept0R(); 168 | case 1 -> handle.accept1R(javaArgs[0]); 169 | case 2 -> handle.accept2R(javaArgs[0], javaArgs[1]); 170 | case 3 -> handle.accept3R(javaArgs[0], javaArgs[1], javaArgs[2]); 171 | case 4 -> handle.accept4R(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3]); 172 | case 5 -> handle.accept5R(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4]); 173 | case 6 -> 174 | handle.accept6R(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5]); 175 | case 7 -> 176 | handle.accept7R(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5], javaArgs[6]); 177 | case 8 -> 178 | handle.accept8R(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5], javaArgs[6], javaArgs[7]); 179 | case 9 -> 180 | handle.accept9R(javaArgs[0], javaArgs[1], javaArgs[2], javaArgs[3], javaArgs[4], javaArgs[5], javaArgs[6], javaArgs[7], javaArgs[8]); 181 | default -> throw new MqlRuntimeError("unreachable arg error"); 182 | }; 183 | 184 | return MqlForeignTypes.toMql(result); 185 | } 186 | 187 | return MqlValue.NULL; 188 | } 189 | } 190 | 191 | public interface NConsumer { 192 | 193 | R accept0R(); 194 | 195 | R accept1R(P1 p1); 196 | 197 | R accept2R(P1 p1, P2 p2); 198 | 199 | R accept3R(P1 p1, P2 p2, P3 p3); 200 | 201 | R accept4R(P1 p1, P2 p2, P3 p3, P4 p4); 202 | 203 | R accept5R(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5); 204 | 205 | R accept6R(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6); 206 | 207 | R accept7R(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7); 208 | 209 | R accept8R(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8); 210 | 211 | R accept9R(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9); 212 | 213 | void accept0V(); 214 | 215 | void accept1V(P1 p1); 216 | 217 | void accept2V(P1 p1, P2 p2); 218 | 219 | void accept3V(P1 p1, P2 p2, P3 p3); 220 | 221 | void accept4V(P1 p1, P2 p2, P3 p3, P4 p4); 222 | 223 | void accept5V(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5); 224 | 225 | void accept6V(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6); 226 | 227 | void accept7V(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7); 228 | 229 | void accept8V(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8); 230 | 231 | void accept9V(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9); 232 | 233 | } 234 | 235 | // String conversion utility, didn't want to add a separate util for this. 236 | 237 | private static final @Language("regexp") String CAMEL_TO_SNAKE_CASE_REGEX = "([a-z])([A-Z]+)"; 238 | private static final String CAMEL_TO_SNAKE_CASE_REPLACEMENT = "$1_$2"; 239 | 240 | private static String camelCaseToSnakeCase(String str) { 241 | return str.replaceAll(CAMEL_TO_SNAKE_CASE_REGEX, CAMEL_TO_SNAKE_CASE_REPLACEMENT).toLowerCase(); 242 | } 243 | } 244 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/foreign/MqlForeignTypes.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.foreign; 2 | 3 | import net.hollowcube.mql.value.MqlNumberValue; 4 | import net.hollowcube.mql.value.MqlValue; 5 | import org.jetbrains.annotations.NotNull; 6 | import org.jetbrains.annotations.UnknownNullability; 7 | 8 | /** 9 | * Conversion utility between java types and MQL types. 10 | *

11 | * todo not sure if other types should be convertable. I think just doubles is fine. 12 | */ 13 | public class MqlForeignTypes { 14 | 15 | public static @NotNull MqlValue toMql(@UnknownNullability Object javaValue) { 16 | if (javaValue == null) return MqlValue.NULL; 17 | if (javaValue instanceof MqlValue value) 18 | return value; 19 | if (javaValue instanceof Double value) 20 | return new MqlNumberValue(value); 21 | // if (javaValue instanceof Float value) 22 | // return new MqlNumberValue(value); 23 | // if (javaValue instanceof Long value) 24 | // return new MqlNumberValue(value); 25 | // if (javaValue instanceof Integer value) 26 | // return new MqlNumberValue(value); 27 | // if (javaValue instanceof Short value) 28 | // return new MqlNumberValue(value); 29 | // if (javaValue instanceof Byte value) 30 | // return new MqlNumberValue(value); 31 | if (javaValue instanceof Boolean value) 32 | return MqlValue.from(value); 33 | throw new RuntimeException("cannot convert " + javaValue.getClass().getSimpleName() + " to mql value"); 34 | } 35 | 36 | public static @UnknownNullability Object fromMql(@NotNull MqlValue value, @NotNull Class targetType) { 37 | if (value instanceof MqlNumberValue numberValue) { 38 | if (Double.class.equals(targetType) || double.class.equals(targetType)) { 39 | return numberValue.value(); 40 | // } else if (Float.class.equals(targetType) || float.class.equals(targetType)) { 41 | // return (float) numberValue.value(); 42 | // } else if (Long.class.equals(targetType) || long.class.equals(targetType)) { 43 | // return (long) numberValue.value(); 44 | // } else if (Integer.class.equals(targetType) || int.class.equals(targetType)) { 45 | // return (int) numberValue.value(); 46 | // } else if (Short.class.equals(targetType) || short.class.equals(targetType)) { 47 | // return (short) numberValue.value(); 48 | // } else if (Byte.class.equals(targetType) || byte.class.equals(targetType)) { 49 | // return (byte) numberValue.value(); 50 | } else if (Boolean.class.equals(targetType) || boolean.class.equals(targetType)) { 51 | return numberValue.value() != 0; 52 | } 53 | throw new RuntimeException("cannot convert number " + targetType.getSimpleName()); 54 | } 55 | throw new RuntimeException("cannot convert " + value.getClass().getSimpleName() + " to " + targetType.getSimpleName()); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/foreign/Query.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.foreign; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.METHOD) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface Query { 11 | String value() default ""; 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/jit/AsmUtil.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.objectweb.asm.ClassReader; 5 | import org.objectweb.asm.MethodVisitor; 6 | import org.objectweb.asm.Opcodes; 7 | import org.objectweb.asm.tree.ClassNode; 8 | import org.objectweb.asm.tree.InsnList; 9 | import org.objectweb.asm.util.Textifier; 10 | import org.objectweb.asm.util.TraceMethodVisitor; 11 | 12 | import java.io.PrintWriter; 13 | import java.io.StringWriter; 14 | import java.lang.invoke.MethodHandles; 15 | import java.lang.reflect.Method; 16 | 17 | public final class AsmUtil { 18 | private AsmUtil() { 19 | } 20 | 21 | public static @NotNull String toDescriptor(@NotNull Class clazz) { 22 | if (boolean.class.equals(clazz)) { 23 | return "Z"; 24 | } else if (byte.class.equals(clazz)) { 25 | return "B"; 26 | } else if (char.class.equals(clazz)) { 27 | return "C"; 28 | } else if (short.class.equals(clazz)) { 29 | return "S"; 30 | } else if (int.class.equals(clazz)) { 31 | return "I"; 32 | } else if (long.class.equals(clazz)) { 33 | return "J"; 34 | } else if (float.class.equals(clazz)) { 35 | return "F"; 36 | } else if (double.class.equals(clazz)) { 37 | return "D"; 38 | } else if (void.class.equals(clazz)) { 39 | return "V"; 40 | } 41 | return "L" + toName(clazz) + ";"; 42 | } 43 | 44 | public static @NotNull String toDescriptor(@NotNull Method method) { 45 | var sb = new StringBuilder("("); 46 | for (var param : method.getParameterTypes()) { 47 | sb.append(toDescriptor(param)); 48 | } 49 | sb.append(")"); 50 | sb.append(toDescriptor(method.getReturnType())); 51 | return sb.toString(); 52 | } 53 | 54 | public static @NotNull String toName(@NotNull Class clazz) { 55 | return clazz.getName().replace(".", "/"); 56 | } 57 | 58 | public static void convert(Class to, Class from, MethodVisitor mv) { 59 | if (to.isAssignableFrom(from)) { 60 | return; 61 | } 62 | //todo handle other conversions 63 | throw new UnsupportedOperationException("Cannot convert from " + from + " to " + to); 64 | } 65 | 66 | @SuppressWarnings("all") 67 | public static Class loadClass(String className, byte[] b) { 68 | try { 69 | var lookup = MethodHandles.lookup(); 70 | var a = lookup.defineHiddenClass(b, true); 71 | return a.lookupClass(); 72 | } catch (Exception e) { 73 | e.printStackTrace(); 74 | throw new RuntimeException(e); 75 | } 76 | // Override defineClass (as it is protected) and define the class. 77 | // Class clazz = null; 78 | // try { 79 | // ClassLoader loader = ClassLoader.getSystemClassLoader(); 80 | // Class cls = (Class) Class.forName("java.lang.ClassLoader"); 81 | // java.lang.reflect.Method method = 82 | // cls.getDeclaredMethod( 83 | // "defineClass", 84 | // new Class[]{String.class, byte[].class, int.class, int.class}); 85 | // 86 | // // Protected method invocation. 87 | // method.setAccessible(true); 88 | // try { 89 | // Object[] args = 90 | // new Object[]{className, b, 0, b.length}; 91 | // clazz = (Class) method.invoke(loader, args); 92 | // } finally { 93 | // method.setAccessible(false); 94 | // } 95 | // } catch (Exception e) { 96 | // e.printStackTrace(); 97 | // System.exit(1); 98 | // } 99 | // return clazz; 100 | } 101 | 102 | public static @NotNull String prettyPrintEvalMethod(byte[] bytecode) { 103 | var str = new StringBuilder(); 104 | var printer = new Textifier(); 105 | var mp = new TraceMethodVisitor(printer); 106 | 107 | var cr = new ClassReader(bytecode); 108 | var cn = new ClassNode(); 109 | cr.accept(cn, 0); 110 | for (var method : cn.methods) { 111 | // Ignore any method that isnt evaluate and not a bridge (we want the concrete impl) 112 | if (!"evaluate".equals(method.name) || (method.access & Opcodes.ACC_BRIDGE) != 0) 113 | continue; 114 | InsnList insns = method.instructions; 115 | for (var insn : insns) { 116 | insn.accept(mp); 117 | StringWriter sw = new StringWriter(); 118 | printer.print(new PrintWriter(sw)); 119 | printer.getText().clear(); 120 | str.append(sw.toString().trim()).append("\n"); 121 | } 122 | } 123 | 124 | return str.toString(); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/jit/MqlCompiler.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | import net.hollowcube.mql.foreign.Query; 4 | import net.hollowcube.mql.parser.MqlParser; 5 | import net.hollowcube.mql.runtime.MqlMath; 6 | import net.hollowcube.mql.tree.*; 7 | import org.jetbrains.annotations.NotNull; 8 | import org.jetbrains.annotations.TestOnly; 9 | import org.objectweb.asm.ClassVisitor; 10 | import org.objectweb.asm.ClassWriter; 11 | import org.objectweb.asm.MethodVisitor; 12 | 13 | import java.lang.invoke.MethodHandle; 14 | import java.lang.invoke.MethodHandles; 15 | import java.lang.reflect.Method; 16 | import java.lang.reflect.Modifier; 17 | import java.lang.reflect.ParameterizedType; 18 | import java.util.ArrayList; 19 | import java.util.HashMap; 20 | import java.util.List; 21 | import java.util.Map; 22 | import java.util.concurrent.atomic.AtomicInteger; 23 | 24 | import static org.objectweb.asm.Opcodes.*; 25 | 26 | /** 27 | * A compiler for MQL scripts. 28 | *

29 | * Some reflection calls are cached, so this object should be reused as much as possible. 30 | *

31 | * Note: This class is not thread-safe, and must be synchronized externally. 32 | */ 33 | public class MqlCompiler { 34 | private static final AtomicInteger COUNTER = new AtomicInteger(); 35 | private static final ClassInfo MATH_CI = new ClassInfo(MqlMath.class, true); 36 | 37 | private final MethodHandles.Lookup lookup; 38 | private final Class scriptInterface; 39 | private final Class[] generics; 40 | 41 | private Method evalMethod; 42 | private ParamInfo[] evalMethodParams; 43 | private String evalFnDescriptor; 44 | 45 | public MqlCompiler(@NotNull MethodHandles.Lookup lookup, Class scriptInterface, Class... generics) { 46 | this.lookup = lookup; 47 | this.scriptInterface = scriptInterface; 48 | this.generics = generics; 49 | parseScriptInterface(); 50 | } 51 | 52 | public Class compile(String script) { 53 | String sourceHash = Integer.toHexString(script.hashCode()); 54 | // Could cache based on the hash if compiling many times over is a valid use case, but I don't think it is. 55 | 56 | String className = String.format("mql$%s$%d", sourceHash, COUNTER.getAndIncrement()); 57 | byte[] bytecode = compileBytecode(className, script); 58 | return (Class) AsmUtil.loadClass(className, bytecode); 59 | } 60 | 61 | @TestOnly 62 | public byte[] compileBytecode(String className, String script) { 63 | 64 | // Parse to an expression tree 65 | MqlExpr expr = new MqlParser(script).parse(); 66 | 67 | // Create the class 68 | ClassWriter scriptClass = new ClassWriter(ClassWriter.COMPUTE_MAXS); 69 | var sig = new StringBuilder(); 70 | sig.append('L').append(AsmUtil.toName(scriptInterface)).append('<'); 71 | for (Class generic : generics) 72 | sig.append(AsmUtil.toDescriptor(generic)); 73 | sig.append(">;"); 74 | var targetPackage = scriptInterface.getPackageName().replace('.', '/'); 75 | scriptClass.visit(V17, ACC_PUBLIC | ACC_FINAL | ACC_SYNTHETIC, targetPackage + "/" + className, sig.toString(), 76 | AsmUtil.toName(Object.class), new String[]{AsmUtil.toName(scriptInterface)}); 77 | 78 | // Generate required synthetics 79 | generateSynthetics(className, scriptClass); 80 | 81 | // Generate evaluate method 82 | MethodVisitor mv = scriptClass.visitMethod(ACC_PUBLIC, evalMethod.getName(), evalFnDescriptor, null, null); 83 | mv.visitCode(); 84 | new BytecodeGeneratingVisitor(className, mv).visit(expr, null); 85 | mv.visitInsn(DRETURN); // ok because all expressions leave a double on the stack 86 | mv.visitMaxs(0, 0); 87 | mv.visitEnd(); 88 | 89 | // Finish script class and return it 90 | scriptClass.visitEnd(); 91 | return scriptClass.toByteArray(); 92 | } 93 | 94 | 95 | /** 96 | * Ast visitor that generates bytecode for the given expression in the given method. 97 | *

98 | * Note: Every expression _must_ leave a double on the stack. If the expression has no result, it should leave 0. 99 | */ 100 | private class BytecodeGeneratingVisitor implements MqlVisitor { 101 | private final String className; 102 | private final MethodVisitor method; 103 | 104 | private BytecodeGeneratingVisitor(@NotNull String className, @NotNull MethodVisitor method) { 105 | this.className = className; 106 | this.method = method; 107 | } 108 | 109 | @Override 110 | public Void visitBinaryExpr(@NotNull MqlBinaryExpr expr, Void unused) { 111 | // Visit both sides, resulting in two doubles on the stack 112 | visit(expr.lhs(), null); 113 | visit(expr.rhs(), null); 114 | 115 | // Perform the operation 116 | switch (expr.operator()) { 117 | case PLUS -> method.visitInsn(DADD); 118 | case MINUS -> method.visitInsn(DSUB); 119 | case MUL -> method.visitInsn(DMUL); 120 | case DIV -> method.visitInsn(DDIV); 121 | case NULL_COALESCE -> { 122 | throw new RuntimeException("Null coalesce operator not supported in JIT mode"); 123 | } 124 | case GTE -> 125 | method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlRuntime.class), "gte", "(DD)D", false); 126 | case GE -> method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlRuntime.class), "ge", "(DD)D", false); 127 | case LTE -> 128 | method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlRuntime.class), "lte", "(DD)D", false); 129 | case LE -> method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlRuntime.class), "le", "(DD)D", false); 130 | case EQ -> method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlRuntime.class), "eq", "(DD)D", false); 131 | case NEQ -> 132 | method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlRuntime.class), "neq", "(DD)D", false); 133 | } 134 | 135 | return null; 136 | } 137 | 138 | @Override 139 | public Void visitAccessExpr(@NotNull MqlAccessExpr expr, Void unused) { 140 | // For now treat this as a zero args call, since we do not yet support assignment or field operators. 141 | if (!(expr.lhs() instanceof MqlIdentExpr ident)) 142 | throw new UnsupportedOperationException("Nested queries are not supported"); 143 | handleCall(ident.value(), expr.target(), new MqlArgListExpr(List.of())); 144 | return null; 145 | } 146 | 147 | @Override 148 | public Void visitCallExpr(MqlCallExpr expr, Void unused) { 149 | if (!(expr.access().lhs() instanceof MqlIdentExpr ident)) 150 | throw new UnsupportedOperationException("Nested queries are not supported"); 151 | 152 | handleCall(ident.value(), expr.access().target(), expr.argList()); 153 | return null; 154 | } 155 | 156 | private void handleCall(String queryName, String methodName, MqlArgListExpr args) { 157 | // If this is a math call, it will not be a known parameter 158 | if ("math".equals(queryName) || "m".equals(queryName)) { 159 | var method = MATH_CI.findMethod(methodName, args.size()); 160 | if (method == null) { 161 | throw new UnsupportedOperationException("Method not found with " + args.size() + ": " + methodName); 162 | } 163 | 164 | for (int i = 0; i < args.size(); i++) { 165 | visit(args.args().get(i), null); 166 | AsmUtil.convert(method.getParameterTypes()[i], double.class, this.method); 167 | } 168 | 169 | // Call the method 170 | this.method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlMath.class), method.getName(), AsmUtil.toDescriptor(method), false); 171 | return; 172 | } 173 | 174 | // Try to find a matching context object from script interface parameters. 175 | for (int j = 0; j < evalMethodParams.length; j++) { 176 | var param = evalMethodParams[j]; 177 | boolean found = false; 178 | for (var name : param.names) { 179 | if (name.equals(queryName)) { 180 | found = true; 181 | break; 182 | } 183 | } 184 | 185 | if (!found) continue; 186 | 187 | // Found the query object being referenced 188 | var method = param.ci.findMethod(methodName, args.size()); 189 | if (method == null) { 190 | throw new UnsupportedOperationException("Method not found with " + args.size() + ": " + methodName); 191 | } 192 | 193 | // Load the query object 194 | this.method.visitVarInsn(ALOAD, j + 1); 195 | 196 | // Load the parameters 197 | for (int i = 0; i < args.size(); i++) { 198 | visit(args.args().get(i), null); 199 | AsmUtil.convert(method.getParameterTypes()[i], double.class, this.method); 200 | } 201 | 202 | // Call the method 203 | this.method.visitMethodInsn(INVOKEVIRTUAL, AsmUtil.toName(param.ci.type), method.getName(), AsmUtil.toDescriptor(method), false); 204 | 205 | return; 206 | } 207 | 208 | throw new RuntimeException("Unknown query object: " + queryName); 209 | } 210 | 211 | @Override 212 | public Void visitUnaryExpr(@NotNull MqlUnaryExpr expr, Void unused) { 213 | visit(expr.rhs(), null); 214 | 215 | switch (expr.operator()) { 216 | case NEGATE -> method.visitInsn(DNEG); 217 | } 218 | 219 | return null; 220 | } 221 | 222 | @Override 223 | public Void visitTernaryExpr(MqlTernaryExpr expr, Void unused) { 224 | //todo this is a cursed implementation. It needs to be implemented in java for sanity, 225 | // but also because this is semantically incorrect. The ternary operator is not short-circuiting. 226 | visit(expr.condition(), null); 227 | visit(expr.trueCase(), null); 228 | visit(expr.falseCase(), null); 229 | 230 | method.visitMethodInsn(INVOKESTATIC, AsmUtil.toName(MqlRuntime.class), "ternary", "(DDD)D", false); 231 | 232 | return null; 233 | } 234 | 235 | @Override 236 | public Void visitNumberExpr(@NotNull MqlNumberExpr expr, Void unused) { 237 | double value = expr.value().value(); 238 | if (value == 0) { 239 | method.visitInsn(DCONST_0); 240 | } else if (value == 1) { 241 | method.visitInsn(DCONST_1); 242 | } else { 243 | method.visitLdcInsn(value); 244 | } 245 | return null; 246 | } 247 | 248 | } 249 | 250 | private void parseScriptInterface() { 251 | if (!scriptInterface.isInterface()) 252 | throw new IllegalArgumentException("Script interface must be an interface"); 253 | 254 | // Eval method 255 | var fnDesc = new StringBuilder().append('('); 256 | for (var method : scriptInterface.getMethods()) { 257 | if ((method.getModifiers() & Modifier.ABSTRACT) == 0) continue; 258 | if (evalMethod != null) throw new IllegalArgumentException("Script interface must have exactly one abstract method"); 259 | evalMethod = method; 260 | } 261 | if (evalMethod == null) throw new IllegalArgumentException("Script interface must have exactly one abstract"); 262 | evalMethodParams = new ParamInfo[evalMethod.getParameterCount()]; 263 | int genericIndex = 0; 264 | for (int i = 0; i < evalMethod.getParameterCount(); i++) { 265 | var param = evalMethod.getParameters()[i]; 266 | MqlEnv env = param.getAnnotation(MqlEnv.class); 267 | if (env == null) throw new IllegalArgumentException("Script interface parameters must be annotated with @MqlEnv"); 268 | 269 | if (param.getParameterizedType() instanceof ParameterizedType) { 270 | if (genericIndex >= generics.length) throw new IllegalArgumentException("Too many generic parameters"); 271 | evalMethodParams[i] = new ParamInfo(env.value(), new ClassInfo(generics[genericIndex++]), true); 272 | } else { 273 | evalMethodParams[i] = new ParamInfo(env.value(), new ClassInfo(param.getType()), false); 274 | } 275 | 276 | fnDesc.append(AsmUtil.toDescriptor(evalMethodParams[i].ci.type)); 277 | } 278 | evalFnDescriptor = fnDesc.append(")D").toString(); 279 | 280 | // Generic types 281 | if (generics.length != scriptInterface.getTypeParameters().length) 282 | throw new IllegalArgumentException("Script interface must have the same number of generic types as the generics parameter"); 283 | 284 | // Return type 285 | if (evalMethod.getReturnType() != double.class) 286 | throw new IllegalArgumentException("Script interface must return a double"); 287 | } 288 | 289 | private void generateSynthetics(@NotNull String className, @NotNull ClassVisitor cv) { 290 | // Add empty constructor 291 | var mv = cv.visitMethod(ACC_PUBLIC, "", "()V", null, null); 292 | mv.visitCode(); 293 | mv.visitVarInsn(ALOAD, 0); 294 | mv.visitMethodInsn(INVOKESPECIAL, AsmUtil.toName(Object.class), "", "()V", false); 295 | mv.visitInsn(RETURN); 296 | mv.visitMaxs(1, 1); 297 | mv.visitEnd(); 298 | 299 | // Insert bridge method for eval method if it has any generic parameters 300 | if (generics.length != 0) { 301 | var desc = new StringBuilder(); 302 | desc.append('('); 303 | for (ParamInfo param : evalMethodParams) { 304 | if (param.isGeneric) desc.append(AsmUtil.toDescriptor(Object.class)); 305 | else desc.append(AsmUtil.toDescriptor(param.ci.type)); 306 | } 307 | desc.append(")D"); 308 | 309 | mv = cv.visitMethod(ACC_PUBLIC | ACC_SYNTHETIC | ACC_BRIDGE, evalMethod.getName(), desc.toString(), null, null); 310 | mv.visitCode(); 311 | 312 | int paramIndex = 0; 313 | mv.visitVarInsn(ALOAD, paramIndex++); // this 314 | for (var param : evalMethodParams) { 315 | mv.visitVarInsn(ALOAD, paramIndex++); 316 | // If generic, cast to correct type 317 | if (param.isGeneric) { 318 | mv.visitTypeInsn(CHECKCAST, AsmUtil.toName(param.ci.type)); 319 | } 320 | } 321 | mv.visitMethodInsn(INVOKEVIRTUAL, className, "evaluate", evalFnDescriptor, false); 322 | mv.visitInsn(DRETURN); 323 | 324 | mv.visitMaxs(0, 0); 325 | mv.visitEnd(); 326 | } 327 | } 328 | 329 | private record ParamInfo(String[] names, ClassInfo ci, boolean isGeneric) { 330 | } 331 | 332 | private static class ClassInfo { 333 | private final Class type; 334 | private final boolean allowStatic; 335 | private final Map> methodsByName = new HashMap<>(); 336 | 337 | private ClassInfo(Class type) { 338 | this(type, false); 339 | } 340 | 341 | private ClassInfo(Class type, boolean allowStatic) { 342 | this.type = type; 343 | this.allowStatic = allowStatic; 344 | discoverMethods(type); 345 | } 346 | 347 | public Class getType() { 348 | return type; 349 | } 350 | 351 | public Method findMethod(String name, int params) { 352 | for (var method : methodsByName.getOrDefault(name, List.of())) { 353 | if (method.getParameterCount() == params) 354 | return method; 355 | } 356 | 357 | return null; 358 | } 359 | 360 | private void discoverMethods(Class type) { 361 | for (var method : type.getMethods()) { 362 | if (!allowStatic && (method.getModifiers() & Modifier.STATIC) != 0) continue; 363 | if (!method.isAnnotationPresent(Query.class)) continue; 364 | for (var paramType : method.getParameterTypes()) { 365 | if (!paramType.equals(double.class) && !paramType.equals(boolean.class)) 366 | throw new RuntimeException("Query method parameters must be either double or boolean"); 367 | } 368 | methodsByName.computeIfAbsent(method.getName(), k -> new ArrayList<>()) 369 | .add(method); 370 | } 371 | } 372 | } 373 | } 374 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/jit/MqlEnv.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Target(ElementType.PARAMETER) 9 | @Retention(RetentionPolicy.RUNTIME) 10 | public @interface MqlEnv { 11 | String[] value(); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/jit/MqlQueryScript.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | /** 4 | * An example MQL script interface. May be used if only a query object is required, otherwise serves as documentation. 5 | *

6 | * A script interface is a java interface with the following properties: 7 | *

    8 | *
  • Must be public, non-sealed.
  • 9 | *
  • Must have a single abstract method which returns a double ({@link FunctionalInterface} can enforce this at compile time, but is not required)
  • 10 | *
  • The abstract method may have 1 or more parameters, but all must be annotated with {@link MqlEnv}.
  • 11 | *
  • The abstract method may not have generic parameters.
  • 12 | *
  • The interface may use generic parameters, but they must be passed to the {@link MqlCompiler}
  • 13 | *
14 | */ 15 | @FunctionalInterface 16 | public interface MqlQueryScript { 17 | double evaluate(@MqlEnv({"query", "q"}) Query query); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/jit/MqlRuntime.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | public final class MqlRuntime { 4 | private MqlRuntime() { 5 | } 6 | 7 | public static double ternary(double condition, double ifTrue, double ifFalse) { 8 | return condition != 0 ? ifTrue : ifFalse; 9 | } 10 | 11 | public static double gte(double lhs, double rhs) { 12 | return lhs >= rhs ? 1 : 0; 13 | } 14 | 15 | public static double ge(double lhs, double rhs) { 16 | return lhs > rhs ? 1 : 0; 17 | } 18 | 19 | public static double lte(double lhs, double rhs) { 20 | return lhs <= rhs ? 1 : 0; 21 | } 22 | 23 | public static double le(double lhs, double rhs) { 24 | return lhs < rhs ? 1 : 0; 25 | } 26 | 27 | public static double eq(double lhs, double rhs) { 28 | return lhs == rhs ? 1 : 0; 29 | } 30 | 31 | public static double neq(double lhs, double rhs) { 32 | return lhs != rhs ? 1 : 0; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/parser/MqlLexer.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.parser; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.jetbrains.annotations.Nullable; 5 | 6 | public class MqlLexer { 7 | private final String source; 8 | 9 | private int start = 0; 10 | private int cursor = 0; 11 | 12 | public MqlLexer(@NotNull String source) { 13 | this.source = source; 14 | } 15 | 16 | /** 17 | * Returns the next token in the input, or null if the end of file was reached. 18 | * 19 | * @throws MqlParseError if there is an unexpected token. 20 | */ 21 | public @Nullable MqlToken next() { 22 | start = cursor; 23 | 24 | if (atEnd()) return null; 25 | 26 | consumeWhitespace(); 27 | 28 | char c = advance(); 29 | if (isAlpha(c)) 30 | return ident(); 31 | if (isDigit(c)) 32 | return number(); 33 | 34 | return symbol(c); 35 | } 36 | 37 | /** 38 | * Returns the next token without stepping to the next token in the input, 39 | * or null if the end of file was reached. 40 | * 41 | * @throws MqlParseError if there is an unexpected token. 42 | */ 43 | public @Nullable MqlToken peek() { 44 | var result = next(); 45 | cursor = start; // Reset to where it was before the call to next. 46 | return result; 47 | } 48 | 49 | public void expect(@NotNull MqlToken.Type type) { 50 | var next = next(); 51 | if (next == null || next.type() != type) 52 | throw new MqlParseError("Expected " + type + " but got " + next); 53 | } 54 | 55 | public @NotNull String span(@NotNull MqlToken token) { 56 | return source.substring(start, cursor).strip(); 57 | } 58 | 59 | private void consumeWhitespace() { 60 | while (true) { 61 | switch (peek0()) { 62 | case ' ', '\t', '\r', '\n' -> advance(); 63 | default -> { 64 | return; 65 | } 66 | } 67 | } 68 | } 69 | 70 | private MqlToken ident() { 71 | while (isAlpha(peek0()) || isDigit(peek0())) { 72 | advance(); 73 | } 74 | 75 | return new MqlToken(MqlToken.Type.IDENT, start, cursor); 76 | } 77 | 78 | private MqlToken number() { 79 | // Pre decimal 80 | while (isDigit(peek0())) 81 | advance(); 82 | 83 | // Decimal, if present 84 | if (match('.')) { 85 | while (isDigit(peek0())) 86 | advance(); 87 | } 88 | 89 | return new MqlToken(MqlToken.Type.NUMBER, start, cursor); 90 | } 91 | 92 | private MqlToken symbol(char c) { 93 | var tokenType = switch (c) { 94 | // @formatter:off 95 | case '+' -> MqlToken.Type.PLUS; 96 | case '-' -> MqlToken.Type.MINUS; 97 | case '*' -> MqlToken.Type.STAR; 98 | case '/' -> MqlToken.Type.SLASH; 99 | case '.' -> MqlToken.Type.DOT; 100 | case ',' -> MqlToken.Type.COMMA; 101 | case '?' -> { 102 | if (match('?')) { 103 | yield MqlToken.Type.QUESTIONQUESTION; 104 | } else { 105 | yield MqlToken.Type.QUESTION; 106 | } 107 | } 108 | case ':' -> MqlToken.Type.COLON; 109 | case '(' -> MqlToken.Type.LPAREN; 110 | case ')' -> MqlToken.Type.RPAREN; 111 | case '>' -> { 112 | if (match('=')) { 113 | yield MqlToken.Type.GTE; 114 | } else { 115 | yield MqlToken.Type.GE; 116 | } 117 | } 118 | case '<' -> { 119 | if (match('=')) { 120 | yield MqlToken.Type.LTE; 121 | } else { 122 | yield MqlToken.Type.LE; 123 | } 124 | } 125 | case '=' -> { 126 | if (match('=')) { 127 | yield MqlToken.Type.EQ; 128 | } else { 129 | throw new MqlParseError(String.format("unexpected token '%s' at %d.", c, cursor)); 130 | } 131 | } 132 | case '!' -> { 133 | if (match('=')) { 134 | yield MqlToken.Type.NEQ; 135 | } else { 136 | throw new MqlParseError(String.format("unexpected token '%s' at %d.", c, cursor)); 137 | } 138 | } 139 | default -> throw new MqlParseError( 140 | String.format("unexpected token '%s' at %d.", c, cursor)); 141 | // @formatter:on 142 | }; 143 | return new MqlToken(tokenType, start, cursor); 144 | } 145 | 146 | private boolean atEnd() { 147 | return cursor >= source.length(); 148 | } 149 | 150 | private char peek0() { 151 | if (atEnd()) 152 | return '\u0000'; 153 | return source.charAt(cursor); 154 | } 155 | 156 | private char advance() { 157 | if (atEnd()) throw new MqlParseError("unexpected end of input"); 158 | return source.charAt(cursor++); 159 | } 160 | 161 | private boolean match(char c) { 162 | if (atEnd()) return false; 163 | if (peek0() != c) return false; 164 | advance(); 165 | return true; 166 | } 167 | 168 | private boolean isAlpha(char c) { 169 | return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; 170 | } 171 | 172 | private boolean isDigit(char c) { 173 | return c >= '0' && c <= '9'; 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/parser/MqlParseError.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.parser; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public class MqlParseError extends RuntimeException { 6 | 7 | public MqlParseError(@NotNull String message) { 8 | super(message); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/parser/MqlParser.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.parser; 2 | 3 | import net.hollowcube.mql.tree.*; 4 | import org.jetbrains.annotations.NotNull; 5 | import org.jetbrains.annotations.Nullable; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | public class MqlParser { 11 | private final MqlLexer lexer; 12 | 13 | public MqlParser(@NotNull String source) { 14 | this.lexer = new MqlLexer(source); 15 | } 16 | 17 | public @NotNull MqlExpr parse() { 18 | return expr(0); 19 | } 20 | 21 | private @NotNull MqlExpr expr(int minBindingPower) { 22 | MqlExpr lhs = lhs(); 23 | 24 | while (true) { 25 | Operator op = operator(); 26 | if (op == null) break; 27 | 28 | var postfixBindingPower = op.postfixBindingPower(); 29 | if (postfixBindingPower != -1) { 30 | if (postfixBindingPower < minBindingPower) break; 31 | lexer.next(); // Operator token 32 | 33 | lhs = switch (op) { 34 | case TERNARY -> { 35 | var trueExpr = expr(0); 36 | lexer.expect(MqlToken.Type.COLON); 37 | var falseExpr = expr(postfixBindingPower); 38 | yield new MqlTernaryExpr(lhs, trueExpr, falseExpr); 39 | } 40 | case LPAREN -> { 41 | if (lhs instanceof MqlAccessExpr access) { 42 | // Get argument list 43 | List args = new ArrayList<>(); 44 | var next = lexer.peek(); 45 | 46 | if (next != null && next.type() != MqlToken.Type.RPAREN) { 47 | do { 48 | args.add(expr(0)); 49 | next = lexer.peek(); 50 | } while (next != null && next.type() == MqlToken.Type.COMMA && lexer.next() != null); 51 | 52 | lexer.expect(MqlToken.Type.RPAREN); 53 | yield new MqlCallExpr(access, new MqlArgListExpr(args)); 54 | } 55 | } 56 | yield lhs; 57 | } 58 | default -> throw new IllegalStateException("Unexpected value: " + op); 59 | }; 60 | 61 | continue; 62 | } 63 | 64 | // Stop if operator left binding power is less than the current min 65 | if (op.lbp < minBindingPower) break; 66 | 67 | lexer.next(); // Operator token 68 | 69 | // Parse right side expression 70 | MqlExpr rhs = expr(op.rbp); 71 | lhs = switch (op) { 72 | case MEMBER_ACCESS -> { 73 | if (!(rhs instanceof MqlIdentExpr ident)) 74 | throw new MqlParseError("rhs of member access must be an ident, was " + rhs); 75 | yield new MqlAccessExpr(lhs, ident.value()); 76 | } 77 | default -> new MqlBinaryExpr(op.op, lhs, rhs); 78 | }; 79 | } 80 | 81 | return lhs; 82 | } 83 | 84 | /** 85 | * Parses a possible left side expression. 86 | */ 87 | private @NotNull MqlExpr lhs() { 88 | MqlToken token = lexer.next(); 89 | if (token == null) throw new MqlParseError("unexpected end of input"); 90 | 91 | return switch (token.type()) { 92 | case NUMBER -> new MqlNumberExpr(Double.parseDouble(lexer.span(token))); 93 | case IDENT -> new MqlIdentExpr(lexer.span(token)); 94 | case MINUS -> { 95 | var rhs = expr(Operator.MINUS.prefixBindingPower()); 96 | yield new MqlUnaryExpr(MqlUnaryExpr.Op.NEGATE, rhs); 97 | } 98 | case LPAREN -> { 99 | var expr = expr(0); 100 | lexer.expect(MqlToken.Type.RPAREN); 101 | yield expr; 102 | } 103 | //todo better error handling 104 | default -> throw new MqlParseError("unexpected token " + token); 105 | }; 106 | } 107 | 108 | private @Nullable Operator operator() { 109 | MqlToken token = lexer.peek(); 110 | if (token == null) return null; 111 | return switch (token.type()) { 112 | case PLUS -> Operator.PLUS; 113 | case MINUS -> Operator.MINUS; 114 | case SLASH -> Operator.DIV; 115 | case STAR -> Operator.MUL; 116 | case DOT -> Operator.MEMBER_ACCESS; 117 | case QUESTION -> Operator.TERNARY; 118 | case QUESTIONQUESTION -> Operator.NULL_COALESCE; 119 | case LPAREN -> Operator.LPAREN; 120 | case GTE -> Operator.GTE; 121 | case GE -> Operator.GE; 122 | case LTE -> Operator.LTE; 123 | case LE -> Operator.LE; 124 | case EQ -> Operator.EQ; 125 | case NEQ -> Operator.NEQ; 126 | default -> null; 127 | }; 128 | } 129 | 130 | private enum Operator { 131 | NULL_COALESCE(5, 6, MqlBinaryExpr.Op.NULL_COALESCE), 132 | PLUS(25, 26, MqlBinaryExpr.Op.PLUS), 133 | MINUS(25, 26, MqlBinaryExpr.Op.MINUS), 134 | DIV(27, 28, MqlBinaryExpr.Op.DIV), 135 | MUL(27, 28, MqlBinaryExpr.Op.MUL), 136 | LPAREN(30, 30, null), 137 | 138 | GTE(30, 31, MqlBinaryExpr.Op.GTE), 139 | GE(30, 31, MqlBinaryExpr.Op.GE), 140 | LTE(30, 31, MqlBinaryExpr.Op.LTE), 141 | LE(30, 31, MqlBinaryExpr.Op.LE), 142 | EQ(30, 31, MqlBinaryExpr.Op.EQ), 143 | NEQ(30, 31, MqlBinaryExpr.Op.NEQ), 144 | 145 | MEMBER_ACCESS(35, 36, null), 146 | TERNARY(0, 0, null); // Open of a ternary expression (?), only a postfix operator 147 | 148 | private final int lbp; 149 | private final int rbp; 150 | private final MqlBinaryExpr.Op op; 151 | 152 | Operator(int lbp, int rbp, MqlBinaryExpr.Op op) { 153 | this.lbp = lbp; 154 | this.rbp = rbp; 155 | this.op = op; 156 | } 157 | 158 | public int prefixBindingPower() { 159 | return switch (this) { 160 | case MINUS -> 30; 161 | default -> -1; 162 | }; 163 | } 164 | 165 | public int postfixBindingPower() { 166 | return switch (this) { 167 | case TERNARY -> 1; 168 | case LPAREN -> 34; 169 | default -> -1; 170 | }; 171 | } 172 | } 173 | 174 | } 175 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/parser/MqlToken.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.parser; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | record MqlToken(@NotNull Type type, int start, int end) { 6 | 7 | enum Type { 8 | PLUS, MINUS, STAR, SLASH, 9 | LPAREN, RPAREN, 10 | DOT, COMMA, COLON, QUESTION, QUESTIONQUESTION, 11 | GTE, GE, LTE, LE, EQ, NEQ, 12 | NUMBER, IDENT; 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/runtime/MqlMath.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.runtime; 2 | 3 | import net.hollowcube.mql.foreign.MqlForeignFunctions; 4 | import net.hollowcube.mql.foreign.Query; 5 | 6 | import java.util.concurrent.ThreadLocalRandom; 7 | 8 | public class MqlMath { 9 | 10 | public static final MqlScope INSTANCE = MqlForeignFunctions.create(MqlMath.class, null); 11 | 12 | private MqlMath() { 13 | } 14 | 15 | /** 16 | * Absolute value of value 17 | */ 18 | @Query 19 | public static double abs(double value) { 20 | return Math.abs(value); 21 | } 22 | 23 | /** 24 | * arccos of value 25 | */ 26 | @Query 27 | public static double acos(double value) { 28 | return Math.toDegrees(Math.acos(value)); 29 | } 30 | 31 | /** 32 | * arcsin of value 33 | */ 34 | @Query 35 | public static double asin(double value) { 36 | return Math.toDegrees(Math.asin(value)); 37 | } 38 | 39 | /** 40 | * arctan of value 41 | */ 42 | @Query 43 | public static double atan(double value) { 44 | return Math.toDegrees(Math.atan(value)); 45 | } 46 | 47 | /** 48 | * arctan of y/x. NOTE: the order of arguments! 49 | */ 50 | @Query 51 | public static double atan2(double y, double x) { 52 | return Math.toDegrees(Math.atan2(y, x)); 53 | } 54 | 55 | /** 56 | * Round value up to nearest integral number 57 | */ 58 | @Query 59 | public static double ceil(double value) { 60 | return Math.ceil(value); 61 | } 62 | 63 | /** 64 | * Clamp value to between min and max inclusive 65 | */ 66 | @Query 67 | public static double clamp(double value, double min, double max) { 68 | return Math.min(Math.max(value, min), max); 69 | } 70 | 71 | /** 72 | * Cosine (in degrees) of value 73 | */ 74 | @Query 75 | public static double cos(double value) { 76 | return Math.cos(Math.toRadians(value)); 77 | } 78 | 79 | /** 80 | * Returns the sum of 'num' random numbers, each with a value from low to high. Note: the generated random numbers are not integers like normal dice. For that, use math.die_roll_integer. 81 | */ 82 | @Query 83 | public static double dieRoll(double num, double low, double high) { 84 | double total = 0; 85 | for (int i = 0; i < num; i++) 86 | total += random(low, high); 87 | return total; 88 | } 89 | 90 | /** 91 | * Returns the sum of 'num' random integer numbers, each with a value from low to high. Note: the generated random numbers are integers like normal dice. 92 | */ 93 | @Query 94 | public static double dieRollInteger(double num, double low, double high) { 95 | double total = 0; 96 | for (int i = 0; i < num; i++) 97 | total += randomInteger(low, high); 98 | return total; 99 | } 100 | 101 | /** 102 | * Calculates e to the value 'nth' power 103 | */ 104 | @Query 105 | public static double exp(double value) { 106 | return Math.exp(value); 107 | } 108 | 109 | /** 110 | * Round value down to nearest integral number 111 | */ 112 | @Query 113 | public static double floor(double value) { 114 | return Math.floor(value); 115 | } 116 | 117 | /** 118 | * Useful for simple smooth curve interpolation using one of the Hermite Basis functions: 3t^2 - 2t^3. Note that while any valid float is a valid input, this function works best in the range [0,1]. 119 | */ 120 | @Query 121 | public static double hermiteBlend(double value) { 122 | //todo: implement me 123 | throw new MqlRuntimeError("hermite_blend not implemented"); 124 | } 125 | 126 | /** 127 | * Lerp from start to end via zeroToOne 128 | */ 129 | @Query 130 | public static double lerp(double start, double end, double zeroToOne) { 131 | //todo test me 132 | zeroToOne = clamp(zeroToOne, 0, 1); 133 | return start * zeroToOne + end * (1D - zeroToOne); 134 | } 135 | 136 | /** 137 | * Lerp the shortest direction around a circle from start degrees to end degrees via zeroToOne 138 | */ 139 | @Query 140 | public static double lerprotate(double start, double end, double zeroToOne) { 141 | //todo test me 142 | zeroToOne = clamp(zeroToOne, 0, 1); 143 | double diff = end - start; 144 | if (diff > 180) diff -= 360; 145 | else if (diff < -180) diff += 360; 146 | return start + diff * zeroToOne; 147 | } 148 | 149 | /** 150 | * Natural logarithm of value 151 | */ 152 | @Query 153 | public static double ln(double value) { 154 | return Math.log(value); 155 | } 156 | 157 | /** 158 | * Return highest value of A or B 159 | */ 160 | @Query 161 | public static double max(double a, double b) { 162 | return Math.max(a, b); 163 | } 164 | 165 | /** 166 | * Return lowest value of A or B 167 | */ 168 | @Query 169 | public static double min(double a, double b) { 170 | return Math.min(a, b); 171 | } 172 | 173 | /** 174 | * Minimize angle magnitude (in degrees) into the range [-180, 180) 175 | */ 176 | @Query 177 | public static double minAngle(double value) { 178 | //todo: implement me 179 | throw new MqlRuntimeError("hermite_blend not implemented"); 180 | } 181 | 182 | /** 183 | * Return the remainder of value / denominator 184 | */ 185 | @Query 186 | public static double mod(double value, double denominator) { 187 | return value % denominator; 188 | } 189 | 190 | /** 191 | * Returns the float representation of the constant pi. 192 | */ 193 | @Query 194 | public static double pi() { 195 | return Math.PI; 196 | } 197 | 198 | /** 199 | * Elevates base to the exponent'th power 200 | */ 201 | @Query 202 | public static double pow(double base, double exponent) { 203 | return Math.pow(base, exponent); 204 | } 205 | 206 | /** 207 | * Random value between low (inclusive) and high (exclusive) 208 | *

209 | * Note: The original molang spec says that the range is inclusive, but this high end is exclusive. 210 | */ 211 | @Query 212 | public static double random(double low, double high) { 213 | return ThreadLocalRandom.current().nextDouble(low, high); 214 | } 215 | 216 | /** 217 | * Random integer value between low and high (inclusive) 218 | */ 219 | @Query 220 | public static double randomInteger(double low, double high) { 221 | return ThreadLocalRandom.current().nextInt((int) low, (int) high + 1); 222 | } 223 | 224 | /** 225 | * Round value to nearest integral number 226 | */ 227 | @Query 228 | public static double round(double value) { 229 | return Math.round(value); 230 | } 231 | 232 | /** 233 | * Sine (in degrees) of value 234 | */ 235 | @Query 236 | public static double sin(double value) { 237 | return Math.sin(Math.toRadians(value)); 238 | } 239 | 240 | /** 241 | * Square root of value 242 | */ 243 | @Query 244 | public static double sqrt(double value) { 245 | return Math.sqrt(value); 246 | } 247 | 248 | /** 249 | * Round value towards zero 250 | */ 251 | @Query 252 | public static double trunc(double value) { 253 | return value < 0 ? Math.ceil(value) : Math.floor(value); 254 | } 255 | 256 | } 257 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/runtime/MqlRuntimeError.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.runtime; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public class MqlRuntimeError extends RuntimeException { 6 | public MqlRuntimeError(@NotNull String message) { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/runtime/MqlScope.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.runtime; 2 | 3 | import net.hollowcube.mql.value.MqlHolder; 4 | import net.hollowcube.mql.value.MqlValue; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | public interface MqlScope extends MqlHolder { 8 | 9 | MqlScope EMPTY = unused -> MqlValue.NULL; 10 | 11 | @NotNull MqlValue get(@NotNull String name); 12 | 13 | interface Mutable extends MqlScope { 14 | 15 | void set(@NotNull String name, @NotNull MqlValue value); 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/runtime/MqlScopeImpl.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.runtime; 2 | 3 | import net.hollowcube.mql.value.MqlValue; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | public class MqlScopeImpl implements MqlScope { 10 | protected final Map data = new HashMap<>(); 11 | 12 | @Override 13 | public @NotNull MqlValue get(@NotNull String name) { 14 | return data.getOrDefault(name, MqlValue.NULL); 15 | } 16 | 17 | 18 | public static class Mutable extends MqlScopeImpl implements MqlScope.Mutable { 19 | 20 | @Override 21 | public void set(@NotNull String name, @NotNull MqlValue value) { 22 | data.put(name, value); 23 | } 24 | 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/runtime/MqlScriptScope.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.runtime; 2 | 3 | import net.hollowcube.mql.value.MqlValue; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | public class MqlScriptScope implements MqlScope { 7 | 8 | private final MqlScope query; 9 | private final MqlScope.Mutable actor; 10 | private final MqlScope context; 11 | private final MqlScope.Mutable temp = new MqlScopeImpl.Mutable(); 12 | 13 | public MqlScriptScope(@NotNull MqlScope query, @NotNull Mutable actor, @NotNull MqlScope context) { 14 | this.query = query; 15 | this.actor = actor; 16 | this.context = context; 17 | } 18 | 19 | @Override 20 | public @NotNull MqlValue get(@NotNull String name) { 21 | return switch (name) { 22 | case "math", "m", "Math" -> MqlMath.INSTANCE; 23 | case "query", "q" -> query; 24 | case "temp", "t" -> temp; 25 | case "variable", "v" -> actor; 26 | case "context", "c" -> context; 27 | default -> throw new MqlRuntimeError("unknown environment object: " + name); 28 | }; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlAccessExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlHolder; 5 | import net.hollowcube.mql.value.MqlValue; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public record MqlAccessExpr( 9 | @NotNull MqlExpr lhs, String target) implements MqlExpr { 10 | 11 | @Override 12 | public MqlValue evaluate(@NotNull MqlScope scope) { 13 | var lhs = lhs().evaluate(scope).cast(MqlHolder.class); 14 | return lhs.get(target()); 15 | } 16 | 17 | @Override 18 | public R visit(@NotNull MqlVisitor visitor, P p) { 19 | return visitor.visitAccessExpr(this, p); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlArgListExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlValue; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | import java.util.List; 8 | 9 | public record MqlArgListExpr(List args) implements MqlExpr { 10 | @Override 11 | public MqlValue evaluate(@NotNull MqlScope scope) { 12 | return null; 13 | } 14 | 15 | @Override 16 | public R visit(@NotNull MqlVisitor visitor, P p) { 17 | return visitor.visitArgListExpr(this, p); 18 | } 19 | 20 | public int size() { 21 | return args().size(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlBinaryExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlNumberValue; 5 | import net.hollowcube.mql.value.MqlValue; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public record MqlBinaryExpr( 9 | @NotNull Op operator, 10 | @NotNull MqlExpr lhs, 11 | @NotNull MqlExpr rhs 12 | ) implements MqlExpr { 13 | public enum Op { 14 | PLUS, 15 | MINUS, 16 | DIV, 17 | MUL, 18 | NULL_COALESCE, 19 | GTE, 20 | GE, 21 | LTE, 22 | LE, 23 | EQ, 24 | NEQ 25 | } 26 | 27 | @Override 28 | public MqlValue evaluate(@NotNull MqlScope scope) { 29 | // Handle lazy evaluation of null coalescing lhs and rhs 30 | if (operator() == Op.NULL_COALESCE) { 31 | var lhs = lhs().evaluate(scope).cast(MqlNumberValue.class); 32 | if (lhs.value() != 0) { 33 | return lhs; 34 | } 35 | 36 | return rhs().evaluate(scope); 37 | } 38 | 39 | // The rest use both lhs and rhs always 40 | MqlNumberValue lhs = lhs().evaluate(scope).cast(MqlNumberValue.class); 41 | MqlNumberValue rhs = rhs().evaluate(scope).cast(MqlNumberValue.class); 42 | 43 | return switch (operator()) { 44 | case PLUS -> new MqlNumberValue(lhs.value() + rhs.value()); 45 | case MINUS -> new MqlNumberValue(lhs.value() - rhs.value()); 46 | case DIV -> new MqlNumberValue(lhs.value() / rhs.value()); 47 | case MUL -> new MqlNumberValue(lhs.value() * rhs.value()); 48 | case GTE -> new MqlNumberValue(lhs.value() >= rhs.value() ? 1 : 0); 49 | case GE -> new MqlNumberValue(lhs.value() > rhs.value() ? 1 : 0); 50 | case LTE -> new MqlNumberValue(lhs.value() <= rhs.value() ? 1 : 0); 51 | case LE -> new MqlNumberValue(lhs.value() < rhs.value() ? 1 : 0); 52 | case EQ -> new MqlNumberValue(lhs.value() == rhs.value() ? 1 : 0); 53 | case NEQ -> new MqlNumberValue(lhs.value() != rhs.value() ? 1 : 0); 54 | case NULL_COALESCE -> throw new RuntimeException("unreachable"); 55 | }; 56 | } 57 | 58 | @Override 59 | public R visit(@NotNull MqlVisitor visitor, P p) { 60 | return visitor.visitBinaryExpr(this, p); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlCallExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlCallable; 5 | import net.hollowcube.mql.value.MqlNumberValue; 6 | import net.hollowcube.mql.value.MqlValue; 7 | import org.jetbrains.annotations.NotNull; 8 | 9 | public record MqlCallExpr(@NotNull MqlAccessExpr access, @NotNull MqlArgListExpr argList) implements MqlExpr { 10 | @Override 11 | public MqlValue evaluate(@NotNull MqlScope scope) { 12 | var callable = access().evaluate(scope).cast(MqlCallable.class); 13 | return callable.call(argList.args(), scope).cast(MqlNumberValue.class); 14 | } 15 | 16 | @Override 17 | public R visit(@NotNull MqlVisitor visitor, P p) { 18 | return visitor.visitCallExpr(this, p); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlValue; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | public sealed interface MqlExpr permits MqlAccessExpr, MqlArgListExpr, MqlBinaryExpr, MqlCallExpr, MqlIdentExpr, MqlNumberExpr, MqlTernaryExpr, MqlUnaryExpr { 8 | 9 | MqlValue evaluate(@NotNull MqlScope scope); 10 | 11 | R visit(@NotNull MqlVisitor visitor, P p); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlIdentExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlValue; 5 | import org.jetbrains.annotations.NotNull; 6 | 7 | public record MqlIdentExpr(@NotNull String value) implements MqlExpr { 8 | 9 | @Override 10 | public MqlValue evaluate(@NotNull MqlScope scope) { 11 | return scope.get(value); 12 | } 13 | 14 | @Override 15 | public R visit(@NotNull MqlVisitor visitor, P p) { 16 | return visitor.visitRefExpr(this, p); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlNumberExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlNumberValue; 5 | import net.hollowcube.mql.value.MqlValue; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public record MqlNumberExpr(@NotNull MqlNumberValue value) implements MqlExpr { 9 | 10 | public MqlNumberExpr(double value) { 11 | this(new MqlNumberValue(value)); 12 | } 13 | 14 | @Override 15 | public MqlValue evaluate(@NotNull MqlScope scope) { 16 | return value; 17 | } 18 | 19 | @Override 20 | public R visit(@NotNull MqlVisitor visitor, P p) { 21 | return visitor.visitNumberExpr(this, p); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlTernaryExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlNumberValue; 5 | import net.hollowcube.mql.value.MqlValue; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public record MqlTernaryExpr( 9 | @NotNull MqlExpr condition, 10 | @NotNull MqlExpr trueCase, 11 | @NotNull MqlExpr falseCase 12 | ) implements MqlExpr { 13 | 14 | @Override 15 | public MqlValue evaluate(@NotNull MqlScope scope) { 16 | var condition = condition().evaluate(scope).cast(MqlNumberValue.class); 17 | return condition.value() != 0 ? trueCase().evaluate(scope) : falseCase().evaluate(scope); 18 | } 19 | 20 | @Override 21 | public R visit(@NotNull MqlVisitor visitor, P p) { 22 | return visitor.visitTernaryExpr(this, p); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlUnaryExpr.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.value.MqlNumberValue; 5 | import net.hollowcube.mql.value.MqlValue; 6 | import org.jetbrains.annotations.NotNull; 7 | 8 | public record MqlUnaryExpr( 9 | @NotNull Op operator, 10 | @NotNull MqlExpr rhs 11 | ) implements MqlExpr { 12 | public enum Op { 13 | NEGATE, 14 | } 15 | 16 | @Override 17 | public MqlValue evaluate(@NotNull MqlScope scope) { 18 | MqlNumberValue rhs = rhs().evaluate(scope).cast(MqlNumberValue.class); 19 | 20 | return switch (operator()) { 21 | case NEGATE -> new MqlNumberValue(-rhs.value()); 22 | }; 23 | } 24 | 25 | @Override 26 | public R visit(@NotNull MqlVisitor visitor, P p) { 27 | return visitor.visitUnaryExpr(this, p); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/tree/MqlVisitor.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.tree; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | // @formatter:off 6 | public interface MqlVisitor { 7 | 8 | default R visitBinaryExpr(@NotNull MqlBinaryExpr expr, P p) { 9 | return defaultValue(); 10 | } 11 | 12 | default R visitUnaryExpr(@NotNull MqlUnaryExpr expr, P p) { 13 | return defaultValue(); 14 | } 15 | 16 | default R visitAccessExpr(@NotNull MqlAccessExpr expr, P p) { 17 | return defaultValue(); 18 | } 19 | 20 | default R visitNumberExpr(@NotNull MqlNumberExpr expr, P p) { 21 | return defaultValue(); 22 | } 23 | 24 | default R visitRefExpr(@NotNull MqlIdentExpr expr, P p) { 25 | return defaultValue(); 26 | } 27 | 28 | default R visitArgListExpr(MqlArgListExpr mqlArgListExpr, P p) { 29 | return defaultValue(); 30 | } 31 | 32 | ; 33 | 34 | default R visitTernaryExpr(MqlTernaryExpr expr, P p) { 35 | return defaultValue(); 36 | } 37 | 38 | default R visitCallExpr(MqlCallExpr expr, P p) { 39 | return defaultValue(); 40 | } 41 | 42 | default R visit(@NotNull MqlExpr expr, P p) { 43 | return expr.visit(this, p); 44 | } 45 | 46 | default R defaultValue() { 47 | return null; 48 | } 49 | } 50 | // @formatter:on 51 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/util/MqlPrinter.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.util; 2 | 3 | import net.hollowcube.mql.tree.*; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | public class MqlPrinter implements MqlVisitor { 7 | 8 | @Override 9 | public String visitBinaryExpr(@NotNull MqlBinaryExpr expr, Void unused) { 10 | return String.format( 11 | "(%s %s %s)", 12 | switch (expr.operator()) { 13 | case PLUS -> "+"; 14 | case MINUS -> "-"; 15 | case MUL -> "*"; 16 | case DIV -> "/"; 17 | case NULL_COALESCE -> "??"; 18 | case GTE -> ">="; 19 | case GE -> ">"; 20 | case LTE -> "<="; 21 | case LE -> "<"; 22 | case EQ -> "=="; 23 | case NEQ -> "!="; 24 | }, 25 | visit(expr.lhs(), null), 26 | visit(expr.rhs(), null) 27 | ); 28 | } 29 | 30 | @Override 31 | public String visitUnaryExpr(@NotNull MqlUnaryExpr expr, Void unused) { 32 | return String.format( 33 | "(%s %s)", 34 | switch (expr.operator()) { 35 | case NEGATE -> "-"; 36 | }, 37 | visit(expr.rhs(), null) 38 | ); 39 | } 40 | 41 | @Override 42 | public String visitAccessExpr(@NotNull MqlAccessExpr expr, Void unused) { 43 | return String.format( 44 | "(. %s %s)", 45 | visit(expr.lhs(), null), 46 | expr.target() 47 | ); 48 | } 49 | 50 | @Override 51 | public String visitNumberExpr(@NotNull MqlNumberExpr expr, Void unused) { 52 | return String.valueOf(expr.value()); 53 | } 54 | 55 | @Override 56 | public String visitRefExpr(@NotNull MqlIdentExpr expr, Void unused) { 57 | return expr.value(); 58 | } 59 | 60 | @Override 61 | public String visitArgListExpr(@NotNull MqlArgListExpr expr, Void unused) { 62 | StringBuilder sb = new StringBuilder(); 63 | sb.append("("); 64 | 65 | for (int i = 0; i < expr.args().size(); i++) { 66 | sb.append(visit(expr.args().get(i), null)); 67 | if (i != expr.args().size() - 1) { 68 | sb.append(" "); 69 | } 70 | } 71 | 72 | sb.append(")"); 73 | return sb.toString(); 74 | } 75 | 76 | @Override 77 | public String visitTernaryExpr(MqlTernaryExpr expr, Void unused) { 78 | return String.format( 79 | "(? %s %s %s)", 80 | visit(expr.condition(), null), 81 | visit(expr.trueCase(), null), 82 | visit(expr.falseCase(), null) 83 | ); 84 | } 85 | 86 | @Override 87 | public String visitCallExpr(MqlCallExpr expr, Void unused) { 88 | return String.format( 89 | "(? %s %s)", 90 | visit(expr.access(), null), 91 | visit(expr.argList(), null) 92 | ); 93 | } 94 | 95 | @Override 96 | public String defaultValue() { 97 | return "##Error"; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/value/MqlCallable.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.value; 2 | 3 | import net.hollowcube.mql.runtime.MqlScope; 4 | import net.hollowcube.mql.tree.MqlExpr; 5 | import org.jetbrains.annotations.NotNull; 6 | import org.jetbrains.annotations.Nullable; 7 | 8 | import java.util.List; 9 | 10 | @FunctionalInterface 11 | public non-sealed interface MqlCallable extends MqlValue { 12 | 13 | /** 14 | * Returns the arity of the function, or -1 if it is variadic/otherwise unknown 15 | */ 16 | default int arity() { 17 | return -1; 18 | } 19 | 20 | @NotNull MqlValue call(@NotNull List args, @Nullable MqlScope scope); 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/value/MqlHolder.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.value; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | 5 | public non-sealed interface MqlHolder extends MqlValue { 6 | 7 | @NotNull MqlValue get(@NotNull String name); 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/value/MqlIdentValue.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.value; 2 | 3 | import org.jetbrains.annotations.ApiStatus; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | @ApiStatus.Internal 7 | public record MqlIdentValue(@NotNull String value) implements MqlValue { 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/value/MqlNumberValue.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.value; 2 | 3 | public record MqlNumberValue(double value) implements MqlValue { 4 | 5 | @Override 6 | public String toString() { 7 | return String.valueOf(value); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/net/hollowcube/mql/value/MqlValue.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.value; 2 | 3 | import net.hollowcube.mql.runtime.MqlRuntimeError; 4 | import org.jetbrains.annotations.NotNull; 5 | 6 | /** 7 | * Mutable marker for any possible mql value. 8 | */ 9 | public sealed interface MqlValue permits MqlCallable, MqlHolder, MqlIdentValue, MqlNumberValue { 10 | MqlValue NULL = new MqlNumberValue(0.0); 11 | 12 | static @NotNull MqlValue from(boolean bool) { 13 | return new MqlNumberValue(bool ? 1 : 0); 14 | } 15 | 16 | static @NotNull MqlValue from(double dbl) { 17 | return new MqlNumberValue(dbl); 18 | } 19 | 20 | default Target cast(@NotNull Class targetType) { 21 | if (targetType.isInstance(this)) 22 | //noinspection unchecked 23 | return (Target) this; 24 | throw new MqlRuntimeError("cannot cast " + this.getClass().getSimpleName() + " to " + targetType.getSimpleName()); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/TestMql.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql; 2 | 3 | import net.hollowcube.mql.parser.MqlParser; 4 | import net.hollowcube.mql.runtime.MqlRuntimeError; 5 | import net.hollowcube.mql.runtime.MqlScope; 6 | import net.hollowcube.mql.runtime.MqlScopeImpl; 7 | import net.hollowcube.mql.runtime.MqlScriptScope; 8 | import net.hollowcube.mql.value.MqlHolder; 9 | import net.hollowcube.mql.value.MqlNumberValue; 10 | import net.hollowcube.mql.value.MqlValue; 11 | import org.jetbrains.annotations.NotNull; 12 | import org.junit.jupiter.api.Test; 13 | 14 | import static org.junit.jupiter.api.Assertions.assertEquals; 15 | import static org.junit.jupiter.api.Assertions.assertTrue; 16 | 17 | public class TestMql { 18 | // This is a weird test case 19 | 20 | @Test 21 | public void basicQueryCall() { 22 | var source = "q.is_alive"; 23 | var expr = new MqlParser(source).parse(); 24 | 25 | var scope = new MqlScope() { 26 | @Override 27 | public @NotNull MqlValue get(@NotNull String name) { 28 | if (!name.equals("q") && !name.equals("query")) 29 | throw new MqlRuntimeError("unknown environment object: " + name); 30 | return (MqlHolder) queryFunction -> switch (queryFunction) { 31 | case "is_alive" -> new MqlNumberValue(1); 32 | default -> throw new MqlRuntimeError("no such query function: " + queryFunction); 33 | }; 34 | } 35 | }; 36 | var result = expr.evaluate(scope); 37 | assertTrue(result instanceof MqlNumberValue); 38 | assertEquals(1, ((MqlNumberValue) result).value()); 39 | } 40 | 41 | @Test 42 | public void testAdd() { 43 | var source = "10 + 10 + 10"; 44 | 45 | var expr = new MqlParser(source).parse(); 46 | var scopeImpl = new MqlScopeImpl(); 47 | var vars = new MqlScopeImpl.Mutable(); 48 | 49 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 50 | var result = expr.evaluate(scope); 51 | 52 | assertTrue(result instanceof MqlNumberValue); 53 | assertEquals(30, ((MqlNumberValue) result).value()); 54 | } 55 | 56 | @Test 57 | public void testSub() { 58 | var source = "10 - 10 - 10 - 10"; 59 | 60 | var expr = new MqlParser(source).parse(); 61 | var scopeImpl = new MqlScopeImpl(); 62 | var vars = new MqlScopeImpl.Mutable(); 63 | 64 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 65 | var result = expr.evaluate(scope); 66 | 67 | assertTrue(result instanceof MqlNumberValue); 68 | assertEquals(-20, ((MqlNumberValue) result).value()); 69 | } 70 | 71 | @Test 72 | public void testMul() { 73 | var source = "10 * 10 * 10 * 10"; 74 | 75 | var expr = new MqlParser(source).parse(); 76 | var scopeImpl = new MqlScopeImpl(); 77 | var vars = new MqlScopeImpl.Mutable(); 78 | 79 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 80 | var result = expr.evaluate(scope); 81 | 82 | assertTrue(result instanceof MqlNumberValue); 83 | assertEquals(10 * 10 * 10 * 10, ((MqlNumberValue) result).value()); 84 | } 85 | 86 | @Test 87 | public void testDiv() { 88 | var source = "10000 / 10 / 10 / 10"; 89 | 90 | var expr = new MqlParser(source).parse(); 91 | var scopeImpl = new MqlScopeImpl(); 92 | var vars = new MqlScopeImpl.Mutable(); 93 | 94 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 95 | var result = expr.evaluate(scope); 96 | 97 | assertTrue(result instanceof MqlNumberValue); 98 | assertEquals(10000 / 10 / 10 / 10, ((MqlNumberValue) result).value()); 99 | } 100 | 101 | @Test 102 | public void testMixed() { 103 | var source = "10 + 3 * 3 - 1 * 5"; 104 | 105 | var expr = new MqlParser(source).parse(); 106 | var scopeImpl = new MqlScopeImpl(); 107 | var vars = new MqlScopeImpl.Mutable(); 108 | 109 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 110 | var result = expr.evaluate(scope); 111 | 112 | assertTrue(result instanceof MqlNumberValue); 113 | assertEquals(14, ((MqlNumberValue) result).value()); 114 | } 115 | 116 | @Test 117 | public void testBracketRecursive() { 118 | var source = "((((1))))"; 119 | 120 | var expr = new MqlParser(source).parse(); 121 | 122 | var scopeImpl = new MqlScopeImpl(); 123 | var vars = new MqlScopeImpl.Mutable(); 124 | 125 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 126 | var result = expr.evaluate(scope); 127 | 128 | assertTrue(result instanceof MqlNumberValue); 129 | assertEquals(1, ((MqlNumberValue) result).value()); 130 | } 131 | 132 | @Test 133 | public void testBrackets() { 134 | var source = "(10 + 3) * (3 - 1) - 5 + (1 - 10)"; 135 | 136 | var expr = new MqlParser(source).parse(); 137 | 138 | var scopeImpl = new MqlScopeImpl(); 139 | var vars = new MqlScopeImpl.Mutable(); 140 | 141 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 142 | var result = expr.evaluate(scope); 143 | 144 | assertTrue(result instanceof MqlNumberValue); 145 | assertEquals((10 + 3) * (3 - 1) - 5 + (1 - 10), ((MqlNumberValue) result).value()); 146 | } 147 | 148 | @Test 149 | public void testBracketsNested() { 150 | var source = "((10 + (3)) * (3 - 1)) - 5 + ((2 * 3) - 10) * (10 + (10 * (3 + 3)))"; 151 | 152 | var expr = new MqlParser(source).parse(); 153 | 154 | var scopeImpl = new MqlScopeImpl(); 155 | var vars = new MqlScopeImpl.Mutable(); 156 | 157 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 158 | var result = expr.evaluate(scope); 159 | 160 | assertTrue(result instanceof MqlNumberValue); 161 | assertEquals(((10 + (3)) * (3 - 1)) - 5 + ((2 * 3) - 10) * (10 + (10 * (3 + 3))), ((MqlNumberValue) result).value()); 162 | } 163 | 164 | @Test 165 | public void testParams() { 166 | var source = "math.pow(10, 2)"; 167 | 168 | var expr = new MqlParser(source).parse(); 169 | 170 | var scopeImpl = new MqlScopeImpl(); 171 | var vars = new MqlScopeImpl.Mutable(); 172 | 173 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 174 | var result = expr.evaluate(scope); 175 | 176 | assertTrue(result instanceof MqlNumberValue); 177 | assertEquals(10 * 10, ((MqlNumberValue) result).value()); 178 | } 179 | 180 | @Test 181 | public void testParams2() { 182 | var source = "math.sqrt(4)"; 183 | 184 | var expr = new MqlParser(source).parse(); 185 | 186 | var scopeImpl = new MqlScopeImpl(); 187 | var vars = new MqlScopeImpl.Mutable(); 188 | 189 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 190 | var result = expr.evaluate(scope); 191 | 192 | assertTrue(result instanceof MqlNumberValue); 193 | assertEquals(2, ((MqlNumberValue) result).value()); 194 | } 195 | 196 | @Test 197 | public void testParamsExtended() { 198 | var source = "math.pow(10, 2) + 1"; 199 | 200 | var expr = new MqlParser(source).parse(); 201 | 202 | var scopeImpl = new MqlScopeImpl(); 203 | var vars = new MqlScopeImpl.Mutable(); 204 | 205 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 206 | var result = expr.evaluate(scope); 207 | 208 | assertTrue(result instanceof MqlNumberValue); 209 | assertEquals(10 * 10 + 1, ((MqlNumberValue) result).value()); 210 | } 211 | 212 | @Test 213 | public void testParamsExtended2() { 214 | var source = "math.pow(10 + 1, 2) + 1"; 215 | 216 | var expr = new MqlParser(source).parse(); 217 | 218 | var scopeImpl = new MqlScopeImpl(); 219 | var vars = new MqlScopeImpl.Mutable(); 220 | 221 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 222 | var result = expr.evaluate(scope); 223 | 224 | assertTrue(result instanceof MqlNumberValue); 225 | assertEquals(11 * 11 + 1, ((MqlNumberValue) result).value()); 226 | } 227 | 228 | @Test 229 | public void testParamsNested() { 230 | var source = "math.pow(math.pow(2 + 1, 3), math.pow(3 , 1)) + 1"; 231 | 232 | var expr = new MqlParser(source).parse(); 233 | 234 | var scopeImpl = new MqlScopeImpl(); 235 | var vars = new MqlScopeImpl.Mutable(); 236 | 237 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 238 | var result = expr.evaluate(scope); 239 | 240 | assertTrue(result instanceof MqlNumberValue); 241 | assertEquals(19684, ((MqlNumberValue) result).value()); 242 | } 243 | 244 | @Test 245 | public void testPI() { 246 | var source = "math.pi + 1"; 247 | 248 | var expr = new MqlParser(source).parse(); 249 | var scopeImpl = new MqlScopeImpl(); 250 | var vars = new MqlScopeImpl.Mutable(); 251 | 252 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 253 | 254 | var result = expr.evaluate(scope); 255 | 256 | assertTrue(result instanceof MqlNumberValue); 257 | assertEquals(Math.PI + 1, ((MqlNumberValue) result).value()); 258 | } 259 | 260 | @Test 261 | public void testEqTrue() { 262 | var source = "1 == 1"; 263 | 264 | var expr = new MqlParser(source).parse(); 265 | var scopeImpl = new MqlScopeImpl(); 266 | var vars = new MqlScopeImpl.Mutable(); 267 | 268 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 269 | 270 | var result = expr.evaluate(scope); 271 | 272 | assertTrue(result instanceof MqlNumberValue); 273 | assertEquals(1, ((MqlNumberValue) result).value()); 274 | } 275 | 276 | @Test 277 | public void testEqFalse() { 278 | var source = "1 == 2"; 279 | 280 | var expr = new MqlParser(source).parse(); 281 | 282 | var scopeImpl = new MqlScopeImpl(); 283 | var vars = new MqlScopeImpl.Mutable(); 284 | 285 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 286 | 287 | var result = expr.evaluate(scope); 288 | 289 | assertTrue(result instanceof MqlNumberValue); 290 | assertEquals(0, ((MqlNumberValue) result).value()); 291 | } 292 | 293 | @Test 294 | public void testGteTrue() { 295 | var source = "1 >= 1"; 296 | 297 | var expr = new MqlParser(source).parse(); 298 | var scopeImpl = new MqlScopeImpl(); 299 | var vars = new MqlScopeImpl.Mutable(); 300 | 301 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 302 | 303 | var result = expr.evaluate(scope); 304 | 305 | assertTrue(result instanceof MqlNumberValue); 306 | assertEquals(1, ((MqlNumberValue) result).value()); 307 | } 308 | 309 | @Test 310 | public void testGteFalse() { 311 | var source = "1 >= 2"; 312 | 313 | var expr = new MqlParser(source).parse(); 314 | var scopeImpl = new MqlScopeImpl(); 315 | var vars = new MqlScopeImpl.Mutable(); 316 | 317 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 318 | 319 | var result = expr.evaluate(scope); 320 | 321 | assertTrue(result instanceof MqlNumberValue); 322 | assertEquals(0, ((MqlNumberValue) result).value()); 323 | } 324 | 325 | @Test 326 | public void testGtTrue() { 327 | var source = "2 > 1"; 328 | 329 | var expr = new MqlParser(source).parse(); 330 | var scopeImpl = new MqlScopeImpl(); 331 | var vars = new MqlScopeImpl.Mutable(); 332 | 333 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 334 | 335 | var result = expr.evaluate(scope); 336 | 337 | assertTrue(result instanceof MqlNumberValue); 338 | assertEquals(1, ((MqlNumberValue) result).value()); 339 | } 340 | 341 | @Test 342 | public void testGtFalse() { 343 | var source = "1 > 1"; 344 | 345 | var expr = new MqlParser(source).parse(); 346 | var scopeImpl = new MqlScopeImpl(); 347 | var vars = new MqlScopeImpl.Mutable(); 348 | 349 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 350 | 351 | var result = expr.evaluate(scope); 352 | 353 | assertTrue(result instanceof MqlNumberValue); 354 | assertEquals(0, ((MqlNumberValue) result).value()); 355 | } 356 | 357 | @Test 358 | public void testLteTrue() { 359 | var source = "1 <= 1"; 360 | 361 | var expr = new MqlParser(source).parse(); 362 | var scopeImpl = new MqlScopeImpl(); 363 | var vars = new MqlScopeImpl.Mutable(); 364 | 365 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 366 | 367 | var result = expr.evaluate(scope); 368 | 369 | assertTrue(result instanceof MqlNumberValue); 370 | assertEquals(1, ((MqlNumberValue) result).value()); 371 | } 372 | 373 | @Test 374 | public void testLteFalse() { 375 | var source = "2 <= 1"; 376 | 377 | var expr = new MqlParser(source).parse(); 378 | var scopeImpl = new MqlScopeImpl(); 379 | var vars = new MqlScopeImpl.Mutable(); 380 | 381 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 382 | 383 | var result = expr.evaluate(scope); 384 | 385 | assertTrue(result instanceof MqlNumberValue); 386 | assertEquals(0, ((MqlNumberValue) result).value()); 387 | } 388 | 389 | @Test 390 | public void testLtTrue() { 391 | var source = "1 < 2"; 392 | 393 | var expr = new MqlParser(source).parse(); 394 | var scopeImpl = new MqlScopeImpl(); 395 | var vars = new MqlScopeImpl.Mutable(); 396 | 397 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 398 | 399 | var result = expr.evaluate(scope); 400 | 401 | assertTrue(result instanceof MqlNumberValue); 402 | assertEquals(1, ((MqlNumberValue) result).value()); 403 | } 404 | 405 | @Test 406 | public void testLtFalse() { 407 | var source = "1 < 1"; 408 | 409 | var expr = new MqlParser(source).parse(); 410 | var scopeImpl = new MqlScopeImpl(); 411 | var vars = new MqlScopeImpl.Mutable(); 412 | 413 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 414 | 415 | var result = expr.evaluate(scope); 416 | 417 | assertTrue(result instanceof MqlNumberValue); 418 | assertEquals(0, ((MqlNumberValue) result).value()); 419 | } 420 | 421 | @Test 422 | public void testNeqTrue() { 423 | var source = "1 != 2"; 424 | 425 | var expr = new MqlParser(source).parse(); 426 | var scopeImpl = new MqlScopeImpl(); 427 | var vars = new MqlScopeImpl.Mutable(); 428 | 429 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 430 | 431 | var result = expr.evaluate(scope); 432 | 433 | assertTrue(result instanceof MqlNumberValue); 434 | assertEquals(1, ((MqlNumberValue) result).value()); 435 | } 436 | 437 | @Test 438 | public void testNeqFalse() { 439 | var source = "1 != 1"; 440 | 441 | var expr = new MqlParser(source).parse(); 442 | var scopeImpl = new MqlScopeImpl(); 443 | var vars = new MqlScopeImpl.Mutable(); 444 | 445 | var scope = new MqlScriptScope(scopeImpl, vars, scopeImpl); 446 | 447 | var result = expr.evaluate(scope); 448 | 449 | assertTrue(result instanceof MqlNumberValue); 450 | assertEquals(0, ((MqlNumberValue) result).value()); 451 | } 452 | } 453 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/foreign/TestMqlForeignFunctions.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.foreign; 2 | 3 | import net.hollowcube.mql.tree.MqlNumberExpr; 4 | import net.hollowcube.mql.value.MqlCallable; 5 | import net.hollowcube.mql.value.MqlValue; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.lang.reflect.Method; 9 | import java.util.List; 10 | import java.util.concurrent.atomic.AtomicBoolean; 11 | import java.util.concurrent.atomic.AtomicReference; 12 | 13 | import static org.junit.jupiter.api.Assertions.assertEquals; 14 | import static org.junit.jupiter.api.Assertions.assertTrue; 15 | 16 | public class TestMqlForeignFunctions { 17 | 18 | private static final AtomicBoolean test1Called = new AtomicBoolean(false); 19 | 20 | public static void test1() { 21 | test1Called.set(true); 22 | } 23 | 24 | @Test 25 | public void emptyVoidFunction() throws Exception { 26 | Method method = getClass().getMethod("test1"); 27 | MqlCallable function = MqlForeignFunctions.createForeign(method, null); 28 | assertEquals(0, function.arity()); 29 | assertEquals(MqlValue.NULL, function.call(List.of(), null)); 30 | assertTrue(test1Called.get()); 31 | } 32 | 33 | private static final AtomicReference test2Value = new AtomicReference<>(0.0); 34 | 35 | public static void test2(double value) { 36 | test2Value.set(value); 37 | } 38 | 39 | @Test 40 | public void singleArgVoidFunction() throws Exception { 41 | Method method = getClass().getMethod("test2", double.class); 42 | MqlCallable function = MqlForeignFunctions.createForeign(method, null); 43 | MqlValue result = function.call(List.of(new MqlNumberExpr(10.5)), null); 44 | 45 | assertEquals(1, function.arity()); 46 | assertEquals(MqlValue.NULL, result); 47 | assertEquals(10.5, test2Value.get()); 48 | } 49 | 50 | public static double test3() { 51 | return 10.5; 52 | } 53 | 54 | @Test 55 | public void emptyNonVoidFunction() throws Exception { 56 | Method method = getClass().getMethod("test3"); 57 | MqlCallable function = MqlForeignFunctions.createForeign(method, null); 58 | MqlValue result = function.call(List.of(), null); 59 | 60 | assertEquals(0, function.arity()); 61 | assertEquals(MqlValue.from(10.5), result); 62 | } 63 | 64 | public static double test4(double a, double b) { 65 | return a + b; 66 | } 67 | 68 | @Test 69 | public void multiParamNonVoidFunction() throws Exception { 70 | Method method = getClass().getMethod("test4", double.class, double.class); 71 | MqlCallable function = MqlForeignFunctions.createForeign(method, null); 72 | MqlValue result = function.call(List.of(new MqlNumberExpr(10.5), new MqlNumberExpr(20.5)), null); 73 | 74 | assertEquals(2, function.arity()); 75 | assertEquals(MqlValue.from(31), result); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/jit/BaseScript.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | public interface BaseScript { 4 | double evaluate(); 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/jit/QueryScript.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | public interface QueryScript { 4 | double evaluate(@MqlEnv({"query", "q"}) QueryTest query); 5 | } 6 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/jit/QueryTest.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | import net.hollowcube.mql.foreign.Query; 4 | 5 | public class QueryTest { 6 | 7 | @Query 8 | public double dbl(double value) { 9 | return value * 2; 10 | } 11 | 12 | @Query 13 | public double mul(double a, double b) { 14 | return a * b; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/jit/TestCompilation.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.lang.invoke.MethodHandles; 7 | 8 | import static org.junit.jupiter.api.Assertions.assertEquals; 9 | 10 | public class TestCompilation { 11 | 12 | @Test 13 | public void singleNumber() { 14 | check(BaseScript.class, "0", """ 15 | DCONST_0 16 | DRETURN 17 | """); 18 | check(BaseScript.class, "1", """ 19 | DCONST_1 20 | DRETURN 21 | """); 22 | check(BaseScript.class, "1.234", """ 23 | LDC 1.234 24 | DRETURN 25 | """); 26 | } 27 | 28 | @Test 29 | public void simpleAddition() { 30 | check(BaseScript.class, "1 + 1", """ 31 | DCONST_1 32 | DCONST_1 33 | DADD 34 | DRETURN 35 | """); 36 | } 37 | 38 | @Test 39 | public void callQuerySingleArg() { 40 | check(QueryScript.class, "q.dbl(1.0)", """ 41 | ALOAD 1 42 | DCONST_1 43 | INVOKEVIRTUAL net/hollowcube/mql/jit/QueryTest.dbl (D)D 44 | DRETURN 45 | """); 46 | } 47 | 48 | @Test 49 | public void callQueryMultiArg() { 50 | check(QueryScript.class, "q.mul(1.0, 2.0)", """ 51 | ALOAD 1 52 | DCONST_1 53 | LDC 2.0 54 | INVOKEVIRTUAL net/hollowcube/mql/jit/QueryTest.mul (DD)D 55 | DRETURN 56 | """); 57 | } 58 | 59 | @Test 60 | public void callQueryInnerCall() { 61 | check(QueryScript.class, "q.mul(2.0, q.dbl(2.0))", """ 62 | ALOAD 1 63 | LDC 2.0 64 | ALOAD 1 65 | LDC 2.0 66 | INVOKEVIRTUAL net/hollowcube/mql/jit/QueryTest.dbl (D)D 67 | INVOKEVIRTUAL net/hollowcube/mql/jit/QueryTest.mul (DD)D 68 | DRETURN 69 | """); 70 | } 71 | 72 | private void check(@NotNull Class script, @NotNull String source, @NotNull String expected) { 73 | var compiler = new MqlCompiler<>(MethodHandles.lookup(), script); 74 | byte[] bytecode = compiler.compileBytecode("mql$test", source); 75 | 76 | var str = AsmUtil.prettyPrintEvalMethod(bytecode); 77 | assertEquals(expected, str); 78 | } 79 | } -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/jit/TestExecution.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | import org.jetbrains.annotations.NotNull; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.lang.invoke.MethodHandles; 7 | 8 | import static org.junit.jupiter.api.Assertions.assertEquals; 9 | 10 | public class TestExecution { 11 | 12 | @Test 13 | public void singleNumber() { 14 | var script = compile(BaseScript.class, "0"); 15 | assertEquals(0, script.evaluate()); 16 | } 17 | 18 | @Test 19 | public void simpleAddition() { 20 | var script = compile(BaseScript.class, "1+1"); 21 | assertEquals(2, script.evaluate()); 22 | } 23 | 24 | @Test 25 | public void simpleQueryCall() { 26 | var script = compile(QueryScript.class, "q.dbl(2.0)"); 27 | assertEquals(4, script.evaluate(new QueryTest())); 28 | } 29 | 30 | @Test 31 | public void ternarySimple() { 32 | var script = compile(BaseScript.class, "1.0 ? 2.0 : 3.0"); 33 | assertEquals(2, script.evaluate()); 34 | } 35 | 36 | @Test 37 | public void gte() { 38 | var script = compile(BaseScript.class, "1.0 >= 2.0"); 39 | assertEquals(0, script.evaluate()); 40 | } 41 | 42 | @Test 43 | public void math() { 44 | var script = compile(BaseScript.class, "math.abs(-100)"); 45 | assertEquals(100, script.evaluate()); 46 | } 47 | 48 | private T compile(@NotNull Class scriptInterface, @NotNull String source) { 49 | var compiler = new MqlCompiler<>(MethodHandles.lookup(), scriptInterface); 50 | Class scriptClass = compiler.compile(source); 51 | 52 | try { 53 | return scriptClass.newInstance(); 54 | } catch (InstantiationException | IllegalAccessException e) { 55 | throw new RuntimeException(e); 56 | } 57 | } 58 | } -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/jit/TestRegression.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.jit; 2 | 3 | import net.hollowcube.mql.foreign.Query; 4 | import net.hollowcube.mql.parser.MqlParser; 5 | import net.hollowcube.mql.util.MqlPrinter; 6 | import org.jetbrains.annotations.NotNull; 7 | import org.junit.jupiter.api.Test; 8 | 9 | import java.lang.invoke.MethodHandles; 10 | 11 | import static org.junit.jupiter.api.Assertions.assertEquals; 12 | 13 | public class TestRegression { 14 | 15 | @Test 16 | public void clampParse() { 17 | parse("math.clamp(1, 10, 20)", "(? (. math clamp) (1.0 10.0 20.0))"); 18 | } 19 | 20 | @Test 21 | public void mathAndClampParse() { 22 | parse("1 + math.clamp(1, 10, 20)", "(+ 1.0 (? (. math clamp) (1.0 10.0 20.0)))"); 23 | } 24 | 25 | @Test 26 | public void mathAndClampCompile() { 27 | compile(BaseScript.class, "1 + 1 + math.clamp(1, 10, 20)", """ 28 | DCONST_1 29 | DCONST_1 30 | DADD 31 | DCONST_1 32 | LDC 10.0 33 | LDC 20.0 34 | INVOKESTATIC net/hollowcube/mql/runtime/MqlMath.clamp (DDD)D 35 | DADD 36 | DRETURN 37 | """); 38 | } 39 | 40 | @Test 41 | public void mathAndClampExec() { 42 | var script = execute(BaseScript.class, "1 + 1 + math.clamp(1, 10, 20)"); 43 | assertEquals(12, script.evaluate()); 44 | } 45 | 46 | public static class TestClass { 47 | @Query 48 | public double variable() { 49 | return 12; 50 | } 51 | } 52 | 53 | @FunctionalInterface 54 | public interface TestScript { 55 | double evaluate(@MqlEnv({"variable", "v"}) TestClass emitter); 56 | } 57 | 58 | @Test 59 | public void variableVariableParse() { 60 | parse("variable.variable", "(. variable variable)"); 61 | } 62 | 63 | @Test 64 | public void variableVariable() { 65 | var script = execute(TestScript.class, "variable.variable"); 66 | assertEquals(12, script.evaluate(new TestClass())); 67 | } 68 | 69 | @Test 70 | public void sameScriptTwice() { 71 | var script = execute(TestScript.class, "variable.variable + 1"); 72 | assertEquals(13, script.evaluate(new TestClass())); 73 | script = execute(TestScript.class, "variable.variable + 1"); 74 | assertEquals(13, script.evaluate(new TestClass())); 75 | } 76 | 77 | 78 | private void parse(String input, String expected) { 79 | var expr = new MqlParser(input).parse(); 80 | var actual = new MqlPrinter().visit(expr, null); 81 | 82 | assertEquals(expected, actual); 83 | } 84 | 85 | private void compile(@NotNull Class script, @NotNull String source, @NotNull String expected) { 86 | var compiler = new MqlCompiler<>(MethodHandles.lookup(), script); 87 | byte[] bytecode = compiler.compileBytecode("mql$test", source); 88 | 89 | var str = AsmUtil.prettyPrintEvalMethod(bytecode); 90 | assertEquals(expected, str); 91 | } 92 | 93 | private T execute(@NotNull Class scriptInterface, @NotNull String source) { 94 | var compiler = new MqlCompiler<>(MethodHandles.lookup(), scriptInterface); 95 | Class scriptClass = compiler.compile(source); 96 | 97 | try { 98 | return scriptClass.newInstance(); 99 | } catch (InstantiationException | IllegalAccessException e) { 100 | throw new RuntimeException(e); 101 | } 102 | } 103 | } -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/parser/TestMqlLexer.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.parser; 2 | 3 | import org.junit.jupiter.params.ParameterizedTest; 4 | import org.junit.jupiter.params.provider.Arguments; 5 | import org.junit.jupiter.params.provider.MethodSource; 6 | 7 | import java.util.stream.Stream; 8 | 9 | import static org.junit.jupiter.api.Assertions.*; 10 | 11 | public class TestMqlLexer { 12 | 13 | @ParameterizedTest 14 | @MethodSource("individualSymbols") 15 | public void testIndividualSymbols(String input, MqlToken.Type expected) { 16 | var lexer = new MqlLexer(input); 17 | 18 | var token = lexer.next(); 19 | assertNotNull(token); 20 | assertEquals(expected, token.type()); 21 | 22 | var eof = lexer.next(); 23 | assertNull(eof); 24 | } 25 | 26 | private static Stream individualSymbols() { 27 | return Stream.of( 28 | Arguments.of("+", MqlToken.Type.PLUS), 29 | Arguments.of("-", MqlToken.Type.MINUS), 30 | Arguments.of("*", MqlToken.Type.STAR), 31 | Arguments.of("/", MqlToken.Type.SLASH), 32 | Arguments.of(".", MqlToken.Type.DOT), 33 | Arguments.of(",", MqlToken.Type.COMMA), 34 | Arguments.of("?", MqlToken.Type.QUESTION), 35 | Arguments.of("??", MqlToken.Type.QUESTIONQUESTION), 36 | Arguments.of("(", MqlToken.Type.LPAREN), 37 | Arguments.of(")", MqlToken.Type.RPAREN), 38 | 39 | Arguments.of("123", MqlToken.Type.NUMBER), 40 | Arguments.of("123.", MqlToken.Type.NUMBER), 41 | Arguments.of("123.456", MqlToken.Type.NUMBER), 42 | 43 | Arguments.of("abc", MqlToken.Type.IDENT), 44 | Arguments.of("aBc", MqlToken.Type.IDENT), 45 | Arguments.of("aBc1", MqlToken.Type.IDENT) 46 | ); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/parser/TestMqlParser.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.parser; 2 | 3 | import net.hollowcube.mql.util.MqlPrinter; 4 | import org.junit.jupiter.params.ParameterizedTest; 5 | import org.junit.jupiter.params.provider.Arguments; 6 | import org.junit.jupiter.params.provider.MethodSource; 7 | 8 | import java.util.stream.Stream; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertEquals; 11 | 12 | public class TestMqlParser { 13 | 14 | @MethodSource("inputPairs") 15 | @ParameterizedTest(name = "{0}") 16 | public void testInputPairs(String name, String input, String expected) { 17 | var expr = new MqlParser(input).parse(); 18 | var actual = new MqlPrinter().visit(expr, null); 19 | 20 | assertEquals(expected, actual); 21 | } 22 | 23 | private static Stream inputPairs() { 24 | return Stream.of( 25 | Arguments.of("basic number", 26 | "1", "1.0"), 27 | Arguments.of("basic ref", 28 | "abc", "abc"), 29 | Arguments.of("basic add", 30 | "1 + 2", "(+ 1.0 2.0)"), 31 | Arguments.of("nested add", 32 | "1 + 2 + 3", "(+ (+ 1.0 2.0) 3.0)"), 33 | Arguments.of("negate simple", 34 | "-1", "(- 1.0)"), 35 | Arguments.of("negate nested", 36 | "---1", "(- (- (- 1.0)))"), 37 | Arguments.of("negate precedence", 38 | "-2 + 1", "(+ (- 2.0) 1.0)"), 39 | Arguments.of("basic access", 40 | "a.b", "(. a b)"), 41 | Arguments.of("access/add precedence", 42 | "a.b + 1", "(+ (. a b) 1.0)"), 43 | Arguments.of("null coalesce precedence", 44 | "a.b ?? 1", "(?? (. a b) 1.0)"), 45 | Arguments.of("null coalesce precedence 2", 46 | "1 + 2 ?? 1", "(?? (+ 1.0 2.0) 1.0)"), //todo is this correct? should it be (+ 1.0 (?? 2.0 1.0))? 47 | Arguments.of("normalize case 1", 48 | "q.is_alive()", "(. q is_alive)"), 49 | Arguments.of("normalize case 2", 50 | "q.is_alive", "(. q is_alive)"), 51 | Arguments.of("single ternary simple", 52 | "1 ? 2 : 3", "(? 1.0 2.0 3.0)"), 53 | Arguments.of("nested ternary", 54 | "1 ? 2 : 3 ? 4 : 5", "(? 1.0 2.0 (? 3.0 4.0 5.0))"), 55 | Arguments.of("ternary add precedence", 56 | "1 ? 2 + 3 : 4", "(? 1.0 (+ 2.0 3.0) 4.0)") 57 | ); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/net/hollowcube/mql/runtime/TestMqlMath.java: -------------------------------------------------------------------------------- 1 | package net.hollowcube.mql.runtime; 2 | 3 | import net.hollowcube.mql.tree.MqlNumberExpr; 4 | import net.hollowcube.mql.value.MqlCallable; 5 | import net.hollowcube.mql.value.MqlValue; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.util.List; 9 | 10 | import static org.junit.jupiter.api.Assertions.assertEquals; 11 | 12 | public class TestMqlMath { 13 | 14 | @Test 15 | public void testForeignMath() { 16 | MqlValue result = MqlMath.INSTANCE.get("sqrt").cast(MqlCallable.class) 17 | .call(List.of(new MqlNumberExpr(4)), null); 18 | 19 | assertEquals(MqlValue.from(2), result); 20 | } 21 | 22 | // hermiteBlend 23 | // lerp 24 | // lerprotate 25 | 26 | } 27 | --------------------------------------------------------------------------------