Skip to main content

run/
run.rs

1//! Example runner for FiddlerScript programs.
2//!
3//! This example demonstrates how to use the FiddlerScript interpreter
4//! to run scripts from strings or files.
5
6use fiddler_script::Interpreter;
7
8fn main() {
9    println!("=== FiddlerScript Examples ===\n");
10
11    // Example 1: Basic arithmetic
12    println!("Example 1: Basic Arithmetic");
13    run_example(
14        r#"
15let x = 10;
16let y = 20;
17let sum = x + y;
18print("Sum:", sum);
19"#,
20    );
21
22    // Example 2: Control flow
23    println!("\nExample 2: Control Flow");
24    run_example(
25        r#"
26let age = 18;
27if (age >= 18) {
28    print("You are an adult");
29} else {
30    print("You are a minor");
31}
32"#,
33    );
34
35    // Example 3: For loop
36    println!("\nExample 3: For Loop");
37    run_example(
38        r#"
39print("Counting from 1 to 5:");
40for (let i = 1; i <= 5; i = i + 1) {
41    print(i);
42}
43"#,
44    );
45
46    // Example 4: Functions
47    println!("\nExample 4: Functions");
48    run_example(
49        r#"
50fn add(a, b) {
51    return a + b;
52}
53
54fn multiply(a, b) {
55    return a * b;
56}
57
58let result = add(5, 3);
59print("5 + 3 =", result);
60
61let product = multiply(4, 7);
62print("4 * 7 =", product);
63"#,
64    );
65
66    // Example 5: Recursion (Factorial)
67    println!("\nExample 5: Factorial");
68    run_example(
69        r#"
70fn factorial(n) {
71    if (n <= 1) {
72        return 1;
73    }
74    return n * factorial(n - 1);
75}
76
77print("5! =", factorial(5));
78print("10! =", factorial(10));
79"#,
80    );
81
82    // Example 6: Fibonacci
83    println!("\nExample 6: Fibonacci");
84    run_example(
85        r#"
86fn fibonacci(n) {
87    if (n <= 1) {
88        return n;
89    }
90    return fibonacci(n - 1) + fibonacci(n - 2);
91}
92
93print("First 10 Fibonacci numbers:");
94for (let i = 0; i < 10; i = i + 1) {
95    print(fibonacci(i));
96}
97"#,
98    );
99
100    // Example 7: String operations
101    println!("\nExample 7: String Operations");
102    run_example(
103        r#"
104let greeting = "Hello";
105let name = "World";
106let message = greeting + " " + name + "!";
107print(message);
108print("Length:", len(message));
109"#,
110    );
111
112    // Example 8: Boolean logic
113    println!("\nExample 8: Boolean Logic");
114    run_example(
115        r#"
116let a = true;
117let b = false;
118
119print("a =", a);
120print("b =", b);
121print("a && b =", a && b);
122print("a || b =", a || b);
123print("!a =", !a);
124print("!b =", !b);
125"#,
126    );
127}
128
129fn run_example(source: &str) {
130    let mut interpreter = Interpreter::new();
131    match interpreter.run(source) {
132        Ok(_) => {}
133        Err(e) => eprintln!("Error: {}", e),
134    }
135}