finx 0.1.0

A fast, lightweight embeddable scripting language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! # Finx Engine
//!
//! A high-level API for the Finx embeddable scripting language.
//!
//! ## Features
//!
//! - **Fast execution**: Stack-based virtual machine with optimized bytecode
//! - **Easy integration**: Simple API for embedding in Rust applications
//! - **Native functions**: Register Rust functions to be called from scripts
//! - **Context management**: Maintain state between script executions
//! - **File and string execution**: Run scripts from files or string literals
//! - **Error handling**: Comprehensive error types with helpful messages
//!
//! ## Quick Start
//!
//! ```rust
//! use finx::Finx;
//! use std::rc::Rc;
//!
//! // Create a new language engine
//! let mut engine = Finx::new();
//!
//! // Run a simple script
//! let result = engine.eval("1 + 2 * 3").unwrap();
//! println!("Result: {}", result); // Result: 7
//!
//! // Register a native function
//! engine.register_function("add", Rc::new(|args| {
//!     if let [a, b] = args {
//!         if let (Some(a), Some(b)) = (a.as_num(), b.as_num()) {
//!             return (a + b).into();
//!         }
//!     }
//!     panic!("add expects two numbers");
//! }), 2);
//!
//! // Use the native function in a script
//! let result = engine.eval("add(10, 20)").unwrap();
//! println!("Result: {}", result); // Result: 30
//! ```

use crate::compiler::{compile_for_eval, compile_for_eval_with_natives};
use crate::lexer::Token;
use crate::parser::{ParseError, Parser};
use crate::vm::{NativeFn, VM, Value, eval_code_with_vm};
use logos::Logos;
use std::cell::RefCell;
use std::collections::HashMap;
use std::fmt;
use std::fs;
use std::path::Path;
use std::rc::Rc;

/// Result type for Finx operations
pub type Result<T> = std::result::Result<T, FinxError>;

/// Comprehensive error type for Finx operations
#[derive(Debug)]
pub enum FinxError {
    /// Lexical analysis error
    LexError(String),
    /// Parsing error
    ParseError(ParseError),
    /// Runtime error during execution
    RuntimeError(String),
    /// File I/O error
    IoError(std::io::Error),
    /// Native function registration error
    NativeFunctionError(String),
    /// Compiler error
    CompilerError(String),
    /// VM execution error
    VmError(String),
    /// Type error for operations
    TypeError(String),
    /// Undefined variable error
    UndefinedVariable(String),
}

impl fmt::Display for FinxError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FinxError::LexError(msg) => write!(f, "Lexical error: {}", msg),
            FinxError::ParseError(err) => write!(f, "Parse error: {}", err),
            FinxError::RuntimeError(msg) => write!(f, "Runtime error: {}", msg),
            FinxError::IoError(err) => write!(f, "IO error: {}", err),
            FinxError::NativeFunctionError(msg) => write!(f, "Native function error: {}", msg),
            FinxError::CompilerError(msg) => write!(f, "Compiler error: {}", msg),
            FinxError::VmError(msg) => write!(f, "VM error: {}", msg),
            FinxError::TypeError(msg) => write!(f, "Type error: {}", msg),
            FinxError::UndefinedVariable(msg) => write!(f, "Undefined variable: {}", msg),
        }
    }
}

impl std::error::Error for FinxError {}

impl From<ParseError> for FinxError {
    fn from(err: ParseError) -> Self {
        FinxError::ParseError(err)
    }
}

impl From<std::io::Error> for FinxError {
    fn from(err: std::io::Error) -> Self {
        FinxError::IoError(err)
    }
}

/// Main engine for the Finx scripting language
///
/// The `Finx` struct provides a high-level interface for executing scripts,
/// managing state, and integrating with Rust applications.
///
/// ## Example
///
/// ```rust
/// use finx::Finx;
///
/// let mut engine = Finx::new();
///
/// // Execute a script and get the result
/// let result = engine.eval("let x = 42; x * 2").unwrap();
/// println!("Result: {}", result);
///
/// // Variables persist between calls
/// let result = engine.eval("x + 10").unwrap();
/// println!("Result: {}", result); // Uses x from previous execution
/// ```
pub struct Finx {
    vm: VM,
    native_functions: HashMap<String, (NativeFn, usize)>,
    globals_initialized: bool,
    /// Track all known global names (native functions + user-defined functions)
    known_globals: HashMap<String, usize>,
    next_global: usize,
    print_output: Rc<RefCell<Vec<String>>>,
}

impl Finx {
    /// Creates a new Finx engine with default native functions
    ///
    /// This includes common functions like `abs`, `sqrt`, `min`, `max`, etc.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    /// let result = engine.eval("abs(-42)").unwrap();
    /// assert_eq!(result.as_num(), Some(42.0));
    /// ```
    pub fn new() -> Self {
        let mut engine = Self {
            vm: VM::new(),
            native_functions: HashMap::new(),
            globals_initialized: false,
            known_globals: HashMap::new(),
            next_global: 0,
            print_output: Rc::new(RefCell::new(Vec::new())),
        };
        engine.register_default_functions();
        engine
    }

    /// Creates a new Finx engine without any default functions
    ///
    /// The engine starts with a clean state and no registered native functions.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::without_defaults();
    /// ```
    pub fn without_defaults() -> Self {
        Self {
            vm: VM::new(),
            native_functions: HashMap::new(),
            globals_initialized: false,
            known_globals: HashMap::new(),
            next_global: 0,
            print_output: Rc::new(RefCell::new(Vec::new())),
        }
    }

    /// Registers a native function that can be called from scripts
    ///
    /// ## Arguments
    ///
    /// * `name` - The name of the function as it will appear in scripts
    /// * `func` - The Rust function to call. Must match the signature `fn(&[Value]) -> Value`
    /// * `num_params` - The number of parameters the function expects
    /// ## Example
    ///
    /// ```rust
    /// use finx::{Finx, Value};
    /// use std::rc::Rc;
    ///
    /// let mut engine = Finx::new();
    ///
    /// // Register a function that adds two numbers
    /// engine.register_function("add", Rc::new(|args| {
    ///     if let [a, b] = args {
    ///         if let (Some(a), Some(b)) = (a.as_num(), b.as_num()) {
    ///             return Value::from(a + b);
    ///         }
    ///     }
    ///     panic!("add expects two numbers");
    /// }), 2);
    ///
    /// let result = engine.eval("add(10, 20)").unwrap();
    /// assert_eq!(result.as_num(), Some(30.0));
    /// ```
    pub fn register_function(&mut self, name: &str, func: NativeFn, num_params: usize) {
        self.native_functions
            .insert(name.to_string(), (func.clone(), num_params));
        self.vm.register_native_function(name, func, num_params);

        // Track the function name as a global
        if !self.known_globals.contains_key(name) {
            self.known_globals
                .insert(name.to_string(), self.next_global);
            self.next_global += 1;
        }

        self.globals_initialized = false; // Need to reinitialize globals
    }

    /// Registers a native function using a function pointer (backward compatibility)
    ///
    /// ## Arguments
    ///
    /// * `name` - The name of the function as it will appear in scripts
    /// * `func` - The Rust function pointer to call
    /// * `num_params` - The number of parameters the function expects
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::{Finx, Value};
    ///
    /// fn add_numbers(args: &[Value]) -> Value {
    ///     if let [a, b] = args {
    ///         if let (Some(a), Some(b)) = (a.as_num(), b.as_num()) {
    ///             return Value::from(a + b);
    ///         }
    ///     }
    ///     Value::Null
    /// }
    ///
    /// let mut engine = Finx::new();
    /// engine.register_function_ptr("add", add_numbers, 2);
    /// ```
    pub fn register_function_ptr(
        &mut self,
        name: &str,
        func: fn(&[Value]) -> Value,
        num_params: usize,
    ) {
        let func_rc = Rc::new(func);
        self.register_function(name, func_rc, num_params);
    }

    /// Registers a native function using a closure with captured state
    ///
    /// ## Arguments
    ///
    /// * `name` - The name of the function as it will appear in scripts
    /// * `closure` - The closure to call. Can capture variables from the surrounding scope.
    /// * `num_params` - The number of parameters the function expects
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::{Finx, Value};
    ///
    /// let mut engine = Finx::new();
    ///
    /// // Register a closure that captures a multiplier
    /// let multiplier = 3.0;
    /// engine.register_closure("triple", move |args| {
    ///     if let [Value::Number(n)] = args {
    ///         Value::Number(n * multiplier)
    ///     } else {
    ///         Value::Null
    ///     }
    /// }, 1);
    ///
    /// let result = engine.eval("triple(10)").unwrap();
    /// assert_eq!(result.as_num(), Some(30.0));
    /// ```
    pub fn register_closure<F>(&mut self, name: &str, closure: F, num_params: usize)
    where
        F: Fn(&[Value]) -> Value + 'static,
    {
        let func_rc = Rc::new(closure);
        self.register_function(name, func_rc, num_params);
    }

    /// Registers multiple native functions at once
    /// ## Example
    ///
    /// ```rust
    /// use finx::{Finx, Value};
    /// use std::rc::Rc;
    ///
    /// let mut engine = Finx::new();
    ///
    /// engine.register_functions(&[
    ///     ("add", Rc::new(|args| {
    ///         if let [a, b] = args {
    ///             if let (Some(a), Some(b)) = (a.as_num(), b.as_num()) {
    ///                 return Value::from(a + b);
    ///             }
    ///         }
    ///         panic!("add expects two numbers");
    ///     }), 2),
    ///     ("multiply", Rc::new(|args| {
    ///         if let [a, b] = args {
    ///             if let (Some(a), Some(b)) = (a.as_num(), b.as_num()) {
    ///                 return Value::from(a * b);
    ///             }
    ///         }
    ///         panic!("multiply expects two numbers");
    ///     }), 2),
    /// ]);
    /// ```
    pub fn register_functions(&mut self, functions: &[(&str, NativeFn, usize)]) {
        for (name, func, num_params) in functions {
            self.register_function(name, func.clone(), *num_params);
        }
    }

    /// Evaluates a script from a string and returns the result
    ///
    /// The script is executed in the current context, so variables and functions
    /// defined in previous calls are available.
    ///
    /// ## Arguments
    ///
    /// * `source` - The script source code to execute
    ///
    /// ## Returns
    ///
    /// The result of the last expression in the script, or `Value::Null` if the
    /// script doesn't produce a value.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    ///
    /// // Simple expression
    /// let result = engine.eval("2 + 3 * 4").unwrap();
    /// assert_eq!(result.as_num(), Some(14.0));
    ///    /// // Define and use variables
    /// engine.eval("let x = 10").unwrap();
    /// let result = engine.eval("x * 2").unwrap();
    /// assert_eq!(result.as_num(), Some(20.0));
    /// ```
    pub fn eval(&mut self, source: &str) -> Result<Value> {
        let tokens = self.tokenize(source)?;
        let ast = self.parse(&tokens)?;
        let instructions = self.compile(ast)?;
        self.ensure_globals_initialized();
        eval_code_with_vm(&mut self.vm, instructions)
    }

    /// Executes a script from a file
    ///
    /// ## Arguments
    ///
    /// * `path` - Path to the script file
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    /// let result = engine.eval_file("example_scripts/example.fx").unwrap();
    /// ```
    pub fn eval_file<P: AsRef<Path>>(&mut self, path: P) -> Result<Value> {
        let source = fs::read_to_string(path)?;
        self.eval(&source)
    }

    /// Executes a script without returning a value
    ///
    /// This is useful for scripts that primarily have side effects (like defining
    /// functions or setting up state) rather than computing a result.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    ///
    /// // Define a function
    /// engine.execute("fn factorial(n) { if n <= 1 { return 1; } return n * factorial(n - 1); }").unwrap();
    ///
    /// // Use the function
    /// let result = engine.eval("factorial(5)").unwrap();
    /// assert_eq!(result.as_num(), Some(120.0));
    /// ```
    pub fn execute(&mut self, source: &str) -> Result<()> {
        self.eval(source)?;
        Ok(())
    }

    /// Executes a script file without returning a value
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    /// engine.execute_file("example_scripts/example.fx").unwrap();
    /// ```
    pub fn execute_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
        self.eval_file(path)?;
        Ok(())
    }

    /// Gets all output from `print` statements
    ///
    /// Returns a slice of all strings that have been printed during script execution.
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    /// engine.execute("print('Hello'); print('World');").unwrap();
    ///
    /// let output = engine.get_output();
    /// assert_eq!(output, &["Hello", "World"]);
    /// ```
    pub fn get_output(&self) -> Vec<String> {
        self.print_output.borrow().clone()
    }

    /// Clears all print output
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    /// engine.execute("print('Hello');").unwrap();
    /// assert_eq!(engine.get_output().len(), 1);
    ///
    /// engine.clear_output();
    /// assert_eq!(engine.get_output().len(), 0);
    /// ```
    pub fn clear_output(&mut self) {
        self.print_output.borrow_mut().clear();
    }

    /// Sets the maximum recursion depth for function calls
    ///
    /// ## Arguments
    ///
    /// * `depth` - Maximum number of nested function calls allowed
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    /// engine.set_max_recursion_depth(100);
    /// ```
    pub fn set_max_recursion_depth(&mut self, depth: usize) {
        self.vm.set_max_recursion_depth(depth);
    }

    /// Gets the names of all registered native functions
    ///
    /// ## Example
    ///
    /// ```rust
    /// use finx::Finx;
    ///
    /// let mut engine = Finx::new();
    /// let functions = engine.get_native_function_names();
    /// assert!(functions.contains(&"abs".to_string()));
    /// ```
    pub fn get_native_function_names(&self) -> Vec<String> {
        self.native_functions.keys().cloned().collect()
    }

    // Private helper methods

    /// Tokenizes source code into tokens
    fn tokenize(&self, source: &str) -> Result<Vec<Token>> {
        let tokens: std::result::Result<Vec<Token>, _> = Token::lexer(source).collect();

        match tokens {
            Ok(tokens) => {
                let clean_tokens: Vec<Token> = tokens
                    .into_iter()
                    .filter(|t| !matches!(t, Token::Error))
                    .collect();

                Ok(clean_tokens)
            }
            Err(_) => Err(FinxError::LexError("Failed to tokenize source".to_string())),
        }
    }

    /// Parses tokens into an AST
    fn parse(&self, tokens: &[Token]) -> Result<Vec<crate::parser::Stmt>> {
        let mut parser = Parser::new(tokens);
        parser.parse().map_err(FinxError::from)
    }
    /// Compiles AST into bytecode
    fn compile(&mut self, ast: Vec<crate::parser::Stmt>) -> Result<Vec<crate::vm::Instruction>> {
        // Extract function names and variable names from AST and add them to known_globals
        self.extract_global_names(&ast);

        // Create a sorted list of all known global names for consistent ordering
        // This ensures native functions are always in the same positions
        let mut all_globals: Vec<(String, usize)> = self
            .known_globals
            .iter()
            .map(|(name, &index)| (name.clone(), index))
            .collect();
        all_globals.sort_by_key(|(_, index)| *index);
        let sorted_global_names: Vec<String> =
            all_globals.into_iter().map(|(name, _)| name).collect();

        if sorted_global_names.is_empty() {
            compile_for_eval(ast)
        } else {
            compile_for_eval_with_natives(ast, &sorted_global_names)
        }
    }

    /// Ensures global variables are properly initialized for all globals (native functions + variables)
    fn ensure_globals_initialized(&mut self) {
        if !self.globals_initialized {
            // Initialize globals vector to accommodate all known globals
            let max_global_index = self.known_globals.values().max().copied().unwrap_or(0);
            self.vm.ensure_globals_capacity(max_global_index + 1); // Set up native functions in their correct positions
            for (name, &index) in &self.known_globals {
                if let Some((native_func, num_params)) = self.native_functions.get(name) {
                    let native_function = crate::vm::NativeFunction {
                        func: native_func.clone(),
                        name: name.clone(),
                        num_params: *num_params,
                    };
                    self.vm
                        .set_global_at_index(index, Value::_NativeFunction(native_function));
                }
                // Variables will be initialized as Null and set when StoreGlobal is executed
            }

            self.globals_initialized = true;
        }
    }

    /// Extracts function names and variable names from the AST and adds them to known_globals
    fn extract_global_names(&mut self, stmts: &[crate::parser::Stmt]) {
        for stmt in stmts {
            match stmt {
                crate::parser::Stmt::Fn { name, .. } => {
                    if !self.known_globals.contains_key(name) {
                        self.known_globals.insert(name.clone(), self.next_global);
                        self.next_global += 1;
                    }
                }
                crate::parser::Stmt::Let { name, .. } => {
                    // Track variable names as globals too
                    if !self.known_globals.contains_key(name) {
                        self.known_globals.insert(name.clone(), self.next_global);
                        self.next_global += 1;
                    }
                }
                // For nested statements (like in if/while blocks), recursively extract
                crate::parser::Stmt::If {
                    then_branch,
                    else_branch,
                    ..
                } => {
                    self.extract_global_names(then_branch);
                    if let Some(else_stmt) = else_branch {
                        match else_stmt.as_ref() {
                            crate::parser::Stmt::If { .. } => {
                                self.extract_global_names(&[*else_stmt.clone()])
                            }
                            _ => {} // Single statement else branch, no functions to extract
                        }
                    }
                }
                crate::parser::Stmt::While { body, .. } => {
                    self.extract_global_names(body);
                }
                crate::parser::Stmt::For { body, .. } => {
                    self.extract_global_names(body);
                }
                _ => {} // Other statement types don't contain function definitions
            }
        }
    }

    /// Registers common mathematical and utility functions
    fn register_default_functions(&mut self) {
        // Mathematical functions
        self.register_function(
            "abs",
            Rc::new(|args| {
                if let [Value::Number(n)] = args {
                    Value::Number(n.abs())
                } else {
                    Value::Null // Return null instead of panicking
                }
            }),
            1,
        );

        let print_output = self.print_output.clone();
        self.register_function(
            "print",
            Rc::new(move |args| {
                let string = format!(
                    "{}",
                    args.iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(" ")
                );

                println!("{}", string);
                print_output.borrow_mut().push(string);

                Value::Null
            }),
            1,
        );

        self.register_function(
            "sqrt",
            Rc::new(|args| {
                if let [Value::Number(n)] = args {
                    Value::Number(n.sqrt())
                } else {
                    Value::Null
                }
            }),
            1,
        );

        self.register_function(
            "min",
            Rc::new(|args| {
                if let [Value::Number(a), Value::Number(b)] = args {
                    Value::Number(a.min(*b))
                } else {
                    Value::Null
                }
            }),
            2,
        );

        self.register_function(
            "max",
            Rc::new(|args| {
                if let [Value::Number(a), Value::Number(b)] = args {
                    Value::Number(a.max(*b))
                } else {
                    Value::Null
                }
            }),
            2,
        );

        self.register_function(
            "pow",
            Rc::new(|args| {
                if let [Value::Number(base), Value::Number(exp)] = args {
                    Value::Number(base.powf(*exp))
                } else {
                    Value::Null
                }
            }),
            2,
        );

        // String functions
        self.register_function(
            "len",
            Rc::new(|args| match args {
                [Value::Str(s)] => Value::Number(s.len() as f64),
                _ => Value::Null,
            }),
            1,
        );

        // Type checking functions
        self.register_function(
            "is_num",
            Rc::new(|args| {
                if args.len() == 1 {
                    Value::Bool(matches!(args[0], Value::Number(_)))
                } else {
                    Value::Null
                }
            }),
            1,
        );

        self.register_function(
            "is_str",
            Rc::new(|args| {
                if args.len() == 1 {
                    Value::Bool(matches!(args[0], Value::Str(_)))
                } else {
                    Value::Null
                }
            }),
            1,
        );

        self.register_function(
            "is_bool",
            Rc::new(|args| {
                if args.len() == 1 {
                    Value::Bool(matches!(args[0], Value::Bool(_)))
                } else {
                    Value::Null
                }
            }),
            1,
        );

        self.register_function(
            "is_null",
            Rc::new(|args| {
                if args.len() == 1 {
                    Value::Bool(matches!(args[0], Value::Null))
                } else {
                    Value::Null
                }
            }),
            1,
        );
    }
}

impl Default for Finx {
    fn default() -> Self {
        Self::new()
    }
}

/// Convenience macro for easily registering native functions
///
/// ## Example
///
/// ```rust
/// use finx::{Finx, register_function, Value};
///
/// let mut engine = Finx::new();
///
/// register_function!(engine, "add", 2, |a: f64, b: f64| -> f64 {
///     a + b
/// });
///
/// register_function!(engine, "greet", 1, |name: &str| -> String {
///     format!("Hello, {}!", name)
/// });
/// ```
#[macro_export]
macro_rules! register_function {
    // Single parameter version - f64
    ($engine:expr, $name:expr, 1, |$param:ident: f64| -> $return_type:ty $body:block) => {
        $engine.register_function(
            $name,
            std::rc::Rc::new(|args| {
                if args.len() != 1 {
                    return $crate::vm::Value::Null;
                }
                match &args[0] {
                    $crate::vm::Value::Number(n) => {
                        let $param = *n;
                        let result: $return_type = $body;
                        result.into()
                    }
                    _ => $crate::vm::Value::Null,
                }
            }),
            1,
        );
    };

    // Single parameter version - &str
    ($engine:expr, $name:expr, 1, |$param:ident: &str| -> $return_type:ty $body:block) => {
        $engine.register_function(
            $name,
            std::rc::Rc::new(|args| {
                if args.len() != 1 {
                    return $crate::vm::Value::Null;
                }
                match &args[0] {
                    $crate::vm::Value::Str(s) => {
                        let $param = s.as_str();
                        let result: $return_type = $body;
                        result.into()
                    }
                    _ => $crate::vm::Value::Null,
                }
            }),
            1,
        );
    };

    // Single parameter version - bool
    ($engine:expr, $name:expr, 1, |$param:ident: bool| -> $return_type:ty $body:block) => {
        $engine.register_function(
            $name,
            std::rc::Rc::new(|args| {
                if args.len() != 1 {
                    return $crate::vm::Value::Null;
                }
                match &args[0] {
                    $crate::vm::Value::Bool(b) => {
                        let $param = *b;
                        let result: $return_type = $body;
                        result.into()
                    }
                    _ => $crate::vm::Value::Null,
                }
            }),
            1,
        );
    };

    // Two parameter version - both f64
    ($engine:expr, $name:expr, 2, |$param1:ident: f64, $param2:ident: f64| -> $return_type:ty $body:block) => {
        $engine.register_function(
            $name,
            std::rc::Rc::new(|args| {
                if args.len() != 2 {
                    return $crate::vm::Value::Null;
                }
                match (&args[0], &args[1]) {
                    ($crate::vm::Value::Number(n1), $crate::vm::Value::Number(n2)) => {
                        let $param1 = *n1;
                        let $param2 = *n2;
                        let result: $return_type = $body;
                        result.into()
                    }
                    _ => $crate::vm::Value::Null,
                }
            }),
            2,
        );
    };

    // Two parameter version - f64, &str
    ($engine:expr, $name:expr, 2, |$param1:ident: f64, $param2:ident: &str| -> $return_type:ty $body:block) => {
        $engine.register_function(
            $name,
            std::rc::Rc::new(|args| {
                if args.len() != 2 {
                    return $crate::vm::Value::Null;
                }
                match (&args[0], &args[1]) {
                    ($crate::vm::Value::Number(n), $crate::vm::Value::Str(s)) => {
                        let $param1 = *n;
                        let $param2 = s.as_str();
                        let result: $return_type = $body;
                        result.into()
                    }
                    _ => $crate::vm::Value::Null,
                }
            }),
            2,
        );
    };

    // Two parameter version - &str, f64
    ($engine:expr, $name:expr, 2, |$param1:ident: &str, $param2:ident: f64| -> $return_type:ty $body:block) => {
        $engine.register_function(
            $name,
            std::rc::Rc::new(|args| {
                if args.len() != 2 {
                    return $crate::vm::Value::Null;
                }
                match (&args[0], &args[1]) {
                    ($crate::vm::Value::Str(s), $crate::vm::Value::Number(n)) => {
                        let $param1 = s.as_str();
                        let $param2 = *n;
                        let result: $return_type = $body;
                        result.into()
                    }
                    _ => $crate::vm::Value::Null,
                }
            }),
            2,
        );
    };

    // Two parameter version - both &str
    ($engine:expr, $name:expr, 2, |$param1:ident: &str, $param2:ident: &str| -> $return_type:ty $body:block) => {
        $engine.register_function(
            $name,
            std::rc::Rc::new(|args| {
                if args.len() != 2 {
                    return $crate::vm::Value::Null;
                }
                match (&args[0], &args[1]) {
                    ($crate::vm::Value::Str(s1), $crate::vm::Value::Str(s2)) => {
                        let $param1 = s1.as_str();
                        let $param2 = s2.as_str();
                        let result: $return_type = $body;
                        result.into()
                    }
                    _ => $crate::vm::Value::Null,
                }
            }),
            2,
        );
    };
}