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
//! # Finx - Embeddable Scripting Language
//!
//! Finx is a fast, lightweight scripting language designed for easy embedding in Rust applications. It features a stack-based virtual machine, lexical scoping with closures, and a simple but powerful syntax.
//!
//! ### Basic Usage
//!
//! ```rust
//! use finx::Finx;
//!
//! fn main() {
//!     // Create a new language engine
//!     let mut engine = Finx::new();
//!
//!     // Run a simple expression
//!     let result = engine.eval("2 + 3 * 4").unwrap();
//!     println!("Result: {}", result); // Result: 14
//!
//!     // Define variables and functions
//!     engine.execute(r#"
//!         let name = "World";
//!
//!         fn greet(person) {
//!             return "Hello, " + person + "!";
//!         }
//!     "#).unwrap();
//!
//!     // Use defined variables and functions
//!     let greeting = engine.eval("greet(name)").unwrap();
//!     println!("{}", greeting); // Hello, World!
//! }
//! ```
//!
//! ### Native Functions
//!
//! Register Rust functions to be called from scripts:
//!
//! ```rust
//! use finx::{Finx, Value};
//!
//! let mut engine = Finx::new();
//!
//! // Register a simple math function
//! engine.register_closure("multiply", |args: &[Value]| {
//!     if let [Value::Number(a), Value::Number(b)] = args {
//!         Value::Number(a * b)
//!     } else {
//!         panic!("multiply expects two numbers");
//!     }
//! }, 2);
//!
//! // Use the native function in a script
//! let result = engine.eval("multiply(6, 7)").unwrap();
//! assert_eq!(result.as_num(), Some(42.0));
//! ```
//!
//! ### Using the Convenience Macro
//!
//! For easier native function registration:
//!
//! ```rust
//! use finx::{Finx, register_function};
//!
//! let mut engine = Finx::new();
//!
//! register_function!(engine, "add", 2, |a: f64, b: f64| -> f64 {
//!     a + b
//! });
//!
//! register_function!(engine, "format_name", 2, |first: &str, last: &str| -> String {
//!     format!("{}, {}", last, first)
//! });
//!
//! let result = engine.eval(r#"format_name("John", "Doe")"#).unwrap();
//! assert_eq!(result.as_str(), Some("Doe, John"));
//! ```
//!
//! ### Native Functions with Closures
//!
//! Finx supports advanced native functions using closures, enabling state capture and more dynamic behavior:
//!
//! #### Basic Closure Registration
//!
//! ```rust
//! use finx::{Finx, Value};
//! use std::rc::Rc;
//!
//! let mut engine = Finx::new();
//!
//! // Simple closure with captured state
//! let prefix = "LOG: ".to_string();
//! engine.register_function("log", Rc::new(move |args| {
//!     if let [Value::Str(msg)] = args {
//!         println!("{}{}", prefix, msg);
//!     }
//!     Value::Null
//! }), 1);
//!
//! engine.execute(r#"log("Hello from script!");"#).unwrap();
//! // Output: LOG: Hello from script!
//! ```
//!
//! #### Shared Mutable State
//!
//! For shared state between multiple closures, use `Rc<RefCell<T>>`:
//!
//! ```rust
//! use finx::{Finx, Value};
//! use std::rc::Rc;
//! use std::cell::RefCell;
//!
//! let mut engine = Finx::new();
//!
//! // Shared counter state
//! let counter = Rc::new(RefCell::new(0_i32));
//!
//! // Increment function
//! let counter_clone = counter.clone();
//! engine.register_function("increment", Rc::new(move |_args| {
//!     let mut count = counter_clone.borrow_mut();
//!     *count += 1;
//!     Value::Number(*count as f64)
//! }), 0);
//!
//! // Get current count
//! let counter_clone = counter.clone();
//! engine.register_function("get_count", Rc::new(move |_args| {
//!     let count = counter_clone.borrow();
//!     Value::Number(*count as f64)
//! }), 0);
//!
//! // Reset counter
//! let counter_clone = counter.clone();
//! engine.register_function("reset", Rc::new(move |_args| {
//!     let mut count = counter_clone.borrow_mut();
//!     *count = 0;
//!     Value::Null
//! }), 0);
//!
//! engine.execute(r#"
//!     print(increment()); // 1
//!     print(increment()); // 2
//!     print(get_count()); // 2
//!     reset();
//!     print(get_count()); // 0
//! "#).unwrap();
//! ```
//!
//! #### Configuration-Driven Functions
//!
//! Create functions that adapt based on configuration:
//!
//! ```rust
//! use finx::{Finx, Value};
//! use std::rc::Rc;
//!
//! let mut engine = Finx::new();
//!
//! // Configuration
//! struct Config {
//!     debug: bool,
//!     log_level: String,
//! }
//!
//! let config = Config {
//!     debug: true,
//!     log_level: "INFO".to_string(),
//! };
//!
//! // Logger that respects configuration
//! engine.register_function("log", Rc::new(move |args| {
//!     if let [Value::Str(level), Value::Str(msg)] = args {
//!         if config.debug || **level != "DEBUG" {
//!             println!("[{}] {}", level, msg);
//!         }
//!     }
//!     Value::Null
//! }), 2);
//!
//! engine.execute(r#"
//!     log("INFO", "Application started");
//!     log("DEBUG", "This might not show");
//! "#).unwrap();
//! ```
//!
//! #### When to Use Closures vs Function Pointers
//!
//! **Use Closures When:**
//! - You need to capture configuration or state
//! - Functions need to share mutable state
//! - You want to create factory functions for different behaviors
//! - You need access to external resources (files, network, etc.)
//!
//! **Use Function Pointers When:**
//! - Simple, stateless operations
//! - Maximum performance is critical
//! - Functions are pure/mathematical
//! - Backward compatibility with existing code
//!
//! **Convenience Method:**
//!
//! ```rust
//! use finx::Finx;
//! use std::rc::Rc;
//!
//! let mut engine = Finx::new();
//!
//! // For closures
//! engine.register_closure("add", |args| {
//!     // Implementation
//!     finx::Value::Null
//! }, 2);
//! ```
//!
//! ## Language Syntax
//!
//! Finx supports a familiar, C-like syntax:
//!
//! ### Variables and Assignment
//!
//! ```javascript
//! let x = 42;
//! let name = "Alice";
//! let is_valid = true;
//! let empty = null;
//!
//! x = x + 1;  // Reassignment
//! ```
//!
//! ### Functions
//!
//! ```javascript
//! fn add(a, b) {
//!     return a + b;
//! }
//!
//! fn factorial(n) {
//!     if n <= 1 {
//!         return 1;
//!     }
//!     return n * factorial(n - 1);
//! }
//! ```
//!
//! ### Closures
//!
//! ```javascript
//! fn make_counter() {
//!     let count = 0;
//!
//!     fn increment() {
//!         count = count + 1;
//!         return count;
//!     }
//!
//!     return increment;
//! }
//!
//! let counter = make_counter();
//! print(counter()); // 1
//! print(counter()); // 2
//! ```
//!
//! ### Control Flow
//!
//! ```javascript
//! // Conditionals
//! if x > 0 {
//!     print("Positive");
//! } else if x < 0 {
//!     print("Negative");
//! } else {
//!     print("Zero");
//! }
//!
//! // Loops
//! let i = 0;
//! while i < 5 {
//!     print(i);
//!     i = i + 1;
//! }
//!
//! for i in 0..10 {
//!     print(i);
//! }
//! ```
//!
//! ### Built-in Functions
//!
//! When using `Finx::new()`, you get access to common functions:
//!
//! ```javascript
//! print(abs(-42));        // 42
//! print(sqrt(16));        // 4
//! print(max(10, 20));     // 20
//! print(min(10, 20));     // 10
//! print(pow(2, 3));       // 8
//!
//! print(is_num(42));      // true
//! print(is_str("test"));  // true
//! ```
//!
//! ## Error Handling
//!
//! Finx provides comprehensive error handling:
//!
//! ```rust
//! use finx::{Finx, FinxError};
//!
//! let mut engine = Finx::new();
//!
//! match engine.eval("unknown_variable") {
//!     Ok(result) => println!("Result: {}", result),
//!     Err(FinxError::RuntimeError(msg)) => println!("Runtime error: {}", msg),
//!     Err(FinxError::ParseError(err)) => println!("Parse error: {}", err),
//!     Err(err) => println!("Other error: {}", err),
//! }
//! ```
//!
//! ## Advanced Usage
//!
//! ### Running Scripts from Files
//!
//! ```rust
//! use finx::Finx;
//!
//! let mut engine = Finx::new();
//!
//! // Execute a script file
//! engine.execute_file("example_scripts/example.fx").unwrap();
//!
//! // Evaluate an expression from a file
//! let result = engine.eval_file("example_scripts/example.fx").unwrap();
//! ```
//!
//! ### Managing Output
//!
//! ```rust
//! use finx::Finx;
//!
//! let mut engine = Finx::new();
//!
//! engine.execute(r#"
//!     print("Hello");
//!     print("World");
//! "#).unwrap();
//!
//! // Get all print output
//! let output = engine.get_output();
//! assert_eq!(output, &["Hello", "World"]);
//!
//! // Clear output for next execution
//! engine.clear_output();
//! ```
//!
//! ### Performance Tuning
//!
//! ```rust
//! use finx::Finx;
//!
//! let mut engine = Finx::new();
//!
//! // Set recursion limits
//! engine.set_max_recursion_depth(500);
//! ```
//!
//! ## Value Types
//!
//! Finx supports the following data types:
//!
//! - **Numbers**: 64-bit floating point (`42`, `3.14`, `-1.5`)
//! - **Strings**: UTF-8 strings (`"hello"`, `"world"`)
//! - **Booleans**: `true` and `false`
//! - **Null**: `null` value
//! - **Functions**: First-class functions and closures
//!
//! ### Working with Values
//!
//! ```rust
//! use finx::{Finx, Value};
//!
//! let mut engine = Finx::new();
//! let result = engine.eval("42").unwrap();
//!
//! match result {
//!     Value::Number(n) => println!("Got number: {}", n),
//!     Value::Str(ref s) => println!("Got string: {}", s),
//!     Value::Bool(b) => println!("Got boolean: {}", b),
//!     Value::Null => println!("Got null"),
//!     _ => println!("Got other value"),
//! }
//!
//! // Or use convenience methods
//! if let Some(num) = result.as_num() {
//!     println!("Number value: {}", num);
//! }
//! ```

pub mod compiler;
pub mod engine;
pub mod lexer;
pub mod parser;
pub mod vm;

// Re-export main types for easy use
pub use engine::{Finx, FinxError, Result};
pub use vm::{NativeFn, Value};