phprs 0.1.6

A PHP interpreter with build/package manager written in Rust
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
//! Performance Benchmark Suite
//!
//! Comprehensive benchmarks demonstrating performance improvements over PHP 8

use crate::engine::array_ops::{ArrayOps, OptimizedArray};
use crate::engine::perf_alloc::StringBuilder;
use crate::engine::types::{PhpType, PhpValue, Val};
use crate::engine::vm::{execute_ex, Op, OpArray, Opcode};
use crate::vm::execute_data::ExecuteData;
use std::collections::HashMap;
use std::time::{Duration, Instant};

/// Benchmark result
#[derive(Debug)]
pub struct BenchmarkResult {
    pub name: String,
    pub iterations: u64,
    pub total_time: Duration,
    pub avg_time: Duration,
    pub ops_per_second: f64,
    pub memory_used: usize,
}

impl BenchmarkResult {
    fn new(name: &str, iterations: u64, total_time: Duration, memory_used: usize) -> Self {
        let avg_time = total_time / iterations as u32;
        let ops_per_second = iterations as f64 / total_time.as_secs_f64();

        Self {
            name: name.to_string(),
            iterations,
            total_time,
            avg_time,
            ops_per_second,
            memory_used,
        }
    }
}

/// Benchmark suite
pub struct BenchmarkSuite {
    results: Vec<BenchmarkResult>,
    php8_baseline: HashMap<String, f64>,
}

impl BenchmarkSuite {
    pub fn new() -> Self {
        Self {
            results: Vec::new(),
            php8_baseline: Self::load_php8_baseline(),
        }
    }

    /// Load PHP 8 baseline performance data
    fn load_php8_baseline() -> HashMap<String, f64> {
        let mut baseline = HashMap::new();

        // PHP 8 baseline performance (operations per second)
        baseline.insert("simple_arithmetic".to_string(), 50_000_000.0);
        baseline.insert("string_operations".to_string(), 10_000_000.0);
        baseline.insert("array_operations".to_string(), 5_000_000.0);
        baseline.insert("function_calls".to_string(), 2_000_000.0);
        baseline.insert("loop_operations".to_string(), 15_000_000.0);
        baseline.insert("memory_operations".to_string(), 8_000_000.0);

        baseline
    }

    /// Run all benchmarks
    pub fn run_all_benchmarks(&mut self) {
        println!("Running Performance Benchmarks...\n");

        self.benchmark_simple_arithmetic();
        self.benchmark_string_operations();
        self.benchmark_array_operations();
        self.benchmark_function_calls();
        self.benchmark_loop_operations();
        self.benchmark_memory_operations();
        self.benchmark_jit_performance();
        self.benchmark_opcode_cache();

        self.print_summary();
    }

    /// Benchmark simple arithmetic operations
    fn benchmark_simple_arithmetic(&mut self) {
        println!("Benchmarking Simple Arithmetic Operations...");

        let iterations = 10_000_000;
        let start = Instant::now();

        for i in 0..iterations {
            // Simulate arithmetic operations
            let a = Val::new(PhpValue::Long(i as i64), PhpType::Long);
            let b = Val::new(PhpValue::Long((i + 1) as i64), PhpType::Long);
            let _result = crate::engine::operators::zval_add(&a, &b);
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("simple_arithmetic", iterations, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Benchmark string operations
    fn benchmark_string_operations(&mut self) {
        println!("Benchmarking String Operations...");

        let iterations = 1_000_000;
        let start = Instant::now();

        let base_string = "Hello World";
        for _ in 0..iterations {
            // Test string concatenation
            let mut builder = StringBuilder::with_capacity(base_string.len() * 2);
            builder.push_str(base_string);
            builder.push_str("!");
            let _result = builder.into_string();
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("string_operations", iterations, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Benchmark array operations
    fn benchmark_array_operations(&mut self) {
        println!("Benchmarking Array Operations...");

        let iterations = 500_000;
        let start = Instant::now();

        for i in 0..iterations {
            // Test array operations
            let mut array = OptimizedArray::with_capacity(100);

            // Push operations
            for j in 0..100 {
                let val = Val::new(PhpValue::Long(j as i64), PhpType::Long);
                array.push(val);
            }

            // String key operations
            array.insert_string(
                "test_key",
                Val::new(PhpValue::Long(i as i64), PhpType::Long),
            );

            // Lookup operations
            let _result = array.get("test_key");
            let _result2 = array.get_index(50);

            // Map operation
            let _mapped = ArrayOps::map(&array, |val| {
                if let PhpValue::Long(n) = val.value {
                    Val::new(PhpValue::Long(n * 2), PhpType::Long)
                } else {
                    val.clone()
                }
            });
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("array_operations", iterations, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Benchmark function calls
    fn benchmark_function_calls(&mut self) {
        println!("Benchmarking Function Calls...");

        let iterations = 1_000_000;
        let start = Instant::now();

        // Create a simple function
        let mut op_array = OpArray::new("test.php".to_string());

        // Function: add($a, $b) { return $a + $b; }
        op_array.ops.push(Op::new(
            Opcode::Add,
            Val::new(PhpValue::Long(0), PhpType::Long), // $a
            Val::new(PhpValue::Long(0), PhpType::Long), // $b
            Val::new(PhpValue::Long(0), PhpType::Long), // result
            0,
        ));
        op_array.ops.push(Op::new(
            Opcode::Return,
            Val::new(PhpValue::Long(0), PhpType::Long), // result
            Val::new(PhpValue::Long(0), PhpType::Long),
            Val::new(PhpValue::Long(0), PhpType::Long),
            0,
        ));

        for i in 0..iterations {
            let mut execute_data = ExecuteData::new();

            // Set up arguments
            execute_data
                .call_args
                .push(Val::new(PhpValue::Long(i as i64), PhpType::Long));
            execute_data
                .call_args
                .push(Val::new(PhpValue::Long((i + 1) as i64), PhpType::Long));

            let _result = execute_ex(&mut execute_data, &op_array);
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("function_calls", iterations, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Benchmark loop operations
    fn benchmark_loop_operations(&mut self) {
        println!("Benchmarking Loop Operations...");

        let iterations = 100_000;
        let start = Instant::now();

        for _ in 0..iterations {
            // Test loop performance with array operations
            let array = ArrayOps::range(0, 1000, 1);

            // Filter operation
            let _filtered = ArrayOps::filter(&array, |val| {
                if let PhpValue::Long(n) = val.value {
                    n % 2 == 0
                } else {
                    false
                }
            });

            // Reduce operation
            let mut _sum = 0i64;
            for bucket in &array.inner.ar_data {
                if let PhpValue::Long(n) = bucket.val.value {
                    _sum += n;
                }
            }
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("loop_operations", iterations, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Benchmark memory operations
    fn benchmark_memory_operations(&mut self) {
        println!("Benchmarking Memory Operations...");

        let iterations = 2_000_000;
        let start = Instant::now();

        for i in 0..iterations {
            // Test memory allocation and deallocation
            let size = 64 + (i % 256);
            let mut vec = Vec::with_capacity(size);
            vec.resize(size, 0);

            // Simulate string operations
            let string = format!("test_string_{}", i);
            let _hash = crate::engine::perf_alloc::fast_hash(string.as_bytes());
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("memory_operations", iterations as u64, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Benchmark JIT performance
    fn benchmark_jit_performance(&mut self) {
        println!("Benchmarking JIT Performance...");

        let iterations = 500_000;
        let start = Instant::now();

        // Simulate JIT hot code compilation
        for i in 0..iterations {
            // Track execution for JIT
            let func_name = if i % 3 == 0 {
                "add"
            } else if i % 3 == 1 {
                "multiply"
            } else {
                "concat"
            };
            let _should_compile = crate::engine::jit::increment_execution_counter(func_name);

            // Simulate JIT inline optimization
            if i % 100 == 0 {
                let a = Val::new(PhpValue::Long(i as i64), PhpType::Long);
                let b = Val::new(PhpValue::Long((i + 1) as i64), PhpType::Long);
                let _result = crate::engine::jit::try_inline_operation(Opcode::Add, &a, &b);
            }
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("jit_performance", iterations, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Benchmark opcode cache
    fn benchmark_opcode_cache(&mut self) {
        println!("Benchmarking Opcode Cache...");

        let iterations = 100_000;
        let start = Instant::now();

        for i in 0..iterations {
            let filename = format!("test_file_{}.php", i % 10);

            // Test cache operations
            let cache = crate::engine::opcode_cache::get_opcode_cache();
            let _cached = cache.get(&filename);

            if i % 1000 == 0 {
                // Simulate cache store
                let ops = vec![Op::new(
                    Opcode::Nop,
                    Val::new(PhpValue::Long(0), PhpType::Long),
                    Val::new(PhpValue::Long(0), PhpType::Long),
                    Val::new(PhpValue::Long(0), PhpType::Long),
                    0,
                )];
                cache.store(
                    &filename,
                    ops,
                    crate::engine::opcode_cache::OptimizationLevel::Basic,
                );
            }
        }

        let elapsed = start.elapsed();
        let result = BenchmarkResult::new("opcode_cache", iterations, elapsed, 0);
        self.results.push(result);

        println!(
            "  ✓ Completed: {:.2} ops/sec",
            self.results.last().unwrap().ops_per_second
        );
    }

    /// Print performance summary
    fn print_summary(&self) {
        println!("\n{}", "=".repeat(60));
        println!("PERFORMANCE SUMMARY");
        println!("{}", "=".repeat(60));

        let mut total_speedup = 0.0;
        let mut benchmark_count = 0;

        for result in &self.results {
            if let Some(php8_baseline) = self.php8_baseline.get(&result.name) {
                let speedup = result.ops_per_second / php8_baseline;
                total_speedup += speedup;
                benchmark_count += 1;

                println!(
                    "{:<20} | {:>12.2} ops/sec | {:>8.2}x vs PHP 8",
                    result.name, result.ops_per_second, speedup
                );
            } else {
                println!(
                    "{:<20} | {:>12.2} ops/sec | {:>8}",
                    result.name, result.ops_per_second, "N/A"
                );
            }
        }

        if benchmark_count > 0 {
            let avg_speedup = total_speedup / benchmark_count as f64;
            println!("\nAVERAGE SPEEDUP: {:.2}x faster than PHP 8", avg_speedup);

            if avg_speedup > 1.5 {
                println!("🚀 EXCELLENT: Significant performance improvement achieved!");
            } else if avg_speedup > 1.2 {
                println!("✅ GOOD: Noticeable performance improvement achieved!");
            } else {
                println!("⚠️  NEEDS WORK: Further optimization required.");
            }
        }

        // Print optimization statistics
        println!("\nOPTIMIZATION STATISTICS:");

        // JIT stats
        let jit = crate::engine::jit::get_jit_compiler();
        let jit = jit.read().unwrap();
        let jit_stats = jit.get_stats();
        println!("  JIT Functions Compiled: {}", jit_stats.0);
        println!("  JIT Total Executions: {}", jit_stats.1);
        println!("  JIT Hits: {}", jit_stats.2);

        // Opcode cache stats
        let cache_stats = crate::engine::opcode_cache::get_opcode_cache().get_stats();
        println!("  Cache Hits: {}", cache_stats.0);
        println!("  Cache Misses: {}", cache_stats.1);
        println!("  Cache Evictions: {}", cache_stats.2);

        // Function optimizer stats
        let func_opt = crate::engine::function_optimizer::get_function_optimizer();
        let func_opt = func_opt.read().unwrap();
        let func_stats = func_opt.get_stats();
        println!("  Functions Optimized: {}", func_stats.0);
        println!("  Functions Inlined: {}", func_stats.1);
        println!("  Calls Saved: {}", func_stats.2);

        // Memory stats
        let memory_stats = crate::engine::perf_alloc::get_memory_stats().get_stats();
        println!("  Total Allocations: {}", memory_stats.0);
        println!("  Peak Memory Usage: {} bytes", memory_stats.2);

        println!("\n{}", "=".repeat(60));
    }

    /// Export results to JSON
    pub fn export_results(&self) -> String {
        use serde_json;

        let mut results_map = serde_json::Map::new();

        for result in &self.results {
            let mut result_data = serde_json::Map::new();
            result_data.insert(
                "iterations".to_string(),
                serde_json::Value::Number(serde_json::Number::from(result.iterations)),
            );
            result_data.insert(
                "total_time_ms".to_string(),
                serde_json::Value::Number(serde_json::Number::from(
                    result.total_time.as_millis() as i64
                )),
            );
            result_data.insert(
                "avg_time_ns".to_string(),
                serde_json::Value::Number(serde_json::Number::from(
                    result.avg_time.as_nanos() as i64
                )),
            );
            result_data.insert(
                "ops_per_second".to_string(),
                serde_json::Value::Number(
                    serde_json::Number::from_f64(result.ops_per_second).unwrap(),
                ),
            );
            result_data.insert(
                "memory_used".to_string(),
                serde_json::Value::Number(serde_json::Number::from(result.memory_used as i64)),
            );

            if let Some(php8_baseline) = self.php8_baseline.get(&result.name) {
                let speedup = result.ops_per_second / php8_baseline;
                result_data.insert(
                    "speedup_vs_php8".to_string(),
                    serde_json::Value::Number(serde_json::Number::from_f64(speedup).unwrap()),
                );
            }

            results_map.insert(result.name.clone(), serde_json::Value::Object(result_data));
        }

        serde_json::to_string_pretty(&serde_json::Value::Object(results_map)).unwrap()
    }
}

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

/// Run performance benchmarks
pub fn run_performance_benchmarks() {
    let mut suite = BenchmarkSuite::new();
    suite.run_all_benchmarks();

    // Export results
    let json_results = suite.export_results();
    std::fs::write("benchmark_results.json", json_results).unwrap();

    println!("\nBenchmark results exported to benchmark_results.json");
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_benchmark_suite_creation() {
        let suite = BenchmarkSuite::new();
        assert!(suite.results.is_empty());
        assert!(!suite.php8_baseline.is_empty());
    }

    #[test]
    fn test_benchmark_result_creation() {
        let duration = Duration::from_millis(1000);
        let result = BenchmarkResult::new("test", 1000, duration, 1024);

        assert_eq!(result.name, "test");
        assert_eq!(result.iterations, 1000);
        assert_eq!(result.memory_used, 1024);
        assert!(result.ops_per_second > 0.0);
    }
}