Skip to content

Commit 53ebb8e

Browse files
committed
modules: Improved old code and added new modules
1 parent d88aa50 commit 53ebb8e

File tree

4 files changed

+704
-87
lines changed

4 files changed

+704
-87
lines changed

src/main/java/org/piccode/rt/modules/NativeFunctionFactory.java

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
package org.piccode.rt.modules;
22

3+
import com.github.tomaslanger.chalk.Chalk;
34
import java.util.List;
45
import java.util.Map;
6+
import org.piccode.ast.Ast;
57
import org.piccode.ast.FunctionAst;
68
import org.piccode.ast.IdentifierAst;
79
import org.piccode.rt.Context;
810
import org.piccode.rt.NativeFunction;
11+
import org.piccode.rt.PiccodeException;
912
import org.piccode.rt.PiccodeValue;
1013

1114
/**
@@ -14,15 +17,14 @@
1417
*/
1518
public class NativeFunctionFactory {
1619

17-
1820
public static NativeFunction create(String name, List<String> args, TriFunction<List<PiccodeValue>, Map<String, PiccodeValue>, Integer, PiccodeValue> fx, Integer frame) {
1921
NativeFunction func = new NativeFunction(name, args, null, frame) {
2022
@Override
2123
public PiccodeValue invoke(List<PiccodeValue> args, Map<String, PiccodeValue> namedArgs, Integer frame) {
22-
var ctx = frame == null ?
23-
Context.top
24-
: Context.getContextAt(frame);
25-
24+
var ctx = frame == null
25+
? Context.top
26+
: Context.getContextAt(frame);
27+
2628
var parent = ctx.getTopFrame().caller;
2729

2830
if (parent instanceof FunctionAst func) {
@@ -33,10 +35,18 @@ public PiccodeValue invoke(List<PiccodeValue> args, Map<String, PiccodeValue> na
3335
id.file = parent.file;
3436
id.line = parent.line;
3537
id.column = parent.column;
36-
ctx.pushStackFrame(id);
37-
var result = fx.apply(args, namedArgs, frame);
38-
ctx.dropStackFrame();
39-
return result;
38+
39+
var self = (NativeFunction) this;
40+
if (self.params.size() != args.size()) {
41+
var expected = Chalk.on(self.params.size() + "").green();
42+
var received = Chalk.on(args.size() + "").red();
43+
throw new PiccodeException(id.file, id.line, id.column,
44+
"Invalid number of parameters passed to native function `" + Chalk.on(id.text).green() + "` , expcted " + expected + " but got " + received);
45+
}
46+
47+
return Ast.safeExecute(frame, id, (node) -> {
48+
return fx.apply(args, namedArgs, frame);
49+
});
4050
}
4151

4252
@Override

0 commit comments

Comments
 (0)