diff --git a/build.gradle.kts b/build.gradle.kts index c7fee8e..61d879a 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -26,15 +26,16 @@ val neoforge: SourceSet by sourceSets.creating { dependencies { implementation("org.jetbrains:annotations:24.1.0") implementation("com.google.code.gson:gson:2.10") - + implementation("it.unimi.dsi:fastutil:8.5.16") + testImplementation("org.java-websocket:Java-WebSocket:1.6.0") "fabricImplementation"("net.fabricmc:fabric-loader:0.15.0") { isTransitive = false} "neoforgeImplementation"("net.neoforged.fancymodloader:loader:3.0.13") { isTransitive = false} } java { - sourceCompatibility = JavaVersion.VERSION_21 - targetCompatibility = JavaVersion.VERSION_21 + sourceCompatibility = JavaVersion.VERSION_25 + targetCompatibility = JavaVersion.VERSION_25 } tasks.jar { @@ -42,6 +43,10 @@ tasks.jar { from(neoforge.output) } +tasks.withType().forEach { + it.options.compilerArgs.add("--enable-preview") +} + tasks.register("sourcesJar") { group = "build" archiveClassifier.set("sources") @@ -52,6 +57,7 @@ tasks.register("sourcesJar") { val baseUrl = "https://raw.githubusercontent.com/SkyblockAPI/Repo/refs/heads/main/cloudflare" +/* val downloadRepo = tasks.create("downloadRepo") { val outDir = layout.buildDirectory.dir("backup_repo") val outDirPath = outDir.get().asFile.toPath().resolve("backup") @@ -98,7 +104,7 @@ sourceSets.main.configure { tasks.build.configure { this.dependsOn(downloadRepo) this.mustRunAfter(downloadRepo) -} +}*/ publishing { publications { diff --git a/data.jsonc b/data.jsonc new file mode 100644 index 0000000..be37f90 --- /dev/null +++ b/data.jsonc @@ -0,0 +1,3 @@ +{ + "modifier": "gilded" +} diff --git a/gradle.properties b/gradle.properties index c37a224..0d46059 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,2 +1,2 @@ group=tech.thatgravyboat.repo-lib -version=4.1.11 \ No newline at end of file +version=4.1.11 diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 19a6bde..11c44cc 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.0-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip networkTimeout=10000 -validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/src/main/java/tech/thatgravyboat/repolib/api/AttributesAPI.java b/src/main/java/tech/thatgravyboat/repolib/api/AttributesAPI.java index d7758d9..6344ef6 100644 --- a/src/main/java/tech/thatgravyboat/repolib/api/AttributesAPI.java +++ b/src/main/java/tech/thatgravyboat/repolib/api/AttributesAPI.java @@ -63,7 +63,7 @@ public static Attribute fromJson(JsonObject jsonObject) { jsonObject.get("attribute_id").getAsString(), jsonObject.get("shard_name").getAsString(), jsonObject.get("shard_id").getAsString(), - jsonObject.get("name").getAsString(), + jsonObject.get("names").getAsString(), jsonObject.get("item").getAsString(), Optional.ofNullable(jsonObject.get("texture")).map(JsonElement::getAsString).orElse(null), jsonObject.get("rarity").getAsString(), diff --git a/src/main/java/tech/thatgravyboat/repolib/api/EnchantsAPI.java b/src/main/java/tech/thatgravyboat/repolib/api/EnchantsAPI.java index 96f31eb..4780267 100644 --- a/src/main/java/tech/thatgravyboat/repolib/api/EnchantsAPI.java +++ b/src/main/java/tech/thatgravyboat/repolib/api/EnchantsAPI.java @@ -52,7 +52,7 @@ public static Enchant fromJson(JsonObject object) { try { return new Enchant( object.get("id").getAsString(), - object.get("name").getAsString(), + object.get("names").getAsString(), object.get("isUltimate").getAsBoolean(), object.getAsJsonArray("levels") .asList() diff --git a/src/main/java/tech/thatgravyboat/repolib/api/MobsAPI.java b/src/main/java/tech/thatgravyboat/repolib/api/MobsAPI.java index 1d4307f..f88cae0 100644 --- a/src/main/java/tech/thatgravyboat/repolib/api/MobsAPI.java +++ b/src/main/java/tech/thatgravyboat/repolib/api/MobsAPI.java @@ -32,7 +32,7 @@ void load(JsonElement json) { mobObject.has("position") ? Position.fromJson(mobObject.getAsJsonObject("position")) : null, JsonHelper.getStringOrNull(mobObject, "texture"), mobObject.get("itemId").getAsString(), - mobObject.get("name").getAsString(), + mobObject.get("names").getAsString(), JsonHelper.getStringOrNull(mobObject, "type"), mobObject.has("lootTables") ? mobObject.getAsJsonArray("lootTables") @@ -51,7 +51,7 @@ void load(JsonElement json) { private static LootTable loadLootTable(JsonObject json) { return new LootTable( - json.get("name").getAsString(), + json.get("names").getAsString(), JsonHelper.getInt(json, "mobLevel", 0), JsonHelper.getInt(json, "xp", 0), JsonHelper.getInt(json, "combatXp", 0), diff --git a/src/main/java/tech/thatgravyboat/repolib/api/PetsAPI.java b/src/main/java/tech/thatgravyboat/repolib/api/PetsAPI.java index 9d330a0..48ae6ed 100644 --- a/src/main/java/tech/thatgravyboat/repolib/api/PetsAPI.java +++ b/src/main/java/tech/thatgravyboat/repolib/api/PetsAPI.java @@ -91,7 +91,7 @@ public record Data( private static Data fromJson(JsonObject json) { JsonObject tiers = json.get("tiers").getAsJsonObject(); return new Data( - json.get("name").getAsString(), + json.get("names").getAsString(), tiers.entrySet() .stream() .collect(Collectors.toMap( diff --git a/src/main/java/tech/thatgravyboat/repolib/api/PotionsAPI.java b/src/main/java/tech/thatgravyboat/repolib/api/PotionsAPI.java index 5e40ce0..be16cbf 100644 --- a/src/main/java/tech/thatgravyboat/repolib/api/PotionsAPI.java +++ b/src/main/java/tech/thatgravyboat/repolib/api/PotionsAPI.java @@ -64,7 +64,7 @@ public static Potion fromJson(String id, JsonObject object) { .map(JsonElement::getAsJsonObject) .map(PotionLevel::fromJson) .collect(Collectors.toMap(PotionLevel::level, Function.identity())), - object.get("name").getAsString(), + object.get("names").getAsString(), JsonHelper.getString(object, "type", null), JsonHelper.getString(object, "internal_potion", null), object.get("vanilla_effect").getAsString() diff --git a/src/main/java/tech/thatgravyboat/repolib/api/RunesAPI.java b/src/main/java/tech/thatgravyboat/repolib/api/RunesAPI.java index 5d0944d..d113491 100644 --- a/src/main/java/tech/thatgravyboat/repolib/api/RunesAPI.java +++ b/src/main/java/tech/thatgravyboat/repolib/api/RunesAPI.java @@ -52,7 +52,7 @@ static Rune fromJson(String id, JsonObject json) { id, json.get("tier").getAsInt(), json.get("texture").getAsString(), - json.get("name").getAsString(), + json.get("names").getAsString(), json.getAsJsonArray("lore").asList() .stream() .map(JsonElement::getAsString) diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/BundleLoader.java b/src/main/java/tech/thatgravyboat/repolib/v2/BundleLoader.java new file mode 100644 index 0000000..c6448dd --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/BundleLoader.java @@ -0,0 +1,136 @@ +package tech.thatgravyboat.repolib.v2; + +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import tech.thatgravyboat.repolib.v2.binary.ByteBufferImpl; +import tech.thatgravyboat.repolib.v2.binary.DecoderContext; +import tech.thatgravyboat.repolib.v2.binary.NameTable; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.FunctionValueFile; +import tech.thatgravyboat.repolib.v2.expl.ModuleFile; +import tech.thatgravyboat.repolib.v2.expl.StackFile; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.LayeredStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; + +import java.io.BufferedInputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.zip.GZIPInputStream; + +import static tech.thatgravyboat.repolib.v2.binary.RepoBinaryUtils.BINARY_VERSION; +import static tech.thatgravyboat.repolib.v2.binary.RepoBinaryUtils.MAGIC_NUMBER; + +public class BundleLoader implements RepoLoader { + + private final Path path; + private Map> modules = new HashMap<>(); + private Map stackFiles = new HashMap<>(); + private ModuleFile rootFile = null; + private Expression rootList = null; + private final RepoConstants constants = new RepoConstants(this); + + public BundleLoader(Path bundle) { + this.path = bundle; + } + + @Override + public List load() throws IOException { + + var inputStream = Files.newInputStream(this.path); + try (inputStream; var gzipInputStream = new GZIPInputStream(new BufferedInputStream(inputStream))) { + var buffer = new ByteBufferImpl(gzipInputStream); + if (buffer.readByte() != MAGIC_NUMBER[0] || buffer.readByte() != MAGIC_NUMBER[1] || buffer.readByte() != MAGIC_NUMBER[2]) { + throw new UnsupportedOperationException("Can't decode non repo bundle!"); + } + var fileVersion = buffer.readShort(); + if (fileVersion != BINARY_VERSION) { + if (fileVersion < BINARY_VERSION) { + throw new UnsupportedOperationException("File was compiled by an older version!"); + } + throw new UnsupportedOperationException("File was compiled by a newer version!"); + } + + var context = new DecoderContext(buffer); + context.updateTable(NameTable.CODEC.decode(context).freezeForDecode()); + + var bundle = RepoBundle.CODEC.decode(context); + + this.modules = bundle.modules(); + this.stackFiles = bundle.stackFiles(); + this.rootList = bundle.rootList(); + this.rootFile = bundle.rootFile(); + } + return List.of(); + } + + @Override + public Map> files() { + return this.modules; + } + + @Override + public ModuleFile rootFile() { + return this.rootFile; + } + + @Override + public Expression rootList() { + return this.rootList; + } + + @Override + public Map stackFiles() { + return this.stackFiles; + } + + @Override + public RepoInstance create() { + return new RepoInstance(this, constants, new RepoListConstants(constants, this)); + } + + @Override + public StackFile stackFile(String name) { + StackFile stackFile = stackFiles.get(name); + if (stackFile != null && stackFile.needsInitialization()) { + stackFile.init(this, constants); + } + return stackFile; + } + + @Override + public FunctionValue module(String name) { + FunctionValue module = modules.get(name); + if (module != null && module.needsInitialization()) { + module.initialize(createEvaluator()); + } + return module; + } + + @Override + public Collection modules() { + return this.modules.keySet(); + } + + @Override + public RepoBundle bundle() { + return new RepoBundle( + this.rootFile, + this.rootList, + this.stackFiles, + this.modules + ); + } + + public Evaluator createEvaluator() { + return new Evaluator(new LayeredStructValue( + new MutableStructValue(), + constants + ), this::module); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/FolderLoader.java b/src/main/java/tech/thatgravyboat/repolib/v2/FolderLoader.java new file mode 100644 index 0000000..afa4dea --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/FolderLoader.java @@ -0,0 +1,211 @@ +package tech.thatgravyboat.repolib.v2; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import tech.thatgravyboat.repolib.v2.binary.RepoBinaryUtils; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.FunctionValueFile; +import tech.thatgravyboat.repolib.v2.expl.ModuleFile; +import tech.thatgravyboat.repolib.v2.expl.StackFile; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.LayeredStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.*; + +public class FolderLoader implements FileVisitor, RepoLoader { + + public final Path path; + private final Map> files = new HashMap<>(); + private Expression rootList = null; + private ModuleFile rootFile = null; + private final Map stackFiles = new HashMap<>(); + private final List errors = new ArrayList<>(); + private final RepoConstants constants = new RepoConstants(this); + + public FolderLoader(Path path) { + this.path = path; + } + + public List load() throws IOException { + files.clear(); + stackFiles.clear(); + rootList = null; + rootFile = null; + + errors.clear(); + Files.walkFileTree(path, this); + + var constants = new RepoConstants(this); + + System.out.println("meow!"); + + for (var entry : this.stackFiles.values()) { + entry.init(this, constants); + } + + Path root = path.resolve("root.srlm"); + if (Files.isRegularFile(root) && Files.exists(root)) { + String file = Files.readString(root, StandardCharsets.UTF_8); + + var rootFile = Expression.parseModuleOrThrow( + this, + "root", + file + ); + this.files.put("root", rootFile); + this.rootFile = rootFile; + } + + if (rootList == null) { + errors.add(new LoadingErrors(path, "No root list file found.")); + } + if (rootFile == null) { + errors.add(new LoadingErrors(path, "No root module file found.")); + } + + return errors; + } + + public Evaluator createEvaluator() { + return new Evaluator(new LayeredStructValue( + new MutableStructValue(), + constants + ), this::module); + } + + public Collection modules() { + return files.keySet(); + } + + public FunctionValue module(String name) { + FunctionValue module = files.get(name); + if (module != null && module.needsInitialization()) { + module.initialize(createEvaluator()); + } + return module; + } + + public StackFile stackFile(String fileName) { + StackFile stackFile = stackFiles.get(fileName); + if (stackFile != null && stackFile.needsInitialization()) { + stackFile.init(this, constants); + } + return stackFile; + } + + public Map stackFiles() { + return stackFiles; + } + + public Expression rootList() { + return rootList; + } + + public ModuleFile rootFile() { + return rootFile; + } + + public RepoInstance create() { + var repoConstants = new RepoConstants(this); + return new RepoInstance(this, repoConstants, new RepoListConstants(repoConstants, this)); + } + + private static String unescape(String encoded) { + return encoded + .replace("<", "<") + .replace("&do;", ".") + .replace(">", ">") + .replace("&cl;", ":") + .replace("&dq;", "\"") + .replace("&fs;", "/") + .replace("&bs;", "\\") + .replace("π", "|") + .replace("&qu;", "?") + .replace("&as;", "*") + .replace("&an;", "&"); + } + + @Override + public @NotNull FileVisitResult preVisitDirectory( + Path dir, + @NotNull BasicFileAttributes attrs + ) throws IOException { + if (Files.isHidden(dir) || dir.getFileName().toString().startsWith(".")) return FileVisitResult.SKIP_SUBTREE; + return FileVisitResult.CONTINUE; + } + + @Override + public @NotNull FileVisitResult visitFile(Path file, @NotNull BasicFileAttributes attrs) { + if (file.getFileName().toString().startsWith(".")) return FileVisitResult.CONTINUE; + + try { + var relativeFileName = FolderLoader.this.path.relativize(file).toString().replace("\\", "/"); + if (relativeFileName.lastIndexOf('.') == -1) return FileVisitResult.CONTINUE; + var relativeName = unescape(relativeFileName.substring(0, relativeFileName.lastIndexOf('.'))); + + var content = Files.readString(file, StandardCharsets.UTF_8); + if (relativeFileName.endsWith(".srls")) { + var expression = Expression.parseFileOrThrow(this, content, relativeName); + stackFiles.put(relativeName, expression); + } else if (relativeFileName.equals("root.srlm")) { + return FileVisitResult.CONTINUE; + } else if (relativeFileName.endsWith(".srlm")) { + var expression = Expression.parseModuleOrThrow(this, relativeName, content); + files.put(relativeName, expression); + } else if (relativeFileName.endsWith(".srlf")) { + var expression = Expression.parseFunctionOrThrow(this, relativeName, content); + files.put(relativeName, expression); + } else if (relativeFileName.equals("root.srll")) { + rootList = Expression.parse(content); + } + } catch (Exception exception) { + errors.add(new LoadingErrors(file, exception)); + } + + return FileVisitResult.CONTINUE; + } + + @Override + public @NotNull FileVisitResult visitFileFailed(Path file, @NotNull IOException exc) { + return FileVisitResult.CONTINUE; + } + + @Override + public @NotNull FileVisitResult postVisitDirectory(Path dir, @Nullable IOException exc) { + return FileVisitResult.CONTINUE; + } + + public byte[] buildRepoBundle() { + try (var stream = new ByteArrayOutputStream()) { + RepoBinaryUtils.bundle(stream, this); + return stream.toByteArray(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + + @Override + public RepoBundle bundle() { + return new RepoBundle( + this.rootFile, + this.rootList, + this.stackFiles, + this.files + ); + } + + public Map> files() { + return files; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/LoadingErrors.java b/src/main/java/tech/thatgravyboat/repolib/v2/LoadingErrors.java new file mode 100644 index 0000000..81601d0 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/LoadingErrors.java @@ -0,0 +1,9 @@ +package tech.thatgravyboat.repolib.v2; + +import java.nio.file.Path; + +public record LoadingErrors(Path file, Throwable reason) { + public LoadingErrors(Path file, String reason) { + this(file, new RuntimeException(reason)); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/RepoBundle.java b/src/main/java/tech/thatgravyboat/repolib/v2/RepoBundle.java new file mode 100644 index 0000000..42821c0 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/RepoBundle.java @@ -0,0 +1,20 @@ +package tech.thatgravyboat.repolib.v2; + +import java.util.Map; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryFileTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.expl.FunctionValueFile; +import tech.thatgravyboat.repolib.v2.expl.ModuleFile; +import tech.thatgravyboat.repolib.v2.expl.StackFile; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; + +public record RepoBundle(ModuleFile rootFile, Expression rootList, Map stackFiles, Map> modules) { + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + ModuleFile.CODEC.nullable().forGetter(RepoBundle::rootFile), + BinaryCodec.EXPRESSION.nullable().forGetter(RepoBundle::rootList), + BinaryCodec.map(BinaryCodec.STRING, StackFile.CODEC).forGetter(RepoBundle::stackFiles), + BinaryCodec.map(BinaryCodec.STRING, BinaryFileTypeRegistry.FUNCTION_FILE).forGetter(RepoBundle::modules), + RepoBundle::new + ); +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/RepoConfig.java b/src/main/java/tech/thatgravyboat/repolib/v2/RepoConfig.java new file mode 100644 index 0000000..935c692 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/RepoConfig.java @@ -0,0 +1,57 @@ +package tech.thatgravyboat.repolib.v2; + +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.NilValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +import java.util.Map; +import java.util.Set; + +public class RepoConfig implements KeyValue { + + private boolean romanNumerals = true; + + public static final RepoConfig DEFAULT = new RepoConfig(); + + public RepoConfig() { + } + + @Override + public Value get(String field) { + return switch (field) { + case "roman_numerals" -> BoolValue.wrap(romanNumerals); + default -> NIL; + }; + } + + @Override + public Set keySet() { + return Set.of("roman_numerals"); + } + + @Override + public Map sourceMap() { + return Map.of("roman_numerals", this); + } + + public RepoConfig withRomanNumerals(boolean romanNumerals) { + this.romanNumerals = romanNumerals; + return this; + } + + @Override + public Mutable toMutable() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean contains(String field) { + return !(get(field) instanceof NilValue); + } + + @Override + public boolean isEmpty() { + return false; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/RepoConstants.java b/src/main/java/tech/thatgravyboat/repolib/v2/RepoConstants.java new file mode 100644 index 0000000..b287386 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/RepoConstants.java @@ -0,0 +1,146 @@ +package tech.thatgravyboat.repolib.v2; + +import tech.thatgravyboat.repolib.v2.builtin.BuiltinArray; +import tech.thatgravyboat.repolib.v2.builtin.BuiltinBoolean; +import tech.thatgravyboat.repolib.v2.builtin.BuiltinComponent; +import tech.thatgravyboat.repolib.v2.builtin.BuiltinMath; +import tech.thatgravyboat.repolib.v2.builtin.BuiltinObjects; +import tech.thatgravyboat.repolib.v2.builtin.BuiltinRarities; +import tech.thatgravyboat.repolib.v2.builtin.BuiltinString; +import tech.thatgravyboat.repolib.v2.builtin.Constants; +import tech.thatgravyboat.repolib.v2.expl.ModuleFile; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public final class RepoConstants implements StructValue.Forwarding { + private RepoLoader loader; + private final Constants constants = new Constants((builder) -> { + builder.field("Math", BuiltinMath.MATH); + builder.field("Objects", BuiltinObjects.OBJECTS); + builder.field("Rarity", BuiltinRarities.RARITY); + builder.field("String", BuiltinString.STRING); + builder.field("Boolean", BuiltinBoolean.BOOLEAN); + builder.field("Component", BuiltinComponent.COMPONENT); + builder.field("Array", BuiltinArray.ARRAY); + + + builder.function("include", function -> { + function.arity(1, 2); + function.vararg(true); + function.execute((evaluator, args) -> { + var value = args.getFirst().asString(); + var requested = loader.module(value); + if (requested == null) { + return evaluator.panic("Requested include " + value + " doesn't exist!"); + } + + if (args.size() == 2) { + var scope = args.get(1).asMutableStruct(); + return evaluator.pushPop(value, scope, () -> { + evaluator.evaluate(requested); + return Value.NIL; + }); + } else { + return evaluator.pushPop(value, () -> { + evaluator.evaluate(requested); + return Value.NIL; + }); + } + }); + }); + + builder.function("call", function -> { + function.arity(1, 2); + function.vararg(true); + function.execute((evaluator, args) -> { + var value = args.getFirst().asString(); + var requested = loader.module(value); + if (requested == null) { + return evaluator.panic("Requested include " + value + " doesn't exist!"); + } + if (args.size() == 2) { + var scope = args.get(1).asMutableStruct(); + return evaluator.pushPop(value, scope, () -> evaluator.evaluate(requested)); + } else { + return evaluator.pushPop(value, () -> evaluator.evaluate(requested)); + } + }); + }); + + builder.function("static", function -> { + function.arity(1); + function.execute((evaluator, args) -> { + var arg = args.getFirst(); + if (arg instanceof ModuleFile file) { + return file.staticData(); + } + + var value = arg.asString(); + var requested = loader.module(value); + if (requested == null) { + return evaluator.panic("Requested include " + value + " doesn't exist!"); + } + if (requested instanceof ModuleFile module) { + return module.staticData(); + } + + return evaluator.panic("Can't access static data of non module file!"); + }); + }); + + builder.function("list", function -> { + function.arity(1); + function.execute((evaluator, args) -> { + var arg = args.getFirst(); + var prefix = arg.asString(); + var allModules = loader.modules(); + var resultList = MutableArrayValue.create(); + for (String module : allModules) { + if (module.startsWith(prefix) && module.lastIndexOf('/') < prefix.length()) { + resultList.add(new StrValue(module.substring(prefix.length()))); + } + } + return resultList; + }); + }); + + builder.function("dirs", function -> { + function.arity(1); + function.execute((evaluator, args) -> { + var arg = args.getFirst(); + var prefix = arg.asString(); + var allModules = loader.modules(); + var resultList = MutableArrayValue.create(); + for (String module : allModules) { + if (module.startsWith(prefix)) { + int lastSlash = module.lastIndexOf('/'); + if (lastSlash > prefix.length()) { + resultList.add(new StrValue(module.substring(prefix.length(), lastSlash))); + } + } + } + return resultList; + }); + }); + + builder.function("print", (function) -> { + function.vararg(true); + function.executeSimpleVoid((values) -> System.out.println(values.stream().map(Value::prettyPrint).toList())); + }); + }); + + public RepoConstants(RepoLoader loader) { + this.loader = loader; + } + + @Override + public StructValue delegate() { + return constants; + } + + public RepoLoader loader() { + return loader; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/RepoInstance.java b/src/main/java/tech/thatgravyboat/repolib/v2/RepoInstance.java new file mode 100644 index 0000000..30f328c --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/RepoInstance.java @@ -0,0 +1,102 @@ +package tech.thatgravyboat.repolib.v2; + +import java.util.Objects; +import tech.thatgravyboat.repolib.v2.expl.ContentInfo; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.ImmutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.LayeredStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; + +import java.util.LinkedList; +import java.util.List; + +import static tech.thatgravyboat.repolib.v2.builtin.Constants.Builder.FunctionBuilder; + +public record RepoInstance( + RepoLoader loader, + RepoConstants constants, + RepoListConstants listConstants +) { + + public List listStacks() { + var constants = this.constants.toMutable(); + var stacks = new LinkedList(); + constants.set( + "id", FunctionBuilder.create(function -> { + function.arity(1); + function.executeVoid((evaluator, args) -> { + var data = args.getFirst(); + if (data instanceof StructValue struct) { + stacks.add(struct); + return; + } + evaluator.error("'id' expected struct but got " + data); + }); + + })); + var evaluator = new Evaluator(listConstants, this.loader::module); + evaluator.evaluate(loader.rootList()); + return stacks; + } + + public RepoStackResult createStack(StructValue data) { + return this.createStack(data, null); + } + + public RepoStackResult createStack(StructValue data, StructValue profile) { + return this.createStack(data, profile, RepoConfig.DEFAULT); + } + + public RepoStackResult createStack(StructValue data, StructValue profile, RepoConfig repoConfig) { + var constants = this.constants.toMutableStruct(); + constants.set("data", data); + constants.set("profile", Objects.requireNonNullElseGet(profile, this::getEmptyProfile)); + var evaluator = new Evaluator(constants, this.loader::module); + evaluator.evaluate(loader.rootFile()); + var file = evaluator.getField("file").asStringOrNull(); + if (file == null) { + return null; + } + + return createStack(file, data, profile, repoConfig); + } + + private StructValue getEmptyProfile() { + return ImmutableStructValue.EMPTY; + } + + public StructValue getMaxedProfile() { + var profile = this.loader.module("profile"); + if (profile == null) { + return getEmptyProfile(); + } + + var profileStruct = new MutableStructValue(); + + var evaluator = new Evaluator(new LayeredStructValue(profileStruct, this.constants), this.loader::module); + evaluator.evaluate(profile); + return new ImmutableStructValue(profileStruct.fields()); + } + + public RepoStackResult createStack(String id, StructValue data) { + return createStack(id, data, this.getEmptyProfile(), RepoConfig.DEFAULT); + } + public RepoStackResult createStack(String id, StructValue data, StructValue profile) { + return createStack(id, data, profile, RepoConfig.DEFAULT); + } + + public RepoStackResult createStack(String id, StructValue data, StructValue profile, RepoConfig repoConfig) { + var stackFile = loader.stackFile(id); + var evaluator = stackFile.createEvaluator(constants, data, Objects.requireNonNullElseGet(profile, this::getEmptyProfile), repoConfig, this.loader::module); + var stack = stackFile.evaluateScript(evaluator); + return new RepoStackResult(stack, evaluator.debugs, evaluator.errors); + } + + public record RepoStackResult( + StructValue stack, + List debug, + List error + ) { + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/RepoListConstants.java b/src/main/java/tech/thatgravyboat/repolib/v2/RepoListConstants.java new file mode 100644 index 0000000..61c535f --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/RepoListConstants.java @@ -0,0 +1,44 @@ +package tech.thatgravyboat.repolib.v2; + +import tech.thatgravyboat.repolib.v2.builtin.Constants; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; + +public class RepoListConstants implements StructValue.Forwarding { + private final RepoLoader loader; + private final Constants constants; + + public RepoListConstants(RepoConstants repoConstants, RepoLoader loader) { + this.loader = loader; + this.constants = new Constants((builder) -> { + for (var repoConstant : repoConstants) { + builder.field(repoConstant.getKey(), repoConstant.getValue()); + } + + builder.function("list", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var array = MutableArrayValue.create(); + + var prefix = values.getFirst().asString(); + for (var stackEntry : loader.stackFiles().entrySet()) { + if (stackEntry.getKey().startsWith(prefix)) { + array.add(stackEntry.getValue().meta()); + } + } + + return array; + }); + }); + }); + } + + @Override + public StructValue delegate() { + return constants; + } + + public RepoLoader loader() { + return loader; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/RepoLoader.java b/src/main/java/tech/thatgravyboat/repolib/v2/RepoLoader.java new file mode 100644 index 0000000..c5250bd --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/RepoLoader.java @@ -0,0 +1,29 @@ +package tech.thatgravyboat.repolib.v2; + +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.FunctionValueFile; +import tech.thatgravyboat.repolib.v2.expl.ModuleFile; +import tech.thatgravyboat.repolib.v2.expl.StackFile; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; + +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +public interface RepoLoader { + + List load() throws IOException; + Map> files(); + ModuleFile rootFile(); + Expression rootList(); + Map stackFiles(); + RepoInstance create(); + StackFile stackFile(String name); + FunctionValue module(String name); + Collection modules(); + Evaluator createEvaluator(); + + RepoBundle bundle(); +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/SkyblockRarity.java b/src/main/java/tech/thatgravyboat/repolib/v2/SkyblockRarity.java new file mode 100644 index 0000000..a4f65fb --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/SkyblockRarity.java @@ -0,0 +1,59 @@ +package tech.thatgravyboat.repolib.v2; + +import java.util.Optional; + +public enum SkyblockRarity { + COMMON("white"), + UNCOMMON("green"), + RARE("blue"), + EPIC("dark_purple"), + LEGENDARY("gold"), + MYTHIC("light_purple"), + DIVINE("aqua"), + ULTIMATE("dark_red"), + SPECIAL("red"), + VERY_SPECIAL("red"), + ADMIN("red"), + ; + + private final String color; + + SkyblockRarity(String color) { + this.color = color; + } + + public String color() { + return color; + } + + public SkyblockRarity next() { + return switch (this) { + case COMMON -> UNCOMMON; + case UNCOMMON -> RARE; + case RARE -> EPIC; + case EPIC -> LEGENDARY; + case LEGENDARY -> MYTHIC; + case MYTHIC -> DIVINE; + case DIVINE -> ULTIMATE; + case ULTIMATE -> SPECIAL; + case SPECIAL -> VERY_SPECIAL; + default -> this; + }; + } + + public static Optional next(String current) { + return fromString(current).map(SkyblockRarity::next); + } + + public static Optional fromString(String rarity) { + try { + return Optional.of(SkyblockRarity.valueOf(rarity)); + } catch (IllegalArgumentException ignored) { + return Optional.empty(); + } + } + + public static Optional color(String rarity) { + return fromString(rarity).map(SkyblockRarity::color); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryCodec.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryCodec.java new file mode 100644 index 0000000..40b19c4 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryCodec.java @@ -0,0 +1,279 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Function; +import org.jetbrains.annotations.ApiStatus; +import tech.thatgravyboat.repolib.v2.RepoBundle; +import tech.thatgravyboat.repolib.v2.expl.FunctionValueFile; +import tech.thatgravyboat.repolib.v2.expl.expression.DebugExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; + +@ApiStatus.Internal +public interface BinaryCodec extends Decoder, Encoder { + + BinaryCodec INT = simple(ByteBuffer::writeInt, ByteBuffer::readInt); + BinaryCodec BOOLEAN = simple(ByteBuffer::writeBoolean, ByteBuffer::readBoolean); + BinaryCodec LONG = simple(ByteBuffer::writeLong, ByteBuffer::readLong); + BinaryCodec SHORT = simple(ByteBuffer::writeShort, ByteBuffer::readShort); + BinaryCodec DOUBLE = simple(ByteBuffer::writeDouble, ByteBuffer::readDouble); + BinaryCodec BYTE = simple(ByteBuffer::writeByte, ByteBuffer::readByte); + BinaryCodec BYTE_ARRAY = simple(ByteBuffer::writeByteArray, ByteBuffer::readByteArray); + BinaryCodec LITERAL_STRING = simple(ByteBuffer::writeString, ByteBuffer::readString); + BinaryCodec STRING = new BinaryCodec<>() { + @Override + public String decode(DecoderContext context) throws IOException { + return context.readLiteral(); + } + + @Override + public void collectLiterals(String data, NameTable table) { + table.insert(data); + } + + @Override + public void encode(EncoderContext context, String data) { + context.writeLiteral(data); + } + }; + + BinaryCodec> EXPRESSION = new BinaryCodec<>() { + @Override + public Expression decode(DecoderContext context) throws IOException { + return ExpressionCodec.read(context); + } + + @Override + public void collectLiterals(Expression data, NameTable table) { + data.expressionId().codec().collectLiterals(cast(data), table); + } + + @Override + public void encode(EncoderContext context, Expression data) { + ExpressionCodec.write(cast(data), context); + } + }; + BinaryCodec> NULLABLE_EXPRESSION = nullable(EXPRESSION); + + static > BinaryCodec enumCodec(Type[] types) { + return new BinaryCodec<>() { + @Override + public Type decode(DecoderContext context) throws IOException { + return types[context.readInt()]; + } + + @Override + public void collectLiterals(Type data, NameTable table) {} + + @Override + public void encode(EncoderContext context, Type data) { + context.writeInt(data.ordinal()); + } + }; + } + + static BinaryCodec unit(Type instance) { + return new BinaryCodec<>() { + @Override + public Type decode(DecoderContext context) { + return instance; + } + + @Override + public void collectLiterals(Type data, NameTable table) {} + + @Override + public void encode(EncoderContext context, Type data) {} + }; + } + + default void encodeStart(Type data, ByteBuffer buffer) { + var nameTable = NameTable.builder(); + + this.collectLiterals(data, nameTable); + var context = new EncoderContext(nameTable.freezeForEncode(), buffer); + NameTable.CODEC.encode(context, nameTable); + this.encode(context, data); + } + + void collectLiterals(Type data, NameTable table); + + static T cast(B b) { + //noinspection unchecked + return (T) b; + } + + default BinaryCodec> collection() { + return collection(this); + } + + default BinaryCodec nullable() { + return nullable(this); + } + + static BinaryCodec> collection(BinaryCodec codec) { + return new BinaryCodec<>() { + @Override + public Collection decode(DecoderContext context) throws IOException { + var amount = context.readInt(); + var list = new ArrayList(); + for (var i = 0; i < amount; i++) { + list.add(codec.decode(context)); + } + return list; + } + + @Override + public void collectLiterals(Collection data, NameTable table) { + for (var datum : data) { + codec.collectLiterals(datum, table); + } + } + + @Override + public void encode(EncoderContext context, Collection data) { + context.writeInt(data.size()); + for (var datum : data) { + codec.encode(context, datum); + } + } + }; + } + + static BinaryCodec> map(BinaryCodec keyCodec, BinaryCodec valueCodec) { + return new BinaryCodec<>() { + @Override + public Map decode(DecoderContext context) throws IOException { + var size = context.readInt(); + var map = new HashMap(); + + for (var i = 0; i < size; i++) { + map.put(keyCodec.decode(context), valueCodec.decode(context)); + } + + return map; + } + + @Override + public void collectLiterals(Map data, NameTable table) { + for (var keyValueEntry : data.entrySet()) { + keyCodec.collectLiterals(keyValueEntry.getKey(), table); + valueCodec.collectLiterals(keyValueEntry.getValue(), table); + } + } + + @Override + public void encode(EncoderContext context, Map data) { + context.writeInt(data.size()); + + for (var keyValueEntry : data.entrySet()) { + keyCodec.encode(context, keyValueEntry.getKey()); + valueCodec.encode(context, keyValueEntry.getValue()); + } + } + }; + } + + static BinaryCodec nullable(BinaryCodec codec) { + return new BinaryCodec<>() { + @Override + public void encode(EncoderContext context, Type data) { + if (data == null) { + context.writeBoolean(false); + } else { + context.writeBoolean(true); + codec.encode(context, data); + } + } + + @Override + public void collectLiterals(Type data, NameTable table) { + if (data == null) { + return; + } + codec.collectLiterals(data, table); + } + + @Override + public Type decode(DecoderContext context) throws IOException { + if (context.readBoolean()) { + return codec.decode(context); + } + + return null; + } + }; + } + + + private static BinaryCodec simple(Encoder encoder, Decoder decoder) { + return new BinaryCodec<>() { + @Override + public void encode(EncoderContext context, Type data) { + encoder.encode(context, data); + } + + @Override + public void collectLiterals(Type data, NameTable table) {} + + @Override + public Type decode(DecoderContext context) throws IOException { + return decoder.decode(context); + } + }; + } + + default BinaryCodec mapped(Function to, Function from) { + final var self = this; + return new BinaryCodec<>() { + @Override + public Mapped decode(DecoderContext context) throws IOException { + return to.apply(self.decode(context)); + } + + @Override + public void collectLiterals(Mapped data, NameTable table) { + self.collectLiterals(from.apply(data), table); + } + + @Override + public void encode(EncoderContext context, Mapped data) { + self.encode(context, from.apply(data)); + } + }; + } + + default Entry forGetter(Function getter) { + return new Entry<>(this, getter); + } + + record Entry(BinaryCodec codec, Function getter) { + } + + static BinaryCodec dispatch(BinaryCodec keyCodec, Map> map, Function keySupplier) { + return new BinaryCodec<>() { + @Override + public Type decode(DecoderContext context) throws IOException { + var key = keyCodec.decode(context); + var codec = map.get(key); + return codec.decode(context); + } + + @Override + public void collectLiterals(Type data, NameTable table) { + map.get(keySupplier.apply(data)).collectLiterals(cast(data), table); + } + + @Override + public void encode(EncoderContext context, Type data) { + var key = keySupplier.apply(data); + keyCodec.encode(context, key); + var codec = map.get(keySupplier.apply(data)); + codec.encode(context, cast(data)); + } + }; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryFileTypeRegistry.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryFileTypeRegistry.java new file mode 100644 index 0000000..2b15f34 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryFileTypeRegistry.java @@ -0,0 +1,65 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import it.unimi.dsi.fastutil.bytes.Byte2ObjectArrayMap; +import it.unimi.dsi.fastutil.bytes.Byte2ObjectMap; + +import java.io.IOException; +import java.util.HashMap; +import java.util.concurrent.atomic.AtomicInteger; +import tech.thatgravyboat.repolib.v2.expl.FunctionValueFile; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; + +public class BinaryFileTypeRegistry { + + static final Byte2ObjectMap>> registry = new Byte2ObjectArrayMap<>(); + static final AtomicInteger counter = new AtomicInteger(); + + public static final BinaryCodec> CODEC = BinaryCodec.dispatch(BinaryCodec.BYTE, BinaryCodec.cast(registry), (type) -> type.fileId().id()); + + public static final BinaryCodec> FUNCTION_FILE = BinaryCodec.dispatch(BinaryCodec.BYTE, new HashMap<>() {{ + put(FileTypes.FUNCTION.id(), FileTypes.FUNCTION); + put(FileTypes.MODULE.id(), FileTypes.MODULE); + }}, (type) -> type.fileId().id()); + + public static > FileType readUntyped( + Type type, + DecoderContext context + ) throws IOException { + return type.decode(context); + } + + public static TypedFile read(DecoderContext context) throws IOException { + var typeByte = context.readByte(); + var type = registry.get(typeByte); + if (type == null) { + throw new IOException("Unknown file type " + typeByte); + } + + return type.decode(context); + } + + public static > void write(EncoderContext context, Type data) { + context.writeByte(data.fileId().id); + data.fileId().codec.encode(context, data); + } + + public record Type>( + BinaryCodec codec, + byte id) implements BinaryCodec { + + @Override + public FileType decode(DecoderContext buffer) throws IOException { + return codec.decode(buffer); + } + + @Override + public void encode(EncoderContext context, FileType data) { + this.codec.encode(context, data); + } + + @Override + public void collectLiterals(FileType data, NameTable table) { + this.codec.collectLiterals(data, table); + } + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryRecordBuilder.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryRecordBuilder.java new file mode 100644 index 0000000..12a04bf --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/BinaryRecordBuilder.java @@ -0,0 +1,135 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import java.io.IOException; +import java.util.function.Function; + +public class BinaryRecordBuilder { + + public static BinaryCodec of( + BinaryCodec.Entry first, + Function constructor + ) { + return new BinaryCodec() { + @Override + public Instance decode(DecoderContext context) throws IOException { + return constructor.apply(first.codec().decode(context)); + } + + @Override + public void collectLiterals(Instance data, NameTable table) { + first.codec().collectLiterals(first.getter().apply(data), table); + } + + @Override + public void encode(EncoderContext context, Instance data) { + first.codec().encode(context, first.getter().apply(data)); + } + }; + } + + public interface Function2 { + R apply(A a, B b); + } + + public static BinaryCodec of( + BinaryCodec.Entry first, + BinaryCodec.Entry second, + Function2 constructor + ) { + return new BinaryCodec<>() { + @Override + public Instance decode(DecoderContext context) throws IOException { + var a = first.codec().decode(context); + var b = second.codec().decode(context); + return constructor.apply(a, b); + } + + @Override + public void collectLiterals(Instance data, NameTable table) { + first.codec().collectLiterals(first.getter().apply(data), table); + second.codec().collectLiterals(second.getter().apply(data), table); + } + + @Override + public void encode(EncoderContext context, Instance data) { + first.codec().encode(context, first.getter().apply(data)); + second.codec().encode(context, second.getter().apply(data)); + } + }; + } + + + public interface Function3 { + R apply(A a, B b, C c); + } + + public static BinaryCodec of( + BinaryCodec.Entry first, + BinaryCodec.Entry second, + BinaryCodec.Entry third, + Function3 constructor + ) { + return new BinaryCodec<>() { + @Override + public Instance decode(DecoderContext context) throws IOException { + var a = first.codec().decode(context); + var b = second.codec().decode(context); + var c = third.codec().decode(context); + return constructor.apply(a, b, c); + } + + @Override + public void collectLiterals(Instance data, NameTable table) { + first.codec().collectLiterals(first.getter().apply(data), table); + second.codec().collectLiterals(second.getter().apply(data), table); + third.codec().collectLiterals(third.getter().apply(data), table); + } + + @Override + public void encode(EncoderContext context, Instance data) { + first.codec().encode(context, first.getter().apply(data)); + second.codec().encode(context, second.getter().apply(data)); + third.codec().encode(context, third.getter().apply(data)); + } + }; + } + public interface Function4 { + R apply(A a, B b, C c, D d); + } + + public static BinaryCodec of( + BinaryCodec.Entry first, + BinaryCodec.Entry second, + BinaryCodec.Entry third, + BinaryCodec.Entry fourth, + Function4 constructor + ) { + return new BinaryCodec<>() { + @Override + public Instance decode(DecoderContext context) throws IOException { + var a = first.codec().decode(context); + var b = second.codec().decode(context); + var c = third.codec().decode(context); + var d = fourth.codec().decode(context); + return constructor.apply(a, b, c, d); + } + + @Override + public void collectLiterals(Instance data, NameTable table) { + first.codec().collectLiterals(first.getter().apply(data), table); + second.codec().collectLiterals(second.getter().apply(data), table); + third.codec().collectLiterals(third.getter().apply(data), table); + fourth.codec().collectLiterals(fourth.getter().apply(data), table); + } + + @Override + public void encode(EncoderContext context, Instance data) { + first.codec().encode(context, first.getter().apply(data)); + second.codec().encode(context, second.getter().apply(data)); + third.codec().encode(context, third.getter().apply(data)); + fourth.codec().encode(context, fourth.getter().apply(data)); + } + }; + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/ByteBuffer.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ByteBuffer.java new file mode 100644 index 0000000..d6d1cdb --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ByteBuffer.java @@ -0,0 +1,125 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import java.io.IOException; +import java.util.Collection; +import java.util.function.BiConsumer; + +public interface ByteBuffer { + + byte readByte() throws IOException; + + short readShort() throws IOException; + + int readInt() throws IOException; + + long readLong() throws IOException; + + void writeByte(byte b); + + void writeShort(short s); + + void writeInt(int i); + + void writeLong(long l); + + void writeByteArray(byte[] array); + + byte[] readByteArray() throws IOException; + + void writeString(String value); + + String readString() throws IOException; + + void writeBoolean(boolean bool); + + boolean readBoolean() throws IOException; + + void writeDouble(double value); + + double readDouble() throws IOException; + + interface Forwarding extends ByteBuffer { + ByteBuffer delegate(); + + @Override + default byte readByte() throws IOException { + return delegate().readByte(); + } + + @Override + default short readShort() throws IOException { + return delegate().readShort(); + } + + @Override + default int readInt() throws IOException { + return delegate().readInt(); + } + + @Override + default long readLong() throws IOException { + return delegate().readLong(); + } + + @Override + default void writeByte(byte b) { + delegate().writeByte(b); + } + + @Override + default void writeShort(short s) { + delegate().writeShort(s); + } + + @Override + default void writeInt(int i) { + delegate().writeInt(i); + } + + @Override + default void writeLong(long l) { + delegate().writeLong(l); + } + + @Override + default void writeByteArray(byte[] array) { + delegate().writeByteArray(array); + } + + @Override + default byte[] readByteArray() throws IOException { + return delegate().readByteArray(); + } + + @Override + default void writeString(String value) { + delegate().writeString(value); + } + + @Override + default String readString() throws IOException { + return delegate().readString(); + } + + @Override + default void writeBoolean(boolean bool) { + delegate().writeBoolean(bool); + } + + @Override + default boolean readBoolean() throws IOException { + return delegate().readBoolean(); + } + + @Override + default void writeDouble(double value) { + delegate().writeDouble(value); + } + + @Override + default double readDouble() throws IOException { + return delegate().readDouble(); + } + + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/ByteBufferImpl.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ByteBufferImpl.java new file mode 100644 index 0000000..f54d445 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ByteBufferImpl.java @@ -0,0 +1,154 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Objects; + +public record ByteBufferImpl(InputStream input, OutputStream output) implements ByteBuffer { + public static final int MAX_VARINT_SIZE = 5; + private static final int MAX_VARLONG_SIZE = 10; + private static final int DATA_BITS_MASK = 127; + private static final int CONTINUATION_BIT_MASK = 128; + + public ByteBufferImpl(InputStream input) { + this(input, null); + } + + public ByteBufferImpl(OutputStream output) { + this(null, output); + } + + @Override + public InputStream input() { + return Objects.requireNonNull(this.input, "Can't read on output byte buffer"); + } + + @Override + public OutputStream output() { + return Objects.requireNonNull(this.output, "Can't write on input byte buffer"); + } + + public byte readByte() throws IOException { + return this.input().readNBytes(1)[0]; + } + + public short readShort() throws IOException { + short value = (short) (readByte() << Short.SIZE / 2); + value |= readByte(); + return value; + } + + public int readInt() throws IOException { + int out = 0; + int bytes = 0; + + byte in; + do { + in = this.readByte(); + out |= (in & DATA_BITS_MASK) << bytes++ * 7; + if (bytes > MAX_VARINT_SIZE) { + throw new RuntimeException("VarInt too big"); + } + } while (hasContinuationBit(in)); + + return out; + } + + public long readLong() throws IOException { + long out = 0L; + int bytes = 0; + + byte in; + do { + in = this.readByte(); + out |= (long)(in & DATA_BITS_MASK) << bytes++ * 7; + if (bytes > MAX_VARLONG_SIZE) { + throw new RuntimeException("VarLong too big"); + } + } while (hasContinuationBit(in)); + + return out; + } + + public void writeByte(byte b) { + try { + this.output().write(b); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public void writeShort(short s) { + writeByte((byte) ((s >>> Short.SIZE / 2) & 0xFF)); + writeByte((byte) (s & 0xFF)); + } + + public void writeInt(int value) { + while ((value & -CONTINUATION_BIT_MASK) != 0) { + this.writeByte((byte) (value & DATA_BITS_MASK | CONTINUATION_BIT_MASK)); + value >>>= 7; + } + + this.writeByte((byte) value); + } + + public void writeLong(long value) { + while ((value & -128L) != 0L) { + this.writeByte((byte) ((value & DATA_BITS_MASK) | CONTINUATION_BIT_MASK)); + value >>>= 7; + } + + this.writeByte((byte) value); + } + + public void writeByteArray(byte[] array) { + this.writeInt(array.length); + try { + this.output().write(array); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public byte[] readByteArray() throws IOException { + var length = this.readInt(); + var actual = this.input().readNBytes(length); + if (actual.length != length) { + throw new IOException("Expected " + length + " bytes but only got " + actual); + } + return actual; + } + + public void writeString(String value) { + this.writeByteArray(value.getBytes(StandardCharsets.UTF_8)); + } + + public String readString() throws IOException { + return new String(this.readByteArray(), StandardCharsets.UTF_8); + } + + public void writeBoolean(boolean bool) { + writeByte((byte) (bool ? 1 : 0)); + } + + public boolean readBoolean() throws IOException { + return readByte() == 1; + } + + public void writeDouble(double value) { + this.writeLong(Double.doubleToRawLongBits(value)); + } + + public double readDouble() throws IOException { + return Double.longBitsToDouble(this.readLong()); + } + + + public static boolean hasContinuationBit(byte in) { + return (in & CONTINUATION_BIT_MASK) == CONTINUATION_BIT_MASK; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/DataType.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/DataType.java new file mode 100644 index 0000000..6554d80 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/DataType.java @@ -0,0 +1,6 @@ +package tech.thatgravyboat.repolib.v2.binary; + +public interface DataType { + + byte id(); +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/Decoder.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/Decoder.java new file mode 100644 index 0000000..06bb382 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/Decoder.java @@ -0,0 +1,7 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import java.io.IOException; + +public interface Decoder { + Type decode(DecoderContext context) throws IOException; +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/DecoderContext.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/DecoderContext.java new file mode 100644 index 0000000..6cfbc4d --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/DecoderContext.java @@ -0,0 +1,45 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.shorts.Short2IntArrayMap; +import it.unimi.dsi.fastutil.shorts.Short2ObjectMap; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; + +public class DecoderContext implements ByteBuffer.Forwarding { + + Int2ObjectMap nameTable; + private final ByteBuffer buffer; + + public DecoderContext(ByteBuffer buffer) { + this.buffer = buffer; + } + + public String readLiteral() throws IOException { + return this.nameTable.get(buffer.readInt()); + } + + public void updateTable(Int2ObjectMap newTable) { + this.nameTable = newTable; + } + + public Collection readCollection(Decoder decoder) throws IOException { + var size = readInt(); + if (size == 0) { + return Collections.emptyList(); + } + var list = new ArrayList(size); + for (var i = 0; i < size; i++) { + list.add(decoder.decode(this)); + } + return list; + } + + @Override + public ByteBuffer delegate() { + return this.buffer; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/Encodable.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/Encodable.java new file mode 100644 index 0000000..4b26b48 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/Encodable.java @@ -0,0 +1,8 @@ +package tech.thatgravyboat.repolib.v2.binary; + +public interface Encodable { + + void precode(NameTable table); + void encode(EncoderContext context); + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/Encoder.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/Encoder.java new file mode 100644 index 0000000..45f5899 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/Encoder.java @@ -0,0 +1,7 @@ +package tech.thatgravyboat.repolib.v2.binary; + +public interface Encoder { + + public void encode(EncoderContext context, Type data); + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/EncoderContext.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/EncoderContext.java new file mode 100644 index 0000000..991c809 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/EncoderContext.java @@ -0,0 +1,36 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import java.util.Collection; +import java.util.List; +import java.util.function.BiConsumer; + +public class EncoderContext implements ByteBuffer.Forwarding { + + List nameTable; + private final ByteBuffer buffer; + + public EncoderContext(List nameTable, ByteBuffer buffer) { + this.nameTable = nameTable; + this.buffer = buffer; + } + + public void writeLiteral(String string) { + var index = nameTable.indexOf(string); + if (index == -1) { + throw new UnsupportedOperationException("Unknown literal " + string); + } + buffer.writeInt(index); + } + + @Override + public ByteBuffer delegate() { + return this.buffer; + } + + public void writeCollection(Collection data, BiConsumer serializer) { + writeInt(data.size()); + for (var datum : data) { + serializer.accept(datum, this); + } + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/EnumCodec.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/EnumCodec.java new file mode 100644 index 0000000..84f5f1b --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/EnumCodec.java @@ -0,0 +1,15 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import java.io.IOException; + +public record EnumCodec>(Type[] types) implements Decoder { + @Override + public Type decode(DecoderContext buffer) throws IOException { + return types[buffer.readByte()]; + } + + public static > void encode(Type type, EncoderContext buffer) { + buffer.writeByte((byte) type.ordinal()); + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionCodec.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionCodec.java new file mode 100644 index 0000000..6aaec26 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionCodec.java @@ -0,0 +1,24 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; + +import java.io.IOException; + +public class ExpressionCodec { + + public static Expression read(DecoderContext buffer) throws IOException { + var typeByte = buffer.readByte(); + var type = ExpressionTypeRegistry.registry.get(typeByte); + if (type == null) { + throw new IOException("Unknown expression type " + typeByte); + } + + return type.decode(buffer); + } + + public static > void write(FileType data, EncoderContext buffer) { + var expression = data.expressionId(); + buffer.writeByte(expression.id()); + expression.encode(buffer, data); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionTypeRegistry.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionTypeRegistry.java new file mode 100644 index 0000000..f355067 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionTypeRegistry.java @@ -0,0 +1,34 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import it.unimi.dsi.fastutil.bytes.Byte2ObjectArrayMap; +import it.unimi.dsi.fastutil.bytes.Byte2ObjectMap; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; + +import java.io.IOException; +import java.util.concurrent.atomic.AtomicInteger; + +public class ExpressionTypeRegistry { + + static final AtomicInteger counter = new AtomicInteger(); + static final Byte2ObjectMap> registry = new Byte2ObjectArrayMap<>(); + + public record Type>( + BinaryCodec codec, + byte id + ) implements BinaryCodec { + @Override + public ExpressionType decode(DecoderContext context) throws IOException { + return this.codec.decode(context); + } + + @Override + public void encode(EncoderContext context, ExpressionType data) { + this.codec.encode(context, data); + } + + @Override + public void collectLiterals(ExpressionType data, NameTable table) { + this.codec.collectLiterals(data, table); + } + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionTypes.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionTypes.java new file mode 100644 index 0000000..cc8b003 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/ExpressionTypes.java @@ -0,0 +1,65 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import tech.thatgravyboat.repolib.v2.expl.expression.AccessExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ArrayExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.AssignExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BinaryExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BlockExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BoolExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.CallExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.DebugExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.expression.FileAccessExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.FileCallExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ForEachExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ForExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.IfExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.InExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.LambdaExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.LambdaIdentityFunction; +import tech.thatgravyboat.repolib.v2.expl.expression.MatchExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.NumExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.RangeExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ReturnExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StatementExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StrExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StructExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.UnaryExpression; + +public class ExpressionTypes { + public static final ExpressionTypeRegistry.Type STRING = register(StrExpression.CODEC); + public static final ExpressionTypeRegistry.Type BOOLEAN = register(BoolExpression.CODEC); + public static final ExpressionTypeRegistry.Type NUMBER = register(NumExpression.CODEC); + public static final ExpressionTypeRegistry.Type ACCESS = register(AccessExpression.CODEC); + public static final ExpressionTypeRegistry.Type ARRAY = register(ArrayExpression.CODEC); + public static final ExpressionTypeRegistry.Type ASSIGN = register(AssignExpression.CODEC); + public static final ExpressionTypeRegistry.Type BINARY = register(BinaryExpression.CODEC); + public static final ExpressionTypeRegistry.Type BLOCK = register(BlockExpression.CODEC); + public static final ExpressionTypeRegistry.Type BLOCK_LAST_ELEMENT = register(BlockExpression.LastElement.CODEC); + public static final ExpressionTypeRegistry.Type CALL = register(CallExpression.CODEC); + public static final ExpressionTypeRegistry.Type DEBUG = register(DebugExpression.CODEC); + public static final ExpressionTypeRegistry.Type FILE_ACCESS = register(FileAccessExpression.CODEC); + public static final ExpressionTypeRegistry.Type FILE_CALL = register(FileCallExpression.CODEC); + public static final ExpressionTypeRegistry.Type FOR_EACH = register(ForEachExpression.CODEC); + public static final ExpressionTypeRegistry.Type FOR = register(ForExpression.CODEC); + public static final ExpressionTypeRegistry.Type IF = register(IfExpression.CODEC); + public static final ExpressionTypeRegistry.Type IN = register(InExpression.CODEC); + public static final ExpressionTypeRegistry.Type LAMBDA = register(LambdaExpression.CODEC); + public static final ExpressionTypeRegistry.Type LAMBDA_IDENTITY = register(LambdaIdentityFunction.CODEC); + public static final ExpressionTypeRegistry.Type MATCH = register(MatchExpression.CODEC); + public static final ExpressionTypeRegistry.Type RANGE = register(RangeExpression.CODEC); + public static final ExpressionTypeRegistry.Type RETURN = register(ReturnExpression.CODEC); + public static final ExpressionTypeRegistry.Type STATEMENT = register(StatementExpression.CODEC); + public static final ExpressionTypeRegistry.Type STRUCT = register(StructExpression.CODEC); + public static final ExpressionTypeRegistry.Type UNARY = register(UnaryExpression.CODEC); + + private static > ExpressionTypeRegistry.Type register( + BinaryCodec decoder + ) { + var type = new ExpressionTypeRegistry.Type<>(decoder, (byte) ExpressionTypeRegistry.counter.getAndIncrement()); + ExpressionTypeRegistry.registry.put(type.id(), type); + return type; + } + + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/FileTypes.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/FileTypes.java new file mode 100644 index 0000000..3aba210 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/FileTypes.java @@ -0,0 +1,21 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import tech.thatgravyboat.repolib.v2.expl.FunctionFile; +import tech.thatgravyboat.repolib.v2.expl.ModuleFile; +import tech.thatgravyboat.repolib.v2.expl.StackFile; + +public class FileTypes { + public static final BinaryFileTypeRegistry.Type MODULE = register(ModuleFile.CODEC); + public static final BinaryFileTypeRegistry.Type STACK = register(StackFile.CODEC); + public static final BinaryFileTypeRegistry.Type FUNCTION = register(FunctionFile.CODEC); + + + private static > BinaryFileTypeRegistry.Type register( + BinaryCodec codec + ) { + var type = new BinaryFileTypeRegistry.Type<>(codec, (byte) BinaryFileTypeRegistry.counter.getAndIncrement()); + BinaryFileTypeRegistry.registry.put(type.id(), type); + return type; + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/NameTable.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/NameTable.java new file mode 100644 index 0000000..2493af8 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/NameTable.java @@ -0,0 +1,40 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import it.unimi.dsi.fastutil.ints.Int2ObjectArrayMap; +import it.unimi.dsi.fastutil.ints.Int2ObjectMap; +import it.unimi.dsi.fastutil.shorts.Short2ObjectArrayMap; +import it.unimi.dsi.fastutil.shorts.Short2ObjectMap; +import org.jetbrains.annotations.Nullable; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; + +public final record NameTable(Collection names) { + public static final BinaryCodec CODEC = BinaryCodec.LITERAL_STRING.collection().mapped(NameTable::new, NameTable::names); + public static NameTable builder() { + return new NameTable(new HashSet<>()); + } + + + public void insert(String name) { + this.names.add(name); + } + + public List freezeForEncode() { + return List.copyOf(this.names); + } + + public Int2ObjectMap freezeForDecode() { + var names = List.copyOf(this.names); + var map = new Int2ObjectArrayMap(); + for (var i = 0; i < names.size(); i++) { + map.put(i, names.get(i)); + } + + return map; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/RepoBinaryUtils.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/RepoBinaryUtils.java new file mode 100644 index 0000000..b7a278a --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/RepoBinaryUtils.java @@ -0,0 +1,32 @@ +package tech.thatgravyboat.repolib.v2.binary; + +import tech.thatgravyboat.repolib.v2.RepoBundle; +import tech.thatgravyboat.repolib.v2.RepoLoader; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +public class RepoBinaryUtils { + + public static final short BINARY_VERSION = 0; + public static byte[] MAGIC_NUMBER = new byte[]{'S', 'R', 'B'}; + + public static void bundle(OutputStream stream, RepoLoader loader) { + try (var gzipOutputStream = new GZIPOutputStream(stream)) { + var buffer = new ByteBufferImpl(gzipOutputStream); + buffer.writeByte(MAGIC_NUMBER[0]); + buffer.writeByte(MAGIC_NUMBER[1]); + buffer.writeByte(MAGIC_NUMBER[2]); + buffer.writeShort(BINARY_VERSION); + + RepoBundle.CODEC.encodeStart(loader.bundle(), buffer); + + } catch (IOException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/binary/TypedFile.java b/src/main/java/tech/thatgravyboat/repolib/v2/binary/TypedFile.java new file mode 100644 index 0000000..42f91dc --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/binary/TypedFile.java @@ -0,0 +1,5 @@ +package tech.thatgravyboat.repolib.v2.binary; + +public interface TypedFile> { + BinaryFileTypeRegistry.Type fileId(); +} \ No newline at end of file diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinArray.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinArray.java new file mode 100644 index 0000000..99684d3 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinArray.java @@ -0,0 +1,38 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import tech.thatgravyboat.repolib.v2.expl.value.ArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; + +import java.util.Comparator; +import java.util.function.Function; +import java.util.stream.StreamSupport; + +public class BuiltinArray { + + + public static final KeyValue ARRAY = new Constants(builder -> { + + builder.function( + "sorted", function -> { + function.arity(1); + function.execute((evaluator, args) -> { + var array = args.getFirst().asArray(); + var sorted = MutableArrayValue.create(); + StreamSupport.stream(array.spliterator(), false) + .sorted(Comparator.comparing(Function.identity())) + .forEach(sorted::add); + + return sorted; + }); + }); + + builder.function( + "of", function -> { + function.vararg(true); + function.execute((evaluator, args) -> MutableArrayValue.create(ArrayValue.flatten(args))); + }); + + }); + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinBoolean.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinBoolean.java new file mode 100644 index 0000000..51bb2ea --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinBoolean.java @@ -0,0 +1,46 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.List; +import java.util.Locale; + +public class BuiltinBoolean { + + public static final KeyValue BOOLEAN = new Constants(builder -> { + builder.function("and", function -> { + function.arity(2); + function.execute(BuiltinBoolean::and); + }); + builder.function("or", function -> { + function.arity(2); + function.execute(BuiltinBoolean::or); + }); + }); + + private static Value wrap(boolean bool) { + return bool ? BoolValue.TRUE : BoolValue.FALSE; + } + + private static Value and(Evaluator evaluator, List values) { + var first = values.getFirst().asBoolean(); + var second = values.get(1).asBoolean(); + + return wrap(first && second); + } + + private static Value or(Evaluator evaluator, List values) { + var first = values.getFirst().asBoolean(); + var second = values.get(1).asBoolean(); + + return wrap(first || second); + } + + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinComponent.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinComponent.java new file mode 100644 index 0000000..9909396 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinComponent.java @@ -0,0 +1,182 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class BuiltinComponent { + + private static final String[] thousandsPlace = new String[]{"", "M", "MM", "MMM"}; + private static final String[] hundredsPlace = new String[]{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; + private static final String[] tensPlace = new String[]{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; + private static final String[] onesPlace = new String[]{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; + public static final Constants COMPONENT = new Constants(builder -> { + builder.function( + "join", function -> { + function.vararg(true); + function.execute(((evaluator, values) -> { + var components = MutableArrayValue.create(); + values.forEach(components::add); + return components; + })); + }); + + builder.function( + "asString", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var stringBuilder = new StringBuilder(); + asString(evaluator, values.getFirst(), stringBuilder); + + return new StrValue(stringBuilder.toString()); + } + ); + }); + + builder.function( + "asRoman", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + return new StrValue(toRomanNumeral((int) first)); + }); + }); + + builder.function( + "splitToLength", function -> { + function.arity(2); + function.execute((evaluator, values) -> splitToLength(evaluator, values.getFirst(), (int) values.get(1).asNumber())); + }); + + builder.function( + "asComponent", function -> { + function.arity(1); + function.execute((evaluator, values) -> parseComponent(evaluator, values.getFirst())); + }); + }); + + private static StructValue parseComponent(Evaluator evaluator, Value value) { + return switch (value) { + case ArrayValue array -> new MutableStructValue(new HashMap<>(Map.of("extra", array))); + case StructValue kv -> kv; + case StrValue literal -> new MutableStructValue(new HashMap<>(Map.of("text", literal))); + default -> evaluator.panic("Invalid component type " + value.type()); + }; + } + + private static ArrayValue splitToLength(Evaluator evaluator, Value value, int maxLength) { + if (value instanceof ArrayValue array) { + var result = MutableArrayValue.create(); + + for (var line : array) { + for (var lines : splitToLength(evaluator, line, maxLength)) { + result.add(lines); + } + } + + return result; + } + var text = parseComponent(evaluator, value); + + var accumulator = new ArrayList(); + extractSections(evaluator, text, accumulator, new MutableStructValue()); + + var result = MutableArrayValue.create(); + var current = MutableArrayValue.create(); + var currentLength = 0; + + for (var entry : accumulator) { + var literal = entry.get("text").asString(); + + if (currentLength + literal.length() >= maxLength && !literal.isBlank()) { + result.add(new MutableStructValue(new HashMap<>(Map.of("extra", current)))); + current = MutableArrayValue.create(); + currentLength = 0; + } + currentLength += literal.length(); + current.add(entry); + } + + result.add(new MutableStructValue(new HashMap<>(Map.of("extra", current)))); + return result; + } + + private static void extractSections( + Evaluator evaluator, + StructValue text, + List accumulator, + T parent + ) { + text.forEach(entry -> { + if (entry.getKey().equals("text") || entry.getKey().equals("extra")) { + return; + } + parent.set(entry.getKey(), entry.getValue()); + }); + + if (text.contains("text")) { + var literalText = text.get("text").asString(); + if (text.get("do_not_split") == BoolValue.TRUE) { + var entry = new MutableStructValue(parent); + entry.set("text", new StrValue(literalText)); + accumulator.add(entry); + } else { + var textLength = literalText.length(); + var consumed = 0; + do { + var next = literalText.indexOf(' ', consumed); + final String span; + if (next == -1) { + span = literalText.substring(consumed); + consumed = textLength; + } else { + span = literalText.substring(consumed, next + 1); + consumed = next + 1; + } + + var entry = new MutableStructValue(parent); + entry.set("text", new StrValue(span)); + accumulator.add(entry); + } while (consumed < textLength); + } + } + + if (text.contains("extra")) { + var extra = text.get("extra").asArray(); + for (var value : extra) { + var extraParent = new MutableStructValue(parent); + extractSections(evaluator, parseComponent(evaluator, value), accumulator, extraParent); + } + } + } + + private static void asString(Evaluator evaluator, Value values, StringBuilder stringBuilder) { + if (values instanceof KeyValue kv) { + if (kv.contains("text")) { + stringBuilder.append(kv.get("text").asString()); + } + + if (kv.contains("extra")) { + var extra = kv.get("extra").asArray(); + for (var value : extra) { + asString(evaluator, value, stringBuilder); + } + } + } else if (values instanceof StrValue(String value)) { + stringBuilder.append(value); + } else { + evaluator.panic("Failed to read " + values + " as a component."); + } + } + + private static String toRomanNumeral(int number) { + if (number >= 4000) return "TOO_HIGH_NUMBER"; + if (number == 0) return "O"; + if (number < 0) return "TOO_LOW_NUMBER"; + return thousandsPlace[number / 1000] + hundredsPlace[number % 1000 / 100] + tensPlace[number % 100 / 10] + onesPlace[number % 10]; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinMath.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinMath.java new file mode 100644 index 0000000..b32965d --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinMath.java @@ -0,0 +1,193 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import tech.thatgravyboat.repolib.v2.expl.value.ArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public class BuiltinMath { + + public static final Constants MATH = new Constants(builder -> { + + builder.function("gt", function -> { + function.arity(2); + function.execute((evaluator, args) -> { + var first = args.getFirst().asNumber(); + var second = args.get(1).asNumber(); + + return BoolValue.wrap(first > second); + }); + }); + + builder.function("gte", function -> { + function.arity(2); + function.execute((evaluator, args) -> { + var first = args.getFirst().asNumber(); + var second = args.get(1).asNumber(); + + return BoolValue.wrap(first >= second); + }); + }); + + builder.function("lt", function -> { + function.arity(2); + function.execute((evaluator, args) -> { + var first = args.getFirst().asNumber(); + var second = args.get(1).asNumber(); + + return BoolValue.wrap(first < second); + }); + }); + + builder.function("lte", function -> { + function.arity(2); + function.execute((evaluator, args) -> { + var first = args.getFirst().asNumber(); + var second = args.get(1).asNumber(); + + return BoolValue.wrap(first <= second); + }); + }); + + builder.function("add", function -> { + function.vararg(true); + function.arity(1); + function.execute((evaluator, values) -> { + double sum = 0; + + for (var value : values) { + if (value instanceof ArrayValue array) { + for (var arrayValue : array) { + sum += arrayValue.asNumber(); + } + } else { + sum += value.asNumber(); + } + } + + return new NumValue(sum); + }); + }); + + builder.function("sub", function -> { + function.vararg(true); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + var second = values.get(1).asNumber(); + + return new NumValue(first - second); + }); + }); + + builder.function("pow", function -> { + function.vararg(true); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + var second = values.get(1).asNumber(); + + return new NumValue(Math.pow(first, second)); + }); + }); + + builder.function("min", function -> { + function.vararg(true); + function.arity(1); + function.execute((evaluator, values) -> { + var flattened = ArrayValue.flatten(values); + double min = flattened.getFirst().asNumber(); + + for (var value : flattened) { + min = Math.min(value.asNumber(), min); + } + + return new NumValue(min); + }); + }); + + builder.function("max", function -> { + function.vararg(true); + function.arity(1); + function.execute((evaluator, values) -> { + var flattened = ArrayValue.flatten(values); + double min = flattened.getFirst().asNumber(); + + for (var value : flattened) { + min = Math.max(value.asNumber(), min); + } + + return new NumValue(min); + }); + }); + + builder.function("abs", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + return new NumValue(Math.abs(values.getFirst().asNumber())); + }); + }); + + builder.function("mul", function -> { + function.arity(2); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + var second = values.get(1).asNumber(); + return new NumValue(first * second); + }); + }); + + builder.function("div", function -> { + function.arity(2); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + var second = values.get(1).asNumber(); + if (second == 0) { + return evaluator.panic("Can't divide by 0!"); + } + return new NumValue(first / second); + }); + }); + + builder.function("floor", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + + return new NumValue(Math.floor(first)); + }); + }); + + builder.function("ceil", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + + return new NumValue(Math.ceil(first)); + }); + }); + + builder.function("round", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + + return new NumValue(Math.round(first)); + }); + }); + + builder.function("clamp", function -> { + function.arity(3); + function.execute((evaluator, values) -> { + var first = values.getFirst().asNumber(); + var second = values.get(1).asNumber(); + var third = values.get(2).asNumber(); + + return new NumValue(Math.clamp(first, second, third)); + }); + }); + + builder.constant("PI", Math.PI); + builder.constant("E", Math.E); + + + }); +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinObjects.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinObjects.java new file mode 100644 index 0000000..0d26c1c --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinObjects.java @@ -0,0 +1,60 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public class BuiltinObjects { + + public static String toString(Value value) { + return switch (value) { + case StrValue str -> str.value(); + case NumValue(double num) -> num == (int) num ? Integer.toString((int) num) : Double.toString(num); + default -> value.toString(); + }; + } + + public static final KeyValue OBJECTS = new Constants(builder -> { + + builder.function("toString", function -> { + function.arity(1); + function.executeSimple(args -> { + var firstArg = args.getFirst(); + + return switch (firstArg) { + case StrValue str -> str; + case NumValue num -> new StrValue(String.valueOf(num)); + default -> new StrValue(firstArg.toString()); + }; + }); + }); + + builder.function("entries", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var first = values.getFirst(); + if (first instanceof StructValue struct) { + var array = MutableArrayValue.create(); + + for (var entry : struct) { + var entryStruct = new MutableStructValue(); + + entryStruct.set("key", new StrValue(entry.getKey())); + entryStruct.set("value", entry.getValue()); + + array.add(entryStruct); + } + return array; + } + + return evaluator.panic("Can't call Objects.entries on non struct type."); + }); + }); + + }); + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinRarities.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinRarities.java new file mode 100644 index 0000000..5ba46f3 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinRarities.java @@ -0,0 +1,127 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import tech.thatgravyboat.repolib.v2.SkyblockRarity; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public class BuiltinRarities { + + + public static FunctionValue STACK_RARITY = FunctionValue.builder((builder) -> { + builder.arity(0); + builder.executeArgless(evaluator -> { + var meta = evaluator.getField("meta"); + var baseRarity = evaluator.getField(meta, "rarity").asString(); + if (baseRarity == null) { + return evaluator.panic("Item doesn't have a base rarity!"); + } + + var rarity = SkyblockRarity.fromString(baseRarity); + if (rarity.isEmpty()) { + return evaluator.panic("Unable to convert " + baseRarity + " to rarity!"); + } + + var currentRarity = rarity.get(); + + var data = evaluator.getField("data"); + + var rarityUpgrades = evaluator.getField(data, "rarity_upgrades").asNumber(0); + if (rarityUpgrades > 0) { + while (rarityUpgrades > 0) { + currentRarity = currentRarity.next(); + rarityUpgrades--; + } + } + + if (evaluator.getField(data, "baseStatBoostPercentage").asNumber(0) >= 50) { + currentRarity = currentRarity.next(); + } + + return new StrValue(currentRarity.name()); + }); + }); + + public static FunctionValue IS_RECOMBOBULATED = FunctionValue.builder((builder) -> { + builder.arity(0); + builder.executeArgless(evaluator -> { + var data = evaluator.getField("data"); + + var rarityUpgrades = evaluator.getField(data, "rarity_upgrades").asNumber(0); + if (rarityUpgrades > 0) { + return BoolValue.TRUE; + } + + return BoolValue.FALSE; + }); + }); + + public static final Constants RARITY = new Constants(builder -> { + + builder.function("color", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var first = values.getFirst(); + var rarity = first.asStringOrNull(); + if (rarity == null) { + return evaluator.panic("Provided rarity is not a string!"); + } + + var color = SkyblockRarity.color(rarity); + + if (color.isEmpty()) { + return evaluator.panic("Unknown rarity " + rarity + "!"); + } + + return new StrValue(color.get()); + }); + }); + builder.function("names", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var first = values.getFirst(); + var rarity = first.asStringOrNull(); + if (rarity == null) { + return evaluator.panic("Provided rarity is not a string!"); + } + + var rarityValue = SkyblockRarity.fromString(rarity); + + if (rarityValue.isEmpty()) { + return evaluator.panic("Unknown rarity " + rarity + "!"); + } + + return new StrValue(rarityValue.get().name()); + }); + }); + + builder.field("stack", STACK_RARITY); + builder.field("isRecombobulated", IS_RECOMBOBULATED); + + builder.function("upgrade", function -> { + function.arity(2); + function.execute((evaluator, values) -> { + var first = values.getFirst(); + var rarity = first.asString(); + var rarityValue = SkyblockRarity.fromString(rarity); + + if (rarityValue.isEmpty()) { + return evaluator.panic("Unknown rarity " + rarity + "!"); + } + + var rarityResult = rarityValue.get(); + var upgrade = (int) values.get(1).asNumber(); + for (int i = 0; i < upgrade; i++) { + rarityResult = rarityResult.next(); + } + + return new StrValue(rarityResult.name()); + }); + }); + }); + + private BuiltinRarities() { + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinString.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinString.java new file mode 100644 index 0000000..d1d8848 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/BuiltinString.java @@ -0,0 +1,143 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import java.text.CompactNumberFormat; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; +import java.util.List; +import java.util.Locale; + +public class BuiltinString { + + public static final KeyValue STRING = new Constants(builder -> { + builder.function("concat", function -> { + function.vararg(true); + function.executeSimple(args -> { + + var string = new StringBuilder(); + + for (var arg : args) { + string.append(BuiltinObjects.toString(arg)); + } + + return new StrValue(string.toString()); + }); + }); + + builder.function("eqIc", function -> { + function.arity(2); + function.execute((evaluator, values) -> { + var first = values.getFirst().asString(); + var second = values.get(1).asString(); + + return BoolValue.wrap(first.equalsIgnoreCase(second)); + }); + }); + + builder.function("uppercase", function -> { + function.arity(1); + function.execute(BuiltinString::uppercase); + }); + + builder.function("lowercase", function -> { + function.arity(1); + function.execute(BuiltinString::lowercase); + }); + + builder.function("snake_case", function -> { + function.arity(1); + function.execute(BuiltinString::snake_case); + }); + + builder.function("formatted", function -> { + function.arity(1); + var format = new DecimalFormat("+#.####;-#.####", DecimalFormatSymbols.getInstance(Locale.ROOT)); + function.execute((evaluator, values) -> { + var arg = values.getFirst(); + return new StrValue(format.format(arg.asNumber())); + }); + }); + builder.function("percentage", function -> { + function.arity(1); + var format = new DecimalFormat("+#.####%;-#.####%", DecimalFormatSymbols.getInstance(Locale.ROOT)); + function.execute((evaluator, values) -> { + var arg = values.getFirst(); + return new StrValue(format.format(arg.asNumber())); + }); + }); + builder.function("uFormatted", function -> { + function.arity(1); + var format = new DecimalFormat("#.####;#.####", DecimalFormatSymbols.getInstance(Locale.ROOT)); + function.execute((evaluator, values) -> { + var arg = values.getFirst(); + return new StrValue(format.format(arg.asNumber())); + }); + }); + + builder.function("formattedI", function -> { + function.arity(1); + var format = new DecimalFormat("+#;-#", DecimalFormatSymbols.getInstance(Locale.ROOT)); + function.execute((evaluator, values) -> { + var arg = values.getFirst(); + return new StrValue(format.format(arg.asNumber())); + }); + }); + builder.function("percentageI", function -> { + function.arity(1); + var format = new DecimalFormat("+#%;-#%", DecimalFormatSymbols.getInstance(Locale.ROOT)); + function.execute((evaluator, values) -> { + var arg = values.getFirst(); + return new StrValue(format.format(arg.asNumber())); + }); + }); + builder.function("uFormattedI", function -> { + function.arity(1); + var format = new DecimalFormat("#;#", DecimalFormatSymbols.getInstance(Locale.ROOT)); + function.execute((evaluator, values) -> { + var arg = values.getFirst(); + return new StrValue(format.format(arg.asNumber())); + }); + }); + builder.function("compact", function -> { + function.arity(1, 2); + var format = new CompactNumberFormat( + "#;#", + DecimalFormatSymbols.getInstance(Locale.ROOT), + new String[]{ + "", "", "", + "0K", "00K", "000K", + "0M", "00M", "000M", + "0B", "00B", "000B", + "0T", "00T", "000T" + }); + function.execute((evaluator, values) -> { + var arg = values.getFirst(); + int digits; + if (values.size() == 2) { + digits = (int) values.get(1).asNumber(); + } else { + digits = 1; + } + + format.setMinimumFractionDigits(digits); + format.setMaximumFractionDigits(digits); + return new StrValue(format.format(arg.asNumber())); + }); + }); + }); + + private static Value uppercase(Evaluator evaluator, List args) { + return new StrValue(args.getFirst().asStringOrNull().toUpperCase(Locale.ROOT)); + } + private static Value lowercase(Evaluator evaluator, List args) { + return new StrValue(args.getFirst().asStringOrNull().toLowerCase(Locale.ROOT)); + } + private static Value snake_case(Evaluator evaluator, List args) { + return new StrValue(args.getFirst().asStringOrNull().toLowerCase(Locale.ROOT).replace(" ", "_")); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/builtin/Constants.java b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/Constants.java new file mode 100644 index 0000000..cf1a9dd --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/builtin/Constants.java @@ -0,0 +1,263 @@ +package tech.thatgravyboat.repolib.v2.builtin; + +import com.google.gson.*; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.*; + +import java.util.*; +import java.util.function.*; + +public record Constants(Map map) implements StructValue { + public Constants(Consumer builder) { + this(Builder.create(builder, ImmutableStructValue::new)); + } + + @Override + public Value get(String field) { + if (field.equals("this")) return this; + return map.get(field); + } + + @Override + public MutableStructValue toMutableStruct() { + return new MutableStructValue(new HashMap<>(map)); + } + + @Override + public int size() { + return this.map.size(); + } + + @Override + public boolean contains(String field) { + return map.containsKey(field); + } + + public static Mutable mutable(Consumer builder) { + return new MutableStructValue(Builder.create(builder, MutableStructValue::new)); + } + + public static StructValue kvFromJson(JsonObject jsonObject) { + Map structKeys = new HashMap<>(); + for (String key : jsonObject.keySet()) { + var jsonEntry = jsonObject.get(key); + structKeys.put(key, valueFromJson(jsonEntry)); + } + return new ImmutableStructValue(structKeys); + } + + private static Value valueFromJson(JsonElement element) { + return switch (element) { + case JsonObject subObject: { + yield kvFromJson(subObject); + } + case JsonArray jsonArray: { + List array = new ArrayList<>(jsonArray.size()); + for (var arrayElement : jsonArray) { + array.add(valueFromJson(arrayElement)); + } + yield MutableArrayValue.create(array).toImmutableArray(); + } + case JsonPrimitive primitive: { + if (primitive.isNumber()) { + yield new NumValue(primitive.getAsDouble()); + } else if (primitive.isBoolean()) { + yield BoolValue.wrap(primitive.getAsBoolean()); + } else if (primitive.isString()) { + yield new StrValue(primitive.getAsString()); + } + yield Value.NIL; + } + case JsonNull ignored: { + yield Value.NIL; + } + default: + throw new IllegalStateException("Unexpected value: " + element); + }; + } + + @Override + public Set keySet() { + return map.keySet(); + } + + @Override + public Map sourceMap() { + Map result = new HashMap<>(map.size()); + for (String key : keySet()) { + result.put(key, this); + } + return result; + } + + @Override + public @NotNull Iterator> iterator() { + return map.entrySet().iterator(); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + public static class Builder { + private Function, KeyValue> struct; + private final Map map = new HashMap<>(); + + private Builder() { + } + + private static Map create(Consumer builderConsumer, Function, KeyValue> struct) { + var builder = new Builder(); + builder.struct = struct; + builderConsumer.accept(builder); + return builder.map; + } + + public void constant(String name, String value) { + field(name, new StrValue(value)); + } + + public void constant(String name, boolean value) { + field(name, BoolValue.wrap(value)); + } + + public void constant(String name, int value) { + field(name, new NumValue(value)); + } + + public void constant(String name, long value) { + field(name, new NumValue(value)); + } + + public void constant(String name, float value) { + field(name, new NumValue(value)); + } + + public void constant(String name, double value) { + field(name, new NumValue(value)); + } + + public void function(String name, Consumer function) { + field(name, FunctionBuilder.create(function)); + } + + public void struct(String name, Consumer builder) { + field(name, struct.apply(Builder.create(builder, struct))); + } + + public void mutableStruct(String name, Consumer builder) { + field(name, struct.apply(Builder.create(builder, MutableStructValue::new))); + } + + public void immutableStruct(String name, Consumer builder) { + field(name, struct.apply(Builder.create(builder, ImmutableStructValue::new))); + } + + public void field(String name, Value value) { + map.putIfAbsent(name, value); + } + + public static class FunctionBuilder { + private int arityMin = 0; + private int arityMax = Short.MAX_VALUE; + private boolean vararg = false; + private BiFunction, Value> executor; + + public static FunctionValue create(Consumer builderConsumer) { + var builder = new FunctionBuilder(); + builderConsumer.accept(builder); + int arityMin = builder.arityMin; + int arityMax = builder.arityMax; + boolean vararg = builder.vararg; + var executor = builder.executor; + return new LambdaFunctionValue((evaluator, args) -> { + if ((vararg && (args.size() > arityMax || args.size() < arityMin)) || (!vararg && args.size() != arityMin)) { + evaluator.error("Arity mismatched, expected " + arityMin + (arityMin != arityMax ? + " - " + arityMax : + "") + " arguments but got " + args.size()); + return NIL; + } + + return executor.apply(evaluator, args); + }, vararg, arityMin, arityMax); + } + + public void vararg(boolean isVararg) { + this.vararg = isVararg; + } + + public void arity(int arity) { + if (arity < 0) { + throw new IllegalArgumentException("Arity " + arity + "out of range [0;["); + } + arityMin = arity; + arityMax = Short.MAX_VALUE; + } + + public void arity(int arityMin, int arityMax) { + if (arityMax <= arityMin) { + throw new IllegalArgumentException("Max arity is below (or equal) min arity!"); + } + if (arityMax < 0 || arityMin < 0) { + throw new IllegalArgumentException("Arity is out of range"); + } + this.arityMin = arityMin; + this.arityMax = arityMax; + vararg = true; + } + + public void execute(BiFunction, Value> executor) { + this.executor = executor; + } + + public void executeVoid(BiConsumer> executor) { + this.executor = (evaluator, values) -> { + executor.accept(evaluator, values); + return NIL; + }; + } + + public void executeArgless(Function executor) { + this.executor = ((evaluator, _) -> executor.apply(evaluator)); + } + + public void executeArglessVoid(Consumer executor) { + this.executeVoid((evaluator, _) -> executor.accept(evaluator)); + } + + public void executeSimple(Function, Value> executor) { + this.executor = ((_, values) -> executor.apply(values)); + } + + public void executeSimpleVoid(Consumer> executor) { + this.executeVoid((_, args) -> executor.accept(args)); + } + + public void supply(Supplier executor) { + this.executor = ((_, _) -> executor.get()); + } + + public void runs(Runnable executor) { + this.executeVoid((_, _) -> executor.run()); + } + + public int getArityMin() { + return arityMin; + } + + public int getArityMax() { + return arityMax; + } + + public boolean isVararg() { + return vararg; + } + + public BiFunction, Value> getExecutor() { + return executor; + } + } + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/ContentInfo.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/ContentInfo.java new file mode 100644 index 0000000..f22d80d --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/ContentInfo.java @@ -0,0 +1,4 @@ +package tech.thatgravyboat.repolib.v2.expl; + +public record ContentInfo(String stack, String message) { +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/Evaluator.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/Evaluator.java new file mode 100644 index 0000000..b2f71e9 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/Evaluator.java @@ -0,0 +1,240 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import org.jetbrains.annotations.Contract; +import tech.thatgravyboat.repolib.v2.expl.expression.AccessExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.AssignExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BlockExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BoolExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.CallExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.DebugExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.expression.FileAccessExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ForExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.IfExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.InExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.LambdaExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.LambdaIdentityFunction; +import tech.thatgravyboat.repolib.v2.expl.expression.NumExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StatementExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StrExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StructExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.UnaryExpression; +import tech.thatgravyboat.repolib.v2.expl.value.ArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.ImmutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.LambdaFunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.LayeredStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.NilValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.ScopeLayeredStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructuredFunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public class Evaluator { + + public static final int MAX_ITERATIONS = Short.MAX_VALUE; + + public final KeyValue defaults; + private final Scope scope; + private final Function fileFunction; + public final List debugs = new ArrayList<>(); + public final LinkedList stack = new LinkedList<>(); + public final List errors = new ArrayList<>(); + + public void push(String stack) { + this.scope.push(); + this.stack.addLast(stack); + } + + public void push(StructValue.MutableStruct scope, String stack) { + this.scope.pushWithScope(scope); + this.stack.addLast(stack); + } + + public void pop() { + this.scope.pop(); + this.stack.removeLast(); + } + + public KeyValue scope() { + return this.scope.get(); + } + + public Value pushPop(String stack, StructValue.MutableStruct scope, Supplier supplier) { + try { + this.scope.pushWithScope(scope); + this.stack.addLast(stack); + return supplier.get(); + } finally { + this.scope.pop(); + this.stack.removeLast(); + } + } + + public Value pushPop(String stack, Supplier supplier) { + try { + this.scope.push(); + this.stack.addLast(stack); + return supplier.get(); + } finally { + this.scope.pop(); + this.stack.removeLast(); + } + } + + public void setInOverlay(String field, Value value) { + var scope = this.scope.get(); + if (scope instanceof ScopeLayeredStructValue(StructValue ignored, StructValue.MutableStruct overlay)) { + overlay.set(field, value); + } + } + + private String stack() { + var stringBuilder = new StringBuilder(); + for (var s : this.stack) { + stringBuilder.append('['); + stringBuilder.append(s); + stringBuilder.append(']'); + } + + return stringBuilder.toString(); + } + + public Evaluator(StructValue defaults, Function fileFunction) { + this.fileFunction = fileFunction; + this.defaults = defaults; + scope = new Scope(defaults instanceof LayeredStructValue ? defaults : + new LayeredStructValue(new MutableStructValue(), defaults)); + } + + public static final Evaluator CONSTANT = new Evaluator(ImmutableStructValue.EMPTY, _ -> null); + + public Value evaluate(Expression expression) { + try { + if (expression != null && expression.canReturnValueBeReturned()) { + return eval0(expression); + } else { + eval0(expression); + } + } catch (ExecutionExceptions.Return ret) { + return ret.retVal; + } catch (ExecutionExceptions.Break e) { + error("Break statement not within loop."); + } catch (ExecutionExceptions.Continue e) { + error("Continue statement not within loop."); + } + return Value.NIL; + } + + @Contract("_->fail") + public T panic(String message) { + throw new Panic(message); + } + + public void error(String message) { + errors.add(new ContentInfo(this.stack(), message)); + } + + public void debug(String message) { + debugs.add(new ContentInfo(this.stack(), message)); + } + + public Value getField(Value holder, String field) { + if (holder instanceof KeyValue kv) { + return kv.get(field); + } + throw new Panic("Unable to access property " + field + " of non key/value " + holder); + } + + public Value getField(String field) { + return scope.get().get(field); + } + + public void setField(String field, Value value) { + KeyValue currentScope = scope.get(); + if (currentScope instanceof KeyValue.Mutable mutable) { + mutable.set(field, value); + } + } + + public Value eval0(Expression expression) { + try { + if (expression != null) { + return expression.evaluate(this); + } + } catch (Panic e) { + error(e.getMessage()); + } + return Value.NIL; + } + + public void set(String fieldName, Value value) { + set(scope.get(), fieldName, value); + } + + public Value set(Value value, String fieldName, Value val) { + if (value instanceof KeyValue.Mutable keyValue) { + keyValue.set(fieldName, val); + return val; + } else if (value instanceof KeyValue) { + throw new Panic("Unable to set property '" + fieldName + "' on immutable key/value " + value); + } + + throw new Panic("Unable to set property '" + fieldName + "' on non key/value " + value); + } + + public FunctionValue getFileAccess(String name) { + var file = fileFunction.apply(name); + if (file == null) { + throw new Panic("requested include " + name + " not found!"); + } + return file; + } + + public static class Panic extends RuntimeException { + + public Panic(String message) { + super(message); + } + } + + private static class Scope { + StructValue defaults; + LinkedList scopes = new LinkedList<>(); + + public Scope(StructValue defaults) { + this.defaults = defaults; + scopes.add(defaults); + } + + public KeyValue get() { + return scopes.getLast(); + } + + public void push() { + scopes.add(new ScopeLayeredStructValue(scopes.getLast(), new MutableStructValue())); + } + + public void pushWithScope(StructValue.MutableStruct newScope) { + scopes.add(new ScopeLayeredStructValue(defaults, newScope)); + } + + public void pop() { + if (scopes.size() == 1) { + throw new IllegalStateException("Cannot pop base scope"); + } + scopes.removeLast(); + } + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/ExecutionExceptions.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/ExecutionExceptions.java new file mode 100644 index 0000000..40e9807 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/ExecutionExceptions.java @@ -0,0 +1,19 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public class ExecutionExceptions { + + public static final Return RETURN = new Return(Value.NIL); + public static final Break BREAK = new Break(); + public static final Continue CONTINUE = new Continue(); + + public static class Return extends RuntimeException { + public Value retVal; + public Return(Value retVal) { + this.retVal = retVal; + } + } + public static class Break extends RuntimeException {} + public static class Continue extends RuntimeException {} +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/FunctionFile.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/FunctionFile.java new file mode 100644 index 0000000..25055d3 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/FunctionFile.java @@ -0,0 +1,99 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import java.util.Collection; +import java.util.List; + +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryFileTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.FileTypes; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.expression.LambdaExpression; +import tech.thatgravyboat.repolib.v2.expl.value.LambdaValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructuredFunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record FunctionFile(String name, Collection arguments, Expression body) implements LambdaValue, StructuredFunctionValue, + FunctionValueFile { + + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.STRING.forGetter(FunctionFile::name), + LambdaExpression.LambdaArgument.CODEC.collection().forGetter(FunctionFile::arguments), + BinaryCodec.EXPRESSION.forGetter(FunctionFile::body), + FunctionFile::new + ); + + @Override + public Value apply(Evaluator evaluator, StructValue structValue) { + for (var argument : arguments) { + if (argument.optional()) continue; + if (!structValue.contains(argument.name())) { + return evaluator.panic("Missing required argument on " + name); + } + } + + return evaluator.pushPop(name, structValue.toMutableStruct(), () -> evaluator.evaluate(this.body)); + } + + @Override + public Value apply(Evaluator evaluator, List values) { + + return evaluator.pushPop(name, () -> { + + for (var argument : arguments) { + if (argument.optional() && argument.position() >= values.size()) continue; + evaluator.set(argument.name(), values.get(argument.position())); + } + + return evaluator.evaluate(body); + }); + } + + @Override + public boolean vararg() { + int min = 0; + int max = 0; + boolean hasEncounteredOptional = false; + + for (var argument : arguments) { + max++; + + if (argument.optional()) { + hasEncounteredOptional = true; + continue; + } + + if (hasEncounteredOptional) { + throw new IllegalStateException("Optional before required argument!"); + } + + min++; + } + + return min != max; + } + + @Override + public int arityMin() { + int min = 0; + for (var argument : arguments) { + if (argument.optional()) continue; + + min++; + } + + return min; + } + + @Override + public int arityMax() { + return this.arguments.size(); + } + + @Override + public BinaryFileTypeRegistry.Type fileId() { + return FileTypes.FUNCTION; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/FunctionValueFile.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/FunctionValueFile.java new file mode 100644 index 0000000..2531f84 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/FunctionValueFile.java @@ -0,0 +1,7 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import tech.thatgravyboat.repolib.v2.binary.TypedFile; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; + +public interface FunctionValueFile> extends FunctionValue, TypedFile { +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/Lexer.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/Lexer.java new file mode 100644 index 0000000..b794b58 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/Lexer.java @@ -0,0 +1,413 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import org.jetbrains.annotations.Nullable; + +import java.util.function.Predicate; + +public final class Lexer { + private final String source; + private int start = 0; + private int cursor = 0; + + public Lexer(String source) { + this.source = source; + } + + public @Nullable Token peek() { + var result = next(); + cursor = start; // Reset to where it was before the call to next. + return result; + } + + public void expect(Token type) { + var next = next(); + if (next != type) { + throw new IllegalStateException("Expected " + type + " but got " + next); + } + } + + public void expect(Token type, String span) { + expect(type); + if (!span().equals(span)) { + throw new IllegalStateException("Expected " + span + " but got " + span()); + } + } + + public @Nullable Token next() { + consumeWhitespace(); + + start = cursor; + if (atEnd()) { + return null; + } + + char c = advance(); + if (isAlpha(c)) { + return identOrKeyword(); + } else if (isDigit(c)) { + return number(); + } else if (c == '\'' || c == '"') { + return string(c); + } + + return symbol(c); + } + + private Token string(char quote) { + while (peek0() != quote) { + var isEscaped = peek0() == '\\'; + advance(); + if (isEscaped && peek0() == quote) { + advance(); + } + } + + match(quote); + + return Token.LITERAL_STR; + } + + private Token symbol(char c) { + return switch (c) { + case '[' -> Token.L_BRACKET; + case ']' -> Token.R_BRACKET; + case '(' -> Token.L_PARENTHESES; + case ')' -> Token.R_PARENTHESES; + case '{' -> Token.L_BRACE; + case '}' -> Token.R_BRACE; + case ',' -> Token.COMMA; + case '=' -> { + if (match('=')) { + yield Token.EQUAL; + } + + yield Token.ASSIGN; + } + case '+' -> { + if (match('=')) { + yield Token.PLUS_ASSIGN; + } + + yield Token.PLUS; + } + case '.' -> { + if (match('.')) { + if (match('<')) { + yield Token.INCLUSIVE_EXCLUSIVE_RANGE; + } + yield Token.INCLUSIVE_INCLUSIVE_RANGE; + } + yield Token.DOT; + } + case '>' -> { + if (match('.')) { + if (match('.')) { + if (match('<')) { + yield Token.EXCLUSIVE_EXCLUSIVE_RANGE; + } + yield Token.EXCLUSIVE_INCLUSIVE_RANGE; + } + yield unexpected(c); + } + + if (peek0() == '=') { + advance(); + yield Token.GTE; + } + yield Token.GT; + } + case '<' -> { + if (peek0() == '=') { + advance(); + yield Token.LTE; + } + yield Token.LT; + } + case '-' -> { + if (match('>')) { + yield Token.LAMBDA_ARROW; + } + + if (match('=')) { + yield Token.MINUS_ASSIGN; + } + + yield Token.MINUS; + } + case '/' -> { + + if (match('=')) { + yield Token.DIV_ASSIGN; + } + + yield Token.DIV; + } + case '*' -> { + + if (match('=')) { + yield Token.MUL_ASSIGN; + } + + yield Token.MUL; + } + case '%' -> { + + if (match('=')) { + yield Token.MOD_ASSIGN; + } + + yield Token.MOD; + } + case '|' -> { + if (!match('|')) { + yield Token.LAMBDA_FUNCTION_PARAMETERS; + } + yield Token.OR; + } + case '&' -> { + if (!match('&')) { + unexpected(c); + } + yield Token.AND; + } + case '!' -> { + if (match("in")) { + yield Token.NOT_IN; + } + yield Token.NOT; + } + case '?' -> Token.QUESTION; + case ':' -> { + if (match(':')) { + yield Token.DOUBLE_COLON; + } + + yield Token.COLON; + } + case ';' -> Token.SEMICOLON; + default -> unexpected(c); + }; + } + + private Token identOrKeyword() { + advanceWhile(it -> isAlpha(it) || isDigit(it)); + + return switch (span()) { + case "true", "false" -> Token.LITERAL_BOOL; + case "if" -> Token.IF; + case "debug" -> Token.DEBUG; + case "else" -> Token.ELSE; + case "in" -> Token.IN; + case "for" -> Token.FOR; + case "return" -> Token.RETURN; + case "break" -> Token.BREAK; + case "continue" -> Token.CONTINUE; + case "match" -> Token.MATCH; + default -> Token.IDENT; + }; + } + + private Token number() { + advanceWhile(this::isDigit); + + if (match('.')) { + if (isDigit(peek0())) { + advanceWhile(this::isDigit); + } else { + // don't consume the . in case there are no digits afterwards + cursor--; + } + } + + return Token.LITERAL_NUM; + } + + public String span() { + return source.substring(start, cursor).strip(); + } + + public String peekSpan() { + next(); + var span = span(); + cursor = start; // Reset to where it was before the call to next. + return span; + } + + private void consumeWhitespace() { + boolean inComment = false; + while (!atEnd()) { + if (peek0() == '#') { + inComment = true; + advance(); + } else if (inComment && peek0() == '\n') { + inComment = false; + advance(); + } else if (inComment || Character.isWhitespace(peek0())) { + advance(); + } else { + break; + } + } + } + + public boolean atEnd() { + return cursor >= source.length(); + } + + private char peek0() { + if (atEnd()) { + return '\u0000'; + } + return source.charAt(cursor); + } + + private void advanceWhile(Predicate condition) { + while (condition.test(peek0())) { + advance(); + } + } + + private char advance() { + if (atEnd()) { + throw new IllegalStateException("unexpected end of input"); + } + return source.charAt(cursor++); + } + + private boolean match(String string) { + var cursor = this.cursor; + StringBuilder buffer = new StringBuilder(); + for (int i = 0; i < string.length(); i++) { + if (this.atEnd()) break; + buffer.append(this.advance()); + } + + if (buffer.toString().equals(string)) { + return true; + } + + this.cursor = cursor; + return false; + } + + private boolean match(char c) { + if (atEnd()) { + return false; + } + if (peek0() != c) { + return false; + } + advance(); + return true; + } + + private boolean isAlpha(char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; + } + + private boolean isDigit(char c) { + return c >= '0' && c <= '9'; + } + + private Token unexpected(char c) { + throw new IllegalStateException(String.format("unexpected token '%s' at %d.", c, cursor)); + } + + public String near() { + return this.source.substring(Math.max(this.cursor - 20, 0), this.cursor); + } + + public enum Token { + IDENT, + LITERAL_STR, + LITERAL_NUM, + LITERAL_BOOL, + + // Keywords + IF, + DEBUG, + ELSE, + IN, + NOT_IN, + FOR, + RETURN, + BREAK, + CONTINUE, + MATCH, + + ASSIGN, + + L_PARENTHESES, + R_PARENTHESES, + + COMMA, + DOT, + + INCLUSIVE_INCLUSIVE_RANGE, + INCLUSIVE_EXCLUSIVE_RANGE, + EXCLUSIVE_INCLUSIVE_RANGE, + EXCLUSIVE_EXCLUSIVE_RANGE, + + QUESTION, + COLON, + DOUBLE_COLON, + SEMICOLON, + + NOT, + LAMBDA_FUNCTION_PARAMETERS, + LAMBDA_ARROW, + + GT, + GTE, + LT, + LTE, + EQUAL, + + L_BRACKET, + R_BRACKET, + + L_BRACE, + R_BRACE, + + PLUS, + MINUS, + MUL, + DIV, + POW, + MOD, + + PLUS_ASSIGN, + MINUS_ASSIGN, + MUL_ASSIGN, + DIV_ASSIGN, + POW_ASSIGN, + MOD_ASSIGN, + + AND, + OR, + ; + + public static final Token[] BINARY = new Token[]{ + PLUS, + MINUS, + MUL, + IN, + DIV, + POW, + MOD, + AND, + OR, + INCLUSIVE_INCLUSIVE_RANGE, + INCLUSIVE_EXCLUSIVE_RANGE, + EXCLUSIVE_INCLUSIVE_RANGE, + EXCLUSIVE_EXCLUSIVE_RANGE, + GT, + GTE, + LT, + LTE, + EQUAL, + }; + } + +} + diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/ModuleFile.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/ModuleFile.java new file mode 100644 index 0000000..fb685c1 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/ModuleFile.java @@ -0,0 +1,104 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import java.util.List; +import java.util.Objects; + +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryFileTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.FileTypes; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.value.ImmutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public final class ModuleFile implements FunctionValueFile { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.STRING.forGetter(ModuleFile::name), + BinaryCodec.NULLABLE_EXPRESSION.forGetter(ModuleFile::staticDataExpression), + BinaryCodec.EXPRESSION.forGetter(ModuleFile::script), + ModuleFile::new + ); + + private final String name; + private final Expression script; + private KeyValue staticData; + private final Expression staticDataExpression; + private boolean hasInitialized = false; + + public ModuleFile(String name, Expression staticData, Expression script) { + this.name = name; + this.script = script; + staticDataExpression = staticData; + if (staticData == null) { + this.staticData = ImmutableStructValue.EMPTY; + hasInitialized = true; + } + } + + @Override + public boolean needsInitialization() { + return !hasInitialized; + } + + @Override + public void initialize(Evaluator evaluator) { + if (hasInitialized) return; + var data = ((StructValue) Objects.requireNonNullElse(evaluator, Evaluator.CONSTANT).eval0(staticDataExpression)); + if (data instanceof KeyValue.Mutable mutable) { + this.staticData = mutable.toFullyImmutable(); + } else { + this.staticData = data; + } + } + + public KeyValue staticData() { + return staticData; + } + + private Expression staticDataExpression() { + return this.staticDataExpression; + } + + private Expression script() { + return this.script; + } + + private String name() { + return this.name; + } + + @Override + public boolean canReturnValueBeReturned() { + return true; + } + + @Override + public Value evaluate(Evaluator evaluator) { + evaluator.setInOverlay("static_data", this.staticData); + return evaluator.evaluate(script); + } + + private Value evaluate0(Evaluator evaluator) { + evaluator.setInOverlay("static_data", this.staticData); + return evaluator.evaluate(script); + } + + @Override + public Value apply(Evaluator evaluator, List args) { + if (args.size() == 1) { + var scope = args.getFirst().asMutableStruct(); + return evaluator.pushPop(name, scope, () -> this.evaluate0(evaluator)); + } else { + return evaluator.pushPop(name, () -> this.evaluate0(evaluator)); + } + } + + @Override + public BinaryFileTypeRegistry.Type fileId() { + return FileTypes.MODULE; + } +} + diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/Parser.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/Parser.java new file mode 100644 index 0000000..c8c5195 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/Parser.java @@ -0,0 +1,687 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; +import tech.thatgravyboat.repolib.v2.RepoLoader; +import tech.thatgravyboat.repolib.v2.expl.expression.AccessExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ArrayExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.AssignExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BinaryExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BlockExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.BoolExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.CallExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.DebugExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.expression.FileAccessExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.FileCallExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ForEachExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ForExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.IfExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.InExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.LambdaExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.LambdaIdentityFunction; +import tech.thatgravyboat.repolib.v2.expl.expression.MatchExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.NumExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.RangeExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.ReturnExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StatementExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StrExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.StructExpression; +import tech.thatgravyboat.repolib.v2.expl.expression.UnaryExpression; + +public final class Parser { + private final String source; + private final Lexer lexer; + + public Parser(String source) { + this.source = source; + this.lexer = new Lexer(source); + } + + static class Holder { + + final String name; + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + Optional expression = Optional.empty(); + + Holder(String name) { + this.name = name; + } + + void update(Supplier expressionSupplier) { + if (expression.isPresent()) { + throw new UnsupportedOperationException("Duplicate section " + name + "!"); + } + + expression = Optional.of(expressionSupplier.get()); + } + + Type get() { + return expression.orElseThrow(); + } + + Type get(Supplier defaultExpression) { + return expression.orElseGet(defaultExpression); + } + } + + public StackFile parseFile(RepoLoader loader, String name) { + Holder> meta = new Holder<>("meta"); + Holder> script = new Holder<>("script"); + + while (lexer.peek() == Lexer.Token.IDENT) { + lexer.next(); + switch (lexer.span()) { + case "meta" -> meta.update(this::block); + case "script" -> script.update(this::block); + } + } + + return new StackFile(name, meta.get(), script.get(StackFile.DEFAULT_SCRIPT)); + } + + public ModuleFile parseModuleFile(String name, RepoLoader loader) { + Holder> struct = new Holder<>("static"); + + if (lexer.peek() == Lexer.Token.IDENT && "static".equals(lexer.peekSpan())) { + lexer.next(); + struct.update(() -> { + + if (lexer.peek() == Lexer.Token.IDENT && "eval".equals(lexer.peekSpan())) { + this.lexer.next(); + return this.block(); + } else { + var expr = this.parseUntil(Lexer.Token.SEMICOLON); + if (expr instanceof StructExpression structExpression) { + return structExpression; + } + } + + throw new RuntimeException("Expected struct expression for static data"); + }); + lexer.expect(Lexer.Token.SEMICOLON); + } + + return new ModuleFile(name, struct.get(() -> null), parseExpression()); + } + + public FunctionFile parseFunctionFile(String name, RepoLoader loader) { + var arguments = new ArrayList(); + + if (this.lexer.peek() == Lexer.Token.LAMBDA_FUNCTION_PARAMETERS) { + lexer.expect(Lexer.Token.LAMBDA_FUNCTION_PARAMETERS); + arguments(arguments); + } else { + lexer.expect(Lexer.Token.OR); + } + + return new FunctionFile(name, arguments, parseExpression()); + } + + public Expression parseExpression() { + List> expressions = new ArrayList<>(); + + while (this.lexer.peek() != null) { + var expression = parseUntil(Lexer.Token.SEMICOLON, null); + if (lexer.atEnd()) { + expressions.add(new BlockExpression.LastElement(expression)); + } else { + expressions.add(expression); + if (lexer.peek() == Lexer.Token.SEMICOLON || expression.requiresSemicolon()) { + lexer.expect(Lexer.Token.SEMICOLON); + } + } + } + + if (expressions.size() == 1) { + return expressions.getFirst(); + } else { + return new BlockExpression(expressions); + } + } + + public Expression parseBinaryOrNormalUntil(Lexer.Token... ends) { + return parseBinaryOrNormalUntil(true, ends); + } + + public Expression parseBinaryOrNormalUntil(boolean allowChainedPlus, Lexer.Token... ends) { + var end = join(ends, Lexer.Token.BINARY); + var first = parseUntil(end); + + var peek = lexer.peek(); + return switch (peek) { + case INCLUSIVE_EXCLUSIVE_RANGE, EXCLUSIVE_INCLUSIVE_RANGE, INCLUSIVE_INCLUSIVE_RANGE, + EXCLUSIVE_EXCLUSIVE_RANGE -> { + var type = lexer.next(); + boolean inclusiveStart = + type == Lexer.Token.INCLUSIVE_EXCLUSIVE_RANGE || type == Lexer.Token.INCLUSIVE_INCLUSIVE_RANGE; + boolean inclusiveEnd = + type == Lexer.Token.EXCLUSIVE_INCLUSIVE_RANGE || type == Lexer.Token.INCLUSIVE_INCLUSIVE_RANGE; + var second = parseBinaryOrNormalUntil(end); + + yield new RangeExpression(inclusiveStart, inclusiveEnd, first, second); + } + case IN, NOT_IN -> { + final var negate = this.lexer.peek() == Lexer.Token.NOT_IN; + if (negate) { + this.lexer.expect(Lexer.Token.NOT_IN); + } else { + this.lexer.expect(Lexer.Token.IN); + } + + this.lexer.expect(Lexer.Token.IDENT); + var rightHandAccess = this.memberAccess(null); + var in = new InExpression(rightHandAccess, first); + + yield negate ? new UnaryExpression(UnaryExpression.Op.NOT, in) : in; + } + case PLUS -> { + lexer.next(); + yield new BinaryExpression( + BinaryExpression.Op.PLUS, + first, + allowChainedPlus ? parseBinaryOrNormalUntil(end) : parseUntil(end)); + } + case MINUS -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.MINUS, first, parseUntil(end)); + } + case DIV -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.DIV, first, parseUntil(end)); + } + case MUL -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.MUL, first, parseUntil(end)); + } + case MOD -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.MOD, first, parseUntil(end)); + } + case AND -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.AND, first, parseUntil(end)); + } + case OR -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.OR, first, parseUntil(end)); + } + case GT -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.GT, first, parseUntil(end)); + } + case GTE -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.GTE, first, parseUntil(end)); + } + case LT -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.LT, first, parseUntil(end)); + } + case LTE -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.LTE, first, parseUntil(end)); + } + case EQUAL -> { + lexer.next(); + yield new BinaryExpression(BinaryExpression.Op.EQUAL, first, parseUntil(end)); + } + case null, default -> first; + }; + } + + public Expression memberAccessor(Expression expression, Lexer.Token... end) { + if (expression instanceof AccessExpression access) { + var result = switch (lexer.peek()) { + + case PLUS_ASSIGN -> { + lexer.next(); + yield new AssignExpression( + access, + new BinaryExpression(BinaryExpression.Op.PLUS, access, parseBinaryOrNormalUntil(end))); + } + case MINUS_ASSIGN -> { + lexer.next(); + yield new AssignExpression( + access, + new BinaryExpression(BinaryExpression.Op.MINUS, access, parseBinaryOrNormalUntil(end))); + } + case DIV_ASSIGN -> { + lexer.next(); + yield new AssignExpression( + access, + new BinaryExpression(BinaryExpression.Op.DIV, access, parseBinaryOrNormalUntil(end))); + } + case MUL_ASSIGN -> { + lexer.next(); + yield new AssignExpression( + access, + new BinaryExpression(BinaryExpression.Op.MUL, access, parseBinaryOrNormalUntil(end))); + } + case MOD_ASSIGN -> { + lexer.next(); + yield new AssignExpression( + access, + new BinaryExpression(BinaryExpression.Op.MOD, access, parseBinaryOrNormalUntil(end))); + } + case Lexer.Token.ASSIGN -> { + lexer.next(); + + var value = parseBinaryOrNormalUntil(end); + + yield new AssignExpression(access, value); + } + case null, default -> null; + }; + + if (result != null) { + return result; + } + } + + return switch (lexer.peek()) { + case Lexer.Token.L_PARENTHESES -> { + lexer.next(); + + List> args = new ArrayList<>(); + var next = lexer.peek(); + + if (next != null && next != Lexer.Token.R_PARENTHESES) { + do { + args.add(parseBinaryOrNormalUntil(Lexer.Token.COMMA, Lexer.Token.R_PARENTHESES)); + next = lexer.peek(); + } while (next == Lexer.Token.COMMA && lexer.next() != null); + } + lexer.expect(Lexer.Token.R_PARENTHESES); + + var call = new CallExpression(expression, args); + + if (lexer.peek() == Lexer.Token.DOT) { + lexer.expect(Lexer.Token.DOT); + lexer.next(); + var access = memberAccess(call); + yield memberAccessor(access, end); + } + + yield memberAccessor(call, end); + } + case Lexer.Token.L_BRACE -> { + lexer.next(); + var arg = structExpr(); + + var call = new FileCallExpression(expression, arg); + + if (lexer.peek() == Lexer.Token.DOT) { + lexer.expect(Lexer.Token.DOT); + lexer.next(); + var access = memberAccess(call); + yield memberAccessor(access, end); + } + + yield memberAccessor(call, end); + + } + case null, default -> expression; + }; + } + + public Expression parseUntil(Lexer.Token... end) { + var endings = new HashSet<>(Arrays.asList(end)); + var expression = switch (lexer.next()) { + case DOUBLE_COLON -> memberAccessor(fileExpression(), end); + case IDENT -> memberAccessor(memberAccess(null), end); + case IF -> ifExpr(); + case FOR -> forExpr(); + case LITERAL_STR -> { + var span = lexer.span(); + + if (lexer.peek() == Lexer.Token.NOT_IN || lexer.peek() == Lexer.Token.IN) { + var negate = lexer.peek() == Lexer.Token.NOT_IN; + if (negate) { + lexer.expect(Lexer.Token.NOT_IN); + } else { + lexer.expect(Lexer.Token.IN); + } + lexer.expect(Lexer.Token.IDENT); // The first span must be expected as memberAccess checks for + // the span right away. + var access = memberAccess(null); + var field = span.substring(1, span.length() - 1); + var inExpr = new InExpression(access, new StrExpression(field)); + + yield negate ? new UnaryExpression(UnaryExpression.Op.NOT, inExpr) : inExpr; + } + + yield new StrExpression(span.substring(1, span.length() - 1)); + } + case LITERAL_NUM -> new NumExpression(Double.parseDouble(lexer.span())); + case LITERAL_BOOL -> new BoolExpression(Boolean.parseBoolean(lexer.span())); + case DEBUG -> DebugExpression.INSTANCE; + case L_BRACE -> structExpr(); + case L_BRACKET -> { + ArrayExpression array = new ArrayExpression(new ArrayList<>()); + + while (lexer.peek() != Lexer.Token.R_BRACKET) { + array.list().add(parseBinaryOrNormalUntil(Lexer.Token.COMMA, Lexer.Token.R_BRACKET)); + + if (lexer.peek() == Lexer.Token.COMMA) { + lexer.next(); + } + } + lexer.expect(Lexer.Token.R_BRACKET); + + yield array; + } + case L_PARENTHESES -> { + var expr = parseBinaryOrNormalUntil(join(end, Lexer.Token.R_PARENTHESES)); + lexer.expect(Lexer.Token.R_PARENTHESES); + yield expr; + } + case RETURN -> { + if (lexer.peek() != null && !endings.contains(lexer.peek())) { + yield new ReturnExpression(parseBinaryOrNormalUntil(end)); + } + yield new StatementExpression(StatementExpression.Op.RETURN); + } + case BREAK -> new StatementExpression(StatementExpression.Op.BREAK); + case CONTINUE -> new StatementExpression(StatementExpression.Op.CONTINUE); + case MINUS -> new UnaryExpression(UnaryExpression.Op.NEGATE, parseUntil(end)); + case NOT -> new UnaryExpression(UnaryExpression.Op.NOT, parseUntil(end)); + case MATCH -> matchExpr(); + case LAMBDA_FUNCTION_PARAMETERS -> lambdaExpr(true); + case OR -> lambdaExpr(false); + case null, default -> throw new IllegalStateException("Unexpected value: " + lexer.span()); + }; + + if (endings.contains(lexer.peek())) { + return expression; + } + + if (!expression.requiresSemicolon() && lexer.peek() != Lexer.Token.SEMICOLON) { + return expression; + } + throw new IllegalStateException( + "Expected one of " + endings + " but got " + lexer.peek() + " near " + lexer.near()); + } + + private Lexer.Token[] join(Lexer.Token[] first, Lexer.Token... tokens) { + var newArray = new Lexer.Token[first.length + tokens.length]; + System.arraycopy(first, 0, newArray, 0, first.length); + System.arraycopy(tokens, 0, newArray, first.length, tokens.length); + return newArray; + } + + private void arguments(List arguments) { + while (lexer.peek() != Lexer.Token.LAMBDA_FUNCTION_PARAMETERS) { + lexer.expect(Lexer.Token.IDENT); + var name = lexer.span(); + boolean isOptional; + if (lexer.peek() == Lexer.Token.QUESTION) { + lexer.next(); + isOptional = true; + } else { + isOptional = false; + } + + arguments.add(new LambdaExpression.LambdaArgument(name, arguments.size(), isOptional)); + if (lexer.peek() != Lexer.Token.LAMBDA_FUNCTION_PARAMETERS) { + lexer.expect(Lexer.Token.COMMA); + } + } + + lexer.expect(Lexer.Token.LAMBDA_FUNCTION_PARAMETERS); + } + + private Expression lambdaExpr(boolean withArguments) { + var arguments = new ArrayList(); + if (withArguments) { + arguments(arguments); + } + + var scope = scopeOrSingleStatement(true); + return new LambdaExpression(arguments, new BlockExpression.LastElement(scope)); + } + + private StructExpression structExpr() { + Map> fields = new HashMap<>(); + AccessExpression accessor = null; + + while (lexer.peek() != Lexer.Token.R_BRACE) { + String field; + if (lexer.peek() == Lexer.Token.INCLUSIVE_INCLUSIVE_RANGE) { + this.lexer.expect(Lexer.Token.INCLUSIVE_INCLUSIVE_RANGE); + this.lexer.expect(Lexer.Token.DOT); + this.lexer.expect(Lexer.Token.IDENT); + accessor = this.memberAccess(null); + break; + } + + if (lexer.peek() == Lexer.Token.IDENT) { + lexer.next(); + field = lexer.span(); + } else { + lexer.expect(Lexer.Token.LITERAL_STR); + field = lexer.span(); + field = field.substring(1, field.length() - 1); + } + + if (lexer.peek() == Lexer.Token.COLON) { + lexer.expect(Lexer.Token.COLON); + var expr = parseBinaryOrNormalUntil(Lexer.Token.COMMA, Lexer.Token.R_BRACE); + if (expr instanceof LambdaExpression lambda) { + fields.put(field, new LambdaIdentityFunction(lambda)); + } else { + fields.put(field, expr); + } + } else { + fields.put(field, new AccessExpression(null, new StrExpression(field))); + if (this.lexer.peek() != Lexer.Token.COMMA) { + break; + } + } + + if (lexer.peek() == Lexer.Token.COMMA) { + lexer.next(); + } + } + lexer.expect(Lexer.Token.R_BRACE); + + return new StructExpression(fields, accessor); + } + + private Expression matchExpr() { + final Expression value; + if (lexer.peek() == Lexer.Token.L_PARENTHESES) { + lexer.expect(Lexer.Token.L_PARENTHESES); + value = parseBinaryOrNormalUntil(Lexer.Token.R_PARENTHESES); + lexer.expect(Lexer.Token.R_PARENTHESES); + } else { + value = new BoolExpression(true); + } + + var branches = new LinkedList(); + + lexer.expect(Lexer.Token.L_BRACE); + while (lexer.peek() != Lexer.Token.R_BRACE) { + MatchExpression.MatchCondition condition; + switch (lexer.peek()) { + case GT -> condition = MatchExpression.MatchCondition.GT; + case LT -> condition = MatchExpression.MatchCondition.LT; + case LTE -> condition = MatchExpression.MatchCondition.LTE; + case GTE -> condition = MatchExpression.MatchCondition.GTE; + case ELSE -> condition = MatchExpression.MatchCondition.ELSE; + case null, default -> condition = MatchExpression.MatchCondition.EQUALS; + } + + if (condition != MatchExpression.MatchCondition.EQUALS) { + lexer.next(); + } + + var check = condition == MatchExpression.MatchCondition.ELSE ? null : parseUntil(Lexer.Token.LAMBDA_ARROW); + lexer.expect(Lexer.Token.LAMBDA_ARROW); + var branch = scopeOrSingleStatement(true, Lexer.Token.COMMA); + + lexer.expect(Lexer.Token.COMMA); + branches.add(new MatchExpression.MatchBranch(condition, check, branch)); + } + lexer.expect(Lexer.Token.R_BRACE); + + return new MatchExpression(value, branches); + } + + private Expression ifExpr() { + lexer.expect(Lexer.Token.L_PARENTHESES); + var cond = parseBinaryOrNormalUntil(Lexer.Token.R_PARENTHESES); + lexer.expect(Lexer.Token.R_PARENTHESES); + + Expression thenExpr = scopeOrSingleStatement(); + Expression elseExpr = null; + if (lexer.peek() == Lexer.Token.ELSE) { + lexer.next(); + + if (lexer.peek() == Lexer.Token.IF) { + lexer.next(); + elseExpr = ifExpr(); + } else { + elseExpr = scopeOrSingleStatement(); + } + } + + return new IfExpression(cond, thenExpr, elseExpr); + } + + private Expression forExpr() { + lexer.expect(Lexer.Token.L_PARENTHESES); + + Expression init = parseUntil(Lexer.Token.SEMICOLON, Lexer.Token.COLON); + + if (lexer.peek() == Lexer.Token.COLON && init instanceof AccessExpression access) { + lexer.expect(Lexer.Token.COLON); + + var array = parseBinaryOrNormalUntil(Lexer.Token.R_PARENTHESES); + lexer.expect(Lexer.Token.R_PARENTHESES); + + var body = scopeOrSingleStatement(); + + return new ForEachExpression(access, array, body); + } else { + lexer.expect(Lexer.Token.SEMICOLON); + + Expression cond = parseBinaryOrNormalUntil(Lexer.Token.SEMICOLON); + lexer.expect(Lexer.Token.SEMICOLON); + + Expression incr = parseBinaryOrNormalUntil(Lexer.Token.R_PARENTHESES); + lexer.expect(Lexer.Token.R_PARENTHESES); + + var body = scopeOrSingleStatement(); + + return new ForExpression(init, cond, incr, body); + } + } + + private Expression scopeOrSingleStatement() { + return scopeOrSingleStatement(false); + } + + private Expression scopeOrSingleStatement(Lexer.Token... ends) { + return scopeOrSingleStatement(false, ends); + } + + private Expression scopeOrSingleStatement(boolean allowBinary) { + return scopeOrSingleStatement(allowBinary, Lexer.Token.SEMICOLON); + } + + private Expression scopeOrSingleStatement(boolean allowBinary, Lexer.Token... ends) { + if (lexer.peek() == Lexer.Token.L_BRACE) { + return block(); + } + return allowBinary ? parseBinaryOrNormalUntil(ends) : parseUntil(ends); + } + + private BlockExpression block() { + lexer.expect(Lexer.Token.L_BRACE); + + var block = new BlockExpression(new ArrayList<>()); + + while (lexer.peek() != Lexer.Token.R_BRACE) { + var expression = parseUntil(Lexer.Token.SEMICOLON, Lexer.Token.R_BRACE); + if (lexer.peek() == Lexer.Token.R_BRACE) { + block.exprs().add(new BlockExpression.LastElement(expression)); + } else { + block.exprs().add(expression); + lexer.expect(Lexer.Token.SEMICOLON); + } + } + lexer.expect(Lexer.Token.R_BRACE); + + return block; + } + + private AccessExpression memberAccess(Expression lhs) { + var access = new AccessExpression(lhs, new StrExpression(lexer.span())); + + Lexer.Token next; + loop: + while ((next = lexer.peek()) != null) { + switch (next) { + case Lexer.Token.IDENT -> { + lexer.next(); + access = new AccessExpression(access, new StrExpression(lexer.span())); + } + case Lexer.Token.DOT -> lexer.next(); + case Lexer.Token.L_BRACKET -> { + lexer.next(); + var field = parseBinaryOrNormalUntil(Lexer.Token.R_BRACKET); + lexer.expect(Lexer.Token.R_BRACKET); + access = new AccessExpression(access, field); + } + default -> { + break loop; + } + } + } + + return access; + } + + private FileAccessExpression fileExpression() { + + List> path = new ArrayList<>(); + + Lexer.Token next; + loop: + while ((next = lexer.peek()) != null) { + // System.out.println() + switch (next) { + case Lexer.Token.IDENT -> { + lexer.next(); + path.addLast(new StrExpression(lexer.span())); + lexer.expect(Lexer.Token.DOUBLE_COLON); + } + case Lexer.Token.LT -> { + lexer.next(); + var field = parseUntil(Lexer.Token.GT); + lexer.expect(Lexer.Token.GT); + path.addLast(field); + lexer.expect(Lexer.Token.DOUBLE_COLON); + } + default -> { + break loop; + } + } + } + + return new FileAccessExpression(path); + } + + public String source() { + return source; + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/StackFile.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/StackFile.java new file mode 100644 index 0000000..ee49ed8 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/StackFile.java @@ -0,0 +1,231 @@ +package tech.thatgravyboat.repolib.v2.expl; + +import tech.thatgravyboat.repolib.v2.RepoConfig; +import tech.thatgravyboat.repolib.v2.RepoConstants; +import tech.thatgravyboat.repolib.v2.RepoLoader; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryFileTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.FileTypes; +import tech.thatgravyboat.repolib.v2.binary.TypedFile; +import tech.thatgravyboat.repolib.v2.builtin.Constants; +import tech.thatgravyboat.repolib.v2.expl.expression.Expression; +import tech.thatgravyboat.repolib.v2.expl.expression.NonSerializableExpression; +import tech.thatgravyboat.repolib.v2.expl.value.ArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.ImmutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.LayeredStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.function.Supplier; + +public final class StackFile implements NonSerializableExpression, TypedFile { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.STRING.forGetter(StackFile::name), + BinaryCodec.NULLABLE_EXPRESSION.forGetter(StackFile::metaScript), + BinaryCodec.NULLABLE_EXPRESSION.forGetter(StackFile::script), + StackFile::new + ); + + private static final Expression SCRIPT = Expression.parse("include(\"item\");"); + public static final Supplier> DEFAULT_SCRIPT = () -> SCRIPT; + private final String name; + private final Expression script; + private final Expression metaScript; + private KeyValue meta; + private boolean isInitializing = false; + + public StackFile(String name, Expression meta, Expression script) { + this.name = name; + this.script = script; + this.metaScript = meta; + } + + public boolean needsInitialization() { + return meta == null; + } + + public void init(RepoLoader loader, RepoConstants constants) { + if (this.isInitializing) { + throw new IllegalStateException("Stack is currently being initialized!"); + } + this.isInitializing = true; + + var struct = new MutableStructValue(); + struct.set( + "include", Constants.Builder.FunctionBuilder.create(function -> { + function.arity(1); + function.execute((evaluator, args) -> { + var value = args.getFirst().asString(); + var requested = loader.module(value); + if (requested == null) { + return evaluator.panic("Requested include " + value + " doesn't exist!"); + } + evaluator.pushPop( + value, () -> { + evaluator.evaluate(requested); + return Value.NIL; + }); + + return Value.NIL; + }); + })); + struct.set( + "static", Constants.Builder.FunctionBuilder.create(function -> { + function.arity(1); + function.execute((evaluator, args) -> { + var value = args.getFirst().asString(); + var requested = loader.module(value); + if (requested == null) { + return evaluator.panic("Requested include " + value + " doesn't exist!"); + } + if (requested instanceof ModuleFile module) { + return module.staticData(); + } + + return evaluator.panic("Can't access static data of non module file!"); + }); + })); + struct.set("categories", MutableArrayValue.create()); + var evaluator = new Evaluator(new LayeredStructValue(struct, constants), loader::module); + evaluator.evaluate(this.metaScript); + struct.fields().remove("include"); + this.meta = struct.toFullyImmutable(); + } + + @Override + public Value evaluate(Evaluator evaluator) { + evaluateScript(evaluator); + return Value.NIL; + } + + public KeyValue meta() { + return meta; + } + + public String name() { + return name; + } + + private Expression metaScript() { + return metaScript; + } + private Expression script() { + return script; + } + + public Evaluator createEvaluator(StructValue overrides, Function lookup) { + return createEvaluator(overrides, ImmutableStructValue.EMPTY, RepoConfig.DEFAULT, lookup); + } + + public Evaluator createEvaluator(StructValue overrides, StructValue data, Function lookup) { + return createEvaluator(overrides, data, RepoConfig.DEFAULT, lookup); + } + + public Evaluator createEvaluator( + StructValue overrides, + StructValue data, + RepoConfig config, + Function lookup + ) { + return this.createEvaluator(overrides, data, ImmutableStructValue.EMPTY, config, lookup); + } + + public Evaluator createEvaluator( + StructValue overrides, + StructValue data, + StructValue profile, + RepoConfig config, + Function lookup + ) { + var inputs = new MutableStructValue(); + + for (var entry : overrides) { + inputs.set(entry.getKey(), entry.getValue()); + } + + inputs.set("config", config); + + inputs.set( + "stack", Constants.mutable((builder) -> builder.field( + "lore", MutableArrayValue.create(entries -> new Constants(lore -> { + var section = new AtomicBoolean(); + + lore.function( + "empty", (function) -> { + function.vararg(true); + function.execute(((evaluator, values) -> { + entries.add(ImmutableStructValue.EMPTY); + + return Value.NIL; + })); + }); + lore.function( + "beginSection", (function) -> function.runs(() -> { + if (section.get()) { + entries.add(ImmutableStructValue.EMPTY); + } + section.set(false); + })); + lore.function( + "endSection", (function) -> function.runs(() -> { + if (section.get()) { + entries.add(ImmutableStructValue.EMPTY); + } + section.set(false); + })); + lore.function("clear", (function) -> function.runs(entries::clear)); + lore.function( + "add", function -> { + function.arity(1); + function.executeSimpleVoid(args -> { + section.set(true); + entries.add(args.getFirst()); + }); + }); + lore.function( + "addAll", function -> { + function.arity(1); + function.executeVoid((evaluator, args) -> { + var values = ArrayValue.flatten(args); + if (values.isEmpty()) { + return; + } + section.set(true); + entries.addAll(values); + }); + }); + + })))).toMutable()); + inputs.set("data", data); + inputs.set("categories", MutableArrayValue.create()); + inputs.set("profile", profile); + inputs.set("meta", this.meta); + + return new Evaluator(inputs, lookup); + } + + public StructValue evaluateScript(Evaluator evaluator) { + evaluator.evaluate(script); + + return evaluator.defaults.get("stack") instanceof StructValue value ? value : ImmutableStructValue.EMPTY; + } + + public KeyValue evaluate(StructValue overrides, Function lookup) { + return evaluateScript(createEvaluator(overrides, lookup)); + } + + @Override + public BinaryFileTypeRegistry.Type fileId() { + return FileTypes.STACK; + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/AccessExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/AccessExpression.java new file mode 100644 index 0000000..6bb7340 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/AccessExpression.java @@ -0,0 +1,52 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.Objects; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.ArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record AccessExpression(@Nullable Expression lhs, Expression field) + implements Expression { + + public static BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.NULLABLE_EXPRESSION.forGetter(AccessExpression::lhs), + BinaryCodec.EXPRESSION.forGetter(AccessExpression::field), + AccessExpression::new); + + @Override + public @NotNull String toString() { + return lhs + "." + field; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.ACCESS; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var lhs = lhs(); + var field = evaluator.eval0(field()); + + if (lhs == null) { + return evaluator.scope().get(field.asString()); + } + var left = evaluator.eval0(lhs); + if (left instanceof ArrayValue arrayValue && field instanceof NumValue(double value)) { + return arrayValue.get((int) value); + } + if (left instanceof KeyValue keyValue) { + return Objects.requireNonNullElse(keyValue.get(field.asString()), Value.NIL); + } + + throw new Evaluator.Panic("Unable to access property " + field() + " of non key/value " + lhs); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ArrayExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ArrayExpression.java new file mode 100644 index 0000000..08a16c4 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ArrayExpression.java @@ -0,0 +1,41 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.ArrayList; +import java.util.Collection; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record ArrayExpression(Collection> list) implements Expression { + + public static final BinaryCodec CODEC = + BinaryCodec.EXPRESSION.collection().mapped(ArrayExpression::new, ArrayExpression::list); + + @Override + public @NotNull String toString() { + return list.toString(); + } + + + @Override + public Value evaluate(Evaluator evaluator) { + var array = MutableArrayValue.create(new ArrayList<>()); + + for (var expression : list) { + array.add(evaluator.eval0(expression)); + } + + return array; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.ARRAY; + } + + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/AssignExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/AssignExpression.java new file mode 100644 index 0000000..a3c638f --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/AssignExpression.java @@ -0,0 +1,45 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record AssignExpression(AccessExpression lhs, Expression value) implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + AccessExpression.CODEC.forGetter(AssignExpression::lhs), + BinaryCodec.EXPRESSION.forGetter(AssignExpression::value), + AssignExpression::new); + + @Override + public @NotNull String toString() { + return lhs + " = " + value; + } + + @Override + public boolean requiresSemicolon() { + return value.requiresSemicolon(); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.ASSIGN; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var access = lhs(); + final Value field; + if (access.lhs() == null) { + field = evaluator.scope(); + } else { + field = evaluator.eval0(access.lhs()); + } + + return evaluator.set(field, evaluator.eval0(access.field()).asString(), evaluator.eval0(value())); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BinaryExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BinaryExpression.java new file mode 100644 index 0000000..ecee50b --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BinaryExpression.java @@ -0,0 +1,180 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.io.IOException; +import java.util.Objects; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.DecoderContext; +import tech.thatgravyboat.repolib.v2.binary.ExpressionCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record BinaryExpression(Op op, Expression first, Expression second) + implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + Op.CODEC.forGetter(BinaryExpression::op), + BinaryCodec.EXPRESSION.forGetter(BinaryExpression::first), + BinaryCodec.EXPRESSION.forGetter(BinaryExpression::second), + BinaryExpression::new); + + @Override + public Value evaluate(Evaluator evaluator) { + return op.performRaw(evaluator, first, second); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.BINARY; + } + + public static BinaryExpression decode(DecoderContext buffer) throws IOException { + return new BinaryExpression( + Op.CODEC.decode(buffer), + ExpressionCodec.read(buffer), + ExpressionCodec.read(buffer)); + } + + public enum Op { + PLUS { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + + if (first instanceof NumValue(double aNum) && second instanceof NumValue(double bNum)) { + return new NumValue(aNum + bNum); + } else if (first instanceof StrValue(String aStr) && second instanceof StrValue(String bStr)) { + return new StrValue(aStr + bStr); + } else if (first instanceof MutableArrayValue array) { + array.add(second); + return first; + } + + return evaluator.panic("Unable to add " + second.type() + " to " + first.type()); + } + + }, + MINUS { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return new NumValue(a - b); + } + }, + MUL { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return new NumValue(a * b); + } + + }, + DIV { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return new NumValue(a / b); + } + + }, + MOD { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return new NumValue(a % b); + } + + }, + POW { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return new NumValue(Math.pow(a, b)); + } + + }, + AND { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + return BoolValue.wrap(first.asBoolean() && second.asBoolean()); + } + + @Override + public Value performRaw(Evaluator evaluator, Expression first, Expression second) { + return BoolValue.wrap(evaluator.eval0(first).asBoolean() && evaluator.eval0(second).asBoolean()); + } + + }, + OR { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + return BoolValue.wrap(first.asBoolean() || second.asBoolean()); + } + + @Override + public Value performRaw(Evaluator evaluator, Expression first, Expression second) { + return BoolValue.wrap(evaluator.eval0(first).asBoolean() || + evaluator.eval0(second).asBoolean()); + } + + }, + GT { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return BoolValue.wrap(a > b); + } + }, + GTE { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return BoolValue.wrap(a >= b); + } + }, + LT { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return BoolValue.wrap(a < b); + } + }, + LTE { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + var a = first.asNumber(); + var b = second.asNumber(); + return BoolValue.wrap(a <= b); + } + + }, + EQUAL { + @Override + public Value perform(Evaluator evaluator, Value first, Value second) { + return BoolValue.wrap(Objects.equals(first, second)); + } + + }; + + public static final BinaryCodec CODEC = BinaryCodec.enumCodec(values()); + + public abstract Value perform(Evaluator evaluator, Value first, Value second); + + public Value performRaw(Evaluator evaluator, Expression first, Expression second) { + return perform(evaluator, evaluator.eval0(first), evaluator.eval0(second)); + } + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BlockExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BlockExpression.java new file mode 100644 index 0000000..e416cfd --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BlockExpression.java @@ -0,0 +1,68 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.Collection; +import java.util.stream.Collectors; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record BlockExpression(Collection> exprs) implements Expression { + public static final BinaryCodec CODEC = + BinaryCodec.EXPRESSION.collection().mapped(BlockExpression::new, BlockExpression::exprs); + + @Override + public @NotNull String toString() { + if (exprs.isEmpty()) { + return "{}"; + } + return "{" + exprs.stream().map(Expression::toString).collect(Collectors.joining("; ")) + "}"; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.BLOCK; + } + + @Override + public Value evaluate(Evaluator evaluator) { + Value last = Value.NIL; + for (var expr : exprs()) { + if (expr.canReturnValueBeReturned()) { + last = evaluator.eval0(expr); + } else { + evaluator.eval0(expr); + } + } + + return last; + } + + public record LastElement(Expression expression) implements Expression { + public static final BinaryCodec CODEC = + BinaryCodec.EXPRESSION.mapped(LastElement::new, LastElement::expression); + + @Override + public Value evaluate(Evaluator evaluator) { + return evaluator.eval0(this.expression); + } + + @Override + public boolean canReturnValueBeReturned() { + return true; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.BLOCK_LAST_ELEMENT; + } + + } + + @Override + public boolean canReturnValueBeReturned() { + return true; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BoolExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BoolExpression.java new file mode 100644 index 0000000..d362b41 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/BoolExpression.java @@ -0,0 +1,30 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record BoolExpression(boolean value) implements Expression { + + public static final BinaryCodec CODEC = + BinaryCodec.BOOLEAN.mapped(BoolExpression::new, BoolExpression::value); + + @Override + public @NotNull String toString() { + return Boolean.toString(value); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.BOOLEAN; + } + + @Override + public Value evaluate(Evaluator evaluator) { + return BoolValue.wrap(this.value); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/CallExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/CallExpression.java new file mode 100644 index 0000000..9349e71 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/CallExpression.java @@ -0,0 +1,44 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.stream.Collectors; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record CallExpression(Expression lhs, Collection> args) implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.EXPRESSION.forGetter(CallExpression::lhs), + BinaryCodec.EXPRESSION.collection().forGetter(CallExpression::args), + CallExpression::new); + + @Override + public @NotNull String toString() { + return lhs + "(" + args.stream().map(Expression::toString).collect(Collectors.joining(", ")) + ")"; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.CALL; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var left = evaluator.eval0(lhs()); + + var args = new ArrayList(); + for (var arg : args()) { + args.add(evaluator.eval0(arg)); + } + + return evaluator.pushPop(lhs().toString(), () -> left.asFunctionValue().apply(evaluator, args)); + } + + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/DebugExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/DebugExpression.java new file mode 100644 index 0000000..991200d --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/DebugExpression.java @@ -0,0 +1,26 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public final class DebugExpression implements Expression { + + public static DebugExpression INSTANCE = new DebugExpression(); + + public static final BinaryCodec CODEC = BinaryCodec.unit(INSTANCE); + + private DebugExpression() {} + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.DEBUG; + } + + @Override + public Value evaluate(Evaluator evaluator) { + return Value.NIL; // Set breakpoint here + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/Expression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/Expression.java new file mode 100644 index 0000000..6b0104c --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/Expression.java @@ -0,0 +1,51 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + + +import tech.thatgravyboat.repolib.v2.RepoLoader; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.FunctionFile; +import tech.thatgravyboat.repolib.v2.expl.ModuleFile; +import tech.thatgravyboat.repolib.v2.expl.Parser; +import tech.thatgravyboat.repolib.v2.expl.StackFile; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public sealed interface Expression> + permits AccessExpression, ArrayExpression, AssignExpression, BinaryExpression, BlockExpression, + BlockExpression.LastElement, BoolExpression, CallExpression, DebugExpression, FileAccessExpression, + FileCallExpression, ForEachExpression, ForExpression, IfExpression, InExpression, LambdaExpression, + LambdaIdentityFunction, MatchExpression, NonSerializableExpression, NumExpression, RangeExpression, + ReturnExpression, StatementExpression, StrExpression, StructExpression, UnaryExpression { + + static StackFile parseFileOrThrow(RepoLoader loader, String source, String name) { + return new Parser(source).parseFile(loader, name); + } + + static ModuleFile parseModuleOrThrow(RepoLoader loader, String name, String source) { + return new Parser(source).parseModuleFile(name, loader); + } + + static FunctionFile parseFunctionOrThrow(RepoLoader loader, String name, String source) { + return new Parser(source).parseFunctionFile(name, loader); + } + + static Expression parse(String source) { + return new Parser(source).parseExpression(); + } + + default boolean requiresSemicolon() { + return true; + } + + default boolean canReturnValueBeReturned() { + return false; + } + + ExpressionTypeRegistry.Type expressionId(); + + Value evaluate(Evaluator evaluator); + default Value evaluateStructValue(Evaluator evaluator, MutableStructValue self) { + return this.evaluate(evaluator); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/FileAccessExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/FileAccessExpression.java new file mode 100644 index 0000000..ec7d934 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/FileAccessExpression.java @@ -0,0 +1,45 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.ArrayList; +import java.util.Collection; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record FileAccessExpression(Collection> path) implements Expression { + + public static final BinaryCodec CODEC = + BinaryCodec.EXPRESSION.collection().mapped(FileAccessExpression::new, FileAccessExpression::path); + + @Override + public @NotNull String toString() { + return path.toString(); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.FILE_ACCESS; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var list = new ArrayList(); + + for (var expr : path()) { + list.add(evaluator.eval0(expr).asString()); + } + + var result = evaluator.getFileAccess(String.join("/", list)); + + if (result == null) { + throw new Evaluator.Panic("failed to find " + String.join("/", list)); + } + + return result; + } + + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/FileCallExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/FileCallExpression.java new file mode 100644 index 0000000..d2dc4bd --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/FileCallExpression.java @@ -0,0 +1,40 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + + +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record FileCallExpression(Expression access, StructExpression expr) + implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.EXPRESSION.forGetter(FileCallExpression::access), + StructExpression.CODEC.forGetter(FileCallExpression::expr), + FileCallExpression::new); + + @Override + public @NotNull String toString() { + return access + " " + expr; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var function = evaluator.eval0(access).asStructuredFunction(); + var structValue = expr.evaluate(evaluator); + + return function.apply(evaluator, structValue); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.FILE_CALL; + } + + +} + diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ForEachExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ForEachExpression.java new file mode 100644 index 0000000..6e82711 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ForEachExpression.java @@ -0,0 +1,57 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.ExecutionExceptions; +import tech.thatgravyboat.repolib.v2.expl.value.NilValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record ForEachExpression(AccessExpression field, Expression array, Expression body) + implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + AccessExpression.CODEC.forGetter(ForEachExpression::field), + BinaryCodec.EXPRESSION.forGetter(ForEachExpression::array), + BinaryCodec.EXPRESSION.forGetter(ForEachExpression::field), + ForEachExpression::new); + + @Override + public Value evaluate(Evaluator evaluator) { + var values = evaluator.eval0(array).asArray(); + + try { + values.forEach(value -> { + try { + evaluator.pushPop( + this.toString(), () -> { + evaluator.eval0(new AssignExpression(field, value)); + return evaluator.eval0(body); + }); + } catch (ExecutionExceptions.Continue ignored) { + } + }); + } catch (ExecutionExceptions.Break ignored) { + } + return NilValue.NIL; + } + + @Override + public @NotNull String toString() { + return "for (%s : %s) %s".formatted(field, array, body); + } + + @Override + public boolean requiresSemicolon() { + return false; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.FOR_EACH; + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ForExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ForExpression.java new file mode 100644 index 0000000..35c29e4 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ForExpression.java @@ -0,0 +1,81 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.ExecutionExceptions; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record ForExpression( + @Nullable Expression init, @Nullable Expression cond, @Nullable Expression incr, Expression body +) implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.EXPRESSION.nullable().forGetter(ForExpression::init), + BinaryCodec.EXPRESSION.nullable().forGetter(ForExpression::cond), + BinaryCodec.EXPRESSION.nullable().forGetter(ForExpression::incr), + BinaryCodec.EXPRESSION.forGetter(ForExpression::body), + ForExpression::new); + + @Override + public @NotNull String toString() { + return "for (%s;%s;%s) %s".formatted( + init == null ? "" : init, + cond == null ? "" : cond, + incr == null ? "" : incr, + body); + } + + @Override + public boolean requiresSemicolon() { + return false; + } + + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.FOR; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var init = init(); + if (init != null) { + evaluator.eval0(init); + } + + int iteration = 0; + + while (true) { + if (iteration > Evaluator.MAX_ITERATIONS) { + throw new Evaluator.Panic("For loop has iterated more than %d times, aborting to prevent infinite loop.".formatted(Evaluator.MAX_ITERATIONS)); + } + + var cond = cond(); + if (cond != null && !evaluator.eval0(cond).asBooleanConversion()) { + break; + } + + try { + evaluator.pushPop("for (...; " + cond() + "; ...)", () -> evaluator.eval0(body())); + } catch (ExecutionExceptions.Break e) { + break; + } catch (ExecutionExceptions.Continue e) { + // do nothing, just continue to the next iteration. + } + + var incr = incr(); + if (incr != null) { + evaluator.eval0(incr); + } + + iteration++; + } + + return Value.NIL; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/IfExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/IfExpression.java new file mode 100644 index 0000000..ab546d1 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/IfExpression.java @@ -0,0 +1,51 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record IfExpression(Expression cond, Expression thenExpr, @Nullable Expression elseExpr) + implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.EXPRESSION.forGetter(IfExpression::cond), + BinaryCodec.EXPRESSION.forGetter(IfExpression::thenExpr), + BinaryCodec.EXPRESSION.nullable().forGetter(IfExpression::elseExpr), + IfExpression::new); + + @Override + public @NotNull String toString() { + if (elseExpr == null) { + return String.format("if (%s) %s", cond, thenExpr); + } + return String.format("if (%s) %s else %s", cond, thenExpr, elseExpr); + } + + @Override + public boolean requiresSemicolon() { + return false; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.IF; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var condition = evaluator.eval0(cond()).asBooleanConversion(); + + if (condition) { + return evaluator.pushPop("if (" + cond() + ")", () -> evaluator.eval0(thenExpr())); + } else if (elseExpr() != null) { + return evaluator.pushPop("if (" + cond() + ") { ... } else", () -> evaluator.eval0(elseExpr())); + } + + return Value.NIL; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/InExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/InExpression.java new file mode 100644 index 0000000..4799fac --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/InExpression.java @@ -0,0 +1,32 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.KeyValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record InExpression(AccessExpression holder, Expression field) implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + AccessExpression.CODEC.forGetter(InExpression::holder), + BinaryCodec.EXPRESSION.forGetter(InExpression::field), + InExpression::new); + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.IN; + } + + @Override + public Value evaluate(Evaluator evaluator) { + var holder = holder().evaluate(evaluator); + String field = evaluator.eval0(field()).asString(); + + return holder.containsValue(field); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/LambdaExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/LambdaExpression.java new file mode 100644 index 0000000..b882321 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/LambdaExpression.java @@ -0,0 +1,95 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.Collection; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.FunctionValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record LambdaExpression( + Collection arguments, Expression body, Value function, boolean requiresSemicolon +) implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + LambdaArgument.CODEC.collection().forGetter(LambdaExpression::arguments), + BinaryCodec.EXPRESSION.forGetter(LambdaExpression::body), + LambdaExpression::new); + + public LambdaExpression(Collection arguments, Expression body) { + this(arguments, body, null); + } + + public LambdaExpression(Collection arguments, Expression body, Value self) { + this( + arguments, body, FunctionValue.builder(builder -> { + int min = 0; + int max = 0; + boolean hasEncounteredOptional = false; + + for (var argument : arguments) { + max++; + + if (argument.optional) { + hasEncounteredOptional = true; + continue; + } + + if (hasEncounteredOptional) { + throw new IllegalStateException("Optional before required argument!"); + } + + min++; + } + + if (min != max) { + builder.arity(min, max); + } else { + builder.arity(min); + } + + builder.execute((evaluator, values) -> evaluator.pushPop( + "lambda", () -> { + if (self != null) { + evaluator.set("self", self); + } + + for (var argument : arguments) { + if (argument.optional() && argument.position() >= values.size()) { + continue; + } + evaluator.set(argument.name, values.get(argument.position)); + } + + return evaluator.evaluate(body); + })); + }), body.requiresSemicolon()); + } + + + @Override + public Value evaluate(Evaluator _evaluator) { + return function; + } + + @Override + public boolean canReturnValueBeReturned() { + return true; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.LAMBDA; + } + + public record LambdaArgument(String name, int position, boolean optional) { + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.STRING.forGetter(LambdaArgument::name), + BinaryCodec.INT.forGetter(LambdaArgument::position), + BinaryCodec.BOOLEAN.forGetter(LambdaArgument::optional), + LambdaArgument::new); + + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/LambdaIdentityFunction.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/LambdaIdentityFunction.java new file mode 100644 index 0000000..96d9be5 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/LambdaIdentityFunction.java @@ -0,0 +1,30 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record LambdaIdentityFunction(LambdaExpression expression) + implements Expression { + + public static final BinaryCodec CODEC = + LambdaExpression.CODEC.mapped(LambdaIdentityFunction::new, LambdaIdentityFunction::expression); + + @Override + public Value evaluate(Evaluator evaluator) { + return null; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.LAMBDA_IDENTITY; + } + + @Override + public Value evaluateStructValue(Evaluator evaluator, MutableStructValue self) { + return new LambdaExpression(this.expression.arguments(), this.expression.body(), self).function(); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/MatchExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/MatchExpression.java new file mode 100644 index 0000000..6ac3d2d --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/MatchExpression.java @@ -0,0 +1,103 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.Collection; +import org.jetbrains.annotations.Nullable; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record MatchExpression(Expression value, Collection branches) + implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.EXPRESSION.forGetter(MatchExpression::value), + MatchBranch.CODEC.collection().forGetter(MatchExpression::branches), + MatchExpression::new); + + @Override + public Value evaluate(Evaluator evaluator) { + var value = evaluator.eval0(this.value); + + for (var branch : branches) { + if (branch.condition.compare(evaluator, value, evaluator.eval0(branch.check))) { + return evaluator.eval0(branch.branch); + } + } + + return Value.NIL; + } + + @Override + public boolean requiresSemicolon() { + return false; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.MATCH; + } + + public record MatchBranch(MatchCondition condition, @Nullable Expression check, Expression branch) { + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + MatchCondition.CODEC.forGetter(MatchBranch::condition), + BinaryCodec.EXPRESSION.nullable().forGetter(MatchBranch::check), + BinaryCodec.EXPRESSION.forGetter(MatchBranch::branch), + MatchBranch::new); + } + + public enum MatchCondition { + EQUALS { + @Override + public boolean compare(Evaluator evaluator, Value value, Value testValue) { + return value.equals(testValue); + } + }, + ELSE { + @Override + public boolean compare(Evaluator evaluator, Value value, Value testValue) { + return true; + } + }, + LT { + @Override + public boolean compare(Evaluator evaluator, Value value, Value testValue) { + var first = value.asNumber(); + var second = testValue.asNumber(); + return first < second; + } + }, + GT { + @Override + public boolean compare(Evaluator evaluator, Value value, Value testValue) { + var first = value.asNumber(); + var second = testValue.asNumber(); + return first > second; + } + }, + LTE { + @Override + public boolean compare(Evaluator evaluator, Value value, Value testValue) { + var first = value.asNumber(); + var second = testValue.asNumber(); + return first <= second; + } + }, + GTE { + @Override + public boolean compare(Evaluator evaluator, Value value, Value testValue) { + var first = value.asNumber(); + var second = testValue.asNumber(); + return first >= second; + } + }, + ; + + public static final BinaryCodec CODEC = BinaryCodec.enumCodec(values()); + + + public abstract boolean compare(Evaluator evaluator, Value value, Value testValue); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/NonSerializableExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/NonSerializableExpression.java new file mode 100644 index 0000000..379673e --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/NonSerializableExpression.java @@ -0,0 +1,10 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; + +public non-sealed interface NonSerializableExpression extends Expression { + @Override + default ExpressionTypeRegistry.Type expressionId() { + throw new UnsupportedOperationException("Unable to serialize " + this.getClass().getSimpleName()); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/NumExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/NumExpression.java new file mode 100644 index 0000000..9f598c4 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/NumExpression.java @@ -0,0 +1,30 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record NumExpression(double value) implements Expression { + + public static final BinaryCodec CODEC = + BinaryCodec.DOUBLE.mapped(NumExpression::new, NumExpression::value); + + @Override + public @NotNull String toString() { + return String.valueOf(value); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.NUMBER; + } + + @Override + public Value evaluate(Evaluator evaluator) { + return new NumValue(this.value); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/RangeExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/RangeExpression.java new file mode 100644 index 0000000..9c347c9 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/RangeExpression.java @@ -0,0 +1,48 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.LinkedList; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record RangeExpression(boolean inclusiveStart, boolean inclusiveEnd, Expression from, Expression to) + implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.BYTE.forGetter(owner -> { + byte set = (byte) (owner.inclusiveStart ? 1 : 0); + if (owner.inclusiveEnd) { + set |= 2; + } + return set; + }), + BinaryCodec.EXPRESSION.forGetter(RangeExpression::from), + BinaryCodec.EXPRESSION.forGetter(RangeExpression::to), + (packed, from, to) -> new RangeExpression((packed & 1) == 1, (packed & 2) == 2, from, to)); + + @Override + public Value evaluate(Evaluator evaluator) { + var number = evaluator.eval0(from).asNumber(); + var second = evaluator.eval0(to).asNumber(); + + var array = new LinkedList(); + var range = (second - number - (inclusiveEnd ? 0 : 1)); + if (range < 0) { + return evaluator.panic("Num range start smaller then end!"); + } + for (int i = inclusiveStart ? 0 : 1; i <= range; i++) { + array.add(new NumValue(number + i)); + } + return MutableArrayValue.create(array); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.RANGE; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ReturnExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ReturnExpression.java new file mode 100644 index 0000000..74936dc --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/ReturnExpression.java @@ -0,0 +1,25 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.ExecutionExceptions; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record ReturnExpression(Expression retExpr) implements Expression { + + public static final BinaryCodec CODEC = + BinaryCodec.EXPRESSION.mapped(ReturnExpression::new, ReturnExpression::retExpr); + + @Override + public Value evaluate(Evaluator evaluator) { + throw new ExecutionExceptions.Return(evaluator.eval0(retExpr)); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.RETURN; + } + +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StatementExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StatementExpression.java new file mode 100644 index 0000000..9ba5171 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StatementExpression.java @@ -0,0 +1,50 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import java.util.Locale; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.ExecutionExceptions; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record StatementExpression(Op op) implements Expression { + + public static final BinaryCodec CODEC = + Op.CODEC.mapped(StatementExpression::new, StatementExpression::op); + + @Override + public @NotNull String toString() { + return op.name().toLowerCase(Locale.ROOT); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.STATEMENT; + } + + public enum Op { + RETURN(ExecutionExceptions.RETURN), + BREAK(ExecutionExceptions.BREAK), + CONTINUE(ExecutionExceptions.CONTINUE), + ; + + private final RuntimeException exception; + + Op(RuntimeException exception) { + this.exception = exception; + } + + public Value raise() { + throw exception; + } + + public static final BinaryCodec CODEC = BinaryCodec.enumCodec(values()); + } + + @Override + public Value evaluate(Evaluator evaluator) { + return this.op.raise(); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StrExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StrExpression.java new file mode 100644 index 0000000..3db5e89 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StrExpression.java @@ -0,0 +1,30 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record StrExpression(String value) implements Expression { + + public static final BinaryCodec CODEC = + BinaryCodec.STRING.mapped(StrExpression::new, StrExpression::value); + + @Override + public @NotNull String toString() { + return "\"" + value + "\""; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.STRING; + } + + @Override + public Value evaluate(Evaluator evaluator) { + return new StrValue(this.value); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StructExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StructExpression.java new file mode 100644 index 0000000..6c8c67a --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/StructExpression.java @@ -0,0 +1,55 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.LayeredStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record StructExpression(Map> fields, @Nullable AccessExpression spread) + implements Expression { + + public static final BinaryCodec CODEC = BinaryRecordBuilder.of( + BinaryCodec.map(BinaryCodec.STRING, BinaryCodec.EXPRESSION).forGetter(StructExpression::fields), + AccessExpression.CODEC.nullable().forGetter(StructExpression::spread), + StructExpression::new); + + @Override + public @NotNull String toString() { + return fields.entrySet() + .stream() + .map(e -> e.getKey() + ": " + e.getValue()) + .collect(Collectors.joining(", ", "{", "}")); + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.STRUCT; + } + + @Override + public StructValue evaluate(Evaluator evaluator) { + var fields = new MutableStructValue(new HashMap<>()); + + for (var entry : fields().entrySet()) { + fields.set(entry.getKey(), entry.getValue().evaluateStructValue(evaluator, fields)); + } + + if (spread() != null) { + return new LayeredStructValue(fields, evaluator.eval0(spread()).asStruct()); + } + + return fields; + + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/UnaryExpression.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/UnaryExpression.java new file mode 100644 index 0000000..df83f13 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/expression/UnaryExpression.java @@ -0,0 +1,58 @@ +package tech.thatgravyboat.repolib.v2.expl.expression; + +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.binary.BinaryCodec; +import tech.thatgravyboat.repolib.v2.binary.BinaryRecordBuilder; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypeRegistry; +import tech.thatgravyboat.repolib.v2.binary.ExpressionTypes; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public record UnaryExpression(Op op, Expression rhs) implements Expression { + + public static BinaryCodec CODEC = BinaryRecordBuilder.of( + Op.CODEC.forGetter(UnaryExpression::op), + BinaryCodec.EXPRESSION.forGetter(UnaryExpression::rhs), + UnaryExpression::new); + + @Override + public @NotNull String toString() { + return switch (op) { + case NEGATE -> "-" + rhs; + case NOT -> "!" + rhs; + }; + } + + @Override + public ExpressionTypeRegistry.Type expressionId() { + return ExpressionTypes.UNARY; + } + + @Override + public Value evaluate(Evaluator evaluator) { + return op().evaluate(evaluator.eval0(rhs())); + + } + + public enum Op { + NEGATE { + @Override + public Value evaluate(Value value) { + return new NumValue(-value.asNumber()); + } + }, + NOT { + @Override + public Value evaluate(Value value) { + return BoolValue.wrap(!value.asBooleanConversion()); + } + }, + ; + + public abstract Value evaluate(Value value); + public static final BinaryCodec CODEC = BinaryCodec.enumCodec(values()); + } +} + diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ArrayValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ArrayValue.java new file mode 100644 index 0000000..1f1fbf9 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ArrayValue.java @@ -0,0 +1,232 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import tech.thatgravyboat.repolib.v2.builtin.Constants; + +import java.util.LinkedList; +import java.util.List; + +public non-sealed interface ArrayValue extends Value, KeyValue, Iterable { + public static String prettyPrint(ArrayValue array, String prefix, int depth) { + var values = getValues(array); + var stringBuilder = new StringBuilder(); + + stringBuilder.append("[").append("\n"); + for (var value : values) { + stringBuilder.append(prefix).append(" ").append(Value.prettyPrint(value, prefix, depth + 1)).append(",\n"); + } + stringBuilder.append(prefix).append("]"); + + return stringBuilder.toString(); + } + + @Override + default String type() { + return "array"; + } + + static List flatten(List values) { + List list = new LinkedList<>(); + for (var value : values) { + if (value instanceof ArrayValue array) { + list.addAll(getValues(array)); + } else { + list.add(value); + } + } + return list; + } + + static List getValues(ArrayValue array) { + List list = new LinkedList<>(); + array.forEach(list::add); + return list; + } + + static List flatten(ArrayValue array) { + return flatten(getValues(array)); + } + + static Value get(List entries, int index) { + if ((index < 0 && -index > entries.size()) || (index >= entries.size())) { + return Value.NIL; + } + + return entries.get(Math.floorMod(index, entries.size())); + } + + static KeyValue.Mutable createPrototype(List entries, boolean mutable, StructValue prototype) { + var prototypes = prototype.iterator(); + + return new KeyValue.Mutable.Forwarding() { + final KeyValue.Mutable base = Constants.mutable(builder -> { + prototypes.forEachRemaining(entry -> builder.field(entry.getKey(), entry.getValue())); + + builder.function("get", function -> { + function.arity(1); + function.execute((evaluator, args) -> ArrayValue.get(entries, (int) args.getFirst().asNumber())); + }); + + builder.function("contains", function -> { + function.arity(1); + function.execute((evaluator, args) -> BoolValue.wrap(entries.contains(args.getFirst()))); + }); + + builder.function("chunked", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var amount = values.getFirst().asNumber(); + + var array = MutableArrayValue.create(); + + var current = MutableArrayValue.create(); + for (var entry : entries) { + if (current.entries().size() >= amount) { + array.add(current); + current = MutableArrayValue.create(); + } + current.add(entry); + } + + if (!current.entries().isEmpty()) { + array.add(current); + } + + return array; + }); + }); + + builder.function("forEach", function -> { + function.arity(1); + function.executeVoid((evaluator, values) -> { + var lambda = values.getFirst().asLambda(); + if (lambda.arityMin() == 1 || (lambda.vararg() && lambda.arityMin() >= 1)) { + for (var entry : entries) { + lambda.apply(evaluator, List.of(entry)); + } + } else { + evaluator.panic("Unable to invoke for each lambda, no matching entry found."); + } + }); + }); + builder.function("forEachIndexed", function -> { + function.arity(1); + function.executeVoid((evaluator, values) -> { + var lambda = values.getFirst().asLambda(); + if (lambda.arityMin() == 2 || (lambda.vararg() && lambda.arityMin() >= 2)) { + for (var i = 0; i < entries.size(); i++) { + lambda.apply(evaluator, List.of(entries.get(i), new NumValue(i))); + } + } else { + evaluator.panic("Unable to invoke for each lambda, no matching entry found."); + } + }); + }); + + + builder.function("map", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var result = MutableArrayValue.create(); + + var lambda = values.getFirst().asLambda(); + if (lambda.arityMin() == 1 || (lambda.vararg() && lambda.arityMin() >= 1)) { + for (var entry : entries) { + result.add(lambda.apply(evaluator, List.of(entry))); + } + } else { + evaluator.panic("Unable to invoke for each lambda, no matching entry found."); + } + + return result; + }); + }); + builder.function("mapIndexed", function -> { + function.arity(1); + function.execute((evaluator, values) -> { + var result = MutableArrayValue.create(); + + var lambda = values.getFirst().asLambda(); + if (lambda.arityMin() == 2 || (lambda.vararg() && lambda.arityMin() >= 2)) { + for (var i = 0; i < entries.size(); i++) { + result.add(lambda.apply(evaluator, List.of(entries.get(i), new NumValue(i)))); + } + } else { + evaluator.panic("Unable to invoke for each lambda, no matching entry found."); + } + + return result; + }); + }); + + if (!mutable) { + return; + } + builder.function( + "add", function -> { + function.arity(1); + function.executeSimpleVoid(args -> entries.add(args.getFirst())); + }); + + builder.function( + "addFirst", function -> { + function.arity(1); + function.executeSimpleVoid(args -> entries.addFirst(args.getFirst())); + }); + + builder.function("addAll", function -> { + function.arity(1); + function.executeVoid((evaluator, args) -> { + entries.addAll(ArrayValue.flatten(args)); + }); + }); + + builder.function( + "set", function -> { + function.arity(2); + function.executeVoid((evaluator, args) -> { + var index = args.getFirst().asNumber(); + entries.set((int) index, args.get(1)); + }); + }); + + builder.function( + "clear", function -> { + function.arity(0); + function.runs(entries::clear); + }); + }); + + @Override + public Mutable delegate() { + return base; + } + + @Override + public Value get(String field) { + return switch (field) { + case "length", "size" -> new NumValue(entries.size()); + case null, default -> base.get(field); + }; + } + }; + } + + Value get(int index); + + KeyValue.Mutable toMutableArray(); + + interface Mutable extends ArrayValue, KeyValue.Mutable { + + void set(int index, Value value); + + void add(Value value); + + ArrayValue toImmutableArray(); + + } + + @Override + default ArrayValue asArray() { + return this; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/BoolValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/BoolValue.java new file mode 100644 index 0000000..201597c --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/BoolValue.java @@ -0,0 +1,51 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import org.jetbrains.annotations.NotNull; + +public final class BoolValue implements Value { + public static final Value TRUE = new BoolValue(true); + public static final Value FALSE = new BoolValue(false); + private final boolean value; + + private BoolValue(boolean value) {this.value = value;} + + public static Value wrap(boolean value) { + return value ? TRUE : FALSE; + } + + @Override + public @NotNull String toString() { + return Boolean.toString(value); + } + + @Override + public int compareTo(@NotNull Value value) { + if (value instanceof BoolValue boolValue) { + return Boolean.compare(this.value, boolValue.value); + } + return 0; + } + + @Override + public String type() { + return "boolean"; + } + + public boolean value() {return value;} + + + @Override + public int hashCode() { + return Boolean.hashCode(value); + } + + @Override + public boolean asBooleanConversion() { + return this.value; + } + + @Override + public boolean asBoolean() { + return this.value; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/FunctionValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/FunctionValue.java new file mode 100644 index 0000000..6be667a --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/FunctionValue.java @@ -0,0 +1,33 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import tech.thatgravyboat.repolib.v2.builtin.Constants; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; + +import java.util.List; +import java.util.function.Consumer; + +@FunctionalInterface +non-sealed public interface FunctionValue extends Value { + static FunctionValue NIL = (e, a) -> Value.NIL; + + public static FunctionValue builder(Consumer builder) { + return Constants.Builder.FunctionBuilder.create(builder); + } + + default boolean needsInitialization() { + return false; + } + default void initialize(Evaluator evaluator) {}; + + Value apply(Evaluator evaluator, List args); + + @Override + default String type() { + return "function"; + } + + @Override + default FunctionValue asFunctionValue() { + return this; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ImmutableArrayValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ImmutableArrayValue.java new file mode 100644 index 0000000..97da036 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ImmutableArrayValue.java @@ -0,0 +1,46 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +public record ImmutableArrayValue( + List entries, + KeyValue prototype +) implements ArrayValue, KeyValue.Forwarding { + public ImmutableArrayValue(List entries, StructValue prototype) { + this(entries, ArrayValue.createPrototype(entries, false, prototype)); + } + + @Override + public Value get(int index) { + return ArrayValue.get(entries, index); + } + + @Override + public KeyValue.Mutable toMutableArray() { + return new MutableArrayValue(new ArrayList<>(entries), prototype.toMutable()); + } + + @Override + public KeyValue delegate() { + return prototype; + } + + @Override + public @NotNull String toString() { + return entries.toString(); + } + + @Override + public @NotNull Iterator iterator() { + return entries.iterator(); + } + + @Override + public boolean isEmpty() { + return entries.isEmpty(); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ImmutableStructValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ImmutableStructValue.java new file mode 100644 index 0000000..8ee6ea0 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ImmutableStructValue.java @@ -0,0 +1,64 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import org.jetbrains.annotations.NotNull; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +public record ImmutableStructValue(Map fields) implements StructValue { + + public static final ImmutableStructValue EMPTY = new ImmutableStructValue(Map.of()); + + @Override + public Value get(String field) { + if (field.equals("this")) return this; + return fields.getOrDefault(field, NIL); + } + + @Override + public @NotNull String toString() { + return fields.toString(); + } + + @Override + public int size() { + return this.fields.size(); + } + + @Override + public boolean contains(String field) { + return fields.containsKey(field); + } + + @Override + public Set keySet() { + return fields.keySet(); + } + + @Override + public Map sourceMap() { + if (fields.isEmpty()) return Map.of(); + Map result = new HashMap<>(fields.size() * 2); + for (String key : keySet()) { + result.put(key, this); + } + return result; + } + + @Override + public @NotNull Iterator> iterator() { + return fields.entrySet().iterator(); + } + + @Override + public boolean isEmpty() { + return fields.isEmpty(); + } + + @Override + public MutableStruct toMutableStruct() { + return new MutableStructValue(new HashMap<>(fields)); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/KeyValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/KeyValue.java new file mode 100644 index 0000000..bb5cb61 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/KeyValue.java @@ -0,0 +1,100 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import java.util.Map; +import java.util.Set; + +non-sealed public interface KeyValue extends Value { + Value get(String field); + + Mutable toMutable(); + + boolean contains(String field); + + boolean isEmpty(); + + Set keySet(); + Map sourceMap(); + + interface Forwarding extends KeyValue { + KeyValue delegate(); + + @Override + default Value get(String field) { + return delegate().get(field); + } + + @Override + default Mutable toMutable() { + return delegate().toMutable(); + } + + @Override + default boolean contains(String field) { + return delegate().contains(field); + } + + @Override + default boolean isEmpty() { + return delegate().isEmpty(); + } + + @Override + default Set keySet() { + return delegate().keySet(); + } + + @Override + default Map sourceMap() { + return delegate().sourceMap(); + } + } + + interface Mutable extends KeyValue { + void set(String field, Value value); + + KeyValue toImmutable(); + + KeyValue toFullyImmutable(); + + interface Forwarding extends KeyValue.Forwarding, KeyValue.Mutable { + + @Override + KeyValue.Mutable delegate(); + + @Override + default KeyValue toImmutable() { + return delegate().toImmutable(); + } + + @Override + default KeyValue toFullyImmutable() { + return delegate().toFullyImmutable(); + } + + @Override + default void set(String field, Value value) { + delegate().set(field, value); + } + } + } + + @Override + default String type() { + return "object"; + } + + @Override + default boolean asBooleanConversion() { + return !this.isEmpty(); + } + + @Override + default KeyValue asKeyValue() { + return this; + } + + @Override + default Value containsValue(String value) { + return BoolValue.wrap(this.contains(value)); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LambdaFunctionValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LambdaFunctionValue.java new file mode 100644 index 0000000..01de9f6 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LambdaFunctionValue.java @@ -0,0 +1,21 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import java.util.List; +import java.util.function.BiFunction; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; + +public record LambdaFunctionValue( + BiFunction, Value> executor, boolean vararg, int arityMin, int arityMax +) implements LambdaValue { + + @Override + public Value apply(Evaluator evaluator, List args) { + return executor.apply(evaluator, args); + } + + @Override + public LambdaFunctionValue asLambda() { + return this; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LambdaValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LambdaValue.java new file mode 100644 index 0000000..fe9dc42 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LambdaValue.java @@ -0,0 +1,8 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +public interface LambdaValue extends FunctionValue { + + boolean vararg(); + int arityMin(); + int arityMax(); +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LayeredStructValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LayeredStructValue.java new file mode 100644 index 0000000..ae78c47 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/LayeredStructValue.java @@ -0,0 +1,104 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public record LayeredStructValue(StructValue.MutableStruct base, KeyValue overlay) implements StructValue.MutableStruct { + @Override + public Value get(String field) { + if (overlay.contains(field)) { + return overlay.get(field); + } + + return base.get(field); + } + + @Override + public int size() { + return this.base.size(); + } + + @Override + public StructValue.MutableStruct toMutableStruct() { + return this; + } + + @Override + public boolean contains(String field) { + if (overlay.isEmpty()) { + if (base.isEmpty()) return false; + return base.contains(field); + } + if (base.isEmpty()) { + return overlay.contains(field); + } + return overlay.contains(field) || base.contains(field) ; + } + + @Override + public void set(String field, Value value) { + base.set(field, value); + } + + @Override + public KeyValue toImmutable() { + return base.toImmutable(); + } + + @Override + public KeyValue toFullyImmutable() { + return base.toFullyImmutable(); + } + + @Override + public boolean isEmpty() { + return overlay.isEmpty() && base.isEmpty(); + } + + @Override + public Set keySet() { + Set baseKeySet = base.keySet(); + Set overlayKeySet = overlay.keySet(); + + if (baseKeySet.isEmpty()) return overlayKeySet; + if (overlayKeySet.isEmpty()) return baseKeySet; + + Set set = new HashSet<>((baseKeySet.size() + overlayKeySet.size()) * 2); + set.addAll(baseKeySet); + set.addAll(overlayKeySet); + return set; + } + + @Override + public Map sourceMap() { + Map overlayMap = overlay.sourceMap(); + Map baseMap = base.sourceMap(); + if (overlayMap.isEmpty()) return baseMap; + if (baseMap.isEmpty()) return overlayMap; + Map result = new HashMap<>((overlayMap.size() + baseMap.size()) * 2); + result.putAll(baseMap); + result.putAll(overlayMap); + return result; + } + + @Override + public @NotNull Iterator> iterator() { + var keys = sourceMap(); + + var parent = keys.entrySet().iterator(); + + return new Iterator<>() { + @Override + public boolean hasNext() { + return parent.hasNext(); + } + + @Override + public Map.Entry next() { + Map.Entry key = parent.next(); + return Map.entry(key.getKey(), key.getValue().get(key.getKey())); + } + }; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/MutableArrayValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/MutableArrayValue.java new file mode 100644 index 0000000..7ff90a6 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/MutableArrayValue.java @@ -0,0 +1,81 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import org.jetbrains.annotations.NotNull; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.function.Function; + +public record MutableArrayValue( + List entries, + KeyValue.Mutable prototype +) implements ArrayValue.Mutable, KeyValue.Mutable.Forwarding { + public static MutableArrayValue create(List entries, StructValue prototype) { + return new MutableArrayValue(entries, ArrayValue.createPrototype(entries, true, prototype)); + } + public static MutableArrayValue create(Function, StructValue> prototype) { + List entries = new ArrayList<>(); + return new MutableArrayValue(entries, ArrayValue.createPrototype(entries, true, prototype.apply(entries))); + } + public static MutableArrayValue create(StructValue prototype) { + List entries = new ArrayList<>(); + return new MutableArrayValue(entries, ArrayValue.createPrototype(entries, true, prototype)); + } + + public static MutableArrayValue create(List entries) { + return new MutableArrayValue(entries, ArrayValue.createPrototype(entries, true, ImmutableStructValue.EMPTY)); + } + + public static MutableArrayValue create() { + return create(new ArrayList<>()); + } + + @Override + public Value get(int index) { + return ArrayValue.get(entries, index); + } + + @Override + public KeyValue.Mutable toMutableArray() { + return new MutableArrayValue(new ArrayList<>(entries), prototype.toMutable()); + } + + @Override + public void set(int index, Value value) { + while (entries.size() < index) { + entries.add(NIL); + } + entries.set(index, value); + } + + @Override + public void add(Value value) { + entries.add(value); + } + + @Override + public ArrayValue toImmutableArray() { + return new ImmutableArrayValue(new ArrayList<>(entries), prototype.toImmutable()); + } + + @Override + public KeyValue.Mutable delegate() { + return prototype; + } + + @Override + public @NotNull Iterator iterator() { + return this.entries.iterator(); + } + + @Override + public @NotNull String toString() { + return entries.toString(); + } + + @Override + public boolean isEmpty() { + return entries.isEmpty(); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/MutableStructValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/MutableStructValue.java new file mode 100644 index 0000000..6003c7f --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/MutableStructValue.java @@ -0,0 +1,101 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; +import org.jetbrains.annotations.NotNull; + +import java.util.*; + +public record MutableStructValue(Map fields) implements StructValue.MutableStruct { + public MutableStructValue() { + this(new HashMap<>()); + } + public MutableStructValue(StructValue value) { + this(asMap(value)); + } + + private static Map asMap(StructValue value) { + return switch (value) { + case MutableStructValue(Map fields) -> new HashMap<>(fields); + case ImmutableStructValue(Map fields) -> new HashMap<>(fields); + default -> { + var map = new HashMap(); + value.forEach(entry -> map.put(entry.getKey(), entry.getValue())); + yield map; + } + }; + } + + @Override + public int size() { + return this.fields.size(); + } + + @Override + public Value get(String field) { + if (field.equals("this")) return this; + return fields.computeIfAbsent(field, (ignored) -> new MutableStructValue()); + } + + @Override + public void set(String field, Value value) { + fields.put(field, value); + } + + @Override + public @NotNull String toString() { + return fields.toString(); + } + + @Override + public boolean contains(String field) { + return fields.containsKey(field); + } + + @Override + public KeyValue toImmutable() { + return new ImmutableStructValue(Map.copyOf(fields)); + } + + @Override + public KeyValue toFullyImmutable() { + var map = new HashMap(); + for (var entry : fields.entrySet()) { + if (entry instanceof Mutable mutable) { + map.put(entry.getKey(), mutable.toFullyImmutable()); + } else { + map.put(entry.getKey(), entry.getValue()); + } + } + return new ImmutableStructValue(Map.copyOf(map)); + } + + @Override + public MutableStructValue toMutableStruct() { + return new MutableStructValue(new HashMap<>(fields)); + } + + @Override + public Set keySet() { + return fields.keySet(); + } + + @Override + public Map sourceMap() { + if (fields.isEmpty()) return Map.of(); + Map result = new HashMap<>(fields.size() * 2); + for (String key : keySet()) { + result.put(key, this); + } + return result; + } + + @Override + public @NotNull Iterator> iterator() { + return fields.entrySet().iterator(); + } + + @Override + public boolean isEmpty() { + return fields.isEmpty(); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/NilValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/NilValue.java new file mode 100644 index 0000000..1e4e1eb --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/NilValue.java @@ -0,0 +1,20 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import org.jetbrains.annotations.NotNull; + +public record NilValue() implements Value { + @Override + public @NotNull String toString() { + return "undefined"; + } + + @Override + public String type() { + return "null"; + } + + @Override + public boolean asBooleanConversion() { + return false; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/NumValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/NumValue.java new file mode 100644 index 0000000..0f723ae --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/NumValue.java @@ -0,0 +1,56 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +public record NumValue(double value) implements Value { + public NumValue(boolean value) { + this(value ? 1.0 : 0.0); + } + + @Override + public @NotNull String toString() { + return String.valueOf(value); + } + + @Override + public int compareTo(@NotNull Value value) { + if (value instanceof NumValue(double literal)) { + return Double.compare(this.value, literal); + } + return 0; + } + + @Override + public boolean equals(Object o) { + if (o instanceof NumValue(double literal)) { + return value == literal; + } + return false; + } + + @Override + public int hashCode() { + return Double.hashCode(this.value); + } + + @Override + public String type() { + return "number"; + } + + @Override + public boolean asBooleanConversion() { + return this.value != 0; + } + + @Override + public double asNumber() { + return this.value; + } + + @Override + public double asNumber(double defaultValue) { + return this.value; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ScopeLayeredStructValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ScopeLayeredStructValue.java new file mode 100644 index 0000000..77042ca --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/ScopeLayeredStructValue.java @@ -0,0 +1,130 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap; +import java.util.*; + +import org.jetbrains.annotations.NotNull; + +public record ScopeLayeredStructValue(StructValue base, StructValue.MutableStruct overlay) implements StructValue.MutableStruct { + + @Override + public void set(String field, Value value) { + if (base.contains(field) && !overlay.contains(field)) { + if (base instanceof KeyValue.Mutable mutableBase) { + mutableBase.set(field, value); + } + } else { + overlay.set(field, value); + } + } + + @Override + public ImmutableStructValue toImmutable() { + var map = new HashMap(base.size() + overlay.size()); + + base.forEach((entry) -> map.put(entry.getKey(), entry.getValue())); + overlay.forEach((entry) -> map.put(entry.getKey(), entry.getValue())); + + return new ImmutableStructValue(map); + } + + @Override + public int size() { + return this.base.size() + this.overlay.size(); + } + + @Override + public KeyValue toFullyImmutable() { + var map = new HashMap(); + for (var maps : List.of(base, overlay)) { + for (var entry : maps) { + if (entry instanceof Mutable mutable) { + map.put(entry.getKey(), mutable.toFullyImmutable()); + } else { + map.put(entry.getKey(), entry.getValue()); + } + } + } + return new ImmutableStructValue(Map.copyOf(map)); + } + + @Override + public boolean contains(String field) { + if (overlay.isEmpty()) { + if (base.isEmpty()) return false; + return base.contains(field); + } + if (base.isEmpty()) { + return overlay.contains(field); + } + return base.contains(field) || overlay.contains(field) ; + } + + @Override + public Value get(String field) { + if (field.equals("this")) { + return this; + } + + if (base.contains(field) && !overlay.contains(field)) { + return base.get(field); + } + return overlay.get(field); + } + + @Override + public boolean isEmpty() { + return overlay.isEmpty() && base.isEmpty(); + } + + @Override + public MutableStruct toMutableStruct() { + return new ScopeLayeredStructValue(base.toMutableStruct(), overlay.toMutableStruct()); + } + + @Override + public Set keySet() { + Set baseKeySet = base.keySet(); + Set overlayKeySet = overlay.keySet(); + + if (baseKeySet.isEmpty()) return overlayKeySet; + if (overlayKeySet.isEmpty()) return baseKeySet; + + Set set = new HashSet<>((baseKeySet.size() + overlayKeySet.size()) * 2); + set.addAll(baseKeySet); + set.addAll(overlayKeySet); + return set; + } + + @Override + public Map sourceMap() { + Map overlayMap = overlay.sourceMap(); + Map baseMap = base.sourceMap(); + if (overlayMap.isEmpty()) return baseMap; + if (baseMap.isEmpty()) return overlayMap; + Map result = new HashMap<>((overlayMap.size() + baseMap.size()) * 2); + result.putAll(baseMap); + result.putAll(overlayMap); + return result; + } + + @Override + public @NotNull Iterator> iterator() { + var keys = sourceMap(); + + var parent = keys.entrySet().iterator(); + + return new Iterator<>() { + @Override + public boolean hasNext() { + return parent.hasNext(); + } + + @Override + public Map.Entry next() { + Map.Entry key = parent.next(); + return Map.entry(key.getKey(), key.getValue().get(key.getKey())); + } + }; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StrValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StrValue.java new file mode 100644 index 0000000..2e49d74 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StrValue.java @@ -0,0 +1,57 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import java.util.Objects; +import org.jetbrains.annotations.NotNull; + +public record StrValue(String value) implements Value { + @Override + public @NotNull String toString() { + return '"' + value + '"'; + } + + @Override + public int compareTo(@NotNull Value other) { + if (other instanceof StrValue(String c)) { + return value.compareTo(c); + } + return 0; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof StrValue(String literal)) { + return Objects.equals(this.value, literal); + } + return false; + } + + @Override + public int hashCode() { + return value.hashCode(); + } + + @Override + public String type() { + return "string"; + } + + @Override + public String asString() { + return this.value; + } + + @Override + public String asStringOrNull() { + return this.value; + } + + @Override + public boolean asBooleanConversion() { + return !this.value.isEmpty(); + } + + @Override + public Value containsValue(String value) { + return BoolValue.wrap(this.value.contains(value)); + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StructValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StructValue.java new file mode 100644 index 0000000..e9f15a9 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StructValue.java @@ -0,0 +1,87 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import org.jetbrains.annotations.NotNull; + +import java.util.Iterator; +import java.util.Map; + +public interface StructValue extends KeyValue, Iterable> { + + StructValue.MutableStruct toMutableStruct(); + + @Override + default Mutable toMutable() { + return this.toMutableStruct(); + } + + int size(); + + static String prettyPrint(StructValue result) { + return prettyPrint(result, "", 0); + } + static String prettyPrint(StructValue result, String prefix, int depth) { + var builder = new StringBuilder(); + builder.append("{"); + + boolean isEmpty = true; + for (var entry : result) { + isEmpty = false; + builder.append("\n").append(prefix) + .append(" ") + .append(entry.getKey()) + .append(": ") + .append(Value.prettyPrint(entry.getValue(), prefix, depth + 1)) + .append(","); + } + + if (isEmpty) { + builder.append("}"); + } else { + builder.append("\n").append(prefix).append("}"); + } + + return builder.toString(); + } + + interface MutableStruct extends StructValue, KeyValue.Mutable { + + @Override + default MutableStruct asMutableStruct() { + return this; + } + } + + interface Forwarding extends KeyValue.Forwarding, StructValue { + @Override + StructValue delegate(); + + default StructValue.MutableStruct toMutableStruct() { + return delegate().toMutableStruct(); + } + + @Override + default StructValue.Mutable toMutable() { + return toMutableStruct(); + } + + @Override + default @NotNull Iterator> iterator() { + return delegate().iterator(); + } + + @Override + default int size() { + return delegate().size(); + } + } + + @Override + default String type() { + return "struct"; + } + + @Override + default StructValue asStruct() { + return this; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StructuredFunctionValue.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StructuredFunctionValue.java new file mode 100644 index 0000000..c4512f9 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/StructuredFunctionValue.java @@ -0,0 +1,15 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import java.util.List; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; + +public interface StructuredFunctionValue extends FunctionValue { + + Value apply(Evaluator evaluator, StructValue structValue); + Value apply(Evaluator evaluator, List args); + + @Override + default StructuredFunctionValue asStructuredFunction() { + return this; + } +} diff --git a/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/Value.java b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/Value.java new file mode 100644 index 0000000..d87ad16 --- /dev/null +++ b/src/main/java/tech/thatgravyboat/repolib/v2/expl/value/Value.java @@ -0,0 +1,101 @@ +package tech.thatgravyboat.repolib.v2.expl.value; + +import java.util.Locale; +import org.jetbrains.annotations.NotNull; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.expression.NonSerializableExpression; + +public sealed interface Value extends Comparable, NonSerializableExpression + permits ArrayValue, BoolValue, FunctionValue, KeyValue, NilValue, NumValue, StrValue { + + static String prettyPrint(Value value) { + return prettyPrint(value, "", 0); + } + + static String prettyPrint(Value value, String prefix, int depth) { + return switch (value) { + case ArrayValue arr when depth < 10 -> ArrayValue.prettyPrint(arr, prefix + " ", depth); + case ArrayValue ignored -> "[Array]"; + case LambdaFunctionValue lambda -> "[function arityMin=%s arityMax=%s vararg=%s]".formatted( + lambda.arityMin(), + lambda.arityMax(), + lambda.vararg()); + case FunctionValue ignored -> "[function]"; + case StructValue s when depth < 10 -> StructValue.prettyPrint(s, prefix + " ", depth); + case KeyValue kv -> "[Object " + kv.getClass().getSimpleName().toLowerCase(Locale.ROOT) + "]"; + default -> value.toString(); + }; + } + + String type(); + + Value NIL = new NilValue(); + + @Override + default int compareTo(@NotNull Value o) { + return 0; + } + + @Override + default Value evaluate(Evaluator evaluator) { + return this; + } + + default String asString() { + throw new Evaluator.Panic("Failed to convert " + this + " into a string"); + } + + default double asNumber() { + throw new Evaluator.Panic("Failed to convert " + this + " into a string"); + } + + default double asNumber(double defaultValue) { + return defaultValue; + } + + default boolean asBoolean() { + throw new Evaluator.Panic("Failed to convert " + this + " into a boolean"); + } + + default boolean asBooleanConversion() { + throw new Evaluator.Panic("Unable to convert " + this + " into boolean."); + } + + default StructValue asStruct() { + throw new Evaluator.Panic("Failed to convert " + this + " into a struct"); + } + + default StructValue.MutableStruct asMutableStruct() { + throw new Evaluator.Panic("Failed to convert " + this + " into a mutable struct"); + } + + default String asStringOrNull() { + return null; + } + + default StructuredFunctionValue asStructuredFunction() { + throw new Evaluator.Panic("Failed to convert " + this + " into a Structured Function"); + } + + default LambdaFunctionValue asLambda() { + throw new Evaluator.Panic("Failed to convert " + this + " into a function"); + } + + default FunctionValue asFunctionValue() { + throw new Evaluator.Panic("Failed to convert " + this + " into a function"); + } + + default ArrayValue asArray() { + throw new Evaluator.Panic("Failed to convert " + this + " into an array"); + } + + default KeyValue asKeyValue() { + throw new Evaluator.Panic("Failed to convert " + this + " into a key value"); + } + + default Value containsValue(String value) { + throw new Evaluator.Panic( + "Can't check if '" + value + "' is in non string or keyvalue type " + this); + } + +} diff --git a/src/test/java/CompilerMain.java b/src/test/java/CompilerMain.java new file mode 100644 index 0000000..13ac150 --- /dev/null +++ b/src/test/java/CompilerMain.java @@ -0,0 +1,37 @@ +import tech.thatgravyboat.repolib.v2.FolderLoader; +import tech.thatgravyboat.repolib.v2.RepoConstants; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; +import tech.thatgravyboat.repolib.v2.expl.Parser; + +void main() { + try { + var repoLoader = new FolderLoader(Path.of("src/test/repo")); + + var errors = repoLoader.load(); + for (var error : errors) { + IO.println("Failed to load file " + error.file() + " due to " + error.reason()); + error.reason().printStackTrace(); + } + var constants = new RepoConstants(repoLoader); + var evaluator = new Evaluator(constants, repoLoader::module); + var meow = new Parser(""" +return if (true) { + return 5; +} else { +5 +}; +""").parseModuleFile("test", repoLoader); +// meow.init(constants); +// System.out.println(meow.meta()); + IO.println(meow.evaluate(evaluator)); + + IO.println(meow); + +// var file = repoLoader.getModule("silly"); +// var res = file.apply(evaluator, List.of()); +// System.out.println(res); + + } catch (Exception e) { + throw new RuntimeException(e); + } +} diff --git a/src/test/java/Main.java b/src/test/java/Main.java new file mode 100644 index 0000000..d9c42a8 --- /dev/null +++ b/src/test/java/Main.java @@ -0,0 +1,29 @@ +import java.util.List; +import tech.thatgravyboat.repolib.v2.RepoConstants; +import tech.thatgravyboat.repolib.v2.FolderLoader; +import tech.thatgravyboat.repolib.v2.expl.Evaluator; + +import java.io.IOException; +import java.nio.file.Path; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +public class Main { + + public static void main(String[] args) throws IOException { + var repoLoader = new FolderLoader(Path.of("src/test/repo")); + var errors = repoLoader.load(); + for (var error : errors) { + System.out.println("Failed to load file " + error.file() + " due to " + error.reason()); + error.reason().printStackTrace(); + } + var file = repoLoader.module("silly"); + + var constants = new RepoConstants(repoLoader); + var evaluator = new Evaluator(constants, repoLoader::module); + + var res = file.apply(evaluator, List.of()); + + System.out.println(Value.prettyPrint(res)); + } + +} diff --git a/src/test/java/Main2.java b/src/test/java/Main2.java new file mode 100644 index 0000000..605f089 --- /dev/null +++ b/src/test/java/Main2.java @@ -0,0 +1,248 @@ +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.IntConsumer; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; +import tech.thatgravyboat.repolib.v2.BundleLoader; +import tech.thatgravyboat.repolib.v2.FolderLoader; +import tech.thatgravyboat.repolib.v2.RepoConfig; +import tech.thatgravyboat.repolib.v2.expl.value.*; + +@SuppressWarnings("OptionalUsedAsFieldOrParameterType") +public class Main2 extends WebSocketServer { + private final List connections = new ArrayList<>(); + public String lastModifiedItem = "items/aspect_of_the_void"; + + boolean running = true; + + static void main(String[] args) throws IOException { + FolderLoader loader = new FolderLoader(Path.of("Repo-Data").toRealPath().normalize().toAbsolutePath()); + + var errors = loader.load(); + + var path = Path.of("bundle.srb"); + if (errors.isEmpty()) { + Files.write(path, loader.buildRepoBundle(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); + var bundleLoader = new BundleLoader(path); + var instance = bundleLoader.create(); + bundleLoader.load(); + var stackFile = Objects.requireNonNull(bundleLoader.stackFile("items/slayer/enderman/aspect_of_the_void")); + + { + + var evaluator = stackFile.createEvaluator(instance.constants(), ImmutableStructValue.EMPTY, RepoConfig.DEFAULT, bundleLoader::module); + var stack = stackFile.evaluateScript(evaluator); + evaluator.errors.forEach(System.out::println); + evaluator.debugs.forEach(System.out::println); + System.out.println(stack); + } + } + } + + private static StructValue toValue(JsonObject data) { + return new MutableStructValue(data.entrySet() + .stream() + .map((entry) -> Map.entry(entry.getKey(), toValue(entry.getValue()))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); + } + + private static ArrayValue toValue(JsonArray data) { + return MutableArrayValue.create(data.asList().stream().map(Main2::toValue).toList()); + } + + private static Value toValue(JsonElement element) { + return switch (element) { + case JsonObject object -> toValue(object); + case JsonArray array -> toValue(array); + case JsonPrimitive primitive when primitive.isBoolean() -> BoolValue.wrap(primitive.getAsBoolean()); + case JsonPrimitive primitive when primitive.isNumber() -> + new NumValue(primitive.getAsNumber().doubleValue()); + case JsonPrimitive primitive when primitive.isString() -> new StrValue(primitive.getAsString()); + case JsonNull nil -> NilValue.NIL; + default -> throw new NoSuchElementException(""); + }; + } + + + private static JsonElement toJson(Value value) { + return switch (value) { + case StructValue kv -> StreamSupport.stream(kv.spliterator(), false) + .map((e) -> Map.entry(e.getKey(), toJson(e.getValue()))) + .collect( + JsonObject::new, + (obj, entry) -> obj.add(entry.getKey(), entry.getValue()), + (obj1, obj2) -> obj1.asMap().forEach(obj2::add)); + case ArrayValue array -> StreamSupport.stream(array.spliterator(), false) + .map(Main2::toJson) + .collect(JsonArray::new, JsonArray::add, JsonArray::addAll); + case StrValue(String val) -> new JsonPrimitive(val); + case NumValue(double val) -> new JsonPrimitive(val); + case BoolValue bool -> new JsonPrimitive(bool.value()); + case NilValue nil -> JsonNull.INSTANCE; + default -> throw new NoSuchElementException(""); + }; + } + + private static JsonObject asComponent(Value value) { + return switch (value) { + case StrValue(String literal) -> { + var obj = new JsonObject(); + obj.addProperty("text", literal); + yield obj; + } + case ArrayValue array -> { + var obj = new JsonObject(); + obj.add( + "extra", + StreamSupport.stream(array.spliterator(), false) + .map(Main2::asComponent) + .collect(JsonArray::new, JsonArray::add, JsonArray::addAll)); + yield obj; + } + case StructValue val -> { + if (val.isEmpty()) { + yield new JsonObject(); + } + var obj = new JsonObject(); + + color(val.get("color")).ifPresent(setString(obj, "color")); + color(val.get("shadow_color")).ifPresent(setString(obj, "shadow_color")); + getBool(val, "bold").ifPresent(setBoolean(obj, "bold")); + getBool(val, "italic").or(() -> Optional.of(false)).ifPresent(setBoolean(obj, "italic")); + getBool(val, "obfuscated").ifPresent(setBoolean(obj, "obfuscated")); + getBool(val, "strikethrough").ifPresent(setBoolean(obj, "strikethrough")); + getBool(val, "underlined").ifPresent(setBoolean(obj, "underlined")); + getString(val, "font").ifPresent(setString(obj, "font")); + getString(val, "text").ifPresent(setString(obj, "text")); + + if (val.get("extra") instanceof ArrayValue arr) { + var extra = new JsonArray(); + arr.forEach(v -> extra.add(asComponent(v))); + obj.add("extra", extra); + } + + yield obj; + } + default -> throw new NoSuchElementException(""); + }; + } + + private static Optional getBool(StructValue val, String field) { + return Optional.of(val.get(field)).filter(it -> it instanceof BoolValue).map(it -> ((BoolValue) it).value()); + } + + private static Optional getString(StructValue val, String field) { + return Optional.of(val.get(field)).filter(it -> it instanceof StrValue).map(it -> ((StrValue) it).value()); + } + + private static IntConsumer setInt(JsonObject obj, String field) { + return (value) -> obj.addProperty(field, "#" + Integer.toString(value, 16)); + } + + private static Consumer setBoolean(JsonObject obj, String field) { + return (value) -> obj.addProperty(field, value); + } + + private static Consumer setString(JsonObject obj, String field) { + return (value) -> obj.addProperty(field, value); + } + + static Optional BLACK = Optional.of("black"); + static Optional DARK_BLUE = Optional.of("dark_blue"); + static Optional DARK_GREEN = Optional.of("dark_green"); + static Optional DARK_AQUA = Optional.of("dark_aqua"); + static Optional DARK_RED = Optional.of("dark_red"); + static Optional DARK_PURPLE = Optional.of("dark_purple"); + static Optional GOLD = Optional.of("gold"); + static Optional GRAY = Optional.of("gray"); + static Optional DARK_GRAY = Optional.of("dark_gray"); + static Optional BLUE = Optional.of("blue"); + static Optional GREEN = Optional.of("green"); + static Optional AQUA = Optional.of("aqua"); + static Optional RED = Optional.of("red"); + static Optional LIGHT_PURPLE = Optional.of("light_purple"); + static Optional YELLOW = Optional.of("yellow"); + static Optional WHITE = Optional.of("white"); + + private static Optional color(Value value) { + if (!(value instanceof StrValue(String color))) { + return Optional.empty(); + } + + return switch (color.toLowerCase(Locale.ROOT)) { + case "black" -> BLACK; + case "dark_blue" -> DARK_BLUE; + case "dark_green" -> DARK_GREEN; + case "cyan", "dark_aqua" -> DARK_AQUA; + case "lime", "green" -> GREEN; + case "dark_red" -> DARK_RED; + case "dark_purple", "magenta" -> DARK_PURPLE; + case "gold", "orange" -> GOLD; + case "gray" -> GRAY; + case "dark_gray" -> DARK_GRAY; + case "blue" -> BLUE; + case "aqua" -> AQUA; + case "red" -> RED; + case "light_purple", "pink" -> LIGHT_PURPLE; + case "yellow" -> YELLOW; + case "white" -> WHITE; + default -> { + if (color.startsWith("#")) { + yield Optional.of(color); + } + + yield Optional.empty(); + } + }; + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + connections.add(conn); + System.out.println("a client connected"); + + conn.send(""" + if (!window.hasAlreadyBeenPipped) {window.hasAlreadyBeenPipped = true;const theCanvas = document.querySelector("canvas#tooltipCanvas");theCanvas.onclick = async function () {theCanvas.onclick = undefined;const pipWindow = await window.documentPictureInPicture.requestWindow({width: theCanvas.clientWidth,height: theCanvas.clientHeight,});[...document.styleSheets].forEach((styleSheet) => {try {const cssRules = [...styleSheet.cssRules].map((rule) => rule.cssText).join("");const style = document.createElement("style");style.textContent = cssRules;pipWindow.document.head.appendChild(style);} catch (e) {const link = document.createElement("link");link.rel = "stylesheet";link.type = styleSheet.type;link.media = styleSheet.media;link.href = styleSheet.href;pipWindow.document.head.appendChild(link);}});pipWindow.document.body.append(theCanvas);theCanvas.onclick=()=>{pipWindow.resizeTo(theCanvas.clientWidth + (pipWindow.window.outerWidth - pipWindow.window.innerWidth), theCanvas.clientHeight + (pipWindow.window.outerHeight - pipWindow.window.innerHeight))}}} + """); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + connections.remove(conn); + } + + @Override + public void onMessage(WebSocket conn, String message) { + conn.sendPing(); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + System.out.println( + " > (()=>{function c() {const ws = new WebSocket(\"ws://localhost:8008\");ws.onopen=()=>ws.send" + + "(\"ping\");ws.onmessage=(m)=>eval(m.data);ws.onclose=(meow)=>setTimeout(c, 1000)};c()})() <"); + } + + @Override + public void stop(int timeout, String closeMessage) throws InterruptedException { + super.stop(timeout, closeMessage); + running = false; + } +} diff --git a/src/test/java/Main3.java b/src/test/java/Main3.java new file mode 100644 index 0000000..5b21651 --- /dev/null +++ b/src/test/java/Main3.java @@ -0,0 +1,51 @@ +import com.google.gson.JsonParser; +import tech.thatgravyboat.repolib.v2.FolderLoader; +import tech.thatgravyboat.repolib.v2.RepoConfig; +import tech.thatgravyboat.repolib.v2.RepoLoader; +import tech.thatgravyboat.repolib.v2.builtin.Constants; +import tech.thatgravyboat.repolib.v2.expl.value.ImmutableStructValue; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.util.Objects; + +public class Main3 { + public static void main(String[] args) throws IOException { + Path repoPath = Path.of("Repo-Data").toRealPath().normalize().toAbsolutePath(); + RepoLoader loader = new FolderLoader(repoPath); + var instance = loader.create(); + + var errors = loader.load(); + + errors.forEach(System.out::println); + + var data = + JsonParser.parseString(Files.readString(Path.of("data.jsonc"), StandardCharsets.UTF_8)).getAsJsonObject(); + + var constData = Constants.kvFromJson(data); + + var stackFile = Objects.requireNonNull(loader.stackFile("items/slayer/enderman/aspect_of_the_void")); + + { + var evaluator = stackFile.createEvaluator(instance.constants(), constData, RepoConfig.DEFAULT, loader::module); + var stack = stackFile.evaluateScript(evaluator); + evaluator.errors.forEach(System.out::println); + evaluator.debugs.forEach(System.out::println); + System.out.println(stack);; + } + + long uncompiledSum = 0; + for (int i = 0; i < 100000; i++) { + long noCompileStart = System.nanoTime(); + var noCompileEvaluator = stackFile.createEvaluator(instance.constants(), ImmutableStructValue.EMPTY, RepoConfig.DEFAULT, loader::module); + var noCompileStack = stackFile.evaluateScript(noCompileEvaluator); + uncompiledSum += System.nanoTime() - noCompileStart; + System.out.print("Try " + i + " (avg " + uncompiledSum / ((i + 1) * 1000000.0) + "ms)\r"); + } + + System.out.println("Took " + (uncompiledSum / 100_000_000000.0) + "ms (uncompiled)"); + } +} diff --git a/src/test/java/utils/Main.java b/src/test/java/utils/Main.java new file mode 100644 index 0000000..e3061b5 --- /dev/null +++ b/src/test/java/utils/Main.java @@ -0,0 +1,295 @@ +package utils; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.IntConsumer; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; +import org.java_websocket.WebSocket; +import org.java_websocket.handshake.ClientHandshake; +import org.java_websocket.server.WebSocketServer; +import tech.thatgravyboat.repolib.v2.RepoConfig; +import tech.thatgravyboat.repolib.v2.FolderLoader; +import tech.thatgravyboat.repolib.v2.expl.value.ArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.BoolValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableArrayValue; +import tech.thatgravyboat.repolib.v2.expl.value.MutableStructValue; +import tech.thatgravyboat.repolib.v2.expl.value.NilValue; +import tech.thatgravyboat.repolib.v2.expl.value.NumValue; +import tech.thatgravyboat.repolib.v2.expl.value.StrValue; +import tech.thatgravyboat.repolib.v2.expl.value.StructValue; +import tech.thatgravyboat.repolib.v2.expl.value.Value; + +@SuppressWarnings("OptionalUsedAsFieldOrParameterType") +public class Main extends WebSocketServer { + private List connections = new ArrayList<>(); + public String lastModifiedItem = "items/aspect_of_the_void"; + + boolean running = true; + + public static void main(String[] args) throws IOException { + new Main(); + } + + private final FolderLoader loader = new FolderLoader(Path.of("Repo-Data").toRealPath().normalize().toAbsolutePath()); + + public Main() throws IOException { + super(new InetSocketAddress("0.0.0.0", 8008)); + start(); + reloadAndSend(); + new Thread(() -> { + try { + new WatchDir(loader.path, this).processEvents(); + } catch (IOException e) { + throw new RuntimeException(e); + } + }).start(); + } + + private int reloadCount = 0; + + public void reloadAndSend() throws IOException { + var instance = loader.create(); + + var errors = loader.load(); + System.out.printf("Reloading (%d %s)%n", reloadCount++, lastModifiedItem); + errors.forEach(System.out::println); + + var data = + JsonParser.parseString(Files.readString(Path.of("data.jsonc"), StandardCharsets.UTF_8)).getAsJsonObject(); + var profile = + JsonParser.parseString(Files.readString(Path.of("profile.jsonc"), StandardCharsets.UTF_8)).getAsJsonObject(); + + var stackFile = Objects.requireNonNull(loader.stackFile(lastModifiedItem)); + var evaluator = stackFile.createEvaluator(instance.constants(), toValue(data), toValue(profile), RepoConfig.DEFAULT, this.loader::module); + var stack = stackFile.evaluateScript(evaluator); + + evaluator.errors.forEach(System.out::println); + evaluator.debugs.forEach(System.out::println); + + var item = new JsonObject(); + item.add("minecraft:custom_name", asComponent(stack.get("names"))); + //noinspection RedundantCast + item.add("minecraft:lore", asComponent((ArrayValue) stack.get("lore")).get("extra")); + item.add("minecraft:custom_data", data); + + var itemStack = new JsonObject(); + itemStack.add("components", item); + + this.connections.forEach(webSocket -> { + webSocket.send("importFromJson(`%s`)".formatted(itemStack.toString().replaceAll("`", "\\`"))); + }); + } + + private StructValue toValue(JsonObject data) { + return new MutableStructValue(data.entrySet() + .stream() + .map((entry) -> Map.entry(entry.getKey(), toValue(entry.getValue()))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))); + } + + private ArrayValue toValue(JsonArray data) { + return MutableArrayValue.create(data.asList().stream().map(this::toValue).toList()); + } + + private Value toValue(JsonElement element) { + return switch (element) { + case JsonObject object -> toValue(object); + case JsonArray array -> toValue(array); + case JsonPrimitive primitive when primitive.isBoolean() -> BoolValue.wrap(primitive.getAsBoolean()); + case JsonPrimitive primitive when primitive.isNumber() -> + new NumValue(primitive.getAsNumber().doubleValue()); + case JsonPrimitive primitive when primitive.isString() -> new StrValue(primitive.getAsString()); + case JsonNull nil -> NilValue.NIL; + default -> throw new NoSuchElementException(""); + }; + } + + + private JsonElement toJson(Value value) { + return switch (value) { + case StructValue kv -> StreamSupport.stream(kv.spliterator(), false) + .map((e) -> Map.entry(e.getKey(), toJson(e.getValue()))) + .collect( + JsonObject::new, + (obj, entry) -> obj.add(entry.getKey(), entry.getValue()), + (obj1, obj2) -> obj1.asMap().forEach(obj2::add)); + case ArrayValue array -> StreamSupport.stream(array.spliterator(), false) + .map(this::toJson) + .collect(JsonArray::new, JsonArray::add, JsonArray::addAll); + case StrValue(String val) -> new JsonPrimitive(val); + case NumValue(double val) -> new JsonPrimitive(val); + case BoolValue bool -> new JsonPrimitive(bool.value()); + case NilValue nil -> JsonNull.INSTANCE; + default -> throw new NoSuchElementException(""); + }; + } + + private JsonObject asComponent(Value value) { + return switch (value) { + case StrValue(String literal) -> { + var obj = new JsonObject(); + obj.addProperty("text", literal); + yield obj; + } + case ArrayValue array -> { + var obj = new JsonObject(); + obj.add( + "extra", + StreamSupport.stream(array.spliterator(), false) + .map(this::asComponent) + .collect(JsonArray::new, JsonArray::add, JsonArray::addAll)); + yield obj; + } + case StructValue val -> { + if (val.isEmpty()) { + yield new JsonObject(); + } + var obj = new JsonObject(); + + color(val.get("color")).ifPresent(setString(obj, "color")); + color(val.get("shadow_color")).ifPresent(setString(obj, "shadow_color")); + getBool(val, "bold").ifPresent(setBoolean(obj, "bold")); + getBool(val, "italic").or(() -> Optional.of(false)).ifPresent(setBoolean(obj, "italic")); + getBool(val, "obfuscated").ifPresent(setBoolean(obj, "obfuscated")); + getBool(val, "strikethrough").ifPresent(setBoolean(obj, "strikethrough")); + getBool(val, "underlined").ifPresent(setBoolean(obj, "underlined")); + getString(val, "font").ifPresent(setString(obj, "font")); + getString(val, "text").ifPresent(setString(obj, "text")); + + if (val.get("extra") instanceof ArrayValue arr) { + var extra = new JsonArray(); + arr.forEach(v -> extra.add(asComponent(v))); + obj.add("extra", extra); + } + + yield obj; + } + default -> throw new NoSuchElementException(""); + }; + } + + private Optional getBool(StructValue val, String field) { + return Optional.of(val.get(field)).filter(it -> it instanceof BoolValue).map(it -> ((BoolValue) it).value()); + } + + private Optional getString(StructValue val, String field) { + return Optional.of(val.get(field)).filter(it -> it instanceof StrValue).map(it -> ((StrValue) it).value()); + } + + private IntConsumer setInt(JsonObject obj, String field) { + return (value) -> obj.addProperty(field, "#" + Integer.toString(value, 16)); + } + + private Consumer setBoolean(JsonObject obj, String field) { + return (value) -> obj.addProperty(field, value); + } + + private Consumer setString(JsonObject obj, String field) { + return (value) -> obj.addProperty(field, value); + } + + Optional BLACK = Optional.of("black"); + Optional DARK_BLUE = Optional.of("dark_blue"); + Optional DARK_GREEN = Optional.of("dark_green"); + Optional DARK_AQUA = Optional.of("dark_aqua"); + Optional DARK_RED = Optional.of("dark_red"); + Optional DARK_PURPLE = Optional.of("dark_purple"); + Optional GOLD = Optional.of("gold"); + Optional GRAY = Optional.of("gray"); + Optional DARK_GRAY = Optional.of("dark_gray"); + Optional BLUE = Optional.of("blue"); + Optional GREEN = Optional.of("green"); + Optional AQUA = Optional.of("aqua"); + Optional RED = Optional.of("red"); + Optional LIGHT_PURPLE = Optional.of("light_purple"); + Optional YELLOW = Optional.of("yellow"); + Optional WHITE = Optional.of("white"); + + private Optional color(Value value) { + if (!(value instanceof StrValue(String color))) { + return Optional.empty(); + } + + return switch (color.toLowerCase(Locale.ROOT)) { + case "black" -> BLACK; + case "dark_blue" -> DARK_BLUE; + case "dark_green" -> DARK_GREEN; + case "cyan", "dark_aqua" -> DARK_AQUA; + case "lime", "green" -> GREEN; + case "dark_red" -> DARK_RED; + case "dark_purple", "magenta" -> DARK_PURPLE; + case "gold", "orange" -> GOLD; + case "gray" -> GRAY; + case "dark_gray" -> DARK_GRAY; + case "blue" -> BLUE; + case "aqua" -> AQUA; + case "red" -> RED; + case "light_purple", "pink" -> LIGHT_PURPLE; + case "yellow" -> YELLOW; + case "white" -> WHITE; + default -> { + if (color.startsWith("#")) { + yield Optional.of(color); + } + + yield Optional.empty(); + } + }; + } + + @Override + public void onOpen(WebSocket conn, ClientHandshake handshake) { + connections.add(conn); + System.out.println("a client connected"); + + conn.send(""" + if (!window.hasAlreadyBeenPipped) {window.hasAlreadyBeenPipped = true;const theCanvas = document.querySelector("canvas#tooltipCanvas");theCanvas.onclick = async function () {theCanvas.onclick = undefined;const pipWindow = await window.documentPictureInPicture.requestWindow({width: theCanvas.clientWidth,height: theCanvas.clientHeight,});[...document.styleSheets].forEach((styleSheet) => {try {const cssRules = [...styleSheet.cssRules].map((rule) => rule.cssText).join("");const style = document.createElement("style");style.textContent = cssRules;pipWindow.document.head.appendChild(style);} catch (e) {const link = document.createElement("link");link.rel = "stylesheet";link.type = styleSheet.type;link.media = styleSheet.media;link.href = styleSheet.href;pipWindow.document.head.appendChild(link);}});pipWindow.document.body.append(theCanvas);theCanvas.onclick=()=>{pipWindow.resizeTo(theCanvas.clientWidth + (pipWindow.window.outerWidth - pipWindow.window.innerWidth), theCanvas.clientHeight + (pipWindow.window.outerHeight - pipWindow.window.innerHeight))}}} + """); + } + + @Override + public void onClose(WebSocket conn, int code, String reason, boolean remote) { + connections.remove(conn); + } + + @Override + public void onMessage(WebSocket conn, String message) { + conn.sendPing(); + } + + @Override + public void onError(WebSocket conn, Exception ex) { + + } + + @Override + public void onStart() { + System.out.println( + " > (()=>{function c() {const ws = new WebSocket(\"ws://localhost:8008\");ws.onopen=()=>ws.send" + + "(\"ping\");ws.onmessage=(m)=>eval(m.data);ws.onclose=(meow)=>setTimeout(c, 1000)};c()})() <"); + } + + @Override + public void stop(int timeout, String closeMessage) throws InterruptedException { + super.stop(timeout, closeMessage); + running = false; + } +} diff --git a/src/test/java/utils/WatchDir.java b/src/test/java/utils/WatchDir.java new file mode 100644 index 0000000..a408191 --- /dev/null +++ b/src/test/java/utils/WatchDir.java @@ -0,0 +1,127 @@ +package utils; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.StandardWatchEventKinds; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +public class WatchDir { + + private final WatchService watcher; + private final Map keys; + private final Path dir; + private final Main main; + + @SuppressWarnings("unchecked") + static WatchEvent cast(WatchEvent event) { + return (WatchEvent)event; + } + + /** + * Register the given directory with the WatchService + */ + private void register(Path dir) throws IOException { + WatchKey key = dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); + keys.put(key, dir); + } + + private void registerAll(final Path start) throws IOException { + Files.walkFileTree(start, new SimpleFileVisitor() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) + throws IOException + { + register(dir); + return FileVisitResult.CONTINUE; + } + }); + } + + WatchDir(Path dir, Main main) throws IOException { + this.dir = dir; + this.main = main; + this.watcher = FileSystems.getDefault().newWatchService(); + this.keys = new HashMap<>(); + + registerAll(dir); + } + + /** + * Process all events for keys queued to the watcher + */ + void processEvents() { + while (main.running) { + WatchKey key; + try { + key = watcher.poll(100, TimeUnit.MILLISECONDS); + } catch (InterruptedException x) { + return; + } + if (key == null) { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + continue; + } + + + Path dir = keys.get(key); + if (dir == null) { + System.out.println(key); + System.err.println("WatchKey not recognized!! :C"); + continue; + } + + for (WatchEvent event: key.pollEvents()) { + var kind = event.kind(); + WatchEvent ev = cast(event); + Path name = ev.context(); + Path child = dir.resolve(name); + + var fileName = this.dir.relativize(child).toString(); + if (fileName.endsWith("srls")) { + main.lastModifiedItem = fileName.substring(0, fileName.lastIndexOf('.')); + } + + if ((kind == StandardWatchEventKinds.ENTRY_CREATE)) { + + try { + if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) { + registerAll(child); + } + } catch (IOException x) { + // ignore to keep sample readable + } + } + } + + try { + main.reloadAndSend(); + } catch (IOException e) { + e.printStackTrace(); + } + + boolean valid = key.reset(); + if (!valid) { + keys.remove(key); + + if (keys.isEmpty()) { + break; + } + } + } + } +} \ No newline at end of file diff --git a/src/test/repo/printf.srlf b/src/test/repo/printf.srlf new file mode 100644 index 0000000..c2053a6 --- /dev/null +++ b/src/test/repo/printf.srlf @@ -0,0 +1,10 @@ +| message, severity? | + + +prefix = match (severity) { + "debug" -> "[DEBUG]", + "error" -> "[ERROR]", + else -> "[INFO]", +} + +print(prefix, message); \ No newline at end of file diff --git a/src/test/repo/silly.srlm b/src/test/repo/silly.srlm new file mode 100644 index 0000000..e8a52fe --- /dev/null +++ b/src/test/repo/silly.srlm @@ -0,0 +1,45 @@ +print("test"); + +name = "print"; + +printf = ::<(name + "f")>::; + +printf("silly"); +printf("silly", "debug"); + +printf{ + message: "meow", + severity: "error", +}; + + total_star_count = 10; +if (!total_star_count) return []; + +stars = [" "]; + +orange_star_count = Math.clamp(total_star_count, 0, 5); + +if (orange_star_count > 0) { + stars += { + text: "✪", + color: "orange" + }; +} + +remaining_stars = total_star_count - orange_star_count; + +if (remaining_stars > 0) stars.add({ + text: match (remaining_stars) { + 1 -> "➊1", + 2 -> "➋2", + 3 -> "➌3", + 4 -> "➍4", + 5 -> "➎5", + else -> "?", + }, + color: "red" +}); + +print(stars); + +stars; \ No newline at end of file