11package org .piccode .rt .modules ;
22
3+ import com .github .tomaslanger .chalk .Chalk ;
34import java .util .List ;
45import java .util .Map ;
6+ import org .piccode .ast .Ast ;
57import org .piccode .ast .FunctionAst ;
68import org .piccode .ast .IdentifierAst ;
79import org .piccode .rt .Context ;
810import org .piccode .rt .NativeFunction ;
11+ import org .piccode .rt .PiccodeException ;
912import org .piccode .rt .PiccodeValue ;
1013
1114/**
1417 */
1518public 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