Separate constants and functions in module, don't load it twice

This commit is contained in:
aNNiMON 2023-09-09 18:59:53 +03:00 committed by Victor Melnik
parent 6d0886316c
commit 99bdd1c953
31 changed files with 687 additions and 542 deletions

View File

@ -8,6 +8,8 @@ import java.awt.Dimension;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.IntBuffer; import java.nio.IntBuffer;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javafx.application.Platform; import javafx.application.Platform;
@ -83,7 +85,9 @@ public final class canvasfx implements Module {
} }
} }
public static void initConstants() { @Override
public Map<String, Value> constants() {
final var result = new HashMap<String, Value>(11);
// Color class // Color class
final Map<Value, Value> colors = Arrays.stream(Color.class.getDeclaredFields()) final Map<Value, Value> colors = Arrays.stream(Color.class.getDeclaredFields())
.filter(f -> Modifier.isStatic(f.getModifiers())) .filter(f -> Modifier.isStatic(f.getModifiers()))
@ -98,94 +102,96 @@ public final class canvasfx implements Module {
colors.put(new StringValue("rgb"), new FunctionValue(new rgbColor())); colors.put(new StringValue("rgb"), new FunctionValue(new rgbColor()));
colors.put(new StringValue("hsb"), new FunctionValue(new hsbColor())); colors.put(new StringValue("hsb"), new FunctionValue(new hsbColor()));
colors.put(new StringValue("web"), new FunctionValue(new webColor())); colors.put(new StringValue("web"), new FunctionValue(new webColor()));
ScopeHandler.setConstant("Color", new MapValue(colors)); result.put("Color", new MapValue(colors));
final MapValue arcType = new MapValue(ArcType.values().length); final MapValue arcType = new MapValue(ArcType.values().length);
for (ArcType value : ArcType.values()) { for (ArcType value : ArcType.values()) {
arcType.set(value.name(), NumberValue.of(value.ordinal())); arcType.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("ArcType", arcType); result.put("ArcType", arcType);
final MapValue fillRule = new MapValue(FillRule.values().length); final MapValue fillRule = new MapValue(FillRule.values().length);
for (FillRule value : FillRule.values()) { for (FillRule value : FillRule.values()) {
fillRule.set(value.name(), NumberValue.of(value.ordinal())); fillRule.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("FillRule", fillRule); result.put("FillRule", fillRule);
final MapValue blendMode = new MapValue(BlendMode.values().length); final MapValue blendMode = new MapValue(BlendMode.values().length);
for (BlendMode value : BlendMode.values()) { for (BlendMode value : BlendMode.values()) {
blendMode.set(value.name(), NumberValue.of(value.ordinal())); blendMode.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("BlendMode", blendMode); result.put("BlendMode", blendMode);
final MapValue lineCap = new MapValue(StrokeLineCap.values().length); final MapValue lineCap = new MapValue(StrokeLineCap.values().length);
for (StrokeLineCap value : StrokeLineCap.values()) { for (StrokeLineCap value : StrokeLineCap.values()) {
lineCap.set(value.name(), NumberValue.of(value.ordinal())); lineCap.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("StrokeLineCap", lineCap); result.put("StrokeLineCap", lineCap);
final MapValue lineJoin = new MapValue(StrokeLineJoin.values().length); final MapValue lineJoin = new MapValue(StrokeLineJoin.values().length);
for (StrokeLineJoin value : StrokeLineJoin.values()) { for (StrokeLineJoin value : StrokeLineJoin.values()) {
lineJoin.set(value.name(), NumberValue.of(value.ordinal())); lineJoin.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("StrokeLineJoin", lineJoin); result.put("StrokeLineJoin", lineJoin);
final MapValue textAlignment = new MapValue(TextAlignment.values().length); final MapValue textAlignment = new MapValue(TextAlignment.values().length);
for (TextAlignment value : TextAlignment.values()) { for (TextAlignment value : TextAlignment.values()) {
textAlignment.set(value.name(), NumberValue.of(value.ordinal())); textAlignment.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("TextAlignment", textAlignment); result.put("TextAlignment", textAlignment);
final MapValue vPos = new MapValue(VPos.values().length); final MapValue vPos = new MapValue(VPos.values().length);
for (VPos value : VPos.values()) { for (VPos value : VPos.values()) {
vPos.set(value.name(), NumberValue.of(value.ordinal())); vPos.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("VPos", vPos); result.put("VPos", vPos);
final MapValue events = new MapValue(Events.values().length); final MapValue events = new MapValue(Events.values().length);
for (Events value : Events.values()) { for (Events value : Events.values()) {
events.set(value.name(), NumberValue.of(value.ordinal())); events.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("Events", events); result.put("Events", events);
final MapValue mouseButton = new MapValue(MouseButton.values().length); final MapValue mouseButton = new MapValue(MouseButton.values().length);
for (MouseButton value : MouseButton.values()) { for (MouseButton value : MouseButton.values()) {
mouseButton.set(value.name(), NumberValue.of(value.ordinal())); mouseButton.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("MouseButton", mouseButton); result.put("MouseButton", mouseButton);
final MapValue keyCodes = new MapValue(KeyCode.values().length); final MapValue keyCodes = new MapValue(KeyCode.values().length);
for (KeyCode value : KeyCode.values()) { for (KeyCode value : KeyCode.values()) {
keyCodes.set(value.name(), NumberValue.of(value.ordinal())); keyCodes.set(value.name(), NumberValue.of(value.ordinal()));
} }
ScopeHandler.setConstant("KeyCode", keyCodes); result.put("KeyCode", keyCodes);
return result;
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); final var result = new LinkedHashMap<String, Function>(20);
ScopeHandler.setFunction("window", new CreateWindow()); result.put("window", new CreateWindow());
ScopeHandler.setFunction("repaint", new Repaint()); result.put("repaint", new Repaint());
ScopeHandler.setFunction("BlendEffect", new BlendEffect()); result.put("BlendEffect", new BlendEffect());
ScopeHandler.setFunction("BloomEffect", new BloomEffect()); result.put("BloomEffect", new BloomEffect());
ScopeHandler.setFunction("BoxBlurEffect", new BoxBlurEffect()); result.put("BoxBlurEffect", new BoxBlurEffect());
ScopeHandler.setFunction("ColorAdjustEffect", new ColorAdjustEffect()); result.put("ColorAdjustEffect", new ColorAdjustEffect());
ScopeHandler.setFunction("ColorInputEffect", new ColorInputEffect()); result.put("ColorInputEffect", new ColorInputEffect());
ScopeHandler.setFunction("DropShadowEffect", new DropShadowEffect()); result.put("DropShadowEffect", new DropShadowEffect());
ScopeHandler.setFunction("GaussianBlurEffect", new GaussianBlurEffect()); result.put("GaussianBlurEffect", new GaussianBlurEffect());
ScopeHandler.setFunction("GlowEffect", new GlowEffect()); result.put("GlowEffect", new GlowEffect());
ScopeHandler.setFunction("InnerShadowEffect", new InnerShadowEffect()); result.put("InnerShadowEffect", new InnerShadowEffect());
ScopeHandler.setFunction("LightingEffect", new LightingEffect()); result.put("LightingEffect", new LightingEffect());
ScopeHandler.setFunction("MotionBlurEffect", new MotionBlurEffect()); result.put("MotionBlurEffect", new MotionBlurEffect());
ScopeHandler.setFunction("PerspectiveTransformEffect", new PerspectiveTransformEffect()); result.put("PerspectiveTransformEffect", new PerspectiveTransformEffect());
ScopeHandler.setFunction("ReflectionEffect", new ReflectionEffect()); result.put("ReflectionEffect", new ReflectionEffect());
ScopeHandler.setFunction("SepiaToneEffect", new SepiaToneEffect()); result.put("SepiaToneEffect", new SepiaToneEffect());
ScopeHandler.setFunction("ShadowEffect", new ShadowEffect()); result.put("ShadowEffect", new ShadowEffect());
ScopeHandler.setFunction("addEventFilter", new addEventFilter()); result.put("addEventFilter", new addEventFilter());
ScopeHandler.setFunction("addEventHandler", new addEventHandler()); result.put("addEventHandler", new addEventHandler());
ScopeHandler.setFunction("createImage", new createImage()); result.put("createImage", new createImage());
return result;
} }
private static class ColorValue implements Value { private static class ColorValue implements Value {

View File

@ -4,21 +4,24 @@ import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Base64; import java.util.Base64;
import java.util.Map;
public class base64 implements Module { public class base64 implements Module {
private static final int TYPE_URL_SAFE = 8; private static final int TYPE_URL_SAFE = 8;
public static void initConstants() { @Override
ScopeHandler.setConstant("BASE64_URL_SAFE", NumberValue.of(TYPE_URL_SAFE)); public Map<String, Value> constants() {
return Map.of("BASE64_URL_SAFE", NumberValue.of(TYPE_URL_SAFE));
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.of(
ScopeHandler.setFunction("base64encode", this::base64encode); "base64encode", this::base64encode,
ScopeHandler.setFunction("base64decode", this::base64decode); "base64decode", this::base64decode,
ScopeHandler.setFunction("base64encodeToString", this::base64encodeToString); "base64encodeToString", this::base64encodeToString
);
} }
private Value base64encode(Value[] args) { private Value base64encode(Value[] args) {

View File

@ -12,9 +12,12 @@ import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter; import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage; import java.awt.image.BufferedImage;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.JOptionPane; import javax.swing.JOptionPane;
import javax.swing.JPanel; import javax.swing.JPanel;
import static java.util.Map.entry;
/** /**
* *
@ -29,34 +32,39 @@ public final class canvas implements Module {
private static NumberValue lastKey; private static NumberValue lastKey;
private static ArrayValue mouseHover; private static ArrayValue mouseHover;
public static void initConstants() {
ScopeHandler.setConstant("VK_UP", NumberValue.of(KeyEvent.VK_UP)); @Override
ScopeHandler.setConstant("VK_DOWN", NumberValue.of(KeyEvent.VK_DOWN)); public Map<String, Value> constants() {
ScopeHandler.setConstant("VK_LEFT", NumberValue.of(KeyEvent.VK_LEFT)); return Map.ofEntries(
ScopeHandler.setConstant("VK_RIGHT", NumberValue.of(KeyEvent.VK_RIGHT)); entry("VK_UP", NumberValue.of(KeyEvent.VK_UP)),
ScopeHandler.setConstant("VK_FIRE", NumberValue.of(KeyEvent.VK_ENTER)); entry("VK_DOWN", NumberValue.of(KeyEvent.VK_DOWN)),
ScopeHandler.setConstant("VK_ESCAPE", NumberValue.of(KeyEvent.VK_ESCAPE)); entry("VK_LEFT", NumberValue.of(KeyEvent.VK_LEFT)),
entry("VK_RIGHT", NumberValue.of(KeyEvent.VK_RIGHT)),
entry("VK_FIRE", NumberValue.of(KeyEvent.VK_ENTER)),
entry("VK_ESCAPE", NumberValue.of(KeyEvent.VK_ESCAPE))
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants();
ScopeHandler.setFunction("window", new CreateWindow());
ScopeHandler.setFunction("prompt", new Prompt());
ScopeHandler.setFunction("keypressed", new KeyPressed());
ScopeHandler.setFunction("mousehover", new MouseHover());
ScopeHandler.setFunction("line", intConsumer4Convert(canvas::line));
ScopeHandler.setFunction("oval", intConsumer4Convert(canvas::oval));
ScopeHandler.setFunction("foval", intConsumer4Convert(canvas::foval));
ScopeHandler.setFunction("rect", intConsumer4Convert(canvas::rect));
ScopeHandler.setFunction("frect", intConsumer4Convert(canvas::frect));
ScopeHandler.setFunction("clip", intConsumer4Convert(canvas::clip));
ScopeHandler.setFunction("drawstring", new DrawString());
ScopeHandler.setFunction("color", new SetColor());
ScopeHandler.setFunction("repaint", new Repaint());
lastKey = NumberValue.MINUS_ONE; lastKey = NumberValue.MINUS_ONE;
mouseHover = new ArrayValue(new Value[] { NumberValue.ZERO, NumberValue.ZERO }); mouseHover = new ArrayValue(new Value[] { NumberValue.ZERO, NumberValue.ZERO });
final var result = new LinkedHashMap<String, Function>(15);
result.put("window", new CreateWindow());
result.put("prompt", new Prompt());
result.put("keypressed", new KeyPressed());
result.put("mousehover", new MouseHover());
result.put("line", intConsumer4Convert(canvas::line));
result.put("oval", intConsumer4Convert(canvas::oval));
result.put("foval", intConsumer4Convert(canvas::foval));
result.put("rect", intConsumer4Convert(canvas::rect));
result.put("frect", intConsumer4Convert(canvas::frect));
result.put("clip", intConsumer4Convert(canvas::clip));
result.put("drawstring", new DrawString());
result.put("color", new SetColor());
result.put("repaint", new Repaint());
return result;
} }
@FunctionalInterface @FunctionalInterface

View File

@ -3,29 +3,28 @@ package com.annimon.ownlang.modules.collections;
import com.annimon.ownlang.exceptions.TypeException; import com.annimon.ownlang.exceptions.TypeException;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.Comparator; import java.util.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Supplier; import java.util.function.Supplier;
import static java.util.Map.entry;
public class collections implements Module { public class collections implements Module {
public static void initConstants() { @Override
public Map<String, Value> constants() {
return Collections.emptyMap();
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.ofEntries(
ScopeHandler.setFunction("hashMap", mapFunction(HashMap::new)); entry("hashMap", mapFunction(HashMap::new)),
ScopeHandler.setFunction("linkedHashMap", mapFunction(LinkedHashMap::new)); entry("linkedHashMap", mapFunction(LinkedHashMap::new)),
ScopeHandler.setFunction("concurrentHashMap", mapFunction(ConcurrentHashMap::new)); entry("concurrentHashMap", mapFunction(ConcurrentHashMap::new)),
ScopeHandler.setFunction("treeMap", sortedMapFunction(TreeMap::new, TreeMap::new)); entry("treeMap", sortedMapFunction(TreeMap::new, TreeMap::new)),
ScopeHandler.setFunction("concurrentSkipListMap", sortedMapFunction(ConcurrentSkipListMap::new, ConcurrentSkipListMap::new)); entry("concurrentSkipListMap", sortedMapFunction(ConcurrentSkipListMap::new, ConcurrentSkipListMap::new))
);
} }
private Function mapFunction(final Supplier<Map<Value, Value>> mapSupplier) { private Function mapFunction(final Supplier<Map<Value, Value>> mapSupplier) {

View File

@ -6,9 +6,7 @@ import com.annimon.ownlang.modules.Module;
import java.text.DateFormat; import java.text.DateFormat;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.Calendar; import java.util.*;
import java.util.Date;
import java.util.Locale;
/** /**
* *
@ -27,21 +25,25 @@ public final class date implements Module {
SECOND = new StringValue("second"), SECOND = new StringValue("second"),
MILLISECOND = new StringValue("millisecond"); MILLISECOND = new StringValue("millisecond");
public static void initConstants() { @Override
ScopeHandler.setConstant("STYLE_FULL", NumberValue.of(DateFormat.FULL)); public Map<String, Value> constants() {
ScopeHandler.setConstant("STYLE_LONG", NumberValue.of(DateFormat.LONG)); return Map.of(
ScopeHandler.setConstant("STYLE_MEDIUM", NumberValue.of(DateFormat.MEDIUM)); "STYLE_FULL", NumberValue.of(DateFormat.FULL),
ScopeHandler.setConstant("STYLE_SHORT", NumberValue.of(DateFormat.SHORT)); "STYLE_LONG", NumberValue.of(DateFormat.LONG),
"STYLE_MEDIUM", NumberValue.of(DateFormat.MEDIUM),
"STYLE_SHORT", NumberValue.of(DateFormat.SHORT)
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.of(
ScopeHandler.setFunction("newDate", new date_newDate()); "newDate", new date_newDate(),
ScopeHandler.setFunction("newFormat", new date_newFormat()); "newFormat", new date_newFormat(),
ScopeHandler.setFunction("formatDate", new date_format()); "formatDate", new date_format(),
ScopeHandler.setFunction("parseDate", new date_parse()); "parseDate", new date_parse(),
ScopeHandler.setFunction("toTimestamp", new date_toTimestamp()); "toTimestamp", new date_toTimestamp()
);
} }
//<editor-fold defaultstate="collapsed" desc="Values"> //<editor-fold defaultstate="collapsed" desc="Values">

View File

@ -9,13 +9,22 @@ import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Collections;
import java.util.Map;
public final class downloader implements Module { public final class downloader implements Module {
@Override @Override
public void init() { public Map<String, Value> constants() {
ScopeHandler.setFunction("getContentLength", this::getContentLength); return Collections.emptyMap();
ScopeHandler.setFunction("downloader", this::downloader); }
@Override
public Map<String, Function> functions() {
return Map.of(
"getContentLength", this::getContentLength,
"downloader", this::downloader
);
} }
private Value getContentLength(Value[] args) { private Value getContentLength(Value[] args) {

View File

@ -18,6 +18,7 @@ import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel; import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
/** /**
@ -28,71 +29,74 @@ public final class files implements Module {
private static Map<Integer, FileInfo> files; private static Map<Integer, FileInfo> files;
public static void initConstants() { @Override
ScopeHandler.setConstant("FILES_COMPARATOR", new FunctionValue(new filesComparatorFunction())); public Map<String, Value> constants() {
return Map.of(
"FILES_COMPARATOR", new FunctionValue(new filesComparatorFunction())
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
files = new HashMap<>(); files = new HashMap<>();
initConstants(); final var result = new LinkedHashMap<String, Function>(50);
result.put("fopen", new fopen());
ScopeHandler.setFunction("fopen", new fopen()); result.put("flush", new flush());
ScopeHandler.setFunction("flush", new flush()); result.put("fclose", new fclose());
ScopeHandler.setFunction("fclose", new fclose());
// Operations // Operations
ScopeHandler.setFunction("copy", new copy()); result.put("copy", new copy());
ScopeHandler.setFunction("delete", fileToBoolean(File::delete)); result.put("delete", fileToBoolean(File::delete));
ScopeHandler.setFunction("listFiles", new listFiles()); result.put("listFiles", new listFiles());
ScopeHandler.setFunction("mkdir", fileToBoolean(File::mkdir)); result.put("mkdir", fileToBoolean(File::mkdir));
ScopeHandler.setFunction("mkdirs", fileToBoolean(File::mkdirs)); result.put("mkdirs", fileToBoolean(File::mkdirs));
ScopeHandler.setFunction("rename", new rename()); result.put("rename", new rename());
// Permissions and statuses // Permissions and statuses
ScopeHandler.setFunction("canExecute", fileToBoolean(File::canExecute)); result.put("canExecute", fileToBoolean(File::canExecute));
ScopeHandler.setFunction("canRead", fileToBoolean(File::canRead)); result.put("canRead", fileToBoolean(File::canRead));
ScopeHandler.setFunction("canWrite", fileToBoolean(File::canWrite)); result.put("canWrite", fileToBoolean(File::canWrite));
ScopeHandler.setFunction("isDirectory", fileToBoolean(File::isDirectory)); result.put("isDirectory", fileToBoolean(File::isDirectory));
ScopeHandler.setFunction("isFile", fileToBoolean(File::isFile)); result.put("isFile", fileToBoolean(File::isFile));
ScopeHandler.setFunction("isHidden", fileToBoolean(File::isHidden)); result.put("isHidden", fileToBoolean(File::isHidden));
ScopeHandler.setFunction("setExecutable", new setExecutable()); result.put("setExecutable", new setExecutable());
ScopeHandler.setFunction("setReadable", new setReadable()); result.put("setReadable", new setReadable());
ScopeHandler.setFunction("setReadOnly", new setReadOnly()); result.put("setReadOnly", new setReadOnly());
ScopeHandler.setFunction("setWritable", new setWritable()); result.put("setWritable", new setWritable());
ScopeHandler.setFunction("exists", fileToBoolean(File::exists)); result.put("exists", fileToBoolean(File::exists));
ScopeHandler.setFunction("fileSize", new fileSize()); result.put("fileSize", new fileSize());
ScopeHandler.setFunction("getParent", new getParent()); result.put("getParent", new getParent());
ScopeHandler.setFunction("lastModified", new lastModified()); result.put("lastModified", new lastModified());
ScopeHandler.setFunction("setLastModified", new setLastModified()); result.put("setLastModified", new setLastModified());
// IO // IO
ScopeHandler.setFunction("readBoolean", new readBoolean()); result.put("readBoolean", new readBoolean());
ScopeHandler.setFunction("readByte", new readByte()); result.put("readByte", new readByte());
ScopeHandler.setFunction("readBytes", new readBytes()); result.put("readBytes", new readBytes());
ScopeHandler.setFunction("readAllBytes", new readAllBytes()); result.put("readAllBytes", new readAllBytes());
ScopeHandler.setFunction("readChar", new readChar()); result.put("readChar", new readChar());
ScopeHandler.setFunction("readShort", new readShort()); result.put("readShort", new readShort());
ScopeHandler.setFunction("readInt", new readInt()); result.put("readInt", new readInt());
ScopeHandler.setFunction("readLong", new readLong()); result.put("readLong", new readLong());
ScopeHandler.setFunction("readFloat", new readFloat()); result.put("readFloat", new readFloat());
ScopeHandler.setFunction("readDouble", new readDouble()); result.put("readDouble", new readDouble());
ScopeHandler.setFunction("readUTF", new readUTF()); result.put("readUTF", new readUTF());
ScopeHandler.setFunction("readLine", new readLine()); result.put("readLine", new readLine());
ScopeHandler.setFunction("readText", new readText()); result.put("readText", new readText());
ScopeHandler.setFunction("writeBoolean", new writeBoolean()); result.put("writeBoolean", new writeBoolean());
ScopeHandler.setFunction("writeByte", new writeByte()); result.put("writeByte", new writeByte());
ScopeHandler.setFunction("writeBytes", new writeBytes()); result.put("writeBytes", new writeBytes());
ScopeHandler.setFunction("writeChar", new writeChar()); result.put("writeChar", new writeChar());
ScopeHandler.setFunction("writeShort", new writeShort()); result.put("writeShort", new writeShort());
ScopeHandler.setFunction("writeInt", new writeInt()); result.put("writeInt", new writeInt());
ScopeHandler.setFunction("writeLong", new writeLong()); result.put("writeLong", new writeLong());
ScopeHandler.setFunction("writeFloat", new writeFloat()); result.put("writeFloat", new writeFloat());
ScopeHandler.setFunction("writeDouble", new writeDouble()); result.put("writeDouble", new writeDouble());
ScopeHandler.setFunction("writeUTF", new writeUTF()); result.put("writeUTF", new writeUTF());
ScopeHandler.setFunction("writeLine", new writeLine()); result.put("writeLine", new writeLine());
ScopeHandler.setFunction("writeText", new writeText()); result.put("writeText", new writeText());
return result;
} }
private static class filesComparatorFunction implements Function { private static class filesComparatorFunction implements Function {

View File

@ -4,6 +4,8 @@ import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.awt.BorderLayout; import java.awt.BorderLayout;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.BoxLayout; import javax.swing.BoxLayout;
import javax.swing.JFrame; import javax.swing.JFrame;
import javax.swing.ScrollPaneConstants; import javax.swing.ScrollPaneConstants;
@ -15,14 +17,16 @@ import javax.swing.SwingConstants;
*/ */
public final class forms implements Module { public final class forms implements Module {
public static void initConstants() { @Override
public Map<String, Value> constants() {
final var result = new LinkedHashMap<String, Value>(10);
// JFrame constants // JFrame constants
ScopeHandler.setConstant("DISPOSE_ON_CLOSE", NumberValue.of(JFrame.DISPOSE_ON_CLOSE)); result.put("DISPOSE_ON_CLOSE", NumberValue.of(JFrame.DISPOSE_ON_CLOSE));
ScopeHandler.setConstant("DO_NOTHING_ON_CLOSE", NumberValue.of(JFrame.DO_NOTHING_ON_CLOSE)); result.put("DO_NOTHING_ON_CLOSE", NumberValue.of(JFrame.DO_NOTHING_ON_CLOSE));
ScopeHandler.setConstant("EXIT_ON_CLOSE", NumberValue.of(JFrame.EXIT_ON_CLOSE)); result.put("EXIT_ON_CLOSE", NumberValue.of(JFrame.EXIT_ON_CLOSE));
ScopeHandler.setConstant("HIDE_ON_CLOSE", NumberValue.of(JFrame.HIDE_ON_CLOSE)); result.put("HIDE_ON_CLOSE", NumberValue.of(JFrame.HIDE_ON_CLOSE));
// SwinfConstants // SwingConstants
final MapValue swing = new MapValue(20); final MapValue swing = new MapValue(20);
swing.set("BOTTOM", NumberValue.of(SwingConstants.BOTTOM)); swing.set("BOTTOM", NumberValue.of(SwingConstants.BOTTOM));
swing.set("CENTER", NumberValue.of(SwingConstants.CENTER)); swing.set("CENTER", NumberValue.of(SwingConstants.CENTER));
@ -43,7 +47,7 @@ public final class forms implements Module {
swing.set("TRAILING", NumberValue.of(SwingConstants.TRAILING)); swing.set("TRAILING", NumberValue.of(SwingConstants.TRAILING));
swing.set("VERTICAL", NumberValue.of(SwingConstants.VERTICAL)); swing.set("VERTICAL", NumberValue.of(SwingConstants.VERTICAL));
swing.set("WEST", NumberValue.of(SwingConstants.WEST)); swing.set("WEST", NumberValue.of(SwingConstants.WEST));
ScopeHandler.setConstant("SwingConstants", swing); result.put("SwingConstants", swing);
// LayoutManagers constants // LayoutManagers constants
final MapValue border = new MapValue(13); final MapValue border = new MapValue(13);
@ -60,7 +64,7 @@ public final class forms implements Module {
border.set("PAGE_START", new StringValue(BorderLayout.PAGE_START)); border.set("PAGE_START", new StringValue(BorderLayout.PAGE_START));
border.set("SOUTH", new StringValue(BorderLayout.SOUTH)); border.set("SOUTH", new StringValue(BorderLayout.SOUTH));
border.set("WEST", new StringValue(BorderLayout.WEST)); border.set("WEST", new StringValue(BorderLayout.WEST));
ScopeHandler.setConstant("BorderLayout", border); result.put("BorderLayout", border);
// ScrollPane constants // ScrollPane constants
final MapValue scrollpane = new MapValue(13); final MapValue scrollpane = new MapValue(13);
@ -85,14 +89,14 @@ public final class forms implements Module {
scrollpane.set("VERTICAL_SCROLLBAR_ALWAYS", NumberValue.of(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS)); scrollpane.set("VERTICAL_SCROLLBAR_ALWAYS", NumberValue.of(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS));
scrollpane.set("VERTICAL_SCROLLBAR_AS_NEEDED", NumberValue.of(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED)); scrollpane.set("VERTICAL_SCROLLBAR_AS_NEEDED", NumberValue.of(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED));
scrollpane.set("VERTICAL_SCROLLBAR_NEVER", NumberValue.of(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER)); scrollpane.set("VERTICAL_SCROLLBAR_NEVER", NumberValue.of(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER));
ScopeHandler.setConstant("ScrollPaneConstants", scrollpane); result.put("ScrollPaneConstants", scrollpane);
final MapValue box = new MapValue(4); final MapValue box = new MapValue(4);
box.set("LINE_AXIS", NumberValue.of(BoxLayout.LINE_AXIS)); box.set("LINE_AXIS", NumberValue.of(BoxLayout.LINE_AXIS));
box.set("PAGE_AXIS", NumberValue.of(BoxLayout.PAGE_AXIS)); box.set("PAGE_AXIS", NumberValue.of(BoxLayout.PAGE_AXIS));
box.set("X_AXIS", NumberValue.of(BoxLayout.X_AXIS)); box.set("X_AXIS", NumberValue.of(BoxLayout.X_AXIS));
box.set("Y_AXIS", NumberValue.of(BoxLayout.Y_AXIS)); box.set("Y_AXIS", NumberValue.of(BoxLayout.Y_AXIS));
ScopeHandler.setConstant("BoxLayout", box); result.put("BoxLayout", box);
final MapValue windowEvent = new MapValue(4); final MapValue windowEvent = new MapValue(4);
windowEvent.set("WINDOW_FIRST", NumberValue.of(WindowEvent.WINDOW_FIRST)); windowEvent.set("WINDOW_FIRST", NumberValue.of(WindowEvent.WINDOW_FIRST));
@ -107,27 +111,29 @@ public final class forms implements Module {
windowEvent.set("WINDOW_LOST_FOCUS", NumberValue.of(WindowEvent.WINDOW_LOST_FOCUS)); windowEvent.set("WINDOW_LOST_FOCUS", NumberValue.of(WindowEvent.WINDOW_LOST_FOCUS));
windowEvent.set("WINDOW_STATE_CHANGED", NumberValue.of(WindowEvent.WINDOW_STATE_CHANGED)); windowEvent.set("WINDOW_STATE_CHANGED", NumberValue.of(WindowEvent.WINDOW_STATE_CHANGED));
windowEvent.set("WINDOW_LAST", NumberValue.of(WindowEvent.WINDOW_LAST)); windowEvent.set("WINDOW_LAST", NumberValue.of(WindowEvent.WINDOW_LAST));
ScopeHandler.setConstant("WindowEvent", windowEvent); result.put("WindowEvent", windowEvent);
return result;
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); final var result = new LinkedHashMap<String, Function>(16);
// Components // Components
ScopeHandler.setFunction("newButton", Components::newButton); result.put("newButton", Components::newButton);
ScopeHandler.setFunction("newLabel", Components::newLabel); result.put("newLabel", Components::newLabel);
ScopeHandler.setFunction("newPanel", Components::newPanel); result.put("newPanel", Components::newPanel);
ScopeHandler.setFunction("newProgressBar", Components::newProgressBar); result.put("newProgressBar", Components::newProgressBar);
ScopeHandler.setFunction("newScrollPane", Components::newScrollPane); result.put("newScrollPane", Components::newScrollPane);
ScopeHandler.setFunction("newTextArea", Components::newTextArea); result.put("newTextArea", Components::newTextArea);
ScopeHandler.setFunction("newTextField", Components::newTextField); result.put("newTextField", Components::newTextField);
ScopeHandler.setFunction("newWindow", Components::newWindow); result.put("newWindow", Components::newWindow);
// LayoutManagers // LayoutManagers
ScopeHandler.setFunction("borderLayout", LayoutManagers::borderLayout); result.put("borderLayout", LayoutManagers::borderLayout);
ScopeHandler.setFunction("boxLayout", LayoutManagers::boxLayout); result.put("boxLayout", LayoutManagers::boxLayout);
ScopeHandler.setFunction("cardLayout", LayoutManagers::cardLayout); result.put("cardLayout", LayoutManagers::cardLayout);
ScopeHandler.setFunction("gridLayout", LayoutManagers::gridLayout); result.put("gridLayout", LayoutManagers::gridLayout);
ScopeHandler.setFunction("flowLayout", LayoutManagers::flowLayout); result.put("flowLayout", LayoutManagers::flowLayout);
return result;
} }
} }

View File

@ -1,8 +1,11 @@
package com.annimon.ownlang.modules.functional; package com.annimon.ownlang.modules.functional;
import com.annimon.ownlang.lib.Function;
import com.annimon.ownlang.lib.FunctionValue; import com.annimon.ownlang.lib.FunctionValue;
import com.annimon.ownlang.lib.ScopeHandler; import com.annimon.ownlang.lib.Value;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.HashMap;
import java.util.Map;
/** /**
* *
@ -10,24 +13,26 @@ import com.annimon.ownlang.modules.Module;
*/ */
public final class functional implements Module { public final class functional implements Module {
public static void initConstants() { @Override
ScopeHandler.setConstant("IDENTITY", new FunctionValue(args -> args[0])); public Map<String, Value> constants() {
return Map.of("IDENTITY", new FunctionValue(args -> args[0]));
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); final var result = new HashMap<String, Function>(15);
ScopeHandler.setFunction("foreach", new functional_foreach()); result.put("foreach", new functional_foreach());
ScopeHandler.setFunction("map", new functional_map()); result.put("map", new functional_map());
ScopeHandler.setFunction("flatmap", new functional_flatmap()); result.put("flatmap", new functional_flatmap());
ScopeHandler.setFunction("reduce", new functional_reduce()); result.put("reduce", new functional_reduce());
ScopeHandler.setFunction("filter", new functional_filter(false)); result.put("filter", new functional_filter(false));
ScopeHandler.setFunction("sortby", new functional_sortby()); result.put("sortby", new functional_sortby());
ScopeHandler.setFunction("takewhile", new functional_filter(true)); result.put("takewhile", new functional_filter(true));
ScopeHandler.setFunction("dropwhile", new functional_dropwhile()); result.put("dropwhile", new functional_dropwhile());
ScopeHandler.setFunction("chain", new functional_chain()); result.put("chain", new functional_chain());
ScopeHandler.setFunction("stream", new functional_stream()); result.put("stream", new functional_stream());
ScopeHandler.setFunction("combine", new functional_combine()); result.put("combine", new functional_combine());
return result;
} }
} }

View File

@ -3,25 +3,27 @@ package com.annimon.ownlang.modules.gzip;
import com.annimon.ownlang.exceptions.TypeException; import com.annimon.ownlang.exceptions.TypeException;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.io.ByteArrayInputStream; import java.io.*;
import java.io.ByteArrayOutputStream; import java.util.Collections;
import java.io.File; import java.util.Map;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream; import java.util.zip.GZIPOutputStream;
public class gzip implements Module { public class gzip implements Module {
@Override @Override
public void init() { public Map<String, Value> constants() {
ScopeHandler.setFunction("gzip", this::gzipFile); return Collections.emptyMap();
ScopeHandler.setFunction("gzipBytes", this::gzipBytes); }
ScopeHandler.setFunction("ungzip", this::ungzipFile);
ScopeHandler.setFunction("ungzipBytes", this::ungzipBytes); @Override
public Map<String, Function> functions() {
return Map.of(
"gzip", this::gzipFile,
"gzipBytes", this::gzipBytes,
"ungzip", this::ungzipFile,
"ungzipBytes", this::ungzipBytes
);
} }
private Value gzipFile(Value[] args) { private Value gzipFile(Value[] args) {

View File

@ -1,7 +1,10 @@
package com.annimon.ownlang.modules.http; package com.annimon.ownlang.modules.http;
import com.annimon.ownlang.lib.ScopeHandler; import com.annimon.ownlang.lib.Function;
import com.annimon.ownlang.lib.Value;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.Collections;
import java.util.Map;
/** /**
* *
@ -9,14 +12,17 @@ import com.annimon.ownlang.modules.Module;
*/ */
public final class http implements Module { public final class http implements Module {
public static void initConstants() { @Override
public Map<String, Value> constants() {
return Collections.emptyMap();
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.of(
ScopeHandler.setFunction("urlencode", new http_urlencode()); "urlencode", new http_urlencode(),
ScopeHandler.setFunction("http", new http_http()); "http", new http_http(),
ScopeHandler.setFunction("download", new http_download()); "download", new http_download()
);
} }
} }

View File

@ -7,9 +7,8 @@ import java.lang.reflect.Constructor;
import java.lang.reflect.Field; import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays; import static java.util.Map.entry;
import java.util.List;
/** /**
* Java interoperability module. * Java interoperability module.
@ -20,48 +19,51 @@ public final class java implements Module {
private static final Value NULL = new NullValue(); private static final Value NULL = new NullValue();
public static void initConstants() { @Override
public Map<String, Value> constants() {
final var result = new LinkedHashMap<String, Value>(16);
result.put("null", NULL);
result.put("boolean.class", new ClassValue(boolean.class));
result.put("boolean[].class", new ClassValue(boolean[].class));
result.put("boolean[][].class", new ClassValue(boolean[][].class));
result.put("byte.class", new ClassValue(byte.class));
result.put("byte[].class", new ClassValue(byte[].class));
result.put("byte[][].class", new ClassValue(byte[][].class));
result.put("short.class", new ClassValue(short.class));
result.put("short[].class", new ClassValue(short[].class));
result.put("short[][].class", new ClassValue(short[][].class));
result.put("char.class", new ClassValue(char.class));
result.put("char[].class", new ClassValue(char[].class));
result.put("char[][].class", new ClassValue(char[][].class));
result.put("int.class", new ClassValue(int.class));
result.put("int[].class", new ClassValue(int[].class));
result.put("int[][].class", new ClassValue(int[][].class));
result.put("long.class", new ClassValue(long.class));
result.put("long[].class", new ClassValue(long[].class));
result.put("long[][].class", new ClassValue(long[][].class));
result.put("float.class", new ClassValue(float.class));
result.put("float[].class", new ClassValue(float[].class));
result.put("float[][].class", new ClassValue(float[][].class));
result.put("double.class", new ClassValue(double.class));
result.put("double[].class", new ClassValue(double[].class));
result.put("double[][].class", new ClassValue(double[][].class));
result.put("String.class", new ClassValue(String.class));
result.put("String[].class", new ClassValue(String[].class));
result.put("String[][].class", new ClassValue(String[][].class));
result.put("Object.class", new ClassValue(Object.class));
result.put("Object[].class", new ClassValue(Object[].class));
result.put("Object[][].class", new ClassValue(Object[][].class));
return result;
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.ofEntries(
ScopeHandler.setConstant("null", NULL); entry("isNull", this::isNull),
ScopeHandler.setConstant("boolean.class", new ClassValue(boolean.class)); entry("newClass", this::newClass),
ScopeHandler.setConstant("boolean[].class", new ClassValue(boolean[].class)); entry("toObject", this::toObject),
ScopeHandler.setConstant("boolean[][].class", new ClassValue(boolean[][].class)); entry("toValue", this::toValue)
ScopeHandler.setConstant("byte.class", new ClassValue(byte.class)); );
ScopeHandler.setConstant("byte[].class", new ClassValue(byte[].class));
ScopeHandler.setConstant("byte[][].class", new ClassValue(byte[][].class));
ScopeHandler.setConstant("short.class", new ClassValue(short.class));
ScopeHandler.setConstant("short[].class", new ClassValue(short[].class));
ScopeHandler.setConstant("short[][].class", new ClassValue(short[][].class));
ScopeHandler.setConstant("char.class", new ClassValue(char.class));
ScopeHandler.setConstant("char[].class", new ClassValue(char[].class));
ScopeHandler.setConstant("char[][].class", new ClassValue(char[][].class));
ScopeHandler.setConstant("int.class", new ClassValue(int.class));
ScopeHandler.setConstant("int[].class", new ClassValue(int[].class));
ScopeHandler.setConstant("int[][].class", new ClassValue(int[][].class));
ScopeHandler.setConstant("long.class", new ClassValue(long.class));
ScopeHandler.setConstant("long[].class", new ClassValue(long[].class));
ScopeHandler.setConstant("long[][].class", new ClassValue(long[][].class));
ScopeHandler.setConstant("float.class", new ClassValue(float.class));
ScopeHandler.setConstant("float[].class", new ClassValue(float[].class));
ScopeHandler.setConstant("float[][].class", new ClassValue(float[][].class));
ScopeHandler.setConstant("double.class", new ClassValue(double.class));
ScopeHandler.setConstant("double[].class", new ClassValue(double[].class));
ScopeHandler.setConstant("double[][].class", new ClassValue(double[][].class));
ScopeHandler.setConstant("String.class", new ClassValue(String.class));
ScopeHandler.setConstant("String[].class", new ClassValue(String[].class));
ScopeHandler.setConstant("String[][].class", new ClassValue(String[][].class));
ScopeHandler.setConstant("Object.class", new ClassValue(Object.class));
ScopeHandler.setConstant("Object[].class", new ClassValue(Object[].class));
ScopeHandler.setConstant("Object[][].class", new ClassValue(Object[][].class));
ScopeHandler.setFunction("isNull", this::isNull);
ScopeHandler.setFunction("newClass", this::newClass);
ScopeHandler.setFunction("toObject", this::toObject);
ScopeHandler.setFunction("toValue", this::toValue);
} }
//<editor-fold defaultstate="collapsed" desc="Values"> //<editor-fold defaultstate="collapsed" desc="Values">

View File

@ -16,6 +16,8 @@ import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.sql.Time; import java.sql.Time;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiFunction; import java.util.function.BiFunction;
import java.util.function.Function; import java.util.function.Function;
@ -25,39 +27,43 @@ import java.util.function.Function;
*/ */
public final class jdbc implements Module { public final class jdbc implements Module {
public static void initConstants() { @Override
ScopeHandler.setConstant("TRANSACTION_NONE", NumberValue.of(Connection.TRANSACTION_NONE)); public Map<String, Value> constants() {
ScopeHandler.setConstant("TRANSACTION_READ_COMMITTED", NumberValue.of(Connection.TRANSACTION_READ_COMMITTED)); final var result = new LinkedHashMap<String, Value>(25);
ScopeHandler.setConstant("TRANSACTION_READ_UNCOMMITTED", NumberValue.of(Connection.TRANSACTION_READ_UNCOMMITTED)); result.put("TRANSACTION_NONE", NumberValue.of(Connection.TRANSACTION_NONE));
ScopeHandler.setConstant("TRANSACTION_REPEATABLE_READ", NumberValue.of(Connection.TRANSACTION_REPEATABLE_READ)); result.put("TRANSACTION_READ_COMMITTED", NumberValue.of(Connection.TRANSACTION_READ_COMMITTED));
ScopeHandler.setConstant("TRANSACTION_SERIALIZABLE", NumberValue.of(Connection.TRANSACTION_SERIALIZABLE)); result.put("TRANSACTION_READ_UNCOMMITTED", NumberValue.of(Connection.TRANSACTION_READ_UNCOMMITTED));
result.put("TRANSACTION_REPEATABLE_READ", NumberValue.of(Connection.TRANSACTION_REPEATABLE_READ));
result.put("TRANSACTION_SERIALIZABLE", NumberValue.of(Connection.TRANSACTION_SERIALIZABLE));
ScopeHandler.setConstant("CLOSE_ALL_RESULTS", NumberValue.of(Statement.CLOSE_ALL_RESULTS)); result.put("CLOSE_ALL_RESULTS", NumberValue.of(Statement.CLOSE_ALL_RESULTS));
ScopeHandler.setConstant("CLOSE_CURRENT_RESULT", NumberValue.of(Statement.CLOSE_CURRENT_RESULT)); result.put("CLOSE_CURRENT_RESULT", NumberValue.of(Statement.CLOSE_CURRENT_RESULT));
ScopeHandler.setConstant("EXECUTE_FAILED", NumberValue.of(Statement.EXECUTE_FAILED)); result.put("EXECUTE_FAILED", NumberValue.of(Statement.EXECUTE_FAILED));
ScopeHandler.setConstant("KEEP_CURRENT_RESULT", NumberValue.of(Statement.KEEP_CURRENT_RESULT)); result.put("KEEP_CURRENT_RESULT", NumberValue.of(Statement.KEEP_CURRENT_RESULT));
ScopeHandler.setConstant("NO_GENERATED_KEYS", NumberValue.of(Statement.NO_GENERATED_KEYS)); result.put("NO_GENERATED_KEYS", NumberValue.of(Statement.NO_GENERATED_KEYS));
ScopeHandler.setConstant("RETURN_GENERATED_KEYS", NumberValue.of(Statement.RETURN_GENERATED_KEYS)); result.put("RETURN_GENERATED_KEYS", NumberValue.of(Statement.RETURN_GENERATED_KEYS));
ScopeHandler.setConstant("SUCCESS_NO_INFO", NumberValue.of(Statement.SUCCESS_NO_INFO)); result.put("SUCCESS_NO_INFO", NumberValue.of(Statement.SUCCESS_NO_INFO));
ScopeHandler.setConstant("CLOSE_CURSORS_AT_COMMIT", NumberValue.of(ResultSet.CLOSE_CURSORS_AT_COMMIT)); result.put("CLOSE_CURSORS_AT_COMMIT", NumberValue.of(ResultSet.CLOSE_CURSORS_AT_COMMIT));
ScopeHandler.setConstant("CONCUR_READ_ONLY", NumberValue.of(ResultSet.CONCUR_READ_ONLY)); result.put("CONCUR_READ_ONLY", NumberValue.of(ResultSet.CONCUR_READ_ONLY));
ScopeHandler.setConstant("CONCUR_UPDATABLE", NumberValue.of(ResultSet.CONCUR_UPDATABLE)); result.put("CONCUR_UPDATABLE", NumberValue.of(ResultSet.CONCUR_UPDATABLE));
ScopeHandler.setConstant("FETCH_FORWARD", NumberValue.of(ResultSet.FETCH_FORWARD)); result.put("FETCH_FORWARD", NumberValue.of(ResultSet.FETCH_FORWARD));
ScopeHandler.setConstant("FETCH_REVERSE", NumberValue.of(ResultSet.FETCH_REVERSE)); result.put("FETCH_REVERSE", NumberValue.of(ResultSet.FETCH_REVERSE));
ScopeHandler.setConstant("FETCH_UNKNOWN", NumberValue.of(ResultSet.FETCH_UNKNOWN)); result.put("FETCH_UNKNOWN", NumberValue.of(ResultSet.FETCH_UNKNOWN));
ScopeHandler.setConstant("HOLD_CURSORS_OVER_COMMIT", NumberValue.of(ResultSet.HOLD_CURSORS_OVER_COMMIT)); result.put("HOLD_CURSORS_OVER_COMMIT", NumberValue.of(ResultSet.HOLD_CURSORS_OVER_COMMIT));
ScopeHandler.setConstant("TYPE_FORWARD_ONLY", NumberValue.of(ResultSet.TYPE_FORWARD_ONLY)); result.put("TYPE_FORWARD_ONLY", NumberValue.of(ResultSet.TYPE_FORWARD_ONLY));
ScopeHandler.setConstant("TYPE_SCROLL_INSENSITIVE", NumberValue.of(ResultSet.TYPE_SCROLL_INSENSITIVE)); result.put("TYPE_SCROLL_INSENSITIVE", NumberValue.of(ResultSet.TYPE_SCROLL_INSENSITIVE));
ScopeHandler.setConstant("TYPE_SCROLL_SENSITIVE", NumberValue.of(ResultSet.TYPE_SCROLL_SENSITIVE)); result.put("TYPE_SCROLL_SENSITIVE", NumberValue.of(ResultSet.TYPE_SCROLL_SENSITIVE));
return result;
} }
@Override @Override
public void init() { public Map<String, com.annimon.ownlang.lib.Function> functions() {
initConstants(); return Map.of(
ScopeHandler.setFunction("getConnection", getConnectionFunction()); "getConnection", getConnectionFunction(),
ScopeHandler.setFunction("sqlite", getConnectionFunction("jdbc:sqlite:")); "sqlite", getConnectionFunction("jdbc:sqlite:"),
ScopeHandler.setFunction("mysql", getConnectionFunction("jdbc:")); "mysql", getConnectionFunction("jdbc:")
);
} }
private static com.annimon.ownlang.lib.Function getConnectionFunction() { private static com.annimon.ownlang.lib.Function getConnectionFunction() {

View File

@ -1,7 +1,10 @@
package com.annimon.ownlang.modules.json; package com.annimon.ownlang.modules.json;
import com.annimon.ownlang.lib.ScopeHandler; import com.annimon.ownlang.lib.Function;
import com.annimon.ownlang.lib.Value;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.Collections;
import java.util.Map;
/** /**
* *
@ -9,13 +12,16 @@ import com.annimon.ownlang.modules.Module;
*/ */
public final class json implements Module { public final class json implements Module {
public static void initConstants() { @Override
public Map<String, Value> constants() {
return Collections.emptyMap();
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.of(
ScopeHandler.setFunction("jsonencode", new json_encode()); "jsonencode", new json_encode(),
ScopeHandler.setFunction("jsondecode", new json_decode()); "jsondecode", new json_decode()
);
} }
} }

View File

@ -2,6 +2,8 @@ package com.annimon.ownlang.modules.math;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.DoubleBinaryOperator; import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleFunction; import java.util.function.DoubleFunction;
import java.util.function.DoubleUnaryOperator; import java.util.function.DoubleUnaryOperator;
@ -15,50 +17,54 @@ public final class math implements Module {
private static final DoubleFunction<NumberValue> doubleToNumber = NumberValue::of; private static final DoubleFunction<NumberValue> doubleToNumber = NumberValue::of;
public static void initConstants() { @Override
ScopeHandler.setConstant("PI", NumberValue.of(Math.PI)); public Map<String, Value> constants() {
ScopeHandler.setConstant("E", NumberValue.of(Math.E)); return Map.of(
"PI", NumberValue.of(Math.PI),
"E", NumberValue.of(Math.E)
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); final var result = new LinkedHashMap<String, Function>(16);
ScopeHandler.setFunction("abs", math::abs); result.put("abs", math::abs);
ScopeHandler.setFunction("acos", functionConvert(Math::acos)); result.put("acos", functionConvert(Math::acos));
ScopeHandler.setFunction("asin", functionConvert(Math::asin)); result.put("asin", functionConvert(Math::asin));
ScopeHandler.setFunction("atan", functionConvert(Math::atan)); result.put("atan", functionConvert(Math::atan));
ScopeHandler.setFunction("atan2", biFunctionConvert(Math::atan2)); result.put("atan2", biFunctionConvert(Math::atan2));
ScopeHandler.setFunction("cbrt", functionConvert(Math::cbrt)); result.put("cbrt", functionConvert(Math::cbrt));
ScopeHandler.setFunction("ceil", functionConvert(Math::ceil)); result.put("ceil", functionConvert(Math::ceil));
ScopeHandler.setFunction("copySign", math::copySign); result.put("copySign", math::copySign);
ScopeHandler.setFunction("cos", functionConvert(Math::cos)); result.put("cos", functionConvert(Math::cos));
ScopeHandler.setFunction("cosh", functionConvert(Math::cosh)); result.put("cosh", functionConvert(Math::cosh));
ScopeHandler.setFunction("exp", functionConvert(Math::exp)); result.put("exp", functionConvert(Math::exp));
ScopeHandler.setFunction("expm1", functionConvert(Math::expm1)); result.put("expm1", functionConvert(Math::expm1));
ScopeHandler.setFunction("floor", functionConvert(Math::floor)); result.put("floor", functionConvert(Math::floor));
ScopeHandler.setFunction("getExponent", math::getExponent); result.put("getExponent", math::getExponent);
ScopeHandler.setFunction("hypot", biFunctionConvert(Math::hypot)); result.put("hypot", biFunctionConvert(Math::hypot));
ScopeHandler.setFunction("IEEEremainder", biFunctionConvert(Math::IEEEremainder)); result.put("IEEEremainder", biFunctionConvert(Math::IEEEremainder));
ScopeHandler.setFunction("log", functionConvert(Math::log)); result.put("log", functionConvert(Math::log));
ScopeHandler.setFunction("log1p", functionConvert(Math::log1p)); result.put("log1p", functionConvert(Math::log1p));
ScopeHandler.setFunction("log10", functionConvert(Math::log10)); result.put("log10", functionConvert(Math::log10));
ScopeHandler.setFunction("max", math::max); result.put("max", math::max);
ScopeHandler.setFunction("min", math::min); result.put("min", math::min);
ScopeHandler.setFunction("nextAfter", math::nextAfter); result.put("nextAfter", math::nextAfter);
ScopeHandler.setFunction("nextUp", functionConvert(Math::nextUp, Math::nextUp)); result.put("nextUp", functionConvert(Math::nextUp, Math::nextUp));
ScopeHandler.setFunction("nextDown", functionConvert(Math::nextDown, Math::nextDown)); result.put("nextDown", functionConvert(Math::nextDown, Math::nextDown));
ScopeHandler.setFunction("pow", biFunctionConvert(Math::pow)); result.put("pow", biFunctionConvert(Math::pow));
ScopeHandler.setFunction("rint", functionConvert(Math::rint)); result.put("rint", functionConvert(Math::rint));
ScopeHandler.setFunction("round", math::round); result.put("round", math::round);
ScopeHandler.setFunction("signum", functionConvert(Math::signum, Math::signum)); result.put("signum", functionConvert(Math::signum, Math::signum));
ScopeHandler.setFunction("sin", functionConvert(Math::sin)); result.put("sin", functionConvert(Math::sin));
ScopeHandler.setFunction("sinh", functionConvert(Math::sinh)); result.put("sinh", functionConvert(Math::sinh));
ScopeHandler.setFunction("sqrt", functionConvert(Math::sqrt)); result.put("sqrt", functionConvert(Math::sqrt));
ScopeHandler.setFunction("tan", functionConvert(Math::tan)); result.put("tan", functionConvert(Math::tan));
ScopeHandler.setFunction("tanh", functionConvert(Math::tanh)); result.put("tanh", functionConvert(Math::tanh));
ScopeHandler.setFunction("toDegrees", functionConvert(Math::toDegrees)); result.put("toDegrees", functionConvert(Math::toDegrees));
ScopeHandler.setFunction("toRadians", functionConvert(Math::toRadians)); result.put("toRadians", functionConvert(Math::toRadians));
ScopeHandler.setFunction("ulp", functionConvert(Math::ulp, Math::ulp)); result.put("ulp", functionConvert(Math::ulp, Math::ulp));
return result;
} }
private static Value abs(Value[] args) { private static Value abs(Value[] args) {

View File

@ -8,12 +8,15 @@ import okhttp3.MediaType;
import okhttp3.MultipartBody; import okhttp3.MultipartBody;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import okhttp3.RequestBody; import okhttp3.RequestBody;
import java.util.Collections;
import java.util.Map;
public final class okhttp implements Module { public final class okhttp implements Module {
private static final HttpClientValue defaultClient = new HttpClientValue(new OkHttpClient()); private static final HttpClientValue defaultClient = new HttpClientValue(new OkHttpClient());
public static void initConstants() { @Override
public Map<String, Value> constants() {
MapValue requestBody = new MapValue(5); MapValue requestBody = new MapValue(5);
requestBody.set("bytes", args -> { requestBody.set("bytes", args -> {
Arguments.checkOrOr(2, 4, args.length); Arguments.checkOrOr(2, 4, args.length);
@ -49,27 +52,30 @@ public final class okhttp implements Module {
args[1].asString() args[1].asString()
)); ));
}); });
ScopeHandler.setConstant("RequestBody", requestBody);
MapValue multipartBody = new MapValue(10); MapValue multipartBody = new MapValue(6);
multipartBody.set("ALTERNATIVE", new StringValue(MultipartBody.ALTERNATIVE.toString())); multipartBody.set("ALTERNATIVE", new StringValue(MultipartBody.ALTERNATIVE.toString()));
multipartBody.set("DIGEST", new StringValue(MultipartBody.DIGEST.toString())); multipartBody.set("DIGEST", new StringValue(MultipartBody.DIGEST.toString()));
multipartBody.set("FORM", new StringValue(MultipartBody.FORM.toString())); multipartBody.set("FORM", new StringValue(MultipartBody.FORM.toString()));
multipartBody.set("MIXED", new StringValue(MultipartBody.MIXED.toString())); multipartBody.set("MIXED", new StringValue(MultipartBody.MIXED.toString()));
multipartBody.set("PARALLEL", new StringValue(MultipartBody.PARALLEL.toString())); multipartBody.set("PARALLEL", new StringValue(MultipartBody.PARALLEL.toString()));
multipartBody.set("builder", args -> new MultipartBodyBuilderValue()); multipartBody.set("builder", args -> new MultipartBodyBuilderValue());
ScopeHandler.setConstant("MultipartBody", multipartBody);
MapValue okhttp = new MapValue(5); MapValue okhttp = new MapValue(3);
okhttp.set("client", defaultClient); okhttp.set("client", defaultClient);
okhttp.set("request", args -> new RequestBuilderValue()); okhttp.set("request", args -> new RequestBuilderValue());
ScopeHandler.setConstant("okhttp", okhttp);
return Map.of(
"RequestBody", requestBody,
"MultipartBody", multipartBody,
"okhttp", okhttp
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Collections.emptyMap();
} }
} }

View File

@ -4,7 +4,10 @@ import com.annimon.ownlang.Console;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
* *
@ -12,18 +15,21 @@ import java.util.List;
*/ */
public final class ounit implements Module { public final class ounit implements Module {
public static void initConstants() { @Override
public Map<String, Value> constants() {
return Collections.emptyMap();
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); final var result = new LinkedHashMap<String, Function>(16);
ScopeHandler.setFunction("assertEquals", new assertEquals()); result.put("assertEquals", new assertEquals());
ScopeHandler.setFunction("assertNotEquals", new assertNotEquals()); result.put("assertNotEquals", new assertNotEquals());
ScopeHandler.setFunction("assertSameType", new assertSameType()); result.put("assertSameType", new assertSameType());
ScopeHandler.setFunction("assertTrue", new assertTrue()); result.put("assertTrue", new assertTrue());
ScopeHandler.setFunction("assertFalse", new assertFalse()); result.put("assertFalse", new assertFalse());
ScopeHandler.setFunction("runTests", new runTests()); result.put("runTests", new runTests());
return result;
} }
private static String microsToSeconds(long micros) { private static String microsToSeconds(long micros) {
@ -35,7 +41,7 @@ public final class ounit implements Module {
public Value execute(Value[] args) { public Value execute(Value[] args) {
Arguments.check(2, args.length); Arguments.check(2, args.length);
if (args[0].equals(args[1])) return NumberValue.ONE; if (args[0].equals(args[1])) return NumberValue.ONE;
throw new OUnitAssertionException("Values are not equals: " throw new OUnitAssertionException("Values are not equal: "
+ "1: " + args[0] + ", 2: " + args[1]); + "1: " + args[0] + ", 2: " + args[1]);
} }
} }
@ -45,7 +51,7 @@ public final class ounit implements Module {
public Value execute(Value[] args) { public Value execute(Value[] args) {
Arguments.check(2, args.length); Arguments.check(2, args.length);
if (!args[0].equals(args[1])) return NumberValue.ONE; if (!args[0].equals(args[1])) return NumberValue.ONE;
throw new OUnitAssertionException("Values are equals: " + args[0]); throw new OUnitAssertionException("Values are equal: " + args[0]);
} }
} }

View File

@ -2,11 +2,13 @@ package com.annimon.ownlang.modules.regex;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.Map;
import java.util.regex.Pattern; import java.util.regex.Pattern;
public final class regex implements Module { public final class regex implements Module {
public static void initConstants() { @Override
public Map<String, Value> constants() {
MapValue map = new MapValue(20); MapValue map = new MapValue(20);
map.set("UNIX_LINES", NumberValue.of(Pattern.UNIX_LINES)); map.set("UNIX_LINES", NumberValue.of(Pattern.UNIX_LINES));
map.set("I", NumberValue.of(Pattern.CASE_INSENSITIVE)); map.set("I", NumberValue.of(Pattern.CASE_INSENSITIVE));
@ -37,13 +39,12 @@ public final class regex implements Module {
return ArrayValue.of(pattern.split(args[1].asString(), limit)); return ArrayValue.of(pattern.split(args[1].asString(), limit));
}); });
map.set("compile", regex::compile); map.set("compile", regex::compile);
ScopeHandler.setConstant("Pattern", map); return Map.of("Pattern", map);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.of("regex", regex::compile);
ScopeHandler.setFunction("regex", regex::compile);
} }
private static Value compile(Value[] args) { private static Value compile(Value[] args) {

View File

@ -9,6 +9,7 @@ import java.awt.event.KeyEvent;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.function.IntConsumer; import java.util.function.IntConsumer;
import static java.util.Map.entry;
/** /**
* *
@ -28,50 +29,42 @@ public final class robot implements Module {
private static Robot awtRobot; private static Robot awtRobot;
public static void initConstants() { @Override
ScopeHandler.setConstant("VK_DOWN", NumberValue.of(KeyEvent.VK_DOWN)); public Map<String, Value> constants() {
ScopeHandler.setConstant("VK_LEFT", NumberValue.of(KeyEvent.VK_LEFT)); return Map.ofEntries(
ScopeHandler.setConstant("VK_RIGHT", NumberValue.of(KeyEvent.VK_RIGHT)); entry("VK_DOWN", NumberValue.of(KeyEvent.VK_DOWN)),
ScopeHandler.setConstant("VK_FIRE", NumberValue.of(KeyEvent.VK_ENTER)); entry("VK_LEFT", NumberValue.of(KeyEvent.VK_LEFT)),
ScopeHandler.setConstant("VK_ESCAPE", NumberValue.of(KeyEvent.VK_ESCAPE)); entry("VK_RIGHT", NumberValue.of(KeyEvent.VK_RIGHT)),
entry("VK_FIRE", NumberValue.of(KeyEvent.VK_ENTER)),
entry("VK_ESCAPE", NumberValue.of(KeyEvent.VK_ESCAPE)),
ScopeHandler.setConstant("BUTTON1", NumberValue.of(InputEvent.BUTTON1_MASK)); entry("BUTTON1", NumberValue.of(InputEvent.BUTTON1_MASK)),
ScopeHandler.setConstant("BUTTON2", NumberValue.of(InputEvent.BUTTON2_MASK)); entry("BUTTON2", NumberValue.of(InputEvent.BUTTON2_MASK)),
ScopeHandler.setConstant("BUTTON3", NumberValue.of(InputEvent.BUTTON3_MASK)); entry("BUTTON3", NumberValue.of(InputEvent.BUTTON3_MASK))
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); final var result = new HashMap<String, Function>(16);
boolean isRobotInitialized = initialize(); boolean isRobotInitialized = initialize();
if (isRobotInitialized) { if (isRobotInitialized) {
ScopeHandler.setFunction("click", convertFunction(robot::click)); result.put("click", convertFunction(robot::click));
ScopeHandler.setFunction("delay", convertFunction(awtRobot::delay)); result.put("delay", convertFunction(awtRobot::delay));
ScopeHandler.setFunction("setAutoDelay", convertFunction(awtRobot::setAutoDelay)); result.put("setAutoDelay", convertFunction(awtRobot::setAutoDelay));
ScopeHandler.setFunction("keyPress", convertFunction(awtRobot::keyPress)); result.put("keyPress", convertFunction(awtRobot::keyPress));
ScopeHandler.setFunction("keyRelease", convertFunction(awtRobot::keyRelease)); result.put("keyRelease", convertFunction(awtRobot::keyRelease));
ScopeHandler.setFunction("mousePress", convertFunction(awtRobot::mousePress)); result.put("mousePress", convertFunction(awtRobot::mousePress));
ScopeHandler.setFunction("mouseRelease", convertFunction(awtRobot::mouseRelease)); result.put("mouseRelease", convertFunction(awtRobot::mouseRelease));
ScopeHandler.setFunction("mouseWheel", convertFunction(awtRobot::mouseWheel)); result.put("mouseWheel", convertFunction(awtRobot::mouseWheel));
ScopeHandler.setFunction("mouseMove", (args) -> { result.put("mouseMove", this::mouseMove);
Arguments.check(2, args.length); result.put("typeText",this::typeText);
try { result.put("toClipboard", new robot_toclipboard());
awtRobot.mouseMove(args[0].asInt(), args[1].asInt()); result.put("fromClipboard", new robot_fromclipboard());
} catch (IllegalArgumentException iae) { }
return NumberValue.ZERO;
});
ScopeHandler.setFunction("typeText", (args) -> {
Arguments.check(1, args.length);
try {
typeText(args[0].asString());
} catch (IllegalArgumentException iae) { }
return NumberValue.ZERO;
});
ScopeHandler.setFunction("toClipboard", new robot_toclipboard());
ScopeHandler.setFunction("fromClipboard", new robot_fromclipboard());
} }
ScopeHandler.setFunction("execProcess", new robot_exec(robot_exec.Mode.EXEC)); result.put("execProcess", new robot_exec(robot_exec.Mode.EXEC));
ScopeHandler.setFunction("execProcessAndWait", new robot_exec(robot_exec.Mode.EXEC_AND_WAIT)); result.put("execProcessAndWait", new robot_exec(robot_exec.Mode.EXEC_AND_WAIT));
return result;
} }
private static boolean initialize() { private static boolean initialize() {
@ -84,6 +77,22 @@ public final class robot implements Module {
} }
} }
private Value mouseMove(Value[] args) {
Arguments.check(2, args.length);
try {
awtRobot.mouseMove(args[0].asInt(), args[1].asInt());
} catch (IllegalArgumentException iae) { }
return NumberValue.ZERO;
}
private Value typeText(Value[] args) {
Arguments.check(1, args.length);
try {
typeText(args[0].asString());
} catch (IllegalArgumentException iae) { }
return NumberValue.ZERO;
}
private static Function convertFunction(IntConsumer consumer) { private static Function convertFunction(IntConsumer consumer) {
return args -> { return args -> {
Arguments.check(1, args.length); Arguments.check(1, args.length);

View File

@ -6,6 +6,8 @@ import com.annimon.ownlang.modules.Module;
import io.socket.client.IO; import io.socket.client.IO;
import io.socket.client.Socket; import io.socket.client.Socket;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.LinkedHashMap;
import java.util.Map;
/** /**
* socket.io module. * socket.io module.
@ -14,27 +16,29 @@ import java.net.URISyntaxException;
*/ */
public final class socket implements Module { public final class socket implements Module {
public static void initConstants() { @Override
ScopeHandler.setConstant("EVENT_CONNECT", new StringValue(Socket.EVENT_CONNECT)); public Map<String, Value> constants() {
ScopeHandler.setConstant("EVENT_CONNECTING", new StringValue(Socket.EVENT_CONNECTING)); final var result = new LinkedHashMap<String, Value>(15);
ScopeHandler.setConstant("EVENT_CONNECT_ERROR", new StringValue(Socket.EVENT_CONNECT_ERROR)); result.put("EVENT_CONNECT", new StringValue(Socket.EVENT_CONNECT));
ScopeHandler.setConstant("EVENT_CONNECT_TIMEOUT", new StringValue(Socket.EVENT_CONNECT_TIMEOUT)); result.put("EVENT_CONNECTING", new StringValue(Socket.EVENT_CONNECTING));
ScopeHandler.setConstant("EVENT_DISCONNECT", new StringValue(Socket.EVENT_DISCONNECT)); result.put("EVENT_CONNECT_ERROR", new StringValue(Socket.EVENT_CONNECT_ERROR));
ScopeHandler.setConstant("EVENT_ERROR", new StringValue(Socket.EVENT_ERROR)); result.put("EVENT_CONNECT_TIMEOUT", new StringValue(Socket.EVENT_CONNECT_TIMEOUT));
ScopeHandler.setConstant("EVENT_MESSAGE", new StringValue(Socket.EVENT_MESSAGE)); result.put("EVENT_DISCONNECT", new StringValue(Socket.EVENT_DISCONNECT));
ScopeHandler.setConstant("EVENT_PING", new StringValue(Socket.EVENT_PING)); result.put("EVENT_ERROR", new StringValue(Socket.EVENT_ERROR));
ScopeHandler.setConstant("EVENT_PONG", new StringValue(Socket.EVENT_PONG)); result.put("EVENT_MESSAGE", new StringValue(Socket.EVENT_MESSAGE));
ScopeHandler.setConstant("EVENT_RECONNECT", new StringValue(Socket.EVENT_RECONNECT)); result.put("EVENT_PING", new StringValue(Socket.EVENT_PING));
ScopeHandler.setConstant("EVENT_RECONNECTING", new StringValue(Socket.EVENT_RECONNECTING)); result.put("EVENT_PONG", new StringValue(Socket.EVENT_PONG));
ScopeHandler.setConstant("EVENT_RECONNECT_ATTEMPT", new StringValue(Socket.EVENT_RECONNECT_ATTEMPT)); result.put("EVENT_RECONNECT", new StringValue(Socket.EVENT_RECONNECT));
ScopeHandler.setConstant("EVENT_RECONNECT_ERROR", new StringValue(Socket.EVENT_RECONNECT_ERROR)); result.put("EVENT_RECONNECTING", new StringValue(Socket.EVENT_RECONNECTING));
ScopeHandler.setConstant("EVENT_RECONNECT_FAILED", new StringValue(Socket.EVENT_RECONNECT_FAILED)); result.put("EVENT_RECONNECT_ATTEMPT", new StringValue(Socket.EVENT_RECONNECT_ATTEMPT));
result.put("EVENT_RECONNECT_ERROR", new StringValue(Socket.EVENT_RECONNECT_ERROR));
result.put("EVENT_RECONNECT_FAILED", new StringValue(Socket.EVENT_RECONNECT_FAILED));
return result;
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.of("newSocket", socket::newSocket);
ScopeHandler.setFunction("newSocket", socket::newSocket);
} }
private static Value newSocket(Value[] args) { private static Value newSocket(Value[] args) {

View File

@ -4,6 +4,8 @@ import com.annimon.ownlang.Shared;
import com.annimon.ownlang.Version; import com.annimon.ownlang.Version;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.Map;
import static java.util.Map.entry;
/** /**
* *
@ -11,63 +13,68 @@ import com.annimon.ownlang.modules.Module;
*/ */
public final class std implements Module { public final class std implements Module {
public static void initConstants() { @Override
public Map<String, Value> constants() {
MapValue ownlang = new MapValue(5); MapValue ownlang = new MapValue(5);
ownlang.set("PLATFORM", new StringValue("desktop")); ownlang.set("PLATFORM", new StringValue("desktop"));
ownlang.set("VERSION", new StringValue(Version.VERSION)); ownlang.set("VERSION", new StringValue(Version.VERSION));
ownlang.set("VERSION_MAJOR", NumberValue.of(Version.VERSION_MAJOR)); ownlang.set("VERSION_MAJOR", NumberValue.of(Version.VERSION_MAJOR));
ownlang.set("VERSION_MINOR", NumberValue.of(Version.VERSION_MINOR)); ownlang.set("VERSION_MINOR", NumberValue.of(Version.VERSION_MINOR));
ownlang.set("VERSION_PATCH", NumberValue.of(Version.VERSION_PATCH)); ownlang.set("VERSION_PATCH", NumberValue.of(Version.VERSION_PATCH));
ScopeHandler.setConstant("OwnLang", ownlang);
return Map.of(
"OwnLang", ownlang,
"ARGS", ArrayValue.of(Shared.getOwnlangArgs())
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.ofEntries(
ScopeHandler.setConstant("ARGS", ArrayValue.of(Shared.getOwnlangArgs())); // is not constant entry("echo", new std_echo()),
ScopeHandler.setFunction("echo", new std_echo()); entry("readln", new std_readln()),
ScopeHandler.setFunction("readln", new std_readln()); entry("length", new std_length()),
ScopeHandler.setFunction("length", new std_length()); entry("rand", new std_rand()),
ScopeHandler.setFunction("rand", new std_rand()); entry("time", new std_time()),
ScopeHandler.setFunction("time", new std_time()); entry("sleep", new std_sleep()),
ScopeHandler.setFunction("sleep", new std_sleep()); entry("thread", new std_thread()),
ScopeHandler.setFunction("thread", new std_thread()); entry("sync", new std_sync()),
ScopeHandler.setFunction("sync", new std_sync()); entry("try", new std_try()),
ScopeHandler.setFunction("try", new std_try()); entry("default", new std_default()),
ScopeHandler.setFunction("default", new std_default());
// Numbers // Numbers
ScopeHandler.setFunction("toHexString", NumberFunctions::toHexString); entry("toHexString", NumberFunctions::toHexString),
// String // String
ScopeHandler.setFunction("getBytes", StringFunctions::getBytes); entry("getBytes", StringFunctions::getBytes),
ScopeHandler.setFunction("sprintf", new std_sprintf()); entry("sprintf", new std_sprintf()),
ScopeHandler.setFunction("split", new std_split()); entry("split", new std_split()),
ScopeHandler.setFunction("indexOf", new std_indexof()); entry("indexOf", new std_indexof()),
ScopeHandler.setFunction("lastIndexOf", new std_lastindexof()); entry("lastIndexOf", new std_lastindexof()),
ScopeHandler.setFunction("charAt", new std_charat()); entry("charAt", new std_charat()),
ScopeHandler.setFunction("toChar", new std_tochar()); entry("toChar", new std_tochar()),
ScopeHandler.setFunction("substring", new std_substring()); entry("substring", new std_substring()),
ScopeHandler.setFunction("toLowerCase", new std_tolowercase()); entry("toLowerCase", new std_tolowercase()),
ScopeHandler.setFunction("toUpperCase", new std_touppercase()); entry("toUpperCase", new std_touppercase()),
ScopeHandler.setFunction("trim", new std_trim()); entry("trim", new std_trim()),
ScopeHandler.setFunction("replace", new std_replace()); entry("replace", new std_replace()),
ScopeHandler.setFunction("replaceAll", new std_replaceall()); entry("replaceAll", new std_replaceall()),
ScopeHandler.setFunction("replaceFirst", new std_replacefirst()); entry("replaceFirst", new std_replacefirst()),
ScopeHandler.setFunction("parseInt", StringFunctions::parseInt); entry("parseInt", StringFunctions::parseInt),
ScopeHandler.setFunction("parseLong", StringFunctions::parseLong); entry("parseLong", StringFunctions::parseLong),
ScopeHandler.setFunction("stripMargin", StringFunctions::stripMargin); entry("stripMargin", StringFunctions::stripMargin),
// Arrays and maps // Arrays and map,
ScopeHandler.setFunction("newarray", new std_newarray()); entry("newarray", new std_newarray()),
ScopeHandler.setFunction("join", new std_join()); entry("join", new std_join()),
ScopeHandler.setFunction("sort", new std_sort()); entry("sort", new std_sort()),
ScopeHandler.setFunction("arrayCombine", new std_arrayCombine()); entry("arrayCombine", new std_arrayCombine()),
ScopeHandler.setFunction("arrayKeyExists", new std_arrayKeyExists()); entry("arrayKeyExists", new std_arrayKeyExists()),
ScopeHandler.setFunction("arrayKeys", new std_arrayKeys()); entry("arrayKeys", new std_arrayKeys()),
ScopeHandler.setFunction("arrayValues", new std_arrayValues()); entry("arrayValues", new std_arrayValues()),
ScopeHandler.setFunction("arraySplice", new std_arraySplice()); entry("arraySplice", new std_arraySplice()),
ScopeHandler.setFunction("range", new std_range()); entry("range", new std_range()),
ScopeHandler.setFunction("stringFromBytes", ArrayFunctions::stringFromBytes); entry("stringFromBytes", ArrayFunctions::stringFromBytes)
);
} }
} }

View File

@ -2,6 +2,8 @@ package com.annimon.ownlang.modules.types;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.Map;
import static java.util.Map.entry;
/** /**
* *
@ -9,27 +11,31 @@ import com.annimon.ownlang.modules.Module;
*/ */
public final class types implements Module { public final class types implements Module {
public static void initConstants() { @Override
ScopeHandler.setConstant("OBJECT", NumberValue.of(Types.OBJECT)); public Map<String, Value> constants() {
ScopeHandler.setConstant("NUMBER", NumberValue.of(Types.NUMBER)); return Map.ofEntries(
ScopeHandler.setConstant("STRING", NumberValue.of(Types.STRING)); entry("OBJECT", NumberValue.of(Types.OBJECT)),
ScopeHandler.setConstant("ARRAY", NumberValue.of(Types.ARRAY)); entry("NUMBER", NumberValue.of(Types.NUMBER)),
ScopeHandler.setConstant("MAP", NumberValue.of(Types.MAP)); entry("STRING", NumberValue.of(Types.STRING)),
ScopeHandler.setConstant("FUNCTION", NumberValue.of(Types.FUNCTION)); entry("ARRAY", NumberValue.of(Types.ARRAY)),
entry("MAP", NumberValue.of(Types.MAP)),
entry("FUNCTION", NumberValue.of(Types.FUNCTION))
);
} }
@Override @Override
public void init() { public Map<String, Function> functions() {
initConstants(); return Map.ofEntries(
ScopeHandler.setFunction("typeof", args -> NumberValue.of(args[0].type())); entry("typeof", args -> NumberValue.of(args[0].type())),
ScopeHandler.setFunction("string", args -> new StringValue(args[0].asString())); entry("string", args -> new StringValue(args[0].asString())),
ScopeHandler.setFunction("number", args -> NumberValue.of(args[0].asNumber())); entry("number", args -> NumberValue.of(args[0].asNumber())),
ScopeHandler.setFunction("byte", args -> NumberValue.of((byte)args[0].asInt())); entry("byte", args -> NumberValue.of((byte)args[0].asInt())),
ScopeHandler.setFunction("short", args -> NumberValue.of((short)args[0].asInt())); entry("short", args -> NumberValue.of((short)args[0].asInt())),
ScopeHandler.setFunction("int", args -> NumberValue.of(args[0].asInt())); entry("int", args -> NumberValue.of(args[0].asInt())),
ScopeHandler.setFunction("long", args -> NumberValue.of((long)args[0].asNumber())); entry("long", args -> NumberValue.of((long)args[0].asNumber())),
ScopeHandler.setFunction("float", args -> NumberValue.of((float)args[0].asNumber())); entry("float", args -> NumberValue.of((float)args[0].asNumber())),
ScopeHandler.setFunction("double", args -> NumberValue.of(args[0].asNumber())); entry("double", args -> NumberValue.of(args[0].asNumber()))
);
} }
} }

View File

@ -2,6 +2,8 @@ package com.annimon.ownlang.modules.yaml;
import com.annimon.ownlang.lib.*; import com.annimon.ownlang.lib.*;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.util.Collections;
import java.util.Map;
/** /**
* *
@ -10,8 +12,15 @@ import com.annimon.ownlang.modules.Module;
public final class yaml implements Module { public final class yaml implements Module {
@Override @Override
public void init() { public Map<String, Value> constants() {
ScopeHandler.setFunction("yamlencode", new yaml_encode()); return Collections.emptyMap();
ScopeHandler.setFunction("yamldecode", new yaml_decode()); }
@Override
public Map<String, Function> functions() {
return Map.of(
"yamlencode", new yaml_encode(),
"yamldecode", new yaml_decode()
);
} }
} }

View File

@ -9,23 +9,28 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.util.ArrayList; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import static java.util.Map.entry;
public class zip implements Module { public class zip implements Module {
@Override @Override
public void init() { public Map<String, Value> constants() {
ScopeHandler.setFunction("zip", this::zipWithMapper); return Collections.emptyMap();
ScopeHandler.setFunction("zipFiles", this::zipFiles); }
ScopeHandler.setFunction("unzip", this::unzip);
ScopeHandler.setFunction("unzipFiles", this::unzipFiles); @Override
ScopeHandler.setFunction("listZipEntries", this::listZipEntries); public Map<String, Function> functions() {
return Map.ofEntries(
entry("zip", this::zipWithMapper),
entry("zipFiles", this::zipFiles),
entry("unzip", this::unzip),
entry("unzipFiles", this::unzipFiles),
entry("listZipEntries", this::listZipEntries)
);
} }
private Value zipWithMapper(Value[] args) { private Value zipWithMapper(Value[] args) {

View File

@ -0,0 +1,28 @@
package com.annimon.ownlang.lib;
import com.annimon.ownlang.modules.Module;
public final class ModuleLoader {
private static final String PACKAGE = "com.annimon.ownlang.modules.%s.%s";
private ModuleLoader() { }
public static Module load(String name) {
try {
return (Module) Class.forName(String.format(PACKAGE, name, name))
.getDeclaredConstructor()
.newInstance();
} catch (Exception ex) {
throw new RuntimeException("Unable to load module " + name, ex);
}
}
public static void loadAndUse(String name) {
final var rootScope = ScopeHandler.rootScope();
if (rootScope.isModuleLoaded(name)) return;
final var module = load(name);
rootScope.getConstants().putAll(module.constants());
rootScope.getFunctions().putAll(module.functions());
}
}

View File

@ -1,17 +1,21 @@
package com.annimon.ownlang.lib; package com.annimon.ownlang.lib;
import java.util.Map; import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
final class RootScope extends Scope { final class RootScope extends Scope {
private final Map<String, Value> constants; private final Map<String, Value> constants;
private final Map<String, Function> functions; private final Map<String, Function> functions;
private final Set<String> loadedModules;
RootScope() { RootScope() {
functions = new ConcurrentHashMap<>(); functions = new ConcurrentHashMap<>();
constants = new ConcurrentHashMap<>(); constants = new ConcurrentHashMap<>();
constants.put("true", NumberValue.ONE); constants.put("true", NumberValue.ONE);
constants.put("false", NumberValue.ZERO); constants.put("false", NumberValue.ZERO);
loadedModules = new CopyOnWriteArraySet<>();
} }
@Override @Override
@ -65,4 +69,17 @@ final class RootScope extends Scope {
public Map<String, Function> getFunctions() { public Map<String, Function> getFunctions() {
return functions; return functions;
} }
public Set<String> getLoadedModules() {
return loadedModules;
}
public boolean isModuleLoaded(String name) {
return loadedModules.contains(name);
}
public void addLoadedModule(String name) {
loadedModules.add(name);
}
} }

View File

@ -28,6 +28,10 @@ public final class ScopeHandler {
return rootScope.getFunctions(); return rootScope.getFunctions();
} }
static RootScope rootScope() {
return rootScope;
}
/** /**
* Resets a scope for new program execution * Resets a scope for new program execution
*/ */
@ -56,7 +60,6 @@ public final class ScopeHandler {
} }
public static boolean isFunctionExists(String name) { public static boolean isFunctionExists(String name) {
return rootScope.containsFunction(name); return rootScope.containsFunction(name);
} }

View File

@ -1,10 +1,16 @@
package com.annimon.ownlang.modules; package com.annimon.ownlang.modules;
import com.annimon.ownlang.lib.Function;
import com.annimon.ownlang.lib.Value;
import java.util.Map;
/** /**
* * Main interface for modules
* @author aNNiMON * @author aNNiMON
*/ */
public interface Module { public interface Module {
void init(); Map<String, Value> constants();
Map<String, Function> functions();
} }

View File

@ -1,18 +1,17 @@
package com.annimon.ownlang.parser.ast; package com.annimon.ownlang.parser.ast;
import com.annimon.ownlang.lib.ModuleLoader;
import com.annimon.ownlang.lib.Value;
import com.annimon.ownlang.modules.Module; import com.annimon.ownlang.modules.Module;
import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
/** /**
* *
* @author aNNiMON * @author aNNiMON
*/ */
public final class UseStatement extends InterruptableNode implements Statement { public final class UseStatement extends InterruptableNode implements Statement {
private static final String PACKAGE = "com.annimon.ownlang.modules.%s.%s";
private static final String INIT_CONSTANTS_METHOD = "initConstants";
public final Collection<String> modules; public final Collection<String> modules;
public UseStatement(Collection<String> modules) { public UseStatement(Collection<String> modules) {
@ -23,35 +22,17 @@ public final class UseStatement extends InterruptableNode implements Statement {
public void execute() { public void execute() {
super.interruptionCheck(); super.interruptionCheck();
for (String module : modules) { for (String module : modules) {
loadModule(module); ModuleLoader.loadAndUse(module);
} }
} }
private void loadModule(String name) { public Map<String, Value> loadConstants() {
try { final var result = new LinkedHashMap<String, Value>();
final Module module = (Module) Class.forName(String.format(PACKAGE, name, name)) for (String moduleName : modules) {
.getDeclaredConstructor() final Module module = ModuleLoader.load(moduleName);
.newInstance(); result.putAll(module.constants());
module.init();
} catch (Exception ex) {
throw new RuntimeException("Unable to load module " + name, ex);
}
}
public void loadConstants() {
for (String module : modules) {
loadConstants(module);
}
}
private void loadConstants(String moduleName) {
try {
final Class<?> moduleClass = Class.forName(String.format(PACKAGE, moduleName, moduleName));
final Method method = moduleClass.getMethod(INIT_CONSTANTS_METHOD);
method.invoke(this);
} catch (Exception ex) {
// ignore
} }
return result;
} }
@Override @Override

View File

@ -1,13 +1,11 @@
package com.annimon.ownlang.parser.optimization; package com.annimon.ownlang.parser.optimization;
import com.annimon.ownlang.lib.ScopeHandler;
import com.annimon.ownlang.lib.Value; import com.annimon.ownlang.lib.Value;
import com.annimon.ownlang.lib.Variables;
import com.annimon.ownlang.parser.ast.*; import com.annimon.ownlang.parser.ast.*;
import static com.annimon.ownlang.parser.visitors.VisitorUtils.isValue;
import static com.annimon.ownlang.parser.visitors.VisitorUtils.isVariable;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static com.annimon.ownlang.parser.visitors.VisitorUtils.isValue;
import static com.annimon.ownlang.parser.visitors.VisitorUtils.isVariable;
public class VariablesGrabber extends OptimizationVisitor<Map<String, VariableInfo>> { public class VariablesGrabber extends OptimizationVisitor<Map<String, VariableInfo>> {
@ -100,18 +98,11 @@ public class VariablesGrabber extends OptimizationVisitor<Map<String, VariableIn
@Override @Override
public Node visit(UseStatement s, Map<String, VariableInfo> t) { public Node visit(UseStatement s, Map<String, VariableInfo> t) {
if (grabModuleConstants) { if (grabModuleConstants) {
// To get module constants we need to store current constants, clear all, then load module. for (Map.Entry<String, Value> entry : s.loadConstants().entrySet()) {
final Map<String, Value> currentConstants = new HashMap<>(ScopeHandler.constants());
ScopeHandler.constants().clear();
s.loadConstants();
// Grab module constants
for (Map.Entry<String, Value> entry : ScopeHandler.constants().entrySet()) {
final VariableInfo var = variableInfo(t, entry.getKey()); final VariableInfo var = variableInfo(t, entry.getKey());
var.value = entry.getValue(); var.value = entry.getValue();
t.put(entry.getKey(), var); t.put(entry.getKey(), var);
} }
// Restore previous constants
ScopeHandler.constants().putAll(currentConstants);
} }
return super.visit(s, t); return super.visit(s, t);
} }

View File

@ -28,16 +28,12 @@ public final class ModulesInfoCreator {
.map(File::getName) .map(File::getName)
.toArray(String[]::new); .toArray(String[]::new);
for (String moduleName : moduleNames) { for (String moduleName : moduleNames) {
final String moduleClassPath = String.format("com.annimon.ownlang.modules.%s.%s", moduleName, moduleName); final Module module = ModuleLoader.load(moduleName);
Class<?> moduleClass = Class.forName(moduleClassPath);
ScopeHandler.resetScope();
final Module module = (Module) moduleClass.getDeclaredConstructor().newInstance();
module.init();
final ModuleInfo moduleInfo = new ModuleInfo(moduleName); final ModuleInfo moduleInfo = new ModuleInfo(moduleName);
moduleInfo.functions.addAll(ScopeHandler.functions().keySet()); moduleInfo.functions.addAll(module.functions().keySet());
moduleInfo.constants.putAll(ScopeHandler.constants()); moduleInfo.constants.putAll(module.constants());
moduleInfo.types.addAll(listValues(moduleClass)); moduleInfo.types.addAll(listValues(module.getClass()));
moduleInfos.add(moduleInfo); moduleInfos.add(moduleInfo);
} }