4 Commits

Author SHA1 Message Date
  kindlich 457cb2dbec
Some more tests for basic class members 4 years ago
  kindlich 4eb8d63929
Removed unused scripts, added Example script for Conway's game of life 4 years ago
  kindlich 1bf0933315
Change some logging for tests 4 years ago
  kindlich e9ab512059
Added char to JavaNativeModule 4 years ago
26 changed files with 512 additions and 425 deletions
  1. 12
    0
      JavaBytecodeCompiler/src/main/java/org/openzen/zenscript/javabytecode/compiler/definitions/JavaMemberVisitor.java
  2. 16
    14
      JavaIntegration/src/main/java/org/openzen/zencode/java/JavaNativeModule.java
  3. 1
    1
      JavaIntegration/src/main/java/org/openzen/zencode/java/logger/ScriptingEngineStreamLogger.java
  4. 30
    0
      ScriptingExample/scripts/Cell.zs
  5. 42
    0
      ScriptingExample/scripts/ConwayGrid.zs
  6. 5
    0
      ScriptingExample/scripts/ExpandRangeUsize.zs
  7. 27
    0
      ScriptingExample/scripts/GridTest.zs
  8. 0
    51
      ScriptingExample/scripts/nope/match.zs
  9. 9
    76
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/Globals.java
  10. 51
    68
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/Main.java
  11. 0
    17
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestBaseInterface.java
  12. 0
    60
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestClass.java
  13. 0
    14
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestGenericInterface.java
  14. 0
    17
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestInterface.java
  15. 0
    24
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/EventManager.java
  16. 0
    41
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/IEvent.java
  17. 0
    4
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/SomeMCEvent.java
  18. 0
    25
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/impl/CTStringedEvent.java
  19. 0
    12
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/impl/StringedEvent.java
  20. 40
    0
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/gui/SwingGrid.java
  21. 35
    0
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/gui/UpdatableGrid.java
  22. 32
    0
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/threading/TimeSpan.java
  23. 21
    0
      ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/threading/ZCThread.java
  24. 90
    0
      ScriptingExample/src/test/java/org/openzen/zenscript/scriptingexample/tests/actual_test/classes/AddingClasses.java
  25. 66
    0
      ScriptingExample/src/test/java/org/openzen/zenscript/scriptingexample/tests/helpers/ScriptBuilder.java
  26. 35
    1
      ScriptingExample/src/test/java/org/openzen/zenscript/scriptingexample/tests/helpers/ZenCodeTestLogger.java

+ 12
- 0
JavaBytecodeCompiler/src/main/java/org/openzen/zenscript/javabytecode/compiler/definitions/JavaMemberVisitor.java View File

@@ -112,6 +112,18 @@ public class JavaMemberVisitor implements MemberVisitor<Void> {
112 112
 				constructorWriter.invokeSpecial(Type.getInternalName(Object.class), "<init>", "()V");
113 113
 			}
114 114
         }
115
+    
116
+        for(IDefinitionMember membersOfSameType : member.definition.members) {
117
+            if(membersOfSameType instanceof FieldMember) {
118
+                final FieldMember fieldMember = ((FieldMember) membersOfSameType);
119
+                final Expression initializer = fieldMember.initializer;
120
+                if(initializer != null) {
121
+                    constructorWriter.loadObject(0);
122
+                    initializer.accept(statementVisitor.expressionVisitor);
123
+                    constructorWriter.putField(context.getJavaField(fieldMember));
124
+                }
125
+            }
126
+        }
115 127
 
116 128
 		for (TypeParameter typeParameter : definition.typeParameters) {
117 129
 			final JavaTypeParameterInfo typeParameterInfo = javaModule.getTypeParameterInfo(typeParameter);

+ 16
- 14
JavaIntegration/src/main/java/org/openzen/zencode/java/JavaNativeModule.java View File

@@ -78,12 +78,13 @@ public class JavaNativeModule {
78 78
 		typeByClass.put(void.class, BasicTypeID.VOID);
79 79
 		typeByClass.put(boolean.class, BasicTypeID.BOOL);
80 80
 		typeByClass.put(byte.class, BasicTypeID.SBYTE);
81
-		typeByClass.put(short.class, BasicTypeID.SHORT);
82
-		typeByClass.put(int.class, BasicTypeID.INT);
83
-		typeByClass.put(long.class, BasicTypeID.LONG);
84
-		typeByClass.put(float.class, BasicTypeID.FLOAT);
85
-		typeByClass.put(double.class, BasicTypeID.DOUBLE);
86
-		typeByClass.put(String.class, StringTypeID.INSTANCE);
81
+        typeByClass.put(char.class, BasicTypeID.CHAR);
82
+        typeByClass.put(short.class, BasicTypeID.SHORT);
83
+        typeByClass.put(int.class, BasicTypeID.INT);
84
+        typeByClass.put(long.class, BasicTypeID.LONG);
85
+        typeByClass.put(float.class, BasicTypeID.FLOAT);
86
+        typeByClass.put(double.class, BasicTypeID.DOUBLE);
87
+        typeByClass.put(String.class, StringTypeID.INSTANCE);
87 88
 		typeByClass.put(Boolean.class, registry.getOptional(BasicTypeID.BOOL));
88 89
 		typeByClass.put(Byte.class, registry.getOptional(BasicTypeID.BYTE));
89 90
 		typeByClass.put(Short.class, registry.getOptional(BasicTypeID.SHORT));
@@ -93,13 +94,14 @@ public class JavaNativeModule {
93 94
 		typeByClass.put(Double.class, registry.getOptional(BasicTypeID.DOUBLE));
94 95
 
95 96
 		unsignedByClass.put(byte.class, BasicTypeID.BYTE);
96
-		unsignedByClass.put(short.class, BasicTypeID.USHORT);
97
-		unsignedByClass.put(int.class, BasicTypeID.UINT);
98
-		unsignedByClass.put(long.class, BasicTypeID.ULONG);
99
-		unsignedByClass.put(Byte.class, registry.getOptional(BasicTypeID.BYTE));
100
-		unsignedByClass.put(Short.class, registry.getOptional(BasicTypeID.SHORT));
101
-		unsignedByClass.put(Integer.class, registry.getOptional(BasicTypeID.INT));
102
-		unsignedByClass.put(Long.class, registry.getOptional(BasicTypeID.LONG));
97
+        unsignedByClass.put(char.class, BasicTypeID.CHAR);
98
+        unsignedByClass.put(short.class, BasicTypeID.USHORT);
99
+        unsignedByClass.put(int.class, BasicTypeID.UINT);
100
+        unsignedByClass.put(long.class, BasicTypeID.ULONG);
101
+        unsignedByClass.put(Byte.class, registry.getOptional(BasicTypeID.BYTE));
102
+        unsignedByClass.put(Short.class, registry.getOptional(BasicTypeID.SHORT));
103
+        unsignedByClass.put(Integer.class, registry.getOptional(BasicTypeID.INT));
104
+        unsignedByClass.put(Long.class, registry.getOptional(BasicTypeID.LONG));
103 105
 	}
104 106
 
105 107
 	public SemanticModule toSemantic(ModuleSpace space) {
@@ -225,7 +227,7 @@ public class JavaNativeModule {
225 227
 	}
226 228
 	
227 229
 	private boolean isInBasePackage(String className) {
228
-		return className.startsWith(basePackage + ".") || className.startsWith("java.lang.") || className.startsWith("java.util.");
230
+		return className.startsWith(module.name) || className.startsWith(basePackage + ".") || className.startsWith("java.lang.") || className.startsWith("java.util.");
229 231
 	}
230 232
 
231 233
 	private ZSPackage getPackage(String className) {

+ 1
- 1
JavaIntegration/src/main/java/org/openzen/zencode/java/logger/ScriptingEngineStreamLogger.java View File

@@ -63,7 +63,7 @@ public class ScriptingEngineStreamLogger implements ScriptingEngineLogger {
63 63
     
64 64
     @Override
65 65
     public void logCompileException(CompileException exception) {
66
-        throw new UnsupportedOperationException();
66
+        throwingErr("Compile Exception:", exception);
67 67
     }
68 68
     
69 69
     @Override

+ 30
- 0
ScriptingExample/scripts/Cell.zs View File

@@ -0,0 +1,30 @@
1
+public class Cell {
2
+
3
+    public var alive as bool;
4
+    private var row as usize;
5
+    private var column as usize;
6
+
7
+    public this(row as usize, column as usize) {
8
+        this(row, column, false);
9
+    }
10
+
11
+    public this(row as usize, column as usize, alive as bool) {
12
+            this.row = row;
13
+            this.column = column;
14
+            this.alive = alive;
15
+    }
16
+
17
+    public getCellNextTick(currentGrid as ConwayGrid) as Cell {
18
+        //+2 because upperbound exclusive
19
+        var range = currentGrid[(row - 1) .. (row + 2), (column - 1) .. (column + 2)];
20
+        var aliveCellsIn3x3Grid = range.filter(element => element.alive).length;
21
+
22
+
23
+        if(!alive) {
24
+            return new Cell(row, column, aliveCellsIn3x3Grid == 3);
25
+        }
26
+
27
+        //2. Any live cell with two or three live neighbours lives on to the next generation.
28
+        return new Cell(row, column, aliveCellsIn3x3Grid == 3 || aliveCellsIn3x3Grid == 4);
29
+    }
30
+}

+ 42
- 0
ScriptingExample/scripts/ConwayGrid.zs View File

@@ -0,0 +1,42 @@
1
+import example.gui.UpdatableGrid;
2
+
3
+public class ConwayGrid {
4
+    public var cells as Cell[,];
5
+    private var width as usize;
6
+    private var height as usize;
7
+
8
+    public this(width as usize, height as usize) {
9
+        this.cells = new Cell[,](width, height, (row, column) => new Cell(row, column));
10
+        this.width = width;
11
+        this.height = height;
12
+    }
13
+
14
+    public []=(row as int, column as int, alive as bool) as void {
15
+        this.cells[row,column].alive = alive;
16
+    }
17
+
18
+    public update() as void {
19
+        var gridCapture = this;
20
+        this.cells = new Cell[,](width, height, (row, column) => gridCapture.cells[row, column].getCellNextTick(gridCapture));
21
+    }
22
+
23
+    //public [](row as usize, column as usize) as Cell => cells[row,column];
24
+
25
+    public [](rows as usize .. usize, columns as usize .. usize) as Cell[]{
26
+        var usedRows = rows.withBounds(0 .. height);
27
+        var usedColumns = columns.withBounds(0 .. width);
28
+
29
+        var rowSpan = usedRows.to - usedRows.from;
30
+        var columnSpan = usedColumns.to - usedColumns.from;
31
+        var cells = this.cells;
32
+        return new Cell[](rowSpan * columnSpan, cellNo => cells[usedRows.from + (cellNo / columnSpan), usedColumns.from + (cellNo % columnSpan)]);
33
+    }
34
+
35
+    public updateDisplay(display as UpdatableGrid) as void {
36
+        for row in 0 .. height {
37
+            for column in 0 .. width {
38
+                display[row, column] = (cells[row,column].alive ? 'X' : ' ') as char;
39
+            }
40
+        }
41
+    }
42
+}

+ 5
- 0
ScriptingExample/scripts/ExpandRangeUsize.zs View File

@@ -0,0 +1,5 @@
1
+public expand usize .. usize {
2
+    public withBounds(bounds as usize .. usize) as usize .. usize {
3
+        return (from < bounds.from ? bounds.from : from) .. (to > bounds.to ? bounds.to : to);
4
+    }
5
+}

+ 27
- 0
ScriptingExample/scripts/GridTest.zs View File

@@ -0,0 +1,27 @@
1
+import example.gui.UpdatableGrid;
2
+import example.threading.ZCThread;
3
+
4
+var height = 25;
5
+var width = 25;
6
+
7
+var grid = new UpdatableGrid(height, width);
8
+var conwayGrid = new ConwayGrid(height, width);
9
+
10
+conwayGrid[4,5] = true;
11
+conwayGrid[5,4] = true;
12
+conwayGrid[5,5] = true;
13
+conwayGrid[5,6] = true;
14
+
15
+
16
+conwayGrid.updateDisplay(grid);
17
+grid.show("Hello World");
18
+
19
+var i = 0;
20
+while(true) {
21
+    println("Generation " + i);
22
+    conwayGrid.updateDisplay(grid);
23
+    grid.update();
24
+    ZCThread.sleep((1).seconds());
25
+    conwayGrid.update();
26
+    i++;
27
+}

+ 0
- 51
ScriptingExample/scripts/nope/match.zs View File

@@ -1,51 +0,0 @@
1
-val test as int = 10;
2
-val tt1 = "tt";
3
-val tt2 = "tt3";
4
-val tt4 = "tt5";
5
-
6
-
7
-println(match 10 {
8
-	1 => "one",
9
-	10 => "yo",
10
-	//tt1 === "tt1" for some compiler issue it takes the variable as string input?
11
-	100 => match tt1 {
12
-		"10" => "t",
13
-		"tt1" => tt1,
14
-		"tt2" => tt1 + tt4,
15
-		default => tt4
16
-	},
17
-	default => tt2
18
-});
19
-
20
-
21
-println(tt1);
22
-
23
-//println(match test {
24
-//	case 1 : "tt",
25
-//	default : "kk"
26
-//});
27
-
28
-
29
-
30
-function myFunc (par1 as int) as void {
31
-
32
-    val v0 = par1 - 1;
33
-	println(match par1 {
34
-		10 => v0,
35
-		default => match(v0) {
36
-			10 => 99,
37
-			default => v0
38
-		}
39
-	});
40
-}
41
-
42
-
43
-myFunc(10);
44
-myFunc(11);
45
-myFunc(12);
46
-
47
-
48
-val t = (a as int) as int => a;
49
-
50
-
51
-println(t(10));

+ 9
- 76
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/Globals.java View File

@@ -5,85 +5,18 @@
5 5
  */
6 6
 package org.openzen.zenscript.scriptingexample;
7 7
 
8
-import org.openzen.zencode.java.ZenCodeGlobals;
9
-import static org.openzen.zencode.java.ZenCodeType.*;
8
+import org.openzen.zencode.java.*;
10 9
 
11 10
 /**
12
- *
13 11
  * @author Hoofdgebruiker
14 12
  */
15 13
 public class Globals implements ZenCodeGlobals {
16
-	private Globals() {}
17
-	
18
-	@Global
19
-	public static TestClass something = new TestClass("hello");
20
-	
21
-	@Global
22
-	public static TestClass[] makeArray(int amount) {
23
-		TestClass[] result = new TestClass[amount];
24
-		for (int i = 0; i < result.length; i++)
25
-			result[i] = new TestClass("test " + i);
26
-		return result;
27
-	}
28
-	
29
-	@Global
30
-	public static void println(String message) {
31
-		System.out.println(message);
32
-	}
33
-	
34
-	@Global
35
-	public static void printMany(TestClass[] objects) {
36
-		System.out.println(objects.length + " objects present:");
37
-		for (TestClass object : objects)
38
-			System.out.println("  - " + object.getName());
39
-	}
40
-	
41
-	@Global
42
-    public static void addShapedRecipe(String name, TestClass output, TestClass[][] inputs) {
43
-		System.out.println("Added " + name);
44
-	}
45
-	
46
-	@Global
47
-	public static void floatMethod(float argument) {
48
-		System.out.println(argument);
49
-	}
50
-	
51
-	@Global
52
-	public static void invokeFunctional(MyFunctionalInterface greeter) {
53
-		System.out.println("doSomething: " + greeter.doSomething("world"));
54
-	}
55
-	
56
-	@Global
57
-	public static void invokeFunctionalInt(MyFunctionalInterfaceInt calculator){
58
-		System.out.println("FunctionalInt: " + calculator.doSomething(7, 13));
59
-	}
60
-	
61
-	@Global
62
-	public static void testOptional(MyOptionalInterface function) {
63
-		System.out.println("Null: " + function.doSomething(null));
64
-		System.out.println("Hello: " + function.doSomething("hello"));
65
-	}
66
-	
67
-	public static TestClass bracket(String value) {
68
-		return new TestClass(value);
69
-	}
70
-
71
-	public static String staticToString(String value) {
72
-		return value;
73
-	}
74
-	
75
-	@FunctionalInterface
76
-	public static interface MyFunctionalInterface {
77
-		String doSomething(String value);
78
-	}
79
-	
80
-	@FunctionalInterface
81
-	public static interface MyFunctionalInterfaceInt {
82
-		int doSomething(int valueA, int valueB);
83
-	}
84
-	
85
-	@FunctionalInterface
86
-	public static interface MyOptionalInterface {
87
-		int doSomething(@Nullable String value);
88
-	}
14
+    
15
+    private Globals() {
16
+    }
17
+    
18
+    @Global
19
+    public static void println(String message) {
20
+        System.out.println(message);
21
+    }
89 22
 }

+ 51
- 68
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/Main.java View File

@@ -1,73 +1,56 @@
1 1
 package org.openzen.zenscript.scriptingexample;
2 2
 
3
-import java.io.File;
4
-import java.io.IOException;
5
-import java.nio.file.Files;
6
-import java.nio.file.Path;
7
-import java.util.HashMap;
8
-import java.util.Map;
9
-
10
-import org.openzen.zencode.java.JavaNativeModule;
11
-import org.openzen.zencode.java.ScriptingEngine;
12
-import org.openzen.zencode.shared.CompileException;
13
-import org.openzen.zencode.shared.FileSourceFile;
14
-import org.openzen.zencode.shared.SourceFile;
15
-import org.openzen.zenscript.codemodel.FunctionParameter;
16
-import org.openzen.zenscript.codemodel.SemanticModule;
17
-import org.openzen.zenscript.codemodel.type.StringTypeID;
18
-import org.openzen.zenscript.lexer.ParseException;
19
-import org.openzen.zenscript.parser.BracketExpressionParser;
20
-import org.openzen.zenscript.parser.EscapableBracketParser;
21
-import org.openzen.zenscript.parser.PrefixedBracketParser;
22
-import org.openzen.zenscript.parser.SimpleBracketParser;
23
-import org.openzen.zenscript.scriptingexample.events.EventManager;
24
-import org.openzen.zenscript.scriptingexample.events.IEvent;
25
-import org.openzen.zenscript.scriptingexample.events.impl.CTStringedEvent;
26
-import org.openzen.zencode.java.logger.ScriptingEngineStreamLogger;
3
+import org.openzen.zencode.java.*;
4
+import org.openzen.zencode.java.logger.*;
5
+import org.openzen.zencode.shared.*;
6
+import org.openzen.zenscript.codemodel.*;
7
+import org.openzen.zenscript.codemodel.type.*;
8
+import org.openzen.zenscript.lexer.*;
9
+import org.openzen.zenscript.parser.*;
10
+import org.openzen.zenscript.scriptingexample.gui.*;
11
+import org.openzen.zenscript.scriptingexample.threading.*;
12
+
13
+import java.io.*;
14
+import java.nio.file.*;
15
+import java.util.*;
27 16
 
28 17
 public class Main {
29
-	public static void main(String[] args) throws CompileException, ParseException, IOException, NoSuchMethodException {
30
-		ScriptingEngine scriptingEngine = new ScriptingEngine(new ScriptingEngineStreamLogger());
31
-		scriptingEngine.debug = true;
32
-
33
-		JavaNativeModule example = scriptingEngine.createNativeModule("example", "org.openzen.zenscript.scriptingexample");
34
-		example.addGlobals(Globals.class);
35
-		example.addClass(TestBaseInterface.class);
36
-		example.addClass(TestGenericInterface.class);
37
-		example.addClass(TestClass.class);
38
-		example.addClass(TestInterface.class);
39
-		example.addClass(IEvent.class);
40
-		example.addClass(EventManager.class);
41
-		example.addClass(CTStringedEvent.class);
42
-		scriptingEngine.registerNativeProvided(example);
43
-
44
-		File inputDirectory = new File("scripts");
45
-		final SourceFile[] sourceFiles = Files.walk(inputDirectory.getAbsoluteFile().toPath())
46
-				.map(Path::toFile)
47
-				.filter(File::isFile)
48
-				.filter(f -> f.getName().endsWith(".zs"))
49
-				.filter(f -> !f.getAbsolutePath().contains("nope"))
50
-				.map(f -> new FileSourceFile(f.getName(), f))
51
-				.toArray(SourceFile[]::new);
52
-		//File[] inputFiles = Optional.ofNullable(inputDirectory.listFiles((dir, name) -> name.endsWith(".zs"))).orElseGet(() -> new File[0]);
53
-		//SourceFile[] sourceFiles = new SourceFile[inputFiles.length];
54
-		//for (int i = 0; i < inputFiles.length; i++)
55
-		//	sourceFiles[i] = new FileSourceFile(inputFiles[i].getName(), inputFiles[i]);
56
-
57
-		final PrefixedBracketParser parser = new PrefixedBracketParser(null);
58
-		BracketExpressionParser testParser = new SimpleBracketParser(scriptingEngine.registry, example.loadStaticMethod(Globals.class.getMethod("bracket", String.class)));
59
-		parser.register("test", testParser);
60
-		BracketExpressionParser toStringParser = new EscapableBracketParser(scriptingEngine.registry, example.loadStaticMethod(Globals.class.getMethod("staticToString", String.class)));
61
-		parser.register("toString", toStringParser);
62
-		FunctionParameter parameter = new FunctionParameter(scriptingEngine.registry.getArray(StringTypeID.AUTO, 1).stored(), "args");
63
-		SemanticModule scripts = scriptingEngine.createScriptedModule("script", sourceFiles, parser, new FunctionParameter[] { parameter });
64
-		if (!scripts.isValid())
65
-			return;
66
-
67
-		scriptingEngine.registerCompiled(scripts);
68
-
69
-		Map<FunctionParameter, Object> scriptArgs = new HashMap<>();
70
-		scriptArgs.put(parameter, new String[] { "hello", "world", "example" });
71
-		scriptingEngine.run(scriptArgs);
72
-	}
18
+    
19
+    public static void main(String[] args) throws CompileException, ParseException, IOException, NoSuchMethodException {
20
+        ScriptingEngine scriptingEngine = new ScriptingEngine(new ScriptingEngineStreamLogger());
21
+        scriptingEngine.debug = true;
22
+        
23
+        JavaNativeModule example = scriptingEngine.createNativeModule("example", "org.openzen.zenscript.scriptingexample");
24
+        example.addGlobals(Globals.class);
25
+        
26
+        example.addClass(UpdatableGrid.class);
27
+        example.addClass(TimeSpan.class);
28
+        example.addClass(TimeSpan.ExpandInt.class);
29
+        example.addClass(ZCThread.class);
30
+        
31
+        scriptingEngine.registerNativeProvided(example);
32
+        
33
+        File inputDirectory = new File("scripts");
34
+        final SourceFile[] sourceFiles = Files.walk(inputDirectory.getAbsoluteFile().toPath())
35
+                .map(Path::toFile)
36
+                .filter(File::isFile)
37
+                .filter(f -> f.getName().endsWith(".zs"))
38
+                .filter(f -> !f.getAbsolutePath().contains("nope"))
39
+                .map(f -> new FileSourceFile(f.getName(), f))
40
+                .toArray(SourceFile[]::new);
41
+        
42
+        final PrefixedBracketParser parser = new PrefixedBracketParser(null);
43
+        
44
+        FunctionParameter parameter = new FunctionParameter(scriptingEngine.registry.getArray(StringTypeID.AUTO, 1)
45
+                .stored(), "args");
46
+        SemanticModule scripts = scriptingEngine.createScriptedModule("script", sourceFiles, parser, new FunctionParameter[]{parameter});
47
+        if(!scripts.isValid())
48
+            return;
49
+        
50
+        scriptingEngine.registerCompiled(scripts);
51
+        
52
+        Map<FunctionParameter, Object> scriptArgs = new HashMap<>();
53
+        scriptArgs.put(parameter, new String[]{"hello", "world", "example"});
54
+        scriptingEngine.run(scriptArgs);
55
+    }
73 56
 }

+ 0
- 17
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestBaseInterface.java View File

@@ -1,17 +0,0 @@
1
-/*
2
- * To change this license header, choose License Headers in Project Properties.
3
- * To change this template file, choose Tools | Templates
4
- * and open the template in the editor.
5
- */
6
-package org.openzen.zenscript.scriptingexample;
7
-
8
-import org.openzen.zencode.java.ZenCodeType;
9
-
10
-/**
11
- *
12
- * @author Hoofdgebruiker
13
- */
14
-public interface TestBaseInterface<T> extends ZenCodeType {
15
-	@Method
16
-	T getValue();
17
-}

+ 0
- 60
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestClass.java View File

@@ -1,60 +0,0 @@
1
-/*
2
- * To change this license header, choose License Headers in Project Properties.
3
- * To change this template file, choose Tools | Templates
4
- * and open the template in the editor.
5
- */
6
-package org.openzen.zenscript.scriptingexample;
7
-
8
-/**
9
- *
10
- * @author Hoofdgebruiker
11
- */
12
-public class TestClass implements TestInterface {
13
-	private final String name;
14
-	
15
-	@Constructor
16
-	public TestClass(String name) {
17
-		this.name = name;
18
-	}
19
-	
20
-	@Getter
21
-	public String getName() {
22
-		return name;
23
-	}
24
-	
25
-	@Method
26
-	public void dump() {
27
-		System.out.println("TestClass " + name);
28
-	}
29
-	
30
-	@Method
31
-	public TestClass wrap(String quotes) {
32
-		return new TestClass(quotes + name + quotes);
33
-	}
34
-	
35
-	@Caster(implicit = true)
36
-	@Override
37
-	public String toString() {
38
-		return name;
39
-	}
40
-
41
-	@Override
42
-	public String interfaceMethod() {
43
-		return "Interface method of " + name;
44
-	}
45
-	
46
-	@Override
47
-	public String getValue() {
48
-		return "getValue " + name;
49
-	}
50
-	
51
-	@Method
52
-	public TestGenericInterface<String> generate() {
53
-		return () -> name;
54
-	}
55
-	
56
-	@Method
57
-	public void withDefaultParameter(String a, @OptionalString("world") String b) {
58
-		System.out.println(a + " " + b);
59
-	}
60
-}

+ 0
- 14
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestGenericInterface.java View File

@@ -1,14 +0,0 @@
1
-/*
2
- * To change this license header, choose License Headers in Project Properties.
3
- * To change this template file, choose Tools | Templates
4
- * and open the template in the editor.
5
- */
6
-package org.openzen.zenscript.scriptingexample;
7
-
8
-/**
9
- *
10
- * @author Hoofdgebruiker
11
- */
12
-public interface TestGenericInterface<T> extends TestBaseInterface<T> {
13
-	
14
-}

+ 0
- 17
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/TestInterface.java View File

@@ -1,17 +0,0 @@
1
-/*
2
- * To change this license header, choose License Headers in Project Properties.
3
- * To change this template file, choose Tools | Templates
4
- * and open the template in the editor.
5
- */
6
-package org.openzen.zenscript.scriptingexample;
7
-
8
-import org.openzen.zencode.java.ZenCodeType;
9
-
10
-/**
11
- *
12
- * @author Hoofdgebruiker
13
- */
14
-public interface TestInterface extends ZenCodeType, TestGenericInterface<String> {
15
-	@Method
16
-	String interfaceMethod();
17
-}

+ 0
- 24
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/EventManager.java View File

@@ -1,24 +0,0 @@
1
-package org.openzen.zenscript.scriptingexample.events;
2
-
3
-import org.openzen.zencode.java.ZenCodeType;
4
-import org.openzen.zenscript.scriptingexample.events.impl.CTStringedEvent;
5
-import org.openzen.zenscript.scriptingexample.events.impl.StringedEvent;
6
-
7
-@ZenCodeType.Name("example.org.openzen.scripting_example.events.EventManager")
8
-public class EventManager {
9
-    @ZenCodeType.Method
10
-    public static void register(IEvent<?, ?> event) {
11
-    //public static <EVE extends IEvent<EVE, VA>, VA extends SomeMCEvent> void register(IEvent<EVE, VA> event) {
12
-        System.out.println("HIT!!!");
13
-
14
-        if(event instanceof CTStringedEvent) {
15
-            ((CTStringedEvent)event).getHandler().accept(new CTStringedEvent(null));
16
-        }
17
-    }
18
-
19
-    //@ZenCodeType.Method
20
-    //public static void register(CTStringedEvent event) {
21
-    //    System.out.println("HIT!!!");
22
-    //    event.getConsumer().accept(new StringedEvent("Abcdef"));
23
-    //}
24
-}

+ 0
- 41
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/IEvent.java View File

@@ -1,41 +0,0 @@
1
-package org.openzen.zenscript.scriptingexample.events;
2
-
3
-import org.openzen.zencode.java.ZenCodeType;
4
-
5
-import java.util.function.Consumer;
6
-
7
-@ZenCodeType.Name("example.org.openzen.scripting_example.events.IEvent")
8
-public abstract class IEvent<E extends IEvent<E, V>, V extends SomeMCEvent> {
9
-
10
-    private V internal;
11
-
12
-    private Consumer<E> handler;
13
-
14
-    public IEvent(V internal) {
15
-        this.internal = internal;
16
-    }
17
-
18
-    @ZenCodeType.Constructor
19
-    public IEvent(Consumer<E> handler) {
20
-        this.handler = handler;
21
-    }
22
-
23
-    public void setInternal(V internal) {
24
-        this.internal = internal;
25
-    }
26
-
27
-    public abstract Consumer<V> getConsumer();
28
-
29
-
30
-    public V getInternal() {
31
-        return internal;
32
-    }
33
-
34
-    public Consumer<E> getHandler() {
35
-        return handler;
36
-    }
37
-
38
-    public void setHandler(Consumer<E> handler) {
39
-        this.handler = handler;
40
-    }
41
-}

+ 0
- 4
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/SomeMCEvent.java View File

@@ -1,4 +0,0 @@
1
-package org.openzen.zenscript.scriptingexample.events;
2
-
3
-public interface SomeMCEvent {
4
-}

+ 0
- 25
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/impl/CTStringedEvent.java View File

@@ -1,25 +0,0 @@
1
-package org.openzen.zenscript.scriptingexample.events.impl;
2
-
3
-import org.openzen.zencode.java.ZenCodeType;
4
-import org.openzen.zenscript.scriptingexample.events.IEvent;
5
-
6
-import java.util.function.Consumer;
7
-
8
-@ZenCodeType.Name("example.org.openzen.scripting_example.events.CTStringedEvent")
9
-public class CTStringedEvent extends IEvent<CTStringedEvent, StringedEvent> {
10
-
11
-    @ZenCodeType.Getter("blub")
12
-    public String getBlub() {
13
-        return "ASDF";
14
-    }
15
-
16
-    @ZenCodeType.Constructor
17
-    public CTStringedEvent(Consumer<CTStringedEvent> handler) {
18
-        super(handler);
19
-    }
20
-
21
-    @Override
22
-    public Consumer<StringedEvent> getConsumer() {
23
-        return stringedEvent -> getHandler().accept(new CTStringedEvent(null));
24
-    }
25
-}

+ 0
- 12
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/events/impl/StringedEvent.java View File

@@ -1,12 +0,0 @@
1
-package org.openzen.zenscript.scriptingexample.events.impl;
2
-
3
-import org.openzen.zenscript.scriptingexample.events.SomeMCEvent;
4
-
5
-public class StringedEvent implements SomeMCEvent {
6
-    private final String text;
7
-
8
-    public StringedEvent(String text) {
9
-
10
-        this.text = text;
11
-    }
12
-}

+ 40
- 0
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/gui/SwingGrid.java View File

@@ -0,0 +1,40 @@
1
+package org.openzen.zenscript.scriptingexample.gui;
2
+
3
+import javax.swing.*;
4
+import java.awt.*;
5
+
6
+public class SwingGrid extends JFrame {
7
+    
8
+    private final char[][] grid;
9
+    private final JLabel[][] labelGrid;
10
+    
11
+    public SwingGrid(String title, char[][] grid) throws HeadlessException {
12
+        super(title);
13
+        this.grid = grid;
14
+        this.setLayout(new GridLayout(grid.length, 0));
15
+        
16
+        labelGrid = new JLabel[grid.length][grid[0].length];
17
+        for(int i = 0; i < grid.length; i++) {
18
+            char[] chars = grid[i];
19
+            for(int j = 0; j < chars.length; j++) {
20
+                this.add(labelGrid[i][j] = new JLabel(String.valueOf(chars[j]), SwingConstants.CENTER));
21
+            }
22
+        }
23
+        
24
+        this.setLocationRelativeTo(null);
25
+        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
26
+        EventQueue.invokeLater(() -> {
27
+            this.setVisible(true);
28
+        });
29
+    }
30
+    
31
+    
32
+    public void update() {
33
+        for(int i = 0; i < grid.length; i++) {
34
+            char[] chars = grid[i];
35
+            for(int j = 0; j < chars.length; j++) {
36
+                labelGrid[i][j].setText(String.valueOf(chars[j]));
37
+            }
38
+        }
39
+    }
40
+}

+ 35
- 0
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/gui/UpdatableGrid.java View File

@@ -0,0 +1,35 @@
1
+package org.openzen.zenscript.scriptingexample.gui;
2
+
3
+import org.openzen.zencode.java.*;
4
+
5
+@ZenCodeType.Name("example.gui.UpdatableGrid")
6
+public class UpdatableGrid {
7
+    
8
+    private final char[][] grid;
9
+    private SwingGrid swingGrid;
10
+    
11
+    @ZenCodeType.Constructor
12
+    public UpdatableGrid(int rows, int columns) {
13
+        grid = new char[rows][columns];
14
+    }
15
+    
16
+    @ZenCodeType.Operator(ZenCodeType.OperatorType.INDEXSET)
17
+    public void setValue(@ZenCodeType.USize int row, @ZenCodeType.USize int column, char value) {
18
+        grid[row][column] = value;
19
+    }
20
+    
21
+    @ZenCodeType.Method
22
+    public void show(String name, @ZenCodeType.OptionalInt(600) int width, @ZenCodeType.OptionalInt(480) int height) {
23
+        if(swingGrid == null) {
24
+            swingGrid = new SwingGrid(name, grid);
25
+        }
26
+        swingGrid.setSize(width, height);
27
+    }
28
+    
29
+    @ZenCodeType.Method
30
+    public void update() {
31
+        if(swingGrid != null) {
32
+            swingGrid.update();
33
+        }
34
+    }
35
+}

+ 32
- 0
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/threading/TimeSpan.java View File

@@ -0,0 +1,32 @@
1
+package org.openzen.zenscript.scriptingexample.threading;
2
+
3
+import org.openzen.zencode.java.*;
4
+
5
+@ZenCodeType.Name("example.threading.TimeSpan")
6
+public class TimeSpan {
7
+    private final long timeNanos;
8
+    
9
+    public TimeSpan(long timeNanos) {
10
+        this.timeNanos = timeNanos;
11
+    }
12
+    
13
+    @ZenCodeType.Getter("timeMillis")
14
+    public long getTimeMillis() {
15
+        return timeNanos;
16
+    }
17
+    
18
+    @ZenCodeType.Expansion("int")
19
+    public static final class ExpandInt {
20
+        @ZenCodeType.Method
21
+        public static TimeSpan seconds(int _this) {
22
+            return new TimeSpan(_this * 1_000);
23
+        }
24
+        
25
+        @ZenCodeType.Method
26
+        @ZenCodeType.Caster(implicit = true)
27
+        public static TimeSpan milliSeconds(int _this) {
28
+            return new TimeSpan(_this);
29
+        }
30
+        
31
+    }
32
+}

+ 21
- 0
ScriptingExample/src/main/java/org/openzen/zenscript/scriptingexample/threading/ZCThread.java View File

@@ -0,0 +1,21 @@
1
+package org.openzen.zenscript.scriptingexample.threading;
2
+
3
+import org.openzen.zencode.java.*;
4
+
5
+@ZenCodeType.Name("example.threading.ZCThread")
6
+public class ZCThread {
7
+    
8
+    @ZenCodeType.Method
9
+    public static void sleep(TimeSpan timeSpan) {
10
+        sleep(timeSpan.getTimeMillis());
11
+    }
12
+    
13
+    @ZenCodeType.Method
14
+    public static void sleep(long millis) {
15
+        try {
16
+            Thread.sleep(millis);
17
+        } catch(InterruptedException e) {
18
+            e.printStackTrace();
19
+        }
20
+    }
21
+}

+ 90
- 0
ScriptingExample/src/test/java/org/openzen/zenscript/scriptingexample/tests/actual_test/classes/AddingClasses.java View File

@@ -0,0 +1,90 @@
1
+package org.openzen.zenscript.scriptingexample.tests.actual_test.classes;
2
+
3
+import org.junit.jupiter.api.*;
4
+import org.openzen.zenscript.scriptingexample.tests.helpers.*;
5
+
6
+public class AddingClasses extends ZenCodeTest {
7
+    
8
+    @Test
9
+    public void emptyClassCompiles() {
10
+        ScriptBuilder.create().add("public class SomeClass {").add("}").execute(this);
11
+        logger.assertNoErrors();
12
+    }
13
+    
14
+    @Test
15
+    public void memberGettable() {
16
+        ScriptBuilder.create()
17
+                .add("public class SomeClass {")
18
+                .add("    public var x as string;")
19
+                .add("    public this(){x = 'Hello World';}")
20
+                .add("}")
21
+                .add("")
22
+                .add("println(new SomeClass().x);")
23
+                .execute(this);
24
+        
25
+        logger.assertNoErrors();
26
+        logger.assertPrintOutputSize(1);
27
+        logger.assertPrintOutput(0, "Hello World");
28
+    }
29
+    
30
+    @Test
31
+    public void functionCallable() {
32
+        ScriptBuilder.create()
33
+                .add("public class SomeClass {")
34
+                .add("    public this(){}")
35
+                .add("    public callMeMaybe() as void {println('Hello World!');}")
36
+                .add("}")
37
+                .add("")
38
+                .add("new SomeClass().callMeMaybe();")
39
+                .execute(this);
40
+        
41
+        logger.assertPrintOutputSize(1);
42
+        logger.assertPrintOutput(0, "Hello World!");
43
+    }
44
+    
45
+    @Test
46
+    public void classAccessibleFromOtherScript() {
47
+        ScriptBuilder.create()
48
+                .add("public class SomeClass {")
49
+                .add("    public this(){}")
50
+                .add("    public callMeMaybe() as void {println('Hello World!');}")
51
+                .add("}")
52
+                .add("")
53
+                .startNewScript()
54
+                .add("new SomeClass().callMeMaybe();")
55
+                .execute(this);
56
+        
57
+        logger.assertPrintOutputSize(1);
58
+        logger.assertPrintOutput(0, "Hello World!");
59
+    }
60
+    
61
+    @Test
62
+    public void fieldInitializerSetsField() {
63
+        ScriptBuilder.create()
64
+                .add("public class SomeClass {")
65
+                .add("    public var x as string = 'Hello World';")
66
+                .add("    public this(){}")
67
+                .add("}")
68
+                .add("")
69
+                .add("println(new SomeClass().x);")
70
+                .execute(this);
71
+        
72
+        logger.assertPrintOutputSize(1);
73
+        logger.assertPrintOutput(0, "Hello World");
74
+    }
75
+    
76
+    @Test
77
+    public void constructorOverridesFieldInitializer() {
78
+        ScriptBuilder.create()
79
+                .add("public class SomeClass {")
80
+                .add("    public var x as string = 'Hello World';")
81
+                .add("    public this(){this.x = 'Goodbye World';}")
82
+                .add("}")
83
+                .add("")
84
+                .add("println(new SomeClass().x);")
85
+                .execute(this);
86
+        
87
+        logger.assertPrintOutputSize(1);
88
+        logger.assertPrintOutput(0, "Goodbye World");
89
+    }
90
+}

+ 66
- 0
ScriptingExample/src/test/java/org/openzen/zenscript/scriptingexample/tests/helpers/ScriptBuilder.java View File

@@ -0,0 +1,66 @@
1
+package org.openzen.zenscript.scriptingexample.tests.helpers;
2
+
3
+import java.util.*;
4
+
5
+public class ScriptBuilder {
6
+    
7
+    private final List<String> scripts;
8
+    private StringJoiner currentScriptJoiner;
9
+    
10
+    private ScriptBuilder() {
11
+        scripts = new ArrayList<>();
12
+        startNewScript();
13
+    }
14
+    
15
+    /**
16
+     * Creates a {@link StringJoiner} that merges with newlines.
17
+     * The only real reason for this to exist is that it allows code formatting to work properly lol
18
+     */
19
+    public static ScriptBuilder create() {
20
+        return new ScriptBuilder();
21
+    }
22
+    
23
+    public ScriptBuilder add(String line) {
24
+        currentScriptJoiner.add(line);
25
+        return this;
26
+    }
27
+    
28
+    public ScriptBuilder startNewScript() {
29
+        if(currentScriptJoiner != null) {
30
+            scripts.add(currentScriptJoiner.toString());
31
+        }
32
+        
33
+        currentScriptJoiner = new StringJoiner(System.lineSeparator());
34
+        return this;
35
+    }
36
+    
37
+    public void appendScriptsToTest(ZenCodeTest test) {
38
+        startNewScript();
39
+    
40
+        for(String script : scripts) {
41
+            test.addScript(script);
42
+        }
43
+    }
44
+    
45
+    public void execute(ZenCodeTest test, LogTolerance logTolerance) {
46
+        appendScriptsToTest(test);
47
+        test.executeEngine();
48
+        switch(logTolerance) {
49
+            case NO_WARNINGS:
50
+                test.logger.assertNoWarnings();
51
+            case NO_ERRORS:
52
+                test.logger.assertNoErrors();
53
+                break;
54
+            case ALLOW_ERRORS:
55
+                break;
56
+        }
57
+    }
58
+    
59
+    public void execute(ZenCodeTest test) {
60
+        execute(test, LogTolerance.NO_WARNINGS);
61
+    }
62
+    
63
+    public enum LogTolerance {
64
+        NO_WARNINGS, NO_ERRORS, ALLOW_ERRORS
65
+    }
66
+}

+ 35
- 1
ScriptingExample/src/test/java/org/openzen/zenscript/scriptingexample/tests/helpers/ZenCodeTestLogger.java View File

@@ -9,6 +9,8 @@ public class ZenCodeTestLogger extends ScriptingEngineStreamLogger {
9 9
     
10 10
     private static final boolean logDebug = false;
11 11
     private final List<String> printlnOutputs = new ArrayList<>();
12
+    private final List<String> errors = new ArrayList<>();
13
+    private final List<String> warnings = new ArrayList<>();
12 14
     private boolean isEngineComplete = false;
13 15
     
14 16
     @Override
@@ -18,9 +20,33 @@ public class ZenCodeTestLogger extends ScriptingEngineStreamLogger {
18 20
         }
19 21
     }
20 22
     
23
+    @Override
24
+    public void warning(String message) {
25
+        warnings.add(message);
26
+        super.warning(message);
27
+    }
28
+    
29
+    @Override
30
+    public void throwingWarn(String message, Throwable throwable) {
31
+        warnings.add(message);
32
+        super.throwingWarn(message, throwable);
33
+    }
34
+    
21 35
     public void logPrintln(String line) {
22 36
         info(line);
23
-        this.printlnOutputs.addAll(Arrays.asList(line.split(System.lineSeparator())));
37
+        this.printlnOutputs.addAll(Arrays.asList(String.valueOf(line).split(System.lineSeparator())));
38
+    }
39
+    
40
+    @Override
41
+    public void error(String message) {
42
+        errors.add(message);
43
+        super.error(message);
44
+    }
45
+    
46
+    @Override
47
+    public void throwingErr(String message, Throwable throwable) {
48
+        errors.add(message);
49
+        super.throwingErr(message, throwable);
24 50
     }
25 51
     
26 52
     void setEngineComplete() {
@@ -40,4 +66,12 @@ public class ZenCodeTestLogger extends ScriptingEngineStreamLogger {
40 66
         }
41 67
         Assertions.assertEquals(size, printlnOutputs.size());
42 68
     }
69
+    
70
+    public void assertNoErrors() {
71
+        Assertions.assertEquals(0, errors.size());
72
+    }
73
+    
74
+    public void assertNoWarnings() {
75
+        Assertions.assertEquals(0, warnings.size());
76
+    }
43 77
 }

Loading…
Cancel
Save